@imtbl/wallet 2.12.5 → 2.12.6-alpha.0
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 +688 -0
- package/dist/browser/index.js +45 -45
- package/dist/node/index.cjs +64 -68
- package/dist/node/index.js +48 -48
- package/dist/types/connectWallet.d.ts +13 -19
- package/dist/types/guardian/index.d.ts +10 -5
- package/dist/types/magic/magicTEESigner.d.ts +3 -4
- package/dist/types/sequence/sequenceProvider.d.ts +4 -4
- package/dist/types/sequence/signer/identityInstrumentSigner.d.ts +2 -2
- package/dist/types/sequence/signer/index.d.ts +5 -4
- package/dist/types/sequence/signer/privateKeySigner.d.ts +2 -2
- package/dist/types/sequence/user/registerUser.d.ts +3 -3
- package/dist/types/types.d.ts +39 -9
- package/dist/types/zkEvm/relayerClient.d.ts +8 -4
- package/dist/types/zkEvm/user/registerZkEvmUser.d.ts +7 -4
- package/dist/types/zkEvm/zkEvmProvider.d.ts +13 -5
- package/package.json +7 -7
- package/src/connectWallet.test.ts +16 -22
- package/src/connectWallet.ts +79 -53
- package/src/guardian/index.ts +40 -25
- package/src/magic/magicTEESigner.ts +8 -6
- package/src/sequence/sequenceProvider.ts +17 -9
- package/src/sequence/signer/identityInstrumentSigner.ts +8 -6
- package/src/sequence/signer/index.ts +8 -12
- package/src/sequence/signer/privateKeySigner.ts +6 -5
- package/src/sequence/user/registerUser.ts +5 -4
- package/src/types.ts +44 -12
- package/src/zkEvm/relayerClient.ts +22 -6
- package/src/zkEvm/user/registerZkEvmUser.ts +16 -5
- package/src/zkEvm/zkEvmProvider.ts +56 -29
package/dist/node/index.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export {
|
|
3
|
-
import * as
|
|
1
|
+
import { isUserZkEvm, TypedEventEmitter, Auth, decodeJwtPayload } from '@imtbl/auth';
|
|
2
|
+
export { TypedEventEmitter, isUserZkEvm } from '@imtbl/auth';
|
|
3
|
+
import * as SI from '@imtbl/generated-clients';
|
|
4
4
|
import { createConfig, MultiRollupApiClients, mr as mr$1, MagicTeeApiClients } from '@imtbl/generated-clients';
|
|
5
5
|
import { utils, trackError, trackFlow, identify, trackDuration } from '@imtbl/metrics';
|
|
6
6
|
import { parseAbiParameters, zeroAddress, encodeAbiParameters, keccak256, getContract, encodePacked, toBytes, encodeFunctionData, hashTypedData, hashMessage, createPublicClient, http, toHex, getAddress, concat, parseAbi } from 'viem';
|
|
7
7
|
import * as xn from 'node:crypto';
|
|
8
|
-
import * as
|
|
8
|
+
import * as xV from 'viem/chains';
|
|
9
9
|
import { privateKeyToAccount } from 'viem/accounts';
|
|
10
10
|
|
|
11
|
-
var Mk=Object.defineProperty;var be=(s,e)=>{for(var t in e)Mk(s,t,{get:e[t],enumerable:!0});};var h0=(t=>(t.ZKEVM="zkevm",t.ARBITRUM_ONE="arbitrum_one",t))(h0||{}),
|
|
11
|
+
var Mk=Object.defineProperty;var be=(s,e)=>{for(var t in e)Mk(s,t,{get:e[t],enumerable:!0});};var h0=(t=>(t.ZKEVM="zkevm",t.ARBITRUM_ONE="arbitrum_one",t))(h0||{}),YA=(t=>(t.ACCOUNTS_REQUESTED="accountsRequested",t.LOGGED_OUT="loggedOut",t))(YA||{}),ZA=(e=>(e.ACCOUNTS_CHANGED="accountsChanged",e))(ZA||{}),$k=(a=>(a.PENDING="PENDING",a.SUBMITTED="SUBMITTED",a.SUCCESSFUL="SUCCESSFUL",a.REVERTED="REVERTED",a.FAILED="FAILED",a.CANCELLED="CANCELLED",a))($k||{});var cI={};be(cI,{coerceNonceSpace:()=>aI,digestOfTransactionsAndNonce:()=>iI,encodeMessageSubDigest:()=>p0,encodeNonce:()=>oI,encodedTransactions:()=>Rw,getEip155ChainId:()=>Jt,getNonce:()=>ql,getNormalisedTransactions:()=>m0,packSignatures:()=>y0,signAndPackTypedData:()=>Vw,signERC191Message:()=>Dw,signMetaTransactions:()=>g0});var Tw={mainModule:{abi:[{type:"function",name:"nonce",constant:!0,inputs:[],outputs:[{type:"uint256"}],payable:!1,stateMutability:"view"},{type:"function",name:"readNonce",constant:!0,inputs:[{type:"uint256",name:"_space"}],outputs:[{type:"uint256"}],payable:!1,stateMutability:"view"},{type:"function",name:"execute",constant:!1,inputs:[{components:[{type:"bool",name:"delegateCall"},{type:"bool",name:"revertOnError"},{type:"uint256",name:"gasLimit"},{type:"address",name:"target"},{type:"uint256",name:"value"},{type:"bytes",name:"data"}],name:"_txs",type:"tuple[]"},{type:"uint256",name:"_nonce"},{type:"bytes",name:"_signature"}],outputs:[],payable:!1,stateMutability:"nonpayable"}]}};var eI=s=>{let e=toBytes(s),t=e[0]<<8|e[1],n=[];for(let r=2;r<e.length;){let i=e[r++],a=e[r++];if(i===0)n.push({unrecovered:!0,weight:a,signature:toHex(e.slice(r,r+66)),isDynamic:!1}),r+=66;else if(i===1)n.push({weight:a,address:getAddress(toHex(e.slice(r,r+20)))}),r+=20;else if(i===2){let o=getAddress(toHex(e.slice(r,r+20)));r+=20;let c=e[r]<<8|e[r+1];r+=2,n.push({unrecovered:!0,weight:a,signature:toHex(e.slice(r,r+c)),address:o,isDynamic:!0}),r+=c;}else throw new Error(`Unknown signature part type: ${i}`)}return {version:1,threshold:t,signers:n}},Bw=s=>{let{signers:e,threshold:t}=s,n=e.map(r=>{let i=Number(r.weight);if(r.address&&r.signature===void 0)return encodePacked(["uint8","uint8","address"],[1,i,r.address]);if(r.signature===void 0)throw new Error("Signature value missing for signer");if(r.isDynamic){let a=toBytes(r.signature),o=r.address?getAddress(r.address):void 0;if(!o)throw new Error("Dynamic signature part must include an address");return encodePacked(["uint8","uint8","address","uint16","bytes"],[2,i,o,a.length,toHex(a)])}return encodePacked(["uint8","uint8","bytes"],[0,i,r.signature])});return encodePacked(["uint16",...new Array(n.length).fill("bytes")],[t,...n])};var sI=1,Yk=1,Zk=2,nI="02",Qk="",rI=parseAbiParameters("(bool delegateCall, bool revertOnError, uint256 gasLimit, address target, uint256 value, bytes data)[]"),m0=s=>s.map(e=>({delegateCall:e.delegateCall===!0,revertOnError:e.revertOnError===!0,gasLimit:e.gasLimit??BigInt(0),target:e.to??zeroAddress,value:e.value??BigInt(0),data:e.data??"0x"})),iI=(s,e)=>{let t=e.map(r=>({delegateCall:r.delegateCall,revertOnError:r.revertOnError,gasLimit:r.gasLimit,target:r.target,value:r.value,data:r.data})),n=encodeAbiParameters([{type:"uint256"},...rI],[s,t]);return keccak256(n)},Rw=s=>{let e=s.map(t=>({delegateCall:t.delegateCall,revertOnError:t.revertOnError,gasLimit:t.gasLimit,target:t.target,value:t.value,data:t.data}));return encodeAbiParameters(rI,[e])},aI=s=>s||0n,oI=(s,e)=>{let t=BigInt(s)*2n**96n;return BigInt(e)+t},ql=async(s,e,t)=>{try{let n=getContract({address:e,abi:Tw.mainModule.abi,client:s}),r=aI(t),i=await n.read.readNonce([r]);if(typeof i=="bigint")return oI(r,i);throw new Error("Unexpected result from contract.readNonce() call.")}catch(n){if(n instanceof Error&&(n.message.includes("returned no data")||n.message.includes("execution reverted")||n.message.includes("ContractFunctionExecutionError")))return BigInt(0);throw n}},p0=(s,e,t)=>encodePacked(["string","uint256","address","bytes32"],[Qk,s,e,t]),g0=async(s,e,t,n,r)=>{let i=m0(s),a=iI(e,i),o=p0(t,n,a),c=keccak256(o),u=toBytes(c),h=`${await r.signMessage(u)}${nI}`,m=Bw({version:1,threshold:Yk,signers:[{isDynamic:!1,unrecovered:!0,weight:sI,signature:h}]}),y=i.map(g=>({delegateCall:g.delegateCall,revertOnError:g.revertOnError,gasLimit:g.gasLimit,target:g.target,value:g.value,data:g.data}));return encodeFunctionData({abi:Tw.mainModule.abi,functionName:"execute",args:[y,e,m]})},Xk=s=>{let e=`0x0000${s}`;return eI(e)},y0=(s,e,t)=>{let n=`${s}${nI}`,{signers:r}=Xk(t),a=[...r,{isDynamic:!1,unrecovered:!0,weight:sI,signature:n,address:e}].sort((o,c)=>{let u=BigInt(o.address??0),l=BigInt(c.address??0);return u<=l?-1:u===l?0:1});return Bw({version:1,threshold:Zk,signers:a})},Vw=async(s,e,t,n,r)=>{let i={...s.types},{EIP712Domain:a,...o}=i,c=hashTypedData({domain:s.domain,types:o,primaryType:s.primaryType,message:s.message}),u=p0(t,n,c),l=keccak256(u),h=toBytes(l),m=await r.signMessage(h),y=await r.getAddress();return y0(m,y,e)},Dw=async(s,e,t,n)=>{let r=hashMessage(e),i=p0(s,n,r),a=keccak256(i),o=toBytes(a);return t.signMessage(o)},Jt=s=>`eip155:${s}`;var Fl=class s{config;rpcProvider;getUser;constructor({config:e,rpcProvider:t,getUser:n}){this.config=e,this.rpcProvider=t,this.getUser=n;}static getResponsePreview(e){return e.length>100?`${e.substring(0,50)}...${e.substring(e.length-50)}`:e}async getUserZkEvm(){let e=await this.getUser();if(!e||!isUserZkEvm(e))throw new Error("User not authenticated or missing zkEvm data");return e}async postToRelayer(e){let t={id:1,jsonrpc:"2.0",...e},n=await this.getUserZkEvm(),r=await fetch(`${this.config.relayerUrl}/v1/transactions`,{method:"POST",headers:{Authorization:`Bearer ${n.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify(t)}),i=await r.text();if(!r.ok){let o=s.getResponsePreview(i);throw new Error(`Relayer HTTP error: ${r.status}. Content: "${o}"`)}let a;try{a=JSON.parse(i);}catch(o){let c=s.getResponsePreview(i);throw new Error(`Relayer JSON parse error: ${o instanceof Error?o.message:"Unknown error"}. Content: "${c}"`)}if(a.error)throw new Error(a.error);return a}getPreferredFeeTokenSymbol(){return this.config.feeTokenSymbol}async ethSendTransaction(e,t){let n=await this.rpcProvider.getChainId(),r={method:"eth_sendTransaction",params:[{to:e,data:t,chainId:Jt(Number(n))}]},{result:i}=await this.postToRelayer(r);return i}async imGetTransactionByHash(e){let t={method:"im_getTransactionByHash",params:[e]},{result:n}=await this.postToRelayer(t);return n}async imGetFeeOptions(e,t){let n=await this.rpcProvider.getChainId(),r={method:"im_getFeeOptions",params:[{userAddress:e,data:t,chainId:Jt(Number(n))}]},{result:i}=await this.postToRelayer(r);return i}async imSignTypedData(e,t){let n=await this.rpcProvider.getChainId(),r={method:"im_signTypedData",params:[{address:e,eip712Payload:t,chainId:Jt(Number(n))}]},{result:i}=await this.postToRelayer(r);return i}async imSign(e,t){let n=await this.rpcProvider.getChainId(),r={method:"im_sign",params:[{address:e,message:t,chainId:Jt(Number(n))}]},{result:i}=await this.postToRelayer(r);return i}};var Kl=(r=>(r[r.USER_REJECTED_REQUEST=4001]="USER_REJECTED_REQUEST",r[r.UNAUTHORIZED=4100]="UNAUTHORIZED",r[r.UNSUPPORTED_METHOD=4200]="UNSUPPORTED_METHOD",r[r.DISCONNECTED=4900]="DISCONNECTED",r))(Kl||{}),Os=(o=>(o[o.RPC_SERVER_ERROR=-32e3]="RPC_SERVER_ERROR",o[o.INVALID_REQUEST=-32600]="INVALID_REQUEST",o[o.METHOD_NOT_FOUND=-32601]="METHOD_NOT_FOUND",o[o.INVALID_PARAMS=-32602]="INVALID_PARAMS",o[o.INTERNAL_ERROR=-32603]="INTERNAL_ERROR",o[o.PARSE_ERROR=-32700]="PARSE_ERROR",o[o.TRANSACTION_REJECTED=-32003]="TRANSACTION_REJECTED",o))(Os||{}),te=class extends Error{message;code;constructor(e,t){super(t),this.message=t,this.code=e;}};function tP(s){return s.startsWith("0x")?s:`0x${s}`}function sP(s){return s.startsWith("0x")?s.slice(2):s}function Uw(s,e){return s.padStart(e,"0")}function nP(s){let e=Uw(s.r.toString(16),64),t=Uw(s.s.toString(16),64),n=Uw(s.recoveryParam?.toString(16)||"",2);return tP(e+t+n)}function rP(s){if(!s.trim())return;let e=parseInt(s,16);return e>=27?e-27:e}function iP(s,e=64){let t=sP(s);return {r:BigInt(`0x${t.substring(0,e)}`),s:BigInt(`0x${t.substring(e,e*2)}`),recoveryParam:rP(t.substring(e*2,e*2+2))}}async function uI(s,e){let t=await e.signMessage(s),n=iP(t);return nP(n)}var aP="Only sign this message from Immutable Passport";async function lI({getUser:s,ethSigner:e,multiRollupApiClients:t,accessToken:n,rpcProvider:r,flow:i}){let a=e.getAddress();a.then(()=>i.addEvent("endGetAddress"));let o=uI(aP,e);o.then(()=>i.addEvent("endSignRaw"));let c=r.getChainId();c.then(()=>i.addEvent("endDetectNetwork"));let u=t.chainsApi.listChains();u.then(()=>i.addEvent("endListChains"));let[l,h,m,y]=await Promise.all([a,o,c,u]),g=Jt(Number(m)),w=y.data?.result?.find(S=>S.id===g)?.name;if(!w)throw new te(-32603,`Chain name does not exist on for chain id ${m}`);try{let S=await t.passportApi.createCounterfactualAddressV2({chainName:w,createCounterfactualAddressRequest:{ethereum_address:l,ethereum_signature:h}},{headers:{Authorization:`Bearer ${n}`}});return i.addEvent("endCreateCounterfactualAddress"),s&&s().catch(()=>{}),S.data.counterfactual_address}catch(S){throw new te(-32603,`Failed to create counterfactual address: ${S}`)}}var Gl="imx_passport_confirmation";var w0=({url:s,title:e,width:t,height:n})=>{let r=Math.max(0,Math.round(window.screenX+(window.outerWidth-t)/2)),i=Math.max(0,Math.round(window.screenY+(window.outerHeight-n)/2)),a=window.open(s,e,`
|
|
12
12
|
scrollbars=yes,
|
|
13
13
|
width=${t},
|
|
14
14
|
height=${n},
|
|
15
15
|
top=${i},
|
|
16
16
|
left=${r}
|
|
17
|
-
`);if(!a)throw new Error("Failed to open confirmation screen");return a.focus(),a};var Wl="passport-overlay",
|
|
17
|
+
`);if(!a)throw new Error("Failed to open confirmation screen");return a.focus(),a};var Wl="passport-overlay",hI="passport-overlay-contents",b0=`${Wl}-close`,S0=`${Wl}-try-again`,fI=`
|
|
18
18
|
<svg
|
|
19
19
|
viewBox="0 0 20 20"
|
|
20
20
|
fill="none"
|
|
@@ -26,7 +26,7 @@ var Mk=Object.defineProperty;var be=(s,e)=>{for(var t in e)Mk(s,t,{get:e[t],enum
|
|
|
26
26
|
fill="#F3F3F3"
|
|
27
27
|
/>
|
|
28
28
|
</svg>
|
|
29
|
-
`,
|
|
29
|
+
`,dI=`
|
|
30
30
|
<svg
|
|
31
31
|
viewBox="0 0 17 16"
|
|
32
32
|
fill="none"
|
|
@@ -40,7 +40,7 @@ var Mk=Object.defineProperty;var be=(s,e)=>{for(var t in e)Mk(s,t,{get:e[t],enum
|
|
|
40
40
|
fill="#E01A3D"
|
|
41
41
|
/>
|
|
42
42
|
</svg>
|
|
43
|
-
`,
|
|
43
|
+
`,Lw=`
|
|
44
44
|
<svg
|
|
45
45
|
style="
|
|
46
46
|
max-width: 123px !important;
|
|
@@ -223,7 +223,7 @@ var Mk=Object.defineProperty;var be=(s,e)=>{for(var t in e)Mk(s,t,{get:e[t],enum
|
|
|
223
223
|
</clipPath>
|
|
224
224
|
</defs>
|
|
225
225
|
</svg>
|
|
226
|
-
`;var
|
|
226
|
+
`;var oP=()=>`
|
|
227
227
|
<button
|
|
228
228
|
id="${b0}"
|
|
229
229
|
style="
|
|
@@ -241,9 +241,9 @@ var Mk=Object.defineProperty;var be=(s,e)=>{for(var t in e)Mk(s,t,{get:e[t],enum
|
|
|
241
241
|
justify-content: center !important;
|
|
242
242
|
"
|
|
243
243
|
>
|
|
244
|
-
${
|
|
244
|
+
${fI}
|
|
245
245
|
</button>
|
|
246
|
-
`,
|
|
246
|
+
`,mI=()=>`
|
|
247
247
|
<button
|
|
248
248
|
id="${S0}"
|
|
249
249
|
style="
|
|
@@ -260,8 +260,8 @@ var Mk=Object.defineProperty;var be=(s,e)=>{for(var t in e)Mk(s,t,{get:e[t],enum
|
|
|
260
260
|
>
|
|
261
261
|
Try again
|
|
262
262
|
</button>
|
|
263
|
-
`,
|
|
264
|
-
${
|
|
263
|
+
`,cP=()=>`
|
|
264
|
+
${Lw}
|
|
265
265
|
<div
|
|
266
266
|
style="
|
|
267
267
|
color: #e01a3d !important;
|
|
@@ -271,7 +271,7 @@ var Mk=Object.defineProperty;var be=(s,e)=>{for(var t in e)Mk(s,t,{get:e[t],enum
|
|
|
271
271
|
margin-bottom: 10px !important;
|
|
272
272
|
"
|
|
273
273
|
>
|
|
274
|
-
${
|
|
274
|
+
${dI}
|
|
275
275
|
Pop-up blocked
|
|
276
276
|
</div>
|
|
277
277
|
<p style="
|
|
@@ -284,9 +284,9 @@ var Mk=Object.defineProperty;var be=(s,e)=>{for(var t in e)Mk(s,t,{get:e[t],enum
|
|
|
284
284
|
If the problem continues, adjust your<br />
|
|
285
285
|
browser settings.
|
|
286
286
|
</p>
|
|
287
|
-
${
|
|
288
|
-
`,
|
|
289
|
-
${
|
|
287
|
+
${mI()}
|
|
288
|
+
`,uP=()=>`
|
|
289
|
+
${Lw}
|
|
290
290
|
<p style="
|
|
291
291
|
color: #b6b6b6 !important;
|
|
292
292
|
text-align: center !important;
|
|
@@ -295,8 +295,8 @@ var Mk=Object.defineProperty;var be=(s,e)=>{for(var t in e)Mk(s,t,{get:e[t],enum
|
|
|
295
295
|
>
|
|
296
296
|
Secure pop-up not showing?<br />We'll help you re-launch
|
|
297
297
|
</p>
|
|
298
|
-
${
|
|
299
|
-
`,
|
|
298
|
+
${mI()}
|
|
299
|
+
`,pI=s=>`
|
|
300
300
|
<div
|
|
301
301
|
id="${Wl}"
|
|
302
302
|
style="
|
|
@@ -321,9 +321,9 @@ var Mk=Object.defineProperty;var be=(s,e)=>{for(var t in e)Mk(s,t,{get:e[t],enum
|
|
|
321
321
|
z-index: 2147483647 !important;
|
|
322
322
|
"
|
|
323
323
|
>
|
|
324
|
-
${
|
|
324
|
+
${oP()}
|
|
325
325
|
<div
|
|
326
|
-
id="${
|
|
326
|
+
id="${hI}"
|
|
327
327
|
style="
|
|
328
328
|
display: flex !important;
|
|
329
329
|
flex-direction: column !important;
|
|
@@ -334,45 +334,45 @@ var Mk=Object.defineProperty;var be=(s,e)=>{for(var t in e)Mk(s,t,{get:e[t],enum
|
|
|
334
334
|
${s??""}
|
|
335
335
|
</div>
|
|
336
336
|
</div>
|
|
337
|
-
`;function v0({id:s,href:e,rel:t,crossOrigin:n}){let r=`${Wl}-${s}`;if(!document.getElementById(r)){let i=document.createElement("link");i.id=r,i.href=e,t&&(i.rel=t),n&&(i.crossOrigin=n),document.head.appendChild(i);}}var yI=()=>gI(oP()),wI=()=>gI(cP());var rc=class{disableGenericPopupOverlay;disableBlockedPopupOverlay;overlay;isBlockedOverlay;tryAgainListener;onCloseListener;constructor(e,t=!1){this.disableBlockedPopupOverlay=e.disableBlockedPopupOverlay||!1,this.disableGenericPopupOverlay=e.disableGenericPopupOverlay||!1,this.isBlockedOverlay=t;}append(e,t){this.shouldAppendOverlay()&&(this.appendOverlay(),this.updateTryAgainButton(e),this.updateCloseButton(t));}update(e){this.updateTryAgainButton(e);}remove(){this.overlay&&this.overlay.remove();}shouldAppendOverlay(){return !(this.disableGenericPopupOverlay&&this.disableBlockedPopupOverlay||this.disableGenericPopupOverlay&&!this.isBlockedOverlay||this.disableBlockedPopupOverlay&&this.isBlockedOverlay)}appendOverlay(){if(!this.overlay){v0({id:"link-googleapis",href:"https://fonts.googleapis.com"}),v0({id:"link-gstatic",href:"https://fonts.gstatic.com",crossOrigin:"anonymous"}),v0({id:"link-roboto",href:"https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,400;0,500;0,700;1,400;1,500;1,700&display=swap",rel:"stylesheet"});let t=document.createElement("div");t.innerHTML=this.isBlockedOverlay?yI():wI(),document.body.insertAdjacentElement("beforeend",t),this.overlay=t;}}updateTryAgainButton(e){let t=document.getElementById(S0);t&&(this.tryAgainListener&&t.removeEventListener("click",this.tryAgainListener),this.tryAgainListener=e,t.addEventListener("click",e));}updateCloseButton(e){let t=document.getElementById(b0);t&&(this.onCloseListener&&t.removeEventListener("click",this.onCloseListener),this.onCloseListener=e,t.addEventListener("click",e));}};var ic=(s=>(s.PRODUCTION="production",s.SANDBOX="sandbox",s))(ic||{}),uP=(s=>(s.API_KEY="x-immutable-api-key",s.PUBLISHABLE_KEY="x-immutable-publishable-key",s.RATE_LIMITING_KEY="x-api-key",s))(uP||{});var Jl=13371,Gi=13473,_w=42161,Mw=421614,Sr={13371:{magicPublishableApiKey:"pk_live_10F423798A540ED7",magicProviderId:"aa80b860-8869-4f13-9000-6a6ad3d20017"},13473:{magicPublishableApiKey:"pk_live_10F423798A540ED7",magicProviderId:"aa80b860-8869-4f13-9000-6a6ad3d20017"}};var zl={chainId:13371,name:"Immutable zkEVM",rpcUrl:"https://rpc.immutable.com",relayerUrl:"https://api.immutable.com/relayer-mr",apiUrl:"https://api.immutable.com",passportDomain:"https://passport.immutable.com",magicPublishableApiKey:Sr[13371].magicPublishableApiKey,magicProviderId:Sr[13371].magicProviderId,magicTeeBasePath:"https://tee.express.magiclabs.com"},Yl={chainId:13473,name:"Immutable zkEVM Testnet",rpcUrl:"https://rpc.testnet.immutable.com",relayerUrl:"https://api.sandbox.immutable.com/relayer-mr",apiUrl:"https://api.sandbox.immutable.com",passportDomain:"https://passport.sandbox.immutable.com",magicPublishableApiKey:Sr[13473].magicPublishableApiKey,magicProviderId:Sr[13473].magicProviderId,magicTeeBasePath:"https://tee.express.magiclabs.com"},x0={chainId:42161,name:"Arbitrum One",rpcUrl:"https://arb1.arbitrum.io/rpc",relayerUrl:"https://next-arbitrum-one-relayer.sequence.app",nodeUrl:"https://next-nodes.sequence.app/arbitrum-one",apiUrl:"https://api.immutable.com",passportDomain:"https://passport.immutable.com",feeTokenSymbol:"ETH",sequenceIdentityInstrumentEndpoint:"https://next-identity.sequence.app"},E0={chainId:421614,name:"Arbitrum Sepolia",rpcUrl:"https://sepolia-rollup.arbitrum.io/rpc",relayerUrl:"https://next-arbitrum-sepolia-relayer.sequence.app",nodeUrl:"https://next-nodes.sequence.app/arbitrum-sepolia",apiUrl:"https://api.sandbox.immutable.com",passportDomain:"https://passport.sandbox.immutable.com",feeTokenSymbol:"ETH",sequenceIdentityInstrumentEndpoint:"https://next-identity.sequence-dev.app"},A0=[Yl,zl],lP={chains:[zl]},hP={chains:[Yl]},fP={chains:A0},dP={chains:[x0]},mP={chains:[E0]};var bI={zkevm:{[ic.PRODUCTION]:zl,[ic.SANDBOX]:Yl},arbitrum_one:{[ic.PRODUCTION]:x0,[ic.SANDBOX]:E0}};function gP(){let s={};for(let[e,t]of Object.entries(bI))for(let n of Object.values(t))s[n.chainId]=e;return s[15003]="zkevm",s}var yP=gP();function wP(s,e){let t=bI[s];if(!t)throw new Error(`Chain ${s} is not supported`);let n=t[e];if(!n)throw new Error(`Chain ${s} is not configured for environment ${e}`);return n}function ac(s){let e=typeof s=="string"?parseInt(s.includes(":")?s.split(":")[1]:s,10):s;return yP[e]??"zkevm"}var $w="Confirm this transaction",qw=720,Fw=480,SI=1e3;var oc=class{config;confirmationWindow;popupOptions;overlay;overlayClosed;timer;constructor(e){this.config=e,this.overlayClosed=!1;}getHref(e,t){let n=`${this.config.passportDomain}/transaction-confirmation/${e}`;if(t){let r=t?Object.keys(t).map(i=>`${i}=${t[i]}`).join("&"):"";n=`${n}?${r}`;}return n}requestConfirmation(e,t,n,r){return new Promise((i,a)=>{let o=({data:u,origin:l})=>{if(!(l!==this.config.passportDomain||u.eventType!==Gl))switch(u.messageType){case"confirmation_window_ready":{this.confirmationWindow?.postMessage({eventType:Gl,messageType:"confirmation_start"},this.config.passportDomain);break}case"transaction_confirmed":{this.closeWindow(),i({confirmed:!0});break}case"transaction_rejected":{this.closeWindow(),i({confirmed:!1});break}case"transaction_error":{this.closeWindow(),a(new Error("Error during transaction confirmation"));break}default:this.closeWindow(),a(new Error("Unsupported message type"));}},c="";if(n===vI.mr.TransactionApprovalRequestChainTypeEnum.Starkex)c=this.getHref("transaction",{transactionId:e,etherAddress:t,chainType:n});else {let l=(r?ac(r):"zkevm").replace("_","-");c=this.getHref(`${l}/transaction`,{transactionID:e,etherAddress:t,chainType:n,chainID:r});}window.addEventListener("message",o),this.showConfirmationScreen(c,o,i);})}requestMessageConfirmation(e,t,n,r){return new Promise((i,a)=>{let o=({data:h,origin:m})=>{if(!(m!==this.config.passportDomain||h.eventType!==Gl))switch(h.messageType){case"confirmation_window_ready":{this.confirmationWindow?.postMessage({eventType:Gl,messageType:"confirmation_start"},this.config.passportDomain);break}case"message_confirmed":{this.closeWindow(),i({confirmed:!0});break}case"message_rejected":{this.closeWindow(),i({confirmed:!1});break}case"message_error":{this.closeWindow(),a(new Error("Error during message confirmation"));break}default:this.closeWindow(),a(new Error("Unsupported message type"));}};window.addEventListener("message",o);let u=ac(r).replace("_","-"),l=this.getHref(`${u}/message`,{messageID:e,etherAddress:t,chainID:r,messageType:n});this.showConfirmationScreen(l,o,i);})}showServiceUnavailable(){return new Promise((e,t)=>{this.showConfirmationScreen(this.getHref("unavailable"),()=>{},()=>{this.closeWindow(),t(new Error("Service unavailable"));});})}loading(e){if(!this.config.crossSdkBridgeEnabled){this.popupOptions=e;try{this.confirmationWindow=w0({url:this.getHref("loading"),title:$w,width:e?.width||Fw,height:e?.height||qw}),this.overlay=new rc(this.config.popupOverlayOptions||{});}catch(t){let n=t instanceof Error?t.message:String(t);trackError("passport","confirmationPopupDenied",new Error(n)),this.overlay=new rc(this.config.popupOverlayOptions||{},!0);}this.overlay.append(()=>{try{this.confirmationWindow?.close(),this.confirmationWindow=w0({url:this.getHref("loading"),title:$w,width:this.popupOptions?.width||Fw,height:this.popupOptions?.height||qw});}catch{}},()=>{this.overlayClosed=!0,this.closeWindow();});}}closeWindow(){this.confirmationWindow?.close(),this.overlay?.remove(),this.overlay=void 0;}showConfirmationScreen(e,t,n){if(this.confirmationWindow&&(this.confirmationWindow.location.href=e),!this.overlay){this.overlayClosed=!1,n({confirmed:!1});return}let r=()=>{(this.confirmationWindow?.closed||this.overlayClosed)&&(clearInterval(this.timer),window.removeEventListener("message",t),n({confirmed:!1}),this.overlayClosed=!1,this.confirmationWindow=void 0);};this.timer=setInterval(r,SI),this.overlay.update(()=>this.recreateConfirmationWindow(e,r));}recreateConfirmationWindow(e,t){try{clearInterval(this.timer),this.confirmationWindow?.close(),this.confirmationWindow=w0({url:e,title:$w,width:this.popupOptions?.width||Fw,height:this.popupOptions?.height||qw}),this.timer=setInterval(t,SI);}catch{}}};var Wi=(o=>(o.WALLET_CONNECTION_ERROR="WALLET_CONNECTION_ERROR",o.TRANSACTION_REJECTED="TRANSACTION_REJECTED",o.INVALID_CONFIGURATION="INVALID_CONFIGURATION",o.UNAUTHORIZED="UNAUTHORIZED",o.GUARDIAN_ERROR="GUARDIAN_ERROR",o.SERVICE_UNAVAILABLE_ERROR="SERVICE_UNAVAILABLE_ERROR",o.NOT_LOGGED_IN_ERROR="NOT_LOGGED_IN_ERROR",o))(Wi||{}),ze=class extends Error{type;constructor(e,t){super(e),this.name="WalletError",this.type=t;}};var Ji=s=>typeof s=="object"&&s!==null&&"isAxiosError"in s;var Kw="Transaction requires confirmation but this functionality is not supported in this environment. Please contact Immutable support if you need to enable this feature.",I0=s=>BigInt(s).toString(),vP=s=>{try{return s.map(e=>({delegateCall:e.delegateCall===!0,revertOnError:e.revertOnError===!0,gasLimit:e.gasLimit?I0(e.gasLimit):"0",target:e.to??zeroAddress,value:e.value?I0(e.value):"0",data:e.data?e.data.toString():"0x"}))}catch(e){let t=e instanceof Error?e.message:String(e);throw new ne(-32602,`Transaction failed to parsing: ${t}`)}},cc=class{guardianApi;confirmationScreen;crossSdkBridgeEnabled;auth;constructor({config:e,auth:t,guardianApi:n,authConfig:r}){this.confirmationScreen=new oc(r),this.crossSdkBridgeEnabled=e.crossSdkBridgeEnabled,this.guardianApi=n,this.auth=t;}withConfirmationScreen(e){return t=>this.withConfirmationScreenTask(e)(t)()}withConfirmationScreenTask(e){return t=>async()=>{this.confirmationScreen.loading(e);try{return await t()}catch(n){throw n instanceof ze&&n.type==="SERVICE_UNAVAILABLE_ERROR"?(await this.confirmationScreen.showServiceUnavailable(),n):(this.confirmationScreen.closeWindow(),n)}}}withDefaultConfirmationScreenTask(e){return this.withConfirmationScreenTask()(e)}async evaluateEVMTransaction({chainId:e,nonce:t,metaTransactions:n}){let r=await this.auth.getUserZkEvm(),i={Authorization:`Bearer ${r.accessToken}`},a=vP(n);try{return (await this.guardianApi.evaluateTransaction({id:"evm",transactionEvaluationRequest:{chainType:"evm",chainId:e,transactionData:{nonce:t,userAddress:r.zkEvm.ethAddress,metaTransactions:a}}},{headers:i})).data}catch(o){if(Ji(o)&&o.response?.status===403)throw new ze("Service unavailable","SERVICE_UNAVAILABLE_ERROR");let c=o instanceof Error?o.message:String(o);throw new ne(-32603,`Transaction failed to validate with error: ${c}`)}}async validateEVMTransaction({chainId:e,nonce:t,metaTransactions:n,isBackgroundTransaction:r}){let i=await this.evaluateEVMTransaction({chainId:e,nonce:t,metaTransactions:n}),{confirmationRequired:a,transactionId:o}=i;if(a&&this.crossSdkBridgeEnabled)throw new ne(-32003,Kw);if(a&&o){let c=await this.auth.getUserZkEvm();if(!(await this.confirmationScreen.requestConfirmation(o,c.zkEvm.ethAddress,vI.mr.TransactionApprovalRequestChainTypeEnum.Evm,e)).confirmed)throw new ne(-32003,"Transaction rejected by user")}else r||this.confirmationScreen.closeWindow();}async handleEIP712MessageEvaluation({chainID:e,payload:t}){try{let n=await this.auth.getUserZkEvm();if(n===null)throw new ne(4100,"User not logged in. Please log in first.");return (await this.guardianApi.evaluateMessage({messageEvaluationRequest:{chainID:e,payload:t}},{headers:{Authorization:`Bearer ${n.accessToken}`}})).data}catch(n){let r=n instanceof Error?n.message:String(n);throw new ne(-32603,`Message failed to validate with error: ${r}`)}}async evaluateEIP712Message({chainID:e,payload:t}){let{messageId:n,confirmationRequired:r}=await this.handleEIP712MessageEvaluation({chainID:e,payload:t});if(r&&this.crossSdkBridgeEnabled)throw new ne(-32003,Kw);if(r&&n){let i=await this.auth.getUserZkEvm();if(!(await this.confirmationScreen.requestMessageConfirmation(n,i.zkEvm.ethAddress,"eip712",e)).confirmed)throw new ne(-32003,"Signature rejected by user")}else this.confirmationScreen.closeWindow();}async handleERC191MessageEvaluation({chainID:e,payload:t}){try{let n=await this.auth.getUserZkEvm();if(n===null)throw new ne(4100,"User not logged in. Please log in first.");return (await this.guardianApi.evaluateErc191Message({eRC191MessageEvaluationRequest:{chainID:Jt(Number(e)),payload:t}},{headers:{Authorization:`Bearer ${n.accessToken}`}})).data}catch(n){let r=n instanceof Error?n.message:String(n);throw new ne(-32603,`Message failed to validate with error: ${r}`)}}async evaluateERC191Message({chainID:e,payload:t}){let{messageId:n,confirmationRequired:r}=await this.handleERC191MessageEvaluation({chainID:e,payload:t});if(r&&this.crossSdkBridgeEnabled)throw new ne(-32003,Kw);if(r&&n){let i=await this.auth.getUserZkEvm();if(!(await this.confirmationScreen.requestMessageConfirmation(n,i.zkEvm.ethAddress,"erc191",String(e))).confirmed)throw new ne(-32003,"Signature rejected by user")}else this.confirmationScreen.closeWindow();}};var xP=s=>new Promise(e=>{setTimeout(()=>e(),s);}),C0=async(s,e)=>{let{retries:t=3,interval:n=1e3,finalErr:r=Error("Retry failed"),finallyFn:i=()=>{}}=e||{};try{return await s()}catch{return t<=0?Promise.reject(r):(await xP(n),C0(s,{retries:t-1,finalErr:r,finallyFn:i}))}finally{t<=0&&i();}};var EP=30,AP=1e3,IP=async(s,e,t)=>{let n=m0([s]),r=Dw(n),i=await t.imGetFeeOptions(e,r);if(!i||!Array.isArray(i))throw new Error("Invalid fee options received from relayer");let a=t.getPreferredFeeTokenSymbol(),o=i.find(c=>c.tokenSymbol===a);if(!o)throw new Error(`Failed to retrieve fees for ${a} token`);return o},CP=async(s,e,t,n,r)=>{if(!s.to)throw new ne(-32602,'eth_sendTransaction requires a "to" field');let i={to:s.to.toString(),data:s.data,nonce:BigInt(0),value:s.value,revertOnError:!0},[a,o]=await Promise.all([ql(e,n,r),IP(i,n,t)]),c=[{...i,nonce:a}],u=BigInt(o.tokenPrice);return u!==BigInt(0)&&c.push({nonce:a,to:o.recipientAddress,value:u,revertOnError:!0}),c},N0=async(s,e,t)=>{let r=await C0(async()=>{let i=await s.imGetTransactionByHash(e);if(i.status==="PENDING")throw new Error;return i},{retries:EP,interval:AP,finalErr:new ne(-32e3,"transaction hash not generated in time")});if(t.addEvent("endRetrieveRelayerTransaction"),!["SUBMITTED","SUCCESSFUL"].includes(r.status)){let i=`Transaction failed to submit with status ${r.status}.`;throw r.statusMessage&&(i+=` Error message: ${r.statusMessage}`),new ne(-32e3,i)}return r},k0=async({transactionRequest:s,ethSigner:e,rpcProvider:t,guardianClient:n,relayerClient:r,zkEvmAddress:i,flow:a,nonceSpace:o,isBackgroundTransaction:c})=>{let u=await t.getChainId(),l=BigInt(u);a.addEvent("endDetectNetwork");let h=await CP(s,t,r,i,o);a.addEvent("endBuildMetaTransactions");let{nonce:m}=h[0];if(typeof m>"u")throw new Error("Failed to retrieve nonce from the smart wallet");let y=async()=>{await n.validateEVMTransaction({chainId:Jt(Number(u)),nonce:I0(m),metaTransactions:h,isBackgroundTransaction:c}),a.addEvent("endValidateEVMTransaction");},g=async()=>{let C=await g0(h,m,l,i,e);return a.addEvent("endGetSignedMetaTransactions"),C},[,w]=await Promise.all([y(),g()]),S=await r.ethSendTransaction(i,w);return a.addEvent("endRelayerSendTransaction"),{signedTransactions:w,relayerId:S,nonce:m}},NP=async s=>{if(!s.to)throw new ne(-32602,'im_signEjectionTransaction requires a "to" field');if(typeof s.nonce>"u")throw new ne(-32602,'im_signEjectionTransaction requires a "nonce" field');if(!s.chainId)throw new ne(-32602,'im_signEjectionTransaction requires a "chainId" field');return [{to:s.to.toString(),data:s.data,nonce:s.nonce??void 0,value:s.value,revertOnError:!0}]},EI=async({transactionRequest:s,ethSigner:e,zkEvmAddress:t,flow:n})=>{let r=await NP(s);n.addEvent("endBuildMetaTransactions");let i=await g0(r,s.nonce,BigInt(s.chainId??0),t,e);return n.addEvent("endGetSignedMetaTransactions"),{to:t,data:i,chainId:Jt(Number(s.chainId??0))}};var Gw=async({params:s,ethSigner:e,rpcProvider:t,relayerClient:n,guardianClient:r,zkEvmAddress:i,flow:a,nonceSpace:o,isBackgroundTransaction:c=!1})=>{let u=s[0],{relayerId:l}=await k0({transactionRequest:u,ethSigner:e,rpcProvider:t,guardianClient:r,relayerClient:n,zkEvmAddress:i,flow:a,nonceSpace:o,isBackgroundTransaction:c}),{hash:h}=await N0(n,l,a);return h};var AI=["types","domain","primaryType","message"],kP=s=>AI.every(e=>e in s),PP=(s,e)=>{let t;if(typeof s=="string")try{t=JSON.parse(s);}catch(r){throw new ne(-32602,`Failed to parse typed data JSON: ${r}`)}else if(typeof s=="object")t=s;else throw new ne(-32602,`Invalid typed data argument: ${s}`);if(!kP(t))throw new ne(-32602,`Invalid typed data argument. The following properties are required: ${AI.join(", ")}`);let n=t.domain?.chainId;if(n){let r;if(typeof n=="string"?n.startsWith("0x")?r=parseInt(n,16):r=parseInt(n,10):r=Number(n),t.domain.chainId=r,BigInt(r)!==e)throw new ne(-32602,`Invalid chainId, expected ${e}`)}return t},II=async({params:s,method:e,ethSigner:t,rpcProvider:n,relayerClient:r,guardianClient:i,flow:a})=>{let o=s[0],c=s[1];if(!o||!c)throw new ne(-32602,`${e} requires an address and a typed data JSON`);let u=await n.getChainId(),l=PP(c,BigInt(u));a.addEvent("endDetectNetwork"),await i.evaluateEIP712Message({chainID:String(u),payload:l}),a.addEvent("endValidateMessage");let h=await r.imSignTypedData(o,l);a.addEvent("endRelayerSignTypedData");let m=await Lw(l,h,BigInt(u),o,t);return a.addEvent("getSignedTypedData"),m};var BP=s=>{let e=0;for(;e<s.length&&s[e]===0;)e++;return s.slice(e)},OP=s=>{if(typeof TextDecoder<"u")return new TextDecoder("utf-8").decode(s);let e="";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return decodeURIComponent(escape(e))},CI=s=>{if(!s)return s;try{let e=toBytes(s),t=BP(e);return OP(t)}catch{return s}};var P0=async({params:s,ethSigner:e,zkEvmAddress:t,rpcProvider:n,guardianClient:r,relayerClient:i,flow:a})=>{let o=s[0],c=s[1];if(!c||!o)throw new ne(-32602,"personal_sign requires an address and a message");if(c.toLowerCase()!==t.toLowerCase())throw new ne(-32602,"personal_sign requires the signer to be the from address");let u=CI(o),l=await n.getChainId();a.addEvent("endDetectNetwork");let h=BigInt(l),m=jw(h,u,e,c);m.then(()=>a.addEvent("endEOASignature")),await r.evaluateERC191Message({chainID:h,payload:u}),a.addEvent("endEvaluateERC191Message");let[y,g]=await Promise.all([m,i.imSign(c,u)]);a.addEvent("endRelayerSign");let w=await e.getAddress();return a.addEvent("endGetEOAAddress"),y0(y,w,g)};var RP="/v1/sdk/session-activity/check",T0,NI=s=>{T0||(T0=s);},VP=s=>{let e=new URL(RP,T0);return Object.entries(s).forEach(([t,n])=>{n!=null&&e.searchParams.append(t,String(n));}),e.toString()};async function kI(s){if(!T0)throw new Error("Client not initialised");let e=await fetch(VP(s));if(e.status!==404){if(!e.ok)throw new Error(`Session activity request failed with status ${e.status}`);return e.json()}}function TI(s,e){return (...t)=>{try{let n=s(...t);return n instanceof Promise?n.catch(r=>(r instanceof Error&&trackError("passport","sessionActivityError",r),e)):n}catch(n){return n instanceof Error&&trackError("passport","sessionActivityError",n),e}}}var{getItem:BI,setItem:Ww}=utils.localStorage,Jw="sessionActivitySendCount",OI="sessionActivityDate",zw={},vr={},B0={},RI=()=>{vr=BI(Jw)||{};let s=BI(OI),e=new Date,t=e.getFullYear(),n=`${e.getMonth()+1}`.padStart(2,"0"),r=`${e.getDate()}`.padStart(2,"0"),i=`${t}-${n}-${r}`;(!s||s!==i)&&(vr={}),Ww(OI,i),Ww(Jw,vr);};RI();var _P=s=>{RI(),vr[s]||(vr[s]=0),vr[s]++,Ww(Jw,vr),zw[s]=0;},MP=async s=>new Promise(e=>{setTimeout(e,s*1e3);}),$P=async s=>{let e=s.flow||trackFlow("passport","sendSessionActivity"),t=s.passportClient;if(!t)throw e.addEvent("No Passport Client ID"),new Error("No Passport Client ID provided");if(B0[t])return;B0[t]=!0;let{sendTransaction:n,sessionActivityApiUrl:r}=s;if(!n)throw new Error("No sendTransaction function provided");if(!r)throw new Error("No session activity API URL provided");NI(r);let i=s.walletAddress;if(!i)throw e.addEvent("No Passport Wallet Address"),new Error("No wallet address");let a;try{if(a=await kI({clientId:t,wallet:i,checkCount:zw[t]||0,sendCount:vr[t]||0}),zw[t]++,!a)return}catch(o){throw e.addEvent("Failed to fetch details"),new Error("Failed to get details",{cause:o})}if(a&&a.contractAddress&&a.functionName){let o=parseAbi([`function ${a.functionName}()`]),c=encodeFunctionData({abi:o,functionName:a.functionName}),u=a.contractAddress;try{e.addEvent("Start Sending Transaction");let l=await s.sendTransaction([{to:u,from:i,data:c}],e);_P(t),e.addEvent("Transaction Sent",{tx:l});}catch(l){e.addEvent("Failed to send Transaction");let h=new Error("Failed to send transaction",{cause:l});trackError("passport","sessionActivityError",h,{flowId:e.details.flowId});}}a&&a.delay&&a.delay>0&&(e.addEvent("Delaying Transaction",{delay:a.delay}),await MP(a.delay),setTimeout(()=>{e.addEvent("Retrying after Delay"),B0[t]=!1,VI({...s,flow:e});},0));},VI=s=>TI($P)(s).then(()=>{B0[s.passportClient]=!1;}),DI=VI;var LI=async({params:s,ethSigner:e,rpcProvider:t,relayerClient:n,guardianClient:r,zkEvmAddress:i,flow:a})=>{let o={to:i,value:0n},{relayerId:c}=await k0({transactionRequest:o,ethSigner:e,rpcProvider:t,guardianClient:r,relayerClient:n,zkEvmAddress:i,flow:a});return r.withConfirmationScreen()(async()=>{let u=await P0({params:s,ethSigner:e,zkEvmAddress:i,rpcProvider:t,guardianClient:r,relayerClient:n,flow:a});return await N0(n,c,a),u})};var jI=async({params:s,ethSigner:e,zkEvmAddress:t,flow:n})=>{if(!s||s.length!==1)throw new ne(-32602,"im_signEjectionTransaction requires a singular param (hash)");let r=s[0];return await EI({transactionRequest:r,ethSigner:e,zkEvmAddress:t,flow:n})};var O0=s=>"zkEvm"in s,Xl=class{#e;#s;#n;#t;#a;#i;#r;#u;#c;#o;isPassport=!0;constructor({auth:e,config:t,multiRollupApiClients:n,passportEventEmitter:r,guardianClient:i,ethSigner:a,user:o,sessionActivityApiUrl:c}){this.#e=e,this.#s=t,this.#i=i,this.#a=r,this.#n=c,this.#o=a,this.#r=createPublicClient({transport:http(this.#s.zkEvmRpcUrl)}),this.#c=new Fl({config:this.#s,rpcProvider:this.#r,auth:this.#e}),this.#u=n,this.#t=new TypedEventEmitter,o&&O0(o)&&this.#h(o.zkEvm.ethAddress),r.on(AuthEvents.LOGGED_IN,u=>{O0(u)&&this.#h(u.zkEvm.ethAddress);}),r.on(AuthEvents.LOGGED_OUT,this.#f),r.on("accountsRequested",DI);}#f=()=>{this.#t.emit("accountsChanged",[]);};async#h(e,t){if(!this.#n)return;let n=BigInt(1),r=async(i,a)=>await Gw({params:i,ethSigner:this.#o,guardianClient:this.#i,rpcProvider:this.#r,relayerClient:this.#c,zkEvmAddress:e,flow:a,nonceSpace:n,isBackgroundTransaction:!0});this.#a.emit("accountsRequested",{sessionActivityApiUrl:this.#n,sendTransaction:r,walletAddress:e,passportClient:t||await this.#e.getClientId()});}async#l(){try{let e=await this.#e.getUser();return e&&O0(e)?e.zkEvm.ethAddress:void 0}catch{return}}async#d(e){switch(e.method){case"eth_requestAccounts":{let t=await this.#l();if(t)return [t];let n=trackFlow("passport","ethRequestAccounts");try{let r=await this.#e.getUserOrLogin();n.addEvent("endGetUserOrLogin");let i;return O0(r)?i=r.zkEvm.ethAddress:(n.addEvent("startUserRegistration"),i=await hI({ethSigner:this.#o,auth:this.#e,multiRollupApiClients:this.#u,accessToken:r.accessToken,rpcProvider:this.#r,flow:n}),n.addEvent("endUserRegistration")),this.#t.emit("accountsChanged",[i]),identify({passportId:r.profile.sub}),this.#h(i),[i]}catch(r){throw r instanceof Error?trackError("passport","ethRequestAccounts",r,{flowId:n.details.flowId}):n.addEvent("errored"),r}finally{n.addEvent("End");}}case"eth_sendTransaction":{let t=await this.#l();if(!t)throw new ne(4100,"Unauthorised - call eth_requestAccounts first");let n=trackFlow("passport","ethSendTransaction");try{return await this.#i.withConfirmationScreen({width:480,height:720})(async()=>await Gw({params:e.params||[],ethSigner:this.#o,guardianClient:this.#i,rpcProvider:this.#r,relayerClient:this.#c,zkEvmAddress:t,flow:n}))}catch(r){throw r instanceof Error?trackError("passport","eth_sendTransaction",r,{flowId:n.details.flowId}):n.addEvent("errored"),r}finally{n.addEvent("End");}}case"eth_accounts":{let t=await this.#l();return t?[t]:[]}case"personal_sign":{let t=await this.#l();if(!t)throw new ne(4100,"Unauthorised - call eth_requestAccounts first");let n=trackFlow("passport","personalSign");try{return await this.#i.withConfirmationScreen({width:480,height:720})(async()=>this.#s.forceScwDeployBeforeMessageSignature&&!(await ql(this.#r,t)>BigInt(0))?await LI({params:e.params||[],zkEvmAddress:t,ethSigner:this.#o,rpcProvider:this.#r,guardianClient:this.#i,relayerClient:this.#c,flow:n}):await P0({params:e.params||[],zkEvmAddress:t,ethSigner:this.#o,rpcProvider:this.#r,guardianClient:this.#i,relayerClient:this.#c,flow:n}))}catch(r){throw r instanceof Error?trackError("passport","personal_sign",r,{flowId:n.details.flowId}):n.addEvent("errored"),r}finally{n.addEvent("End");}}case"eth_signTypedData":case"eth_signTypedData_v4":{if(!await this.#l())throw new ne(4100,"Unauthorised - call eth_requestAccounts first");let n=trackFlow("passport","ethSignTypedDataV4");try{return await this.#i.withConfirmationScreen({width:480,height:720})(async()=>await II({method:e.method,params:e.params||[],ethSigner:this.#o,rpcProvider:this.#r,relayerClient:this.#c,guardianClient:this.#i,flow:n}))}catch(r){throw r instanceof Error?trackError("passport","eth_signTypedData",r,{flowId:n.details.flowId}):n.addEvent("errored"),r}finally{n.addEvent("End");}}case"eth_chainId":{let t=await this.#r.getChainId();return toHex(t)}case"eth_getBalance":case"eth_getCode":case"eth_getTransactionCount":{let[t,n]=e.params||[];return this.#r.request({method:e.method,params:[t,n||"latest"]})}case"eth_getStorageAt":{let[t,n,r]=e.params||[];return this.#r.request({method:"eth_getStorageAt",params:[t,n,r||"latest"]})}case"eth_call":case"eth_estimateGas":{let[t,n]=e.params||[];return this.#r.request({method:e.method,params:[t,n||"latest"]})}case"eth_gasPrice":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":return this.#r.request({method:e.method,params:e.params||[]});case"im_signEjectionTransaction":{let t=await this.#l();if(!t)throw new ne(4100,"Unauthorised - call eth_requestAccounts first");let n=trackFlow("passport","imSignEjectionTransaction");try{return await jI({params:e.params||[],ethSigner:this.#o,zkEvmAddress:t,flow:n})}catch(r){throw r instanceof Error?trackError("passport","imSignEjectionTransaction",r,{flowId:n.details.flowId}):n.addEvent("errored"),r}finally{n.addEvent("End");}}case"im_addSessionActivity":{let[t]=e.params||[],n=await this.#l();return n&&this.#h(n,t),null}default:throw new ne(4200,"Method not supported")}}async request(e){try{return this.#d(e)}catch(t){throw t instanceof ne?t:t instanceof Error?new ne(-32603,t.message):new ne(-32603,"Internal error")}}on(e,t){this.#t.on(e,t);}removeListener(e,t){this.#t.removeListener(e,t);}};var JP="Only sign this message from Immutable Passport";function zP(s){let e=s.startsWith("0x")?s.slice(2):s,t=e.substring(0,64),n=e.substring(64,128),r=e.substring(128,130),i=parseInt(r,16),o=(i>=27?i-27:i).toString(16).padStart(2,"0");return `0x${t}${n}${o}`}async function Yw({auth:s,ethSigner:e,multiRollupApiClients:t,accessToken:n,rpcProvider:r,flow:i}){let a=e.getAddress();a.then(()=>i.addEvent("endGetAddress"));let o=e.signMessage(JP).then(zP);o.then(()=>i.addEvent("endSignRaw"));let c=r.getChainId();c.then(()=>i.addEvent("endDetectNetwork"));let u=t.chainsApi.listChains();u.then(()=>i.addEvent("endListChains"));let[l,h,m,y]=await Promise.all([a,o,c,u]),g=Jt(Number(m)),w=y.data?.result?.find(S=>S.id===g)?.name;if(!w)throw new ne(-32603,`Chain name does not exist for chain id ${m}`);try{let S=await t.passportApi.createCounterfactualAddressV2({chainName:w,createCounterfactualAddressRequest:{ethereum_address:l,ethereum_signature:h}},{headers:{Authorization:`Bearer ${n}`}});return i.addEvent("endCreateCounterfactualAddress"),s.forceUserRefreshInBackground(),S.data.counterfactual_address}catch(S){throw i.addEvent("errorRegisteringUser"),new ne(-32603,`Failed to create counterfactual address: ${S}`)}}function UI(s,e){return e in s&&!!s[e]?.ethAddress}function HI(s,e){return s[e]?.ethAddress}var eh=class{#e;#s;#n;#t;#a;#i;#r;#u;isPassport=!0;constructor({auth:e,chainConfig:t,multiRollupApiClients:n,guardianClient:r,ethSigner:i,passportEventEmitter:a}){let o=ac(t.chainId);if(o==="zkevm")throw new Error("SequenceProvider cannot be used for zkEVM chains. Use ZkEvmProvider instead.");this.#u=o,this.#e=e,this.#s=t,this.#n=n,this.#i=r,this.#r=i,this.#a=a,this.#t=createPublicClient({transport:http(this.#s.rpcUrl)});}async#c(){let e=await this.#e.getUser();if(e&&UI(e,this.#u))return HI(e,this.#u)}async#o(e){switch(e.method){case"eth_requestAccounts":{let t=await this.#c();if(t)return [t];let n=trackFlow("passport","ethRequestAccounts");try{let r=await this.#e.getUserOrLogin();n.addEvent("endGetUserOrLogin");let i;if(UI(r,this.#u)?i=HI(r,this.#u):(n.addEvent("startUserRegistration"),i=await Yw({auth:this.#e,ethSigner:this.#r,multiRollupApiClients:this.#n,accessToken:r.accessToken,rpcProvider:this.#t,flow:n}),n.addEvent("endUserRegistration")),!i)throw new ne(-32603,"Failed to get user address after registration");return this.#a.emit("accountsChanged",[i]),identify({passportId:r.profile.sub}),[i]}catch(r){throw r instanceof Error?trackError("passport","ethRequestAccounts",r,{flowId:n.details.flowId}):n.addEvent("errored"),r}finally{n.addEvent("End");}}case"eth_accounts":{let t=await this.#c();return t?[t]:[]}case"eth_sendTransaction":throw new ne(4200,"eth_sendTransaction not yet implemented for this chain");case"personal_sign":throw new ne(4200,"personal_sign not yet implemented for this chain");case"eth_signTypedData":case"eth_signTypedData_v4":throw new ne(4200,"eth_signTypedData not yet implemented for this chain");case"eth_chainId":{let t=await this.#t.getChainId();return toHex(t)}case"eth_getBalance":case"eth_getCode":case"eth_getTransactionCount":{let[t,n]=e.params||[];return this.#t.request({method:e.method,params:[t,n||"latest"]})}case"eth_getStorageAt":{let[t,n,r]=e.params||[];return this.#t.request({method:"eth_getStorageAt",params:[t,n,r||"latest"]})}case"eth_call":case"eth_estimateGas":{let[t,n]=e.params||[];return this.#t.request({method:e.method,params:[t,n||"latest"]})}case"eth_gasPrice":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":return this.#t.request({method:e.method,params:e.params||[]});default:throw new ne(4200,"Method not supported")}}async request(e){try{return this.#o(e)}catch(t){throw t instanceof ne?t:t instanceof Error?new ne(-32603,t.message):new ne(-32603,"Internal error")}}on(e,t){this.#a.on(e,t);}removeListener(e,t){this.#a.removeListener(e,t);}};var th=class{passportDomain;zkEvmRpcUrl;relayerUrl;indexerMrBasePath;jsonRpcReferrer;forceScwDeployBeforeMessageSignature;crossSdkBridgeEnabled;feeTokenSymbol;constructor(e){this.passportDomain=e.passportDomain,this.zkEvmRpcUrl=e.zkEvmRpcUrl,this.relayerUrl=e.relayerUrl,this.indexerMrBasePath=e.indexerMrBasePath,this.jsonRpcReferrer=e.jsonRpcReferrer,this.forceScwDeployBeforeMessageSignature=e.forceScwDeployBeforeMessageSignature||!1,this.crossSdkBridgeEnabled=e.crossSdkBridgeEnabled||!1,this.feeTokenSymbol=e.feeTokenSymbol||"IMX";}};var Zw=async(s,e,t=!0,n=!0)=>{let r=trackFlow("passport",e,t);try{return await s(r)}catch(i){throw i instanceof Error?trackError("passport",e,i,{flowId:r.details.flowId}):r.addEvent("errored"),i}finally{n&&r.addEvent("End");}};var MI="ETH",rT=s=>s.reduce((e,t)=>`${e}${t.toString(16).padStart(2,"0")}`,""),iT=s=>{if(typeof TextEncoder<"u")return new TextEncoder().encode(s);let e=unescape(encodeURIComponent(s)),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t},aT=s=>{let e=iT(s),t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n="";for(let r=0;r<e.length;r+=3){let i=e[r],a=e[r+1],o=e[r+2],c=i<<16|(a??0)<<8|(o??0),u=c>>18&63,l=c>>12&63,h=c>>6&63,m=c&63;n+=t[u]+t[l],n+=Number.isFinite(a)?t[h]:"=",n+=Number.isFinite(o)?t[m]:"=";}return n},uc=class s{auth;magicTeeApiClient;userWallet=null;createWalletPromise=null;constructor(e,t){this.auth=e,this.magicTeeApiClient=t;}async getUserWallet(){let{userWallet:e}=this;e||(e=await this.createWallet());let t=await this.getUserOrThrow();if(t.profile.sub!==e.userIdentifier&&(e=await this.createWallet(t)),isUserZkEvm(t)&&t.zkEvm.userAdminAddress.toLowerCase()!==e.walletAddress.toLowerCase())throw new ze(`Wallet address mismatch.Rollup: zkEVM, TEE address: ${e.walletAddress}, profile address: ${t.zkEvm.userAdminAddress}`,"WALLET_CONNECTION_ERROR");return e}async createWallet(e){return this.createWalletPromise?this.createWalletPromise:(this.createWalletPromise=new Promise(async(t,n)=>{try{this.userWallet=null;let r=e||await this.getUserOrThrow(),i=s.getHeaders(r);await Zw(async a=>{try{let o=performance.now(),c=await this.magicTeeApiClient.walletApi.createWalletV1WalletPost({xMagicChain:MI},{headers:i});return trackDuration("passport",a.details.flowName,Math.round(performance.now()-o)),this.userWallet={userIdentifier:r.profile.sub,walletAddress:c.data.public_address},t(this.userWallet)}catch(o){let c="MagicTEE: Failed to initialise EOA";return Ji(o)?o.response?c+=` with status ${o.response.status}: ${JSON.stringify(o.response.data)}`:c+=`: ${o.message}`:c+=`: ${o.message}`,n(new Error(c))}},"magicCreateWallet");}catch(r){n(r);}finally{this.createWalletPromise=null;}}),this.createWalletPromise)}async getUserOrThrow(){let e=await this.auth.getUser();if(!e)throw new ze("User has been logged out","NOT_LOGGED_IN_ERROR");return e}static getHeaders(e){if(!e)throw new ze("User has been logged out","NOT_LOGGED_IN_ERROR");return {Authorization:`Bearer ${e.idToken}`}}async getAddress(){return (await this.getUserWallet()).walletAddress}async signMessage(e){await this.getUserWallet();let t=e instanceof Uint8Array?`0x${rT(e)}`:e,n=await this.getUserOrThrow(),r=s.getHeaders(n);return Zw(async i=>{try{let a=performance.now(),o=await this.magicTeeApiClient.signOperationsApi.signMessageV1WalletSignMessagePost({signMessageRequest:{message_base64:aT(t)},xMagicChain:MI},{headers:r});return trackDuration("passport",i.details.flowName,Math.round(performance.now()-a)),o.data.signature}catch(a){let o="MagicTEE: Failed to sign message using EOA";throw Ji(a)?a.response?o+=` with status ${a.response.status}: ${JSON.stringify(a.response.data)}`:o+=`: ${a.message}`:o+=`: ${a.message}`,new Error(o)}},"magicSignMessage")}};var Qw={icon:'data:image/svg+xml,<svg viewBox="0 0 48 48" class="SvgIcon undefined Logo Logo--PassportSymbolOutlined css-1dn9atd" xmlns="http://www.w3.org/2000/svg"><g data-testid="undefined__g"><circle cx="24" cy="24" r="22.5" fill="url(%23paint0_radial_6324_83922)"></circle><circle cx="24" cy="24" r="22.5" fill="url(%23paint1_radial_6324_83922)"></circle><path d="M24 0C10.7452 0 0 10.7452 0 24C0 37.2548 10.7452 48 24 48C37.2548 48 48 37.2548 48 24C48 10.7452 37.2548 0 24 0ZM23.0718 9.16608C23.7383 8.83951 24.4406 8.86188 25.087 9.2287C27.3282 10.5059 29.5627 11.7942 31.786 13.096C32.5018 13.5165 32.8686 14.1897 32.8708 15.0173C32.8843 17.9184 32.8798 20.8171 32.8708 23.7182C32.8708 23.8255 32.8015 23.9821 32.7143 24.0335C31.8531 24.548 30.9808 25.0423 30.0347 25.5881V25.1318C30.0347 22.148 30.0257 19.1664 30.0414 16.1827C30.0436 15.6101 29.8468 15.241 29.339 14.9525C26.7377 13.474 24.1499 11.9687 21.5575 10.4723C21.4457 10.4075 21.3361 10.3381 21.1661 10.2352C21.8326 9.85722 22.4321 9.47698 23.0673 9.16608H23.0718ZM22.5953 38.8451C22.45 38.7713 22.3426 38.7198 22.2375 38.6595C18.8041 36.68 15.3752 34.687 11.9307 32.7232C10.9644 32.173 10.5238 31.3879 10.5349 30.2852C10.5551 27.9411 10.5484 25.597 10.5372 23.2507C10.5327 22.1927 10.9622 21.4255 11.8926 20.8977C14.3105 19.5221 16.715 18.1264 19.1195 16.7284C19.3275 16.6076 19.4796 16.5875 19.6965 16.7172C20.5264 17.216 21.3719 17.6924 22.2554 18.2024C22.0876 18.3031 21.9601 18.3791 21.8304 18.4552C19.2268 19.9582 16.6278 21.4658 14.0175 22.9599C13.5903 23.2037 13.3912 23.5213 13.3957 24.0179C13.4091 25.8654 13.4114 27.713 13.3957 29.5605C13.3912 30.0705 13.5948 30.3948 14.0332 30.6453C16.7866 32.2199 19.5288 33.8125 22.28 35.3916C22.5126 35.5258 22.611 35.6645 22.6065 35.9418C22.5864 36.888 22.5998 37.8363 22.5998 38.8473L22.5953 38.8451ZM22.5953 33.553C22.356 33.4166 22.1838 33.3204 22.0116 33.2198C19.8285 31.9605 17.6477 30.6967 15.4602 29.4464C15.2231 29.3122 15.1359 29.1668 15.1381 28.8917C15.1538 27.4714 15.1471 26.0511 15.1426 24.6308C15.1426 24.4384 15.1717 24.3064 15.3618 24.1991C16.167 23.7495 16.9633 23.2798 17.7618 22.8212C17.8199 22.7877 17.8826 22.7631 17.9877 22.7116V24.3064C17.9877 25.1698 18.0011 26.0354 17.9832 26.8988C17.972 27.3909 18.1622 27.7241 18.5916 27.9657C19.8285 28.6636 21.0498 29.3883 22.2867 30.0839C22.5305 30.2203 22.6043 30.3724 22.5998 30.6408C22.5842 31.5847 22.5931 32.5308 22.5931 33.5508L22.5953 33.553ZM20.0746 14.91C19.6116 14.6371 19.2157 14.6393 18.7527 14.91C16.1581 16.4265 13.5523 17.9228 10.9487 19.4259C10.8391 19.4908 10.7251 19.5489 10.5305 19.6541C10.5998 18.6654 10.3873 17.7327 10.7251 16.8291C10.9085 16.3348 11.2529 15.9635 11.7092 15.6995C13.8811 14.4447 16.0507 13.1877 18.227 11.9396C19.0211 11.4833 19.8308 11.4945 20.6248 11.953C23.0964 13.3756 25.5657 14.8026 28.0306 16.2341C28.1357 16.2945 28.2677 16.4309 28.2677 16.5338C28.2856 17.5493 28.2788 18.567 28.2788 19.6563C27.3819 19.1396 26.5543 18.6609 25.7267 18.1823C23.8412 17.093 21.9512 16.0149 20.0746 14.91ZM37.4427 30.8779C37.3778 31.6764 36.9103 32.2423 36.2192 32.6404C33.5732 34.1614 30.9294 35.6913 28.2856 37.2168C27.4557 37.6954 26.6259 38.1741 25.7938 38.6527C25.6932 38.7109 25.5903 38.7601 25.4539 38.8317C25.4449 38.693 25.4337 38.5924 25.4337 38.4917C25.4337 37.6149 25.4382 36.7404 25.4293 35.8636C25.4293 35.6645 25.4762 35.5437 25.6596 35.4386C29.5157 33.2198 33.3696 30.9942 37.2212 28.7709C37.2794 28.7374 37.3443 28.7105 37.4539 28.6591C37.4539 29.4375 37.4986 30.1622 37.4427 30.8779ZM37.4628 25.3577C37.4561 26.2658 36.9663 26.9033 36.1901 27.3506C33.175 29.0841 30.1622 30.8265 27.1493 32.5666C26.5991 32.8842 26.0466 33.1996 25.4561 33.5396C25.4472 33.3897 25.436 33.2913 25.436 33.1907C25.436 32.3273 25.4449 31.4617 25.4293 30.5983C25.4248 30.3523 25.5075 30.2226 25.72 30.0995C28.46 28.5271 31.1911 26.9368 33.9355 25.3733C34.4231 25.096 34.6378 24.7538 34.6334 24.1812C34.6132 21.1974 34.6244 18.2136 34.6244 15.2298V14.7087C35.3402 15.1404 36.0112 15.496 36.624 15.9299C37.1832 16.3258 37.465 16.9253 37.4673 17.6164C37.4762 20.1976 37.4829 22.7788 37.465 25.3599L37.4628 25.3577Z" fill="%230D0D0D"></path><path fill-rule="evenodd" d="M24 0C10.7452 0 0 10.7452 0 24C0 37.2548 10.7452 48 24 48C37.2548 48 48 37.2548 48 24C48 10.7452 37.2548 0 24 0ZM24 2C11.8497 2 2 11.8497 2 24C2 36.1503 11.8497 46 24 46C36.1503 46 46 36.1503 46 24C46 11.8497 36.1503 2 24 2Z" fill="url(%23paint2_radial_6324_83922)"></path><path fill-rule="evenodd" d="M24 0C10.7452 0 0 10.7452 0 24C0 37.2548 10.7452 48 24 48C37.2548 48 48 37.2548 48 24C48 10.7452 37.2548 0 24 0ZM24 2C11.8497 2 2 11.8497 2 24C2 36.1503 11.8497 46 24 46C36.1503 46 46 36.1503 46 24C46 11.8497 36.1503 2 24 2Z" fill="url(%23paint3_radial_6324_83922)"></path><defs><radialGradient id="paint0_radial_6324_83922" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(13.4442 13.3899) rotate(44.9817) scale(46.7487 99.1435)"><stop stop-color="%23A3EEF8"></stop><stop offset="0.177083" stop-color="%23A4DCF5"></stop><stop offset="0.380208" stop-color="%23A6AEEC"></stop><stop offset="1" stop-color="%23ECBEE1"></stop></radialGradient><radialGradient id="paint1_radial_6324_83922" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(25.9515 43.7068) rotate(84.265) scale(24.2138 46.3215)"><stop stop-color="%23FCF5EE"></stop><stop offset="0.715135" stop-color="%23ECBEE1" stop-opacity="0"></stop></radialGradient><radialGradient id="paint2_radial_6324_83922" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(12.7405 12.6825) rotate(44.9817) scale(49.8653 105.753)"><stop stop-color="%23A3EEF8"></stop><stop offset="0.177083" stop-color="%23A4DCF5"></stop><stop offset="0.380208" stop-color="%23A6AEEC"></stop><stop offset="1" stop-color="%23ECBEE1"></stop></radialGradient><radialGradient id="paint3_radial_6324_83922" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(26.0816 45.0206) rotate(84.265) scale(25.828 49.4096)"><stop stop-color="%23FCF5EE"></stop><stop offset="0.715135" stop-color="%23ECBEE1" stop-opacity="0"></stop></radialGradient></defs></g></svg>',name:"Immutable Passport",rdns:"com.immutable.passport",uuid:"3f0259bb-54c0-4ff0-85f2-6bb7c2d8b6c8"};function Xw(s){if(typeof window>"u")return;let e=new CustomEvent("eip6963:announceProvider",{detail:Object.freeze(s)});window.dispatchEvent(e);let t=()=>window.dispatchEvent(e);window.addEventListener("eip6963:requestProvider",t);}var xa={};be(xa,{IdentitySigner:()=>Tg,toIdentityAuthKey:()=>ux});var at={};be(at,{format:()=>vT,from:()=>xT});var $I="1.1.0";var lt=class s extends Error{constructor(e,t={}){let n=t.cause instanceof s?t.cause.details:t.cause?.message?t.cause.message:t.details,r=t.cause instanceof s&&t.cause.docsPath||t.docsPath,i=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...r?[`Docs: https://abitype.dev${r}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${$I}`].join(`
|
|
338
|
-
`);super(i),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),t.cause&&(this.cause=t.cause),this.details=n,this.docsPath=r,this.metaMessages=t.metaMessages,this.shortMessage=e;}};function ms(s,e){return s.exec(e)?.groups}var eb=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,tb=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,R0=/^\(.+?\).*?$/;var qI=/^tuple(?<array>(\[(\d*)\])*)$/;function V0(s){let e=s.type;if(qI.test(s.type)&&"components"in s){e="(";let t=s.components.length;for(let r=0;r<t;r++){let i=s.components[r];e+=V0(i),r<t-1&&(e+=", ");}let n=ms(qI,s.type);return e+=`)${n?.array??""}`,V0({...s,type:e})}return "indexed"in s&&s.indexed&&(e=`${e} indexed`),s.name?`${e} ${s.name}`:e}function nn(s){let e="",t=s.length;for(let n=0;n<t;n++){let r=s[n];e+=V0(r),n!==t-1&&(e+=", ");}return e}function vn(s){return s.type==="function"?`function ${s.name}(${nn(s.inputs)})${s.stateMutability&&s.stateMutability!=="nonpayable"?` ${s.stateMutability}`:""}${s.outputs?.length?` returns (${nn(s.outputs)})`:""}`:s.type==="event"?`event ${s.name}(${nn(s.inputs)})`:s.type==="error"?`error ${s.name}(${nn(s.inputs)})`:s.type==="constructor"?`constructor(${nn(s.inputs)})${s.stateMutability==="payable"?" payable":""}`:s.type==="fallback"?`fallback() external${s.stateMutability==="payable"?" payable":""}`:"receive() external payable"}function sb(s){let e=[],t=s.length;for(let n=0;n<t;n++){let r=s[n],i=vn(r);e.push(i);}return e}var FI=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function KI(s){return FI.test(s)}function GI(s){return ms(FI,s)}var WI=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function JI(s){return WI.test(s)}function zI(s){return ms(WI,s)}var YI=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function ZI(s){return YI.test(s)}function QI(s){return ms(YI,s)}var XI=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function xr(s){return XI.test(s)}function e3(s){return ms(XI,s)}var t3=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function s3(s){return t3.test(s)}function n3(s){return ms(t3,s)}var r3=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function i3(s){return r3.test(s)}function a3(s){return ms(r3,s)}var oT=/^receive\(\) external payable$/;function o3(s){return oT.test(s)}var nb=new Set(["memory","indexed","storage","calldata"]),c3=new Set(["indexed"]),D0=new Set(["calldata","memory","storage"]);var L0=class extends lt{constructor({signature:e}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"});}},j0=class extends lt{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"});}},U0=class extends lt{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"});}};var H0=class extends lt{constructor({params:e}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"});}},_0=class extends lt{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"});}},M0=class extends lt{constructor({param:e,name:t}){super("Invalid ABI parameter.",{details:e,metaMessages:[`"${t}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"});}},$0=class extends lt{constructor({param:e,type:t,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${t?` in "${t}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"});}},q0=class extends lt{constructor({param:e,type:t,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${t?` in "${t}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"});}},F0=class extends lt{constructor({abiParameter:e}){super("Invalid ABI parameter.",{details:JSON.stringify(e,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"});}};var rn=class extends lt{constructor({signature:e,type:t}){super(`Invalid ${t} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"});}},K0=class extends lt{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"});}},G0=class extends lt{constructor({signature:e}){super("Invalid struct signature.",{details:e,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"});}};var W0=class extends lt{constructor({type:e}){super("Circular reference detected.",{metaMessages:[`Struct "${e}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"});}};var J0=class extends lt{constructor({current:e,depth:t}){super("Unbalanced parentheses.",{metaMessages:[`"${e.trim()}" has too many ${t>0?"opening":"closing"} parentheses.`],details:`Depth "${t}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"});}};function u3(s,e,t){let n="";if(t)for(let r of Object.entries(t)){if(!r)continue;let i="";for(let a of r[1])i+=`[${a.type}${a.name?`:${a.name}`:""}]`;n+=`(${r[0]}{${i}})`;}return e?`${e}:${s}${n}`:s}var z0=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]]);function sh(s,e={}){if(ZI(s))return cT(s,e);if(JI(s))return uT(s,e);if(KI(s))return lT(s,e);if(s3(s))return hT(s,e);if(i3(s))return fT(s);if(o3(s))return {type:"receive",stateMutability:"payable"};throw new K0({signature:s})}function cT(s,e={}){let t=QI(s);if(!t)throw new rn({signature:s,type:"function"});let n=as(t.parameters),r=[],i=n.length;for(let o=0;o<i;o++)r.push(Rs(n[o],{modifiers:D0,structs:e,type:"function"}));let a=[];if(t.returns){let o=as(t.returns),c=o.length;for(let u=0;u<c;u++)a.push(Rs(o[u],{modifiers:D0,structs:e,type:"function"}));}return {name:t.name,type:"function",stateMutability:t.stateMutability??"nonpayable",inputs:r,outputs:a}}function uT(s,e={}){let t=zI(s);if(!t)throw new rn({signature:s,type:"event"});let n=as(t.parameters),r=[],i=n.length;for(let a=0;a<i;a++)r.push(Rs(n[a],{modifiers:c3,structs:e,type:"event"}));return {name:t.name,type:"event",inputs:r}}function lT(s,e={}){let t=GI(s);if(!t)throw new rn({signature:s,type:"error"});let n=as(t.parameters),r=[],i=n.length;for(let a=0;a<i;a++)r.push(Rs(n[a],{structs:e,type:"error"}));return {name:t.name,type:"error",inputs:r}}function hT(s,e={}){let t=n3(s);if(!t)throw new rn({signature:s,type:"constructor"});let n=as(t.parameters),r=[],i=n.length;for(let a=0;a<i;a++)r.push(Rs(n[a],{structs:e,type:"constructor"}));return {type:"constructor",stateMutability:t.stateMutability??"nonpayable",inputs:r}}function fT(s){let e=a3(s);if(!e)throw new rn({signature:s,type:"fallback"});return {type:"fallback",stateMutability:e.stateMutability??"nonpayable"}}var dT=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,mT=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,pT=/^u?int$/;function Rs(s,e){let t=u3(s,e?.type,e?.structs);if(z0.has(t))return z0.get(t);let n=R0.test(s),r=ms(n?mT:dT,s);if(!r)throw new _0({param:s});if(r.name&&yT(r.name))throw new M0({param:s,name:r.name});let i=r.name?{name:r.name}:{},a=r.modifier==="indexed"?{indexed:!0}:{},o=e?.structs??{},c,u={};if(n){c="tuple";let h=as(r.type),m=[],y=h.length;for(let g=0;g<y;g++)m.push(Rs(h[g],{structs:o}));u={components:m};}else if(r.type in o)c="tuple",u={components:o[r.type]};else if(pT.test(r.type))c=`${r.type}256`;else if(r.type==="address payable")c="address";else if(c=r.type,e?.type!=="struct"&&!rb(c))throw new U0({type:c});if(r.modifier){if(!e?.modifiers?.has?.(r.modifier))throw new $0({param:s,type:e?.type,modifier:r.modifier});if(D0.has(r.modifier)&&!wT(c,!!r.array))throw new q0({param:s,type:e?.type,modifier:r.modifier})}let l={type:`${c}${r.array??""}`,...i,...a,...u};return z0.set(t,l),l}function as(s,e=[],t="",n=0){let r=s.trim().length;for(let i=0;i<r;i++){let a=s[i],o=s.slice(i+1);switch(a){case",":return n===0?as(o,[...e,t.trim()]):as(o,e,`${t}${a}`,n);case"(":return as(o,e,`${t}${a}`,n+1);case")":return as(o,e,`${t}${a}`,n-1);default:return as(o,e,`${t}${a}`,n)}}if(t==="")return e;if(n!==0)throw new J0({current:t,depth:n});return e.push(t.trim()),e}function rb(s){return s==="address"||s==="bool"||s==="function"||s==="string"||eb.test(s)||tb.test(s)}var gT=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;function yT(s){return s==="address"||s==="bool"||s==="function"||s==="string"||s==="tuple"||eb.test(s)||tb.test(s)||gT.test(s)}function wT(s,e){return e||s==="bytes"||s==="string"||s==="tuple"}function lc(s){let e={},t=s.length;for(let a=0;a<t;a++){let o=s[a];if(!xr(o))continue;let c=e3(o);if(!c)throw new rn({signature:o,type:"struct"});let u=c.properties.split(";"),l=[],h=u.length;for(let m=0;m<h;m++){let g=u[m].trim();if(!g)continue;let w=Rs(g,{type:"struct"});l.push(w);}if(!l.length)throw new G0({signature:o});e[c.name]=l;}let n={},r=Object.entries(e),i=r.length;for(let a=0;a<i;a++){let[o,c]=r[a];n[o]=l3(c,e);}return n}var bT=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function l3(s,e,t=new Set){let n=[],r=s.length;for(let i=0;i<r;i++){let a=s[i];if(R0.test(a.type))n.push(a);else {let c=ms(bT,a.type);if(!c?.type)throw new F0({abiParameter:a});let{array:u,type:l}=c;if(l in e){if(t.has(l))throw new W0({type:l});n.push({...a,type:`tuple${u??""}`,components:l3(e[l]??[],e,new Set([...t,l]))});}else if(rb(l))n.push(a);else throw new j0({type:l})}}return n}function ib(s){let e=lc(s),t=[],n=s.length;for(let r=0;r<n;r++){let i=s[r];xr(i)||t.push(sh(i,e));}return t}function Y0(s){let e;if(typeof s=="string")e=sh(s);else {let t=lc(s),n=s.length;for(let r=0;r<n;r++){let i=s[r];if(!xr(i)){e=sh(i,t);break}}}if(!e)throw new L0({signature:s});return e}function Z0(s){let e=[];if(typeof s=="string"){let t=as(s),n=t.length;for(let r=0;r<n;r++)e.push(Rs(t[r],{modifiers:nb}));}else {let t=lc(s),n=s.length;for(let r=0;r<n;r++){let i=s[r];if(xr(i))continue;let a=as(i),o=a.length;for(let c=0;c<o;c++)e.push(Rs(a[c],{modifiers:nb,structs:t}));}}if(e.length===0)throw new H0({params:s});return e}function h3(s){for(let e of s)if(typeof e!="string")return !1;return !0}function vT(s){return sb(s)}function xT(s){return h3(s)?ib(s):s}var f3="0.1.1";function d3(){return f3}var K=class s extends Error{static setStaticOptions(e){s.prototype.docsOrigin=e.docsOrigin,s.prototype.showVersion=e.showVersion,s.prototype.version=e.version;}constructor(e,t={}){let n=(()=>{if(t.cause instanceof s){if(t.cause.details)return t.cause.details;if(t.cause.shortMessage)return t.cause.shortMessage}return t.cause&&"details"in t.cause&&typeof t.cause.details=="string"?t.cause.details:t.cause?.message?t.cause.message:t.details})(),r=t.cause instanceof s&&t.cause.docsPath||t.docsPath,i=t.docsOrigin??s.prototype.docsOrigin,a=`${i}${r??""}`,o=!!(t.version??s.prototype.showVersion),c=t.version??s.prototype.version,u=[e||"An error occurred.",...t.metaMessages?["",...t.metaMessages]:[],...n||r||o?["",n?`Details: ${n}`:void 0,r?`See: ${a}`:void 0,o?`Version: ${c}`:void 0]:[]].filter(l=>typeof l=="string").join(`
|
|
339
|
-
`);super(u,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsOrigin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"showVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.cause=t.cause,this.details=n,this.docs=a,this.docsOrigin=i,this.docsPath=r,this.shortMessage=e,this.showVersion=o,this.version=c;}walk(e){return m3(this,e)}};Object.defineProperty(K,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${d3()}`}});K.setStaticOptions(K.defaultStaticOptions);function m3(s,e){return e?.(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause?m3(s.cause,e):e?null:s}var oe={};be(oe,{keccak256:()=>dt,ripemd160:()=>f4,sha256:()=>wh,validate:()=>Rb});var zi=xn&&typeof xn=="object"&&"webcrypto"in xn?xn.webcrypto:xn&&typeof xn=="object"&&"randomBytes"in xn?xn:void 0;function ET(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Yi(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function an(s,...e){if(!ET(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function p3(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Yi(s.outputLen),Yi(s.blockLen);}function En(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function X0(s,e){an(s);let t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function g3(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function zt(...s){for(let e=0;e<s.length;e++)s[e].fill(0);}function ep(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Vs(s,e){return s<<32-e|s>>>e}function nh(s,e){return s<<e|s>>>32-e>>>0}var AT=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function IT(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function CT(s){for(let e=0;e<s.length;e++)s[e]=IT(s[e]);return s}var ab=AT?s=>s:CT;function NT(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function Zi(s){return typeof s=="string"&&(s=NT(s)),an(s),s}function y3(...s){let e=0;for(let n=0;n<s.length;n++){let r=s[n];an(r),e+=r.length;}let t=new Uint8Array(e);for(let n=0,r=0;n<s.length;n++){let i=s[n];t.set(i,r),r+=i.length;}return t}var Er=class{};function Ar(s){let e=n=>s().update(Zi(n)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function w3(s=32){if(zi&&typeof zi.getRandomValues=="function")return zi.getRandomValues(new Uint8Array(s));if(zi&&typeof zi.randomBytes=="function")return Uint8Array.from(zi.randomBytes(s));throw new Error("crypto.getRandomValues must be defined")}function kT(s,e,t,n){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,n);let r=BigInt(32),i=BigInt(4294967295),a=Number(t>>r&i),o=Number(t&i),c=n?4:0,u=n?0:4;s.setUint32(e+c,a,n),s.setUint32(e+u,o,n);}function ob(s,e,t){return s&e^~s&t}function cb(s,e,t){return s&e^s&t^e&t}var Qi=class extends Er{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=ep(this.buffer);}update(e){En(this),e=Zi(e),an(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let c=ep(e);for(;r<=i-a;a+=r)this.process(c,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){En(this),X0(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,zt(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let h=a;h<r;h++)t[h]=0;kT(n,r-8,BigInt(this.length*8),i),this.process(n,0);let o=ep(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)o.setUint32(4*h,l[h],i);}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},An=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Tt=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Bt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var PT=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),S3=Uint8Array.from(new Array(16).fill(0).map((s,e)=>e)),TT=S3.map(s=>(9*s+5)%16),v3=(()=>{let t=[[S3],[TT]];for(let n=0;n<4;n++)for(let r of t)r.push(r[n].map(i=>PT[i]));return t})(),x3=v3[0],E3=v3[1],A3=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(s=>Uint8Array.from(s)),BT=x3.map((s,e)=>s.map(t=>A3[e][t])),OT=E3.map((s,e)=>s.map(t=>A3[e][t])),RT=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),VT=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function b3(s,e,t,n){return s===0?e^t^n:s===1?e&t|~e&n:s===2?(e|~t)^n:s===3?e&n|t&~n:e^(t|~n)}var tp=new Uint32Array(16),sp=class extends Qi{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776;}get(){let{h0:e,h1:t,h2:n,h3:r,h4:i}=this;return [e,t,n,r,i]}set(e,t,n,r,i){this.h0=e|0,this.h1=t|0,this.h2=n|0,this.h3=r|0,this.h4=i|0;}process(e,t){for(let y=0;y<16;y++,t+=4)tp[y]=e.getUint32(t,!0);let n=this.h0|0,r=n,i=this.h1|0,a=i,o=this.h2|0,c=o,u=this.h3|0,l=u,h=this.h4|0,m=h;for(let y=0;y<5;y++){let g=4-y,w=RT[y],S=VT[y],C=x3[y],N=E3[y],x=BT[y],v=OT[y];for(let I=0;I<16;I++){let D=nh(n+b3(y,i,o,u)+tp[C[I]]+w,x[I])+h|0;n=h,h=u,u=nh(o,10)|0,o=i,i=D;}for(let I=0;I<16;I++){let D=nh(r+b3(g,a,c,l)+tp[N[I]]+S,v[I])+m|0;r=m,m=l,l=nh(c,10)|0,c=a,a=D;}}this.set(this.h1+o+l|0,this.h2+u+m|0,this.h3+h+r|0,this.h4+n+a|0,this.h0+i+c|0);}roundClean(){zt(tp);}destroy(){this.destroyed=!0,zt(this.buffer),this.set(0,0,0,0,0);}},I3=Ar(()=>new sp);var C3=I3;var np=BigInt(4294967295),N3=BigInt(32);function DT(s,e=!1){return e?{h:Number(s&np),l:Number(s>>N3&np)}:{h:Number(s>>N3&np)|0,l:Number(s&np)|0}}function rp(s,e=!1){let t=s.length,n=new Uint32Array(t),r=new Uint32Array(t);for(let i=0;i<t;i++){let{h:a,l:o}=DT(s[i],e);[n[i],r[i]]=[a,o];}return [n,r]}var ub=(s,e,t)=>s>>>t,lb=(s,e,t)=>s<<32-t|e>>>t,Xi=(s,e,t)=>s>>>t|e<<32-t,ea=(s,e,t)=>s<<32-t|e>>>t,rh=(s,e,t)=>s<<64-t|e>>>t-32,ih=(s,e,t)=>s>>>t-32|e<<64-t;var k3=(s,e,t)=>s<<t|e>>>32-t,P3=(s,e,t)=>e<<t|s>>>32-t,T3=(s,e,t)=>e<<t-32|s>>>64-t,B3=(s,e,t)=>s<<t-32|e>>>64-t;function on(s,e,t,n){let r=(e>>>0)+(n>>>0);return {h:s+t+(r/2**32|0)|0,l:r|0}}var O3=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),R3=(s,e,t,n)=>e+t+n+(s/2**32|0)|0,V3=(s,e,t,n)=>(s>>>0)+(e>>>0)+(t>>>0)+(n>>>0),D3=(s,e,t,n,r)=>e+t+n+r+(s/2**32|0)|0,L3=(s,e,t,n,r)=>(s>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),j3=(s,e,t,n,r,i)=>e+t+n+r+i+(s/2**32|0)|0;var jT=BigInt(0),ah=BigInt(1),UT=BigInt(2),HT=BigInt(7),_T=BigInt(256),MT=BigInt(113),_3=[],M3=[],$3=[];for(let s=0,e=ah,t=1,n=0;s<24;s++){[t,n]=[n,(2*t+3*n)%5],_3.push(2*(5*n+t)),M3.push((s+1)*(s+2)/2%64);let r=jT;for(let i=0;i<7;i++)e=(e<<ah^(e>>HT)*MT)%_T,e&UT&&(r^=ah<<(ah<<BigInt(i))-ah);$3.push(r);}var q3=rp($3,!0),$T=q3[0],qT=q3[1],U3=(s,e,t)=>t>32?T3(s,e,t):k3(s,e,t),H3=(s,e,t)=>t>32?B3(s,e,t):P3(s,e,t);function FT(s,e=24){let t=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let a=0;a<10;a++)t[a]=s[a]^s[a+10]^s[a+20]^s[a+30]^s[a+40];for(let a=0;a<10;a+=2){let o=(a+8)%10,c=(a+2)%10,u=t[c],l=t[c+1],h=U3(u,l,1)^t[o],m=H3(u,l,1)^t[o+1];for(let y=0;y<50;y+=10)s[a+y]^=h,s[a+y+1]^=m;}let r=s[2],i=s[3];for(let a=0;a<24;a++){let o=M3[a],c=U3(r,i,o),u=H3(r,i,o),l=_3[a];r=s[l],i=s[l+1],s[l]=c,s[l+1]=u;}for(let a=0;a<50;a+=10){for(let o=0;o<10;o++)t[o]=s[a+o];for(let o=0;o<10;o++)s[a+o]^=~t[(o+2)%10]&t[(o+4)%10];}s[0]^=$T[n],s[1]^=qT[n];}zt(t);}var hb=class s extends Er{constructor(e,t,n,r=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=i,Yi(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=g3(this.state);}clone(){return this._cloneInto()}keccak(){ab(this.state32),FT(this.state32,this.rounds),ab(this.state32),this.posOut=0,this.pos=0;}update(e){En(this),e=Zi(e),an(e);let{blockLen:t,state:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(t-this.pos,r-i);for(let o=0;o<a;o++)n[this.pos++]^=e[i++];this.pos===t&&this.keccak();}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,t&128&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak();}writeInto(e){En(this,!1),an(e),this.finish();let t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();let a=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+a),r),this.posOut+=a,r+=a;}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Yi(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(X0(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,zt(this.state);}_cloneInto(e){let{blockLen:t,suffix:n,outputLen:r,rounds:i,enableXOF:a}=this;return e||(e=new s(t,n,r,a,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=a,e.destroyed=this.destroyed,e}},KT=(s,e,t)=>Ar(()=>new hb(e,s,t));var F3=KT(1,136,256/8);var GT=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ir=new Uint32Array(64),ip=class extends Qi{constructor(e=32){super(64,e,8,!1),this.A=An[0]|0,this.B=An[1]|0,this.C=An[2]|0,this.D=An[3]|0,this.E=An[4]|0,this.F=An[5]|0,this.G=An[6]|0,this.H=An[7]|0;}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:c}=this;return [e,t,n,r,i,a,o,c]}set(e,t,n,r,i,a,o,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=c|0;}process(e,t){for(let h=0;h<16;h++,t+=4)Ir[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let m=Ir[h-15],y=Ir[h-2],g=Vs(m,7)^Vs(m,18)^m>>>3,w=Vs(y,17)^Vs(y,19)^y>>>10;Ir[h]=w+Ir[h-7]+g+Ir[h-16]|0;}let{A:n,B:r,C:i,D:a,E:o,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){let m=Vs(o,6)^Vs(o,11)^Vs(o,25),y=l+m+ob(o,c,u)+GT[h]+Ir[h]|0,w=(Vs(n,2)^Vs(n,13)^Vs(n,22))+cb(n,r,i)|0;l=u,u=c,c=o,o=a+y|0,a=i,i=r,r=n,n=y+w|0;}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,c,u,l);}roundClean(){zt(Ir);}destroy(){this.set(0,0,0,0,0,0,0,0),zt(this.buffer);}};var K3=rp(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(s=>BigInt(s))),WT=K3[0],JT=K3[1],Cr=new Uint32Array(80),Nr=new Uint32Array(80),ap=class extends Qi{constructor(e=64){super(128,e,16,!1),this.Ah=Bt[0]|0,this.Al=Bt[1]|0,this.Bh=Bt[2]|0,this.Bl=Bt[3]|0,this.Ch=Bt[4]|0,this.Cl=Bt[5]|0,this.Dh=Bt[6]|0,this.Dl=Bt[7]|0,this.Eh=Bt[8]|0,this.El=Bt[9]|0,this.Fh=Bt[10]|0,this.Fl=Bt[11]|0,this.Gh=Bt[12]|0,this.Gl=Bt[13]|0,this.Hh=Bt[14]|0,this.Hl=Bt[15]|0;}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:a,Dh:o,Dl:c,Eh:u,El:l,Fh:h,Fl:m,Gh:y,Gl:g,Hh:w,Hl:S}=this;return [e,t,n,r,i,a,o,c,u,l,h,m,y,g,w,S]}set(e,t,n,r,i,a,o,c,u,l,h,m,y,g,w,S){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=a|0,this.Dh=o|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=m|0,this.Gh=y|0,this.Gl=g|0,this.Hh=w|0,this.Hl=S|0;}process(e,t){for(let x=0;x<16;x++,t+=4)Cr[x]=e.getUint32(t),Nr[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let v=Cr[x-15]|0,I=Nr[x-15]|0,D=Xi(v,I,1)^Xi(v,I,8)^ub(v,I,7),F=ea(v,I,1)^ea(v,I,8)^lb(v,I,7),M=Cr[x-2]|0,W=Nr[x-2]|0,se=Xi(M,W,19)^rh(M,W,61)^ub(M,W,6),q=ea(M,W,19)^ih(M,W,61)^lb(M,W,6),J=V3(F,q,Nr[x-7],Nr[x-16]),ae=D3(J,D,se,Cr[x-7],Cr[x-16]);Cr[x]=ae|0,Nr[x]=J|0;}let{Ah:n,Al:r,Bh:i,Bl:a,Ch:o,Cl:c,Dh:u,Dl:l,Eh:h,El:m,Fh:y,Fl:g,Gh:w,Gl:S,Hh:C,Hl:N}=this;for(let x=0;x<80;x++){let v=Xi(h,m,14)^Xi(h,m,18)^rh(h,m,41),I=ea(h,m,14)^ea(h,m,18)^ih(h,m,41),D=h&y^~h&w,F=m&g^~m&S,M=L3(N,I,F,JT[x],Nr[x]),W=j3(M,C,v,D,WT[x],Cr[x]),se=M|0,q=Xi(n,r,28)^rh(n,r,34)^rh(n,r,39),J=ea(n,r,28)^ih(n,r,34)^ih(n,r,39),ae=n&i^n&o^i&o,Be=r&a^r&c^a&c;C=w|0,N=S|0,w=y|0,S=g|0,y=h|0,g=m|0,{h,l:m}=on(u|0,l|0,W|0,se|0),u=o|0,l=c|0,o=i|0,c=a|0,i=n|0,a=r|0;let j=O3(se,J,Be);n=R3(j,W,q,ae),r=j|0;}(({h:n,l:r}=on(this.Ah|0,this.Al|0,n|0,r|0))),{h:i,l:a}=on(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:c}=on(this.Ch|0,this.Cl|0,o|0,c|0),{h:u,l}=on(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:m}=on(this.Eh|0,this.El|0,h|0,m|0),{h:y,l:g}=on(this.Fh|0,this.Fl|0,y|0,g|0),{h:w,l:S}=on(this.Gh|0,this.Gl|0,w|0,S|0),{h:C,l:N}=on(this.Hh|0,this.Hl|0,C|0,N|0),this.set(n,r,i,a,o,c,u,l,h,m,y,g,w,S,C,N);}roundClean(){zt(Cr,Nr);}destroy(){zt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},fb=class extends ap{constructor(){super(48),this.Ah=Tt[0]|0,this.Al=Tt[1]|0,this.Bh=Tt[2]|0,this.Bl=Tt[3]|0,this.Ch=Tt[4]|0,this.Cl=Tt[5]|0,this.Dh=Tt[6]|0,this.Dl=Tt[7]|0,this.Eh=Tt[8]|0,this.El=Tt[9]|0,this.Fh=Tt[10]|0,this.Fl=Tt[11]|0,this.Gh=Tt[12]|0,this.Gl=Tt[13]|0,this.Hh=Tt[14]|0,this.Hl=Tt[15]|0;}};var hc=Ar(()=>new ip);var G3=Ar(()=>new ap),W3=Ar(()=>new fb);var J3=hc;var f={};be(f,{InvalidBytesBooleanError:()=>fp,InvalidBytesTypeError:()=>oa,SizeExceedsPaddingSizeError:()=>hh,SizeOverflowError:()=>lh,SliceOffsetOutOfBoundsError:()=>pc,assert:()=>c6,concat:()=>kb,from:()=>Pn,fromArray:()=>u6,fromBoolean:()=>c4,fromHex:()=>Ye,fromNumber:()=>u4,fromString:()=>Tn,isEqual:()=>l4,padLeft:()=>l6,padRight:()=>h6,random:()=>Nb,size:()=>ps,slice:()=>Pb,toBigInt:()=>Tb,toBoolean:()=>Bb,toHex:()=>h4,toNumber:()=>js,toString:()=>dp,trimLeft:()=>mp,trimRight:()=>hp,validate:()=>Ob});var gb=BigInt(0),pb=BigInt(1);function fc(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function yb(s){if(!fc(s))throw new Error("Uint8Array expected")}function dc(s,e){if(typeof e!="boolean")throw new Error(s+" boolean expected, got "+e)}function oh(s){let e=s.toString(16);return e.length&1?"0"+e:e}function Z3(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?gb:BigInt("0x"+s)}var Q3=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",zT=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function mc(s){if(yb(s),Q3)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=zT[s[t]];return e}var In={_0:48,_9:57,A:65,F:70,a:97,f:102};function z3(s){if(s>=In._0&&s<=In._9)return s-In._0;if(s>=In.A&&s<=In.F)return s-(In.A-10);if(s>=In.a&&s<=In.f)return s-(In.a-10)}function ch(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Q3)return Uint8Array.fromHex(s);let e=s.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let r=0,i=0;r<t;r++,i+=2){let a=z3(s.charCodeAt(i)),o=z3(s.charCodeAt(i+1));if(a===void 0||o===void 0){let c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[r]=a*16+o;}return n}function Cn(s){return Z3(mc(s))}function wb(s){return yb(s),Z3(mc(Uint8Array.from(s).reverse()))}function ta(s,e){return ch(s.toString(16).padStart(e*2,"0"))}function bb(s,e){return ta(s,e).reverse()}function os(s,e,t){let n;if(typeof e=="string")try{n=ch(e);}catch(i){throw new Error(s+" must be hex string or Uint8Array, cause: "+i)}else if(fc(e))n=Uint8Array.from(e);else throw new Error(s+" must be hex string or Uint8Array");let r=n.length;if(typeof t=="number"&&r!==t)throw new Error(s+" of length "+t+" expected, got "+r);return n}function uh(...s){let e=0;for(let n=0;n<s.length;n++){let r=s[n];yb(r),e+=r.length;}let t=new Uint8Array(e);for(let n=0,r=0;n<s.length;n++){let i=s[n];t.set(i,r),r+=i.length;}return t}function op(s,e){if(s.length!==e.length)return !1;let t=0;for(let n=0;n<s.length;n++)t|=s[n]^e[n];return t===0}var db=s=>typeof s=="bigint"&&gb<=s;function cp(s,e,t){return db(s)&&db(e)&&db(t)&&e<=s&&s<t}function sa(s,e,t,n){if(!cp(e,t,n))throw new Error("expected valid "+s+": "+t+" <= n < "+n+", got "+e)}function X3(s){let e;for(e=0;s>gb;s>>=pb,e+=1);return e}var na=s=>(pb<<BigInt(s))-pb,mb=s=>new Uint8Array(s),Y3=s=>Uint8Array.from(s);function e6(s,e,t){if(typeof s!="number"||s<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=mb(s),r=mb(s),i=0,a=()=>{n.fill(1),r.fill(0),i=0;},o=(...h)=>t(r,n,...h),c=(h=mb(0))=>{r=o(Y3([0]),h),n=o(),h.length!==0&&(r=o(Y3([1]),h),n=o());},u=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,m=[];for(;h<e;){n=o();let y=n.slice();m.push(y),h+=n.length;}return uh(...m)};return (h,m)=>{a(),c(h);let y;for(;!(y=m(u()));)c();return a(),y}}var YT={bigint:s=>typeof s=="bigint",function:s=>typeof s=="function",boolean:s=>typeof s=="boolean",string:s=>typeof s=="string",stringOrUint8Array:s=>typeof s=="string"||fc(s),isSafeInteger:s=>Number.isSafeInteger(s),array:s=>Array.isArray(s),field:(s,e)=>e.Fp.isValid(s),hash:s=>typeof s=="function"&&Number.isSafeInteger(s.outputLen)};function ra(s,e,t={}){let n=(r,i,a)=>{let o=YT[i];if(typeof o!="function")throw new Error("invalid validator function");let c=s[r];if(!(a&&c===void 0)&&!o(c,s))throw new Error("param "+String(r)+" is invalid. Expected "+i+", got "+c)};for(let[r,i]of Object.entries(e))n(r,i,!1);for(let[r,i]of Object.entries(t))n(r,i,!0);return s}function Sb(s){let e=new WeakMap;return (t,...n)=>{let r=e.get(t);if(r!==void 0)return r;let i=s(t,...n);return e.set(t,i),i}}var E={};be(E,{IntegerOutOfRangeError:()=>wc,InvalidHexBooleanError:()=>up,InvalidHexTypeError:()=>mh,InvalidHexValueError:()=>ph,InvalidLengthError:()=>gh,SizeExceedsPaddingSizeError:()=>dh,SizeOverflowError:()=>fh,SliceOffsetOutOfBoundsError:()=>gc,assert:()=>o6,concat:()=>Fe,from:()=>Yt,fromBoolean:()=>yh,fromBytes:()=>Ee,fromNumber:()=>le,fromString:()=>cs,isEqual:()=>e4,padLeft:()=>cn,padRight:()=>Ls,random:()=>t4,size:()=>Oe,slice:()=>rt,toBigInt:()=>lp,toBoolean:()=>n4,toBytes:()=>r4,toNumber:()=>Cb,toString:()=>i4,trimLeft:()=>aa,trimRight:()=>s4,validate:()=>Zt});function kn(s,e){if(ps(s)>e)throw new lh({givenSize:ps(s),maxSize:e})}function t6(s,e){if(typeof e=="number"&&e>0&&e>ps(s)-1)throw new pc({offset:e,position:"start",size:ps(s)})}function s6(s,e,t){if(typeof e=="number"&&typeof t=="number"&&ps(s)!==t-e)throw new pc({offset:t,position:"end",size:ps(s)})}var Nn={zero:48,nine:57,A:65,F:70,a:97,f:102};function vb(s){if(s>=Nn.zero&&s<=Nn.nine)return s-Nn.zero;if(s>=Nn.A&&s<=Nn.F)return s-(Nn.A-10);if(s>=Nn.a&&s<=Nn.f)return s-(Nn.a-10)}function xb(s,e={}){let{dir:t,size:n=32}=e;if(n===0)return s;if(s.length>n)throw new hh({size:s.length,targetSize:n,type:"Bytes"});let r=new Uint8Array(n);for(let i=0;i<n;i++){let a=t==="right";r[a?i:n-i-1]=s[a?i:s.length-i-1];}return r}function Eb(s,e={}){let{dir:t="left"}=e,n=s,r=0;for(let i=0;i<n.length-1&&n[t==="left"?i:n.length-i-1].toString()==="0";i++)r++;return n=t==="left"?n.slice(r):n.slice(0,n.length-r),n}function ia(s,e){if(Oe(s)>e)throw new fh({givenSize:Oe(s),maxSize:e})}function r6(s,e){if(typeof e=="number"&&e>0&&e>Oe(s)-1)throw new gc({offset:e,position:"start",size:Oe(s)})}function i6(s,e,t){if(typeof e=="number"&&typeof t=="number"&&Oe(s)!==t-e)throw new gc({offset:t,position:"end",size:Oe(s)})}function Ab(s,e={}){let{dir:t,size:n=32}=e;if(n===0)return s;let r=s.replace("0x","");if(r.length>n*2)throw new dh({size:Math.ceil(r.length/2),targetSize:n,type:"Hex"});return `0x${r[t==="right"?"padEnd":"padStart"](n*2,"0")}`}function Ib(s,e={}){let{dir:t="left"}=e,n=s.replace("0x",""),r=0;for(let i=0;i<n.length-1&&n[t==="left"?i:n.length-i-1].toString()==="0";i++)r++;return n=t==="left"?n.slice(r):n.slice(0,n.length-r),n==="0"?"0x":t==="right"&&n.length%2===1?`0x${n}0`:`0x${n}`}var ZT="#__bigint";function Ds(s,e,t){return JSON.stringify(s,(n,r)=>typeof e=="function"?e(n,r):typeof r=="bigint"?r.toString()+ZT:r,t)}var QT=new TextEncoder,XT=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function o6(s,e={}){let{strict:t=!1}=e;if(!s)throw new mh(s);if(typeof s!="string")throw new mh(s);if(t&&!/^0x[0-9a-fA-F]*$/.test(s))throw new ph(s);if(!s.startsWith("0x"))throw new ph(s)}function Fe(...s){return `0x${s.reduce((e,t)=>e+t.replace("0x",""),"")}`}function Yt(s){return s instanceof Uint8Array?Ee(s):Array.isArray(s)?Ee(new Uint8Array(s)):s}function yh(s,e={}){let t=`0x${Number(s)}`;return typeof e.size=="number"?(ia(t,e.size),cn(t,e.size)):t}function Ee(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=XT[s[r]];let n=`0x${t}`;return typeof e.size=="number"?(ia(n,e.size),Ls(n,e.size)):n}function le(s,e={}){let{signed:t,size:n}=e,r=BigInt(s),i;n?t?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof s=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));let a=typeof i=="bigint"&&t?-i-1n:0;if(i&&r>i||r<a){let u=typeof s=="bigint"?"n":"";throw new wc({max:i?`${i}${u}`:void 0,min:`${a}${u}`,signed:t,size:n,value:`${s}${u}`})}let c=`0x${(t&&r<0?BigInt.asUintN(n*8,BigInt(r)):r).toString(16)}`;return n?cn(c,n):c}function cs(s,e={}){return Ee(QT.encode(s),e)}function e4(s,e){return op(Ye(s),Ye(e))}function cn(s,e){return Ab(s,{dir:"left",size:e})}function Ls(s,e){return Ab(s,{dir:"right",size:e})}function t4(s){return Ee(Nb(s))}function rt(s,e,t,n={}){let{strict:r}=n;r6(s,e);let i=`0x${s.replace("0x","").slice((e??0)*2,(t??s.length)*2)}`;return r&&i6(i,e,t),i}function Oe(s){return Math.ceil((s.length-2)/2)}function aa(s){return Ib(s,{dir:"left"})}function s4(s){return Ib(s,{dir:"right"})}function lp(s,e={}){let{signed:t}=e;e.size&&ia(s,e.size);let n=BigInt(s);if(!t)return n;let r=(s.length-2)/2,i=(1n<<BigInt(r)*8n)-1n,a=i>>1n;return n<=a?n:n-i-1n}function n4(s,e={}){e.size&&ia(s,e.size);let t=aa(s);if(t==="0x")return !1;if(t==="0x1")return !0;throw new up(s)}function r4(s,e={}){return Ye(s,e)}function Cb(s,e={}){let{signed:t,size:n}=e;return Number(!t&&!n?s:lp(s,e))}function i4(s,e={}){let{size:t}=e,n=Ye(s);return t&&(kn(n,t),n=hp(n)),new TextDecoder().decode(n)}function Zt(s,e={}){let{strict:t=!1}=e;try{return o6(s,{strict:t}),!0}catch{return !1}}var wc=class extends K{constructor({max:e,min:t,signed:n,size:r,value:i}){super(`Number \`${i}\` is not in safe${r?` ${r*8}-bit`:""}${n?" signed":" unsigned"} integer range ${e?`(\`${t}\` to \`${e}\`)`:`(above \`${t}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"});}},up=class extends K{constructor(e){super(`Hex value \`"${e}"\` is not a valid boolean.`,{metaMessages:['The hex value must be `"0x0"` (false) or `"0x1"` (true).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexBooleanError"});}},mh=class extends K{constructor(e){super(`Value \`${typeof e=="object"?Ds(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"});}},ph=class extends K{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"});}},gh=class extends K{constructor(e){super(`Hex value \`"${e}"\` is an odd length (${e.length-2} nibbles).`,{metaMessages:["It must be an even length."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidLengthError"});}},fh=class extends K{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"});}},gc=class extends K{constructor({offset:e,position:t,size:n}){super(`Slice ${t==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"});}},dh=class extends K{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"});}};var a4=new TextDecoder,o4=new TextEncoder;function c6(s){if(!(s instanceof Uint8Array)){if(!s)throw new oa(s);if(typeof s!="object")throw new oa(s);if(!("BYTES_PER_ELEMENT"in s))throw new oa(s);if(s.BYTES_PER_ELEMENT!==1||s.constructor.name!=="Uint8Array")throw new oa(s)}}function kb(...s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e);for(let n=0,r=0;n<s.length;n++){let i=s[n];t.set(i,r),r+=i.length;}return t}function Pn(s){return s instanceof Uint8Array?s:typeof s=="string"?Ye(s):u6(s)}function u6(s){return s instanceof Uint8Array?s:new Uint8Array(s)}function c4(s,e={}){let{size:t}=e,n=new Uint8Array(1);return n[0]=Number(s),typeof t=="number"?(kn(n,t),l6(n,t)):n}function Ye(s,e={}){let{size:t}=e,n=s;t&&(ia(s,t),n=Ls(s,t));let r=n.slice(2);r.length%2&&(r=`0${r}`);let i=r.length/2,a=new Uint8Array(i);for(let o=0,c=0;o<i;o++){let u=vb(r.charCodeAt(c++)),l=vb(r.charCodeAt(c++));if(u===void 0||l===void 0)throw new K(`Invalid byte sequence ("${r[c-2]}${r[c-1]}" in "${r}").`);a[o]=u<<4|l;}return a}function u4(s,e){let t=le(s,e);return Ye(t)}function Tn(s,e={}){let{size:t}=e,n=o4.encode(s);return typeof t=="number"?(kn(n,t),h6(n,t)):n}function l4(s,e){return op(s,e)}function l6(s,e){return xb(s,{dir:"left",size:e})}function h6(s,e){return xb(s,{dir:"right",size:e})}function Nb(s){return crypto.getRandomValues(new Uint8Array(s))}function ps(s){return s.length}function Pb(s,e,t,n={}){let{strict:r}=n;t6(s,e);let i=s.slice(e,t);return r&&s6(i,e,t),i}function Tb(s,e={}){let{size:t}=e;typeof t<"u"&&kn(s,t);let n=Ee(s,e);return lp(n,e)}function Bb(s,e={}){let{size:t}=e,n=s;if(typeof t<"u"&&(kn(n,t),n=mp(n)),n.length>1||n[0]>1)throw new fp(n);return !!n[0]}function h4(s,e={}){return Ee(s,e)}function js(s,e={}){let{size:t}=e;typeof t<"u"&&kn(s,t);let n=Ee(s,e);return Cb(n,e)}function dp(s,e={}){let{size:t}=e,n=s;return typeof t<"u"&&(kn(n,t),n=hp(n)),a4.decode(n)}function mp(s){return Eb(s,{dir:"left"})}function hp(s){return Eb(s,{dir:"right"})}function Ob(s){try{return c6(s),!0}catch{return !1}}var fp=class extends K{constructor(e){super(`Bytes value \`${e}\` is not a valid boolean.`,{metaMessages:["The bytes array must contain a single byte of either a `0` or `1` value."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesBooleanError"});}},oa=class extends K{constructor(e){super(`Value \`${typeof e=="object"?Ds(e):e}\` of type \`${typeof e}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"});}},lh=class extends K{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"});}},pc=class extends K{constructor({offset:e,position:t,size:n}){super(`Slice ${t==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SliceOffsetOutOfBoundsError"});}},hh=class extends K{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"});}};function dt(s,e={}){let{as:t=typeof s=="string"?"Hex":"Bytes"}=e,n=F3(Pn(s));return t==="Bytes"?n:Ee(n)}function f4(s,e={}){let{as:t=typeof s=="string"?"Hex":"Bytes"}=e,n=C3(Pn(s));return t==="Bytes"?n:Ee(n)}function wh(s,e={}){let{as:t=typeof s=="string"?"Hex":"Bytes"}=e,n=J3(Pn(s));return t==="Bytes"?n:Ee(n)}function Rb(s){return Zt(s)&&Oe(s)===32}var B={};be(B,{InvalidAddressError:()=>ca,InvalidChecksumError:()=>wp,InvalidInputError:()=>bc,assert:()=>Qt,checksum:()=>Sh,from:()=>g6,fromPublicKey:()=>Ub,isEqual:()=>Hb,validate:()=>ua});var pp=class extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e;}get(e){let t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let n=this.keys().next().value;n&&this.delete(n);}return this}};var d4={checksum:new pp(8192)},gp=d4.checksum;function d6(s,e={}){let{compressed:t}=e,{prefix:n,x:r,y:i}=s;if(t===!1||typeof r=="bigint"&&typeof i=="bigint"){if(n!==4)throw new yp({prefix:n,cause:new Lb});return}if(t===!0||typeof r=="bigint"&&typeof i>"u"){if(n!==3&&n!==2)throw new yp({prefix:n,cause:new Db});return}throw new Vb({publicKey:s})}function Bn(s){let e=(()=>{if(Zt(s))return m6(s);if(Ob(s))return m4(s);let{prefix:t,x:n,y:r}=s;return typeof n=="bigint"&&typeof r=="bigint"?{prefix:t??4,x:n,y:r}:{prefix:t,x:n}})();return d6(e),e}function m4(s){return m6(Ee(s))}function m6(s){if(s.length!==132&&s.length!==130&&s.length!==68)throw new jb({publicKey:s});if(s.length===130){let n=BigInt(rt(s,0,32)),r=BigInt(rt(s,32,64));return {prefix:4,x:n,y:r}}if(s.length===132){let n=Number(rt(s,0,1)),r=BigInt(rt(s,1,33)),i=BigInt(rt(s,33,65));return {prefix:n,x:r,y:i}}let e=Number(rt(s,0,1)),t=BigInt(rt(s,1,33));return {prefix:e,x:t}}function p6(s,e={}){return Ye(kr(s,e))}function kr(s,e={}){d6(s);let{prefix:t,x:n,y:r}=s,{includePrefix:i=!0}=e;return Fe(i?le(t,{size:1}):"0x",le(n,{size:32}),typeof r=="bigint"?le(r,{size:32}):"0x")}var Vb=class extends K{constructor({publicKey:e}){super(`Value \`${Ds(e)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"});}},yp=class extends K{constructor({prefix:e,cause:t}){super(`Prefix "${e}" is invalid.`,{cause:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"});}},Db=class extends K{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"});}},Lb=class extends K{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"});}},jb=class extends K{constructor({publicKey:e}){super(`Value \`${e}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${Oe(Yt(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"});}};var p4=/^0x[a-fA-F0-9]{40}$/;function Qt(s,e={}){let{strict:t=!0}=e;if(!p4.test(s))throw new ca({address:s,cause:new bc});if(t){if(s.toLowerCase()===s)return;if(Sh(s)!==s)throw new ca({address:s,cause:new wp})}}function Sh(s){if(gp.has(s))return gp.get(s);Qt(s,{strict:!1});let e=s.substring(2).toLowerCase(),t=dt(Tn(e),{as:"Bytes"}),n=e.split("");for(let i=0;i<40;i+=2)t[i>>1]>>4>=8&&n[i]&&(n[i]=n[i].toUpperCase()),(t[i>>1]&15)>=8&&n[i+1]&&(n[i+1]=n[i+1].toUpperCase());let r=`0x${n.join("")}`;return gp.set(s,r),r}function g6(s,e={}){let{checksum:t=!1}=e;return Qt(s),t?Sh(s):s}function Ub(s,e={}){let t=dt(`0x${kr(s).slice(4)}`).substring(26);return g6(`0x${t}`,e)}function Hb(s,e){return Qt(s,{strict:!1}),Qt(e,{strict:!1}),s.toLowerCase()===e.toLowerCase()}function ua(s,e={}){let{strict:t=!0}=e??{};try{return Qt(s,{strict:t}),!0}catch{return !1}}var ca=class extends K{constructor({address:e,cause:t}){super(`Address "${e}" is invalid.`,{cause:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"});}},bc=class extends K{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"});}},wp=class extends K{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"});}};function Sp(s){let e=!0,t="",n=0,r="",i=!1;for(let a=0;a<s.length;a++){let o=s[a];if(["(",")",","].includes(o)&&(e=!0),o==="("&&n++,o===")"&&n--,!!e){if(n===0){if(o===" "&&["event","function","error",""].includes(r))r="";else if(r+=o,o===")"){i=!0;break}continue}if(o===" "){s[a-1]!==","&&t!==","&&t!==",("&&(t="",e=!1);continue}r+=o,t+=o;}}if(!i)throw new K("Unable to normalize signature.");return r}function bp(s,e){let t=typeof s,n=e.type;switch(n){case"address":return ua(s,{strict:!1});case"bool":return t==="boolean";case"function":return t==="string";case"string":return t==="string";default:return n==="tuple"&&"components"in e?Object.values(e.components).every((r,i)=>bp(Object.values(s)[i],r)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?t==="number"||t==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?t==="string"||s instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(s)&&s.every(r=>bp(r,{...e,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function _b(s,e,t){for(let n in s){let r=s[n],i=e[n];if(r.type==="tuple"&&i.type==="tuple"&&"components"in r&&"components"in i)return _b(r.components,i.components,t[n]);let a=[r.type,i.type];if(a.includes("address")&&a.includes("bytes20")?!0:a.includes("address")&&a.includes("string")?ua(t[n],{strict:!1}):a.includes("address")&&a.includes("bytes")?ua(t[n],{strict:!1}):!1)return a}}function y6(s,e={}){let{prepare:t=!0}=e,n=Array.isArray(s)?Y0(s):typeof s=="string"?Y0(s):s;return {...n,...t?{hash:Sc(n)}:{}}}function vh(s,e,t){let{args:n=[],prepare:r=!0}=t??{},i=Zt(e,{strict:!1}),a=s.filter(u=>i?u.type==="function"||u.type==="error"?$b(u)===rt(e,0,4):u.type==="event"?Sc(u)===e:!1:"name"in u&&u.name===e);if(a.length===0)throw new vc({name:e});if(a.length===1)return {...a[0],...r?{hash:Sc(a[0])}:{}};let o;for(let u of a){if(!("inputs"in u))continue;if(!n||n.length===0){if(!u.inputs||u.inputs.length===0)return {...u,...r?{hash:Sc(u)}:{}};continue}if(!u.inputs||u.inputs.length===0||u.inputs.length!==n.length)continue;if(n.every((h,m)=>{let y="inputs"in u&&u.inputs[m];return y?bp(h,y):!1})){if(o&&"inputs"in o&&o.inputs){let h=_b(u.inputs,o.inputs,n);if(h)throw new Mb({abiItem:u,type:h[0]},{abiItem:o,type:h[1]})}o=u;}}let c=(()=>{if(o)return o;let[u,...l]=a;return {...u,overloads:l}})();if(!c)throw new vc({name:e});return {...c,...r?{hash:Sc(c)}:{}}}function $b(...s){let e=(()=>{if(Array.isArray(s[0])){let[t,n]=s;return vh(t,n)}return s[0]})();return rt(Sc(e),0,4)}function y4(...s){let e=(()=>{if(Array.isArray(s[0])){let[n,r]=s;return vh(n,r)}return s[0]})(),t=typeof e=="string"?e:vn(e);return Sp(t)}function Sc(...s){let e=(()=>{if(Array.isArray(s[0])){let[t,n]=s;return vh(t,n)}return s[0]})();return typeof e!="string"&&"hash"in e&&e.hash?e.hash:dt(cs(y4(e)))}var Mb=class extends K{constructor(e,t){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${e.type}\` in \`${Sp(vn(e.abiItem))}\`, and`,`\`${t.type}\` in \`${Sp(vn(t.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"});}},vc=class extends K{constructor({name:e,data:t,type:n="item"}){let r=e?` with name "${e}"`:t?` with data "${t}"`:"";super(`ABI ${n}${r} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"});}},vp=class extends K{constructor({data:e}){super(`Selector size is invalid. Expected 4 bytes. Received ${Oe(e)} bytes ("${e}").`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.InvalidSelectorSizeError"});}};var ot={};be(ot,{ArrayLengthMismatchError:()=>Eh,BytesSizeMismatchError:()=>Ec,DataSizeTooSmallError:()=>Np,InvalidArrayError:()=>Ah,InvalidTypeError:()=>ha,LengthMismatchError:()=>Ch,ZeroDataError:()=>kp,decode:()=>Ac,encode:()=>On,encodePacked:()=>Cp,format:()=>V4,from:()=>Pp});var b6=/^(.*)\[([0-9]*)\]$/,xp=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,xc=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,qb=2n**256n-1n;function la(s,e,t){let{checksumAddress:n,staticPosition:r}=t,i=Gb(e.type);if(i){let[a,o]=i;return b4(s,{...e,type:o},{checksumAddress:n,length:a,staticPosition:r})}if(e.type==="tuple")return E4(s,e,{checksumAddress:n,staticPosition:r});if(e.type==="address")return w4(s,{checksum:n});if(e.type==="bool")return S4(s);if(e.type.startsWith("bytes"))return v4(s,e,{staticPosition:r});if(e.type.startsWith("uint")||e.type.startsWith("int"))return x4(s,e);if(e.type==="string")return A4(s,{staticPosition:r});throw new ha(e.type)}var S6=32,Fb=32;function w4(s,e={}){let{checksum:t=!1}=e,n=s.readBytes(32);return [(i=>t?Sh(i):i)(Ee(Pb(n,-20))),32]}function b4(s,e,t){let{checksumAddress:n,length:r,staticPosition:i}=t;if(!r){let c=js(s.readBytes(Fb)),u=i+c,l=u+S6;s.setPosition(u);let h=js(s.readBytes(S6)),m=xh(e),y=0,g=[];for(let w=0;w<h;++w){s.setPosition(l+(m?w*32:y));let[S,C]=la(s,e,{checksumAddress:n,staticPosition:l});y+=C,g.push(S);}return s.setPosition(i+32),[g,32]}if(xh(e)){let c=js(s.readBytes(Fb)),u=i+c,l=[];for(let h=0;h<r;++h){s.setPosition(u+h*32);let[m]=la(s,e,{checksumAddress:n,staticPosition:u});l.push(m);}return s.setPosition(i+32),[l,32]}let a=0,o=[];for(let c=0;c<r;++c){let[u,l]=la(s,e,{checksumAddress:n,staticPosition:i+a});a+=l,o.push(u);}return [o,a]}function S4(s){return [Bb(s.readBytes(32),{size:32}),32]}function v4(s,e,{staticPosition:t}){let[n,r]=e.type.split("bytes");if(!r){let a=js(s.readBytes(32));s.setPosition(t+a);let o=js(s.readBytes(32));if(o===0)return s.setPosition(t+32),["0x",32];let c=s.readBytes(o);return s.setPosition(t+32),[Ee(c),32]}return [Ee(s.readBytes(Number.parseInt(r,10),32)),32]}function x4(s,e){let t=e.type.startsWith("int"),n=Number.parseInt(e.type.split("int")[1]||"256",10),r=s.readBytes(32);return [n>48?Tb(r,{signed:t}):js(r,{signed:t}),32]}function E4(s,e,t){let{checksumAddress:n,staticPosition:r}=t,i=e.components.length===0||e.components.some(({name:c})=>!c),a=i?[]:{},o=0;if(xh(e)){let c=js(s.readBytes(Fb)),u=r+c;for(let l=0;l<e.components.length;++l){let h=e.components[l];s.setPosition(u+o);let[m,y]=la(s,h,{checksumAddress:n,staticPosition:u});o+=y,a[i?l:h?.name]=m;}return s.setPosition(r+32),[a,32]}for(let c=0;c<e.components.length;++c){let u=e.components[c],[l,h]=la(s,u,{checksumAddress:n,staticPosition:r});a[i?c:u?.name]=l,o+=h;}return [a,o]}function A4(s,{staticPosition:e}){let t=js(s.readBytes(32)),n=e+t;s.setPosition(n);let r=js(s.readBytes(32));if(r===0)return s.setPosition(e+32),["",32];let i=s.readBytes(r,32),a=dp(mp(i));return s.setPosition(e+32),[a,32]}function v6({checksumAddress:s,parameters:e,values:t}){let n=[];for(let r=0;r<e.length;r++)n.push(Kb({checksumAddress:s,parameter:e[r],value:t[r]}));return n}function Kb({checksumAddress:s=!1,parameter:e,value:t}){let n=e,r=Gb(n.type);if(r){let[i,a]=r;return C4(t,{checksumAddress:s,length:i,parameter:{...n,type:a}})}if(n.type==="tuple")return B4(t,{checksumAddress:s,parameter:n});if(n.type==="address")return I4(t,{checksum:s});if(n.type==="bool")return k4(t);if(n.type.startsWith("uint")||n.type.startsWith("int")){let i=n.type.startsWith("int"),[,,a="256"]=xc.exec(n.type)??[];return P4(t,{signed:i,size:Number(a)})}if(n.type.startsWith("bytes"))return N4(t,{type:n.type});if(n.type==="string")return T4(t);throw new ha(n.type)}function Ap(s){let e=0;for(let i=0;i<s.length;i++){let{dynamic:a,encoded:o}=s[i];a?e+=32:e+=Oe(o);}let t=[],n=[],r=0;for(let i=0;i<s.length;i++){let{dynamic:a,encoded:o}=s[i];a?(t.push(le(e+r,{size:32})),n.push(o),r+=Oe(o)):t.push(o);}return Fe(...t,...n)}function I4(s,e){let{checksum:t=!1}=e;return Qt(s,{strict:t}),{dynamic:!1,encoded:cn(s.toLowerCase())}}function C4(s,e){let{checksumAddress:t,length:n,parameter:r}=e,i=n===null;if(!Array.isArray(s))throw new Ah(s);if(!i&&s.length!==n)throw new Eh({expectedLength:n,givenLength:s.length,type:`${r.type}[${n}]`});let a=!1,o=[];for(let c=0;c<s.length;c++){let u=Kb({checksumAddress:t,parameter:r,value:s[c]});u.dynamic&&(a=!0),o.push(u);}if(i||a){let c=Ap(o);if(i){let u=le(o.length,{size:32});return {dynamic:!0,encoded:o.length>0?Fe(u,c):u}}if(a)return {dynamic:!0,encoded:c}}return {dynamic:!1,encoded:Fe(...o.map(({encoded:c})=>c))}}function N4(s,{type:e}){let[,t]=e.split("bytes"),n=Oe(s);if(!t){let r=s;return n%32!==0&&(r=Ls(r,Math.ceil((s.length-2)/2/32)*32)),{dynamic:!0,encoded:Fe(cn(le(n,{size:32})),r)}}if(n!==Number.parseInt(t,10))throw new Ec({expectedSize:Number.parseInt(t,10),value:s});return {dynamic:!1,encoded:Ls(s)}}function k4(s){if(typeof s!="boolean")throw new K(`Invalid boolean value: "${s}" (type: ${typeof s}). Expected: \`true\` or \`false\`.`);return {dynamic:!1,encoded:cn(yh(s))}}function P4(s,{signed:e,size:t}){if(typeof t=="number"){let n=2n**(BigInt(t)-(e?1n:0n))-1n,r=e?-n-1n:0n;if(s>n||s<r)throw new wc({max:n.toString(),min:r.toString(),signed:e,size:t/8,value:s.toString()})}return {dynamic:!1,encoded:le(s,{size:32,signed:e})}}function T4(s){let e=cs(s),t=Math.ceil(Oe(e)/32),n=[];for(let r=0;r<t;r++)n.push(Ls(rt(e,r*32,(r+1)*32)));return {dynamic:!0,encoded:Fe(Ls(le(Oe(e),{size:32})),...n)}}function B4(s,e){let{checksumAddress:t,parameter:n}=e,r=!1,i=[];for(let a=0;a<n.components.length;a++){let o=n.components[a],c=Array.isArray(s)?a:o.name,u=Kb({checksumAddress:t,parameter:o,value:s[c]});i.push(u),u.dynamic&&(r=!0);}return {dynamic:r,encoded:r?Ap(i):Fe(...i.map(({encoded:a})=>a))}}function Gb(s){let e=s.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function xh(s){let{type:e}=s;if(e==="string"||e==="bytes"||e.endsWith("[]"))return !0;if(e==="tuple")return s.components?.some(xh);let t=Gb(s.type);return !!(t&&xh({...s,type:t[1]}))}var R4={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new Jb({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(s){if(s<0||s>this.bytes.length-1)throw new Wb({length:this.bytes.length,position:s})},decrementPosition(s){if(s<0)throw new Ip({offset:s});let e=this.position-s;this.assertPosition(e),this.position=e;},getReadCount(s){return this.positionReadCount.get(s||this.position)||0},incrementPosition(s){if(s<0)throw new Ip({offset:s});let e=this.position+s;this.assertPosition(e),this.position=e;},inspectByte(s){let e=s??this.position;return this.assertPosition(e),this.bytes[e]},inspectBytes(s,e){let t=e??this.position;return this.assertPosition(t+s-1),this.bytes.subarray(t,t+s)},inspectUint8(s){let e=s??this.position;return this.assertPosition(e),this.bytes[e]},inspectUint16(s){let e=s??this.position;return this.assertPosition(e+1),this.dataView.getUint16(e)},inspectUint24(s){let e=s??this.position;return this.assertPosition(e+2),(this.dataView.getUint16(e)<<8)+this.dataView.getUint8(e+2)},inspectUint32(s){let e=s??this.position;return this.assertPosition(e+3),this.dataView.getUint32(e)},pushByte(s){this.assertPosition(this.position),this.bytes[this.position]=s,this.position++;},pushBytes(s){this.assertPosition(this.position+s.length-1),this.bytes.set(s,this.position),this.position+=s.length;},pushUint8(s){this.assertPosition(this.position),this.bytes[this.position]=s,this.position++;},pushUint16(s){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,s),this.position+=2;},pushUint24(s){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,s>>8),this.dataView.setUint8(this.position+2,s&255),this.position+=3;},pushUint32(s){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,s),this.position+=4;},readByte(){this.assertReadLimit(),this._touch();let s=this.inspectByte();return this.position++,s},readBytes(s,e){this.assertReadLimit(),this._touch();let t=this.inspectBytes(s);return this.position+=e??s,t},readUint8(){this.assertReadLimit(),this._touch();let s=this.inspectUint8();return this.position+=1,s},readUint16(){this.assertReadLimit(),this._touch();let s=this.inspectUint16();return this.position+=2,s},readUint24(){this.assertReadLimit(),this._touch();let s=this.inspectUint24();return this.position+=3,s},readUint32(){this.assertReadLimit(),this._touch();let s=this.inspectUint32();return this.position+=4,s},get remaining(){return this.bytes.length-this.position},setPosition(s){let e=this.position;return this.assertPosition(s),this.position=s,()=>this.position=e},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let s=this.getReadCount();this.positionReadCount.set(this.position,s+1),s>0&&this.recursiveReadCount++;}};function Ih(s,{recursiveReadLimit:e=8192}={}){let t=Object.create(R4);return t.bytes=s,t.dataView=new DataView(s.buffer,s.byteOffset,s.byteLength),t.positionReadCount=new Map,t.recursiveReadLimit=e,t}var Ip=class extends K{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"});}},Wb=class extends K{constructor({length:e,position:t}){super(`Position \`${t}\` is out of bounds (\`0 < position < ${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"});}},Jb=class extends K{constructor({count:e,limit:t}){super(`Recursive read limit of \`${t}\` exceeded (recursive read count: \`${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"});}};function Ac(s,e,t={}){let{as:n="Array",checksumAddress:r=!1}=t,i=typeof e=="string"?Ye(e):e,a=Ih(i);if(ps(i)===0&&s.length>0)throw new kp;if(ps(i)&&ps(i)<32)throw new Np({data:typeof e=="string"?e:Ee(e),parameters:s,size:ps(i)});let o=0,c=n==="Array"?[]:{};for(let u=0;u<s.length;++u){let l=s[u];a.setPosition(o);let[h,m]=la(a,l,{checksumAddress:r,staticPosition:0});o+=m,n==="Array"?c.push(h):c[l.name??u]=h;}return c}function On(s,e,t){let{checksumAddress:n=!1}=t??{};if(s.length!==e.length)throw new Ch({expectedLength:s.length,givenLength:e.length});let r=v6({checksumAddress:n,parameters:s,values:e}),i=Ap(r);return i.length===0?"0x":i}function Cp(s,e){if(s.length!==e.length)throw new Ch({expectedLength:s.length,givenLength:e.length});let t=[];for(let n=0;n<s.length;n++){let r=s[n],i=e[n];t.push(Cp.encode(r,i));}return Fe(...t)}(function(s){function e(t,n,r=!1){if(t==="address"){let c=n;return Qt(c),cn(c.toLowerCase(),r?32:0)}if(t==="string")return cs(n);if(t==="bytes")return n;if(t==="bool")return cn(yh(n),r?32:1);let i=t.match(xc);if(i){let[c,u,l="256"]=i,h=Number.parseInt(l,10)/8;return le(n,{size:r?32:h,signed:u==="int"})}let a=t.match(xp);if(a){let[c,u]=a;if(Number.parseInt(u,10)!==(n.length-2)/2)throw new Ec({expectedSize:Number.parseInt(u,10),value:n});return Ls(n,r?32:0)}let o=t.match(b6);if(o&&Array.isArray(n)){let[c,u]=o,l=[];for(let h=0;h<n.length;h++)l.push(e(u,n[h],!0));return l.length===0?"0x":Fe(...l)}throw new ha(t)}s.encode=e;})(Cp||(Cp={}));function V4(s){return nn(s)}function Pp(s){return Array.isArray(s)&&typeof s[0]=="string"?Z0(s):typeof s=="string"?Z0(s):s}var Np=class extends K{constructor({data:e,parameters:t,size:n}){super(`Data size of ${n} bytes is too small for given parameters.`,{metaMessages:[`Params: (${nn(t)})`,`Data: ${e} (${n} bytes)`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"});}},kp=class extends K{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.'),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"});}},Eh=class extends K{constructor({expectedLength:e,givenLength:t,type:n}){super(`Array length mismatch for type \`${n}\`. Expected: \`${e}\`. Given: \`${t}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"});}},Ec=class extends K{constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" (bytes${Oe(t)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"});}},Ch=class extends K{constructor({expectedLength:e,givenLength:t}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${t}`].join(`
|
|
340
|
-
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"});}},Ah=class extends K{constructor(e){super(`Value \`${e}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"});}},ha=class extends K{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"});}};var te={};be(te,{decodeData:()=>D4,decodeResult:()=>L4,encodeData:()=>j4,encodeResult:()=>U4,format:()=>H4,from:()=>_4,fromAbi:()=>fa,getSelector:()=>E6});function D4(...s){let[e,t]=(()=>{if(Array.isArray(s[0])){let[i,a,o]=s;return [fa(i,a),o]}return s})(),{overloads:n}=e;if(Oe(t)<4)throw new vp({data:t});if(e.inputs?.length===0)return;let r=n?fa([e,...n],t):e;if(!(Oe(t)<=4))return Ac(r.inputs,rt(t,4))}function L4(...s){let[e,t,n={}]=(()=>{if(Array.isArray(s[0])){let[i,a,o,c]=s;return [fa(i,a),o,c]}return s})(),r=Ac(e.outputs,t,n);if(!(r&&Object.keys(r).length===0))return r&&Object.keys(r).length===1?Array.isArray(r)?r[0]:Object.values(r)[0]:r}function j4(...s){let[e,t=[]]=(()=>{if(Array.isArray(s[0])){let[u,l,h]=s;return [fa(u,l,{args:h}),h]}let[o,c]=s;return [o,c]})(),{overloads:n}=e,r=n?fa([e,...n],e.name,{args:t}):e,i=E6(r),a=t.length>0?On(r.inputs,t):void 0;return a?Fe(i,a):i}function U4(...s){let[e,t,n={}]=(()=>{if(Array.isArray(s[0])){let[a,o,c,u]=s;return [fa(a,o),c,u]}return s})(),{as:r="Array"}=n,i=e.outputs.length===1?[t]:Array.isArray(t)?t:r==="Object"?Object.values(t):[t];return On(e.outputs,i)}function H4(s){return vn(s)}function _4(s,e={}){return y6(s,e)}function fa(s,e,t){let n=vh(s,e,t);if(n.type!=="function")throw new vc({name:e,type:"function"});return n}function E6(s){return $b(s)}function A6(s){let e=[];for(let t=0;t<s.length;t++){let[n,r]=s[t];n&&Qt(n,{strict:!1}),e.push({address:n,storageKeys:r.map(i=>Rb(i)?i:aa(i))});}return e}function I6(s){if(!s||s.length===0)return [];let e=[];for(let{address:t,storageKeys:n}of s){for(let r=0;r<n.length;r++)if(Oe(n[r])!==32)throw new zb({storageKey:n[r]});t&&Qt(t,{strict:!1}),e.push([t,n]);}return e}var zb=class extends K{constructor({storageKey:e}){super(`Size for storage key "${e}" is invalid. Expected 32 bytes. Got ${Oe(e)} bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AccessList.InvalidStorageKeySizeError"});}};function k6(s){return M4(s,"Hex")}function M4(s,e){let t=e,n=(()=>{if(typeof s=="string"){if(s.length>3&&s.length%2!==0)throw new gh(s);return Ye(s)}return s})(),r=Ih(n,{recursiveReadLimit:Number.POSITIVE_INFINITY});return P6(r,t)}function P6(s,e="Hex"){if(s.bytes.length===0)return e==="Hex"?Ee(s.bytes):s.bytes;let t=s.readByte();if(t<128&&s.decrementPosition(1),t<192){let r=N6(s,t,128),i=s.readBytes(r);return e==="Hex"?Ee(i):i}let n=N6(s,t,192);return $4(s,n,e)}function N6(s,e,t){if(t===128&&e<128)return 1;if(e<=t+55)return e-t;if(e===t+55+1)return s.readUint8();if(e===t+55+2)return s.readUint16();if(e===t+55+3)return s.readUint24();if(e===t+55+4)return s.readUint32();throw new K("Invalid RLP prefix")}function $4(s,e,t){let n=s.position,r=[];for(;s.position-n<e;)r.push(P6(s,t));return r}function q4(s,e){let{as:t}=e,n=B6(s),r=Ih(new Uint8Array(n.length));return n.encode(r),t==="Hex"?Ee(r.bytes):r.bytes}function T6(s,e={}){let{as:t="Hex"}=e;return q4(s,{as:t})}function B6(s){return Array.isArray(s)?F4(s.map(e=>B6(e))):K4(s)}function F4(s){let e=s.reduce((r,i)=>r+i.length,0),t=O6(e);return {length:e<=55?1+e:1+t+e,encode(r){e<=55?r.pushByte(192+e):(r.pushByte(247+t),t===1?r.pushUint8(e):t===2?r.pushUint16(e):t===3?r.pushUint24(e):r.pushUint32(e));for(let{encode:i}of s)i(r);}}}function K4(s){let e=typeof s=="string"?Ye(s):s,t=O6(e.length);return {length:e.length===1&&e[0]<128?1:e.length<=55?1+e.length:1+t+e.length,encode(r){e.length===1&&e[0]<128?r.pushBytes(e):e.length<=55?(r.pushByte(128+e.length),r.pushBytes(e)):(r.pushByte(183+t),t===1?r.pushUint8(e.length):t===2?r.pushUint16(e.length):t===3?r.pushUint24(e.length):r.pushUint32(e.length),r.pushBytes(e));}}}function O6(s){if(s<=255)return 1;if(s<=65535)return 2;if(s<=16777215)return 3;if(s<=4294967295)return 4;throw new K("Length is too large.")}var At={};be(At,{InvalidRError:()=>Rp,InvalidSError:()=>Vp,InvalidSerializedSizeError:()=>Op,InvalidVError:()=>Dp,InvalidYParityError:()=>ma,MissingPropertiesError:()=>Cc,assert:()=>Lp,extract:()=>jp,from:()=>Nh,fromBytes:()=>Q6,fromDerBytes:()=>cB,fromDerHex:()=>X6,fromHex:()=>fS,fromLegacy:()=>eC,fromRpc:()=>tC,fromTuple:()=>dS,toBytes:()=>uB,toDerBytes:()=>lB,toDerHex:()=>hB,toHex:()=>sC,toLegacy:()=>fB,toRpc:()=>mS,toTuple:()=>pS,vToYParity:()=>Up,validate:()=>dB,yParityToV:()=>gS});var Tp=class extends Er{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,p3(e);let n=Zi(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let a=0;a<i.length;a++)i[a]^=54;this.iHash.update(i),this.oHash=e.create();for(let a=0;a<i.length;a++)i[a]^=106;this.oHash.update(i),zt(i);}update(e){return En(this),this.iHash.update(e),this}digestInto(e){En(this),an(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy();}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy();}},Yb=(s,e,t)=>new Tp(s,e).update(t).digest();Yb.create=(s,e)=>new Tp(s,e);var Xt=BigInt(0),_t=BigInt(1),da=BigInt(2),G4=BigInt(3),D6=BigInt(4),L6=BigInt(5),j6=BigInt(8);function Ht(s,e){let t=s%e;return t>=Xt?t:e+t}function gs(s,e,t){let n=s;for(;e-- >Xt;)n*=n,n%=t;return n}function Bp(s,e){if(s===Xt)throw new Error("invert: expected non-zero number");if(e<=Xt)throw new Error("invert: expected positive modulus, got "+e);let t=Ht(s,e),n=e,r=Xt,a=_t;for(;t!==Xt;){let u=n/t,l=n%t,h=r-a*u;n=t,t=l,r=a,a=h;}if(n!==_t)throw new Error("invert: does not exist");return Ht(r,e)}function U6(s,e){let t=(s.ORDER+_t)/D6,n=s.pow(e,t);if(!s.eql(s.sqr(n),e))throw new Error("Cannot find square root");return n}function W4(s,e){let t=(s.ORDER-L6)/j6,n=s.mul(e,da),r=s.pow(n,t),i=s.mul(e,r),a=s.mul(s.mul(i,da),r),o=s.mul(i,s.sub(a,s.ONE));if(!s.eql(s.sqr(o),e))throw new Error("Cannot find square root");return o}function J4(s){if(s<BigInt(3))throw new Error("sqrt is not defined for small field");let e=s-_t,t=0;for(;e%da===Xt;)e/=da,t++;let n=da,r=Rn(s);for(;V6(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return U6;let i=r.pow(n,e),a=(e+_t)/da;return function(c,u){if(c.is0(u))return u;if(V6(c,u)!==1)throw new Error("Cannot find square root");let l=t,h=c.mul(c.ONE,i),m=c.pow(u,e),y=c.pow(u,a);for(;!c.eql(m,c.ONE);){if(c.is0(m))return c.ZERO;let g=1,w=c.sqr(m);for(;!c.eql(w,c.ONE);)if(g++,w=c.sqr(w),g===l)throw new Error("Cannot find square root");let S=_t<<BigInt(l-g-1),C=c.pow(h,S);l=g,h=c.sqr(C),m=c.mul(m,h),y=c.mul(y,C);}return y}}function z4(s){return s%D6===G4?U6:s%j6===L6?W4:J4(s)}var Y4=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Zb(s){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Y4.reduce((n,r)=>(n[r]="function",n),e);return ra(s,t)}function Z4(s,e,t){if(t<Xt)throw new Error("invalid exponent, negatives unsupported");if(t===Xt)return s.ONE;if(t===_t)return e;let n=s.ONE,r=e;for(;t>Xt;)t&_t&&(n=s.mul(n,r)),r=s.sqr(r),t>>=_t;return n}function Qb(s,e,t=!1){let n=new Array(e.length).fill(t?s.ZERO:void 0),r=e.reduce((a,o,c)=>s.is0(o)?a:(n[c]=a,s.mul(a,o)),s.ONE),i=s.inv(r);return e.reduceRight((a,o,c)=>s.is0(o)?a:(n[c]=s.mul(a,n[c]),s.mul(a,o)),i),n}function V6(s,e){let t=(s.ORDER-_t)/da,n=s.pow(e,t),r=s.eql(n,s.ONE),i=s.eql(n,s.ZERO),a=s.eql(n,s.neg(s.ONE));if(!r&&!i&&!a)throw new Error("invalid Legendre symbol result");return r?1:i?0:-1}function Xb(s,e){e!==void 0&&Yi(e);let t=e!==void 0?e:s.toString(2).length,n=Math.ceil(t/8);return {nBitLength:t,nByteLength:n}}function Rn(s,e,t=!1,n={}){if(s<=Xt)throw new Error("invalid field: expected ORDER > 0, got "+s);let{nBitLength:r,nByteLength:i}=Xb(s,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let a,o=Object.freeze({ORDER:s,isLE:t,BITS:r,BYTES:i,MASK:na(r),ZERO:Xt,ONE:_t,create:c=>Ht(c,s),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Xt<=c&&c<s},is0:c=>c===Xt,isOdd:c=>(c&_t)===_t,neg:c=>Ht(-c,s),eql:(c,u)=>c===u,sqr:c=>Ht(c*c,s),add:(c,u)=>Ht(c+u,s),sub:(c,u)=>Ht(c-u,s),mul:(c,u)=>Ht(c*u,s),pow:(c,u)=>Z4(o,c,u),div:(c,u)=>Ht(c*Bp(u,s),s),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Bp(c,s),sqrt:n.sqrt||(c=>(a||(a=z4(s)),a(o,c))),toBytes:c=>t?bb(c,i):ta(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return t?wb(c):Cn(c)},invertBatch:c=>Qb(o,c),cmov:(c,u,l)=>l?u:c});return Object.freeze(o)}function H6(s){if(typeof s!="bigint")throw new Error("field order must be bigint");let e=s.toString(2).length;return Math.ceil(e/8)}function eS(s){let e=H6(s);return e+Math.ceil(e/2)}function _6(s,e,t=!1){let n=s.length,r=H6(e),i=eS(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let a=t?wb(s):Cn(s),o=Ht(a,e-_t)+_t;return t?bb(o,r):ta(o,r)}var M6=BigInt(0),iS=BigInt(1);function tS(s,e){let t=e.negate();return s?t:e}function q6(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function sS(s,e){q6(s,e);let t=Math.ceil(e/s)+1,n=2**(s-1),r=2**s,i=na(s),a=BigInt(s);return {windows:t,windowSize:n,mask:i,maxNumber:r,shiftBy:a}}function $6(s,e,t){let{windowSize:n,mask:r,maxNumber:i,shiftBy:a}=t,o=Number(s&r),c=s>>a;o>n&&(o-=i,c+=iS);let u=e*n,l=u+Math.abs(o)-1,h=o===0,m=o<0,y=e%2!==0;return {nextN:c,offset:l,isZero:h,isNeg:m,isNegF:y,offsetF:u}}function Q4(s,e){if(!Array.isArray(s))throw new Error("array expected");s.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)});}function X4(s,e){if(!Array.isArray(s))throw new Error("array of scalars expected");s.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)});}var nS=new WeakMap,F6=new WeakMap;function rS(s){return F6.get(s)||1}function K6(s,e){return {constTimeNegate:tS,hasPrecomputes(t){return rS(t)!==1},unsafeLadder(t,n,r=s.ZERO){let i=t;for(;n>M6;)n&iS&&(r=r.add(i)),i=i.double(),n>>=iS;return r},precomputeWindow(t,n){let{windows:r,windowSize:i}=sS(n,e),a=[],o=t,c=o;for(let u=0;u<r;u++){c=o,a.push(c);for(let l=1;l<i;l++)c=c.add(o),a.push(c);o=c.double();}return a},wNAF(t,n,r){let i=s.ZERO,a=s.BASE,o=sS(t,e);for(let c=0;c<o.windows;c++){let{nextN:u,offset:l,isZero:h,isNeg:m,isNegF:y,offsetF:g}=$6(r,c,o);r=u,h?a=a.add(tS(y,n[g])):i=i.add(tS(m,n[l]));}return {p:i,f:a}},wNAFUnsafe(t,n,r,i=s.ZERO){let a=sS(t,e);for(let o=0;o<a.windows&&r!==M6;o++){let{nextN:c,offset:u,isZero:l,isNeg:h}=$6(r,o,a);if(r=c,!l){let m=n[u];i=i.add(h?m.negate():m);}}return i},getPrecomputes(t,n,r){let i=nS.get(n);return i||(i=this.precomputeWindow(n,t),t!==1&&nS.set(n,r(i))),i},wNAFCached(t,n,r){let i=rS(t);return this.wNAF(i,this.getPrecomputes(i,t,r),n)},wNAFCachedUnsafe(t,n,r,i){let a=rS(t);return a===1?this.unsafeLadder(t,n,i):this.wNAFUnsafe(a,this.getPrecomputes(a,t,r),n,i)},setWindowSize(t,n){q6(n,e),F6.set(t,n),nS.delete(t);}}}function G6(s,e,t,n){Q4(t,s),X4(n,e);let r=t.length,i=n.length;if(r!==i)throw new Error("arrays of points and scalars must have equal length");let a=s.ZERO,o=X3(BigInt(r)),c=1;o>12?c=o-3:o>4?c=o-2:o>0&&(c=2);let u=na(c),l=new Array(Number(u)+1).fill(a),h=Math.floor((e.BITS-1)/c)*c,m=a;for(let y=h;y>=0;y-=c){l.fill(a);for(let w=0;w<i;w++){let S=n[w],C=Number(S>>BigInt(y)&u);l[C]=l[C].add(t[w]);}let g=a;for(let w=l.length-1,S=a;w>0;w--)S=S.add(l[w]),g=g.add(S);if(m=m.add(g),y!==0)for(let w=0;w<c;w++)m=m.double();}return m}function aS(s){return Zb(s.Fp),ra(s,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Xb(s.n,s.nBitLength),...s,p:s.Fp.ORDER})}function W6(s){s.lowS!==void 0&&dc("lowS",s.lowS),s.prehash!==void 0&&dc("prehash",s.prehash);}function eB(s){let e=aS(s);ra(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:t,Fp:n,a:r}=e;if(t){if(!n.eql(r,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}var uS=class extends Error{constructor(e=""){super(e);}},Vn={Err:uS,_tlv:{encode:(s,e)=>{let{Err:t}=Vn;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,r=oh(n);if(r.length/2&128)throw new t("tlv.encode: long form length too big");let i=n>127?oh(r.length/2|128):"";return oh(s)+i+r+e},decode(s,e){let{Err:t}=Vn,n=0;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==s)throw new t("tlv.decode: wrong tlv");let r=e[n++],i=!!(r&128),a=0;if(!i)a=r;else {let c=r&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let l of u)a=a<<8|l;if(n+=c,a<128)throw new t("tlv.decode(long): not minimal encoding")}let o=e.subarray(n,n+a);if(o.length!==a)throw new t("tlv.decode: wrong value length");return {v:o,l:e.subarray(n+a)}}},_int:{encode(s){let{Err:e}=Vn;if(s<Dn)throw new e("integer: negative integers are not allowed");let t=oh(s);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(s){let{Err:e}=Vn;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Cn(s)}},toSig(s){let{Err:e,_int:t,_tlv:n}=Vn,r=os("signature",s),{v:i,l:a}=n.decode(48,r);if(a.length)throw new e("invalid signature: left bytes after parsing");let{v:o,l:c}=n.decode(2,i),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return {r:t.decode(o),s:t.decode(u)}},hexFromSig(s){let{_tlv:e,_int:t}=Vn,n=e.encode(2,t.encode(s.r)),r=e.encode(2,t.encode(s.s)),i=n+r;return e.encode(48,i)}};function oS(s,e){return mc(ta(s,e))}var Dn=BigInt(0),Et=BigInt(1);BigInt(2);var cS=BigInt(3),tB=BigInt(4);function sB(s){let e=eB(s),{Fp:t}=e,n=Rn(e.n,e.nBitLength),r=e.toBytes||((x,v,I)=>{let D=v.toAffine();return uh(Uint8Array.from([4]),t.toBytes(D.x),t.toBytes(D.y))}),i=e.fromBytes||(x=>{let v=x.subarray(1),I=t.fromBytes(v.subarray(0,t.BYTES)),D=t.fromBytes(v.subarray(t.BYTES,2*t.BYTES));return {x:I,y:D}});function a(x){let{a:v,b:I}=e,D=t.sqr(x),F=t.mul(D,x);return t.add(t.add(F,t.mul(x,v)),I)}function o(x,v){let I=t.sqr(v),D=a(x);return t.eql(I,D)}if(!o(e.Gx,e.Gy))throw new Error("bad curve params: generator point");let c=t.mul(t.pow(e.a,cS),tB),u=t.mul(t.sqr(e.b),BigInt(27));if(t.is0(t.add(c,u)))throw new Error("bad curve params: a or b");function l(x){return cp(x,Et,e.n)}function h(x){let{allowedPrivateKeyLengths:v,nByteLength:I,wrapPrivateKey:D,n:F}=e;if(v&&typeof x!="bigint"){if(fc(x)&&(x=mc(x)),typeof x!="string"||!v.includes(x.length))throw new Error("invalid private key");x=x.padStart(I*2,"0");}let M;try{M=typeof x=="bigint"?x:Cn(os("private key",x,I));}catch{throw new Error("invalid private key, expected hex or "+I+" bytes, got "+typeof x)}return D&&(M=Ht(M,F)),sa("private key",M,Et,F),M}function m(x){if(!(x instanceof w))throw new Error("ProjectivePoint expected")}let y=Sb((x,v)=>{let{px:I,py:D,pz:F}=x;if(t.eql(F,t.ONE))return {x:I,y:D};let M=x.is0();v==null&&(v=M?t.ONE:t.inv(F));let W=t.mul(I,v),se=t.mul(D,v),q=t.mul(F,v);if(M)return {x:t.ZERO,y:t.ZERO};if(!t.eql(q,t.ONE))throw new Error("invZ was invalid");return {x:W,y:se}}),g=Sb(x=>{if(x.is0()){if(e.allowInfinityPoint&&!t.is0(x.py))return;throw new Error("bad point: ZERO")}let{x:v,y:I}=x.toAffine();if(!t.isValid(v)||!t.isValid(I))throw new Error("bad point: x or y not FE");if(!o(v,I))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return !0});class w{constructor(v,I,D){if(v==null||!t.isValid(v))throw new Error("x required");if(I==null||!t.isValid(I)||t.is0(I))throw new Error("y required");if(D==null||!t.isValid(D))throw new Error("z required");this.px=v,this.py=I,this.pz=D,Object.freeze(this);}static fromAffine(v){let{x:I,y:D}=v||{};if(!v||!t.isValid(I)||!t.isValid(D))throw new Error("invalid affine point");if(v instanceof w)throw new Error("projective point not allowed");let F=M=>t.eql(M,t.ZERO);return F(I)&&F(D)?w.ZERO:new w(I,D,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(v){let I=Qb(t,v.map(D=>D.pz));return v.map((D,F)=>D.toAffine(I[F])).map(w.fromAffine)}static fromHex(v){let I=w.fromAffine(i(os("pointHex",v)));return I.assertValidity(),I}static fromPrivateKey(v){return w.BASE.multiply(h(v))}static msm(v,I){return G6(w,n,v,I)}_setWindowSize(v){N.setWindowSize(this,v);}assertValidity(){g(this);}hasEvenY(){let{y:v}=this.toAffine();if(t.isOdd)return !t.isOdd(v);throw new Error("Field doesn't support isOdd")}equals(v){m(v);let{px:I,py:D,pz:F}=this,{px:M,py:W,pz:se}=v,q=t.eql(t.mul(I,se),t.mul(M,F)),J=t.eql(t.mul(D,se),t.mul(W,F));return q&&J}negate(){return new w(this.px,t.neg(this.py),this.pz)}double(){let{a:v,b:I}=e,D=t.mul(I,cS),{px:F,py:M,pz:W}=this,se=t.ZERO,q=t.ZERO,J=t.ZERO,ae=t.mul(F,F),Be=t.mul(M,M),j=t.mul(W,W),_=t.mul(F,M);return _=t.add(_,_),J=t.mul(F,W),J=t.add(J,J),se=t.mul(v,J),q=t.mul(D,j),q=t.add(se,q),se=t.sub(Be,q),q=t.add(Be,q),q=t.mul(se,q),se=t.mul(_,se),J=t.mul(D,J),j=t.mul(v,j),_=t.sub(ae,j),_=t.mul(v,_),_=t.add(_,J),J=t.add(ae,ae),ae=t.add(J,ae),ae=t.add(ae,j),ae=t.mul(ae,_),q=t.add(q,ae),j=t.mul(M,W),j=t.add(j,j),ae=t.mul(j,_),se=t.sub(se,ae),J=t.mul(j,Be),J=t.add(J,J),J=t.add(J,J),new w(se,q,J)}add(v){m(v);let{px:I,py:D,pz:F}=this,{px:M,py:W,pz:se}=v,q=t.ZERO,J=t.ZERO,ae=t.ZERO,Be=e.a,j=t.mul(e.b,cS),_=t.mul(I,M),Q=t.mul(D,W),me=t.mul(F,se),X=t.add(I,D),U=t.add(M,W);X=t.mul(X,U),U=t.add(_,Q),X=t.sub(X,U),U=t.add(I,F);let z=t.add(M,se);return U=t.mul(U,z),z=t.add(_,me),U=t.sub(U,z),z=t.add(D,F),q=t.add(W,se),z=t.mul(z,q),q=t.add(Q,me),z=t.sub(z,q),ae=t.mul(Be,U),q=t.mul(j,me),ae=t.add(q,ae),q=t.sub(Q,ae),ae=t.add(Q,ae),J=t.mul(q,ae),Q=t.add(_,_),Q=t.add(Q,_),me=t.mul(Be,me),U=t.mul(j,U),Q=t.add(Q,me),me=t.sub(_,me),me=t.mul(Be,me),U=t.add(U,me),_=t.mul(Q,U),J=t.add(J,_),_=t.mul(z,U),q=t.mul(X,q),q=t.sub(q,_),_=t.mul(X,Q),ae=t.mul(z,ae),ae=t.add(ae,_),new w(q,J,ae)}subtract(v){return this.add(v.negate())}is0(){return this.equals(w.ZERO)}wNAF(v){return N.wNAFCached(this,v,w.normalizeZ)}multiplyUnsafe(v){let{endo:I,n:D}=e;sa("scalar",v,Dn,D);let F=w.ZERO;if(v===Dn)return F;if(this.is0()||v===Et)return this;if(!I||N.hasPrecomputes(this))return N.wNAFCachedUnsafe(this,v,w.normalizeZ);let{k1neg:M,k1:W,k2neg:se,k2:q}=I.splitScalar(v),J=F,ae=F,Be=this;for(;W>Dn||q>Dn;)W&Et&&(J=J.add(Be)),q&Et&&(ae=ae.add(Be)),Be=Be.double(),W>>=Et,q>>=Et;return M&&(J=J.negate()),se&&(ae=ae.negate()),ae=new w(t.mul(ae.px,I.beta),ae.py,ae.pz),J.add(ae)}multiply(v){let{endo:I,n:D}=e;sa("scalar",v,Et,D);let F,M;if(I){let{k1neg:W,k1:se,k2neg:q,k2:J}=I.splitScalar(v),{p:ae,f:Be}=this.wNAF(se),{p:j,f:_}=this.wNAF(J);ae=N.constTimeNegate(W,ae),j=N.constTimeNegate(q,j),j=new w(t.mul(j.px,I.beta),j.py,j.pz),F=ae.add(j),M=Be.add(_);}else {let{p:W,f:se}=this.wNAF(v);F=W,M=se;}return w.normalizeZ([F,M])[0]}multiplyAndAddUnsafe(v,I,D){let F=w.BASE,M=(se,q)=>q===Dn||q===Et||!se.equals(F)?se.multiplyUnsafe(q):se.multiply(q),W=M(this,I).add(M(v,D));return W.is0()?void 0:W}toAffine(v){return y(this,v)}isTorsionFree(){let{h:v,isTorsionFree:I}=e;if(v===Et)return !0;if(I)return I(w,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:v,clearCofactor:I}=e;return v===Et?this:I?I(w,this):this.multiplyUnsafe(e.h)}toRawBytes(v=!0){return dc("isCompressed",v),this.assertValidity(),r(w,this,v)}toHex(v=!0){return dc("isCompressed",v),mc(this.toRawBytes(v))}}w.BASE=new w(e.Gx,e.Gy,t.ONE),w.ZERO=new w(t.ZERO,t.ONE,t.ZERO);let{endo:S,nBitLength:C}=e,N=K6(w,S?Math.ceil(C/2):C);return {CURVE:e,ProjectivePoint:w,normPrivateKeyToScalar:h,weierstrassEquation:a,isWithinCurveOrder:l}}function nB(s){let e=aS(s);return ra(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function J6(s){let e=nB(s),{Fp:t,n,nByteLength:r,nBitLength:i}=e,a=t.BYTES+1,o=2*t.BYTES+1;function c(j){return Ht(j,n)}function u(j){return Bp(j,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:h,weierstrassEquation:m,isWithinCurveOrder:y}=sB({...e,toBytes(j,_,Q){let me=_.toAffine(),X=t.toBytes(me.x),U=uh;return dc("isCompressed",Q),Q?U(Uint8Array.from([_.hasEvenY()?2:3]),X):U(Uint8Array.from([4]),X,t.toBytes(me.y))},fromBytes(j){let _=j.length,Q=j[0],me=j.subarray(1);if(_===a&&(Q===2||Q===3)){let X=Cn(me);if(!cp(X,Et,t.ORDER))throw new Error("Point is not on curve");let U=m(X),z;try{z=t.sqrt(U);}catch(xe){let Ve=xe instanceof Error?": "+xe.message:"";throw new Error("Point is not on curve"+Ve)}let Y=(z&Et)===Et;return (Q&1)===1!==Y&&(z=t.neg(z)),{x:X,y:z}}else if(_===o&&Q===4){let X=t.fromBytes(me.subarray(0,t.BYTES)),U=t.fromBytes(me.subarray(t.BYTES,2*t.BYTES));return {x:X,y:U}}else {let X=a,U=o;throw new Error("invalid Point, expected length of "+X+", or uncompressed "+U+", got "+_)}}});function g(j){let _=n>>Et;return j>_}function w(j){return g(j)?c(-j):j}let S=(j,_,Q)=>Cn(j.slice(_,Q));class C{constructor(_,Q,me){sa("r",_,Et,n),sa("s",Q,Et,n),this.r=_,this.s=Q,me!=null&&(this.recovery=me),Object.freeze(this);}static fromCompact(_){let Q=r;return _=os("compactSignature",_,Q*2),new C(S(_,0,Q),S(_,Q,2*Q))}static fromDER(_){let{r:Q,s:me}=Vn.toSig(os("DER",_));return new C(Q,me)}assertValidity(){}addRecoveryBit(_){return new C(this.r,this.s,_)}recoverPublicKey(_){let{r:Q,s:me,recovery:X}=this,U=F(os("msgHash",_));if(X==null||![0,1,2,3].includes(X))throw new Error("recovery id invalid");let z=X===2||X===3?Q+e.n:Q;if(z>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let Y=X&1?"03":"02",pe=l.fromHex(Y+oS(z,t.BYTES)),xe=u(z),Ve=c(-U*xe),Ut=c(me*xe),He=l.BASE.multiplyAndAddUnsafe(pe,Ve,Ut);if(!He)throw new Error("point at infinify");return He.assertValidity(),He}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new C(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return ch(this.toDERHex())}toDERHex(){return Vn.hexFromSig(this)}toCompactRawBytes(){return ch(this.toCompactHex())}toCompactHex(){let _=r;return oS(this.r,_)+oS(this.s,_)}}let N={isValidPrivateKey(j){try{return h(j),!0}catch{return !1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{let j=eS(e.n);return _6(e.randomBytes(j),e.n)},precompute(j=8,_=l.BASE){return _._setWindowSize(j),_.multiply(BigInt(3)),_}};function x(j,_=!0){return l.fromPrivateKey(j).toRawBytes(_)}function v(j){if(typeof j=="bigint")return !1;if(j instanceof l)return !0;let Q=os("key",j).length,me=t.BYTES,X=me+1,U=2*me+1;if(!(e.allowedPrivateKeyLengths||r===X))return Q===X||Q===U}function I(j,_,Q=!0){if(v(j)===!0)throw new Error("first arg must be private key");if(v(_)===!1)throw new Error("second arg must be public key");return l.fromHex(_).multiply(h(j)).toRawBytes(Q)}let D=e.bits2int||function(j){if(j.length>8192)throw new Error("input is too large");let _=Cn(j),Q=j.length*8-i;return Q>0?_>>BigInt(Q):_},F=e.bits2int_modN||function(j){return c(D(j))},M=na(i);function W(j){return sa("num < 2^"+i,j,Dn,M),ta(j,r)}function se(j,_,Q=q){if(["recovered","canonical"].some(ee=>ee in Q))throw new Error("sign() legacy options not supported");let{hash:me,randomBytes:X}=e,{lowS:U,prehash:z,extraEntropy:Y}=Q;U==null&&(U=!0),j=os("msgHash",j),W6(Q),z&&(j=os("prehashed msgHash",me(j)));let pe=F(j),xe=h(_),Ve=[W(xe),W(pe)];if(Y!=null&&Y!==!1){let ee=Y===!0?X(t.BYTES):Y;Ve.push(os("extraEntropy",ee));}let Ut=uh(...Ve),He=pe;function ke(ee){let rs=D(ee);if(!y(rs))return;let Cs=u(rs),is=l.BASE.multiply(rs).toAffine(),De=c(is.x);if(De===Dn)return;let Ml=c(Cs*c(He+De*xe));if(Ml===Dn)return;let nc=(is.x===De?0:2)|Number(is.y&Et),YA=Ml;return U&&g(Ml)&&(YA=w(Ml),nc^=1),new C(De,YA,nc)}return {seed:Ut,k2sig:ke}}let q={lowS:e.lowS,prehash:!1},J={lowS:e.lowS,prehash:!1};function ae(j,_,Q=q){let{seed:me,k2sig:X}=se(j,_,Q),U=e;return e6(U.hash.outputLen,U.nByteLength,U.hmac)(me,X)}l.BASE._setWindowSize(8);function Be(j,_,Q,me=J){let X=j;_=os("msgHash",_),Q=os("publicKey",Q);let{lowS:U,prehash:z,format:Y}=me;if(W6(me),"strict"in me)throw new Error("options.strict was renamed to lowS");if(Y!==void 0&&Y!=="compact"&&Y!=="der")throw new Error("format must be compact or der");let pe=typeof X=="string"||fc(X),xe=!pe&&!Y&&typeof X=="object"&&X!==null&&typeof X.r=="bigint"&&typeof X.s=="bigint";if(!pe&&!xe)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let Ve,Ut;try{if(xe&&(Ve=new C(X.r,X.s)),pe){try{Y!=="compact"&&(Ve=C.fromDER(X));}catch(nc){if(!(nc instanceof Vn.Err))throw nc}!Ve&&Y!=="der"&&(Ve=C.fromCompact(X));}Ut=l.fromHex(Q);}catch{return !1}if(!Ve||U&&Ve.hasHighS())return !1;z&&(_=e.hash(_));let{r:He,s:ke}=Ve,ee=F(_),rs=u(ke),Cs=c(ee*rs),is=c(He*rs),De=l.BASE.multiplyAndAddUnsafe(Ut,Cs,is)?.toAffine();return De?c(De.x)===He:!1}return {CURVE:e,getPublicKey:x,getSharedSecret:I,sign:ae,verify:Be,ProjectivePoint:l,Signature:C,utils:N}}function rB(s){return {hash:s,hmac:(e,...t)=>Yb(s,e,y3(...t)),randomBytes:w3}}function Ic(s,e){let t=n=>J6({...s,...rB(n)});return {...t(e),create:t}}var Z6=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),z6=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),iB=BigInt(0),aB=BigInt(1),lS=BigInt(2),Y6=(s,e)=>(s+e/lS)/e;function oB(s){let e=Z6,t=BigInt(3),n=BigInt(6),r=BigInt(11),i=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),u=s*s*s%e,l=u*u*s%e,h=gs(l,t,e)*l%e,m=gs(h,t,e)*l%e,y=gs(m,lS,e)*u%e,g=gs(y,r,e)*y%e,w=gs(g,i,e)*g%e,S=gs(w,o,e)*w%e,C=gs(S,c,e)*S%e,N=gs(C,o,e)*w%e,x=gs(N,t,e)*l%e,v=gs(x,a,e)*g%e,I=gs(v,n,e)*u%e,D=gs(I,lS,e);if(!hS.eql(hS.sqr(D),s))throw new Error("Cannot find square root");return D}var hS=Rn(Z6,void 0,void 0,{sqrt:oB}),ys=Ic({a:iB,b:BigInt(7),Fp:hS,n:z6,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:s=>{let e=z6,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-aB*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),r=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=t,a=BigInt("0x100000000000000000000000000000000"),o=Y6(i*s,e),c=Y6(-n*s,e),u=Ht(s-o*t-c*r,e),l=Ht(-o*n-c*i,e),h=u>a,m=l>a;if(h&&(u=e-u),m&&(l=e-l),u>a||l>a)throw new Error("splitScalar: Endomorphism failed, k="+s);return {k1neg:h,k1:u,k2neg:m,k2:l}}}},hc);function Lp(s,e={}){let{recovered:t}=e;if(typeof s.r>"u")throw new Cc({signature:s});if(typeof s.s>"u")throw new Cc({signature:s});if(t&&typeof s.yParity>"u")throw new Cc({signature:s});if(s.r<0n||s.r>qb)throw new Rp({value:s.r});if(s.s<0n||s.s>qb)throw new Vp({value:s.s});if(typeof s.yParity=="number"&&s.yParity!==0&&s.yParity!==1)throw new ma({value:s.yParity})}function Q6(s){return fS(Ee(s))}function fS(s){if(s.length!==130&&s.length!==132)throw new Op({signature:s});let e=BigInt(rt(s,0,32)),t=BigInt(rt(s,32,64)),n=(()=>{let r=+`0x${s.slice(130)}`;if(!Number.isNaN(r))try{return Up(r)}catch{throw new ma({value:r})}})();return typeof n>"u"?{r:e,s:t}:{r:e,s:t,yParity:n}}function jp(s){if(!(typeof s.r>"u")&&!(typeof s.s>"u"))return Nh(s)}function Nh(s){let e=typeof s=="string"?fS(s):s instanceof Uint8Array?Q6(s):typeof s.r=="string"?tC(s):s.v?eC(s):{r:s.r,s:s.s,...typeof s.yParity<"u"?{yParity:s.yParity}:{}};return Lp(e),e}function cB(s){return X6(Ee(s))}function X6(s){let{r:e,s:t}=ys.Signature.fromDER(Yt(s).slice(2));return {r:e,s:t}}function eC(s){return {r:s.r,s:s.s,yParity:Up(s.v)}}function tC(s){let e=(()=>{let t=s.v?Number(s.v):void 0,n=s.yParity?Number(s.yParity):void 0;if(typeof t=="number"&&typeof n!="number"&&(n=Up(t)),typeof n!="number")throw new ma({value:s.yParity});return n})();return {r:BigInt(s.r),s:BigInt(s.s),yParity:e}}function dS(s){let[e,t,n]=s;return Nh({r:t==="0x"?0n:BigInt(t),s:n==="0x"?0n:BigInt(n),yParity:e==="0x"?0:Number(e)})}function uB(s){return Ye(sC(s))}function sC(s){Lp(s);let e=s.r,t=s.s;return Fe(le(e,{size:32}),le(t,{size:32}),typeof s.yParity=="number"?le(gS(s.yParity),{size:1}):"0x")}function lB(s){return new ys.Signature(s.r,s.s).toDERRawBytes()}function hB(s){return `0x${new ys.Signature(s.r,s.s).toDERHex()}`}function fB(s){return {r:s.r,s:s.s,v:gS(s.yParity)}}function mS(s){let{r:e,s:t,yParity:n}=s;return {r:le(e,{size:32}),s:le(t,{size:32}),yParity:n===0?"0x0":"0x1"}}function pS(s){let{r:e,s:t,yParity:n}=s;return [n?"0x01":"0x",e===0n?"0x":aa(le(e)),t===0n?"0x":aa(le(t))]}function dB(s,e={}){try{return Lp(s,e),!0}catch{return !1}}function Up(s){if(s===0||s===27)return 0;if(s===1||s===28)return 1;if(s>=35)return s%2===0?1:0;throw new Dp({value:s})}function gS(s){if(s===0)return 27;if(s===1)return 28;throw new ma({value:s})}var Op=class extends K{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Oe(Yt(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"});}},Cc=class extends K{constructor({signature:e}){super(`Signature \`${Ds(e)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"});}},Rp=class extends K{constructor({value:e}){super(`Value \`${e}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"});}},Vp=class extends K{constructor({value:e}){super(`Value \`${e}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"});}},ma=class extends K{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"});}},Dp=class extends K{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"});}};var mB=new TextEncoder,pB=new TextDecoder,Hp=Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((s,e)=>[e,s.charCodeAt(0)])),_p={...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((s,e)=>[s.charCodeAt(0),e])),61:0,45:62,95:63};function gB(s,e={}){let{pad:t=!0,url:n=!1}=e,r=new Uint8Array(Math.ceil(s.length/3)*4);for(let c=0,u=0;u<s.length;c+=4,u+=3){let l=(s[u]<<16)+(s[u+1]<<8)+(s[u+2]|0);r[c]=Hp[l>>18],r[c+1]=Hp[l>>12&63],r[c+2]=Hp[l>>6&63],r[c+3]=Hp[l&63];}let i=s.length%3,a=Math.floor(s.length/3)*4+(i&&i+1),o=pB.decode(new Uint8Array(r.buffer,0,a));return t&&i===1&&(o+="=="),t&&i===2&&(o+="="),n&&(o=o.replaceAll("+","-").replaceAll("/","_")),o}function nC(s,e={}){return gB(Ye(s),e)}function kh(s){let e=s.replace(/=+$/,""),t=e.length,n=new Uint8Array(t+3);mB.encodeInto(e+"===",n);for(let i=0,a=0;i<e.length;i+=4,a+=3){let o=(_p[n[i]]<<18)+(_p[n[i+1]]<<12)+(_p[n[i+2]]<<6)+_p[n[i+3]];n[a]=o>>16,n[a+1]=o>>8&255,n[a+2]=o&255;}let r=(t>>2)*3+(t%4&&t%4-1);return new Uint8Array(n.buffer,0,r)}var Ot={};be(Ot,{createKeyPair:()=>wB,getPublicKey:()=>aC,getSharedSecret:()=>bB,noble:()=>yB,randomPrivateKey:()=>oC,recoverAddress:()=>cC,recoverPublicKey:()=>uC,sign:()=>SB,verify:()=>vB});var Mp=!1;var yB=ys;function wB(s={}){let{as:e="Hex"}=s,t=oC({as:e}),n=aC({privateKey:t});return {privateKey:t,publicKey:n}}function aC(s){let{privateKey:e}=s,t=ys.ProjectivePoint.fromPrivateKey(Yt(e).slice(2));return Bn(t)}function bB(s){let{as:e="Hex",privateKey:t,publicKey:n}=s,a=ys.ProjectivePoint.fromHex(kr(n).slice(2)).multiply(ys.utils.normPrivateKeyToScalar(Yt(t).slice(2))).toRawBytes(!0);return e==="Hex"?Ee(a):a}function oC(s={}){let{as:e="Hex"}=s,t=ys.utils.randomPrivateKey();return e==="Hex"?Ee(t):t}function cC(s){return Ub(uC(s))}function uC(s){let{payload:e,signature:t}=s,{r:n,s:r,yParity:i}=t,o=new ys.Signature(BigInt(n),BigInt(r)).addRecoveryBit(i).recoverPublicKey(Yt(e).substring(2));return Bn(o)}function SB(s){let{extraEntropy:e=Mp,hash:t,payload:n,privateKey:r}=s,{r:i,s:a,recovery:o}=ys.sign(Pn(n),Pn(r),{extraEntropy:typeof e=="boolean"?e:Yt(e).slice(2),lowS:!0,...t?{prehash:!0}:{}});return {r:i,s:a,yParity:o}}function vB(s){let{address:e,hash:t,payload:n,publicKey:r,signature:i}=s;return e?Hb(e,cC({payload:n,signature:i})):ys.verify(i,Pn(n),p6(r),...t?[{prehash:!0,lowS:!0}]:[])}function lC(s,e={}){return {...s,blockNumber:s.blockNumber?BigInt(s.blockNumber):null,logIndex:s.logIndex?Number(s.logIndex):null,transactionIndex:s.transactionIndex?Number(s.transactionIndex):null}}function hC(s,e={}){return {address:s.address,blockHash:s.blockHash,blockNumber:typeof s.blockNumber=="bigint"?le(s.blockNumber):null,data:s.data,logIndex:typeof s.logIndex=="number"?le(s.logIndex):null,topics:s.topics,transactionHash:s.transactionHash,transactionIndex:typeof s.transactionIndex=="number"?le(s.transactionIndex):null,removed:s.removed}}var Nc={};be(Nc,{createKeyPair:()=>PB,getPublicKey:()=>gC,getSharedSecret:()=>TB,noble:()=>kB,randomPrivateKey:()=>yC,recoverPublicKey:()=>BB,sign:()=>OB,verify:()=>bS});var dC=Rn(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),xB=dC.create(BigInt("-3")),EB=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),yS=Ic({a:xB,b:EB,Fp:dC,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},hc);var mC=Rn(BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff")),AB=mC.create(BigInt("-3")),IB=BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef");Ic({a:AB,b:IB,Fp:mC,n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"),h:BigInt(1),lowS:!1},W3);var pC=Rn(BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")),CB=pC.create(BigInt("-3")),NB=BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00");Ic({a:CB,b:NB,Fp:pC,n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"),h:BigInt(1),lowS:!1,allowedPrivateKeyLengths:[130,131,132]},G3);var wS=yS,Ln=yS;var kB=Ln;function PB(s={}){let{as:e="Hex"}=s,t=yC({as:e}),n=gC({privateKey:t});return {privateKey:t,publicKey:n}}function gC(s){let{privateKey:e}=s,t=Ln.ProjectivePoint.fromPrivateKey(typeof e=="string"?e.slice(2):Ee(e).slice(2));return Bn(t)}function TB(s){let{as:e="Hex",privateKey:t,publicKey:n}=s,r=Ln.ProjectivePoint.fromHex(kr(n).slice(2)),i=typeof t=="string"?t.slice(2):Ee(t).slice(2),o=r.multiply(Ln.utils.normPrivateKeyToScalar(i)).toRawBytes(!0);return e==="Hex"?Ee(o):o}function yC(s={}){let{as:e="Hex"}=s,t=Ln.utils.randomPrivateKey();return e==="Hex"?Ee(t):t}function BB(s){let{payload:e,signature:t}=s,{r:n,s:r,yParity:i}=t,a=new Ln.Signature(BigInt(n),BigInt(r)).addRecoveryBit(i),o=e instanceof Uint8Array?Ee(e):e,c=a.recoverPublicKey(o.substring(2));return Bn(c)}function OB(s){let{extraEntropy:e=Mp,hash:t,payload:n,privateKey:r}=s,{r:i,s:a,recovery:o}=Ln.sign(n instanceof Uint8Array?n:Ye(n),r instanceof Uint8Array?r:Ye(r),{extraEntropy:typeof e=="boolean"?e:Yt(e).slice(2),lowS:!0,...t?{prehash:!0}:{}});return {r:i,s:a,yParity:o}}function bS(s){let{hash:e,payload:t,publicKey:n,signature:r}=s;return Ln.verify(r,t instanceof Uint8Array?t:Ye(t),kr(n).substring(2),...e?[{prehash:!0,lowS:!0}]:[])}var $p={};be($p,{encode:()=>wC,getSignPayload:()=>RB});function wC(s){let e=Yt(s);return Fe("0x19",cs(`Ethereum Signed Message:
|
|
341
|
-
`+Oe(e)),e)}function
|
|
342
|
-
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TransactionEnvelope.TipAboveFeeCapError"});}};var pa={};be(pa,{assert:()=>Ph,deserialize:()=>EC,from:()=>DB,getSignPayload:()=>LB,hash:()=>AC,serialize:()=>IC,serializedType:()=>xC,toRpc:()=>jB,type:()=>SS,validate:()=>UB});var xC="0x02",SS="eip1559";function Ph(s){let{chainId:e,maxPriorityFeePerGas:t,maxFeePerGas:n,to:r}=s;if(e<=0)throw new Kp({chainId:e});if(r&&Qt(r,{strict:!1}),n&&BigInt(n)>2n**256n-1n)throw new Fp({feeCap:n});if(t&&n&&t>n)throw new Wp({maxFeePerGas:n,maxPriorityFeePerGas:t})}function EC(s){let e=k6(rt(s,1)),[t,n,r,i,a,o,c,u,l,h,m,y]=e;if(!(e.length===9||e.length===12))throw new Gp({attributes:{chainId:t,nonce:n,maxPriorityFeePerGas:r,maxFeePerGas:i,gas:a,to:o,value:c,data:u,accessList:l,...e.length>9?{yParity:h,r:m,s:y}:{}},serialized:s,type:SS});let g={chainId:Number(t),type:SS};Zt(o)&&o!=="0x"&&(g.to=o),Zt(a)&&a!=="0x"&&(g.gas=BigInt(a)),Zt(u)&&u!=="0x"&&(g.data=u),Zt(n)&&(g.nonce=n==="0x"?0n:BigInt(n)),Zt(c)&&c!=="0x"&&(g.value=BigInt(c)),Zt(i)&&i!=="0x"&&(g.maxFeePerGas=BigInt(i)),Zt(r)&&r!=="0x"&&(g.maxPriorityFeePerGas=BigInt(r)),l.length!==0&&l!=="0x"&&(g.accessList=A6(l));let w=m&&y&&h?dS([h,m,y]):void 0;return w&&(g={...g,...w}),Ph(g),g}function DB(s,e={}){let{signature:t}=e,n=typeof s=="string"?EC(s):s;return Ph(n),{...n,...t?Nh(t):{},type:"eip1559"}}function LB(s){return AC(s,{presign:!0})}function AC(s,e={}){let{presign:t}=e;return dt(IC({...s,...t?{r:void 0,s:void 0,yParity:void 0,v:void 0}:{}}))}function IC(s,e={}){let{chainId:t,gas:n,nonce:r,to:i,value:a,maxFeePerGas:o,maxPriorityFeePerGas:c,accessList:u,data:l,input:h}=s;Ph(s);let m=I6(u),y=jp(e.signature||s),g=[le(t),r?le(r):"0x",c?le(c):"0x",o?le(o):"0x",n?le(n):"0x",i??"0x",a?le(a):"0x",l??h??"0x",m,...y?pS(y):[]];return Fe(xC,T6(g))}function jB(s){let e=jp(s);return {...s,chainId:le(s.chainId),data:s.data??s.input,type:"0x2",...typeof s.gas=="bigint"?{gas:le(s.gas)}:{},...typeof s.nonce=="bigint"?{nonce:le(s.nonce)}:{},...typeof s.value=="bigint"?{value:le(s.value)}:{},...typeof s.maxFeePerGas=="bigint"?{maxFeePerGas:le(s.maxFeePerGas)}:{},...typeof s.maxPriorityFeePerGas=="bigint"?{maxPriorityFeePerGas:le(s.maxPriorityFeePerGas)}:{},...e?mS(e):{}}}function UB(s){try{return Ph(s),!0}catch{return !1}}var kc={};be(kc,{fromRpc:()=>HB,fromRpcStatus:()=>CC,fromRpcType:()=>kC,toRpc:()=>_B,toRpcStatus:()=>NC,toRpcType:()=>PC});var CC={"0x0":"reverted","0x1":"success"},NC={reverted:"0x0",success:"0x1"},kC={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"},PC={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function HB(s){return s?{...s,blobGasPrice:s.blobGasPrice?BigInt(s.blobGasPrice):void 0,blobGasUsed:s.blobGasUsed?BigInt(s.blobGasUsed):void 0,blockNumber:BigInt(s.blockNumber??0n),cumulativeGasUsed:BigInt(s.cumulativeGasUsed??0n),effectiveGasPrice:BigInt(s.effectiveGasPrice??0n),gasUsed:BigInt(s.gasUsed??0n),logs:s.logs.map(e=>lC(e,{pending:!1})),status:CC[s.status],transactionIndex:Number(s.transactionIndex??0),type:kC[s.type]||s.type}:null}function _B(s){return {blobGasPrice:s.blobGasPrice?le(s.blobGasPrice):void 0,blobGasUsed:s.blobGasUsed?le(s.blobGasUsed):void 0,blockHash:s.blockHash,blockNumber:le(s.blockNumber),contractAddress:s.contractAddress,cumulativeGasUsed:le(s.cumulativeGasUsed),effectiveGasPrice:le(s.effectiveGasPrice),from:s.from,gasUsed:le(s.gasUsed),logs:s.logs.map(hC),logsBloom:s.logsBloom,root:s.root,status:NC[s.status],to:s.to,transactionHash:s.transactionHash,transactionIndex:le(s.transactionIndex),type:PC[s.type]??s.type}}var Th={};be(Th,{BytesSizeMismatchError:()=>Jp,InvalidDomainError:()=>zp,InvalidPrimaryTypeError:()=>Yp,InvalidStructTypeError:()=>Zp,assert:()=>vS,domainSeparator:()=>MB,encode:()=>TC,encodeData:()=>IS,encodeField:()=>CS,encodeType:()=>BC,extractEip712DomainTypes:()=>Qp,findTypeDependencies:()=>NS,getSignPayload:()=>xS,hashDomain:()=>ES,hashStruct:()=>AS,hashType:()=>OC,serialize:()=>$B,validate:()=>qB});function vS(s){let{domain:e,message:t,primaryType:n,types:r}=s,i=(a,o)=>{for(let c of a){let{name:u,type:l}=c,h=o[u],m=l.match(xc);if(m&&(typeof h=="number"||typeof h=="bigint")){let[,w,S]=m;le(h,{signed:w==="int",size:Number.parseInt(S??"",10)/8});}if(l==="address"&&typeof h=="string"&&!ua(h))throw new ca({address:h,cause:new bc});let y=l.match(xp);if(y){let[,w]=y;if(w&&Oe(h)!==Number.parseInt(w,10))throw new Jp({expectedSize:Number.parseInt(w,10),givenSize:Oe(h)})}let g=r[l];g&&(FB(l),i(g,h));}};if(r.EIP712Domain&&e){if(typeof e!="object")throw new zp({domain:e});i(r.EIP712Domain,e);}if(n!=="EIP712Domain")if(r[n])i(r[n],t);else throw new Yp({primaryType:n,types:r})}function MB(s){return ES({domain:s})}function TC(s){let{domain:e={},message:t,primaryType:n}=s,r={EIP712Domain:Qp(e),...s.types};vS({domain:e,message:t,primaryType:n,types:r});let i=["0x19","0x01"];return e&&i.push(ES({domain:e,types:r})),n!=="EIP712Domain"&&i.push(AS({data:t,primaryType:n,types:r})),Fe(...i)}function BC(s){let{primaryType:e,types:t}=s,n="",r=NS({primaryType:e,types:t});r.delete(e);let i=[e,...Array.from(r).sort()];for(let a of i)n+=`${a}(${(t[a]??[]).map(({name:o,type:c})=>`${c} ${o}`).join(",")})`;return n}function Qp(s){return [typeof s?.name=="string"&&{name:"name",type:"string"},s?.version&&{name:"version",type:"string"},(typeof s?.chainId=="number"||typeof s?.chainId=="bigint")&&{name:"chainId",type:"uint256"},s?.verifyingContract&&{name:"verifyingContract",type:"address"},s?.salt&&{name:"salt",type:"bytes32"}].filter(Boolean)}function xS(s){return dt(TC(s))}function ES(s){let{domain:e,types:t}=s;return AS({data:e,primaryType:"EIP712Domain",types:{...t,EIP712Domain:t?.EIP712Domain||Qp(e)}})}function AS(s){let{data:e,primaryType:t,types:n}=s,r=IS({data:e,primaryType:t,types:n});return dt(r)}function $B(s){let{domain:e,message:t,primaryType:n,types:r}=s,i=(c,u)=>{let l={...u};for(let h of c){let{name:m,type:y}=h;y==="address"&&(l[m]=l[m].toLowerCase());}return l},a=(()=>{if(!e)return {};let c=r.EIP712Domain??Qp(e);return i(c,e)})(),o=(()=>{if(n!=="EIP712Domain")return r[n]?i(r[n],t):{}})();return Ds({domain:a,message:o,primaryType:n,types:r},(c,u)=>typeof u=="bigint"?u.toString():u)}function qB(s){try{return vS(s),!0}catch{return !1}}var Jp=class extends K{constructor({expectedSize:e,givenSize:t}){super(`Expected bytes${e}, got bytes${t}.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TypedData.BytesSizeMismatchError"});}},zp=class extends K{constructor({domain:e}){super(`Invalid domain "${Ds(e)}".`,{metaMessages:["Must be a valid EIP-712 domain."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TypedData.InvalidDomainError"});}},Yp=class extends K{constructor({primaryType:e,types:t}){super(`Invalid primary type \`${e}\` must be one of \`${JSON.stringify(Object.keys(t))}\`.`,{metaMessages:["Check that the primary type is a key in `types`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TypedData.InvalidPrimaryTypeError"});}},Zp=class extends K{constructor({type:e}){super(`Struct type "${e}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TypedData.InvalidStructTypeError"});}};function IS(s){let{data:e,primaryType:t,types:n}=s,r=[{type:"bytes32"}],i=[OC({primaryType:t,types:n})];for(let a of n[t]??[]){let[o,c]=CS({types:n,name:a.name,type:a.type,value:e[a.name]});r.push(o),i.push(c);}return On(r,i)}function OC(s){let{primaryType:e,types:t}=s,n=cs(BC({primaryType:e,types:t}));return dt(n)}function CS(s){let{types:e,name:t,type:n,value:r}=s;if(e[n]!==void 0)return [{type:"bytes32"},dt(IS({data:r,primaryType:n,types:e}))];if(n==="bytes")return r=`0x${(r.length%2?"0":"")+r.slice(2)}`,[{type:"bytes32"},dt(r,{as:"Hex"})];if(n==="string")return [{type:"bytes32"},dt(Tn(r),{as:"Hex"})];if(n.lastIndexOf("]")===n.length-1){let i=n.slice(0,n.lastIndexOf("[")),a=r.map(o=>CS({name:t,type:i,types:e,value:o}));return [{type:"bytes32"},dt(On(a.map(([o])=>o),a.map(([,o])=>o)))]}return [{type:n},r]}function NS(s,e=new Set){let{primaryType:t,types:n}=s,i=t.match(/^\w*/u)?.[0];if(e.has(i)||n[i]===void 0)return e;e.add(i);for(let a of n[i])NS({primaryType:a.type,types:n},e);return e}function FB(s){if(s==="address"||s==="bool"||s==="string"||s.startsWith("bytes")||s.startsWith("uint")||s.startsWith("int"))throw new Zp({type:s})}var Tr={};be(Tr,{CredentialCreationFailedError:()=>Pr,CredentialRequestFailedError:()=>Bh,createChallenge:()=>DC,createCredential:()=>GB,getAuthenticatorData:()=>LC,getClientDataJSON:()=>jC,getCredentialCreationOptions:()=>UC,getCredentialRequestOptions:()=>HC,getSignPayload:()=>WB,sign:()=>JB,verify:()=>zB});function RC(s){let e=s[4]===0?5:4,t=e+32,n=s[t+2]===0?t+3:t+2,r=BigInt(Ee(s.slice(e,t))),i=BigInt(Ee(s.slice(n)));return {r,s:i>wS.CURVE.n/2n?wS.CURVE.n-i:i}}async function VC(s){try{let e=s.getPublicKey();if(!e)throw new Pr;let t=new Uint8Array(e),n=await crypto.subtle.importKey("spki",new Uint8Array(t),{name:"ECDSA",namedCurve:"P-256",hash:"SHA-256"},!0,["verify"]),r=new Uint8Array(await crypto.subtle.exportKey("raw",n));return Bn(r)}catch(e){if(e.message!=="Permission denied to access object")throw e;let t=new Uint8Array(s.attestationObject),n=32,r=88,i=c=>{let u=new Uint8Array([c,r,n]);for(let l=0;l<t.length-u.length;l++)if(u.every((h,m)=>t[l+m]===h))return l+u.length;throw new Pr},a=i(33),o=i(34);return Bn(new Uint8Array([4,...t.slice(a,a+n),...t.slice(o,o+n)]))}}var DC=Uint8Array.from([105,171,180,181,160,222,75,198,42,42,32,31,141,37,186,233]);async function GB(s){let{createFn:e=window.navigator.credentials.create.bind(window.navigator.credentials),...t}=s,n=UC(t);try{let r=await e(n);if(!r)throw new Pr;let i=r.response,a=await VC(i);return {id:r.id,publicKey:a,raw:r}}catch(r){throw new Pr({cause:r})}}function LC(s={}){let{flag:e=5,rpId:t=window.location.hostname,signCount:n=0}=s,r=wh(cs(t)),i=le(e,{size:1}),a=le(n,{size:4});return Fe(r,i,a)}function jC(s){let{challenge:e,crossOrigin:t=!1,extraClientData:n,origin:r=window.location.origin}=s;return JSON.stringify({type:"webauthn.get",challenge:nC(e,{url:!0,pad:!1}),origin:r,crossOrigin:t,...n})}function UC(s){let{attestation:e="none",authenticatorSelection:t={residentKey:"preferred",requireResidentKey:!1,userVerification:"required"},challenge:n=DC,excludeCredentialIds:r,extensions:i,name:a,rp:o={id:window.location.hostname,name:window.document.title},user:c}=s,u=c?.name??a;return {publicKey:{attestation:e,authenticatorSelection:t,challenge:typeof n=="string"?Ye(n):n,...r?{excludeCredentials:r?.map(l=>({id:kh(l),type:"public-key"}))}:{},pubKeyCredParams:[{type:"public-key",alg:-7}],...i&&{extensions:i},rp:o,user:{id:c?.id??dt(Tn(u),{as:"Bytes"}),name:u,displayName:c?.displayName??u}}}}function HC(s){let{credentialId:e,challenge:t,extensions:n,rpId:r=window.location.hostname,userVerification:i="required"}=s;return {publicKey:{...e?{allowCredentials:Array.isArray(e)?e.map(a=>({id:kh(a),type:"public-key"})):[{id:kh(e),type:"public-key"}]}:{},challenge:Ye(t),...n&&{extensions:n},rpId:r,userVerification:i}}}function WB(s){let{challenge:e,crossOrigin:t,extraClientData:n,flag:r,origin:i,rpId:a,signCount:o,userVerification:c="required"}=s,u=LC({flag:r,rpId:a,signCount:o}),l=jC({challenge:e,crossOrigin:t,extraClientData:n,origin:i}),h=wh(cs(l)),m=l.indexOf('"challenge"'),y=l.indexOf('"type"'),g={authenticatorData:u,clientDataJSON:l,challengeIndex:m,typeIndex:y,userVerificationRequired:c==="required"},w=Fe(u,h);return {metadata:g,payload:w}}async function JB(s){let{getFn:e=window.navigator.credentials.get.bind(window.navigator.credentials),...t}=s,n=HC(t);try{let r=await e(n);if(!r)throw new Bh;let i=r.response,a=String.fromCharCode(...new Uint8Array(i.clientDataJSON)),o=a.indexOf('"challenge"'),c=a.indexOf('"type"'),u=RC(new Uint8Array(i.signature));return {metadata:{authenticatorData:Ee(new Uint8Array(i.authenticatorData)),clientDataJSON:a,challengeIndex:o,typeIndex:c,userVerificationRequired:n.publicKey.userVerification==="required"},signature:u,raw:r}}catch(r){throw new Bh({cause:r})}}function zB(s){let{challenge:e,hash:t=!0,metadata:n,publicKey:r,signature:i}=s,{authenticatorData:a,challengeIndex:o,clientDataJSON:c,typeIndex:u,userVerificationRequired:l}=n,h=Ye(a);if(h.length<37)return !1;let m=h[32];if((m&1)!==1||l&&(m&4)!==4||(m&8)!==8&&(m&16)===16)return !1;if(u!==void 0){let N='"type":"webauthn.get"';if(N!==c.slice(Number(u),N.length+1))return !1}let y=o!==void 0?c.slice(Number(o)).match(/^"challenge":"(.*?)"/):c.match(/"challenge":"(.*?)"/);if(!y)return !1;let[g,w]=y;if(Ee(kh(w))!==e)return !1;let S=wh(Tn(c),{as:"Bytes"}),C=kb(h,S);return bS({hash:t,payload:C,publicKey:r,signature:i})}var Pr=class extends K{constructor({cause:e}={}){super("Failed to create credential.",{cause:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"WebAuthnP256.CredentialCreationFailedError"});}},Bh=class extends K{constructor({cause:e}={}){super("Failed to request credential.",{cause:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"WebAuthnP256.CredentialRequestFailedError"});}};var Vc={};be(Vc,{from:()=>MO});var Pe={};be(Pe,{configFromJson:()=>jO,configToJson:()=>LO,evaluateConfigurationSafety:()=>HO,findSignerLeaf:()=>Lh,flatLeavesToTopology:()=>cv,getSigners:()=>DO,getWeight:()=>jh,hasInvalidValues:()=>Oc,hashConfiguration:()=>qt,isAnyAddressSubdigestLeaf:()=>Hs,isConfig:()=>Rc,isLeaf:()=>n5,isNestedLeaf:()=>es,isNode:()=>mt,isNodeLeaf:()=>Ct,isSapientSignerLeaf:()=>$t,isSignerLeaf:()=>Mt,isSubdigestLeaf:()=>Us,isTopology:()=>Bc,maximumDepth:()=>Uh,mergeTopology:()=>mg,normalizeSignerSignature:()=>UO,replaceAddress:()=>dg,topologyToFlatLeaves:()=>lg});var Rt={};be(Rt,{FLAG_ADDRESS:()=>XS,FLAG_BRANCH:()=>tv,FLAG_NESTED:()=>nv,FLAG_NODE:()=>ng,FLAG_SIGNATURE_ANY_ADDRESS_SUBDIGEST:()=>iv,FLAG_SIGNATURE_ERC1271:()=>ev,FLAG_SIGNATURE_ETH_SIGN:()=>rv,FLAG_SIGNATURE_HASH:()=>QS,FLAG_SIGNATURE_SAPIENT:()=>rg,FLAG_SIGNATURE_SAPIENT_COMPACT:()=>av,FLAG_SUBDIGEST:()=>sv,decodeSignature:()=>QC,encodeChainedSignature:()=>XC,encodeSignature:()=>e5,encodeTopology:()=>Rh,fillLeaves:()=>eg,isRawConfig:()=>cg,isRawLeaf:()=>ZC,isRawNestedLeaf:()=>Dh,isRawNode:()=>ig,isRawSignature:()=>YC,isRawSignerLeaf:()=>Vh,isRawTopology:()=>ag,isSignatureOfSapientSignerLeaf:()=>PO,isSignedSapientSignerLeaf:()=>ov,isSignedSignerLeaf:()=>ug,parseBranch:()=>og,rawSignatureFromJson:()=>OO,rawSignatureToJson:()=>TO,recover:()=>YS});var _e={};be(_e,{DEPLOY:()=>_C,DefaultGuestAddress:()=>QB,EXECUTE:()=>sO,EXECUTE_USER_OP:()=>TS,GET_IMPLEMENTATION:()=>XB,GET_LIMIT_USAGE:()=>oO,IMAGE_HASH:()=>eO,INCREMENT_USAGE_LIMIT:()=>aO,IS_VALID_SIGNATURE:()=>Oh,PlaceholderAddress:()=>ZB,READ_ENTRYPOINT:()=>iO,READ_NONCE:()=>tO,READ_NONCE_4337:()=>rO,RECOVER_SAPIENT_SIGNATURE:()=>kS,RECOVER_SAPIENT_SIGNATURE_COMPACT:()=>PS,UPDATE_IMAGE_HASH:()=>nO,ZeroAddress:()=>YB});var YB="0x0000000000000000000000000000000000000000",ZB="0xffff0000ffff0000ffff0000ffff0000ffff0000",QB="0x0000000000006Ac72ed1d192fa28f0058D3F8806",Oh=at.from(["function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4 magicValue)"])[0],_C=at.from(["function deploy(address _mainModule, bytes32 _salt) public payable returns (address _contract)"])[0],XB=at.from(["function getImplementation() external view returns (address)"])[0],eO=at.from(["function imageHash() external view returns (bytes32)"])[0],tO=at.from(["function readNonce(uint256 _space) public view returns (uint256)"])[0],sO=at.from(["function execute(bytes calldata _payload, bytes calldata _signature) external"])[0],nO=at.from(["function updateImageHash(bytes32 _imageHash) external"])[0],kS=at.from(["function recoverSapientSignature((uint8 kind,bool noChainId,(address to,uint256 value,bytes data,uint256 gasLimit,bool delegateCall,bool onlyFallback,uint256 behaviorOnError)[] calls,uint256 space,uint256 nonce,bytes message,bytes32 imageHash,bytes32 digest,address[] parentWallets) calldata _payload, bytes calldata _signature) external view returns (bytes32)"])[0],PS=at.from(["function recoverSapientSignatureCompact(bytes32 _digest, bytes calldata _signature) external view returns (bytes32)"])[0],TS=at.from(["function executeUserOp(bytes calldata _userOp) external"])[0],rO=at.from(["function getNonce(address _account, uint192 _key) public view returns (uint256)"])[0],iO=at.from(["function entrypoint() public view returns (address)"])[0],aO=at.from([{type:"function",name:"incrementUsageLimit",inputs:[{name:"limits",type:"tuple[]",internalType:"struct UsageLimit[]",components:[{name:"usageHash",type:"bytes32",internalType:"bytes32"},{name:"usageAmount",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"nonpayable"}])[0],oO=at.from(["function getLimitUsage(address wallet, bytes32 usageHash) public view returns (uint256)"])[0];var jn={};be(jn,{InvalidWrappedSignatureError:()=>Xp,assert:()=>OS,from:()=>lO,magicBytes:()=>BS,universalSignatureValidatorAbi:()=>uO,universalSignatureValidatorBytecode:()=>cO,unwrap:()=>MC,validate:()=>fO,wrap:()=>hO});var BS="0x6492649264926492649264926492649264926492649264926492649264926492",cO="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",uO=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}];function OS(s){if(rt(s,-32)!==BS)throw new Xp(s)}function lO(s){return typeof s=="string"?MC(s):s}function MC(s){OS(s);let[e,t,n]=Ac(Pp("address, bytes, bytes"),s);return {data:t,signature:n,to:e}}function hO(s){let{data:e,signature:t,to:n}=s;return Fe(On(Pp("address, bytes, bytes"),[n,e,t]),BS)}function fO(s){try{return OS(s),!0}catch{return !1}}var Xp=class extends K{constructor(e){super(`Value \`${e}\` is an invalid ERC-6492 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"});}};function RS(s,{to:e,data:t}){let n=E.concat(ot.encode([{type:"address"},{type:"bytes"},{type:"bytes"}],[e,E.from(t),E.from(s)]),jn.magicBytes);switch(typeof s){case"object":return E.toBytes(n);case"string":return n}}function $C(s){switch(typeof s){case"object":if(f.toHex(s.subarray(-jn.magicBytes.slice(2).length/2))===jn.magicBytes){let[e,t,n]=ot.decode([{type:"address"},{type:"bytes"},{type:"bytes"}],s.subarray(0,-jn.magicBytes.slice(2).length/2));return {signature:E.toBytes(n),erc6492:{to:e,data:E.toBytes(t)}}}else return {signature:s};case"string":if(s.endsWith(jn.magicBytes.slice(2)))try{let[e,t,n]=ot.decode([{type:"address"},{type:"bytes"},{type:"bytes"}],s.slice(0,-jn.magicBytes.slice(2).length));return {signature:n,erc6492:{to:e,data:t}}}catch{return {signature:s}}else return {signature:s}}}var ce={};be(ce,{BEHAVIOR_ABORT_ON_ERROR:()=>$S,BEHAVIOR_IGNORE_ERROR:()=>_S,BEHAVIOR_REVERT_ON_ERROR:()=>MS,KIND_CONFIG_UPDATE:()=>US,KIND_DIGEST:()=>HS,KIND_MESSAGE:()=>jS,KIND_TRANSACTIONS:()=>LS,decode:()=>CO,decodeBehaviorOnError:()=>zC,encode:()=>KC,encode4337Nonce:()=>GC,encodeBehaviorOnError:()=>Tc,encodeSapient:()=>EO,fromAbiFormat:()=>kO,fromCall:()=>yO,fromConfigUpdate:()=>qS,fromDigest:()=>gO,fromMessage:()=>pO,hash:()=>Pc,hashCall:()=>IO,isCalls:()=>wO,isCalls4337_07:()=>vO,isConfigUpdate:()=>SO,isDigest:()=>FC,isMessage:()=>bO,isParented:()=>xO,isRecovery:()=>FS,isSessionImplicitAuthorize:()=>GS,to4337Message:()=>JC,to4337UserOperation:()=>WC,toAbiFormat:()=>JS,toRecovery:()=>KS,toTyped:()=>WS});var ya={};be(ya,{createJSONReplacer:()=>VS,createJSONReviver:()=>DS,fromJSON:()=>mO,minBytesFor:()=>ws,packRSY:()=>Un,toJSON:()=>dO,unpackRSY:()=>ga});function ws(s){return Math.ceil(s.toString(16).length/2)}function Un({r:s,s:e,yParity:t}){let n=f.padLeft(f.fromNumber(s),32),r=f.padLeft(f.fromNumber(e),32);return t%2===1&&(r[0]|=128),f.concat(n,r)}function ga(s){let e=f.toBigInt(s.slice(0,32)),t=s.slice(32,64),n=t[0]&128?1:0,r=new Uint8Array(t);r[0]=r[0]&127;let i=f.toBigInt(r);return {r:e,s:i,yParity:n}}function VS(s){return (e,t)=>typeof t=="bigint"?{__bigint:"0x"+t.toString(16)}:t instanceof Uint8Array?{__uint8array:Array.from(t)}:s?s(e,t):t}function DS(s){return (e,t)=>{if(t&&typeof t=="object"&&"__bigint"in t&&Object.keys(t).length===1){let n=t.__bigint;if(typeof n=="string"&&n.startsWith("0x"))return BigInt(n)}if(t&&typeof t=="object"&&"__uint8array"in t&&Object.keys(t).length===1){let n=t.__uint8array;if(Array.isArray(n))return new Uint8Array(n)}return s?s(e,t):t}}function dO(s,e,t){let n=e instanceof Function?VS(e):VS();return JSON.stringify(s,n,t)}function mO(s,e){let t=e?DS(e):DS();return JSON.parse(s,t)}var LS=0,jS=1,US=2,HS=3,_S=0,MS=1,$S=2;function pO(s){return {type:"message",message:s}}function qS(s){return {type:"config-update",imageHash:s}}function gO(s){return {type:"digest",digest:s}}function yO(s,e,t){return {type:"call",nonce:s,space:e,calls:t}}function wO(s){return s.type==="call"}function bO(s){return s.type==="message"}function SO(s){return s.type==="config-update"}function FC(s){return s.type==="digest"}function FS(s){return GS(s)?!1:s.recovery===!0}function vO(s){return s.type==="call_4337_07"}function xO(s){return "parentWallets"in s}function KS(s){return FS(s)?s:{...s,recovery:!0}}function GS(s){return s.type==="session-implicit-authorize"}function KC(s,e){let t=s.calls.length,n=ws(s.nonce);if(n>15)throw new Error("Nonce is too large");let r=0;s.space===0n&&(r|=1),r|=n<<1,t===1&&(r|=16);let i=0;if(t!==1)if(t<256)i=1;else if(t<65536)i=2,r|=32;else throw new Error("Too many calls");let a=f.fromNumber(r,{size:1});if(s.space!==0n){let o=f.padLeft(f.fromNumber(s.space),20);a=f.concat(a,o);}if(n>0){let o=f.padLeft(f.fromNumber(s.nonce),n);a=f.concat(a,o);}t!==1&&(i===1?a=f.concat(a,f.fromNumber(t,{size:1})):a=f.concat(a,f.fromNumber(t,{size:2})));for(let o of s.calls){let c=0;if(e&&B.isEqual(o.to,e)&&(c|=1),o.value!==0n&&(c|=2),o.data&&o.data.length>0&&(c|=4),o.gasLimit!==0n&&(c|=8),o.delegateCall&&(c|=16),o.onlyFallback&&(c|=32),c|=Tc(o.behaviorOnError)<<6,a=f.concat(a,f.fromNumber(c,{size:1})),!(c&1)){let u=f.fromHex(o.to);if(u.length!==20)throw new Error(`Invalid 'to' address: ${o.to}`);a=f.concat(a,u);}if(c&2){let u=f.padLeft(f.fromNumber(o.value),32);a=f.concat(a,u);}if(c&4){let u=f.fromHex(o.data).length;if(u>16777215)throw new Error("Data too large");let l=f.fromNumber(u,{size:3});a=f.concat(a,l,f.fromHex(o.data));}if(c&8){let u=f.padLeft(f.fromNumber(o.gasLimit),32);a=f.concat(a,u);}}return a}function EO(s,e){let t={kind:0,noChainId:!s,calls:[],space:0n,nonce:0n,message:"0x",imageHash:"0x0000000000000000000000000000000000000000000000000000000000000000",digest:"0x0000000000000000000000000000000000000000000000000000000000000000",parentWallets:e.parentWallets??[]};switch(e.type){case"call":t.kind=0,t.calls=e.calls.map(n=>({...n,data:n.data,behaviorOnError:BigInt(Tc(n.behaviorOnError))})),t.space=e.space,t.nonce=e.nonce;break;case"message":t.kind=1,t.message=e.message;break;case"config-update":t.kind=2,t.imageHash=e.imageHash;break;case"digest":t.kind=3,t.digest=e.digest;break}return t}function Pc(s,e,t){if(FC(t))return f.fromHex(t.digest);if(GS(t))return It.hash(t.attestation);let n=WS(s,e,t);return f.fromHex(xS(n))}function AO(s,e,t){return FS(s)?{name:"Sequence Wallet - Recovery Mode",version:"1",chainId:Number(t),verifyingContract:e}:{name:"Sequence Wallet",version:"3",chainId:Number(t),verifyingContract:e}}function GC(s,e){if(s>6277101735386680763835789423207666416102355444464034512895n)throw new RangeError("key exceeds 192 bits");if(e>18446744073709551615n)throw new RangeError("seq exceeds 64 bits");return s<<64n|e}function WS(s,e,t){let n=AO(t,s,e);switch(t.type){case"call":{let r={Calls:[{name:"calls",type:"Call[]"},{name:"space",type:"uint256"},{name:"nonce",type:"uint256"},{name:"wallets",type:"address[]"}],Call:[{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"},{name:"gasLimit",type:"uint256"},{name:"delegateCall",type:"bool"},{name:"onlyFallback",type:"bool"},{name:"behaviorOnError",type:"uint256"}]},i={calls:t.calls.map(a=>({to:a.to,value:a.value.toString(),data:a.data,gasLimit:a.gasLimit.toString(),delegateCall:a.delegateCall,onlyFallback:a.onlyFallback,behaviorOnError:BigInt(Tc(a.behaviorOnError)).toString()})),space:t.space.toString(),nonce:t.nonce.toString(),wallets:t.parentWallets??[]};return {domain:n,types:r,primaryType:"Calls",message:i}}case"message":{let r={Message:[{name:"message",type:"bytes"},{name:"wallets",type:"address[]"}]},i={message:t.message,wallets:t.parentWallets??[]};return {domain:n,types:r,primaryType:"Message",message:i}}case"config-update":{let r={ConfigUpdate:[{name:"imageHash",type:"bytes32"},{name:"wallets",type:"address[]"}]},i={imageHash:t.imageHash,wallets:t.parentWallets??[]};return {domain:n,types:r,primaryType:"ConfigUpdate",message:i}}case"digest":throw new Error("Digest does not support typed data - Use message instead");case"session-implicit-authorize":throw new Error("Payload does not support typed data");case"call_4337_07":{let r={type:"message",message:JC(t,s,e)};return WS(s,e,r)}}}function WC(s,e,t){let n={type:"call",space:0n,nonce:0n,calls:s.calls},r=E.fromBytes(KC(n));return {sender:e,nonce:GC(s.space,s.nonce),callData:te.encodeData(TS,[r]),callGasLimit:s.callGasLimit,maxFeePerGas:s.maxFeePerGas,maxPriorityFeePerGas:s.maxPriorityFeePerGas,preVerificationGas:s.preVerificationGas,verificationGasLimit:s.verificationGasLimit,factory:s.factory,factoryData:s.factoryData,paymaster:s.paymaster,paymasterData:s.paymasterData,paymasterPostOpGasLimit:s.paymasterPostOpGasLimit,paymasterVerificationGasLimit:s.paymasterVerificationGasLimit,signature:t}}function JC(s,e,t){let n=WC(s,e),r=E.concat(E.padLeft(E.fromNumber(n.verificationGasLimit),16),E.padLeft(E.fromNumber(n.callGasLimit),16)),i=E.concat(E.padLeft(E.fromNumber(n.maxPriorityFeePerGas),16),E.padLeft(E.fromNumber(n.maxFeePerGas),16)),a=oe.keccak256(n.factory&&n.factoryData?E.concat(n.factory,n.factoryData):"0x"),o=oe.keccak256(n.paymaster?E.concat(n.paymaster,E.padLeft(E.fromNumber(n.paymasterVerificationGasLimit||0),16),E.padLeft(E.fromNumber(n.paymasterPostOpGasLimit||0),16),n.paymasterData||"0x"):"0x"),c=ot.encode([{type:"address"},{type:"uint256"},{type:"bytes32"},{type:"bytes32"},{type:"bytes32"},{type:"uint256"},{type:"bytes32"},{type:"bytes32"}],[n.sender,n.nonce,a,oe.keccak256(n.callData),r,n.preVerificationGas,i,o]);return ot.encode([{type:"bytes32"},{type:"address"},{type:"uint256"}],[oe.keccak256(c),s.entrypoint,BigInt(t)])}function Tc(s){switch(s){case"ignore":return _S;case"revert":return MS;case"abort":return $S}}function IO(s){let e=oe.keccak256(f.fromString("Call(address to,uint256 value,bytes data,uint256 gasLimit,bool delegateCall,bool onlyFallback,uint256 behaviorOnError)"));return oe.keccak256(ot.encode([{type:"bytes32"},{type:"address"},{type:"uint256"},{type:"bytes32"},{type:"uint256"},{type:"bool"},{type:"bool"},{type:"uint256"}],[E.from(e),E.from(s.to),s.value,E.from(oe.keccak256(s.data)),s.gasLimit,s.delegateCall,s.onlyFallback,BigInt(Tc(s.behaviorOnError))]))}function CO(s,e){let t=0;if(s.length<1)throw new Error("Invalid packed data: missing globalFlag");let n=f.toNumber(s.slice(t,t+1));t+=1;let r=(n&1)===1,i=0n;if(!r){if(t+20>s.length)throw new Error("Invalid packed data: not enough bytes for space");i=f.toBigInt(s.slice(t,t+20)),t+=20;}let a=n>>1&7,o=0n;if(a>0){if(t+a>s.length)throw new Error("Invalid packed data: not enough bytes for nonce");o=f.toBigInt(s.slice(t,t+a)),t+=a;}let c=1;if(!((n&16)===16)){let m=(n&32)===32?2:1;if(t+m>s.length)throw new Error("Invalid packed data: not enough bytes for callsCount");c=f.toNumber(s.slice(t,t+m)),t+=m;}let l=[];for(let h=0;h<c;h++){if(t+1>s.length)throw new Error("Invalid packed data: missing call flags");let m=f.toNumber(s.slice(t,t+1));t+=1;let y;if((m&1)===1){if(!e)throw new Error('Missing "self" address for toSelf call');y=e;}else {if(t+20>s.length)throw new Error("Invalid packed data: not enough bytes for address");y=f.toHex(s.slice(t,t+20)),t+=20;}let g=0n;if((m&2)===2){if(t+32>s.length)throw new Error("Invalid packed data: not enough bytes for value");g=f.toBigInt(s.slice(t,t+32)),t+=32;}let w=f.fromHex("0x");if((m&4)===4){if(t+3>s.length)throw new Error("Invalid packed data: not enough bytes for data length");let I=f.toNumber(s.slice(t,t+3));if(t+=3,t+I>s.length)throw new Error("Invalid packed data: not enough bytes for call data");w=s.slice(t,t+I),t+=I;}let S=0n;if((m&8)===8){if(t+32>s.length)throw new Error("Invalid packed data: not enough bytes for gasLimit");S=f.toBigInt(s.slice(t,t+32)),t+=32;}let C=(m&16)===16,N=(m&32)===32,x=(m&192)>>6,v=zC(x);l.push({to:y,value:g,data:f.toHex(w),gasLimit:S,delegateCall:C,onlyFallback:N,behaviorOnError:v});}return {type:"call",space:i,nonce:o,calls:l}}function zC(s){switch(s){case 0:return "ignore";case 1:return "revert";case 2:return "abort";default:throw new Error(`Invalid behaviorOnError value: ${s}`)}}function NO(s){switch(s){case _S:return "ignore";case MS:return "revert";case $S:return "abort";default:throw new Error(`Unknown behavior: ${s}`)}}function kO(s){if(s.kind===LS)return {type:"call",nonce:s.nonce,space:s.space,calls:s.calls.map(e=>({to:B.from(e.to),value:e.value,data:e.data,gasLimit:e.gasLimit,delegateCall:e.delegateCall,onlyFallback:e.onlyFallback,behaviorOnError:NO(Number(e.behaviorOnError))})),parentWallets:s.parentWallets.map(e=>B.from(e))};if(s.kind===jS)return {type:"message",message:s.message,parentWallets:s.parentWallets.map(e=>B.from(e))};if(s.kind===US)return {type:"config-update",imageHash:s.imageHash,parentWallets:s.parentWallets.map(e=>B.from(e))};if(s.kind===HS)return {type:"digest",digest:s.digest,parentWallets:s.parentWallets.map(e=>B.from(e))};throw new Error("Not implemented")}function JS(s){if(s.type==="call")return {kind:LS,noChainId:!1,calls:s.calls.map(e=>({to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit,delegateCall:e.delegateCall,onlyFallback:e.onlyFallback,behaviorOnError:BigInt(Tc(e.behaviorOnError))})),space:s.space,nonce:s.nonce,message:"0x",imageHash:"0x0000000000000000000000000000000000000000000000000000000000000000",digest:"0x0000000000000000000000000000000000000000000000000000000000000000",parentWallets:s.parentWallets??[]};if(s.type==="message")return {kind:jS,noChainId:!1,calls:[],space:0n,nonce:0n,message:s.message,imageHash:"0x0000000000000000000000000000000000000000000000000000000000000000",digest:"0x0000000000000000000000000000000000000000000000000000000000000000",parentWallets:s.parentWallets??[]};if(s.type==="config-update")return {kind:US,noChainId:!1,calls:[],space:0n,nonce:0n,message:"0x",imageHash:s.imageHash,digest:"0x0000000000000000000000000000000000000000000000000000000000000000",parentWallets:s.parentWallets??[]};if(s.type==="digest")return {kind:HS,noChainId:!1,calls:[],space:0n,nonce:0n,message:"0x",imageHash:"0x0000000000000000000000000000000000000000000000000000000000000000",digest:s.digest,parentWallets:s.parentWallets??[]};throw new Error("Invalid payload type")}var QS=0,XS=1,ev=2,ng=3,tv=4,sv=5,nv=6,rv=7,iv=8,rg=9,av=10;function PO(s){return "type"in s&&(s.type==="sapient_compact"||s.type==="sapient")&&typeof s=="object"&&"address"in s&&"data"in s}function YC(s){return typeof s=="object"&&s&&typeof s.noChainId=="boolean"&&(s.checkpointerData===void 0||f.validate(s.checkpointerData))&&cg(s.configuration)&&(s.suffix===void 0||Array.isArray(s.suffix)&&s.suffix.every(e=>YC(e)&&e.checkpointerData===void 0))}function cg(s){return s&&typeof s=="object"&&typeof s.threshold=="bigint"&&typeof s.checkpoint=="bigint"&&ag(s.topology)&&(s.checkpointer===void 0||B.validate(s.checkpointer))}function Vh(s){return typeof s=="object"&&"weight"in s&&"signature"in s}function ug(s){return Mt(s)&&"signature"in s}function ov(s){return $t(s)&&"signature"in s}function ig(s){return Array.isArray(s)&&s.length===2&&(ag(s[0])||Bc(s[0]))&&(ag(s[1])||Bc(s[1]))}function ag(s){return ig(s)||ZC(s)}function ZC(s){return typeof s=="object"&&"weight"in s&&!("tree"in s)}function Dh(s){return typeof s=="object"&&"tree"in s&&"weight"in s&&"threshold"in s}function QC(s){let{signature:e,erc6492:t}=$C(s);if(e.length<1)throw new Error("Signature is empty");let n=e[0],r=1,i=(n&2)===2,a,o;if((n&64)===64){if(r+20>e.length)throw new Error("Not enough bytes for checkpointer address");if(a=f.toHex(e.slice(r,r+20)),r+=20,r+3>e.length)throw new Error("Not enough bytes for checkpointer data size");let w=f.toNumber(e.slice(r,r+3));if(r+=3,r+w>e.length)throw new Error("Not enough bytes for checkpointer data");o=e.slice(r,r+w),r+=w;}let c=(n&28)>>2;if(r+c>e.length)throw new Error("Not enough bytes for checkpoint");let u=f.toBigInt(e.slice(r,r+c));r+=c;let l=((n&32)>>5)+1;if(r+l>e.length)throw new Error("Not enough bytes for threshold");let h=f.toBigInt(e.slice(r,r+l));if(r+=l,(n&1)===1){let w=[];for(;r<e.length;){if(r+3>e.length)throw new Error("Not enough bytes for chained subsignature size");let S=f.toNumber(e.subarray(r,r+3));if(r+=3,r+S>e.length)throw new Error("Not enough bytes for chained subsignature");let C=QC(e.subarray(r,r+S));if(r+=S,C.checkpointerData)throw new Error("Chained subsignature has checkpointer data");w.push({...C,checkpointerData:void 0});}if(w.length===0)throw new Error("Chained signature has no subsignatures");return {...w[0],suffix:w.slice(1),erc6492:t}}let{nodes:m,leftover:y}=og(e.slice(r));if(y.length!==0)throw new Error("Leftover bytes in signature");let g=zS(m);return {noChainId:i,checkpointerData:o,configuration:{threshold:h,checkpoint:u,topology:g,checkpointer:a},erc6492:t}}function og(s){let e=[],t=0;for(;t<s.length;){let n=s[t];t++;let r=(n&240)>>4;if(r===QS){let i=n&15;if(i===0){if(t>=s.length)throw new Error("Not enough bytes for dynamic weight");i=s[t],t++;}if(t+64>s.length)throw new Error("Not enough bytes for hash signature (r + yParityAndS)");let a=ga(s.slice(t,t+64));t+=64,e.push({type:"unrecovered-signer",weight:BigInt(i),signature:{type:"hash",...a}});continue}if(r===XS){let i=n&15;if(i===0){if(t>=s.length)throw new Error("Not enough bytes for address weight");i=s[t],t++;}if(t+20>s.length)throw new Error("Not enough bytes for address leaf");let a=f.toHex(s.slice(t,t+20));t+=20,e.push({type:"signer",address:a,weight:BigInt(i)});continue}if(r===ev){let i=n&3;if(i===0){if(t>=s.length)throw new Error("Not enough bytes for ERC1271 weight");i=s[t],t++;}if(t+20>s.length)throw new Error("Not enough bytes for ERC1271 signer address");let a=f.toHex(s.slice(t,t+20));t+=20;let o=(n&12)>>2;if(t+o>s.length)throw new Error("Not enough bytes for ERC1271 sizeSize");let c=f.toNumber(s.slice(t,t+o));if(t+=o,t+c>s.length)throw new Error("Not enough bytes for ERC1271 data");let u=s.slice(t,t+c);t+=c,e.push({type:"unrecovered-signer",weight:BigInt(i),signature:{type:"erc1271",address:a,data:f.toHex(u)}});continue}if(r===ng){if(t+32>s.length)throw new Error("Not enough bytes for node leaf");let i=s.slice(t,t+32);t+=32,e.push(f.toHex(i));continue}if(r===tv){let i=n&15;if(t+i>s.length)throw new Error("Not enough bytes for branch sizeSize");let a=f.toNumber(s.slice(t,t+i));if(t+=i,t+a>s.length)throw new Error("Not enough bytes in sub-branch");let o=s.slice(t,t+a);t+=a;let{nodes:c,leftover:u}=og(o);if(u.length>0)throw new Error("Leftover bytes in sub-branch");let l=zS(c);e.push(l);continue}if(r===sv){if(t+32>s.length)throw new Error("Not enough bytes for subdigest");let i=s.slice(t,t+32);t+=32,e.push({type:"subdigest",digest:f.toHex(i)});continue}if(r===nv){let i=(n&12)>>2;if(i===0){if(t>=s.length)throw new Error("Not enough bytes for nested weight");i=s[t],t++;}let a=n&3;if(a===0){if(t+2>s.length)throw new Error("Not enough bytes for nested threshold");a=f.toNumber(s.slice(t,t+2)),t+=2;}if(t+3>s.length)throw new Error("Not enough bytes for nested sub-tree size");let o=f.toNumber(s.slice(t,t+3));if(t+=3,t+o>s.length)throw new Error("Not enough bytes for nested sub-tree");let c=s.slice(t,t+o);t+=o;let{nodes:u,leftover:l}=og(c);if(l.length>0)throw new Error("Leftover bytes in nested sub-tree");let h=zS(u);e.push({type:"nested",tree:h,weight:BigInt(i),threshold:BigInt(a)});continue}if(r===rv){let i=n&15;if(i===0){if(t>=s.length)throw new Error("Not enough bytes for dynamic weight in eth_sign");i=s[t],t++;}if(t+64>s.length)throw new Error("Not enough bytes for eth_sign signature");let a=ga(s.slice(t,t+64));t+=64,e.push({type:"unrecovered-signer",weight:BigInt(i),signature:{type:"eth_sign",...a}});continue}if(r===iv){if(t+32>s.length)throw new Error("Not enough bytes for any address subdigest");let i=s.slice(t,t+32);t+=32,e.push({type:"any-address-subdigest",digest:f.toHex(i)});continue}if(r===rg||r===av){let i=n&3;if(i===0){if(t>=s.length)throw new Error("Not enough bytes for sapient weight");i=s[t],t++;}if(t+20>s.length)throw new Error("Not enough bytes for sapient signer address");let a=f.toHex(s.slice(t,t+20));t+=20;let o=(n&12)>>2;if(t+o>s.length)throw new Error("Not enough bytes for sapient signature size");let c=f.toNumber(s.slice(t,t+o));if(t+=o,t+c>s.length)throw new Error("Not enough bytes for sapient signature data");let u=s.slice(t,t+c);t+=c,e.push({type:"unrecovered-signer",weight:BigInt(i),signature:{address:a,data:f.toHex(u),type:r===rg?"sapient":"sapient_compact"}});continue}throw new Error(`Invalid signature flag: 0x${r.toString(16)}`)}return {nodes:e,leftover:s.slice(t)}}function eg(s,e){if(mt(s))return [eg(s[0],e),eg(s[1],e)];if(Mt(s)){let t=e(s);return t?{...s,signature:t}:s}if($t(s)){let t=e(s);return t?{...s,signature:t}:s}if(Us(s)||Hs(s))return s;if(es(s))return {...s,tree:eg(s.tree,e)};if(Ct(s))return s;throw new Error("Invalid topology")}function XC(s){let e=1,t=s[s.length-1];t?.configuration.checkpointer&&(e|=64);let n=f.fromNumber(e);if(t?.configuration.checkpointer){n=f.concat(n,f.padLeft(f.fromHex(t.configuration.checkpointer),20));let r=t.checkpointerData?.length??0;if(r>16777215)throw new Error("Checkpointer data too large");let i=f.padLeft(f.fromNumber(r),3);n=f.concat(n,i,t.checkpointerData??f.fromArray([]));}for(let r=0;r<s.length;r++){let i=s[r],a=e5(i,!0,r===s.length-1);if(a.length>16777215)throw new Error("Chained signature too large");let o=f.padLeft(f.fromNumber(a.length),3);n=f.concat(n,o,a);}return n}function e5(s,e,t){let{noChainId:n,checkpointerData:r,configuration:i,suffix:a,erc6492:o}=s;if(a?.length){let w=XC([{...s,suffix:void 0,erc6492:void 0},...a]);return o?RS(w,o):w}let c=0;n&&(c|=2);let u=ws(i.checkpoint);if(u>7)throw new Error("Checkpoint too large");c|=u<<2;let l=ws(i.threshold);if(l=l===0?1:l,l>2)throw new Error("Threshold too large");c|=l==2?32:0,i.checkpointer&&!t&&(c|=64);let h=f.fromNumber(c);if(i.checkpointer&&!t&&(h=f.concat(h,f.padLeft(f.fromHex(i.checkpointer),20)),!e)){let w=r?.length??0;if(w>16777215)throw new Error("Checkpointer data too large");let S=f.padLeft(f.fromNumber(w),3);h=f.concat(h,S,r??f.fromArray([]));}let m=f.padLeft(f.fromNumber(i.checkpoint),u);h=f.concat(h,m);let y=f.padLeft(f.fromNumber(i.threshold),l);h=f.concat(h,y);let g=Rh(i.topology,s);return h=f.concat(h,g),o?RS(h,o):h}function Rh(s,e={}){if(mt(s)||ig(s)){let t=Rh(s[0],e),n=Rh(s[1],e);if(mt(s[1])||ig(s[1])){let i=ws(BigInt(n.length));if(i>15)throw new Error("Branch too large");let a=tv<<4|i;return f.concat(t,f.fromNumber(a),f.padLeft(f.fromNumber(n.length),i),n)}else return f.concat(t,n)}if(es(s)||Dh(s)){let t=Rh(s.tree,e),n=nv<<4,r=f.fromArray([]);if(s.weight<=3n&&s.weight>0n)n|=Number(s.weight)<<2;else if(s.weight<=255n)r=f.fromNumber(Number(s.weight));else throw new Error("Weight too large");let i=f.fromArray([]);if(s.threshold<=3n&&s.threshold>0n)n|=Number(s.threshold);else if(s.threshold<=65535n)i=f.padLeft(f.fromNumber(Number(s.threshold)),2);else throw new Error("Threshold too large");if(t.length>16777215)throw new Error("Nested tree too large");return f.concat(f.fromNumber(n),r,i,f.padLeft(f.fromNumber(t.length),3),t)}if(Ct(s))return f.concat(f.fromNumber(ng<<4),f.fromHex(s));if(ug(s)||Vh(s))if(s.signature.type==="hash"||s.signature.type==="eth_sign"){let t=(s.signature.type==="hash"?QS:rv)<<4,n=f.fromArray([]);if(s.weight<=15n&&s.weight>0n)t|=Number(s.weight);else if(s.weight<=255n)n=f.fromNumber(Number(s.weight));else throw new Error("Weight too large");let r=Un(s.signature);return f.concat(f.fromNumber(t),n,r)}else if(s.signature.type==="erc1271"){let t=ev<<4,n=ws(BigInt(s.signature.data.length));if(n>3)throw new Error("Signature too large");t|=n<<2;let r=f.fromArray([]);if(s.weight<=3n&&s.weight>0n)t|=Number(s.weight);else if(s.weight<=255n)r=f.fromNumber(Number(s.weight));else throw new Error("Weight too large");return f.concat(f.fromNumber(t),r,f.padLeft(f.fromHex(s.signature.address),20),f.padLeft(f.fromNumber(f.fromHex(s.signature.data).length),n),f.fromHex(s.signature.data))}else if(s.signature.type==="sapient"||s.signature.type==="sapient_compact"){let t=(s.signature.type==="sapient"?rg:av)<<4,n=f.fromHex(s.signature.data),r=ws(BigInt(n.length));if(r>3)throw new Error("Signature too large");t|=r<<2;let i=f.fromArray([]);if(s.weight<=3n&&s.weight>0n)t|=Number(s.weight);else if(s.weight<=255n)i=f.fromNumber(Number(s.weight));else throw new Error("Weight too large");return f.concat(f.fromNumber(t),i,f.padLeft(f.fromHex(s.signature.address),20),f.padLeft(f.fromNumber(n.length),r),n)}else throw new Error(`Invalid signature type: ${s.signature.type}`);if(Mt(s)){let t=XS<<4,n=f.fromArray([]);if(s.weight<=15n&&s.weight>0n)t|=Number(s.weight);else if(s.weight<=255n)n=f.fromNumber(Number(s.weight));else throw new Error("Weight too large");return f.concat(f.fromNumber(t),n,f.padLeft(f.fromHex(s.address),20))}if($t(s)){let t=qt(s);return f.concat(f.fromNumber(ng<<4),t)}if(Us(s))return f.concat(f.fromNumber(sv<<4),f.fromHex(s.digest));if(Hs(s))return f.concat(f.fromNumber(iv<<4),f.fromHex(s.digest));throw new Error("Invalid topology")}function zS(s){if(s.length===0)throw new Error("Empty signature tree");if(s.length===1)return s[0];let e=s[0];for(let t=1;t<s.length;t++)e=[e,s[t]];return e}function TO(s){return JSON.stringify(t5(s))}function t5(s){return {noChainId:s.noChainId,checkpointerData:s.checkpointerData?f.toHex(s.checkpointerData):void 0,configuration:{threshold:s.configuration.threshold.toString(),checkpoint:s.configuration.checkpoint.toString(),topology:tg(s.configuration.topology),checkpointer:s.configuration.checkpointer},suffix:s.suffix?s.suffix.map(e=>t5(e)):void 0}}function tg(s){if(Array.isArray(s))return [tg(s[0]),tg(s[1])];if(typeof s=="object"&&s!==null&&"type"in s)switch(s.type){case"signer":return {type:"signer",address:s.address,weight:s.weight.toString()};case"sapient-signer":return {type:"sapient-signer",address:s.address,weight:s.weight.toString(),imageHash:s.imageHash};case"subdigest":return {type:"subdigest",digest:s.digest};case"any-address-subdigest":return {type:"any-address-subdigest",digest:s.digest};case"nested":return {type:"nested",tree:tg(s.tree),weight:s.weight.toString(),threshold:s.threshold.toString()};case"unrecovered-signer":return {type:"unrecovered-signer",weight:s.weight.toString(),signature:BO(s.signature)};default:throw new Error("Invalid raw topology type")}if(typeof s=="string")return s;throw new Error("Invalid raw topology format")}function BO(s){if(s.type==="eth_sign"||s.type==="hash")return {type:s.type,r:E.fromNumber(s.r,{size:32}),s:E.fromNumber(s.s,{size:32}),yParity:s.yParity};if(s.type==="erc1271")return {type:s.type,address:s.address,data:s.data};if(s.type==="sapient"||s.type==="sapient_compact")return {type:s.type,address:s.address,data:s.data};throw new Error("Unknown signature type in raw signature")}function OO(s){let e=JSON.parse(s);return s5(e)}function s5(s){return {noChainId:s.noChainId,checkpointerData:s.checkpointerData?f.fromHex(s.checkpointerData):void 0,configuration:{threshold:BigInt(s.configuration.threshold),checkpoint:BigInt(s.configuration.checkpoint),topology:sg(s.configuration.topology),checkpointer:s.configuration.checkpointer},suffix:s.suffix?s.suffix.map(e=>s5(e)):void 0}}function sg(s){if(Array.isArray(s)){if(s.length!==2)throw new Error("Invalid raw topology node");return [sg(s[0]),sg(s[1])]}if(typeof s=="object"&&s!==null&&"type"in s)switch(s.type){case"signer":return {type:"signer",address:s.address,weight:BigInt(s.weight)};case"sapient-signer":return {type:"sapient-signer",address:s.address,weight:BigInt(s.weight),imageHash:s.imageHash};case"subdigest":return {type:"subdigest",digest:s.digest};case"any-address-subdigest":return {type:"any-address-subdigest",digest:s.digest};case"nested":return {type:"nested",tree:sg(s.tree),weight:BigInt(s.weight),threshold:BigInt(s.threshold)};case"unrecovered-signer":return {type:"unrecovered-signer",weight:BigInt(s.weight),signature:RO(s.signature)};default:throw new Error("Invalid raw topology type")}if(typeof s=="string")return s;throw new Error("Invalid raw topology format")}function RO(s){switch(s.type){case"eth_sign":case"hash":return {type:s.type,r:E.toBigInt(s.r),s:E.toBigInt(s.s),yParity:s.yParity};case"erc1271":return {type:"erc1271",address:s.address,data:s.data};case"sapient":case"sapient_compact":return {type:s.type,address:s.address,data:s.data};default:throw new Error("Invalid signature type in raw signature")}}async function YS(s,e,t,n,r){if(s.suffix?.length){let o=!1,{configuration:c,weight:u}=await YS({...s,suffix:void 0},e,t,n,r);o||=u<c.threshold;for(let l of s.suffix){let h=await YS(l,e,l.noChainId?0:t,qS(f.toHex(qt(c))),r);o||=h.weight<h.configuration.threshold,o||=h.configuration.checkpoint>=c.checkpoint,c=h.configuration,u=h.weight;}return {configuration:c,weight:o?0n:u}}let{topology:i,weight:a}=await ZS(s.configuration.topology,e,t,n,r);return {configuration:{...s.configuration,topology:i},weight:a}}async function ZS(s,e,t,n,r){let i=Pc(e,t,n);if(Vh(s))switch(s.signature.type){case"eth_sign":case"hash":return {topology:{type:"signer",address:Ot.recoverAddress({payload:s.signature.type==="eth_sign"?oe.keccak256(ot.encodePacked(["string","bytes32"],[`Ethereum Signed Message:
|
|
343
|
-
32`,f.toHex(i)])):i,signature:s.signature}),weight:s.weight,signed:!0,signature:s.signature},weight:s.weight};case"erc1271":switch(r?.provider){case void 0:case"assume-invalid":if(r?.throw!==!1)throw new Error(`unable to validate signer ${s.signature.address} erc-1271 signature`);return {topology:{type:"signer",address:s.signature.address,weight:s.weight},weight:0n};case"assume-valid":return {topology:{type:"signer",address:s.signature.address,weight:s.weight,signed:!0,signature:s.signature},weight:s.weight};default:let a="provider"in r.provider?r.provider.provider:r.provider,o="block"in r.provider?r.provider.block:void 0,c={to:s.signature.address,data:
|
|
337
|
+
`;function v0({id:s,href:e,rel:t,crossOrigin:n}){let r=`${Wl}-${s}`;if(!document.getElementById(r)){let i=document.createElement("link");i.id=r,i.href=e,t&&(i.rel=t),n&&(i.crossOrigin=n),document.head.appendChild(i);}}var gI=()=>pI(cP()),yI=()=>pI(uP());var rc=class{disableGenericPopupOverlay;disableBlockedPopupOverlay;overlay;isBlockedOverlay;tryAgainListener;onCloseListener;constructor(e,t=!1){this.disableBlockedPopupOverlay=e.disableBlockedPopupOverlay||!1,this.disableGenericPopupOverlay=e.disableGenericPopupOverlay||!1,this.isBlockedOverlay=t;}append(e,t){this.shouldAppendOverlay()&&(this.appendOverlay(),this.updateTryAgainButton(e),this.updateCloseButton(t));}update(e){this.updateTryAgainButton(e);}remove(){this.overlay&&this.overlay.remove();}shouldAppendOverlay(){return !(this.disableGenericPopupOverlay&&this.disableBlockedPopupOverlay||this.disableGenericPopupOverlay&&!this.isBlockedOverlay||this.disableBlockedPopupOverlay&&this.isBlockedOverlay)}appendOverlay(){if(!this.overlay){v0({id:"link-googleapis",href:"https://fonts.googleapis.com"}),v0({id:"link-gstatic",href:"https://fonts.gstatic.com",crossOrigin:"anonymous"}),v0({id:"link-roboto",href:"https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,400;0,500;0,700;1,400;1,500;1,700&display=swap",rel:"stylesheet"});let t=document.createElement("div");t.innerHTML=this.isBlockedOverlay?gI():yI(),document.body.insertAdjacentElement("beforeend",t),this.overlay=t;}}updateTryAgainButton(e){let t=document.getElementById(S0);t&&(this.tryAgainListener&&t.removeEventListener("click",this.tryAgainListener),this.tryAgainListener=e,t.addEventListener("click",e));}updateCloseButton(e){let t=document.getElementById(b0);t&&(this.onCloseListener&&t.removeEventListener("click",this.onCloseListener),this.onCloseListener=e,t.addEventListener("click",e));}};var ic=(s=>(s.PRODUCTION="production",s.SANDBOX="sandbox",s))(ic||{}),lP=(s=>(s.API_KEY="x-immutable-api-key",s.PUBLISHABLE_KEY="x-immutable-publishable-key",s.RATE_LIMITING_KEY="x-api-key",s))(lP||{});var Jl=13371,Gi=13473,jw=42161,Hw=421614,Sr={13371:{magicPublishableApiKey:"pk_live_10F423798A540ED7",magicProviderId:"aa80b860-8869-4f13-9000-6a6ad3d20017"},13473:{magicPublishableApiKey:"pk_live_10F423798A540ED7",magicProviderId:"aa80b860-8869-4f13-9000-6a6ad3d20017"}};var zl={chainId:13371,name:"Immutable zkEVM",rpcUrl:"https://rpc.immutable.com",relayerUrl:"https://api.immutable.com/relayer-mr",apiUrl:"https://api.immutable.com",passportDomain:"https://passport.immutable.com",magicPublishableApiKey:Sr[13371].magicPublishableApiKey,magicProviderId:Sr[13371].magicProviderId,magicTeeBasePath:"https://tee.express.magiclabs.com"},Yl={chainId:13473,name:"Immutable zkEVM Testnet",rpcUrl:"https://rpc.testnet.immutable.com",relayerUrl:"https://api.sandbox.immutable.com/relayer-mr",apiUrl:"https://api.sandbox.immutable.com",passportDomain:"https://passport.sandbox.immutable.com",magicPublishableApiKey:Sr[13473].magicPublishableApiKey,magicProviderId:Sr[13473].magicProviderId,magicTeeBasePath:"https://tee.express.magiclabs.com"},x0={chainId:42161,name:"Arbitrum One",rpcUrl:"https://arb1.arbitrum.io/rpc",relayerUrl:"https://next-arbitrum-one-relayer.sequence.app",nodeUrl:"https://next-nodes.sequence.app/arbitrum-one",apiUrl:"https://api.immutable.com",passportDomain:"https://passport.immutable.com",feeTokenSymbol:"ETH",sequenceIdentityInstrumentEndpoint:"https://next-identity.sequence.app"},E0={chainId:421614,name:"Arbitrum Sepolia",rpcUrl:"https://sepolia-rollup.arbitrum.io/rpc",relayerUrl:"https://next-arbitrum-sepolia-relayer.sequence.app",nodeUrl:"https://next-nodes.sequence.app/arbitrum-sepolia",apiUrl:"https://api.sandbox.immutable.com",passportDomain:"https://passport.sandbox.immutable.com",feeTokenSymbol:"ETH",sequenceIdentityInstrumentEndpoint:"https://next-identity.sequence-dev.app"},A0=[Yl,zl],hP={chains:[zl]},fP={chains:[Yl]},dP={chains:A0},mP={chains:[x0]},pP={chains:[E0]};var wI={zkevm:{[ic.PRODUCTION]:zl,[ic.SANDBOX]:Yl},arbitrum_one:{[ic.PRODUCTION]:x0,[ic.SANDBOX]:E0}};function yP(){let s={};for(let[e,t]of Object.entries(wI))for(let n of Object.values(t))s[n.chainId]=e;return s[15003]="zkevm",s}var wP=yP();function bP(s,e){let t=wI[s];if(!t)throw new Error(`Chain ${s} is not supported`);let n=t[e];if(!n)throw new Error(`Chain ${s} is not configured for environment ${e}`);return n}function ac(s){let e=typeof s=="string"?parseInt(s.includes(":")?s.split(":")[1]:s,10):s;return wP[e]??"zkevm"}var _w="Confirm this transaction",Mw=720,$w=480,bI=1e3;var oc=class{config;confirmationWindow;popupOptions;overlay;overlayClosed;timer;constructor(e){this.config=e,this.overlayClosed=!1;}getHref(e,t){let n=`${this.config.passportDomain}/transaction-confirmation/${e}`;if(t){let r=t?Object.keys(t).map(i=>`${i}=${t[i]}`).join("&"):"";n=`${n}?${r}`;}return n}requestConfirmation(e,t,n,r){return new Promise((i,a)=>{let o=({data:u,origin:l})=>{if(!(l!==this.config.passportDomain||u.eventType!==Gl))switch(u.messageType){case"confirmation_window_ready":{this.confirmationWindow?.postMessage({eventType:Gl,messageType:"confirmation_start"},this.config.passportDomain);break}case"transaction_confirmed":{this.closeWindow(),i({confirmed:!0});break}case"transaction_rejected":{this.closeWindow(),i({confirmed:!1});break}case"transaction_error":{this.closeWindow(),a(new Error("Error during transaction confirmation"));break}default:this.closeWindow(),a(new Error("Unsupported message type"));}},c="";if(n===SI.mr.TransactionApprovalRequestChainTypeEnum.Starkex)c=this.getHref("transaction",{transactionId:e,etherAddress:t,chainType:n});else {let l=(r?ac(r):"zkevm").replace("_","-");c=this.getHref(`${l}/transaction`,{transactionID:e,etherAddress:t,chainType:n,chainID:r});}window.addEventListener("message",o),this.showConfirmationScreen(c,o,i);})}requestMessageConfirmation(e,t,n,r){return new Promise((i,a)=>{let o=({data:h,origin:m})=>{if(!(m!==this.config.passportDomain||h.eventType!==Gl))switch(h.messageType){case"confirmation_window_ready":{this.confirmationWindow?.postMessage({eventType:Gl,messageType:"confirmation_start"},this.config.passportDomain);break}case"message_confirmed":{this.closeWindow(),i({confirmed:!0});break}case"message_rejected":{this.closeWindow(),i({confirmed:!1});break}case"message_error":{this.closeWindow(),a(new Error("Error during message confirmation"));break}default:this.closeWindow(),a(new Error("Unsupported message type"));}};window.addEventListener("message",o);let u=ac(r).replace("_","-"),l=this.getHref(`${u}/message`,{messageID:e,etherAddress:t,chainID:r,messageType:n});this.showConfirmationScreen(l,o,i);})}showServiceUnavailable(){return new Promise((e,t)=>{this.showConfirmationScreen(this.getHref("unavailable"),()=>{},()=>{this.closeWindow(),t(new Error("Service unavailable"));});})}loading(e){if(!this.config.crossSdkBridgeEnabled){this.popupOptions=e;try{this.confirmationWindow=w0({url:this.getHref("loading"),title:_w,width:e?.width||$w,height:e?.height||Mw}),this.overlay=new rc(this.config.popupOverlayOptions||{});}catch(t){let n=t instanceof Error?t.message:String(t);trackError("passport","confirmationPopupDenied",new Error(n)),this.overlay=new rc(this.config.popupOverlayOptions||{},!0);}this.overlay.append(()=>{try{this.confirmationWindow?.close(),this.confirmationWindow=w0({url:this.getHref("loading"),title:_w,width:this.popupOptions?.width||$w,height:this.popupOptions?.height||Mw});}catch{}},()=>{this.overlayClosed=!0,this.closeWindow();});}}closeWindow(){this.confirmationWindow?.close(),this.overlay?.remove(),this.overlay=void 0;}showConfirmationScreen(e,t,n){if(this.confirmationWindow&&(this.confirmationWindow.location.href=e),!this.overlay){this.overlayClosed=!1,n({confirmed:!1});return}let r=()=>{(this.confirmationWindow?.closed||this.overlayClosed)&&(clearInterval(this.timer),window.removeEventListener("message",t),n({confirmed:!1}),this.overlayClosed=!1,this.confirmationWindow=void 0);};this.timer=setInterval(r,bI),this.overlay.update(()=>this.recreateConfirmationWindow(e,r));}recreateConfirmationWindow(e,t){try{clearInterval(this.timer),this.confirmationWindow?.close(),this.confirmationWindow=w0({url:e,title:_w,width:this.popupOptions?.width||$w,height:this.popupOptions?.height||Mw}),this.timer=setInterval(t,bI);}catch{}}};var Wi=(o=>(o.WALLET_CONNECTION_ERROR="WALLET_CONNECTION_ERROR",o.TRANSACTION_REJECTED="TRANSACTION_REJECTED",o.INVALID_CONFIGURATION="INVALID_CONFIGURATION",o.UNAUTHORIZED="UNAUTHORIZED",o.GUARDIAN_ERROR="GUARDIAN_ERROR",o.SERVICE_UNAVAILABLE_ERROR="SERVICE_UNAVAILABLE_ERROR",o.NOT_LOGGED_IN_ERROR="NOT_LOGGED_IN_ERROR",o))(Wi||{}),ze=class extends Error{type;constructor(e,t){super(e),this.name="WalletError",this.type=t;}};var Ji=s=>typeof s=="object"&&s!==null&&"isAxiosError"in s;var qw="Transaction requires confirmation but this functionality is not supported in this environment. Please contact Immutable support if you need to enable this feature.",I0=s=>BigInt(s).toString(),EP=s=>{try{return s.map(e=>({delegateCall:e.delegateCall===!0,revertOnError:e.revertOnError===!0,gasLimit:e.gasLimit?I0(e.gasLimit):"0",target:e.to??zeroAddress,value:e.value?I0(e.value):"0",data:e.data?e.data.toString():"0x"}))}catch(e){let t=e instanceof Error?e.message:String(e);throw new te(-32602,`Transaction failed to parsing: ${t}`)}},cc=class{guardianApi;confirmationScreen;crossSdkBridgeEnabled;getUser;constructor({config:e,getUser:t,guardianApi:n,passportDomain:r,clientId:i}){this.confirmationScreen=new oc({authenticationDomain:"https://auth.immutable.com",passportDomain:r,oidcConfiguration:{clientId:i,redirectUri:"https://auth.immutable.com/im-logged-in"},crossSdkBridgeEnabled:e.crossSdkBridgeEnabled}),this.crossSdkBridgeEnabled=e.crossSdkBridgeEnabled,this.guardianApi=n,this.getUser=t;}async getUserZkEvm(){let e=await this.getUser();if(!e||!isUserZkEvm(e))throw new te(4100,"User not authenticated or missing zkEvm data");return e}withConfirmationScreen(e){return t=>this.withConfirmationScreenTask(e)(t)()}withConfirmationScreenTask(e){return t=>async()=>{this.confirmationScreen.loading(e);try{return await t()}catch(n){throw n instanceof ze&&n.type==="SERVICE_UNAVAILABLE_ERROR"?(await this.confirmationScreen.showServiceUnavailable(),n):(this.confirmationScreen.closeWindow(),n)}}}withDefaultConfirmationScreenTask(e){return this.withConfirmationScreenTask()(e)}async evaluateEVMTransaction({chainId:e,nonce:t,metaTransactions:n}){let r=await this.getUserZkEvm(),i={Authorization:`Bearer ${r.accessToken}`},a=EP(n);try{return (await this.guardianApi.evaluateTransaction({id:"evm",transactionEvaluationRequest:{chainType:"evm",chainId:e,transactionData:{nonce:t,userAddress:r.zkEvm.ethAddress,metaTransactions:a}}},{headers:i})).data}catch(o){if(Ji(o)&&o.response?.status===403)throw new ze("Service unavailable","SERVICE_UNAVAILABLE_ERROR");let c=o instanceof Error?o.message:String(o);throw new te(-32603,`Transaction failed to validate with error: ${c}`)}}async validateEVMTransaction({chainId:e,nonce:t,metaTransactions:n,isBackgroundTransaction:r}){let i=await this.evaluateEVMTransaction({chainId:e,nonce:t,metaTransactions:n}),{confirmationRequired:a,transactionId:o}=i;if(a&&this.crossSdkBridgeEnabled)throw new te(-32003,qw);if(a&&o){let c=await this.getUserZkEvm();if(!(await this.confirmationScreen.requestConfirmation(o,c.zkEvm.ethAddress,SI.mr.TransactionApprovalRequestChainTypeEnum.Evm,e)).confirmed)throw new te(-32003,"Transaction rejected by user")}else r||this.confirmationScreen.closeWindow();}async handleEIP712MessageEvaluation({chainID:e,payload:t}){try{let n=await this.getUserZkEvm();return (await this.guardianApi.evaluateMessage({messageEvaluationRequest:{chainID:e,payload:t}},{headers:{Authorization:`Bearer ${n.accessToken}`}})).data}catch(n){let r=n instanceof Error?n.message:String(n);throw new te(-32603,`Message failed to validate with error: ${r}`)}}async evaluateEIP712Message({chainID:e,payload:t}){let{messageId:n,confirmationRequired:r}=await this.handleEIP712MessageEvaluation({chainID:e,payload:t});if(r&&this.crossSdkBridgeEnabled)throw new te(-32003,qw);if(r&&n){let i=await this.getUserZkEvm();if(!(await this.confirmationScreen.requestMessageConfirmation(n,i.zkEvm.ethAddress,"eip712",e)).confirmed)throw new te(-32003,"Signature rejected by user")}else this.confirmationScreen.closeWindow();}async handleERC191MessageEvaluation({chainID:e,payload:t}){try{let n=await this.getUserZkEvm();return (await this.guardianApi.evaluateErc191Message({eRC191MessageEvaluationRequest:{chainID:Jt(Number(e)),payload:t}},{headers:{Authorization:`Bearer ${n.accessToken}`}})).data}catch(n){let r=n instanceof Error?n.message:String(n);throw new te(-32603,`Message failed to validate with error: ${r}`)}}async evaluateERC191Message({chainID:e,payload:t}){let{messageId:n,confirmationRequired:r}=await this.handleERC191MessageEvaluation({chainID:e,payload:t});if(r&&this.crossSdkBridgeEnabled)throw new te(-32003,qw);if(r&&n){let i=await this.getUserZkEvm();if(!(await this.confirmationScreen.requestMessageConfirmation(n,i.zkEvm.ethAddress,"erc191",String(e))).confirmed)throw new te(-32003,"Signature rejected by user")}else this.confirmationScreen.closeWindow();}};var AP=s=>new Promise(e=>{setTimeout(()=>e(),s);}),C0=async(s,e)=>{let{retries:t=3,interval:n=1e3,finalErr:r=Error("Retry failed"),finallyFn:i=()=>{}}=e||{};try{return await s()}catch{return t<=0?Promise.reject(r):(await AP(n),C0(s,{retries:t-1,finalErr:r,finallyFn:i}))}finally{t<=0&&i();}};var IP=30,CP=1e3,NP=async(s,e,t)=>{let n=m0([s]),r=Rw(n),i=await t.imGetFeeOptions(e,r);if(!i||!Array.isArray(i))throw new Error("Invalid fee options received from relayer");let a=t.getPreferredFeeTokenSymbol(),o=i.find(c=>c.tokenSymbol===a);if(!o)throw new Error(`Failed to retrieve fees for ${a} token`);return o},kP=async(s,e,t,n,r)=>{if(!s.to)throw new te(-32602,'eth_sendTransaction requires a "to" field');let i={to:s.to.toString(),data:s.data,nonce:BigInt(0),value:s.value,revertOnError:!0},[a,o]=await Promise.all([ql(e,n,r),NP(i,n,t)]),c=[{...i,nonce:a}],u=BigInt(o.tokenPrice);return u!==BigInt(0)&&c.push({nonce:a,to:o.recipientAddress,value:u,revertOnError:!0}),c},N0=async(s,e,t)=>{let r=await C0(async()=>{let i=await s.imGetTransactionByHash(e);if(i.status==="PENDING")throw new Error;return i},{retries:IP,interval:CP,finalErr:new te(-32e3,"transaction hash not generated in time")});if(t.addEvent("endRetrieveRelayerTransaction"),!["SUBMITTED","SUCCESSFUL"].includes(r.status)){let i=`Transaction failed to submit with status ${r.status}.`;throw r.statusMessage&&(i+=` Error message: ${r.statusMessage}`),new te(-32e3,i)}return r},k0=async({transactionRequest:s,ethSigner:e,rpcProvider:t,guardianClient:n,relayerClient:r,zkEvmAddress:i,flow:a,nonceSpace:o,isBackgroundTransaction:c})=>{let u=await t.getChainId(),l=BigInt(u);a.addEvent("endDetectNetwork");let h=await kP(s,t,r,i,o);a.addEvent("endBuildMetaTransactions");let{nonce:m}=h[0];if(typeof m>"u")throw new Error("Failed to retrieve nonce from the smart wallet");let y=async()=>{await n.validateEVMTransaction({chainId:Jt(Number(u)),nonce:I0(m),metaTransactions:h,isBackgroundTransaction:c}),a.addEvent("endValidateEVMTransaction");},g=async()=>{let C=await g0(h,m,l,i,e);return a.addEvent("endGetSignedMetaTransactions"),C},[,w]=await Promise.all([y(),g()]),S=await r.ethSendTransaction(i,w);return a.addEvent("endRelayerSendTransaction"),{signedTransactions:w,relayerId:S,nonce:m}},PP=async s=>{if(!s.to)throw new te(-32602,'im_signEjectionTransaction requires a "to" field');if(typeof s.nonce>"u")throw new te(-32602,'im_signEjectionTransaction requires a "nonce" field');if(!s.chainId)throw new te(-32602,'im_signEjectionTransaction requires a "chainId" field');return [{to:s.to.toString(),data:s.data,nonce:s.nonce??void 0,value:s.value,revertOnError:!0}]},xI=async({transactionRequest:s,ethSigner:e,zkEvmAddress:t,flow:n})=>{let r=await PP(s);n.addEvent("endBuildMetaTransactions");let i=await g0(r,s.nonce,BigInt(s.chainId??0),t,e);return n.addEvent("endGetSignedMetaTransactions"),{to:t,data:i,chainId:Jt(Number(s.chainId??0))}};var Fw=async({params:s,ethSigner:e,rpcProvider:t,relayerClient:n,guardianClient:r,zkEvmAddress:i,flow:a,nonceSpace:o,isBackgroundTransaction:c=!1})=>{let u=s[0],{relayerId:l}=await k0({transactionRequest:u,ethSigner:e,rpcProvider:t,guardianClient:r,relayerClient:n,zkEvmAddress:i,flow:a,nonceSpace:o,isBackgroundTransaction:c}),{hash:h}=await N0(n,l,a);return h};var EI=["types","domain","primaryType","message"],TP=s=>EI.every(e=>e in s),BP=(s,e)=>{let t;if(typeof s=="string")try{t=JSON.parse(s);}catch(r){throw new te(-32602,`Failed to parse typed data JSON: ${r}`)}else if(typeof s=="object")t=s;else throw new te(-32602,`Invalid typed data argument: ${s}`);if(!TP(t))throw new te(-32602,`Invalid typed data argument. The following properties are required: ${EI.join(", ")}`);let n=t.domain?.chainId;if(n){let r;if(typeof n=="string"?n.startsWith("0x")?r=parseInt(n,16):r=parseInt(n,10):r=Number(n),t.domain.chainId=r,BigInt(r)!==e)throw new te(-32602,`Invalid chainId, expected ${e}`)}return t},AI=async({params:s,method:e,ethSigner:t,rpcProvider:n,relayerClient:r,guardianClient:i,flow:a})=>{let o=s[0],c=s[1];if(!o||!c)throw new te(-32602,`${e} requires an address and a typed data JSON`);let u=await n.getChainId(),l=BP(c,BigInt(u));a.addEvent("endDetectNetwork"),await i.evaluateEIP712Message({chainID:String(u),payload:l}),a.addEvent("endValidateMessage");let h=await r.imSignTypedData(o,l);a.addEvent("endRelayerSignTypedData");let m=await Vw(l,h,BigInt(u),o,t);return a.addEvent("getSignedTypedData"),m};var RP=s=>{let e=0;for(;e<s.length&&s[e]===0;)e++;return s.slice(e)},VP=s=>{if(typeof TextDecoder<"u")return new TextDecoder("utf-8").decode(s);let e="";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return decodeURIComponent(escape(e))},II=s=>{if(!s)return s;try{let e=toBytes(s),t=RP(e);return VP(t)}catch{return s}};var P0=async({params:s,ethSigner:e,zkEvmAddress:t,rpcProvider:n,guardianClient:r,relayerClient:i,flow:a})=>{let o=s[0],c=s[1];if(!c||!o)throw new te(-32602,"personal_sign requires an address and a message");if(c.toLowerCase()!==t.toLowerCase())throw new te(-32602,"personal_sign requires the signer to be the from address");let u=II(o),l=await n.getChainId();a.addEvent("endDetectNetwork");let h=BigInt(l),m=Dw(h,u,e,c);m.then(()=>a.addEvent("endEOASignature")),await r.evaluateERC191Message({chainID:h,payload:u}),a.addEvent("endEvaluateERC191Message");let[y,g]=await Promise.all([m,i.imSign(c,u)]);a.addEvent("endRelayerSign");let w=await e.getAddress();return a.addEvent("endGetEOAAddress"),y0(y,w,g)};var DP="/v1/sdk/session-activity/check",T0,CI=s=>{T0||(T0=s);},UP=s=>{let e=new URL(DP,T0);return Object.entries(s).forEach(([t,n])=>{n!=null&&e.searchParams.append(t,String(n));}),e.toString()};async function NI(s){if(!T0)throw new Error("Client not initialised");let e=await fetch(UP(s));if(e.status!==404){if(!e.ok)throw new Error(`Session activity request failed with status ${e.status}`);return e.json()}}function PI(s,e){return (...t)=>{try{let n=s(...t);return n instanceof Promise?n.catch(r=>(r instanceof Error&&trackError("passport","sessionActivityError",r),e)):n}catch(n){return n instanceof Error&&trackError("passport","sessionActivityError",n),e}}}var{getItem:TI,setItem:Kw}=utils.localStorage,Gw="sessionActivitySendCount",BI="sessionActivityDate",Ww={},vr={},B0={},OI=()=>{vr=TI(Gw)||{};let s=TI(BI),e=new Date,t=e.getFullYear(),n=`${e.getMonth()+1}`.padStart(2,"0"),r=`${e.getDate()}`.padStart(2,"0"),i=`${t}-${n}-${r}`;(!s||s!==i)&&(vr={}),Kw(BI,i),Kw(Gw,vr);};OI();var $P=s=>{OI(),vr[s]||(vr[s]=0),vr[s]++,Kw(Gw,vr),Ww[s]=0;},qP=async s=>new Promise(e=>{setTimeout(e,s*1e3);}),FP=async s=>{let e=s.flow||trackFlow("passport","sendSessionActivity"),t=s.passportClient;if(!t)throw e.addEvent("No Passport Client ID"),new Error("No Passport Client ID provided");if(B0[t])return;B0[t]=!0;let{sendTransaction:n,sessionActivityApiUrl:r}=s;if(!n)throw new Error("No sendTransaction function provided");if(!r)throw new Error("No session activity API URL provided");CI(r);let i=s.walletAddress;if(!i)throw e.addEvent("No Passport Wallet Address"),new Error("No wallet address");let a;try{if(a=await NI({clientId:t,wallet:i,checkCount:Ww[t]||0,sendCount:vr[t]||0}),Ww[t]++,!a)return}catch(o){throw e.addEvent("Failed to fetch details"),new Error("Failed to get details",{cause:o})}if(a&&a.contractAddress&&a.functionName){let o=parseAbi([`function ${a.functionName}()`]),c=encodeFunctionData({abi:o,functionName:a.functionName}),u=a.contractAddress;try{e.addEvent("Start Sending Transaction");let l=await s.sendTransaction([{to:u,from:i,data:c}],e);$P(t),e.addEvent("Transaction Sent",{tx:l});}catch(l){e.addEvent("Failed to send Transaction");let h=new Error("Failed to send transaction",{cause:l});trackError("passport","sessionActivityError",h,{flowId:e.details.flowId});}}a&&a.delay&&a.delay>0&&(e.addEvent("Delaying Transaction",{delay:a.delay}),await qP(a.delay),setTimeout(()=>{e.addEvent("Retrying after Delay"),B0[t]=!1,RI({...s,flow:e});},0));},RI=s=>PI(FP)(s).then(()=>{B0[s.passportClient]=!1;}),VI=RI;var DI=async({params:s,ethSigner:e,rpcProvider:t,relayerClient:n,guardianClient:r,zkEvmAddress:i,flow:a})=>{let o={to:i,value:0n},{relayerId:c}=await k0({transactionRequest:o,ethSigner:e,rpcProvider:t,guardianClient:r,relayerClient:n,zkEvmAddress:i,flow:a});return r.withConfirmationScreen()(async()=>{let u=await P0({params:s,ethSigner:e,zkEvmAddress:i,rpcProvider:t,guardianClient:r,relayerClient:n,flow:a});return await N0(n,c,a),u})};var UI=async({params:s,ethSigner:e,zkEvmAddress:t,flow:n})=>{if(!s||s.length!==1)throw new te(-32602,"im_signEjectionTransaction requires a singular param (hash)");let r=s[0];return await xI({transactionRequest:r,ethSigner:e,zkEvmAddress:t,flow:n})};var Jw=s=>!!s.zkEvm,Xl=class{#e;#s;#n;#t;#a;#i;#r;#u;#c;#o;#f;isPassport=!0;constructor({getUser:e,clientId:t,config:n,multiRollupApiClients:r,walletEventEmitter:i,guardianClient:a,ethSigner:o,user:c,sessionActivityApiUrl:u}){this.#e=e,this.#f=t,this.#s=n,this.#i=a,this.#a=i,this.#n=u,this.#o=o,this.#r=createPublicClient({transport:http(this.#s.zkEvmRpcUrl)}),this.#c=new Fl({config:this.#s,rpcProvider:this.#r,getUser:this.#e}),this.#u=r,this.#t=new TypedEventEmitter,c&&Jw(c)&&this.#h(c.zkEvm.ethAddress),i.on("loggedOut",this.#d),i.on("accountsRequested",VI);}#d=()=>{this.#t.emit("accountsChanged",[]);};async#m(){return this.#e()}async#h(e){if(!this.#n)return;let t=BigInt(1),n=async(r,i)=>await Fw({params:r,ethSigner:this.#o,guardianClient:this.#i,rpcProvider:this.#r,relayerClient:this.#c,zkEvmAddress:e,flow:i,nonceSpace:t,isBackgroundTransaction:!0});this.#a.emit("accountsRequested",{sessionActivityApiUrl:this.#n,sendTransaction:n,walletAddress:e,passportClient:this.#f});}async#l(){try{let e=await this.#m();return e&&Jw(e)?e.zkEvm.ethAddress:void 0}catch{return}}async#p(e){switch(e.method){case"eth_requestAccounts":{let t=await this.#l();if(t)return [t];let n=trackFlow("passport","ethRequestAccounts");try{let r=await this.#e();if(!r)throw new te(4100,"User not authenticated. Please log in first.");n.addEvent("endGetUser");let i;return Jw(r)?i=r.zkEvm.ethAddress:(n.addEvent("startUserRegistration"),i=await lI({ethSigner:this.#o,getUser:this.#e,multiRollupApiClients:this.#u,accessToken:r.accessToken,rpcProvider:this.#r,flow:n}),n.addEvent("endUserRegistration"),await this.#e(!0),n.addEvent("endForceRefresh")),this.#t.emit("accountsChanged",[i]),identify({passportId:r.profile.sub}),this.#h(i),[i]}catch(r){throw r instanceof Error?trackError("passport","ethRequestAccounts",r,{flowId:n.details.flowId}):n.addEvent("errored"),r}finally{n.addEvent("End");}}case"eth_sendTransaction":{let t=await this.#l();if(!t)throw new te(4100,"Unauthorised - call eth_requestAccounts first");let n=trackFlow("passport","ethSendTransaction");try{return await this.#i.withConfirmationScreen({width:480,height:720})(async()=>await Fw({params:e.params||[],ethSigner:this.#o,guardianClient:this.#i,rpcProvider:this.#r,relayerClient:this.#c,zkEvmAddress:t,flow:n}))}catch(r){throw r instanceof Error?trackError("passport","eth_sendTransaction",r,{flowId:n.details.flowId}):n.addEvent("errored"),r}finally{n.addEvent("End");}}case"eth_accounts":{let t=await this.#l();return t?[t]:[]}case"personal_sign":{let t=await this.#l();if(!t)throw new te(4100,"Unauthorised - call eth_requestAccounts first");let n=trackFlow("passport","personalSign");try{return await this.#i.withConfirmationScreen({width:480,height:720})(async()=>this.#s.forceScwDeployBeforeMessageSignature&&!(await ql(this.#r,t)>BigInt(0))?await DI({params:e.params||[],zkEvmAddress:t,ethSigner:this.#o,rpcProvider:this.#r,guardianClient:this.#i,relayerClient:this.#c,flow:n}):await P0({params:e.params||[],zkEvmAddress:t,ethSigner:this.#o,rpcProvider:this.#r,guardianClient:this.#i,relayerClient:this.#c,flow:n}))}catch(r){throw r instanceof Error?trackError("passport","personal_sign",r,{flowId:n.details.flowId}):n.addEvent("errored"),r}finally{n.addEvent("End");}}case"eth_signTypedData":case"eth_signTypedData_v4":{if(!await this.#l())throw new te(4100,"Unauthorised - call eth_requestAccounts first");let n=trackFlow("passport","ethSignTypedDataV4");try{return await this.#i.withConfirmationScreen({width:480,height:720})(async()=>await AI({method:e.method,params:e.params||[],ethSigner:this.#o,rpcProvider:this.#r,relayerClient:this.#c,guardianClient:this.#i,flow:n}))}catch(r){throw r instanceof Error?trackError("passport","eth_signTypedData",r,{flowId:n.details.flowId}):n.addEvent("errored"),r}finally{n.addEvent("End");}}case"eth_chainId":{let t=await this.#r.getChainId();return toHex(t)}case"eth_getBalance":case"eth_getCode":case"eth_getTransactionCount":{let[t,n]=e.params||[];return this.#r.request({method:e.method,params:[t,n||"latest"]})}case"eth_getStorageAt":{let[t,n,r]=e.params||[];return this.#r.request({method:"eth_getStorageAt",params:[t,n,r||"latest"]})}case"eth_call":case"eth_estimateGas":{let[t,n]=e.params||[];return this.#r.request({method:e.method,params:[t,n||"latest"]})}case"eth_gasPrice":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":return this.#r.request({method:e.method,params:e.params||[]});case"im_signEjectionTransaction":{let t=await this.#l();if(!t)throw new te(4100,"Unauthorised - call eth_requestAccounts first");let n=trackFlow("passport","imSignEjectionTransaction");try{return await UI({params:e.params||[],ethSigner:this.#o,zkEvmAddress:t,flow:n})}catch(r){throw r instanceof Error?trackError("passport","imSignEjectionTransaction",r,{flowId:n.details.flowId}):n.addEvent("errored"),r}finally{n.addEvent("End");}}case"im_addSessionActivity":{let t=await this.#l();return t&&this.#h(t),null}default:throw new te(4200,"Method not supported")}}async request(e){try{return this.#p(e)}catch(t){throw t instanceof te?t:t instanceof Error?new te(-32603,t.message):new te(-32603,"Internal error")}}on(e,t){this.#t.on(e,t);}removeListener(e,t){this.#t.removeListener(e,t);}};var YP="Only sign this message from Immutable Passport";function ZP(s){let e=s.startsWith("0x")?s.slice(2):s,t=e.substring(0,64),n=e.substring(64,128),r=e.substring(128,130),i=parseInt(r,16),o=(i>=27?i-27:i).toString(16).padStart(2,"0");return `0x${t}${n}${o}`}async function zw({getUser:s,ethSigner:e,multiRollupApiClients:t,accessToken:n,rpcProvider:r,flow:i}){let a=e.getAddress();a.then(()=>i.addEvent("endGetAddress"));let o=e.signMessage(YP).then(ZP);o.then(()=>i.addEvent("endSignRaw"));let c=r.getChainId();c.then(()=>i.addEvent("endDetectNetwork"));let u=t.chainsApi.listChains();u.then(()=>i.addEvent("endListChains"));let[l,h,m,y]=await Promise.all([a,o,c,u]),g=Jt(Number(m)),w=y.data?.result?.find(S=>S.id===g)?.name;if(!w)throw new te(-32603,`Chain name does not exist for chain id ${m}`);try{let S=await t.passportApi.createCounterfactualAddressV2({chainName:w,createCounterfactualAddressRequest:{ethereum_address:l,ethereum_signature:h}},{headers:{Authorization:`Bearer ${n}`}});return i.addEvent("endCreateCounterfactualAddress"),s(!0).catch(()=>{}),S.data.counterfactual_address}catch(S){throw i.addEvent("errorRegisteringUser"),new te(-32603,`Failed to create counterfactual address: ${S}`)}}function LI(s,e){return e in s&&!!s[e]?.ethAddress}function jI(s,e){return s[e]?.ethAddress}var eh=class{#e;#s;#n;#t;#a;#i;#r;#u;isPassport=!0;constructor({getUser:e,chainConfig:t,multiRollupApiClients:n,guardianClient:r,ethSigner:i,passportEventEmitter:a}){let o=ac(t.chainId);if(o==="zkevm")throw new Error("SequenceProvider cannot be used for zkEVM chains. Use ZkEvmProvider instead.");this.#u=o,this.#e=e,this.#s=t,this.#n=n,this.#i=r,this.#r=i,this.#a=a,this.#t=createPublicClient({transport:http(this.#s.rpcUrl)});}async#c(){let e=await this.#e();if(e&&LI(e,this.#u))return jI(e,this.#u)}async#o(e){switch(e.method){case"eth_requestAccounts":{let t=await this.#c();if(t)return [t];let n=trackFlow("passport","ethRequestAccounts");try{let r=await this.#e();if(n.addEvent("endGetUser"),!r)throw new te(-32603,"User not authenticated");let i;if(LI(r,this.#u)?i=jI(r,this.#u):(n.addEvent("startUserRegistration"),i=await zw({getUser:this.#e,ethSigner:this.#r,multiRollupApiClients:this.#n,accessToken:r.accessToken,rpcProvider:this.#t,flow:n}),n.addEvent("endUserRegistration")),!i)throw new te(-32603,"Failed to get user address after registration");return this.#a.emit("accountsChanged",[i]),identify({passportId:r.profile.sub}),[i]}catch(r){throw r instanceof Error?trackError("passport","ethRequestAccounts",r,{flowId:n.details.flowId}):n.addEvent("errored"),r}finally{n.addEvent("End");}}case"eth_accounts":{let t=await this.#c();return t?[t]:[]}case"eth_sendTransaction":throw new te(4200,"eth_sendTransaction not yet implemented for this chain");case"personal_sign":throw new te(4200,"personal_sign not yet implemented for this chain");case"eth_signTypedData":case"eth_signTypedData_v4":throw new te(4200,"eth_signTypedData not yet implemented for this chain");case"eth_chainId":{let t=await this.#t.getChainId();return toHex(t)}case"eth_getBalance":case"eth_getCode":case"eth_getTransactionCount":{let[t,n]=e.params||[];return this.#t.request({method:e.method,params:[t,n||"latest"]})}case"eth_getStorageAt":{let[t,n,r]=e.params||[];return this.#t.request({method:"eth_getStorageAt",params:[t,n,r||"latest"]})}case"eth_call":case"eth_estimateGas":{let[t,n]=e.params||[];return this.#t.request({method:e.method,params:[t,n||"latest"]})}case"eth_gasPrice":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":return this.#t.request({method:e.method,params:e.params||[]});default:throw new te(4200,"Method not supported")}}async request(e){try{return this.#o(e)}catch(t){throw t instanceof te?t:t instanceof Error?new te(-32603,t.message):new te(-32603,"Internal error")}}on(e,t){this.#a.on(e,t);}removeListener(e,t){this.#a.removeListener(e,t);}};var th=class{passportDomain;zkEvmRpcUrl;relayerUrl;indexerMrBasePath;jsonRpcReferrer;forceScwDeployBeforeMessageSignature;crossSdkBridgeEnabled;feeTokenSymbol;constructor(e){this.passportDomain=e.passportDomain,this.zkEvmRpcUrl=e.zkEvmRpcUrl,this.relayerUrl=e.relayerUrl,this.indexerMrBasePath=e.indexerMrBasePath,this.jsonRpcReferrer=e.jsonRpcReferrer,this.forceScwDeployBeforeMessageSignature=e.forceScwDeployBeforeMessageSignature||!1,this.crossSdkBridgeEnabled=e.crossSdkBridgeEnabled||!1,this.feeTokenSymbol=e.feeTokenSymbol||"IMX";}};var Yw=async(s,e,t=!0,n=!0)=>{let r=trackFlow("passport",e,t);try{return await s(r)}catch(i){throw i instanceof Error?trackError("passport",e,i,{flowId:r.details.flowId}):r.addEvent("errored"),i}finally{n&&r.addEvent("End");}};var _I="ETH",aT=s=>s.reduce((e,t)=>`${e}${t.toString(16).padStart(2,"0")}`,""),oT=s=>{if(typeof TextEncoder<"u")return new TextEncoder().encode(s);let e=unescape(encodeURIComponent(s)),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t},cT=s=>{let e=oT(s),t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n="";for(let r=0;r<e.length;r+=3){let i=e[r],a=e[r+1],o=e[r+2],c=i<<16|(a??0)<<8|(o??0),u=c>>18&63,l=c>>12&63,h=c>>6&63,m=c&63;n+=t[u]+t[l],n+=Number.isFinite(a)?t[h]:"=",n+=Number.isFinite(o)?t[m]:"=";}return n},uc=class s{getUser;magicTeeApiClient;userWallet=null;createWalletPromise=null;constructor(e,t){this.getUser=e,this.magicTeeApiClient=t;}async getUserWallet(){let{userWallet:e}=this;e||(e=await this.createWallet());let t=await this.getUserOrThrow();if(t.profile.sub!==e.userIdentifier&&(e=await this.createWallet(t)),isUserZkEvm(t)&&t.zkEvm.userAdminAddress.toLowerCase()!==e.walletAddress.toLowerCase())throw new ze(`Wallet address mismatch.Rollup: zkEVM, TEE address: ${e.walletAddress}, profile address: ${t.zkEvm.userAdminAddress}`,"WALLET_CONNECTION_ERROR");return e}async createWallet(e){return this.createWalletPromise?this.createWalletPromise:(this.createWalletPromise=new Promise(async(t,n)=>{try{this.userWallet=null;let r=e||await this.getUserOrThrow(),i=s.getHeaders(r);await Yw(async a=>{try{let o=performance.now(),c=await this.magicTeeApiClient.walletApi.createWalletV1WalletPost({xMagicChain:_I},{headers:i});return trackDuration("passport",a.details.flowName,Math.round(performance.now()-o)),this.userWallet={userIdentifier:r.profile.sub,walletAddress:c.data.public_address},t(this.userWallet)}catch(o){let c="MagicTEE: Failed to initialise EOA";return Ji(o)?o.response?c+=` with status ${o.response.status}: ${JSON.stringify(o.response.data)}`:c+=`: ${o.message}`:c+=`: ${o.message}`,n(new Error(c))}},"magicCreateWallet");}catch(r){n(r);}finally{this.createWalletPromise=null;}}),this.createWalletPromise)}async getUserOrThrow(){let e=await this.getUser();if(!e)throw new ze("User has been logged out","NOT_LOGGED_IN_ERROR");return e}static getHeaders(e){if(!e)throw new ze("User has been logged out","NOT_LOGGED_IN_ERROR");return {Authorization:`Bearer ${e.idToken}`}}async getAddress(){return (await this.getUserWallet()).walletAddress}async signMessage(e){await this.getUserWallet();let t=e instanceof Uint8Array?`0x${aT(e)}`:e,n=await this.getUserOrThrow(),r=s.getHeaders(n);return Yw(async i=>{try{let a=performance.now(),o=await this.magicTeeApiClient.signOperationsApi.signMessageV1WalletSignMessagePost({signMessageRequest:{message_base64:cT(t)},xMagicChain:_I},{headers:r});return trackDuration("passport",i.details.flowName,Math.round(performance.now()-a)),o.data.signature}catch(a){let o="MagicTEE: Failed to sign message using EOA";throw Ji(a)?a.response?o+=` with status ${a.response.status}: ${JSON.stringify(a.response.data)}`:o+=`: ${a.message}`:o+=`: ${a.message}`,new Error(o)}},"magicSignMessage")}};var Zw={icon:'data:image/svg+xml,<svg viewBox="0 0 48 48" class="SvgIcon undefined Logo Logo--PassportSymbolOutlined css-1dn9atd" xmlns="http://www.w3.org/2000/svg"><g data-testid="undefined__g"><circle cx="24" cy="24" r="22.5" fill="url(%23paint0_radial_6324_83922)"></circle><circle cx="24" cy="24" r="22.5" fill="url(%23paint1_radial_6324_83922)"></circle><path d="M24 0C10.7452 0 0 10.7452 0 24C0 37.2548 10.7452 48 24 48C37.2548 48 48 37.2548 48 24C48 10.7452 37.2548 0 24 0ZM23.0718 9.16608C23.7383 8.83951 24.4406 8.86188 25.087 9.2287C27.3282 10.5059 29.5627 11.7942 31.786 13.096C32.5018 13.5165 32.8686 14.1897 32.8708 15.0173C32.8843 17.9184 32.8798 20.8171 32.8708 23.7182C32.8708 23.8255 32.8015 23.9821 32.7143 24.0335C31.8531 24.548 30.9808 25.0423 30.0347 25.5881V25.1318C30.0347 22.148 30.0257 19.1664 30.0414 16.1827C30.0436 15.6101 29.8468 15.241 29.339 14.9525C26.7377 13.474 24.1499 11.9687 21.5575 10.4723C21.4457 10.4075 21.3361 10.3381 21.1661 10.2352C21.8326 9.85722 22.4321 9.47698 23.0673 9.16608H23.0718ZM22.5953 38.8451C22.45 38.7713 22.3426 38.7198 22.2375 38.6595C18.8041 36.68 15.3752 34.687 11.9307 32.7232C10.9644 32.173 10.5238 31.3879 10.5349 30.2852C10.5551 27.9411 10.5484 25.597 10.5372 23.2507C10.5327 22.1927 10.9622 21.4255 11.8926 20.8977C14.3105 19.5221 16.715 18.1264 19.1195 16.7284C19.3275 16.6076 19.4796 16.5875 19.6965 16.7172C20.5264 17.216 21.3719 17.6924 22.2554 18.2024C22.0876 18.3031 21.9601 18.3791 21.8304 18.4552C19.2268 19.9582 16.6278 21.4658 14.0175 22.9599C13.5903 23.2037 13.3912 23.5213 13.3957 24.0179C13.4091 25.8654 13.4114 27.713 13.3957 29.5605C13.3912 30.0705 13.5948 30.3948 14.0332 30.6453C16.7866 32.2199 19.5288 33.8125 22.28 35.3916C22.5126 35.5258 22.611 35.6645 22.6065 35.9418C22.5864 36.888 22.5998 37.8363 22.5998 38.8473L22.5953 38.8451ZM22.5953 33.553C22.356 33.4166 22.1838 33.3204 22.0116 33.2198C19.8285 31.9605 17.6477 30.6967 15.4602 29.4464C15.2231 29.3122 15.1359 29.1668 15.1381 28.8917C15.1538 27.4714 15.1471 26.0511 15.1426 24.6308C15.1426 24.4384 15.1717 24.3064 15.3618 24.1991C16.167 23.7495 16.9633 23.2798 17.7618 22.8212C17.8199 22.7877 17.8826 22.7631 17.9877 22.7116V24.3064C17.9877 25.1698 18.0011 26.0354 17.9832 26.8988C17.972 27.3909 18.1622 27.7241 18.5916 27.9657C19.8285 28.6636 21.0498 29.3883 22.2867 30.0839C22.5305 30.2203 22.6043 30.3724 22.5998 30.6408C22.5842 31.5847 22.5931 32.5308 22.5931 33.5508L22.5953 33.553ZM20.0746 14.91C19.6116 14.6371 19.2157 14.6393 18.7527 14.91C16.1581 16.4265 13.5523 17.9228 10.9487 19.4259C10.8391 19.4908 10.7251 19.5489 10.5305 19.6541C10.5998 18.6654 10.3873 17.7327 10.7251 16.8291C10.9085 16.3348 11.2529 15.9635 11.7092 15.6995C13.8811 14.4447 16.0507 13.1877 18.227 11.9396C19.0211 11.4833 19.8308 11.4945 20.6248 11.953C23.0964 13.3756 25.5657 14.8026 28.0306 16.2341C28.1357 16.2945 28.2677 16.4309 28.2677 16.5338C28.2856 17.5493 28.2788 18.567 28.2788 19.6563C27.3819 19.1396 26.5543 18.6609 25.7267 18.1823C23.8412 17.093 21.9512 16.0149 20.0746 14.91ZM37.4427 30.8779C37.3778 31.6764 36.9103 32.2423 36.2192 32.6404C33.5732 34.1614 30.9294 35.6913 28.2856 37.2168C27.4557 37.6954 26.6259 38.1741 25.7938 38.6527C25.6932 38.7109 25.5903 38.7601 25.4539 38.8317C25.4449 38.693 25.4337 38.5924 25.4337 38.4917C25.4337 37.6149 25.4382 36.7404 25.4293 35.8636C25.4293 35.6645 25.4762 35.5437 25.6596 35.4386C29.5157 33.2198 33.3696 30.9942 37.2212 28.7709C37.2794 28.7374 37.3443 28.7105 37.4539 28.6591C37.4539 29.4375 37.4986 30.1622 37.4427 30.8779ZM37.4628 25.3577C37.4561 26.2658 36.9663 26.9033 36.1901 27.3506C33.175 29.0841 30.1622 30.8265 27.1493 32.5666C26.5991 32.8842 26.0466 33.1996 25.4561 33.5396C25.4472 33.3897 25.436 33.2913 25.436 33.1907C25.436 32.3273 25.4449 31.4617 25.4293 30.5983C25.4248 30.3523 25.5075 30.2226 25.72 30.0995C28.46 28.5271 31.1911 26.9368 33.9355 25.3733C34.4231 25.096 34.6378 24.7538 34.6334 24.1812C34.6132 21.1974 34.6244 18.2136 34.6244 15.2298V14.7087C35.3402 15.1404 36.0112 15.496 36.624 15.9299C37.1832 16.3258 37.465 16.9253 37.4673 17.6164C37.4762 20.1976 37.4829 22.7788 37.465 25.3599L37.4628 25.3577Z" fill="%230D0D0D"></path><path fill-rule="evenodd" d="M24 0C10.7452 0 0 10.7452 0 24C0 37.2548 10.7452 48 24 48C37.2548 48 48 37.2548 48 24C48 10.7452 37.2548 0 24 0ZM24 2C11.8497 2 2 11.8497 2 24C2 36.1503 11.8497 46 24 46C36.1503 46 46 36.1503 46 24C46 11.8497 36.1503 2 24 2Z" fill="url(%23paint2_radial_6324_83922)"></path><path fill-rule="evenodd" d="M24 0C10.7452 0 0 10.7452 0 24C0 37.2548 10.7452 48 24 48C37.2548 48 48 37.2548 48 24C48 10.7452 37.2548 0 24 0ZM24 2C11.8497 2 2 11.8497 2 24C2 36.1503 11.8497 46 24 46C36.1503 46 46 36.1503 46 24C46 11.8497 36.1503 2 24 2Z" fill="url(%23paint3_radial_6324_83922)"></path><defs><radialGradient id="paint0_radial_6324_83922" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(13.4442 13.3899) rotate(44.9817) scale(46.7487 99.1435)"><stop stop-color="%23A3EEF8"></stop><stop offset="0.177083" stop-color="%23A4DCF5"></stop><stop offset="0.380208" stop-color="%23A6AEEC"></stop><stop offset="1" stop-color="%23ECBEE1"></stop></radialGradient><radialGradient id="paint1_radial_6324_83922" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(25.9515 43.7068) rotate(84.265) scale(24.2138 46.3215)"><stop stop-color="%23FCF5EE"></stop><stop offset="0.715135" stop-color="%23ECBEE1" stop-opacity="0"></stop></radialGradient><radialGradient id="paint2_radial_6324_83922" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(12.7405 12.6825) rotate(44.9817) scale(49.8653 105.753)"><stop stop-color="%23A3EEF8"></stop><stop offset="0.177083" stop-color="%23A4DCF5"></stop><stop offset="0.380208" stop-color="%23A6AEEC"></stop><stop offset="1" stop-color="%23ECBEE1"></stop></radialGradient><radialGradient id="paint3_radial_6324_83922" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(26.0816 45.0206) rotate(84.265) scale(25.828 49.4096)"><stop stop-color="%23FCF5EE"></stop><stop offset="0.715135" stop-color="%23ECBEE1" stop-opacity="0"></stop></radialGradient></defs></g></svg>',name:"Immutable Passport",rdns:"com.immutable.passport",uuid:"3f0259bb-54c0-4ff0-85f2-6bb7c2d8b6c8"};function Qw(s){if(typeof window>"u")return;let e=new CustomEvent("eip6963:announceProvider",{detail:Object.freeze(s)});window.dispatchEvent(e);let t=()=>window.dispatchEvent(e);window.addEventListener("eip6963:requestProvider",t);}var xa={};be(xa,{IdentitySigner:()=>Pg,toIdentityAuthKey:()=>cx});var at={};be(at,{format:()=>ET,from:()=>AT});var MI="1.1.0";var lt=class s extends Error{constructor(e,t={}){let n=t.cause instanceof s?t.cause.details:t.cause?.message?t.cause.message:t.details,r=t.cause instanceof s&&t.cause.docsPath||t.docsPath,i=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...r?[`Docs: https://abitype.dev${r}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${MI}`].join(`
|
|
338
|
+
`);super(i),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),t.cause&&(this.cause=t.cause),this.details=n,this.docsPath=r,this.metaMessages=t.metaMessages,this.shortMessage=e;}};function ms(s,e){return s.exec(e)?.groups}var Xw=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,eb=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,O0=/^\(.+?\).*?$/;var $I=/^tuple(?<array>(\[(\d*)\])*)$/;function R0(s){let e=s.type;if($I.test(s.type)&&"components"in s){e="(";let t=s.components.length;for(let r=0;r<t;r++){let i=s.components[r];e+=R0(i),r<t-1&&(e+=", ");}let n=ms($I,s.type);return e+=`)${n?.array??""}`,R0({...s,type:e})}return "indexed"in s&&s.indexed&&(e=`${e} indexed`),s.name?`${e} ${s.name}`:e}function nn(s){let e="",t=s.length;for(let n=0;n<t;n++){let r=s[n];e+=R0(r),n!==t-1&&(e+=", ");}return e}function vn(s){return s.type==="function"?`function ${s.name}(${nn(s.inputs)})${s.stateMutability&&s.stateMutability!=="nonpayable"?` ${s.stateMutability}`:""}${s.outputs?.length?` returns (${nn(s.outputs)})`:""}`:s.type==="event"?`event ${s.name}(${nn(s.inputs)})`:s.type==="error"?`error ${s.name}(${nn(s.inputs)})`:s.type==="constructor"?`constructor(${nn(s.inputs)})${s.stateMutability==="payable"?" payable":""}`:s.type==="fallback"?`fallback() external${s.stateMutability==="payable"?" payable":""}`:"receive() external payable"}function tb(s){let e=[],t=s.length;for(let n=0;n<t;n++){let r=s[n],i=vn(r);e.push(i);}return e}var qI=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function FI(s){return qI.test(s)}function KI(s){return ms(qI,s)}var GI=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function WI(s){return GI.test(s)}function JI(s){return ms(GI,s)}var zI=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function YI(s){return zI.test(s)}function ZI(s){return ms(zI,s)}var QI=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function xr(s){return QI.test(s)}function XI(s){return ms(QI,s)}var e3=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function t3(s){return e3.test(s)}function s3(s){return ms(e3,s)}var n3=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function r3(s){return n3.test(s)}function i3(s){return ms(n3,s)}var uT=/^receive\(\) external payable$/;function a3(s){return uT.test(s)}var sb=new Set(["memory","indexed","storage","calldata"]),o3=new Set(["indexed"]),V0=new Set(["calldata","memory","storage"]);var D0=class extends lt{constructor({signature:e}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"});}},U0=class extends lt{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"});}},L0=class extends lt{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"});}};var j0=class extends lt{constructor({params:e}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"});}},H0=class extends lt{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"});}},_0=class extends lt{constructor({param:e,name:t}){super("Invalid ABI parameter.",{details:e,metaMessages:[`"${t}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"});}},M0=class extends lt{constructor({param:e,type:t,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${t?` in "${t}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"});}},$0=class extends lt{constructor({param:e,type:t,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${t?` in "${t}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"});}},q0=class extends lt{constructor({abiParameter:e}){super("Invalid ABI parameter.",{details:JSON.stringify(e,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"});}};var rn=class extends lt{constructor({signature:e,type:t}){super(`Invalid ${t} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"});}},F0=class extends lt{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"});}},K0=class extends lt{constructor({signature:e}){super("Invalid struct signature.",{details:e,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"});}};var G0=class extends lt{constructor({type:e}){super("Circular reference detected.",{metaMessages:[`Struct "${e}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"});}};var W0=class extends lt{constructor({current:e,depth:t}){super("Unbalanced parentheses.",{metaMessages:[`"${e.trim()}" has too many ${t>0?"opening":"closing"} parentheses.`],details:`Depth "${t}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"});}};function c3(s,e,t){let n="";if(t)for(let r of Object.entries(t)){if(!r)continue;let i="";for(let a of r[1])i+=`[${a.type}${a.name?`:${a.name}`:""}]`;n+=`(${r[0]}{${i}})`;}return e?`${e}:${s}${n}`:s}var J0=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]]);function sh(s,e={}){if(YI(s))return lT(s,e);if(WI(s))return hT(s,e);if(FI(s))return fT(s,e);if(t3(s))return dT(s,e);if(r3(s))return mT(s);if(a3(s))return {type:"receive",stateMutability:"payable"};throw new F0({signature:s})}function lT(s,e={}){let t=ZI(s);if(!t)throw new rn({signature:s,type:"function"});let n=as(t.parameters),r=[],i=n.length;for(let o=0;o<i;o++)r.push(Rs(n[o],{modifiers:V0,structs:e,type:"function"}));let a=[];if(t.returns){let o=as(t.returns),c=o.length;for(let u=0;u<c;u++)a.push(Rs(o[u],{modifiers:V0,structs:e,type:"function"}));}return {name:t.name,type:"function",stateMutability:t.stateMutability??"nonpayable",inputs:r,outputs:a}}function hT(s,e={}){let t=JI(s);if(!t)throw new rn({signature:s,type:"event"});let n=as(t.parameters),r=[],i=n.length;for(let a=0;a<i;a++)r.push(Rs(n[a],{modifiers:o3,structs:e,type:"event"}));return {name:t.name,type:"event",inputs:r}}function fT(s,e={}){let t=KI(s);if(!t)throw new rn({signature:s,type:"error"});let n=as(t.parameters),r=[],i=n.length;for(let a=0;a<i;a++)r.push(Rs(n[a],{structs:e,type:"error"}));return {name:t.name,type:"error",inputs:r}}function dT(s,e={}){let t=s3(s);if(!t)throw new rn({signature:s,type:"constructor"});let n=as(t.parameters),r=[],i=n.length;for(let a=0;a<i;a++)r.push(Rs(n[a],{structs:e,type:"constructor"}));return {type:"constructor",stateMutability:t.stateMutability??"nonpayable",inputs:r}}function mT(s){let e=i3(s);if(!e)throw new rn({signature:s,type:"fallback"});return {type:"fallback",stateMutability:e.stateMutability??"nonpayable"}}var pT=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,gT=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,yT=/^u?int$/;function Rs(s,e){let t=c3(s,e?.type,e?.structs);if(J0.has(t))return J0.get(t);let n=O0.test(s),r=ms(n?gT:pT,s);if(!r)throw new H0({param:s});if(r.name&&bT(r.name))throw new _0({param:s,name:r.name});let i=r.name?{name:r.name}:{},a=r.modifier==="indexed"?{indexed:!0}:{},o=e?.structs??{},c,u={};if(n){c="tuple";let h=as(r.type),m=[],y=h.length;for(let g=0;g<y;g++)m.push(Rs(h[g],{structs:o}));u={components:m};}else if(r.type in o)c="tuple",u={components:o[r.type]};else if(yT.test(r.type))c=`${r.type}256`;else if(r.type==="address payable")c="address";else if(c=r.type,e?.type!=="struct"&&!nb(c))throw new L0({type:c});if(r.modifier){if(!e?.modifiers?.has?.(r.modifier))throw new M0({param:s,type:e?.type,modifier:r.modifier});if(V0.has(r.modifier)&&!ST(c,!!r.array))throw new $0({param:s,type:e?.type,modifier:r.modifier})}let l={type:`${c}${r.array??""}`,...i,...a,...u};return J0.set(t,l),l}function as(s,e=[],t="",n=0){let r=s.trim().length;for(let i=0;i<r;i++){let a=s[i],o=s.slice(i+1);switch(a){case",":return n===0?as(o,[...e,t.trim()]):as(o,e,`${t}${a}`,n);case"(":return as(o,e,`${t}${a}`,n+1);case")":return as(o,e,`${t}${a}`,n-1);default:return as(o,e,`${t}${a}`,n)}}if(t==="")return e;if(n!==0)throw new W0({current:t,depth:n});return e.push(t.trim()),e}function nb(s){return s==="address"||s==="bool"||s==="function"||s==="string"||Xw.test(s)||eb.test(s)}var wT=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;function bT(s){return s==="address"||s==="bool"||s==="function"||s==="string"||s==="tuple"||Xw.test(s)||eb.test(s)||wT.test(s)}function ST(s,e){return e||s==="bytes"||s==="string"||s==="tuple"}function lc(s){let e={},t=s.length;for(let a=0;a<t;a++){let o=s[a];if(!xr(o))continue;let c=XI(o);if(!c)throw new rn({signature:o,type:"struct"});let u=c.properties.split(";"),l=[],h=u.length;for(let m=0;m<h;m++){let g=u[m].trim();if(!g)continue;let w=Rs(g,{type:"struct"});l.push(w);}if(!l.length)throw new K0({signature:o});e[c.name]=l;}let n={},r=Object.entries(e),i=r.length;for(let a=0;a<i;a++){let[o,c]=r[a];n[o]=u3(c,e);}return n}var vT=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function u3(s,e,t=new Set){let n=[],r=s.length;for(let i=0;i<r;i++){let a=s[i];if(O0.test(a.type))n.push(a);else {let c=ms(vT,a.type);if(!c?.type)throw new q0({abiParameter:a});let{array:u,type:l}=c;if(l in e){if(t.has(l))throw new G0({type:l});n.push({...a,type:`tuple${u??""}`,components:u3(e[l]??[],e,new Set([...t,l]))});}else if(nb(l))n.push(a);else throw new U0({type:l})}}return n}function rb(s){let e=lc(s),t=[],n=s.length;for(let r=0;r<n;r++){let i=s[r];xr(i)||t.push(sh(i,e));}return t}function z0(s){let e;if(typeof s=="string")e=sh(s);else {let t=lc(s),n=s.length;for(let r=0;r<n;r++){let i=s[r];if(!xr(i)){e=sh(i,t);break}}}if(!e)throw new D0({signature:s});return e}function Y0(s){let e=[];if(typeof s=="string"){let t=as(s),n=t.length;for(let r=0;r<n;r++)e.push(Rs(t[r],{modifiers:sb}));}else {let t=lc(s),n=s.length;for(let r=0;r<n;r++){let i=s[r];if(xr(i))continue;let a=as(i),o=a.length;for(let c=0;c<o;c++)e.push(Rs(a[c],{modifiers:sb,structs:t}));}}if(e.length===0)throw new j0({params:s});return e}function l3(s){for(let e of s)if(typeof e!="string")return !1;return !0}function ET(s){return tb(s)}function AT(s){return l3(s)?rb(s):s}var h3="0.1.1";function f3(){return h3}var K=class s extends Error{static setStaticOptions(e){s.prototype.docsOrigin=e.docsOrigin,s.prototype.showVersion=e.showVersion,s.prototype.version=e.version;}constructor(e,t={}){let n=(()=>{if(t.cause instanceof s){if(t.cause.details)return t.cause.details;if(t.cause.shortMessage)return t.cause.shortMessage}return t.cause&&"details"in t.cause&&typeof t.cause.details=="string"?t.cause.details:t.cause?.message?t.cause.message:t.details})(),r=t.cause instanceof s&&t.cause.docsPath||t.docsPath,i=t.docsOrigin??s.prototype.docsOrigin,a=`${i}${r??""}`,o=!!(t.version??s.prototype.showVersion),c=t.version??s.prototype.version,u=[e||"An error occurred.",...t.metaMessages?["",...t.metaMessages]:[],...n||r||o?["",n?`Details: ${n}`:void 0,r?`See: ${a}`:void 0,o?`Version: ${c}`:void 0]:[]].filter(l=>typeof l=="string").join(`
|
|
339
|
+
`);super(u,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsOrigin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"showVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.cause=t.cause,this.details=n,this.docs=a,this.docsOrigin=i,this.docsPath=r,this.shortMessage=e,this.showVersion=o,this.version=c;}walk(e){return d3(this,e)}};Object.defineProperty(K,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${f3()}`}});K.setStaticOptions(K.defaultStaticOptions);function d3(s,e){return e?.(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause?d3(s.cause,e):e?null:s}var oe={};be(oe,{keccak256:()=>dt,ripemd160:()=>m4,sha256:()=>wh,validate:()=>Ob});var zi=xn&&typeof xn=="object"&&"webcrypto"in xn?xn.webcrypto:xn&&typeof xn=="object"&&"randomBytes"in xn?xn:void 0;function IT(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Yi(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function an(s,...e){if(!IT(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function m3(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Yi(s.outputLen),Yi(s.blockLen);}function En(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Q0(s,e){an(s);let t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function p3(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function zt(...s){for(let e=0;e<s.length;e++)s[e].fill(0);}function X0(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Vs(s,e){return s<<32-e|s>>>e}function nh(s,e){return s<<e|s>>>32-e>>>0}var CT=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function NT(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function kT(s){for(let e=0;e<s.length;e++)s[e]=NT(s[e]);return s}var ib=CT?s=>s:kT;function PT(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function Zi(s){return typeof s=="string"&&(s=PT(s)),an(s),s}function g3(...s){let e=0;for(let n=0;n<s.length;n++){let r=s[n];an(r),e+=r.length;}let t=new Uint8Array(e);for(let n=0,r=0;n<s.length;n++){let i=s[n];t.set(i,r),r+=i.length;}return t}var Er=class{};function Ar(s){let e=n=>s().update(Zi(n)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function y3(s=32){if(zi&&typeof zi.getRandomValues=="function")return zi.getRandomValues(new Uint8Array(s));if(zi&&typeof zi.randomBytes=="function")return Uint8Array.from(zi.randomBytes(s));throw new Error("crypto.getRandomValues must be defined")}function TT(s,e,t,n){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,n);let r=BigInt(32),i=BigInt(4294967295),a=Number(t>>r&i),o=Number(t&i),c=n?4:0,u=n?0:4;s.setUint32(e+c,a,n),s.setUint32(e+u,o,n);}function ab(s,e,t){return s&e^~s&t}function ob(s,e,t){return s&e^s&t^e&t}var Qi=class extends Er{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=X0(this.buffer);}update(e){En(this),e=Zi(e),an(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let c=X0(e);for(;r<=i-a;a+=r)this.process(c,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){En(this),Q0(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,zt(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let h=a;h<r;h++)t[h]=0;TT(n,r-8,BigInt(this.length*8),i),this.process(n,0);let o=X0(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)o.setUint32(4*h,l[h],i);}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},An=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Tt=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Bt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var BT=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),b3=Uint8Array.from(new Array(16).fill(0).map((s,e)=>e)),OT=b3.map(s=>(9*s+5)%16),S3=(()=>{let t=[[b3],[OT]];for(let n=0;n<4;n++)for(let r of t)r.push(r[n].map(i=>BT[i]));return t})(),v3=S3[0],x3=S3[1],E3=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(s=>Uint8Array.from(s)),RT=v3.map((s,e)=>s.map(t=>E3[e][t])),VT=x3.map((s,e)=>s.map(t=>E3[e][t])),DT=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),UT=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function w3(s,e,t,n){return s===0?e^t^n:s===1?e&t|~e&n:s===2?(e|~t)^n:s===3?e&n|t&~n:e^(t|~n)}var ep=new Uint32Array(16),tp=class extends Qi{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776;}get(){let{h0:e,h1:t,h2:n,h3:r,h4:i}=this;return [e,t,n,r,i]}set(e,t,n,r,i){this.h0=e|0,this.h1=t|0,this.h2=n|0,this.h3=r|0,this.h4=i|0;}process(e,t){for(let y=0;y<16;y++,t+=4)ep[y]=e.getUint32(t,!0);let n=this.h0|0,r=n,i=this.h1|0,a=i,o=this.h2|0,c=o,u=this.h3|0,l=u,h=this.h4|0,m=h;for(let y=0;y<5;y++){let g=4-y,w=DT[y],S=UT[y],C=v3[y],k=x3[y],x=RT[y],v=VT[y];for(let I=0;I<16;I++){let D=nh(n+w3(y,i,o,u)+ep[C[I]]+w,x[I])+h|0;n=h,h=u,u=nh(o,10)|0,o=i,i=D;}for(let I=0;I<16;I++){let D=nh(r+w3(g,a,c,l)+ep[k[I]]+S,v[I])+m|0;r=m,m=l,l=nh(c,10)|0,c=a,a=D;}}this.set(this.h1+o+l|0,this.h2+u+m|0,this.h3+h+r|0,this.h4+n+a|0,this.h0+i+c|0);}roundClean(){zt(ep);}destroy(){this.destroyed=!0,zt(this.buffer),this.set(0,0,0,0,0);}},A3=Ar(()=>new tp);var I3=A3;var sp=BigInt(4294967295),C3=BigInt(32);function LT(s,e=!1){return e?{h:Number(s&sp),l:Number(s>>C3&sp)}:{h:Number(s>>C3&sp)|0,l:Number(s&sp)|0}}function np(s,e=!1){let t=s.length,n=new Uint32Array(t),r=new Uint32Array(t);for(let i=0;i<t;i++){let{h:a,l:o}=LT(s[i],e);[n[i],r[i]]=[a,o];}return [n,r]}var cb=(s,e,t)=>s>>>t,ub=(s,e,t)=>s<<32-t|e>>>t,Xi=(s,e,t)=>s>>>t|e<<32-t,ea=(s,e,t)=>s<<32-t|e>>>t,rh=(s,e,t)=>s<<64-t|e>>>t-32,ih=(s,e,t)=>s>>>t-32|e<<64-t;var N3=(s,e,t)=>s<<t|e>>>32-t,k3=(s,e,t)=>e<<t|s>>>32-t,P3=(s,e,t)=>e<<t-32|s>>>64-t,T3=(s,e,t)=>s<<t-32|e>>>64-t;function on(s,e,t,n){let r=(e>>>0)+(n>>>0);return {h:s+t+(r/2**32|0)|0,l:r|0}}var B3=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),O3=(s,e,t,n)=>e+t+n+(s/2**32|0)|0,R3=(s,e,t,n)=>(s>>>0)+(e>>>0)+(t>>>0)+(n>>>0),V3=(s,e,t,n,r)=>e+t+n+r+(s/2**32|0)|0,D3=(s,e,t,n,r)=>(s>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),U3=(s,e,t,n,r,i)=>e+t+n+r+i+(s/2**32|0)|0;var HT=BigInt(0),ah=BigInt(1),_T=BigInt(2),MT=BigInt(7),$T=BigInt(256),qT=BigInt(113),H3=[],_3=[],M3=[];for(let s=0,e=ah,t=1,n=0;s<24;s++){[t,n]=[n,(2*t+3*n)%5],H3.push(2*(5*n+t)),_3.push((s+1)*(s+2)/2%64);let r=HT;for(let i=0;i<7;i++)e=(e<<ah^(e>>MT)*qT)%$T,e&_T&&(r^=ah<<(ah<<BigInt(i))-ah);M3.push(r);}var $3=np(M3,!0),FT=$3[0],KT=$3[1],L3=(s,e,t)=>t>32?P3(s,e,t):N3(s,e,t),j3=(s,e,t)=>t>32?T3(s,e,t):k3(s,e,t);function GT(s,e=24){let t=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let a=0;a<10;a++)t[a]=s[a]^s[a+10]^s[a+20]^s[a+30]^s[a+40];for(let a=0;a<10;a+=2){let o=(a+8)%10,c=(a+2)%10,u=t[c],l=t[c+1],h=L3(u,l,1)^t[o],m=j3(u,l,1)^t[o+1];for(let y=0;y<50;y+=10)s[a+y]^=h,s[a+y+1]^=m;}let r=s[2],i=s[3];for(let a=0;a<24;a++){let o=_3[a],c=L3(r,i,o),u=j3(r,i,o),l=H3[a];r=s[l],i=s[l+1],s[l]=c,s[l+1]=u;}for(let a=0;a<50;a+=10){for(let o=0;o<10;o++)t[o]=s[a+o];for(let o=0;o<10;o++)s[a+o]^=~t[(o+2)%10]&t[(o+4)%10];}s[0]^=FT[n],s[1]^=KT[n];}zt(t);}var lb=class s extends Er{constructor(e,t,n,r=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=i,Yi(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=p3(this.state);}clone(){return this._cloneInto()}keccak(){ib(this.state32),GT(this.state32,this.rounds),ib(this.state32),this.posOut=0,this.pos=0;}update(e){En(this),e=Zi(e),an(e);let{blockLen:t,state:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(t-this.pos,r-i);for(let o=0;o<a;o++)n[this.pos++]^=e[i++];this.pos===t&&this.keccak();}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,t&128&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak();}writeInto(e){En(this,!1),an(e),this.finish();let t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();let a=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+a),r),this.posOut+=a,r+=a;}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Yi(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Q0(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,zt(this.state);}_cloneInto(e){let{blockLen:t,suffix:n,outputLen:r,rounds:i,enableXOF:a}=this;return e||(e=new s(t,n,r,a,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=a,e.destroyed=this.destroyed,e}},WT=(s,e,t)=>Ar(()=>new lb(e,s,t));var q3=WT(1,136,256/8);var JT=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ir=new Uint32Array(64),rp=class extends Qi{constructor(e=32){super(64,e,8,!1),this.A=An[0]|0,this.B=An[1]|0,this.C=An[2]|0,this.D=An[3]|0,this.E=An[4]|0,this.F=An[5]|0,this.G=An[6]|0,this.H=An[7]|0;}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:c}=this;return [e,t,n,r,i,a,o,c]}set(e,t,n,r,i,a,o,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=c|0;}process(e,t){for(let h=0;h<16;h++,t+=4)Ir[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let m=Ir[h-15],y=Ir[h-2],g=Vs(m,7)^Vs(m,18)^m>>>3,w=Vs(y,17)^Vs(y,19)^y>>>10;Ir[h]=w+Ir[h-7]+g+Ir[h-16]|0;}let{A:n,B:r,C:i,D:a,E:o,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){let m=Vs(o,6)^Vs(o,11)^Vs(o,25),y=l+m+ab(o,c,u)+JT[h]+Ir[h]|0,w=(Vs(n,2)^Vs(n,13)^Vs(n,22))+ob(n,r,i)|0;l=u,u=c,c=o,o=a+y|0,a=i,i=r,r=n,n=y+w|0;}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,c,u,l);}roundClean(){zt(Ir);}destroy(){this.set(0,0,0,0,0,0,0,0),zt(this.buffer);}};var F3=np(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(s=>BigInt(s))),zT=F3[0],YT=F3[1],Cr=new Uint32Array(80),Nr=new Uint32Array(80),ip=class extends Qi{constructor(e=64){super(128,e,16,!1),this.Ah=Bt[0]|0,this.Al=Bt[1]|0,this.Bh=Bt[2]|0,this.Bl=Bt[3]|0,this.Ch=Bt[4]|0,this.Cl=Bt[5]|0,this.Dh=Bt[6]|0,this.Dl=Bt[7]|0,this.Eh=Bt[8]|0,this.El=Bt[9]|0,this.Fh=Bt[10]|0,this.Fl=Bt[11]|0,this.Gh=Bt[12]|0,this.Gl=Bt[13]|0,this.Hh=Bt[14]|0,this.Hl=Bt[15]|0;}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:a,Dh:o,Dl:c,Eh:u,El:l,Fh:h,Fl:m,Gh:y,Gl:g,Hh:w,Hl:S}=this;return [e,t,n,r,i,a,o,c,u,l,h,m,y,g,w,S]}set(e,t,n,r,i,a,o,c,u,l,h,m,y,g,w,S){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=a|0,this.Dh=o|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=m|0,this.Gh=y|0,this.Gl=g|0,this.Hh=w|0,this.Hl=S|0;}process(e,t){for(let x=0;x<16;x++,t+=4)Cr[x]=e.getUint32(t),Nr[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let v=Cr[x-15]|0,I=Nr[x-15]|0,D=Xi(v,I,1)^Xi(v,I,8)^cb(v,I,7),F=ea(v,I,1)^ea(v,I,8)^ub(v,I,7),M=Cr[x-2]|0,W=Nr[x-2]|0,ne=Xi(M,W,19)^rh(M,W,61)^cb(M,W,6),q=ea(M,W,19)^ih(M,W,61)^ub(M,W,6),J=R3(F,q,Nr[x-7],Nr[x-16]),ae=V3(J,D,ne,Cr[x-7],Cr[x-16]);Cr[x]=ae|0,Nr[x]=J|0;}let{Ah:n,Al:r,Bh:i,Bl:a,Ch:o,Cl:c,Dh:u,Dl:l,Eh:h,El:m,Fh:y,Fl:g,Gh:w,Gl:S,Hh:C,Hl:k}=this;for(let x=0;x<80;x++){let v=Xi(h,m,14)^Xi(h,m,18)^rh(h,m,41),I=ea(h,m,14)^ea(h,m,18)^ih(h,m,41),D=h&y^~h&w,F=m&g^~m&S,M=D3(k,I,F,YT[x],Nr[x]),W=U3(M,C,v,D,zT[x],Cr[x]),ne=M|0,q=Xi(n,r,28)^rh(n,r,34)^rh(n,r,39),J=ea(n,r,28)^ih(n,r,34)^ih(n,r,39),ae=n&i^n&o^i&o,Be=r&a^r&c^a&c;C=w|0,k=S|0,w=y|0,S=g|0,y=h|0,g=m|0,{h,l:m}=on(u|0,l|0,W|0,ne|0),u=o|0,l=c|0,o=i|0,c=a|0,i=n|0,a=r|0;let L=B3(ne,J,Be);n=O3(L,W,q,ae),r=L|0;}(({h:n,l:r}=on(this.Ah|0,this.Al|0,n|0,r|0))),{h:i,l:a}=on(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:c}=on(this.Ch|0,this.Cl|0,o|0,c|0),{h:u,l}=on(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:m}=on(this.Eh|0,this.El|0,h|0,m|0),{h:y,l:g}=on(this.Fh|0,this.Fl|0,y|0,g|0),{h:w,l:S}=on(this.Gh|0,this.Gl|0,w|0,S|0),{h:C,l:k}=on(this.Hh|0,this.Hl|0,C|0,k|0),this.set(n,r,i,a,o,c,u,l,h,m,y,g,w,S,C,k);}roundClean(){zt(Cr,Nr);}destroy(){zt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},hb=class extends ip{constructor(){super(48),this.Ah=Tt[0]|0,this.Al=Tt[1]|0,this.Bh=Tt[2]|0,this.Bl=Tt[3]|0,this.Ch=Tt[4]|0,this.Cl=Tt[5]|0,this.Dh=Tt[6]|0,this.Dl=Tt[7]|0,this.Eh=Tt[8]|0,this.El=Tt[9]|0,this.Fh=Tt[10]|0,this.Fl=Tt[11]|0,this.Gh=Tt[12]|0,this.Gl=Tt[13]|0,this.Hh=Tt[14]|0,this.Hl=Tt[15]|0;}};var hc=Ar(()=>new rp);var K3=Ar(()=>new ip),G3=Ar(()=>new hb);var W3=hc;var f={};be(f,{InvalidBytesBooleanError:()=>hp,InvalidBytesTypeError:()=>oa,SizeExceedsPaddingSizeError:()=>hh,SizeOverflowError:()=>lh,SliceOffsetOutOfBoundsError:()=>pc,assert:()=>o6,concat:()=>Nb,from:()=>Pn,fromArray:()=>c6,fromBoolean:()=>l4,fromHex:()=>Ye,fromNumber:()=>h4,fromString:()=>Tn,isEqual:()=>f4,padLeft:()=>u6,padRight:()=>l6,random:()=>Cb,size:()=>ps,slice:()=>kb,toBigInt:()=>Pb,toBoolean:()=>Tb,toHex:()=>d4,toNumber:()=>Ls,toString:()=>fp,trimLeft:()=>dp,trimRight:()=>lp,validate:()=>Bb});var pb=BigInt(0),mb=BigInt(1);function fc(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function gb(s){if(!fc(s))throw new Error("Uint8Array expected")}function dc(s,e){if(typeof e!="boolean")throw new Error(s+" boolean expected, got "+e)}function oh(s){let e=s.toString(16);return e.length&1?"0"+e:e}function Y3(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?pb:BigInt("0x"+s)}var Z3=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ZT=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function mc(s){if(gb(s),Z3)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=ZT[s[t]];return e}var In={_0:48,_9:57,A:65,F:70,a:97,f:102};function J3(s){if(s>=In._0&&s<=In._9)return s-In._0;if(s>=In.A&&s<=In.F)return s-(In.A-10);if(s>=In.a&&s<=In.f)return s-(In.a-10)}function ch(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Z3)return Uint8Array.fromHex(s);let e=s.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let r=0,i=0;r<t;r++,i+=2){let a=J3(s.charCodeAt(i)),o=J3(s.charCodeAt(i+1));if(a===void 0||o===void 0){let c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[r]=a*16+o;}return n}function Cn(s){return Y3(mc(s))}function yb(s){return gb(s),Y3(mc(Uint8Array.from(s).reverse()))}function ta(s,e){return ch(s.toString(16).padStart(e*2,"0"))}function wb(s,e){return ta(s,e).reverse()}function os(s,e,t){let n;if(typeof e=="string")try{n=ch(e);}catch(i){throw new Error(s+" must be hex string or Uint8Array, cause: "+i)}else if(fc(e))n=Uint8Array.from(e);else throw new Error(s+" must be hex string or Uint8Array");let r=n.length;if(typeof t=="number"&&r!==t)throw new Error(s+" of length "+t+" expected, got "+r);return n}function uh(...s){let e=0;for(let n=0;n<s.length;n++){let r=s[n];gb(r),e+=r.length;}let t=new Uint8Array(e);for(let n=0,r=0;n<s.length;n++){let i=s[n];t.set(i,r),r+=i.length;}return t}function ap(s,e){if(s.length!==e.length)return !1;let t=0;for(let n=0;n<s.length;n++)t|=s[n]^e[n];return t===0}var fb=s=>typeof s=="bigint"&&pb<=s;function op(s,e,t){return fb(s)&&fb(e)&&fb(t)&&e<=s&&s<t}function sa(s,e,t,n){if(!op(e,t,n))throw new Error("expected valid "+s+": "+t+" <= n < "+n+", got "+e)}function Q3(s){let e;for(e=0;s>pb;s>>=mb,e+=1);return e}var na=s=>(mb<<BigInt(s))-mb,db=s=>new Uint8Array(s),z3=s=>Uint8Array.from(s);function X3(s,e,t){if(typeof s!="number"||s<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=db(s),r=db(s),i=0,a=()=>{n.fill(1),r.fill(0),i=0;},o=(...h)=>t(r,n,...h),c=(h=db(0))=>{r=o(z3([0]),h),n=o(),h.length!==0&&(r=o(z3([1]),h),n=o());},u=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,m=[];for(;h<e;){n=o();let y=n.slice();m.push(y),h+=n.length;}return uh(...m)};return (h,m)=>{a(),c(h);let y;for(;!(y=m(u()));)c();return a(),y}}var QT={bigint:s=>typeof s=="bigint",function:s=>typeof s=="function",boolean:s=>typeof s=="boolean",string:s=>typeof s=="string",stringOrUint8Array:s=>typeof s=="string"||fc(s),isSafeInteger:s=>Number.isSafeInteger(s),array:s=>Array.isArray(s),field:(s,e)=>e.Fp.isValid(s),hash:s=>typeof s=="function"&&Number.isSafeInteger(s.outputLen)};function ra(s,e,t={}){let n=(r,i,a)=>{let o=QT[i];if(typeof o!="function")throw new Error("invalid validator function");let c=s[r];if(!(a&&c===void 0)&&!o(c,s))throw new Error("param "+String(r)+" is invalid. Expected "+i+", got "+c)};for(let[r,i]of Object.entries(e))n(r,i,!1);for(let[r,i]of Object.entries(t))n(r,i,!0);return s}function bb(s){let e=new WeakMap;return (t,...n)=>{let r=e.get(t);if(r!==void 0)return r;let i=s(t,...n);return e.set(t,i),i}}var E={};be(E,{IntegerOutOfRangeError:()=>wc,InvalidHexBooleanError:()=>cp,InvalidHexTypeError:()=>mh,InvalidHexValueError:()=>ph,InvalidLengthError:()=>gh,SizeExceedsPaddingSizeError:()=>dh,SizeOverflowError:()=>fh,SliceOffsetOutOfBoundsError:()=>gc,assert:()=>a6,concat:()=>Fe,from:()=>Yt,fromBoolean:()=>yh,fromBytes:()=>Ee,fromNumber:()=>le,fromString:()=>cs,isEqual:()=>s4,padLeft:()=>cn,padRight:()=>Us,random:()=>n4,size:()=>Oe,slice:()=>rt,toBigInt:()=>up,toBoolean:()=>i4,toBytes:()=>a4,toNumber:()=>Ib,toString:()=>o4,trimLeft:()=>aa,trimRight:()=>r4,validate:()=>Zt});function kn(s,e){if(ps(s)>e)throw new lh({givenSize:ps(s),maxSize:e})}function e6(s,e){if(typeof e=="number"&&e>0&&e>ps(s)-1)throw new pc({offset:e,position:"start",size:ps(s)})}function t6(s,e,t){if(typeof e=="number"&&typeof t=="number"&&ps(s)!==t-e)throw new pc({offset:t,position:"end",size:ps(s)})}var Nn={zero:48,nine:57,A:65,F:70,a:97,f:102};function Sb(s){if(s>=Nn.zero&&s<=Nn.nine)return s-Nn.zero;if(s>=Nn.A&&s<=Nn.F)return s-(Nn.A-10);if(s>=Nn.a&&s<=Nn.f)return s-(Nn.a-10)}function vb(s,e={}){let{dir:t,size:n=32}=e;if(n===0)return s;if(s.length>n)throw new hh({size:s.length,targetSize:n,type:"Bytes"});let r=new Uint8Array(n);for(let i=0;i<n;i++){let a=t==="right";r[a?i:n-i-1]=s[a?i:s.length-i-1];}return r}function xb(s,e={}){let{dir:t="left"}=e,n=s,r=0;for(let i=0;i<n.length-1&&n[t==="left"?i:n.length-i-1].toString()==="0";i++)r++;return n=t==="left"?n.slice(r):n.slice(0,n.length-r),n}function ia(s,e){if(Oe(s)>e)throw new fh({givenSize:Oe(s),maxSize:e})}function n6(s,e){if(typeof e=="number"&&e>0&&e>Oe(s)-1)throw new gc({offset:e,position:"start",size:Oe(s)})}function r6(s,e,t){if(typeof e=="number"&&typeof t=="number"&&Oe(s)!==t-e)throw new gc({offset:t,position:"end",size:Oe(s)})}function Eb(s,e={}){let{dir:t,size:n=32}=e;if(n===0)return s;let r=s.replace("0x","");if(r.length>n*2)throw new dh({size:Math.ceil(r.length/2),targetSize:n,type:"Hex"});return `0x${r[t==="right"?"padEnd":"padStart"](n*2,"0")}`}function Ab(s,e={}){let{dir:t="left"}=e,n=s.replace("0x",""),r=0;for(let i=0;i<n.length-1&&n[t==="left"?i:n.length-i-1].toString()==="0";i++)r++;return n=t==="left"?n.slice(r):n.slice(0,n.length-r),n==="0"?"0x":t==="right"&&n.length%2===1?`0x${n}0`:`0x${n}`}var XT="#__bigint";function Ds(s,e,t){return JSON.stringify(s,(n,r)=>typeof e=="function"?e(n,r):typeof r=="bigint"?r.toString()+XT:r,t)}var e4=new TextEncoder,t4=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function a6(s,e={}){let{strict:t=!1}=e;if(!s)throw new mh(s);if(typeof s!="string")throw new mh(s);if(t&&!/^0x[0-9a-fA-F]*$/.test(s))throw new ph(s);if(!s.startsWith("0x"))throw new ph(s)}function Fe(...s){return `0x${s.reduce((e,t)=>e+t.replace("0x",""),"")}`}function Yt(s){return s instanceof Uint8Array?Ee(s):Array.isArray(s)?Ee(new Uint8Array(s)):s}function yh(s,e={}){let t=`0x${Number(s)}`;return typeof e.size=="number"?(ia(t,e.size),cn(t,e.size)):t}function Ee(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=t4[s[r]];let n=`0x${t}`;return typeof e.size=="number"?(ia(n,e.size),Us(n,e.size)):n}function le(s,e={}){let{signed:t,size:n}=e,r=BigInt(s),i;n?t?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof s=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));let a=typeof i=="bigint"&&t?-i-1n:0;if(i&&r>i||r<a){let u=typeof s=="bigint"?"n":"";throw new wc({max:i?`${i}${u}`:void 0,min:`${a}${u}`,signed:t,size:n,value:`${s}${u}`})}let c=`0x${(t&&r<0?BigInt.asUintN(n*8,BigInt(r)):r).toString(16)}`;return n?cn(c,n):c}function cs(s,e={}){return Ee(e4.encode(s),e)}function s4(s,e){return ap(Ye(s),Ye(e))}function cn(s,e){return Eb(s,{dir:"left",size:e})}function Us(s,e){return Eb(s,{dir:"right",size:e})}function n4(s){return Ee(Cb(s))}function rt(s,e,t,n={}){let{strict:r}=n;n6(s,e);let i=`0x${s.replace("0x","").slice((e??0)*2,(t??s.length)*2)}`;return r&&r6(i,e,t),i}function Oe(s){return Math.ceil((s.length-2)/2)}function aa(s){return Ab(s,{dir:"left"})}function r4(s){return Ab(s,{dir:"right"})}function up(s,e={}){let{signed:t}=e;e.size&&ia(s,e.size);let n=BigInt(s);if(!t)return n;let r=(s.length-2)/2,i=(1n<<BigInt(r)*8n)-1n,a=i>>1n;return n<=a?n:n-i-1n}function i4(s,e={}){e.size&&ia(s,e.size);let t=aa(s);if(t==="0x")return !1;if(t==="0x1")return !0;throw new cp(s)}function a4(s,e={}){return Ye(s,e)}function Ib(s,e={}){let{signed:t,size:n}=e;return Number(!t&&!n?s:up(s,e))}function o4(s,e={}){let{size:t}=e,n=Ye(s);return t&&(kn(n,t),n=lp(n)),new TextDecoder().decode(n)}function Zt(s,e={}){let{strict:t=!1}=e;try{return a6(s,{strict:t}),!0}catch{return !1}}var wc=class extends K{constructor({max:e,min:t,signed:n,size:r,value:i}){super(`Number \`${i}\` is not in safe${r?` ${r*8}-bit`:""}${n?" signed":" unsigned"} integer range ${e?`(\`${t}\` to \`${e}\`)`:`(above \`${t}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"});}},cp=class extends K{constructor(e){super(`Hex value \`"${e}"\` is not a valid boolean.`,{metaMessages:['The hex value must be `"0x0"` (false) or `"0x1"` (true).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexBooleanError"});}},mh=class extends K{constructor(e){super(`Value \`${typeof e=="object"?Ds(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"});}},ph=class extends K{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"});}},gh=class extends K{constructor(e){super(`Hex value \`"${e}"\` is an odd length (${e.length-2} nibbles).`,{metaMessages:["It must be an even length."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidLengthError"});}},fh=class extends K{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"});}},gc=class extends K{constructor({offset:e,position:t,size:n}){super(`Slice ${t==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"});}},dh=class extends K{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"});}};var c4=new TextDecoder,u4=new TextEncoder;function o6(s){if(!(s instanceof Uint8Array)){if(!s)throw new oa(s);if(typeof s!="object")throw new oa(s);if(!("BYTES_PER_ELEMENT"in s))throw new oa(s);if(s.BYTES_PER_ELEMENT!==1||s.constructor.name!=="Uint8Array")throw new oa(s)}}function Nb(...s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e);for(let n=0,r=0;n<s.length;n++){let i=s[n];t.set(i,r),r+=i.length;}return t}function Pn(s){return s instanceof Uint8Array?s:typeof s=="string"?Ye(s):c6(s)}function c6(s){return s instanceof Uint8Array?s:new Uint8Array(s)}function l4(s,e={}){let{size:t}=e,n=new Uint8Array(1);return n[0]=Number(s),typeof t=="number"?(kn(n,t),u6(n,t)):n}function Ye(s,e={}){let{size:t}=e,n=s;t&&(ia(s,t),n=Us(s,t));let r=n.slice(2);r.length%2&&(r=`0${r}`);let i=r.length/2,a=new Uint8Array(i);for(let o=0,c=0;o<i;o++){let u=Sb(r.charCodeAt(c++)),l=Sb(r.charCodeAt(c++));if(u===void 0||l===void 0)throw new K(`Invalid byte sequence ("${r[c-2]}${r[c-1]}" in "${r}").`);a[o]=u<<4|l;}return a}function h4(s,e){let t=le(s,e);return Ye(t)}function Tn(s,e={}){let{size:t}=e,n=u4.encode(s);return typeof t=="number"?(kn(n,t),l6(n,t)):n}function f4(s,e){return ap(s,e)}function u6(s,e){return vb(s,{dir:"left",size:e})}function l6(s,e){return vb(s,{dir:"right",size:e})}function Cb(s){return crypto.getRandomValues(new Uint8Array(s))}function ps(s){return s.length}function kb(s,e,t,n={}){let{strict:r}=n;e6(s,e);let i=s.slice(e,t);return r&&t6(i,e,t),i}function Pb(s,e={}){let{size:t}=e;typeof t<"u"&&kn(s,t);let n=Ee(s,e);return up(n,e)}function Tb(s,e={}){let{size:t}=e,n=s;if(typeof t<"u"&&(kn(n,t),n=dp(n)),n.length>1||n[0]>1)throw new hp(n);return !!n[0]}function d4(s,e={}){return Ee(s,e)}function Ls(s,e={}){let{size:t}=e;typeof t<"u"&&kn(s,t);let n=Ee(s,e);return Ib(n,e)}function fp(s,e={}){let{size:t}=e,n=s;return typeof t<"u"&&(kn(n,t),n=lp(n)),c4.decode(n)}function dp(s){return xb(s,{dir:"left"})}function lp(s){return xb(s,{dir:"right"})}function Bb(s){try{return o6(s),!0}catch{return !1}}var hp=class extends K{constructor(e){super(`Bytes value \`${e}\` is not a valid boolean.`,{metaMessages:["The bytes array must contain a single byte of either a `0` or `1` value."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesBooleanError"});}},oa=class extends K{constructor(e){super(`Value \`${typeof e=="object"?Ds(e):e}\` of type \`${typeof e}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"});}},lh=class extends K{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"});}},pc=class extends K{constructor({offset:e,position:t,size:n}){super(`Slice ${t==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SliceOffsetOutOfBoundsError"});}},hh=class extends K{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"});}};function dt(s,e={}){let{as:t=typeof s=="string"?"Hex":"Bytes"}=e,n=q3(Pn(s));return t==="Bytes"?n:Ee(n)}function m4(s,e={}){let{as:t=typeof s=="string"?"Hex":"Bytes"}=e,n=I3(Pn(s));return t==="Bytes"?n:Ee(n)}function wh(s,e={}){let{as:t=typeof s=="string"?"Hex":"Bytes"}=e,n=W3(Pn(s));return t==="Bytes"?n:Ee(n)}function Ob(s){return Zt(s)&&Oe(s)===32}var B={};be(B,{InvalidAddressError:()=>ca,InvalidChecksumError:()=>yp,InvalidInputError:()=>bc,assert:()=>Qt,checksum:()=>Sh,from:()=>p6,fromPublicKey:()=>Lb,isEqual:()=>jb,validate:()=>ua});var mp=class extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e;}get(e){let t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let n=this.keys().next().value;n&&this.delete(n);}return this}};var p4={checksum:new mp(8192)},pp=p4.checksum;function f6(s,e={}){let{compressed:t}=e,{prefix:n,x:r,y:i}=s;if(t===!1||typeof r=="bigint"&&typeof i=="bigint"){if(n!==4)throw new gp({prefix:n,cause:new Db});return}if(t===!0||typeof r=="bigint"&&typeof i>"u"){if(n!==3&&n!==2)throw new gp({prefix:n,cause:new Vb});return}throw new Rb({publicKey:s})}function Bn(s){let e=(()=>{if(Zt(s))return d6(s);if(Bb(s))return g4(s);let{prefix:t,x:n,y:r}=s;return typeof n=="bigint"&&typeof r=="bigint"?{prefix:t??4,x:n,y:r}:{prefix:t,x:n}})();return f6(e),e}function g4(s){return d6(Ee(s))}function d6(s){if(s.length!==132&&s.length!==130&&s.length!==68)throw new Ub({publicKey:s});if(s.length===130){let n=BigInt(rt(s,0,32)),r=BigInt(rt(s,32,64));return {prefix:4,x:n,y:r}}if(s.length===132){let n=Number(rt(s,0,1)),r=BigInt(rt(s,1,33)),i=BigInt(rt(s,33,65));return {prefix:n,x:r,y:i}}let e=Number(rt(s,0,1)),t=BigInt(rt(s,1,33));return {prefix:e,x:t}}function m6(s,e={}){return Ye(kr(s,e))}function kr(s,e={}){f6(s);let{prefix:t,x:n,y:r}=s,{includePrefix:i=!0}=e;return Fe(i?le(t,{size:1}):"0x",le(n,{size:32}),typeof r=="bigint"?le(r,{size:32}):"0x")}var Rb=class extends K{constructor({publicKey:e}){super(`Value \`${Ds(e)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"});}},gp=class extends K{constructor({prefix:e,cause:t}){super(`Prefix "${e}" is invalid.`,{cause:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"});}},Vb=class extends K{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"});}},Db=class extends K{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"});}},Ub=class extends K{constructor({publicKey:e}){super(`Value \`${e}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${Oe(Yt(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"});}};var y4=/^0x[a-fA-F0-9]{40}$/;function Qt(s,e={}){let{strict:t=!0}=e;if(!y4.test(s))throw new ca({address:s,cause:new bc});if(t){if(s.toLowerCase()===s)return;if(Sh(s)!==s)throw new ca({address:s,cause:new yp})}}function Sh(s){if(pp.has(s))return pp.get(s);Qt(s,{strict:!1});let e=s.substring(2).toLowerCase(),t=dt(Tn(e),{as:"Bytes"}),n=e.split("");for(let i=0;i<40;i+=2)t[i>>1]>>4>=8&&n[i]&&(n[i]=n[i].toUpperCase()),(t[i>>1]&15)>=8&&n[i+1]&&(n[i+1]=n[i+1].toUpperCase());let r=`0x${n.join("")}`;return pp.set(s,r),r}function p6(s,e={}){let{checksum:t=!1}=e;return Qt(s),t?Sh(s):s}function Lb(s,e={}){let t=dt(`0x${kr(s).slice(4)}`).substring(26);return p6(`0x${t}`,e)}function jb(s,e){return Qt(s,{strict:!1}),Qt(e,{strict:!1}),s.toLowerCase()===e.toLowerCase()}function ua(s,e={}){let{strict:t=!0}=e??{};try{return Qt(s,{strict:t}),!0}catch{return !1}}var ca=class extends K{constructor({address:e,cause:t}){super(`Address "${e}" is invalid.`,{cause:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"});}},bc=class extends K{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"});}},yp=class extends K{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"});}};function bp(s){let e=!0,t="",n=0,r="",i=!1;for(let a=0;a<s.length;a++){let o=s[a];if(["(",")",","].includes(o)&&(e=!0),o==="("&&n++,o===")"&&n--,!!e){if(n===0){if(o===" "&&["event","function","error",""].includes(r))r="";else if(r+=o,o===")"){i=!0;break}continue}if(o===" "){s[a-1]!==","&&t!==","&&t!==",("&&(t="",e=!1);continue}r+=o,t+=o;}}if(!i)throw new K("Unable to normalize signature.");return r}function wp(s,e){let t=typeof s,n=e.type;switch(n){case"address":return ua(s,{strict:!1});case"bool":return t==="boolean";case"function":return t==="string";case"string":return t==="string";default:return n==="tuple"&&"components"in e?Object.values(e.components).every((r,i)=>wp(Object.values(s)[i],r)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?t==="number"||t==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?t==="string"||s instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(s)&&s.every(r=>wp(r,{...e,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function Hb(s,e,t){for(let n in s){let r=s[n],i=e[n];if(r.type==="tuple"&&i.type==="tuple"&&"components"in r&&"components"in i)return Hb(r.components,i.components,t[n]);let a=[r.type,i.type];if(a.includes("address")&&a.includes("bytes20")?!0:a.includes("address")&&a.includes("string")?ua(t[n],{strict:!1}):a.includes("address")&&a.includes("bytes")?ua(t[n],{strict:!1}):!1)return a}}function g6(s,e={}){let{prepare:t=!0}=e,n=Array.isArray(s)?z0(s):typeof s=="string"?z0(s):s;return {...n,...t?{hash:Sc(n)}:{}}}function vh(s,e,t){let{args:n=[],prepare:r=!0}=t??{},i=Zt(e,{strict:!1}),a=s.filter(u=>i?u.type==="function"||u.type==="error"?Mb(u)===rt(e,0,4):u.type==="event"?Sc(u)===e:!1:"name"in u&&u.name===e);if(a.length===0)throw new vc({name:e});if(a.length===1)return {...a[0],...r?{hash:Sc(a[0])}:{}};let o;for(let u of a){if(!("inputs"in u))continue;if(!n||n.length===0){if(!u.inputs||u.inputs.length===0)return {...u,...r?{hash:Sc(u)}:{}};continue}if(!u.inputs||u.inputs.length===0||u.inputs.length!==n.length)continue;if(n.every((h,m)=>{let y="inputs"in u&&u.inputs[m];return y?wp(h,y):!1})){if(o&&"inputs"in o&&o.inputs){let h=Hb(u.inputs,o.inputs,n);if(h)throw new _b({abiItem:u,type:h[0]},{abiItem:o,type:h[1]})}o=u;}}let c=(()=>{if(o)return o;let[u,...l]=a;return {...u,overloads:l}})();if(!c)throw new vc({name:e});return {...c,...r?{hash:Sc(c)}:{}}}function Mb(...s){let e=(()=>{if(Array.isArray(s[0])){let[t,n]=s;return vh(t,n)}return s[0]})();return rt(Sc(e),0,4)}function b4(...s){let e=(()=>{if(Array.isArray(s[0])){let[n,r]=s;return vh(n,r)}return s[0]})(),t=typeof e=="string"?e:vn(e);return bp(t)}function Sc(...s){let e=(()=>{if(Array.isArray(s[0])){let[t,n]=s;return vh(t,n)}return s[0]})();return typeof e!="string"&&"hash"in e&&e.hash?e.hash:dt(cs(b4(e)))}var _b=class extends K{constructor(e,t){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${e.type}\` in \`${bp(vn(e.abiItem))}\`, and`,`\`${t.type}\` in \`${bp(vn(t.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"});}},vc=class extends K{constructor({name:e,data:t,type:n="item"}){let r=e?` with name "${e}"`:t?` with data "${t}"`:"";super(`ABI ${n}${r} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"});}},Sp=class extends K{constructor({data:e}){super(`Selector size is invalid. Expected 4 bytes. Received ${Oe(e)} bytes ("${e}").`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.InvalidSelectorSizeError"});}};var ot={};be(ot,{ArrayLengthMismatchError:()=>Eh,BytesSizeMismatchError:()=>Ec,DataSizeTooSmallError:()=>Cp,InvalidArrayError:()=>Ah,InvalidTypeError:()=>ha,LengthMismatchError:()=>Ch,ZeroDataError:()=>Np,decode:()=>Ac,encode:()=>On,encodePacked:()=>Ip,format:()=>U4,from:()=>kp});var w6=/^(.*)\[([0-9]*)\]$/,vp=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,xc=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,$b=2n**256n-1n;function la(s,e,t){let{checksumAddress:n,staticPosition:r}=t,i=Kb(e.type);if(i){let[a,o]=i;return v4(s,{...e,type:o},{checksumAddress:n,length:a,staticPosition:r})}if(e.type==="tuple")return I4(s,e,{checksumAddress:n,staticPosition:r});if(e.type==="address")return S4(s,{checksum:n});if(e.type==="bool")return x4(s);if(e.type.startsWith("bytes"))return E4(s,e,{staticPosition:r});if(e.type.startsWith("uint")||e.type.startsWith("int"))return A4(s,e);if(e.type==="string")return C4(s,{staticPosition:r});throw new ha(e.type)}var b6=32,qb=32;function S4(s,e={}){let{checksum:t=!1}=e,n=s.readBytes(32);return [(i=>t?Sh(i):i)(Ee(kb(n,-20))),32]}function v4(s,e,t){let{checksumAddress:n,length:r,staticPosition:i}=t;if(!r){let c=Ls(s.readBytes(qb)),u=i+c,l=u+b6;s.setPosition(u);let h=Ls(s.readBytes(b6)),m=xh(e),y=0,g=[];for(let w=0;w<h;++w){s.setPosition(l+(m?w*32:y));let[S,C]=la(s,e,{checksumAddress:n,staticPosition:l});y+=C,g.push(S);}return s.setPosition(i+32),[g,32]}if(xh(e)){let c=Ls(s.readBytes(qb)),u=i+c,l=[];for(let h=0;h<r;++h){s.setPosition(u+h*32);let[m]=la(s,e,{checksumAddress:n,staticPosition:u});l.push(m);}return s.setPosition(i+32),[l,32]}let a=0,o=[];for(let c=0;c<r;++c){let[u,l]=la(s,e,{checksumAddress:n,staticPosition:i+a});a+=l,o.push(u);}return [o,a]}function x4(s){return [Tb(s.readBytes(32),{size:32}),32]}function E4(s,e,{staticPosition:t}){let[n,r]=e.type.split("bytes");if(!r){let a=Ls(s.readBytes(32));s.setPosition(t+a);let o=Ls(s.readBytes(32));if(o===0)return s.setPosition(t+32),["0x",32];let c=s.readBytes(o);return s.setPosition(t+32),[Ee(c),32]}return [Ee(s.readBytes(Number.parseInt(r,10),32)),32]}function A4(s,e){let t=e.type.startsWith("int"),n=Number.parseInt(e.type.split("int")[1]||"256",10),r=s.readBytes(32);return [n>48?Pb(r,{signed:t}):Ls(r,{signed:t}),32]}function I4(s,e,t){let{checksumAddress:n,staticPosition:r}=t,i=e.components.length===0||e.components.some(({name:c})=>!c),a=i?[]:{},o=0;if(xh(e)){let c=Ls(s.readBytes(qb)),u=r+c;for(let l=0;l<e.components.length;++l){let h=e.components[l];s.setPosition(u+o);let[m,y]=la(s,h,{checksumAddress:n,staticPosition:u});o+=y,a[i?l:h?.name]=m;}return s.setPosition(r+32),[a,32]}for(let c=0;c<e.components.length;++c){let u=e.components[c],[l,h]=la(s,u,{checksumAddress:n,staticPosition:r});a[i?c:u?.name]=l,o+=h;}return [a,o]}function C4(s,{staticPosition:e}){let t=Ls(s.readBytes(32)),n=e+t;s.setPosition(n);let r=Ls(s.readBytes(32));if(r===0)return s.setPosition(e+32),["",32];let i=s.readBytes(r,32),a=fp(dp(i));return s.setPosition(e+32),[a,32]}function S6({checksumAddress:s,parameters:e,values:t}){let n=[];for(let r=0;r<e.length;r++)n.push(Fb({checksumAddress:s,parameter:e[r],value:t[r]}));return n}function Fb({checksumAddress:s=!1,parameter:e,value:t}){let n=e,r=Kb(n.type);if(r){let[i,a]=r;return k4(t,{checksumAddress:s,length:i,parameter:{...n,type:a}})}if(n.type==="tuple")return R4(t,{checksumAddress:s,parameter:n});if(n.type==="address")return N4(t,{checksum:s});if(n.type==="bool")return T4(t);if(n.type.startsWith("uint")||n.type.startsWith("int")){let i=n.type.startsWith("int"),[,,a="256"]=xc.exec(n.type)??[];return B4(t,{signed:i,size:Number(a)})}if(n.type.startsWith("bytes"))return P4(t,{type:n.type});if(n.type==="string")return O4(t);throw new ha(n.type)}function Ep(s){let e=0;for(let i=0;i<s.length;i++){let{dynamic:a,encoded:o}=s[i];a?e+=32:e+=Oe(o);}let t=[],n=[],r=0;for(let i=0;i<s.length;i++){let{dynamic:a,encoded:o}=s[i];a?(t.push(le(e+r,{size:32})),n.push(o),r+=Oe(o)):t.push(o);}return Fe(...t,...n)}function N4(s,e){let{checksum:t=!1}=e;return Qt(s,{strict:t}),{dynamic:!1,encoded:cn(s.toLowerCase())}}function k4(s,e){let{checksumAddress:t,length:n,parameter:r}=e,i=n===null;if(!Array.isArray(s))throw new Ah(s);if(!i&&s.length!==n)throw new Eh({expectedLength:n,givenLength:s.length,type:`${r.type}[${n}]`});let a=!1,o=[];for(let c=0;c<s.length;c++){let u=Fb({checksumAddress:t,parameter:r,value:s[c]});u.dynamic&&(a=!0),o.push(u);}if(i||a){let c=Ep(o);if(i){let u=le(o.length,{size:32});return {dynamic:!0,encoded:o.length>0?Fe(u,c):u}}if(a)return {dynamic:!0,encoded:c}}return {dynamic:!1,encoded:Fe(...o.map(({encoded:c})=>c))}}function P4(s,{type:e}){let[,t]=e.split("bytes"),n=Oe(s);if(!t){let r=s;return n%32!==0&&(r=Us(r,Math.ceil((s.length-2)/2/32)*32)),{dynamic:!0,encoded:Fe(cn(le(n,{size:32})),r)}}if(n!==Number.parseInt(t,10))throw new Ec({expectedSize:Number.parseInt(t,10),value:s});return {dynamic:!1,encoded:Us(s)}}function T4(s){if(typeof s!="boolean")throw new K(`Invalid boolean value: "${s}" (type: ${typeof s}). Expected: \`true\` or \`false\`.`);return {dynamic:!1,encoded:cn(yh(s))}}function B4(s,{signed:e,size:t}){if(typeof t=="number"){let n=2n**(BigInt(t)-(e?1n:0n))-1n,r=e?-n-1n:0n;if(s>n||s<r)throw new wc({max:n.toString(),min:r.toString(),signed:e,size:t/8,value:s.toString()})}return {dynamic:!1,encoded:le(s,{size:32,signed:e})}}function O4(s){let e=cs(s),t=Math.ceil(Oe(e)/32),n=[];for(let r=0;r<t;r++)n.push(Us(rt(e,r*32,(r+1)*32)));return {dynamic:!0,encoded:Fe(Us(le(Oe(e),{size:32})),...n)}}function R4(s,e){let{checksumAddress:t,parameter:n}=e,r=!1,i=[];for(let a=0;a<n.components.length;a++){let o=n.components[a],c=Array.isArray(s)?a:o.name,u=Fb({checksumAddress:t,parameter:o,value:s[c]});i.push(u),u.dynamic&&(r=!0);}return {dynamic:r,encoded:r?Ep(i):Fe(...i.map(({encoded:a})=>a))}}function Kb(s){let e=s.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function xh(s){let{type:e}=s;if(e==="string"||e==="bytes"||e.endsWith("[]"))return !0;if(e==="tuple")return s.components?.some(xh);let t=Kb(s.type);return !!(t&&xh({...s,type:t[1]}))}var D4={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new Wb({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(s){if(s<0||s>this.bytes.length-1)throw new Gb({length:this.bytes.length,position:s})},decrementPosition(s){if(s<0)throw new Ap({offset:s});let e=this.position-s;this.assertPosition(e),this.position=e;},getReadCount(s){return this.positionReadCount.get(s||this.position)||0},incrementPosition(s){if(s<0)throw new Ap({offset:s});let e=this.position+s;this.assertPosition(e),this.position=e;},inspectByte(s){let e=s??this.position;return this.assertPosition(e),this.bytes[e]},inspectBytes(s,e){let t=e??this.position;return this.assertPosition(t+s-1),this.bytes.subarray(t,t+s)},inspectUint8(s){let e=s??this.position;return this.assertPosition(e),this.bytes[e]},inspectUint16(s){let e=s??this.position;return this.assertPosition(e+1),this.dataView.getUint16(e)},inspectUint24(s){let e=s??this.position;return this.assertPosition(e+2),(this.dataView.getUint16(e)<<8)+this.dataView.getUint8(e+2)},inspectUint32(s){let e=s??this.position;return this.assertPosition(e+3),this.dataView.getUint32(e)},pushByte(s){this.assertPosition(this.position),this.bytes[this.position]=s,this.position++;},pushBytes(s){this.assertPosition(this.position+s.length-1),this.bytes.set(s,this.position),this.position+=s.length;},pushUint8(s){this.assertPosition(this.position),this.bytes[this.position]=s,this.position++;},pushUint16(s){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,s),this.position+=2;},pushUint24(s){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,s>>8),this.dataView.setUint8(this.position+2,s&255),this.position+=3;},pushUint32(s){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,s),this.position+=4;},readByte(){this.assertReadLimit(),this._touch();let s=this.inspectByte();return this.position++,s},readBytes(s,e){this.assertReadLimit(),this._touch();let t=this.inspectBytes(s);return this.position+=e??s,t},readUint8(){this.assertReadLimit(),this._touch();let s=this.inspectUint8();return this.position+=1,s},readUint16(){this.assertReadLimit(),this._touch();let s=this.inspectUint16();return this.position+=2,s},readUint24(){this.assertReadLimit(),this._touch();let s=this.inspectUint24();return this.position+=3,s},readUint32(){this.assertReadLimit(),this._touch();let s=this.inspectUint32();return this.position+=4,s},get remaining(){return this.bytes.length-this.position},setPosition(s){let e=this.position;return this.assertPosition(s),this.position=s,()=>this.position=e},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let s=this.getReadCount();this.positionReadCount.set(this.position,s+1),s>0&&this.recursiveReadCount++;}};function Ih(s,{recursiveReadLimit:e=8192}={}){let t=Object.create(D4);return t.bytes=s,t.dataView=new DataView(s.buffer,s.byteOffset,s.byteLength),t.positionReadCount=new Map,t.recursiveReadLimit=e,t}var Ap=class extends K{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"});}},Gb=class extends K{constructor({length:e,position:t}){super(`Position \`${t}\` is out of bounds (\`0 < position < ${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"});}},Wb=class extends K{constructor({count:e,limit:t}){super(`Recursive read limit of \`${t}\` exceeded (recursive read count: \`${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"});}};function Ac(s,e,t={}){let{as:n="Array",checksumAddress:r=!1}=t,i=typeof e=="string"?Ye(e):e,a=Ih(i);if(ps(i)===0&&s.length>0)throw new Np;if(ps(i)&&ps(i)<32)throw new Cp({data:typeof e=="string"?e:Ee(e),parameters:s,size:ps(i)});let o=0,c=n==="Array"?[]:{};for(let u=0;u<s.length;++u){let l=s[u];a.setPosition(o);let[h,m]=la(a,l,{checksumAddress:r,staticPosition:0});o+=m,n==="Array"?c.push(h):c[l.name??u]=h;}return c}function On(s,e,t){let{checksumAddress:n=!1}=t??{};if(s.length!==e.length)throw new Ch({expectedLength:s.length,givenLength:e.length});let r=S6({checksumAddress:n,parameters:s,values:e}),i=Ep(r);return i.length===0?"0x":i}function Ip(s,e){if(s.length!==e.length)throw new Ch({expectedLength:s.length,givenLength:e.length});let t=[];for(let n=0;n<s.length;n++){let r=s[n],i=e[n];t.push(Ip.encode(r,i));}return Fe(...t)}(function(s){function e(t,n,r=!1){if(t==="address"){let c=n;return Qt(c),cn(c.toLowerCase(),r?32:0)}if(t==="string")return cs(n);if(t==="bytes")return n;if(t==="bool")return cn(yh(n),r?32:1);let i=t.match(xc);if(i){let[c,u,l="256"]=i,h=Number.parseInt(l,10)/8;return le(n,{size:r?32:h,signed:u==="int"})}let a=t.match(vp);if(a){let[c,u]=a;if(Number.parseInt(u,10)!==(n.length-2)/2)throw new Ec({expectedSize:Number.parseInt(u,10),value:n});return Us(n,r?32:0)}let o=t.match(w6);if(o&&Array.isArray(n)){let[c,u]=o,l=[];for(let h=0;h<n.length;h++)l.push(e(u,n[h],!0));return l.length===0?"0x":Fe(...l)}throw new ha(t)}s.encode=e;})(Ip||(Ip={}));function U4(s){return nn(s)}function kp(s){return Array.isArray(s)&&typeof s[0]=="string"?Y0(s):typeof s=="string"?Y0(s):s}var Cp=class extends K{constructor({data:e,parameters:t,size:n}){super(`Data size of ${n} bytes is too small for given parameters.`,{metaMessages:[`Params: (${nn(t)})`,`Data: ${e} (${n} bytes)`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"});}},Np=class extends K{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.'),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"});}},Eh=class extends K{constructor({expectedLength:e,givenLength:t,type:n}){super(`Array length mismatch for type \`${n}\`. Expected: \`${e}\`. Given: \`${t}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"});}},Ec=class extends K{constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" (bytes${Oe(t)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"});}},Ch=class extends K{constructor({expectedLength:e,givenLength:t}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${t}`].join(`
|
|
340
|
+
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"});}},Ah=class extends K{constructor(e){super(`Value \`${e}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"});}},ha=class extends K{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"});}};var se={};be(se,{decodeData:()=>L4,decodeResult:()=>j4,encodeData:()=>H4,encodeResult:()=>_4,format:()=>M4,from:()=>$4,fromAbi:()=>fa,getSelector:()=>x6});function L4(...s){let[e,t]=(()=>{if(Array.isArray(s[0])){let[i,a,o]=s;return [fa(i,a),o]}return s})(),{overloads:n}=e;if(Oe(t)<4)throw new Sp({data:t});if(e.inputs?.length===0)return;let r=n?fa([e,...n],t):e;if(!(Oe(t)<=4))return Ac(r.inputs,rt(t,4))}function j4(...s){let[e,t,n={}]=(()=>{if(Array.isArray(s[0])){let[i,a,o,c]=s;return [fa(i,a),o,c]}return s})(),r=Ac(e.outputs,t,n);if(!(r&&Object.keys(r).length===0))return r&&Object.keys(r).length===1?Array.isArray(r)?r[0]:Object.values(r)[0]:r}function H4(...s){let[e,t=[]]=(()=>{if(Array.isArray(s[0])){let[u,l,h]=s;return [fa(u,l,{args:h}),h]}let[o,c]=s;return [o,c]})(),{overloads:n}=e,r=n?fa([e,...n],e.name,{args:t}):e,i=x6(r),a=t.length>0?On(r.inputs,t):void 0;return a?Fe(i,a):i}function _4(...s){let[e,t,n={}]=(()=>{if(Array.isArray(s[0])){let[a,o,c,u]=s;return [fa(a,o),c,u]}return s})(),{as:r="Array"}=n,i=e.outputs.length===1?[t]:Array.isArray(t)?t:r==="Object"?Object.values(t):[t];return On(e.outputs,i)}function M4(s){return vn(s)}function $4(s,e={}){return g6(s,e)}function fa(s,e,t){let n=vh(s,e,t);if(n.type!=="function")throw new vc({name:e,type:"function"});return n}function x6(s){return Mb(s)}function E6(s){let e=[];for(let t=0;t<s.length;t++){let[n,r]=s[t];n&&Qt(n,{strict:!1}),e.push({address:n,storageKeys:r.map(i=>Ob(i)?i:aa(i))});}return e}function A6(s){if(!s||s.length===0)return [];let e=[];for(let{address:t,storageKeys:n}of s){for(let r=0;r<n.length;r++)if(Oe(n[r])!==32)throw new Jb({storageKey:n[r]});t&&Qt(t,{strict:!1}),e.push([t,n]);}return e}var Jb=class extends K{constructor({storageKey:e}){super(`Size for storage key "${e}" is invalid. Expected 32 bytes. Got ${Oe(e)} bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AccessList.InvalidStorageKeySizeError"});}};function N6(s){return q4(s,"Hex")}function q4(s,e){let t=e,n=(()=>{if(typeof s=="string"){if(s.length>3&&s.length%2!==0)throw new gh(s);return Ye(s)}return s})(),r=Ih(n,{recursiveReadLimit:Number.POSITIVE_INFINITY});return k6(r,t)}function k6(s,e="Hex"){if(s.bytes.length===0)return e==="Hex"?Ee(s.bytes):s.bytes;let t=s.readByte();if(t<128&&s.decrementPosition(1),t<192){let r=C6(s,t,128),i=s.readBytes(r);return e==="Hex"?Ee(i):i}let n=C6(s,t,192);return F4(s,n,e)}function C6(s,e,t){if(t===128&&e<128)return 1;if(e<=t+55)return e-t;if(e===t+55+1)return s.readUint8();if(e===t+55+2)return s.readUint16();if(e===t+55+3)return s.readUint24();if(e===t+55+4)return s.readUint32();throw new K("Invalid RLP prefix")}function F4(s,e,t){let n=s.position,r=[];for(;s.position-n<e;)r.push(k6(s,t));return r}function K4(s,e){let{as:t}=e,n=T6(s),r=Ih(new Uint8Array(n.length));return n.encode(r),t==="Hex"?Ee(r.bytes):r.bytes}function P6(s,e={}){let{as:t="Hex"}=e;return K4(s,{as:t})}function T6(s){return Array.isArray(s)?G4(s.map(e=>T6(e))):W4(s)}function G4(s){let e=s.reduce((r,i)=>r+i.length,0),t=B6(e);return {length:e<=55?1+e:1+t+e,encode(r){e<=55?r.pushByte(192+e):(r.pushByte(247+t),t===1?r.pushUint8(e):t===2?r.pushUint16(e):t===3?r.pushUint24(e):r.pushUint32(e));for(let{encode:i}of s)i(r);}}}function W4(s){let e=typeof s=="string"?Ye(s):s,t=B6(e.length);return {length:e.length===1&&e[0]<128?1:e.length<=55?1+e.length:1+t+e.length,encode(r){e.length===1&&e[0]<128?r.pushBytes(e):e.length<=55?(r.pushByte(128+e.length),r.pushBytes(e)):(r.pushByte(183+t),t===1?r.pushUint8(e.length):t===2?r.pushUint16(e.length):t===3?r.pushUint24(e.length):r.pushUint32(e.length),r.pushBytes(e));}}}function B6(s){if(s<=255)return 1;if(s<=65535)return 2;if(s<=16777215)return 3;if(s<=4294967295)return 4;throw new K("Length is too large.")}var At={};be(At,{InvalidRError:()=>Op,InvalidSError:()=>Rp,InvalidSerializedSizeError:()=>Bp,InvalidVError:()=>Vp,InvalidYParityError:()=>ma,MissingPropertiesError:()=>Cc,assert:()=>Dp,extract:()=>Up,from:()=>Nh,fromBytes:()=>Z6,fromDerBytes:()=>lB,fromDerHex:()=>Q6,fromHex:()=>hS,fromLegacy:()=>X6,fromRpc:()=>eC,fromTuple:()=>fS,toBytes:()=>hB,toDerBytes:()=>fB,toDerHex:()=>dB,toHex:()=>tC,toLegacy:()=>mB,toRpc:()=>dS,toTuple:()=>mS,vToYParity:()=>Lp,validate:()=>pB,yParityToV:()=>pS});var Pp=class extends Er{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,m3(e);let n=Zi(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let a=0;a<i.length;a++)i[a]^=54;this.iHash.update(i),this.oHash=e.create();for(let a=0;a<i.length;a++)i[a]^=106;this.oHash.update(i),zt(i);}update(e){return En(this),this.iHash.update(e),this}digestInto(e){En(this),an(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy();}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy();}},zb=(s,e,t)=>new Pp(s,e).update(t).digest();zb.create=(s,e)=>new Pp(s,e);var Xt=BigInt(0),_t=BigInt(1),da=BigInt(2),J4=BigInt(3),V6=BigInt(4),D6=BigInt(5),U6=BigInt(8);function Ht(s,e){let t=s%e;return t>=Xt?t:e+t}function gs(s,e,t){let n=s;for(;e-- >Xt;)n*=n,n%=t;return n}function Tp(s,e){if(s===Xt)throw new Error("invert: expected non-zero number");if(e<=Xt)throw new Error("invert: expected positive modulus, got "+e);let t=Ht(s,e),n=e,r=Xt,a=_t;for(;t!==Xt;){let u=n/t,l=n%t,h=r-a*u;n=t,t=l,r=a,a=h;}if(n!==_t)throw new Error("invert: does not exist");return Ht(r,e)}function L6(s,e){let t=(s.ORDER+_t)/V6,n=s.pow(e,t);if(!s.eql(s.sqr(n),e))throw new Error("Cannot find square root");return n}function z4(s,e){let t=(s.ORDER-D6)/U6,n=s.mul(e,da),r=s.pow(n,t),i=s.mul(e,r),a=s.mul(s.mul(i,da),r),o=s.mul(i,s.sub(a,s.ONE));if(!s.eql(s.sqr(o),e))throw new Error("Cannot find square root");return o}function Y4(s){if(s<BigInt(3))throw new Error("sqrt is not defined for small field");let e=s-_t,t=0;for(;e%da===Xt;)e/=da,t++;let n=da,r=Rn(s);for(;R6(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return L6;let i=r.pow(n,e),a=(e+_t)/da;return function(c,u){if(c.is0(u))return u;if(R6(c,u)!==1)throw new Error("Cannot find square root");let l=t,h=c.mul(c.ONE,i),m=c.pow(u,e),y=c.pow(u,a);for(;!c.eql(m,c.ONE);){if(c.is0(m))return c.ZERO;let g=1,w=c.sqr(m);for(;!c.eql(w,c.ONE);)if(g++,w=c.sqr(w),g===l)throw new Error("Cannot find square root");let S=_t<<BigInt(l-g-1),C=c.pow(h,S);l=g,h=c.sqr(C),m=c.mul(m,h),y=c.mul(y,C);}return y}}function Z4(s){return s%V6===J4?L6:s%U6===D6?z4:Y4(s)}var Q4=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yb(s){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Q4.reduce((n,r)=>(n[r]="function",n),e);return ra(s,t)}function X4(s,e,t){if(t<Xt)throw new Error("invalid exponent, negatives unsupported");if(t===Xt)return s.ONE;if(t===_t)return e;let n=s.ONE,r=e;for(;t>Xt;)t&_t&&(n=s.mul(n,r)),r=s.sqr(r),t>>=_t;return n}function Zb(s,e,t=!1){let n=new Array(e.length).fill(t?s.ZERO:void 0),r=e.reduce((a,o,c)=>s.is0(o)?a:(n[c]=a,s.mul(a,o)),s.ONE),i=s.inv(r);return e.reduceRight((a,o,c)=>s.is0(o)?a:(n[c]=s.mul(a,n[c]),s.mul(a,o)),i),n}function R6(s,e){let t=(s.ORDER-_t)/da,n=s.pow(e,t),r=s.eql(n,s.ONE),i=s.eql(n,s.ZERO),a=s.eql(n,s.neg(s.ONE));if(!r&&!i&&!a)throw new Error("invalid Legendre symbol result");return r?1:i?0:-1}function Qb(s,e){e!==void 0&&Yi(e);let t=e!==void 0?e:s.toString(2).length,n=Math.ceil(t/8);return {nBitLength:t,nByteLength:n}}function Rn(s,e,t=!1,n={}){if(s<=Xt)throw new Error("invalid field: expected ORDER > 0, got "+s);let{nBitLength:r,nByteLength:i}=Qb(s,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let a,o=Object.freeze({ORDER:s,isLE:t,BITS:r,BYTES:i,MASK:na(r),ZERO:Xt,ONE:_t,create:c=>Ht(c,s),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Xt<=c&&c<s},is0:c=>c===Xt,isOdd:c=>(c&_t)===_t,neg:c=>Ht(-c,s),eql:(c,u)=>c===u,sqr:c=>Ht(c*c,s),add:(c,u)=>Ht(c+u,s),sub:(c,u)=>Ht(c-u,s),mul:(c,u)=>Ht(c*u,s),pow:(c,u)=>X4(o,c,u),div:(c,u)=>Ht(c*Tp(u,s),s),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Tp(c,s),sqrt:n.sqrt||(c=>(a||(a=Z4(s)),a(o,c))),toBytes:c=>t?wb(c,i):ta(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return t?yb(c):Cn(c)},invertBatch:c=>Zb(o,c),cmov:(c,u,l)=>l?u:c});return Object.freeze(o)}function j6(s){if(typeof s!="bigint")throw new Error("field order must be bigint");let e=s.toString(2).length;return Math.ceil(e/8)}function Xb(s){let e=j6(s);return e+Math.ceil(e/2)}function H6(s,e,t=!1){let n=s.length,r=j6(e),i=Xb(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let a=t?yb(s):Cn(s),o=Ht(a,e-_t)+_t;return t?wb(o,r):ta(o,r)}var _6=BigInt(0),rS=BigInt(1);function eS(s,e){let t=e.negate();return s?t:e}function $6(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function tS(s,e){$6(s,e);let t=Math.ceil(e/s)+1,n=2**(s-1),r=2**s,i=na(s),a=BigInt(s);return {windows:t,windowSize:n,mask:i,maxNumber:r,shiftBy:a}}function M6(s,e,t){let{windowSize:n,mask:r,maxNumber:i,shiftBy:a}=t,o=Number(s&r),c=s>>a;o>n&&(o-=i,c+=rS);let u=e*n,l=u+Math.abs(o)-1,h=o===0,m=o<0,y=e%2!==0;return {nextN:c,offset:l,isZero:h,isNeg:m,isNegF:y,offsetF:u}}function eB(s,e){if(!Array.isArray(s))throw new Error("array expected");s.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)});}function tB(s,e){if(!Array.isArray(s))throw new Error("array of scalars expected");s.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)});}var sS=new WeakMap,q6=new WeakMap;function nS(s){return q6.get(s)||1}function F6(s,e){return {constTimeNegate:eS,hasPrecomputes(t){return nS(t)!==1},unsafeLadder(t,n,r=s.ZERO){let i=t;for(;n>_6;)n&rS&&(r=r.add(i)),i=i.double(),n>>=rS;return r},precomputeWindow(t,n){let{windows:r,windowSize:i}=tS(n,e),a=[],o=t,c=o;for(let u=0;u<r;u++){c=o,a.push(c);for(let l=1;l<i;l++)c=c.add(o),a.push(c);o=c.double();}return a},wNAF(t,n,r){let i=s.ZERO,a=s.BASE,o=tS(t,e);for(let c=0;c<o.windows;c++){let{nextN:u,offset:l,isZero:h,isNeg:m,isNegF:y,offsetF:g}=M6(r,c,o);r=u,h?a=a.add(eS(y,n[g])):i=i.add(eS(m,n[l]));}return {p:i,f:a}},wNAFUnsafe(t,n,r,i=s.ZERO){let a=tS(t,e);for(let o=0;o<a.windows&&r!==_6;o++){let{nextN:c,offset:u,isZero:l,isNeg:h}=M6(r,o,a);if(r=c,!l){let m=n[u];i=i.add(h?m.negate():m);}}return i},getPrecomputes(t,n,r){let i=sS.get(n);return i||(i=this.precomputeWindow(n,t),t!==1&&sS.set(n,r(i))),i},wNAFCached(t,n,r){let i=nS(t);return this.wNAF(i,this.getPrecomputes(i,t,r),n)},wNAFCachedUnsafe(t,n,r,i){let a=nS(t);return a===1?this.unsafeLadder(t,n,i):this.wNAFUnsafe(a,this.getPrecomputes(a,t,r),n,i)},setWindowSize(t,n){$6(n,e),q6.set(t,n),sS.delete(t);}}}function K6(s,e,t,n){eB(t,s),tB(n,e);let r=t.length,i=n.length;if(r!==i)throw new Error("arrays of points and scalars must have equal length");let a=s.ZERO,o=Q3(BigInt(r)),c=1;o>12?c=o-3:o>4?c=o-2:o>0&&(c=2);let u=na(c),l=new Array(Number(u)+1).fill(a),h=Math.floor((e.BITS-1)/c)*c,m=a;for(let y=h;y>=0;y-=c){l.fill(a);for(let w=0;w<i;w++){let S=n[w],C=Number(S>>BigInt(y)&u);l[C]=l[C].add(t[w]);}let g=a;for(let w=l.length-1,S=a;w>0;w--)S=S.add(l[w]),g=g.add(S);if(m=m.add(g),y!==0)for(let w=0;w<c;w++)m=m.double();}return m}function iS(s){return Yb(s.Fp),ra(s,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Qb(s.n,s.nBitLength),...s,p:s.Fp.ORDER})}function G6(s){s.lowS!==void 0&&dc("lowS",s.lowS),s.prehash!==void 0&&dc("prehash",s.prehash);}function sB(s){let e=iS(s);ra(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:t,Fp:n,a:r}=e;if(t){if(!n.eql(r,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}var cS=class extends Error{constructor(e=""){super(e);}},Vn={Err:cS,_tlv:{encode:(s,e)=>{let{Err:t}=Vn;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,r=oh(n);if(r.length/2&128)throw new t("tlv.encode: long form length too big");let i=n>127?oh(r.length/2|128):"";return oh(s)+i+r+e},decode(s,e){let{Err:t}=Vn,n=0;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==s)throw new t("tlv.decode: wrong tlv");let r=e[n++],i=!!(r&128),a=0;if(!i)a=r;else {let c=r&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let l of u)a=a<<8|l;if(n+=c,a<128)throw new t("tlv.decode(long): not minimal encoding")}let o=e.subarray(n,n+a);if(o.length!==a)throw new t("tlv.decode: wrong value length");return {v:o,l:e.subarray(n+a)}}},_int:{encode(s){let{Err:e}=Vn;if(s<Dn)throw new e("integer: negative integers are not allowed");let t=oh(s);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(s){let{Err:e}=Vn;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Cn(s)}},toSig(s){let{Err:e,_int:t,_tlv:n}=Vn,r=os("signature",s),{v:i,l:a}=n.decode(48,r);if(a.length)throw new e("invalid signature: left bytes after parsing");let{v:o,l:c}=n.decode(2,i),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return {r:t.decode(o),s:t.decode(u)}},hexFromSig(s){let{_tlv:e,_int:t}=Vn,n=e.encode(2,t.encode(s.r)),r=e.encode(2,t.encode(s.s)),i=n+r;return e.encode(48,i)}};function aS(s,e){return mc(ta(s,e))}var Dn=BigInt(0),Et=BigInt(1);BigInt(2);var oS=BigInt(3),nB=BigInt(4);function rB(s){let e=sB(s),{Fp:t}=e,n=Rn(e.n,e.nBitLength),r=e.toBytes||((x,v,I)=>{let D=v.toAffine();return uh(Uint8Array.from([4]),t.toBytes(D.x),t.toBytes(D.y))}),i=e.fromBytes||(x=>{let v=x.subarray(1),I=t.fromBytes(v.subarray(0,t.BYTES)),D=t.fromBytes(v.subarray(t.BYTES,2*t.BYTES));return {x:I,y:D}});function a(x){let{a:v,b:I}=e,D=t.sqr(x),F=t.mul(D,x);return t.add(t.add(F,t.mul(x,v)),I)}function o(x,v){let I=t.sqr(v),D=a(x);return t.eql(I,D)}if(!o(e.Gx,e.Gy))throw new Error("bad curve params: generator point");let c=t.mul(t.pow(e.a,oS),nB),u=t.mul(t.sqr(e.b),BigInt(27));if(t.is0(t.add(c,u)))throw new Error("bad curve params: a or b");function l(x){return op(x,Et,e.n)}function h(x){let{allowedPrivateKeyLengths:v,nByteLength:I,wrapPrivateKey:D,n:F}=e;if(v&&typeof x!="bigint"){if(fc(x)&&(x=mc(x)),typeof x!="string"||!v.includes(x.length))throw new Error("invalid private key");x=x.padStart(I*2,"0");}let M;try{M=typeof x=="bigint"?x:Cn(os("private key",x,I));}catch{throw new Error("invalid private key, expected hex or "+I+" bytes, got "+typeof x)}return D&&(M=Ht(M,F)),sa("private key",M,Et,F),M}function m(x){if(!(x instanceof w))throw new Error("ProjectivePoint expected")}let y=bb((x,v)=>{let{px:I,py:D,pz:F}=x;if(t.eql(F,t.ONE))return {x:I,y:D};let M=x.is0();v==null&&(v=M?t.ONE:t.inv(F));let W=t.mul(I,v),ne=t.mul(D,v),q=t.mul(F,v);if(M)return {x:t.ZERO,y:t.ZERO};if(!t.eql(q,t.ONE))throw new Error("invZ was invalid");return {x:W,y:ne}}),g=bb(x=>{if(x.is0()){if(e.allowInfinityPoint&&!t.is0(x.py))return;throw new Error("bad point: ZERO")}let{x:v,y:I}=x.toAffine();if(!t.isValid(v)||!t.isValid(I))throw new Error("bad point: x or y not FE");if(!o(v,I))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return !0});class w{constructor(v,I,D){if(v==null||!t.isValid(v))throw new Error("x required");if(I==null||!t.isValid(I)||t.is0(I))throw new Error("y required");if(D==null||!t.isValid(D))throw new Error("z required");this.px=v,this.py=I,this.pz=D,Object.freeze(this);}static fromAffine(v){let{x:I,y:D}=v||{};if(!v||!t.isValid(I)||!t.isValid(D))throw new Error("invalid affine point");if(v instanceof w)throw new Error("projective point not allowed");let F=M=>t.eql(M,t.ZERO);return F(I)&&F(D)?w.ZERO:new w(I,D,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(v){let I=Zb(t,v.map(D=>D.pz));return v.map((D,F)=>D.toAffine(I[F])).map(w.fromAffine)}static fromHex(v){let I=w.fromAffine(i(os("pointHex",v)));return I.assertValidity(),I}static fromPrivateKey(v){return w.BASE.multiply(h(v))}static msm(v,I){return K6(w,n,v,I)}_setWindowSize(v){k.setWindowSize(this,v);}assertValidity(){g(this);}hasEvenY(){let{y:v}=this.toAffine();if(t.isOdd)return !t.isOdd(v);throw new Error("Field doesn't support isOdd")}equals(v){m(v);let{px:I,py:D,pz:F}=this,{px:M,py:W,pz:ne}=v,q=t.eql(t.mul(I,ne),t.mul(M,F)),J=t.eql(t.mul(D,ne),t.mul(W,F));return q&&J}negate(){return new w(this.px,t.neg(this.py),this.pz)}double(){let{a:v,b:I}=e,D=t.mul(I,oS),{px:F,py:M,pz:W}=this,ne=t.ZERO,q=t.ZERO,J=t.ZERO,ae=t.mul(F,F),Be=t.mul(M,M),L=t.mul(W,W),_=t.mul(F,M);return _=t.add(_,_),J=t.mul(F,W),J=t.add(J,J),ne=t.mul(v,J),q=t.mul(D,L),q=t.add(ne,q),ne=t.sub(Be,q),q=t.add(Be,q),q=t.mul(ne,q),ne=t.mul(_,ne),J=t.mul(D,J),L=t.mul(v,L),_=t.sub(ae,L),_=t.mul(v,_),_=t.add(_,J),J=t.add(ae,ae),ae=t.add(J,ae),ae=t.add(ae,L),ae=t.mul(ae,_),q=t.add(q,ae),L=t.mul(M,W),L=t.add(L,L),ae=t.mul(L,_),ne=t.sub(ne,ae),J=t.mul(L,Be),J=t.add(J,J),J=t.add(J,J),new w(ne,q,J)}add(v){m(v);let{px:I,py:D,pz:F}=this,{px:M,py:W,pz:ne}=v,q=t.ZERO,J=t.ZERO,ae=t.ZERO,Be=e.a,L=t.mul(e.b,oS),_=t.mul(I,M),Q=t.mul(D,W),me=t.mul(F,ne),X=t.add(I,D),j=t.add(M,W);X=t.mul(X,j),j=t.add(_,Q),X=t.sub(X,j),j=t.add(I,F);let z=t.add(M,ne);return j=t.mul(j,z),z=t.add(_,me),j=t.sub(j,z),z=t.add(D,F),q=t.add(W,ne),z=t.mul(z,q),q=t.add(Q,me),z=t.sub(z,q),ae=t.mul(Be,j),q=t.mul(L,me),ae=t.add(q,ae),q=t.sub(Q,ae),ae=t.add(Q,ae),J=t.mul(q,ae),Q=t.add(_,_),Q=t.add(Q,_),me=t.mul(Be,me),j=t.mul(L,j),Q=t.add(Q,me),me=t.sub(_,me),me=t.mul(Be,me),j=t.add(j,me),_=t.mul(Q,j),J=t.add(J,_),_=t.mul(z,j),q=t.mul(X,q),q=t.sub(q,_),_=t.mul(X,Q),ae=t.mul(z,ae),ae=t.add(ae,_),new w(q,J,ae)}subtract(v){return this.add(v.negate())}is0(){return this.equals(w.ZERO)}wNAF(v){return k.wNAFCached(this,v,w.normalizeZ)}multiplyUnsafe(v){let{endo:I,n:D}=e;sa("scalar",v,Dn,D);let F=w.ZERO;if(v===Dn)return F;if(this.is0()||v===Et)return this;if(!I||k.hasPrecomputes(this))return k.wNAFCachedUnsafe(this,v,w.normalizeZ);let{k1neg:M,k1:W,k2neg:ne,k2:q}=I.splitScalar(v),J=F,ae=F,Be=this;for(;W>Dn||q>Dn;)W&Et&&(J=J.add(Be)),q&Et&&(ae=ae.add(Be)),Be=Be.double(),W>>=Et,q>>=Et;return M&&(J=J.negate()),ne&&(ae=ae.negate()),ae=new w(t.mul(ae.px,I.beta),ae.py,ae.pz),J.add(ae)}multiply(v){let{endo:I,n:D}=e;sa("scalar",v,Et,D);let F,M;if(I){let{k1neg:W,k1:ne,k2neg:q,k2:J}=I.splitScalar(v),{p:ae,f:Be}=this.wNAF(ne),{p:L,f:_}=this.wNAF(J);ae=k.constTimeNegate(W,ae),L=k.constTimeNegate(q,L),L=new w(t.mul(L.px,I.beta),L.py,L.pz),F=ae.add(L),M=Be.add(_);}else {let{p:W,f:ne}=this.wNAF(v);F=W,M=ne;}return w.normalizeZ([F,M])[0]}multiplyAndAddUnsafe(v,I,D){let F=w.BASE,M=(ne,q)=>q===Dn||q===Et||!ne.equals(F)?ne.multiplyUnsafe(q):ne.multiply(q),W=M(this,I).add(M(v,D));return W.is0()?void 0:W}toAffine(v){return y(this,v)}isTorsionFree(){let{h:v,isTorsionFree:I}=e;if(v===Et)return !0;if(I)return I(w,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:v,clearCofactor:I}=e;return v===Et?this:I?I(w,this):this.multiplyUnsafe(e.h)}toRawBytes(v=!0){return dc("isCompressed",v),this.assertValidity(),r(w,this,v)}toHex(v=!0){return dc("isCompressed",v),mc(this.toRawBytes(v))}}w.BASE=new w(e.Gx,e.Gy,t.ONE),w.ZERO=new w(t.ZERO,t.ONE,t.ZERO);let{endo:S,nBitLength:C}=e,k=F6(w,S?Math.ceil(C/2):C);return {CURVE:e,ProjectivePoint:w,normPrivateKeyToScalar:h,weierstrassEquation:a,isWithinCurveOrder:l}}function iB(s){let e=iS(s);return ra(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function W6(s){let e=iB(s),{Fp:t,n,nByteLength:r,nBitLength:i}=e,a=t.BYTES+1,o=2*t.BYTES+1;function c(L){return Ht(L,n)}function u(L){return Tp(L,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:h,weierstrassEquation:m,isWithinCurveOrder:y}=rB({...e,toBytes(L,_,Q){let me=_.toAffine(),X=t.toBytes(me.x),j=uh;return dc("isCompressed",Q),Q?j(Uint8Array.from([_.hasEvenY()?2:3]),X):j(Uint8Array.from([4]),X,t.toBytes(me.y))},fromBytes(L){let _=L.length,Q=L[0],me=L.subarray(1);if(_===a&&(Q===2||Q===3)){let X=Cn(me);if(!op(X,Et,t.ORDER))throw new Error("Point is not on curve");let j=m(X),z;try{z=t.sqrt(j);}catch(xe){let Ve=xe instanceof Error?": "+xe.message:"";throw new Error("Point is not on curve"+Ve)}let Y=(z&Et)===Et;return (Q&1)===1!==Y&&(z=t.neg(z)),{x:X,y:z}}else if(_===o&&Q===4){let X=t.fromBytes(me.subarray(0,t.BYTES)),j=t.fromBytes(me.subarray(t.BYTES,2*t.BYTES));return {x:X,y:j}}else {let X=a,j=o;throw new Error("invalid Point, expected length of "+X+", or uncompressed "+j+", got "+_)}}});function g(L){let _=n>>Et;return L>_}function w(L){return g(L)?c(-L):L}let S=(L,_,Q)=>Cn(L.slice(_,Q));class C{constructor(_,Q,me){sa("r",_,Et,n),sa("s",Q,Et,n),this.r=_,this.s=Q,me!=null&&(this.recovery=me),Object.freeze(this);}static fromCompact(_){let Q=r;return _=os("compactSignature",_,Q*2),new C(S(_,0,Q),S(_,Q,2*Q))}static fromDER(_){let{r:Q,s:me}=Vn.toSig(os("DER",_));return new C(Q,me)}assertValidity(){}addRecoveryBit(_){return new C(this.r,this.s,_)}recoverPublicKey(_){let{r:Q,s:me,recovery:X}=this,j=F(os("msgHash",_));if(X==null||![0,1,2,3].includes(X))throw new Error("recovery id invalid");let z=X===2||X===3?Q+e.n:Q;if(z>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let Y=X&1?"03":"02",pe=l.fromHex(Y+aS(z,t.BYTES)),xe=u(z),Ve=c(-j*xe),jt=c(me*xe),He=l.BASE.multiplyAndAddUnsafe(pe,Ve,jt);if(!He)throw new Error("point at infinify");return He.assertValidity(),He}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new C(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return ch(this.toDERHex())}toDERHex(){return Vn.hexFromSig(this)}toCompactRawBytes(){return ch(this.toCompactHex())}toCompactHex(){let _=r;return aS(this.r,_)+aS(this.s,_)}}let k={isValidPrivateKey(L){try{return h(L),!0}catch{return !1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{let L=Xb(e.n);return H6(e.randomBytes(L),e.n)},precompute(L=8,_=l.BASE){return _._setWindowSize(L),_.multiply(BigInt(3)),_}};function x(L,_=!0){return l.fromPrivateKey(L).toRawBytes(_)}function v(L){if(typeof L=="bigint")return !1;if(L instanceof l)return !0;let Q=os("key",L).length,me=t.BYTES,X=me+1,j=2*me+1;if(!(e.allowedPrivateKeyLengths||r===X))return Q===X||Q===j}function I(L,_,Q=!0){if(v(L)===!0)throw new Error("first arg must be private key");if(v(_)===!1)throw new Error("second arg must be public key");return l.fromHex(_).multiply(h(L)).toRawBytes(Q)}let D=e.bits2int||function(L){if(L.length>8192)throw new Error("input is too large");let _=Cn(L),Q=L.length*8-i;return Q>0?_>>BigInt(Q):_},F=e.bits2int_modN||function(L){return c(D(L))},M=na(i);function W(L){return sa("num < 2^"+i,L,Dn,M),ta(L,r)}function ne(L,_,Q=q){if(["recovered","canonical"].some(ee=>ee in Q))throw new Error("sign() legacy options not supported");let{hash:me,randomBytes:X}=e,{lowS:j,prehash:z,extraEntropy:Y}=Q;j==null&&(j=!0),L=os("msgHash",L),G6(Q),z&&(L=os("prehashed msgHash",me(L)));let pe=F(L),xe=h(_),Ve=[W(xe),W(pe)];if(Y!=null&&Y!==!1){let ee=Y===!0?X(t.BYTES):Y;Ve.push(os("extraEntropy",ee));}let jt=uh(...Ve),He=pe;function ke(ee){let rs=D(ee);if(!y(rs))return;let Cs=u(rs),is=l.BASE.multiply(rs).toAffine(),De=c(is.x);if(De===Dn)return;let Ml=c(Cs*c(He+De*xe));if(Ml===Dn)return;let nc=(is.x===De?0:2)|Number(is.y&Et),zA=Ml;return j&&g(Ml)&&(zA=w(Ml),nc^=1),new C(De,zA,nc)}return {seed:jt,k2sig:ke}}let q={lowS:e.lowS,prehash:!1},J={lowS:e.lowS,prehash:!1};function ae(L,_,Q=q){let{seed:me,k2sig:X}=ne(L,_,Q),j=e;return X3(j.hash.outputLen,j.nByteLength,j.hmac)(me,X)}l.BASE._setWindowSize(8);function Be(L,_,Q,me=J){let X=L;_=os("msgHash",_),Q=os("publicKey",Q);let{lowS:j,prehash:z,format:Y}=me;if(G6(me),"strict"in me)throw new Error("options.strict was renamed to lowS");if(Y!==void 0&&Y!=="compact"&&Y!=="der")throw new Error("format must be compact or der");let pe=typeof X=="string"||fc(X),xe=!pe&&!Y&&typeof X=="object"&&X!==null&&typeof X.r=="bigint"&&typeof X.s=="bigint";if(!pe&&!xe)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let Ve,jt;try{if(xe&&(Ve=new C(X.r,X.s)),pe){try{Y!=="compact"&&(Ve=C.fromDER(X));}catch(nc){if(!(nc instanceof Vn.Err))throw nc}!Ve&&Y!=="der"&&(Ve=C.fromCompact(X));}jt=l.fromHex(Q);}catch{return !1}if(!Ve||j&&Ve.hasHighS())return !1;z&&(_=e.hash(_));let{r:He,s:ke}=Ve,ee=F(_),rs=u(ke),Cs=c(ee*rs),is=c(He*rs),De=l.BASE.multiplyAndAddUnsafe(jt,Cs,is)?.toAffine();return De?c(De.x)===He:!1}return {CURVE:e,getPublicKey:x,getSharedSecret:I,sign:ae,verify:Be,ProjectivePoint:l,Signature:C,utils:k}}function aB(s){return {hash:s,hmac:(e,...t)=>zb(s,e,g3(...t)),randomBytes:y3}}function Ic(s,e){let t=n=>W6({...s,...aB(n)});return {...t(e),create:t}}var Y6=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),J6=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),oB=BigInt(0),cB=BigInt(1),uS=BigInt(2),z6=(s,e)=>(s+e/uS)/e;function uB(s){let e=Y6,t=BigInt(3),n=BigInt(6),r=BigInt(11),i=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),u=s*s*s%e,l=u*u*s%e,h=gs(l,t,e)*l%e,m=gs(h,t,e)*l%e,y=gs(m,uS,e)*u%e,g=gs(y,r,e)*y%e,w=gs(g,i,e)*g%e,S=gs(w,o,e)*w%e,C=gs(S,c,e)*S%e,k=gs(C,o,e)*w%e,x=gs(k,t,e)*l%e,v=gs(x,a,e)*g%e,I=gs(v,n,e)*u%e,D=gs(I,uS,e);if(!lS.eql(lS.sqr(D),s))throw new Error("Cannot find square root");return D}var lS=Rn(Y6,void 0,void 0,{sqrt:uB}),ys=Ic({a:oB,b:BigInt(7),Fp:lS,n:J6,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:s=>{let e=J6,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-cB*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),r=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=t,a=BigInt("0x100000000000000000000000000000000"),o=z6(i*s,e),c=z6(-n*s,e),u=Ht(s-o*t-c*r,e),l=Ht(-o*n-c*i,e),h=u>a,m=l>a;if(h&&(u=e-u),m&&(l=e-l),u>a||l>a)throw new Error("splitScalar: Endomorphism failed, k="+s);return {k1neg:h,k1:u,k2neg:m,k2:l}}}},hc);function Dp(s,e={}){let{recovered:t}=e;if(typeof s.r>"u")throw new Cc({signature:s});if(typeof s.s>"u")throw new Cc({signature:s});if(t&&typeof s.yParity>"u")throw new Cc({signature:s});if(s.r<0n||s.r>$b)throw new Op({value:s.r});if(s.s<0n||s.s>$b)throw new Rp({value:s.s});if(typeof s.yParity=="number"&&s.yParity!==0&&s.yParity!==1)throw new ma({value:s.yParity})}function Z6(s){return hS(Ee(s))}function hS(s){if(s.length!==130&&s.length!==132)throw new Bp({signature:s});let e=BigInt(rt(s,0,32)),t=BigInt(rt(s,32,64)),n=(()=>{let r=+`0x${s.slice(130)}`;if(!Number.isNaN(r))try{return Lp(r)}catch{throw new ma({value:r})}})();return typeof n>"u"?{r:e,s:t}:{r:e,s:t,yParity:n}}function Up(s){if(!(typeof s.r>"u")&&!(typeof s.s>"u"))return Nh(s)}function Nh(s){let e=typeof s=="string"?hS(s):s instanceof Uint8Array?Z6(s):typeof s.r=="string"?eC(s):s.v?X6(s):{r:s.r,s:s.s,...typeof s.yParity<"u"?{yParity:s.yParity}:{}};return Dp(e),e}function lB(s){return Q6(Ee(s))}function Q6(s){let{r:e,s:t}=ys.Signature.fromDER(Yt(s).slice(2));return {r:e,s:t}}function X6(s){return {r:s.r,s:s.s,yParity:Lp(s.v)}}function eC(s){let e=(()=>{let t=s.v?Number(s.v):void 0,n=s.yParity?Number(s.yParity):void 0;if(typeof t=="number"&&typeof n!="number"&&(n=Lp(t)),typeof n!="number")throw new ma({value:s.yParity});return n})();return {r:BigInt(s.r),s:BigInt(s.s),yParity:e}}function fS(s){let[e,t,n]=s;return Nh({r:t==="0x"?0n:BigInt(t),s:n==="0x"?0n:BigInt(n),yParity:e==="0x"?0:Number(e)})}function hB(s){return Ye(tC(s))}function tC(s){Dp(s);let e=s.r,t=s.s;return Fe(le(e,{size:32}),le(t,{size:32}),typeof s.yParity=="number"?le(pS(s.yParity),{size:1}):"0x")}function fB(s){return new ys.Signature(s.r,s.s).toDERRawBytes()}function dB(s){return `0x${new ys.Signature(s.r,s.s).toDERHex()}`}function mB(s){return {r:s.r,s:s.s,v:pS(s.yParity)}}function dS(s){let{r:e,s:t,yParity:n}=s;return {r:le(e,{size:32}),s:le(t,{size:32}),yParity:n===0?"0x0":"0x1"}}function mS(s){let{r:e,s:t,yParity:n}=s;return [n?"0x01":"0x",e===0n?"0x":aa(le(e)),t===0n?"0x":aa(le(t))]}function pB(s,e={}){try{return Dp(s,e),!0}catch{return !1}}function Lp(s){if(s===0||s===27)return 0;if(s===1||s===28)return 1;if(s>=35)return s%2===0?1:0;throw new Vp({value:s})}function pS(s){if(s===0)return 27;if(s===1)return 28;throw new ma({value:s})}var Bp=class extends K{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Oe(Yt(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"});}},Cc=class extends K{constructor({signature:e}){super(`Signature \`${Ds(e)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"});}},Op=class extends K{constructor({value:e}){super(`Value \`${e}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"});}},Rp=class extends K{constructor({value:e}){super(`Value \`${e}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"});}},ma=class extends K{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"});}},Vp=class extends K{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"});}};var gB=new TextEncoder,yB=new TextDecoder,jp=Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((s,e)=>[e,s.charCodeAt(0)])),Hp={...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((s,e)=>[s.charCodeAt(0),e])),61:0,45:62,95:63};function wB(s,e={}){let{pad:t=!0,url:n=!1}=e,r=new Uint8Array(Math.ceil(s.length/3)*4);for(let c=0,u=0;u<s.length;c+=4,u+=3){let l=(s[u]<<16)+(s[u+1]<<8)+(s[u+2]|0);r[c]=jp[l>>18],r[c+1]=jp[l>>12&63],r[c+2]=jp[l>>6&63],r[c+3]=jp[l&63];}let i=s.length%3,a=Math.floor(s.length/3)*4+(i&&i+1),o=yB.decode(new Uint8Array(r.buffer,0,a));return t&&i===1&&(o+="=="),t&&i===2&&(o+="="),n&&(o=o.replaceAll("+","-").replaceAll("/","_")),o}function sC(s,e={}){return wB(Ye(s),e)}function kh(s){let e=s.replace(/=+$/,""),t=e.length,n=new Uint8Array(t+3);gB.encodeInto(e+"===",n);for(let i=0,a=0;i<e.length;i+=4,a+=3){let o=(Hp[n[i]]<<18)+(Hp[n[i+1]]<<12)+(Hp[n[i+2]]<<6)+Hp[n[i+3]];n[a]=o>>16,n[a+1]=o>>8&255,n[a+2]=o&255;}let r=(t>>2)*3+(t%4&&t%4-1);return new Uint8Array(n.buffer,0,r)}var Ot={};be(Ot,{createKeyPair:()=>SB,getPublicKey:()=>iC,getSharedSecret:()=>vB,noble:()=>bB,randomPrivateKey:()=>aC,recoverAddress:()=>oC,recoverPublicKey:()=>cC,sign:()=>xB,verify:()=>EB});var _p=!1;var bB=ys;function SB(s={}){let{as:e="Hex"}=s,t=aC({as:e}),n=iC({privateKey:t});return {privateKey:t,publicKey:n}}function iC(s){let{privateKey:e}=s,t=ys.ProjectivePoint.fromPrivateKey(Yt(e).slice(2));return Bn(t)}function vB(s){let{as:e="Hex",privateKey:t,publicKey:n}=s,a=ys.ProjectivePoint.fromHex(kr(n).slice(2)).multiply(ys.utils.normPrivateKeyToScalar(Yt(t).slice(2))).toRawBytes(!0);return e==="Hex"?Ee(a):a}function aC(s={}){let{as:e="Hex"}=s,t=ys.utils.randomPrivateKey();return e==="Hex"?Ee(t):t}function oC(s){return Lb(cC(s))}function cC(s){let{payload:e,signature:t}=s,{r:n,s:r,yParity:i}=t,o=new ys.Signature(BigInt(n),BigInt(r)).addRecoveryBit(i).recoverPublicKey(Yt(e).substring(2));return Bn(o)}function xB(s){let{extraEntropy:e=_p,hash:t,payload:n,privateKey:r}=s,{r:i,s:a,recovery:o}=ys.sign(Pn(n),Pn(r),{extraEntropy:typeof e=="boolean"?e:Yt(e).slice(2),lowS:!0,...t?{prehash:!0}:{}});return {r:i,s:a,yParity:o}}function EB(s){let{address:e,hash:t,payload:n,publicKey:r,signature:i}=s;return e?jb(e,oC({payload:n,signature:i})):ys.verify(i,Pn(n),m6(r),...t?[{prehash:!0,lowS:!0}]:[])}function uC(s,e={}){return {...s,blockNumber:s.blockNumber?BigInt(s.blockNumber):null,logIndex:s.logIndex?Number(s.logIndex):null,transactionIndex:s.transactionIndex?Number(s.transactionIndex):null}}function lC(s,e={}){return {address:s.address,blockHash:s.blockHash,blockNumber:typeof s.blockNumber=="bigint"?le(s.blockNumber):null,data:s.data,logIndex:typeof s.logIndex=="number"?le(s.logIndex):null,topics:s.topics,transactionHash:s.transactionHash,transactionIndex:typeof s.transactionIndex=="number"?le(s.transactionIndex):null,removed:s.removed}}var Nc={};be(Nc,{createKeyPair:()=>BB,getPublicKey:()=>pC,getSharedSecret:()=>OB,noble:()=>TB,randomPrivateKey:()=>gC,recoverPublicKey:()=>RB,sign:()=>VB,verify:()=>wS});var fC=Rn(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),AB=fC.create(BigInt("-3")),IB=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),gS=Ic({a:AB,b:IB,Fp:fC,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},hc);var dC=Rn(BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff")),CB=dC.create(BigInt("-3")),NB=BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef");Ic({a:CB,b:NB,Fp:dC,n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"),h:BigInt(1),lowS:!1},G3);var mC=Rn(BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")),kB=mC.create(BigInt("-3")),PB=BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00");Ic({a:kB,b:PB,Fp:mC,n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"),h:BigInt(1),lowS:!1,allowedPrivateKeyLengths:[130,131,132]},K3);var yS=gS,Un=gS;var TB=Un;function BB(s={}){let{as:e="Hex"}=s,t=gC({as:e}),n=pC({privateKey:t});return {privateKey:t,publicKey:n}}function pC(s){let{privateKey:e}=s,t=Un.ProjectivePoint.fromPrivateKey(typeof e=="string"?e.slice(2):Ee(e).slice(2));return Bn(t)}function OB(s){let{as:e="Hex",privateKey:t,publicKey:n}=s,r=Un.ProjectivePoint.fromHex(kr(n).slice(2)),i=typeof t=="string"?t.slice(2):Ee(t).slice(2),o=r.multiply(Un.utils.normPrivateKeyToScalar(i)).toRawBytes(!0);return e==="Hex"?Ee(o):o}function gC(s={}){let{as:e="Hex"}=s,t=Un.utils.randomPrivateKey();return e==="Hex"?Ee(t):t}function RB(s){let{payload:e,signature:t}=s,{r:n,s:r,yParity:i}=t,a=new Un.Signature(BigInt(n),BigInt(r)).addRecoveryBit(i),o=e instanceof Uint8Array?Ee(e):e,c=a.recoverPublicKey(o.substring(2));return Bn(c)}function VB(s){let{extraEntropy:e=_p,hash:t,payload:n,privateKey:r}=s,{r:i,s:a,recovery:o}=Un.sign(n instanceof Uint8Array?n:Ye(n),r instanceof Uint8Array?r:Ye(r),{extraEntropy:typeof e=="boolean"?e:Yt(e).slice(2),lowS:!0,...t?{prehash:!0}:{}});return {r:i,s:a,yParity:o}}function wS(s){let{hash:e,payload:t,publicKey:n,signature:r}=s;return Un.verify(r,t instanceof Uint8Array?t:Ye(t),kr(n).substring(2),...e?[{prehash:!0,lowS:!0}]:[])}var Mp={};be(Mp,{encode:()=>yC,getSignPayload:()=>DB});function yC(s){let e=Yt(s);return Fe("0x19",cs(`Ethereum Signed Message:
|
|
341
|
+
`+Oe(e)),e)}function DB(s){return dt(yC(s))}var wC={wei:0,gwei:9,szabo:12,finney:15,ether:18};function UB(s,e=0){let t=s.toString(),n=t.startsWith("-");n&&(t=t.slice(1)),t=t.padStart(e,"0");let[r,i]=[t.slice(0,t.length-e),t.slice(t.length-e)];return i=i.replace(/(0+)$/,""),`${n?"-":""}${r||"0"}${i?`.${i}`:""}`}function $p(s,e="wei"){return UB(s,wC.gwei-wC[e])}var qp=class extends K{constructor({feeCap:e}={}){super(`The fee cap (\`maxFeePerGas\`/\`maxPriorityFeePerGas\`${e?` = ${$p(e)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TransactionEnvelope.FeeCapTooHighError"});}};var Fp=class extends K{constructor({chainId:e}){super(typeof e<"u"?`Chain ID "${e}" is invalid.`:"Chain ID is invalid."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TransactionEnvelope.InvalidChainIdError"});}},Kp=class extends K{constructor({attributes:e,serialized:t,type:n}){let r=Object.entries(e).map(([i,a])=>typeof a>"u"?i:void 0).filter(Boolean);super(`Invalid serialized transaction of type "${n}" was provided.`,{metaMessages:[`Serialized Transaction: "${t}"`,r.length>0?`Missing Attributes: ${r.join(", ")}`:""].filter(Boolean)}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TransactionEnvelope.InvalidSerializedError"});}},Gp=class extends K{constructor({maxPriorityFeePerGas:e,maxFeePerGas:t}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${e?` = ${$p(e)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${t?` = ${$p(t)} gwei`:""}).`].join(`
|
|
342
|
+
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TransactionEnvelope.TipAboveFeeCapError"});}};var pa={};be(pa,{assert:()=>Ph,deserialize:()=>xC,from:()=>LB,getSignPayload:()=>jB,hash:()=>EC,serialize:()=>AC,serializedType:()=>vC,toRpc:()=>HB,type:()=>bS,validate:()=>_B});var vC="0x02",bS="eip1559";function Ph(s){let{chainId:e,maxPriorityFeePerGas:t,maxFeePerGas:n,to:r}=s;if(e<=0)throw new Fp({chainId:e});if(r&&Qt(r,{strict:!1}),n&&BigInt(n)>2n**256n-1n)throw new qp({feeCap:n});if(t&&n&&t>n)throw new Gp({maxFeePerGas:n,maxPriorityFeePerGas:t})}function xC(s){let e=N6(rt(s,1)),[t,n,r,i,a,o,c,u,l,h,m,y]=e;if(!(e.length===9||e.length===12))throw new Kp({attributes:{chainId:t,nonce:n,maxPriorityFeePerGas:r,maxFeePerGas:i,gas:a,to:o,value:c,data:u,accessList:l,...e.length>9?{yParity:h,r:m,s:y}:{}},serialized:s,type:bS});let g={chainId:Number(t),type:bS};Zt(o)&&o!=="0x"&&(g.to=o),Zt(a)&&a!=="0x"&&(g.gas=BigInt(a)),Zt(u)&&u!=="0x"&&(g.data=u),Zt(n)&&(g.nonce=n==="0x"?0n:BigInt(n)),Zt(c)&&c!=="0x"&&(g.value=BigInt(c)),Zt(i)&&i!=="0x"&&(g.maxFeePerGas=BigInt(i)),Zt(r)&&r!=="0x"&&(g.maxPriorityFeePerGas=BigInt(r)),l.length!==0&&l!=="0x"&&(g.accessList=E6(l));let w=m&&y&&h?fS([h,m,y]):void 0;return w&&(g={...g,...w}),Ph(g),g}function LB(s,e={}){let{signature:t}=e,n=typeof s=="string"?xC(s):s;return Ph(n),{...n,...t?Nh(t):{},type:"eip1559"}}function jB(s){return EC(s,{presign:!0})}function EC(s,e={}){let{presign:t}=e;return dt(AC({...s,...t?{r:void 0,s:void 0,yParity:void 0,v:void 0}:{}}))}function AC(s,e={}){let{chainId:t,gas:n,nonce:r,to:i,value:a,maxFeePerGas:o,maxPriorityFeePerGas:c,accessList:u,data:l,input:h}=s;Ph(s);let m=A6(u),y=Up(e.signature||s),g=[le(t),r?le(r):"0x",c?le(c):"0x",o?le(o):"0x",n?le(n):"0x",i??"0x",a?le(a):"0x",l??h??"0x",m,...y?mS(y):[]];return Fe(vC,P6(g))}function HB(s){let e=Up(s);return {...s,chainId:le(s.chainId),data:s.data??s.input,type:"0x2",...typeof s.gas=="bigint"?{gas:le(s.gas)}:{},...typeof s.nonce=="bigint"?{nonce:le(s.nonce)}:{},...typeof s.value=="bigint"?{value:le(s.value)}:{},...typeof s.maxFeePerGas=="bigint"?{maxFeePerGas:le(s.maxFeePerGas)}:{},...typeof s.maxPriorityFeePerGas=="bigint"?{maxPriorityFeePerGas:le(s.maxPriorityFeePerGas)}:{},...e?dS(e):{}}}function _B(s){try{return Ph(s),!0}catch{return !1}}var kc={};be(kc,{fromRpc:()=>MB,fromRpcStatus:()=>IC,fromRpcType:()=>NC,toRpc:()=>$B,toRpcStatus:()=>CC,toRpcType:()=>kC});var IC={"0x0":"reverted","0x1":"success"},CC={reverted:"0x0",success:"0x1"},NC={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"},kC={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function MB(s){return s?{...s,blobGasPrice:s.blobGasPrice?BigInt(s.blobGasPrice):void 0,blobGasUsed:s.blobGasUsed?BigInt(s.blobGasUsed):void 0,blockNumber:BigInt(s.blockNumber??0n),cumulativeGasUsed:BigInt(s.cumulativeGasUsed??0n),effectiveGasPrice:BigInt(s.effectiveGasPrice??0n),gasUsed:BigInt(s.gasUsed??0n),logs:s.logs.map(e=>uC(e,{pending:!1})),status:IC[s.status],transactionIndex:Number(s.transactionIndex??0),type:NC[s.type]||s.type}:null}function $B(s){return {blobGasPrice:s.blobGasPrice?le(s.blobGasPrice):void 0,blobGasUsed:s.blobGasUsed?le(s.blobGasUsed):void 0,blockHash:s.blockHash,blockNumber:le(s.blockNumber),contractAddress:s.contractAddress,cumulativeGasUsed:le(s.cumulativeGasUsed),effectiveGasPrice:le(s.effectiveGasPrice),from:s.from,gasUsed:le(s.gasUsed),logs:s.logs.map(lC),logsBloom:s.logsBloom,root:s.root,status:CC[s.status],to:s.to,transactionHash:s.transactionHash,transactionIndex:le(s.transactionIndex),type:kC[s.type]??s.type}}var Th={};be(Th,{BytesSizeMismatchError:()=>Wp,InvalidDomainError:()=>Jp,InvalidPrimaryTypeError:()=>zp,InvalidStructTypeError:()=>Yp,assert:()=>SS,domainSeparator:()=>qB,encode:()=>PC,encodeData:()=>AS,encodeField:()=>IS,encodeType:()=>TC,extractEip712DomainTypes:()=>Zp,findTypeDependencies:()=>CS,getSignPayload:()=>vS,hashDomain:()=>xS,hashStruct:()=>ES,hashType:()=>BC,serialize:()=>FB,validate:()=>KB});function SS(s){let{domain:e,message:t,primaryType:n,types:r}=s,i=(a,o)=>{for(let c of a){let{name:u,type:l}=c,h=o[u],m=l.match(xc);if(m&&(typeof h=="number"||typeof h=="bigint")){let[,w,S]=m;le(h,{signed:w==="int",size:Number.parseInt(S??"",10)/8});}if(l==="address"&&typeof h=="string"&&!ua(h))throw new ca({address:h,cause:new bc});let y=l.match(vp);if(y){let[,w]=y;if(w&&Oe(h)!==Number.parseInt(w,10))throw new Wp({expectedSize:Number.parseInt(w,10),givenSize:Oe(h)})}let g=r[l];g&&(GB(l),i(g,h));}};if(r.EIP712Domain&&e){if(typeof e!="object")throw new Jp({domain:e});i(r.EIP712Domain,e);}if(n!=="EIP712Domain")if(r[n])i(r[n],t);else throw new zp({primaryType:n,types:r})}function qB(s){return xS({domain:s})}function PC(s){let{domain:e={},message:t,primaryType:n}=s,r={EIP712Domain:Zp(e),...s.types};SS({domain:e,message:t,primaryType:n,types:r});let i=["0x19","0x01"];return e&&i.push(xS({domain:e,types:r})),n!=="EIP712Domain"&&i.push(ES({data:t,primaryType:n,types:r})),Fe(...i)}function TC(s){let{primaryType:e,types:t}=s,n="",r=CS({primaryType:e,types:t});r.delete(e);let i=[e,...Array.from(r).sort()];for(let a of i)n+=`${a}(${(t[a]??[]).map(({name:o,type:c})=>`${c} ${o}`).join(",")})`;return n}function Zp(s){return [typeof s?.name=="string"&&{name:"name",type:"string"},s?.version&&{name:"version",type:"string"},(typeof s?.chainId=="number"||typeof s?.chainId=="bigint")&&{name:"chainId",type:"uint256"},s?.verifyingContract&&{name:"verifyingContract",type:"address"},s?.salt&&{name:"salt",type:"bytes32"}].filter(Boolean)}function vS(s){return dt(PC(s))}function xS(s){let{domain:e,types:t}=s;return ES({data:e,primaryType:"EIP712Domain",types:{...t,EIP712Domain:t?.EIP712Domain||Zp(e)}})}function ES(s){let{data:e,primaryType:t,types:n}=s,r=AS({data:e,primaryType:t,types:n});return dt(r)}function FB(s){let{domain:e,message:t,primaryType:n,types:r}=s,i=(c,u)=>{let l={...u};for(let h of c){let{name:m,type:y}=h;y==="address"&&(l[m]=l[m].toLowerCase());}return l},a=(()=>{if(!e)return {};let c=r.EIP712Domain??Zp(e);return i(c,e)})(),o=(()=>{if(n!=="EIP712Domain")return r[n]?i(r[n],t):{}})();return Ds({domain:a,message:o,primaryType:n,types:r},(c,u)=>typeof u=="bigint"?u.toString():u)}function KB(s){try{return SS(s),!0}catch{return !1}}var Wp=class extends K{constructor({expectedSize:e,givenSize:t}){super(`Expected bytes${e}, got bytes${t}.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TypedData.BytesSizeMismatchError"});}},Jp=class extends K{constructor({domain:e}){super(`Invalid domain "${Ds(e)}".`,{metaMessages:["Must be a valid EIP-712 domain."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TypedData.InvalidDomainError"});}},zp=class extends K{constructor({primaryType:e,types:t}){super(`Invalid primary type \`${e}\` must be one of \`${JSON.stringify(Object.keys(t))}\`.`,{metaMessages:["Check that the primary type is a key in `types`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TypedData.InvalidPrimaryTypeError"});}},Yp=class extends K{constructor({type:e}){super(`Struct type "${e}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TypedData.InvalidStructTypeError"});}};function AS(s){let{data:e,primaryType:t,types:n}=s,r=[{type:"bytes32"}],i=[BC({primaryType:t,types:n})];for(let a of n[t]??[]){let[o,c]=IS({types:n,name:a.name,type:a.type,value:e[a.name]});r.push(o),i.push(c);}return On(r,i)}function BC(s){let{primaryType:e,types:t}=s,n=cs(TC({primaryType:e,types:t}));return dt(n)}function IS(s){let{types:e,name:t,type:n,value:r}=s;if(e[n]!==void 0)return [{type:"bytes32"},dt(AS({data:r,primaryType:n,types:e}))];if(n==="bytes")return r=`0x${(r.length%2?"0":"")+r.slice(2)}`,[{type:"bytes32"},dt(r,{as:"Hex"})];if(n==="string")return [{type:"bytes32"},dt(Tn(r),{as:"Hex"})];if(n.lastIndexOf("]")===n.length-1){let i=n.slice(0,n.lastIndexOf("[")),a=r.map(o=>IS({name:t,type:i,types:e,value:o}));return [{type:"bytes32"},dt(On(a.map(([o])=>o),a.map(([,o])=>o)))]}return [{type:n},r]}function CS(s,e=new Set){let{primaryType:t,types:n}=s,i=t.match(/^\w*/u)?.[0];if(e.has(i)||n[i]===void 0)return e;e.add(i);for(let a of n[i])CS({primaryType:a.type,types:n},e);return e}function GB(s){if(s==="address"||s==="bool"||s==="string"||s.startsWith("bytes")||s.startsWith("uint")||s.startsWith("int"))throw new Yp({type:s})}var Tr={};be(Tr,{CredentialCreationFailedError:()=>Pr,CredentialRequestFailedError:()=>Bh,createChallenge:()=>VC,createCredential:()=>JB,getAuthenticatorData:()=>DC,getClientDataJSON:()=>UC,getCredentialCreationOptions:()=>LC,getCredentialRequestOptions:()=>jC,getSignPayload:()=>zB,sign:()=>YB,verify:()=>ZB});function OC(s){let e=s[4]===0?5:4,t=e+32,n=s[t+2]===0?t+3:t+2,r=BigInt(Ee(s.slice(e,t))),i=BigInt(Ee(s.slice(n)));return {r,s:i>yS.CURVE.n/2n?yS.CURVE.n-i:i}}async function RC(s){try{let e=s.getPublicKey();if(!e)throw new Pr;let t=new Uint8Array(e),n=await crypto.subtle.importKey("spki",new Uint8Array(t),{name:"ECDSA",namedCurve:"P-256",hash:"SHA-256"},!0,["verify"]),r=new Uint8Array(await crypto.subtle.exportKey("raw",n));return Bn(r)}catch(e){if(e.message!=="Permission denied to access object")throw e;let t=new Uint8Array(s.attestationObject),n=32,r=88,i=c=>{let u=new Uint8Array([c,r,n]);for(let l=0;l<t.length-u.length;l++)if(u.every((h,m)=>t[l+m]===h))return l+u.length;throw new Pr},a=i(33),o=i(34);return Bn(new Uint8Array([4,...t.slice(a,a+n),...t.slice(o,o+n)]))}}var VC=Uint8Array.from([105,171,180,181,160,222,75,198,42,42,32,31,141,37,186,233]);async function JB(s){let{createFn:e=window.navigator.credentials.create.bind(window.navigator.credentials),...t}=s,n=LC(t);try{let r=await e(n);if(!r)throw new Pr;let i=r.response,a=await RC(i);return {id:r.id,publicKey:a,raw:r}}catch(r){throw new Pr({cause:r})}}function DC(s={}){let{flag:e=5,rpId:t=window.location.hostname,signCount:n=0}=s,r=wh(cs(t)),i=le(e,{size:1}),a=le(n,{size:4});return Fe(r,i,a)}function UC(s){let{challenge:e,crossOrigin:t=!1,extraClientData:n,origin:r=window.location.origin}=s;return JSON.stringify({type:"webauthn.get",challenge:sC(e,{url:!0,pad:!1}),origin:r,crossOrigin:t,...n})}function LC(s){let{attestation:e="none",authenticatorSelection:t={residentKey:"preferred",requireResidentKey:!1,userVerification:"required"},challenge:n=VC,excludeCredentialIds:r,extensions:i,name:a,rp:o={id:window.location.hostname,name:window.document.title},user:c}=s,u=c?.name??a;return {publicKey:{attestation:e,authenticatorSelection:t,challenge:typeof n=="string"?Ye(n):n,...r?{excludeCredentials:r?.map(l=>({id:kh(l),type:"public-key"}))}:{},pubKeyCredParams:[{type:"public-key",alg:-7}],...i&&{extensions:i},rp:o,user:{id:c?.id??dt(Tn(u),{as:"Bytes"}),name:u,displayName:c?.displayName??u}}}}function jC(s){let{credentialId:e,challenge:t,extensions:n,rpId:r=window.location.hostname,userVerification:i="required"}=s;return {publicKey:{...e?{allowCredentials:Array.isArray(e)?e.map(a=>({id:kh(a),type:"public-key"})):[{id:kh(e),type:"public-key"}]}:{},challenge:Ye(t),...n&&{extensions:n},rpId:r,userVerification:i}}}function zB(s){let{challenge:e,crossOrigin:t,extraClientData:n,flag:r,origin:i,rpId:a,signCount:o,userVerification:c="required"}=s,u=DC({flag:r,rpId:a,signCount:o}),l=UC({challenge:e,crossOrigin:t,extraClientData:n,origin:i}),h=wh(cs(l)),m=l.indexOf('"challenge"'),y=l.indexOf('"type"'),g={authenticatorData:u,clientDataJSON:l,challengeIndex:m,typeIndex:y,userVerificationRequired:c==="required"},w=Fe(u,h);return {metadata:g,payload:w}}async function YB(s){let{getFn:e=window.navigator.credentials.get.bind(window.navigator.credentials),...t}=s,n=jC(t);try{let r=await e(n);if(!r)throw new Bh;let i=r.response,a=String.fromCharCode(...new Uint8Array(i.clientDataJSON)),o=a.indexOf('"challenge"'),c=a.indexOf('"type"'),u=OC(new Uint8Array(i.signature));return {metadata:{authenticatorData:Ee(new Uint8Array(i.authenticatorData)),clientDataJSON:a,challengeIndex:o,typeIndex:c,userVerificationRequired:n.publicKey.userVerification==="required"},signature:u,raw:r}}catch(r){throw new Bh({cause:r})}}function ZB(s){let{challenge:e,hash:t=!0,metadata:n,publicKey:r,signature:i}=s,{authenticatorData:a,challengeIndex:o,clientDataJSON:c,typeIndex:u,userVerificationRequired:l}=n,h=Ye(a);if(h.length<37)return !1;let m=h[32];if((m&1)!==1||l&&(m&4)!==4||(m&8)!==8&&(m&16)===16)return !1;if(u!==void 0){let k='"type":"webauthn.get"';if(k!==c.slice(Number(u),k.length+1))return !1}let y=o!==void 0?c.slice(Number(o)).match(/^"challenge":"(.*?)"/):c.match(/"challenge":"(.*?)"/);if(!y)return !1;let[g,w]=y;if(Ee(kh(w))!==e)return !1;let S=wh(Tn(c),{as:"Bytes"}),C=Nb(h,S);return wS({hash:t,payload:C,publicKey:r,signature:i})}var Pr=class extends K{constructor({cause:e}={}){super("Failed to create credential.",{cause:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"WebAuthnP256.CredentialCreationFailedError"});}},Bh=class extends K{constructor({cause:e}={}){super("Failed to request credential.",{cause:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"WebAuthnP256.CredentialRequestFailedError"});}};var Vc={};be(Vc,{from:()=>qO});var Pe={};be(Pe,{configFromJson:()=>HO,configToJson:()=>jO,evaluateConfigurationSafety:()=>MO,findSignerLeaf:()=>Uh,flatLeavesToTopology:()=>ov,getSigners:()=>LO,getWeight:()=>Lh,hasInvalidValues:()=>Oc,hashConfiguration:()=>qt,isAnyAddressSubdigestLeaf:()=>Hs,isConfig:()=>Rc,isLeaf:()=>s5,isNestedLeaf:()=>es,isNode:()=>mt,isNodeLeaf:()=>Ct,isSapientSignerLeaf:()=>$t,isSignerLeaf:()=>Mt,isSubdigestLeaf:()=>js,isTopology:()=>Bc,maximumDepth:()=>jh,mergeTopology:()=>dg,normalizeSignerSignature:()=>_O,replaceAddress:()=>fg,topologyToFlatLeaves:()=>ug});var Rt={};be(Rt,{FLAG_ADDRESS:()=>QS,FLAG_BRANCH:()=>ev,FLAG_NESTED:()=>sv,FLAG_NODE:()=>sg,FLAG_SIGNATURE_ANY_ADDRESS_SUBDIGEST:()=>rv,FLAG_SIGNATURE_ERC1271:()=>XS,FLAG_SIGNATURE_ETH_SIGN:()=>nv,FLAG_SIGNATURE_HASH:()=>ZS,FLAG_SIGNATURE_SAPIENT:()=>ng,FLAG_SIGNATURE_SAPIENT_COMPACT:()=>iv,FLAG_SUBDIGEST:()=>tv,decodeSignature:()=>ZC,encodeChainedSignature:()=>QC,encodeSignature:()=>XC,encodeTopology:()=>Rh,fillLeaves:()=>Xp,isRawConfig:()=>og,isRawLeaf:()=>YC,isRawNestedLeaf:()=>Dh,isRawNode:()=>rg,isRawSignature:()=>zC,isRawSignerLeaf:()=>Vh,isRawTopology:()=>ig,isSignatureOfSapientSignerLeaf:()=>BO,isSignedSapientSignerLeaf:()=>av,isSignedSignerLeaf:()=>cg,parseBranch:()=>ag,rawSignatureFromJson:()=>VO,rawSignatureToJson:()=>OO,recover:()=>zS});var _e={};be(_e,{DEPLOY:()=>HC,DefaultGuestAddress:()=>eO,EXECUTE:()=>rO,EXECUTE_USER_OP:()=>PS,GET_IMPLEMENTATION:()=>tO,GET_LIMIT_USAGE:()=>uO,IMAGE_HASH:()=>sO,INCREMENT_USAGE_LIMIT:()=>cO,IS_VALID_SIGNATURE:()=>Oh,PlaceholderAddress:()=>XB,READ_ENTRYPOINT:()=>oO,READ_NONCE:()=>nO,READ_NONCE_4337:()=>aO,RECOVER_SAPIENT_SIGNATURE:()=>NS,RECOVER_SAPIENT_SIGNATURE_COMPACT:()=>kS,UPDATE_IMAGE_HASH:()=>iO,ZeroAddress:()=>QB});var QB="0x0000000000000000000000000000000000000000",XB="0xffff0000ffff0000ffff0000ffff0000ffff0000",eO="0x0000000000006Ac72ed1d192fa28f0058D3F8806",Oh=at.from(["function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4 magicValue)"])[0],HC=at.from(["function deploy(address _mainModule, bytes32 _salt) public payable returns (address _contract)"])[0],tO=at.from(["function getImplementation() external view returns (address)"])[0],sO=at.from(["function imageHash() external view returns (bytes32)"])[0],nO=at.from(["function readNonce(uint256 _space) public view returns (uint256)"])[0],rO=at.from(["function execute(bytes calldata _payload, bytes calldata _signature) external"])[0],iO=at.from(["function updateImageHash(bytes32 _imageHash) external"])[0],NS=at.from(["function recoverSapientSignature((uint8 kind,bool noChainId,(address to,uint256 value,bytes data,uint256 gasLimit,bool delegateCall,bool onlyFallback,uint256 behaviorOnError)[] calls,uint256 space,uint256 nonce,bytes message,bytes32 imageHash,bytes32 digest,address[] parentWallets) calldata _payload, bytes calldata _signature) external view returns (bytes32)"])[0],kS=at.from(["function recoverSapientSignatureCompact(bytes32 _digest, bytes calldata _signature) external view returns (bytes32)"])[0],PS=at.from(["function executeUserOp(bytes calldata _userOp) external"])[0],aO=at.from(["function getNonce(address _account, uint192 _key) public view returns (uint256)"])[0],oO=at.from(["function entrypoint() public view returns (address)"])[0],cO=at.from([{type:"function",name:"incrementUsageLimit",inputs:[{name:"limits",type:"tuple[]",internalType:"struct UsageLimit[]",components:[{name:"usageHash",type:"bytes32",internalType:"bytes32"},{name:"usageAmount",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"nonpayable"}])[0],uO=at.from(["function getLimitUsage(address wallet, bytes32 usageHash) public view returns (uint256)"])[0];var Ln={};be(Ln,{InvalidWrappedSignatureError:()=>Qp,assert:()=>BS,from:()=>fO,magicBytes:()=>TS,universalSignatureValidatorAbi:()=>hO,universalSignatureValidatorBytecode:()=>lO,unwrap:()=>_C,validate:()=>mO,wrap:()=>dO});var TS="0x6492649264926492649264926492649264926492649264926492649264926492",lO="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",hO=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}];function BS(s){if(rt(s,-32)!==TS)throw new Qp(s)}function fO(s){return typeof s=="string"?_C(s):s}function _C(s){BS(s);let[e,t,n]=Ac(kp("address, bytes, bytes"),s);return {data:t,signature:n,to:e}}function dO(s){let{data:e,signature:t,to:n}=s;return Fe(On(kp("address, bytes, bytes"),[n,e,t]),TS)}function mO(s){try{return BS(s),!0}catch{return !1}}var Qp=class extends K{constructor(e){super(`Value \`${e}\` is an invalid ERC-6492 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"});}};function OS(s,{to:e,data:t}){let n=E.concat(ot.encode([{type:"address"},{type:"bytes"},{type:"bytes"}],[e,E.from(t),E.from(s)]),Ln.magicBytes);switch(typeof s){case"object":return E.toBytes(n);case"string":return n}}function MC(s){switch(typeof s){case"object":if(f.toHex(s.subarray(-Ln.magicBytes.slice(2).length/2))===Ln.magicBytes){let[e,t,n]=ot.decode([{type:"address"},{type:"bytes"},{type:"bytes"}],s.subarray(0,-Ln.magicBytes.slice(2).length/2));return {signature:E.toBytes(n),erc6492:{to:e,data:E.toBytes(t)}}}else return {signature:s};case"string":if(s.endsWith(Ln.magicBytes.slice(2)))try{let[e,t,n]=ot.decode([{type:"address"},{type:"bytes"},{type:"bytes"}],s.slice(0,-Ln.magicBytes.slice(2).length));return {signature:n,erc6492:{to:e,data:t}}}catch{return {signature:s}}else return {signature:s}}}var ce={};be(ce,{BEHAVIOR_ABORT_ON_ERROR:()=>MS,BEHAVIOR_IGNORE_ERROR:()=>HS,BEHAVIOR_REVERT_ON_ERROR:()=>_S,KIND_CONFIG_UPDATE:()=>LS,KIND_DIGEST:()=>jS,KIND_MESSAGE:()=>US,KIND_TRANSACTIONS:()=>DS,decode:()=>kO,decodeBehaviorOnError:()=>JC,encode:()=>FC,encode4337Nonce:()=>KC,encodeBehaviorOnError:()=>Tc,encodeSapient:()=>IO,fromAbiFormat:()=>TO,fromCall:()=>bO,fromConfigUpdate:()=>$S,fromDigest:()=>wO,fromMessage:()=>yO,hash:()=>Pc,hashCall:()=>NO,isCalls:()=>SO,isCalls4337_07:()=>EO,isConfigUpdate:()=>xO,isDigest:()=>qC,isMessage:()=>vO,isParented:()=>AO,isRecovery:()=>qS,isSessionImplicitAuthorize:()=>KS,to4337Message:()=>WC,to4337UserOperation:()=>GC,toAbiFormat:()=>WS,toRecovery:()=>FS,toTyped:()=>GS});var ya={};be(ya,{createJSONReplacer:()=>RS,createJSONReviver:()=>VS,fromJSON:()=>gO,minBytesFor:()=>ws,packRSY:()=>jn,toJSON:()=>pO,unpackRSY:()=>ga});function ws(s){return Math.ceil(s.toString(16).length/2)}function jn({r:s,s:e,yParity:t}){let n=f.padLeft(f.fromNumber(s),32),r=f.padLeft(f.fromNumber(e),32);return t%2===1&&(r[0]|=128),f.concat(n,r)}function ga(s){let e=f.toBigInt(s.slice(0,32)),t=s.slice(32,64),n=t[0]&128?1:0,r=new Uint8Array(t);r[0]=r[0]&127;let i=f.toBigInt(r);return {r:e,s:i,yParity:n}}function RS(s){return (e,t)=>typeof t=="bigint"?{__bigint:"0x"+t.toString(16)}:t instanceof Uint8Array?{__uint8array:Array.from(t)}:s?s(e,t):t}function VS(s){return (e,t)=>{if(t&&typeof t=="object"&&"__bigint"in t&&Object.keys(t).length===1){let n=t.__bigint;if(typeof n=="string"&&n.startsWith("0x"))return BigInt(n)}if(t&&typeof t=="object"&&"__uint8array"in t&&Object.keys(t).length===1){let n=t.__uint8array;if(Array.isArray(n))return new Uint8Array(n)}return s?s(e,t):t}}function pO(s,e,t){let n=e instanceof Function?RS(e):RS();return JSON.stringify(s,n,t)}function gO(s,e){let t=e?VS(e):VS();return JSON.parse(s,t)}var DS=0,US=1,LS=2,jS=3,HS=0,_S=1,MS=2;function yO(s){return {type:"message",message:s}}function $S(s){return {type:"config-update",imageHash:s}}function wO(s){return {type:"digest",digest:s}}function bO(s,e,t){return {type:"call",nonce:s,space:e,calls:t}}function SO(s){return s.type==="call"}function vO(s){return s.type==="message"}function xO(s){return s.type==="config-update"}function qC(s){return s.type==="digest"}function qS(s){return KS(s)?!1:s.recovery===!0}function EO(s){return s.type==="call_4337_07"}function AO(s){return "parentWallets"in s}function FS(s){return qS(s)?s:{...s,recovery:!0}}function KS(s){return s.type==="session-implicit-authorize"}function FC(s,e){let t=s.calls.length,n=ws(s.nonce);if(n>15)throw new Error("Nonce is too large");let r=0;s.space===0n&&(r|=1),r|=n<<1,t===1&&(r|=16);let i=0;if(t!==1)if(t<256)i=1;else if(t<65536)i=2,r|=32;else throw new Error("Too many calls");let a=f.fromNumber(r,{size:1});if(s.space!==0n){let o=f.padLeft(f.fromNumber(s.space),20);a=f.concat(a,o);}if(n>0){let o=f.padLeft(f.fromNumber(s.nonce),n);a=f.concat(a,o);}t!==1&&(i===1?a=f.concat(a,f.fromNumber(t,{size:1})):a=f.concat(a,f.fromNumber(t,{size:2})));for(let o of s.calls){let c=0;if(e&&B.isEqual(o.to,e)&&(c|=1),o.value!==0n&&(c|=2),o.data&&o.data.length>0&&(c|=4),o.gasLimit!==0n&&(c|=8),o.delegateCall&&(c|=16),o.onlyFallback&&(c|=32),c|=Tc(o.behaviorOnError)<<6,a=f.concat(a,f.fromNumber(c,{size:1})),!(c&1)){let u=f.fromHex(o.to);if(u.length!==20)throw new Error(`Invalid 'to' address: ${o.to}`);a=f.concat(a,u);}if(c&2){let u=f.padLeft(f.fromNumber(o.value),32);a=f.concat(a,u);}if(c&4){let u=f.fromHex(o.data).length;if(u>16777215)throw new Error("Data too large");let l=f.fromNumber(u,{size:3});a=f.concat(a,l,f.fromHex(o.data));}if(c&8){let u=f.padLeft(f.fromNumber(o.gasLimit),32);a=f.concat(a,u);}}return a}function IO(s,e){let t={kind:0,noChainId:!s,calls:[],space:0n,nonce:0n,message:"0x",imageHash:"0x0000000000000000000000000000000000000000000000000000000000000000",digest:"0x0000000000000000000000000000000000000000000000000000000000000000",parentWallets:e.parentWallets??[]};switch(e.type){case"call":t.kind=0,t.calls=e.calls.map(n=>({...n,data:n.data,behaviorOnError:BigInt(Tc(n.behaviorOnError))})),t.space=e.space,t.nonce=e.nonce;break;case"message":t.kind=1,t.message=e.message;break;case"config-update":t.kind=2,t.imageHash=e.imageHash;break;case"digest":t.kind=3,t.digest=e.digest;break}return t}function Pc(s,e,t){if(qC(t))return f.fromHex(t.digest);if(KS(t))return It.hash(t.attestation);let n=GS(s,e,t);return f.fromHex(vS(n))}function CO(s,e,t){return qS(s)?{name:"Sequence Wallet - Recovery Mode",version:"1",chainId:Number(t),verifyingContract:e}:{name:"Sequence Wallet",version:"3",chainId:Number(t),verifyingContract:e}}function KC(s,e){if(s>6277101735386680763835789423207666416102355444464034512895n)throw new RangeError("key exceeds 192 bits");if(e>18446744073709551615n)throw new RangeError("seq exceeds 64 bits");return s<<64n|e}function GS(s,e,t){let n=CO(t,s,e);switch(t.type){case"call":{let r={Calls:[{name:"calls",type:"Call[]"},{name:"space",type:"uint256"},{name:"nonce",type:"uint256"},{name:"wallets",type:"address[]"}],Call:[{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"},{name:"gasLimit",type:"uint256"},{name:"delegateCall",type:"bool"},{name:"onlyFallback",type:"bool"},{name:"behaviorOnError",type:"uint256"}]},i={calls:t.calls.map(a=>({to:a.to,value:a.value.toString(),data:a.data,gasLimit:a.gasLimit.toString(),delegateCall:a.delegateCall,onlyFallback:a.onlyFallback,behaviorOnError:BigInt(Tc(a.behaviorOnError)).toString()})),space:t.space.toString(),nonce:t.nonce.toString(),wallets:t.parentWallets??[]};return {domain:n,types:r,primaryType:"Calls",message:i}}case"message":{let r={Message:[{name:"message",type:"bytes"},{name:"wallets",type:"address[]"}]},i={message:t.message,wallets:t.parentWallets??[]};return {domain:n,types:r,primaryType:"Message",message:i}}case"config-update":{let r={ConfigUpdate:[{name:"imageHash",type:"bytes32"},{name:"wallets",type:"address[]"}]},i={imageHash:t.imageHash,wallets:t.parentWallets??[]};return {domain:n,types:r,primaryType:"ConfigUpdate",message:i}}case"digest":throw new Error("Digest does not support typed data - Use message instead");case"session-implicit-authorize":throw new Error("Payload does not support typed data");case"call_4337_07":{let r={type:"message",message:WC(t,s,e)};return GS(s,e,r)}}}function GC(s,e,t){let n={type:"call",space:0n,nonce:0n,calls:s.calls},r=E.fromBytes(FC(n));return {sender:e,nonce:KC(s.space,s.nonce),callData:se.encodeData(PS,[r]),callGasLimit:s.callGasLimit,maxFeePerGas:s.maxFeePerGas,maxPriorityFeePerGas:s.maxPriorityFeePerGas,preVerificationGas:s.preVerificationGas,verificationGasLimit:s.verificationGasLimit,factory:s.factory,factoryData:s.factoryData,paymaster:s.paymaster,paymasterData:s.paymasterData,paymasterPostOpGasLimit:s.paymasterPostOpGasLimit,paymasterVerificationGasLimit:s.paymasterVerificationGasLimit,signature:t}}function WC(s,e,t){let n=GC(s,e),r=E.concat(E.padLeft(E.fromNumber(n.verificationGasLimit),16),E.padLeft(E.fromNumber(n.callGasLimit),16)),i=E.concat(E.padLeft(E.fromNumber(n.maxPriorityFeePerGas),16),E.padLeft(E.fromNumber(n.maxFeePerGas),16)),a=oe.keccak256(n.factory&&n.factoryData?E.concat(n.factory,n.factoryData):"0x"),o=oe.keccak256(n.paymaster?E.concat(n.paymaster,E.padLeft(E.fromNumber(n.paymasterVerificationGasLimit||0),16),E.padLeft(E.fromNumber(n.paymasterPostOpGasLimit||0),16),n.paymasterData||"0x"):"0x"),c=ot.encode([{type:"address"},{type:"uint256"},{type:"bytes32"},{type:"bytes32"},{type:"bytes32"},{type:"uint256"},{type:"bytes32"},{type:"bytes32"}],[n.sender,n.nonce,a,oe.keccak256(n.callData),r,n.preVerificationGas,i,o]);return ot.encode([{type:"bytes32"},{type:"address"},{type:"uint256"}],[oe.keccak256(c),s.entrypoint,BigInt(t)])}function Tc(s){switch(s){case"ignore":return HS;case"revert":return _S;case"abort":return MS}}function NO(s){let e=oe.keccak256(f.fromString("Call(address to,uint256 value,bytes data,uint256 gasLimit,bool delegateCall,bool onlyFallback,uint256 behaviorOnError)"));return oe.keccak256(ot.encode([{type:"bytes32"},{type:"address"},{type:"uint256"},{type:"bytes32"},{type:"uint256"},{type:"bool"},{type:"bool"},{type:"uint256"}],[E.from(e),E.from(s.to),s.value,E.from(oe.keccak256(s.data)),s.gasLimit,s.delegateCall,s.onlyFallback,BigInt(Tc(s.behaviorOnError))]))}function kO(s,e){let t=0;if(s.length<1)throw new Error("Invalid packed data: missing globalFlag");let n=f.toNumber(s.slice(t,t+1));t+=1;let r=(n&1)===1,i=0n;if(!r){if(t+20>s.length)throw new Error("Invalid packed data: not enough bytes for space");i=f.toBigInt(s.slice(t,t+20)),t+=20;}let a=n>>1&7,o=0n;if(a>0){if(t+a>s.length)throw new Error("Invalid packed data: not enough bytes for nonce");o=f.toBigInt(s.slice(t,t+a)),t+=a;}let c=1;if(!((n&16)===16)){let m=(n&32)===32?2:1;if(t+m>s.length)throw new Error("Invalid packed data: not enough bytes for callsCount");c=f.toNumber(s.slice(t,t+m)),t+=m;}let l=[];for(let h=0;h<c;h++){if(t+1>s.length)throw new Error("Invalid packed data: missing call flags");let m=f.toNumber(s.slice(t,t+1));t+=1;let y;if((m&1)===1){if(!e)throw new Error('Missing "self" address for toSelf call');y=e;}else {if(t+20>s.length)throw new Error("Invalid packed data: not enough bytes for address");y=f.toHex(s.slice(t,t+20)),t+=20;}let g=0n;if((m&2)===2){if(t+32>s.length)throw new Error("Invalid packed data: not enough bytes for value");g=f.toBigInt(s.slice(t,t+32)),t+=32;}let w=f.fromHex("0x");if((m&4)===4){if(t+3>s.length)throw new Error("Invalid packed data: not enough bytes for data length");let I=f.toNumber(s.slice(t,t+3));if(t+=3,t+I>s.length)throw new Error("Invalid packed data: not enough bytes for call data");w=s.slice(t,t+I),t+=I;}let S=0n;if((m&8)===8){if(t+32>s.length)throw new Error("Invalid packed data: not enough bytes for gasLimit");S=f.toBigInt(s.slice(t,t+32)),t+=32;}let C=(m&16)===16,k=(m&32)===32,x=(m&192)>>6,v=JC(x);l.push({to:y,value:g,data:f.toHex(w),gasLimit:S,delegateCall:C,onlyFallback:k,behaviorOnError:v});}return {type:"call",space:i,nonce:o,calls:l}}function JC(s){switch(s){case 0:return "ignore";case 1:return "revert";case 2:return "abort";default:throw new Error(`Invalid behaviorOnError value: ${s}`)}}function PO(s){switch(s){case HS:return "ignore";case _S:return "revert";case MS:return "abort";default:throw new Error(`Unknown behavior: ${s}`)}}function TO(s){if(s.kind===DS)return {type:"call",nonce:s.nonce,space:s.space,calls:s.calls.map(e=>({to:B.from(e.to),value:e.value,data:e.data,gasLimit:e.gasLimit,delegateCall:e.delegateCall,onlyFallback:e.onlyFallback,behaviorOnError:PO(Number(e.behaviorOnError))})),parentWallets:s.parentWallets.map(e=>B.from(e))};if(s.kind===US)return {type:"message",message:s.message,parentWallets:s.parentWallets.map(e=>B.from(e))};if(s.kind===LS)return {type:"config-update",imageHash:s.imageHash,parentWallets:s.parentWallets.map(e=>B.from(e))};if(s.kind===jS)return {type:"digest",digest:s.digest,parentWallets:s.parentWallets.map(e=>B.from(e))};throw new Error("Not implemented")}function WS(s){if(s.type==="call")return {kind:DS,noChainId:!1,calls:s.calls.map(e=>({to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit,delegateCall:e.delegateCall,onlyFallback:e.onlyFallback,behaviorOnError:BigInt(Tc(e.behaviorOnError))})),space:s.space,nonce:s.nonce,message:"0x",imageHash:"0x0000000000000000000000000000000000000000000000000000000000000000",digest:"0x0000000000000000000000000000000000000000000000000000000000000000",parentWallets:s.parentWallets??[]};if(s.type==="message")return {kind:US,noChainId:!1,calls:[],space:0n,nonce:0n,message:s.message,imageHash:"0x0000000000000000000000000000000000000000000000000000000000000000",digest:"0x0000000000000000000000000000000000000000000000000000000000000000",parentWallets:s.parentWallets??[]};if(s.type==="config-update")return {kind:LS,noChainId:!1,calls:[],space:0n,nonce:0n,message:"0x",imageHash:s.imageHash,digest:"0x0000000000000000000000000000000000000000000000000000000000000000",parentWallets:s.parentWallets??[]};if(s.type==="digest")return {kind:jS,noChainId:!1,calls:[],space:0n,nonce:0n,message:"0x",imageHash:"0x0000000000000000000000000000000000000000000000000000000000000000",digest:s.digest,parentWallets:s.parentWallets??[]};throw new Error("Invalid payload type")}var ZS=0,QS=1,XS=2,sg=3,ev=4,tv=5,sv=6,nv=7,rv=8,ng=9,iv=10;function BO(s){return "type"in s&&(s.type==="sapient_compact"||s.type==="sapient")&&typeof s=="object"&&"address"in s&&"data"in s}function zC(s){return typeof s=="object"&&s&&typeof s.noChainId=="boolean"&&(s.checkpointerData===void 0||f.validate(s.checkpointerData))&&og(s.configuration)&&(s.suffix===void 0||Array.isArray(s.suffix)&&s.suffix.every(e=>zC(e)&&e.checkpointerData===void 0))}function og(s){return s&&typeof s=="object"&&typeof s.threshold=="bigint"&&typeof s.checkpoint=="bigint"&&ig(s.topology)&&(s.checkpointer===void 0||B.validate(s.checkpointer))}function Vh(s){return typeof s=="object"&&"weight"in s&&"signature"in s}function cg(s){return Mt(s)&&"signature"in s}function av(s){return $t(s)&&"signature"in s}function rg(s){return Array.isArray(s)&&s.length===2&&(ig(s[0])||Bc(s[0]))&&(ig(s[1])||Bc(s[1]))}function ig(s){return rg(s)||YC(s)}function YC(s){return typeof s=="object"&&"weight"in s&&!("tree"in s)}function Dh(s){return typeof s=="object"&&"tree"in s&&"weight"in s&&"threshold"in s}function ZC(s){let{signature:e,erc6492:t}=MC(s);if(e.length<1)throw new Error("Signature is empty");let n=e[0],r=1,i=(n&2)===2,a,o;if((n&64)===64){if(r+20>e.length)throw new Error("Not enough bytes for checkpointer address");if(a=f.toHex(e.slice(r,r+20)),r+=20,r+3>e.length)throw new Error("Not enough bytes for checkpointer data size");let w=f.toNumber(e.slice(r,r+3));if(r+=3,r+w>e.length)throw new Error("Not enough bytes for checkpointer data");o=e.slice(r,r+w),r+=w;}let c=(n&28)>>2;if(r+c>e.length)throw new Error("Not enough bytes for checkpoint");let u=f.toBigInt(e.slice(r,r+c));r+=c;let l=((n&32)>>5)+1;if(r+l>e.length)throw new Error("Not enough bytes for threshold");let h=f.toBigInt(e.slice(r,r+l));if(r+=l,(n&1)===1){let w=[];for(;r<e.length;){if(r+3>e.length)throw new Error("Not enough bytes for chained subsignature size");let S=f.toNumber(e.subarray(r,r+3));if(r+=3,r+S>e.length)throw new Error("Not enough bytes for chained subsignature");let C=ZC(e.subarray(r,r+S));if(r+=S,C.checkpointerData)throw new Error("Chained subsignature has checkpointer data");w.push({...C,checkpointerData:void 0});}if(w.length===0)throw new Error("Chained signature has no subsignatures");return {...w[0],suffix:w.slice(1),erc6492:t}}let{nodes:m,leftover:y}=ag(e.slice(r));if(y.length!==0)throw new Error("Leftover bytes in signature");let g=JS(m);return {noChainId:i,checkpointerData:o,configuration:{threshold:h,checkpoint:u,topology:g,checkpointer:a},erc6492:t}}function ag(s){let e=[],t=0;for(;t<s.length;){let n=s[t];t++;let r=(n&240)>>4;if(r===ZS){let i=n&15;if(i===0){if(t>=s.length)throw new Error("Not enough bytes for dynamic weight");i=s[t],t++;}if(t+64>s.length)throw new Error("Not enough bytes for hash signature (r + yParityAndS)");let a=ga(s.slice(t,t+64));t+=64,e.push({type:"unrecovered-signer",weight:BigInt(i),signature:{type:"hash",...a}});continue}if(r===QS){let i=n&15;if(i===0){if(t>=s.length)throw new Error("Not enough bytes for address weight");i=s[t],t++;}if(t+20>s.length)throw new Error("Not enough bytes for address leaf");let a=f.toHex(s.slice(t,t+20));t+=20,e.push({type:"signer",address:a,weight:BigInt(i)});continue}if(r===XS){let i=n&3;if(i===0){if(t>=s.length)throw new Error("Not enough bytes for ERC1271 weight");i=s[t],t++;}if(t+20>s.length)throw new Error("Not enough bytes for ERC1271 signer address");let a=f.toHex(s.slice(t,t+20));t+=20;let o=(n&12)>>2;if(t+o>s.length)throw new Error("Not enough bytes for ERC1271 sizeSize");let c=f.toNumber(s.slice(t,t+o));if(t+=o,t+c>s.length)throw new Error("Not enough bytes for ERC1271 data");let u=s.slice(t,t+c);t+=c,e.push({type:"unrecovered-signer",weight:BigInt(i),signature:{type:"erc1271",address:a,data:f.toHex(u)}});continue}if(r===sg){if(t+32>s.length)throw new Error("Not enough bytes for node leaf");let i=s.slice(t,t+32);t+=32,e.push(f.toHex(i));continue}if(r===ev){let i=n&15;if(t+i>s.length)throw new Error("Not enough bytes for branch sizeSize");let a=f.toNumber(s.slice(t,t+i));if(t+=i,t+a>s.length)throw new Error("Not enough bytes in sub-branch");let o=s.slice(t,t+a);t+=a;let{nodes:c,leftover:u}=ag(o);if(u.length>0)throw new Error("Leftover bytes in sub-branch");let l=JS(c);e.push(l);continue}if(r===tv){if(t+32>s.length)throw new Error("Not enough bytes for subdigest");let i=s.slice(t,t+32);t+=32,e.push({type:"subdigest",digest:f.toHex(i)});continue}if(r===sv){let i=(n&12)>>2;if(i===0){if(t>=s.length)throw new Error("Not enough bytes for nested weight");i=s[t],t++;}let a=n&3;if(a===0){if(t+2>s.length)throw new Error("Not enough bytes for nested threshold");a=f.toNumber(s.slice(t,t+2)),t+=2;}if(t+3>s.length)throw new Error("Not enough bytes for nested sub-tree size");let o=f.toNumber(s.slice(t,t+3));if(t+=3,t+o>s.length)throw new Error("Not enough bytes for nested sub-tree");let c=s.slice(t,t+o);t+=o;let{nodes:u,leftover:l}=ag(c);if(l.length>0)throw new Error("Leftover bytes in nested sub-tree");let h=JS(u);e.push({type:"nested",tree:h,weight:BigInt(i),threshold:BigInt(a)});continue}if(r===nv){let i=n&15;if(i===0){if(t>=s.length)throw new Error("Not enough bytes for dynamic weight in eth_sign");i=s[t],t++;}if(t+64>s.length)throw new Error("Not enough bytes for eth_sign signature");let a=ga(s.slice(t,t+64));t+=64,e.push({type:"unrecovered-signer",weight:BigInt(i),signature:{type:"eth_sign",...a}});continue}if(r===rv){if(t+32>s.length)throw new Error("Not enough bytes for any address subdigest");let i=s.slice(t,t+32);t+=32,e.push({type:"any-address-subdigest",digest:f.toHex(i)});continue}if(r===ng||r===iv){let i=n&3;if(i===0){if(t>=s.length)throw new Error("Not enough bytes for sapient weight");i=s[t],t++;}if(t+20>s.length)throw new Error("Not enough bytes for sapient signer address");let a=f.toHex(s.slice(t,t+20));t+=20;let o=(n&12)>>2;if(t+o>s.length)throw new Error("Not enough bytes for sapient signature size");let c=f.toNumber(s.slice(t,t+o));if(t+=o,t+c>s.length)throw new Error("Not enough bytes for sapient signature data");let u=s.slice(t,t+c);t+=c,e.push({type:"unrecovered-signer",weight:BigInt(i),signature:{address:a,data:f.toHex(u),type:r===ng?"sapient":"sapient_compact"}});continue}throw new Error(`Invalid signature flag: 0x${r.toString(16)}`)}return {nodes:e,leftover:s.slice(t)}}function Xp(s,e){if(mt(s))return [Xp(s[0],e),Xp(s[1],e)];if(Mt(s)){let t=e(s);return t?{...s,signature:t}:s}if($t(s)){let t=e(s);return t?{...s,signature:t}:s}if(js(s)||Hs(s))return s;if(es(s))return {...s,tree:Xp(s.tree,e)};if(Ct(s))return s;throw new Error("Invalid topology")}function QC(s){let e=1,t=s[s.length-1];t?.configuration.checkpointer&&(e|=64);let n=f.fromNumber(e);if(t?.configuration.checkpointer){n=f.concat(n,f.padLeft(f.fromHex(t.configuration.checkpointer),20));let r=t.checkpointerData?.length??0;if(r>16777215)throw new Error("Checkpointer data too large");let i=f.padLeft(f.fromNumber(r),3);n=f.concat(n,i,t.checkpointerData??f.fromArray([]));}for(let r=0;r<s.length;r++){let i=s[r],a=XC(i,!0,r===s.length-1);if(a.length>16777215)throw new Error("Chained signature too large");let o=f.padLeft(f.fromNumber(a.length),3);n=f.concat(n,o,a);}return n}function XC(s,e,t){let{noChainId:n,checkpointerData:r,configuration:i,suffix:a,erc6492:o}=s;if(a?.length){let w=QC([{...s,suffix:void 0,erc6492:void 0},...a]);return o?OS(w,o):w}let c=0;n&&(c|=2);let u=ws(i.checkpoint);if(u>7)throw new Error("Checkpoint too large");c|=u<<2;let l=ws(i.threshold);if(l=l===0?1:l,l>2)throw new Error("Threshold too large");c|=l==2?32:0,i.checkpointer&&!t&&(c|=64);let h=f.fromNumber(c);if(i.checkpointer&&!t&&(h=f.concat(h,f.padLeft(f.fromHex(i.checkpointer),20)),!e)){let w=r?.length??0;if(w>16777215)throw new Error("Checkpointer data too large");let S=f.padLeft(f.fromNumber(w),3);h=f.concat(h,S,r??f.fromArray([]));}let m=f.padLeft(f.fromNumber(i.checkpoint),u);h=f.concat(h,m);let y=f.padLeft(f.fromNumber(i.threshold),l);h=f.concat(h,y);let g=Rh(i.topology,s);return h=f.concat(h,g),o?OS(h,o):h}function Rh(s,e={}){if(mt(s)||rg(s)){let t=Rh(s[0],e),n=Rh(s[1],e);if(mt(s[1])||rg(s[1])){let i=ws(BigInt(n.length));if(i>15)throw new Error("Branch too large");let a=ev<<4|i;return f.concat(t,f.fromNumber(a),f.padLeft(f.fromNumber(n.length),i),n)}else return f.concat(t,n)}if(es(s)||Dh(s)){let t=Rh(s.tree,e),n=sv<<4,r=f.fromArray([]);if(s.weight<=3n&&s.weight>0n)n|=Number(s.weight)<<2;else if(s.weight<=255n)r=f.fromNumber(Number(s.weight));else throw new Error("Weight too large");let i=f.fromArray([]);if(s.threshold<=3n&&s.threshold>0n)n|=Number(s.threshold);else if(s.threshold<=65535n)i=f.padLeft(f.fromNumber(Number(s.threshold)),2);else throw new Error("Threshold too large");if(t.length>16777215)throw new Error("Nested tree too large");return f.concat(f.fromNumber(n),r,i,f.padLeft(f.fromNumber(t.length),3),t)}if(Ct(s))return f.concat(f.fromNumber(sg<<4),f.fromHex(s));if(cg(s)||Vh(s))if(s.signature.type==="hash"||s.signature.type==="eth_sign"){let t=(s.signature.type==="hash"?ZS:nv)<<4,n=f.fromArray([]);if(s.weight<=15n&&s.weight>0n)t|=Number(s.weight);else if(s.weight<=255n)n=f.fromNumber(Number(s.weight));else throw new Error("Weight too large");let r=jn(s.signature);return f.concat(f.fromNumber(t),n,r)}else if(s.signature.type==="erc1271"){let t=XS<<4,n=ws(BigInt(s.signature.data.length));if(n>3)throw new Error("Signature too large");t|=n<<2;let r=f.fromArray([]);if(s.weight<=3n&&s.weight>0n)t|=Number(s.weight);else if(s.weight<=255n)r=f.fromNumber(Number(s.weight));else throw new Error("Weight too large");return f.concat(f.fromNumber(t),r,f.padLeft(f.fromHex(s.signature.address),20),f.padLeft(f.fromNumber(f.fromHex(s.signature.data).length),n),f.fromHex(s.signature.data))}else if(s.signature.type==="sapient"||s.signature.type==="sapient_compact"){let t=(s.signature.type==="sapient"?ng:iv)<<4,n=f.fromHex(s.signature.data),r=ws(BigInt(n.length));if(r>3)throw new Error("Signature too large");t|=r<<2;let i=f.fromArray([]);if(s.weight<=3n&&s.weight>0n)t|=Number(s.weight);else if(s.weight<=255n)i=f.fromNumber(Number(s.weight));else throw new Error("Weight too large");return f.concat(f.fromNumber(t),i,f.padLeft(f.fromHex(s.signature.address),20),f.padLeft(f.fromNumber(n.length),r),n)}else throw new Error(`Invalid signature type: ${s.signature.type}`);if(Mt(s)){let t=QS<<4,n=f.fromArray([]);if(s.weight<=15n&&s.weight>0n)t|=Number(s.weight);else if(s.weight<=255n)n=f.fromNumber(Number(s.weight));else throw new Error("Weight too large");return f.concat(f.fromNumber(t),n,f.padLeft(f.fromHex(s.address),20))}if($t(s)){let t=qt(s);return f.concat(f.fromNumber(sg<<4),t)}if(js(s))return f.concat(f.fromNumber(tv<<4),f.fromHex(s.digest));if(Hs(s))return f.concat(f.fromNumber(rv<<4),f.fromHex(s.digest));throw new Error("Invalid topology")}function JS(s){if(s.length===0)throw new Error("Empty signature tree");if(s.length===1)return s[0];let e=s[0];for(let t=1;t<s.length;t++)e=[e,s[t]];return e}function OO(s){return JSON.stringify(e5(s))}function e5(s){return {noChainId:s.noChainId,checkpointerData:s.checkpointerData?f.toHex(s.checkpointerData):void 0,configuration:{threshold:s.configuration.threshold.toString(),checkpoint:s.configuration.checkpoint.toString(),topology:eg(s.configuration.topology),checkpointer:s.configuration.checkpointer},suffix:s.suffix?s.suffix.map(e=>e5(e)):void 0}}function eg(s){if(Array.isArray(s))return [eg(s[0]),eg(s[1])];if(typeof s=="object"&&s!==null&&"type"in s)switch(s.type){case"signer":return {type:"signer",address:s.address,weight:s.weight.toString()};case"sapient-signer":return {type:"sapient-signer",address:s.address,weight:s.weight.toString(),imageHash:s.imageHash};case"subdigest":return {type:"subdigest",digest:s.digest};case"any-address-subdigest":return {type:"any-address-subdigest",digest:s.digest};case"nested":return {type:"nested",tree:eg(s.tree),weight:s.weight.toString(),threshold:s.threshold.toString()};case"unrecovered-signer":return {type:"unrecovered-signer",weight:s.weight.toString(),signature:RO(s.signature)};default:throw new Error("Invalid raw topology type")}if(typeof s=="string")return s;throw new Error("Invalid raw topology format")}function RO(s){if(s.type==="eth_sign"||s.type==="hash")return {type:s.type,r:E.fromNumber(s.r,{size:32}),s:E.fromNumber(s.s,{size:32}),yParity:s.yParity};if(s.type==="erc1271")return {type:s.type,address:s.address,data:s.data};if(s.type==="sapient"||s.type==="sapient_compact")return {type:s.type,address:s.address,data:s.data};throw new Error("Unknown signature type in raw signature")}function VO(s){let e=JSON.parse(s);return t5(e)}function t5(s){return {noChainId:s.noChainId,checkpointerData:s.checkpointerData?f.fromHex(s.checkpointerData):void 0,configuration:{threshold:BigInt(s.configuration.threshold),checkpoint:BigInt(s.configuration.checkpoint),topology:tg(s.configuration.topology),checkpointer:s.configuration.checkpointer},suffix:s.suffix?s.suffix.map(e=>t5(e)):void 0}}function tg(s){if(Array.isArray(s)){if(s.length!==2)throw new Error("Invalid raw topology node");return [tg(s[0]),tg(s[1])]}if(typeof s=="object"&&s!==null&&"type"in s)switch(s.type){case"signer":return {type:"signer",address:s.address,weight:BigInt(s.weight)};case"sapient-signer":return {type:"sapient-signer",address:s.address,weight:BigInt(s.weight),imageHash:s.imageHash};case"subdigest":return {type:"subdigest",digest:s.digest};case"any-address-subdigest":return {type:"any-address-subdigest",digest:s.digest};case"nested":return {type:"nested",tree:tg(s.tree),weight:BigInt(s.weight),threshold:BigInt(s.threshold)};case"unrecovered-signer":return {type:"unrecovered-signer",weight:BigInt(s.weight),signature:DO(s.signature)};default:throw new Error("Invalid raw topology type")}if(typeof s=="string")return s;throw new Error("Invalid raw topology format")}function DO(s){switch(s.type){case"eth_sign":case"hash":return {type:s.type,r:E.toBigInt(s.r),s:E.toBigInt(s.s),yParity:s.yParity};case"erc1271":return {type:"erc1271",address:s.address,data:s.data};case"sapient":case"sapient_compact":return {type:s.type,address:s.address,data:s.data};default:throw new Error("Invalid signature type in raw signature")}}async function zS(s,e,t,n,r){if(s.suffix?.length){let o=!1,{configuration:c,weight:u}=await zS({...s,suffix:void 0},e,t,n,r);o||=u<c.threshold;for(let l of s.suffix){let h=await zS(l,e,l.noChainId?0:t,$S(f.toHex(qt(c))),r);o||=h.weight<h.configuration.threshold,o||=h.configuration.checkpoint>=c.checkpoint,c=h.configuration,u=h.weight;}return {configuration:c,weight:o?0n:u}}let{topology:i,weight:a}=await YS(s.configuration.topology,e,t,n,r);return {configuration:{...s.configuration,topology:i},weight:a}}async function YS(s,e,t,n,r){let i=Pc(e,t,n);if(Vh(s))switch(s.signature.type){case"eth_sign":case"hash":return {topology:{type:"signer",address:Ot.recoverAddress({payload:s.signature.type==="eth_sign"?oe.keccak256(ot.encodePacked(["string","bytes32"],[`Ethereum Signed Message:
|
|
343
|
+
32`,f.toHex(i)])):i,signature:s.signature}),weight:s.weight,signed:!0,signature:s.signature},weight:s.weight};case"erc1271":switch(r?.provider){case void 0:case"assume-invalid":if(r?.throw!==!1)throw new Error(`unable to validate signer ${s.signature.address} erc-1271 signature`);return {topology:{type:"signer",address:s.signature.address,weight:s.weight},weight:0n};case"assume-valid":return {topology:{type:"signer",address:s.signature.address,weight:s.weight,signed:!0,signature:s.signature},weight:s.weight};default:let a="provider"in r.provider?r.provider.provider:r.provider,o="block"in r.provider?r.provider.block:void 0,c={to:s.signature.address,data:se.encodeData(Oh,[f.toHex(i),s.signature.data])},u=await a.request({method:"eth_call",params:o===void 0?[c,"latest"]:[c,E.fromNumber(o)]}),l=se.decodeResult(Oh,u);if(E.isEqual(l,se.getSelector(Oh)))return {topology:{type:"signer",address:s.signature.address,weight:s.weight,signed:!0,signature:s.signature},weight:s.weight};if(r?.throw!==!1)throw new Error(`invalid signer ${s.signature.address} erc-1271 signature`);return {topology:{type:"signer",address:s.signature.address,weight:s.weight},weight:0n}}case"sapient":case"sapient_compact":switch(r?.provider){case void 0:case"assume-invalid":case"assume-valid":throw new Error(`unable to validate sapient signer ${s.signature.address} signature`);default:let a="provider"in r.provider?r.provider.provider:r.provider,o="block"in r.provider?r.provider.block:void 0,c={to:s.signature.address,data:s.signature.type==="sapient"?se.encodeData(NS,[UO(t,n),s.signature.data]):se.encodeData(kS,[f.toHex(i),s.signature.data])},u=await a.request({method:"eth_call",params:o===void 0?[c,"latest"]:[c,E.fromNumber(o)]});return {topology:{type:"sapient-signer",address:s.signature.address,weight:s.weight,imageHash:u,signed:!0,signature:s.signature},weight:s.weight}}}else if(Dh(s)){let{topology:a,weight:o}=await YS(s.tree,e,t,n,r);return {topology:{...s,tree:a},weight:o>=s.threshold?s.weight:0n}}else {if(Mt(s))return {topology:s,weight:0n};if($t(s))return {topology:s,weight:0n};if(js(s))return {topology:s,weight:f.isEqual(f.fromHex(s.digest),i)?0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn:0n};if(Hs(s)){let a=Pc(_e.ZeroAddress,t,n);return {topology:s,weight:f.isEqual(f.fromHex(s.digest),a)?0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn:0n}}else {if(Ct(s))return {topology:s,weight:0n};{let[a,o]=await Promise.all(s.map(c=>YS(c,e,t,n,r)));return {topology:[a.topology,o.topology],weight:a.weight+o.weight}}}}}function UO(s,e){switch(e.type){case"call":return {kind:0,noChainId:!s,calls:e.calls.map(t=>({...t,data:t.data,behaviorOnError:t.behaviorOnError==="ignore"?0n:t.behaviorOnError==="revert"?1n:2n})),space:e.space,nonce:e.nonce,message:"0x",imageHash:"0x0000000000000000000000000000000000000000000000000000000000000000",digest:"0x0000000000000000000000000000000000000000000000000000000000000000",parentWallets:e.parentWallets??[]};case"message":return {kind:1,noChainId:!s,calls:[],space:0n,nonce:0n,message:e.message,imageHash:"0x0000000000000000000000000000000000000000000000000000000000000000",digest:"0x0000000000000000000000000000000000000000000000000000000000000000",parentWallets:e.parentWallets??[]};case"config-update":return {kind:2,noChainId:!s,calls:[],space:0n,nonce:0n,message:"0x",imageHash:e.imageHash,digest:"0x0000000000000000000000000000000000000000000000000000000000000000",parentWallets:e.parentWallets??[]};case"digest":return {kind:3,noChainId:!s,calls:[],space:0n,nonce:0n,message:"0x",imageHash:"0x0000000000000000000000000000000000000000000000000000000000000000",digest:e.digest,parentWallets:e.parentWallets??[]};default:throw new Error("Invalid payload type")}}function Mt(s){return typeof s=="object"&&s!==null&&s.type==="signer"}function $t(s){return typeof s=="object"&&s!==null&&s.type==="sapient-signer"}function js(s){return typeof s=="object"&&s!==null&&s.type==="subdigest"}function Hs(s){return typeof s=="object"&&s!==null&&s.type==="any-address-subdigest"}function Ct(s){return E.validate(s)&&s.length===66}function es(s){return typeof s=="object"&&s!==null&&s.type==="nested"}function mt(s){return Array.isArray(s)&&s.length===2&&Bc(s[0])&&Bc(s[1])}function Rc(s){return typeof s=="object"&&"threshold"in s&&"checkpoint"in s&&"topology"in s}function s5(s){return Mt(s)||$t(s)||js(s)||Hs(s)||Ct(s)||es(s)}function Bc(s){return mt(s)||s5(s)}function LO(s){let e=new Set,t=new Set,n=!0,r=i=>{mt(i)?(r(i[0]),r(i[1])):Mt(i)?i.weight&&e.add(i.address):$t(i)?t.add({address:i.address,imageHash:i.imageHash}):Ct(i)?n=!1:es(i)&&i.weight&&r(i.tree);};return r(Rc(s)?s.topology:s),{signers:Array.from(e),sapientSigners:Array.from(t),isComplete:n}}function Uh(s,e){if(Rc(s))return Uh(s.topology,e);if(mt(s))return Uh(s[0],e)||Uh(s[1],e);if(Mt(s)){if(B.isEqual(s.address,e))return s}else if($t(s)){if(B.isEqual(s.address,e))return s}else if(es(s))return Uh(s.tree,e)}function Lh(s,e){if(s=og(s)||Rc(s)?s.topology:s,cg(s))return {weight:s.weight,maxWeight:s.weight};if(Mt(s))return {weight:0n,maxWeight:e(s)?s.weight:0n};if(Vh(s))return {weight:s.weight,maxWeight:s.weight};if(av(s))return {weight:s.weight,maxWeight:s.weight};if($t(s))return {weight:0n,maxWeight:e(s)?s.weight:0n};if(js(s))return {weight:0n,maxWeight:0n};if(Hs(s))return {weight:0n,maxWeight:0n};if(Dh(s)){let{weight:t,maxWeight:n}=Lh(s.tree,e);return {weight:t>=s.threshold?s.weight:0n,maxWeight:n>=s.threshold?s.weight:0n}}else {if(Ct(s))return {weight:0n,maxWeight:0n};{let[t,n]=[Lh(s[0],e),Lh(s[1],e)];return {weight:t.weight+n.weight,maxWeight:t.maxWeight+n.maxWeight}}}}function qt(s){if(Rc(s)){let e=qt(s.topology);return e=oe.keccak256(f.concat(e,f.padLeft(f.fromNumber(s.threshold),32))),e=oe.keccak256(f.concat(e,f.padLeft(f.fromNumber(s.checkpoint),32))),e=oe.keccak256(f.concat(e,f.padLeft(f.fromHex(s.checkpointer??_e.ZeroAddress),32))),e}if(Mt(s))return oe.keccak256(f.concat(f.fromString(`Sequence signer:
|
|
344
344
|
`),f.fromHex(s.address),f.padLeft(f.fromNumber(s.weight),32)));if($t(s))return oe.keccak256(f.concat(f.fromString(`Sequence sapient config:
|
|
345
|
-
`),f.fromHex(s.address),f.padLeft(f.fromNumber(s.weight),32),f.padLeft(f.fromHex(s.imageHash),32)));if(
|
|
345
|
+
`),f.fromHex(s.address),f.padLeft(f.fromNumber(s.weight),32),f.padLeft(f.fromHex(s.imageHash),32)));if(js(s))return oe.keccak256(f.concat(f.fromString(`Sequence static digest:
|
|
346
346
|
`),f.fromHex(s.digest)));if(Hs(s))return oe.keccak256(f.concat(f.fromString(`Sequence any address subdigest:
|
|
347
347
|
`),f.fromHex(s.digest)));if(Ct(s))return f.fromHex(s);if(es(s))return oe.keccak256(f.concat(f.fromString(`Sequence nested config:
|
|
348
|
-
`),qt(s.tree),f.padLeft(f.fromNumber(s.threshold),32),f.padLeft(f.fromNumber(s.weight),32)));if(mt(s))return oe.keccak256(f.concat(qt(s[0]),qt(s[1])));throw new Error("Invalid topology")}function cv(s){if(s.length===0)throw new Error("Cannot create topology from empty leaves");return s.length===1?s[0]:s.length===2?[s[0],s[1]]:[cv(s.slice(0,s.length/2)),cv(s.slice(s.length/2))]}function lg(s){return mt(s)?[...lg(s[0]),...lg(s[1])]:es(s)?[...lg(s.tree)]:[s]}function LO(s){return JSON.stringify({threshold:s.threshold.toString(),checkpoint:s.checkpoint.toString(),topology:hg(s.topology),checkpointer:s.checkpointer})}function jO(s){let e=JSON.parse(s);return {threshold:BigInt(e.threshold),checkpoint:BigInt(e.checkpoint),checkpointer:e.checkpointer,topology:fg(e.topology)}}function hg(s){if(mt(s))return [hg(s[0]),hg(s[1])];if(Mt(s))return {type:"signer",address:s.address,weight:s.weight.toString()};if($t(s))return {type:"sapient-signer",address:s.address,weight:s.weight.toString(),imageHash:s.imageHash};if(Us(s))return {type:"subdigest",digest:s.digest};if(Hs(s))return {type:"any-address-subdigest",digest:s.digest};if(Ct(s))return s;if(es(s))return {type:"nested",tree:hg(s.tree),weight:s.weight.toString(),threshold:s.threshold.toString()};throw new Error("Invalid topology")}function fg(s){if(Array.isArray(s)){if(s.length!==2)throw new Error("Invalid node structure in JSON");return [fg(s[0]),fg(s[1])]}if(typeof s=="string")return s;switch(s.type){case"signer":return {type:"signer",address:s.address,weight:BigInt(s.weight)};case"sapient-signer":return {type:"sapient-signer",address:s.address,weight:BigInt(s.weight),imageHash:s.imageHash};case"subdigest":return {type:"subdigest",digest:s.digest};case"any-address-subdigest":return {type:"any-address-subdigest",digest:s.digest};case"nested":return {type:"nested",tree:fg(s.tree),weight:BigInt(s.weight),threshold:BigInt(s.threshold)};default:throw new Error("Invalid type in topology JSON")}}function UO(s){return s instanceof Promise?{signature:s}:typeof s=="object"&&s&&"signature"in s&&s.signature instanceof Promise?s:{signature:Promise.resolve(s)}}function mg(s,e){if(mt(s)&&mt(e))return [mg(s[0],e[0]),mg(s[1],e[1])];if(mt(s)&&!mt(e)){if(!Ct(e))throw new Error("Topology mismatch: cannot merge node with non-node that is not a node leaf");let t=qt(e);if(!f.isEqual(t,qt(s)))throw new Error("Topology mismatch: node hash does not match");return s}if(!mt(s)&&mt(e)){if(!Ct(s))throw new Error("Topology mismatch: cannot merge node with non-node that is not a node leaf");let t=qt(s);if(!f.isEqual(t,qt(e)))throw new Error("Topology mismatch: node hash does not match");return e}return _O(s,e)}function Oc(s){return Rc(s)?s.threshold>65535n||s.checkpoint>72057594037927935n||Oc(s.topology):mt(s)?Oc(s[0])||Oc(s[1]):es(s)?Oc(s.tree)||s.weight>255n||s.threshold>65535n:Mt(s)||$t(s)?s.weight>255n:!1}function Uh(s){return mt(s)?Math.max(Uh(s[0]),Uh(s[1]))+1:es(s)?Uh(s.tree)+1:0}function HO(s){if(s.threshold===0n)throw new Error("unsafe-threshold-0");if(Oc(s))throw new Error("unsafe-invalid-values");if(Uh(s.topology)>32)throw new Error("unsafe-depth");let{maxWeight:e}=jh(s.topology,()=>!0);if(e<s.threshold)throw new Error("unsafe-threshold")}function _O(s,e){if(Ct(s)&&Ct(e)){if(!E.isEqual(s,e))throw new Error("Topology mismatch: different node leaves");return s}if(Ct(s)&&!Ct(e)){let t=qt(e);if(!f.isEqual(t,f.fromHex(s)))throw new Error("Topology mismatch: node leaf hash does not match");return e}if(!Ct(s)&&Ct(e)){let t=qt(s);if(!f.isEqual(t,f.fromHex(e)))throw new Error("Topology mismatch: node leaf hash does not match");return s}if(Mt(s)&&Mt(e)){if(s.address!==e.address||s.weight!==e.weight)throw new Error("Topology mismatch: signer fields differ");if(!!s.signed!=!!e.signed||!!s.signature!=!!e.signature)throw new Error("Topology mismatch: signer signature fields differ");return s}if($t(s)&&$t(e)){if(s.address!==e.address||s.weight!==e.weight||s.imageHash!==e.imageHash)throw new Error("Topology mismatch: sapient signer fields differ");if(!!s.signed!=!!e.signed||!!s.signature!=!!e.signature)throw new Error("Topology mismatch: sapient signature fields differ");return s}if(Us(s)&&Us(e)){if(!f.isEqual(f.fromHex(s.digest),f.fromHex(e.digest)))throw new Error("Topology mismatch: subdigest fields differ");return s}if(Hs(s)&&Hs(e)){if(!f.isEqual(f.fromHex(s.digest),f.fromHex(e.digest)))throw new Error("Topology mismatch: any-address-subdigest fields differ");return s}if(es(s)&&es(e)){if(s.weight!==e.weight||s.threshold!==e.threshold)throw new Error("Topology mismatch: nested leaf fields differ");let t=mg(s.tree,e.tree);return {type:"nested",weight:s.weight,threshold:s.threshold,tree:t}}throw new Error("Topology mismatch: incompatible leaf types")}function dg(s,e,t){return mt(s)?[dg(s[0],e,t),dg(s[1],e,t)]:es(s)?{...s,tree:dg(s.tree,e,t)}:(Mt(s)||$t(s))&&B.isEqual(s.address,e)?{...s,address:t}:s}function MO(s,e){let t=s instanceof Uint8Array?s:qt(s);return f.toHex(oe.keccak256(f.concat(f.from("0xff"),f.from(e.factory),t,oe.keccak256(f.concat(f.from(e.creationCode),f.padLeft(f.from(e.stage1),32)))),{as:"Bytes"}).subarray(12))}var It={};be(It,{ACCEPT_IMPLICIT_REQUEST_MAGIC_PREFIX:()=>u5,decode:()=>$O,decodeAuthData:()=>a5,encode:()=>r5,encodeAuthData:()=>i5,encodeForJson:()=>o5,fromJson:()=>KO,fromParsed:()=>c5,generateImplicitRequestMagic:()=>GO,hash:()=>qO,toJson:()=>FO});function r5(s){let e=i5(s.authData),t=[f.fromHex(s.approvedSigner,{size:20}),f.padLeft(s.identityType.slice(0,4),4),f.padLeft(s.issuerHash,32),f.padLeft(s.audienceHash,32),f.fromNumber(s.applicationData.length,{size:3}),s.applicationData,e];return f.concat(...t)}function i5(s){return f.concat(f.fromNumber(s.redirectUrl.length,{size:3}),f.fromString(s.redirectUrl),f.fromNumber(s.issuedAt,{size:8}))}function $O(s){let e=f.toHex(s.slice(0,20)),t=s.slice(20,24),n=s.slice(24,56),r=s.slice(56,88),i=f.toNumber(s.slice(88,91)),a=s.slice(91,91+i),o=a5(s.slice(91+i));return {approvedSigner:e,identityType:t,issuerHash:n,audienceHash:r,applicationData:a,authData:o}}function a5(s){let e=f.toNumber(s.slice(0,3)),t=f.toString(s.slice(3,3+e)),n=f.toBigInt(s.slice(3+e,3+e+8));return {redirectUrl:t,issuedAt:n}}function qO(s){return oe.keccak256(r5(s))}function FO(s,e){return JSON.stringify(o5(s),null,e)}function o5(s){return {approvedSigner:s.approvedSigner.toString(),identityType:f.toHex(s.identityType),issuerHash:f.toHex(s.issuerHash),audienceHash:f.toHex(s.audienceHash),applicationData:f.toHex(s.applicationData),authData:{redirectUrl:s.authData.redirectUrl,issuedAt:s.authData.issuedAt.toString()}}}function KO(s){return c5(JSON.parse(s))}function c5(s){return {approvedSigner:B.from(s.approvedSigner),identityType:f.fromHex(s.identityType),issuerHash:f.fromHex(s.issuerHash),audienceHash:f.fromHex(s.audienceHash),applicationData:f.fromHex(s.applicationData),authData:{redirectUrl:s.authData.redirectUrl,issuedAt:BigInt(s.authData.issuedAt)}}}var u5=oe.keccak256(f.fromString("acceptImplicitRequest"));function GO(s,e){return oe.keccak256(f.concat(u5,f.fromHex(e,{size:20}),s.audienceHash,s.issuerHash))}var Hn={};be(Hn,{MASK:()=>WO,MAX_PERMISSIONS_COUNT:()=>pg,MAX_RULES_COUNT:()=>l5,ParameterOperation:()=>uv,abiEncodePermission:()=>ZO,decodeSessionPermissions:()=>gg,encodePermission:()=>h5,encodeSessionPermissions:()=>Hh,encodeSessionPermissionsForJson:()=>yg,parameterRuleToJson:()=>eR,permissionFromJson:()=>sR,permissionStructAbi:()=>f5,permissionToJson:()=>XO,sessionPermissionsFromJson:()=>tR,sessionPermissionsFromParsed:()=>wg,sessionPermissionsToJson:()=>QO});var uv;(function(s){s[s.EQUAL=0]="EQUAL",s[s.NOT_EQUAL=1]="NOT_EQUAL",s[s.GREATER_THAN_OR_EQUAL=2]="GREATER_THAN_OR_EQUAL",s[s.LESS_THAN_OR_EQUAL=3]="LESS_THAN_OR_EQUAL";})(uv||(uv={}));var pg=2**7-1,l5=2**8-1,WO={SELECTOR:f.padRight(f.fromHex("0xffffffff"),32),ADDRESS:f.padLeft(f.fromHex("0xffffffffffffffffffffffffffffffffffffffff"),32),BOOL:f.padLeft(f.fromHex("0x01"),32),BYTES1:f.padLeft(f.from(Array(1).fill(255)),32),BYTES2:f.padLeft(f.from(Array(2).fill(255)),32),BYTES4:f.padLeft(f.from(Array(4).fill(255)),32),BYTES8:f.padLeft(f.from(Array(8).fill(255)),32),BYTES16:f.padLeft(f.from(Array(16).fill(255)),32),BYTES32:f.padLeft(f.from(Array(32).fill(255)),32),INT8:f.padLeft(f.from(Array(1).fill(255)),32),INT16:f.padLeft(f.from(Array(2).fill(255)),32),INT32:f.padLeft(f.from(Array(4).fill(255)),32),INT64:f.padLeft(f.from(Array(8).fill(255)),32),INT128:f.padLeft(f.from(Array(16).fill(255)),32),INT256:f.padLeft(f.from(Array(32).fill(255)),32),UINT8:f.padLeft(f.from(Array(1).fill(255)),32),UINT16:f.padLeft(f.from(Array(2).fill(255)),32),UINT32:f.padLeft(f.from(Array(4).fill(255)),32),UINT64:f.padLeft(f.from(Array(8).fill(255)),32),UINT128:f.padLeft(f.from(Array(16).fill(255)),32),UINT256:f.padLeft(f.from(Array(32).fill(255)),32)};function Hh(s){if(s.permissions.length>pg)throw new Error("Too many permissions");let e=s.permissions.map(h5);return f.concat(f.padLeft(f.fromHex(s.signer),20),f.padLeft(f.fromNumber(s.chainId),32),f.padLeft(f.fromNumber(s.valueLimit),32),f.padLeft(f.fromNumber(s.deadline,{size:8}),8),f.fromNumber(s.permissions.length,{size:1}),f.concat(...e))}function h5(s){if(s.rules.length>l5)throw new Error("Too many rules");let e=s.rules.map(JO);return f.concat(f.padLeft(f.fromHex(s.target),20),f.fromNumber(s.rules.length,{size:1}),f.concat(...e))}function JO(s){let e=Number(s.operation)<<1|(s.cumulative?1:0);return f.concat(f.fromNumber(e),f.padLeft(s.value,32),f.padLeft(f.fromNumber(s.offset),32),f.padLeft(s.mask,32))}function gg(s){let e=f.toHex(s.slice(0,20)),t=f.toNumber(s.slice(20,52)),n=f.toBigInt(s.slice(52,84)),r=f.toBigInt(s.slice(84,92)),i=Number(s[92]),a=[],o=93;for(let c=0;c<i;c++){let{permission:u,consumed:l}=zO(s.slice(o));a.push(u),o+=l;}if(a.length===0)throw new Error("No permissions");return {signer:e,chainId:t,valueLimit:n,deadline:r,permissions:a}}function zO(s){let e=f.toHex(s.slice(0,20)),t=Number(s[20]),n=[],r=21;for(let i=0;i<t;i++){let a=s.slice(r,r+97);n.push(YO(a)),r+=97;}return {permission:{target:e,rules:n},consumed:r}}function YO(s){let e=Number(s[0]),t=(e&1)===1,n=e>>1,r=s.slice(1,33),i=f.toBigInt(s.slice(33,65)),a=s.slice(65,97);return {cumulative:t,operation:n,value:r,offset:i,mask:a}}var f5={internalType:"struct Permission",name:"permission",type:"tuple",components:[{internalType:"address",name:"target",type:"address"},{internalType:"struct ParameterRule[]",name:"rules",type:"tuple[]",components:[{internalType:"bool",name:"cumulative",type:"bool"},{internalType:"enum ParameterOperation",name:"operation",type:"uint8"},{internalType:"bytes32",name:"value",type:"bytes32"},{internalType:"uint256",name:"offset",type:"uint256"},{internalType:"bytes32",name:"mask",type:"bytes32"}]}]};function ZO(s){return ot.encode([f5],[{target:s.target,rules:s.rules.map(e=>({cumulative:e.cumulative,operation:e.operation,value:f.toHex(e.value),offset:e.offset,mask:f.toHex(e.mask)}))}])}function QO(s){return JSON.stringify(yg(s))}function yg(s){return {signer:s.signer.toString(),chainId:s.chainId.toString(),valueLimit:s.valueLimit.toString(),deadline:s.deadline.toString(),permissions:s.permissions.map(d5)}}function XO(s){return JSON.stringify(d5(s))}function d5(s){return {target:s.target.toString(),rules:s.rules.map(m5)}}function eR(s){return JSON.stringify(m5(s))}function m5(s){return {cumulative:s.cumulative,operation:s.operation,value:f.toHex(s.value),offset:s.offset.toString(),mask:f.toHex(s.mask)}}function tR(s){return wg(JSON.parse(s))}function wg(s){return {signer:B.from(s.signer),chainId:Number(s.chainId),valueLimit:BigInt(s.valueLimit),deadline:BigInt(s.deadline),permissions:s.permissions.map(p5)}}function sR(s){return p5(JSON.parse(s))}function p5(s){return {target:B.from(s.target),rules:s.rules.map(e=>({cumulative:e.cumulative,operation:e.operation,value:f.fromHex(e.value),offset:BigInt(e.offset),mask:f.fromHex(e.mask)}))}}var Ns={};be(Ns,{SESSIONS_FLAG_BLACKLIST:()=>Dc,SESSIONS_FLAG_BRANCH:()=>hv,SESSIONS_FLAG_IDENTITY_SIGNER:()=>$h,SESSIONS_FLAG_NODE:()=>lv,SESSIONS_FLAG_PERMISSIONS:()=>Mh,addExplicitSession:()=>uR,addIdentitySigner:()=>hR,addToImplicitBlacklist:()=>fR,balanceSessionsTopology:()=>Kh,cleanSessionsTopology:()=>N5,configurationTreeToSessionsTopology:()=>x5,decodeLeafFromBytes:()=>S5,decodeSessionsTopology:()=>mv,emptySessionsTopology:()=>k5,encodeLeafToGeneric:()=>_h,encodeSessionsTopology:()=>xg,getExplicitSigners:()=>iR,getIdentitySigners:()=>qh,getImplicitBlacklist:()=>rR,getImplicitBlacklistLeaf:()=>Fh,getSessionPermissions:()=>vg,isCompleteSessionsTopology:()=>dv,isSessionsTopology:()=>fv,mergeSessionsTopologies:()=>gv,minimiseSessionsTopology:()=>Eg,removeExplicitSession:()=>cR,removeFromImplicitBlacklist:()=>dR,removeIdentitySigner:()=>lR,sessionsTopologyFromJson:()=>oR,sessionsTopologyToConfigurationTree:()=>v5,sessionsTopologyToJson:()=>aR});var Ss={};be(Ss,{hash:()=>_s,isBranch:()=>bs,isLeaf:()=>Br,isNode:()=>pt,isTree:()=>g5});function bs(s){return Array.isArray(s)&&s.length>=2&&s.every(e=>g5(e))}function Br(s){return s.type==="leaf"&&f.validate(s.value)}function g5(s){return bs(s)||Br(s)||pt(s)}function pt(s){return E.validate(s)&&E.size(s)===32}function _s(s){if(bs(s)){let e=s.map(_s);if(e.length===0)throw new Error("Empty branch");let t=E.toBytes(e[0]);for(let n=1;n<e.length;n++)t=oe.keccak256(f.concat(t,E.toBytes(e[n])));return E.fromBytes(t)}return pt(s)?s:oe.keccak256(s.value,{as:"Hex"})}var Mh=0,lv=1,hv=2,Dc=3,$h=4,y5=32;function un(s){return E.validate(s)&&E.size(s)===y5}function Ms(s){return typeof s=="object"&&s!==null&&"blacklist"in s}function $s(s){return typeof s=="object"&&s!==null&&"identitySigner"in s}function qs(s){return typeof s=="object"&&s!==null&&"signer"in s}function bg(s){return Ms(s)||$s(s)||qs(s)}function Fs(s){return Array.isArray(s)&&s.length>=2&&s.every(e=>fv(e))}function fv(s){return Fs(s)||bg(s)||un(s)}function dv(s){if(!fv(s))return !1;let{identitySignerCount:e,blacklistCount:t}=w5(s);return e>=1&&t===1}function w5(s){let e=0,t=0;if(Fs(s))for(let n of s){let{identitySignerCount:r,blacklistCount:i}=w5(n);e+=r,t+=i;}return $s(s)&&e++,Ms(s)&&t++,{identitySignerCount:e,blacklistCount:t}}function qh(s){return $s(s)?[s.identitySigner]:Fs(s)?s.map(qh).flat():[]}function rR(s){let e=Fh(s);return e?e.blacklist:null}function Fh(s){if(Ms(s))return s;if(Fs(s)){let e=s.map(Fh).filter(t=>t!==null);if(e.length>1)throw new Error("Multiple blacklists");if(e.length===1)return e[0]}return null}function vg(s,e){if(qs(s)&&B.isEqual(s.signer,e))return s;if(Fs(s))for(let t of s){let n=vg(t,e);if(n)return n}return null}function iR(s){return b5(s,[])}function b5(s,e){if(qs(s))return [...e,s.signer];if(Fs(s)){let t=[...e];for(let n of s)t.push(...b5(n,e));return t}return e}function _h(s){if(qs(s))return {type:"leaf",value:f.concat(f.fromNumber(Mh),Hh(s))};if(Ms(s))return {type:"leaf",value:f.concat(f.fromNumber(Dc),f.concat(...s.blacklist.map(e=>f.padLeft(f.fromHex(e),20))))};if($s(s))return {type:"leaf",value:f.concat(f.fromNumber($h),f.padLeft(f.fromHex(s.identitySigner),20))};throw new Error("Invalid leaf")}function S5(s){let e=s[0];if(e===Dc){let t=[];for(let n=1;n<s.length;n+=20)t.push(f.toHex(s.slice(n,n+20)));return {type:"implicit-blacklist",blacklist:t}}if(e===$h)return {type:"identity-signer",identitySigner:f.toHex(s.slice(1,21))};if(e===Mh)return {type:"session-permissions",...gg(s.slice(1))};throw new Error("Invalid leaf")}function v5(s){if(Fs(s))return s.map(v5);if(Ms(s)||$s(s)||qs(s))return _h(s);if(un(s))return s;throw new Error("Invalid topology")}function x5(s){if(bs(s))return s.map(x5);if(pt(s))throw new Error("Unknown in configuration tree");return S5(s.value)}function xg(s){if(Fs(s)){let e=[];for(let i of s)e.push(xg(i));let t=f.concat(...e),n=ws(BigInt(t.length));if(n>15)throw new Error("Branch too large");let r=hv<<4|n;return f.concat(f.fromNumber(r),f.padLeft(f.fromNumber(t.length),n),t)}if(qs(s)){let e=Mh<<4,t=Hh(s);return f.concat(f.fromNumber(e),t)}if(un(s)){let e=lv<<4;return f.concat(f.fromNumber(e),E.toBytes(s))}if(Ms(s)){let e=f.concat(...s.blacklist.map(n=>f.fromHex(n)));if(s.blacklist.length>=15){if(s.blacklist.length>65535)throw new Error("Blacklist too large");return f.concat(f.fromNumber(Dc<<4|15),f.fromNumber(s.blacklist.length,{size:2}),e)}let t=Dc<<4|s.blacklist.length;return f.concat(f.fromNumber(t),e)}if($s(s)){let e=$h<<4;return f.concat(f.fromNumber(e),f.padLeft(f.fromHex(s.identitySigner),20))}throw new Error("Invalid topology")}function mv(s){let{topology:e}=E5(s);return e}function E5(s){if(s.length===0)throw new Error("Empty topology bytes");let e=s[0],t=(e&240)>>4,n=e&15;if(t===hv){if(n===0||n>15)throw new Error("Invalid branch size");let r=1,i=f.toNumber(s.slice(r,r+n));r+=n;let a=s.slice(r,r+i),o=[],c=0;for(;c<a.length;){let{topology:u,pointer:l}=E5(a.slice(c));o.push(u),c+=l;}return {topology:o,pointer:r+i}}else if(t===Mh){let r=gg(s.slice(1)),i=1+Hh(r).length;return {topology:{type:"session-permissions",...r},pointer:i}}else if(t===lv){let r=y5+1;if(s.length<r)throw new Error("Invalid node length");return {topology:E.fromBytes(s.slice(1,r)),pointer:r}}else if(t===Dc){let r=1,i=n;n===15&&(i=f.toNumber(s.slice(r,r+2)),r+=2);let a=[];for(let o=0;o<i;o++){let c=s.slice(r+o*20,r+(o+1)*20);a.push(B.from(E.fromBytes(c)));}return {topology:{type:"implicit-blacklist",blacklist:a},pointer:r+i*20}}else if(t===$h){if(s.length<21)throw new Error("Invalid identity signer length");return {topology:{type:"identity-signer",identitySigner:B.from(E.fromBytes(s.slice(1,21)))},pointer:21}}else throw new Error(`Invalid topology flag: ${t}`)}function aR(s){return JSON.stringify(A5(s))}function A5(s){if(un(s))return s;if(qs(s))return yg(s);if(Ms(s)||$s(s))return s;if(Fs(s))return s.map(e=>A5(e));throw new Error("Invalid topology")}function oR(s){let e=JSON.parse(s);return I5(e)}function I5(s){if(Array.isArray(s))return s.map(t=>I5(t));if(typeof s=="string"&&E.validate(s)&&E.size(s)===32)return s;if(typeof s=="object"&&s!==null&&"signer"in s&&"valueLimit"in s&&"deadline"in s&&"permissions"in s)return {type:"session-permissions",...wg(s)};if(typeof s=="object"&&s!==null&&"identitySigner"in s)return {type:"identity-signer",identitySigner:s.identitySigner};if(typeof s=="object"&&s!==null&&"blacklist"in s)return {type:"implicit-blacklist",blacklist:s.blacklist.map(t=>B.from(t))};throw new Error("Invalid topology")}function pv(s,e){if(bg(s)&&bg(e)){if(s.type===e.type){if(qs(s)&&qs(e)){if(B.isEqual(s.signer,e.signer))return null}else if(Ms(s)&&Ms(e)){let t=s.blacklist.filter(n=>!e.blacklist.includes(n));return t.length===0?null:{type:"implicit-blacklist",blacklist:t}}else if($s(s)&&$s(e)&&B.isEqual(s.identitySigner,e.identitySigner))return null}}else if(un(s)&&un(e)&&E.isEqual(s,e))return null;if(Fs(s)){let t=[];for(let n of s){let r=pv(n,e);r!=null&&t.push(r);}return t.length===0?null:t.length===1?t[0]:t}return s}function cR(s,e){let t=vg(s,e);if(!t)return s;let n=pv(s,t);return n?Kh(n):null}function uR(s,e){if(vg(s,e.signer))throw new Error("Session already exists");let t=gv(s,{type:"session-permissions",...e});return Kh(t)}function lR(s,e){let n=pv(s,{type:"identity-signer",identitySigner:e});return n?Kh(n):null}function hR(s,e){if(qh(s).some(n=>B.isEqual(n,e)))throw new Error("Identity signer already exists");let t=gv(s,{type:"identity-signer",identitySigner:e});return Kh(t)}function gv(s,e){return [s,e]}function C5(s){if(bg(s)||un(s))return [s];let e=[];for(let t of s)e.push(...C5(t));return e}function Sg(s){if(s.length===1)return s[0];if(s.length===0)throw new Error("Cannot build a topology from an empty list");let e=Math.floor(s.length/2),t=s.slice(0,e),n=s.slice(e),r=Sg(t),i=Sg(n);return [r,i]}function Kh(s){return Sg(C5(s))}function N5(s,e=BigInt(Math.floor(Date.now()/1e3))){if(un(s))return s;if(qs(s))return s.deadline<e?null:s;if($s(s)||Ms(s))return s;let t=[];for(let n of s){let r=N5(n,e);r!==null&&t.push(r);}return t.length===0?null:t.length===1?t[0]:t}function Eg(s,e=[],t=[],n){if(Fs(s)){let r=s.map(i=>Eg(i,e,t,n));return r.every(i=>un(i))?oe.keccak256(f.concat(...r.map(i=>E.toBytes(i))),{as:"Hex"}):r}if(qs(s))return e.includes(s.signer)?s:_s(_h(s));if(Ms(s))return t.length===0?_s(_h(s)):s;if($s(s))return n&&!B.isEqual(s.identitySigner,n)?_s(_h(s)):s;if(un(s))return s;throw new Error("Invalid topology")}function fR(s,e){let t=Fh(s);if(!t)throw new Error("No blacklist found");let{blacklist:n}=t;return n.some(r=>B.isEqual(r,e))||(n.push(e),n.sort((r,i)=>BigInt(r)<BigInt(i)?-1:1)),s}function dR(s,e){let t=Fh(s);if(!t)throw new Error("No blacklist found");let{blacklist:n}=t,r=n.filter(i=>i!==e);return t.blacklist=r,s}function k5(s){if(!Array.isArray(s))return k5([s]);let e=[{type:"implicit-blacklist",blacklist:[]},...s.map(t=>({type:"identity-signer",identitySigner:t}))];return Sg(e)}var Or={};be(Or,{decodeSessionSignature:()=>yR,encodeSessionCallSignatureForJson:()=>P5,encodeSessionSignature:()=>gR,hashPayloadWithCallIdx:()=>wR,isExplicitSessionCallSignature:()=>bv,isImplicitSessionCallSignature:()=>Ag,sessionCallSignatureFromJson:()=>pR,sessionCallSignatureFromParsed:()=>T5,sessionCallSignatureToJson:()=>mR});function Ag(s){return "attestation"in s&&"identitySignature"in s&&"sessionSignature"in s}function bv(s){return "permissionIndex"in s&&"sessionSignature"in s}function mR(s){return JSON.stringify(P5(s))}function P5(s){if(Ag(s))return {attestation:It.encodeForJson(s.attestation),identitySignature:yv(s.identitySignature),sessionSignature:yv(s.sessionSignature)};if(bv(s))return {permissionIndex:s.permissionIndex,sessionSignature:yv(s.sessionSignature)};throw new Error("Invalid call signature")}function pR(s){let e=JSON.parse(s);return T5(e)}function T5(s){if(s.attestation)return {attestation:It.fromParsed(s.attestation),identitySignature:wv(s.identitySignature),sessionSignature:wv(s.sessionSignature)};if(s.permissionIndex)return {permissionIndex:s.permissionIndex,sessionSignature:wv(s.sessionSignature)};throw new Error("Invalid call signature")}function yv(s){return `${s.r.toString()}:${s.s.toString()}:${s.yParity+27}`}function wv(s){let e=s.split(":");if(e.length!==3)throw new Error("Signature must be in r:s:v format");let[t,n,r]=e;if(!t||!n||!r)throw new Error("Invalid signature format");return {r:f.toBigInt(f.fromHex(t,{size:32})),s:f.toBigInt(f.fromHex(n,{size:32})),yParity:parseInt(r,10)-27}}function gR(s,e,t,n=[],r=[]){let i=[];if(!dv(e))throw new Error("Incomplete topology");if(!qh(e).some(l=>B.isEqual(l,t)))throw new Error("Identity signer not found");e=Eg(e,n,r,t);let o=xg(e);if(ws(BigInt(o.length))>3)throw new Error("Session topology is too large");i.push(f.fromNumber(o.length,{size:3}),o);let c=new Map,u=[];if(s.filter(Ag).forEach(l=>{if(l.attestation){let h=It.toJson(l.attestation);c.has(h)||(c.set(h,u.length),u.push(f.concat(It.encode(l.attestation),Un(l.identitySignature))));}}),u.length>=128)throw new Error("Too many attestations");i.push(f.fromNumber(u.length,{size:1}),f.concat(...u));for(let l of s)if(Ag(l)){let h=It.toJson(l.attestation),m=c.get(h);if(m===void 0)throw new Error("Failed to find attestation index");let y=128|m;i.push(f.fromNumber(y,{size:1}),Un(l.sessionSignature));}else if(bv(l)){if(l.permissionIndex>pg)throw new Error("Permission index is too large");let h=l.permissionIndex;i.push(f.fromNumber(h,{size:1}),Un(l.sessionSignature));}else throw new Error("Invalid call signature");return f.concat(...i)}function yR(s){let e=0,t=f.toNumber(s.slice(e,e+3));e+=3;let n=s.slice(e,e+t);e+=t;let r=mv(n),i=f.toNumber(s.slice(e,e+1));e+=1;let a=[],o=[];for(let u=0;u<i;u++){let l=It.decode(s.slice(e));e+=It.encode(l).length,a.push(l);let h=ga(s.slice(e,e+64));e+=64,o.push(h);}let c=[];for(;e<s.length;){let u=s[e];e+=1;let l=ga(s.slice(e,e+64));if(e+=64,u&128){let h=u&127;if(h>=a.length)throw new Error("Invalid attestation index");c.push({attestation:a[h],identitySignature:o[h],sessionSignature:l});}else {let h=u;c.push({permissionIndex:BigInt(h),sessionSignature:l});}}return {topology:r,callSignatures:c}}function wR(s,e,t,n,r){if(r&&(B.isEqual(r,Ne.Dev1.sessions)||B.isEqual(r,Ne.Dev2.sessions)||B.isEqual(r,Ne.Rc3.sessions))){let c=e.calls[t],u=!B.isEqual(r,Ne.Rc3.sessions);return E.fromBytes(oe.keccak256(f.concat(f.fromNumber(n,{size:32}),f.fromNumber(e.space,{size:32}),f.fromNumber(e.nonce,{size:32}),u?f.from([]):f.fromNumber(t,{size:32}),f.fromHex(ce.hashCall(c)))))}let a=e.parentWallets;e.parentWallets&&e.parentWallets.length>0&&e.parentWallets.pop();let o=ce.hash(s,n,e);return e.parentWallets=a,E.fromBytes(oe.keccak256(f.concat(o,f.fromNumber(t,{size:32}))))}var wa={};be(wa,{Dev1:()=>B5,Dev2:()=>O5,Dev2_4337:()=>R5,KnownContexts:()=>bR,Rc3:()=>V5,Rc3_4337:()=>D5,Rc4:()=>L5,Rc4_4337:()=>j5,Rc5:()=>U5,Rc5_4337:()=>H5,isKnownContext:()=>SR});var B5={factory:"0xe828630697817291140D6B7A42a2c3b7277bE45a",stage1:"0x2a4fB19F66F1427A5E363Bf1bB3be27b9A9ACC39",stage2:"0xe1299E4456b267123F7Aba29B72C2164ff501BDa",creationCode:"0x603e600e3d39601e805130553df33d3d34601c57363d3d373d363d30545af43d82803e903d91601c57fd5bf3"},O5={factory:"0xFE14B91dE3c5Ca74c4D24608EBcD4B2848aA6010",stage1:"0x300E98ae5bEA4A7291d62Eb0b9feD535E10095dD",stage2:"0x90cb0a8ccf40bEdA60896e408bdc7801033447C6",creationCode:"0x6041600e3d396021805130553df33d3d36153402601f57363d3d373d363d30545af43d82803e903d91601f57fd5bf3"},R5={factory:"0xFE14B91dE3c5Ca74c4D24608EBcD4B2848aA6010",stage1:"0x8Ae58FCc0Ee9b32994CA52c9854deb969DC8fa2A",stage2:"0x30f8e3AceAcDEac8a3F28935D87FD58DC5f71ad2",creationCode:"0x6041600e3d396021805130553df33d3d36153402601f57363d3d373d363d30545af43d82803e903d91601f57fd5bf3",capabilities:{erc4337:{entrypoint:"0x0000000071727De22E5E9d8BAf0edAc6f37da032"}}},V5={factory:"0x00000000000018A77519fcCCa060c2537c9D6d3F",stage1:"0x00000000000084fA81809Dd337311297C5594d62",stage2:"0x7438718F9E4b9B834e305A620EEeCf2B9E6eBE79",creationCode:"0x6041600e3d396021805130553df33d3d36153402601f57363d3d373d363d30545af43d82803e903d91601f57fd5bf3"},D5={factory:"0x00000000000018A77519fcCCa060c2537c9D6d3F",stage1:"0x0000000000005A02E3218e820EA45102F84A35C7",stage2:"0x7706aaC0cc2C42C01CE17136F7475b0E46F2ABA1",creationCode:"0x6041600e3d396021805130553df33d3d36153402601f57363d3d373d363d30545af43d82803e903d91601f57fd5bf3",capabilities:{erc4337:{entrypoint:"0x0000000071727De22E5E9d8BAf0edAc6f37da032"}}},L5={factory:"0x00000000000018A77519fcCCa060c2537c9D6d3F",stage1:"0x0000000000003DF093bc4257E6dCE45D937EF161",stage2:"0x10bE1Abf3cD0918bb1079ECc6b8220c177F34088",creationCode:"0x6041600e3d396021805130553df33d3d36153402601f57363d3d373d363d30545af43d82803e903d91601f57fd5bf3"},j5={factory:"0x00000000000018A77519fcCCa060c2537c9D6d3F",stage1:"0x0000000000003add039FF84b064B7347Fc23C444",stage2:"0x4B3E5735665057A0A15eE448A7293bC01e3b4De9",creationCode:"0x6041600e3d396021805130553df33d3d36153402601f57363d3d373d363d30545af43d82803e903d91601f57fd5bf3",capabilities:{erc4337:{entrypoint:"0x0000000071727De22E5E9d8BAf0edAc6f37da032"}}},U5={factory:"0x00000000000018A77519fcCCa060c2537c9D6d3F",stage1:"0x0000000000001f3C39d61698ab21131a12134454",stage2:"0xD0ae8eF93b7DA4eabb32Ec4d81b7a501DCa04D4C",creationCode:"0x6041600e3d396021805130553df33d3d36153402601f57363d3d373d363d30545af43d82803e903d91601f57fd5bf3"},H5={factory:"0x00000000000018A77519fcCCa060c2537c9D6d3F",stage1:"0x0000000000009caFdeDb6f64Bf5F31a22124B2a8",stage2:"0xcBca3328a731deffE6Ce4c2fb51b585c3c37FB92",creationCode:"0x6041600e3d396021805130553df33d3d36153402601f57363d3d373d363d30545af43d82803e903d91601f57fd5bf3",capabilities:{erc4337:{entrypoint:"0x0000000071727De22E5E9d8BAf0edAc6f37da032"}}},bR=[{name:"Dev1",development:!0,...B5},{name:"Dev2",development:!0,...O5},{name:"Dev2_4337",development:!0,...R5},{name:"Rc3",development:!0,...V5},{name:"Rc3_4337",development:!0,...D5},{name:"Rc4",development:!1,...L5},{name:"Rc4_4337",development:!1,...j5},{name:"Rc5",development:!1,...U5},{name:"Rc5_4337",development:!1,...H5}];function SR(s){return s.name!==void 0&&s.development!==void 0}var Ne={};be(Ne,{Dev1:()=>VR,Dev2:()=>DR,Passkeys:()=>vv,Rc3:()=>LR,Rc4:()=>jR,Rc5:()=>UR,Recovery:()=>Rv});var vv={};be(vv,{decode:()=>IR,encode:()=>ER,fromTree:()=>vR,isValidSignature:()=>AR,metadataNode:()=>_5,metadataTree:()=>Sv,rootFor:()=>xR,toTree:()=>M5});function Sv(s){return typeof s=="object"?{type:"leaf",value:f.fromString(s.credentialId)}:s}function _5(s){return _s(Sv(s))}function M5(s){let e=E.padLeft(s.x,32),t=E.padLeft(s.y,32),n=E.padLeft(s.requireUserVerification?"0x01":"0x00",32);return s.metadata?[[e,t],[n,Sv(s.metadata)]]:[[e,t],[n,E.padLeft("0x00",32)]]}function vR(s){if(!bs(s)||s.length!==2)throw new Error("Invalid tree");let[e,t]=s;if(!bs(e)||e.length!==2)throw new Error("Invalid tree for x,y");let[n,r]=e;if(!pt(n))throw new Error("Invalid x bytes");if(!pt(r))throw new Error("Invalid y bytes");let i=!1,a;if(bs(t)){if(t.length!==2)throw new Error("Invalid tree for c,metadata");let[o,c]=t;if(!pt(o))throw new Error("Invalid c bytes");if(i=E.toBytes(o)[31]===1,bs(c)){if(c.length!==2)throw new Error("Invalid metadata tree");let[l,h]=c;if(!Br(l))throw new Error("Invalid credentialId leaf");let m=new TextDecoder().decode(l.value);if(!bs(h)||h.length!==2)throw new Error("Invalid sub-branch for name and createdAt");let[y,g]=h;if(!Br(y)||!Br(g))throw new Error("Invalid metadata leaves");a={credentialId:m};}else if(pt(c))a=c;else throw new Error("Invalid metadata node")}else {if(!pt(t))throw new Error("Invalid c bytes");i=E.toBytes(t)[31]===1;}return {requireUserVerification:i,x:n,y:r,metadata:a}}function xR(s){return _s(M5(s))}function ER(s){let e=s.clientDataJSON.indexOf('"challenge"'),t=s.clientDataJSON.indexOf('"type"'),n=s.authenticatorData.length,r=s.clientDataJSON.length;if(n>65535)throw new Error("Authenticator data size is too large");if(r>65535)throw new Error("Client data JSON size is too large");let i=n<=255?1:2,a=r<=255?1:2,o=e<=255?1:2,c=t<=255?1:2,u=0;u|=s.publicKey.requireUserVerification?1:0,u|=i-1<<1,u|=a-1<<2,u|=o-1<<3,u|=c-1<<4,s.embedMetadata&&(u|=64);let l=f.from([u]);if(s.embedMetadata){if(!s.publicKey.metadata)throw new Error("Metadata is not present in the public key");l=f.concat(l,E.toBytes(_5(s.publicKey.metadata)));}return l=f.concat(l,f.padLeft(f.fromNumber(n),i)),l=f.concat(l,s.authenticatorData),l=f.concat(l,f.padLeft(f.fromNumber(s.clientDataJSON.length),a)),l=f.concat(l,f.from(new TextEncoder().encode(s.clientDataJSON))),l=f.concat(l,f.padLeft(f.fromNumber(e),o)),l=f.concat(l,f.padLeft(f.fromNumber(t),c)),l=f.concat(l,f.padLeft(s.r,32)),l=f.concat(l,f.padLeft(s.s,32)),l=f.concat(l,f.fromHex(s.publicKey.x)),l=f.concat(l,f.fromHex(s.publicKey.y)),l}function AR(s,e){return Tr.verify({challenge:s,publicKey:{x:E.toBigInt(e.publicKey.x),y:E.toBigInt(e.publicKey.y),prefix:4},metadata:{authenticatorData:E.fromBytes(e.authenticatorData),challengeIndex:e.clientDataJSON.indexOf('"challenge"'),clientDataJSON:e.clientDataJSON,typeIndex:e.clientDataJSON.indexOf('"type"'),userVerificationRequired:e.publicKey.requireUserVerification},signature:{r:f.toBigInt(e.r),s:f.toBigInt(e.s)}})}function IR(s){let e=0,t=s[0];if(e+=1,t===void 0)throw new Error("Invalid flags");let n=(t&1)!==0,r=(t>>1&1)+1,i=(t>>2&1)+1,a=(t>>3&1)+1,o=(t>>4&1)+1,c=(t>>6&1)===1;if(t&32)throw new Error("Fallback to abi decode is not supported in this implementation");let u;if(c){let I=f.slice(s,e,e+32);u=E.fromBytes(I),e+=32;}let l=f.toNumber(f.slice(s,e,e+r));e+=r;let h=f.slice(s,e,e+l);e+=l;let m=f.toNumber(f.slice(s,e,e+i));e+=i;let y=f.slice(s,e,e+m);e+=m;let g=new TextDecoder().decode(y),w=f.toNumber(f.slice(s,e,e+a));e+=a;let S=f.toNumber(f.slice(s,e,e+o));e+=o;let C=f.slice(s,e,e+32);e+=32;let N=f.slice(s,e,e+32);e+=32;let x=f.slice(s,e,e+32);e+=32;let v=f.slice(s,e,e+32);return {publicKey:{requireUserVerification:n,x:E.fromBytes(x),y:E.fromBytes(v),metadata:u},r:C,s:N,authenticatorData:h,clientDataJSON:g,challengeIndex:w,typeIndex:S,embedMetadata:c}}var Rv={};be(Rv,{DOMAIN_NAME:()=>CR,DOMAIN_VERSION:()=>NR,FLAG_BRANCH:()=>Bv,FLAG_NODE:()=>Tv,FLAG_RECOVERY_LEAF:()=>Pv,QUEUED_PAYLOAD_HASHES:()=>F5,QUEUE_PAYLOAD:()=>$5,TIMESTAMP_FOR_QUEUED_PAYLOAD:()=>q5,TOTAL_QUEUED_PAYLOADS:()=>K5,decodeTopology:()=>kR,encodeCalldata:()=>TR,encodeTopology:()=>Cv,fromGenericTree:()=>kv,fromRecoveryLeaves:()=>Nv,getRecoveryLeaves:()=>Av,hashConfiguration:()=>Ev,hashRecoveryPayload:()=>PR,isBranch:()=>ba,isRecoveryLeaf:()=>Lc,isTree:()=>xv,parseBranch:()=>Ov,queuedPayloadHashOf:()=>OR,timestampForQueuedPayload:()=>RR,toGenericTree:()=>Ig,totalQueuedPayloads:()=>BR,trimTopology:()=>Iv});var Pv=1,Tv=3,Bv=4,Gh=f.fromString(`Sequence recovery leaf:
|
|
349
|
-
`),$5=at.from(["function queuePayload(address _wallet, address _signer, (uint8 kind,bool noChainId,(address to,uint256 value,bytes data,uint256 gasLimit,bool delegateCall,bool onlyFallback,uint256 behaviorOnError)[] calls,uint256 space,uint256 nonce,bytes message,bytes32 imageHash,bytes32 digest,address[] parentWallets) calldata _payload, bytes calldata _signature) external"])[0],q5=at.from(["function timestampForQueuedPayload(address _wallet, address _signer, bytes32 _payloadHash) external view returns (uint256)"])[0],F5=at.from(["function queuedPayloadHashes(address _wallet, address _signer, uint256 _index) external view returns (bytes32)"])[0],K5=at.from(["function totalQueuedPayloads(address _wallet, address _signer) external view returns (uint256)"])[0];function Lc(s){return typeof s=="object"&&s!==null&&s.type==="leaf"}function ba(s){return Array.isArray(s)&&s.length===2&&xv(s[0])&&xv(s[1])}function xv(s){return Lc(s)||pt(s)||ba(s)}var CR="Sequence Wallet - Recovery Mode",NR="1";function Ev(s){return _s(Ig(s))}function Av(s){if(Lc(s))return {leaves:[s],isComplete:!0};if(pt(s))return {leaves:[],isComplete:!1};if(ba(s)){let t=Av(s[0]),n=Av(s[1]);return {leaves:[...t.leaves,...n.leaves],isComplete:t.isComplete&&n.isComplete}}else throw new Error("Invalid topology")}function kR(s){let{nodes:e,leftover:t}=Ov(s);if(t.length>0)throw new Error("Leftover bytes in branch");return G5(e)}function Ov(s){if(s.length===0)throw new Error("Empty branch");let e=[],t=0;for(;t<s.length;){let n=s[t];if(n===Pv){if(s.length<t+32)throw new Error("Invalid recovery leaf");let r=B.from(E.fromBytes(s.slice(t+1,t+21))),i=f.toBigInt(s.slice(t+21,t+24)),a=f.toBigInt(s.slice(t+24,t+32));e.push({type:"leaf",signer:r,requiredDeltaTime:i,minTimestamp:a}),t+=32;continue}else if(n===Tv){if(s.length<t+33)throw new Error("Invalid node");let r=E.fromBytes(s.slice(t+1,t+33));e.push(r),t+=33;continue}else if(n===Bv){if(s.length<t+4)throw new Error("Invalid branch");let r=f.toNumber(s.slice(t+1,t+4));if(s.length<t+4+r)throw new Error("Invalid branch");let i=s.slice(t+4,t+4+r),{nodes:a,leftover:o}=Ov(i);if(o.length>0)throw new Error("Leftover bytes in sub-branch");let c=G5(a);e.push(c),t+=4+r;continue}else throw new Error("Invalid flag")}return {nodes:e,leftover:s.slice(t)}}function Iv(s,e){if(Lc(s))return s.signer===e?s:Ev(s);if(pt(s))return s;if(ba(s)){let t=Iv(s[0],e),n=Iv(s[1],e);return pt(t)&&pt(n)?Ev(s):[t,n]}throw new Error("Invalid topology")}function Cv(s){if(ba(s)){let e=Cv(s[0]),t=Cv(s[1]);if(ba(s[1])){if(t.length>16777215)throw new Error("Branch too large");let r=f.fromNumber(Bv),i=f.padLeft(f.fromNumber(t.length),3);return f.concat(e,r,i,t)}else return f.concat(e,t)}if(pt(s)){let e=f.fromNumber(Tv),t=f.fromHex(s,{size:32});return f.concat(e,t)}if(Lc(s)){let e=f.fromNumber(Pv),t=f.fromHex(s.signer,{size:20});if(s.requiredDeltaTime>16777215n)throw new Error("Required delta time too large");let n=f.padLeft(f.fromNumber(s.requiredDeltaTime),3);if(s.minTimestamp>18446744073709551615n)throw new Error("Min timestamp too large");let r=f.padLeft(f.fromNumber(s.minTimestamp),8);return f.concat(e,t,n,r)}throw new Error("Invalid topology")}function G5(s){if(s.length===0)throw new Error("Empty signature tree");if(s.length===1)return s[0];let e=s[0];for(let t=1;t<s.length;t++)e=[e,s[t]];return e}function Nv(s){if(s.length===0)throw new Error("Cannot build a tree with zero leaves");if(s.length===1)return s[0];let e=Math.floor(s.length/2),t=Nv(s.slice(0,e)),n=Nv(s.slice(e));return [t,n]}function PR(s,e,t,n){let r=KS(s);return E.fromBytes(Pc(e,n?0:t,r))}function Ig(s){if(Lc(s))return {type:"leaf",value:f.concat(Gh,f.fromHex(s.signer,{size:20}),f.padLeft(f.fromNumber(s.requiredDeltaTime),32),f.padLeft(f.fromNumber(s.minTimestamp),32))};if(pt(s))return s;if(ba(s))return [Ig(s[0]),Ig(s[1])];throw new Error("Invalid topology")}function kv(s){if(Br(s)){let e=s.value;if(e.length!==Gh.length+84||!f.isEqual(e.slice(0,Gh.length),Gh))throw new Error("Invalid recovery leaf format");let t=Gh.length,n=B.from(E.fromBytes(e.slice(t,t+20))),r=f.toBigInt(e.slice(t+20,t+52)),i=f.toBigInt(e.slice(t+52,t+84));return {type:"leaf",signer:n,requiredDeltaTime:r,minTimestamp:i}}else {if(pt(s))return s;if(bs(s)){if(s.length!==2)throw new Error("Recovery tree only supports binary branches");return [kv(s[0]),kv(s[1])]}else throw new Error("Invalid tree format")}}function TR(s,e,t,n){let r;n.type==="erc1271"?r=n.data:r=f.toHex(Un(n));let i=JS(e);return te.encodeData($5,[s,t,i,r])}async function BR(s,e,t,n){let r=await s.request({method:"eth_call",params:[{to:e,data:te.encodeData(K5,[t,n])},"latest"]});return r==="0x"?0n:E.toBigInt(r)}async function OR(s,e,t,n,r){return await s.request({method:"eth_call",params:[{to:e,data:te.encodeData(F5,[t,n,r])},"latest"]})}async function RR(s,e,t,n,r){let i=await s.request({method:"eth_call",params:[{to:e,data:te.encodeData(q5,[t,n,r])},"latest"]});return E.toBigInt(i)}var VR={passkeys:"0x8f26281dB84C18aAeEa8a53F94c835393229d296",recovery:"0xd98da48C4FF9c19742eA5856A277424557C863a6",sessions:"0x06aa3a8F781F2be39b888Ac8a639c754aEe9dA29"},DR={passkeys:"0x4491845806B757D67BE05BbD877Cab101B9bee5C",recovery:"0xdED857b9b5142832634129aFfc1D67cD106b927c",sessions:"0x06aa3a8F781F2be39b888Ac8a639c754aEe9dA29"},LR={passkeys:"0x0000000000dc2d96870dc108c5E15570B715DFD2",recovery:"0x0000000000213697bCA95E7373787a40858a51C7",sessions:"0x0000000000CC58810c33F3a0D78aA1Ed80FaDcD8"},jR={passkeys:"0x0000000000005204F3711851EAD52CC9c241499a",recovery:"0x000000000001FC499c3E177DD56Febb0A4bc15b7",sessions:"0x00000000000030Bcc832F7d657f50D6Be35C92b3"},UR={passkeys:"0x0000000000005204F3711851EAD52CC9c241499a",recovery:"0x000000000000AB36D17eB1150116371520565205",sessions:"0x00000000000030Bcc832F7d657f50D6Be35C92b3"};var Sa={};be(Sa,{ALL:()=>Vv,ChainId:()=>H,NetworkType:()=>de,getNetworkFromChainId:()=>_R,getNetworkFromName:()=>HR});var de;(function(s){s.MAINNET="mainnet",s.TESTNET="testnet";})(de||(de={}));var H={NONE:0,MAINNET:1,SEPOLIA:11155111,POLYGON:137,POLYGON_ZKEVM:1101,POLYGON_AMOY:80002,BSC:56,BSC_TESTNET:97,OPTIMISM:10,OPTIMISM_SEPOLIA:11155420,ARBITRUM:42161,ARBITRUM_SEPOLIA:421614,ARBITRUM_NOVA:42170,AVALANCHE:43114,AVALANCHE_TESTNET:43113,GNOSIS:100,BASE:8453,BASE_SEPOLIA:84532,HOMEVERSE_TESTNET:40875,HOMEVERSE:19011,XAI:660279,XAI_SEPOLIA:37714555429,TELOS:40,TELOS_TESTNET:41,B3:8333,B3_SEPOLIA:1993,APECHAIN:33139,APECHAIN_TESTNET:33111,BLAST:81457,BLAST_SEPOLIA:168587773,SKALE_NEBULA:1482601649,SKALE_NEBULA_TESTNET:37084624,SONEIUM_MINATO:1946,SONEIUM:1868,TOY_TESTNET:21e6,IMMUTABLE_ZKEVM:13371,IMMUTABLE_ZKEVM_TESTNET:13473,ETHERLINK:42793,ETHERLINK_TESTNET:128123,MOONBEAM:1284,MOONBASE_ALPHA:1287,MONAD:143,MONAD_TESTNET:10143,SOMNIA_TESTNET:50312,SOMNIA:5031,INCENTIV_TESTNET_V2:28802,KATANA:747474,SANDBOX_TESTNET:6252,ARC_TESTNET:5042002},Vv=[{chainId:H.MAINNET,type:de.MAINNET,name:"mainnet",title:"Ethereum",rpcUrl:ge("mainnet"),logoUrl:ye(H.MAINNET),blockExplorer:{name:"Etherscan",url:"https://etherscan.io/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18},ensAddress:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},{chainId:H.SEPOLIA,type:de.TESTNET,name:"sepolia",title:"Sepolia",rpcUrl:ge("sepolia"),logoUrl:ye(H.SEPOLIA),blockExplorer:{name:"Etherscan (Sepolia)",url:"https://sepolia.etherscan.io/"},nativeCurrency:{symbol:"sETH",name:"Sepolia Ether",decimals:18}},{chainId:H.POLYGON,type:de.MAINNET,name:"polygon",title:"Polygon",rpcUrl:ge("polygon"),logoUrl:ye(H.POLYGON),blockExplorer:{name:"Polygonscan",url:"https://polygonscan.com/"},nativeCurrency:{symbol:"POL",name:"POL",decimals:18}},{chainId:H.POLYGON_AMOY,type:de.TESTNET,name:"amoy",title:"Polygon Amoy",rpcUrl:ge("amoy"),logoUrl:ye(H.POLYGON_AMOY),blockExplorer:{name:"OKLink (Amoy)",url:"https://www.oklink.com/amoy/"},nativeCurrency:{symbol:"aPOL",name:"Amoy POL",decimals:18}},{chainId:H.POLYGON_ZKEVM,type:de.MAINNET,name:"polygon-zkevm",title:"Polygon zkEVM",rpcUrl:ge("polygon-zkevm"),logoUrl:ye(H.POLYGON_ZKEVM),blockExplorer:{name:"Polygonscan (zkEVM)",url:"https://zkevm.polygonscan.com/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.BSC,type:de.MAINNET,name:"bsc",title:"BNB Smart Chain",rpcUrl:ge("bsc"),logoUrl:ye(H.BSC),blockExplorer:{name:"BSCScan",url:"https://bscscan.com/"},nativeCurrency:{symbol:"BNB",name:"BNB",decimals:18}},{chainId:H.BSC_TESTNET,type:de.TESTNET,name:"bsc-testnet",title:"BNB Smart Chain Testnet",rpcUrl:ge("bsc-testnet"),logoUrl:ye(H.BSC_TESTNET),blockExplorer:{name:"BSCScan (Testnet)",url:"https://testnet.bscscan.com/"},nativeCurrency:{symbol:"tBNB",name:"Testnet BNB",decimals:18}},{chainId:H.OPTIMISM,type:de.MAINNET,name:"optimism",title:"Optimism",rpcUrl:ge("optimism"),logoUrl:ye(H.OPTIMISM),blockExplorer:{name:"Etherscan (Optimism)",url:"https://optimistic.etherscan.io/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.OPTIMISM_SEPOLIA,type:de.TESTNET,name:"optimism-sepolia",title:"Optimism Sepolia",rpcUrl:ge("optimism-sepolia"),logoUrl:ye(H.OPTIMISM_SEPOLIA),blockExplorer:{name:"Etherscan (Optimism Sepolia)",url:"https://sepolia-optimistic.etherscan.io/"},nativeCurrency:{symbol:"sETH",name:"Sepolia Ether",decimals:18}},{chainId:H.ARBITRUM,type:de.MAINNET,name:"arbitrum",title:"Arbitrum One",rpcUrl:ge("arbitrum"),logoUrl:ye(H.ARBITRUM),blockExplorer:{name:"Arbiscan",url:"https://arbiscan.io/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.ARBITRUM_SEPOLIA,type:de.TESTNET,name:"arbitrum-sepolia",title:"Arbitrum Sepolia",rpcUrl:ge("arbitrum-sepolia"),logoUrl:ye(H.ARBITRUM_SEPOLIA),blockExplorer:{name:"Arbiscan (Sepolia Testnet)",url:"https://sepolia.arbiscan.io/"},nativeCurrency:{symbol:"sETH",name:"Sepolia Ether",decimals:18}},{chainId:H.ARBITRUM_NOVA,type:de.MAINNET,name:"arbitrum-nova",title:"Arbitrum Nova",rpcUrl:ge("arbitrum-nova"),logoUrl:ye(H.ARBITRUM_NOVA),blockExplorer:{name:"Arbiscan Nova",url:"https://nova.arbiscan.io/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.AVALANCHE,type:de.MAINNET,name:"avalanche",title:"Avalanche",rpcUrl:ge("avalanche"),logoUrl:ye(H.AVALANCHE),blockExplorer:{name:"Snowtrace",url:"https://subnets.avax.network/c-chain/"},nativeCurrency:{symbol:"AVAX",name:"AVAX",decimals:18}},{chainId:H.AVALANCHE_TESTNET,type:de.TESTNET,name:"avalanche-testnet",title:"Avalanche Testnet",rpcUrl:ge("avalanche-testnet"),logoUrl:ye(H.AVALANCHE_TESTNET),blockExplorer:{name:"Snowtrace (Testnet)",url:"https://subnets-test.avax.network/c-chain/"},nativeCurrency:{symbol:"tAVAX",name:"Testnet AVAX",decimals:18}},{chainId:H.GNOSIS,type:de.MAINNET,name:"gnosis",title:"Gnosis Chain",rpcUrl:ge("gnosis"),logoUrl:ye(H.GNOSIS),blockExplorer:{name:"Gnosis Chain Explorer",url:"https://blockscout.com/xdai/mainnet/"},nativeCurrency:{symbol:"XDAI",name:"XDAI",decimals:18}},{chainId:H.BASE,type:de.MAINNET,name:"base",title:"Base (Coinbase)",rpcUrl:ge("base"),logoUrl:ye(H.BASE),blockExplorer:{name:"Base Explorer",url:"https://basescan.org/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.BASE_SEPOLIA,type:de.TESTNET,name:"base-sepolia",title:"Base Sepolia",rpcUrl:ge("base-sepolia"),logoUrl:ye(H.BASE_SEPOLIA),blockExplorer:{name:"Base Sepolia Explorer",url:"https://base-sepolia.blockscout.com/"},nativeCurrency:{symbol:"sETH",name:"Sepolia Ether",decimals:18}},{chainId:H.HOMEVERSE,type:de.MAINNET,name:"homeverse",title:"Oasys Homeverse",rpcUrl:ge("homeverse"),logoUrl:ye(H.HOMEVERSE),blockExplorer:{name:"Oasys Homeverse Explorer",url:"https://explorer.oasys.homeverse.games/"},nativeCurrency:{symbol:"OAS",name:"OAS",decimals:18}},{chainId:H.HOMEVERSE_TESTNET,type:de.TESTNET,name:"homeverse-testnet",title:"Oasys Homeverse Testnet",rpcUrl:ge("homeverse-testnet"),logoUrl:ye(H.HOMEVERSE_TESTNET),blockExplorer:{name:"Oasys Homeverse Explorer (Testnet)",url:"https://explorer.testnet.oasys.homeverse.games/"},nativeCurrency:{symbol:"tOAS",name:"Testnet OAS",decimals:18}},{chainId:H.XAI,type:de.MAINNET,name:"xai",title:"Xai",rpcUrl:ge("xai"),logoUrl:ye(H.XAI),blockExplorer:{name:"Xai Explorer",url:"https://explorer.xai-chain.net/"},nativeCurrency:{symbol:"XAI",name:"XAI",decimals:18}},{chainId:H.XAI_SEPOLIA,type:de.TESTNET,name:"xai-sepolia",title:"Xai Sepolia",rpcUrl:ge("xai-sepolia"),logoUrl:ye(H.XAI_SEPOLIA),blockExplorer:{name:"Xai Sepolia Explorer",url:"https://testnet-explorer-v2.xai-chain.net/"},nativeCurrency:{symbol:"sXAI",name:"Sepolia XAI",decimals:18}},{chainId:H.B3,type:de.MAINNET,name:"b3",title:"B3",rpcUrl:ge("b3"),logoUrl:ye(H.B3),blockExplorer:{name:"B3 Explorer",url:"https://explorer.b3.fun/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.B3_SEPOLIA,type:de.TESTNET,name:"b3-sepolia",title:"B3 Sepolia",rpcUrl:ge("b3-sepolia"),logoUrl:ye(H.B3_SEPOLIA),blockExplorer:{name:"B3 Sepolia Explorer",url:"https://sepolia.explorer.b3.fun/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.APECHAIN,type:de.MAINNET,name:"apechain",title:"APE Chain",rpcUrl:ge("apechain"),logoUrl:ye(H.APECHAIN),blockExplorer:{name:"APE Chain Explorer",url:"https://apechain.calderaexplorer.xyz/"},nativeCurrency:{symbol:"APE",name:"ApeCoin",decimals:18}},{chainId:H.APECHAIN_TESTNET,type:de.TESTNET,name:"apechain-testnet",title:"APE Chain Testnet",rpcUrl:ge("apechain-testnet"),logoUrl:ye(H.APECHAIN_TESTNET),blockExplorer:{name:"APE Chain Explorer",url:"https://curtis.explorer.caldera.xyz/"},nativeCurrency:{symbol:"APE",name:"ApeCoin",decimals:18}},{chainId:H.BLAST,type:de.MAINNET,name:"blast",title:"Blast",rpcUrl:ge("blast"),logoUrl:ye(H.BLAST),blockExplorer:{name:"Blast Explorer",url:"https://blastscan.io/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.BLAST_SEPOLIA,type:de.TESTNET,name:"blast-sepolia",title:"Blast Sepolia",rpcUrl:ge("blast-sepolia"),logoUrl:ye(H.BLAST_SEPOLIA),blockExplorer:{name:"Blast Sepolia Explorer",url:"https://sepolia.blastexplorer.io/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.TELOS,type:de.MAINNET,name:"telos",title:"Telos",rpcUrl:ge("telos"),logoUrl:ye(H.TELOS),blockExplorer:{name:"Telos Explorer",url:"https://explorer.telos.net/network/"},nativeCurrency:{symbol:"TLOS",name:"TLOS",decimals:18}},{chainId:H.TELOS_TESTNET,type:de.TESTNET,name:"telos-testnet",title:"Telos Testnet",rpcUrl:ge("telos-testnet"),logoUrl:ye(H.TELOS_TESTNET),blockExplorer:{name:"Telos Testnet Explorer",url:"https://explorer-test.telos.net/network"},nativeCurrency:{symbol:"TLOS",name:"TLOS",decimals:18}},{chainId:H.SKALE_NEBULA,type:de.MAINNET,name:"skale-nebula",title:"SKALE Nebula Gaming Hub",rpcUrl:ge("skale-nebula"),logoUrl:ye(H.SKALE_NEBULA),blockExplorer:{name:"SKALE Nebula Gaming Hub Explorer",url:"https://green-giddy-denebola.explorer.mainnet.skalenodes.com/"},nativeCurrency:{symbol:"sFUEL",name:"SKALE Fuel",decimals:18}},{chainId:H.SKALE_NEBULA_TESTNET,type:de.TESTNET,name:"skale-nebula-testnet",title:"SKALE Nebula Gaming Hub Testnet",rpcUrl:ge("skale-nebula-testnet"),logoUrl:ye(H.SKALE_NEBULA_TESTNET),blockExplorer:{name:"SKALE Nebula Gaming Hub Testnet Explorer",url:"https://lanky-ill-funny-testnet.explorer.testnet.skalenodes.com/"},nativeCurrency:{symbol:"sFUEL",name:"SKALE Fuel",decimals:18}},{chainId:H.SONEIUM,type:de.MAINNET,name:"soneium",title:"Soneium",rpcUrl:ge("soneium"),logoUrl:ye(H.SONEIUM),blockExplorer:{name:"Soneium Explorer",url:"https://soneium.blockscout.com/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.SONEIUM_MINATO,type:de.TESTNET,name:"soneium-minato",title:"Soneium Minato (Testnet)",rpcUrl:ge("soneium-minato"),logoUrl:ye(H.SONEIUM_MINATO),blockExplorer:{name:"Soneium Minato Explorer",url:"https://explorer-testnet.soneium.org/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.TOY_TESTNET,type:de.TESTNET,name:"toy-testnet",title:"TOY (Testnet)",rpcUrl:ge("toy-testnet"),logoUrl:ye(H.TOY_TESTNET),blockExplorer:{name:"TOY Testnet Explorer",url:"https://toy-chain-testnet.explorer.caldera.xyz/"},nativeCurrency:{symbol:"TOY",name:"TOY",decimals:18}},{chainId:H.IMMUTABLE_ZKEVM,type:de.MAINNET,name:"immutable-zkevm",title:"Immutable zkEVM",rpcUrl:ge("immutable-zkevm"),logoUrl:ye(H.IMMUTABLE_ZKEVM),blockExplorer:{name:"Immutable zkEVM Explorer",url:"https://explorer.immutable.com/"},nativeCurrency:{symbol:"IMX",name:"IMX",decimals:18}},{chainId:H.IMMUTABLE_ZKEVM_TESTNET,type:de.TESTNET,name:"immutable-zkevm-testnet",title:"Immutable zkEVM Testnet",rpcUrl:ge("immutable-zkevm-testnet"),logoUrl:ye(H.IMMUTABLE_ZKEVM_TESTNET),blockExplorer:{name:"Immutable zkEVM Testnet Explorer",url:"https://explorer.testnet.immutable.com/"},nativeCurrency:{symbol:"IMX",name:"IMX",decimals:18}},{chainId:H.MOONBEAM,type:de.MAINNET,name:"moonbeam",title:"Moonbeam",rpcUrl:ge("moonbeam"),logoUrl:ye(H.MOONBEAM),blockExplorer:{name:"Moonscan",url:"https://moonscan.io/"},nativeCurrency:{symbol:"GLMR",name:"GLMR",decimals:18}},{chainId:H.MOONBASE_ALPHA,type:de.TESTNET,name:"moonbase-alpha",title:"Moonbase Alpha",rpcUrl:ge("moonbase-alpha"),logoUrl:ye(H.MOONBASE_ALPHA),blockExplorer:{name:"Moonscan (Moonbase Alpha)",url:"https://moonbase.moonscan.io/"},nativeCurrency:{symbol:"GLMR",name:"GLMR",decimals:18}},{chainId:H.ETHERLINK,type:de.MAINNET,name:"etherlink",title:"Etherlink",rpcUrl:ge("etherlink"),logoUrl:ye(H.ETHERLINK),blockExplorer:{name:"Etherlink Explorer",url:"https://explorer.etherlink.com/"},nativeCurrency:{symbol:"XTZ",name:"Tez",decimals:18}},{chainId:H.ETHERLINK_TESTNET,type:de.TESTNET,name:"etherlink-testnet",title:"Etherlink Testnet",rpcUrl:ge("etherlink-testnet"),logoUrl:ye(H.ETHERLINK_TESTNET),blockExplorer:{name:"Etherlink Testnet Explorer",url:"https://testnet.explorer.etherlink.com/"},nativeCurrency:{symbol:"XTZ",name:"Tez",decimals:18}},{chainId:H.MONAD,type:de.MAINNET,name:"monad",title:"Monad",rpcUrl:ge("monad"),logoUrl:ye(H.MONAD),blockExplorer:{name:"Monad Explorer",url:"https://mainnet-beta.monvision.io/"},nativeCurrency:{symbol:"MON",name:"MON",decimals:18}},{chainId:H.MONAD_TESTNET,type:de.TESTNET,name:"monad-testnet",title:"Monad Testnet",rpcUrl:ge("monad-testnet"),logoUrl:ye(H.MONAD_TESTNET),blockExplorer:{name:"Monad Testnet Explorer",url:"https://testnet.monadexplorer.com/"},nativeCurrency:{symbol:"MON",name:"MON",decimals:18}},{chainId:H.SOMNIA,type:de.MAINNET,name:"somnia",title:"Somnia",rpcUrl:ge("somnia"),logoUrl:ye(H.SOMNIA),blockExplorer:{name:"Somnia Explorer",url:"https://mainnet.somnia.w3us.site/"},nativeCurrency:{symbol:"SOMI",name:"SOMI",decimals:18}},{chainId:H.SOMNIA_TESTNET,type:de.TESTNET,name:"somnia-testnet",title:"Somnia Testnet",rpcUrl:ge("somnia-testnet"),logoUrl:ye(H.SOMNIA_TESTNET),blockExplorer:{name:"Somnia Testnet Explorer",url:"https://somnia-testnet.socialscan.io/"},nativeCurrency:{symbol:"STT",name:"STT",decimals:18}},{chainId:H.INCENTIV_TESTNET_V2,type:de.TESTNET,name:"incentiv-testnet-v2",title:"Incentiv Testnet",rpcUrl:ge("incentiv-testnet-v2"),logoUrl:ye(H.INCENTIV_TESTNET_V2),blockExplorer:{name:"Incentiv Testnet Explorer",url:"https://explorer.testnet.incentiv.net/"},nativeCurrency:{symbol:"TCENT",name:"TCENT",decimals:18}},{chainId:H.KATANA,type:de.MAINNET,name:"katana",title:"Katana",rpcUrl:ge("katana"),logoUrl:ye(H.KATANA),blockExplorer:{name:"Katana Explorer",url:"https://katanascan.com/"},nativeCurrency:{symbol:"ETH",name:"ETH",decimals:18}},{chainId:H.SANDBOX_TESTNET,type:de.TESTNET,name:"sandbox-testnet",title:"Sandbox Testnet",rpcUrl:ge("sandbox-testnet"),logoUrl:ye(H.SANDBOX_TESTNET),blockExplorer:{name:"Sandbox Testnet Explorer",url:"https://sandbox-testnet.explorer.caldera.xyz/"},nativeCurrency:{symbol:"SAND",name:"SAND",decimals:18}},{chainId:H.ARC_TESTNET,type:de.TESTNET,name:"arc-testnet",title:"Arc Testnet",rpcUrl:ge("arc-testnet"),logoUrl:ye(H.ARC_TESTNET),blockExplorer:{name:"Arc Testnet Explorer",url:"https://1jr2dw1zdqvyes8u.blockscout.com/"},nativeCurrency:{symbol:"USDC",name:"USDC",decimals:6}}];function ge(s){return `https://nodes.sequence.app/${s}`}function ye(s){return `https://assets.sequence.info/images/networks/medium/${s}.webp`}function HR(s){return Vv.find(e=>e.name===s)}function _R(s){return Vv.find(e=>e.chainId===Number(s))}var W5="$";function J5(s,e){var t="",n=e&&e.include,r=e&&e.exclude;r&&typeof r=="string"&&(r=[r]),n&&n.sort();var i=new WeakMap,a=e&&e.allowCircular,o=e&&e.filterUndefined,c=e&&e.undefinedInArrayToNull;return u(s,W5),t;function u(l,h){if(l===null||typeof l!="object"||l.toJSON!=null)t+=JSON.stringify(l);else if(Array.isArray(l)){var m=i.get(l);if(m!==void 0&&h.startsWith(m)){if(!a)throw new Error("Circular reference detected");t+='"[Circular:'+m+']"';return}i.set(l,h),t+="[";var y=!1;l.forEach(function(C,N){y&&(t+=","),y=!0,c&&C===void 0&&(C=null),u(C,h+"["+N+"]");}),t+="]";}else {var m=i.get(l);if(m!==void 0&&h.startsWith(m)){if(!a)throw new Error("Circular reference detected");t+='"[Circular:'+m+']"';return}i.set(l,h),t+="{";var g=!1,w=function(N){r&&r.includes(N)||(g&&(t+=","),g=!0,t+=JSON.stringify(N),t+=":",u(l[N],h+"."+N));};if(h===W5&&n)n.forEach(function(N){l.hasOwnProperty(N)&&w(N);});else {var S=Object.keys(l);o&&(S=S.filter(function(N){return l[N]!==void 0})),S.sort(),S.forEach(function(N){w(N);});}t+="}";}}}function Cg(s,e){return J5(s,{allowCircular:e,filterUndefined:!0,undefinedInArrayToNull:!0})}var MR="Webrpc",$R="webrpc@v0.23.1;gen-typescript@v0.16.3;identity-instrument@v0.1.0";var ln;(function(s){s.WebCrypto_Secp256r1="WebCrypto_Secp256r1",s.Ethereum_Secp256k1="Ethereum_Secp256k1";})(ln||(ln={}));var _n;(function(s){s.Email="Email",s.OIDC="OIDC";})(_n||(_n={}));var Uc;(function(s){s.OTP="OTP",s.IDToken="IDToken",s.AccessToken="AccessToken",s.AuthCode="AuthCode",s.AuthCodePKCE="AuthCodePKCE";})(Uc||(Uc={}));var Ng=class{hostname;fetch;path="/rpc/IdentityInstrument/";constructor(e,t){this.hostname=e.replace(/\/*$/,""),this.fetch=(n,r)=>t(n,r);}url(e){return this.hostname+this.path+e}commitVerifier=(e,t,n)=>this.fetch(this.url("CommitVerifier"),Dv(e,t,n)).then(r=>Lv(r).then(i=>({verifier:i.verifier,loginHint:i.loginHint,challenge:i.challenge})),r=>{throw jc.new({cause:`fetch(): ${r.message||""}`})});completeAuth=(e,t,n)=>this.fetch(this.url("CompleteAuth"),Dv(e,t,n)).then(r=>Lv(r).then(i=>({signer:i.signer,identity:i.identity})),r=>{throw jc.new({cause:`fetch(): ${r.message||""}`})});sign=(e,t,n)=>this.fetch(this.url("Sign"),Dv(e,t,n)).then(r=>Lv(r).then(i=>({signature:i.signature})),r=>{throw jc.new({cause:`fetch(): ${r.message||""}`})})},Dv=(s={},e={},t=null)=>{let n={...e,"Content-Type":"application/json"};return n[MR]=$R,{method:"POST",headers:n,body:JSON.stringify(s||{}),signal:t}},Lv=s=>s.text().then(e=>{let t;try{t=JSON.parse(e);}catch(n){let r="";throw n instanceof Error&&(r=n.message),kg.new({status:s.status,cause:`JSON.parse(): ${r}: response text: ${e}`})}if(!s.ok){let n=typeof t.code=="number"?t.code:0;throw (qR[n]||Me).new(t)}return t}),Me=class s extends Error{name;code;message;status;cause;msg;constructor(e,t,n,r,i){super(n),this.name=e||"WebrpcError",this.code=typeof t=="number"?t:0,this.message=n||`endpoint error ${this.code}`,this.msg=this.message,this.status=typeof r=="number"?r:0,this.cause=i,Object.setPrototypeOf(this,s.prototype);}static new(e){return new this(e.error,e.code,e.message||e.msg,e.status,e.cause)}},jv=class s extends Me{constructor(e="WebrpcEndpoint",t=0,n="endpoint error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},jc=class s extends Me{constructor(e="WebrpcRequestFailed",t=-1,n="request failed",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Uv=class s extends Me{constructor(e="WebrpcBadRoute",t=-2,n="bad route",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Hv=class s extends Me{constructor(e="WebrpcBadMethod",t=-3,n="bad method",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},_v=class s extends Me{constructor(e="WebrpcBadRequest",t=-4,n="bad request",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},kg=class s extends Me{constructor(e="WebrpcBadResponse",t=-5,n="bad response",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Mv=class s extends Me{constructor(e="WebrpcServerPanic",t=-6,n="server panic",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},$v=class s extends Me{constructor(e="WebrpcInternalError",t=-7,n="internal error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},qv=class s extends Me{constructor(e="WebrpcClientDisconnected",t=-8,n="client disconnected",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Fv=class s extends Me{constructor(e="WebrpcStreamLost",t=-9,n="stream lost",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Kv=class s extends Me{constructor(e="WebrpcStreamFinished",t=-10,n="stream finished",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Gv=class s extends Me{constructor(e="InternalError",t=7100,n="Internal error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Wv=class s extends Me{constructor(e="EncryptionError",t=7101,n="Encryption error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Jv=class s extends Me{constructor(e="DatabaseError",t=7102,n="Database error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},zv=class s extends Me{constructor(e="DataIntegrityError",t=7103,n="Data integrity error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Yv=class s extends Me{constructor(e="IdentityProviderError",t=7104,n="Identity provider error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Zv=class s extends Me{constructor(e="InvalidRequest",t=7200,n="The request was invalid",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Qv=class s extends Me{constructor(e="InvalidSignature",t=7201,n="The signature was invalid",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Xv=class s extends Me{constructor(e="KeyNotFound",t=7202,n="The authentication key was not found",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},ex=class s extends Me{constructor(e="KeyExpired",t=7203,n="The authentication key expired",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},tx=class s extends Me{constructor(e="SignerNotFound",t=7204,n="The signer was not found",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},sx=class s extends Me{constructor(e="ProofVerificationFailed",t=7002,n="The authentication proof could not be verified",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},nx=class s extends Me{constructor(e="AnswerIncorrect",t=7003,n="The provided answer is incorrect",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},rx=class s extends Me{constructor(e="ChallengeExpired",t=7004,n="The challenge has expired",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},ix=class s extends Me{constructor(e="TooManyAttempts",t=7005,n="Too many attempts",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},ax=class s extends Me{constructor(e="OAuthError",t=7006,n="Failed to exchange OAuth credentials",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},ox=class s extends Me{constructor(e="AccessError",t=7007,n="Access error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},z5;(function(s){s.WebrpcEndpoint="WebrpcEndpoint",s.WebrpcRequestFailed="WebrpcRequestFailed",s.WebrpcBadRoute="WebrpcBadRoute",s.WebrpcBadMethod="WebrpcBadMethod",s.WebrpcBadRequest="WebrpcBadRequest",s.WebrpcBadResponse="WebrpcBadResponse",s.WebrpcServerPanic="WebrpcServerPanic",s.WebrpcInternalError="WebrpcInternalError",s.WebrpcClientDisconnected="WebrpcClientDisconnected",s.WebrpcStreamLost="WebrpcStreamLost",s.WebrpcStreamFinished="WebrpcStreamFinished",s.InternalError="InternalError",s.EncryptionError="EncryptionError",s.DatabaseError="DatabaseError",s.DataIntegrityError="DataIntegrityError",s.IdentityProviderError="IdentityProviderError",s.InvalidRequest="InvalidRequest",s.InvalidSignature="InvalidSignature",s.KeyNotFound="KeyNotFound",s.KeyExpired="KeyExpired",s.SignerNotFound="SignerNotFound",s.ProofVerificationFailed="ProofVerificationFailed",s.AnswerIncorrect="AnswerIncorrect",s.ChallengeExpired="ChallengeExpired",s.TooManyAttempts="TooManyAttempts",s.OAuthError="OAuthError",s.AccessError="AccessError";})(z5||(z5={}));var Y5;(function(s){s[s.WebrpcEndpoint=0]="WebrpcEndpoint",s[s.WebrpcRequestFailed=-1]="WebrpcRequestFailed",s[s.WebrpcBadRoute=-2]="WebrpcBadRoute",s[s.WebrpcBadMethod=-3]="WebrpcBadMethod",s[s.WebrpcBadRequest=-4]="WebrpcBadRequest",s[s.WebrpcBadResponse=-5]="WebrpcBadResponse",s[s.WebrpcServerPanic=-6]="WebrpcServerPanic",s[s.WebrpcInternalError=-7]="WebrpcInternalError",s[s.WebrpcClientDisconnected=-8]="WebrpcClientDisconnected",s[s.WebrpcStreamLost=-9]="WebrpcStreamLost",s[s.WebrpcStreamFinished=-10]="WebrpcStreamFinished",s[s.InternalError=7100]="InternalError",s[s.EncryptionError=7101]="EncryptionError",s[s.DatabaseError=7102]="DatabaseError",s[s.DataIntegrityError=7103]="DataIntegrityError",s[s.IdentityProviderError=7104]="IdentityProviderError",s[s.InvalidRequest=7200]="InvalidRequest",s[s.InvalidSignature=7201]="InvalidSignature",s[s.KeyNotFound=7202]="KeyNotFound",s[s.KeyExpired=7203]="KeyExpired",s[s.SignerNotFound=7204]="SignerNotFound",s[s.ProofVerificationFailed=7002]="ProofVerificationFailed",s[s.AnswerIncorrect=7003]="AnswerIncorrect",s[s.ChallengeExpired=7004]="ChallengeExpired",s[s.TooManyAttempts=7005]="TooManyAttempts",s[s.OAuthError=7006]="OAuthError",s[s.AccessError=7007]="AccessError";})(Y5||(Y5={}));var qR={0:jv,[-1]:jc,[-2]:Uv,[-3]:Hv,[-4]:_v,[-5]:kg,[-6]:Mv,[-7]:$v,[-8]:qv,[-9]:Fv,[-10]:Kv,7100:Gv,7101:Wv,7102:Jv,7103:zv,7104:Yv,7200:Zv,7201:Qv,7202:Xv,7203:ex,7204:tx,7002:sx,7003:nx,7004:rx,7005:ix,7006:ax,7007:ox};var va=class extends Error{};va.prototype.name="InvalidTokenError";function FR(s){return decodeURIComponent(atob(s).replace(/(.)/g,(e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n}))}function KR(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return FR(e)}catch{return atob(e)}}function Q5(s,e){if(typeof s!="string")throw new va("Invalid token specified: must be a string");e||(e={});let t=e.header===!0?0:1,n=s.split(".")[t];if(typeof n!="string")throw new va(`Invalid token specified: missing part #${t+1}`);let r;try{r=KR(n);}catch(i){throw new va(`Invalid token specified: invalid base64 for part #${t+1} (${i.message})`)}try{return JSON.parse(r)}catch(i){throw new va(`Invalid token specified: invalid json for part #${t+1} (${i.message})`)}}var cx=class{},Pg=class extends cx{issuer;audience;idToken;handle="";exp="";constructor(e,t,n){super(),this.issuer=e,this.audience=t,this.idToken=n;let r=Q5(this.idToken),i=oe.keccak256(new TextEncoder().encode(this.idToken));this.handle=E.fromBytes(i),this.exp=r.exp?.toString()??"";}getCommitParams(){return {authMode:Uc.IDToken,identityType:_n.OIDC,handle:this.handle,metadata:{iss:this.issuer,aud:this.audience,exp:this.exp}}}getCompleteParams(){return {authMode:Uc.IDToken,identityType:_n.OIDC,verifier:this.handle,answer:this.idToken}}};var Wh=class{scope;rpc;constructor(e,t,n=window.fetch){this.rpc=new Ng(e.endsWith("/")?e.slice(0,-1):e,n),this.scope=t;}async commitVerifier(e,t){let n={...t.getCommitParams(),scope:this.scope},r=await e.sign(f.fromString(Cg(n)));return this.rpc.commitVerifier({params:n,authKey:{address:e.address,keyType:e.keyType},signature:r})}async completeAuth(e,t){let n={...t.getCompleteParams(),signerType:ln.Ethereum_Secp256k1,scope:this.scope},r=await e.sign(f.fromString(Cg(n)));return this.rpc.completeAuth({params:n,authKey:{address:e.address,keyType:e.keyType},signature:r})}async sign(e,t){let n={scope:this.scope,signer:{address:e.signer,keyType:ln.Ethereum_Secp256k1},digest:E.fromBytes(t),nonce:E.fromNumber(Date.now())},r=await this.rpc.sign({params:n,authKey:{address:e.address,keyType:e.keyType},signature:await e.sign(f.fromString(Cg(n)))});return E.assert(r.signature),r.signature}};function ux(s){return {address:s.address,keyType:ln.WebCrypto_Secp256r1,signer:s.identitySigner,async sign(e){let t=await window.crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},s.privateKey,new Uint8Array(e));return E.fromBytes(new Uint8Array(t))}}}var Tg=class{identityInstrument;authKey;constructor(e,t){this.identityInstrument=e,this.authKey=t;}get address(){if(!B.validate(this.authKey.identitySigner))throw new Error("No signer address found");return B.checksum(this.authKey.identitySigner)}async sign(e,t,n){let r=ce.hash(e,t,n);return this.signDigest(r)}async signDigest(e){let t=await this.identityInstrument.sign(ux(this.authKey),e);return {type:"hash",...At.fromHex(t)}}async witness(e,t,n){let r=ce.fromMessage(E.fromString(JSON.stringify({action:"consent-to-be-part-of-wallet",wallet:t,signer:this.address,timestamp:Date.now(),...n}))),i=await this.sign(t,0,r);await e.saveWitnesses(t,0,r,{type:"unrecovered-signer",weight:1n,signature:i});}};function X5(s){return typeof s=="object"&&"signature"in s&&"imageHash"in s}var Hc={};be(Hc,{Cached:()=>Px,Local:()=>Cx,Remote:()=>kx,Sequence:()=>Xh,getWalletsFor:()=>eV,multiplex:()=>fV,normalizeAddressKeys:()=>hn});var Cx={};be(Cx,{IndexedDbStore:()=>Ax,MemoryStore:()=>zh,Provider:()=>Ix});var zh=class{configs=new Map;counterfactualWallets=new Map;payloads=new Map;signerSubdigests=new Map;signatures=new Map;sapientSignerSubdigests=new Map;sapientSignatures=new Map;trees=new Map;deepCopy(e){if(typeof structuredClone=="function")return structuredClone(e);if(e===null||typeof e!="object")return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))return e.map(n=>this.deepCopy(n));if(e instanceof Map)return new Map(Array.from(e,([n,r])=>[this.deepCopy(n),this.deepCopy(r)]));if(e instanceof Set)return new Set(Array.from(e,n=>this.deepCopy(n)));let t={};for(let[n,r]of Object.entries(e))t[n]=this.deepCopy(r);return t}getSignatureKey(e,t){return `${e.toLowerCase()}-${t.toLowerCase()}`}getSapientSignatureKey(e,t,n){return `${e.toLowerCase()}-${n.toLowerCase()}-${t.toLowerCase()}`}async loadConfig(e){let t=this.configs.get(e.toLowerCase());return t?this.deepCopy(t):void 0}async saveConfig(e,t){this.configs.set(e.toLowerCase(),this.deepCopy(t));}async loadCounterfactualWallet(e){let t=this.counterfactualWallets.get(e.toLowerCase());return t?this.deepCopy(t):void 0}async saveCounterfactualWallet(e,t,n){this.counterfactualWallets.set(e.toLowerCase(),this.deepCopy({imageHash:t,context:n}));}async loadPayloadOfSubdigest(e){let t=this.payloads.get(e.toLowerCase());return t?this.deepCopy(t):void 0}async savePayloadOfSubdigest(e,t){this.payloads.set(e.toLowerCase(),this.deepCopy(t));}async loadSubdigestsOfSigner(e){let t=this.signerSubdigests.get(e.toLowerCase());return t?Array.from(t).map(n=>n):[]}async loadSignatureOfSubdigest(e,t){let n=this.getSignatureKey(e,t),r=this.signatures.get(n);return r?this.deepCopy(r):void 0}async saveSignatureOfSubdigest(e,t,n){let r=this.getSignatureKey(e,t);this.signatures.set(r,this.deepCopy(n));let i=e.toLowerCase(),a=t.toLowerCase();this.signerSubdigests.has(i)||this.signerSubdigests.set(i,new Set),this.signerSubdigests.get(i).add(a);}async loadSubdigestsOfSapientSigner(e,t){let n=`${e.toLowerCase()}-${t.toLowerCase()}`,r=this.sapientSignerSubdigests.get(n);return r?Array.from(r).map(i=>i):[]}async loadSapientSignatureOfSubdigest(e,t,n){let r=this.getSapientSignatureKey(e,t,n),i=this.sapientSignatures.get(r);return i?this.deepCopy(i):void 0}async saveSapientSignatureOfSubdigest(e,t,n,r){let i=this.getSapientSignatureKey(e,t,n);this.sapientSignatures.set(i,this.deepCopy(r));let a=`${e.toLowerCase()}-${n.toLowerCase()}`,o=t.toLowerCase();this.sapientSignerSubdigests.has(a)||this.sapientSignerSubdigests.set(a,new Set),this.sapientSignerSubdigests.get(a).add(o);}async loadTree(e){let t=this.trees.get(e.toLowerCase());return t?this.deepCopy(t):void 0}async saveTree(e,t){this.trees.set(e.toLowerCase(),this.deepCopy(t));}};var Ks={};be(Ks,{Guard:()=>xx,Passkey:()=>px,Pk:()=>dx,Session:()=>bx,SessionManager:()=>Sx,isSapientSigner:()=>Ex,isSigner:()=>XR});var dx={};be(dx,{Encrypted:()=>hx,MemoryPkStore:()=>Rr,Pk:()=>fx});var hx={};be(hx,{EncryptedPkStore:()=>Bg,EncryptedPksDb:()=>lx});var lx=class{localStorageKeyPrefix;tableName;dbName="pk-db";dbVersion=1;constructor(e="e_pk_key_",t="e_pk"){this.localStorageKeyPrefix=e,this.tableName=t;}computeDbKey(e){return `pk_${e.toLowerCase()}`}openDB(){return new Promise((e,t)=>{let n=indexedDB.open(this.dbName,this.dbVersion);n.onupgradeneeded=()=>{let r=n.result;r.objectStoreNames.contains(this.tableName)||r.createObjectStore(this.tableName);},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error);})}async putData(e,t){let n=await this.openDB();return new Promise((r,i)=>{let c=n.transaction(this.tableName,"readwrite").objectStore(this.tableName).put(t,e);c.onsuccess=()=>r(),c.onerror=()=>i(c.error);})}async getData(e){let t=await this.openDB();return new Promise((n,r)=>{let o=t.transaction(this.tableName,"readonly").objectStore(this.tableName).get(e);o.onsuccess=()=>n(o.result),o.onerror=()=>r(o.error);})}async getAllData(){let e=await this.openDB();return new Promise((t,n)=>{let a=e.transaction(this.tableName,"readonly").objectStore(this.tableName).getAll();a.onsuccess=()=>t(a.result),a.onerror=()=>n(a.error);})}async generateAndStore(){let e=await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),t=E.random(32),n=Ot.getPublicKey({privateKey:t}),r=B.fromPublicKey(n),i=this.localStorageKeyPrefix+r,a=await window.crypto.subtle.exportKey("jwk",e);window.localStorage.setItem(i,JSON.stringify(a));let c=new TextEncoder().encode(t),u=window.crypto.getRandomValues(new Uint8Array(12)),l=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:u},e,c),h={iv:u,data:l,keyPointer:i,address:r,publicKey:n},m=this.computeDbKey(r);return await this.putData(m,h),h}async getEncryptedEntry(e){let t=this.computeDbKey(e);return this.getData(t)}async getEncryptedPkStore(e){let t=await this.getEncryptedEntry(e);if(t)return new Bg(t)}async listAddresses(){return (await this.getAllData()).map(t=>t.address)}async remove(e){let t=this.computeDbKey(e);await this.putData(t,void 0);let n=this.localStorageKeyPrefix+e;window.localStorage.removeItem(n);}},Bg=class{encrypted;constructor(e){this.encrypted=e;}address(){return this.encrypted.address}publicKey(){return this.encrypted.publicKey}async signDigest(e){let t=window.localStorage.getItem(this.encrypted.keyPointer);if(!t)throw new Error("Encryption key not found in localStorage");let n=JSON.parse(t),r=await window.crypto.subtle.importKey("jwk",n,{name:"AES-GCM"},!1,["decrypt"]),i=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:this.encrypted.iv},r,this.encrypted.data),o=new TextDecoder().decode(i);return Ot.sign({payload:e,privateKey:o})}};var Rr=class{privateKey;constructor(e){this.privateKey=e;}address(){return B.fromPublicKey(this.publicKey())}publicKey(){return Ot.getPublicKey({privateKey:this.privateKey})}signDigest(e){return Promise.resolve(Ot.sign({payload:e,privateKey:this.privateKey}))}},fx=class{privateKey;address;pubKey;constructor(e){this.privateKey=typeof e=="string"?new Rr(e):e,this.pubKey=this.privateKey.publicKey(),this.address=this.privateKey.address();}async sign(e,t,n){let r=ce.hash(e,t,n);return this.signDigest(r)}async signDigest(e){return {...await this.privateKey.signDigest(e),type:"hash"}}async witness(e,t,n){let r=ce.fromMessage(E.fromString(JSON.stringify({action:"consent-to-be-part-of-wallet",wallet:t,signer:this.address,timestamp:Date.now(),...n}))),i=await this.sign(t,0,r);await e.saveWitnesses(t,0,r,{type:"unrecovered-signer",weight:1n,signature:i});}};var px={};be(px,{Passkey:()=>mx,isWitnessMessage:()=>e8});function e8(s){return typeof s=="object"&&s!==null&&"action"in s&&s.action==="consent-to-be-part-of-wallet"}var mx=class s{credentialId;publicKey;address;imageHash;embedMetadata;metadata;constructor(e){this.address=e.extensions.passkeys,this.publicKey=e.publicKey,this.credentialId=e.credentialId,this.embedMetadata=e.embedMetadata??!1,this.imageHash=Ne.Passkeys.rootFor(e.publicKey),this.metadata=e.metadata;}static async loadFromWitness(e,t,n,r){let i=await e.getWitnessForSapient(n,t.passkeys,r);if(!i)throw new Error("Witness for wallet not found");let a=i.payload;if(!ce.isMessage(a))throw new Error("Witness payload is not a message");let o=JSON.parse(E.toString(a.message));if(!e8(o))throw new Error("Witness payload is not a witness message");let c=o.publicKey.metadata||o.metadata;if(typeof c=="string"||!c)throw new Error("Metadata does not contain credential id");let u=Ne.Passkeys.decode(f.fromHex(i.signature.data));return new s({credentialId:c.credentialId,extensions:t,publicKey:o.publicKey,embedMetadata:u.embedMetadata,metadata:c})}static async create(e,t){let n=t?.credentialName??`Sequence (${Date.now()})`,r=await Tr.createCredential({user:{name:n}}),i=E.fromNumber(r.publicKey.x),a=E.fromNumber(r.publicKey.y),o={credentialId:r.id},c=new s({credentialId:r.id,extensions:e,publicKey:{requireUserVerification:t?.requireUserVerification??!0,x:i,y:a,metadata:t?.embedMetadata?o:void 0},embedMetadata:t?.embedMetadata,metadata:o});return t?.stateProvider&&await t.stateProvider.saveTree(Ne.Passkeys.toTree(c.publicKey)),c}static async find(e,t){let n=await Tr.sign({challenge:E.random(32)});if(!n.raw)throw new Error("No credential returned");let r=f.fromHex(n.metadata.authenticatorData),i=oe.sha256(f.fromString(n.metadata.clientDataJSON),{as:"Bytes"}),a=f.concat(r,i),o=oe.sha256(a,{as:"Bytes"}),c=Nc.recoverPublicKey({payload:o,signature:{r:BigInt(n.signature.r),s:BigInt(n.signature.s),yParity:0}}),u=Nc.recoverPublicKey({payload:o,signature:{r:BigInt(n.signature.r),s:BigInt(n.signature.s),yParity:1}}),l={x:E.fromNumber(c.x),y:E.fromNumber(c.y)},h={x:E.fromNumber(u.x),y:E.fromNumber(u.y)},m={credentialId:n.raw.id},y=[Ne.Passkeys.rootFor({...l,requireUserVerification:!0}),Ne.Passkeys.rootFor({...l,requireUserVerification:!1}),Ne.Passkeys.rootFor({...l,requireUserVerification:!0,metadata:m}),Ne.Passkeys.rootFor({...l,requireUserVerification:!1,metadata:m}),Ne.Passkeys.rootFor({...h,requireUserVerification:!0}),Ne.Passkeys.rootFor({...h,requireUserVerification:!1}),Ne.Passkeys.rootFor({...h,requireUserVerification:!0,metadata:m}),Ne.Passkeys.rootFor({...h,requireUserVerification:!1,metadata:m})],w=(await Promise.all(y.map(async S=>{let C=await e.getWalletsForSapient(t.passkeys,S);return Object.keys(C).map(N=>({wallet:B.from(N),imageHash:S}))}))).flat().filter((S,C,N)=>N.findIndex(x=>B.isEqual(x.wallet,S.wallet)&&x.imageHash===S.imageHash)===C);if(w.length!==0)return w.length>1&&console.warn("Multiple signers found for passkey",w),s.loadFromWitness(e,t,w[0].wallet,w[0].imageHash)}async signSapient(e,t,n,r){if(this.imageHash!==r)throw new Error("Unexpected image hash");let i=E.fromBytes(ce.hash(e,t,n)),a=await Tr.sign({challenge:i,credentialId:this.credentialId,userVerification:this.publicKey.requireUserVerification?"required":"discouraged"}),o=f.fromHex(a.metadata.authenticatorData),c=f.fromNumber(a.signature.r),u=f.fromNumber(a.signature.s),l=Ne.Passkeys.encode({publicKey:this.publicKey,r:c,s:u,authenticatorData:o,clientDataJSON:a.metadata.clientDataJSON,embedMetadata:this.embedMetadata});return {address:this.address,data:f.toHex(l),type:"sapient_compact"}}async witness(e,t,n){let r=ce.fromMessage(E.fromString(JSON.stringify({action:"consent-to-be-part-of-wallet",wallet:t,publicKey:this.publicKey,metadata:this.metadata,timestamp:Date.now(),...n}))),i=await this.signSapient(t,0,r,this.imageHash);await e.saveWitnesses(t,0,r,{type:"unrecovered-signer",weight:1n,signature:i});}};var bx={};be(bx,{Explicit:()=>gx,Implicit:()=>yx,isExplicitSessionSigner:()=>Og,isImplicitSessionSigner:()=>wx});var t8="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",gx=class{_privateKey;address;sessionPermissions;constructor(e,t){this._privateKey=typeof e=="string"?new Rr(e):e,this.address=this._privateKey.address(),this.sessionPermissions={...t,signer:this.address};}isValid(e,t){if(this.sessionPermissions.deadline<=BigInt(Math.floor(Date.now()/1e3)))return {isValid:!1,invalidReason:"Expired"};if(this.sessionPermissions.chainId!==0&&this.sessionPermissions.chainId!==t)return {isValid:!1,invalidReason:"Chain ID mismatch"};let n=Ns.getSessionPermissions(e,this.address);if(!n)return {isValid:!1,invalidReason:"Permission not found"};if(n.deadline!==this.sessionPermissions.deadline||n.chainId!==this.sessionPermissions.chainId||n.valueLimit!==this.sessionPermissions.valueLimit||n.permissions.length!==this.sessionPermissions.permissions.length)return {isValid:!1,invalidReason:"Permission mismatch"};for(let[r,i]of n.permissions.entries()){let a=this.sessionPermissions.permissions[r];if(!B.isEqual(i.target,a.target)||i.rules.length!==a.rules.length)return {isValid:!1,invalidReason:"Permission rule mismatch"};for(let[o,c]of i.rules.entries()){let u=a.rules[o];if(c.cumulative!==u.cumulative||c.operation!==u.operation||!f.isEqual(c.value,u.value)||c.offset!==u.offset||!f.isEqual(c.mask,u.mask))return {isValid:!1,invalidReason:"Permission rule mismatch"}}}return {isValid:!0}}async findSupportedPermission(e,t,n,r,i){if(!(this.sessionPermissions.chainId!==0&&this.sessionPermissions.chainId!==t)){if(n.value!==0n){if(!i)throw new Error("Value transaction validation requires a provider");let a=oe.keccak256(ot.encode([{type:"address",name:"signer"},{type:"address",name:"valueTrackingAddress"}],[this.address,t8])),{usageAmount:o}=await this.readCurrentUsageLimit(e,r,a,i),c=f.fromNumber(o+n.value,{size:32});if(f.toBigInt(c)>this.sessionPermissions.valueLimit)return}for(let a of this.sessionPermissions.permissions)if(await this.validatePermission(a,n,e,r,i))return a}}getPermissionUsageHash(e,t){let n={target:e.target,rules:e.rules.map(r=>({cumulative:r.cumulative,operation:r.operation,value:f.toHex(r.value),offset:r.offset,mask:f.toHex(r.mask)}))};return oe.keccak256(ot.encode([{type:"address",name:"signer"},Hn.permissionStructAbi,{type:"uint256",name:"ruleIndex"}],[this.address,n,BigInt(t)]))}getValueUsageHash(){return oe.keccak256(ot.encode([{type:"address",name:"signer"},{type:"address",name:"valueTrackingAddress"}],[this.address,t8]))}async validatePermission(e,t,n,r,i){if(!B.isEqual(e.target,t.to))return !1;for(let[a,o]of e.rules.entries()){let u=f.padRight(f.fromHex(t.data).slice(Number(o.offset),Number(o.offset)+32),32).map((l,h)=>l&o.mask[h]);if(o.cumulative)if(i){let{usageAmount:l}=await this.readCurrentUsageLimit(n,r,this.getPermissionUsageHash(e,a),i);u=f.fromNumber(l+f.toBigInt(u),{size:32});}else throw new Error("Cumulative rules require a provider");if(o.operation===Hn.ParameterOperation.EQUAL&&!f.isEqual(u,o.value)||o.operation===Hn.ParameterOperation.LESS_THAN_OR_EQUAL&&f.toBigInt(u)>f.toBigInt(o.value)||o.operation===Hn.ParameterOperation.NOT_EQUAL&&f.isEqual(u,o.value)||o.operation===Hn.ParameterOperation.GREATER_THAN_OR_EQUAL&&f.toBigInt(u)<f.toBigInt(o.value))return !1}return !0}async supportedCall(e,t,n,r,i){return B.isEqual(n.to,r)&&E.size(n.data)>4&&E.isEqual(E.slice(n.data,0,4),te.getSelector(_e.INCREMENT_USAGE_LIMIT))?!0:!!await this.findSupportedPermission(e,t,n,r,i)}async signCall(e,t,n,r,i,a){let o=n.calls[r],c;if(B.isEqual(o.to,i)&&E.size(o.data)>4&&E.isEqual(E.slice(o.data,0,4),te.getSelector(_e.INCREMENT_USAGE_LIMIT)))c=0;else {let h=await this.findSupportedPermission(e,t,o,i,a);if(!h)throw new Error("Invalid permission");if(c=this.sessionPermissions.permissions.indexOf(h),c===-1)throw new Error("Invalid permission")}let u=Or.hashPayloadWithCallIdx(e,n,r,t,i),l=await this._privateKey.signDigest(f.fromHex(u));return {permissionIndex:BigInt(c),sessionSignature:l}}async readCurrentUsageLimit(e,t,n,r){let i=te.encodeData(_e.GET_LIMIT_USAGE,[e,n]),a=await r.request({method:"eth_call",params:[{to:t,data:i},"latest"]}),o=te.decodeResult(_e.GET_LIMIT_USAGE,a);return {usageHash:n,usageAmount:o}}async prepareIncrements(e,t,n,r,i){let a=[],o=this.getValueUsageHash(),u=(await this.readCurrentUsageLimit(e,r,o,i)).usageAmount;for(let h of n){let m=await this.findSupportedPermission(e,t,h,r,i);if(m){for(let[y,g]of m.rules.entries()){if(!g.cumulative)continue;let S=f.padRight(f.fromHex(h.data).slice(Number(g.offset),Number(g.offset)+32),32).map((x,v)=>x&g.mask[v]);if(f.toBigInt(S)===0n)continue;let C=this.getPermissionUsageHash(m,y),N=a.find(x=>E.isEqual(x.usageHash,C));N?N.increment+=f.toBigInt(S):a.push({usageHash:C,increment:f.toBigInt(S)});}u+=h.value;}}if(a.length===0&&u===0n)return [];let l=await Promise.all(a.map(async({usageHash:h,increment:m})=>{if(m===0n)return null;let y=await this.readCurrentUsageLimit(e,r,h,i);if(E.isEqual(h,o)&&y.usageAmount+m>this.sessionPermissions.valueLimit)throw new Error("Value transaction validation failed");return {usageHash:h,usageAmount:y.usageAmount+m}})).then(h=>h.filter(m=>m!==null));return u>0n&&l.push({usageHash:o,usageAmount:u}),l}};var yx=class{_attestation;_sessionManager;_privateKey;_identitySignature;address;constructor(e,t,n,r){if(this._attestation=t,this._sessionManager=r,this._privateKey=typeof e=="string"?new Rr(e):e,this.address=this._privateKey.address(),this._attestation.approvedSigner!==this.address)throw new Error("Invalid attestation");if(this._attestation.authData.issuedAt>BigInt(Math.floor(Date.now()/1e3)))throw new Error("Attestation issued in the future");this._identitySignature=typeof n=="string"?At.fromHex(n):n;}get identitySigner(){let e=It.hash(this._attestation),t=Ot.recoverPublicKey({payload:e,signature:this._identitySignature});return B.fromPublicKey(t)}isValid(e,t){let n=Ns.getIdentitySigners(e),r=this.identitySigner;return n.some(a=>B.isEqual(a,r))?Ns.getImplicitBlacklist(e)?.some(a=>B.isEqual(a,this.address))?{isValid:!1,invalidReason:"Blacklisted"}:{isValid:!0}:{isValid:!1,invalidReason:"Identity signer not found"}}async supportedCall(e,t,n,r,i){if(!i)throw new Error("Provider is required");try{let a=te.encodeData(s8,[e,{approvedSigner:this._attestation.approvedSigner,identityType:f.toHex(this._attestation.identityType),issuerHash:f.toHex(this._attestation.issuerHash),audienceHash:f.toHex(this._attestation.audienceHash),applicationData:f.toHex(this._attestation.applicationData),authData:this._attestation.authData},{to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,delegateCall:n.delegateCall,onlyFallback:n.onlyFallback,behaviorOnError:BigInt(ce.encodeBehaviorOnError(n.behaviorOnError))}]),o=await i.request({method:"eth_call",params:[{from:this._sessionManager,to:n.to,data:a},"latest"]}),c=E.from(te.decodeResult(s8,o)),u=f.toHex(It.generateImplicitRequestMagic(this._attestation,e));return c===u}catch{return !1}}async signCall(e,t,n,r,i,a){let o=n.calls[r];if(!await this.supportedCall(e,t,o,i,a))throw new Error("Unsupported call");let u=Or.hashPayloadWithCallIdx(e,n,r,t,i),l=await this._privateKey.signDigest(f.fromHex(u));return {attestation:this._attestation,identitySignature:this._identitySignature,sessionSignature:l}}},s8={type:"function",name:"acceptImplicitRequest",inputs:[{name:"wallet",type:"address",internalType:"address"},{name:"attestation",type:"tuple",internalType:"struct Attestation",components:[{name:"approvedSigner",type:"address",internalType:"address"},{name:"identityType",type:"bytes4",internalType:"bytes4"},{name:"issuerHash",type:"bytes32",internalType:"bytes32"},{name:"audienceHash",type:"bytes32",internalType:"bytes32"},{name:"applicationData",type:"bytes",internalType:"bytes"},{internalType:"struct AuthData",name:"authData",type:"tuple",components:[{internalType:"string",name:"redirectUrl",type:"string"},{internalType:"uint64",name:"issuedAt",type:"uint64"}]}]},{name:"call",type:"tuple",internalType:"struct Payload.Call",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"},{name:"gasLimit",type:"uint256",internalType:"uint256"},{name:"delegateCall",type:"bool",internalType:"bool"},{name:"onlyFallback",type:"bool",internalType:"bool"},{name:"behaviorOnError",type:"uint256",internalType:"uint256"}]}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"};function Og(s){return "prepareIncrements"in s}function wx(s){return "identitySigner"in s}var GR=2n**80n-1n,Sx=class s{wallet;stateProvider;address;_implicitSigners;_explicitSigners;_provider;constructor(e,t){this.wallet=e,this.stateProvider=t.stateProvider??e.stateProvider,this.address=t.sessionManagerAddress,this._implicitSigners=t.implicitSigners??[],this._explicitSigners=t.explicitSigners??[],this._provider=t.provider;}get imageHash(){return this.getImageHash()}async getImageHash(){let{configuration:e}=await this.wallet.getStatus(),t=Pe.findSignerLeaf(e,this.address);if(!(!t||!Pe.isSapientSignerLeaf(t)))return t.imageHash}get topology(){return this.getTopology()}async getTopology(){let e=await this.imageHash;if(!e)throw new Error(`Session configuration not found for image hash ${e}`);let t=await this.stateProvider.getTree(e);if(!t)throw new Error(`Session configuration not found for image hash ${e}`);return Ns.configurationTreeToSessionsTopology(t)}withProvider(e){return new s(this.wallet,{sessionManagerAddress:this.address,stateProvider:this.stateProvider,implicitSigners:this._implicitSigners,explicitSigners:this._explicitSigners,provider:e})}withImplicitSigner(e){let t=[...this._implicitSigners,e];return new s(this.wallet,{sessionManagerAddress:this.address,stateProvider:this.stateProvider,implicitSigners:t,explicitSigners:this._explicitSigners,provider:this._provider})}withExplicitSigner(e){let t=[...this._explicitSigners,e];return new s(this.wallet,{sessionManagerAddress:this.address,stateProvider:this.stateProvider,implicitSigners:this._implicitSigners,explicitSigners:t,provider:this._provider})}async listSignerValidity(e){let t=await this.topology,n=new Map;for(let r of this._implicitSigners)n.set(r.address,r.isValid(t,e));for(let r of this._explicitSigners)n.set(r.address,r.isValid(t,e));return Array.from(n.entries()).map(([r,{isValid:i,invalidReason:a}])=>({signer:r,isValid:i,invalidReason:a}))}async findSignersForCalls(e,t,n){let r=await this.topology;if(Ns.getIdentitySigners(r).length===0)throw new Error("Identity signers not found");let a=[...this._implicitSigners,...this._explicitSigners];if(a.length===0)throw new Error("No signers match the topology");let o=[];for(let c of n){let u=!1,l;for(let h of a){try{if(u=await h.supportedCall(e,t,c,this.address,this._provider),u){let m=h.isValid(r,t);m.invalidReason==="Expired"&&(l=h),u=m.isValid;}}catch(m){console.error("findSignersForCalls error",m);continue}if(u){o.push(h);break}}if(!u)throw l?new Error(`Signer supporting call is expired: ${l.address}`):new Error(`No signer supported for call. Call: to=${c.to}, data=${c.data}, value=${c.value}, `)}return o}async prepareIncrement(e,t,n){if(n.length===0)throw new Error("No calls provided");let r=await this.findSignersForCalls(e,t,n),i=new Map;r.forEach((u,l)=>{let h=n[l],m=i.get(u)||[];i.set(u,[...m,h]);});let a=(await Promise.all(Array.from(i.entries()).map(async([u,l])=>Og(u)?u.prepareIncrements(e,t,l,this.address,this._provider):[]))).flat();if(a.length===0)return null;if(a.filter((u,l,h)=>l===h.findIndex(m=>m.usageHash===u.usageHash)).length!==a.length)throw new Error("Repeated usage hashes");let c=te.encodeData(_e.INCREMENT_USAGE_LIMIT,[a]);return {to:this.address,data:c,value:0n,delegateCall:!1,onlyFallback:!1,behaviorOnError:"revert",gasLimit:0n}}async signSapient(e,t,n,r){if(!B.isEqual(e,this.wallet.address))throw new Error("Wallet address mismatch");if(await this.imageHash!==r)throw new Error("Unexpected image hash");if(!ce.isCalls(n)||n.calls.length===0)throw new Error("Only calls are supported");if(n.space>GR)throw new Error(`Space ${n.space} is too large`);let i=await this.findSignersForCalls(e,t,n.calls);if(i.length!==n.calls.length)throw new Error("No signer supported for call");let a=await Promise.all(i.map(async(m,y)=>{try{return m.signCall(e,t,n,y,this.address,this._provider)}catch(g){throw console.error("signSapient error",g),g}})),o=await this.prepareIncrement(e,t,n.calls);if(o){let m;if(B.isEqual(this.address,Ne.Dev1.sessions)||B.isEqual(this.address,Ne.Dev2.sessions)?m=n.calls[n.calls.length-1]:m=n.calls[0],!B.isEqual(o.to,m.to)||!E.isEqual(o.data,m.data))throw new Error("Actual increment call does not match expected increment call")}let c=[],u=[],l;if(await Promise.all(i.map(async m=>{let y=await m.address;if(Og(m))c.find(g=>B.isEqual(g,y))||c.push(y);else if(wx(m)&&!u.find(g=>B.isEqual(g,y))){if(u.push(y),!l)l=m.identitySigner;else if(!B.isEqual(l,m.identitySigner))throw new Error("Multiple implicit signers with different identity signers")}})),!l){let m=Ns.getIdentitySigners(await this.topology);if(m.length===0)throw new Error("No identity signers found");l=m[0];}let h=Or.encodeSessionSignature(a,await this.topology,l,c,u);return {type:"sapient",address:this.address,data:E.from(h)}}async isValidSapientSignature(e,t,n,r){if(!ce.isCalls(n))return !1;if(!this._provider)throw new Error("Provider not set");let i=ce.encodeSapient(t,n),a=te.encodeData(_e.RECOVER_SAPIENT_SIGNATURE,[i,r.data]);try{let o=await this._provider.request({method:"eth_call",params:[{from:e,to:this.address,data:a},"pending"]});return E.from(te.decodeResult(_e.RECOVER_SAPIENT_SIGNATURE,o))===await this.imageHash}catch(o){return console.error("recoverSapientSignature error",o),!1}}};var Vr;(function(s){s.Calls="Calls",s.Message="Message",s.ConfigUpdate="ConfigUpdate",s.SessionImplicitAuthorize="SessionImplicitAuthorize";})(Vr||(Vr={}));var Dr;(function(s){s.Hash="Hash",s.Sapient="Sapient",s.EthSign="EthSign",s.Erc1271="Erc1271";})(Dr||(Dr={}));var n8;(function(s){s.WebrpcEndpoint="WebrpcEndpoint",s.WebrpcRequestFailed="WebrpcRequestFailed",s.WebrpcBadRoute="WebrpcBadRoute",s.WebrpcBadMethod="WebrpcBadMethod",s.WebrpcBadRequest="WebrpcBadRequest",s.WebrpcBadResponse="WebrpcBadResponse",s.WebrpcServerPanic="WebrpcServerPanic",s.WebrpcInternalError="WebrpcInternalError",s.WebrpcClientDisconnected="WebrpcClientDisconnected",s.WebrpcStreamLost="WebrpcStreamLost",s.WebrpcStreamFinished="WebrpcStreamFinished",s.Unauthorized="Unauthorized",s.PermissionDenied="PermissionDenied",s.SessionExpired="SessionExpired",s.MethodNotFound="MethodNotFound",s.RequestConflict="RequestConflict",s.Aborted="Aborted",s.Geoblocked="Geoblocked",s.RateLimited="RateLimited",s.InvalidArgument="InvalidArgument",s.Unavailable="Unavailable",s.QueryFailed="QueryFailed",s.ValidationFailed="ValidationFailed",s.NotFound="NotFound",s.RequiresTOTP="RequiresTOTP",s.RequiresPIN="RequiresPIN";})(n8||(n8={}));var r8;(function(s){s[s.WebrpcEndpoint=0]="WebrpcEndpoint",s[s.WebrpcRequestFailed=-1]="WebrpcRequestFailed",s[s.WebrpcBadRoute=-2]="WebrpcBadRoute",s[s.WebrpcBadMethod=-3]="WebrpcBadMethod",s[s.WebrpcBadRequest=-4]="WebrpcBadRequest",s[s.WebrpcBadResponse=-5]="WebrpcBadResponse",s[s.WebrpcServerPanic=-6]="WebrpcServerPanic",s[s.WebrpcInternalError=-7]="WebrpcInternalError",s[s.WebrpcClientDisconnected=-8]="WebrpcClientDisconnected",s[s.WebrpcStreamLost=-9]="WebrpcStreamLost",s[s.WebrpcStreamFinished=-10]="WebrpcStreamFinished",s[s.Unauthorized=1e3]="Unauthorized",s[s.PermissionDenied=1001]="PermissionDenied",s[s.SessionExpired=1002]="SessionExpired",s[s.MethodNotFound=1003]="MethodNotFound",s[s.RequestConflict=1004]="RequestConflict",s[s.Aborted=1005]="Aborted",s[s.Geoblocked=1006]="Geoblocked",s[s.RateLimited=1007]="RateLimited",s[s.InvalidArgument=2001]="InvalidArgument",s[s.Unavailable=2002]="Unavailable",s[s.QueryFailed=2003]="QueryFailed",s[s.ValidationFailed=2004]="ValidationFailed",s[s.NotFound=3e3]="NotFound",s[s.RequiresTOTP=6600]="RequiresTOTP",s[s.RequiresPIN=6601]="RequiresPIN";})(r8||(r8={}));var xx=class{guard;address;constructor(e){this.guard=e,this.address=this.guard.address;}async signEnvelope(e,t){let n={...e.payload,parentWallets:void 0},r=YR(e.payload),{message:i,digest:a}=ZR(e.wallet,e.chainId,n),o=e.signatures.map(QR),c=await this.guard.signPayload(e.wallet,e.chainId,r,a,i,o,t?{id:t.id,token:t.code,resetAuth:t.resetAuth}:void 0);return {address:this.guard.address,signature:{type:"hash",...c}}}};function YR(s){switch(s.type){case"call":return Vr.Calls;case"message":return Vr.Message;case"config-update":return Vr.ConfigUpdate;case"session-implicit-authorize":return Vr.SessionImplicitAuthorize}throw new Error(`Payload type not supported by Guard: ${s.type}`)}function ZR(s,e,t){if(ce.isSessionImplicitAuthorize(t))return {message:f.fromString(It.toJson(t.attestation)),digest:oe.keccak256(It.encode(t.attestation))};let n=ce.toTyped(s,e,t);return {message:f.fromString(Th.serialize(n)),digest:f.fromHex(Th.getSignPayload(n))}}function QR(s){if(X5(s))return {type:Dr.Sapient,address:s.signature.address,imageHash:s.imageHash,data:s.signature.data};if(s.signature.type=="erc1271")return {type:Dr.Erc1271,address:s.signature.address,data:s.signature.data};let e={eth_sign:Dr.EthSign,hash:Dr.Hash}[s.signature.type];if(!e)throw new Error(`Signature type not supported by Guard: ${s.signature.type}`);return {type:e,address:s.address,data:At.toHex(s.signature)}}function Ex(s){return "signSapient"in s}function XR(s){return "sign"in s}async function eV(s,e){let t=await tV(s,e);return Object.entries(t).map(([n,{chainId:r,payload:i,signature:a}])=>(E.assert(n),{wallet:n,chainId:r,payload:i,signature:a}))}async function tV(s,e){if(Ex(e)){let[t,n]=await Promise.all([e.address,e.imageHash]);return n?s.getWalletsForSapient(t,n):(console.warn("Sapient signer has no imageHash"),{})}else return s.getWallets(await e.address)}function hn(s){return Object.fromEntries(Object.entries(s).map(([e,t])=>[B.checksum(e),t]))}var Rg="configs",Vg="counterfactualWallets",Dg="payloads",Yh="signerSubdigests",Lg="signatures",Zh="sapientSignerSubdigests",jg="sapientSignatures",Ug="trees",Ax=class{_db=null;dbName;constructor(e="sequence-indexeddb"){this.dbName=e;}async openDB(){return this._db?this._db:new Promise((e,t)=>{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let r=n.result;r.objectStoreNames.contains(Rg)||r.createObjectStore(Rg),r.objectStoreNames.contains(Vg)||r.createObjectStore(Vg),r.objectStoreNames.contains(Dg)||r.createObjectStore(Dg),r.objectStoreNames.contains(Yh)||r.createObjectStore(Yh),r.objectStoreNames.contains(Lg)||r.createObjectStore(Lg),r.objectStoreNames.contains(Zh)||r.createObjectStore(Zh),r.objectStoreNames.contains(jg)||r.createObjectStore(jg),r.objectStoreNames.contains(Ug)||r.createObjectStore(Ug);},n.onsuccess=()=>{this._db=n.result,e(this._db);},n.onerror=()=>{t(n.error);};})}async get(e,t){let n=await this.openDB();return new Promise((r,i)=>{let c=n.transaction(e,"readonly").objectStore(e).get(t);c.onsuccess=()=>r(c.result),c.onerror=()=>i(c.error);})}async put(e,t,n){let r=await this.openDB();return new Promise((i,a)=>{let u=r.transaction(e,"readwrite").objectStore(e).put(n,t);u.onsuccess=()=>i(),u.onerror=()=>a(u.error);})}async getSet(e,t){let n=await this.get(e,t)||new Set;return Array.isArray(n)?new Set(n):n}async putSet(e,t,n){await this.put(e,t,Array.from(n));}getSignatureKey(e,t){return `${e.toLowerCase()}-${t.toLowerCase()}`}getSapientSignatureKey(e,t,n){return `${e.toLowerCase()}-${n.toLowerCase()}-${t.toLowerCase()}`}async loadConfig(e){return this.get(Rg,e.toLowerCase())}async saveConfig(e,t){await this.put(Rg,e.toLowerCase(),t);}async loadCounterfactualWallet(e){return this.get(Vg,e.toLowerCase())}async saveCounterfactualWallet(e,t,n){await this.put(Vg,e.toLowerCase(),{imageHash:t,context:n});}async loadPayloadOfSubdigest(e){return this.get(Dg,e.toLowerCase())}async savePayloadOfSubdigest(e,t){await this.put(Dg,e.toLowerCase(),t);}async loadSubdigestsOfSigner(e){let t=await this.getSet(Yh,e.toLowerCase());return Array.from(t)}async loadSignatureOfSubdigest(e,t){let n=this.getSignatureKey(e,t);return this.get(Lg,n.toLowerCase())}async saveSignatureOfSubdigest(e,t,n){let r=this.getSignatureKey(e,t);await this.put(Lg,r.toLowerCase(),n);let i=e.toLowerCase(),a=t.toLowerCase(),o=await this.getSet(Yh,i);o.add(a),await this.putSet(Yh,i,o);}async loadSubdigestsOfSapientSigner(e,t){let n=`${e.toLowerCase()}-${t.toLowerCase()}`,r=await this.getSet(Zh,n);return Array.from(r)}async loadSapientSignatureOfSubdigest(e,t,n){let r=this.getSapientSignatureKey(e,t,n);return this.get(jg,r.toLowerCase())}async saveSapientSignatureOfSubdigest(e,t,n,r){let i=this.getSapientSignatureKey(e,t,n).toLowerCase();await this.put(jg,i,r);let a=`${e.toLowerCase()}-${n.toLowerCase()}`,o=t.toLowerCase(),c=await this.getSet(Zh,a);c.add(o),await this.putSet(Zh,a,c);}async loadTree(e){return this.get(Ug,e.toLowerCase())}async saveTree(e,t){await this.put(Ug,e.toLowerCase(),t);}};var Ix=class{store;extensions;constructor(e=new zh,t=Ne.Rc5){this.store=e,this.extensions=t;}getConfiguration(e){return this.store.loadConfig(e)}async saveWallet(e,t){await this.saveConfig(e);let n=Pe.hashConfiguration(e);await this.saveCounterfactualWallet(Vc.from(n,t),E.fromBytes(n),t);}async saveConfig(e){let t=f.toHex(Pe.hashConfiguration(e)),n=await this.store.loadConfig(t);if(n){let r=Pe.mergeTopology(n.topology,e.topology);return this.store.saveConfig(t,{...n,topology:r})}else return this.store.saveConfig(t,e)}saveCounterfactualWallet(e,t,n){this.store.saveCounterfactualWallet(e,t,n);}getDeploy(e){return this.store.loadCounterfactualWallet(e)}async getWalletsGeneric(e,t){let n=await Promise.all(e.map(i=>this.store.loadPayloadOfSubdigest(i))),r={};for(let i of n){if(!i)continue;let a=B.checksum(i.wallet);if(r[a])continue;let o=E.fromBytes(ce.hash(a,i.chainId,i.content)),c=await t(o);c&&(r[a]={chainId:i.chainId,payload:i.content,signature:c});}return r}async getWallets(e){return hn(await this.getWalletsGeneric(await this.store.loadSubdigestsOfSigner(e),t=>this.store.loadSignatureOfSubdigest(e,t)))}async getWalletsForSapient(e,t){return hn(await this.getWalletsGeneric(await this.store.loadSubdigestsOfSapientSigner(e,t),n=>this.store.loadSapientSignatureOfSubdigest(e,n,t)))}getWitnessFor(e,t){let n=B.checksum(e);return this.getWallets(t).then(r=>r[n])}getWitnessForSapient(e,t,n){let r=B.checksum(e);return this.getWalletsForSapient(t,n).then(i=>i[r])}async saveWitnesses(e,t,n,r){let i=E.fromBytes(ce.hash(e,t,n));await Promise.all([this.saveSignature(i,r),this.store.savePayloadOfSubdigest(i,{content:n,chainId:t,wallet:e})]);}async getConfigurationUpdates(e,t,n){let r=await this.store.loadConfig(t);if(!r)return [];let{signers:i,sapientSigners:a}=Pe.getSigners(r),o=await Promise.all([...i.map(g=>this.store.loadSubdigestsOfSigner(g)),...a.map(g=>this.store.loadSubdigestsOfSapientSigner(g.address,g.imageHash))]),c=[...new Set(o.flat())],u=await Promise.all(c.map(g=>this.store.loadPayloadOfSubdigest(g))),l=await Promise.all(u.filter(g=>g?.content&&ce.isConfigUpdate(g.content)).map(async g=>({payload:g,nextImageHash:g.content.imageHash,config:await this.store.loadConfig(g.content.imageHash)}))),h,m=l.filter(g=>g.config&&g.config.checkpoint>r.checkpoint).sort((g,w)=>g.config.checkpoint>w.config.checkpoint?n?.allUpdates?1:-1:n?.allUpdates?-1:1);for(let g of m){if(h){if(n?.allUpdates){if(g.config.checkpoint<=h.checkpoint)continue}else if(g.config.checkpoint<=h.checkpoint)continue}let w=E.fromBytes(ce.hash(e,g.payload.chainId,g.payload.content)),S=await Promise.all([...i.map(async x=>({signer:x,signature:await this.store.loadSignatureOfSubdigest(x,w)})),...a.map(async x=>({signer:x.address,imageHash:x.imageHash,signature:await this.store.loadSapientSignatureOfSubdigest(x.address,w,x.imageHash)}))]),C=0n,N=Rt.fillLeaves(r.topology,x=>{if(Pe.isSapientSignerLeaf(x)){let I=S.find(({signer:D,imageHash:F})=>F&&B.isEqual(D,x.address)&&F===x.imageHash)?.signature;if(I)return C+=x.weight,I}let v=S.find(({signer:I})=>B.isEqual(I,x.address))?.signature;if(v)return C+=x.weight,v});C<r.threshold||(h={nextImageHash:g.nextImageHash,checkpoint:g.config.checkpoint,signature:{noChainId:!0,configuration:{threshold:r.threshold,checkpoint:r.checkpoint,topology:N}}});}if(!h)return [];let y=await this.getConfigurationUpdates(e,h.nextImageHash,{allUpdates:!0});return [{imageHash:h.nextImageHash,signature:h.signature},...y]}async saveUpdate(e,t,n){let i={type:"config-update",imageHash:f.toHex(Pe.hashConfiguration(t))},a=ce.hash(e,0,i);await this.store.savePayloadOfSubdigest(E.fromBytes(a),{content:i,chainId:0,wallet:e}),await this.saveConfig(t),await this.saveSignature(E.fromBytes(a),n.configuration.topology);}async saveSignature(e,t){if(Rt.isRawNode(t)){await Promise.all([this.saveSignature(e,t[0]),this.saveSignature(e,t[1])]);return}if(Rt.isRawNestedLeaf(t))return this.saveSignature(e,t.tree);if(Rt.isRawSignerLeaf(t)){let n=t.signature.type;if(n==="eth_sign"||n==="hash"){let r=Ot.recoverAddress({payload:n==="eth_sign"?$p.getSignPayload(e):e,signature:t.signature});return this.store.saveSignatureOfSubdigest(r,e,t.signature)}if(Rt.isSignatureOfSapientSignerLeaf(t.signature))switch(t.signature.address.toLowerCase()){case this.extensions.passkeys.toLowerCase():let r=Ne.Passkeys.decode(f.fromHex(t.signature.data));if(!Ne.Passkeys.isValidSignature(e,r))throw new Error("Invalid passkey signature");return this.store.saveSapientSignatureOfSubdigest(t.signature.address,e,Ne.Passkeys.rootFor(r.publicKey),t.signature);default:throw new Error(`Unsupported sapient signer: ${t.signature.address}`)}}}getTree(e){return this.store.loadTree(e)}saveTree(e){return this.store.saveTree(Ss.hash(e),e)}saveConfiguration(e){return this.store.saveConfig(f.toHex(Pe.hashConfiguration(e)),e)}saveDeploy(e,t){return this.store.saveCounterfactualWallet(Vc.from(f.fromHex(e),t),e,t)}async getPayload(e){let t=await this.store.loadPayloadOfSubdigest(e);return t?{chainId:t.chainId,payload:t.content,wallet:t.wallet}:void 0}savePayload(e,t,n){let r=E.fromBytes(ce.hash(e,n,t));return this.store.savePayloadOfSubdigest(r,{content:t,chainId:n,wallet:e})}};var kx={};be(kx,{DevHttpProvider:()=>Nx});var Nx=class{baseUrl;constructor(e){this.baseUrl=e.endsWith("/")?e.slice(0,-1):e;}async request(e,t,n){let r=`${this.baseUrl}${t}`,i={method:e,headers:{}};n&&e==="POST"&&(i.headers={"Content-Type":"application/json"},i.body=ya.toJSON(n));let a;try{a=await fetch(r,i);}catch(o){throw console.error(`Network error during ${e} request to ${r}:`,o),o}if(!a.ok){let o={message:`HTTP error! Status: ${a.status}`};try{let c=await a.text(),u=await ya.fromJSON(c);o={...o,...u};}catch{try{let u=await a.text();o.body=u;}catch{}}throw console.error("HTTP Request Failed:",o),new Error(o.message||`Request failed for ${e} ${t} with status ${a.status}`)}try{if(a.status===204)return;if(a.status===201&&e==="POST"){if((await a.clone().text()).trim()==="")return;let l=await a.text();return await ya.fromJSON(l)}if((await a.clone().text()).trim()==="")return;{let u=await a.text();return await ya.fromJSON(u)}}catch(o){console.error(`Error processing response body for ${e} ${r}:`,o);try{let c=await a.text();throw new Error(`Failed to parse JSON response from server. Status: ${a.status}. Body: "${c}". Original error: ${o instanceof Error?o.message:String(o)}`)}catch{throw new Error(`Failed to parse JSON response from server and could not read response body as text. Status: ${a.status}. Original error: ${o instanceof Error?o.message:String(o)}`)}}}async getConfiguration(e){return await this.request("GET",`/configuration/${e}`)}async getDeploy(e){return this.request("GET",`/deploy/${e}`)}async getWallets(e){return this.request("GET",`/wallets/signer/${e}`)}async getWalletsForSapient(e,t){return this.request("GET",`/wallets/sapient/${e}/${t}`)}async getWitnessFor(e,t){return this.request("GET",`/witness/${e}/signer/${t}`)}async getWitnessForSapient(e,t,n){return this.request("GET",`/witness/sapient/${e}/${t}/${n}`)}async getConfigurationUpdates(e,t,n){let r=n?.allUpdates?"?allUpdates=true":"";return this.request("GET",`/configuration-updates/${e}/from/${t}${r}`)}async getTree(e){return this.request("GET",`/tree/${e}`)}async saveWallet(e,t){await this.request("POST","/wallet",{deployConfiguration:e,context:t});}async saveWitnesses(e,t,n,r){await this.request("POST","/witnesses",{wallet:e,chainId:t,payload:n,signatures:r});}async saveUpdate(e,t,n){await this.request("POST","/update",{wallet:e,configuration:t,signature:n});}async saveTree(e){await this.request("POST","/tree",{tree:e});}saveConfiguration(e){return this.request("POST","/configuration",{config:e})}saveDeploy(e,t){return this.request("POST","/deploy",{imageHash:e,context:t})}async getPayload(e){return this.request("GET",`/payload/${e}`)}async savePayload(e,t,n){return this.request("POST","/payload",{wallet:e,payload:t,chainId:n})}};var Px=class{args;constructor(e){this.args=e;}async getConfiguration(e){let t=await this.args.cache.getConfiguration(e);if(t)return t;let n=await this.args.source.getConfiguration(e);return n&&await this.args.cache.saveConfiguration(n),n}async getDeploy(e){let t=await this.args.cache.getDeploy(e);if(t)return t;let n=await this.args.source.getDeploy(e);return n&&await this.args.cache.saveDeploy(n.imageHash,n.context),n}async getWallets(e){let t=hn(await this.args.cache.getWallets(e)),n=hn(await this.args.source.getWallets(e)),r={...t,...n};for(let[i,a]of Object.entries(r))B.assert(i),n[i]||await this.args.source.saveWitnesses(i,a.chainId,a.payload,{type:"unrecovered-signer",weight:1n,signature:a.signature}),t[i]||await this.args.cache.saveWitnesses(i,a.chainId,a.payload,{type:"unrecovered-signer",weight:1n,signature:a.signature});return r}async getWalletsForSapient(e,t){let n=await this.args.cache.getWalletsForSapient(e,t),r=await this.args.source.getWalletsForSapient(e,t),i={...n,...r};for(let[a,o]of Object.entries(i)){let c=B.from(a);r[c]||await this.args.source.saveWitnesses(c,o.chainId,o.payload,{type:"unrecovered-signer",weight:1n,signature:o.signature}),n[c]||await this.args.cache.saveWitnesses(c,o.chainId,o.payload,{type:"unrecovered-signer",weight:1n,signature:o.signature});}return i}async getWitnessFor(e,t){let n=await this.args.cache.getWitnessFor(e,t);if(n)return n;let r=await this.args.source.getWitnessFor(e,t);return r&&await this.args.cache.saveWitnesses(e,r.chainId,r.payload,{type:"unrecovered-signer",weight:1n,signature:r.signature}),r}async getWitnessForSapient(e,t,n){let r=await this.args.cache.getWitnessForSapient(e,t,n);if(r)return r;let i=await this.args.source.getWitnessForSapient(e,t,n);return i&&await this.args.cache.saveWitnesses(e,i.chainId,i.payload,{type:"unrecovered-signer",weight:1n,signature:i.signature}),i}async getConfigurationUpdates(e,t,n){return this.args.source.getConfigurationUpdates(e,t,n)}async getTree(e){let t=await this.args.cache.getTree(e);if(t)return t;let n=await this.args.source.getTree(e);return n&&await this.args.cache.saveTree(n),n}saveWallet(e,t){return this.args.source.saveWallet(e,t)}saveWitnesses(e,t,n,r){return this.args.source.saveWitnesses(e,t,n,r)}saveUpdate(e,t,n){return this.args.source.saveUpdate(e,t,n)}saveTree(e){return this.args.source.saveTree(e)}saveConfiguration(e){return this.args.source.saveConfiguration(e)}saveDeploy(e,t){return this.args.source.saveDeploy(e,t)}async getPayload(e){let t=await this.args.cache.getPayload(e);if(t)return t;let n=await this.args.source.getPayload(e);return n&&await this.args.cache.savePayload(n.wallet,n.payload,n.chainId),n}savePayload(e,t,n){return this.args.source.savePayload(e,t,n)}};var Xh={};be(Xh,{Provider:()=>Fx});var sV="Webrpc",nV="webrpc@v0.22.1;gen-typescript@v0.16.2;sessions@v0.0.1";var o8;(function(s){s.Transactions="Transactions",s.Message="Message",s.ConfigUpdate="ConfigUpdate",s.Digest="Digest";})(o8||(o8={}));var Ke;(function(s){s.EIP712="EIP712",s.EthSign="EthSign",s.EIP1271="EIP1271",s.Sapient="Sapient",s.SapientCompact="SapientCompact";})(Ke||(Ke={}));var Hg=class{hostname;fetch;path="/rpc/Sessions/";constructor(e,t){this.hostname=e.replace(/\/*$/,""),this.fetch=(n,r)=>t(n,r);}url(e){return this.hostname+this.path+e}ping=(e,t)=>this.fetch(this.url("Ping"),gt({},e,t)).then(n=>yt(n).then(r=>({})),n=>{throw ct.new({cause:`fetch(): ${n.message||""}`})});config=(e,t,n)=>this.fetch(this.url("Config"),gt(e,t,n)).then(r=>yt(r).then(i=>({version:i.version,config:i.config})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});tree=(e,t,n)=>this.fetch(this.url("Tree"),gt(e,t,n)).then(r=>yt(r).then(i=>({version:i.version,tree:i.tree})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});payload=(e,t,n)=>this.fetch(this.url("Payload"),gt(e,t,n)).then(r=>yt(r).then(i=>({version:i.version,payload:i.payload,wallet:i.wallet,chainID:i.chainID})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});wallets=(e,t,n)=>this.fetch(this.url("Wallets"),gt(e,t,n)).then(r=>yt(r).then(i=>({wallets:i.wallets,cursor:i.cursor})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});deployHash=(e,t,n)=>this.fetch(this.url("DeployHash"),gt(e,t,n)).then(r=>yt(r).then(i=>({deployHash:i.deployHash,context:i.context})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});witness=(e,t,n)=>this.fetch(this.url("Witness"),gt(e,t,n)).then(r=>yt(r).then(i=>({witness:i.witness})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});configUpdates=(e,t,n)=>this.fetch(this.url("ConfigUpdates"),gt(e,t,n)).then(r=>yt(r).then(i=>({updates:i.updates})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});migrations=(e,t,n)=>this.fetch(this.url("Migrations"),gt(e,t,n)).then(r=>yt(r).then(i=>({migrations:i.migrations})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveConfig=(e,t,n)=>this.fetch(this.url("SaveConfig"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveTree=(e,t,n)=>this.fetch(this.url("SaveTree"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});savePayload=(e,t,n)=>this.fetch(this.url("SavePayload"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveWallet=(e,t,n)=>this.fetch(this.url("SaveWallet"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveSignature=(e,t,n)=>this.fetch(this.url("SaveSignature"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveSignature2=(e,t,n)=>this.fetch(this.url("SaveSignature2"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveSignerSignatures=(e,t,n)=>this.fetch(this.url("SaveSignerSignatures"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveSignerSignatures2=(e,t,n)=>this.fetch(this.url("SaveSignerSignatures2"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveSignerSignatures3=(e,t,n)=>this.fetch(this.url("SaveSignerSignatures3"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveMigration=(e,t,n)=>this.fetch(this.url("SaveMigration"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})})},gt=(s={},e={},t=null)=>{let n={...e,"Content-Type":"application/json"};return n[sV]=nV,{method:"POST",headers:n,body:JSON.stringify(s||{}),signal:t}},yt=s=>s.text().then(e=>{let t;try{t=JSON.parse(e);}catch(n){let r="";throw n instanceof Error&&(r=n.message),_g.new({status:s.status,cause:`JSON.parse(): ${r}: response text: ${e}`})}if(!s.ok){let n=typeof t.code=="number"?t.code:0;throw (rV[n]||Ft).new(t)}return t}),Ft=class s extends Error{name;code;message;status;cause;msg;constructor(e,t,n,r,i){super(n),this.name=e||"WebrpcError",this.code=typeof t=="number"?t:0,this.message=n||`endpoint error ${this.code}`,this.msg=this.message,this.status=typeof r=="number"?r:0,this.cause=i,Object.setPrototypeOf(this,s.prototype);}static new(e){return new this(e.error,e.code,e.message||e.msg,e.status,e.cause)}},Tx=class s extends Ft{constructor(e="WebrpcEndpoint",t=0,n="endpoint error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},ct=class s extends Ft{constructor(e="WebrpcRequestFailed",t=-1,n="request failed",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Bx=class s extends Ft{constructor(e="WebrpcBadRoute",t=-2,n="bad route",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Ox=class s extends Ft{constructor(e="WebrpcBadMethod",t=-3,n="bad method",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Rx=class s extends Ft{constructor(e="WebrpcBadRequest",t=-4,n="bad request",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},_g=class s extends Ft{constructor(e="WebrpcBadResponse",t=-5,n="bad response",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Vx=class s extends Ft{constructor(e="WebrpcServerPanic",t=-6,n="server panic",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Dx=class s extends Ft{constructor(e="WebrpcInternalError",t=-7,n="internal error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Lx=class s extends Ft{constructor(e="WebrpcClientDisconnected",t=-8,n="client disconnected",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},jx=class s extends Ft{constructor(e="WebrpcStreamLost",t=-9,n="stream lost",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Ux=class s extends Ft{constructor(e="WebrpcStreamFinished",t=-10,n="stream finished",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Hx=class s extends Ft{constructor(e="InvalidArgument",t=1,n="invalid argument",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},_x=class s extends Ft{constructor(e="NotFound",t=2,n="not found",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},c8;(function(s){s.WebrpcEndpoint="WebrpcEndpoint",s.WebrpcRequestFailed="WebrpcRequestFailed",s.WebrpcBadRoute="WebrpcBadRoute",s.WebrpcBadMethod="WebrpcBadMethod",s.WebrpcBadRequest="WebrpcBadRequest",s.WebrpcBadResponse="WebrpcBadResponse",s.WebrpcServerPanic="WebrpcServerPanic",s.WebrpcInternalError="WebrpcInternalError",s.WebrpcClientDisconnected="WebrpcClientDisconnected",s.WebrpcStreamLost="WebrpcStreamLost",s.WebrpcStreamFinished="WebrpcStreamFinished",s.InvalidArgument="InvalidArgument",s.NotFound="NotFound";})(c8||(c8={}));var u8;(function(s){s[s.WebrpcEndpoint=0]="WebrpcEndpoint",s[s.WebrpcRequestFailed=-1]="WebrpcRequestFailed",s[s.WebrpcBadRoute=-2]="WebrpcBadRoute",s[s.WebrpcBadMethod=-3]="WebrpcBadMethod",s[s.WebrpcBadRequest=-4]="WebrpcBadRequest",s[s.WebrpcBadResponse=-5]="WebrpcBadResponse",s[s.WebrpcServerPanic=-6]="WebrpcServerPanic",s[s.WebrpcInternalError=-7]="WebrpcInternalError",s[s.WebrpcClientDisconnected=-8]="WebrpcClientDisconnected",s[s.WebrpcStreamLost=-9]="WebrpcStreamLost",s[s.WebrpcStreamFinished=-10]="WebrpcStreamFinished",s[s.InvalidArgument=1]="InvalidArgument",s[s.NotFound=2]="NotFound";})(u8||(u8={}));var rV={0:Tx,[-1]:ct,[-2]:Bx,[-3]:Ox,[-4]:Rx,[-5]:_g,[-6]:Vx,[-7]:Dx,[-8]:Lx,[-9]:jx,[-10]:Ux,1:Hx,2:_x};var Fx=class{service;constructor(e="https://keymachine.sequence.app"){this.service=new Hg(e,fetch);}async getConfiguration(e){let{version:t,config:n}=await this.service.config({imageHash:e});if(t!==3)throw new Error(`invalid configuration version ${t}, expected version 3`);return oV(n)}async getDeploy(e){let{deployHash:t,context:n}=await this.service.deployHash({wallet:e});return E.assert(t),B.assert(n.factory),B.assert(n.mainModule),B.assert(n.mainModuleUpgradable),E.assert(n.walletCreationCode),{imageHash:t,context:{factory:n.factory,stage1:n.mainModule,stage2:n.mainModuleUpgradable,creationCode:n.walletCreationCode}}}async getWallets(e){let t=await this.service.wallets({signer:e}),n=hn(t.wallets);return Object.fromEntries(Object.entries(n).map(([r,i])=>{switch(B.assert(r),E.assert(i.signature),i.type){case Ke.EIP712:return [r,{chainId:Number(i.chainID),payload:Gs(i.payload),signature:{type:"hash",...At.from(i.signature)}}];case Ke.EthSign:return [r,{chainId:Number(i.chainID),payload:Gs(i.payload),signature:{type:"eth_sign",...At.from(i.signature)}}];case Ke.EIP1271:return [r,{chainId:Number(i.chainID),payload:Gs(i.payload),signature:{type:"erc1271",address:e,data:i.signature}}];case Ke.Sapient:throw new Error(`unexpected sapient signature by ${e}`);case Ke.SapientCompact:throw new Error(`unexpected compact sapient signature by ${e}`)}}))}async getWalletsForSapient(e,t){let n=await this.service.wallets({signer:e,sapientHash:t}),r=hn(n.wallets);return Object.fromEntries(Object.entries(r).map(([i,a])=>{switch(B.assert(i),E.assert(a.signature),a.type){case Ke.EIP712:throw new Error(`unexpected eip-712 signature by ${e}`);case Ke.EthSign:throw new Error(`unexpected eth_sign signature by ${e}`);case Ke.EIP1271:throw new Error(`unexpected erc-1271 signature by ${e}`);case Ke.Sapient:return [i,{chainId:Number(a.chainID),payload:Gs(a.payload),signature:{type:"sapient",address:e,data:a.signature}}];case Ke.SapientCompact:return [i,{chainId:Number(a.chainID),payload:Gs(a.payload),signature:{type:"sapient_compact",address:e,data:a.signature}}]}}))}async getWitnessFor(e,t){try{let{witness:n}=await this.service.witness({signer:t,wallet:e});switch(E.assert(n.signature),n.type){case Ke.EIP712:return {chainId:Number(n.chainID),payload:Gs(n.payload),signature:{type:"hash",...At.from(n.signature)}};case Ke.EthSign:return {chainId:Number(n.chainID),payload:Gs(n.payload),signature:{type:"eth_sign",...At.from(n.signature)}};case Ke.EIP1271:return {chainId:Number(n.chainID),payload:Gs(n.payload),signature:{type:"erc1271",address:t,data:n.signature}};case Ke.Sapient:throw new Error(`unexpected sapient signature by ${t}`);case Ke.SapientCompact:throw new Error(`unexpected compact sapient signature by ${t}`)}}catch{}}async getWitnessForSapient(e,t,n){try{let{witness:r}=await this.service.witness({signer:t,wallet:e,sapientHash:n});switch(E.assert(r.signature),r.type){case Ke.EIP712:throw new Error(`unexpected eip-712 signature by ${t}`);case Ke.EthSign:throw new Error(`unexpected eth_sign signature by ${t}`);case Ke.EIP1271:throw new Error(`unexpected erc-1271 signature by ${t}`);case Ke.Sapient:return {chainId:Number(r.chainID),payload:Gs(r.payload),signature:{type:"sapient",address:t,data:r.signature}};case Ke.SapientCompact:return {chainId:Number(r.chainID),payload:Gs(r.payload),signature:{type:"sapient_compact",address:t,data:r.signature}}}}catch{}}async getConfigurationUpdates(e,t,n){let{updates:r}=await this.service.configUpdates({wallet:e,fromImageHash:t,allUpdates:n?.allUpdates});return Promise.all(r.map(async({toImageHash:i,signature:a})=>{E.assert(i),E.assert(a);let o=Rt.decodeSignature(E.toBytes(a)),{configuration:c}=await Rt.recover(o,e,0,ce.fromConfigUpdate(i),{provider:aV});return {imageHash:i,signature:{...o,configuration:c}}}))}async getTree(e){let{version:t,tree:n}=await this.service.tree({imageHash:e});if(t!==3)throw new Error(`invalid tree version ${t}, expected version 3`);return f8(n)}async getPayload(e){let{version:t,payload:n,wallet:r,chainID:i}=await this.service.payload({digest:e});if(t!==3)throw new Error(`invalid payload version ${t}, expected version 3`);return B.assert(r),{payload:Gs(n),wallet:r,chainId:Number(i)}}async saveWallet(e,t){await this.service.saveWallet({version:3,deployConfig:$x(e),context:{version:3,factory:t.factory,mainModule:t.stage1,mainModuleUpgradable:t.stage2,guestModule:_e.DefaultGuestAddress,walletCreationCode:t.creationCode}});}async saveWitnesses(e,t,n,r){await this.service.saveSignerSignatures3({wallet:e,payload:qx(n),chainID:t.toString(),signatures:Qh(r).map(i=>{switch(i.type){case"hash":return {type:Ke.EIP712,signature:At.toHex(At.from(i))};case"eth_sign":return {type:Ke.EthSign,signature:At.toHex(At.from(i))};case"erc1271":return {type:Ke.EIP1271,signer:i.address,signature:i.data,referenceChainID:t.toString()};case"sapient":return {type:Ke.Sapient,signer:i.address,signature:i.data,referenceChainID:t.toString()};case"sapient_compact":return {type:Ke.SapientCompact,signer:i.address,signature:i.data,referenceChainID:t.toString()}}})});}async saveUpdate(e,t,n){await this.service.saveSignature2({wallet:e,payload:qx(ce.fromConfigUpdate(f.toHex(Pe.hashConfiguration(t)))),chainID:"0",signature:f.toHex(Rt.encodeSignature(n)),toConfig:$x(t)});}async saveTree(e){await this.service.saveTree({version:3,tree:h8(e)});}async saveConfiguration(e){await this.service.saveConfig({version:3,config:$x(e)});}async saveDeploy(e,t){}async savePayload(e,t,n){await this.service.savePayload({version:3,payload:qx(t),wallet:e,chainID:n.toString()});}},iV=[Ne.Dev1.passkeys,Ne.Dev2.passkeys,Ne.Rc3.passkeys,Ne.Rc4.passkeys,Ne.Rc5.passkeys].map(B.checksum),l8="function recoverSapientSignatureCompact(bytes32 _digest, bytes _signature) view returns (bytes32)",Mx=te.from(l8),Kx=class{request=async e=>{switch(e.method){case"eth_call":if(!e.params||!Array.isArray(e.params)||e.params.length===0)throw new Error("eth_call requires transaction parameters");let t=e.params[0];if(!t.data?.startsWith(te.getSelector(Mx)))throw new Error(`unknown selector ${t.data?.slice(0,10)}, expected selector ${te.getSelector(Mx)} for ${l8}`);if(!iV.includes(t.to?B.checksum(t.to):"0x"))throw new Error(`unknown passkey signer ${t.to}`);let[n,r]=te.decodeData(Mx,t.data),i=Ne.Passkeys.decode(E.toBytes(r));if(Ne.Passkeys.isValidSignature(n,i))return Ne.Passkeys.rootFor(i.publicKey);throw new Error(`invalid passkey signature ${r} for digest ${n}`);default:throw new Error(`method ${e.method} not implemented`)}};on=e=>{throw new Error(`unable to listen for ${e}: not implemented`)};removeListener=e=>{throw new Error(`unable to remove listener for ${e}: not implemented`)}},aV=new Kx;function $x(s){return {threshold:fn(s.threshold),checkpoint:fn(s.checkpoint),checkpointer:s.checkpointer,tree:Mg(s.topology)}}function oV(s){return s.checkpointer!==void 0&&B.assert(s.checkpointer),{threshold:BigInt(s.threshold),checkpoint:BigInt(s.checkpoint),checkpointer:s.checkpointer,topology:$g(s.tree)}}function Mg(s){if(Pe.isNode(s))return [Mg(s[0]),Mg(s[1])];if(Pe.isSignerLeaf(s))return {weight:fn(s.weight),address:s.address};if(Pe.isSapientSignerLeaf(s))return {weight:fn(s.weight),address:s.address,imageHash:s.imageHash};if(Pe.isSubdigestLeaf(s))return {subdigest:s.digest};if(Pe.isAnyAddressSubdigestLeaf(s))return {subdigest:s.digest,isAnyAddress:!0};if(Pe.isNestedLeaf(s))return {weight:fn(s.weight),threshold:fn(s.threshold),tree:Mg(s.tree)};if(Pe.isNodeLeaf(s))return s;throw new Error(`unknown topology '${JSON.stringify(s)}'`)}function $g(s){switch(typeof s){case"string":return E.assert(s),s;case"object":if(s instanceof Array)return [$g(s[0]),$g(s[1])];if("weight"in s){if("address"in s)return B.assert(s.address),s.imageHash?(E.assert(s.imageHash),{type:"sapient-signer",address:s.address,weight:BigInt(s.weight),imageHash:s.imageHash}):{type:"signer",address:s.address,weight:BigInt(s.weight)};if("tree"in s)return {type:"nested",weight:BigInt(s.weight),threshold:BigInt(s.threshold),tree:$g(s.tree)}}if("subdigest"in s)return E.assert(s.subdigest),{type:s.isAnyAddress?"any-address-subdigest":"subdigest",digest:s.subdigest}}throw new Error(`unknown config tree '${JSON.stringify(s)}'`)}function qx(s){if(ce.isCalls(s))return {type:"call",space:fn(s.space),nonce:fn(s.nonce),calls:s.calls.map(cV)};if(ce.isMessage(s))return {type:"message",message:s.message};if(ce.isConfigUpdate(s))return {type:"config-update",imageHash:s.imageHash};if(ce.isDigest(s))return {type:"digest",digest:s.digest};throw new Error(`unknown payload '${JSON.stringify(s)}'`)}function Gs(s){switch(s.type){case"call":return {type:"call",space:BigInt(s.space),nonce:BigInt(s.nonce),calls:s.calls.map(uV)};case"message":return E.assert(s.message),{type:"message",message:s.message};case"config-update":return E.assert(s.imageHash),{type:"config-update",imageHash:s.imageHash};case"digest":return E.assert(s.digest),{type:"digest",digest:s.digest}}}function cV(s){return {to:s.to,value:fn(s.value),data:s.data,gasLimit:fn(s.gasLimit),delegateCall:s.delegateCall,onlyFallback:s.onlyFallback,behaviorOnError:s.behaviorOnError}}function uV(s){return B.assert(s.to),E.assert(s.data),{to:s.to,value:BigInt(s.value),data:s.data,gasLimit:BigInt(s.gasLimit),delegateCall:s.delegateCall,onlyFallback:s.onlyFallback,behaviorOnError:s.behaviorOnError}}function h8(s){if(Ss.isBranch(s))return s.map(h8);if(Ss.isLeaf(s))return {data:f.toHex(s.value)};if(Ss.isNode(s))return s;throw new Error(`unknown tree '${JSON.stringify(s)}'`)}function f8(s){switch(typeof s){case"string":return E.assert(s),s;case"object":if(s instanceof Array)return s.map(f8);if("data"in s)return E.assert(s.data),{type:"leaf",value:E.toBytes(s.data)}}throw new Error(`unknown tree '${JSON.stringify(s)}'`)}function fn(s){return s<Number.MIN_SAFE_INTEGER||s>Number.MAX_SAFE_INTEGER?s.toString():Number(s)}function Qh(s){if(Rt.isRawNode(s))return [...Qh(s[0]),...Qh(s[1])];if(Rt.isRawSignerLeaf(s))return [s.signature];if(Pe.isNestedLeaf(s))return Qh(s.tree);if(Rt.isRawNestedLeaf(s))return Qh(s.tree);if(Pe.isSignerLeaf(s))return s.signature?[s.signature]:[];if(Pe.isSapientSignerLeaf(s))return s.signature?[s.signature]:[];if(Pe.isSubdigestLeaf(s))return [];if(Pe.isAnyAddressSubdigestLeaf(s))return [];if(Pe.isNodeLeaf(s))return [];throw new Error(`unknown topology '${JSON.stringify(s)}'`)}function lV(s,e){return typeof e=="bigint"?e.toString():e instanceof Uint8Array?E.fromBytes(e):e}function qg(s){return JSON.stringify(s,lV,2)}function Fg(s){if(typeof s=="bigint")return s.toString();if(s instanceof Uint8Array)return E.fromBytes(s);if(typeof s=="string")return s.toLowerCase();if(Array.isArray(s))return s.map(Fg);if(s&&typeof s=="object"){let e=[];for(let t of Object.keys(s).filter(n=>s[n]!==void 0).sort())e.push([t.toLowerCase(),Fg(s[t])]);return e}return s}function hV(s,e){return JSON.stringify(Fg(s))===JSON.stringify(Fg(e))}function fV(s,e){let t={get(n,r,i){let a=s[r];return typeof a!="function"?Reflect.get(s,r):async(...o)=>{let c=String(r),u=qg(o),l;try{l=await a.apply(s,o);}catch(m){let y=Math.floor(1e6*Math.random()).toString().padStart(6,"0");throw console.trace(`[${y}] calling ${c}: ${u}
|
|
350
|
-
[${y}] warning: reference ${c} threw:`,m),m}let h
|
|
348
|
+
`),qt(s.tree),f.padLeft(f.fromNumber(s.threshold),32),f.padLeft(f.fromNumber(s.weight),32)));if(mt(s))return oe.keccak256(f.concat(qt(s[0]),qt(s[1])));throw new Error("Invalid topology")}function ov(s){if(s.length===0)throw new Error("Cannot create topology from empty leaves");return s.length===1?s[0]:s.length===2?[s[0],s[1]]:[ov(s.slice(0,s.length/2)),ov(s.slice(s.length/2))]}function ug(s){return mt(s)?[...ug(s[0]),...ug(s[1])]:es(s)?[...ug(s.tree)]:[s]}function jO(s){return JSON.stringify({threshold:s.threshold.toString(),checkpoint:s.checkpoint.toString(),topology:lg(s.topology),checkpointer:s.checkpointer})}function HO(s){let e=JSON.parse(s);return {threshold:BigInt(e.threshold),checkpoint:BigInt(e.checkpoint),checkpointer:e.checkpointer,topology:hg(e.topology)}}function lg(s){if(mt(s))return [lg(s[0]),lg(s[1])];if(Mt(s))return {type:"signer",address:s.address,weight:s.weight.toString()};if($t(s))return {type:"sapient-signer",address:s.address,weight:s.weight.toString(),imageHash:s.imageHash};if(js(s))return {type:"subdigest",digest:s.digest};if(Hs(s))return {type:"any-address-subdigest",digest:s.digest};if(Ct(s))return s;if(es(s))return {type:"nested",tree:lg(s.tree),weight:s.weight.toString(),threshold:s.threshold.toString()};throw new Error("Invalid topology")}function hg(s){if(Array.isArray(s)){if(s.length!==2)throw new Error("Invalid node structure in JSON");return [hg(s[0]),hg(s[1])]}if(typeof s=="string")return s;switch(s.type){case"signer":return {type:"signer",address:s.address,weight:BigInt(s.weight)};case"sapient-signer":return {type:"sapient-signer",address:s.address,weight:BigInt(s.weight),imageHash:s.imageHash};case"subdigest":return {type:"subdigest",digest:s.digest};case"any-address-subdigest":return {type:"any-address-subdigest",digest:s.digest};case"nested":return {type:"nested",tree:hg(s.tree),weight:BigInt(s.weight),threshold:BigInt(s.threshold)};default:throw new Error("Invalid type in topology JSON")}}function _O(s){return s instanceof Promise?{signature:s}:typeof s=="object"&&s&&"signature"in s&&s.signature instanceof Promise?s:{signature:Promise.resolve(s)}}function dg(s,e){if(mt(s)&&mt(e))return [dg(s[0],e[0]),dg(s[1],e[1])];if(mt(s)&&!mt(e)){if(!Ct(e))throw new Error("Topology mismatch: cannot merge node with non-node that is not a node leaf");let t=qt(e);if(!f.isEqual(t,qt(s)))throw new Error("Topology mismatch: node hash does not match");return s}if(!mt(s)&&mt(e)){if(!Ct(s))throw new Error("Topology mismatch: cannot merge node with non-node that is not a node leaf");let t=qt(s);if(!f.isEqual(t,qt(e)))throw new Error("Topology mismatch: node hash does not match");return e}return $O(s,e)}function Oc(s){return Rc(s)?s.threshold>65535n||s.checkpoint>72057594037927935n||Oc(s.topology):mt(s)?Oc(s[0])||Oc(s[1]):es(s)?Oc(s.tree)||s.weight>255n||s.threshold>65535n:Mt(s)||$t(s)?s.weight>255n:!1}function jh(s){return mt(s)?Math.max(jh(s[0]),jh(s[1]))+1:es(s)?jh(s.tree)+1:0}function MO(s){if(s.threshold===0n)throw new Error("unsafe-threshold-0");if(Oc(s))throw new Error("unsafe-invalid-values");if(jh(s.topology)>32)throw new Error("unsafe-depth");let{maxWeight:e}=Lh(s.topology,()=>!0);if(e<s.threshold)throw new Error("unsafe-threshold")}function $O(s,e){if(Ct(s)&&Ct(e)){if(!E.isEqual(s,e))throw new Error("Topology mismatch: different node leaves");return s}if(Ct(s)&&!Ct(e)){let t=qt(e);if(!f.isEqual(t,f.fromHex(s)))throw new Error("Topology mismatch: node leaf hash does not match");return e}if(!Ct(s)&&Ct(e)){let t=qt(s);if(!f.isEqual(t,f.fromHex(e)))throw new Error("Topology mismatch: node leaf hash does not match");return s}if(Mt(s)&&Mt(e)){if(s.address!==e.address||s.weight!==e.weight)throw new Error("Topology mismatch: signer fields differ");if(!!s.signed!=!!e.signed||!!s.signature!=!!e.signature)throw new Error("Topology mismatch: signer signature fields differ");return s}if($t(s)&&$t(e)){if(s.address!==e.address||s.weight!==e.weight||s.imageHash!==e.imageHash)throw new Error("Topology mismatch: sapient signer fields differ");if(!!s.signed!=!!e.signed||!!s.signature!=!!e.signature)throw new Error("Topology mismatch: sapient signature fields differ");return s}if(js(s)&&js(e)){if(!f.isEqual(f.fromHex(s.digest),f.fromHex(e.digest)))throw new Error("Topology mismatch: subdigest fields differ");return s}if(Hs(s)&&Hs(e)){if(!f.isEqual(f.fromHex(s.digest),f.fromHex(e.digest)))throw new Error("Topology mismatch: any-address-subdigest fields differ");return s}if(es(s)&&es(e)){if(s.weight!==e.weight||s.threshold!==e.threshold)throw new Error("Topology mismatch: nested leaf fields differ");let t=dg(s.tree,e.tree);return {type:"nested",weight:s.weight,threshold:s.threshold,tree:t}}throw new Error("Topology mismatch: incompatible leaf types")}function fg(s,e,t){return mt(s)?[fg(s[0],e,t),fg(s[1],e,t)]:es(s)?{...s,tree:fg(s.tree,e,t)}:(Mt(s)||$t(s))&&B.isEqual(s.address,e)?{...s,address:t}:s}function qO(s,e){let t=s instanceof Uint8Array?s:qt(s);return f.toHex(oe.keccak256(f.concat(f.from("0xff"),f.from(e.factory),t,oe.keccak256(f.concat(f.from(e.creationCode),f.padLeft(f.from(e.stage1),32)))),{as:"Bytes"}).subarray(12))}var It={};be(It,{ACCEPT_IMPLICIT_REQUEST_MAGIC_PREFIX:()=>c5,decode:()=>FO,decodeAuthData:()=>i5,encode:()=>n5,encodeAuthData:()=>r5,encodeForJson:()=>a5,fromJson:()=>WO,fromParsed:()=>o5,generateImplicitRequestMagic:()=>JO,hash:()=>KO,toJson:()=>GO});function n5(s){let e=r5(s.authData),t=[f.fromHex(s.approvedSigner,{size:20}),f.padLeft(s.identityType.slice(0,4),4),f.padLeft(s.issuerHash,32),f.padLeft(s.audienceHash,32),f.fromNumber(s.applicationData.length,{size:3}),s.applicationData,e];return f.concat(...t)}function r5(s){return f.concat(f.fromNumber(s.redirectUrl.length,{size:3}),f.fromString(s.redirectUrl),f.fromNumber(s.issuedAt,{size:8}))}function FO(s){let e=f.toHex(s.slice(0,20)),t=s.slice(20,24),n=s.slice(24,56),r=s.slice(56,88),i=f.toNumber(s.slice(88,91)),a=s.slice(91,91+i),o=i5(s.slice(91+i));return {approvedSigner:e,identityType:t,issuerHash:n,audienceHash:r,applicationData:a,authData:o}}function i5(s){let e=f.toNumber(s.slice(0,3)),t=f.toString(s.slice(3,3+e)),n=f.toBigInt(s.slice(3+e,3+e+8));return {redirectUrl:t,issuedAt:n}}function KO(s){return oe.keccak256(n5(s))}function GO(s,e){return JSON.stringify(a5(s),null,e)}function a5(s){return {approvedSigner:s.approvedSigner.toString(),identityType:f.toHex(s.identityType),issuerHash:f.toHex(s.issuerHash),audienceHash:f.toHex(s.audienceHash),applicationData:f.toHex(s.applicationData),authData:{redirectUrl:s.authData.redirectUrl,issuedAt:s.authData.issuedAt.toString()}}}function WO(s){return o5(JSON.parse(s))}function o5(s){return {approvedSigner:B.from(s.approvedSigner),identityType:f.fromHex(s.identityType),issuerHash:f.fromHex(s.issuerHash),audienceHash:f.fromHex(s.audienceHash),applicationData:f.fromHex(s.applicationData),authData:{redirectUrl:s.authData.redirectUrl,issuedAt:BigInt(s.authData.issuedAt)}}}var c5=oe.keccak256(f.fromString("acceptImplicitRequest"));function JO(s,e){return oe.keccak256(f.concat(c5,f.fromHex(e,{size:20}),s.audienceHash,s.issuerHash))}var Hn={};be(Hn,{MASK:()=>zO,MAX_PERMISSIONS_COUNT:()=>mg,MAX_RULES_COUNT:()=>u5,ParameterOperation:()=>cv,abiEncodePermission:()=>XO,decodeSessionPermissions:()=>pg,encodePermission:()=>l5,encodeSessionPermissions:()=>Hh,encodeSessionPermissionsForJson:()=>gg,parameterRuleToJson:()=>sR,permissionFromJson:()=>rR,permissionStructAbi:()=>h5,permissionToJson:()=>tR,sessionPermissionsFromJson:()=>nR,sessionPermissionsFromParsed:()=>yg,sessionPermissionsToJson:()=>eR});var cv;(function(s){s[s.EQUAL=0]="EQUAL",s[s.NOT_EQUAL=1]="NOT_EQUAL",s[s.GREATER_THAN_OR_EQUAL=2]="GREATER_THAN_OR_EQUAL",s[s.LESS_THAN_OR_EQUAL=3]="LESS_THAN_OR_EQUAL";})(cv||(cv={}));var mg=2**7-1,u5=2**8-1,zO={SELECTOR:f.padRight(f.fromHex("0xffffffff"),32),ADDRESS:f.padLeft(f.fromHex("0xffffffffffffffffffffffffffffffffffffffff"),32),BOOL:f.padLeft(f.fromHex("0x01"),32),BYTES1:f.padLeft(f.from(Array(1).fill(255)),32),BYTES2:f.padLeft(f.from(Array(2).fill(255)),32),BYTES4:f.padLeft(f.from(Array(4).fill(255)),32),BYTES8:f.padLeft(f.from(Array(8).fill(255)),32),BYTES16:f.padLeft(f.from(Array(16).fill(255)),32),BYTES32:f.padLeft(f.from(Array(32).fill(255)),32),INT8:f.padLeft(f.from(Array(1).fill(255)),32),INT16:f.padLeft(f.from(Array(2).fill(255)),32),INT32:f.padLeft(f.from(Array(4).fill(255)),32),INT64:f.padLeft(f.from(Array(8).fill(255)),32),INT128:f.padLeft(f.from(Array(16).fill(255)),32),INT256:f.padLeft(f.from(Array(32).fill(255)),32),UINT8:f.padLeft(f.from(Array(1).fill(255)),32),UINT16:f.padLeft(f.from(Array(2).fill(255)),32),UINT32:f.padLeft(f.from(Array(4).fill(255)),32),UINT64:f.padLeft(f.from(Array(8).fill(255)),32),UINT128:f.padLeft(f.from(Array(16).fill(255)),32),UINT256:f.padLeft(f.from(Array(32).fill(255)),32)};function Hh(s){if(s.permissions.length>mg)throw new Error("Too many permissions");let e=s.permissions.map(l5);return f.concat(f.padLeft(f.fromHex(s.signer),20),f.padLeft(f.fromNumber(s.chainId),32),f.padLeft(f.fromNumber(s.valueLimit),32),f.padLeft(f.fromNumber(s.deadline,{size:8}),8),f.fromNumber(s.permissions.length,{size:1}),f.concat(...e))}function l5(s){if(s.rules.length>u5)throw new Error("Too many rules");let e=s.rules.map(YO);return f.concat(f.padLeft(f.fromHex(s.target),20),f.fromNumber(s.rules.length,{size:1}),f.concat(...e))}function YO(s){let e=Number(s.operation)<<1|(s.cumulative?1:0);return f.concat(f.fromNumber(e),f.padLeft(s.value,32),f.padLeft(f.fromNumber(s.offset),32),f.padLeft(s.mask,32))}function pg(s){let e=f.toHex(s.slice(0,20)),t=f.toNumber(s.slice(20,52)),n=f.toBigInt(s.slice(52,84)),r=f.toBigInt(s.slice(84,92)),i=Number(s[92]),a=[],o=93;for(let c=0;c<i;c++){let{permission:u,consumed:l}=ZO(s.slice(o));a.push(u),o+=l;}if(a.length===0)throw new Error("No permissions");return {signer:e,chainId:t,valueLimit:n,deadline:r,permissions:a}}function ZO(s){let e=f.toHex(s.slice(0,20)),t=Number(s[20]),n=[],r=21;for(let i=0;i<t;i++){let a=s.slice(r,r+97);n.push(QO(a)),r+=97;}return {permission:{target:e,rules:n},consumed:r}}function QO(s){let e=Number(s[0]),t=(e&1)===1,n=e>>1,r=s.slice(1,33),i=f.toBigInt(s.slice(33,65)),a=s.slice(65,97);return {cumulative:t,operation:n,value:r,offset:i,mask:a}}var h5={internalType:"struct Permission",name:"permission",type:"tuple",components:[{internalType:"address",name:"target",type:"address"},{internalType:"struct ParameterRule[]",name:"rules",type:"tuple[]",components:[{internalType:"bool",name:"cumulative",type:"bool"},{internalType:"enum ParameterOperation",name:"operation",type:"uint8"},{internalType:"bytes32",name:"value",type:"bytes32"},{internalType:"uint256",name:"offset",type:"uint256"},{internalType:"bytes32",name:"mask",type:"bytes32"}]}]};function XO(s){return ot.encode([h5],[{target:s.target,rules:s.rules.map(e=>({cumulative:e.cumulative,operation:e.operation,value:f.toHex(e.value),offset:e.offset,mask:f.toHex(e.mask)}))}])}function eR(s){return JSON.stringify(gg(s))}function gg(s){return {signer:s.signer.toString(),chainId:s.chainId.toString(),valueLimit:s.valueLimit.toString(),deadline:s.deadline.toString(),permissions:s.permissions.map(f5)}}function tR(s){return JSON.stringify(f5(s))}function f5(s){return {target:s.target.toString(),rules:s.rules.map(d5)}}function sR(s){return JSON.stringify(d5(s))}function d5(s){return {cumulative:s.cumulative,operation:s.operation,value:f.toHex(s.value),offset:s.offset.toString(),mask:f.toHex(s.mask)}}function nR(s){return yg(JSON.parse(s))}function yg(s){return {signer:B.from(s.signer),chainId:Number(s.chainId),valueLimit:BigInt(s.valueLimit),deadline:BigInt(s.deadline),permissions:s.permissions.map(m5)}}function rR(s){return m5(JSON.parse(s))}function m5(s){return {target:B.from(s.target),rules:s.rules.map(e=>({cumulative:e.cumulative,operation:e.operation,value:f.fromHex(e.value),offset:BigInt(e.offset),mask:f.fromHex(e.mask)}))}}var Ns={};be(Ns,{SESSIONS_FLAG_BLACKLIST:()=>Dc,SESSIONS_FLAG_BRANCH:()=>lv,SESSIONS_FLAG_IDENTITY_SIGNER:()=>$h,SESSIONS_FLAG_NODE:()=>uv,SESSIONS_FLAG_PERMISSIONS:()=>Mh,addExplicitSession:()=>hR,addIdentitySigner:()=>dR,addToImplicitBlacklist:()=>mR,balanceSessionsTopology:()=>Kh,cleanSessionsTopology:()=>C5,configurationTreeToSessionsTopology:()=>v5,decodeLeafFromBytes:()=>b5,decodeSessionsTopology:()=>dv,emptySessionsTopology:()=>N5,encodeLeafToGeneric:()=>_h,encodeSessionsTopology:()=>vg,getExplicitSigners:()=>oR,getIdentitySigners:()=>qh,getImplicitBlacklist:()=>aR,getImplicitBlacklistLeaf:()=>Fh,getSessionPermissions:()=>Sg,isCompleteSessionsTopology:()=>fv,isSessionsTopology:()=>hv,mergeSessionsTopologies:()=>pv,minimiseSessionsTopology:()=>xg,removeExplicitSession:()=>lR,removeFromImplicitBlacklist:()=>pR,removeIdentitySigner:()=>fR,sessionsTopologyFromJson:()=>uR,sessionsTopologyToConfigurationTree:()=>S5,sessionsTopologyToJson:()=>cR});var Ss={};be(Ss,{hash:()=>_s,isBranch:()=>bs,isLeaf:()=>Br,isNode:()=>pt,isTree:()=>p5});function bs(s){return Array.isArray(s)&&s.length>=2&&s.every(e=>p5(e))}function Br(s){return s.type==="leaf"&&f.validate(s.value)}function p5(s){return bs(s)||Br(s)||pt(s)}function pt(s){return E.validate(s)&&E.size(s)===32}function _s(s){if(bs(s)){let e=s.map(_s);if(e.length===0)throw new Error("Empty branch");let t=E.toBytes(e[0]);for(let n=1;n<e.length;n++)t=oe.keccak256(f.concat(t,E.toBytes(e[n])));return E.fromBytes(t)}return pt(s)?s:oe.keccak256(s.value,{as:"Hex"})}var Mh=0,uv=1,lv=2,Dc=3,$h=4,g5=32;function un(s){return E.validate(s)&&E.size(s)===g5}function Ms(s){return typeof s=="object"&&s!==null&&"blacklist"in s}function $s(s){return typeof s=="object"&&s!==null&&"identitySigner"in s}function qs(s){return typeof s=="object"&&s!==null&&"signer"in s}function wg(s){return Ms(s)||$s(s)||qs(s)}function Fs(s){return Array.isArray(s)&&s.length>=2&&s.every(e=>hv(e))}function hv(s){return Fs(s)||wg(s)||un(s)}function fv(s){if(!hv(s))return !1;let{identitySignerCount:e,blacklistCount:t}=y5(s);return e>=1&&t===1}function y5(s){let e=0,t=0;if(Fs(s))for(let n of s){let{identitySignerCount:r,blacklistCount:i}=y5(n);e+=r,t+=i;}return $s(s)&&e++,Ms(s)&&t++,{identitySignerCount:e,blacklistCount:t}}function qh(s){return $s(s)?[s.identitySigner]:Fs(s)?s.map(qh).flat():[]}function aR(s){let e=Fh(s);return e?e.blacklist:null}function Fh(s){if(Ms(s))return s;if(Fs(s)){let e=s.map(Fh).filter(t=>t!==null);if(e.length>1)throw new Error("Multiple blacklists");if(e.length===1)return e[0]}return null}function Sg(s,e){if(qs(s)&&B.isEqual(s.signer,e))return s;if(Fs(s))for(let t of s){let n=Sg(t,e);if(n)return n}return null}function oR(s){return w5(s,[])}function w5(s,e){if(qs(s))return [...e,s.signer];if(Fs(s)){let t=[...e];for(let n of s)t.push(...w5(n,e));return t}return e}function _h(s){if(qs(s))return {type:"leaf",value:f.concat(f.fromNumber(Mh),Hh(s))};if(Ms(s))return {type:"leaf",value:f.concat(f.fromNumber(Dc),f.concat(...s.blacklist.map(e=>f.padLeft(f.fromHex(e),20))))};if($s(s))return {type:"leaf",value:f.concat(f.fromNumber($h),f.padLeft(f.fromHex(s.identitySigner),20))};throw new Error("Invalid leaf")}function b5(s){let e=s[0];if(e===Dc){let t=[];for(let n=1;n<s.length;n+=20)t.push(f.toHex(s.slice(n,n+20)));return {type:"implicit-blacklist",blacklist:t}}if(e===$h)return {type:"identity-signer",identitySigner:f.toHex(s.slice(1,21))};if(e===Mh)return {type:"session-permissions",...pg(s.slice(1))};throw new Error("Invalid leaf")}function S5(s){if(Fs(s))return s.map(S5);if(Ms(s)||$s(s)||qs(s))return _h(s);if(un(s))return s;throw new Error("Invalid topology")}function v5(s){if(bs(s))return s.map(v5);if(pt(s))throw new Error("Unknown in configuration tree");return b5(s.value)}function vg(s){if(Fs(s)){let e=[];for(let i of s)e.push(vg(i));let t=f.concat(...e),n=ws(BigInt(t.length));if(n>15)throw new Error("Branch too large");let r=lv<<4|n;return f.concat(f.fromNumber(r),f.padLeft(f.fromNumber(t.length),n),t)}if(qs(s)){let e=Mh<<4,t=Hh(s);return f.concat(f.fromNumber(e),t)}if(un(s)){let e=uv<<4;return f.concat(f.fromNumber(e),E.toBytes(s))}if(Ms(s)){let e=f.concat(...s.blacklist.map(n=>f.fromHex(n)));if(s.blacklist.length>=15){if(s.blacklist.length>65535)throw new Error("Blacklist too large");return f.concat(f.fromNumber(Dc<<4|15),f.fromNumber(s.blacklist.length,{size:2}),e)}let t=Dc<<4|s.blacklist.length;return f.concat(f.fromNumber(t),e)}if($s(s)){let e=$h<<4;return f.concat(f.fromNumber(e),f.padLeft(f.fromHex(s.identitySigner),20))}throw new Error("Invalid topology")}function dv(s){let{topology:e}=x5(s);return e}function x5(s){if(s.length===0)throw new Error("Empty topology bytes");let e=s[0],t=(e&240)>>4,n=e&15;if(t===lv){if(n===0||n>15)throw new Error("Invalid branch size");let r=1,i=f.toNumber(s.slice(r,r+n));r+=n;let a=s.slice(r,r+i),o=[],c=0;for(;c<a.length;){let{topology:u,pointer:l}=x5(a.slice(c));o.push(u),c+=l;}return {topology:o,pointer:r+i}}else if(t===Mh){let r=pg(s.slice(1)),i=1+Hh(r).length;return {topology:{type:"session-permissions",...r},pointer:i}}else if(t===uv){let r=g5+1;if(s.length<r)throw new Error("Invalid node length");return {topology:E.fromBytes(s.slice(1,r)),pointer:r}}else if(t===Dc){let r=1,i=n;n===15&&(i=f.toNumber(s.slice(r,r+2)),r+=2);let a=[];for(let o=0;o<i;o++){let c=s.slice(r+o*20,r+(o+1)*20);a.push(B.from(E.fromBytes(c)));}return {topology:{type:"implicit-blacklist",blacklist:a},pointer:r+i*20}}else if(t===$h){if(s.length<21)throw new Error("Invalid identity signer length");return {topology:{type:"identity-signer",identitySigner:B.from(E.fromBytes(s.slice(1,21)))},pointer:21}}else throw new Error(`Invalid topology flag: ${t}`)}function cR(s){return JSON.stringify(E5(s))}function E5(s){if(un(s))return s;if(qs(s))return gg(s);if(Ms(s)||$s(s))return s;if(Fs(s))return s.map(e=>E5(e));throw new Error("Invalid topology")}function uR(s){let e=JSON.parse(s);return A5(e)}function A5(s){if(Array.isArray(s))return s.map(t=>A5(t));if(typeof s=="string"&&E.validate(s)&&E.size(s)===32)return s;if(typeof s=="object"&&s!==null&&"signer"in s&&"valueLimit"in s&&"deadline"in s&&"permissions"in s)return {type:"session-permissions",...yg(s)};if(typeof s=="object"&&s!==null&&"identitySigner"in s)return {type:"identity-signer",identitySigner:s.identitySigner};if(typeof s=="object"&&s!==null&&"blacklist"in s)return {type:"implicit-blacklist",blacklist:s.blacklist.map(t=>B.from(t))};throw new Error("Invalid topology")}function mv(s,e){if(wg(s)&&wg(e)){if(s.type===e.type){if(qs(s)&&qs(e)){if(B.isEqual(s.signer,e.signer))return null}else if(Ms(s)&&Ms(e)){let t=s.blacklist.filter(n=>!e.blacklist.includes(n));return t.length===0?null:{type:"implicit-blacklist",blacklist:t}}else if($s(s)&&$s(e)&&B.isEqual(s.identitySigner,e.identitySigner))return null}}else if(un(s)&&un(e)&&E.isEqual(s,e))return null;if(Fs(s)){let t=[];for(let n of s){let r=mv(n,e);r!=null&&t.push(r);}return t.length===0?null:t.length===1?t[0]:t}return s}function lR(s,e){let t=Sg(s,e);if(!t)return s;let n=mv(s,t);return n?Kh(n):null}function hR(s,e){if(Sg(s,e.signer))throw new Error("Session already exists");let t=pv(s,{type:"session-permissions",...e});return Kh(t)}function fR(s,e){let n=mv(s,{type:"identity-signer",identitySigner:e});return n?Kh(n):null}function dR(s,e){if(qh(s).some(n=>B.isEqual(n,e)))throw new Error("Identity signer already exists");let t=pv(s,{type:"identity-signer",identitySigner:e});return Kh(t)}function pv(s,e){return [s,e]}function I5(s){if(wg(s)||un(s))return [s];let e=[];for(let t of s)e.push(...I5(t));return e}function bg(s){if(s.length===1)return s[0];if(s.length===0)throw new Error("Cannot build a topology from an empty list");let e=Math.floor(s.length/2),t=s.slice(0,e),n=s.slice(e),r=bg(t),i=bg(n);return [r,i]}function Kh(s){return bg(I5(s))}function C5(s,e=BigInt(Math.floor(Date.now()/1e3))){if(un(s))return s;if(qs(s))return s.deadline<e?null:s;if($s(s)||Ms(s))return s;let t=[];for(let n of s){let r=C5(n,e);r!==null&&t.push(r);}return t.length===0?null:t.length===1?t[0]:t}function xg(s,e=[],t=[],n){if(Fs(s)){let r=s.map(i=>xg(i,e,t,n));return r.every(i=>un(i))?oe.keccak256(f.concat(...r.map(i=>E.toBytes(i))),{as:"Hex"}):r}if(qs(s))return e.includes(s.signer)?s:_s(_h(s));if(Ms(s))return t.length===0?_s(_h(s)):s;if($s(s))return n&&!B.isEqual(s.identitySigner,n)?_s(_h(s)):s;if(un(s))return s;throw new Error("Invalid topology")}function mR(s,e){let t=Fh(s);if(!t)throw new Error("No blacklist found");let{blacklist:n}=t;return n.some(r=>B.isEqual(r,e))||(n.push(e),n.sort((r,i)=>BigInt(r)<BigInt(i)?-1:1)),s}function pR(s,e){let t=Fh(s);if(!t)throw new Error("No blacklist found");let{blacklist:n}=t,r=n.filter(i=>i!==e);return t.blacklist=r,s}function N5(s){if(!Array.isArray(s))return N5([s]);let e=[{type:"implicit-blacklist",blacklist:[]},...s.map(t=>({type:"identity-signer",identitySigner:t}))];return bg(e)}var Or={};be(Or,{decodeSessionSignature:()=>bR,encodeSessionCallSignatureForJson:()=>k5,encodeSessionSignature:()=>wR,hashPayloadWithCallIdx:()=>SR,isExplicitSessionCallSignature:()=>wv,isImplicitSessionCallSignature:()=>Eg,sessionCallSignatureFromJson:()=>yR,sessionCallSignatureFromParsed:()=>P5,sessionCallSignatureToJson:()=>gR});function Eg(s){return "attestation"in s&&"identitySignature"in s&&"sessionSignature"in s}function wv(s){return "permissionIndex"in s&&"sessionSignature"in s}function gR(s){return JSON.stringify(k5(s))}function k5(s){if(Eg(s))return {attestation:It.encodeForJson(s.attestation),identitySignature:gv(s.identitySignature),sessionSignature:gv(s.sessionSignature)};if(wv(s))return {permissionIndex:s.permissionIndex,sessionSignature:gv(s.sessionSignature)};throw new Error("Invalid call signature")}function yR(s){let e=JSON.parse(s);return P5(e)}function P5(s){if(s.attestation)return {attestation:It.fromParsed(s.attestation),identitySignature:yv(s.identitySignature),sessionSignature:yv(s.sessionSignature)};if(s.permissionIndex)return {permissionIndex:s.permissionIndex,sessionSignature:yv(s.sessionSignature)};throw new Error("Invalid call signature")}function gv(s){return `${s.r.toString()}:${s.s.toString()}:${s.yParity+27}`}function yv(s){let e=s.split(":");if(e.length!==3)throw new Error("Signature must be in r:s:v format");let[t,n,r]=e;if(!t||!n||!r)throw new Error("Invalid signature format");return {r:f.toBigInt(f.fromHex(t,{size:32})),s:f.toBigInt(f.fromHex(n,{size:32})),yParity:parseInt(r,10)-27}}function wR(s,e,t,n=[],r=[]){let i=[];if(!fv(e))throw new Error("Incomplete topology");if(!qh(e).some(l=>B.isEqual(l,t)))throw new Error("Identity signer not found");e=xg(e,n,r,t);let o=vg(e);if(ws(BigInt(o.length))>3)throw new Error("Session topology is too large");i.push(f.fromNumber(o.length,{size:3}),o);let c=new Map,u=[];if(s.filter(Eg).forEach(l=>{if(l.attestation){let h=It.toJson(l.attestation);c.has(h)||(c.set(h,u.length),u.push(f.concat(It.encode(l.attestation),jn(l.identitySignature))));}}),u.length>=128)throw new Error("Too many attestations");i.push(f.fromNumber(u.length,{size:1}),f.concat(...u));for(let l of s)if(Eg(l)){let h=It.toJson(l.attestation),m=c.get(h);if(m===void 0)throw new Error("Failed to find attestation index");let y=128|m;i.push(f.fromNumber(y,{size:1}),jn(l.sessionSignature));}else if(wv(l)){if(l.permissionIndex>mg)throw new Error("Permission index is too large");let h=l.permissionIndex;i.push(f.fromNumber(h,{size:1}),jn(l.sessionSignature));}else throw new Error("Invalid call signature");return f.concat(...i)}function bR(s){let e=0,t=f.toNumber(s.slice(e,e+3));e+=3;let n=s.slice(e,e+t);e+=t;let r=dv(n),i=f.toNumber(s.slice(e,e+1));e+=1;let a=[],o=[];for(let u=0;u<i;u++){let l=It.decode(s.slice(e));e+=It.encode(l).length,a.push(l);let h=ga(s.slice(e,e+64));e+=64,o.push(h);}let c=[];for(;e<s.length;){let u=s[e];e+=1;let l=ga(s.slice(e,e+64));if(e+=64,u&128){let h=u&127;if(h>=a.length)throw new Error("Invalid attestation index");c.push({attestation:a[h],identitySignature:o[h],sessionSignature:l});}else {let h=u;c.push({permissionIndex:BigInt(h),sessionSignature:l});}}return {topology:r,callSignatures:c}}function SR(s,e,t,n,r){if(r&&(B.isEqual(r,Ne.Dev1.sessions)||B.isEqual(r,Ne.Dev2.sessions)||B.isEqual(r,Ne.Rc3.sessions))){let c=e.calls[t],u=!B.isEqual(r,Ne.Rc3.sessions);return E.fromBytes(oe.keccak256(f.concat(f.fromNumber(n,{size:32}),f.fromNumber(e.space,{size:32}),f.fromNumber(e.nonce,{size:32}),u?f.from([]):f.fromNumber(t,{size:32}),f.fromHex(ce.hashCall(c)))))}let a=e.parentWallets;e.parentWallets&&e.parentWallets.length>0&&e.parentWallets.pop();let o=ce.hash(s,n,e);return e.parentWallets=a,E.fromBytes(oe.keccak256(f.concat(o,f.fromNumber(t,{size:32}))))}var wa={};be(wa,{Dev1:()=>T5,Dev2:()=>B5,Dev2_4337:()=>O5,KnownContexts:()=>vR,Rc3:()=>R5,Rc3_4337:()=>V5,Rc4:()=>D5,Rc4_4337:()=>U5,Rc5:()=>L5,Rc5_4337:()=>j5,isKnownContext:()=>xR});var T5={factory:"0xe828630697817291140D6B7A42a2c3b7277bE45a",stage1:"0x2a4fB19F66F1427A5E363Bf1bB3be27b9A9ACC39",stage2:"0xe1299E4456b267123F7Aba29B72C2164ff501BDa",creationCode:"0x603e600e3d39601e805130553df33d3d34601c57363d3d373d363d30545af43d82803e903d91601c57fd5bf3"},B5={factory:"0xFE14B91dE3c5Ca74c4D24608EBcD4B2848aA6010",stage1:"0x300E98ae5bEA4A7291d62Eb0b9feD535E10095dD",stage2:"0x90cb0a8ccf40bEdA60896e408bdc7801033447C6",creationCode:"0x6041600e3d396021805130553df33d3d36153402601f57363d3d373d363d30545af43d82803e903d91601f57fd5bf3"},O5={factory:"0xFE14B91dE3c5Ca74c4D24608EBcD4B2848aA6010",stage1:"0x8Ae58FCc0Ee9b32994CA52c9854deb969DC8fa2A",stage2:"0x30f8e3AceAcDEac8a3F28935D87FD58DC5f71ad2",creationCode:"0x6041600e3d396021805130553df33d3d36153402601f57363d3d373d363d30545af43d82803e903d91601f57fd5bf3",capabilities:{erc4337:{entrypoint:"0x0000000071727De22E5E9d8BAf0edAc6f37da032"}}},R5={factory:"0x00000000000018A77519fcCCa060c2537c9D6d3F",stage1:"0x00000000000084fA81809Dd337311297C5594d62",stage2:"0x7438718F9E4b9B834e305A620EEeCf2B9E6eBE79",creationCode:"0x6041600e3d396021805130553df33d3d36153402601f57363d3d373d363d30545af43d82803e903d91601f57fd5bf3"},V5={factory:"0x00000000000018A77519fcCCa060c2537c9D6d3F",stage1:"0x0000000000005A02E3218e820EA45102F84A35C7",stage2:"0x7706aaC0cc2C42C01CE17136F7475b0E46F2ABA1",creationCode:"0x6041600e3d396021805130553df33d3d36153402601f57363d3d373d363d30545af43d82803e903d91601f57fd5bf3",capabilities:{erc4337:{entrypoint:"0x0000000071727De22E5E9d8BAf0edAc6f37da032"}}},D5={factory:"0x00000000000018A77519fcCCa060c2537c9D6d3F",stage1:"0x0000000000003DF093bc4257E6dCE45D937EF161",stage2:"0x10bE1Abf3cD0918bb1079ECc6b8220c177F34088",creationCode:"0x6041600e3d396021805130553df33d3d36153402601f57363d3d373d363d30545af43d82803e903d91601f57fd5bf3"},U5={factory:"0x00000000000018A77519fcCCa060c2537c9D6d3F",stage1:"0x0000000000003add039FF84b064B7347Fc23C444",stage2:"0x4B3E5735665057A0A15eE448A7293bC01e3b4De9",creationCode:"0x6041600e3d396021805130553df33d3d36153402601f57363d3d373d363d30545af43d82803e903d91601f57fd5bf3",capabilities:{erc4337:{entrypoint:"0x0000000071727De22E5E9d8BAf0edAc6f37da032"}}},L5={factory:"0x00000000000018A77519fcCCa060c2537c9D6d3F",stage1:"0x0000000000001f3C39d61698ab21131a12134454",stage2:"0xD0ae8eF93b7DA4eabb32Ec4d81b7a501DCa04D4C",creationCode:"0x6041600e3d396021805130553df33d3d36153402601f57363d3d373d363d30545af43d82803e903d91601f57fd5bf3"},j5={factory:"0x00000000000018A77519fcCCa060c2537c9D6d3F",stage1:"0x0000000000009caFdeDb6f64Bf5F31a22124B2a8",stage2:"0xcBca3328a731deffE6Ce4c2fb51b585c3c37FB92",creationCode:"0x6041600e3d396021805130553df33d3d36153402601f57363d3d373d363d30545af43d82803e903d91601f57fd5bf3",capabilities:{erc4337:{entrypoint:"0x0000000071727De22E5E9d8BAf0edAc6f37da032"}}},vR=[{name:"Dev1",development:!0,...T5},{name:"Dev2",development:!0,...B5},{name:"Dev2_4337",development:!0,...O5},{name:"Rc3",development:!0,...R5},{name:"Rc3_4337",development:!0,...V5},{name:"Rc4",development:!1,...D5},{name:"Rc4_4337",development:!1,...U5},{name:"Rc5",development:!1,...L5},{name:"Rc5_4337",development:!1,...j5}];function xR(s){return s.name!==void 0&&s.development!==void 0}var Ne={};be(Ne,{Dev1:()=>UR,Dev2:()=>LR,Passkeys:()=>Sv,Rc3:()=>jR,Rc4:()=>HR,Rc5:()=>_R,Recovery:()=>Ov});var Sv={};be(Sv,{decode:()=>NR,encode:()=>IR,fromTree:()=>ER,isValidSignature:()=>CR,metadataNode:()=>H5,metadataTree:()=>bv,rootFor:()=>AR,toTree:()=>_5});function bv(s){return typeof s=="object"?{type:"leaf",value:f.fromString(s.credentialId)}:s}function H5(s){return _s(bv(s))}function _5(s){let e=E.padLeft(s.x,32),t=E.padLeft(s.y,32),n=E.padLeft(s.requireUserVerification?"0x01":"0x00",32);return s.metadata?[[e,t],[n,bv(s.metadata)]]:[[e,t],[n,E.padLeft("0x00",32)]]}function ER(s){if(!bs(s)||s.length!==2)throw new Error("Invalid tree");let[e,t]=s;if(!bs(e)||e.length!==2)throw new Error("Invalid tree for x,y");let[n,r]=e;if(!pt(n))throw new Error("Invalid x bytes");if(!pt(r))throw new Error("Invalid y bytes");let i=!1,a;if(bs(t)){if(t.length!==2)throw new Error("Invalid tree for c,metadata");let[o,c]=t;if(!pt(o))throw new Error("Invalid c bytes");if(i=E.toBytes(o)[31]===1,bs(c)){if(c.length!==2)throw new Error("Invalid metadata tree");let[l,h]=c;if(!Br(l))throw new Error("Invalid credentialId leaf");let m=new TextDecoder().decode(l.value);if(!bs(h)||h.length!==2)throw new Error("Invalid sub-branch for name and createdAt");let[y,g]=h;if(!Br(y)||!Br(g))throw new Error("Invalid metadata leaves");a={credentialId:m};}else if(pt(c))a=c;else throw new Error("Invalid metadata node")}else {if(!pt(t))throw new Error("Invalid c bytes");i=E.toBytes(t)[31]===1;}return {requireUserVerification:i,x:n,y:r,metadata:a}}function AR(s){return _s(_5(s))}function IR(s){let e=s.clientDataJSON.indexOf('"challenge"'),t=s.clientDataJSON.indexOf('"type"'),n=s.authenticatorData.length,r=s.clientDataJSON.length;if(n>65535)throw new Error("Authenticator data size is too large");if(r>65535)throw new Error("Client data JSON size is too large");let i=n<=255?1:2,a=r<=255?1:2,o=e<=255?1:2,c=t<=255?1:2,u=0;u|=s.publicKey.requireUserVerification?1:0,u|=i-1<<1,u|=a-1<<2,u|=o-1<<3,u|=c-1<<4,s.embedMetadata&&(u|=64);let l=f.from([u]);if(s.embedMetadata){if(!s.publicKey.metadata)throw new Error("Metadata is not present in the public key");l=f.concat(l,E.toBytes(H5(s.publicKey.metadata)));}return l=f.concat(l,f.padLeft(f.fromNumber(n),i)),l=f.concat(l,s.authenticatorData),l=f.concat(l,f.padLeft(f.fromNumber(s.clientDataJSON.length),a)),l=f.concat(l,f.from(new TextEncoder().encode(s.clientDataJSON))),l=f.concat(l,f.padLeft(f.fromNumber(e),o)),l=f.concat(l,f.padLeft(f.fromNumber(t),c)),l=f.concat(l,f.padLeft(s.r,32)),l=f.concat(l,f.padLeft(s.s,32)),l=f.concat(l,f.fromHex(s.publicKey.x)),l=f.concat(l,f.fromHex(s.publicKey.y)),l}function CR(s,e){return Tr.verify({challenge:s,publicKey:{x:E.toBigInt(e.publicKey.x),y:E.toBigInt(e.publicKey.y),prefix:4},metadata:{authenticatorData:E.fromBytes(e.authenticatorData),challengeIndex:e.clientDataJSON.indexOf('"challenge"'),clientDataJSON:e.clientDataJSON,typeIndex:e.clientDataJSON.indexOf('"type"'),userVerificationRequired:e.publicKey.requireUserVerification},signature:{r:f.toBigInt(e.r),s:f.toBigInt(e.s)}})}function NR(s){let e=0,t=s[0];if(e+=1,t===void 0)throw new Error("Invalid flags");let n=(t&1)!==0,r=(t>>1&1)+1,i=(t>>2&1)+1,a=(t>>3&1)+1,o=(t>>4&1)+1,c=(t>>6&1)===1;if(t&32)throw new Error("Fallback to abi decode is not supported in this implementation");let u;if(c){let I=f.slice(s,e,e+32);u=E.fromBytes(I),e+=32;}let l=f.toNumber(f.slice(s,e,e+r));e+=r;let h=f.slice(s,e,e+l);e+=l;let m=f.toNumber(f.slice(s,e,e+i));e+=i;let y=f.slice(s,e,e+m);e+=m;let g=new TextDecoder().decode(y),w=f.toNumber(f.slice(s,e,e+a));e+=a;let S=f.toNumber(f.slice(s,e,e+o));e+=o;let C=f.slice(s,e,e+32);e+=32;let k=f.slice(s,e,e+32);e+=32;let x=f.slice(s,e,e+32);e+=32;let v=f.slice(s,e,e+32);return {publicKey:{requireUserVerification:n,x:E.fromBytes(x),y:E.fromBytes(v),metadata:u},r:C,s:k,authenticatorData:h,clientDataJSON:g,challengeIndex:w,typeIndex:S,embedMetadata:c}}var Ov={};be(Ov,{DOMAIN_NAME:()=>kR,DOMAIN_VERSION:()=>PR,FLAG_BRANCH:()=>Tv,FLAG_NODE:()=>Pv,FLAG_RECOVERY_LEAF:()=>kv,QUEUED_PAYLOAD_HASHES:()=>q5,QUEUE_PAYLOAD:()=>M5,TIMESTAMP_FOR_QUEUED_PAYLOAD:()=>$5,TOTAL_QUEUED_PAYLOADS:()=>F5,decodeTopology:()=>TR,encodeCalldata:()=>OR,encodeTopology:()=>Iv,fromGenericTree:()=>Nv,fromRecoveryLeaves:()=>Cv,getRecoveryLeaves:()=>Ev,hashConfiguration:()=>xv,hashRecoveryPayload:()=>BR,isBranch:()=>ba,isRecoveryLeaf:()=>Uc,isTree:()=>vv,parseBranch:()=>Bv,queuedPayloadHashOf:()=>VR,timestampForQueuedPayload:()=>DR,toGenericTree:()=>Ag,totalQueuedPayloads:()=>RR,trimTopology:()=>Av});var kv=1,Pv=3,Tv=4,Gh=f.fromString(`Sequence recovery leaf:
|
|
349
|
+
`),M5=at.from(["function queuePayload(address _wallet, address _signer, (uint8 kind,bool noChainId,(address to,uint256 value,bytes data,uint256 gasLimit,bool delegateCall,bool onlyFallback,uint256 behaviorOnError)[] calls,uint256 space,uint256 nonce,bytes message,bytes32 imageHash,bytes32 digest,address[] parentWallets) calldata _payload, bytes calldata _signature) external"])[0],$5=at.from(["function timestampForQueuedPayload(address _wallet, address _signer, bytes32 _payloadHash) external view returns (uint256)"])[0],q5=at.from(["function queuedPayloadHashes(address _wallet, address _signer, uint256 _index) external view returns (bytes32)"])[0],F5=at.from(["function totalQueuedPayloads(address _wallet, address _signer) external view returns (uint256)"])[0];function Uc(s){return typeof s=="object"&&s!==null&&s.type==="leaf"}function ba(s){return Array.isArray(s)&&s.length===2&&vv(s[0])&&vv(s[1])}function vv(s){return Uc(s)||pt(s)||ba(s)}var kR="Sequence Wallet - Recovery Mode",PR="1";function xv(s){return _s(Ag(s))}function Ev(s){if(Uc(s))return {leaves:[s],isComplete:!0};if(pt(s))return {leaves:[],isComplete:!1};if(ba(s)){let t=Ev(s[0]),n=Ev(s[1]);return {leaves:[...t.leaves,...n.leaves],isComplete:t.isComplete&&n.isComplete}}else throw new Error("Invalid topology")}function TR(s){let{nodes:e,leftover:t}=Bv(s);if(t.length>0)throw new Error("Leftover bytes in branch");return K5(e)}function Bv(s){if(s.length===0)throw new Error("Empty branch");let e=[],t=0;for(;t<s.length;){let n=s[t];if(n===kv){if(s.length<t+32)throw new Error("Invalid recovery leaf");let r=B.from(E.fromBytes(s.slice(t+1,t+21))),i=f.toBigInt(s.slice(t+21,t+24)),a=f.toBigInt(s.slice(t+24,t+32));e.push({type:"leaf",signer:r,requiredDeltaTime:i,minTimestamp:a}),t+=32;continue}else if(n===Pv){if(s.length<t+33)throw new Error("Invalid node");let r=E.fromBytes(s.slice(t+1,t+33));e.push(r),t+=33;continue}else if(n===Tv){if(s.length<t+4)throw new Error("Invalid branch");let r=f.toNumber(s.slice(t+1,t+4));if(s.length<t+4+r)throw new Error("Invalid branch");let i=s.slice(t+4,t+4+r),{nodes:a,leftover:o}=Bv(i);if(o.length>0)throw new Error("Leftover bytes in sub-branch");let c=K5(a);e.push(c),t+=4+r;continue}else throw new Error("Invalid flag")}return {nodes:e,leftover:s.slice(t)}}function Av(s,e){if(Uc(s))return s.signer===e?s:xv(s);if(pt(s))return s;if(ba(s)){let t=Av(s[0],e),n=Av(s[1],e);return pt(t)&&pt(n)?xv(s):[t,n]}throw new Error("Invalid topology")}function Iv(s){if(ba(s)){let e=Iv(s[0]),t=Iv(s[1]);if(ba(s[1])){if(t.length>16777215)throw new Error("Branch too large");let r=f.fromNumber(Tv),i=f.padLeft(f.fromNumber(t.length),3);return f.concat(e,r,i,t)}else return f.concat(e,t)}if(pt(s)){let e=f.fromNumber(Pv),t=f.fromHex(s,{size:32});return f.concat(e,t)}if(Uc(s)){let e=f.fromNumber(kv),t=f.fromHex(s.signer,{size:20});if(s.requiredDeltaTime>16777215n)throw new Error("Required delta time too large");let n=f.padLeft(f.fromNumber(s.requiredDeltaTime),3);if(s.minTimestamp>18446744073709551615n)throw new Error("Min timestamp too large");let r=f.padLeft(f.fromNumber(s.minTimestamp),8);return f.concat(e,t,n,r)}throw new Error("Invalid topology")}function K5(s){if(s.length===0)throw new Error("Empty signature tree");if(s.length===1)return s[0];let e=s[0];for(let t=1;t<s.length;t++)e=[e,s[t]];return e}function Cv(s){if(s.length===0)throw new Error("Cannot build a tree with zero leaves");if(s.length===1)return s[0];let e=Math.floor(s.length/2),t=Cv(s.slice(0,e)),n=Cv(s.slice(e));return [t,n]}function BR(s,e,t,n){let r=FS(s);return E.fromBytes(Pc(e,n?0:t,r))}function Ag(s){if(Uc(s))return {type:"leaf",value:f.concat(Gh,f.fromHex(s.signer,{size:20}),f.padLeft(f.fromNumber(s.requiredDeltaTime),32),f.padLeft(f.fromNumber(s.minTimestamp),32))};if(pt(s))return s;if(ba(s))return [Ag(s[0]),Ag(s[1])];throw new Error("Invalid topology")}function Nv(s){if(Br(s)){let e=s.value;if(e.length!==Gh.length+84||!f.isEqual(e.slice(0,Gh.length),Gh))throw new Error("Invalid recovery leaf format");let t=Gh.length,n=B.from(E.fromBytes(e.slice(t,t+20))),r=f.toBigInt(e.slice(t+20,t+52)),i=f.toBigInt(e.slice(t+52,t+84));return {type:"leaf",signer:n,requiredDeltaTime:r,minTimestamp:i}}else {if(pt(s))return s;if(bs(s)){if(s.length!==2)throw new Error("Recovery tree only supports binary branches");return [Nv(s[0]),Nv(s[1])]}else throw new Error("Invalid tree format")}}function OR(s,e,t,n){let r;n.type==="erc1271"?r=n.data:r=f.toHex(jn(n));let i=WS(e);return se.encodeData(M5,[s,t,i,r])}async function RR(s,e,t,n){let r=await s.request({method:"eth_call",params:[{to:e,data:se.encodeData(F5,[t,n])},"latest"]});return r==="0x"?0n:E.toBigInt(r)}async function VR(s,e,t,n,r){return await s.request({method:"eth_call",params:[{to:e,data:se.encodeData(q5,[t,n,r])},"latest"]})}async function DR(s,e,t,n,r){let i=await s.request({method:"eth_call",params:[{to:e,data:se.encodeData($5,[t,n,r])},"latest"]});return E.toBigInt(i)}var UR={passkeys:"0x8f26281dB84C18aAeEa8a53F94c835393229d296",recovery:"0xd98da48C4FF9c19742eA5856A277424557C863a6",sessions:"0x06aa3a8F781F2be39b888Ac8a639c754aEe9dA29"},LR={passkeys:"0x4491845806B757D67BE05BbD877Cab101B9bee5C",recovery:"0xdED857b9b5142832634129aFfc1D67cD106b927c",sessions:"0x06aa3a8F781F2be39b888Ac8a639c754aEe9dA29"},jR={passkeys:"0x0000000000dc2d96870dc108c5E15570B715DFD2",recovery:"0x0000000000213697bCA95E7373787a40858a51C7",sessions:"0x0000000000CC58810c33F3a0D78aA1Ed80FaDcD8"},HR={passkeys:"0x0000000000005204F3711851EAD52CC9c241499a",recovery:"0x000000000001FC499c3E177DD56Febb0A4bc15b7",sessions:"0x00000000000030Bcc832F7d657f50D6Be35C92b3"},_R={passkeys:"0x0000000000005204F3711851EAD52CC9c241499a",recovery:"0x000000000000AB36D17eB1150116371520565205",sessions:"0x00000000000030Bcc832F7d657f50D6Be35C92b3"};var Sa={};be(Sa,{ALL:()=>Rv,ChainId:()=>H,NetworkType:()=>de,getNetworkFromChainId:()=>$R,getNetworkFromName:()=>MR});var de;(function(s){s.MAINNET="mainnet",s.TESTNET="testnet";})(de||(de={}));var H={NONE:0,MAINNET:1,SEPOLIA:11155111,POLYGON:137,POLYGON_ZKEVM:1101,POLYGON_AMOY:80002,BSC:56,BSC_TESTNET:97,OPTIMISM:10,OPTIMISM_SEPOLIA:11155420,ARBITRUM:42161,ARBITRUM_SEPOLIA:421614,ARBITRUM_NOVA:42170,AVALANCHE:43114,AVALANCHE_TESTNET:43113,GNOSIS:100,BASE:8453,BASE_SEPOLIA:84532,HOMEVERSE_TESTNET:40875,HOMEVERSE:19011,XAI:660279,XAI_SEPOLIA:37714555429,TELOS:40,TELOS_TESTNET:41,B3:8333,B3_SEPOLIA:1993,APECHAIN:33139,APECHAIN_TESTNET:33111,BLAST:81457,BLAST_SEPOLIA:168587773,SKALE_NEBULA:1482601649,SKALE_NEBULA_TESTNET:37084624,SONEIUM_MINATO:1946,SONEIUM:1868,TOY_TESTNET:21e6,IMMUTABLE_ZKEVM:13371,IMMUTABLE_ZKEVM_TESTNET:13473,ETHERLINK:42793,ETHERLINK_TESTNET:128123,MOONBEAM:1284,MOONBASE_ALPHA:1287,MONAD:143,MONAD_TESTNET:10143,SOMNIA_TESTNET:50312,SOMNIA:5031,INCENTIV_TESTNET_V2:28802,KATANA:747474,SANDBOX_TESTNET:6252,ARC_TESTNET:5042002},Rv=[{chainId:H.MAINNET,type:de.MAINNET,name:"mainnet",title:"Ethereum",rpcUrl:ge("mainnet"),logoUrl:ye(H.MAINNET),blockExplorer:{name:"Etherscan",url:"https://etherscan.io/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18},ensAddress:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},{chainId:H.SEPOLIA,type:de.TESTNET,name:"sepolia",title:"Sepolia",rpcUrl:ge("sepolia"),logoUrl:ye(H.SEPOLIA),blockExplorer:{name:"Etherscan (Sepolia)",url:"https://sepolia.etherscan.io/"},nativeCurrency:{symbol:"sETH",name:"Sepolia Ether",decimals:18}},{chainId:H.POLYGON,type:de.MAINNET,name:"polygon",title:"Polygon",rpcUrl:ge("polygon"),logoUrl:ye(H.POLYGON),blockExplorer:{name:"Polygonscan",url:"https://polygonscan.com/"},nativeCurrency:{symbol:"POL",name:"POL",decimals:18}},{chainId:H.POLYGON_AMOY,type:de.TESTNET,name:"amoy",title:"Polygon Amoy",rpcUrl:ge("amoy"),logoUrl:ye(H.POLYGON_AMOY),blockExplorer:{name:"OKLink (Amoy)",url:"https://www.oklink.com/amoy/"},nativeCurrency:{symbol:"aPOL",name:"Amoy POL",decimals:18}},{chainId:H.POLYGON_ZKEVM,type:de.MAINNET,name:"polygon-zkevm",title:"Polygon zkEVM",rpcUrl:ge("polygon-zkevm"),logoUrl:ye(H.POLYGON_ZKEVM),blockExplorer:{name:"Polygonscan (zkEVM)",url:"https://zkevm.polygonscan.com/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.BSC,type:de.MAINNET,name:"bsc",title:"BNB Smart Chain",rpcUrl:ge("bsc"),logoUrl:ye(H.BSC),blockExplorer:{name:"BSCScan",url:"https://bscscan.com/"},nativeCurrency:{symbol:"BNB",name:"BNB",decimals:18}},{chainId:H.BSC_TESTNET,type:de.TESTNET,name:"bsc-testnet",title:"BNB Smart Chain Testnet",rpcUrl:ge("bsc-testnet"),logoUrl:ye(H.BSC_TESTNET),blockExplorer:{name:"BSCScan (Testnet)",url:"https://testnet.bscscan.com/"},nativeCurrency:{symbol:"tBNB",name:"Testnet BNB",decimals:18}},{chainId:H.OPTIMISM,type:de.MAINNET,name:"optimism",title:"Optimism",rpcUrl:ge("optimism"),logoUrl:ye(H.OPTIMISM),blockExplorer:{name:"Etherscan (Optimism)",url:"https://optimistic.etherscan.io/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.OPTIMISM_SEPOLIA,type:de.TESTNET,name:"optimism-sepolia",title:"Optimism Sepolia",rpcUrl:ge("optimism-sepolia"),logoUrl:ye(H.OPTIMISM_SEPOLIA),blockExplorer:{name:"Etherscan (Optimism Sepolia)",url:"https://sepolia-optimistic.etherscan.io/"},nativeCurrency:{symbol:"sETH",name:"Sepolia Ether",decimals:18}},{chainId:H.ARBITRUM,type:de.MAINNET,name:"arbitrum",title:"Arbitrum One",rpcUrl:ge("arbitrum"),logoUrl:ye(H.ARBITRUM),blockExplorer:{name:"Arbiscan",url:"https://arbiscan.io/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.ARBITRUM_SEPOLIA,type:de.TESTNET,name:"arbitrum-sepolia",title:"Arbitrum Sepolia",rpcUrl:ge("arbitrum-sepolia"),logoUrl:ye(H.ARBITRUM_SEPOLIA),blockExplorer:{name:"Arbiscan (Sepolia Testnet)",url:"https://sepolia.arbiscan.io/"},nativeCurrency:{symbol:"sETH",name:"Sepolia Ether",decimals:18}},{chainId:H.ARBITRUM_NOVA,type:de.MAINNET,name:"arbitrum-nova",title:"Arbitrum Nova",rpcUrl:ge("arbitrum-nova"),logoUrl:ye(H.ARBITRUM_NOVA),blockExplorer:{name:"Arbiscan Nova",url:"https://nova.arbiscan.io/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.AVALANCHE,type:de.MAINNET,name:"avalanche",title:"Avalanche",rpcUrl:ge("avalanche"),logoUrl:ye(H.AVALANCHE),blockExplorer:{name:"Snowtrace",url:"https://subnets.avax.network/c-chain/"},nativeCurrency:{symbol:"AVAX",name:"AVAX",decimals:18}},{chainId:H.AVALANCHE_TESTNET,type:de.TESTNET,name:"avalanche-testnet",title:"Avalanche Testnet",rpcUrl:ge("avalanche-testnet"),logoUrl:ye(H.AVALANCHE_TESTNET),blockExplorer:{name:"Snowtrace (Testnet)",url:"https://subnets-test.avax.network/c-chain/"},nativeCurrency:{symbol:"tAVAX",name:"Testnet AVAX",decimals:18}},{chainId:H.GNOSIS,type:de.MAINNET,name:"gnosis",title:"Gnosis Chain",rpcUrl:ge("gnosis"),logoUrl:ye(H.GNOSIS),blockExplorer:{name:"Gnosis Chain Explorer",url:"https://blockscout.com/xdai/mainnet/"},nativeCurrency:{symbol:"XDAI",name:"XDAI",decimals:18}},{chainId:H.BASE,type:de.MAINNET,name:"base",title:"Base (Coinbase)",rpcUrl:ge("base"),logoUrl:ye(H.BASE),blockExplorer:{name:"Base Explorer",url:"https://basescan.org/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.BASE_SEPOLIA,type:de.TESTNET,name:"base-sepolia",title:"Base Sepolia",rpcUrl:ge("base-sepolia"),logoUrl:ye(H.BASE_SEPOLIA),blockExplorer:{name:"Base Sepolia Explorer",url:"https://base-sepolia.blockscout.com/"},nativeCurrency:{symbol:"sETH",name:"Sepolia Ether",decimals:18}},{chainId:H.HOMEVERSE,type:de.MAINNET,name:"homeverse",title:"Oasys Homeverse",rpcUrl:ge("homeverse"),logoUrl:ye(H.HOMEVERSE),blockExplorer:{name:"Oasys Homeverse Explorer",url:"https://explorer.oasys.homeverse.games/"},nativeCurrency:{symbol:"OAS",name:"OAS",decimals:18}},{chainId:H.HOMEVERSE_TESTNET,type:de.TESTNET,name:"homeverse-testnet",title:"Oasys Homeverse Testnet",rpcUrl:ge("homeverse-testnet"),logoUrl:ye(H.HOMEVERSE_TESTNET),blockExplorer:{name:"Oasys Homeverse Explorer (Testnet)",url:"https://explorer.testnet.oasys.homeverse.games/"},nativeCurrency:{symbol:"tOAS",name:"Testnet OAS",decimals:18}},{chainId:H.XAI,type:de.MAINNET,name:"xai",title:"Xai",rpcUrl:ge("xai"),logoUrl:ye(H.XAI),blockExplorer:{name:"Xai Explorer",url:"https://explorer.xai-chain.net/"},nativeCurrency:{symbol:"XAI",name:"XAI",decimals:18}},{chainId:H.XAI_SEPOLIA,type:de.TESTNET,name:"xai-sepolia",title:"Xai Sepolia",rpcUrl:ge("xai-sepolia"),logoUrl:ye(H.XAI_SEPOLIA),blockExplorer:{name:"Xai Sepolia Explorer",url:"https://testnet-explorer-v2.xai-chain.net/"},nativeCurrency:{symbol:"sXAI",name:"Sepolia XAI",decimals:18}},{chainId:H.B3,type:de.MAINNET,name:"b3",title:"B3",rpcUrl:ge("b3"),logoUrl:ye(H.B3),blockExplorer:{name:"B3 Explorer",url:"https://explorer.b3.fun/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.B3_SEPOLIA,type:de.TESTNET,name:"b3-sepolia",title:"B3 Sepolia",rpcUrl:ge("b3-sepolia"),logoUrl:ye(H.B3_SEPOLIA),blockExplorer:{name:"B3 Sepolia Explorer",url:"https://sepolia.explorer.b3.fun/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.APECHAIN,type:de.MAINNET,name:"apechain",title:"APE Chain",rpcUrl:ge("apechain"),logoUrl:ye(H.APECHAIN),blockExplorer:{name:"APE Chain Explorer",url:"https://apechain.calderaexplorer.xyz/"},nativeCurrency:{symbol:"APE",name:"ApeCoin",decimals:18}},{chainId:H.APECHAIN_TESTNET,type:de.TESTNET,name:"apechain-testnet",title:"APE Chain Testnet",rpcUrl:ge("apechain-testnet"),logoUrl:ye(H.APECHAIN_TESTNET),blockExplorer:{name:"APE Chain Explorer",url:"https://curtis.explorer.caldera.xyz/"},nativeCurrency:{symbol:"APE",name:"ApeCoin",decimals:18}},{chainId:H.BLAST,type:de.MAINNET,name:"blast",title:"Blast",rpcUrl:ge("blast"),logoUrl:ye(H.BLAST),blockExplorer:{name:"Blast Explorer",url:"https://blastscan.io/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.BLAST_SEPOLIA,type:de.TESTNET,name:"blast-sepolia",title:"Blast Sepolia",rpcUrl:ge("blast-sepolia"),logoUrl:ye(H.BLAST_SEPOLIA),blockExplorer:{name:"Blast Sepolia Explorer",url:"https://sepolia.blastexplorer.io/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.TELOS,type:de.MAINNET,name:"telos",title:"Telos",rpcUrl:ge("telos"),logoUrl:ye(H.TELOS),blockExplorer:{name:"Telos Explorer",url:"https://explorer.telos.net/network/"},nativeCurrency:{symbol:"TLOS",name:"TLOS",decimals:18}},{chainId:H.TELOS_TESTNET,type:de.TESTNET,name:"telos-testnet",title:"Telos Testnet",rpcUrl:ge("telos-testnet"),logoUrl:ye(H.TELOS_TESTNET),blockExplorer:{name:"Telos Testnet Explorer",url:"https://explorer-test.telos.net/network"},nativeCurrency:{symbol:"TLOS",name:"TLOS",decimals:18}},{chainId:H.SKALE_NEBULA,type:de.MAINNET,name:"skale-nebula",title:"SKALE Nebula Gaming Hub",rpcUrl:ge("skale-nebula"),logoUrl:ye(H.SKALE_NEBULA),blockExplorer:{name:"SKALE Nebula Gaming Hub Explorer",url:"https://green-giddy-denebola.explorer.mainnet.skalenodes.com/"},nativeCurrency:{symbol:"sFUEL",name:"SKALE Fuel",decimals:18}},{chainId:H.SKALE_NEBULA_TESTNET,type:de.TESTNET,name:"skale-nebula-testnet",title:"SKALE Nebula Gaming Hub Testnet",rpcUrl:ge("skale-nebula-testnet"),logoUrl:ye(H.SKALE_NEBULA_TESTNET),blockExplorer:{name:"SKALE Nebula Gaming Hub Testnet Explorer",url:"https://lanky-ill-funny-testnet.explorer.testnet.skalenodes.com/"},nativeCurrency:{symbol:"sFUEL",name:"SKALE Fuel",decimals:18}},{chainId:H.SONEIUM,type:de.MAINNET,name:"soneium",title:"Soneium",rpcUrl:ge("soneium"),logoUrl:ye(H.SONEIUM),blockExplorer:{name:"Soneium Explorer",url:"https://soneium.blockscout.com/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.SONEIUM_MINATO,type:de.TESTNET,name:"soneium-minato",title:"Soneium Minato (Testnet)",rpcUrl:ge("soneium-minato"),logoUrl:ye(H.SONEIUM_MINATO),blockExplorer:{name:"Soneium Minato Explorer",url:"https://explorer-testnet.soneium.org/"},nativeCurrency:{symbol:"ETH",name:"Ether",decimals:18}},{chainId:H.TOY_TESTNET,type:de.TESTNET,name:"toy-testnet",title:"TOY (Testnet)",rpcUrl:ge("toy-testnet"),logoUrl:ye(H.TOY_TESTNET),blockExplorer:{name:"TOY Testnet Explorer",url:"https://toy-chain-testnet.explorer.caldera.xyz/"},nativeCurrency:{symbol:"TOY",name:"TOY",decimals:18}},{chainId:H.IMMUTABLE_ZKEVM,type:de.MAINNET,name:"immutable-zkevm",title:"Immutable zkEVM",rpcUrl:ge("immutable-zkevm"),logoUrl:ye(H.IMMUTABLE_ZKEVM),blockExplorer:{name:"Immutable zkEVM Explorer",url:"https://explorer.immutable.com/"},nativeCurrency:{symbol:"IMX",name:"IMX",decimals:18}},{chainId:H.IMMUTABLE_ZKEVM_TESTNET,type:de.TESTNET,name:"immutable-zkevm-testnet",title:"Immutable zkEVM Testnet",rpcUrl:ge("immutable-zkevm-testnet"),logoUrl:ye(H.IMMUTABLE_ZKEVM_TESTNET),blockExplorer:{name:"Immutable zkEVM Testnet Explorer",url:"https://explorer.testnet.immutable.com/"},nativeCurrency:{symbol:"IMX",name:"IMX",decimals:18}},{chainId:H.MOONBEAM,type:de.MAINNET,name:"moonbeam",title:"Moonbeam",rpcUrl:ge("moonbeam"),logoUrl:ye(H.MOONBEAM),blockExplorer:{name:"Moonscan",url:"https://moonscan.io/"},nativeCurrency:{symbol:"GLMR",name:"GLMR",decimals:18}},{chainId:H.MOONBASE_ALPHA,type:de.TESTNET,name:"moonbase-alpha",title:"Moonbase Alpha",rpcUrl:ge("moonbase-alpha"),logoUrl:ye(H.MOONBASE_ALPHA),blockExplorer:{name:"Moonscan (Moonbase Alpha)",url:"https://moonbase.moonscan.io/"},nativeCurrency:{symbol:"GLMR",name:"GLMR",decimals:18}},{chainId:H.ETHERLINK,type:de.MAINNET,name:"etherlink",title:"Etherlink",rpcUrl:ge("etherlink"),logoUrl:ye(H.ETHERLINK),blockExplorer:{name:"Etherlink Explorer",url:"https://explorer.etherlink.com/"},nativeCurrency:{symbol:"XTZ",name:"Tez",decimals:18}},{chainId:H.ETHERLINK_TESTNET,type:de.TESTNET,name:"etherlink-testnet",title:"Etherlink Testnet",rpcUrl:ge("etherlink-testnet"),logoUrl:ye(H.ETHERLINK_TESTNET),blockExplorer:{name:"Etherlink Testnet Explorer",url:"https://testnet.explorer.etherlink.com/"},nativeCurrency:{symbol:"XTZ",name:"Tez",decimals:18}},{chainId:H.MONAD,type:de.MAINNET,name:"monad",title:"Monad",rpcUrl:ge("monad"),logoUrl:ye(H.MONAD),blockExplorer:{name:"Monad Explorer",url:"https://mainnet-beta.monvision.io/"},nativeCurrency:{symbol:"MON",name:"MON",decimals:18}},{chainId:H.MONAD_TESTNET,type:de.TESTNET,name:"monad-testnet",title:"Monad Testnet",rpcUrl:ge("monad-testnet"),logoUrl:ye(H.MONAD_TESTNET),blockExplorer:{name:"Monad Testnet Explorer",url:"https://testnet.monadexplorer.com/"},nativeCurrency:{symbol:"MON",name:"MON",decimals:18}},{chainId:H.SOMNIA,type:de.MAINNET,name:"somnia",title:"Somnia",rpcUrl:ge("somnia"),logoUrl:ye(H.SOMNIA),blockExplorer:{name:"Somnia Explorer",url:"https://mainnet.somnia.w3us.site/"},nativeCurrency:{symbol:"SOMI",name:"SOMI",decimals:18}},{chainId:H.SOMNIA_TESTNET,type:de.TESTNET,name:"somnia-testnet",title:"Somnia Testnet",rpcUrl:ge("somnia-testnet"),logoUrl:ye(H.SOMNIA_TESTNET),blockExplorer:{name:"Somnia Testnet Explorer",url:"https://somnia-testnet.socialscan.io/"},nativeCurrency:{symbol:"STT",name:"STT",decimals:18}},{chainId:H.INCENTIV_TESTNET_V2,type:de.TESTNET,name:"incentiv-testnet-v2",title:"Incentiv Testnet",rpcUrl:ge("incentiv-testnet-v2"),logoUrl:ye(H.INCENTIV_TESTNET_V2),blockExplorer:{name:"Incentiv Testnet Explorer",url:"https://explorer.testnet.incentiv.net/"},nativeCurrency:{symbol:"TCENT",name:"TCENT",decimals:18}},{chainId:H.KATANA,type:de.MAINNET,name:"katana",title:"Katana",rpcUrl:ge("katana"),logoUrl:ye(H.KATANA),blockExplorer:{name:"Katana Explorer",url:"https://katanascan.com/"},nativeCurrency:{symbol:"ETH",name:"ETH",decimals:18}},{chainId:H.SANDBOX_TESTNET,type:de.TESTNET,name:"sandbox-testnet",title:"Sandbox Testnet",rpcUrl:ge("sandbox-testnet"),logoUrl:ye(H.SANDBOX_TESTNET),blockExplorer:{name:"Sandbox Testnet Explorer",url:"https://sandbox-testnet.explorer.caldera.xyz/"},nativeCurrency:{symbol:"SAND",name:"SAND",decimals:18}},{chainId:H.ARC_TESTNET,type:de.TESTNET,name:"arc-testnet",title:"Arc Testnet",rpcUrl:ge("arc-testnet"),logoUrl:ye(H.ARC_TESTNET),blockExplorer:{name:"Arc Testnet Explorer",url:"https://1jr2dw1zdqvyes8u.blockscout.com/"},nativeCurrency:{symbol:"USDC",name:"USDC",decimals:6}}];function ge(s){return `https://nodes.sequence.app/${s}`}function ye(s){return `https://assets.sequence.info/images/networks/medium/${s}.webp`}function MR(s){return Rv.find(e=>e.name===s)}function $R(s){return Rv.find(e=>e.chainId===Number(s))}var G5="$";function W5(s,e){var t="",n=e&&e.include,r=e&&e.exclude;r&&typeof r=="string"&&(r=[r]),n&&n.sort();var i=new WeakMap,a=e&&e.allowCircular,o=e&&e.filterUndefined,c=e&&e.undefinedInArrayToNull;return u(s,G5),t;function u(l,h){if(l===null||typeof l!="object"||l.toJSON!=null)t+=JSON.stringify(l);else if(Array.isArray(l)){var m=i.get(l);if(m!==void 0&&h.startsWith(m)){if(!a)throw new Error("Circular reference detected");t+='"[Circular:'+m+']"';return}i.set(l,h),t+="[";var y=!1;l.forEach(function(C,k){y&&(t+=","),y=!0,c&&C===void 0&&(C=null),u(C,h+"["+k+"]");}),t+="]";}else {var m=i.get(l);if(m!==void 0&&h.startsWith(m)){if(!a)throw new Error("Circular reference detected");t+='"[Circular:'+m+']"';return}i.set(l,h),t+="{";var g=!1,w=function(k){r&&r.includes(k)||(g&&(t+=","),g=!0,t+=JSON.stringify(k),t+=":",u(l[k],h+"."+k));};if(h===G5&&n)n.forEach(function(k){l.hasOwnProperty(k)&&w(k);});else {var S=Object.keys(l);o&&(S=S.filter(function(k){return l[k]!==void 0})),S.sort(),S.forEach(function(k){w(k);});}t+="}";}}}function Ig(s,e){return W5(s,{allowCircular:e,filterUndefined:!0,undefinedInArrayToNull:!0})}var qR="Webrpc",FR="webrpc@v0.23.1;gen-typescript@v0.16.3;identity-instrument@v0.1.0";var ln;(function(s){s.WebCrypto_Secp256r1="WebCrypto_Secp256r1",s.Ethereum_Secp256k1="Ethereum_Secp256k1";})(ln||(ln={}));var _n;(function(s){s.Email="Email",s.OIDC="OIDC";})(_n||(_n={}));var jc;(function(s){s.OTP="OTP",s.IDToken="IDToken",s.AccessToken="AccessToken",s.AuthCode="AuthCode",s.AuthCodePKCE="AuthCodePKCE";})(jc||(jc={}));var Cg=class{hostname;fetch;path="/rpc/IdentityInstrument/";constructor(e,t){this.hostname=e.replace(/\/*$/,""),this.fetch=(n,r)=>t(n,r);}url(e){return this.hostname+this.path+e}commitVerifier=(e,t,n)=>this.fetch(this.url("CommitVerifier"),Vv(e,t,n)).then(r=>Dv(r).then(i=>({verifier:i.verifier,loginHint:i.loginHint,challenge:i.challenge})),r=>{throw Lc.new({cause:`fetch(): ${r.message||""}`})});completeAuth=(e,t,n)=>this.fetch(this.url("CompleteAuth"),Vv(e,t,n)).then(r=>Dv(r).then(i=>({signer:i.signer,identity:i.identity})),r=>{throw Lc.new({cause:`fetch(): ${r.message||""}`})});sign=(e,t,n)=>this.fetch(this.url("Sign"),Vv(e,t,n)).then(r=>Dv(r).then(i=>({signature:i.signature})),r=>{throw Lc.new({cause:`fetch(): ${r.message||""}`})})},Vv=(s={},e={},t=null)=>{let n={...e,"Content-Type":"application/json"};return n[qR]=FR,{method:"POST",headers:n,body:JSON.stringify(s||{}),signal:t}},Dv=s=>s.text().then(e=>{let t;try{t=JSON.parse(e);}catch(n){let r="";throw n instanceof Error&&(r=n.message),Ng.new({status:s.status,cause:`JSON.parse(): ${r}: response text: ${e}`})}if(!s.ok){let n=typeof t.code=="number"?t.code:0;throw (KR[n]||Me).new(t)}return t}),Me=class s extends Error{name;code;message;status;cause;msg;constructor(e,t,n,r,i){super(n),this.name=e||"WebrpcError",this.code=typeof t=="number"?t:0,this.message=n||`endpoint error ${this.code}`,this.msg=this.message,this.status=typeof r=="number"?r:0,this.cause=i,Object.setPrototypeOf(this,s.prototype);}static new(e){return new this(e.error,e.code,e.message||e.msg,e.status,e.cause)}},Uv=class s extends Me{constructor(e="WebrpcEndpoint",t=0,n="endpoint error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Lc=class s extends Me{constructor(e="WebrpcRequestFailed",t=-1,n="request failed",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Lv=class s extends Me{constructor(e="WebrpcBadRoute",t=-2,n="bad route",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},jv=class s extends Me{constructor(e="WebrpcBadMethod",t=-3,n="bad method",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Hv=class s extends Me{constructor(e="WebrpcBadRequest",t=-4,n="bad request",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Ng=class s extends Me{constructor(e="WebrpcBadResponse",t=-5,n="bad response",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},_v=class s extends Me{constructor(e="WebrpcServerPanic",t=-6,n="server panic",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Mv=class s extends Me{constructor(e="WebrpcInternalError",t=-7,n="internal error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},$v=class s extends Me{constructor(e="WebrpcClientDisconnected",t=-8,n="client disconnected",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},qv=class s extends Me{constructor(e="WebrpcStreamLost",t=-9,n="stream lost",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Fv=class s extends Me{constructor(e="WebrpcStreamFinished",t=-10,n="stream finished",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Kv=class s extends Me{constructor(e="InternalError",t=7100,n="Internal error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Gv=class s extends Me{constructor(e="EncryptionError",t=7101,n="Encryption error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Wv=class s extends Me{constructor(e="DatabaseError",t=7102,n="Database error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Jv=class s extends Me{constructor(e="DataIntegrityError",t=7103,n="Data integrity error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},zv=class s extends Me{constructor(e="IdentityProviderError",t=7104,n="Identity provider error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Yv=class s extends Me{constructor(e="InvalidRequest",t=7200,n="The request was invalid",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Zv=class s extends Me{constructor(e="InvalidSignature",t=7201,n="The signature was invalid",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Qv=class s extends Me{constructor(e="KeyNotFound",t=7202,n="The authentication key was not found",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Xv=class s extends Me{constructor(e="KeyExpired",t=7203,n="The authentication key expired",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},ex=class s extends Me{constructor(e="SignerNotFound",t=7204,n="The signer was not found",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},tx=class s extends Me{constructor(e="ProofVerificationFailed",t=7002,n="The authentication proof could not be verified",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},sx=class s extends Me{constructor(e="AnswerIncorrect",t=7003,n="The provided answer is incorrect",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},nx=class s extends Me{constructor(e="ChallengeExpired",t=7004,n="The challenge has expired",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},rx=class s extends Me{constructor(e="TooManyAttempts",t=7005,n="Too many attempts",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},ix=class s extends Me{constructor(e="OAuthError",t=7006,n="Failed to exchange OAuth credentials",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},ax=class s extends Me{constructor(e="AccessError",t=7007,n="Access error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},J5;(function(s){s.WebrpcEndpoint="WebrpcEndpoint",s.WebrpcRequestFailed="WebrpcRequestFailed",s.WebrpcBadRoute="WebrpcBadRoute",s.WebrpcBadMethod="WebrpcBadMethod",s.WebrpcBadRequest="WebrpcBadRequest",s.WebrpcBadResponse="WebrpcBadResponse",s.WebrpcServerPanic="WebrpcServerPanic",s.WebrpcInternalError="WebrpcInternalError",s.WebrpcClientDisconnected="WebrpcClientDisconnected",s.WebrpcStreamLost="WebrpcStreamLost",s.WebrpcStreamFinished="WebrpcStreamFinished",s.InternalError="InternalError",s.EncryptionError="EncryptionError",s.DatabaseError="DatabaseError",s.DataIntegrityError="DataIntegrityError",s.IdentityProviderError="IdentityProviderError",s.InvalidRequest="InvalidRequest",s.InvalidSignature="InvalidSignature",s.KeyNotFound="KeyNotFound",s.KeyExpired="KeyExpired",s.SignerNotFound="SignerNotFound",s.ProofVerificationFailed="ProofVerificationFailed",s.AnswerIncorrect="AnswerIncorrect",s.ChallengeExpired="ChallengeExpired",s.TooManyAttempts="TooManyAttempts",s.OAuthError="OAuthError",s.AccessError="AccessError";})(J5||(J5={}));var z5;(function(s){s[s.WebrpcEndpoint=0]="WebrpcEndpoint",s[s.WebrpcRequestFailed=-1]="WebrpcRequestFailed",s[s.WebrpcBadRoute=-2]="WebrpcBadRoute",s[s.WebrpcBadMethod=-3]="WebrpcBadMethod",s[s.WebrpcBadRequest=-4]="WebrpcBadRequest",s[s.WebrpcBadResponse=-5]="WebrpcBadResponse",s[s.WebrpcServerPanic=-6]="WebrpcServerPanic",s[s.WebrpcInternalError=-7]="WebrpcInternalError",s[s.WebrpcClientDisconnected=-8]="WebrpcClientDisconnected",s[s.WebrpcStreamLost=-9]="WebrpcStreamLost",s[s.WebrpcStreamFinished=-10]="WebrpcStreamFinished",s[s.InternalError=7100]="InternalError",s[s.EncryptionError=7101]="EncryptionError",s[s.DatabaseError=7102]="DatabaseError",s[s.DataIntegrityError=7103]="DataIntegrityError",s[s.IdentityProviderError=7104]="IdentityProviderError",s[s.InvalidRequest=7200]="InvalidRequest",s[s.InvalidSignature=7201]="InvalidSignature",s[s.KeyNotFound=7202]="KeyNotFound",s[s.KeyExpired=7203]="KeyExpired",s[s.SignerNotFound=7204]="SignerNotFound",s[s.ProofVerificationFailed=7002]="ProofVerificationFailed",s[s.AnswerIncorrect=7003]="AnswerIncorrect",s[s.ChallengeExpired=7004]="ChallengeExpired",s[s.TooManyAttempts=7005]="TooManyAttempts",s[s.OAuthError=7006]="OAuthError",s[s.AccessError=7007]="AccessError";})(z5||(z5={}));var KR={0:Uv,[-1]:Lc,[-2]:Lv,[-3]:jv,[-4]:Hv,[-5]:Ng,[-6]:_v,[-7]:Mv,[-8]:$v,[-9]:qv,[-10]:Fv,7100:Kv,7101:Gv,7102:Wv,7103:Jv,7104:zv,7200:Yv,7201:Zv,7202:Qv,7203:Xv,7204:ex,7002:tx,7003:sx,7004:nx,7005:rx,7006:ix,7007:ax};var va=class extends Error{};va.prototype.name="InvalidTokenError";function GR(s){return decodeURIComponent(atob(s).replace(/(.)/g,(e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n}))}function WR(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return GR(e)}catch{return atob(e)}}function Z5(s,e){if(typeof s!="string")throw new va("Invalid token specified: must be a string");e||(e={});let t=e.header===!0?0:1,n=s.split(".")[t];if(typeof n!="string")throw new va(`Invalid token specified: missing part #${t+1}`);let r;try{r=WR(n);}catch(i){throw new va(`Invalid token specified: invalid base64 for part #${t+1} (${i.message})`)}try{return JSON.parse(r)}catch(i){throw new va(`Invalid token specified: invalid json for part #${t+1} (${i.message})`)}}var ox=class{},kg=class extends ox{issuer;audience;idToken;handle="";exp="";constructor(e,t,n){super(),this.issuer=e,this.audience=t,this.idToken=n;let r=Z5(this.idToken),i=oe.keccak256(new TextEncoder().encode(this.idToken));this.handle=E.fromBytes(i),this.exp=r.exp?.toString()??"";}getCommitParams(){return {authMode:jc.IDToken,identityType:_n.OIDC,handle:this.handle,metadata:{iss:this.issuer,aud:this.audience,exp:this.exp}}}getCompleteParams(){return {authMode:jc.IDToken,identityType:_n.OIDC,verifier:this.handle,answer:this.idToken}}};var Wh=class{scope;rpc;constructor(e,t,n=window.fetch){this.rpc=new Cg(e.endsWith("/")?e.slice(0,-1):e,n),this.scope=t;}async commitVerifier(e,t){let n={...t.getCommitParams(),scope:this.scope},r=await e.sign(f.fromString(Ig(n)));return this.rpc.commitVerifier({params:n,authKey:{address:e.address,keyType:e.keyType},signature:r})}async completeAuth(e,t){let n={...t.getCompleteParams(),signerType:ln.Ethereum_Secp256k1,scope:this.scope},r=await e.sign(f.fromString(Ig(n)));return this.rpc.completeAuth({params:n,authKey:{address:e.address,keyType:e.keyType},signature:r})}async sign(e,t){let n={scope:this.scope,signer:{address:e.signer,keyType:ln.Ethereum_Secp256k1},digest:E.fromBytes(t),nonce:E.fromNumber(Date.now())},r=await this.rpc.sign({params:n,authKey:{address:e.address,keyType:e.keyType},signature:await e.sign(f.fromString(Ig(n)))});return E.assert(r.signature),r.signature}};function cx(s){return {address:s.address,keyType:ln.WebCrypto_Secp256r1,signer:s.identitySigner,async sign(e){let t=await window.crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},s.privateKey,new Uint8Array(e));return E.fromBytes(new Uint8Array(t))}}}var Pg=class{identityInstrument;authKey;constructor(e,t){this.identityInstrument=e,this.authKey=t;}get address(){if(!B.validate(this.authKey.identitySigner))throw new Error("No signer address found");return B.checksum(this.authKey.identitySigner)}async sign(e,t,n){let r=ce.hash(e,t,n);return this.signDigest(r)}async signDigest(e){let t=await this.identityInstrument.sign(cx(this.authKey),e);return {type:"hash",...At.fromHex(t)}}async witness(e,t,n){let r=ce.fromMessage(E.fromString(JSON.stringify({action:"consent-to-be-part-of-wallet",wallet:t,signer:this.address,timestamp:Date.now(),...n}))),i=await this.sign(t,0,r);await e.saveWitnesses(t,0,r,{type:"unrecovered-signer",weight:1n,signature:i});}};function Q5(s){return typeof s=="object"&&"signature"in s&&"imageHash"in s}var Hc={};be(Hc,{Cached:()=>kx,Local:()=>Ix,Remote:()=>Nx,Sequence:()=>Xh,getWalletsFor:()=>sV,multiplex:()=>mV,normalizeAddressKeys:()=>hn});var Ix={};be(Ix,{IndexedDbStore:()=>Ex,MemoryStore:()=>zh,Provider:()=>Ax});var zh=class{configs=new Map;counterfactualWallets=new Map;payloads=new Map;signerSubdigests=new Map;signatures=new Map;sapientSignerSubdigests=new Map;sapientSignatures=new Map;trees=new Map;deepCopy(e){if(typeof structuredClone=="function")return structuredClone(e);if(e===null||typeof e!="object")return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))return e.map(n=>this.deepCopy(n));if(e instanceof Map)return new Map(Array.from(e,([n,r])=>[this.deepCopy(n),this.deepCopy(r)]));if(e instanceof Set)return new Set(Array.from(e,n=>this.deepCopy(n)));let t={};for(let[n,r]of Object.entries(e))t[n]=this.deepCopy(r);return t}getSignatureKey(e,t){return `${e.toLowerCase()}-${t.toLowerCase()}`}getSapientSignatureKey(e,t,n){return `${e.toLowerCase()}-${n.toLowerCase()}-${t.toLowerCase()}`}async loadConfig(e){let t=this.configs.get(e.toLowerCase());return t?this.deepCopy(t):void 0}async saveConfig(e,t){this.configs.set(e.toLowerCase(),this.deepCopy(t));}async loadCounterfactualWallet(e){let t=this.counterfactualWallets.get(e.toLowerCase());return t?this.deepCopy(t):void 0}async saveCounterfactualWallet(e,t,n){this.counterfactualWallets.set(e.toLowerCase(),this.deepCopy({imageHash:t,context:n}));}async loadPayloadOfSubdigest(e){let t=this.payloads.get(e.toLowerCase());return t?this.deepCopy(t):void 0}async savePayloadOfSubdigest(e,t){this.payloads.set(e.toLowerCase(),this.deepCopy(t));}async loadSubdigestsOfSigner(e){let t=this.signerSubdigests.get(e.toLowerCase());return t?Array.from(t).map(n=>n):[]}async loadSignatureOfSubdigest(e,t){let n=this.getSignatureKey(e,t),r=this.signatures.get(n);return r?this.deepCopy(r):void 0}async saveSignatureOfSubdigest(e,t,n){let r=this.getSignatureKey(e,t);this.signatures.set(r,this.deepCopy(n));let i=e.toLowerCase(),a=t.toLowerCase();this.signerSubdigests.has(i)||this.signerSubdigests.set(i,new Set),this.signerSubdigests.get(i).add(a);}async loadSubdigestsOfSapientSigner(e,t){let n=`${e.toLowerCase()}-${t.toLowerCase()}`,r=this.sapientSignerSubdigests.get(n);return r?Array.from(r).map(i=>i):[]}async loadSapientSignatureOfSubdigest(e,t,n){let r=this.getSapientSignatureKey(e,t,n),i=this.sapientSignatures.get(r);return i?this.deepCopy(i):void 0}async saveSapientSignatureOfSubdigest(e,t,n,r){let i=this.getSapientSignatureKey(e,t,n);this.sapientSignatures.set(i,this.deepCopy(r));let a=`${e.toLowerCase()}-${n.toLowerCase()}`,o=t.toLowerCase();this.sapientSignerSubdigests.has(a)||this.sapientSignerSubdigests.set(a,new Set),this.sapientSignerSubdigests.get(a).add(o);}async loadTree(e){let t=this.trees.get(e.toLowerCase());return t?this.deepCopy(t):void 0}async saveTree(e,t){this.trees.set(e.toLowerCase(),this.deepCopy(t));}};var Ks={};be(Ks,{Guard:()=>vx,Passkey:()=>mx,Pk:()=>fx,Session:()=>wx,SessionManager:()=>bx,isSapientSigner:()=>xx,isSigner:()=>tV});var fx={};be(fx,{Encrypted:()=>lx,MemoryPkStore:()=>Rr,Pk:()=>hx});var lx={};be(lx,{EncryptedPkStore:()=>Tg,EncryptedPksDb:()=>ux});var ux=class{localStorageKeyPrefix;tableName;dbName="pk-db";dbVersion=1;constructor(e="e_pk_key_",t="e_pk"){this.localStorageKeyPrefix=e,this.tableName=t;}computeDbKey(e){return `pk_${e.toLowerCase()}`}openDB(){return new Promise((e,t)=>{let n=indexedDB.open(this.dbName,this.dbVersion);n.onupgradeneeded=()=>{let r=n.result;r.objectStoreNames.contains(this.tableName)||r.createObjectStore(this.tableName);},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error);})}async putData(e,t){let n=await this.openDB();return new Promise((r,i)=>{let c=n.transaction(this.tableName,"readwrite").objectStore(this.tableName).put(t,e);c.onsuccess=()=>r(),c.onerror=()=>i(c.error);})}async getData(e){let t=await this.openDB();return new Promise((n,r)=>{let o=t.transaction(this.tableName,"readonly").objectStore(this.tableName).get(e);o.onsuccess=()=>n(o.result),o.onerror=()=>r(o.error);})}async getAllData(){let e=await this.openDB();return new Promise((t,n)=>{let a=e.transaction(this.tableName,"readonly").objectStore(this.tableName).getAll();a.onsuccess=()=>t(a.result),a.onerror=()=>n(a.error);})}async generateAndStore(){let e=await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),t=E.random(32),n=Ot.getPublicKey({privateKey:t}),r=B.fromPublicKey(n),i=this.localStorageKeyPrefix+r,a=await window.crypto.subtle.exportKey("jwk",e);window.localStorage.setItem(i,JSON.stringify(a));let c=new TextEncoder().encode(t),u=window.crypto.getRandomValues(new Uint8Array(12)),l=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:u},e,c),h={iv:u,data:l,keyPointer:i,address:r,publicKey:n},m=this.computeDbKey(r);return await this.putData(m,h),h}async getEncryptedEntry(e){let t=this.computeDbKey(e);return this.getData(t)}async getEncryptedPkStore(e){let t=await this.getEncryptedEntry(e);if(t)return new Tg(t)}async listAddresses(){return (await this.getAllData()).map(t=>t.address)}async remove(e){let t=this.computeDbKey(e);await this.putData(t,void 0);let n=this.localStorageKeyPrefix+e;window.localStorage.removeItem(n);}},Tg=class{encrypted;constructor(e){this.encrypted=e;}address(){return this.encrypted.address}publicKey(){return this.encrypted.publicKey}async signDigest(e){let t=window.localStorage.getItem(this.encrypted.keyPointer);if(!t)throw new Error("Encryption key not found in localStorage");let n=JSON.parse(t),r=await window.crypto.subtle.importKey("jwk",n,{name:"AES-GCM"},!1,["decrypt"]),i=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:this.encrypted.iv},r,this.encrypted.data),o=new TextDecoder().decode(i);return Ot.sign({payload:e,privateKey:o})}};var Rr=class{privateKey;constructor(e){this.privateKey=e;}address(){return B.fromPublicKey(this.publicKey())}publicKey(){return Ot.getPublicKey({privateKey:this.privateKey})}signDigest(e){return Promise.resolve(Ot.sign({payload:e,privateKey:this.privateKey}))}},hx=class{privateKey;address;pubKey;constructor(e){this.privateKey=typeof e=="string"?new Rr(e):e,this.pubKey=this.privateKey.publicKey(),this.address=this.privateKey.address();}async sign(e,t,n){let r=ce.hash(e,t,n);return this.signDigest(r)}async signDigest(e){return {...await this.privateKey.signDigest(e),type:"hash"}}async witness(e,t,n){let r=ce.fromMessage(E.fromString(JSON.stringify({action:"consent-to-be-part-of-wallet",wallet:t,signer:this.address,timestamp:Date.now(),...n}))),i=await this.sign(t,0,r);await e.saveWitnesses(t,0,r,{type:"unrecovered-signer",weight:1n,signature:i});}};var mx={};be(mx,{Passkey:()=>dx,isWitnessMessage:()=>X5});function X5(s){return typeof s=="object"&&s!==null&&"action"in s&&s.action==="consent-to-be-part-of-wallet"}var dx=class s{credentialId;publicKey;address;imageHash;embedMetadata;metadata;constructor(e){this.address=e.extensions.passkeys,this.publicKey=e.publicKey,this.credentialId=e.credentialId,this.embedMetadata=e.embedMetadata??!1,this.imageHash=Ne.Passkeys.rootFor(e.publicKey),this.metadata=e.metadata;}static async loadFromWitness(e,t,n,r){let i=await e.getWitnessForSapient(n,t.passkeys,r);if(!i)throw new Error("Witness for wallet not found");let a=i.payload;if(!ce.isMessage(a))throw new Error("Witness payload is not a message");let o=JSON.parse(E.toString(a.message));if(!X5(o))throw new Error("Witness payload is not a witness message");let c=o.publicKey.metadata||o.metadata;if(typeof c=="string"||!c)throw new Error("Metadata does not contain credential id");let u=Ne.Passkeys.decode(f.fromHex(i.signature.data));return new s({credentialId:c.credentialId,extensions:t,publicKey:o.publicKey,embedMetadata:u.embedMetadata,metadata:c})}static async create(e,t){let n=t?.credentialName??`Sequence (${Date.now()})`,r=await Tr.createCredential({user:{name:n}}),i=E.fromNumber(r.publicKey.x),a=E.fromNumber(r.publicKey.y),o={credentialId:r.id},c=new s({credentialId:r.id,extensions:e,publicKey:{requireUserVerification:t?.requireUserVerification??!0,x:i,y:a,metadata:t?.embedMetadata?o:void 0},embedMetadata:t?.embedMetadata,metadata:o});return t?.stateProvider&&await t.stateProvider.saveTree(Ne.Passkeys.toTree(c.publicKey)),c}static async find(e,t){let n=await Tr.sign({challenge:E.random(32)});if(!n.raw)throw new Error("No credential returned");let r=f.fromHex(n.metadata.authenticatorData),i=oe.sha256(f.fromString(n.metadata.clientDataJSON),{as:"Bytes"}),a=f.concat(r,i),o=oe.sha256(a,{as:"Bytes"}),c=Nc.recoverPublicKey({payload:o,signature:{r:BigInt(n.signature.r),s:BigInt(n.signature.s),yParity:0}}),u=Nc.recoverPublicKey({payload:o,signature:{r:BigInt(n.signature.r),s:BigInt(n.signature.s),yParity:1}}),l={x:E.fromNumber(c.x),y:E.fromNumber(c.y)},h={x:E.fromNumber(u.x),y:E.fromNumber(u.y)},m={credentialId:n.raw.id},y=[Ne.Passkeys.rootFor({...l,requireUserVerification:!0}),Ne.Passkeys.rootFor({...l,requireUserVerification:!1}),Ne.Passkeys.rootFor({...l,requireUserVerification:!0,metadata:m}),Ne.Passkeys.rootFor({...l,requireUserVerification:!1,metadata:m}),Ne.Passkeys.rootFor({...h,requireUserVerification:!0}),Ne.Passkeys.rootFor({...h,requireUserVerification:!1}),Ne.Passkeys.rootFor({...h,requireUserVerification:!0,metadata:m}),Ne.Passkeys.rootFor({...h,requireUserVerification:!1,metadata:m})],w=(await Promise.all(y.map(async S=>{let C=await e.getWalletsForSapient(t.passkeys,S);return Object.keys(C).map(k=>({wallet:B.from(k),imageHash:S}))}))).flat().filter((S,C,k)=>k.findIndex(x=>B.isEqual(x.wallet,S.wallet)&&x.imageHash===S.imageHash)===C);if(w.length!==0)return w.length>1&&console.warn("Multiple signers found for passkey",w),s.loadFromWitness(e,t,w[0].wallet,w[0].imageHash)}async signSapient(e,t,n,r){if(this.imageHash!==r)throw new Error("Unexpected image hash");let i=E.fromBytes(ce.hash(e,t,n)),a=await Tr.sign({challenge:i,credentialId:this.credentialId,userVerification:this.publicKey.requireUserVerification?"required":"discouraged"}),o=f.fromHex(a.metadata.authenticatorData),c=f.fromNumber(a.signature.r),u=f.fromNumber(a.signature.s),l=Ne.Passkeys.encode({publicKey:this.publicKey,r:c,s:u,authenticatorData:o,clientDataJSON:a.metadata.clientDataJSON,embedMetadata:this.embedMetadata});return {address:this.address,data:f.toHex(l),type:"sapient_compact"}}async witness(e,t,n){let r=ce.fromMessage(E.fromString(JSON.stringify({action:"consent-to-be-part-of-wallet",wallet:t,publicKey:this.publicKey,metadata:this.metadata,timestamp:Date.now(),...n}))),i=await this.signSapient(t,0,r,this.imageHash);await e.saveWitnesses(t,0,r,{type:"unrecovered-signer",weight:1n,signature:i});}};var wx={};be(wx,{Explicit:()=>px,Implicit:()=>gx,isExplicitSessionSigner:()=>Bg,isImplicitSessionSigner:()=>yx});var e8="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",px=class{_privateKey;address;sessionPermissions;constructor(e,t){this._privateKey=typeof e=="string"?new Rr(e):e,this.address=this._privateKey.address(),this.sessionPermissions={...t,signer:this.address};}isValid(e,t){if(this.sessionPermissions.deadline<=BigInt(Math.floor(Date.now()/1e3)))return {isValid:!1,invalidReason:"Expired"};if(this.sessionPermissions.chainId!==0&&this.sessionPermissions.chainId!==t)return {isValid:!1,invalidReason:"Chain ID mismatch"};let n=Ns.getSessionPermissions(e,this.address);if(!n)return {isValid:!1,invalidReason:"Permission not found"};if(n.deadline!==this.sessionPermissions.deadline||n.chainId!==this.sessionPermissions.chainId||n.valueLimit!==this.sessionPermissions.valueLimit||n.permissions.length!==this.sessionPermissions.permissions.length)return {isValid:!1,invalidReason:"Permission mismatch"};for(let[r,i]of n.permissions.entries()){let a=this.sessionPermissions.permissions[r];if(!B.isEqual(i.target,a.target)||i.rules.length!==a.rules.length)return {isValid:!1,invalidReason:"Permission rule mismatch"};for(let[o,c]of i.rules.entries()){let u=a.rules[o];if(c.cumulative!==u.cumulative||c.operation!==u.operation||!f.isEqual(c.value,u.value)||c.offset!==u.offset||!f.isEqual(c.mask,u.mask))return {isValid:!1,invalidReason:"Permission rule mismatch"}}}return {isValid:!0}}async findSupportedPermission(e,t,n,r,i){if(!(this.sessionPermissions.chainId!==0&&this.sessionPermissions.chainId!==t)){if(n.value!==0n){if(!i)throw new Error("Value transaction validation requires a provider");let a=oe.keccak256(ot.encode([{type:"address",name:"signer"},{type:"address",name:"valueTrackingAddress"}],[this.address,e8])),{usageAmount:o}=await this.readCurrentUsageLimit(e,r,a,i),c=f.fromNumber(o+n.value,{size:32});if(f.toBigInt(c)>this.sessionPermissions.valueLimit)return}for(let a of this.sessionPermissions.permissions)if(await this.validatePermission(a,n,e,r,i))return a}}getPermissionUsageHash(e,t){let n={target:e.target,rules:e.rules.map(r=>({cumulative:r.cumulative,operation:r.operation,value:f.toHex(r.value),offset:r.offset,mask:f.toHex(r.mask)}))};return oe.keccak256(ot.encode([{type:"address",name:"signer"},Hn.permissionStructAbi,{type:"uint256",name:"ruleIndex"}],[this.address,n,BigInt(t)]))}getValueUsageHash(){return oe.keccak256(ot.encode([{type:"address",name:"signer"},{type:"address",name:"valueTrackingAddress"}],[this.address,e8]))}async validatePermission(e,t,n,r,i){if(!B.isEqual(e.target,t.to))return !1;for(let[a,o]of e.rules.entries()){let u=f.padRight(f.fromHex(t.data).slice(Number(o.offset),Number(o.offset)+32),32).map((l,h)=>l&o.mask[h]);if(o.cumulative)if(i){let{usageAmount:l}=await this.readCurrentUsageLimit(n,r,this.getPermissionUsageHash(e,a),i);u=f.fromNumber(l+f.toBigInt(u),{size:32});}else throw new Error("Cumulative rules require a provider");if(o.operation===Hn.ParameterOperation.EQUAL&&!f.isEqual(u,o.value)||o.operation===Hn.ParameterOperation.LESS_THAN_OR_EQUAL&&f.toBigInt(u)>f.toBigInt(o.value)||o.operation===Hn.ParameterOperation.NOT_EQUAL&&f.isEqual(u,o.value)||o.operation===Hn.ParameterOperation.GREATER_THAN_OR_EQUAL&&f.toBigInt(u)<f.toBigInt(o.value))return !1}return !0}async supportedCall(e,t,n,r,i){return B.isEqual(n.to,r)&&E.size(n.data)>4&&E.isEqual(E.slice(n.data,0,4),se.getSelector(_e.INCREMENT_USAGE_LIMIT))?!0:!!await this.findSupportedPermission(e,t,n,r,i)}async signCall(e,t,n,r,i,a){let o=n.calls[r],c;if(B.isEqual(o.to,i)&&E.size(o.data)>4&&E.isEqual(E.slice(o.data,0,4),se.getSelector(_e.INCREMENT_USAGE_LIMIT)))c=0;else {let h=await this.findSupportedPermission(e,t,o,i,a);if(!h)throw new Error("Invalid permission");if(c=this.sessionPermissions.permissions.indexOf(h),c===-1)throw new Error("Invalid permission")}let u=Or.hashPayloadWithCallIdx(e,n,r,t,i),l=await this._privateKey.signDigest(f.fromHex(u));return {permissionIndex:BigInt(c),sessionSignature:l}}async readCurrentUsageLimit(e,t,n,r){let i=se.encodeData(_e.GET_LIMIT_USAGE,[e,n]),a=await r.request({method:"eth_call",params:[{to:t,data:i},"latest"]}),o=se.decodeResult(_e.GET_LIMIT_USAGE,a);return {usageHash:n,usageAmount:o}}async prepareIncrements(e,t,n,r,i){let a=[],o=this.getValueUsageHash(),u=(await this.readCurrentUsageLimit(e,r,o,i)).usageAmount;for(let h of n){let m=await this.findSupportedPermission(e,t,h,r,i);if(m){for(let[y,g]of m.rules.entries()){if(!g.cumulative)continue;let S=f.padRight(f.fromHex(h.data).slice(Number(g.offset),Number(g.offset)+32),32).map((x,v)=>x&g.mask[v]);if(f.toBigInt(S)===0n)continue;let C=this.getPermissionUsageHash(m,y),k=a.find(x=>E.isEqual(x.usageHash,C));k?k.increment+=f.toBigInt(S):a.push({usageHash:C,increment:f.toBigInt(S)});}u+=h.value;}}if(a.length===0&&u===0n)return [];let l=await Promise.all(a.map(async({usageHash:h,increment:m})=>{if(m===0n)return null;let y=await this.readCurrentUsageLimit(e,r,h,i);if(E.isEqual(h,o)&&y.usageAmount+m>this.sessionPermissions.valueLimit)throw new Error("Value transaction validation failed");return {usageHash:h,usageAmount:y.usageAmount+m}})).then(h=>h.filter(m=>m!==null));return u>0n&&l.push({usageHash:o,usageAmount:u}),l}};var gx=class{_attestation;_sessionManager;_privateKey;_identitySignature;address;constructor(e,t,n,r){if(this._attestation=t,this._sessionManager=r,this._privateKey=typeof e=="string"?new Rr(e):e,this.address=this._privateKey.address(),this._attestation.approvedSigner!==this.address)throw new Error("Invalid attestation");if(this._attestation.authData.issuedAt>BigInt(Math.floor(Date.now()/1e3)))throw new Error("Attestation issued in the future");this._identitySignature=typeof n=="string"?At.fromHex(n):n;}get identitySigner(){let e=It.hash(this._attestation),t=Ot.recoverPublicKey({payload:e,signature:this._identitySignature});return B.fromPublicKey(t)}isValid(e,t){let n=Ns.getIdentitySigners(e),r=this.identitySigner;return n.some(a=>B.isEqual(a,r))?Ns.getImplicitBlacklist(e)?.some(a=>B.isEqual(a,this.address))?{isValid:!1,invalidReason:"Blacklisted"}:{isValid:!0}:{isValid:!1,invalidReason:"Identity signer not found"}}async supportedCall(e,t,n,r,i){if(!i)throw new Error("Provider is required");try{let a=se.encodeData(t8,[e,{approvedSigner:this._attestation.approvedSigner,identityType:f.toHex(this._attestation.identityType),issuerHash:f.toHex(this._attestation.issuerHash),audienceHash:f.toHex(this._attestation.audienceHash),applicationData:f.toHex(this._attestation.applicationData),authData:this._attestation.authData},{to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,delegateCall:n.delegateCall,onlyFallback:n.onlyFallback,behaviorOnError:BigInt(ce.encodeBehaviorOnError(n.behaviorOnError))}]),o=await i.request({method:"eth_call",params:[{from:this._sessionManager,to:n.to,data:a},"latest"]}),c=E.from(se.decodeResult(t8,o)),u=f.toHex(It.generateImplicitRequestMagic(this._attestation,e));return c===u}catch{return !1}}async signCall(e,t,n,r,i,a){let o=n.calls[r];if(!await this.supportedCall(e,t,o,i,a))throw new Error("Unsupported call");let u=Or.hashPayloadWithCallIdx(e,n,r,t,i),l=await this._privateKey.signDigest(f.fromHex(u));return {attestation:this._attestation,identitySignature:this._identitySignature,sessionSignature:l}}},t8={type:"function",name:"acceptImplicitRequest",inputs:[{name:"wallet",type:"address",internalType:"address"},{name:"attestation",type:"tuple",internalType:"struct Attestation",components:[{name:"approvedSigner",type:"address",internalType:"address"},{name:"identityType",type:"bytes4",internalType:"bytes4"},{name:"issuerHash",type:"bytes32",internalType:"bytes32"},{name:"audienceHash",type:"bytes32",internalType:"bytes32"},{name:"applicationData",type:"bytes",internalType:"bytes"},{internalType:"struct AuthData",name:"authData",type:"tuple",components:[{internalType:"string",name:"redirectUrl",type:"string"},{internalType:"uint64",name:"issuedAt",type:"uint64"}]}]},{name:"call",type:"tuple",internalType:"struct Payload.Call",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"},{name:"gasLimit",type:"uint256",internalType:"uint256"},{name:"delegateCall",type:"bool",internalType:"bool"},{name:"onlyFallback",type:"bool",internalType:"bool"},{name:"behaviorOnError",type:"uint256",internalType:"uint256"}]}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"};function Bg(s){return "prepareIncrements"in s}function yx(s){return "identitySigner"in s}var JR=2n**80n-1n,bx=class s{wallet;stateProvider;address;_implicitSigners;_explicitSigners;_provider;constructor(e,t){this.wallet=e,this.stateProvider=t.stateProvider??e.stateProvider,this.address=t.sessionManagerAddress,this._implicitSigners=t.implicitSigners??[],this._explicitSigners=t.explicitSigners??[],this._provider=t.provider;}get imageHash(){return this.getImageHash()}async getImageHash(){let{configuration:e}=await this.wallet.getStatus(),t=Pe.findSignerLeaf(e,this.address);if(!(!t||!Pe.isSapientSignerLeaf(t)))return t.imageHash}get topology(){return this.getTopology()}async getTopology(){let e=await this.imageHash;if(!e)throw new Error(`Session configuration not found for image hash ${e}`);let t=await this.stateProvider.getTree(e);if(!t)throw new Error(`Session configuration not found for image hash ${e}`);return Ns.configurationTreeToSessionsTopology(t)}withProvider(e){return new s(this.wallet,{sessionManagerAddress:this.address,stateProvider:this.stateProvider,implicitSigners:this._implicitSigners,explicitSigners:this._explicitSigners,provider:e})}withImplicitSigner(e){let t=[...this._implicitSigners,e];return new s(this.wallet,{sessionManagerAddress:this.address,stateProvider:this.stateProvider,implicitSigners:t,explicitSigners:this._explicitSigners,provider:this._provider})}withExplicitSigner(e){let t=[...this._explicitSigners,e];return new s(this.wallet,{sessionManagerAddress:this.address,stateProvider:this.stateProvider,implicitSigners:this._implicitSigners,explicitSigners:t,provider:this._provider})}async listSignerValidity(e){let t=await this.topology,n=new Map;for(let r of this._implicitSigners)n.set(r.address,r.isValid(t,e));for(let r of this._explicitSigners)n.set(r.address,r.isValid(t,e));return Array.from(n.entries()).map(([r,{isValid:i,invalidReason:a}])=>({signer:r,isValid:i,invalidReason:a}))}async findSignersForCalls(e,t,n){let r=await this.topology;if(Ns.getIdentitySigners(r).length===0)throw new Error("Identity signers not found");let a=[...this._implicitSigners,...this._explicitSigners];if(a.length===0)throw new Error("No signers match the topology");let o=[];for(let c of n){let u=!1,l;for(let h of a){try{if(u=await h.supportedCall(e,t,c,this.address,this._provider),u){let m=h.isValid(r,t);m.invalidReason==="Expired"&&(l=h),u=m.isValid;}}catch(m){console.error("findSignersForCalls error",m);continue}if(u){o.push(h);break}}if(!u)throw l?new Error(`Signer supporting call is expired: ${l.address}`):new Error(`No signer supported for call. Call: to=${c.to}, data=${c.data}, value=${c.value}, `)}return o}async prepareIncrement(e,t,n){if(n.length===0)throw new Error("No calls provided");let r=await this.findSignersForCalls(e,t,n),i=new Map;r.forEach((u,l)=>{let h=n[l],m=i.get(u)||[];i.set(u,[...m,h]);});let a=(await Promise.all(Array.from(i.entries()).map(async([u,l])=>Bg(u)?u.prepareIncrements(e,t,l,this.address,this._provider):[]))).flat();if(a.length===0)return null;if(a.filter((u,l,h)=>l===h.findIndex(m=>m.usageHash===u.usageHash)).length!==a.length)throw new Error("Repeated usage hashes");let c=se.encodeData(_e.INCREMENT_USAGE_LIMIT,[a]);return {to:this.address,data:c,value:0n,delegateCall:!1,onlyFallback:!1,behaviorOnError:"revert",gasLimit:0n}}async signSapient(e,t,n,r){if(!B.isEqual(e,this.wallet.address))throw new Error("Wallet address mismatch");if(await this.imageHash!==r)throw new Error("Unexpected image hash");if(!ce.isCalls(n)||n.calls.length===0)throw new Error("Only calls are supported");if(n.space>JR)throw new Error(`Space ${n.space} is too large`);let i=await this.findSignersForCalls(e,t,n.calls);if(i.length!==n.calls.length)throw new Error("No signer supported for call");let a=await Promise.all(i.map(async(m,y)=>{try{return m.signCall(e,t,n,y,this.address,this._provider)}catch(g){throw console.error("signSapient error",g),g}})),o=await this.prepareIncrement(e,t,n.calls);if(o){let m;if(B.isEqual(this.address,Ne.Dev1.sessions)||B.isEqual(this.address,Ne.Dev2.sessions)?m=n.calls[n.calls.length-1]:m=n.calls[0],!B.isEqual(o.to,m.to)||!E.isEqual(o.data,m.data))throw new Error("Actual increment call does not match expected increment call")}let c=[],u=[],l;if(await Promise.all(i.map(async m=>{let y=await m.address;if(Bg(m))c.find(g=>B.isEqual(g,y))||c.push(y);else if(yx(m)&&!u.find(g=>B.isEqual(g,y))){if(u.push(y),!l)l=m.identitySigner;else if(!B.isEqual(l,m.identitySigner))throw new Error("Multiple implicit signers with different identity signers")}})),!l){let m=Ns.getIdentitySigners(await this.topology);if(m.length===0)throw new Error("No identity signers found");l=m[0];}let h=Or.encodeSessionSignature(a,await this.topology,l,c,u);return {type:"sapient",address:this.address,data:E.from(h)}}async isValidSapientSignature(e,t,n,r){if(!ce.isCalls(n))return !1;if(!this._provider)throw new Error("Provider not set");let i=ce.encodeSapient(t,n),a=se.encodeData(_e.RECOVER_SAPIENT_SIGNATURE,[i,r.data]);try{let o=await this._provider.request({method:"eth_call",params:[{from:e,to:this.address,data:a},"pending"]});return E.from(se.decodeResult(_e.RECOVER_SAPIENT_SIGNATURE,o))===await this.imageHash}catch(o){return console.error("recoverSapientSignature error",o),!1}}};var Vr;(function(s){s.Calls="Calls",s.Message="Message",s.ConfigUpdate="ConfigUpdate",s.SessionImplicitAuthorize="SessionImplicitAuthorize";})(Vr||(Vr={}));var Dr;(function(s){s.Hash="Hash",s.Sapient="Sapient",s.EthSign="EthSign",s.Erc1271="Erc1271";})(Dr||(Dr={}));var s8;(function(s){s.WebrpcEndpoint="WebrpcEndpoint",s.WebrpcRequestFailed="WebrpcRequestFailed",s.WebrpcBadRoute="WebrpcBadRoute",s.WebrpcBadMethod="WebrpcBadMethod",s.WebrpcBadRequest="WebrpcBadRequest",s.WebrpcBadResponse="WebrpcBadResponse",s.WebrpcServerPanic="WebrpcServerPanic",s.WebrpcInternalError="WebrpcInternalError",s.WebrpcClientDisconnected="WebrpcClientDisconnected",s.WebrpcStreamLost="WebrpcStreamLost",s.WebrpcStreamFinished="WebrpcStreamFinished",s.Unauthorized="Unauthorized",s.PermissionDenied="PermissionDenied",s.SessionExpired="SessionExpired",s.MethodNotFound="MethodNotFound",s.RequestConflict="RequestConflict",s.Aborted="Aborted",s.Geoblocked="Geoblocked",s.RateLimited="RateLimited",s.InvalidArgument="InvalidArgument",s.Unavailable="Unavailable",s.QueryFailed="QueryFailed",s.ValidationFailed="ValidationFailed",s.NotFound="NotFound",s.RequiresTOTP="RequiresTOTP",s.RequiresPIN="RequiresPIN";})(s8||(s8={}));var n8;(function(s){s[s.WebrpcEndpoint=0]="WebrpcEndpoint",s[s.WebrpcRequestFailed=-1]="WebrpcRequestFailed",s[s.WebrpcBadRoute=-2]="WebrpcBadRoute",s[s.WebrpcBadMethod=-3]="WebrpcBadMethod",s[s.WebrpcBadRequest=-4]="WebrpcBadRequest",s[s.WebrpcBadResponse=-5]="WebrpcBadResponse",s[s.WebrpcServerPanic=-6]="WebrpcServerPanic",s[s.WebrpcInternalError=-7]="WebrpcInternalError",s[s.WebrpcClientDisconnected=-8]="WebrpcClientDisconnected",s[s.WebrpcStreamLost=-9]="WebrpcStreamLost",s[s.WebrpcStreamFinished=-10]="WebrpcStreamFinished",s[s.Unauthorized=1e3]="Unauthorized",s[s.PermissionDenied=1001]="PermissionDenied",s[s.SessionExpired=1002]="SessionExpired",s[s.MethodNotFound=1003]="MethodNotFound",s[s.RequestConflict=1004]="RequestConflict",s[s.Aborted=1005]="Aborted",s[s.Geoblocked=1006]="Geoblocked",s[s.RateLimited=1007]="RateLimited",s[s.InvalidArgument=2001]="InvalidArgument",s[s.Unavailable=2002]="Unavailable",s[s.QueryFailed=2003]="QueryFailed",s[s.ValidationFailed=2004]="ValidationFailed",s[s.NotFound=3e3]="NotFound",s[s.RequiresTOTP=6600]="RequiresTOTP",s[s.RequiresPIN=6601]="RequiresPIN";})(n8||(n8={}));var vx=class{guard;address;constructor(e){this.guard=e,this.address=this.guard.address;}async signEnvelope(e,t){let n={...e.payload,parentWallets:void 0},r=QR(e.payload),{message:i,digest:a}=XR(e.wallet,e.chainId,n),o=e.signatures.map(eV),c=await this.guard.signPayload(e.wallet,e.chainId,r,a,i,o,t?{id:t.id,token:t.code,resetAuth:t.resetAuth}:void 0);return {address:this.guard.address,signature:{type:"hash",...c}}}};function QR(s){switch(s.type){case"call":return Vr.Calls;case"message":return Vr.Message;case"config-update":return Vr.ConfigUpdate;case"session-implicit-authorize":return Vr.SessionImplicitAuthorize}throw new Error(`Payload type not supported by Guard: ${s.type}`)}function XR(s,e,t){if(ce.isSessionImplicitAuthorize(t))return {message:f.fromString(It.toJson(t.attestation)),digest:oe.keccak256(It.encode(t.attestation))};let n=ce.toTyped(s,e,t);return {message:f.fromString(Th.serialize(n)),digest:f.fromHex(Th.getSignPayload(n))}}function eV(s){if(Q5(s))return {type:Dr.Sapient,address:s.signature.address,imageHash:s.imageHash,data:s.signature.data};if(s.signature.type=="erc1271")return {type:Dr.Erc1271,address:s.signature.address,data:s.signature.data};let e={eth_sign:Dr.EthSign,hash:Dr.Hash}[s.signature.type];if(!e)throw new Error(`Signature type not supported by Guard: ${s.signature.type}`);return {type:e,address:s.address,data:At.toHex(s.signature)}}function xx(s){return "signSapient"in s}function tV(s){return "sign"in s}async function sV(s,e){let t=await nV(s,e);return Object.entries(t).map(([n,{chainId:r,payload:i,signature:a}])=>(E.assert(n),{wallet:n,chainId:r,payload:i,signature:a}))}async function nV(s,e){if(xx(e)){let[t,n]=await Promise.all([e.address,e.imageHash]);return n?s.getWalletsForSapient(t,n):(console.warn("Sapient signer has no imageHash"),{})}else return s.getWallets(await e.address)}function hn(s){return Object.fromEntries(Object.entries(s).map(([e,t])=>[B.checksum(e),t]))}var Og="configs",Rg="counterfactualWallets",Vg="payloads",Yh="signerSubdigests",Dg="signatures",Zh="sapientSignerSubdigests",Ug="sapientSignatures",Lg="trees",Ex=class{_db=null;dbName;constructor(e="sequence-indexeddb"){this.dbName=e;}async openDB(){return this._db?this._db:new Promise((e,t)=>{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let r=n.result;r.objectStoreNames.contains(Og)||r.createObjectStore(Og),r.objectStoreNames.contains(Rg)||r.createObjectStore(Rg),r.objectStoreNames.contains(Vg)||r.createObjectStore(Vg),r.objectStoreNames.contains(Yh)||r.createObjectStore(Yh),r.objectStoreNames.contains(Dg)||r.createObjectStore(Dg),r.objectStoreNames.contains(Zh)||r.createObjectStore(Zh),r.objectStoreNames.contains(Ug)||r.createObjectStore(Ug),r.objectStoreNames.contains(Lg)||r.createObjectStore(Lg);},n.onsuccess=()=>{this._db=n.result,e(this._db);},n.onerror=()=>{t(n.error);};})}async get(e,t){let n=await this.openDB();return new Promise((r,i)=>{let c=n.transaction(e,"readonly").objectStore(e).get(t);c.onsuccess=()=>r(c.result),c.onerror=()=>i(c.error);})}async put(e,t,n){let r=await this.openDB();return new Promise((i,a)=>{let u=r.transaction(e,"readwrite").objectStore(e).put(n,t);u.onsuccess=()=>i(),u.onerror=()=>a(u.error);})}async getSet(e,t){let n=await this.get(e,t)||new Set;return Array.isArray(n)?new Set(n):n}async putSet(e,t,n){await this.put(e,t,Array.from(n));}getSignatureKey(e,t){return `${e.toLowerCase()}-${t.toLowerCase()}`}getSapientSignatureKey(e,t,n){return `${e.toLowerCase()}-${n.toLowerCase()}-${t.toLowerCase()}`}async loadConfig(e){return this.get(Og,e.toLowerCase())}async saveConfig(e,t){await this.put(Og,e.toLowerCase(),t);}async loadCounterfactualWallet(e){return this.get(Rg,e.toLowerCase())}async saveCounterfactualWallet(e,t,n){await this.put(Rg,e.toLowerCase(),{imageHash:t,context:n});}async loadPayloadOfSubdigest(e){return this.get(Vg,e.toLowerCase())}async savePayloadOfSubdigest(e,t){await this.put(Vg,e.toLowerCase(),t);}async loadSubdigestsOfSigner(e){let t=await this.getSet(Yh,e.toLowerCase());return Array.from(t)}async loadSignatureOfSubdigest(e,t){let n=this.getSignatureKey(e,t);return this.get(Dg,n.toLowerCase())}async saveSignatureOfSubdigest(e,t,n){let r=this.getSignatureKey(e,t);await this.put(Dg,r.toLowerCase(),n);let i=e.toLowerCase(),a=t.toLowerCase(),o=await this.getSet(Yh,i);o.add(a),await this.putSet(Yh,i,o);}async loadSubdigestsOfSapientSigner(e,t){let n=`${e.toLowerCase()}-${t.toLowerCase()}`,r=await this.getSet(Zh,n);return Array.from(r)}async loadSapientSignatureOfSubdigest(e,t,n){let r=this.getSapientSignatureKey(e,t,n);return this.get(Ug,r.toLowerCase())}async saveSapientSignatureOfSubdigest(e,t,n,r){let i=this.getSapientSignatureKey(e,t,n).toLowerCase();await this.put(Ug,i,r);let a=`${e.toLowerCase()}-${n.toLowerCase()}`,o=t.toLowerCase(),c=await this.getSet(Zh,a);c.add(o),await this.putSet(Zh,a,c);}async loadTree(e){return this.get(Lg,e.toLowerCase())}async saveTree(e,t){await this.put(Lg,e.toLowerCase(),t);}};var Ax=class{store;extensions;constructor(e=new zh,t=Ne.Rc5){this.store=e,this.extensions=t;}getConfiguration(e){return this.store.loadConfig(e)}async saveWallet(e,t){await this.saveConfig(e);let n=Pe.hashConfiguration(e);await this.saveCounterfactualWallet(Vc.from(n,t),E.fromBytes(n),t);}async saveConfig(e){let t=f.toHex(Pe.hashConfiguration(e)),n=await this.store.loadConfig(t);if(n){let r=Pe.mergeTopology(n.topology,e.topology);return this.store.saveConfig(t,{...n,topology:r})}else return this.store.saveConfig(t,e)}saveCounterfactualWallet(e,t,n){this.store.saveCounterfactualWallet(e,t,n);}getDeploy(e){return this.store.loadCounterfactualWallet(e)}async getWalletsGeneric(e,t){let n=await Promise.all(e.map(i=>this.store.loadPayloadOfSubdigest(i))),r={};for(let i of n){if(!i)continue;let a=B.checksum(i.wallet);if(r[a])continue;let o=E.fromBytes(ce.hash(a,i.chainId,i.content)),c=await t(o);c&&(r[a]={chainId:i.chainId,payload:i.content,signature:c});}return r}async getWallets(e){return hn(await this.getWalletsGeneric(await this.store.loadSubdigestsOfSigner(e),t=>this.store.loadSignatureOfSubdigest(e,t)))}async getWalletsForSapient(e,t){return hn(await this.getWalletsGeneric(await this.store.loadSubdigestsOfSapientSigner(e,t),n=>this.store.loadSapientSignatureOfSubdigest(e,n,t)))}getWitnessFor(e,t){let n=B.checksum(e);return this.getWallets(t).then(r=>r[n])}getWitnessForSapient(e,t,n){let r=B.checksum(e);return this.getWalletsForSapient(t,n).then(i=>i[r])}async saveWitnesses(e,t,n,r){let i=E.fromBytes(ce.hash(e,t,n));await Promise.all([this.saveSignature(i,r),this.store.savePayloadOfSubdigest(i,{content:n,chainId:t,wallet:e})]);}async getConfigurationUpdates(e,t,n){let r=await this.store.loadConfig(t);if(!r)return [];let{signers:i,sapientSigners:a}=Pe.getSigners(r),o=await Promise.all([...i.map(g=>this.store.loadSubdigestsOfSigner(g)),...a.map(g=>this.store.loadSubdigestsOfSapientSigner(g.address,g.imageHash))]),c=[...new Set(o.flat())],u=await Promise.all(c.map(g=>this.store.loadPayloadOfSubdigest(g))),l=await Promise.all(u.filter(g=>g?.content&&ce.isConfigUpdate(g.content)).map(async g=>({payload:g,nextImageHash:g.content.imageHash,config:await this.store.loadConfig(g.content.imageHash)}))),h,m=l.filter(g=>g.config&&g.config.checkpoint>r.checkpoint).sort((g,w)=>g.config.checkpoint>w.config.checkpoint?n?.allUpdates?1:-1:n?.allUpdates?-1:1);for(let g of m){if(h){if(n?.allUpdates){if(g.config.checkpoint<=h.checkpoint)continue}else if(g.config.checkpoint<=h.checkpoint)continue}let w=E.fromBytes(ce.hash(e,g.payload.chainId,g.payload.content)),S=await Promise.all([...i.map(async x=>({signer:x,signature:await this.store.loadSignatureOfSubdigest(x,w)})),...a.map(async x=>({signer:x.address,imageHash:x.imageHash,signature:await this.store.loadSapientSignatureOfSubdigest(x.address,w,x.imageHash)}))]),C=0n,k=Rt.fillLeaves(r.topology,x=>{if(Pe.isSapientSignerLeaf(x)){let I=S.find(({signer:D,imageHash:F})=>F&&B.isEqual(D,x.address)&&F===x.imageHash)?.signature;if(I)return C+=x.weight,I}let v=S.find(({signer:I})=>B.isEqual(I,x.address))?.signature;if(v)return C+=x.weight,v});C<r.threshold||(h={nextImageHash:g.nextImageHash,checkpoint:g.config.checkpoint,signature:{noChainId:!0,configuration:{threshold:r.threshold,checkpoint:r.checkpoint,topology:k}}});}if(!h)return [];let y=await this.getConfigurationUpdates(e,h.nextImageHash,{allUpdates:!0});return [{imageHash:h.nextImageHash,signature:h.signature},...y]}async saveUpdate(e,t,n){let i={type:"config-update",imageHash:f.toHex(Pe.hashConfiguration(t))},a=ce.hash(e,0,i);await this.store.savePayloadOfSubdigest(E.fromBytes(a),{content:i,chainId:0,wallet:e}),await this.saveConfig(t),await this.saveSignature(E.fromBytes(a),n.configuration.topology);}async saveSignature(e,t){if(Rt.isRawNode(t)){await Promise.all([this.saveSignature(e,t[0]),this.saveSignature(e,t[1])]);return}if(Rt.isRawNestedLeaf(t))return this.saveSignature(e,t.tree);if(Rt.isRawSignerLeaf(t)){let n=t.signature.type;if(n==="eth_sign"||n==="hash"){let r=Ot.recoverAddress({payload:n==="eth_sign"?Mp.getSignPayload(e):e,signature:t.signature});return this.store.saveSignatureOfSubdigest(r,e,t.signature)}if(Rt.isSignatureOfSapientSignerLeaf(t.signature))switch(t.signature.address.toLowerCase()){case this.extensions.passkeys.toLowerCase():let r=Ne.Passkeys.decode(f.fromHex(t.signature.data));if(!Ne.Passkeys.isValidSignature(e,r))throw new Error("Invalid passkey signature");return this.store.saveSapientSignatureOfSubdigest(t.signature.address,e,Ne.Passkeys.rootFor(r.publicKey),t.signature);default:throw new Error(`Unsupported sapient signer: ${t.signature.address}`)}}}getTree(e){return this.store.loadTree(e)}saveTree(e){return this.store.saveTree(Ss.hash(e),e)}saveConfiguration(e){return this.store.saveConfig(f.toHex(Pe.hashConfiguration(e)),e)}saveDeploy(e,t){return this.store.saveCounterfactualWallet(Vc.from(f.fromHex(e),t),e,t)}async getPayload(e){let t=await this.store.loadPayloadOfSubdigest(e);return t?{chainId:t.chainId,payload:t.content,wallet:t.wallet}:void 0}savePayload(e,t,n){let r=E.fromBytes(ce.hash(e,n,t));return this.store.savePayloadOfSubdigest(r,{content:t,chainId:n,wallet:e})}};var Nx={};be(Nx,{DevHttpProvider:()=>Cx});var Cx=class{baseUrl;constructor(e){this.baseUrl=e.endsWith("/")?e.slice(0,-1):e;}async request(e,t,n){let r=`${this.baseUrl}${t}`,i={method:e,headers:{}};n&&e==="POST"&&(i.headers={"Content-Type":"application/json"},i.body=ya.toJSON(n));let a;try{a=await fetch(r,i);}catch(o){throw console.error(`Network error during ${e} request to ${r}:`,o),o}if(!a.ok){let o={message:`HTTP error! Status: ${a.status}`};try{let c=await a.text(),u=await ya.fromJSON(c);o={...o,...u};}catch{try{let u=await a.text();o.body=u;}catch{}}throw console.error("HTTP Request Failed:",o),new Error(o.message||`Request failed for ${e} ${t} with status ${a.status}`)}try{if(a.status===204)return;if(a.status===201&&e==="POST"){if((await a.clone().text()).trim()==="")return;let l=await a.text();return await ya.fromJSON(l)}if((await a.clone().text()).trim()==="")return;{let u=await a.text();return await ya.fromJSON(u)}}catch(o){console.error(`Error processing response body for ${e} ${r}:`,o);try{let c=await a.text();throw new Error(`Failed to parse JSON response from server. Status: ${a.status}. Body: "${c}". Original error: ${o instanceof Error?o.message:String(o)}`)}catch{throw new Error(`Failed to parse JSON response from server and could not read response body as text. Status: ${a.status}. Original error: ${o instanceof Error?o.message:String(o)}`)}}}async getConfiguration(e){return await this.request("GET",`/configuration/${e}`)}async getDeploy(e){return this.request("GET",`/deploy/${e}`)}async getWallets(e){return this.request("GET",`/wallets/signer/${e}`)}async getWalletsForSapient(e,t){return this.request("GET",`/wallets/sapient/${e}/${t}`)}async getWitnessFor(e,t){return this.request("GET",`/witness/${e}/signer/${t}`)}async getWitnessForSapient(e,t,n){return this.request("GET",`/witness/sapient/${e}/${t}/${n}`)}async getConfigurationUpdates(e,t,n){let r=n?.allUpdates?"?allUpdates=true":"";return this.request("GET",`/configuration-updates/${e}/from/${t}${r}`)}async getTree(e){return this.request("GET",`/tree/${e}`)}async saveWallet(e,t){await this.request("POST","/wallet",{deployConfiguration:e,context:t});}async saveWitnesses(e,t,n,r){await this.request("POST","/witnesses",{wallet:e,chainId:t,payload:n,signatures:r});}async saveUpdate(e,t,n){await this.request("POST","/update",{wallet:e,configuration:t,signature:n});}async saveTree(e){await this.request("POST","/tree",{tree:e});}saveConfiguration(e){return this.request("POST","/configuration",{config:e})}saveDeploy(e,t){return this.request("POST","/deploy",{imageHash:e,context:t})}async getPayload(e){return this.request("GET",`/payload/${e}`)}async savePayload(e,t,n){return this.request("POST","/payload",{wallet:e,payload:t,chainId:n})}};var kx=class{args;constructor(e){this.args=e;}async getConfiguration(e){let t=await this.args.cache.getConfiguration(e);if(t)return t;let n=await this.args.source.getConfiguration(e);return n&&await this.args.cache.saveConfiguration(n),n}async getDeploy(e){let t=await this.args.cache.getDeploy(e);if(t)return t;let n=await this.args.source.getDeploy(e);return n&&await this.args.cache.saveDeploy(n.imageHash,n.context),n}async getWallets(e){let t=hn(await this.args.cache.getWallets(e)),n=hn(await this.args.source.getWallets(e)),r={...t,...n};for(let[i,a]of Object.entries(r))B.assert(i),n[i]||await this.args.source.saveWitnesses(i,a.chainId,a.payload,{type:"unrecovered-signer",weight:1n,signature:a.signature}),t[i]||await this.args.cache.saveWitnesses(i,a.chainId,a.payload,{type:"unrecovered-signer",weight:1n,signature:a.signature});return r}async getWalletsForSapient(e,t){let n=await this.args.cache.getWalletsForSapient(e,t),r=await this.args.source.getWalletsForSapient(e,t),i={...n,...r};for(let[a,o]of Object.entries(i)){let c=B.from(a);r[c]||await this.args.source.saveWitnesses(c,o.chainId,o.payload,{type:"unrecovered-signer",weight:1n,signature:o.signature}),n[c]||await this.args.cache.saveWitnesses(c,o.chainId,o.payload,{type:"unrecovered-signer",weight:1n,signature:o.signature});}return i}async getWitnessFor(e,t){let n=await this.args.cache.getWitnessFor(e,t);if(n)return n;let r=await this.args.source.getWitnessFor(e,t);return r&&await this.args.cache.saveWitnesses(e,r.chainId,r.payload,{type:"unrecovered-signer",weight:1n,signature:r.signature}),r}async getWitnessForSapient(e,t,n){let r=await this.args.cache.getWitnessForSapient(e,t,n);if(r)return r;let i=await this.args.source.getWitnessForSapient(e,t,n);return i&&await this.args.cache.saveWitnesses(e,i.chainId,i.payload,{type:"unrecovered-signer",weight:1n,signature:i.signature}),i}async getConfigurationUpdates(e,t,n){return this.args.source.getConfigurationUpdates(e,t,n)}async getTree(e){let t=await this.args.cache.getTree(e);if(t)return t;let n=await this.args.source.getTree(e);return n&&await this.args.cache.saveTree(n),n}saveWallet(e,t){return this.args.source.saveWallet(e,t)}saveWitnesses(e,t,n,r){return this.args.source.saveWitnesses(e,t,n,r)}saveUpdate(e,t,n){return this.args.source.saveUpdate(e,t,n)}saveTree(e){return this.args.source.saveTree(e)}saveConfiguration(e){return this.args.source.saveConfiguration(e)}saveDeploy(e,t){return this.args.source.saveDeploy(e,t)}async getPayload(e){let t=await this.args.cache.getPayload(e);if(t)return t;let n=await this.args.source.getPayload(e);return n&&await this.args.cache.savePayload(n.wallet,n.payload,n.chainId),n}savePayload(e,t,n){return this.args.source.savePayload(e,t,n)}};var Xh={};be(Xh,{Provider:()=>qx});var rV="Webrpc",iV="webrpc@v0.22.1;gen-typescript@v0.16.2;sessions@v0.0.1";var a8;(function(s){s.Transactions="Transactions",s.Message="Message",s.ConfigUpdate="ConfigUpdate",s.Digest="Digest";})(a8||(a8={}));var Ke;(function(s){s.EIP712="EIP712",s.EthSign="EthSign",s.EIP1271="EIP1271",s.Sapient="Sapient",s.SapientCompact="SapientCompact";})(Ke||(Ke={}));var jg=class{hostname;fetch;path="/rpc/Sessions/";constructor(e,t){this.hostname=e.replace(/\/*$/,""),this.fetch=(n,r)=>t(n,r);}url(e){return this.hostname+this.path+e}ping=(e,t)=>this.fetch(this.url("Ping"),gt({},e,t)).then(n=>yt(n).then(r=>({})),n=>{throw ct.new({cause:`fetch(): ${n.message||""}`})});config=(e,t,n)=>this.fetch(this.url("Config"),gt(e,t,n)).then(r=>yt(r).then(i=>({version:i.version,config:i.config})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});tree=(e,t,n)=>this.fetch(this.url("Tree"),gt(e,t,n)).then(r=>yt(r).then(i=>({version:i.version,tree:i.tree})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});payload=(e,t,n)=>this.fetch(this.url("Payload"),gt(e,t,n)).then(r=>yt(r).then(i=>({version:i.version,payload:i.payload,wallet:i.wallet,chainID:i.chainID})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});wallets=(e,t,n)=>this.fetch(this.url("Wallets"),gt(e,t,n)).then(r=>yt(r).then(i=>({wallets:i.wallets,cursor:i.cursor})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});deployHash=(e,t,n)=>this.fetch(this.url("DeployHash"),gt(e,t,n)).then(r=>yt(r).then(i=>({deployHash:i.deployHash,context:i.context})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});witness=(e,t,n)=>this.fetch(this.url("Witness"),gt(e,t,n)).then(r=>yt(r).then(i=>({witness:i.witness})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});configUpdates=(e,t,n)=>this.fetch(this.url("ConfigUpdates"),gt(e,t,n)).then(r=>yt(r).then(i=>({updates:i.updates})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});migrations=(e,t,n)=>this.fetch(this.url("Migrations"),gt(e,t,n)).then(r=>yt(r).then(i=>({migrations:i.migrations})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveConfig=(e,t,n)=>this.fetch(this.url("SaveConfig"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveTree=(e,t,n)=>this.fetch(this.url("SaveTree"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});savePayload=(e,t,n)=>this.fetch(this.url("SavePayload"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveWallet=(e,t,n)=>this.fetch(this.url("SaveWallet"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveSignature=(e,t,n)=>this.fetch(this.url("SaveSignature"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveSignature2=(e,t,n)=>this.fetch(this.url("SaveSignature2"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveSignerSignatures=(e,t,n)=>this.fetch(this.url("SaveSignerSignatures"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveSignerSignatures2=(e,t,n)=>this.fetch(this.url("SaveSignerSignatures2"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveSignerSignatures3=(e,t,n)=>this.fetch(this.url("SaveSignerSignatures3"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})});saveMigration=(e,t,n)=>this.fetch(this.url("SaveMigration"),gt(e,t,n)).then(r=>yt(r).then(i=>({})),r=>{throw ct.new({cause:`fetch(): ${r.message||""}`})})},gt=(s={},e={},t=null)=>{let n={...e,"Content-Type":"application/json"};return n[rV]=iV,{method:"POST",headers:n,body:JSON.stringify(s||{}),signal:t}},yt=s=>s.text().then(e=>{let t;try{t=JSON.parse(e);}catch(n){let r="";throw n instanceof Error&&(r=n.message),Hg.new({status:s.status,cause:`JSON.parse(): ${r}: response text: ${e}`})}if(!s.ok){let n=typeof t.code=="number"?t.code:0;throw (aV[n]||Ft).new(t)}return t}),Ft=class s extends Error{name;code;message;status;cause;msg;constructor(e,t,n,r,i){super(n),this.name=e||"WebrpcError",this.code=typeof t=="number"?t:0,this.message=n||`endpoint error ${this.code}`,this.msg=this.message,this.status=typeof r=="number"?r:0,this.cause=i,Object.setPrototypeOf(this,s.prototype);}static new(e){return new this(e.error,e.code,e.message||e.msg,e.status,e.cause)}},Px=class s extends Ft{constructor(e="WebrpcEndpoint",t=0,n="endpoint error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},ct=class s extends Ft{constructor(e="WebrpcRequestFailed",t=-1,n="request failed",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Tx=class s extends Ft{constructor(e="WebrpcBadRoute",t=-2,n="bad route",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Bx=class s extends Ft{constructor(e="WebrpcBadMethod",t=-3,n="bad method",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Ox=class s extends Ft{constructor(e="WebrpcBadRequest",t=-4,n="bad request",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Hg=class s extends Ft{constructor(e="WebrpcBadResponse",t=-5,n="bad response",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Rx=class s extends Ft{constructor(e="WebrpcServerPanic",t=-6,n="server panic",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Vx=class s extends Ft{constructor(e="WebrpcInternalError",t=-7,n="internal error",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Dx=class s extends Ft{constructor(e="WebrpcClientDisconnected",t=-8,n="client disconnected",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Ux=class s extends Ft{constructor(e="WebrpcStreamLost",t=-9,n="stream lost",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Lx=class s extends Ft{constructor(e="WebrpcStreamFinished",t=-10,n="stream finished",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},jx=class s extends Ft{constructor(e="InvalidArgument",t=1,n="invalid argument",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},Hx=class s extends Ft{constructor(e="NotFound",t=2,n="not found",r=0,i){super(e,t,n,r,i),Object.setPrototypeOf(this,s.prototype);}},o8;(function(s){s.WebrpcEndpoint="WebrpcEndpoint",s.WebrpcRequestFailed="WebrpcRequestFailed",s.WebrpcBadRoute="WebrpcBadRoute",s.WebrpcBadMethod="WebrpcBadMethod",s.WebrpcBadRequest="WebrpcBadRequest",s.WebrpcBadResponse="WebrpcBadResponse",s.WebrpcServerPanic="WebrpcServerPanic",s.WebrpcInternalError="WebrpcInternalError",s.WebrpcClientDisconnected="WebrpcClientDisconnected",s.WebrpcStreamLost="WebrpcStreamLost",s.WebrpcStreamFinished="WebrpcStreamFinished",s.InvalidArgument="InvalidArgument",s.NotFound="NotFound";})(o8||(o8={}));var c8;(function(s){s[s.WebrpcEndpoint=0]="WebrpcEndpoint",s[s.WebrpcRequestFailed=-1]="WebrpcRequestFailed",s[s.WebrpcBadRoute=-2]="WebrpcBadRoute",s[s.WebrpcBadMethod=-3]="WebrpcBadMethod",s[s.WebrpcBadRequest=-4]="WebrpcBadRequest",s[s.WebrpcBadResponse=-5]="WebrpcBadResponse",s[s.WebrpcServerPanic=-6]="WebrpcServerPanic",s[s.WebrpcInternalError=-7]="WebrpcInternalError",s[s.WebrpcClientDisconnected=-8]="WebrpcClientDisconnected",s[s.WebrpcStreamLost=-9]="WebrpcStreamLost",s[s.WebrpcStreamFinished=-10]="WebrpcStreamFinished",s[s.InvalidArgument=1]="InvalidArgument",s[s.NotFound=2]="NotFound";})(c8||(c8={}));var aV={0:Px,[-1]:ct,[-2]:Tx,[-3]:Bx,[-4]:Ox,[-5]:Hg,[-6]:Rx,[-7]:Vx,[-8]:Dx,[-9]:Ux,[-10]:Lx,1:jx,2:Hx};var qx=class{service;constructor(e="https://keymachine.sequence.app"){this.service=new jg(e,fetch);}async getConfiguration(e){let{version:t,config:n}=await this.service.config({imageHash:e});if(t!==3)throw new Error(`invalid configuration version ${t}, expected version 3`);return uV(n)}async getDeploy(e){let{deployHash:t,context:n}=await this.service.deployHash({wallet:e});return E.assert(t),B.assert(n.factory),B.assert(n.mainModule),B.assert(n.mainModuleUpgradable),E.assert(n.walletCreationCode),{imageHash:t,context:{factory:n.factory,stage1:n.mainModule,stage2:n.mainModuleUpgradable,creationCode:n.walletCreationCode}}}async getWallets(e){let t=await this.service.wallets({signer:e}),n=hn(t.wallets);return Object.fromEntries(Object.entries(n).map(([r,i])=>{switch(B.assert(r),E.assert(i.signature),i.type){case Ke.EIP712:return [r,{chainId:Number(i.chainID),payload:Gs(i.payload),signature:{type:"hash",...At.from(i.signature)}}];case Ke.EthSign:return [r,{chainId:Number(i.chainID),payload:Gs(i.payload),signature:{type:"eth_sign",...At.from(i.signature)}}];case Ke.EIP1271:return [r,{chainId:Number(i.chainID),payload:Gs(i.payload),signature:{type:"erc1271",address:e,data:i.signature}}];case Ke.Sapient:throw new Error(`unexpected sapient signature by ${e}`);case Ke.SapientCompact:throw new Error(`unexpected compact sapient signature by ${e}`)}}))}async getWalletsForSapient(e,t){let n=await this.service.wallets({signer:e,sapientHash:t}),r=hn(n.wallets);return Object.fromEntries(Object.entries(r).map(([i,a])=>{switch(B.assert(i),E.assert(a.signature),a.type){case Ke.EIP712:throw new Error(`unexpected eip-712 signature by ${e}`);case Ke.EthSign:throw new Error(`unexpected eth_sign signature by ${e}`);case Ke.EIP1271:throw new Error(`unexpected erc-1271 signature by ${e}`);case Ke.Sapient:return [i,{chainId:Number(a.chainID),payload:Gs(a.payload),signature:{type:"sapient",address:e,data:a.signature}}];case Ke.SapientCompact:return [i,{chainId:Number(a.chainID),payload:Gs(a.payload),signature:{type:"sapient_compact",address:e,data:a.signature}}]}}))}async getWitnessFor(e,t){try{let{witness:n}=await this.service.witness({signer:t,wallet:e});switch(E.assert(n.signature),n.type){case Ke.EIP712:return {chainId:Number(n.chainID),payload:Gs(n.payload),signature:{type:"hash",...At.from(n.signature)}};case Ke.EthSign:return {chainId:Number(n.chainID),payload:Gs(n.payload),signature:{type:"eth_sign",...At.from(n.signature)}};case Ke.EIP1271:return {chainId:Number(n.chainID),payload:Gs(n.payload),signature:{type:"erc1271",address:t,data:n.signature}};case Ke.Sapient:throw new Error(`unexpected sapient signature by ${t}`);case Ke.SapientCompact:throw new Error(`unexpected compact sapient signature by ${t}`)}}catch{}}async getWitnessForSapient(e,t,n){try{let{witness:r}=await this.service.witness({signer:t,wallet:e,sapientHash:n});switch(E.assert(r.signature),r.type){case Ke.EIP712:throw new Error(`unexpected eip-712 signature by ${t}`);case Ke.EthSign:throw new Error(`unexpected eth_sign signature by ${t}`);case Ke.EIP1271:throw new Error(`unexpected erc-1271 signature by ${t}`);case Ke.Sapient:return {chainId:Number(r.chainID),payload:Gs(r.payload),signature:{type:"sapient",address:t,data:r.signature}};case Ke.SapientCompact:return {chainId:Number(r.chainID),payload:Gs(r.payload),signature:{type:"sapient_compact",address:t,data:r.signature}}}}catch{}}async getConfigurationUpdates(e,t,n){let{updates:r}=await this.service.configUpdates({wallet:e,fromImageHash:t,allUpdates:n?.allUpdates});return Promise.all(r.map(async({toImageHash:i,signature:a})=>{E.assert(i),E.assert(a);let o=Rt.decodeSignature(E.toBytes(a)),{configuration:c}=await Rt.recover(o,e,0,ce.fromConfigUpdate(i),{provider:cV});return {imageHash:i,signature:{...o,configuration:c}}}))}async getTree(e){let{version:t,tree:n}=await this.service.tree({imageHash:e});if(t!==3)throw new Error(`invalid tree version ${t}, expected version 3`);return h8(n)}async getPayload(e){let{version:t,payload:n,wallet:r,chainID:i}=await this.service.payload({digest:e});if(t!==3)throw new Error(`invalid payload version ${t}, expected version 3`);return B.assert(r),{payload:Gs(n),wallet:r,chainId:Number(i)}}async saveWallet(e,t){await this.service.saveWallet({version:3,deployConfig:Mx(e),context:{version:3,factory:t.factory,mainModule:t.stage1,mainModuleUpgradable:t.stage2,guestModule:_e.DefaultGuestAddress,walletCreationCode:t.creationCode}});}async saveWitnesses(e,t,n,r){await this.service.saveSignerSignatures3({wallet:e,payload:$x(n),chainID:t.toString(),signatures:Qh(r).map(i=>{switch(i.type){case"hash":return {type:Ke.EIP712,signature:At.toHex(At.from(i))};case"eth_sign":return {type:Ke.EthSign,signature:At.toHex(At.from(i))};case"erc1271":return {type:Ke.EIP1271,signer:i.address,signature:i.data,referenceChainID:t.toString()};case"sapient":return {type:Ke.Sapient,signer:i.address,signature:i.data,referenceChainID:t.toString()};case"sapient_compact":return {type:Ke.SapientCompact,signer:i.address,signature:i.data,referenceChainID:t.toString()}}})});}async saveUpdate(e,t,n){await this.service.saveSignature2({wallet:e,payload:$x(ce.fromConfigUpdate(f.toHex(Pe.hashConfiguration(t)))),chainID:"0",signature:f.toHex(Rt.encodeSignature(n)),toConfig:Mx(t)});}async saveTree(e){await this.service.saveTree({version:3,tree:l8(e)});}async saveConfiguration(e){await this.service.saveConfig({version:3,config:Mx(e)});}async saveDeploy(e,t){}async savePayload(e,t,n){await this.service.savePayload({version:3,payload:$x(t),wallet:e,chainID:n.toString()});}},oV=[Ne.Dev1.passkeys,Ne.Dev2.passkeys,Ne.Rc3.passkeys,Ne.Rc4.passkeys,Ne.Rc5.passkeys].map(B.checksum),u8="function recoverSapientSignatureCompact(bytes32 _digest, bytes _signature) view returns (bytes32)",_x=se.from(u8),Fx=class{request=async e=>{switch(e.method){case"eth_call":if(!e.params||!Array.isArray(e.params)||e.params.length===0)throw new Error("eth_call requires transaction parameters");let t=e.params[0];if(!t.data?.startsWith(se.getSelector(_x)))throw new Error(`unknown selector ${t.data?.slice(0,10)}, expected selector ${se.getSelector(_x)} for ${u8}`);if(!oV.includes(t.to?B.checksum(t.to):"0x"))throw new Error(`unknown passkey signer ${t.to}`);let[n,r]=se.decodeData(_x,t.data),i=Ne.Passkeys.decode(E.toBytes(r));if(Ne.Passkeys.isValidSignature(n,i))return Ne.Passkeys.rootFor(i.publicKey);throw new Error(`invalid passkey signature ${r} for digest ${n}`);default:throw new Error(`method ${e.method} not implemented`)}};on=e=>{throw new Error(`unable to listen for ${e}: not implemented`)};removeListener=e=>{throw new Error(`unable to remove listener for ${e}: not implemented`)}},cV=new Fx;function Mx(s){return {threshold:fn(s.threshold),checkpoint:fn(s.checkpoint),checkpointer:s.checkpointer,tree:_g(s.topology)}}function uV(s){return s.checkpointer!==void 0&&B.assert(s.checkpointer),{threshold:BigInt(s.threshold),checkpoint:BigInt(s.checkpoint),checkpointer:s.checkpointer,topology:Mg(s.tree)}}function _g(s){if(Pe.isNode(s))return [_g(s[0]),_g(s[1])];if(Pe.isSignerLeaf(s))return {weight:fn(s.weight),address:s.address};if(Pe.isSapientSignerLeaf(s))return {weight:fn(s.weight),address:s.address,imageHash:s.imageHash};if(Pe.isSubdigestLeaf(s))return {subdigest:s.digest};if(Pe.isAnyAddressSubdigestLeaf(s))return {subdigest:s.digest,isAnyAddress:!0};if(Pe.isNestedLeaf(s))return {weight:fn(s.weight),threshold:fn(s.threshold),tree:_g(s.tree)};if(Pe.isNodeLeaf(s))return s;throw new Error(`unknown topology '${JSON.stringify(s)}'`)}function Mg(s){switch(typeof s){case"string":return E.assert(s),s;case"object":if(s instanceof Array)return [Mg(s[0]),Mg(s[1])];if("weight"in s){if("address"in s)return B.assert(s.address),s.imageHash?(E.assert(s.imageHash),{type:"sapient-signer",address:s.address,weight:BigInt(s.weight),imageHash:s.imageHash}):{type:"signer",address:s.address,weight:BigInt(s.weight)};if("tree"in s)return {type:"nested",weight:BigInt(s.weight),threshold:BigInt(s.threshold),tree:Mg(s.tree)}}if("subdigest"in s)return E.assert(s.subdigest),{type:s.isAnyAddress?"any-address-subdigest":"subdigest",digest:s.subdigest}}throw new Error(`unknown config tree '${JSON.stringify(s)}'`)}function $x(s){if(ce.isCalls(s))return {type:"call",space:fn(s.space),nonce:fn(s.nonce),calls:s.calls.map(lV)};if(ce.isMessage(s))return {type:"message",message:s.message};if(ce.isConfigUpdate(s))return {type:"config-update",imageHash:s.imageHash};if(ce.isDigest(s))return {type:"digest",digest:s.digest};throw new Error(`unknown payload '${JSON.stringify(s)}'`)}function Gs(s){switch(s.type){case"call":return {type:"call",space:BigInt(s.space),nonce:BigInt(s.nonce),calls:s.calls.map(hV)};case"message":return E.assert(s.message),{type:"message",message:s.message};case"config-update":return E.assert(s.imageHash),{type:"config-update",imageHash:s.imageHash};case"digest":return E.assert(s.digest),{type:"digest",digest:s.digest}}}function lV(s){return {to:s.to,value:fn(s.value),data:s.data,gasLimit:fn(s.gasLimit),delegateCall:s.delegateCall,onlyFallback:s.onlyFallback,behaviorOnError:s.behaviorOnError}}function hV(s){return B.assert(s.to),E.assert(s.data),{to:s.to,value:BigInt(s.value),data:s.data,gasLimit:BigInt(s.gasLimit),delegateCall:s.delegateCall,onlyFallback:s.onlyFallback,behaviorOnError:s.behaviorOnError}}function l8(s){if(Ss.isBranch(s))return s.map(l8);if(Ss.isLeaf(s))return {data:f.toHex(s.value)};if(Ss.isNode(s))return s;throw new Error(`unknown tree '${JSON.stringify(s)}'`)}function h8(s){switch(typeof s){case"string":return E.assert(s),s;case"object":if(s instanceof Array)return s.map(h8);if("data"in s)return E.assert(s.data),{type:"leaf",value:E.toBytes(s.data)}}throw new Error(`unknown tree '${JSON.stringify(s)}'`)}function fn(s){return s<Number.MIN_SAFE_INTEGER||s>Number.MAX_SAFE_INTEGER?s.toString():Number(s)}function Qh(s){if(Rt.isRawNode(s))return [...Qh(s[0]),...Qh(s[1])];if(Rt.isRawSignerLeaf(s))return [s.signature];if(Pe.isNestedLeaf(s))return Qh(s.tree);if(Rt.isRawNestedLeaf(s))return Qh(s.tree);if(Pe.isSignerLeaf(s))return s.signature?[s.signature]:[];if(Pe.isSapientSignerLeaf(s))return s.signature?[s.signature]:[];if(Pe.isSubdigestLeaf(s))return [];if(Pe.isAnyAddressSubdigestLeaf(s))return [];if(Pe.isNodeLeaf(s))return [];throw new Error(`unknown topology '${JSON.stringify(s)}'`)}function fV(s,e){return typeof e=="bigint"?e.toString():e instanceof Uint8Array?E.fromBytes(e):e}function $g(s){return JSON.stringify(s,fV,2)}function qg(s){if(typeof s=="bigint")return s.toString();if(s instanceof Uint8Array)return E.fromBytes(s);if(typeof s=="string")return s.toLowerCase();if(Array.isArray(s))return s.map(qg);if(s&&typeof s=="object"){let e=[];for(let t of Object.keys(s).filter(n=>s[n]!==void 0).sort())e.push([t.toLowerCase(),qg(s[t])]);return e}return s}function dV(s,e){return JSON.stringify(qg(s))===JSON.stringify(qg(e))}function mV(s,e){let t={get(n,r,i){let a=s[r];return typeof a!="function"?Reflect.get(s,r):async(...o)=>{let c=String(r),u=$g(o),l;try{l=await a.apply(s,o);}catch(m){let y=Math.floor(1e6*Math.random()).toString().padStart(6,"0");throw console.trace(`[${y}] calling ${c}: ${u}
|
|
350
|
+
[${y}] warning: reference ${c} threw:`,m),m}let h=$g(l);return await Promise.all(Object.entries(e).map(async([m,y])=>{let g=y[r];if(typeof g!="function"){let C=Math.floor(1e6*Math.random()).toString().padStart(6,"0");console.trace(`[${C}] calling ${c}: ${u}
|
|
351
351
|
[${C}] reference returned: ${h}
|
|
352
|
-
[${C}] warning: ${m} has no ${c}`);return}let w;try{w=g.apply(y,o),w=await Promise.resolve(w);}catch(C){let
|
|
353
|
-
[${
|
|
354
|
-
[${
|
|
352
|
+
[${C}] warning: ${m} has no ${c}`);return}let w;try{w=g.apply(y,o),w=await Promise.resolve(w);}catch(C){let k=Math.floor(1e6*Math.random()).toString().padStart(6,"0");console.trace(`[${k}] calling ${c}: ${u}
|
|
353
|
+
[${k}] reference returned: ${h}
|
|
354
|
+
[${k}] warning: ${m} ${c} threw:`,C);return}let S=Math.floor(1e6*Math.random()).toString().padStart(6,"0");dV(l,w)?console.trace(`[${S}] calling ${c}: ${u}
|
|
355
355
|
[${S}] reference returned: ${h}
|
|
356
|
-
[${S}] ${m} returned: ${
|
|
356
|
+
[${S}] ${m} returned: ${$g(w)}`):console.trace(`[${S}] calling ${c}: ${u}
|
|
357
357
|
[${S}] reference returned: ${h}
|
|
358
|
-
[${S}] ${m} returned: ${
|
|
359
|
-
[${S}] warning: ${m} ${c} does not match reference`);})),l}}};return new Proxy(s,t)}({knownContexts:wa.KnownContexts,stateProvider:new Xh.Provider,guest:_e.DefaultGuestAddress});var ef={};be(ef,{EIP1193ProviderAdapter:()=>Ia,EIP6963:()=>LE,LocalRelayer:()=>Aa,PkRelayer:()=>BE,RpcRelayer:()=>TE,SequenceRelayer:()=>OE,getChain:()=>S8,isRelayer:()=>EV});var wt;(function(s){s.UNKNOWN="UNKNOWN",s.DROPPED="DROPPED",s.QUEUED="QUEUED",s.SENT="SENT",s.SUCCEEDED="SUCCEEDED",s.PARTIALLY_FAILED="PARTIALLY_FAILED",s.FAILED="FAILED",s.PENDING_PRECONDITION="PENDING_PRECONDITION";})(wt||(wt={}));var m8;(function(s){s.SEND="SEND",s.RECEIVE="RECEIVE",s.BRIDGE_DEPOSIT="BRIDGE_DEPOSIT",s.BRIDGE_WITHDRAW="BRIDGE_WITHDRAW",s.BURN="BURN",s.UNKNOWN="UNKNOWN";})(m8||(m8={}));var p8;(function(s){s.SKIPPED="SKIPPED",s.SUCCEEDED="SUCCEEDED",s.FAILED="FAILED",s.ABORTED="ABORTED",s.REVERTED="REVERTED",s.NOT_ENOUGH_GAS="NOT_ENOUGH_GAS";})(p8||(p8={}));var Kg;(function(s){s.UNKNOWN="UNKNOWN",s.ERC20_TOKEN="ERC20_TOKEN",s.ERC1155_TOKEN="ERC1155_TOKEN";})(Kg||(Kg={}));var g8;(function(s){s.DESC="DESC",s.ASC="ASC";})(g8||(g8={}));var _c=class{hostname;fetch;path="/rpc/Relayer/";constructor(e,t){this.hostname=e.replace(/\/*$/,""),this.fetch=(n,r)=>t(n,r);}url(e){return this.hostname+this.path+e}queryKey={ping:()=>["Relayer","ping"],version:()=>["Relayer","version"],runtimeStatus:()=>["Relayer","runtimeStatus"],getSequenceContext:()=>["Relayer","getSequenceContext"],getChainID:()=>["Relayer","getChainID"],sendMetaTxn:e=>["Relayer","sendMetaTxn",e],getMetaTxnNonce:e=>["Relayer","getMetaTxnNonce",e],getMetaTxnReceipt:e=>["Relayer","getMetaTxnReceipt",e],simulate:e=>["Relayer","simulate",e],simulateV3:e=>["Relayer","simulateV3",e],updateMetaTxnGasLimits:e=>["Relayer","updateMetaTxnGasLimits",e],feeTokens:()=>["Relayer","feeTokens"],feeOptions:e=>["Relayer","feeOptions",e],getMetaTxnNetworkFeeOptions:e=>["Relayer","getMetaTxnNetworkFeeOptions",e],getMetaTransactions:e=>["Relayer","getMetaTransactions",e],getTransactionCost:e=>["Relayer","getTransactionCost",e],sentTransactions:e=>["Relayer","sentTransactions",e],pendingTransactions:e=>["Relayer","pendingTransactions",e],getGasTank:e=>["Relayer","getGasTank",e],addGasTank:e=>["Relayer","addGasTank",e],updateGasTank:e=>["Relayer","updateGasTank",e],nextGasTankBalanceAdjustmentNonce:e=>["Relayer","nextGasTankBalanceAdjustmentNonce",e],adjustGasTankBalance:e=>["Relayer","adjustGasTankBalance",e],getGasTankBalanceAdjustment:e=>["Relayer","getGasTankBalanceAdjustment",e],listGasTankBalanceAdjustments:e=>["Relayer","listGasTankBalanceAdjustments",e],listGasSponsors:e=>["Relayer","listGasSponsors",e],getGasSponsor:e=>["Relayer","getGasSponsor",e],addGasSponsor:e=>["Relayer","addGasSponsor",e],updateGasSponsor:e=>["Relayer","updateGasSponsor",e],removeGasSponsor:e=>["Relayer","removeGasSponsor",e],addressGasSponsors:e=>["Relayer","addressGasSponsors",e],getProjectBalance:e=>["Relayer","getProjectBalance",e],adjustProjectBalance:e=>["Relayer","adjustProjectBalance",e]};ping=(e,t)=>this.fetch(this.url("Ping"),Le("{}",e,t)).then(n=>je(n).then(r=>Ue(r,"PingReturn")),n=>{throw Te.new({cause:`fetch(): ${n instanceof Error?n.message:String(n)}`})});version=(e,t)=>this.fetch(this.url("Version"),Le("{}",e,t)).then(n=>je(n).then(r=>Ue(r,"VersionReturn")),n=>{throw Te.new({cause:`fetch(): ${n instanceof Error?n.message:String(n)}`})});runtimeStatus=(e,t)=>this.fetch(this.url("RuntimeStatus"),Le("{}",e,t)).then(n=>je(n).then(r=>Ue(r,"RuntimeStatusReturn")),n=>{throw Te.new({cause:`fetch(): ${n instanceof Error?n.message:String(n)}`})});getSequenceContext=(e,t)=>this.fetch(this.url("GetSequenceContext"),Le("{}",e,t)).then(n=>je(n).then(r=>Ue(r,"GetSequenceContextReturn")),n=>{throw Te.new({cause:`fetch(): ${n instanceof Error?n.message:String(n)}`})});getChainID=(e,t)=>this.fetch(this.url("GetChainID"),Le("{}",e,t)).then(n=>je(n).then(r=>Ue(r,"GetChainIDReturn")),n=>{throw Te.new({cause:`fetch(): ${n instanceof Error?n.message:String(n)}`})});sendMetaTxn=(e,t,n)=>this.fetch(this.url("SendMetaTxn"),Le(Ze(e,"SendMetaTxnArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"SendMetaTxnReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getMetaTxnNonce=(e,t,n)=>this.fetch(this.url("GetMetaTxnNonce"),Le(Ze(e,"GetMetaTxnNonceArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"GetMetaTxnNonceReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getMetaTxnReceipt=(e,t,n)=>this.fetch(this.url("GetMetaTxnReceipt"),Le(Ze(e,"GetMetaTxnReceiptArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"GetMetaTxnReceiptReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});simulate=(e,t,n)=>this.fetch(this.url("Simulate"),Le(Ze(e,"SimulateArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"SimulateReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});simulateV3=(e,t,n)=>this.fetch(this.url("SimulateV3"),Le(Ze(e,"SimulateV3Args"),t,n)).then(r=>je(r).then(i=>Ue(i,"SimulateV3Return")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});updateMetaTxnGasLimits=(e,t,n)=>this.fetch(this.url("UpdateMetaTxnGasLimits"),Le(Ze(e,"UpdateMetaTxnGasLimitsArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"UpdateMetaTxnGasLimitsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});feeTokens=(e,t)=>this.fetch(this.url("FeeTokens"),Le("{}",e,t)).then(n=>je(n).then(r=>Ue(r,"FeeTokensReturn")),n=>{throw Te.new({cause:`fetch(): ${n instanceof Error?n.message:String(n)}`})});feeOptions=(e,t,n)=>this.fetch(this.url("FeeOptions"),Le(Ze(e,"FeeOptionsArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"FeeOptionsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getMetaTxnNetworkFeeOptions=(e,t,n)=>this.fetch(this.url("GetMetaTxnNetworkFeeOptions"),Le(Ze(e,"GetMetaTxnNetworkFeeOptionsArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"GetMetaTxnNetworkFeeOptionsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getMetaTransactions=(e,t,n)=>this.fetch(this.url("GetMetaTransactions"),Le(Ze(e,"GetMetaTransactionsArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"GetMetaTransactionsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getTransactionCost=(e,t,n)=>this.fetch(this.url("GetTransactionCost"),Le(Ze(e,"GetTransactionCostArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"GetTransactionCostReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});sentTransactions=(e,t,n)=>this.fetch(this.url("SentTransactions"),Le(Ze(e,"SentTransactionsArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"SentTransactionsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});pendingTransactions=(e,t,n)=>this.fetch(this.url("PendingTransactions"),Le(Ze(e,"PendingTransactionsArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"PendingTransactionsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getGasTank=(e,t,n)=>this.fetch(this.url("GetGasTank"),Le(Ze(e,"GetGasTankArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"GetGasTankReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});addGasTank=(e,t,n)=>this.fetch(this.url("AddGasTank"),Le(Ze(e,"AddGasTankArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"AddGasTankReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});updateGasTank=(e,t,n)=>this.fetch(this.url("UpdateGasTank"),Le(Ze(e,"UpdateGasTankArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"UpdateGasTankReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});nextGasTankBalanceAdjustmentNonce=(e,t,n)=>this.fetch(this.url("NextGasTankBalanceAdjustmentNonce"),Le(Ze(e,"NextGasTankBalanceAdjustmentNonceArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"NextGasTankBalanceAdjustmentNonceReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});adjustGasTankBalance=(e,t,n)=>this.fetch(this.url("AdjustGasTankBalance"),Le(Ze(e,"AdjustGasTankBalanceArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"AdjustGasTankBalanceReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getGasTankBalanceAdjustment=(e,t,n)=>this.fetch(this.url("GetGasTankBalanceAdjustment"),Le(Ze(e,"GetGasTankBalanceAdjustmentArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"GetGasTankBalanceAdjustmentReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});listGasTankBalanceAdjustments=(e,t,n)=>this.fetch(this.url("ListGasTankBalanceAdjustments"),Le(Ze(e,"ListGasTankBalanceAdjustmentsArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"ListGasTankBalanceAdjustmentsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});listGasSponsors=(e,t,n)=>this.fetch(this.url("ListGasSponsors"),Le(Ze(e,"ListGasSponsorsArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"ListGasSponsorsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getGasSponsor=(e,t,n)=>this.fetch(this.url("GetGasSponsor"),Le(Ze(e,"GetGasSponsorArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"GetGasSponsorReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});addGasSponsor=(e,t,n)=>this.fetch(this.url("AddGasSponsor"),Le(Ze(e,"AddGasSponsorArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"AddGasSponsorReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});updateGasSponsor=(e,t,n)=>this.fetch(this.url("UpdateGasSponsor"),Le(Ze(e,"UpdateGasSponsorArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"UpdateGasSponsorReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});removeGasSponsor=(e,t,n)=>this.fetch(this.url("RemoveGasSponsor"),Le(Ze(e,"RemoveGasSponsorArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"RemoveGasSponsorReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});addressGasSponsors=(e,t,n)=>this.fetch(this.url("AddressGasSponsors"),Le(Ze(e,"AddressGasSponsorsArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"AddressGasSponsorsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getProjectBalance=(e,t,n)=>this.fetch(this.url("GetProjectBalance"),Le(Ze(e,"GetProjectBalanceArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"GetProjectBalanceReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});adjustProjectBalance=(e,t,n)=>this.fetch(this.url("AdjustProjectBalance"),Le(Ze(e,"AdjustProjectBalanceArgs"),t,n)).then(r=>je(r).then(i=>Ue(i,"AdjustProjectBalanceReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})})},Le=(s="{}",e={},t=null)=>({method:"POST",headers:{...e,"Content-Type":"application/json"},body:s,signal:t}),je=s=>s.text().then(e=>{let t;try{t=JSON.parse(e);}catch(n){throw Ea.new({status:s.status,cause:`JSON.parse(): ${n instanceof Error?n.message:String(n)}: response text: ${e}`})}if(!s.ok){let n=typeof t.code=="number"?t.code:0;throw (pV[n]||Ie).new(t)}return t}),b8={SendMetaTxnArgs:[["preconditions","TransactionPrecondition[]"]],TransactionPrecondition:["minAmount"],Transactions:[["preconditions","TransactionPrecondition[]"]]};function Gx(s,e){if(e==null||typeof e!="object")return e;let t=b8[s]||[];if(!t.length)return e;for(let n of t){if(Array.isArray(n)){let[r,i]=n;if(r.endsWith("[]")){let a=r.slice(0,-2),o=e[a];if(Array.isArray(o))for(let c=0;c<o.length;c++)o[c]=Gx(i,o[c]);}else e[r]&&(e[r]=Gx(i,e[r]));continue}if(n.endsWith("[]")){let r=n.slice(0,-2),i=e[r];if(Array.isArray(i))for(let a=0;a<i.length;a++)typeof i[a]=="bigint"&&(i[a]=i[a].toString());continue}typeof e[n]=="bigint"&&(e[n]=e[n].toString());}return e}function Wx(s,e){if(e==null||typeof e!="object")return e;let t=b8[s]||[];if(!t.length)return e;for(let n of t){if(Array.isArray(n)){let[i,a]=n;if(i.endsWith("[]")){let o=i.slice(0,-2),c=e[o];if(Array.isArray(c))for(let u=0;u<c.length;u++)c[u]=Wx(a,c[u]);}else e[i]&&(e[i]=Wx(a,e[i]));continue}if(n.endsWith("[]")){let i=n.slice(0,-2),a=e[i];if(Array.isArray(a))for(let o=0;o<a.length;o++){let c=a[o];if(typeof c=="string")try{a[o]=BigInt(c);}catch{throw Ea.new({cause:`Invalid bigint value for ${i}[${o}]: ${c}`})}}continue}let r=e[n];if(typeof r=="string")try{e[n]=BigInt(r);}catch{throw Ea.new({cause:`Invalid bigint value for ${n}: ${r}`})}}return e}var Ze=(s,e="")=>JSON.stringify(Gx(e,s)),Ue=(s,e="")=>{let t=s;if(typeof s=="string")try{t=JSON.parse(s);}catch(n){throw Ea.new({cause:`JsonDecode: JSON.parse failed: ${n.message}`})}return Wx(e,t)},Ie=class s extends Error{code;status;constructor(e={}){super(e.message),this.name=e.name||"WebrpcEndpointError",this.code=typeof e.code=="number"?e.code:0,this.message=e.message||"endpoint error",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}static new(e){return new this({message:e.message,code:e.code,status:e.status,cause:e.cause})}},Jx=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcEndpoint",this.code=typeof e.code=="number"?e.code:0,this.message=e.message||"endpoint error",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},Te=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcRequestFailed",this.code=typeof e.code=="number"?e.code:-1,this.message=e.message||"request failed",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},zx=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcBadRoute",this.code=typeof e.code=="number"?e.code:-2,this.message=e.message||"bad route",this.status=typeof e.status=="number"?e.status:404,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},Yx=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcBadMethod",this.code=typeof e.code=="number"?e.code:-3,this.message=e.message||"bad method",this.status=typeof e.status=="number"?e.status:405,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},Zx=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcBadRequest",this.code=typeof e.code=="number"?e.code:-4,this.message=e.message||"bad request",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},Ea=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcBadResponse",this.code=typeof e.code=="number"?e.code:-5,this.message=e.message||"bad response",this.status=typeof e.status=="number"?e.status:500,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},Qx=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcServerPanic",this.code=typeof e.code=="number"?e.code:-6,this.message=e.message||"server panic",this.status=typeof e.status=="number"?e.status:500,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},Xx=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcInternalError",this.code=typeof e.code=="number"?e.code:-7,this.message=e.message||"internal error",this.status=typeof e.status=="number"?e.status:500,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},eE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcClientAborted",this.code=typeof e.code=="number"?e.code:-8,this.message=e.message||"request aborted by client",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},tE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcStreamLost",this.code=typeof e.code=="number"?e.code:-9,this.message=e.message||"stream lost",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},sE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcStreamFinished",this.code=typeof e.code=="number"?e.code:-10,this.message=e.message||"stream finished",this.status=typeof e.status=="number"?e.status:200,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},nE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"Unauthorized",this.code=typeof e.code=="number"?e.code:1e3,this.message=e.message||"Unauthorized access",this.status=typeof e.status=="number"?e.status:401,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},rE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"PermissionDenied",this.code=typeof e.code=="number"?e.code:1001,this.message=e.message||"Permission denied",this.status=typeof e.status=="number"?e.status:403,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},iE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"SessionExpired",this.code=typeof e.code=="number"?e.code:1002,this.message=e.message||"Session expired",this.status=typeof e.status=="number"?e.status:403,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},aE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"MethodNotFound",this.code=typeof e.code=="number"?e.code:1003,this.message=e.message||"Method not found",this.status=typeof e.status=="number"?e.status:404,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},oE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"RequestConflict",this.code=typeof e.code=="number"?e.code:1004,this.message=e.message||"Conflict with target resource",this.status=typeof e.status=="number"?e.status:409,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},cE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"Aborted",this.code=typeof e.code=="number"?e.code:1005,this.message=e.message||"Request aborted",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},uE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"Geoblocked",this.code=typeof e.code=="number"?e.code:1006,this.message=e.message||"Geoblocked region",this.status=typeof e.status=="number"?e.status:451,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},lE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"RateLimited",this.code=typeof e.code=="number"?e.code:1007,this.message=e.message||"Rate-limited. Please slow down.",this.status=typeof e.status=="number"?e.status:429,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},hE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"ProjectNotFound",this.code=typeof e.code=="number"?e.code:1008,this.message=e.message||"Project not found",this.status=typeof e.status=="number"?e.status:401,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},fE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"AccessKeyNotFound",this.code=typeof e.code=="number"?e.code:1101,this.message=e.message||"Access key not found",this.status=typeof e.status=="number"?e.status:401,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},dE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"AccessKeyMismatch",this.code=typeof e.code=="number"?e.code:1102,this.message=e.message||"Access key mismatch",this.status=typeof e.status=="number"?e.status:409,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},mE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"InvalidOrigin",this.code=typeof e.code=="number"?e.code:1103,this.message=e.message||"Invalid origin for Access Key",this.status=typeof e.status=="number"?e.status:403,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},pE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"InvalidService",this.code=typeof e.code=="number"?e.code:1104,this.message=e.message||"Service not enabled for Access key",this.status=typeof e.status=="number"?e.status:403,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},gE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"UnauthorizedUser",this.code=typeof e.code=="number"?e.code:1105,this.message=e.message||"Unauthorized user",this.status=typeof e.status=="number"?e.status:403,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},yE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"QuotaExceeded",this.code=typeof e.code=="number"?e.code:1200,this.message=e.message||"Quota request exceeded",this.status=typeof e.status=="number"?e.status:429,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},wE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"QuotaRateLimit",this.code=typeof e.code=="number"?e.code:1201,this.message=e.message||"Quota rate limit exceeded",this.status=typeof e.status=="number"?e.status:429,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},bE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"NoDefaultKey",this.code=typeof e.code=="number"?e.code:1300,this.message=e.message||"No default access key found",this.status=typeof e.status=="number"?e.status:403,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},SE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"MaxAccessKeys",this.code=typeof e.code=="number"?e.code:1301,this.message=e.message||"Access keys limit reached",this.status=typeof e.status=="number"?e.status:403,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},vE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"AtLeastOneKey",this.code=typeof e.code=="number"?e.code:1302,this.message=e.message||"You need at least one Access Key",this.status=typeof e.status=="number"?e.status:403,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},xE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"Timeout",this.code=typeof e.code=="number"?e.code:1900,this.message=e.message||"Request timed out",this.status=typeof e.status=="number"?e.status:408,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},EE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"InvalidArgument",this.code=typeof e.code=="number"?e.code:2001,this.message=e.message||"Invalid argument",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},AE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"Unavailable",this.code=typeof e.code=="number"?e.code:2002,this.message=e.message||"Unavailable resource",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},IE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"QueryFailed",this.code=typeof e.code=="number"?e.code:2003,this.message=e.message||"Query failed",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},CE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"NotFound",this.code=typeof e.code=="number"?e.code:3e3,this.message=e.message||"Resource not found",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},NE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"InsufficientFee",this.code=typeof e.code=="number"?e.code:3004,this.message=e.message||"Insufficient fee",this.status=typeof e.status=="number"?e.status:402,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},kE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"NotEnoughBalance",this.code=typeof e.code=="number"?e.code:3005,this.message=e.message||"Not enough balance",this.status=typeof e.status=="number"?e.status:402,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},PE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"SimulationFailed",this.code=typeof e.code=="number"?e.code:3006,this.message=e.message||"Simulation failed",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},y8;(function(s){s.WebrpcEndpoint="WebrpcEndpoint",s.WebrpcRequestFailed="WebrpcRequestFailed",s.WebrpcBadRoute="WebrpcBadRoute",s.WebrpcBadMethod="WebrpcBadMethod",s.WebrpcBadRequest="WebrpcBadRequest",s.WebrpcBadResponse="WebrpcBadResponse",s.WebrpcServerPanic="WebrpcServerPanic",s.WebrpcInternalError="WebrpcInternalError",s.WebrpcClientAborted="WebrpcClientAborted",s.WebrpcStreamLost="WebrpcStreamLost",s.WebrpcStreamFinished="WebrpcStreamFinished",s.Unauthorized="Unauthorized",s.PermissionDenied="PermissionDenied",s.SessionExpired="SessionExpired",s.MethodNotFound="MethodNotFound",s.RequestConflict="RequestConflict",s.Aborted="Aborted",s.Geoblocked="Geoblocked",s.RateLimited="RateLimited",s.ProjectNotFound="ProjectNotFound",s.AccessKeyNotFound="AccessKeyNotFound",s.AccessKeyMismatch="AccessKeyMismatch",s.InvalidOrigin="InvalidOrigin",s.InvalidService="InvalidService",s.UnauthorizedUser="UnauthorizedUser",s.QuotaExceeded="QuotaExceeded",s.QuotaRateLimit="QuotaRateLimit",s.NoDefaultKey="NoDefaultKey",s.MaxAccessKeys="MaxAccessKeys",s.AtLeastOneKey="AtLeastOneKey",s.Timeout="Timeout",s.InvalidArgument="InvalidArgument",s.Unavailable="Unavailable",s.QueryFailed="QueryFailed",s.NotFound="NotFound",s.InsufficientFee="InsufficientFee",s.NotEnoughBalance="NotEnoughBalance",s.SimulationFailed="SimulationFailed";})(y8||(y8={}));var w8;(function(s){s[s.WebrpcEndpoint=0]="WebrpcEndpoint",s[s.WebrpcRequestFailed=-1]="WebrpcRequestFailed",s[s.WebrpcBadRoute=-2]="WebrpcBadRoute",s[s.WebrpcBadMethod=-3]="WebrpcBadMethod",s[s.WebrpcBadRequest=-4]="WebrpcBadRequest",s[s.WebrpcBadResponse=-5]="WebrpcBadResponse",s[s.WebrpcServerPanic=-6]="WebrpcServerPanic",s[s.WebrpcInternalError=-7]="WebrpcInternalError",s[s.WebrpcClientAborted=-8]="WebrpcClientAborted",s[s.WebrpcStreamLost=-9]="WebrpcStreamLost",s[s.WebrpcStreamFinished=-10]="WebrpcStreamFinished",s[s.Unauthorized=1e3]="Unauthorized",s[s.PermissionDenied=1001]="PermissionDenied",s[s.SessionExpired=1002]="SessionExpired",s[s.MethodNotFound=1003]="MethodNotFound",s[s.RequestConflict=1004]="RequestConflict",s[s.Aborted=1005]="Aborted",s[s.Geoblocked=1006]="Geoblocked",s[s.RateLimited=1007]="RateLimited",s[s.ProjectNotFound=1008]="ProjectNotFound",s[s.AccessKeyNotFound=1101]="AccessKeyNotFound",s[s.AccessKeyMismatch=1102]="AccessKeyMismatch",s[s.InvalidOrigin=1103]="InvalidOrigin",s[s.InvalidService=1104]="InvalidService",s[s.UnauthorizedUser=1105]="UnauthorizedUser",s[s.QuotaExceeded=1200]="QuotaExceeded",s[s.QuotaRateLimit=1201]="QuotaRateLimit",s[s.NoDefaultKey=1300]="NoDefaultKey",s[s.MaxAccessKeys=1301]="MaxAccessKeys",s[s.AtLeastOneKey=1302]="AtLeastOneKey",s[s.Timeout=1900]="Timeout",s[s.InvalidArgument=2001]="InvalidArgument",s[s.Unavailable=2002]="Unavailable",s[s.QueryFailed=2003]="QueryFailed",s[s.NotFound=3e3]="NotFound",s[s.InsufficientFee=3004]="InsufficientFee",s[s.NotEnoughBalance=3005]="NotEnoughBalance",s[s.SimulationFailed=3006]="SimulationFailed";})(w8||(w8={}));var pV={0:Jx,[-1]:Te,[-2]:zx,[-3]:Yx,[-4]:Zx,[-5]:Ea,[-6]:Qx,[-7]:Xx,[-8]:eE,[-9]:tE,[-10]:sE,1e3:nE,1001:rE,1002:iE,1003:aE,1004:oE,1005:cE,1006:uE,1007:lE,1008:hE,1101:fE,1102:dE,1103:mE,1104:pE,1105:gE,1200:yE,1201:wE,1300:bE,1301:SE,1302:vE,1900:xE,2001:EE,2002:AE,2003:IE,3e3:CE,3004:NE,3005:kE,3006:PE};var Gg=class{address;min;max;constructor(e,t,n){this.address=e,this.min=t,this.max=n;}type(){return "native-balance"}isValid(){if(!this.address)return new Error("address is required");if(this.min!==void 0&&this.max!==void 0&&this.min>this.max)return new Error("min balance cannot be greater than max balance")}},Wg=class{address;token;min;max;constructor(e,t,n,r){this.address=e,this.token=t,this.min=n,this.max=r;}type(){return "erc20-balance"}isValid(){if(!this.address)return new Error("address is required");if(!this.token)return new Error("token address is required");if(this.min!==void 0&&this.max!==void 0&&this.min>this.max)return new Error("min balance cannot be greater than max balance")}},Jg=class{address;token;operator;min;constructor(e,t,n,r){this.address=e,this.token=t,this.operator=n,this.min=r;}type(){return "erc20-approval"}isValid(){if(!this.address)return new Error("address is required");if(!this.token)return new Error("token address is required");if(!this.operator)return new Error("operator address is required");if(this.min===void 0)return new Error("min approval amount is required")}},zg=class{address;token;tokenId;owned;constructor(e,t,n,r){this.address=e,this.token=t,this.tokenId=n,this.owned=r;}type(){return "erc721-ownership"}isValid(){if(!this.address)return new Error("address is required");if(!this.token)return new Error("token address is required");if(this.tokenId===void 0)return new Error("tokenId is required")}},Yg=class{address;token;tokenId;operator;constructor(e,t,n,r){this.address=e,this.token=t,this.tokenId=n,this.operator=r;}type(){return "erc721-approval"}isValid(){if(!this.address)return new Error("address is required");if(!this.token)return new Error("token address is required");if(this.tokenId===void 0)return new Error("tokenId is required");if(!this.operator)return new Error("operator address is required")}},Zg=class{address;token;tokenId;min;max;constructor(e,t,n,r,i){this.address=e,this.token=t,this.tokenId=n,this.min=r,this.max=i;}type(){return "erc1155-balance"}isValid(){if(!this.address)return new Error("address is required");if(!this.token)return new Error("token address is required");if(this.tokenId===void 0)return new Error("tokenId is required");if(this.min!==void 0&&this.max!==void 0&&this.min>this.max)return new Error("min balance cannot be greater than max balance")}},Qg=class{address;token;tokenId;operator;min;constructor(e,t,n,r,i){this.address=e,this.token=t,this.tokenId=n,this.operator=r,this.min=i;}type(){return "erc1155-approval"}isValid(){if(!this.address)return new Error("address is required");if(!this.token)return new Error("token address is required");if(this.tokenId===void 0)return new Error("tokenId is required");if(!this.operator)return new Error("operator address is required");if(this.min===void 0)return new Error("min approval amount is required")}};function Xg(s){if(!s)return;let e;try{switch(s.type){case"native-balance":e=new Gg(B.from(s.ownerAddress),s.minAmount,void 0);break;case"erc20-balance":e=new Wg(B.from(s.ownerAddress),B.from(s.tokenAddress),s.minAmount,void 0);break;case"erc20-approval":e=new Jg(B.from(s.ownerAddress),B.from(s.tokenAddress),B.from(s.ownerAddress),s.minAmount);break;case"erc721-ownership":e=new zg(B.from(s.ownerAddress),B.from(s.tokenAddress),BigInt(0),!0);break;case"erc721-approval":e=new Yg(B.from(s.ownerAddress),B.from(s.tokenAddress),BigInt(0),B.from(s.ownerAddress));break;case"erc1155-balance":e=new Zg(B.from(s.ownerAddress),B.from(s.tokenAddress),BigInt(0),s.minAmount,void 0);break;case"erc1155-approval":e=new Qg(B.from(s.ownerAddress),B.from(s.tokenAddress),BigInt(0),B.from(s.ownerAddress),s.minAmount);break;default:return}let t=e.isValid();if(t){console.warn(`Invalid precondition: ${t.message}`);return}return e}catch(t){console.warn(`Failed to decode precondition: ${t}`);return}}var e1=te.from("function balanceOf(address) returns (uint256)"),t1=te.from("function allowance(address,address) returns (uint256)"),s1=te.from("function ownerOf(uint256) returns (address)"),n1=te.from("function getApproved(uint256) returns (address)"),r1=te.from("function balanceOf(address,uint256) returns (uint256)"),i1=te.from("function isApprovedForAll(address,address) returns (bool)");var vV=s=>({id:s.chainId,name:s.title||s.name,nativeCurrency:{name:s.nativeCurrency.name,symbol:s.nativeCurrency.symbol,decimals:s.nativeCurrency.decimals},rpcUrls:{default:{http:[s.rpcUrl]}},blockExplorers:s.blockExplorer?{default:{name:s.blockExplorer.name||"Explorer",url:s.blockExplorer.url}}:void 0,contracts:s.ensAddress?{ensUniversalResolver:{address:s.ensAddress}}:void 0}),S8=s=>{let e=Sa.getNetworkFromChainId(s);if(e)return vV(e);let t=Object.values(SV).find(n=>typeof n=="object"&&"id"in n&&n.id===s);if(t)return t;throw new Error(`Chain with id ${s} not found in Sequence networks or viem chains`)},TE=class{kind="relayer";type="rpc";id;chainId;client;fetch;provider;projectAccessKey;constructor(e,t,n,r,i){this.id=`rpc:${e}`,this.chainId=t,this.projectAccessKey=i;let a=r||(typeof window<"u"?window.fetch.bind(window):void 0);if(!a)throw new Error("Fetch implementation is required but not available in this environment.");this.fetch=a,this.client=new _c(e,this.fetch);let o=S8(t);this.provider=createPublicClient({chain:o,transport:http(n)});}isAvailable(e,t){return Promise.resolve(this.chainId===t)}async feeTokens(){try{let{isFeeRequired:e,tokens:t,paymentAddress:n}=await this.client.feeTokens();return e?(B.assert(n),{isFeeRequired:e,tokens:t,paymentAddress:n}):{isFeeRequired:e}}catch(e){return console.warn("RpcRelayer.feeTokens failed:",e),{isFeeRequired:!1}}}async feeOptions(e,t,n){let r={type:"call",space:0n,nonce:0n,calls:n},i=ce.encode(r);try{let a=await this.client.feeOptions({wallet:e,to:e,data:f.toHex(i)},{...this.projectAccessKey?{"X-Access-Key":this.projectAccessKey}:void 0}),o=a.quote?{_tag:"FeeQuote",_quote:a.quote}:void 0;return {options:a.options.map(u=>({token:{...u.token,contractAddress:this.mapRpcFeeTokenToAddress(u.token)},to:u.to,value:u.value,gasLimit:u.gasLimit})),quote:o}}catch(a){return console.warn("RpcRelayer.feeOptions failed:",a),{options:[]}}}async sendMetaTxn(e,t,n,r,i,a){console.log("sendMetaTxn",e,t,n,r,i,a);let o={walletAddress:e,contract:t,input:n},c=await this.client.sendMetaTxn({call:o,quote:i?JSON.stringify(i._quote):void 0,preconditions:a},{...this.projectAccessKey?{"X-Access-Key":this.projectAccessKey}:void 0});if(!c.status)throw console.error("RpcRelayer.relay failed",c),new Error(`Relay failed: TxnHash ${c.txnHash}`);return {opHash:E.fromString(c.txnHash)}}async relay(e,t,n,r,i){console.log("relay",e,t,n,r,i);let a={walletAddress:e,contract:e,input:t},o=await this.client.sendMetaTxn({call:a,quote:r?JSON.stringify(r._quote):void 0,preconditions:i},{...this.projectAccessKey?{"X-Access-Key":this.projectAccessKey}:void 0});if(!o.status)throw console.error("RpcRelayer.relay failed",o),new Error(`Relay failed: TxnHash ${o.txnHash}`);return {opHash:`0x${o.txnHash}`}}async status(e,t){try{let n=e.startsWith("0x")?e.substring(2):e,r=await this.client.getMetaTxnReceipt({metaTxID:n}),i=r.receipt;if(!i)return console.warn(`RpcRelayer.status: receipt not found for opHash ${e}`),{status:"unknown"};if(!i.status)return console.warn(`RpcRelayer.status: receipt status not found for opHash ${e}`),{status:"unknown"};switch(i.status){case wt.QUEUED:case wt.PENDING_PRECONDITION:case wt.SENT:return {status:"pending"};case wt.SUCCEEDED:return {status:"confirmed",transactionHash:i.txnHash,data:r};case wt.FAILED:case wt.PARTIALLY_FAILED:return {status:"failed",transactionHash:i.txnHash?i.txnHash:void 0,reason:i.revertReason||"Relayer reported failure",data:r};case wt.DROPPED:return {status:"failed",reason:"Transaction dropped"};case wt.UNKNOWN:default:return {status:"unknown"}}}catch(n){return console.error(`RpcRelayer.status failed for opHash ${e}:`,n),{status:"failed",reason:"Failed to fetch status"}}}async checkPrecondition(e){let t=Xg(e);if(!t)return !1;switch(t.type()){case"native-balance":{let n=t;try{let r=await this.provider.getBalance({address:n.address.toString()}),i=n.min!==void 0?BigInt(n.min):void 0,a=n.max!==void 0?BigInt(n.max):void 0;return i!==void 0&&a!==void 0?r>=i&&r<=a:i!==void 0?r>=i:a!==void 0?r<=a:(console.warn("Native balance precondition has neither min nor max specified"),!1)}catch(r){return console.error("Error checking native balance:",r),!1}}case"erc20-balance":{let n=t;try{let r=te.encodeData(e1,[n.address.toString()]),i=await this.provider.call({to:n.token.toString(),data:r}),a=BigInt(i.toString()),o=n.min!==void 0?BigInt(n.min):void 0,c=n.max!==void 0?BigInt(n.max):void 0;return o!==void 0&&c!==void 0?a>=o&&a<=c:o!==void 0?a>=o:c!==void 0?a<=c:(console.warn("ERC20 balance precondition has neither min nor max specified"),!1)}catch(r){return console.error("Error checking ERC20 balance:",r),!1}}case"erc20-approval":{let n=t;try{let r=te.encodeData(t1,[n.address.toString(),n.operator.toString()]),i=await this.provider.call({to:n.token.toString(),data:r}),a=BigInt(i.toString()),o=BigInt(n.min);return a>=o}catch(r){return console.error("Error checking ERC20 approval:",r),!1}}case"erc721-ownership":{let n=t;try{let r=te.encodeData(s1,[n.tokenId]),c=(await this.provider.call({to:n.token.toString(),data:r})).toString().slice(-40).toLowerCase()===n.address.toString().slice(2).toLowerCase(),u=n.owned!==void 0?n.owned:!0;return c===u}catch(r){return console.error("Error checking ERC721 ownership:",r),!1}}case"erc721-approval":{let n=t;try{let r=te.encodeData(n1,[n.tokenId]);return (await this.provider.call({to:n.token.toString(),data:r})).toString().slice(-40).toLowerCase()===n.operator.toString().slice(2).toLowerCase()}catch(r){return console.error("Error checking ERC721 approval:",r),!1}}case"erc1155-balance":{let n=t;try{let r=te.encodeData(r1,[n.address.toString(),n.tokenId]),i=await this.provider.call({to:n.token.toString(),data:r}),a=BigInt(i.toString()),o=n.min!==void 0?BigInt(n.min):void 0,c=n.max!==void 0?BigInt(n.max):void 0;return o!==void 0&&c!==void 0?a>=o&&a<=c:o!==void 0?a>=o:c!==void 0?a<=c:(console.warn("ERC1155 balance precondition has neither min nor max specified"),!1)}catch(r){return console.error("Error checking ERC1155 balance:",r),!1}}case"erc1155-approval":{let n=t;try{let r=te.encodeData(i1,[n.address.toString(),n.operator.toString()]),i=await this.provider.call({to:n.token.toString(),data:r});return BigInt(i.toString())===1n}catch(r){return console.error("Error checking ERC1155 approval:",r),!1}}default:return !1}}mapRpcFeeTokenToAddress(e){return e.type===Kg.ERC20_TOKEN&&e.contractAddress?B.from(e.contractAddress):_e.ZeroAddress}};var Aa=class s{provider;kind="relayer";type="local";id="local";constructor(e){this.provider=e;}isAvailable(e,t){return Promise.resolve(!0)}static createFromWindow(e){let t=e.ethereum;if(!t){console.warn("Window.ethereum not found, skipping local relayer");return}return new s(new Ia(t))}static createFromProvider(e){return new s(new Ia(e))}feeTokens(){return Promise.resolve({isFeeRequired:!1})}feeOptions(e,t,n){return Promise.resolve({options:[]})}decodeCalls(e){let t=te.getSelector(_e.EXECUTE),n;return e.startsWith(t)?n=te.decodeData(_e.EXECUTE,e)[0]:n=e,ce.decode(f.fromHex(n))}async relay(e,t,n,r,i,a=5e3){let o=async()=>{if(!i||i.length===0)return !0;for(let c of i)if(!await this.checkPrecondition(c))return !1;return !0};return await o()?{opHash:await this.provider.sendTransaction({to:e,data:t},n)}:new Promise((c,u)=>{let l,h=!1,m=async()=>{try{if(h)return;if(await o()){h=!0,clearTimeout(l);let y=await this.provider.sendTransaction({to:e,data:t},n);c({opHash:y});}else l=setTimeout(m,a);}catch(y){h=!0,clearTimeout(l),u(y);}};return l=setTimeout(m,a),()=>{h=!0,clearTimeout(l);}})}async status(e,t){let n=await this.provider.getTransactionReceipt(e,t);return n==="unknown"?{status:"unknown"}:n==="success"?{status:"confirmed",transactionHash:e}:{status:"failed",reason:"failed"}}async checkPrecondition(e){let t=Xg(e);if(!t)return !1;switch(t.type()){case"native-balance":{let n=t,r=await this.provider.getBalance(n.address.toString());return !(n.min!==void 0&&r<n.min||n.max!==void 0&&r>n.max)}case"erc20-balance":{let n=t,r=te.encodeData(e1,[n.address.toString()]),i=await this.provider.call({to:n.token.toString(),data:r}),a=BigInt(i);return !(n.min!==void 0&&a<n.min||n.max!==void 0&&a>n.max)}case"erc20-approval":{let n=t,r=te.encodeData(t1,[n.address.toString(),n.operator.toString()]),i=await this.provider.call({to:n.token.toString(),data:r});return BigInt(i)>=n.min}case"erc721-ownership":{let n=t,r=te.encodeData(s1,[n.tokenId]),o=("0x"+(await this.provider.call({to:n.token.toString(),data:r})).slice(26)).toLowerCase()===n.address.toString().toLowerCase();return n.owned===void 0?o:n.owned===o}case"erc721-approval":{let n=t,r=te.encodeData(n1,[n.tokenId]);return ("0x"+(await this.provider.call({to:n.token.toString(),data:r})).slice(26)).toLowerCase()===n.operator.toString().toLowerCase()}case"erc1155-balance":{let n=t,r=te.encodeData(r1,[n.address.toString(),n.tokenId]),i=await this.provider.call({to:n.token.toString(),data:r}),a=BigInt(i);return !(n.min!==void 0&&a<n.min||n.max!==void 0&&a>n.max)}case"erc1155-approval":{let n=t,r=te.encodeData(i1,[n.address.toString(),n.operator.toString()]),i=await this.provider.call({to:n.token.toString(),data:r});return BigInt(i)===1n}default:return !1}}},Ia=class{provider;constructor(e){this.provider=e;}async trySwitchChain(e){try{await this.provider.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${e.toString(16)}`}]});}catch(t){console.error("Error switching chain",t);}}async sendTransaction(e,t){let r=(await this.provider.request({method:"eth_requestAccounts"}))[0];if(!r){console.warn("No account selected, skipping local relayer");return}return await this.trySwitchChain(t),await this.provider.request({method:"eth_sendTransaction",params:[{from:r,to:e.to,data:e.data}]})}async getBalance(e){let t=await this.provider.request({method:"eth_getBalance",params:[e,"latest"]});return BigInt(t)}async call(e){return await this.provider.request({method:"eth_call",params:[e,"latest"]})}async getTransactionReceipt(e,t){await this.trySwitchChain(t);let n=await this.provider.request({method:"eth_getTransactionReceipt",params:[e]});if(n){let r=kc.fromRpc(n);if(r?.status==="success")return "success";if(r?.status==="reverted")return "failed"}return "unknown"}};var BE=class{provider;kind="relayer";type="pk";id="pk";relayer;constructor(e,t){this.provider=t;let n=B.fromPublicKey(Ot.getPublicKey({privateKey:e}));this.relayer=new Aa({sendTransaction:async(r,i)=>{if(Number(await this.provider.request({method:"eth_chainId"}))!==i)throw new Error("Provider chain id does not match relayer chain id");let o={...r,to:r.to,data:r.data},c=BigInt(await this.provider.request({method:"eth_estimateGas",params:[o]})),u=c>21000n?c*12n/10n:50000n,l=BigInt(await this.provider.request({method:"eth_gasPrice"})),h=100000000n,m=l+h,y=BigInt(await this.provider.request({method:"eth_getBalance",params:[n,"latest"]}));if(y<m*u)throw console.log("Sender balance:",y.toString(),"wei"),new Error("Sender has insufficient balance to pay for gas");let g=BigInt(await this.provider.request({method:"eth_getTransactionCount",params:[n,"latest"]})),w=pa.from({chainId:Number(i),type:"eip1559",from:n,to:o.to,data:o.data,gas:u,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:g,value:0n}),S=Ot.sign({payload:pa.getSignPayload(w),privateKey:e}),C=pa.from(w,{signature:S});return await this.provider.request({method:"eth_sendRawTransaction",params:[pa.serialize(C)]})},getBalance:async r=>{let i=await this.provider.request({method:"eth_getBalance",params:[r,"latest"]});return BigInt(i)},call:async r=>{let i={to:r.to,data:r.data};return await this.provider.request({method:"eth_call",params:[i,"latest"]})},getTransactionReceipt:async(r,i)=>{if(E.assert(r),Number(await this.provider.request({method:"eth_chainId"}))!==i)throw new Error("Provider chain id does not match relayer chain id");let o=await this.provider.request({method:"eth_getTransactionReceipt",params:[r]});return o?kc.fromRpc(o).status==="success"?"success":"failed":"unknown"}});}async isAvailable(e,t){return Number(await this.provider.request({method:"eth_chainId"}))===t}feeTokens(){return this.relayer.feeTokens()}feeOptions(e,t,n){return this.relayer.feeOptions(e,t,n)}async relay(e,t,n,r){if(Number(await this.provider.request({method:"eth_chainId"}))!==n)throw new Error("Provider chain id does not match relayer chain id");return this.relayer.relay(e,t,n)}status(e,t){return this.relayer.status(e,t)}async checkPrecondition(e){return !0}};var OE=class{kind="relayer";type="sequence";id="sequence";service;constructor(e){this.service=new _c(e,fetch);}async isAvailable(e,t){return !0}async feeTokens(){let{isFeeRequired:e,tokens:t,paymentAddress:n}=await this.service.feeTokens();return e?(B.assert(n),{isFeeRequired:e,tokens:t,paymentAddress:n}):{isFeeRequired:e}}async feeOptions(e,t,n){let r=e,i=te.from("function execute(bytes calldata _payload, bytes calldata _signature)"),a=ce.encode({type:"call",space:0n,nonce:0n,calls:n},r),c=te.encodeData(i,[f.toHex(a),"0x0001"]),{options:u,quote:l}=await this.service.feeOptions({wallet:e,to:r,data:c});return {options:u,quote:l?{_tag:"FeeQuote",_quote:l}:void 0}}async checkPrecondition(e){return !1}async relay(e,t,n,r){let i=e,{txnHash:a}=await this.service.sendMetaTxn({call:{walletAddress:i,contract:e,input:t},quote:r&&r._quote});return {opHash:`0x${a}`}}async status(e,t){try{let{receipt:{status:n,revertReason:r,txnReceipt:i}}=await this.service.getMetaTxnReceipt({metaTxID:e});switch(n){case wt.UNKNOWN:return {status:"unknown"};case wt.DROPPED:return {status:"failed",reason:r??n};case wt.QUEUED:return {status:"pending"};case wt.SENT:return {status:"pending"};case wt.SUCCEEDED:{let o=JSON.parse(i).transactionHash;return E.assert(o),{status:"confirmed",transactionHash:o}}case wt.PARTIALLY_FAILED:return {status:"failed",reason:r??n};case wt.FAILED:return {status:"failed",reason:r??n};default:throw new Error(`unknown transaction status '${n}'`)}}catch{return {status:"pending"}}}};var LE={};be(LE,{EIP6963Relayer:()=>a1,getEIP6963Store:()=>x8,getRelayers:()=>xV});function v8(s){if(typeof window>"u")return;let e=t=>s(t.detail);return window.addEventListener("eip6963:announceProvider",e),window.dispatchEvent(new CustomEvent("eip6963:requestProvider")),()=>window.removeEventListener("eip6963:announceProvider",e)}function RE(){let s=new Set,e=[],t=()=>v8(r=>{e.some(({info:i})=>i.uuid===r.info.uuid)||(e=[...e,r],s.forEach(i=>i(e,{added:[r]})));}),n=t();return {_listeners(){return s},clear(){s.forEach(r=>r([],{removed:[...e]})),e=[];},destroy(){this.clear(),s.clear(),n?.();},findProvider({rdns:r}){return e.find(i=>i.info.rdns===r)},getProviders(){return e},reset(){this.clear(),n?.(),n=t();},subscribe(r,{emitImmediately:i}={}){return s.add(r),i&&r(e,{added:e}),()=>s.delete(r)}}}var a1=class{kind="relayer";type="eip6963";id;info;relayer;constructor(e){this.info=e.info,this.id=e.info.uuid,this.relayer=new Aa(new Ia(e.provider));}isAvailable(e,t){return this.relayer.isAvailable(e,t)}feeTokens(){return this.relayer.feeTokens()}feeOptions(e,t,n){return this.relayer.feeOptions(e,t,n)}async relay(e,t,n,r){return this.relayer.relay(e,t,n)}status(e,t){return this.relayer.status(e,t)}async checkPrecondition(e){return this.relayer.checkPrecondition(e)}},VE;function x8(){return VE||(VE=RE()),VE}var DE=new Map;function xV(){let e=x8().getProviders();for(let t of e)DE.has(t.info.uuid)||DE.set(t.info.uuid,new a1(t));return Array.from(DE.values())}function EV(s){return "isAvailable"in s&&"feeOptions"in s&&"relay"in s&&"status"in s&&"checkPrecondition"in s}var $={POS_INT:0,NEG_INT:1,BYTE_STRING:2,UTF8_STRING:3,ARRAY:4,MAP:5,TAG:6,SIMPLE_FLOAT:7},Qe={DATE_STRING:0,DATE_EPOCH:1,POS_BIGINT:2,NEG_BIGINT:3,DECIMAL_FRAC:4,BIGFLOAT:5,BASE64URL_EXPECTED:21,BASE64_EXPECTED:22,BASE16_EXPECTED:23,CBOR:24,URI:32,BASE64URL:33,BASE64:34,MIME:36,SET:258,JSON:262,REGEXP:21066,SELF_DESCRIBED:55799,INVALID_16:65535,INVALID_32:4294967295,INVALID_64:0xffffffffffffffffn},Se={ZERO:0,ONE:24,TWO:25,FOUR:26,EIGHT:27,INDEFINITE:31},dn={FALSE:20,TRUE:21,NULL:22,UNDEFINED:23},st=class{static BREAK=Symbol.for("github.com/hildjj/cbor2/break");static ENCODED=Symbol.for("github.com/hildjj/cbor2/cbor-encoded");static LENGTH=Symbol.for("github.com/hildjj/cbor2/length")},Mc={MIN:-(2n**63n),MAX:2n**64n-1n};var we=class s{static#e=new Map;tag;contents;constructor(e,t=void 0){this.tag=e,this.contents=t;}get noChildren(){return !!s.#e.get(this.tag)?.noChildren}static registerDecoder(e,t,n){let r=this.#e.get(e);return this.#e.set(e,t),r&&("comment"in t||(t.comment=r.comment),"noChildren"in t||(t.noChildren=r.noChildren)),n&&!t.comment&&(t.comment=()=>`(${n})`),r}static clearDecoder(e){let t=this.#e.get(e);return this.#e.delete(e),t}static getDecoder(e){return this.#e.get(e)}static getAllDecoders(){return new Map(this.#e)}*[Symbol.iterator](){yield this.contents;}push(e){return this.contents=e,1}decode(e){let t=s.#e.get(this.tag);return t?t(this,e):this}comment(e,t){let n=s.#e.get(this.tag);if(n?.comment)return n.comment(this,e,t)}toCBOR(){return [this.tag,this.contents]}[Symbol.for("nodejs.util.inspect.custom")](e,t,n){return `${this.tag}(${n(this.contents,t)})`}};function Lr(s){if(s!=null&&typeof s=="object")return s[st.ENCODED]}function E8(s){if(s!=null&&typeof s=="object")return s[st.LENGTH]}function jr(s,e){Object.defineProperty(s,st.ENCODED,{configurable:!0,enumerable:!1,value:e});}function Ur(s,e){let t=Object(s);return jr(t,e),t}var jE=Symbol("CBOR_RANGES");function A8(s,e){Object.defineProperty(s,jE,{configurable:!1,enumerable:!1,writable:!1,value:e});}function tf(s){return s[jE]}function AV(s){return tf(s)!==void 0}function sf(s,e=0,t=s.length-1){let n=s.subarray(e,t),r=tf(s);if(r){let i=[];for(let a of r)if(a[0]>=e&&a[0]+a[1]<=t){let o=[...a];o[0]-=e,i.push(o);}i.length&&A8(n,i);}return n}function o1(s){let e=Math.ceil(s.length/2),t=new Uint8Array(e);e--;for(let n=s.length,r=n-2;n>=0;n=r,r-=2,e--)t[e]=parseInt(s.substring(r,n),16);return t}function Vt(s){return s.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function I8(s){let e=s.reduce((a,o)=>a+o.length,0),t=s.some(a=>AV(a)),n=[],r=new Uint8Array(e),i=0;for(let a of s){if(!(a instanceof Uint8Array))throw new TypeError(`Invalid array: ${a}`);if(r.set(a,i),t){let o=a[jE]??[[0,a.length]];for(let c of o)c[0]+=i;n.push(...o);}i+=a.length;}return t&&A8(r,n),r}function nf(s){let e=atob(s);return Uint8Array.from(e,t=>t.codePointAt(0))}var IV={"-":"+",_:"/"};function C8(s){let e=s.replace(/[_-]/g,t=>IV[t]);return nf(e.padEnd(Math.ceil(e.length/4)*4,"="))}function N8(){let s=new Uint8Array(4),e=new Uint32Array(s.buffer);return !((e[0]=1)&s[0])}function UE(s){let e="";for(let t of s){let n=t.codePointAt(0)?.toString(16).padStart(4,"0");e&&(e+=", "),e+=`U+${n}`;}return e}function c1(s,e){let[t,n,r]=s,[i,a,o]=e,c=Math.min(r.length,o.length);for(let u=0;u<c;u++){let l=r[u]-o[u];if(l!==0)return l}return 0}var rf=class s{static defaultOptions={chunkSize:4096};#e;#s=[];#n=null;#t=0;#a=0;constructor(e={}){if(this.#e={...s.defaultOptions,...e},this.#e.chunkSize<8)throw new RangeError(`Expected size >= 8, got ${this.#e.chunkSize}`);this.#i();}get length(){return this.#a}read(){this.#r();let e=new Uint8Array(this.#a),t=0;for(let n of this.#s)e.set(n,t),t+=n.length;return this.#i(),e}write(e){let t=e.length;t>this.#u()?(this.#r(),t>this.#e.chunkSize?(this.#s.push(e),this.#i()):(this.#i(),this.#s[this.#s.length-1].set(e),this.#t=t)):(this.#s[this.#s.length-1].set(e,this.#t),this.#t+=t),this.#a+=t;}writeUint8(e){this.#c(1),this.#n.setUint8(this.#t,e),this.#o(1);}writeUint16(e,t=!1){this.#c(2),this.#n.setUint16(this.#t,e,t),this.#o(2);}writeUint32(e,t=!1){this.#c(4),this.#n.setUint32(this.#t,e,t),this.#o(4);}writeBigUint64(e,t=!1){this.#c(8),this.#n.setBigUint64(this.#t,e,t),this.#o(8);}writeInt16(e,t=!1){this.#c(2),this.#n.setInt16(this.#t,e,t),this.#o(2);}writeInt32(e,t=!1){this.#c(4),this.#n.setInt32(this.#t,e,t),this.#o(4);}writeBigInt64(e,t=!1){this.#c(8),this.#n.setBigInt64(this.#t,e,t),this.#o(8);}writeFloat32(e,t=!1){this.#c(4),this.#n.setFloat32(this.#t,e,t),this.#o(4);}writeFloat64(e,t=!1){this.#c(8),this.#n.setFloat64(this.#t,e,t),this.#o(8);}clear(){this.#a=0,this.#s=[],this.#i();}#i(){let e=new Uint8Array(this.#e.chunkSize);this.#s.push(e),this.#t=0,this.#n=new DataView(e.buffer,e.byteOffset,e.byteLength);}#r(){if(this.#t===0){this.#s.pop();return}let e=this.#s.length-1;this.#s[e]=this.#s[e].subarray(0,this.#t),this.#t=0,this.#n=null;}#u(){let e=this.#s.length-1;return this.#s[e].length-this.#t}#c(e){this.#u()<e&&(this.#r(),this.#i());}#o(e){this.#t+=e,this.#a+=e;}};function HE(s,e=0,t=!1){let n=s[e]&128?-1:1,r=(s[e]&124)>>2,i=(s[e]&3)<<8|s[e+1];if(r===0){if(t&&i!==0)throw new Error(`Unwanted subnormal: ${n*5960464477539063e-23*i}`);return n*5960464477539063e-23*i}else if(r===31)return i?NaN:n*(1/0);return n*2**(r-25)*(1024+i)}function u1(s){let e=new DataView(new ArrayBuffer(4));e.setFloat32(0,s,!1);let t=e.getUint32(0,!1);if(t&8191)return null;let n=t>>16&32768,r=t>>23&255,i=t&8388607;if(!(r===0&&i===0))if(r>=113&&r<=142)n+=(r-112<<10)+(i>>13);else if(r>=103&&r<113){if(i&(1<<126-r)-1)return null;n+=i+8388608>>126-r;}else if(r===255)n|=31744,n|=i>>13;else return null;return n}function k8(s){if(s!==0){let e=new ArrayBuffer(8),t=new DataView(e);t.setFloat64(0,s,!1);let n=t.getBigUint64(0,!1);if((n&0x7ff0000000000000n)===0n)return n&0x8000000000000000n?-0:0}return s}function P8(s){switch(s.length){case 2:HE(s,0,!0);break;case 4:{let e=new DataView(s.buffer,s.byteOffset,s.byteLength),t=e.getUint32(0,!1);if(!(t&2139095040)&&t&8388607)throw new Error(`Unwanted subnormal: ${e.getFloat32(0,!1)}`);break}case 8:{let e=new DataView(s.buffer,s.byteOffset,s.byteLength),t=e.getBigUint64(0,!1);if((t&0x7ff0000000000000n)===0n&&t&0x000fffffffffffn)throw new Error(`Unwanted subnormal: ${e.getFloat64(0,!1)}`);break}default:throw new TypeError(`Bad input to isSubnormal: ${s}`)}}var T8=$.SIMPLE_FLOAT<<5|Se.TWO,CV=$.SIMPLE_FLOAT<<5|Se.FOUR,NV=$.SIMPLE_FLOAT<<5|Se.EIGHT,kV=$.SIMPLE_FLOAT<<5|dn.TRUE,PV=$.SIMPLE_FLOAT<<5|dn.FALSE,TV=$.SIMPLE_FLOAT<<5|dn.UNDEFINED,BV=$.SIMPLE_FLOAT<<5|dn.NULL,OV=new TextEncoder,l1={...rf.defaultOptions,avoidInts:!1,cde:!1,collapseBigInts:!0,dcbor:!1,float64:!1,flushToZero:!1,forceEndian:null,ignoreOriginalEncoding:!1,largeNegativeAsBigInt:!1,reduceUnsafeNumbers:!1,rejectBigInts:!1,rejectCustomSimples:!1,rejectDuplicateKeys:!1,rejectFloats:!1,rejectUndefined:!1,simplifyNegativeZero:!1,sortKeys:null,stringNormalization:null},$E={cde:!0,ignoreOriginalEncoding:!0,sortKeys:c1},B8={...$E,dcbor:!0,largeNegativeAsBigInt:!0,reduceUnsafeNumbers:!0,rejectCustomSimples:!0,rejectDuplicateKeys:!0,rejectUndefined:!0,simplifyNegativeZero:!0,stringNormalization:"NFC"};function O8(s){let e=s<0;return typeof s=="bigint"?[e?-s-1n:s,e]:[e?-s-1:s,e]}function _E(s,e,t){if(t.rejectFloats)throw new Error(`Attempt to encode an unwanted floating point number: ${s}`);if(isNaN(s))e.writeUint8(T8),e.writeUint16(32256);else if(!t.float64&&Math.fround(s)===s){let n=u1(s);n===null?(e.writeUint8(CV),e.writeFloat32(s)):(e.writeUint8(T8),e.writeUint16(n));}else e.writeUint8(NV),e.writeFloat64(s);}function vs(s,e,t){let[n,r]=O8(s);if(r&&t)throw new TypeError(`Negative size: ${s}`);t??=r?$.NEG_INT:$.POS_INT,t<<=5,n<24?e.writeUint8(t|n):n<=255?(e.writeUint8(t|Se.ONE),e.writeUint8(n)):n<=65535?(e.writeUint8(t|Se.TWO),e.writeUint16(n)):n<=4294967295?(e.writeUint8(t|Se.FOUR),e.writeUint32(n)):(e.writeUint8(t|Se.EIGHT),e.writeBigUint64(BigInt(n)));}function af(s,e,t){typeof s=="number"?vs(s,e,$.TAG):typeof s=="object"&&!t.ignoreOriginalEncoding&&st.ENCODED in s?e.write(s[st.ENCODED]):s<=Number.MAX_SAFE_INTEGER?vs(Number(s),e,$.TAG):(e.writeUint8($.TAG<<5|Se.EIGHT),e.writeBigUint64(BigInt(s)));}function R8(s,e,t){let[n,r]=O8(s);if(t.collapseBigInts&&(!t.largeNegativeAsBigInt||s>=-0x8000000000000000n)){if(n<=0xffffffffn){vs(Number(s),e);return}if(n<=0xffffffffffffffffn){let u=(r?$.NEG_INT:$.POS_INT)<<5;e.writeUint8(u|Se.EIGHT),e.writeBigUint64(n);return}}if(t.rejectBigInts)throw new Error(`Attempt to encode unwanted bigint: ${s}`);let i=r?Qe.NEG_BIGINT:Qe.POS_BIGINT,a=n.toString(16),o=a.length%2?"0":"";af(i,e,t);let c=o1(o+a);vs(c.length,e,$.BYTE_STRING),e.write(c);}function RV(s,e,t){t.flushToZero&&(s=k8(s)),Object.is(s,-0)?t.simplifyNegativeZero?t.avoidInts?_E(0,e,t):vs(0,e):_E(s,e,t):!t.avoidInts&&Number.isSafeInteger(s)?vs(s,e):t.reduceUnsafeNumbers&&Math.floor(s)===s&&s>=Mc.MIN&&s<=Mc.MAX?R8(BigInt(s),e,t):_E(s,e,t);}function VV(s,e,t){let n=t.stringNormalization?s.normalize(t.stringNormalization):s,r=OV.encode(n);vs(r.length,e,$.UTF8_STRING),e.write(r);}function DV(s,e,t){let n=s;h1(n,n.length,$.ARRAY,e,t);for(let r of n)Hr(r,e,t);}function LV(s,e){let t=s;vs(t.length,e,$.BYTE_STRING),e.write(t);}var ME=new Map([[Array,DV],[Uint8Array,LV]]);function it(s,e){let t=ME.get(s);return ME.set(s,e),t}function h1(s,e,t,n,r){let i=E8(s);i&&!r.ignoreOriginalEncoding?n.write(i):vs(e,n,t);}function jV(s,e,t){if(s===null){e.writeUint8(BV);return}if(!t.ignoreOriginalEncoding&&st.ENCODED in s){e.write(s[st.ENCODED]);return}let n=ME.get(s.constructor);if(n){let i=n(s,e,t);i&&((typeof i[0]=="bigint"||isFinite(Number(i[0])))&&af(i[0],e,t),Hr(i[1],e,t));return}if(typeof s.toCBOR=="function"){let i=s.toCBOR(e,t);i&&((typeof i[0]=="bigint"||isFinite(Number(i[0])))&&af(i[0],e,t),Hr(i[1],e,t));return}if(typeof s.toJSON=="function"){Hr(s.toJSON(),e,t);return}let r=Object.entries(s).map(i=>[i[0],i[1],$n(i[0],t)]);t.sortKeys&&r.sort(t.sortKeys),h1(s,r.length,$.MAP,e,t);for(let[i,a,o]of r)e.write(o),Hr(a,e,t);}function Hr(s,e,t){switch(typeof s){case"number":RV(s,e,t);break;case"bigint":R8(s,e,t);break;case"string":VV(s,e,t);break;case"boolean":e.writeUint8(s?kV:PV);break;case"undefined":if(t.rejectUndefined)throw new Error("Attempt to encode unwanted undefined.");e.writeUint8(TV);break;case"object":jV(s,e,t);break;case"symbol":throw new TypeError(`Unknown symbol: ${s.toString()}`);default:throw new TypeError(`Unknown type: ${typeof s}, ${String(s)}`)}}function $n(s,e={}){let t={...l1};e.dcbor?Object.assign(t,B8):e.cde&&Object.assign(t,$E),Object.assign(t,e);let n=new rf(t);return Hr(s,n,t),n.read()}var Ca=(s=>(s[s.NEVER=-1]="NEVER",s[s.PREFERRED=0]="PREFERRED",s[s.ALWAYS=1]="ALWAYS",s))(Ca||{});var Ws=class s{static KnownSimple=new Map([[dn.FALSE,!1],[dn.TRUE,!0],[dn.NULL,null],[dn.UNDEFINED,void 0]]);value;constructor(e){this.value=e;}static create(e){return s.KnownSimple.has(e)?s.KnownSimple.get(e):new s(e)}toCBOR(e,t){if(t.rejectCustomSimples)throw new Error(`Cannot encode non-standard Simple value: ${this.value}`);vs(this.value,e,$.SIMPLE_FLOAT);}toString(){return `simple(${this.value})`}decode(){return s.KnownSimple.has(this.value)?s.KnownSimple.get(this.value):this}[Symbol.for("nodejs.util.inspect.custom")](e,t,n){return `simple(${n(this.value,t)})`}};var UV=new TextDecoder("utf8",{fatal:!0,ignoreBOM:!0}),qn=class s{static defaultOptions={maxDepth:1024,encoding:"hex",requirePreferred:!1};#e;#s;#n=0;#t;constructor(e,t){if(this.#t={...s.defaultOptions,...t},typeof e=="string")switch(this.#t.encoding){case"hex":this.#e=o1(e);break;case"base64":this.#e=nf(e);break;default:throw new TypeError(`Encoding not implemented: "${this.#t.encoding}"`)}else this.#e=e;this.#s=new DataView(this.#e.buffer,this.#e.byteOffset,this.#e.byteLength);}toHere(e){return sf(this.#e,e,this.#n)}*[Symbol.iterator](){if(yield*this.#a(0),this.#n!==this.#e.length)throw new Error("Extra data in input")}*#a(e){if(e++>this.#t.maxDepth)throw new Error(`Maximum depth ${this.#t.maxDepth} exceeded`);let t=this.#n,n=this.#s.getUint8(this.#n++),r=n>>5,i=n&31,a=i,o=!1,c=0;switch(i){case Se.ONE:if(c=1,a=this.#s.getUint8(this.#n),r===$.SIMPLE_FLOAT){if(a<32)throw new Error(`Invalid simple encoding in extra byte: ${a}`);o=!0;}else if(this.#t.requirePreferred&&a<24)throw new Error(`Unexpectedly long integer encoding (1) for ${a}`);break;case Se.TWO:if(c=2,r===$.SIMPLE_FLOAT)a=HE(this.#e,this.#n);else if(a=this.#s.getUint16(this.#n,!1),this.#t.requirePreferred&&a<=255)throw new Error(`Unexpectedly long integer encoding (2) for ${a}`);break;case Se.FOUR:if(c=4,r===$.SIMPLE_FLOAT)a=this.#s.getFloat32(this.#n,!1);else if(a=this.#s.getUint32(this.#n,!1),this.#t.requirePreferred&&a<=65535)throw new Error(`Unexpectedly long integer encoding (4) for ${a}`);break;case Se.EIGHT:{if(c=8,r===$.SIMPLE_FLOAT)a=this.#s.getFloat64(this.#n,!1);else if(a=this.#s.getBigUint64(this.#n,!1),a<=Number.MAX_SAFE_INTEGER&&(a=Number(a)),this.#t.requirePreferred&&a<=4294967295)throw new Error(`Unexpectedly long integer encoding (8) for ${a}`);break}case 28:case 29:case 30:throw new Error(`Additional info not implemented: ${i}`);case Se.INDEFINITE:switch(r){case $.POS_INT:case $.NEG_INT:case $.TAG:throw new Error(`Invalid indefinite encoding for MT ${r}`);case $.SIMPLE_FLOAT:yield [r,i,st.BREAK,t,0];return}a=1/0;break;default:o=!0;}switch(this.#n+=c,r){case $.POS_INT:yield [r,i,a,t,c];break;case $.NEG_INT:yield [r,i,typeof a=="bigint"?-1n-a:-1-Number(a),t,c];break;case $.BYTE_STRING:a===1/0?yield*this.#r(r,e,t):yield [r,i,this.#i(a),t,a];break;case $.UTF8_STRING:a===1/0?yield*this.#r(r,e,t):yield [r,i,UV.decode(this.#i(a)),t,a];break;case $.ARRAY:if(a===1/0)yield*this.#r(r,e,t,!1);else {let u=Number(a);yield [r,i,u,t,c];for(let l=0;l<u;l++)yield*this.#a(e+1);}break;case $.MAP:if(a===1/0)yield*this.#r(r,e,t,!1);else {let u=Number(a);yield [r,i,u,t,c];for(let l=0;l<u;l++)yield*this.#a(e),yield*this.#a(e);}break;case $.TAG:yield [r,i,a,t,c],yield*this.#a(e);break;case $.SIMPLE_FLOAT:{let u=a;o&&(a=Ws.create(Number(a))),yield [r,i,a,t,u];break}}}#i(e){let t=sf(this.#e,this.#n,this.#n+=e);if(t.length!==e)throw new Error(`Unexpected end of stream reading ${e} bytes, got ${t.length}`);return t}*#r(e,t,n,r=!0){for(yield [e,Se.INDEFINITE,1/0,n,1/0];;){let i=this.#a(t),a=i.next(),[o,c,u]=a.value;if(u===st.BREAK){yield a.value,i.next();return}if(r){if(o!==e)throw new Error(`Unmatched major type. Expected ${e}, got ${o}.`);if(c===Se.INDEFINITE)throw new Error("New stream started in typed stream")}yield a.value,yield*i;}}};var HV=new Map([[Se.ZERO,1],[Se.ONE,2],[Se.TWO,3],[Se.FOUR,5],[Se.EIGHT,9]]),_V=new Uint8Array(0);function MV(s,e){return !e.boxed&&!e.preferMap&&s.every(([t])=>typeof t=="string")?Object.fromEntries(s):new Map(s)}var ts=class s{static defaultDecodeOptions={...qn.defaultOptions,ParentType:s,boxed:!1,cde:!1,dcbor:!1,diagnosticSizes:Ca.PREFERRED,convertUnsafeIntsToFloat:!1,createObject:MV,pretty:!1,preferMap:!1,rejectLargeNegatives:!1,rejectBigInts:!1,rejectDuplicateKeys:!1,rejectFloats:!1,rejectInts:!1,rejectLongLoundNaN:!1,rejectLongFloats:!1,rejectNegativeZero:!1,rejectSimple:!1,rejectStreaming:!1,rejectStringsNotNormalizedAs:null,rejectSubnormals:!1,rejectUndefined:!1,rejectUnsafeFloatInts:!1,saveOriginal:!1,sortKeys:null};static cdeDecodeOptions={cde:!0,rejectStreaming:!0,requirePreferred:!0,sortKeys:c1};static dcborDecodeOptions={...this.cdeDecodeOptions,dcbor:!0,convertUnsafeIntsToFloat:!0,rejectDuplicateKeys:!0,rejectLargeNegatives:!0,rejectLongLoundNaN:!0,rejectLongFloats:!0,rejectNegativeZero:!0,rejectSimple:!0,rejectUndefined:!0,rejectUnsafeFloatInts:!0,rejectStringsNotNormalizedAs:"NFC"};parent;mt;ai;left;offset;count=0;children=[];depth=0;#e;#s=null;constructor(e,t,n,r){if([this.mt,this.ai,,this.offset]=e,this.left=t,this.parent=n,this.#e=r,n&&(this.depth=n.depth+1),this.mt===$.MAP&&(this.#e.sortKeys||this.#e.rejectDuplicateKeys)&&(this.#s=[]),this.#e.rejectStreaming&&this.ai===Se.INDEFINITE)throw new Error("Streaming not supported")}get isStreaming(){return this.left===1/0}get done(){return this.left===0}static create(e,t,n,r){let[i,a,o,c]=e;switch(i){case $.POS_INT:case $.NEG_INT:{if(n.rejectInts)throw new Error(`Unexpected integer: ${o}`);if(n.rejectLargeNegatives&&o<-0x8000000000000000n)throw new Error(`Invalid 65bit negative number: ${o}`);let u=o;return n.convertUnsafeIntsToFloat&&u>=Mc.MIN&&u<=Mc.MAX&&(u=Number(o)),n.boxed?Ur(u,r.toHere(c)):u}case $.SIMPLE_FLOAT:if(a>Se.ONE){if(n.rejectFloats)throw new Error(`Decoding unwanted floating point number: ${o}`);if(n.rejectNegativeZero&&Object.is(o,-0))throw new Error("Decoding negative zero");if(n.rejectLongLoundNaN&&isNaN(o)){let u=r.toHere(c);if(u.length!==3||u[1]!==126||u[2]!==0)throw new Error(`Invalid NaN encoding: "${Vt(u)}"`)}if(n.rejectSubnormals&&P8(r.toHere(c+1)),n.rejectLongFloats){let u=$n(o,{chunkSize:9,reduceUnsafeNumbers:n.rejectUnsafeFloatInts});if(u[0]>>5!==i)throw new Error(`Should have been encoded as int, not float: ${o}`);if(u.length<HV.get(a))throw new Error(`Number should have been encoded shorter: ${o}`)}if(typeof o=="number"&&n.boxed)return Ur(o,r.toHere(c))}else {if(n.rejectSimple&&o instanceof Ws)throw new Error(`Invalid simple value: ${o}`);if(n.rejectUndefined&&o===void 0)throw new Error("Unexpected undefined")}return o;case $.BYTE_STRING:case $.UTF8_STRING:if(o===1/0)return new n.ParentType(e,1/0,t,n);if(n.rejectStringsNotNormalizedAs&&typeof o=="string"){let u=o.normalize(n.rejectStringsNotNormalizedAs);if(o!==u)throw new Error(`String not normalized as "${n.rejectStringsNotNormalizedAs}", got [${UE(o)}] instead of [${UE(u)}]`)}return n.boxed?Ur(o,r.toHere(c)):o;case $.ARRAY:return new n.ParentType(e,o,t,n);case $.MAP:return new n.ParentType(e,o*2,t,n);case $.TAG:{let u=new n.ParentType(e,1,t,n);return u.children=new we(o),u}}throw new TypeError(`Invalid major type: ${i}`)}static decodeToEncodeOpts(e){return {...l1,avoidInts:e.rejectInts,float64:!e.rejectLongFloats,flushToZero:e.rejectSubnormals,largeNegativeAsBigInt:e.rejectLargeNegatives,sortKeys:e.sortKeys}}push(e,t,n){if(this.children.push(e),this.#s){let r=Lr(e)||t.toHere(n);this.#s.push(r);}return --this.left}replaceLast(e,t,n){let r,i=-1/0;if(this.children instanceof we?(i=0,r=this.children.contents,this.children.contents=e):(i=this.children.length-1,r=this.children[i],this.children[i]=e),this.#s){let a=Lr(e)||n.toHere(t.offset);this.#s[i]=a;}return r}convert(e){let t;switch(this.mt){case $.ARRAY:t=this.children;break;case $.MAP:{let n=this.#n();if(this.#e.sortKeys){let r;for(let i of n){if(r&&this.#e.sortKeys(r,i)>=0)throw new Error(`Duplicate or out of order key: "0x${i[2]}"`);r=i;}}else if(this.#e.rejectDuplicateKeys){let r=new Set;for(let[i,a,o]of n){let c=Vt(o);if(r.has(c))throw new Error(`Duplicate key: "0x${c}"`);r.add(c);}}t=this.#e.createObject(n,this.#e);break}case $.BYTE_STRING:return I8(this.children);case $.UTF8_STRING:{let n=this.children.join("");t=this.#e.boxed?Ur(n,e.toHere(this.offset)):n;break}case $.TAG:t=this.children.decode(this.#e);break;default:throw new TypeError(`Invalid mt on convert: ${this.mt}`)}return this.#e.saveOriginal&&t&&typeof t=="object"&&jr(t,e.toHere(this.offset)),t}#n(){let e=this.children,t=e.length;if(t%2)throw new Error("Missing map value");let n=new Array(t/2);if(this.#s)for(let r=0;r<t;r+=2)n[r>>1]=[e[r],e[r+1],this.#s[r]];else for(let r=0;r<t;r+=2)n[r>>1]=[e[r],e[r+1],_V];return n}};var qE=" ",$V=new TextEncoder,f1=class extends ts{close="";quote='"';get isEmptyStream(){return (this.mt===$.UTF8_STRING||this.mt===$.BYTE_STRING)&&this.count===0}};function _r(s,e,t,n){let r="";if(e===Se.INDEFINITE)r+="_";else {if(n.diagnosticSizes===Ca.NEVER)return "";{let i=n.diagnosticSizes===Ca.ALWAYS;if(!i){let a=Se.ZERO;if(Object.is(t,-0))a=Se.TWO;else if(s===$.POS_INT||s===$.NEG_INT){let o=t<0,c=typeof t=="bigint"?1n:1,u=o?-t-c:t;u<=23?a=Number(u):u<=255?a=Se.ONE:u<=65535?a=Se.TWO:u<=4294967295?a=Se.FOUR:a=Se.EIGHT;}else isFinite(t)?Math.fround(t)===t?u1(t)==null?a=Se.FOUR:a=Se.TWO:a=Se.EIGHT:a=Se.TWO;i=a!==e;}i&&(r+="_",e<Se.ONE?r+="i":r+=String(e-24));}}return r}function FE(s,e){let t={...ts.defaultDecodeOptions,...e,ParentType:f1},n=new qn(s,t),r,i,a="";for(let o of n){let[c,u,l]=o;switch(r&&(r.count>0&&l!==st.BREAK&&(r.mt===$.MAP&&r.count%2?a+=": ":(a+=",",t.pretty||(a+=" "))),t.pretty&&(r.mt!==$.MAP||r.count%2===0)&&(a+=`
|
|
360
|
-
${
|
|
361
|
-
${
|
|
362
|
-
${
|
|
363
|
-
`,r.length>i+1){let c=of((s.depth+1)*2),u=tf(r);if(u?.length){u.sort((h,m)=>h[0]-m[0]||m[1]-h[1]);let l=0;for(let[h,m,y]of u)if(!(h<l)){if(l=h+m,y==="<<"){n+=of(e.minCol+1),n+="--",n+=c,n+="<< ";let g=sf(r,h,h+m),w=tf(g);if(w){let S=w.findIndex(([C,
|
|
364
|
-
`,n+=
|
|
358
|
+
[${S}] ${m} returned: ${$g(w)}
|
|
359
|
+
[${S}] warning: ${m} ${c} does not match reference`);})),l}}};return new Proxy(s,t)}({knownContexts:wa.KnownContexts,stateProvider:new Xh.Provider,guest:_e.DefaultGuestAddress});var ef={};be(ef,{EIP1193ProviderAdapter:()=>Ia,EIP6963:()=>DE,LocalRelayer:()=>Aa,PkRelayer:()=>TE,RpcRelayer:()=>PE,SequenceRelayer:()=>BE,getChain:()=>b8,isRelayer:()=>IV});var wt;(function(s){s.UNKNOWN="UNKNOWN",s.DROPPED="DROPPED",s.QUEUED="QUEUED",s.SENT="SENT",s.SUCCEEDED="SUCCEEDED",s.PARTIALLY_FAILED="PARTIALLY_FAILED",s.FAILED="FAILED",s.PENDING_PRECONDITION="PENDING_PRECONDITION";})(wt||(wt={}));var d8;(function(s){s.SEND="SEND",s.RECEIVE="RECEIVE",s.BRIDGE_DEPOSIT="BRIDGE_DEPOSIT",s.BRIDGE_WITHDRAW="BRIDGE_WITHDRAW",s.BURN="BURN",s.UNKNOWN="UNKNOWN";})(d8||(d8={}));var m8;(function(s){s.SKIPPED="SKIPPED",s.SUCCEEDED="SUCCEEDED",s.FAILED="FAILED",s.ABORTED="ABORTED",s.REVERTED="REVERTED",s.NOT_ENOUGH_GAS="NOT_ENOUGH_GAS";})(m8||(m8={}));var Fg;(function(s){s.UNKNOWN="UNKNOWN",s.ERC20_TOKEN="ERC20_TOKEN",s.ERC1155_TOKEN="ERC1155_TOKEN";})(Fg||(Fg={}));var p8;(function(s){s.DESC="DESC",s.ASC="ASC";})(p8||(p8={}));var _c=class{hostname;fetch;path="/rpc/Relayer/";constructor(e,t){this.hostname=e.replace(/\/*$/,""),this.fetch=(n,r)=>t(n,r);}url(e){return this.hostname+this.path+e}queryKey={ping:()=>["Relayer","ping"],version:()=>["Relayer","version"],runtimeStatus:()=>["Relayer","runtimeStatus"],getSequenceContext:()=>["Relayer","getSequenceContext"],getChainID:()=>["Relayer","getChainID"],sendMetaTxn:e=>["Relayer","sendMetaTxn",e],getMetaTxnNonce:e=>["Relayer","getMetaTxnNonce",e],getMetaTxnReceipt:e=>["Relayer","getMetaTxnReceipt",e],simulate:e=>["Relayer","simulate",e],simulateV3:e=>["Relayer","simulateV3",e],updateMetaTxnGasLimits:e=>["Relayer","updateMetaTxnGasLimits",e],feeTokens:()=>["Relayer","feeTokens"],feeOptions:e=>["Relayer","feeOptions",e],getMetaTxnNetworkFeeOptions:e=>["Relayer","getMetaTxnNetworkFeeOptions",e],getMetaTransactions:e=>["Relayer","getMetaTransactions",e],getTransactionCost:e=>["Relayer","getTransactionCost",e],sentTransactions:e=>["Relayer","sentTransactions",e],pendingTransactions:e=>["Relayer","pendingTransactions",e],getGasTank:e=>["Relayer","getGasTank",e],addGasTank:e=>["Relayer","addGasTank",e],updateGasTank:e=>["Relayer","updateGasTank",e],nextGasTankBalanceAdjustmentNonce:e=>["Relayer","nextGasTankBalanceAdjustmentNonce",e],adjustGasTankBalance:e=>["Relayer","adjustGasTankBalance",e],getGasTankBalanceAdjustment:e=>["Relayer","getGasTankBalanceAdjustment",e],listGasTankBalanceAdjustments:e=>["Relayer","listGasTankBalanceAdjustments",e],listGasSponsors:e=>["Relayer","listGasSponsors",e],getGasSponsor:e=>["Relayer","getGasSponsor",e],addGasSponsor:e=>["Relayer","addGasSponsor",e],updateGasSponsor:e=>["Relayer","updateGasSponsor",e],removeGasSponsor:e=>["Relayer","removeGasSponsor",e],addressGasSponsors:e=>["Relayer","addressGasSponsors",e],getProjectBalance:e=>["Relayer","getProjectBalance",e],adjustProjectBalance:e=>["Relayer","adjustProjectBalance",e]};ping=(e,t)=>this.fetch(this.url("Ping"),Ue("{}",e,t)).then(n=>Le(n).then(r=>je(r,"PingReturn")),n=>{throw Te.new({cause:`fetch(): ${n instanceof Error?n.message:String(n)}`})});version=(e,t)=>this.fetch(this.url("Version"),Ue("{}",e,t)).then(n=>Le(n).then(r=>je(r,"VersionReturn")),n=>{throw Te.new({cause:`fetch(): ${n instanceof Error?n.message:String(n)}`})});runtimeStatus=(e,t)=>this.fetch(this.url("RuntimeStatus"),Ue("{}",e,t)).then(n=>Le(n).then(r=>je(r,"RuntimeStatusReturn")),n=>{throw Te.new({cause:`fetch(): ${n instanceof Error?n.message:String(n)}`})});getSequenceContext=(e,t)=>this.fetch(this.url("GetSequenceContext"),Ue("{}",e,t)).then(n=>Le(n).then(r=>je(r,"GetSequenceContextReturn")),n=>{throw Te.new({cause:`fetch(): ${n instanceof Error?n.message:String(n)}`})});getChainID=(e,t)=>this.fetch(this.url("GetChainID"),Ue("{}",e,t)).then(n=>Le(n).then(r=>je(r,"GetChainIDReturn")),n=>{throw Te.new({cause:`fetch(): ${n instanceof Error?n.message:String(n)}`})});sendMetaTxn=(e,t,n)=>this.fetch(this.url("SendMetaTxn"),Ue(Ze(e,"SendMetaTxnArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"SendMetaTxnReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getMetaTxnNonce=(e,t,n)=>this.fetch(this.url("GetMetaTxnNonce"),Ue(Ze(e,"GetMetaTxnNonceArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"GetMetaTxnNonceReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getMetaTxnReceipt=(e,t,n)=>this.fetch(this.url("GetMetaTxnReceipt"),Ue(Ze(e,"GetMetaTxnReceiptArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"GetMetaTxnReceiptReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});simulate=(e,t,n)=>this.fetch(this.url("Simulate"),Ue(Ze(e,"SimulateArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"SimulateReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});simulateV3=(e,t,n)=>this.fetch(this.url("SimulateV3"),Ue(Ze(e,"SimulateV3Args"),t,n)).then(r=>Le(r).then(i=>je(i,"SimulateV3Return")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});updateMetaTxnGasLimits=(e,t,n)=>this.fetch(this.url("UpdateMetaTxnGasLimits"),Ue(Ze(e,"UpdateMetaTxnGasLimitsArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"UpdateMetaTxnGasLimitsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});feeTokens=(e,t)=>this.fetch(this.url("FeeTokens"),Ue("{}",e,t)).then(n=>Le(n).then(r=>je(r,"FeeTokensReturn")),n=>{throw Te.new({cause:`fetch(): ${n instanceof Error?n.message:String(n)}`})});feeOptions=(e,t,n)=>this.fetch(this.url("FeeOptions"),Ue(Ze(e,"FeeOptionsArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"FeeOptionsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getMetaTxnNetworkFeeOptions=(e,t,n)=>this.fetch(this.url("GetMetaTxnNetworkFeeOptions"),Ue(Ze(e,"GetMetaTxnNetworkFeeOptionsArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"GetMetaTxnNetworkFeeOptionsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getMetaTransactions=(e,t,n)=>this.fetch(this.url("GetMetaTransactions"),Ue(Ze(e,"GetMetaTransactionsArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"GetMetaTransactionsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getTransactionCost=(e,t,n)=>this.fetch(this.url("GetTransactionCost"),Ue(Ze(e,"GetTransactionCostArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"GetTransactionCostReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});sentTransactions=(e,t,n)=>this.fetch(this.url("SentTransactions"),Ue(Ze(e,"SentTransactionsArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"SentTransactionsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});pendingTransactions=(e,t,n)=>this.fetch(this.url("PendingTransactions"),Ue(Ze(e,"PendingTransactionsArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"PendingTransactionsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getGasTank=(e,t,n)=>this.fetch(this.url("GetGasTank"),Ue(Ze(e,"GetGasTankArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"GetGasTankReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});addGasTank=(e,t,n)=>this.fetch(this.url("AddGasTank"),Ue(Ze(e,"AddGasTankArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"AddGasTankReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});updateGasTank=(e,t,n)=>this.fetch(this.url("UpdateGasTank"),Ue(Ze(e,"UpdateGasTankArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"UpdateGasTankReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});nextGasTankBalanceAdjustmentNonce=(e,t,n)=>this.fetch(this.url("NextGasTankBalanceAdjustmentNonce"),Ue(Ze(e,"NextGasTankBalanceAdjustmentNonceArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"NextGasTankBalanceAdjustmentNonceReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});adjustGasTankBalance=(e,t,n)=>this.fetch(this.url("AdjustGasTankBalance"),Ue(Ze(e,"AdjustGasTankBalanceArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"AdjustGasTankBalanceReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getGasTankBalanceAdjustment=(e,t,n)=>this.fetch(this.url("GetGasTankBalanceAdjustment"),Ue(Ze(e,"GetGasTankBalanceAdjustmentArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"GetGasTankBalanceAdjustmentReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});listGasTankBalanceAdjustments=(e,t,n)=>this.fetch(this.url("ListGasTankBalanceAdjustments"),Ue(Ze(e,"ListGasTankBalanceAdjustmentsArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"ListGasTankBalanceAdjustmentsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});listGasSponsors=(e,t,n)=>this.fetch(this.url("ListGasSponsors"),Ue(Ze(e,"ListGasSponsorsArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"ListGasSponsorsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getGasSponsor=(e,t,n)=>this.fetch(this.url("GetGasSponsor"),Ue(Ze(e,"GetGasSponsorArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"GetGasSponsorReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});addGasSponsor=(e,t,n)=>this.fetch(this.url("AddGasSponsor"),Ue(Ze(e,"AddGasSponsorArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"AddGasSponsorReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});updateGasSponsor=(e,t,n)=>this.fetch(this.url("UpdateGasSponsor"),Ue(Ze(e,"UpdateGasSponsorArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"UpdateGasSponsorReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});removeGasSponsor=(e,t,n)=>this.fetch(this.url("RemoveGasSponsor"),Ue(Ze(e,"RemoveGasSponsorArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"RemoveGasSponsorReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});addressGasSponsors=(e,t,n)=>this.fetch(this.url("AddressGasSponsors"),Ue(Ze(e,"AddressGasSponsorsArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"AddressGasSponsorsReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});getProjectBalance=(e,t,n)=>this.fetch(this.url("GetProjectBalance"),Ue(Ze(e,"GetProjectBalanceArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"GetProjectBalanceReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})});adjustProjectBalance=(e,t,n)=>this.fetch(this.url("AdjustProjectBalance"),Ue(Ze(e,"AdjustProjectBalanceArgs"),t,n)).then(r=>Le(r).then(i=>je(i,"AdjustProjectBalanceReturn")),r=>{throw Te.new({cause:`fetch(): ${r instanceof Error?r.message:String(r)}`})})},Ue=(s="{}",e={},t=null)=>({method:"POST",headers:{...e,"Content-Type":"application/json"},body:s,signal:t}),Le=s=>s.text().then(e=>{let t;try{t=JSON.parse(e);}catch(n){throw Ea.new({status:s.status,cause:`JSON.parse(): ${n instanceof Error?n.message:String(n)}: response text: ${e}`})}if(!s.ok){let n=typeof t.code=="number"?t.code:0;throw (yV[n]||Ie).new(t)}return t}),w8={SendMetaTxnArgs:[["preconditions","TransactionPrecondition[]"]],TransactionPrecondition:["minAmount"],Transactions:[["preconditions","TransactionPrecondition[]"]]};function Kx(s,e){if(e==null||typeof e!="object")return e;let t=w8[s]||[];if(!t.length)return e;for(let n of t){if(Array.isArray(n)){let[r,i]=n;if(r.endsWith("[]")){let a=r.slice(0,-2),o=e[a];if(Array.isArray(o))for(let c=0;c<o.length;c++)o[c]=Kx(i,o[c]);}else e[r]&&(e[r]=Kx(i,e[r]));continue}if(n.endsWith("[]")){let r=n.slice(0,-2),i=e[r];if(Array.isArray(i))for(let a=0;a<i.length;a++)typeof i[a]=="bigint"&&(i[a]=i[a].toString());continue}typeof e[n]=="bigint"&&(e[n]=e[n].toString());}return e}function Gx(s,e){if(e==null||typeof e!="object")return e;let t=w8[s]||[];if(!t.length)return e;for(let n of t){if(Array.isArray(n)){let[i,a]=n;if(i.endsWith("[]")){let o=i.slice(0,-2),c=e[o];if(Array.isArray(c))for(let u=0;u<c.length;u++)c[u]=Gx(a,c[u]);}else e[i]&&(e[i]=Gx(a,e[i]));continue}if(n.endsWith("[]")){let i=n.slice(0,-2),a=e[i];if(Array.isArray(a))for(let o=0;o<a.length;o++){let c=a[o];if(typeof c=="string")try{a[o]=BigInt(c);}catch{throw Ea.new({cause:`Invalid bigint value for ${i}[${o}]: ${c}`})}}continue}let r=e[n];if(typeof r=="string")try{e[n]=BigInt(r);}catch{throw Ea.new({cause:`Invalid bigint value for ${n}: ${r}`})}}return e}var Ze=(s,e="")=>JSON.stringify(Kx(e,s)),je=(s,e="")=>{let t=s;if(typeof s=="string")try{t=JSON.parse(s);}catch(n){throw Ea.new({cause:`JsonDecode: JSON.parse failed: ${n.message}`})}return Gx(e,t)},Ie=class s extends Error{code;status;constructor(e={}){super(e.message),this.name=e.name||"WebrpcEndpointError",this.code=typeof e.code=="number"?e.code:0,this.message=e.message||"endpoint error",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}static new(e){return new this({message:e.message,code:e.code,status:e.status,cause:e.cause})}},Wx=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcEndpoint",this.code=typeof e.code=="number"?e.code:0,this.message=e.message||"endpoint error",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},Te=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcRequestFailed",this.code=typeof e.code=="number"?e.code:-1,this.message=e.message||"request failed",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},Jx=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcBadRoute",this.code=typeof e.code=="number"?e.code:-2,this.message=e.message||"bad route",this.status=typeof e.status=="number"?e.status:404,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},zx=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcBadMethod",this.code=typeof e.code=="number"?e.code:-3,this.message=e.message||"bad method",this.status=typeof e.status=="number"?e.status:405,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},Yx=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcBadRequest",this.code=typeof e.code=="number"?e.code:-4,this.message=e.message||"bad request",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},Ea=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcBadResponse",this.code=typeof e.code=="number"?e.code:-5,this.message=e.message||"bad response",this.status=typeof e.status=="number"?e.status:500,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},Zx=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcServerPanic",this.code=typeof e.code=="number"?e.code:-6,this.message=e.message||"server panic",this.status=typeof e.status=="number"?e.status:500,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},Qx=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcInternalError",this.code=typeof e.code=="number"?e.code:-7,this.message=e.message||"internal error",this.status=typeof e.status=="number"?e.status:500,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},Xx=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcClientAborted",this.code=typeof e.code=="number"?e.code:-8,this.message=e.message||"request aborted by client",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},eE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcStreamLost",this.code=typeof e.code=="number"?e.code:-9,this.message=e.message||"stream lost",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},tE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"WebrpcStreamFinished",this.code=typeof e.code=="number"?e.code:-10,this.message=e.message||"stream finished",this.status=typeof e.status=="number"?e.status:200,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},sE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"Unauthorized",this.code=typeof e.code=="number"?e.code:1e3,this.message=e.message||"Unauthorized access",this.status=typeof e.status=="number"?e.status:401,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},nE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"PermissionDenied",this.code=typeof e.code=="number"?e.code:1001,this.message=e.message||"Permission denied",this.status=typeof e.status=="number"?e.status:403,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},rE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"SessionExpired",this.code=typeof e.code=="number"?e.code:1002,this.message=e.message||"Session expired",this.status=typeof e.status=="number"?e.status:403,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},iE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"MethodNotFound",this.code=typeof e.code=="number"?e.code:1003,this.message=e.message||"Method not found",this.status=typeof e.status=="number"?e.status:404,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},aE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"RequestConflict",this.code=typeof e.code=="number"?e.code:1004,this.message=e.message||"Conflict with target resource",this.status=typeof e.status=="number"?e.status:409,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},oE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"Aborted",this.code=typeof e.code=="number"?e.code:1005,this.message=e.message||"Request aborted",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},cE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"Geoblocked",this.code=typeof e.code=="number"?e.code:1006,this.message=e.message||"Geoblocked region",this.status=typeof e.status=="number"?e.status:451,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},uE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"RateLimited",this.code=typeof e.code=="number"?e.code:1007,this.message=e.message||"Rate-limited. Please slow down.",this.status=typeof e.status=="number"?e.status:429,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},lE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"ProjectNotFound",this.code=typeof e.code=="number"?e.code:1008,this.message=e.message||"Project not found",this.status=typeof e.status=="number"?e.status:401,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},hE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"AccessKeyNotFound",this.code=typeof e.code=="number"?e.code:1101,this.message=e.message||"Access key not found",this.status=typeof e.status=="number"?e.status:401,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},fE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"AccessKeyMismatch",this.code=typeof e.code=="number"?e.code:1102,this.message=e.message||"Access key mismatch",this.status=typeof e.status=="number"?e.status:409,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},dE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"InvalidOrigin",this.code=typeof e.code=="number"?e.code:1103,this.message=e.message||"Invalid origin for Access Key",this.status=typeof e.status=="number"?e.status:403,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},mE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"InvalidService",this.code=typeof e.code=="number"?e.code:1104,this.message=e.message||"Service not enabled for Access key",this.status=typeof e.status=="number"?e.status:403,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},pE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"UnauthorizedUser",this.code=typeof e.code=="number"?e.code:1105,this.message=e.message||"Unauthorized user",this.status=typeof e.status=="number"?e.status:403,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},gE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"QuotaExceeded",this.code=typeof e.code=="number"?e.code:1200,this.message=e.message||"Quota request exceeded",this.status=typeof e.status=="number"?e.status:429,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},yE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"QuotaRateLimit",this.code=typeof e.code=="number"?e.code:1201,this.message=e.message||"Quota rate limit exceeded",this.status=typeof e.status=="number"?e.status:429,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},wE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"NoDefaultKey",this.code=typeof e.code=="number"?e.code:1300,this.message=e.message||"No default access key found",this.status=typeof e.status=="number"?e.status:403,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},bE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"MaxAccessKeys",this.code=typeof e.code=="number"?e.code:1301,this.message=e.message||"Access keys limit reached",this.status=typeof e.status=="number"?e.status:403,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},SE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"AtLeastOneKey",this.code=typeof e.code=="number"?e.code:1302,this.message=e.message||"You need at least one Access Key",this.status=typeof e.status=="number"?e.status:403,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},vE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"Timeout",this.code=typeof e.code=="number"?e.code:1900,this.message=e.message||"Request timed out",this.status=typeof e.status=="number"?e.status:408,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},xE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"InvalidArgument",this.code=typeof e.code=="number"?e.code:2001,this.message=e.message||"Invalid argument",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},EE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"Unavailable",this.code=typeof e.code=="number"?e.code:2002,this.message=e.message||"Unavailable resource",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},AE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"QueryFailed",this.code=typeof e.code=="number"?e.code:2003,this.message=e.message||"Query failed",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},IE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"NotFound",this.code=typeof e.code=="number"?e.code:3e3,this.message=e.message||"Resource not found",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},CE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"InsufficientFee",this.code=typeof e.code=="number"?e.code:3004,this.message=e.message||"Insufficient fee",this.status=typeof e.status=="number"?e.status:402,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},NE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"NotEnoughBalance",this.code=typeof e.code=="number"?e.code:3005,this.message=e.message||"Not enough balance",this.status=typeof e.status=="number"?e.status:402,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},kE=class s extends Ie{constructor(e={}){super(e),this.name=e.name||"SimulationFailed",this.code=typeof e.code=="number"?e.code:3006,this.message=e.message||"Simulation failed",this.status=typeof e.status=="number"?e.status:400,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,s.prototype);}},g8;(function(s){s.WebrpcEndpoint="WebrpcEndpoint",s.WebrpcRequestFailed="WebrpcRequestFailed",s.WebrpcBadRoute="WebrpcBadRoute",s.WebrpcBadMethod="WebrpcBadMethod",s.WebrpcBadRequest="WebrpcBadRequest",s.WebrpcBadResponse="WebrpcBadResponse",s.WebrpcServerPanic="WebrpcServerPanic",s.WebrpcInternalError="WebrpcInternalError",s.WebrpcClientAborted="WebrpcClientAborted",s.WebrpcStreamLost="WebrpcStreamLost",s.WebrpcStreamFinished="WebrpcStreamFinished",s.Unauthorized="Unauthorized",s.PermissionDenied="PermissionDenied",s.SessionExpired="SessionExpired",s.MethodNotFound="MethodNotFound",s.RequestConflict="RequestConflict",s.Aborted="Aborted",s.Geoblocked="Geoblocked",s.RateLimited="RateLimited",s.ProjectNotFound="ProjectNotFound",s.AccessKeyNotFound="AccessKeyNotFound",s.AccessKeyMismatch="AccessKeyMismatch",s.InvalidOrigin="InvalidOrigin",s.InvalidService="InvalidService",s.UnauthorizedUser="UnauthorizedUser",s.QuotaExceeded="QuotaExceeded",s.QuotaRateLimit="QuotaRateLimit",s.NoDefaultKey="NoDefaultKey",s.MaxAccessKeys="MaxAccessKeys",s.AtLeastOneKey="AtLeastOneKey",s.Timeout="Timeout",s.InvalidArgument="InvalidArgument",s.Unavailable="Unavailable",s.QueryFailed="QueryFailed",s.NotFound="NotFound",s.InsufficientFee="InsufficientFee",s.NotEnoughBalance="NotEnoughBalance",s.SimulationFailed="SimulationFailed";})(g8||(g8={}));var y8;(function(s){s[s.WebrpcEndpoint=0]="WebrpcEndpoint",s[s.WebrpcRequestFailed=-1]="WebrpcRequestFailed",s[s.WebrpcBadRoute=-2]="WebrpcBadRoute",s[s.WebrpcBadMethod=-3]="WebrpcBadMethod",s[s.WebrpcBadRequest=-4]="WebrpcBadRequest",s[s.WebrpcBadResponse=-5]="WebrpcBadResponse",s[s.WebrpcServerPanic=-6]="WebrpcServerPanic",s[s.WebrpcInternalError=-7]="WebrpcInternalError",s[s.WebrpcClientAborted=-8]="WebrpcClientAborted",s[s.WebrpcStreamLost=-9]="WebrpcStreamLost",s[s.WebrpcStreamFinished=-10]="WebrpcStreamFinished",s[s.Unauthorized=1e3]="Unauthorized",s[s.PermissionDenied=1001]="PermissionDenied",s[s.SessionExpired=1002]="SessionExpired",s[s.MethodNotFound=1003]="MethodNotFound",s[s.RequestConflict=1004]="RequestConflict",s[s.Aborted=1005]="Aborted",s[s.Geoblocked=1006]="Geoblocked",s[s.RateLimited=1007]="RateLimited",s[s.ProjectNotFound=1008]="ProjectNotFound",s[s.AccessKeyNotFound=1101]="AccessKeyNotFound",s[s.AccessKeyMismatch=1102]="AccessKeyMismatch",s[s.InvalidOrigin=1103]="InvalidOrigin",s[s.InvalidService=1104]="InvalidService",s[s.UnauthorizedUser=1105]="UnauthorizedUser",s[s.QuotaExceeded=1200]="QuotaExceeded",s[s.QuotaRateLimit=1201]="QuotaRateLimit",s[s.NoDefaultKey=1300]="NoDefaultKey",s[s.MaxAccessKeys=1301]="MaxAccessKeys",s[s.AtLeastOneKey=1302]="AtLeastOneKey",s[s.Timeout=1900]="Timeout",s[s.InvalidArgument=2001]="InvalidArgument",s[s.Unavailable=2002]="Unavailable",s[s.QueryFailed=2003]="QueryFailed",s[s.NotFound=3e3]="NotFound",s[s.InsufficientFee=3004]="InsufficientFee",s[s.NotEnoughBalance=3005]="NotEnoughBalance",s[s.SimulationFailed=3006]="SimulationFailed";})(y8||(y8={}));var yV={0:Wx,[-1]:Te,[-2]:Jx,[-3]:zx,[-4]:Yx,[-5]:Ea,[-6]:Zx,[-7]:Qx,[-8]:Xx,[-9]:eE,[-10]:tE,1e3:sE,1001:nE,1002:rE,1003:iE,1004:aE,1005:oE,1006:cE,1007:uE,1008:lE,1101:hE,1102:fE,1103:dE,1104:mE,1105:pE,1200:gE,1201:yE,1300:wE,1301:bE,1302:SE,1900:vE,2001:xE,2002:EE,2003:AE,3e3:IE,3004:CE,3005:NE,3006:kE};var Kg=class{address;min;max;constructor(e,t,n){this.address=e,this.min=t,this.max=n;}type(){return "native-balance"}isValid(){if(!this.address)return new Error("address is required");if(this.min!==void 0&&this.max!==void 0&&this.min>this.max)return new Error("min balance cannot be greater than max balance")}},Gg=class{address;token;min;max;constructor(e,t,n,r){this.address=e,this.token=t,this.min=n,this.max=r;}type(){return "erc20-balance"}isValid(){if(!this.address)return new Error("address is required");if(!this.token)return new Error("token address is required");if(this.min!==void 0&&this.max!==void 0&&this.min>this.max)return new Error("min balance cannot be greater than max balance")}},Wg=class{address;token;operator;min;constructor(e,t,n,r){this.address=e,this.token=t,this.operator=n,this.min=r;}type(){return "erc20-approval"}isValid(){if(!this.address)return new Error("address is required");if(!this.token)return new Error("token address is required");if(!this.operator)return new Error("operator address is required");if(this.min===void 0)return new Error("min approval amount is required")}},Jg=class{address;token;tokenId;owned;constructor(e,t,n,r){this.address=e,this.token=t,this.tokenId=n,this.owned=r;}type(){return "erc721-ownership"}isValid(){if(!this.address)return new Error("address is required");if(!this.token)return new Error("token address is required");if(this.tokenId===void 0)return new Error("tokenId is required")}},zg=class{address;token;tokenId;operator;constructor(e,t,n,r){this.address=e,this.token=t,this.tokenId=n,this.operator=r;}type(){return "erc721-approval"}isValid(){if(!this.address)return new Error("address is required");if(!this.token)return new Error("token address is required");if(this.tokenId===void 0)return new Error("tokenId is required");if(!this.operator)return new Error("operator address is required")}},Yg=class{address;token;tokenId;min;max;constructor(e,t,n,r,i){this.address=e,this.token=t,this.tokenId=n,this.min=r,this.max=i;}type(){return "erc1155-balance"}isValid(){if(!this.address)return new Error("address is required");if(!this.token)return new Error("token address is required");if(this.tokenId===void 0)return new Error("tokenId is required");if(this.min!==void 0&&this.max!==void 0&&this.min>this.max)return new Error("min balance cannot be greater than max balance")}},Zg=class{address;token;tokenId;operator;min;constructor(e,t,n,r,i){this.address=e,this.token=t,this.tokenId=n,this.operator=r,this.min=i;}type(){return "erc1155-approval"}isValid(){if(!this.address)return new Error("address is required");if(!this.token)return new Error("token address is required");if(this.tokenId===void 0)return new Error("tokenId is required");if(!this.operator)return new Error("operator address is required");if(this.min===void 0)return new Error("min approval amount is required")}};function Qg(s){if(!s)return;let e;try{switch(s.type){case"native-balance":e=new Kg(B.from(s.ownerAddress),s.minAmount,void 0);break;case"erc20-balance":e=new Gg(B.from(s.ownerAddress),B.from(s.tokenAddress),s.minAmount,void 0);break;case"erc20-approval":e=new Wg(B.from(s.ownerAddress),B.from(s.tokenAddress),B.from(s.ownerAddress),s.minAmount);break;case"erc721-ownership":e=new Jg(B.from(s.ownerAddress),B.from(s.tokenAddress),BigInt(0),!0);break;case"erc721-approval":e=new zg(B.from(s.ownerAddress),B.from(s.tokenAddress),BigInt(0),B.from(s.ownerAddress));break;case"erc1155-balance":e=new Yg(B.from(s.ownerAddress),B.from(s.tokenAddress),BigInt(0),s.minAmount,void 0);break;case"erc1155-approval":e=new Zg(B.from(s.ownerAddress),B.from(s.tokenAddress),BigInt(0),B.from(s.ownerAddress),s.minAmount);break;default:return}let t=e.isValid();if(t){console.warn(`Invalid precondition: ${t.message}`);return}return e}catch(t){console.warn(`Failed to decode precondition: ${t}`);return}}var Xg=se.from("function balanceOf(address) returns (uint256)"),e1=se.from("function allowance(address,address) returns (uint256)"),t1=se.from("function ownerOf(uint256) returns (address)"),s1=se.from("function getApproved(uint256) returns (address)"),n1=se.from("function balanceOf(address,uint256) returns (uint256)"),r1=se.from("function isApprovedForAll(address,address) returns (bool)");var EV=s=>({id:s.chainId,name:s.title||s.name,nativeCurrency:{name:s.nativeCurrency.name,symbol:s.nativeCurrency.symbol,decimals:s.nativeCurrency.decimals},rpcUrls:{default:{http:[s.rpcUrl]}},blockExplorers:s.blockExplorer?{default:{name:s.blockExplorer.name||"Explorer",url:s.blockExplorer.url}}:void 0,contracts:s.ensAddress?{ensUniversalResolver:{address:s.ensAddress}}:void 0}),b8=s=>{let e=Sa.getNetworkFromChainId(s);if(e)return EV(e);let t=Object.values(xV).find(n=>typeof n=="object"&&"id"in n&&n.id===s);if(t)return t;throw new Error(`Chain with id ${s} not found in Sequence networks or viem chains`)},PE=class{kind="relayer";type="rpc";id;chainId;client;fetch;provider;projectAccessKey;constructor(e,t,n,r,i){this.id=`rpc:${e}`,this.chainId=t,this.projectAccessKey=i;let a=r||(typeof window<"u"?window.fetch.bind(window):void 0);if(!a)throw new Error("Fetch implementation is required but not available in this environment.");this.fetch=a,this.client=new _c(e,this.fetch);let o=b8(t);this.provider=createPublicClient({chain:o,transport:http(n)});}isAvailable(e,t){return Promise.resolve(this.chainId===t)}async feeTokens(){try{let{isFeeRequired:e,tokens:t,paymentAddress:n}=await this.client.feeTokens();return e?(B.assert(n),{isFeeRequired:e,tokens:t,paymentAddress:n}):{isFeeRequired:e}}catch(e){return console.warn("RpcRelayer.feeTokens failed:",e),{isFeeRequired:!1}}}async feeOptions(e,t,n){let r={type:"call",space:0n,nonce:0n,calls:n},i=ce.encode(r);try{let a=await this.client.feeOptions({wallet:e,to:e,data:f.toHex(i)},{...this.projectAccessKey?{"X-Access-Key":this.projectAccessKey}:void 0}),o=a.quote?{_tag:"FeeQuote",_quote:a.quote}:void 0;return {options:a.options.map(u=>({token:{...u.token,contractAddress:this.mapRpcFeeTokenToAddress(u.token)},to:u.to,value:u.value,gasLimit:u.gasLimit})),quote:o}}catch(a){return console.warn("RpcRelayer.feeOptions failed:",a),{options:[]}}}async sendMetaTxn(e,t,n,r,i,a){console.log("sendMetaTxn",e,t,n,r,i,a);let o={walletAddress:e,contract:t,input:n},c=await this.client.sendMetaTxn({call:o,quote:i?JSON.stringify(i._quote):void 0,preconditions:a},{...this.projectAccessKey?{"X-Access-Key":this.projectAccessKey}:void 0});if(!c.status)throw console.error("RpcRelayer.relay failed",c),new Error(`Relay failed: TxnHash ${c.txnHash}`);return {opHash:E.fromString(c.txnHash)}}async relay(e,t,n,r,i){console.log("relay",e,t,n,r,i);let a={walletAddress:e,contract:e,input:t},o=await this.client.sendMetaTxn({call:a,quote:r?JSON.stringify(r._quote):void 0,preconditions:i},{...this.projectAccessKey?{"X-Access-Key":this.projectAccessKey}:void 0});if(!o.status)throw console.error("RpcRelayer.relay failed",o),new Error(`Relay failed: TxnHash ${o.txnHash}`);return {opHash:`0x${o.txnHash}`}}async status(e,t){try{let n=e.startsWith("0x")?e.substring(2):e,r=await this.client.getMetaTxnReceipt({metaTxID:n}),i=r.receipt;if(!i)return console.warn(`RpcRelayer.status: receipt not found for opHash ${e}`),{status:"unknown"};if(!i.status)return console.warn(`RpcRelayer.status: receipt status not found for opHash ${e}`),{status:"unknown"};switch(i.status){case wt.QUEUED:case wt.PENDING_PRECONDITION:case wt.SENT:return {status:"pending"};case wt.SUCCEEDED:return {status:"confirmed",transactionHash:i.txnHash,data:r};case wt.FAILED:case wt.PARTIALLY_FAILED:return {status:"failed",transactionHash:i.txnHash?i.txnHash:void 0,reason:i.revertReason||"Relayer reported failure",data:r};case wt.DROPPED:return {status:"failed",reason:"Transaction dropped"};case wt.UNKNOWN:default:return {status:"unknown"}}}catch(n){return console.error(`RpcRelayer.status failed for opHash ${e}:`,n),{status:"failed",reason:"Failed to fetch status"}}}async checkPrecondition(e){let t=Qg(e);if(!t)return !1;switch(t.type()){case"native-balance":{let n=t;try{let r=await this.provider.getBalance({address:n.address.toString()}),i=n.min!==void 0?BigInt(n.min):void 0,a=n.max!==void 0?BigInt(n.max):void 0;return i!==void 0&&a!==void 0?r>=i&&r<=a:i!==void 0?r>=i:a!==void 0?r<=a:(console.warn("Native balance precondition has neither min nor max specified"),!1)}catch(r){return console.error("Error checking native balance:",r),!1}}case"erc20-balance":{let n=t;try{let r=se.encodeData(Xg,[n.address.toString()]),i=await this.provider.call({to:n.token.toString(),data:r}),a=BigInt(i.toString()),o=n.min!==void 0?BigInt(n.min):void 0,c=n.max!==void 0?BigInt(n.max):void 0;return o!==void 0&&c!==void 0?a>=o&&a<=c:o!==void 0?a>=o:c!==void 0?a<=c:(console.warn("ERC20 balance precondition has neither min nor max specified"),!1)}catch(r){return console.error("Error checking ERC20 balance:",r),!1}}case"erc20-approval":{let n=t;try{let r=se.encodeData(e1,[n.address.toString(),n.operator.toString()]),i=await this.provider.call({to:n.token.toString(),data:r}),a=BigInt(i.toString()),o=BigInt(n.min);return a>=o}catch(r){return console.error("Error checking ERC20 approval:",r),!1}}case"erc721-ownership":{let n=t;try{let r=se.encodeData(t1,[n.tokenId]),c=(await this.provider.call({to:n.token.toString(),data:r})).toString().slice(-40).toLowerCase()===n.address.toString().slice(2).toLowerCase(),u=n.owned!==void 0?n.owned:!0;return c===u}catch(r){return console.error("Error checking ERC721 ownership:",r),!1}}case"erc721-approval":{let n=t;try{let r=se.encodeData(s1,[n.tokenId]);return (await this.provider.call({to:n.token.toString(),data:r})).toString().slice(-40).toLowerCase()===n.operator.toString().slice(2).toLowerCase()}catch(r){return console.error("Error checking ERC721 approval:",r),!1}}case"erc1155-balance":{let n=t;try{let r=se.encodeData(n1,[n.address.toString(),n.tokenId]),i=await this.provider.call({to:n.token.toString(),data:r}),a=BigInt(i.toString()),o=n.min!==void 0?BigInt(n.min):void 0,c=n.max!==void 0?BigInt(n.max):void 0;return o!==void 0&&c!==void 0?a>=o&&a<=c:o!==void 0?a>=o:c!==void 0?a<=c:(console.warn("ERC1155 balance precondition has neither min nor max specified"),!1)}catch(r){return console.error("Error checking ERC1155 balance:",r),!1}}case"erc1155-approval":{let n=t;try{let r=se.encodeData(r1,[n.address.toString(),n.operator.toString()]),i=await this.provider.call({to:n.token.toString(),data:r});return BigInt(i.toString())===1n}catch(r){return console.error("Error checking ERC1155 approval:",r),!1}}default:return !1}}mapRpcFeeTokenToAddress(e){return e.type===Fg.ERC20_TOKEN&&e.contractAddress?B.from(e.contractAddress):_e.ZeroAddress}};var Aa=class s{provider;kind="relayer";type="local";id="local";constructor(e){this.provider=e;}isAvailable(e,t){return Promise.resolve(!0)}static createFromWindow(e){let t=e.ethereum;if(!t){console.warn("Window.ethereum not found, skipping local relayer");return}return new s(new Ia(t))}static createFromProvider(e){return new s(new Ia(e))}feeTokens(){return Promise.resolve({isFeeRequired:!1})}feeOptions(e,t,n){return Promise.resolve({options:[]})}decodeCalls(e){let t=se.getSelector(_e.EXECUTE),n;return e.startsWith(t)?n=se.decodeData(_e.EXECUTE,e)[0]:n=e,ce.decode(f.fromHex(n))}async relay(e,t,n,r,i,a=5e3){let o=async()=>{if(!i||i.length===0)return !0;for(let c of i)if(!await this.checkPrecondition(c))return !1;return !0};return await o()?{opHash:await this.provider.sendTransaction({to:e,data:t},n)}:new Promise((c,u)=>{let l,h=!1,m=async()=>{try{if(h)return;if(await o()){h=!0,clearTimeout(l);let y=await this.provider.sendTransaction({to:e,data:t},n);c({opHash:y});}else l=setTimeout(m,a);}catch(y){h=!0,clearTimeout(l),u(y);}};return l=setTimeout(m,a),()=>{h=!0,clearTimeout(l);}})}async status(e,t){let n=await this.provider.getTransactionReceipt(e,t);return n==="unknown"?{status:"unknown"}:n==="success"?{status:"confirmed",transactionHash:e}:{status:"failed",reason:"failed"}}async checkPrecondition(e){let t=Qg(e);if(!t)return !1;switch(t.type()){case"native-balance":{let n=t,r=await this.provider.getBalance(n.address.toString());return !(n.min!==void 0&&r<n.min||n.max!==void 0&&r>n.max)}case"erc20-balance":{let n=t,r=se.encodeData(Xg,[n.address.toString()]),i=await this.provider.call({to:n.token.toString(),data:r}),a=BigInt(i);return !(n.min!==void 0&&a<n.min||n.max!==void 0&&a>n.max)}case"erc20-approval":{let n=t,r=se.encodeData(e1,[n.address.toString(),n.operator.toString()]),i=await this.provider.call({to:n.token.toString(),data:r});return BigInt(i)>=n.min}case"erc721-ownership":{let n=t,r=se.encodeData(t1,[n.tokenId]),o=("0x"+(await this.provider.call({to:n.token.toString(),data:r})).slice(26)).toLowerCase()===n.address.toString().toLowerCase();return n.owned===void 0?o:n.owned===o}case"erc721-approval":{let n=t,r=se.encodeData(s1,[n.tokenId]);return ("0x"+(await this.provider.call({to:n.token.toString(),data:r})).slice(26)).toLowerCase()===n.operator.toString().toLowerCase()}case"erc1155-balance":{let n=t,r=se.encodeData(n1,[n.address.toString(),n.tokenId]),i=await this.provider.call({to:n.token.toString(),data:r}),a=BigInt(i);return !(n.min!==void 0&&a<n.min||n.max!==void 0&&a>n.max)}case"erc1155-approval":{let n=t,r=se.encodeData(r1,[n.address.toString(),n.operator.toString()]),i=await this.provider.call({to:n.token.toString(),data:r});return BigInt(i)===1n}default:return !1}}},Ia=class{provider;constructor(e){this.provider=e;}async trySwitchChain(e){try{await this.provider.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${e.toString(16)}`}]});}catch(t){console.error("Error switching chain",t);}}async sendTransaction(e,t){let r=(await this.provider.request({method:"eth_requestAccounts"}))[0];if(!r){console.warn("No account selected, skipping local relayer");return}return await this.trySwitchChain(t),await this.provider.request({method:"eth_sendTransaction",params:[{from:r,to:e.to,data:e.data}]})}async getBalance(e){let t=await this.provider.request({method:"eth_getBalance",params:[e,"latest"]});return BigInt(t)}async call(e){return await this.provider.request({method:"eth_call",params:[e,"latest"]})}async getTransactionReceipt(e,t){await this.trySwitchChain(t);let n=await this.provider.request({method:"eth_getTransactionReceipt",params:[e]});if(n){let r=kc.fromRpc(n);if(r?.status==="success")return "success";if(r?.status==="reverted")return "failed"}return "unknown"}};var TE=class{provider;kind="relayer";type="pk";id="pk";relayer;constructor(e,t){this.provider=t;let n=B.fromPublicKey(Ot.getPublicKey({privateKey:e}));this.relayer=new Aa({sendTransaction:async(r,i)=>{if(Number(await this.provider.request({method:"eth_chainId"}))!==i)throw new Error("Provider chain id does not match relayer chain id");let o={...r,to:r.to,data:r.data},c=BigInt(await this.provider.request({method:"eth_estimateGas",params:[o]})),u=c>21000n?c*12n/10n:50000n,l=BigInt(await this.provider.request({method:"eth_gasPrice"})),h=100000000n,m=l+h,y=BigInt(await this.provider.request({method:"eth_getBalance",params:[n,"latest"]}));if(y<m*u)throw console.log("Sender balance:",y.toString(),"wei"),new Error("Sender has insufficient balance to pay for gas");let g=BigInt(await this.provider.request({method:"eth_getTransactionCount",params:[n,"latest"]})),w=pa.from({chainId:Number(i),type:"eip1559",from:n,to:o.to,data:o.data,gas:u,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:g,value:0n}),S=Ot.sign({payload:pa.getSignPayload(w),privateKey:e}),C=pa.from(w,{signature:S});return await this.provider.request({method:"eth_sendRawTransaction",params:[pa.serialize(C)]})},getBalance:async r=>{let i=await this.provider.request({method:"eth_getBalance",params:[r,"latest"]});return BigInt(i)},call:async r=>{let i={to:r.to,data:r.data};return await this.provider.request({method:"eth_call",params:[i,"latest"]})},getTransactionReceipt:async(r,i)=>{if(E.assert(r),Number(await this.provider.request({method:"eth_chainId"}))!==i)throw new Error("Provider chain id does not match relayer chain id");let o=await this.provider.request({method:"eth_getTransactionReceipt",params:[r]});return o?kc.fromRpc(o).status==="success"?"success":"failed":"unknown"}});}async isAvailable(e,t){return Number(await this.provider.request({method:"eth_chainId"}))===t}feeTokens(){return this.relayer.feeTokens()}feeOptions(e,t,n){return this.relayer.feeOptions(e,t,n)}async relay(e,t,n,r){if(Number(await this.provider.request({method:"eth_chainId"}))!==n)throw new Error("Provider chain id does not match relayer chain id");return this.relayer.relay(e,t,n)}status(e,t){return this.relayer.status(e,t)}async checkPrecondition(e){return !0}};var BE=class{kind="relayer";type="sequence";id="sequence";service;constructor(e){this.service=new _c(e,fetch);}async isAvailable(e,t){return !0}async feeTokens(){let{isFeeRequired:e,tokens:t,paymentAddress:n}=await this.service.feeTokens();return e?(B.assert(n),{isFeeRequired:e,tokens:t,paymentAddress:n}):{isFeeRequired:e}}async feeOptions(e,t,n){let r=e,i=se.from("function execute(bytes calldata _payload, bytes calldata _signature)"),a=ce.encode({type:"call",space:0n,nonce:0n,calls:n},r),c=se.encodeData(i,[f.toHex(a),"0x0001"]),{options:u,quote:l}=await this.service.feeOptions({wallet:e,to:r,data:c});return {options:u,quote:l?{_tag:"FeeQuote",_quote:l}:void 0}}async checkPrecondition(e){return !1}async relay(e,t,n,r){let i=e,{txnHash:a}=await this.service.sendMetaTxn({call:{walletAddress:i,contract:e,input:t},quote:r&&r._quote});return {opHash:`0x${a}`}}async status(e,t){try{let{receipt:{status:n,revertReason:r,txnReceipt:i}}=await this.service.getMetaTxnReceipt({metaTxID:e});switch(n){case wt.UNKNOWN:return {status:"unknown"};case wt.DROPPED:return {status:"failed",reason:r??n};case wt.QUEUED:return {status:"pending"};case wt.SENT:return {status:"pending"};case wt.SUCCEEDED:{let o=JSON.parse(i).transactionHash;return E.assert(o),{status:"confirmed",transactionHash:o}}case wt.PARTIALLY_FAILED:return {status:"failed",reason:r??n};case wt.FAILED:return {status:"failed",reason:r??n};default:throw new Error(`unknown transaction status '${n}'`)}}catch{return {status:"pending"}}}};var DE={};be(DE,{EIP6963Relayer:()=>i1,getEIP6963Store:()=>v8,getRelayers:()=>AV});function S8(s){if(typeof window>"u")return;let e=t=>s(t.detail);return window.addEventListener("eip6963:announceProvider",e),window.dispatchEvent(new CustomEvent("eip6963:requestProvider")),()=>window.removeEventListener("eip6963:announceProvider",e)}function OE(){let s=new Set,e=[],t=()=>S8(r=>{e.some(({info:i})=>i.uuid===r.info.uuid)||(e=[...e,r],s.forEach(i=>i(e,{added:[r]})));}),n=t();return {_listeners(){return s},clear(){s.forEach(r=>r([],{removed:[...e]})),e=[];},destroy(){this.clear(),s.clear(),n?.();},findProvider({rdns:r}){return e.find(i=>i.info.rdns===r)},getProviders(){return e},reset(){this.clear(),n?.(),n=t();},subscribe(r,{emitImmediately:i}={}){return s.add(r),i&&r(e,{added:e}),()=>s.delete(r)}}}var i1=class{kind="relayer";type="eip6963";id;info;relayer;constructor(e){this.info=e.info,this.id=e.info.uuid,this.relayer=new Aa(new Ia(e.provider));}isAvailable(e,t){return this.relayer.isAvailable(e,t)}feeTokens(){return this.relayer.feeTokens()}feeOptions(e,t,n){return this.relayer.feeOptions(e,t,n)}async relay(e,t,n,r){return this.relayer.relay(e,t,n)}status(e,t){return this.relayer.status(e,t)}async checkPrecondition(e){return this.relayer.checkPrecondition(e)}},RE;function v8(){return RE||(RE=OE()),RE}var VE=new Map;function AV(){let e=v8().getProviders();for(let t of e)VE.has(t.info.uuid)||VE.set(t.info.uuid,new i1(t));return Array.from(VE.values())}function IV(s){return "isAvailable"in s&&"feeOptions"in s&&"relay"in s&&"status"in s&&"checkPrecondition"in s}var $={POS_INT:0,NEG_INT:1,BYTE_STRING:2,UTF8_STRING:3,ARRAY:4,MAP:5,TAG:6,SIMPLE_FLOAT:7},Qe={DATE_STRING:0,DATE_EPOCH:1,POS_BIGINT:2,NEG_BIGINT:3,DECIMAL_FRAC:4,BIGFLOAT:5,BASE64URL_EXPECTED:21,BASE64_EXPECTED:22,BASE16_EXPECTED:23,CBOR:24,URI:32,BASE64URL:33,BASE64:34,MIME:36,SET:258,JSON:262,REGEXP:21066,SELF_DESCRIBED:55799,INVALID_16:65535,INVALID_32:4294967295,INVALID_64:0xffffffffffffffffn},Se={ZERO:0,ONE:24,TWO:25,FOUR:26,EIGHT:27,INDEFINITE:31},dn={FALSE:20,TRUE:21,NULL:22,UNDEFINED:23},st=class{static BREAK=Symbol.for("github.com/hildjj/cbor2/break");static ENCODED=Symbol.for("github.com/hildjj/cbor2/cbor-encoded");static LENGTH=Symbol.for("github.com/hildjj/cbor2/length")},Mc={MIN:-(2n**63n),MAX:2n**64n-1n};var we=class s{static#e=new Map;tag;contents;constructor(e,t=void 0){this.tag=e,this.contents=t;}get noChildren(){return !!s.#e.get(this.tag)?.noChildren}static registerDecoder(e,t,n){let r=this.#e.get(e);return this.#e.set(e,t),r&&("comment"in t||(t.comment=r.comment),"noChildren"in t||(t.noChildren=r.noChildren)),n&&!t.comment&&(t.comment=()=>`(${n})`),r}static clearDecoder(e){let t=this.#e.get(e);return this.#e.delete(e),t}static getDecoder(e){return this.#e.get(e)}static getAllDecoders(){return new Map(this.#e)}*[Symbol.iterator](){yield this.contents;}push(e){return this.contents=e,1}decode(e){let t=s.#e.get(this.tag);return t?t(this,e):this}comment(e,t){let n=s.#e.get(this.tag);if(n?.comment)return n.comment(this,e,t)}toCBOR(){return [this.tag,this.contents]}[Symbol.for("nodejs.util.inspect.custom")](e,t,n){return `${this.tag}(${n(this.contents,t)})`}};function Ur(s){if(s!=null&&typeof s=="object")return s[st.ENCODED]}function x8(s){if(s!=null&&typeof s=="object")return s[st.LENGTH]}function Lr(s,e){Object.defineProperty(s,st.ENCODED,{configurable:!0,enumerable:!1,value:e});}function jr(s,e){let t=Object(s);return Lr(t,e),t}var UE=Symbol("CBOR_RANGES");function E8(s,e){Object.defineProperty(s,UE,{configurable:!1,enumerable:!1,writable:!1,value:e});}function tf(s){return s[UE]}function CV(s){return tf(s)!==void 0}function sf(s,e=0,t=s.length-1){let n=s.subarray(e,t),r=tf(s);if(r){let i=[];for(let a of r)if(a[0]>=e&&a[0]+a[1]<=t){let o=[...a];o[0]-=e,i.push(o);}i.length&&E8(n,i);}return n}function a1(s){let e=Math.ceil(s.length/2),t=new Uint8Array(e);e--;for(let n=s.length,r=n-2;n>=0;n=r,r-=2,e--)t[e]=parseInt(s.substring(r,n),16);return t}function Vt(s){return s.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function A8(s){let e=s.reduce((a,o)=>a+o.length,0),t=s.some(a=>CV(a)),n=[],r=new Uint8Array(e),i=0;for(let a of s){if(!(a instanceof Uint8Array))throw new TypeError(`Invalid array: ${a}`);if(r.set(a,i),t){let o=a[UE]??[[0,a.length]];for(let c of o)c[0]+=i;n.push(...o);}i+=a.length;}return t&&E8(r,n),r}function nf(s){let e=atob(s);return Uint8Array.from(e,t=>t.codePointAt(0))}var NV={"-":"+",_:"/"};function I8(s){let e=s.replace(/[_-]/g,t=>NV[t]);return nf(e.padEnd(Math.ceil(e.length/4)*4,"="))}function C8(){let s=new Uint8Array(4),e=new Uint32Array(s.buffer);return !((e[0]=1)&s[0])}function LE(s){let e="";for(let t of s){let n=t.codePointAt(0)?.toString(16).padStart(4,"0");e&&(e+=", "),e+=`U+${n}`;}return e}function o1(s,e){let[t,n,r]=s,[i,a,o]=e,c=Math.min(r.length,o.length);for(let u=0;u<c;u++){let l=r[u]-o[u];if(l!==0)return l}return 0}var rf=class s{static defaultOptions={chunkSize:4096};#e;#s=[];#n=null;#t=0;#a=0;constructor(e={}){if(this.#e={...s.defaultOptions,...e},this.#e.chunkSize<8)throw new RangeError(`Expected size >= 8, got ${this.#e.chunkSize}`);this.#i();}get length(){return this.#a}read(){this.#r();let e=new Uint8Array(this.#a),t=0;for(let n of this.#s)e.set(n,t),t+=n.length;return this.#i(),e}write(e){let t=e.length;t>this.#u()?(this.#r(),t>this.#e.chunkSize?(this.#s.push(e),this.#i()):(this.#i(),this.#s[this.#s.length-1].set(e),this.#t=t)):(this.#s[this.#s.length-1].set(e,this.#t),this.#t+=t),this.#a+=t;}writeUint8(e){this.#c(1),this.#n.setUint8(this.#t,e),this.#o(1);}writeUint16(e,t=!1){this.#c(2),this.#n.setUint16(this.#t,e,t),this.#o(2);}writeUint32(e,t=!1){this.#c(4),this.#n.setUint32(this.#t,e,t),this.#o(4);}writeBigUint64(e,t=!1){this.#c(8),this.#n.setBigUint64(this.#t,e,t),this.#o(8);}writeInt16(e,t=!1){this.#c(2),this.#n.setInt16(this.#t,e,t),this.#o(2);}writeInt32(e,t=!1){this.#c(4),this.#n.setInt32(this.#t,e,t),this.#o(4);}writeBigInt64(e,t=!1){this.#c(8),this.#n.setBigInt64(this.#t,e,t),this.#o(8);}writeFloat32(e,t=!1){this.#c(4),this.#n.setFloat32(this.#t,e,t),this.#o(4);}writeFloat64(e,t=!1){this.#c(8),this.#n.setFloat64(this.#t,e,t),this.#o(8);}clear(){this.#a=0,this.#s=[],this.#i();}#i(){let e=new Uint8Array(this.#e.chunkSize);this.#s.push(e),this.#t=0,this.#n=new DataView(e.buffer,e.byteOffset,e.byteLength);}#r(){if(this.#t===0){this.#s.pop();return}let e=this.#s.length-1;this.#s[e]=this.#s[e].subarray(0,this.#t),this.#t=0,this.#n=null;}#u(){let e=this.#s.length-1;return this.#s[e].length-this.#t}#c(e){this.#u()<e&&(this.#r(),this.#i());}#o(e){this.#t+=e,this.#a+=e;}};function jE(s,e=0,t=!1){let n=s[e]&128?-1:1,r=(s[e]&124)>>2,i=(s[e]&3)<<8|s[e+1];if(r===0){if(t&&i!==0)throw new Error(`Unwanted subnormal: ${n*5960464477539063e-23*i}`);return n*5960464477539063e-23*i}else if(r===31)return i?NaN:n*(1/0);return n*2**(r-25)*(1024+i)}function c1(s){let e=new DataView(new ArrayBuffer(4));e.setFloat32(0,s,!1);let t=e.getUint32(0,!1);if(t&8191)return null;let n=t>>16&32768,r=t>>23&255,i=t&8388607;if(!(r===0&&i===0))if(r>=113&&r<=142)n+=(r-112<<10)+(i>>13);else if(r>=103&&r<113){if(i&(1<<126-r)-1)return null;n+=i+8388608>>126-r;}else if(r===255)n|=31744,n|=i>>13;else return null;return n}function N8(s){if(s!==0){let e=new ArrayBuffer(8),t=new DataView(e);t.setFloat64(0,s,!1);let n=t.getBigUint64(0,!1);if((n&0x7ff0000000000000n)===0n)return n&0x8000000000000000n?-0:0}return s}function k8(s){switch(s.length){case 2:jE(s,0,!0);break;case 4:{let e=new DataView(s.buffer,s.byteOffset,s.byteLength),t=e.getUint32(0,!1);if(!(t&2139095040)&&t&8388607)throw new Error(`Unwanted subnormal: ${e.getFloat32(0,!1)}`);break}case 8:{let e=new DataView(s.buffer,s.byteOffset,s.byteLength),t=e.getBigUint64(0,!1);if((t&0x7ff0000000000000n)===0n&&t&0x000fffffffffffn)throw new Error(`Unwanted subnormal: ${e.getFloat64(0,!1)}`);break}default:throw new TypeError(`Bad input to isSubnormal: ${s}`)}}var P8=$.SIMPLE_FLOAT<<5|Se.TWO,kV=$.SIMPLE_FLOAT<<5|Se.FOUR,PV=$.SIMPLE_FLOAT<<5|Se.EIGHT,TV=$.SIMPLE_FLOAT<<5|dn.TRUE,BV=$.SIMPLE_FLOAT<<5|dn.FALSE,OV=$.SIMPLE_FLOAT<<5|dn.UNDEFINED,RV=$.SIMPLE_FLOAT<<5|dn.NULL,VV=new TextEncoder,u1={...rf.defaultOptions,avoidInts:!1,cde:!1,collapseBigInts:!0,dcbor:!1,float64:!1,flushToZero:!1,forceEndian:null,ignoreOriginalEncoding:!1,largeNegativeAsBigInt:!1,reduceUnsafeNumbers:!1,rejectBigInts:!1,rejectCustomSimples:!1,rejectDuplicateKeys:!1,rejectFloats:!1,rejectUndefined:!1,simplifyNegativeZero:!1,sortKeys:null,stringNormalization:null},ME={cde:!0,ignoreOriginalEncoding:!0,sortKeys:o1},T8={...ME,dcbor:!0,largeNegativeAsBigInt:!0,reduceUnsafeNumbers:!0,rejectCustomSimples:!0,rejectDuplicateKeys:!0,rejectUndefined:!0,simplifyNegativeZero:!0,stringNormalization:"NFC"};function B8(s){let e=s<0;return typeof s=="bigint"?[e?-s-1n:s,e]:[e?-s-1:s,e]}function HE(s,e,t){if(t.rejectFloats)throw new Error(`Attempt to encode an unwanted floating point number: ${s}`);if(isNaN(s))e.writeUint8(P8),e.writeUint16(32256);else if(!t.float64&&Math.fround(s)===s){let n=c1(s);n===null?(e.writeUint8(kV),e.writeFloat32(s)):(e.writeUint8(P8),e.writeUint16(n));}else e.writeUint8(PV),e.writeFloat64(s);}function vs(s,e,t){let[n,r]=B8(s);if(r&&t)throw new TypeError(`Negative size: ${s}`);t??=r?$.NEG_INT:$.POS_INT,t<<=5,n<24?e.writeUint8(t|n):n<=255?(e.writeUint8(t|Se.ONE),e.writeUint8(n)):n<=65535?(e.writeUint8(t|Se.TWO),e.writeUint16(n)):n<=4294967295?(e.writeUint8(t|Se.FOUR),e.writeUint32(n)):(e.writeUint8(t|Se.EIGHT),e.writeBigUint64(BigInt(n)));}function af(s,e,t){typeof s=="number"?vs(s,e,$.TAG):typeof s=="object"&&!t.ignoreOriginalEncoding&&st.ENCODED in s?e.write(s[st.ENCODED]):s<=Number.MAX_SAFE_INTEGER?vs(Number(s),e,$.TAG):(e.writeUint8($.TAG<<5|Se.EIGHT),e.writeBigUint64(BigInt(s)));}function O8(s,e,t){let[n,r]=B8(s);if(t.collapseBigInts&&(!t.largeNegativeAsBigInt||s>=-0x8000000000000000n)){if(n<=0xffffffffn){vs(Number(s),e);return}if(n<=0xffffffffffffffffn){let u=(r?$.NEG_INT:$.POS_INT)<<5;e.writeUint8(u|Se.EIGHT),e.writeBigUint64(n);return}}if(t.rejectBigInts)throw new Error(`Attempt to encode unwanted bigint: ${s}`);let i=r?Qe.NEG_BIGINT:Qe.POS_BIGINT,a=n.toString(16),o=a.length%2?"0":"";af(i,e,t);let c=a1(o+a);vs(c.length,e,$.BYTE_STRING),e.write(c);}function DV(s,e,t){t.flushToZero&&(s=N8(s)),Object.is(s,-0)?t.simplifyNegativeZero?t.avoidInts?HE(0,e,t):vs(0,e):HE(s,e,t):!t.avoidInts&&Number.isSafeInteger(s)?vs(s,e):t.reduceUnsafeNumbers&&Math.floor(s)===s&&s>=Mc.MIN&&s<=Mc.MAX?O8(BigInt(s),e,t):HE(s,e,t);}function UV(s,e,t){let n=t.stringNormalization?s.normalize(t.stringNormalization):s,r=VV.encode(n);vs(r.length,e,$.UTF8_STRING),e.write(r);}function LV(s,e,t){let n=s;l1(n,n.length,$.ARRAY,e,t);for(let r of n)Hr(r,e,t);}function jV(s,e){let t=s;vs(t.length,e,$.BYTE_STRING),e.write(t);}var _E=new Map([[Array,LV],[Uint8Array,jV]]);function it(s,e){let t=_E.get(s);return _E.set(s,e),t}function l1(s,e,t,n,r){let i=x8(s);i&&!r.ignoreOriginalEncoding?n.write(i):vs(e,n,t);}function HV(s,e,t){if(s===null){e.writeUint8(RV);return}if(!t.ignoreOriginalEncoding&&st.ENCODED in s){e.write(s[st.ENCODED]);return}let n=_E.get(s.constructor);if(n){let i=n(s,e,t);i&&((typeof i[0]=="bigint"||isFinite(Number(i[0])))&&af(i[0],e,t),Hr(i[1],e,t));return}if(typeof s.toCBOR=="function"){let i=s.toCBOR(e,t);i&&((typeof i[0]=="bigint"||isFinite(Number(i[0])))&&af(i[0],e,t),Hr(i[1],e,t));return}if(typeof s.toJSON=="function"){Hr(s.toJSON(),e,t);return}let r=Object.entries(s).map(i=>[i[0],i[1],$n(i[0],t)]);t.sortKeys&&r.sort(t.sortKeys),l1(s,r.length,$.MAP,e,t);for(let[i,a,o]of r)e.write(o),Hr(a,e,t);}function Hr(s,e,t){switch(typeof s){case"number":DV(s,e,t);break;case"bigint":O8(s,e,t);break;case"string":UV(s,e,t);break;case"boolean":e.writeUint8(s?TV:BV);break;case"undefined":if(t.rejectUndefined)throw new Error("Attempt to encode unwanted undefined.");e.writeUint8(OV);break;case"object":HV(s,e,t);break;case"symbol":throw new TypeError(`Unknown symbol: ${s.toString()}`);default:throw new TypeError(`Unknown type: ${typeof s}, ${String(s)}`)}}function $n(s,e={}){let t={...u1};e.dcbor?Object.assign(t,T8):e.cde&&Object.assign(t,ME),Object.assign(t,e);let n=new rf(t);return Hr(s,n,t),n.read()}var Ca=(s=>(s[s.NEVER=-1]="NEVER",s[s.PREFERRED=0]="PREFERRED",s[s.ALWAYS=1]="ALWAYS",s))(Ca||{});var Ws=class s{static KnownSimple=new Map([[dn.FALSE,!1],[dn.TRUE,!0],[dn.NULL,null],[dn.UNDEFINED,void 0]]);value;constructor(e){this.value=e;}static create(e){return s.KnownSimple.has(e)?s.KnownSimple.get(e):new s(e)}toCBOR(e,t){if(t.rejectCustomSimples)throw new Error(`Cannot encode non-standard Simple value: ${this.value}`);vs(this.value,e,$.SIMPLE_FLOAT);}toString(){return `simple(${this.value})`}decode(){return s.KnownSimple.has(this.value)?s.KnownSimple.get(this.value):this}[Symbol.for("nodejs.util.inspect.custom")](e,t,n){return `simple(${n(this.value,t)})`}};var _V=new TextDecoder("utf8",{fatal:!0,ignoreBOM:!0}),qn=class s{static defaultOptions={maxDepth:1024,encoding:"hex",requirePreferred:!1};#e;#s;#n=0;#t;constructor(e,t){if(this.#t={...s.defaultOptions,...t},typeof e=="string")switch(this.#t.encoding){case"hex":this.#e=a1(e);break;case"base64":this.#e=nf(e);break;default:throw new TypeError(`Encoding not implemented: "${this.#t.encoding}"`)}else this.#e=e;this.#s=new DataView(this.#e.buffer,this.#e.byteOffset,this.#e.byteLength);}toHere(e){return sf(this.#e,e,this.#n)}*[Symbol.iterator](){if(yield*this.#a(0),this.#n!==this.#e.length)throw new Error("Extra data in input")}*#a(e){if(e++>this.#t.maxDepth)throw new Error(`Maximum depth ${this.#t.maxDepth} exceeded`);let t=this.#n,n=this.#s.getUint8(this.#n++),r=n>>5,i=n&31,a=i,o=!1,c=0;switch(i){case Se.ONE:if(c=1,a=this.#s.getUint8(this.#n),r===$.SIMPLE_FLOAT){if(a<32)throw new Error(`Invalid simple encoding in extra byte: ${a}`);o=!0;}else if(this.#t.requirePreferred&&a<24)throw new Error(`Unexpectedly long integer encoding (1) for ${a}`);break;case Se.TWO:if(c=2,r===$.SIMPLE_FLOAT)a=jE(this.#e,this.#n);else if(a=this.#s.getUint16(this.#n,!1),this.#t.requirePreferred&&a<=255)throw new Error(`Unexpectedly long integer encoding (2) for ${a}`);break;case Se.FOUR:if(c=4,r===$.SIMPLE_FLOAT)a=this.#s.getFloat32(this.#n,!1);else if(a=this.#s.getUint32(this.#n,!1),this.#t.requirePreferred&&a<=65535)throw new Error(`Unexpectedly long integer encoding (4) for ${a}`);break;case Se.EIGHT:{if(c=8,r===$.SIMPLE_FLOAT)a=this.#s.getFloat64(this.#n,!1);else if(a=this.#s.getBigUint64(this.#n,!1),a<=Number.MAX_SAFE_INTEGER&&(a=Number(a)),this.#t.requirePreferred&&a<=4294967295)throw new Error(`Unexpectedly long integer encoding (8) for ${a}`);break}case 28:case 29:case 30:throw new Error(`Additional info not implemented: ${i}`);case Se.INDEFINITE:switch(r){case $.POS_INT:case $.NEG_INT:case $.TAG:throw new Error(`Invalid indefinite encoding for MT ${r}`);case $.SIMPLE_FLOAT:yield [r,i,st.BREAK,t,0];return}a=1/0;break;default:o=!0;}switch(this.#n+=c,r){case $.POS_INT:yield [r,i,a,t,c];break;case $.NEG_INT:yield [r,i,typeof a=="bigint"?-1n-a:-1-Number(a),t,c];break;case $.BYTE_STRING:a===1/0?yield*this.#r(r,e,t):yield [r,i,this.#i(a),t,a];break;case $.UTF8_STRING:a===1/0?yield*this.#r(r,e,t):yield [r,i,_V.decode(this.#i(a)),t,a];break;case $.ARRAY:if(a===1/0)yield*this.#r(r,e,t,!1);else {let u=Number(a);yield [r,i,u,t,c];for(let l=0;l<u;l++)yield*this.#a(e+1);}break;case $.MAP:if(a===1/0)yield*this.#r(r,e,t,!1);else {let u=Number(a);yield [r,i,u,t,c];for(let l=0;l<u;l++)yield*this.#a(e),yield*this.#a(e);}break;case $.TAG:yield [r,i,a,t,c],yield*this.#a(e);break;case $.SIMPLE_FLOAT:{let u=a;o&&(a=Ws.create(Number(a))),yield [r,i,a,t,u];break}}}#i(e){let t=sf(this.#e,this.#n,this.#n+=e);if(t.length!==e)throw new Error(`Unexpected end of stream reading ${e} bytes, got ${t.length}`);return t}*#r(e,t,n,r=!0){for(yield [e,Se.INDEFINITE,1/0,n,1/0];;){let i=this.#a(t),a=i.next(),[o,c,u]=a.value;if(u===st.BREAK){yield a.value,i.next();return}if(r){if(o!==e)throw new Error(`Unmatched major type. Expected ${e}, got ${o}.`);if(c===Se.INDEFINITE)throw new Error("New stream started in typed stream")}yield a.value,yield*i;}}};var MV=new Map([[Se.ZERO,1],[Se.ONE,2],[Se.TWO,3],[Se.FOUR,5],[Se.EIGHT,9]]),$V=new Uint8Array(0);function qV(s,e){return !e.boxed&&!e.preferMap&&s.every(([t])=>typeof t=="string")?Object.fromEntries(s):new Map(s)}var ts=class s{static defaultDecodeOptions={...qn.defaultOptions,ParentType:s,boxed:!1,cde:!1,dcbor:!1,diagnosticSizes:Ca.PREFERRED,convertUnsafeIntsToFloat:!1,createObject:qV,pretty:!1,preferMap:!1,rejectLargeNegatives:!1,rejectBigInts:!1,rejectDuplicateKeys:!1,rejectFloats:!1,rejectInts:!1,rejectLongLoundNaN:!1,rejectLongFloats:!1,rejectNegativeZero:!1,rejectSimple:!1,rejectStreaming:!1,rejectStringsNotNormalizedAs:null,rejectSubnormals:!1,rejectUndefined:!1,rejectUnsafeFloatInts:!1,saveOriginal:!1,sortKeys:null};static cdeDecodeOptions={cde:!0,rejectStreaming:!0,requirePreferred:!0,sortKeys:o1};static dcborDecodeOptions={...this.cdeDecodeOptions,dcbor:!0,convertUnsafeIntsToFloat:!0,rejectDuplicateKeys:!0,rejectLargeNegatives:!0,rejectLongLoundNaN:!0,rejectLongFloats:!0,rejectNegativeZero:!0,rejectSimple:!0,rejectUndefined:!0,rejectUnsafeFloatInts:!0,rejectStringsNotNormalizedAs:"NFC"};parent;mt;ai;left;offset;count=0;children=[];depth=0;#e;#s=null;constructor(e,t,n,r){if([this.mt,this.ai,,this.offset]=e,this.left=t,this.parent=n,this.#e=r,n&&(this.depth=n.depth+1),this.mt===$.MAP&&(this.#e.sortKeys||this.#e.rejectDuplicateKeys)&&(this.#s=[]),this.#e.rejectStreaming&&this.ai===Se.INDEFINITE)throw new Error("Streaming not supported")}get isStreaming(){return this.left===1/0}get done(){return this.left===0}static create(e,t,n,r){let[i,a,o,c]=e;switch(i){case $.POS_INT:case $.NEG_INT:{if(n.rejectInts)throw new Error(`Unexpected integer: ${o}`);if(n.rejectLargeNegatives&&o<-0x8000000000000000n)throw new Error(`Invalid 65bit negative number: ${o}`);let u=o;return n.convertUnsafeIntsToFloat&&u>=Mc.MIN&&u<=Mc.MAX&&(u=Number(o)),n.boxed?jr(u,r.toHere(c)):u}case $.SIMPLE_FLOAT:if(a>Se.ONE){if(n.rejectFloats)throw new Error(`Decoding unwanted floating point number: ${o}`);if(n.rejectNegativeZero&&Object.is(o,-0))throw new Error("Decoding negative zero");if(n.rejectLongLoundNaN&&isNaN(o)){let u=r.toHere(c);if(u.length!==3||u[1]!==126||u[2]!==0)throw new Error(`Invalid NaN encoding: "${Vt(u)}"`)}if(n.rejectSubnormals&&k8(r.toHere(c+1)),n.rejectLongFloats){let u=$n(o,{chunkSize:9,reduceUnsafeNumbers:n.rejectUnsafeFloatInts});if(u[0]>>5!==i)throw new Error(`Should have been encoded as int, not float: ${o}`);if(u.length<MV.get(a))throw new Error(`Number should have been encoded shorter: ${o}`)}if(typeof o=="number"&&n.boxed)return jr(o,r.toHere(c))}else {if(n.rejectSimple&&o instanceof Ws)throw new Error(`Invalid simple value: ${o}`);if(n.rejectUndefined&&o===void 0)throw new Error("Unexpected undefined")}return o;case $.BYTE_STRING:case $.UTF8_STRING:if(o===1/0)return new n.ParentType(e,1/0,t,n);if(n.rejectStringsNotNormalizedAs&&typeof o=="string"){let u=o.normalize(n.rejectStringsNotNormalizedAs);if(o!==u)throw new Error(`String not normalized as "${n.rejectStringsNotNormalizedAs}", got [${LE(o)}] instead of [${LE(u)}]`)}return n.boxed?jr(o,r.toHere(c)):o;case $.ARRAY:return new n.ParentType(e,o,t,n);case $.MAP:return new n.ParentType(e,o*2,t,n);case $.TAG:{let u=new n.ParentType(e,1,t,n);return u.children=new we(o),u}}throw new TypeError(`Invalid major type: ${i}`)}static decodeToEncodeOpts(e){return {...u1,avoidInts:e.rejectInts,float64:!e.rejectLongFloats,flushToZero:e.rejectSubnormals,largeNegativeAsBigInt:e.rejectLargeNegatives,sortKeys:e.sortKeys}}push(e,t,n){if(this.children.push(e),this.#s){let r=Ur(e)||t.toHere(n);this.#s.push(r);}return --this.left}replaceLast(e,t,n){let r,i=-1/0;if(this.children instanceof we?(i=0,r=this.children.contents,this.children.contents=e):(i=this.children.length-1,r=this.children[i],this.children[i]=e),this.#s){let a=Ur(e)||n.toHere(t.offset);this.#s[i]=a;}return r}convert(e){let t;switch(this.mt){case $.ARRAY:t=this.children;break;case $.MAP:{let n=this.#n();if(this.#e.sortKeys){let r;for(let i of n){if(r&&this.#e.sortKeys(r,i)>=0)throw new Error(`Duplicate or out of order key: "0x${i[2]}"`);r=i;}}else if(this.#e.rejectDuplicateKeys){let r=new Set;for(let[i,a,o]of n){let c=Vt(o);if(r.has(c))throw new Error(`Duplicate key: "0x${c}"`);r.add(c);}}t=this.#e.createObject(n,this.#e);break}case $.BYTE_STRING:return A8(this.children);case $.UTF8_STRING:{let n=this.children.join("");t=this.#e.boxed?jr(n,e.toHere(this.offset)):n;break}case $.TAG:t=this.children.decode(this.#e);break;default:throw new TypeError(`Invalid mt on convert: ${this.mt}`)}return this.#e.saveOriginal&&t&&typeof t=="object"&&Lr(t,e.toHere(this.offset)),t}#n(){let e=this.children,t=e.length;if(t%2)throw new Error("Missing map value");let n=new Array(t/2);if(this.#s)for(let r=0;r<t;r+=2)n[r>>1]=[e[r],e[r+1],this.#s[r]];else for(let r=0;r<t;r+=2)n[r>>1]=[e[r],e[r+1],$V];return n}};var $E=" ",FV=new TextEncoder,h1=class extends ts{close="";quote='"';get isEmptyStream(){return (this.mt===$.UTF8_STRING||this.mt===$.BYTE_STRING)&&this.count===0}};function _r(s,e,t,n){let r="";if(e===Se.INDEFINITE)r+="_";else {if(n.diagnosticSizes===Ca.NEVER)return "";{let i=n.diagnosticSizes===Ca.ALWAYS;if(!i){let a=Se.ZERO;if(Object.is(t,-0))a=Se.TWO;else if(s===$.POS_INT||s===$.NEG_INT){let o=t<0,c=typeof t=="bigint"?1n:1,u=o?-t-c:t;u<=23?a=Number(u):u<=255?a=Se.ONE:u<=65535?a=Se.TWO:u<=4294967295?a=Se.FOUR:a=Se.EIGHT;}else isFinite(t)?Math.fround(t)===t?c1(t)==null?a=Se.FOUR:a=Se.TWO:a=Se.EIGHT:a=Se.TWO;i=a!==e;}i&&(r+="_",e<Se.ONE?r+="i":r+=String(e-24));}}return r}function qE(s,e){let t={...ts.defaultDecodeOptions,...e,ParentType:h1},n=new qn(s,t),r,i,a="";for(let o of n){let[c,u,l]=o;switch(r&&(r.count>0&&l!==st.BREAK&&(r.mt===$.MAP&&r.count%2?a+=": ":(a+=",",t.pretty||(a+=" "))),t.pretty&&(r.mt!==$.MAP||r.count%2===0)&&(a+=`
|
|
360
|
+
${$E.repeat(r.depth+1)}`)),i=ts.create(o,r,t,n),c){case $.POS_INT:case $.NEG_INT:a+=String(l),a+=_r(c,u,l,t);break;case $.SIMPLE_FLOAT:if(l!==st.BREAK)if(typeof l=="number"){let h=Object.is(l,-0)?"-0.0":String(l);a+=h,isFinite(l)&&!/[.e]/.test(h)&&(a+=".0"),a+=_r(c,u,l,t);}else l instanceof Ws?(a+="simple(",a+=String(l.value),a+=_r($.POS_INT,u,l.value,t),a+=")"):a+=String(l);break;case $.BYTE_STRING:l===1/0?(a+="(_ ",i.close=")",i.quote="'"):(a+="h'",a+=Vt(l),a+="'",a+=_r($.POS_INT,u,l.length,t));break;case $.UTF8_STRING:l===1/0?(a+="(_ ",i.close=")"):(a+=JSON.stringify(l),a+=_r($.POS_INT,u,FV.encode(l).length,t));break;case $.ARRAY:{a+="[";let h=_r($.POS_INT,u,l,t);a+=h,h&&(a+=" "),t.pretty&&l?i.close=`
|
|
361
|
+
${$E.repeat(i.depth)}]`:i.close="]";break}case $.MAP:{a+="{";let h=_r($.POS_INT,u,l,t);a+=h,h&&(a+=" "),t.pretty&&l?i.close=`
|
|
362
|
+
${$E.repeat(i.depth)}}`:i.close="}";break}case $.TAG:a+=String(l),a+=_r($.POS_INT,u,l,t),a+="(",i.close=")";break}if(i===st.BREAK)if(r?.isStreaming)r.left=0;else throw new Error("Unexpected BREAK");else r&&(r.count++,r.left--);for(i instanceof h1&&(r=i);r?.done;){if(r.isEmptyStream)a=a.slice(0,-3),a+=`${r.quote}${r.quote}_`;else {if(r.mt===$.MAP&&r.count%2!==0)throw new Error(`Odd streaming map size: ${r.count}`);a+=r.close;}r=r.parent;}}return a}var KV=new TextDecoder,cf=class extends ts{depth=0;leaf=!1;value;length;[st.ENCODED];constructor(e,t,n,r){super(e,t,n,r),this.parent?this.depth=this.parent.depth+1:this.depth=r.initialDepth,[,,this.value,,this.length]=e;}numBytes(){switch(this.ai){case Se.ONE:return 1;case Se.TWO:return 2;case Se.FOUR:return 4;case Se.EIGHT:return 8}return 0}};function R8(s){return s instanceof cf}function f1(s,e){return s===1/0?"Indefinite":e?`${s} ${e}${s!==1&&s!==1n?"s":""}`:String(s)}function of(s){return "".padStart(s," ")}function V8(s,e,t){let n="";n+=of(s.depth*2);let r=Ur(s);n+=Vt(r.subarray(0,1));let i=s.numBytes();i&&(n+=" ",n+=Vt(r.subarray(1,i+1))),n=n.padEnd(e.minCol+1," "),n+="-- ",t!==void 0&&(n+=of(s.depth*2),t!==""&&(n+=`[${t}] `));let a=!1,[o]=s.children;switch(s.mt){case $.POS_INT:n+=`Unsigned: ${o}`,typeof o=="bigint"&&(n+="n");break;case $.NEG_INT:n+=`Negative: ${o}`,typeof o=="bigint"&&(n+="n");break;case $.BYTE_STRING:n+=`Bytes (Length: ${f1(s.length)})`;break;case $.UTF8_STRING:n+=`UTF8 (Length: ${f1(s.length)})`,s.length!==1/0&&(n+=`: ${JSON.stringify(o)}`);break;case $.ARRAY:n+=`Array (Length: ${f1(s.value,"item")})`;break;case $.MAP:n+=`Map (Length: ${f1(s.value,"pair")})`;break;case $.TAG:{n+=`Tag #${s.value}`;let c=s.children,[u]=c.contents.children,l=new we(c.tag,u);Lr(l,r);let h=l.comment(e,s.depth);h&&(n+=": ",n+=h),a||=l.noChildren;break}case $.SIMPLE_FLOAT:o===st.BREAK?n+="BREAK":s.ai>Se.ONE?Object.is(o,-0)?n+="Float: -0":n+=`Float: ${o}`:(n+="Simple: ",o instanceof Ws?n+=o.value:n+=o);break}if(!a)if(s.leaf){if(n+=`
|
|
363
|
+
`,r.length>i+1){let c=of((s.depth+1)*2),u=tf(r);if(u?.length){u.sort((h,m)=>h[0]-m[0]||m[1]-h[1]);let l=0;for(let[h,m,y]of u)if(!(h<l)){if(l=h+m,y==="<<"){n+=of(e.minCol+1),n+="--",n+=c,n+="<< ";let g=sf(r,h,h+m),w=tf(g);if(w){let S=w.findIndex(([C,k,x])=>C===0&&k===m&&x==="<<");S>=0&&w.splice(S,1);}n+=qE(g),n+=` >>
|
|
364
|
+
`,n+=d1(g,{initialDepth:s.depth+1,minCol:e.minCol,noPrefixHex:!0});continue}else y==="'"&&(n+=of(e.minCol+1),n+="--",n+=c,n+="'",n+=KV.decode(r.subarray(h,h+m)),n+=`'
|
|
365
365
|
`);if(h>i)for(let g=h;g<h+m;g+=8){let w=Math.min(g+8,h+m);n+=c,n+=Vt(r.subarray(g,w)),n+=`
|
|
366
366
|
`;}}}else for(let l=i+1;l<r.length;l+=8)n+=c,n+=Vt(r.subarray(l,l+8)),n+=`
|
|
367
367
|
`;}}else {n+=`
|
|
368
|
-
`;let c=0;for(let u of s.children){if(
|
|
369
|
-
`;return a+=
|
|
368
|
+
`;let c=0;for(let u of s.children){if(R8(u)){let l=String(c);s.mt===$.MAP?l=c%2?`val ${(c-1)/2}`:`key ${c/2}`:s.mt===$.TAG&&(l=""),n+=V8(u,e,l);}c++;}}return n}var GV={...ts.defaultDecodeOptions,initialDepth:0,noPrefixHex:!1,minCol:0};function d1(s,e){let t={...GV,...e,ParentType:cf,saveOriginal:!0},n=new qn(s,t),r,i;for(let o of n){if(i=ts.create(o,r,t,n),o[2]===st.BREAK)if(r?.isStreaming)r.left=1;else throw new Error("Unexpected BREAK");if(!R8(i)){let l=new cf(o,0,r,t);l.leaf=!0,l.children.push(i),Lr(l,n.toHere(o[3])),i=l;}let c=(i.depth+1)*2,u=i.numBytes();for(u&&(c+=1,c+=u*2),t.minCol=Math.max(t.minCol,c),r&&r.push(i,n,o[3]),r=i;r?.done;)i=r,i.leaf||Lr(i,n.toHere(i.offset)),{parent:r}=r;}e&&(e.minCol=t.minCol);let a=t.noPrefixHex?"":`0x${Vt(n.toHere(0))}
|
|
369
|
+
`;return a+=V8(i,t),a}var D8=!C8();function _8(s){if(typeof s=="object"&&s){if(s.constructor!==Number)throw new Error(`Expected number: ${s}`)}else if(typeof s!="number")throw new Error(`Expected number: ${s}`)}function $r(s){if(typeof s=="object"&&s){if(s.constructor!==String)throw new Error(`Expected string: ${s}`)}else if(typeof s!="string")throw new Error(`Expected string: ${s}`)}function Na(s){if(!(s instanceof Uint8Array))throw new Error(`Expected Uint8Array: ${s}`)}function M8(s){if(!Array.isArray(s))throw new Error(`Expected Array: ${s}`)}it(Map,(s,e,t)=>{let n=[...s.entries()].map(r=>[r[0],r[1],$n(r[0],t)]);if(t.rejectDuplicateKeys){let r=new Set;for(let[i,a,o]of n){let c=Vt(o);if(r.has(c))throw new Error(`Duplicate map key: 0x${c}`);r.add(c);}}t.sortKeys&&n.sort(t.sortKeys),l1(s,s.size,$.MAP,e,t);for(let[r,i,a]of n)e.write(a),Hr(i,e,t);});function U8(s){return $r(s.contents),new Date(s.contents)}U8.comment=s=>($r(s.contents),`(String Date) ${new Date(s.contents).toISOString()}`),we.registerDecoder(Qe.DATE_STRING,U8);function L8(s){return _8(s.contents),new Date(s.contents*1e3)}L8.comment=s=>(_8(s.contents),`(Epoch Date) ${new Date(s.contents*1e3).toISOString()}`),we.registerDecoder(Qe.DATE_EPOCH,L8),it(Date,s=>[Qe.DATE_EPOCH,s.valueOf()/1e3]);function p1(s,e,t){if(Na(e.contents),t.rejectBigInts)throw new Error(`Decoding unwanted big integer: ${e}(h'${Vt(e.contents)}')`);if(t.requirePreferred&&e.contents[0]===0)throw new Error(`Decoding overly-large bigint: ${e.tag}(h'${Vt(e.contents)})`);let n=e.contents.reduce((r,i)=>r<<8n|BigInt(i),0n);if(s&&(n=-1n-n),t.requirePreferred&&n>=Number.MIN_SAFE_INTEGER&&n<=Number.MAX_SAFE_INTEGER)throw new Error(`Decoding bigint that could have been int: ${n}n`);return t.boxed?jr(n,e.contents):n}var j8=p1.bind(null,!1),H8=p1.bind(null,!0);j8.comment=(s,e)=>`(Positive BigInt) ${p1(!1,s,e)}n`,H8.comment=(s,e)=>`(Negative BigInt) ${p1(!0,s,e)}n`,we.registerDecoder(Qe.POS_BIGINT,j8),we.registerDecoder(Qe.NEG_BIGINT,H8);function FE(s,e){return Na(s.contents),s}FE.comment=(s,e,t)=>{Na(s.contents);let n={...e,initialDepth:t+2,noPrefixHex:!0},r=Ur(s),i=2**((r[0]&31)-24)+1,a=r[i]&31,o=Vt(r.subarray(i,++i));a>=24&&(o+=" ",o+=Vt(r.subarray(i,i+2**(a-24)))),n.minCol=Math.max(n.minCol,(t+1)*2+o.length);let c=d1(s.contents,n),u=`Embedded CBOR
|
|
370
370
|
`;return u+=`${"".padStart((t+1)*2," ")}${o}`.padEnd(n.minCol+1," "),u+=`-- Bytes (Length: ${s.contents.length})
|
|
371
|
-
`,u+=c,u},KE.noChildren=!0,we.registerDecoder(Qe.CBOR,KE),we.registerDecoder(Qe.URI,s=>($r(s.contents),new URL(s.contents)),"URI"),it(URL,s=>[Qe.URI,s.toString()]),we.registerDecoder(Qe.BASE64URL,s=>($r(s.contents),C8(s.contents)),"Base64url-encoded"),we.registerDecoder(Qe.BASE64,s=>($r(s.contents),nf(s.contents)),"Base64-encoded"),we.registerDecoder(35,s=>($r(s.contents),new RegExp(s.contents)),"RegExp"),we.registerDecoder(21065,s=>{$r(s.contents);let e=`^(?:${s.contents})$`;return new RegExp(e,"u")},"I-RegExp"),we.registerDecoder(Qe.REGEXP,s=>{if($8(s.contents),s.contents.length<1||s.contents.length>2)throw new Error(`Invalid RegExp Array: ${s.contents}`);return new RegExp(s.contents[0],s.contents[1])},"RegExp"),it(RegExp,s=>[Qe.REGEXP,[s.source,s.flags]]),we.registerDecoder(64,s=>(Na(s.contents),s.contents),"uint8 Typed Array");function Kt(s,e,t){Na(s.contents);let n=s.contents.length;if(n%e.BYTES_PER_ELEMENT!==0)throw new Error(`Number of bytes must be divisible by ${e.BYTES_PER_ELEMENT}, got: ${n}`);n/=e.BYTES_PER_ELEMENT;let r=new e(n),i=new DataView(s.contents.buffer,s.contents.byteOffset,s.contents.byteLength),a=i[`get${e.name.replace(/Array/,"")}`].bind(i);for(let o=0;o<n;o++)r[o]=a(o*e.BYTES_PER_ELEMENT,t);return r}function Mr(s,e,t,n,r){let i=r.forceEndian??L8;if(af(i?e:t,s,r),vs(n.byteLength,s,$.BYTE_STRING),L8===i)s.write(new Uint8Array(n.buffer,n.byteOffset,n.byteLength));else {let a=`write${n.constructor.name.replace(/Array/,"")}`,o=s[a].bind(s);for(let c of n)o(c,i);}}we.registerDecoder(65,s=>Kt(s,Uint16Array,!1),"uint16, big endian, Typed Array"),we.registerDecoder(66,s=>Kt(s,Uint32Array,!1),"uint32, big endian, Typed Array"),we.registerDecoder(67,s=>Kt(s,BigUint64Array,!1),"uint64, big endian, Typed Array"),we.registerDecoder(68,s=>(Na(s.contents),new Uint8ClampedArray(s.contents)),"uint8 Typed Array, clamped arithmetic"),it(Uint8ClampedArray,s=>[68,new Uint8Array(s.buffer,s.byteOffset,s.byteLength)]),we.registerDecoder(69,s=>Kt(s,Uint16Array,!0),"uint16, little endian, Typed Array"),it(Uint16Array,(s,e,t)=>Mr(e,69,65,s,t)),we.registerDecoder(70,s=>Kt(s,Uint32Array,!0),"uint32, little endian, Typed Array"),it(Uint32Array,(s,e,t)=>Mr(e,70,66,s,t)),we.registerDecoder(71,s=>Kt(s,BigUint64Array,!0),"uint64, little endian, Typed Array"),it(BigUint64Array,(s,e,t)=>Mr(e,71,67,s,t)),we.registerDecoder(72,s=>(Na(s.contents),new Int8Array(s.contents)),"sint8 Typed Array"),it(Int8Array,s=>[72,new Uint8Array(s.buffer,s.byteOffset,s.byteLength)]),we.registerDecoder(73,s=>Kt(s,Int16Array,!1),"sint16, big endian, Typed Array"),we.registerDecoder(74,s=>Kt(s,Int32Array,!1),"sint32, big endian, Typed Array"),we.registerDecoder(75,s=>Kt(s,BigInt64Array,!1),"sint64, big endian, Typed Array"),we.registerDecoder(77,s=>Kt(s,Int16Array,!0),"sint16, little endian, Typed Array"),it(Int16Array,(s,e,t)=>Mr(e,77,73,s,t)),we.registerDecoder(78,s=>Kt(s,Int32Array,!0),"sint32, little endian, Typed Array"),it(Int32Array,(s,e,t)=>Mr(e,78,74,s,t)),we.registerDecoder(79,s=>Kt(s,BigInt64Array,!0),"sint64, little endian, Typed Array"),it(BigInt64Array,(s,e,t)=>Mr(e,79,75,s,t)),we.registerDecoder(81,s=>Kt(s,Float32Array,!1),"IEEE 754 binary32, big endian, Typed Array"),we.registerDecoder(82,s=>Kt(s,Float64Array,!1),"IEEE 754 binary64, big endian, Typed Array"),we.registerDecoder(85,s=>Kt(s,Float32Array,!0),"IEEE 754 binary32, little endian, Typed Array"),it(Float32Array,(s,e,t)=>Mr(e,85,81,s,t)),we.registerDecoder(86,s=>Kt(s,Float64Array,!0),"IEEE 754 binary64, big endian, Typed Array"),it(Float64Array,(s,e,t)=>Mr(e,86,82,s,t)),we.registerDecoder(Qe.SET,(s,e)=>{if($8(s.contents),e.sortKeys){let t=ts.decodeToEncodeOpts(e),n=null;for(let r of s.contents){let i=[r,void 0,$n(r,t)];if(n&&e.sortKeys(n,i)>=0)throw new Error(`Set items out of order in tag #${Qe.SET}`);n=i;}}return new Set(s.contents)},"Set"),it(Set,(s,e,t)=>{let n=[...s];if(t.sortKeys){let r=n.map(i=>[i,void 0,$n(i,t)]);r.sort(t.sortKeys),n=r.map(([i])=>i);}return [Qe.SET,n]}),we.registerDecoder(Qe.JSON,s=>($r(s.contents),JSON.parse(s.contents)),"JSON-encoded"),we.registerDecoder(Qe.SELF_DESCRIBED,s=>s.contents,"Self-Described"),we.registerDecoder(Qe.INVALID_16,()=>{throw new Error(`Tag always invalid: ${Qe.INVALID_16}`)},"Invalid"),we.registerDecoder(Qe.INVALID_32,()=>{throw new Error(`Tag always invalid: ${Qe.INVALID_32}`)},"Invalid"),we.registerDecoder(Qe.INVALID_64,()=>{throw new Error(`Tag always invalid: ${Qe.INVALID_64}`)},"Invalid");function GE(s){throw new Error(`Encoding ${s.constructor.name} intentionally unimplmented. It is not concrete enough to interoperate. Convert to Uint8Array first.`)}it(ArrayBuffer,GE),it(DataView,GE),typeof SharedArrayBuffer<"u"&&it(SharedArrayBuffer,GE);function p1(s){return [NaN,s.valueOf()]}it(Boolean,p1),it(Number,p1),it(String,p1),it(BigInt,p1);var GV="[object ArrayBuffer]",re=class s{static isArrayBuffer(e){return Object.prototype.toString.call(e)===GV}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=s.toUint8Array(e),r=s.toUint8Array(t);if(n.length!==r.byteLength)return !1;for(let i=0;i<n.length;i++)if(n[i]!==r[i])return !1;return !0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let a of t)n+=a.byteLength;let r=new Uint8Array(n),i=0;for(let a of t){let o=this.toUint8Array(a);r.set(o,i),i+=o.length;}return e[e.length-1]instanceof Function?this.toView(r,e[e.length-1]):r.buffer}},WE="string",WV=/^[0-9a-f\s]+$/i,JV=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,zV=/^[a-zA-Z0-9-_]+$/,y1=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n.buffer}static toString(e){let t=re.toUint8Array(e),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return decodeURIComponent(escape(n))}},ks=class{static toString(e,t=!1){let n=re.toArrayBuffer(e),r=new DataView(n),i="";for(let a=0;a<n.byteLength;a+=2){let o=r.getUint16(a,t);i+=String.fromCharCode(o);}return i}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),r=new DataView(n);for(let i=0;i<e.length;i++)r.setUint16(i*2,e.charCodeAt(i),t);return n}},he=class s{static isHex(e){return typeof e===WE&&WV.test(e)}static isBase64(e){return typeof e===WE&&JV.test(e)}static isBase64Url(e){return typeof e===WE&&zV.test(e)}static ToString(e,t="utf8"){let n=re.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return ks.toString(n,!0);case"utf16":case"utf16be":return ks.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return ks.fromString(e,!0);case"utf16":case"utf16be":return ks.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=re.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!s.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!s.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=s.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return y1.fromString(e);case"utf16":case"utf16be":return ks.fromString(e);case"utf16le":case"usc2":return ks.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=s.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return y1.toString(e);case"utf16":case"utf16be":return ks.toString(e);case"utf16le":case"usc2":return ks.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);return n.buffer}static ToBinary(e){let t=re.toUint8Array(e),n="";for(let r=0;r<t.length;r++)n+=String.fromCharCode(t[r]);return n}static ToHex(e){let t=re.toUint8Array(e),n="",r=t.length;for(let i=0;i<r;i++){let a=t[i];a<16&&(n+="0"),n+=a.toString(16);}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!s.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r=r+2){let i=t.slice(r,r+2);n[r/2]=parseInt(i,16);}return n.buffer}static ToUtf16String(e,t=!1){return ks.toString(e,t)}static FromUtf16String(e,t=!1){return ks.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};he.DEFAULT_UTF8_ENCODING="utf8";function d(s,e,t){var n;return s instanceof Object&&(n=s[e])!==null&&n!==void 0?n:t}function w1(s,e=0,t=s.byteLength-e,n=!1){let r="";for(let i of new Uint8Array(s,e,t)){let a=i.toString(16).toUpperCase();a.length===1&&(r+="0"),r+=a,n&&(r+=" ");}return r.trim()}function Fn(s,e){let t=0;if(s.length===1)return s[0];for(let n=s.length-1;n>=0;n--)t+=s[s.length-1-n]*Math.pow(2,e*n);return t}function Js(s,e,t=-1){let n=t,r=s,i=0,a=Math.pow(2,e);for(let o=1;o<8;o++){if(s<a){let c;if(n<0)c=new ArrayBuffer(o),i=o;else {if(n<o)return new ArrayBuffer(0);c=new ArrayBuffer(n),i=n;}let u=new Uint8Array(c);for(let l=o-1;l>=0;l--){let h=Math.pow(2,l*e);u[i-l-1]=Math.floor(r/h),r-=u[i-l-1]*h;}return c}a*=Math.pow(2,e);}return new ArrayBuffer(0)}function ka(...s){let e=0,t=0;for(let i of s)e+=i.byteLength;let n=new ArrayBuffer(e),r=new Uint8Array(n);for(let i of s)r.set(new Uint8Array(i),t),t+=i.byteLength;return n}function b1(...s){let e=0,t=0;for(let i of s)e+=i.length;let n=new ArrayBuffer(e),r=new Uint8Array(n);for(let i of s)r.set(i,t),t+=i.length;return r}function JE(){let s=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let o=s[0]===255&&s[1]&128,c=s[0]===0&&(s[1]&128)===0;(o||c)&&this.warnings.push("Needlessly long format");}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let o=0;o<this.valueHex.byteLength;o++)t[o]=0;t[0]=s[0]&128;let n=Fn(t,8),r=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(r);for(let o=0;o<this.valueHex.byteLength;o++)i[o]=s[o];return i[0]&=127,Fn(i,8)-n}function F8(s){let e=s<0?s*-1:s,t=128;for(let n=1;n<8;n++){if(e<=t){if(s<0){let a=t-e,o=Js(a,8,n),c=new Uint8Array(o);return c[0]|=128,o}let r=Js(e,8,n),i=new Uint8Array(r);if(i[0]&128){let a=r.slice(0),o=new Uint8Array(a);r=new ArrayBuffer(r.byteLength+1),i=new Uint8Array(r);for(let c=0;c<a.byteLength;c++)i[c+1]=o[c];i[0]=0;}return r}t*=Math.pow(2,8);}return new ArrayBuffer(0)}function qr(s,e){if(s.byteLength!==e.byteLength)return !1;let t=new Uint8Array(s),n=new Uint8Array(e);for(let r=0;r<t.length;r++)if(t[r]!==n[r])return !1;return !0}function us(s,e){let t=s.toString(10);if(e<t.length)return "";let n=e-t.length,r=new Array(n);for(let a=0;a<n;a++)r[a]="0";return r.join("").concat(t)}var K8="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",G8="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=";function S1(s,e=!1,t=!1,n=!1){let r=0,i=0,a=0,o="",c=e?G8:K8;if(n){let u=0;for(let l=0;l<s.length;l++)if(s.charCodeAt(l)!==0){u=l;break}s=s.slice(u);}for(;r<s.length;){let u=s.charCodeAt(r++);r>=s.length&&(i=1);let l=s.charCodeAt(r++);r>=s.length&&(a=1);let h=s.charCodeAt(r++),m=u>>2,y=(u&3)<<4|l>>4,g=(l&15)<<2|h>>6,w=h&63;i===1?g=w=64:a===1&&(w=64),t?g===64?o+=`${c.charAt(m)}${c.charAt(y)}`:w===64?o+=`${c.charAt(m)}${c.charAt(y)}${c.charAt(g)}`:o+=`${c.charAt(m)}${c.charAt(y)}${c.charAt(g)}${c.charAt(w)}`:o+=`${c.charAt(m)}${c.charAt(y)}${c.charAt(g)}${c.charAt(w)}`;}return o}function $c(s,e=!1,t=!1){let n=e?G8:K8;function r(c){for(let u=0;u<64;u++)if(n.charAt(u)===c)return u;return 64}function i(c){return c===64?0:c}let a=0,o="";for(;a<s.length;){let c=r(s.charAt(a++)),u=a>=s.length?0:r(s.charAt(a++)),l=a>=s.length?0:r(s.charAt(a++)),h=a>=s.length?0:r(s.charAt(a++)),m=i(c)<<2|i(u)>>4,y=(i(u)&15)<<4|i(l)>>2,g=(i(l)&3)<<6|i(h);o+=String.fromCharCode(m),l!==64&&(o+=String.fromCharCode(y)),h!==64&&(o+=String.fromCharCode(g));}if(t){let c=o.length,u=-1;for(let l=c-1;l>=0;l--)if(o.charCodeAt(l)!==0){u=l;break}u!==-1?o=o.slice(0,u+1):o="";}return o}function uf(s){let e="",t=new Uint8Array(s);for(let n of t)e+=String.fromCharCode(n);return e}function Pa(s){let e=s.length,t=new ArrayBuffer(e),n=new Uint8Array(t);for(let r=0;r<e;r++)n[r]=s.charCodeAt(r);return t}var YV=Math.log(2);function W8(s){let e=Math.log(s)/YV,t=Math.floor(e),n=Math.round(e);return t===n?t:n}function V(s,e){for(let t of e)delete s[t];}function v1(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function YE(s){let e=0,t=0;for(let r=0;r<s.length;r++){let i=s[r];e+=i.byteLength;}let n=new Uint8Array(e);for(let r=0;r<s.length;r++){let i=s[r];n.set(new Uint8Array(i),t),t+=i.byteLength;}return n.buffer}function Jn(s,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(s.error="Wrong parameter: inputOffset less than zero",!1):n<0?(s.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(s.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(s.error="Wrong parameter: inputBuffer has zero length",!1):(s.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var ff=class{constructor(){this.items=[];}write(e){this.items.push(e);}final(){return YE(this.items)}},lf=[new Uint8Array([1])],z8="0123456789",zE="name",Y8="valueHexView",ZV="isHexOnly",QV="idBlock",XV="tagClass",e7="tagNumber",t7="isConstructed",s7="fromBER",n7="toBER",r7="local",ls="",gn=new ArrayBuffer(0),F1=new Uint8Array(0),df="EndOfContent",Q8="OCTET STRING",X8="BIT STRING";function zn(s){var e;return e=class extends s{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n);}constructor(...n){var r;super(...n);let i=n[0]||{};this.isHexOnly=(r=i.isHexOnly)!==null&&r!==void 0?r:!1,this.valueHexView=i.valueHex?re.toUint8Array(i.valueHex):F1;}fromBER(n,r,i){let a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Jn(this,a,r,i))return -1;let o=r+i;return this.valueHexView=a.subarray(r,o),this.valueHexView.length?(this.blockLength=i,o):(this.warnings.push("Zero buffer length"),r)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",gn)}toJSON(){return {...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:he.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Kn=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e);}constructor({blockLength:e=0,error:t=ls,warnings:n=[],valueBeforeDecode:r=F1}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=re.toUint8Array(r);}toJSON(){return {blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:he.ToHex(this.valueBeforeDecodeView)}}};Kn.NAME="baseBlock";var Gt=class extends Kn{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Gt.NAME="valueBlock";var x1=class extends zn(Kn){constructor({idBlock:e={}}={}){var t,n,r,i;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?re.toUint8Array(e.valueHex):F1,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(r=e.tagNumber)!==null&&r!==void 0?r:-1,this.isConstructed=(i=e.isConstructed)!==null&&i!==void 0?i:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1);}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",gn}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let r=new Uint8Array(1);if(!e){let i=this.tagNumber;i&=31,t|=i,r[0]=t;}return r.buffer}if(!this.isHexOnly){let r=Js(this.tagNumber,7),i=new Uint8Array(r),a=r.byteLength,o=new Uint8Array(a+1);if(o[0]=t|31,!e){for(let c=0;c<a-1;c++)o[c+1]=i[c]|128;o[a]=i[a-1];}return o.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let r=this.valueHexView;for(let i=0;i<r.length-1;i++)n[i+1]=r[i]|128;n[this.valueHexView.byteLength]=r[r.length-1];}return n.buffer}fromBER(e,t,n){let r=re.toUint8Array(e);if(!Jn(this,r,t,n))return -1;let i=r.subarray(t,t+n);if(i.length===0)return this.error="Zero buffer length",-1;switch(i[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(i[0]&32)===32,this.isHexOnly=!1;let o=i[0]&31;if(o!==31)this.tagNumber=o,this.blockLength=1;else {let c=1,u=this.valueHexView=new Uint8Array(255),l=255;for(;i[c]&128;){if(u[c-1]=i[c]&127,c++,c>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c===l){l+=255;let m=new Uint8Array(l);for(let y=0;y<u.length;y++)m[y]=u[y];u=this.valueHexView=new Uint8Array(l);}}this.blockLength=c+1,u[c-1]=i[c]&127;let h=new Uint8Array(c);for(let m=0;m<c;m++)h[m]=u[m];u=this.valueHexView=new Uint8Array(c),u.set(h),this.blockLength<=9?this.tagNumber=Fn(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"));}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return {...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};x1.NAME="identificationBlock";var E1=class extends Kn{constructor({lenBlock:e={}}={}){var t,n,r;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(r=e.length)!==null&&r!==void 0?r:0;}fromBER(e,t,n){let r=re.toUint8Array(e);if(!Jn(this,r,t,n))return -1;let i=r.subarray(t,t+n);if(i.length===0)return this.error="Zero buffer length",-1;if(i[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=i[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,t+this.blockLength;let a=i[0]&127;if(a>8)return this.error="Too big integer",-1;if(a+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let o=t+1,c=r.subarray(o,o+a);return c[a-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Fn(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=a+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let r=Js(this.length,8);if(r.byteLength>127)return this.error="Too big length",gn;if(t=new ArrayBuffer(r.byteLength+1),e)return t;let i=new Uint8Array(r);n=new Uint8Array(t),n[0]=r.byteLength|128;for(let a=0;a<r.byteLength;a++)n[a+1]=i[a];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return {...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};E1.NAME="lengthBlock";var Z={},Dt=class extends Kn{constructor({name:e=ls,optional:t=!1,primitiveSchema:n,...r}={},i){super(r),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new x1(r),this.lenBlock=new E1(r),this.valueBlock=i?new i(r):new Gt(r);}fromBER(e,t,n){let r=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return r===-1?(this.error=this.valueBlock.error,r):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),r)}toBER(e,t){let n=t||new ff;t||eN(this);let r=this.idBlock.toBER(e);if(n.write(r),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else {let i=this.valueBlock.toBER(e);this.lenBlock.length=i.byteLength;let a=this.lenBlock.toBER(e);n.write(a),n.write(i);}return t?gn:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():he.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=he.ToHex(this.valueBlock.valueBeforeDecodeView);return `${e} : ${t}`}isEqual(e){if(this===e)return !0;if(!(e instanceof this.constructor))return !1;let t=this.toBER(),n=e.toBER();return qr(t,n)}};Dt.NAME="BaseBlock";function eN(s){var e;if(s instanceof Z.Constructed)for(let t of s.valueBlock.value)eN(t)&&(s.lenBlock.isIndefiniteForm=!0);return !!(!((e=s.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var A1=class extends Dt{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e;}constructor({value:e=ls,...t}={},n){super(t,n),e&&this.fromString(e);}fromBER(e,t,n){let r=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return r===-1?(this.error=this.valueBlock.error,r):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),r)}onAsciiEncoding(){return `${this.constructor.NAME} : '${this.valueBlock.value}'`}};A1.NAME="BaseStringBlock";var I1=class extends zn(Gt){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e;}};I1.NAME="PrimitiveValueBlock";var tN,ie=class extends Dt{constructor(e={}){super(e,I1),this.idBlock.isConstructed=!1;}};tN=ie;Z.Primitive=tN;ie.NAME="PRIMITIVE";function i7(s,e){if(s instanceof e)return s;let t=new e;return t.idBlock=s.idBlock,t.lenBlock=s.lenBlock,t.warnings=s.warnings,t.valueBeforeDecodeView=s.valueBeforeDecodeView,t}function yf(s,e=0,t=s.length){let n=e,r=new Dt({},Gt),i=new Kn;if(!Jn(i,s,e,t))return r.error=i.error,{offset:-1,result:r};if(!s.subarray(e,e+t).length)return r.error="Zero buffer length",{offset:-1,result:r};let o=r.idBlock.fromBER(s,e,t);if(r.idBlock.warnings.length&&r.warnings.concat(r.idBlock.warnings),o===-1)return r.error=r.idBlock.error,{offset:-1,result:r};if(e=o,t-=r.idBlock.blockLength,o=r.lenBlock.fromBER(s,e,t),r.lenBlock.warnings.length&&r.warnings.concat(r.lenBlock.warnings),o===-1)return r.error=r.lenBlock.error,{offset:-1,result:r};if(e=o,t-=r.lenBlock.blockLength,!r.idBlock.isConstructed&&r.lenBlock.isIndefiniteForm)return r.error="Indefinite length form used for primitive encoding form",{offset:-1,result:r};let c=Dt;switch(r.idBlock.tagClass){case 1:if(r.idBlock.tagNumber>=37&&r.idBlock.isHexOnly===!1)return r.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:r};switch(r.idBlock.tagNumber){case 0:if(r.idBlock.isConstructed&&r.lenBlock.length>0)return r.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:r};c=Z.EndOfContent;break;case 1:c=Z.Boolean;break;case 2:c=Z.Integer;break;case 3:c=Z.BitString;break;case 4:c=Z.OctetString;break;case 5:c=Z.Null;break;case 6:c=Z.ObjectIdentifier;break;case 10:c=Z.Enumerated;break;case 12:c=Z.Utf8String;break;case 13:c=Z.RelativeObjectIdentifier;break;case 14:c=Z.TIME;break;case 15:return r.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:r};case 16:c=Z.Sequence;break;case 17:c=Z.Set;break;case 18:c=Z.NumericString;break;case 19:c=Z.PrintableString;break;case 20:c=Z.TeletexString;break;case 21:c=Z.VideotexString;break;case 22:c=Z.IA5String;break;case 23:c=Z.UTCTime;break;case 24:c=Z.GeneralizedTime;break;case 25:c=Z.GraphicString;break;case 26:c=Z.VisibleString;break;case 27:c=Z.GeneralString;break;case 28:c=Z.UniversalString;break;case 29:c=Z.CharacterString;break;case 30:c=Z.BmpString;break;case 31:c=Z.DATE;break;case 32:c=Z.TimeOfDay;break;case 33:c=Z.DateTime;break;case 34:c=Z.Duration;break;default:{let u=r.idBlock.isConstructed?new Z.Constructed:new Z.Primitive;u.idBlock=r.idBlock,u.lenBlock=r.lenBlock,u.warnings=r.warnings,r=u;}}break;case 2:case 3:case 4:default:c=r.idBlock.isConstructed?Z.Constructed:Z.Primitive;}return r=i7(r,c),o=r.fromBER(s,e,r.lenBlock.isIndefiniteForm?t:r.lenBlock.length),r.valueBeforeDecodeView=s.subarray(n,n+r.blockLength),{offset:o,result:r}}function ht(s){if(!s.byteLength){let e=new Dt({},Gt);return e.error="Input buffer has zero length",{offset:-1,result:e}}return yf(re.toUint8Array(s).slice(),0,s.byteLength)}function a7(s,e){return s?1:e}var mn=class extends Gt{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t;}fromBER(e,t,n){let r=re.toUint8Array(e);if(!Jn(this,r,t,n))return -1;if(this.valueBeforeDecodeView=r.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let i=t;for(;a7(this.isIndefiniteForm,n)>0;){let a=yf(r,i,n);if(a.offset===-1)return this.error=a.result.error,this.warnings.concat(a.result.warnings),-1;if(i=a.offset,this.blockLength+=a.result.blockLength,n-=a.result.blockLength,this.value.push(a.result),this.isIndefiniteForm&&a.result.constructor.NAME===df)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===df?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){let n=t||new ff;for(let r=0;r<this.value.length;r++)this.value[r].toBER(e,n);return t?gn:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};mn.NAME="ConstructedValueBlock";var sN,A=class extends Dt{constructor(e={}){super(e,mn),this.idBlock.isConstructed=!0;}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let r=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return r===-1?(this.error=this.valueBlock.error,r):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),r)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
371
|
+
`,u+=c,u},FE.noChildren=!0,we.registerDecoder(Qe.CBOR,FE),we.registerDecoder(Qe.URI,s=>($r(s.contents),new URL(s.contents)),"URI"),it(URL,s=>[Qe.URI,s.toString()]),we.registerDecoder(Qe.BASE64URL,s=>($r(s.contents),I8(s.contents)),"Base64url-encoded"),we.registerDecoder(Qe.BASE64,s=>($r(s.contents),nf(s.contents)),"Base64-encoded"),we.registerDecoder(35,s=>($r(s.contents),new RegExp(s.contents)),"RegExp"),we.registerDecoder(21065,s=>{$r(s.contents);let e=`^(?:${s.contents})$`;return new RegExp(e,"u")},"I-RegExp"),we.registerDecoder(Qe.REGEXP,s=>{if(M8(s.contents),s.contents.length<1||s.contents.length>2)throw new Error(`Invalid RegExp Array: ${s.contents}`);return new RegExp(s.contents[0],s.contents[1])},"RegExp"),it(RegExp,s=>[Qe.REGEXP,[s.source,s.flags]]),we.registerDecoder(64,s=>(Na(s.contents),s.contents),"uint8 Typed Array");function Kt(s,e,t){Na(s.contents);let n=s.contents.length;if(n%e.BYTES_PER_ELEMENT!==0)throw new Error(`Number of bytes must be divisible by ${e.BYTES_PER_ELEMENT}, got: ${n}`);n/=e.BYTES_PER_ELEMENT;let r=new e(n),i=new DataView(s.contents.buffer,s.contents.byteOffset,s.contents.byteLength),a=i[`get${e.name.replace(/Array/,"")}`].bind(i);for(let o=0;o<n;o++)r[o]=a(o*e.BYTES_PER_ELEMENT,t);return r}function Mr(s,e,t,n,r){let i=r.forceEndian??D8;if(af(i?e:t,s,r),vs(n.byteLength,s,$.BYTE_STRING),D8===i)s.write(new Uint8Array(n.buffer,n.byteOffset,n.byteLength));else {let a=`write${n.constructor.name.replace(/Array/,"")}`,o=s[a].bind(s);for(let c of n)o(c,i);}}we.registerDecoder(65,s=>Kt(s,Uint16Array,!1),"uint16, big endian, Typed Array"),we.registerDecoder(66,s=>Kt(s,Uint32Array,!1),"uint32, big endian, Typed Array"),we.registerDecoder(67,s=>Kt(s,BigUint64Array,!1),"uint64, big endian, Typed Array"),we.registerDecoder(68,s=>(Na(s.contents),new Uint8ClampedArray(s.contents)),"uint8 Typed Array, clamped arithmetic"),it(Uint8ClampedArray,s=>[68,new Uint8Array(s.buffer,s.byteOffset,s.byteLength)]),we.registerDecoder(69,s=>Kt(s,Uint16Array,!0),"uint16, little endian, Typed Array"),it(Uint16Array,(s,e,t)=>Mr(e,69,65,s,t)),we.registerDecoder(70,s=>Kt(s,Uint32Array,!0),"uint32, little endian, Typed Array"),it(Uint32Array,(s,e,t)=>Mr(e,70,66,s,t)),we.registerDecoder(71,s=>Kt(s,BigUint64Array,!0),"uint64, little endian, Typed Array"),it(BigUint64Array,(s,e,t)=>Mr(e,71,67,s,t)),we.registerDecoder(72,s=>(Na(s.contents),new Int8Array(s.contents)),"sint8 Typed Array"),it(Int8Array,s=>[72,new Uint8Array(s.buffer,s.byteOffset,s.byteLength)]),we.registerDecoder(73,s=>Kt(s,Int16Array,!1),"sint16, big endian, Typed Array"),we.registerDecoder(74,s=>Kt(s,Int32Array,!1),"sint32, big endian, Typed Array"),we.registerDecoder(75,s=>Kt(s,BigInt64Array,!1),"sint64, big endian, Typed Array"),we.registerDecoder(77,s=>Kt(s,Int16Array,!0),"sint16, little endian, Typed Array"),it(Int16Array,(s,e,t)=>Mr(e,77,73,s,t)),we.registerDecoder(78,s=>Kt(s,Int32Array,!0),"sint32, little endian, Typed Array"),it(Int32Array,(s,e,t)=>Mr(e,78,74,s,t)),we.registerDecoder(79,s=>Kt(s,BigInt64Array,!0),"sint64, little endian, Typed Array"),it(BigInt64Array,(s,e,t)=>Mr(e,79,75,s,t)),we.registerDecoder(81,s=>Kt(s,Float32Array,!1),"IEEE 754 binary32, big endian, Typed Array"),we.registerDecoder(82,s=>Kt(s,Float64Array,!1),"IEEE 754 binary64, big endian, Typed Array"),we.registerDecoder(85,s=>Kt(s,Float32Array,!0),"IEEE 754 binary32, little endian, Typed Array"),it(Float32Array,(s,e,t)=>Mr(e,85,81,s,t)),we.registerDecoder(86,s=>Kt(s,Float64Array,!0),"IEEE 754 binary64, big endian, Typed Array"),it(Float64Array,(s,e,t)=>Mr(e,86,82,s,t)),we.registerDecoder(Qe.SET,(s,e)=>{if(M8(s.contents),e.sortKeys){let t=ts.decodeToEncodeOpts(e),n=null;for(let r of s.contents){let i=[r,void 0,$n(r,t)];if(n&&e.sortKeys(n,i)>=0)throw new Error(`Set items out of order in tag #${Qe.SET}`);n=i;}}return new Set(s.contents)},"Set"),it(Set,(s,e,t)=>{let n=[...s];if(t.sortKeys){let r=n.map(i=>[i,void 0,$n(i,t)]);r.sort(t.sortKeys),n=r.map(([i])=>i);}return [Qe.SET,n]}),we.registerDecoder(Qe.JSON,s=>($r(s.contents),JSON.parse(s.contents)),"JSON-encoded"),we.registerDecoder(Qe.SELF_DESCRIBED,s=>s.contents,"Self-Described"),we.registerDecoder(Qe.INVALID_16,()=>{throw new Error(`Tag always invalid: ${Qe.INVALID_16}`)},"Invalid"),we.registerDecoder(Qe.INVALID_32,()=>{throw new Error(`Tag always invalid: ${Qe.INVALID_32}`)},"Invalid"),we.registerDecoder(Qe.INVALID_64,()=>{throw new Error(`Tag always invalid: ${Qe.INVALID_64}`)},"Invalid");function KE(s){throw new Error(`Encoding ${s.constructor.name} intentionally unimplmented. It is not concrete enough to interoperate. Convert to Uint8Array first.`)}it(ArrayBuffer,KE),it(DataView,KE),typeof SharedArrayBuffer<"u"&&it(SharedArrayBuffer,KE);function m1(s){return [NaN,s.valueOf()]}it(Boolean,m1),it(Number,m1),it(String,m1),it(BigInt,m1);var JV="[object ArrayBuffer]",re=class s{static isArrayBuffer(e){return Object.prototype.toString.call(e)===JV}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=s.toUint8Array(e),r=s.toUint8Array(t);if(n.length!==r.byteLength)return !1;for(let i=0;i<n.length;i++)if(n[i]!==r[i])return !1;return !0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let a of t)n+=a.byteLength;let r=new Uint8Array(n),i=0;for(let a of t){let o=this.toUint8Array(a);r.set(o,i),i+=o.length;}return e[e.length-1]instanceof Function?this.toView(r,e[e.length-1]):r.buffer}},GE="string",zV=/^[0-9a-f\s]+$/i,YV=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,ZV=/^[a-zA-Z0-9-_]+$/,g1=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n.buffer}static toString(e){let t=re.toUint8Array(e),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return decodeURIComponent(escape(n))}},ks=class{static toString(e,t=!1){let n=re.toArrayBuffer(e),r=new DataView(n),i="";for(let a=0;a<n.byteLength;a+=2){let o=r.getUint16(a,t);i+=String.fromCharCode(o);}return i}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),r=new DataView(n);for(let i=0;i<e.length;i++)r.setUint16(i*2,e.charCodeAt(i),t);return n}},he=class s{static isHex(e){return typeof e===GE&&zV.test(e)}static isBase64(e){return typeof e===GE&&YV.test(e)}static isBase64Url(e){return typeof e===GE&&ZV.test(e)}static ToString(e,t="utf8"){let n=re.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return ks.toString(n,!0);case"utf16":case"utf16be":return ks.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return ks.fromString(e,!0);case"utf16":case"utf16be":return ks.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=re.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!s.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!s.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=s.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return g1.fromString(e);case"utf16":case"utf16be":return ks.fromString(e);case"utf16le":case"usc2":return ks.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=s.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return g1.toString(e);case"utf16":case"utf16be":return ks.toString(e);case"utf16le":case"usc2":return ks.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);return n.buffer}static ToBinary(e){let t=re.toUint8Array(e),n="";for(let r=0;r<t.length;r++)n+=String.fromCharCode(t[r]);return n}static ToHex(e){let t=re.toUint8Array(e),n="",r=t.length;for(let i=0;i<r;i++){let a=t[i];a<16&&(n+="0"),n+=a.toString(16);}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!s.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r=r+2){let i=t.slice(r,r+2);n[r/2]=parseInt(i,16);}return n.buffer}static ToUtf16String(e,t=!1){return ks.toString(e,t)}static FromUtf16String(e,t=!1){return ks.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};he.DEFAULT_UTF8_ENCODING="utf8";function d(s,e,t){var n;return s instanceof Object&&(n=s[e])!==null&&n!==void 0?n:t}function y1(s,e=0,t=s.byteLength-e,n=!1){let r="";for(let i of new Uint8Array(s,e,t)){let a=i.toString(16).toUpperCase();a.length===1&&(r+="0"),r+=a,n&&(r+=" ");}return r.trim()}function Fn(s,e){let t=0;if(s.length===1)return s[0];for(let n=s.length-1;n>=0;n--)t+=s[s.length-1-n]*Math.pow(2,e*n);return t}function Js(s,e,t=-1){let n=t,r=s,i=0,a=Math.pow(2,e);for(let o=1;o<8;o++){if(s<a){let c;if(n<0)c=new ArrayBuffer(o),i=o;else {if(n<o)return new ArrayBuffer(0);c=new ArrayBuffer(n),i=n;}let u=new Uint8Array(c);for(let l=o-1;l>=0;l--){let h=Math.pow(2,l*e);u[i-l-1]=Math.floor(r/h),r-=u[i-l-1]*h;}return c}a*=Math.pow(2,e);}return new ArrayBuffer(0)}function ka(...s){let e=0,t=0;for(let i of s)e+=i.byteLength;let n=new ArrayBuffer(e),r=new Uint8Array(n);for(let i of s)r.set(new Uint8Array(i),t),t+=i.byteLength;return n}function w1(...s){let e=0,t=0;for(let i of s)e+=i.length;let n=new ArrayBuffer(e),r=new Uint8Array(n);for(let i of s)r.set(i,t),t+=i.length;return r}function WE(){let s=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let o=s[0]===255&&s[1]&128,c=s[0]===0&&(s[1]&128)===0;(o||c)&&this.warnings.push("Needlessly long format");}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let o=0;o<this.valueHex.byteLength;o++)t[o]=0;t[0]=s[0]&128;let n=Fn(t,8),r=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(r);for(let o=0;o<this.valueHex.byteLength;o++)i[o]=s[o];return i[0]&=127,Fn(i,8)-n}function q8(s){let e=s<0?s*-1:s,t=128;for(let n=1;n<8;n++){if(e<=t){if(s<0){let a=t-e,o=Js(a,8,n),c=new Uint8Array(o);return c[0]|=128,o}let r=Js(e,8,n),i=new Uint8Array(r);if(i[0]&128){let a=r.slice(0),o=new Uint8Array(a);r=new ArrayBuffer(r.byteLength+1),i=new Uint8Array(r);for(let c=0;c<a.byteLength;c++)i[c+1]=o[c];i[0]=0;}return r}t*=Math.pow(2,8);}return new ArrayBuffer(0)}function qr(s,e){if(s.byteLength!==e.byteLength)return !1;let t=new Uint8Array(s),n=new Uint8Array(e);for(let r=0;r<t.length;r++)if(t[r]!==n[r])return !1;return !0}function us(s,e){let t=s.toString(10);if(e<t.length)return "";let n=e-t.length,r=new Array(n);for(let a=0;a<n;a++)r[a]="0";return r.join("").concat(t)}var F8="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",K8="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=";function b1(s,e=!1,t=!1,n=!1){let r=0,i=0,a=0,o="",c=e?K8:F8;if(n){let u=0;for(let l=0;l<s.length;l++)if(s.charCodeAt(l)!==0){u=l;break}s=s.slice(u);}for(;r<s.length;){let u=s.charCodeAt(r++);r>=s.length&&(i=1);let l=s.charCodeAt(r++);r>=s.length&&(a=1);let h=s.charCodeAt(r++),m=u>>2,y=(u&3)<<4|l>>4,g=(l&15)<<2|h>>6,w=h&63;i===1?g=w=64:a===1&&(w=64),t?g===64?o+=`${c.charAt(m)}${c.charAt(y)}`:w===64?o+=`${c.charAt(m)}${c.charAt(y)}${c.charAt(g)}`:o+=`${c.charAt(m)}${c.charAt(y)}${c.charAt(g)}${c.charAt(w)}`:o+=`${c.charAt(m)}${c.charAt(y)}${c.charAt(g)}${c.charAt(w)}`;}return o}function $c(s,e=!1,t=!1){let n=e?K8:F8;function r(c){for(let u=0;u<64;u++)if(n.charAt(u)===c)return u;return 64}function i(c){return c===64?0:c}let a=0,o="";for(;a<s.length;){let c=r(s.charAt(a++)),u=a>=s.length?0:r(s.charAt(a++)),l=a>=s.length?0:r(s.charAt(a++)),h=a>=s.length?0:r(s.charAt(a++)),m=i(c)<<2|i(u)>>4,y=(i(u)&15)<<4|i(l)>>2,g=(i(l)&3)<<6|i(h);o+=String.fromCharCode(m),l!==64&&(o+=String.fromCharCode(y)),h!==64&&(o+=String.fromCharCode(g));}if(t){let c=o.length,u=-1;for(let l=c-1;l>=0;l--)if(o.charCodeAt(l)!==0){u=l;break}u!==-1?o=o.slice(0,u+1):o="";}return o}function uf(s){let e="",t=new Uint8Array(s);for(let n of t)e+=String.fromCharCode(n);return e}function Pa(s){let e=s.length,t=new ArrayBuffer(e),n=new Uint8Array(t);for(let r=0;r<e;r++)n[r]=s.charCodeAt(r);return t}var QV=Math.log(2);function G8(s){let e=Math.log(s)/QV,t=Math.floor(e),n=Math.round(e);return t===n?t:n}function V(s,e){for(let t of e)delete s[t];}function S1(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function zE(s){let e=0,t=0;for(let r=0;r<s.length;r++){let i=s[r];e+=i.byteLength;}let n=new Uint8Array(e);for(let r=0;r<s.length;r++){let i=s[r];n.set(new Uint8Array(i),t),t+=i.byteLength;}return n.buffer}function Jn(s,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(s.error="Wrong parameter: inputOffset less than zero",!1):n<0?(s.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(s.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(s.error="Wrong parameter: inputBuffer has zero length",!1):(s.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var ff=class{constructor(){this.items=[];}write(e){this.items.push(e);}final(){return zE(this.items)}},lf=[new Uint8Array([1])],J8="0123456789",JE="name",z8="valueHexView",XV="isHexOnly",e7="idBlock",t7="tagClass",s7="tagNumber",n7="isConstructed",r7="fromBER",i7="toBER",a7="local",ls="",gn=new ArrayBuffer(0),q1=new Uint8Array(0),df="EndOfContent",Z8="OCTET STRING",Q8="BIT STRING";function zn(s){var e;return e=class extends s{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n);}constructor(...n){var r;super(...n);let i=n[0]||{};this.isHexOnly=(r=i.isHexOnly)!==null&&r!==void 0?r:!1,this.valueHexView=i.valueHex?re.toUint8Array(i.valueHex):q1;}fromBER(n,r,i){let a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Jn(this,a,r,i))return -1;let o=r+i;return this.valueHexView=a.subarray(r,o),this.valueHexView.length?(this.blockLength=i,o):(this.warnings.push("Zero buffer length"),r)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",gn)}toJSON(){return {...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:he.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Kn=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e);}constructor({blockLength:e=0,error:t=ls,warnings:n=[],valueBeforeDecode:r=q1}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=re.toUint8Array(r);}toJSON(){return {blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:he.ToHex(this.valueBeforeDecodeView)}}};Kn.NAME="baseBlock";var Gt=class extends Kn{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Gt.NAME="valueBlock";var v1=class extends zn(Kn){constructor({idBlock:e={}}={}){var t,n,r,i;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?re.toUint8Array(e.valueHex):q1,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(r=e.tagNumber)!==null&&r!==void 0?r:-1,this.isConstructed=(i=e.isConstructed)!==null&&i!==void 0?i:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1);}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",gn}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let r=new Uint8Array(1);if(!e){let i=this.tagNumber;i&=31,t|=i,r[0]=t;}return r.buffer}if(!this.isHexOnly){let r=Js(this.tagNumber,7),i=new Uint8Array(r),a=r.byteLength,o=new Uint8Array(a+1);if(o[0]=t|31,!e){for(let c=0;c<a-1;c++)o[c+1]=i[c]|128;o[a]=i[a-1];}return o.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let r=this.valueHexView;for(let i=0;i<r.length-1;i++)n[i+1]=r[i]|128;n[this.valueHexView.byteLength]=r[r.length-1];}return n.buffer}fromBER(e,t,n){let r=re.toUint8Array(e);if(!Jn(this,r,t,n))return -1;let i=r.subarray(t,t+n);if(i.length===0)return this.error="Zero buffer length",-1;switch(i[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(i[0]&32)===32,this.isHexOnly=!1;let o=i[0]&31;if(o!==31)this.tagNumber=o,this.blockLength=1;else {let c=1,u=this.valueHexView=new Uint8Array(255),l=255;for(;i[c]&128;){if(u[c-1]=i[c]&127,c++,c>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c===l){l+=255;let m=new Uint8Array(l);for(let y=0;y<u.length;y++)m[y]=u[y];u=this.valueHexView=new Uint8Array(l);}}this.blockLength=c+1,u[c-1]=i[c]&127;let h=new Uint8Array(c);for(let m=0;m<c;m++)h[m]=u[m];u=this.valueHexView=new Uint8Array(c),u.set(h),this.blockLength<=9?this.tagNumber=Fn(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"));}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return {...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};v1.NAME="identificationBlock";var x1=class extends Kn{constructor({lenBlock:e={}}={}){var t,n,r;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(r=e.length)!==null&&r!==void 0?r:0;}fromBER(e,t,n){let r=re.toUint8Array(e);if(!Jn(this,r,t,n))return -1;let i=r.subarray(t,t+n);if(i.length===0)return this.error="Zero buffer length",-1;if(i[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=i[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,t+this.blockLength;let a=i[0]&127;if(a>8)return this.error="Too big integer",-1;if(a+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let o=t+1,c=r.subarray(o,o+a);return c[a-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Fn(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=a+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let r=Js(this.length,8);if(r.byteLength>127)return this.error="Too big length",gn;if(t=new ArrayBuffer(r.byteLength+1),e)return t;let i=new Uint8Array(r);n=new Uint8Array(t),n[0]=r.byteLength|128;for(let a=0;a<r.byteLength;a++)n[a+1]=i[a];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return {...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};x1.NAME="lengthBlock";var Z={},Dt=class extends Kn{constructor({name:e=ls,optional:t=!1,primitiveSchema:n,...r}={},i){super(r),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new v1(r),this.lenBlock=new x1(r),this.valueBlock=i?new i(r):new Gt(r);}fromBER(e,t,n){let r=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return r===-1?(this.error=this.valueBlock.error,r):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),r)}toBER(e,t){let n=t||new ff;t||X8(this);let r=this.idBlock.toBER(e);if(n.write(r),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else {let i=this.valueBlock.toBER(e);this.lenBlock.length=i.byteLength;let a=this.lenBlock.toBER(e);n.write(a),n.write(i);}return t?gn:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():he.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=he.ToHex(this.valueBlock.valueBeforeDecodeView);return `${e} : ${t}`}isEqual(e){if(this===e)return !0;if(!(e instanceof this.constructor))return !1;let t=this.toBER(),n=e.toBER();return qr(t,n)}};Dt.NAME="BaseBlock";function X8(s){var e;if(s instanceof Z.Constructed)for(let t of s.valueBlock.value)X8(t)&&(s.lenBlock.isIndefiniteForm=!0);return !!(!((e=s.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var E1=class extends Dt{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e;}constructor({value:e=ls,...t}={},n){super(t,n),e&&this.fromString(e);}fromBER(e,t,n){let r=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return r===-1?(this.error=this.valueBlock.error,r):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),r)}onAsciiEncoding(){return `${this.constructor.NAME} : '${this.valueBlock.value}'`}};E1.NAME="BaseStringBlock";var A1=class extends zn(Gt){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e;}};A1.NAME="PrimitiveValueBlock";var eN,ie=class extends Dt{constructor(e={}){super(e,A1),this.idBlock.isConstructed=!1;}};eN=ie;Z.Primitive=eN;ie.NAME="PRIMITIVE";function o7(s,e){if(s instanceof e)return s;let t=new e;return t.idBlock=s.idBlock,t.lenBlock=s.lenBlock,t.warnings=s.warnings,t.valueBeforeDecodeView=s.valueBeforeDecodeView,t}function yf(s,e=0,t=s.length){let n=e,r=new Dt({},Gt),i=new Kn;if(!Jn(i,s,e,t))return r.error=i.error,{offset:-1,result:r};if(!s.subarray(e,e+t).length)return r.error="Zero buffer length",{offset:-1,result:r};let o=r.idBlock.fromBER(s,e,t);if(r.idBlock.warnings.length&&r.warnings.concat(r.idBlock.warnings),o===-1)return r.error=r.idBlock.error,{offset:-1,result:r};if(e=o,t-=r.idBlock.blockLength,o=r.lenBlock.fromBER(s,e,t),r.lenBlock.warnings.length&&r.warnings.concat(r.lenBlock.warnings),o===-1)return r.error=r.lenBlock.error,{offset:-1,result:r};if(e=o,t-=r.lenBlock.blockLength,!r.idBlock.isConstructed&&r.lenBlock.isIndefiniteForm)return r.error="Indefinite length form used for primitive encoding form",{offset:-1,result:r};let c=Dt;switch(r.idBlock.tagClass){case 1:if(r.idBlock.tagNumber>=37&&r.idBlock.isHexOnly===!1)return r.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:r};switch(r.idBlock.tagNumber){case 0:if(r.idBlock.isConstructed&&r.lenBlock.length>0)return r.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:r};c=Z.EndOfContent;break;case 1:c=Z.Boolean;break;case 2:c=Z.Integer;break;case 3:c=Z.BitString;break;case 4:c=Z.OctetString;break;case 5:c=Z.Null;break;case 6:c=Z.ObjectIdentifier;break;case 10:c=Z.Enumerated;break;case 12:c=Z.Utf8String;break;case 13:c=Z.RelativeObjectIdentifier;break;case 14:c=Z.TIME;break;case 15:return r.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:r};case 16:c=Z.Sequence;break;case 17:c=Z.Set;break;case 18:c=Z.NumericString;break;case 19:c=Z.PrintableString;break;case 20:c=Z.TeletexString;break;case 21:c=Z.VideotexString;break;case 22:c=Z.IA5String;break;case 23:c=Z.UTCTime;break;case 24:c=Z.GeneralizedTime;break;case 25:c=Z.GraphicString;break;case 26:c=Z.VisibleString;break;case 27:c=Z.GeneralString;break;case 28:c=Z.UniversalString;break;case 29:c=Z.CharacterString;break;case 30:c=Z.BmpString;break;case 31:c=Z.DATE;break;case 32:c=Z.TimeOfDay;break;case 33:c=Z.DateTime;break;case 34:c=Z.Duration;break;default:{let u=r.idBlock.isConstructed?new Z.Constructed:new Z.Primitive;u.idBlock=r.idBlock,u.lenBlock=r.lenBlock,u.warnings=r.warnings,r=u;}}break;case 2:case 3:case 4:default:c=r.idBlock.isConstructed?Z.Constructed:Z.Primitive;}return r=o7(r,c),o=r.fromBER(s,e,r.lenBlock.isIndefiniteForm?t:r.lenBlock.length),r.valueBeforeDecodeView=s.subarray(n,n+r.blockLength),{offset:o,result:r}}function ht(s){if(!s.byteLength){let e=new Dt({},Gt);return e.error="Input buffer has zero length",{offset:-1,result:e}}return yf(re.toUint8Array(s).slice(),0,s.byteLength)}function c7(s,e){return s?1:e}var mn=class extends Gt{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t;}fromBER(e,t,n){let r=re.toUint8Array(e);if(!Jn(this,r,t,n))return -1;if(this.valueBeforeDecodeView=r.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let i=t;for(;c7(this.isIndefiniteForm,n)>0;){let a=yf(r,i,n);if(a.offset===-1)return this.error=a.result.error,this.warnings.concat(a.result.warnings),-1;if(i=a.offset,this.blockLength+=a.result.blockLength,n-=a.result.blockLength,this.value.push(a.result),this.isIndefiniteForm&&a.result.constructor.NAME===df)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===df?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){let n=t||new ff;for(let r=0;r<this.value.length;r++)this.value[r].toBER(e,n);return t?gn:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};mn.NAME="ConstructedValueBlock";var tN,A=class extends Dt{constructor(e={}){super(e,mn),this.idBlock.isConstructed=!0;}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let r=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return r===-1?(this.error=this.valueBlock.error,r):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),r)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
372
372
|
`).map(r=>` ${r}`).join(`
|
|
373
373
|
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
374
374
|
${e.join(`
|
|
375
|
-
`)}`:`${t} :`}};sN=A;Z.Constructed=sN;A.NAME="CONSTRUCTED";var C1=class extends Gt{fromBER(e,t,n){return t}toBER(e){return gn}};C1.override="EndOfContentValueBlock";var nN,N1=class extends Dt{constructor(e={}){super(e,C1),this.idBlock.tagClass=1,this.idBlock.tagNumber=0;}};nN=N1;Z.EndOfContent=nN;N1.NAME=df;var rN,Xe=class extends Dt{constructor(e={}){super(e,Gt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5;}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let r=new Uint8Array(n);r[0]=5,r[1]=0;}return t&&t.write(n),n}onAsciiEncoding(){return `${this.constructor.NAME}`}};rN=Xe;Z.Null=rN;Xe.NAME="NULL";var k1=class extends zn(Gt){get value(){for(let e of this.valueHexView)if(e>0)return !0;return !1}set value(e){this.valueHexView[0]=e?255:0;}constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=re.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e);}fromBER(e,t,n){let r=re.toUint8Array(e);return Jn(this,r,t,n)?(this.valueHexView=r.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,JE.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return {...super.toJSON(),value:this.value}}};k1.NAME="BooleanValueBlock";var iN,xs=class extends Dt{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e;}constructor(e={}){super(e,k1),this.idBlock.tagClass=1,this.idBlock.tagNumber=1;}onAsciiEncoding(){return `${this.constructor.NAME} : ${this.getValue}`}};iN=xs;Z.Boolean=iN;xs.NAME="BOOLEAN";var P1=class extends zn(mn){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e;}fromBER(e,t,n){let r=0;if(this.isConstructed){if(this.isHexOnly=!1,r=mn.prototype.fromBER.call(this,e,t,n),r===-1)return r;for(let i=0;i<this.value.length;i++){let a=this.value[i].constructor.NAME;if(a===df){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==Q8)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,r=super.fromBER(e,t,n),this.blockLength=n;return r}toBER(e,t){return this.isConstructed?mn.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return {...super.toJSON(),isConstructed:this.isConstructed}}};P1.NAME="OctetStringValueBlock";var ZE,L=class extends Dt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var r,i;(r=n.isConstructed)!==null&&r!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},P1),this.idBlock.tagClass=1,this.idBlock.tagNumber=4;}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let a=yf(i,0,i.byteLength);a.offset!==-1&&a.offset===n&&(this.valueBlock.value=[a.result]);}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return A.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,t=he.ToHex(this.valueBlock.valueHexView);return `${e} : ${t}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof ZE&&e.push(t.valueBlock.valueHexView);return re.concat(e)}};ZE=L;Z.OctetString=ZE;L.NAME=Q8;var T1=class extends zn(mn){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength;}fromBER(e,t,n){if(!n)return t;let r=-1;if(this.isConstructed){if(r=mn.prototype.fromBER.call(this,e,t,n),r===-1)return r;for(let o of this.value){let c=o.constructor.NAME;if(c===df){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==X8)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=o.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits;}return r}let i=re.toUint8Array(e);if(!Jn(this,i,t,n))return -1;let a=i.subarray(t,t+n);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let o=a.subarray(1);try{if(o.byteLength){let c=yf(o,0,o.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result]);}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,t+n}toBER(e,t){if(this.isConstructed)return mn.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let r=new Uint8Array(1);return r[0]=0,r.buffer}let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return {...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};T1.NAME="BitStringValueBlock";var aN,Ae=class extends Dt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var r,i;(r=n.isConstructed)!==null&&r!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},T1),this.idBlock.tagClass=1,this.idBlock.tagNumber=3;}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return A.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let a of t)e.push(a.toString(2).padStart(8,"0"));let n=e.join(""),r=this.constructor.NAME,i=n.substring(0,n.length-this.valueBlock.unusedBits);return `${r} : ${i}`}}};aN=Ae;Z.BitString=aN;Ae.NAME=X8;var oN;function o7(s,e){let t=new Uint8Array([0]),n=new Uint8Array(s),r=new Uint8Array(e),i=n.slice(0),a=i.length-1,o=r.slice(0),c=o.length-1,u=0,l=c<a?a:c,h=0;for(let m=l;m>=0;m--,h++){switch(!0){case h<o.length:u=i[a-h]+o[c-h]+t[0];break;default:u=i[a-h]+t[0];}switch(t[0]=u/10,!0){case h>=i.length:i=b1(new Uint8Array([u%10]),i);break;default:i[a-h]=u%10;}}return t[0]>0&&(i=b1(t,i)),i}function Z8(s){if(s>=lf.length)for(let e=lf.length;e<=s;e++){let t=new Uint8Array([0]),n=lf[e-1].slice(0);for(let r=n.length-1;r>=0;r--){let i=new Uint8Array([(n[r]<<1)+t[0]]);t[0]=i[0]/10,n[r]=i[0]%10;}t[0]>0&&(n=b1(t,n)),lf.push(n);}return lf[s]}function c7(s,e){let t=0,n=new Uint8Array(s),r=new Uint8Array(e),i=n.slice(0),a=i.length-1,o=r.slice(0),c=o.length-1,u,l=0;for(let h=c;h>=0;h--,l++)switch(u=i[a-l]-o[c-l]-t,!0){case u<0:t=1,i[a-l]=u+10;break;default:t=0,i[a-l]=u;}if(t>0)for(let h=a-c+1;h>=0;h--,l++)if(u=i[a-l]-t,u<0)t=1,i[a-l]=u+10;else {t=0,i[a-l]=u;break}return i.slice()}var mf=class extends zn(Gt){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=JE.call(this)));}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e);}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(F8(e));}get valueDec(){return this._valueDec}fromDER(e,t,n,r=0){let i=this.fromBER(e,t,n);if(i===-1)return i;let a=this.valueHexView;return a[0]===0&&a[1]&128?this.valueHexView=a.subarray(1):r!==0&&a.length<r&&(r-a.length>1&&(r=a.length+1),this.valueHexView=a.subarray(r-a.length)),i}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n;}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let r=super.fromBER(e,t,n);return r===-1||this.setValueHex(),r}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return {...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,r,i=this.valueHexView,a="",o=!1;for(let c=i.byteLength-1;c>=0;c--){r=i[c];for(let u=0;u<8;u++){if((r&1)===1)switch(n){case e:t=c7(Z8(n),t),a="-";break;default:t=o7(t,Z8(n));}n++,r>>=1;}}for(let c=0;c<t.length;c++)t[c]&&(o=!0),o&&(a+=z8.charAt(t[c]));return o===!1&&(a+=z8.charAt(0)),a}};oN=mf;mf.NAME="IntegerValueBlock";Object.defineProperty(oN.prototype,"valueHex",{set:function(s){this.valueHexView=new Uint8Array(s),this.setValueHex();},get:function(){return this.valueHexView.slice().buffer}});var hf,k=class extends Dt{constructor(e={}){super(e,mf),this.idBlock.tagClass=1,this.idBlock.tagNumber=2;}toBigInt(){return v1(),BigInt(this.valueBlock.toString())}static fromBigInt(e){v1();let t=BigInt(e),n=new ff,r=t.toString(16).replace(/^-/,""),i=new Uint8Array(he.FromHex(r));if(t<0){let o=new Uint8Array(i.length+(i[0]&128?1:0));o[0]|=128;let u=BigInt(`0x${he.ToHex(o)}`)+t,l=re.toUint8Array(he.FromHex(u.toString(16)));l[0]|=128,n.write(l);}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new hf({valueHex:n.final()})}convertToDER(){let e=new hf({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new hf({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return `${this.constructor.NAME} : ${this.valueBlock.toString()}`}};hf=k;Z.Integer=hf;k.NAME="INTEGER";var cN,pn=class extends k{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10;}};cN=pn;Z.Enumerated=cN;pn.NAME="ENUMERATED";var pf=class extends zn(Gt){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t;}fromBER(e,t,n){if(!n)return t;let r=re.toUint8Array(e);if(!Jn(this,r,t,n))return -1;let i=r.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let o=0;o<n&&(this.valueHexView[o]=i[o]&127,this.blockLength++,!!(i[o]&128));o++);let a=new Uint8Array(this.blockLength);for(let o=0;o<this.blockLength;o++)a[o]=this.valueHexView[o];return this.valueHexView=a,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Fn(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){v1();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let r=0;r<n.length;r++)n[r]=parseInt(t.slice(r*7,r*7+7),2)+(r+1<n.length?128:0);this.fromBER(n.buffer,0,n.length);}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let r=this.valueHexView,i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength-1;a++)i[a]=r[a]|128;return i[this.blockLength-1]=r[this.blockLength-1],i.buffer}let t=Js(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",gn;let n=new Uint8Array(t.byteLength);if(!e){let r=new Uint8Array(t),i=t.byteLength-1;for(let a=0;a<i;a++)n[a]=r[a]|128;n[i]=r[i];}return n}toString(){let e="";if(this.isHexOnly)e=he.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString();}else e=this.valueDec.toString();return e}toJSON(){return {...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};pf.NAME="sidBlock";var B1=class extends Gt{constructor({value:e=ls,...t}={}){super(t),this.value=[],e&&this.fromString(e);}fromBER(e,t,n){let r=t;for(;n>0;){let i=new pf;if(r=i.fromBER(e,r,n),r===-1)return this.blockLength=0,this.error=i.error,r;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i);}return r}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let r=this.value[n].toBER(e);if(r.byteLength===0)return this.error=this.value[n].error,gn;t.push(r);}return YE(t)}fromString(e){this.value=[];let t=0,n=0,r="",i=!1;do if(n=e.indexOf(".",t),n===-1?r=e.substring(t):r=e.substring(t,n),t=n+1,i){let a=this.value[0],o=0;switch(a.valueDec){case 0:break;case 1:o=40;break;case 2:o=80;break;default:this.value=[];return}let c=parseInt(r,10);if(isNaN(c))return;a.valueDec=c+o,i=!1;}else {let a=new pf;if(r>Number.MAX_SAFE_INTEGER){v1();let o=BigInt(r);a.valueBigInt=o;}else if(a.valueDec=parseInt(r,10),isNaN(a.valueDec))return;this.value.length||(a.isFirstSid=!0,i=!0),this.value.push(a);}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let r=this.value[n].toString();n!==0&&(e=`${e}.`),t?(r=`{${r}}`,this.value[n].isFirstSid?e=`2.{${r} - 80}`:e+=r):e+=r;}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};B1.NAME="ObjectIdentifierValueBlock";var uN,G=class extends Dt{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e);}constructor(e={}){super(e,B1),this.idBlock.tagClass=1,this.idBlock.tagNumber=6;}onAsciiEncoding(){return `${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return {...super.toJSON(),value:this.getValue()}}};uN=G;Z.ObjectIdentifier=uN;G.NAME="OBJECT IDENTIFIER";var gf=class extends zn(Kn){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e;}fromBER(e,t,n){if(n===0)return t;let r=re.toUint8Array(e);if(!Jn(this,r,t,n))return -1;let i=r.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let o=0;o<n&&(this.valueHexView[o]=i[o]&127,this.blockLength++,!!(i[o]&128));o++);let a=new Uint8Array(this.blockLength);for(let o=0;o<this.blockLength;o++)a[o]=this.valueHexView[o];return this.valueHexView=a,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Fn(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let r=this.valueHexView,i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength-1;a++)i[a]=r[a]|128;return i[this.blockLength-1]=r[this.blockLength-1],i.buffer}let t=Js(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",gn;let n=new Uint8Array(t.byteLength);if(!e){let r=new Uint8Array(t),i=t.byteLength-1;for(let a=0;a<i;a++)n[a]=r[a]|128;n[i]=r[i];}return n.buffer}toString(){let e="";return this.isHexOnly?e=he.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return {...super.toJSON(),valueDec:this.valueDec}}};gf.NAME="relativeSidBlock";var O1=class extends Gt{constructor({value:e=ls,...t}={}){super(t),this.value=[],e&&this.fromString(e);}fromBER(e,t,n){let r=t;for(;n>0;){let i=new gf;if(r=i.fromBER(e,r,n),r===-1)return this.blockLength=0,this.error=i.error,r;this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i);}return r}toBER(e,t){let n=[];for(let r=0;r<this.value.length;r++){let i=this.value[r].toBER(e);if(i.byteLength===0)return this.error=this.value[r].error,gn;n.push(i);}return YE(n)}fromString(e){this.value=[];let t=0,n=0,r="";do{n=e.indexOf(".",t),n===-1?r=e.substring(t):r=e.substring(t,n),t=n+1;let i=new gf;if(i.valueDec=parseInt(r,10),isNaN(i.valueDec))return !0;this.value.push(i);}while(n!==-1);return !0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let r=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(r=`{${r}}`),e+=r;}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};O1.NAME="RelativeObjectIdentifierValueBlock";var lN,R1=class extends Dt{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e);}constructor(e={}){super(e,O1),this.idBlock.tagClass=1,this.idBlock.tagNumber=13;}onAsciiEncoding(){return `${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return {...super.toJSON(),value:this.getValue()}}};lN=R1;Z.RelativeObjectIdentifier=lN;R1.NAME="RelativeObjectIdentifier";var hN,b=class extends A{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16;}};hN=b;Z.Sequence=hN;b.NAME="SEQUENCE";var fN,et=class extends A{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17;}};fN=et;Z.Set=fN;et.NAME="SET";var V1=class extends zn(Gt){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ls;}toJSON(){return {...super.toJSON(),value:this.value}}};V1.NAME="StringValueBlock";var D1=class extends V1{};D1.NAME="SimpleStringValueBlock";var ss=class extends A1{constructor({...e}={}){super(e,D1);}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,re.toUint8Array(e));}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);this.valueBlock.value=e;}};ss.NAME="SIMPLE STRING";var L1=class extends ss{fromBuffer(e){this.valueBlock.valueHexView=re.toUint8Array(e);try{this.valueBlock.value=he.ToUtf8String(e);}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=he.ToBinary(e);}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(he.FromUtf8String(e)),this.valueBlock.value=e;}};L1.NAME="Utf8StringValueBlock";var dN,hs=class extends L1{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12;}};dN=hs;Z.Utf8String=dN;hs.NAME="UTF8String";var j1=class extends ss{fromBuffer(e){this.valueBlock.value=he.ToUtf16String(e),this.valueBlock.valueHexView=re.toUint8Array(e);}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(he.FromUtf16String(e));}};j1.NAME="BmpStringValueBlock";var mN,Fr=class extends j1{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30;}};mN=Fr;Z.BmpString=mN;Fr.NAME="BMPString";var U1=class extends ss{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let r=0;r<n.length;r+=4)n[r]=n[r+3],n[r+1]=n[r+2],n[r+2]=0,n[r+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t));}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let r=0;r<t;r++){let i=Js(e.charCodeAt(r),8),a=new Uint8Array(i);if(a.length>4)continue;let o=4-a.length;for(let c=a.length-1;c>=0;c--)n[r*4+c+o]=a[c];}this.valueBlock.value=e;}};U1.NAME="UniversalStringValueBlock";var pN,Kr=class extends U1{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28;}};pN=Kr;Z.UniversalString=pN;Kr.NAME="UniversalString";var gN,Gn=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18;}};gN=Gn;Z.NumericString=gN;Gn.NAME="NumericString";var yN,fs=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19;}};yN=fs;Z.PrintableString=yN;fs.NAME="PrintableString";var wN,Gr=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20;}};wN=Gr;Z.TeletexString=wN;Gr.NAME="TeletexString";var bN,qc=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21;}};bN=qc;Z.VideotexString=bN;qc.NAME="VideotexString";var SN,Ta=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22;}};SN=Ta;Z.IA5String=SN;Ta.NAME="IA5String";var vN,Fc=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25;}};vN=Fc;Z.GraphicString=vN;Fc.NAME="GraphicString";var xN,Ba=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26;}};xN=Ba;Z.VisibleString=xN;Ba.NAME="VisibleString";var EN,Kc=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27;}};EN=Kc;Z.GeneralString=EN;Kc.NAME="GeneralString";var AN,Gc=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29;}};AN=Gc;Z.CharacterString=AN;Gc.NAME="CharacterString";var IN,Wn=class extends Ba{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let r=0;r<e.length;r++)this.valueBlock.valueHexView[r]=e.charCodeAt(r);}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23;}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,re.toUint8Array(e)));}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds();}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let r=parseInt(n[1],10);r>=50?this.year=1900+r:this.year=2e3+r,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10);}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=us(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=us(this.month,2),t[2]=us(this.day,2),t[3]=us(this.hour,2),t[4]=us(this.minute,2),t[5]=us(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return `${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return {...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};IN=Wn;Z.UTCTime=IN;Wn.NAME="UTCTime";var CN,Ge=class extends Wn{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24;}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds();}toDate(){let e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t=!1,n="",r="",i=0,a,o=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else {let h=new Number(e[e.length-1]);if(isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");n=e;}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else {let h=1,m=n.indexOf("+"),y="";if(m===-1&&(m=n.indexOf("-"),h=-1),m!==-1){if(y=n.substring(m+1),n=n.substring(0,m),y.length!==2&&y.length!==4)throw new Error("Wrong input string for conversion");let g=parseInt(y.substring(0,2),10);if(isNaN(g.valueOf()))throw new Error("Wrong input string for conversion");if(o=h*g,y.length===4){if(g=parseInt(y.substring(2,4),10),isNaN(g.valueOf()))throw new Error("Wrong input string for conversion");c=h*g;}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let h=new Number(`0${n.substring(u)}`);if(isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");i=h.valueOf(),r=n.substring(0,u);}else r=n;switch(!0){case r.length===8:if(a=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case r.length===10:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let h=60*i;this.minute=Math.floor(h),h=60*(h-this.minute),this.second=Math.floor(h),h=1e3*(h-this.second),this.millisecond=Math.floor(h);}break;case r.length===12:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let h=60*i;this.second=Math.floor(h),h=1e3*(h-this.second),this.millisecond=Math.floor(h);}break;case r.length===14:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let h=1e3*i;this.millisecond=Math.floor(h);}break;default:throw new Error("Wrong input string for conversion")}let l=a.exec(r);if(l===null)throw new Error("Wrong input string for conversion");for(let h=1;h<l.length;h++)switch(h){case 1:this.year=parseInt(l[h],10);break;case 2:this.month=parseInt(l[h],10);break;case 3:this.day=parseInt(l[h],10);break;case 4:this.hour=parseInt(l[h],10)+o;break;case 5:this.minute=parseInt(l[h],10)+c;break;case 6:this.second=parseInt(l[h],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let h=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=h.getUTCFullYear(),this.month=h.getUTCMonth(),this.day=h.getUTCDay(),this.hour=h.getUTCHours(),this.minute=h.getUTCMinutes(),this.second=h.getUTCSeconds(),this.millisecond=h.getUTCMilliseconds();}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(us(this.year,4)),t.push(us(this.month,2)),t.push(us(this.day,2)),t.push(us(this.hour,2)),t.push(us(this.minute,2)),t.push(us(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(us(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return {...super.toJSON(),millisecond:this.millisecond}}};CN=Ge;Z.GeneralizedTime=CN;Ge.NAME="GeneralizedTime";var NN,H1=class extends hs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31;}};NN=H1;Z.DATE=NN;H1.NAME="DATE";var kN,_1=class extends hs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32;}};kN=_1;Z.TimeOfDay=kN;_1.NAME="TimeOfDay";var PN,M1=class extends hs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33;}};PN=M1;Z.DateTime=PN;M1.NAME="DateTime";var TN,$1=class extends hs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34;}};TN=$1;Z.Duration=TN;$1.NAME="Duration";var BN,q1=class extends hs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14;}};BN=q1;Z.TIME=BN;q1.NAME="TIME";var ue=class{constructor({name:e=ls,optional:t=!1}={}){this.name=e,this.optional=t;}},We=class extends ue{constructor({value:e=[],...t}={}){super(t),this.value=e;}},fe=class extends ue{constructor({value:e=new ue,local:t=!1,...n}={}){super(n),this.value=e,this.local=t;}},Oa=class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=re.toUint8Array(e);}constructor({data:e=F1}={}){this.dataView=re.toUint8Array(e);}fromBER(e,t,n){let r=t+n;return this.dataView=re.toUint8Array(e).subarray(t,r),r}toBER(e){return this.dataView.slice().buffer}};function R(s,e,t){if(t instanceof We){for(let i of t.value)if(R(s,e,i).verified)return {verified:!0,result:s};{let i={verified:!1,result:{error:"Wrong values for Choice type"}};return t.hasOwnProperty(zE)&&(i.name=t.name),i}}if(t instanceof ue)return t.hasOwnProperty(zE)&&(s[t.name]=e),{verified:!0,result:s};if(!(s instanceof Object))return {verified:!1,result:{error:"Wrong root object"}};if(!(e instanceof Object))return {verified:!1,result:{error:"Wrong ASN.1 data"}};if(!(t instanceof Object))return {verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(QV in t))return {verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(s7 in t.idBlock))return {verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(n7 in t.idBlock))return {verified:!1,result:{error:"Wrong ASN.1 schema"}};let n=t.idBlock.toBER(!1);if(n.byteLength===0)return {verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(t.idBlock.fromBER(n,0,n.byteLength)===-1)return {verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(t.idBlock.hasOwnProperty(XV)===!1)return {verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.tagClass!==e.idBlock.tagClass)return {verified:!1,result:s};if(t.idBlock.hasOwnProperty(e7)===!1)return {verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.tagNumber!==e.idBlock.tagNumber)return {verified:!1,result:s};if(t.idBlock.hasOwnProperty(t7)===!1)return {verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.isConstructed!==e.idBlock.isConstructed)return {verified:!1,result:s};if(!(ZV in t.idBlock))return {verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.isHexOnly!==e.idBlock.isHexOnly)return {verified:!1,result:s};if(t.idBlock.isHexOnly){if(!(Y8 in t.idBlock))return {verified:!1,result:{error:"Wrong ASN.1 schema"}};let i=t.idBlock.valueHexView,a=e.idBlock.valueHexView;if(i.length!==a.length)return {verified:!1,result:s};for(let o=0;o<i.length;o++)if(i[o]!==a[1])return {verified:!1,result:s}}if(t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ls),t.name&&(s[t.name]=e)),t instanceof Z.Constructed){let i=0,a={verified:!1,result:{error:"Unknown error"}},o=t.valueBlock.value.length;if(o>0&&t.valueBlock.value[0]instanceof fe&&(o=e.valueBlock.value.length),o===0)return {verified:!0,result:s};if(e.valueBlock.value.length===0&&t.valueBlock.value.length!==0){let c=!0;for(let u=0;u<t.valueBlock.value.length;u++)c=c&&(t.valueBlock.value[u].optional||!1);return c?{verified:!0,result:s}:(t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ls),t.name&&delete s[t.name]),s.error="Inconsistent object length",{verified:!1,result:s})}for(let c=0;c<o;c++)if(c-i>=e.valueBlock.value.length){if(t.valueBlock.value[c].optional===!1){let u={verified:!1,result:s};return s.error="Inconsistent length between ASN.1 data and schema",t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ls),t.name&&(delete s[t.name],u.name=t.name)),u}}else if(t.valueBlock.value[0]instanceof fe){if(a=R(s,e.valueBlock.value[c],t.valueBlock.value[0].value),a.verified===!1)if(t.valueBlock.value[0].optional)i++;else return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ls),t.name&&delete s[t.name]),a;if(zE in t.valueBlock.value[0]&&t.valueBlock.value[0].name.length>0){let u={};r7 in t.valueBlock.value[0]&&t.valueBlock.value[0].local?u=e:u=s,typeof u[t.valueBlock.value[0].name]>"u"&&(u[t.valueBlock.value[0].name]=[]),u[t.valueBlock.value[0].name].push(e.valueBlock.value[c]);}}else if(a=R(s,e.valueBlock.value[c-i],t.valueBlock.value[c]),a.verified===!1)if(t.valueBlock.value[c].optional)i++;else return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ls),t.name&&delete s[t.name]),a;if(a.verified===!1){let c={verified:!1,result:s};return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ls),t.name&&(delete s[t.name],c.name=t.name)),c}return {verified:!0,result:s}}if(t.primitiveSchema&&Y8 in e.valueBlock){let i=yf(e.valueBlock.valueHexView);if(i.offset===-1){let a={verified:!1,result:i.result};return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ls),t.name&&(delete s[t.name],a.name=t.name)),a}return R(s,i.result,t.primitiveSchema)}return {verified:!0,result:s}}var Lt=class s{constructor(e={}){if("view"in e)this.fromUint8Array(e.view);else if("buffer"in e)this.fromArrayBuffer(e.buffer);else if("string"in e)this.fromString(e.string);else if("hexstring"in e)this.fromHexString(e.hexstring);else if("length"in e&&e.length>0){if(this.length=e.length,e.stub)for(let t=0;t<this._view.length;t++)this._view[t]=e.stub;}else this.length=0;}set buffer(e){this._buffer=e,this._view=new Uint8Array(this._buffer);}get buffer(){return this._buffer}set view(e){this._buffer=new ArrayBuffer(e.length),this._view=new Uint8Array(this._buffer),this._view.set(e);}get view(){return this._view}get length(){return this.view.byteLength}set length(e){this._buffer=new ArrayBuffer(e),this._view=new Uint8Array(this._buffer);}clear(){this._buffer=new ArrayBuffer(0),this._view=new Uint8Array(this._buffer);}fromArrayBuffer(e){this._buffer=e,this._view=new Uint8Array(this._buffer);}fromUint8Array(e){this.fromArrayBuffer(new Uint8Array(e).buffer);}fromString(e){let t=e.length;this.length=t;for(let n=0;n<t;n++)this.view[n]=e.charCodeAt(n);}toString(e=0,t=this.view.length-e){let n="";(e>=this.view.length||e<0)&&(e=0),(t>=this.view.length||t<0)&&(t=this.view.length-e);for(let r=e;r<e+t;r++)n+=String.fromCharCode(this.view[r]);return n}fromHexString(e){let t=e.length;this.buffer=new ArrayBuffer(t>>1),this.view=new Uint8Array(this.buffer);let n=new Map;n.set("0",0),n.set("1",1),n.set("2",2),n.set("3",3),n.set("4",4),n.set("5",5),n.set("6",6),n.set("7",7),n.set("8",8),n.set("9",9),n.set("A",10),n.set("a",10),n.set("B",11),n.set("b",11),n.set("C",12),n.set("c",12),n.set("D",13),n.set("d",13),n.set("E",14),n.set("e",14),n.set("F",15),n.set("f",15);let r=0,i=0;for(let a=0;a<t;a++)a%2?(i|=n.get(e.charAt(a)),this.view[r]=i,r++):i=n.get(e.charAt(a))<<4;}toHexString(e=0,t=this.view.length-e){let n="";(e>=this.view.length||e<0)&&(e=0),(t>=this.view.length||t<0)&&(t=this.view.length-e);for(let r=e;r<e+t;r++){let i=this.view[r].toString(16).toUpperCase();n=n+(i.length==1?"0":"")+i;}return n}copy(e=0,t=this.length-e){if(!e&&!this.length)return new s;if(e<0||e>this.length-1)throw new Error(`Wrong start position: ${e}`);return new s({buffer:this._buffer.slice(e,e+t)})}slice(e=0,t=this.length){if(!e&&!this.length)return new s;if(e<0||e>this.length-1)throw new Error(`Wrong start position: ${e}`);return new s({buffer:this._buffer.slice(e,t)})}realloc(e){let t=new ArrayBuffer(e),n=new Uint8Array(t);e>this._view.length?n.set(this._view):n.set(new Uint8Array(this._buffer,0,e)),this._buffer=t,this._view=new Uint8Array(this._buffer);}append(e){let t=this.length,n=e.length,r=e._view.subarray();this.realloc(t+n),this._view.set(r,t);}insert(e,t=0,n=this.length-t){return t>this.length-1?!1:(n>this.length-t&&(n=this.length-t),n>e.length&&(n=e.length),n==e.length?this._view.set(e._view,t):this._view.set(e._view.subarray(0,n),t),!0)}isEqual(e){if(this.length!=e.length)return !1;for(let t=0;t<e.length;t++)if(this.view[t]!=e.view[t])return !1;return !0}isEqualView(e){if(e.length!=this.view.length)return !1;for(let t=0;t<e.length;t++)if(this.view[t]!=e[t])return !1;return !0}findPattern(e,t,n,r){let{start:i,length:a,backward:o}=this.prepareFindParameters(t,n,r),c=e.length;if(c>a)return -1;let u=[];for(let l=0;l<c;l++)u.push(e.view[l]);for(let l=0;l<=a-c;l++){let h=!0,m=o?i-c-l:i+l;for(let y=0;y<c;y++)if(this.view[y+m]!=u[y]){h=!1;break}if(h)return o?i-c-l:i+c+l}return -1}findFirstIn(e,t,n,r){let{start:i,length:a,backward:o}=this.prepareFindParameters(t,n,r),c={id:-1,position:o?0:i+a,length:0};for(let u=0;u<e.length;u++){let l=this.findPattern(e[u],i,a,o);if(l!=-1){let h=!1,m=e[u].length;o?l-m>=c.position-c.length&&(h=!0):l-m<=c.position-c.length&&(h=!0),h&&(c.position=l,c.id=u,c.length=m);}}return c}findAllIn(e,t,n){let{start:r,length:i}=this.prepareFindParameters(t,n),a=[],o={id:-1,position:r};do{let c=o.position;if(o=this.findFirstIn(e,o.position,i),o.id==-1)break;i-=o.position-c,a.push({id:o.id,position:o.position});}while(!0);return a}findAllPatternIn(e,t,n){let{start:r,length:i}=this.prepareFindParameters(t,n),a=[],o=e.length;if(o>i)return -1;let c=Array.from(e.view);for(let u=0;u<=i-o;u++){let l=!0,h=r+u;for(let m=0;m<o;m++)if(this.view[m+h]!=c[m]){l=!1;break}l&&(a.push(r+o+u),u+=o-1);}return a}findFirstNotIn(e,t,n,r){let{start:i,length:a,backward:o}=this.prepareFindParameters(t,n,r),c={left:{id:-1,position:i},right:{id:-1,position:0},value:new s},u=a;for(;u>0;){if(c.right=this.findFirstIn(e,o?i-a+u:i+a-u,u,o),c.right.id==-1){a=u,o?i-=a:i=c.left.position,c.value=new s({buffer:this._buffer.slice(i,i+a)});break}if(c.right.position!=(o?c.left.position-e[c.right.id].length:c.left.position+e[c.right.id].length)){o?(i=c.right.position+e[c.right.id].length,a=c.left.position-c.right.position-e[c.right.id].length):(i=c.left.position,a=c.right.position-c.left.position-e[c.right.id].length),c.value=new s({buffer:this._buffer.slice(i,i+a)});break}c.left=c.right,u-=e[c.right.id].length;}if(o){let l=c.right;c.right=c.left,c.left=l;}return c}findAllNotIn(e,t,n){let{start:r,length:i}=this.prepareFindParameters(t,n),a=[],o={left:{id:-1,position:r},right:{id:-1,position:r},value:new s};do{let c=o.right.position;o=this.findFirstNotIn(e,o.right.position,i),i-=o.right.position-c,a.push({left:{id:o.left.id,position:o.left.position},right:{id:o.right.id,position:o.right.position},value:o.value});}while(o.right.id!=-1);return a}findFirstSequence(e,t,n,r){let{start:i,length:a,backward:o}=this.prepareFindParameters(t,n,r),c=this.skipNotPatterns(e,i,a,o);if(c==-1)return {position:-1,value:new s};let u=this.skipPatterns(e,c,a-(o?i-c:c-i),o);o?(i=u,a=c-u):(i=c,a=u-c);let l=new s({buffer:this._buffer.slice(i,i+a)});return {position:u,value:l}}findAllSequences(e,t,n){let{start:r,length:i}=this.prepareFindParameters(t,n),a=[],o={position:r,value:new s};do{let c=o.position;o=this.findFirstSequence(e,o.position,i),o.position!=-1&&(i-=o.position-c,a.push({position:o.position,value:o.value}));}while(o.position!=-1);return a}findPairedPatterns(e,t,n,r){let i=[];if(e.isEqual(t))return i;let{start:a,length:o}=this.prepareFindParameters(n,r),c=0,u=this.findAllPatternIn(e,a,o);if(!Array.isArray(u)||u.length==0)return i;let l=this.findAllPatternIn(t,a,o);if(!Array.isArray(l)||l.length==0)return i;for(;c<u.length&&l.length!=0;){if(u[0]==l[0]){i.push({left:u[0],right:l[0]}),u.splice(0,1),l.splice(0,1);continue}if(u[c]>l[0])break;for(;u[c]<l[0]&&(c++,!(c>=u.length)););i.push({left:u[c-1],right:l[0]}),u.splice(c-1,1),l.splice(0,1),c=0;}return i.sort((h,m)=>h.left-m.left),i}findPairedArrays(e,t,n,r){let{start:i,length:a}=this.prepareFindParameters(n,r),o=[],c=0,u=this.findAllIn(e,i,a);if(u.length==0)return o;let l=this.findAllIn(t,i,a);if(l.length==0)return o;for(;c<u.length&&l.length!=0;){if(u[0].position==l[0].position){o.push({left:u[0],right:l[0]}),u.splice(0,1),l.splice(0,1);continue}if(u[c].position>l[0].position)break;for(;u[c].position<l[0].position&&(c++,!(c>=u.length)););o.push({left:u[c-1],right:l[0]}),u.splice(c-1,1),l.splice(0,1),c=0;}return o.sort((h,m)=>h.left.position-m.left.position),o}replacePattern(e,t,n,r,i=null){let a=[],o,c={status:-1,searchPatternPositions:[],replacePatternPositions:[]},{start:u,length:l}=this.prepareFindParameters(n,r);if(i==null){if(a=this.findAllIn([e],u,l),a.length==0)return c}else a=i;c.searchPatternPositions.push(...Array.from(a,g=>g.position));let h=e.length-t.length,m=new ArrayBuffer(this.view.length-a.length*h),y=new Uint8Array(m);for(y.set(new Uint8Array(this.buffer,0,u)),o=0;o<a.length;o++){let g=o==0?u:a[o-1].position;y.set(new Uint8Array(this.buffer,g,a[o].position-e.length-g),g-o*h),y.set(t.view,a[o].position-e.length-o*h),c.replacePatternPositions.push(a[o].position-e.length-o*h);}return o--,y.set(new Uint8Array(this.buffer,a[o].position,this.length-a[o].position),a[o].position-e.length+t.length-o*h),this.buffer=m,this.view=new Uint8Array(this.buffer),c.status=1,c}skipPatterns(e,t,n,r){let{start:i,length:a,backward:o}=this.prepareFindParameters(t,n,r),c=i;for(let u=0;u<e.length;u++){let l=e[u].length,h=o?c-l:c,m=!0;for(let y=0;y<l;y++)if(this.view[y+h]!=e[u].view[y]){m=!1;break}if(m){if(u=-1,o){if(c-=l,c<=0)return c}else if(c+=l,c>=i+a)return c}}return c}skipNotPatterns(e,t,n,r){let{start:i,length:a,backward:o}=this.prepareFindParameters(t,n,r),c=-1;for(let u=0;u<a;u++){for(let l=0;l<e.length;l++){let h=e[l].length,m=o?i-u-h:i+u,y=!0;for(let g=0;g<h;g++)if(this.view[g+m]!=e[l].view[g]){y=!1;break}if(y){c=o?i-u:i+u;break}}if(c!=-1)break}return c}prepareFindParameters(e=null,t=null,n=!1){return e===null&&(e=n?this.length:0),e>this.length&&(e=this.length),n?(t===null&&(t=e),t>e&&(t=e)):(t===null&&(t=this.length-e),t>this.length-e&&(t=this.length-e)),{start:e,length:t,backward:n}}};var l7=16777216,Yn=class s{constructor(e={}){this._stream=new Lt,this._length=0,this._start=0,this.backward=!1,this.appendBlock=0,this.prevLength=0,this.prevStart=0,"view"in e?this.stream=new Lt({view:e.view}):"buffer"in e?this.stream=new Lt({buffer:e.buffer}):"string"in e?this.stream=new Lt({string:e.string}):"hexstring"in e?this.stream=new Lt({hexstring:e.hexstring}):"stream"in e?this.stream=e.stream.slice():this.stream=new Lt,"backward"in e&&e.backward&&(this.backward=e.backward,this._start=this.stream.length),"length"in e&&e.length>0&&(this._length=e.length),"start"in e&&e.start&&e.start>0&&(this._start=e.start),"appendBlock"in e&&e.appendBlock&&e.appendBlock>0&&(this.appendBlock=e.appendBlock);}set stream(e){this._stream=e,this.prevLength=this._length,this._length=e.length,this.prevStart=this._start,this._start=0;}get stream(){return this._stream}set length(e){this.prevLength=this._length,this._length=e;}get length(){return this.appendBlock?this.start:this._length}set start(e){e>this.stream.length||(this.prevStart=this._start,this.prevLength=this._length,this._length-=this.backward?this._start-e:e-this._start,this._start=e);}get start(){return this._start}get buffer(){return this._stream.buffer.slice(0,this._length)}resetPosition(){this._start=this.prevStart,this._length=this.prevLength;}findPattern(e,t=null){(t==null||t>this.length)&&(t=this.length);let n=this.stream.findPattern(e,this.start,this.length,this.backward);if(n==-1)return n;if(this.backward){if(n<this.start-e.length-t)return -1}else if(n>this.start+e.length+t)return -1;return this.start=n,n}findFirstIn(e,t=null){(t==null||t>this.length)&&(t=this.length);let n=this.stream.findFirstIn(e,this.start,this.length,this.backward);if(n.id==-1)return n;if(this.backward){if(n.position<this.start-e[n.id].length-t)return {id:-1,position:this.backward?0:this.start+this.length}}else if(n.position>this.start+e[n.id].length+t)return {id:-1,position:this.backward?0:this.start+this.length};return this.start=n.position,n}findAllIn(e){let t=this.backward?this.start-this.length:this.start;return this.stream.findAllIn(e,t,this.length)}findFirstNotIn(e,t=null){(t==null||t>this._length)&&(t=this._length);let n=this._stream.findFirstNotIn(e,this._start,this._length,this.backward);if(n.left.id==-1&&n.right.id==-1)return n;if(this.backward){if(n.right.id!=-1&&n.right.position<this._start-e[n.right.id].length-t)return {left:{id:-1,position:this._start},right:{id:-1,position:0},value:new Lt}}else if(n.left.id!=-1&&n.left.position>this._start+e[n.left.id].length+t)return {left:{id:-1,position:this._start},right:{id:-1,position:0},value:new Lt};return this.backward?n.left.id==-1?this.start=0:this.start=n.left.position:n.right.id==-1?this.start=this._start+this._length:this.start=n.right.position,n}findAllNotIn(e){let t=this.backward?this._start-this._length:this._start;return this._stream.findAllNotIn(e,t,this._length)}findFirstSequence(e,t=null,n=null){(t==null||t>this._length)&&(t=this._length),(n==null||n>t)&&(n=t);let r=this._stream.findFirstSequence(e,this._start,t,this.backward);if(r.value.length==0)return r;if(this.backward){if(r.position<this._start-r.value.length-n)return {position:-1,value:new Lt}}else if(r.position>this._start+r.value.length+n)return {position:-1,value:new Lt};return this.start=r.position,r}findAllSequences(e){let t=this.backward?this.start-this.length:this.start;return this.stream.findAllSequences(e,t,this.length)}findPairedPatterns(e,t,n=null){(n==null||n>this.length)&&(n=this.length);let r=this.backward?this.start-this.length:this.start,i=this.stream.findPairedPatterns(e,t,r,this.length);if(i.length){if(this.backward){if(i[0].right<this.start-t.length-n)return []}else if(i[0].left>this.start+e.length+n)return []}return i}findPairedArrays(e,t,n=null){(n==null||n>this.length)&&(n=this.length);let r=this.backward?this.start-this.length:this.start,i=this.stream.findPairedArrays(e,t,r,this.length);if(i.length){if(this.backward){if(i[0].right.position<this.start-t[i[0].right.id].length-n)return []}else if(i[0].left.position>this.start+e[i[0].left.id].length+n)return []}return i}replacePattern(e,t){let n=this.backward?this.start-this.length:this.start;return this.stream.replacePattern(e,t,n,this.length)}skipPatterns(e){let t=this.stream.skipPatterns(e,this.start,this.length,this.backward);return this.start=t,t}skipNotPatterns(e){let t=this.stream.skipNotPatterns(e,this.start,this.length,this.backward);return t==-1?-1:(this.start=t,t)}append(e){this.beforeAppend(e.length),this._stream.view.set(e.view,this._start),this._length+=e.length*2,this.start=this._start+e.length,this.prevLength-=e.length*2;}appendView(e){this.beforeAppend(e.length),this._stream.view.set(e,this._start),this._length+=e.length*2,this.start=this._start+e.length,this.prevLength-=e.length*2;}appendChar(e){this.beforeAppend(1),this._stream.view[this._start]=e,this._length+=2,this.start=this._start+1,this.prevLength-=2;}appendUint16(e){this.beforeAppend(2);let t=new Uint16Array([e]),n=new Uint8Array(t.buffer);this.stream.view[this._start]=n[1],this._stream.view[this._start+1]=n[0],this._length+=4,this.start=this._start+2,this.prevLength-=4;}appendUint24(e){this.beforeAppend(3);let t=new Uint32Array([e]),n=new Uint8Array(t.buffer);this._stream.view[this._start]=n[2],this._stream.view[this._start+1]=n[1],this._stream.view[this._start+2]=n[0],this._length+=6,this.start=this._start+3,this.prevLength-=6;}appendUint32(e){this.beforeAppend(4);let t=new Uint32Array([e]),n=new Uint8Array(t.buffer);this._stream.view[this._start]=n[3],this._stream.view[this._start+1]=n[2],this._stream.view[this._start+2]=n[1],this._stream.view[this._start+3]=n[0],this._length+=8,this.start=this._start+4,this.prevLength-=8;}appendInt16(e){this.beforeAppend(2);let t=new Int16Array([e]),n=new Uint8Array(t.buffer);this._stream.view[this._start]=n[1],this._stream.view[this._start+1]=n[0],this._length+=4,this.start=this._start+2,this.prevLength-=4;}appendInt32(e){this.beforeAppend(4);let t=new Int32Array([e]),n=new Uint8Array(t.buffer);this._stream.view[this._start]=n[3],this._stream.view[this._start+1]=n[2],this._stream.view[this._start+2]=n[1],this._stream.view[this._start+3]=n[0],this._length+=8,this.start=this._start+4,this.prevLength-=8;}getBlock(e,t=!0){if(this._length<=0)return new Uint8Array(0);this._length<e&&(e=this._length);let n;if(this.backward){let r=this._stream.view.subarray(this._length-e,this._length);n=new Uint8Array(e);for(let i=0;i<e;i++)n[e-1-i]=r[i];}else n=this._stream.view.subarray(this._start,this._start+e);return t&&(this.start+=this.backward?-1*e:e),n}getUint16(e=!0){let t=this.getBlock(2,e);return t.length<2?0:t[0]<<8|t[1]}getInt16(e=!0){let t=this.getUint16(e),n=32768;return t&n?-(n-(t^n)):t}getUint24(e=!0){let t=this.getBlock(4,e);return t.length<3?0:t[0]<<16|t[1]<<8|t[2]}getUint32(e=!0){let t=this.getBlock(4,e);return t.length<4?0:t[0]*l7+(t[1]<<16)+(t[2]<<8)+t[3]}getInt32(e=!0){let t=this.getUint32(e),n=2147483648;return t&n?-(n-(t^n)):t}beforeAppend(e){this._start+e>this._stream.length&&(e>this.appendBlock&&(this.appendBlock=e+s.APPEND_BLOCK),this._stream.realloc(this._stream.length+this.appendBlock));}};Yn.APPEND_BLOCK=1e3;function f7(s){return s instanceof Uint8Array||s!=null&&typeof s=="object"&&s.constructor.name==="Uint8Array"}function QE(s,...e){if(!f7(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${s.length}`)}function XE(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function ON(s,e){QE(s);let t=e.outputLen;if(s.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var G1=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),zs=(s,e)=>s<<32-e|s>>>e,W1=(s,e)=>s<<e|s>>>32-e>>>0;new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function d7(s){if(typeof s!="string")throw new Error(`utf8ToBytes expected string, got ${typeof s}`);return new Uint8Array(new TextEncoder().encode(s))}function e2(s){return typeof s=="string"&&(s=d7(s)),QE(s),s}var K1=class{clone(){return this._cloneInto()}};function Ra(s){let e=n=>s().update(e2(n)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function m7(s,e,t,n){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,n);let r=BigInt(32),i=BigInt(4294967295),a=Number(t>>r&i),o=Number(t&i),c=n?4:0,u=n?0:4;s.setUint32(e+c,a,n),s.setUint32(e+u,o,n);}var J1=(s,e,t)=>s&e^~s&t,z1=(s,e,t)=>s&e^s&t^e&t,Wr=class extends K1{constructor(e,t,n,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=G1(this.buffer);}update(e){XE(this);let{view:t,buffer:n,blockLen:r}=this;e=e2(e);let i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let c=G1(e);for(;r<=i-a;a+=r)this.process(c,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){XE(this),ON(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>r-a&&(this.process(n,0),a=0);for(let h=a;h<r;h++)t[h]=0;m7(n,r-8,BigInt(this.length*8),i),this.process(n,0);let o=G1(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)o.setUint32(4*h,l[h],i);}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.length=r,e.pos=o,e.finished=i,e.destroyed=a,r%t&&e.buffer.set(n),e}};var wf=new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),Jr=new Uint32Array(80),t2=class extends Wr{constructor(){super(64,20,8,!1),this.A=wf[0]|0,this.B=wf[1]|0,this.C=wf[2]|0,this.D=wf[3]|0,this.E=wf[4]|0;}get(){let{A:e,B:t,C:n,D:r,E:i}=this;return [e,t,n,r,i]}set(e,t,n,r,i){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0;}process(e,t){for(let c=0;c<16;c++,t+=4)Jr[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)Jr[c]=W1(Jr[c-3]^Jr[c-8]^Jr[c-14]^Jr[c-16],1);let{A:n,B:r,C:i,D:a,E:o}=this;for(let c=0;c<80;c++){let u,l;c<20?(u=J1(r,i,a),l=1518500249):c<40?(u=r^i^a,l=1859775393):c<60?(u=z1(r,i,a),l=2400959708):(u=r^i^a,l=3395469782);let h=W1(n,5)+u+o+l+Jr[c]|0;o=a,a=i,i=W1(r,30),r=n,n=h;}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,this.set(n,r,i,a,o);}roundClean(){Jr.fill(0);}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0);}},RN=Ra(()=>new t2);var p7=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),zr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Yr=new Uint32Array(64),s2=class extends Wr{constructor(){super(64,32,8,!1),this.A=zr[0]|0,this.B=zr[1]|0,this.C=zr[2]|0,this.D=zr[3]|0,this.E=zr[4]|0,this.F=zr[5]|0,this.G=zr[6]|0,this.H=zr[7]|0;}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:c}=this;return [e,t,n,r,i,a,o,c]}set(e,t,n,r,i,a,o,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=c|0;}process(e,t){for(let h=0;h<16;h++,t+=4)Yr[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let m=Yr[h-15],y=Yr[h-2],g=zs(m,7)^zs(m,18)^m>>>3,w=zs(y,17)^zs(y,19)^y>>>10;Yr[h]=w+Yr[h-7]+g+Yr[h-16]|0;}let{A:n,B:r,C:i,D:a,E:o,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){let m=zs(o,6)^zs(o,11)^zs(o,25),y=l+m+J1(o,c,u)+p7[h]+Yr[h]|0,w=(zs(n,2)^zs(n,13)^zs(n,22))+z1(n,r,i)|0;l=u,u=c,c=o,o=a+y|0,a=i,i=r,r=n,n=y+w|0;}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,c,u,l);}roundClean(){Yr.fill(0);}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0);}};var n2=Ra(()=>new s2);var Y1=BigInt(4294967295),r2=BigInt(32);function VN(s,e=!1){return e?{h:Number(s&Y1),l:Number(s>>r2&Y1)}:{h:Number(s>>r2&Y1)|0,l:Number(s&Y1)|0}}function g7(s,e=!1){let t=new Uint32Array(s.length),n=new Uint32Array(s.length);for(let r=0;r<s.length;r++){let{h:i,l:a}=VN(s[r],e);[t[r],n[r]]=[i,a];}return [t,n]}var y7=(s,e)=>BigInt(s>>>0)<<r2|BigInt(e>>>0),w7=(s,e,t)=>s>>>t,b7=(s,e,t)=>s<<32-t|e>>>t,S7=(s,e,t)=>s>>>t|e<<32-t,v7=(s,e,t)=>s<<32-t|e>>>t,x7=(s,e,t)=>s<<64-t|e>>>t-32,E7=(s,e,t)=>s>>>t-32|e<<64-t,A7=(s,e)=>e,I7=(s,e)=>s,C7=(s,e,t)=>s<<t|e>>>32-t,N7=(s,e,t)=>e<<t|s>>>32-t,k7=(s,e,t)=>e<<t-32|s>>>64-t,P7=(s,e,t)=>s<<t-32|e>>>64-t;function T7(s,e,t,n){let r=(e>>>0)+(n>>>0);return {h:s+t+(r/2**32|0)|0,l:r|0}}var B7=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),O7=(s,e,t,n)=>e+t+n+(s/2**32|0)|0,R7=(s,e,t,n)=>(s>>>0)+(e>>>0)+(t>>>0)+(n>>>0),V7=(s,e,t,n,r)=>e+t+n+r+(s/2**32|0)|0,D7=(s,e,t,n,r)=>(s>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),L7=(s,e,t,n,r,i)=>e+t+n+r+i+(s/2**32|0)|0;var j7={fromBig:VN,split:g7,toBig:y7,shrSH:w7,shrSL:b7,rotrSH:S7,rotrSL:v7,rotrBH:x7,rotrBL:E7,rotr32H:A7,rotr32L:I7,rotlSH:C7,rotlSL:N7,rotlBH:k7,rotlBL:P7,add:T7,add3L:B7,add3H:O7,add4L:R7,add4H:V7,add5H:L7,add5L:D7},Ce=j7;var[U7,H7]=Ce.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(s=>BigInt(s))),Zr=new Uint32Array(80),Qr=new Uint32Array(80),Z1=class extends Wr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209;}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:a,Dh:o,Dl:c,Eh:u,El:l,Fh:h,Fl:m,Gh:y,Gl:g,Hh:w,Hl:S}=this;return [e,t,n,r,i,a,o,c,u,l,h,m,y,g,w,S]}set(e,t,n,r,i,a,o,c,u,l,h,m,y,g,w,S){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=a|0,this.Dh=o|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=m|0,this.Gh=y|0,this.Gl=g|0,this.Hh=w|0,this.Hl=S|0;}process(e,t){for(let x=0;x<16;x++,t+=4)Zr[x]=e.getUint32(t),Qr[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let v=Zr[x-15]|0,I=Qr[x-15]|0,D=Ce.rotrSH(v,I,1)^Ce.rotrSH(v,I,8)^Ce.shrSH(v,I,7),F=Ce.rotrSL(v,I,1)^Ce.rotrSL(v,I,8)^Ce.shrSL(v,I,7),M=Zr[x-2]|0,W=Qr[x-2]|0,se=Ce.rotrSH(M,W,19)^Ce.rotrBH(M,W,61)^Ce.shrSH(M,W,6),q=Ce.rotrSL(M,W,19)^Ce.rotrBL(M,W,61)^Ce.shrSL(M,W,6),J=Ce.add4L(F,q,Qr[x-7],Qr[x-16]),ae=Ce.add4H(J,D,se,Zr[x-7],Zr[x-16]);Zr[x]=ae|0,Qr[x]=J|0;}let{Ah:n,Al:r,Bh:i,Bl:a,Ch:o,Cl:c,Dh:u,Dl:l,Eh:h,El:m,Fh:y,Fl:g,Gh:w,Gl:S,Hh:C,Hl:N}=this;for(let x=0;x<80;x++){let v=Ce.rotrSH(h,m,14)^Ce.rotrSH(h,m,18)^Ce.rotrBH(h,m,41),I=Ce.rotrSL(h,m,14)^Ce.rotrSL(h,m,18)^Ce.rotrBL(h,m,41),D=h&y^~h&w,F=m&g^~m&S,M=Ce.add5L(N,I,F,H7[x],Qr[x]),W=Ce.add5H(M,C,v,D,U7[x],Zr[x]),se=M|0,q=Ce.rotrSH(n,r,28)^Ce.rotrBH(n,r,34)^Ce.rotrBH(n,r,39),J=Ce.rotrSL(n,r,28)^Ce.rotrBL(n,r,34)^Ce.rotrBL(n,r,39),ae=n&i^n&o^i&o,Be=r&a^r&c^a&c;C=w|0,N=S|0,w=y|0,S=g|0,y=h|0,g=m|0,{h,l:m}=Ce.add(u|0,l|0,W|0,se|0),u=o|0,l=c|0,o=i|0,c=a|0,i=n|0,a=r|0;let j=Ce.add3L(se,J,Be);n=Ce.add3H(j,W,q,ae),r=j|0;}(({h:n,l:r}=Ce.add(this.Ah|0,this.Al|0,n|0,r|0))),{h:i,l:a}=Ce.add(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:c}=Ce.add(this.Ch|0,this.Cl|0,o|0,c|0),{h:u,l}=Ce.add(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:m}=Ce.add(this.Eh|0,this.El|0,h|0,m|0),{h:y,l:g}=Ce.add(this.Fh|0,this.Fl|0,y|0,g|0),{h:w,l:S}=Ce.add(this.Gh|0,this.Gl|0,w|0,S|0),{h:C,l:N}=Ce.add(this.Hh|0,this.Hl|0,C|0,N|0),this.set(n,r,i,a,o,c,u,l,h,m,y,g,w,S,C,N);}roundClean(){Zr.fill(0),Qr.fill(0);}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}};var i2=class extends Z1{constructor(){super(),this.Ah=-876896931,this.Al=-1056596264,this.Bh=1654270250,this.Bl=914150663,this.Ch=-1856437926,this.Cl=812702999,this.Dh=355462360,this.Dl=-150054599,this.Eh=1731405415,this.El=-4191439,this.Fh=-1900787065,this.Fl=1750603025,this.Gh=-619958771,this.Gl=1694076839,this.Hh=1203062813,this.Hl=-1090891868,this.outputLen=48;}},a2=Ra(()=>new Z1);var o2=Ra(()=>new i2);var ut=new ArrayBuffer(0),p="",$e=class s extends TypeError{constructor(){super(...arguments),this.name=s.NAME;}static isType(e,t){if(typeof t=="string"){if(t==="Array"&&Array.isArray(e))return !0;if(t==="ArrayBuffer"&&e instanceof ArrayBuffer)return !0;if(t==="ArrayBufferView"&&ArrayBuffer.isView(e))return !0;if(typeof e===t)return !0}else if(e instanceof t)return !0;return !1}static assert(e,t,...n){for(let i of n)if(this.isType(e,i))return;let r=n.map(i=>i instanceof Function&&"name"in i?i.name:`${i}`);throw new s(`Parameter '${t}' is not of type ${r.length>1?`(${r.join(" or ")})`:r[0]}`)}};$e.NAME="ArgumentError";var Re=class s extends TypeError{static assert(...e){let t=null,n,r;typeof e[0]=="string"?(t=e[0],n=e[1],r=e.slice(2)):(n=e[0],r=e.slice(1)),$e.assert(n,"parameters","object");for(let i of r){let a=n[i];if(a==null)throw new s(i,t)}}static assertEmpty(e,t,n){if(e==null)throw new s(t,n)}constructor(e,t=null,n){super(),this.name=s.NAME,this.field=e,t&&(this.target=t),n?this.message=n:this.message=`Absent mandatory parameter '${e}' ${t?` in '${t}'`:p}`;}};Re.NAME="ParameterError";var T=class s extends Error{static assertSchema(e,t){if(!e.verified)throw new Error(`Object's schema was not verified against input data for ${t}`)}static assert(e,t){if(e.offset===-1)throw new s(`Error during parsing of ASN.1 data. Data is not correct for '${t}'.`)}constructor(e){super(e),this.name="AsnError";}},O=class{static blockName(){return this.CLASS_NAME}static fromBER(e){let t=ht(e);T.assert(t,this.name);try{return new this({schema:t.result})}catch{throw new T(`Cannot create '${this.CLASS_NAME}' from ASN.1 object`)}}static defaultValues(e){throw new Error(`Invalid member name for ${this.CLASS_NAME} class: ${e}`)}static schema(e={}){throw new Error(`Method '${this.CLASS_NAME}.schema' should be overridden`)}get className(){return this.constructor.CLASS_NAME}toString(e="hex"){let t;try{t=this.toSchema();}catch{t=this.toSchema(!0);}return he.ToString(t.toBER(),e)}};O.CLASS_NAME="PkiObject";function Ui(s){let e=!1,t=p,n=s.trim();for(let r=0;r<n.length;r++)n.charCodeAt(r)===32?e===!1&&(e=!0):(e&&(t+=" ",e=!1),t+=n[r]);return t.toLowerCase()}var bf="type",c2="value",km=class s extends O{constructor(e={}){super(),this.type=d(e,bf,s.defaultValues(bf)),this.value=d(e,c2,s.defaultValues(c2)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case bf:return p;case c2:return {};default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.type||p}),new ue({name:t.value||p})]})}fromSchema(e){V(e,[bf,"typeValue"]);let t=R(e,e,s.schema({names:{type:bf,value:"typeValue"}}));T.assertSchema(t,this.className),this.type=t.result.type.valueBlock.toString(),this.value=t.result.typeValue;}toSchema(){return new b({value:[new G({value:this.type}),this.value]})}toJSON(){let e={type:this.type};return Object.keys(this.value).length!==0?e.value=this.value.toJSON():e.value=this.value,e}isEqual(e){let t=[hs.blockName(),Fr.blockName(),Kr.blockName(),Gn.blockName(),fs.blockName(),Gr.blockName(),qc.blockName(),Ta.blockName(),Fc.blockName(),Ba.blockName(),Kc.blockName(),Gc.blockName()];if(e instanceof ArrayBuffer)return re.isEqual(this.value.valueBeforeDecodeView,e);if(e.constructor.blockName()===s.blockName()){if(this.type!==e.type)return !1;let n=[!1,!1],r=this.value.constructor.blockName();for(let a of t)r===a&&(n[0]=!0),e.value.constructor.blockName()===a&&(n[1]=!0);if(n[0]!==n[1])return !1;if(n[0]&&n[1]){let a=Ui(this.value.valueBlock.value),o=Ui(e.value.valueBlock.value);if(a.localeCompare(o)!==0)return !1}else if(!re.isEqual(this.value.valueBeforeDecodeView,e.value.valueBeforeDecodeView))return !1;return !0}return !1}};km.CLASS_NAME="AttributeTypeAndValue";var Va="typesAndValues",Q1="valueBeforeDecode",DN="RDN",Je=class s extends O{constructor(e={}){super(),this.typesAndValues=d(e,Va,s.defaultValues(Va)),this.valueBeforeDecode=d(e,Q1,s.defaultValues(Q1)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Va:return [];case Q1:return ut;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Va:return t.length===0;case Q1:return t.byteLength===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.repeatedSequence||p,value:new et({value:[new fe({name:t.repeatedSet||p,value:km.schema(t.typeAndValue||{})})]})})]})}fromSchema(e){V(e,[DN,Va]);let t=R(e,e,s.schema({names:{blockName:DN,repeatedSet:Va}}));T.assertSchema(t,this.className),Va in t.result&&(this.typesAndValues=Array.from(t.result.typesAndValues,n=>new km({schema:n}))),this.valueBeforeDecode=t.result.RDN.valueBeforeDecodeView.slice().buffer;}toSchema(){if(this.valueBeforeDecode.byteLength===0)return new b({value:[new et({value:Array.from(this.typesAndValues,t=>t.toSchema())})]});let e=ht(this.valueBeforeDecode);if(T.assert(e,"RelativeDistinguishedNames"),!(e.result instanceof b))throw new Error("ASN.1 result should be SEQUENCE");return e.result}toJSON(){return {typesAndValues:Array.from(this.typesAndValues,e=>e.toJSON())}}isEqual(e){if(e instanceof s){if(this.typesAndValues.length!==e.typesAndValues.length)return !1;for(let[t,n]of this.typesAndValues.entries())if(n.isEqual(e.typesAndValues[t])===!1)return !1;return !0}return e instanceof ArrayBuffer?qr(this.valueBeforeDecode,e):!1}};Je.CLASS_NAME="RelativeDistinguishedNames";var Of="type",Rf="value";function _7(s={},e=!1){let t=d(s,"names",{});return new b({optional:e,value:[new A({optional:!0,idBlock:{tagClass:2,tagNumber:1},name:t.country_name||p,value:[new We({value:[new Gn,new fs]})]}),new A({optional:!0,idBlock:{tagClass:2,tagNumber:2},name:t.administration_domain_name||p,value:[new We({value:[new Gn,new fs]})]}),new ie({optional:!0,idBlock:{tagClass:3,tagNumber:0},name:t.network_address||p,isHexOnly:!0}),new ie({optional:!0,idBlock:{tagClass:3,tagNumber:1},name:t.terminal_identifier||p,isHexOnly:!0}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:2},name:t.private_domain_name||p,value:[new We({value:[new Gn,new fs]})]}),new ie({optional:!0,idBlock:{tagClass:3,tagNumber:3},name:t.organization_name||p,isHexOnly:!0}),new ie({optional:!0,name:t.numeric_user_identifier||p,idBlock:{tagClass:3,tagNumber:4},isHexOnly:!0}),new A({optional:!0,name:t.personal_name||p,idBlock:{tagClass:3,tagNumber:5},value:[new ie({idBlock:{tagClass:3,tagNumber:0},isHexOnly:!0}),new ie({optional:!0,idBlock:{tagClass:3,tagNumber:1},isHexOnly:!0}),new ie({optional:!0,idBlock:{tagClass:3,tagNumber:2},isHexOnly:!0}),new ie({optional:!0,idBlock:{tagClass:3,tagNumber:3},isHexOnly:!0})]}),new A({optional:!0,name:t.organizational_unit_names||p,idBlock:{tagClass:3,tagNumber:6},value:[new fe({value:new fs})]})]})}function M7(s=!1){return new b({optional:s,value:[new fs,new fs]})}function $7(s=!1){return new et({optional:s,value:[new ie({optional:!0,idBlock:{tagClass:3,tagNumber:0},isHexOnly:!0}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new ue]})]})}var qe=class s extends O{constructor(e={}){super(),this.type=d(e,Of,s.defaultValues(Of)),this.value=d(e,Rf,s.defaultValues(Rf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Of:return 9;case Rf:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Of:return t===s.defaultValues(e);case Rf:return Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new We({value:[new A({idBlock:{tagClass:3,tagNumber:0},name:t.blockName||p,value:[new G,new A({idBlock:{tagClass:3,tagNumber:0},value:[new ue]})]}),new ie({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:1}}),new ie({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:2}}),new A({idBlock:{tagClass:3,tagNumber:3},name:t.blockName||p,value:[_7(t.builtInStandardAttributes||{},!1),M7(!0),$7(!0)]}),new A({idBlock:{tagClass:3,tagNumber:4},name:t.blockName||p,value:[Je.schema(t.directoryName||{})]}),new A({idBlock:{tagClass:3,tagNumber:5},name:t.blockName||p,value:[new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new We({value:[new Gr,new fs,new Kr,new hs,new Fr]})]}),new A({idBlock:{tagClass:3,tagNumber:1},value:[new We({value:[new Gr,new fs,new Kr,new hs,new Fr]})]})]}),new ie({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:6}}),new ie({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:7}}),new ie({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:8}})]})}fromSchema(e){V(e,["blockName","otherName","rfc822Name","dNSName","x400Address","directoryName","ediPartyName","uniformResourceIdentifier","iPAddress","registeredID"]);let t=R(e,e,s.schema({names:{blockName:"blockName",otherName:"otherName",rfc822Name:"rfc822Name",dNSName:"dNSName",x400Address:"x400Address",directoryName:{names:{blockName:"directoryName"}},ediPartyName:"ediPartyName",uniformResourceIdentifier:"uniformResourceIdentifier",iPAddress:"iPAddress",registeredID:"registeredID"}}));switch(T.assertSchema(t,this.className),this.type=t.result.blockName.idBlock.tagNumber,this.type){case 0:this.value=t.result.blockName;break;case 1:case 2:case 6:{let n=t.result.blockName;n.idBlock.tagClass=1,n.idBlock.tagNumber=22;let r=n.toBER(!1),i=ht(r);T.assert(i,"GeneralName value"),this.value=i.result.valueBlock.value;}break;case 3:this.value=t.result.blockName;break;case 4:this.value=new Je({schema:t.result.directoryName});break;case 5:this.value=t.result.ediPartyName;break;case 7:this.value=new L({valueHex:t.result.blockName.valueBlock.valueHex});break;case 8:{let n=t.result.blockName;n.idBlock.tagClass=1,n.idBlock.tagNumber=6;let r=n.toBER(!1),i=ht(r);T.assert(i,"GeneralName registeredID"),this.value=i.result.valueBlock.toString();}break}}toSchema(){switch(this.type){case 0:case 3:case 5:return new A({idBlock:{tagClass:3,tagNumber:this.type},value:[this.value]});case 1:case 2:case 6:{let e=new Ta({value:this.value});return e.idBlock.tagClass=3,e.idBlock.tagNumber=this.type,e}case 4:return new A({idBlock:{tagClass:3,tagNumber:4},value:[this.value.toSchema()]});case 7:{let e=this.value;return e.idBlock.tagClass=3,e.idBlock.tagNumber=this.type,e}case 8:{let e=new G({value:this.value});return e.idBlock.tagClass=3,e.idBlock.tagNumber=this.type,e}default:return s.schema()}}toJSON(){let e={type:this.type,value:p};if(typeof this.value=="string")e.value=this.value;else try{e.value=this.value.toJSON();}catch{}return e}};qe.CLASS_NAME="GeneralName";var Vf="accessMethod",Df="accessLocation",q7=[Vf,Df],Pm=class s extends O{constructor(e={}){super(),this.accessMethod=d(e,Vf,s.defaultValues(Vf)),this.accessLocation=d(e,Df,s.defaultValues(Df)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Vf:return p;case Df:return new qe;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.accessMethod||p}),qe.schema(t.accessLocation||{})]})}fromSchema(e){V(e,q7);let t=R(e,e,s.schema({names:{accessMethod:Vf,accessLocation:{names:{blockName:Df}}}}));T.assertSchema(t,this.className),this.accessMethod=t.result.accessMethod.valueBlock.toString(),this.accessLocation=new qe({schema:t.result.accessLocation});}toSchema(){return new b({value:[new G({value:this.accessMethod}),this.accessLocation.toSchema()]})}toJSON(){return {accessMethod:this.accessMethod,accessLocation:this.accessLocation.toJSON()}}};Pm.CLASS_NAME="AccessDescription";var ei="seconds",ti="millis",si="micros",lr=class s extends O{constructor(e={}){super(),ei in e&&(this.seconds=d(e,ei,s.defaultValues(ei))),ti in e&&(this.millis=d(e,ti,s.defaultValues(ti))),si in e&&(this.micros=d(e,si,s.defaultValues(si))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ei:case ti:case si:return 0;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ei:case ti:case si:return t===s.defaultValues(e);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,optional:!0,value:[new k({optional:!0,name:t.seconds||p}),new ie({name:t.millis||p,optional:!0,idBlock:{tagClass:3,tagNumber:0}}),new ie({name:t.micros||p,optional:!0,idBlock:{tagClass:3,tagNumber:1}})]})}fromSchema(e){V(e,[ei,ti,si]);let t=R(e,e,s.schema({names:{seconds:ei,millis:ti,micros:si}}));if(T.assertSchema(t,this.className),"seconds"in t.result&&(this.seconds=t.result.seconds.valueBlock.valueDec),"millis"in t.result){let n=new k({valueHex:t.result.millis.valueBlock.valueHex});this.millis=n.valueBlock.valueDec;}if("micros"in t.result){let n=new k({valueHex:t.result.micros.valueBlock.valueHex});this.micros=n.valueBlock.valueDec;}}toSchema(){let e=[];if(this.seconds!==void 0&&e.push(new k({value:this.seconds})),this.millis!==void 0){let t=new k({value:this.millis});e.push(new ie({idBlock:{tagClass:3,tagNumber:0},valueHex:t.valueBlock.valueHexView}));}if(this.micros!==void 0){let t=new k({value:this.micros});e.push(new ie({idBlock:{tagClass:3,tagNumber:1},valueHex:t.valueBlock.valueHexView}));}return new b({value:e})}toJSON(){let e={};return this.seconds!==void 0&&(e.seconds=this.seconds),this.millis!==void 0&&(e.millis=this.millis),this.micros!==void 0&&(e.micros=this.micros),e}};lr.CLASS_NAME="Accuracy";var X1="algorithmId",Sf="algorithmParams",ak="algorithm",j2="params",F7=[ak,j2],P=class s extends O{constructor(e={}){super(),this.algorithmId=d(e,X1,s.defaultValues(X1)),Sf in e&&(this.algorithmParams=d(e,Sf,s.defaultValues(Sf))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case X1:return p;case Sf:return new ue;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case X1:return t===p;case Sf:return t instanceof ue;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,optional:t.optional||!1,value:[new G({name:t.algorithmIdentifier||p}),new ue({name:t.algorithmParams||p,optional:!0})]})}fromSchema(e){V(e,F7);let t=R(e,e,s.schema({names:{algorithmIdentifier:ak,algorithmParams:j2}}));T.assertSchema(t,this.className),this.algorithmId=t.result.algorithm.valueBlock.toString(),j2 in t.result&&(this.algorithmParams=t.result.params);}toSchema(){let e=[];return e.push(new G({value:this.algorithmId})),this.algorithmParams&&!(this.algorithmParams instanceof ue)&&e.push(this.algorithmParams),new b({value:e})}toJSON(){let e={algorithmId:this.algorithmId};return this.algorithmParams&&!(this.algorithmParams instanceof ue)&&(e.algorithmParams=this.algorithmParams.toJSON()),e}isEqual(e){return !(e instanceof s)||this.algorithmId!==e.algorithmId?!1:this.algorithmParams?e.algorithmParams?JSON.stringify(this.algorithmParams)===JSON.stringify(e.algorithmParams):!1:!e.algorithmParams}};P.CLASS_NAME="AlgorithmIdentifier";var eu="altNames",K7=[eu],Tm=class s extends O{constructor(e={}){super(),this.altNames=d(e,eu,s.defaultValues(eu)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case eu:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.altNames||p,value:qe.schema()})]})}fromSchema(e){V(e,K7);let t=R(e,e,s.schema({names:{altNames:eu}}));T.assertSchema(t,this.className),eu in t.result&&(this.altNames=Array.from(t.result.altNames,n=>new qe({schema:n})));}toSchema(){return new b({value:Array.from(this.altNames,e=>e.toSchema())})}toJSON(){return {altNames:Array.from(this.altNames,e=>e.toJSON())}}};Tm.CLASS_NAME="AltName";var tu="type",su="values",G7=[tu,su],nt=class s extends O{constructor(e={}){super(),this.type=d(e,tu,s.defaultValues(tu)),this.values=d(e,su,s.defaultValues(su)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case tu:return p;case su:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case tu:return t===p;case su:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.type||p}),new et({name:t.setName||p,value:[new fe({name:t.values||p,value:new ue})]})]})}fromSchema(e){V(e,G7);let t=R(e,e,s.schema({names:{type:tu,values:su}}));T.assertSchema(t,this.className),this.type=t.result.type.valueBlock.toString(),this.values=t.result.values;}toSchema(){return new b({value:[new G({value:this.type}),new et({value:this.values})]})}toJSON(){return {type:this.type,values:Array.from(this.values,e=>e.toJSON())}}};nt.CLASS_NAME="Attribute";var Lf="notBeforeTime",jf="notAfterTime",W7=[Lf,jf],pr=class s extends O{constructor(e={}){super(),this.notBeforeTime=d(e,Lf,s.defaultValues(Lf)),this.notAfterTime=d(e,jf,s.defaultValues(jf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Lf:case jf:return new Date(0,0,0);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new Ge({name:t.notBeforeTime||p}),new Ge({name:t.notAfterTime||p})]})}fromSchema(e){V(e,W7);let t=R(e,e,s.schema({names:{notBeforeTime:Lf,notAfterTime:jf}}));T.assertSchema(t,this.className),this.notBeforeTime=t.result.notBeforeTime.toDate(),this.notAfterTime=t.result.notAfterTime.toDate();}toSchema(){return new b({value:[new Ge({valueDate:this.notBeforeTime}),new Ge({valueDate:this.notAfterTime})]})}toJSON(){return {notBeforeTime:this.notBeforeTime,notAfterTime:this.notAfterTime}}};pr.CLASS_NAME="AttCertValidityPeriod";var vf="names",LN="generalNames",bt=class s extends O{constructor(e={}){super(),this.names=d(e,vf,s.defaultValues(vf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case"names":return [];default:return super.defaultValues(e)}}static schema(e={},t=!1){let n=d(e,vf,{});return new b({optional:t,name:n.blockName||p,value:[new fe({name:n.generalNames||p,value:qe.schema()})]})}fromSchema(e){V(e,[vf,LN]);let t=R(e,e,s.schema({names:{blockName:vf,generalNames:LN}}));T.assertSchema(t,this.className),this.names=Array.from(t.result.generalNames,n=>new qe({schema:n}));}toSchema(){return new b({value:Array.from(this.names,e=>e.toSchema())})}toJSON(){return {names:Array.from(this.names,e=>e.toJSON())}}};bt.CLASS_NAME="GeneralNames";var J7="2.5.29.9",z7="2.5.29.14",Y7="2.5.29.15",Z7="2.5.29.16",ok="2.5.29.17",ck="2.5.29.18",gA="2.5.29.19",Q7="2.5.29.20",X7="2.5.29.27",e9="2.5.29.21",t9="2.5.29.24",uk="2.5.29.28",lk="2.5.29.29",hk="2.5.29.30",fk="2.5.29.31",yA="2.5.29.46",dk="2.5.29.32",Ps="2.5.29.32.0",s9="1.3.6.1.4.1.311.21.10",mk="2.5.29.33",wA="2.5.29.35",pk="2.5.29.36",n9="2.5.29.37",r9="2.5.29.54",bA="1.3.6.1.5.5.7.1.1",i9="1.3.6.1.5.5.7.1.11",a9="1.3.6.1.4.1.11129.2.4.2";var o9="1.3.6.1.4.1.311.21.7",c9="1.3.6.1.4.1.311.21.1",u9="1.3.6.1.5.5.7.1.3",SA="1.2.840.113549.1.7.1",gk="1.2.840.113549.1.7.2",yk="1.2.840.113549.1.7.3",wk="1.2.840.113549.1.7.6",l9="1.2.840.113549.1.9.16.1.4",jN="1.2.840.113549.1.9.22.1",h9="1.2.840.113549.1.9.22.2",UN="1.2.840.113549.1.9.22.3",HN="1.2.840.113549.1.9.23.1",f9="1.3.6.1.5.5.7",vA=`${f9}.48`,Ay=`${vA}.1.1`;var Ua="keyIdentifier",Ha="authorityCertIssuer",_a="authorityCertSerialNumber",d9=[Ua,Ha,_a],Bm=class s extends O{constructor(e={}){super(),Ua in e&&(this.keyIdentifier=d(e,Ua,s.defaultValues(Ua))),Ha in e&&(this.authorityCertIssuer=d(e,Ha,s.defaultValues(Ha))),_a in e&&(this.authorityCertSerialNumber=d(e,_a,s.defaultValues(_a))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ua:return new L;case Ha:return [];case _a:return new k;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new ie({name:t.keyIdentifier||p,optional:!0,idBlock:{tagClass:3,tagNumber:0}}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new fe({name:t.authorityCertIssuer||p,value:qe.schema()})]}),new ie({name:t.authorityCertSerialNumber||p,optional:!0,idBlock:{tagClass:3,tagNumber:2}})]})}fromSchema(e){V(e,d9);let t=R(e,e,s.schema({names:{keyIdentifier:Ua,authorityCertIssuer:Ha,authorityCertSerialNumber:_a}}));T.assertSchema(t,this.className),Ua in t.result&&(this.keyIdentifier=new L({valueHex:t.result.keyIdentifier.valueBlock.valueHex})),Ha in t.result&&(this.authorityCertIssuer=Array.from(t.result.authorityCertIssuer,n=>new qe({schema:n}))),_a in t.result&&(this.authorityCertSerialNumber=new k({valueHex:t.result.authorityCertSerialNumber.valueBlock.valueHex}));}toSchema(){let e=[];return this.keyIdentifier&&e.push(new ie({idBlock:{tagClass:3,tagNumber:0},valueHex:this.keyIdentifier.valueBlock.valueHexView})),this.authorityCertIssuer&&e.push(new A({idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.authorityCertIssuer,t=>t.toSchema())})),this.authorityCertSerialNumber&&e.push(new ie({idBlock:{tagClass:3,tagNumber:2},valueHex:this.authorityCertSerialNumber.valueBlock.valueHexView})),new b({value:e})}toJSON(){let e={};return this.keyIdentifier&&(e.keyIdentifier=this.keyIdentifier.toJSON()),this.authorityCertIssuer&&(e.authorityCertIssuer=Array.from(this.authorityCertIssuer,t=>t.toJSON())),this.authorityCertSerialNumber&&(e.authorityCertSerialNumber=this.authorityCertSerialNumber.toJSON()),e}};Bm.CLASS_NAME="AuthorityKeyIdentifier";var Da="pathLenConstraint",La="cA",Om=class s extends O{constructor(e={}){super(),this.cA=d(e,La,!1),Da in e&&(this.pathLenConstraint=d(e,Da,0)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case La:return !1;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new xs({optional:!0,name:t.cA||p}),new k({optional:!0,name:t.pathLenConstraint||p})]})}fromSchema(e){V(e,[La,Da]);let t=R(e,e,s.schema({names:{cA:La,pathLenConstraint:Da}}));T.assertSchema(t,this.className),La in t.result&&(this.cA=t.result.cA.valueBlock.value),Da in t.result&&(t.result.pathLenConstraint.valueBlock.isHexOnly?this.pathLenConstraint=t.result.pathLenConstraint:this.pathLenConstraint=t.result.pathLenConstraint.valueBlock.valueDec);}toSchema(){let e=[];return this.cA!==s.defaultValues(La)&&e.push(new xs({value:this.cA})),Da in this&&(this.pathLenConstraint instanceof k?e.push(this.pathLenConstraint):e.push(new k({value:this.pathLenConstraint}))),new b({value:e})}toJSON(){let e={};return this.cA!==s.defaultValues(La)&&(e.cA=this.cA),Da in this&&(this.pathLenConstraint instanceof k?e.pathLenConstraint=this.pathLenConstraint.toJSON():e.pathLenConstraint=this.pathLenConstraint),e}};Om.CLASS_NAME="BasicConstraints";var u2="certificateIndex",l2="keyIndex",tw=class s extends O{constructor(e={}){super(),this.certificateIndex=d(e,u2,s.defaultValues(u2)),this.keyIndex=d(e,l2,s.defaultValues(l2)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case u2:case l2:return 0;default:return super.defaultValues(e)}}static schema(){return new k}fromSchema(e){if(e.constructor.blockName()!==k.blockName())throw new Error("Object's schema was not verified against input data for CAVersion");let t=e.valueBlock.valueHex.slice(0),n=new Uint8Array(t);switch(!0){case t.byteLength<4:{let h=new ArrayBuffer(4);new Uint8Array(h).set(n,4-t.byteLength),t=h.slice(0);}break;case t.byteLength>4:{let h=new ArrayBuffer(4);new Uint8Array(h).set(n.slice(0,4)),t=h.slice(0);}break}let r=t.slice(0,2),i=new Uint8Array(r),a=i[0];i[0]=i[1],i[1]=a;let o=new Uint16Array(r);this.keyIndex=o[0];let c=t.slice(2),u=new Uint8Array(c);a=u[0],u[0]=u[1],u[1]=a;let l=new Uint16Array(c);this.certificateIndex=l[0];}toSchema(){let e=new ArrayBuffer(2),t=new Uint16Array(e);t[0]=this.certificateIndex;let n=new Uint8Array(e),r=n[0];n[0]=n[1],n[1]=r;let i=new ArrayBuffer(2),a=new Uint16Array(i);a[0]=this.keyIndex;let o=new Uint8Array(i);return r=o[0],o[0]=o[1],o[1]=r,new k({valueHex:ka(i,e)})}toJSON(){return {certificateIndex:this.certificateIndex,keyIndex:this.keyIndex}}};tw.CLASS_NAME="CAVersion";var Uf="policyQualifierId",Hf="qualifier",m9=[Uf,Hf],Rm=class s extends O{constructor(e={}){super(),this.policyQualifierId=d(e,Uf,s.defaultValues(Uf)),this.qualifier=d(e,Hf,s.defaultValues(Hf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Uf:return p;case Hf:return new ue;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.policyQualifierId||p}),new ue({name:t.qualifier||p})]})}fromSchema(e){V(e,m9);let t=R(e,e,s.schema({names:{policyQualifierId:Uf,qualifier:Hf}}));T.assertSchema(t,this.className),this.policyQualifierId=t.result.policyQualifierId.valueBlock.toString(),this.qualifier=t.result.qualifier;}toSchema(){return new b({value:[new G({value:this.policyQualifierId}),this.qualifier]})}toJSON(){return {policyQualifierId:this.policyQualifierId,qualifier:this.qualifier.toJSON()}}};Rm.CLASS_NAME="PolicyQualifierInfo";var _f="policyIdentifier",Ma="policyQualifiers",p9=[_f,Ma],Vm=class s extends O{constructor(e={}){super(),this.policyIdentifier=d(e,_f,s.defaultValues(_f)),Ma in e&&(this.policyQualifiers=d(e,Ma,s.defaultValues(Ma))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case _f:return p;case Ma:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.policyIdentifier||p}),new b({optional:!0,value:[new fe({name:t.policyQualifiers||p,value:Rm.schema()})]})]})}fromSchema(e){V(e,p9);let t=R(e,e,s.schema({names:{policyIdentifier:_f,policyQualifiers:Ma}}));T.assertSchema(t,this.className),this.policyIdentifier=t.result.policyIdentifier.valueBlock.toString(),Ma in t.result&&(this.policyQualifiers=Array.from(t.result.policyQualifiers,n=>new Rm({schema:n})));}toSchema(){let e=[];return e.push(new G({value:this.policyIdentifier})),this.policyQualifiers&&e.push(new b({value:Array.from(this.policyQualifiers,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={policyIdentifier:this.policyIdentifier};return this.policyQualifiers&&(e.policyQualifiers=Array.from(this.policyQualifiers,t=>t.toJSON())),e}};Vm.CLASS_NAME="PolicyInformation";var Mf="certificatePolicies",g9=[Mf],Dm=class s extends O{constructor(e={}){super(),this.certificatePolicies=d(e,Mf,s.defaultValues(Mf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Mf:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.certificatePolicies||p,value:Vm.schema()})]})}fromSchema(e){V(e,g9);let t=R(e,e,s.schema({names:{certificatePolicies:Mf}}));T.assertSchema(t,this.className),this.certificatePolicies=Array.from(t.result.certificatePolicies,n=>new Vm({schema:n}));}toSchema(){return new b({value:Array.from(this.certificatePolicies,e=>e.toSchema())})}toJSON(){return {certificatePolicies:Array.from(this.certificatePolicies,e=>e.toJSON())}}};Dm.CLASS_NAME="CertificatePolicies";var $f="templateID",Qn="templateMajorVersion",Xn="templateMinorVersion",y9=[$f,Qn,Xn],U2=class s extends O{constructor(e={}){super(),this.templateID=d(e,$f,s.defaultValues($f)),Qn in e&&(this.templateMajorVersion=d(e,Qn,s.defaultValues(Qn))),Xn in e&&(this.templateMinorVersion=d(e,Xn,s.defaultValues(Xn))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case $f:return p;case Qn:case Xn:return 0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.templateID||p}),new k({name:t.templateMajorVersion||p,optional:!0}),new k({name:t.templateMinorVersion||p,optional:!0})]})}fromSchema(e){V(e,y9);let t=R(e,e,s.schema({names:{templateID:$f,templateMajorVersion:Qn,templateMinorVersion:Xn}}));T.assertSchema(t,this.className),this.templateID=t.result.templateID.valueBlock.toString(),Qn in t.result&&(this.templateMajorVersion=t.result.templateMajorVersion.valueBlock.valueDec),Xn in t.result&&(this.templateMinorVersion=t.result.templateMinorVersion.valueBlock.valueDec);}toSchema(){let e=[];return e.push(new G({value:this.templateID})),Qn in this&&e.push(new k({value:this.templateMajorVersion})),Xn in this&&e.push(new k({value:this.templateMinorVersion})),new b({value:e})}toJSON(){let e={templateID:this.templateID};return Qn in this&&(e.templateMajorVersion=this.templateMajorVersion),Xn in this&&(e.templateMinorVersion=this.templateMinorVersion),e}},$a="distributionPoint",bk="distributionPointNames",qa="reasons",Fa="cRLIssuer",Sk="cRLIssuerNames",w9=[$a,bk,qa,Fa,Sk],Lm=class s extends O{constructor(e={}){super(),$a in e&&(this.distributionPoint=d(e,$a,s.defaultValues($a))),qa in e&&(this.reasons=d(e,qa,s.defaultValues(qa))),Fa in e&&(this.cRLIssuer=d(e,Fa,s.defaultValues(Fa))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case $a:return [];case qa:return new Ae;case Fa:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new We({value:[new A({name:t.distributionPoint||p,optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new fe({name:t.distributionPointNames||p,value:qe.schema()})]}),new A({name:t.distributionPoint||p,optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Je.schema().valueBlock.value})]})]}),new ie({name:t.reasons||p,optional:!0,idBlock:{tagClass:3,tagNumber:1}}),new A({name:t.cRLIssuer||p,optional:!0,idBlock:{tagClass:3,tagNumber:2},value:[new fe({name:t.cRLIssuerNames||p,value:qe.schema()})]})]})}fromSchema(e){V(e,w9);let t=R(e,e,s.schema({names:{distributionPoint:$a,distributionPointNames:bk,reasons:qa,cRLIssuer:Fa,cRLIssuerNames:Sk}}));T.assertSchema(t,this.className),$a in t.result&&(t.result.distributionPoint.idBlock.tagNumber===0&&(this.distributionPoint=Array.from(t.result.distributionPointNames,n=>new qe({schema:n}))),t.result.distributionPoint.idBlock.tagNumber===1&&(this.distributionPoint=new Je({schema:new b({value:t.result.distributionPoint.valueBlock.value})}))),qa in t.result&&(this.reasons=new Ae({valueHex:t.result.reasons.valueBlock.valueHex})),Fa in t.result&&(this.cRLIssuer=Array.from(t.result.cRLIssuerNames,n=>new qe({schema:n})));}toSchema(){let e=[];if(this.distributionPoint){let t;this.distributionPoint instanceof Array?t=new A({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.distributionPoint,n=>n.toSchema())}):t=new A({idBlock:{tagClass:3,tagNumber:1},value:[this.distributionPoint.toSchema()]}),e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[t]}));}return this.reasons&&e.push(new ie({idBlock:{tagClass:3,tagNumber:1},valueHex:this.reasons.valueBlock.valueHexView})),this.cRLIssuer&&e.push(new A({idBlock:{tagClass:3,tagNumber:2},value:Array.from(this.cRLIssuer,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={};return this.distributionPoint&&(this.distributionPoint instanceof Array?e.distributionPoint=Array.from(this.distributionPoint,t=>t.toJSON()):e.distributionPoint=this.distributionPoint.toJSON()),this.reasons&&(e.reasons=this.reasons.toJSON()),this.cRLIssuer&&(e.cRLIssuer=Array.from(this.cRLIssuer,t=>t.toJSON())),e}};Lm.CLASS_NAME="DistributionPoint";var qf="distributionPoints",b9=[qf],jm=class s extends O{constructor(e={}){super(),this.distributionPoints=d(e,qf,s.defaultValues(qf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case qf:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.distributionPoints||p,value:Lm.schema()})]})}fromSchema(e){V(e,b9);let t=R(e,e,s.schema({names:{distributionPoints:qf}}));T.assertSchema(t,this.className),this.distributionPoints=Array.from(t.result.distributionPoints,n=>new Lm({schema:n}));}toSchema(){return new b({value:Array.from(this.distributionPoints,e=>e.toSchema())})}toJSON(){return {distributionPoints:Array.from(this.distributionPoints,e=>e.toJSON())}}};jm.CLASS_NAME="CRLDistributionPoints";var Ff="keyPurposes",S9=[Ff],sw=class s extends O{constructor(e={}){super(),this.keyPurposes=d(e,Ff,s.defaultValues(Ff)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ff:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.keyPurposes||p,value:new G})]})}fromSchema(e){V(e,S9);let t=R(e,e,s.schema({names:{keyPurposes:Ff}}));T.assertSchema(t,this.className),this.keyPurposes=Array.from(t.result.keyPurposes,n=>n.valueBlock.toString());}toSchema(){return new b({value:Array.from(this.keyPurposes,e=>new G({value:e}))})}toJSON(){return {keyPurposes:Array.from(this.keyPurposes)}}};sw.CLASS_NAME="ExtKeyUsage";var xf="accessDescriptions",Um=class s extends O{constructor(e={}){super(),this.accessDescriptions=d(e,xf,s.defaultValues(xf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case xf:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.accessDescriptions||p,value:Pm.schema()})]})}fromSchema(e){V(e,[xf]);let t=R(e,e,s.schema({names:{accessDescriptions:xf}}));T.assertSchema(t,this.className),this.accessDescriptions=Array.from(t.result.accessDescriptions,n=>new Pm({schema:n}));}toSchema(){return new b({value:Array.from(this.accessDescriptions,e=>e.toSchema())})}toJSON(){return {accessDescriptions:Array.from(this.accessDescriptions,e=>e.toJSON())}}};Um.CLASS_NAME="InfoAccess";var Ka="distributionPoint",vk="distributionPointNames",ni="onlyContainsUserCerts",ri="onlyContainsCACerts",ii="onlySomeReasons",ai="indirectCRL",oi="onlyContainsAttributeCerts",v9=[Ka,vk,ni,ri,ii,ai,oi],nw=class s extends O{constructor(e={}){super(),Ka in e&&(this.distributionPoint=d(e,Ka,s.defaultValues(Ka))),this.onlyContainsUserCerts=d(e,ni,s.defaultValues(ni)),this.onlyContainsCACerts=d(e,ri,s.defaultValues(ri)),ii in e&&(this.onlySomeReasons=d(e,ii,s.defaultValues(ii))),this.indirectCRL=d(e,ai,s.defaultValues(ai)),this.onlyContainsAttributeCerts=d(e,oi,s.defaultValues(oi)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ka:return [];case ni:return !1;case ri:return !1;case ii:return 0;case ai:return !1;case oi:return !1;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new We({value:[new A({name:t.distributionPoint||p,idBlock:{tagClass:3,tagNumber:0},value:[new fe({name:t.distributionPointNames||p,value:qe.schema()})]}),new A({name:t.distributionPoint||p,idBlock:{tagClass:3,tagNumber:1},value:Je.schema().valueBlock.value})]})]}),new ie({name:t.onlyContainsUserCerts||p,optional:!0,idBlock:{tagClass:3,tagNumber:1}}),new ie({name:t.onlyContainsCACerts||p,optional:!0,idBlock:{tagClass:3,tagNumber:2}}),new ie({name:t.onlySomeReasons||p,optional:!0,idBlock:{tagClass:3,tagNumber:3}}),new ie({name:t.indirectCRL||p,optional:!0,idBlock:{tagClass:3,tagNumber:4}}),new ie({name:t.onlyContainsAttributeCerts||p,optional:!0,idBlock:{tagClass:3,tagNumber:5}})]})}fromSchema(e){V(e,v9);let t=R(e,e,s.schema({names:{distributionPoint:Ka,distributionPointNames:vk,onlyContainsUserCerts:ni,onlyContainsCACerts:ri,onlySomeReasons:ii,indirectCRL:ai,onlyContainsAttributeCerts:oi}}));if(T.assertSchema(t,this.className),Ka in t.result)switch(!0){case t.result.distributionPoint.idBlock.tagNumber===0:this.distributionPoint=Array.from(t.result.distributionPointNames,n=>new qe({schema:n}));break;case t.result.distributionPoint.idBlock.tagNumber===1:this.distributionPoint=new Je({schema:new b({value:t.result.distributionPoint.valueBlock.value})});break;default:throw new Error("Unknown tagNumber for distributionPoint: {$asn1.result.distributionPoint.idBlock.tagNumber}")}if(ni in t.result){let n=new Uint8Array(t.result.onlyContainsUserCerts.valueBlock.valueHex);this.onlyContainsUserCerts=n[0]!==0;}if(ri in t.result){let n=new Uint8Array(t.result.onlyContainsCACerts.valueBlock.valueHex);this.onlyContainsCACerts=n[0]!==0;}if(ii in t.result){let n=new Uint8Array(t.result.onlySomeReasons.valueBlock.valueHex);this.onlySomeReasons=n[0];}if(ai in t.result){let n=new Uint8Array(t.result.indirectCRL.valueBlock.valueHex);this.indirectCRL=n[0]!==0;}if(oi in t.result){let n=new Uint8Array(t.result.onlyContainsAttributeCerts.valueBlock.valueHex);this.onlyContainsAttributeCerts=n[0]!==0;}}toSchema(){let e=[];if(this.distributionPoint){let t;this.distributionPoint instanceof Array?t=new A({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.distributionPoint,n=>n.toSchema())}):(t=this.distributionPoint.toSchema(),t.idBlock.tagClass=3,t.idBlock.tagNumber=1),e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[t]}));}if(this.onlyContainsUserCerts!==s.defaultValues(ni)&&e.push(new ie({idBlock:{tagClass:3,tagNumber:1},valueHex:new Uint8Array([255]).buffer})),this.onlyContainsCACerts!==s.defaultValues(ri)&&e.push(new ie({idBlock:{tagClass:3,tagNumber:2},valueHex:new Uint8Array([255]).buffer})),this.onlySomeReasons!==void 0){let t=new ArrayBuffer(1),n=new Uint8Array(t);n[0]=this.onlySomeReasons,e.push(new ie({idBlock:{tagClass:3,tagNumber:3},valueHex:t}));}return this.indirectCRL!==s.defaultValues(ai)&&e.push(new ie({idBlock:{tagClass:3,tagNumber:4},valueHex:new Uint8Array([255]).buffer})),this.onlyContainsAttributeCerts!==s.defaultValues(oi)&&e.push(new ie({idBlock:{tagClass:3,tagNumber:5},valueHex:new Uint8Array([255]).buffer})),new b({value:e})}toJSON(){let e={};return this.distributionPoint&&(this.distributionPoint instanceof Array?e.distributionPoint=Array.from(this.distributionPoint,t=>t.toJSON()):e.distributionPoint=this.distributionPoint.toJSON()),this.onlyContainsUserCerts!==s.defaultValues(ni)&&(e.onlyContainsUserCerts=this.onlyContainsUserCerts),this.onlyContainsCACerts!==s.defaultValues(ri)&&(e.onlyContainsCACerts=this.onlyContainsCACerts),ii in this&&(e.onlySomeReasons=this.onlySomeReasons),this.indirectCRL!==s.defaultValues(ai)&&(e.indirectCRL=this.indirectCRL),this.onlyContainsAttributeCerts!==s.defaultValues(oi)&&(e.onlyContainsAttributeCerts=this.onlyContainsAttributeCerts),e}};nw.CLASS_NAME="IssuingDistributionPoint";var Kf="base",nu="minimum",ci="maximum",x9=[Kf,nu,ci],$o=class s extends O{constructor(e={}){super(),this.base=d(e,Kf,s.defaultValues(Kf)),this.minimum=d(e,nu,s.defaultValues(nu)),ci in e&&(this.maximum=d(e,ci,s.defaultValues(ci))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Kf:return new qe;case nu:return 0;case ci:return 0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[qe.schema(t.base||{}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new k({name:t.minimum||p})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new k({name:t.maximum||p})]})]})}fromSchema(e){V(e,x9);let t=R(e,e,s.schema({names:{base:{names:{blockName:Kf}},minimum:nu,maximum:ci}}));T.assertSchema(t,this.className),this.base=new qe({schema:t.result.base}),nu in t.result&&(t.result.minimum.valueBlock.isHexOnly?this.minimum=t.result.minimum:this.minimum=t.result.minimum.valueBlock.valueDec),ci in t.result&&(t.result.maximum.valueBlock.isHexOnly?this.maximum=t.result.maximum:this.maximum=t.result.maximum.valueBlock.valueDec);}toSchema(){let e=[];if(e.push(this.base.toSchema()),this.minimum!==0){let t=0;this.minimum instanceof k?t=this.minimum:t=new k({value:this.minimum}),e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[t]}));}if(ci in this){let t=0;this.maximum instanceof k?t=this.maximum:t=new k({value:this.maximum}),e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[t]}));}return new b({value:e})}toJSON(){let e={base:this.base.toJSON()};return this.minimum!==0&&(typeof this.minimum=="number"?e.minimum=this.minimum:e.minimum=this.minimum.toJSON()),this.maximum!==void 0&&(typeof this.maximum=="number"?e.maximum=this.maximum:e.maximum=this.maximum.toJSON()),e}};$o.CLASS_NAME="GeneralSubtree";var Ga="permittedSubtrees",Wa="excludedSubtrees",E9=[Ga,Wa],rw=class s extends O{constructor(e={}){super(),Ga in e&&(this.permittedSubtrees=d(e,Ga,s.defaultValues(Ga))),Wa in e&&(this.excludedSubtrees=d(e,Wa,s.defaultValues(Wa))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ga:case Wa:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new fe({name:t.permittedSubtrees||p,value:$o.schema()})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new fe({name:t.excludedSubtrees||p,value:$o.schema()})]})]})}fromSchema(e){V(e,E9);let t=R(e,e,s.schema({names:{permittedSubtrees:Ga,excludedSubtrees:Wa}}));T.assertSchema(t,this.className),Ga in t.result&&(this.permittedSubtrees=Array.from(t.result.permittedSubtrees,n=>new $o({schema:n}))),Wa in t.result&&(this.excludedSubtrees=Array.from(t.result.excludedSubtrees,n=>new $o({schema:n})));}toSchema(){let e=[];return this.permittedSubtrees&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.permittedSubtrees,t=>t.toSchema())})),this.excludedSubtrees&&e.push(new A({idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.excludedSubtrees,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={};return this.permittedSubtrees&&(e.permittedSubtrees=Array.from(this.permittedSubtrees,t=>t.toJSON())),this.excludedSubtrees&&(e.excludedSubtrees=Array.from(this.excludedSubtrees,t=>t.toJSON())),e}};rw.CLASS_NAME="NameConstraints";var er="requireExplicitPolicy",tr="inhibitPolicyMapping",A9=[er,tr],iw=class s extends O{constructor(e={}){super(),er in e&&(this.requireExplicitPolicy=d(e,er,s.defaultValues(er))),tr in e&&(this.inhibitPolicyMapping=d(e,tr,s.defaultValues(tr))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case er:return 0;case tr:return 0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new ie({name:t.requireExplicitPolicy||p,optional:!0,idBlock:{tagClass:3,tagNumber:0}}),new ie({name:t.inhibitPolicyMapping||p,optional:!0,idBlock:{tagClass:3,tagNumber:1}})]})}fromSchema(e){V(e,A9);let t=R(e,e,s.schema({names:{requireExplicitPolicy:er,inhibitPolicyMapping:tr}}));if(T.assertSchema(t,this.className),er in t.result){let n=t.result.requireExplicitPolicy;n.idBlock.tagClass=1,n.idBlock.tagNumber=2;let r=n.toBER(!1),i=ht(r);T.assert(i,"Integer"),this.requireExplicitPolicy=i.result.valueBlock.valueDec;}if(tr in t.result){let n=t.result.inhibitPolicyMapping;n.idBlock.tagClass=1,n.idBlock.tagNumber=2;let r=n.toBER(!1),i=ht(r);T.assert(i,"Integer"),this.inhibitPolicyMapping=i.result.valueBlock.valueDec;}}toSchema(){let e=[];if(er in this){let t=new k({value:this.requireExplicitPolicy});t.idBlock.tagClass=3,t.idBlock.tagNumber=0,e.push(t);}if(tr in this){let t=new k({value:this.inhibitPolicyMapping});t.idBlock.tagClass=3,t.idBlock.tagNumber=1,e.push(t);}return new b({value:e})}toJSON(){let e={};return er in this&&(e.requireExplicitPolicy=this.requireExplicitPolicy),tr in this&&(e.inhibitPolicyMapping=this.inhibitPolicyMapping),e}};iw.CLASS_NAME="PolicyConstraints";var Gf="issuerDomainPolicy",Wf="subjectDomainPolicy",I9=[Gf,Wf],Hm=class s extends O{constructor(e={}){super(),this.issuerDomainPolicy=d(e,Gf,s.defaultValues(Gf)),this.subjectDomainPolicy=d(e,Wf,s.defaultValues(Wf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Gf:return p;case Wf:return p;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.issuerDomainPolicy||p}),new G({name:t.subjectDomainPolicy||p})]})}fromSchema(e){V(e,I9);let t=R(e,e,s.schema({names:{issuerDomainPolicy:Gf,subjectDomainPolicy:Wf}}));T.assertSchema(t,this.className),this.issuerDomainPolicy=t.result.issuerDomainPolicy.valueBlock.toString(),this.subjectDomainPolicy=t.result.subjectDomainPolicy.valueBlock.toString();}toSchema(){return new b({value:[new G({value:this.issuerDomainPolicy}),new G({value:this.subjectDomainPolicy})]})}toJSON(){return {issuerDomainPolicy:this.issuerDomainPolicy,subjectDomainPolicy:this.subjectDomainPolicy}}};Hm.CLASS_NAME="PolicyMapping";var Jf="mappings",C9=[Jf],aw=class s extends O{constructor(e={}){super(),this.mappings=d(e,Jf,s.defaultValues(Jf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Jf:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.mappings||p,value:Hm.schema()})]})}fromSchema(e){V(e,C9);let t=R(e,e,s.schema({names:{mappings:Jf}}));T.assertSchema(t,this.className),this.mappings=Array.from(t.result.mappings,n=>new Hm({schema:n}));}toSchema(){return new b({value:Array.from(this.mappings,e=>e.toSchema())})}toJSON(){return {mappings:Array.from(this.mappings,e=>e.toJSON())}}};aw.CLASS_NAME="PolicyMappings";var ui="notBefore",li="notAfter",N9=[ui,li],ow=class s extends O{constructor(e={}){super(),ui in e&&(this.notBefore=d(e,ui,s.defaultValues(ui))),li in e&&(this.notAfter=d(e,li,s.defaultValues(li))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ui:return new Date;case li:return new Date;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new ie({name:t.notBefore||p,optional:!0,idBlock:{tagClass:3,tagNumber:0}}),new ie({name:t.notAfter||p,optional:!0,idBlock:{tagClass:3,tagNumber:1}})]})}fromSchema(e){V(e,N9);let t=R(e,e,s.schema({names:{notBefore:ui,notAfter:li}}));if(T.assertSchema(t,this.className),ui in t.result){let n=new Ge;n.fromBuffer(t.result.notBefore.valueBlock.valueHex),this.notBefore=n.toDate();}if(li in t.result){let n=new Ge({valueHex:t.result.notAfter.valueBlock.valueHex});n.fromBuffer(t.result.notAfter.valueBlock.valueHex),this.notAfter=n.toDate();}}toSchema(){let e=[];return ui in this&&e.push(new ie({idBlock:{tagClass:3,tagNumber:0},valueHex:new Ge({valueDate:this.notBefore}).valueBlock.valueHexView})),li in this&&e.push(new ie({idBlock:{tagClass:3,tagNumber:1},valueHex:new Ge({valueDate:this.notAfter}).valueBlock.valueHexView})),new b({value:e})}toJSON(){let e={};return this.notBefore&&(e.notBefore=this.notBefore),this.notAfter&&(e.notAfter=this.notAfter),e}};ow.CLASS_NAME="PrivateKeyUsagePeriod";var ru="id",sr="type",iu="values",k9=[ru,sr],P9=[iu],_m=class s extends O{constructor(e={}){super(),this.id=d(e,ru,s.defaultValues(ru)),sr in e&&(this.type=d(e,sr,s.defaultValues(sr))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ru:return p;case sr:return new Xe;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ru:return t===p;case sr:return t instanceof Xe;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.id||p}),new ue({name:t.type||p,optional:!0})]})}fromSchema(e){V(e,k9);let t=R(e,e,s.schema({names:{id:ru,type:sr}}));T.assertSchema(t,this.className),this.id=t.result.id.valueBlock.toString(),sr in t.result&&(this.type=t.result.type);}toSchema(){let e=[new G({value:this.id})];return sr in this&&e.push(this.type),new b({value:e})}toJSON(){let e={id:this.id};return this.type&&(e.type=this.type.toJSON()),e}};_m.CLASS_NAME="QCStatement";var cw=class s extends O{constructor(e={}){super(),this.values=d(e,iu,s.defaultValues(iu)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case iu:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case iu:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.values||p,value:_m.schema(t.value||{})})]})}fromSchema(e){V(e,P9);let t=R(e,e,s.schema({names:{values:iu}}));T.assertSchema(t,this.className),this.values=Array.from(t.result.values,n=>new _m({schema:n}));}toSchema(){return new b({value:Array.from(this.values,e=>e.toSchema())})}toJSON(){return {values:Array.from(this.values,e=>e.toJSON())}}};cw.CLASS_NAME="QCStatements";var Ja,Sn=class{static register(e,t,n){this.namedCurves[e.toLowerCase()]=this.namedCurves[t]={name:e,id:t,size:n};}static find(e){return this.namedCurves[e.toLowerCase()]||null}};Ja=Sn;Sn.namedCurves={};Ja.register("P-256","1.2.840.10045.3.1.7",32),Ja.register("P-384","1.3.132.0.34",48),Ja.register("P-521","1.3.132.0.35",66),Ja.register("brainpoolP256r1","1.3.36.3.3.2.8.1.1.7",32),Ja.register("brainpoolP384r1","1.3.36.3.3.2.8.1.1.11",48),Ja.register("brainpoolP512r1","1.3.36.3.3.2.8.1.1.13",64);var ey="x",ty="y",sy="namedCurve",tn=class s extends O{constructor(e={}){super(),this.x=d(e,ey,s.defaultValues(ey)),this.y=d(e,ty,s.defaultValues(ty)),this.namedCurve=d(e,sy,s.defaultValues(sy)),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ey:case ty:return ut;case sy:return p;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ey:case ty:return t instanceof ArrayBuffer&&qr(t,s.defaultValues(e));case sy:return typeof t=="string"&&t===s.defaultValues(e);default:return super.defaultValues(e)}}static schema(){return new Oa}fromSchema(e){let t=re.toUint8Array(e);if(t[0]!==4)throw new Error("Object's schema was not verified against input data for ECPublicKey");let n=Sn.find(this.namedCurve);if(!n)throw new Error(`Incorrect curve OID: ${this.namedCurve}`);let r=n.size;if(t.byteLength!==r*2+1)throw new Error("Object's schema was not verified against input data for ECPublicKey");this.namedCurve=n.name,this.x=t.slice(1,r+1).buffer,this.y=t.slice(1+r,r*2+1).buffer;}toSchema(){return new Oa({data:ka(new Uint8Array([4]).buffer,this.x,this.y)})}toJSON(){let e=Sn.find(this.namedCurve);return {crv:e?e.name:this.namedCurve,x:S1(uf(this.x),!0,!0,!1),y:S1(uf(this.y),!0,!0,!1)}}fromJSON(e){Re.assert("json",e,"crv","x","y");let t=0,n=Sn.find(e.crv);n&&(this.namedCurve=n.id,t=n.size);let r=Pa($c(e.x,!0));if(r.byteLength<t){this.x=new ArrayBuffer(t);let a=new Uint8Array(this.x),o=new Uint8Array(r);a.set(o,1);}else this.x=r.slice(0,t);let i=Pa($c(e.y,!0));if(i.byteLength<t){this.y=new ArrayBuffer(t);let a=new Uint8Array(this.y),o=new Uint8Array(i);a.set(o,1);}else this.y=i.slice(0,t);}};tn.CLASS_NAME="ECPublicKey";var zf="modulus",Yf="publicExponent",T9=[zf,Yf],Mm=class s extends O{constructor(e={}){super(),this.modulus=d(e,zf,s.defaultValues(zf)),this.publicExponent=d(e,Yf,s.defaultValues(Yf)),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case zf:return new k;case Yf:return new k;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new k({name:t.modulus||p}),new k({name:t.publicExponent||p})]})}fromSchema(e){V(e,T9);let t=R(e,e,s.schema({names:{modulus:zf,publicExponent:Yf}}));T.assertSchema(t,this.className),this.modulus=t.result.modulus.convertFromDER(256),this.publicExponent=t.result.publicExponent;}toSchema(){return new b({value:[this.modulus.convertToDER(),this.publicExponent]})}toJSON(){return {n:he.ToBase64Url(this.modulus.valueBlock.valueHexView),e:he.ToBase64Url(this.publicExponent.valueBlock.valueHexView)}}fromJSON(e){Re.assert("json",e,"n","e");let t=Pa($c(e.n,!0));this.modulus=new k({valueHex:t.slice(0,Math.pow(2,W8(t.byteLength)))}),this.publicExponent=new k({valueHex:Pa($c(e.e,!0)).slice(0,3)});}};Mm.CLASS_NAME="RSAPublicKey";var Zf="algorithm",Qf="subjectPublicKey",B9=[Zf,Qf],As=class s extends O{get parsedKey(){if(this._parsedKey===void 0){switch(this.algorithm.algorithmId){case"1.2.840.10045.2.1":if("algorithmParams"in this.algorithm&&this.algorithm.algorithmParams.constructor.blockName()===G.blockName())try{this._parsedKey=new tn({namedCurve:this.algorithm.algorithmParams.valueBlock.toString(),schema:this.subjectPublicKey.valueBlock.valueHexView});}catch{}break;case"1.2.840.113549.1.1.1":{let e=ht(this.subjectPublicKey.valueBlock.valueHexView);if(e.offset!==-1)try{this._parsedKey=new Mm({schema:e.result});}catch{}}break}this._parsedKey||(this._parsedKey=null);}return this._parsedKey||void 0}set parsedKey(e){this._parsedKey=e;}constructor(e={}){super(),this.algorithm=d(e,Zf,s.defaultValues(Zf)),this.subjectPublicKey=d(e,Qf,s.defaultValues(Qf));let t=d(e,"parsedKey",null);t&&(this.parsedKey=t),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Zf:return new P;case Qf:return new Ae;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.algorithm||{}),new Ae({name:t.subjectPublicKey||p})]})}fromSchema(e){V(e,B9);let t=R(e,e,s.schema({names:{algorithm:{names:{blockName:Zf}},subjectPublicKey:Qf}}));T.assertSchema(t,this.className),this.algorithm=new P({schema:t.result.algorithm}),this.subjectPublicKey=t.result.subjectPublicKey;}toSchema(){return new b({value:[this.algorithm.toSchema(),this.subjectPublicKey]})}toJSON(){if(!this.parsedKey)return {algorithm:this.algorithm.toJSON(),subjectPublicKey:this.subjectPublicKey.toJSON()};let e={};switch(this.algorithm.algorithmId){case"1.2.840.10045.2.1":e.kty="EC";break;case"1.2.840.113549.1.1.1":e.kty="RSA";break}let t=this.parsedKey.toJSON();return Object.assign(e,t),e}fromJSON(e){if("kty"in e){switch(e.kty.toUpperCase()){case"EC":this.parsedKey=new tn({json:e}),this.algorithm=new P({algorithmId:"1.2.840.10045.2.1",algorithmParams:new G({value:this.parsedKey.namedCurve})});break;case"RSA":this.parsedKey=new Mm({json:e}),this.algorithm=new P({algorithmId:"1.2.840.113549.1.1.1",algorithmParams:new Xe});break;default:throw new Error(`Invalid value for "kty" parameter: ${e.kty}`)}this.subjectPublicKey=new Ae({valueHex:this.parsedKey.toSchema().toBER(!1)});}}async importKey(e,t=ve(!0)){try{if(!e)throw new Error("Need to provide publicKey input parameter");let n=await t.exportKey("spki",e),r=ht(n);try{this.fromSchema(r.result);}catch{throw new Error("Error during initializing object from schema")}}catch(n){let r=n instanceof Error?n.message:`${n}`;throw new Error(`Error during exporting public key: ${r}`)}}};As.CLASS_NAME="PublicKeyInfo";var au="version",ou="privateKey",Ys="namedCurve",hi="publicKey",O9=[au,ou,Ys,hi],$m=class s extends O{constructor(e={}){super(),this.version=d(e,au,s.defaultValues(au)),this.privateKey=d(e,ou,s.defaultValues(ou)),Ys in e&&(this.namedCurve=d(e,Ys,s.defaultValues(Ys))),hi in e&&(this.publicKey=d(e,hi,s.defaultValues(hi))),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case au:return 1;case ou:return new L;case Ys:return p;case hi:return new tn;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case au:return t===s.defaultValues(e);case ou:return t.isEqual(s.defaultValues(e));case Ys:return t===p;case hi:return tn.compareWithDefault(Ys,t.namedCurve)&&tn.compareWithDefault("x",t.x)&&tn.compareWithDefault("y",t.y);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new k({name:t.version||p}),new L({name:t.privateKey||p}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new G({name:t.namedCurve||p})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new Ae({name:t.publicKey||p})]})]})}fromSchema(e){V(e,O9);let t=R(e,e,s.schema({names:{version:au,privateKey:ou,namedCurve:Ys,publicKey:hi}}));if(T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.privateKey=t.result.privateKey,Ys in t.result&&(this.namedCurve=t.result.namedCurve.valueBlock.toString()),hi in t.result){let n={schema:t.result.publicKey.valueBlock.valueHex};Ys in this&&(n.namedCurve=this.namedCurve),this.publicKey=new tn(n);}}toSchema(){let e=[new k({value:this.version}),this.privateKey];return this.namedCurve&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[new G({value:this.namedCurve})]})),this.publicKey&&e.push(new A({idBlock:{tagClass:3,tagNumber:1},value:[new Ae({valueHex:this.publicKey.toSchema().toBER(!1)})]})),new b({value:e})}toJSON(){if(!this.namedCurve||s.compareWithDefault(Ys,this.namedCurve))throw new Error('Not enough information for making JSON: absent "namedCurve" value');let e=Sn.find(this.namedCurve),t={crv:e?e.name:this.namedCurve,d:he.ToBase64Url(this.privateKey.valueBlock.valueHexView)};if(this.publicKey){let n=this.publicKey.toJSON();t.x=n.x,t.y=n.y;}return t}fromJSON(e){Re.assert("json",e,"crv","d");let t=0,n=Sn.find(e.crv);n&&(this.namedCurve=n.id,t=n.size);let r=he.FromBase64Url(e.d);if(r.byteLength<t){let i=new ArrayBuffer(t),a=new Uint8Array(i),o=new Uint8Array(r);a.set(o,1),this.privateKey=new L({valueHex:i});}else this.privateKey=new L({valueHex:r.slice(0,t)});e.x&&e.y&&(this.publicKey=new tn({json:e}));}};$m.CLASS_NAME="ECPrivateKey";var Xf="prime",ed="exponent",td="coefficient",R9=[Xf,ed,td],Sl=class s extends O{constructor(e={}){super(),this.prime=d(e,Xf,s.defaultValues(Xf)),this.exponent=d(e,ed,s.defaultValues(ed)),this.coefficient=d(e,td,s.defaultValues(td)),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Xf:return new k;case ed:return new k;case td:return new k;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new k({name:t.prime||p}),new k({name:t.exponent||p}),new k({name:t.coefficient||p})]})}fromSchema(e){V(e,R9);let t=R(e,e,s.schema({names:{prime:Xf,exponent:ed,coefficient:td}}));T.assertSchema(t,this.className),this.prime=t.result.prime.convertFromDER(),this.exponent=t.result.exponent.convertFromDER(),this.coefficient=t.result.coefficient.convertFromDER();}toSchema(){return new b({value:[this.prime.convertToDER(),this.exponent.convertToDER(),this.coefficient.convertToDER()]})}toJSON(){return {r:he.ToBase64Url(this.prime.valueBlock.valueHexView),d:he.ToBase64Url(this.exponent.valueBlock.valueHexView),t:he.ToBase64Url(this.coefficient.valueBlock.valueHexView)}}fromJSON(e){Re.assert("json",e,"r","d","r"),this.prime=new k({valueHex:he.FromBase64Url(e.r)}),this.exponent=new k({valueHex:he.FromBase64Url(e.d)}),this.coefficient=new k({valueHex:he.FromBase64Url(e.t)});}};Sl.CLASS_NAME="OtherPrimeInfo";var sd="version",nd="modulus",rd="publicExponent",id="privateExponent",ad="prime1",od="prime2",cd="exponent1",ud="exponent2",ld="coefficient",za="otherPrimeInfos",V9=[sd,nd,rd,id,ad,od,cd,ud,ld,za],qm=class s extends O{constructor(e={}){super(),this.version=d(e,sd,s.defaultValues(sd)),this.modulus=d(e,nd,s.defaultValues(nd)),this.publicExponent=d(e,rd,s.defaultValues(rd)),this.privateExponent=d(e,id,s.defaultValues(id)),this.prime1=d(e,ad,s.defaultValues(ad)),this.prime2=d(e,od,s.defaultValues(od)),this.exponent1=d(e,cd,s.defaultValues(cd)),this.exponent2=d(e,ud,s.defaultValues(ud)),this.coefficient=d(e,ld,s.defaultValues(ld)),za in e&&(this.otherPrimeInfos=d(e,za,s.defaultValues(za))),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case sd:return 0;case nd:return new k;case rd:return new k;case id:return new k;case ad:return new k;case od:return new k;case cd:return new k;case ud:return new k;case ld:return new k;case za:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new k({name:t.version||p}),new k({name:t.modulus||p}),new k({name:t.publicExponent||p}),new k({name:t.privateExponent||p}),new k({name:t.prime1||p}),new k({name:t.prime2||p}),new k({name:t.exponent1||p}),new k({name:t.exponent2||p}),new k({name:t.coefficient||p}),new b({optional:!0,value:[new fe({name:t.otherPrimeInfosName||p,value:Sl.schema(t.otherPrimeInfo||{})})]})]})}fromSchema(e){V(e,V9);let t=R(e,e,s.schema({names:{version:sd,modulus:nd,publicExponent:rd,privateExponent:id,prime1:ad,prime2:od,exponent1:cd,exponent2:ud,coefficient:ld,otherPrimeInfo:{names:{blockName:za}}}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.modulus=t.result.modulus.convertFromDER(256),this.publicExponent=t.result.publicExponent,this.privateExponent=t.result.privateExponent.convertFromDER(256),this.prime1=t.result.prime1.convertFromDER(128),this.prime2=t.result.prime2.convertFromDER(128),this.exponent1=t.result.exponent1.convertFromDER(128),this.exponent2=t.result.exponent2.convertFromDER(128),this.coefficient=t.result.coefficient.convertFromDER(128),za in t.result&&(this.otherPrimeInfos=Array.from(t.result.otherPrimeInfos,n=>new Sl({schema:n})));}toSchema(){let e=[];return e.push(new k({value:this.version})),e.push(this.modulus.convertToDER()),e.push(this.publicExponent),e.push(this.privateExponent.convertToDER()),e.push(this.prime1.convertToDER()),e.push(this.prime2.convertToDER()),e.push(this.exponent1.convertToDER()),e.push(this.exponent2.convertToDER()),e.push(this.coefficient.convertToDER()),this.otherPrimeInfos&&e.push(new b({value:Array.from(this.otherPrimeInfos,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={n:he.ToBase64Url(this.modulus.valueBlock.valueHexView),e:he.ToBase64Url(this.publicExponent.valueBlock.valueHexView),d:he.ToBase64Url(this.privateExponent.valueBlock.valueHexView),p:he.ToBase64Url(this.prime1.valueBlock.valueHexView),q:he.ToBase64Url(this.prime2.valueBlock.valueHexView),dp:he.ToBase64Url(this.exponent1.valueBlock.valueHexView),dq:he.ToBase64Url(this.exponent2.valueBlock.valueHexView),qi:he.ToBase64Url(this.coefficient.valueBlock.valueHexView)};return this.otherPrimeInfos&&(e.oth=Array.from(this.otherPrimeInfos,t=>t.toJSON())),e}fromJSON(e){Re.assert("json",e,"n","e","d","p","q","dp","dq","qi"),this.modulus=new k({valueHex:he.FromBase64Url(e.n)}),this.publicExponent=new k({valueHex:he.FromBase64Url(e.e)}),this.privateExponent=new k({valueHex:he.FromBase64Url(e.d)}),this.prime1=new k({valueHex:he.FromBase64Url(e.p)}),this.prime2=new k({valueHex:he.FromBase64Url(e.q)}),this.exponent1=new k({valueHex:he.FromBase64Url(e.dp)}),this.exponent2=new k({valueHex:he.FromBase64Url(e.dq)}),this.coefficient=new k({valueHex:he.FromBase64Url(e.qi)}),e.oth&&(this.otherPrimeInfos=Array.from(e.oth,t=>new Sl({json:t})));}};qm.CLASS_NAME="RSAPrivateKey";var hd="version",fd="privateKeyAlgorithm",dd="privateKey",Ya="attributes",ny="parsedKey",D9=[hd,fd,dd,Ya],Yo=class s extends O{constructor(e={}){super(),this.version=d(e,hd,s.defaultValues(hd)),this.privateKeyAlgorithm=d(e,fd,s.defaultValues(fd)),this.privateKey=d(e,dd,s.defaultValues(dd)),Ya in e&&(this.attributes=d(e,Ya,s.defaultValues(Ya))),ny in e&&(this.parsedKey=d(e,ny,s.defaultValues(ny))),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case hd:return 0;case fd:return new P;case dd:return new L;case Ya:return [];case ny:return {};default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new k({name:t.version||p}),P.schema(t.privateKeyAlgorithm||{}),new L({name:t.privateKey||p}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new fe({name:t.attributes||p,value:nt.schema()})]})]})}fromSchema(e){V(e,D9);let t=R(e,e,s.schema({names:{version:hd,privateKeyAlgorithm:{names:{blockName:fd}},privateKey:dd,attributes:Ya}}));switch(T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.privateKeyAlgorithm=new P({schema:t.result.privateKeyAlgorithm}),this.privateKey=t.result.privateKey,Ya in t.result&&(this.attributes=Array.from(t.result.attributes,n=>new nt({schema:n}))),this.privateKeyAlgorithm.algorithmId){case"1.2.840.113549.1.1.1":{let n=ht(this.privateKey.valueBlock.valueHexView);n.offset!==-1&&(this.parsedKey=new qm({schema:n.result}));}break;case"1.2.840.10045.2.1":if("algorithmParams"in this.privateKeyAlgorithm&&this.privateKeyAlgorithm.algorithmParams instanceof G){let n=ht(this.privateKey.valueBlock.valueHexView);n.offset!==-1&&(this.parsedKey=new $m({namedCurve:this.privateKeyAlgorithm.algorithmParams.valueBlock.toString(),schema:n.result}));}break}}toSchema(){let e=[new k({value:this.version}),this.privateKeyAlgorithm.toSchema(),this.privateKey];return this.attributes&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.attributes,t=>t.toSchema())})),new b({value:e})}toJSON(){if(!this.parsedKey){let n={version:this.version,privateKeyAlgorithm:this.privateKeyAlgorithm.toJSON(),privateKey:this.privateKey.toJSON()};return this.attributes&&(n.attributes=Array.from(this.attributes,r=>r.toJSON())),n}let e={};switch(this.privateKeyAlgorithm.algorithmId){case"1.2.840.10045.2.1":e.kty="EC";break;case"1.2.840.113549.1.1.1":e.kty="RSA";break}let t=this.parsedKey.toJSON();return Object.assign(e,t),e}fromJSON(e){if("kty"in e){switch(e.kty.toUpperCase()){case"EC":this.parsedKey=new $m({json:e}),this.privateKeyAlgorithm=new P({algorithmId:"1.2.840.10045.2.1",algorithmParams:new G({value:this.parsedKey.namedCurve})});break;case"RSA":this.parsedKey=new qm({json:e}),this.privateKeyAlgorithm=new P({algorithmId:"1.2.840.113549.1.1.1",algorithmParams:new Xe});break;default:throw new Error(`Invalid value for "kty" parameter: ${e.kty}`)}this.privateKey=new L({valueHex:this.parsedKey.toSchema().toBER(!1)});}}};Yo.CLASS_NAME="PrivateKeyInfo";var cu="contentType",uu="contentEncryptionAlgorithm",Za="encryptedContent",L9=[cu,uu,Za],_N=1024,kt=class s extends O{constructor(e={}){if(super(),this.contentType=d(e,cu,s.defaultValues(cu)),this.contentEncryptionAlgorithm=d(e,uu,s.defaultValues(uu)),Za in e&&e.encryptedContent&&(this.encryptedContent=e.encryptedContent,this.encryptedContent.idBlock.tagClass===1&&this.encryptedContent.idBlock.tagNumber===4&&this.encryptedContent.idBlock.isConstructed===!1&&!e.disableSplit)){let t=new L({idBlock:{isConstructed:!0},isConstructed:!0}),n=0,r=this.encryptedContent.valueBlock.valueHexView.slice().buffer,i=r.byteLength;for(;i>0;){let a=new Uint8Array(r,n,n+_N>r.byteLength?r.byteLength-n:_N),o=new ArrayBuffer(a.length),c=new Uint8Array(o);for(let u=0;u<c.length;u++)c[u]=a[u];t.valueBlock.value.push(new L({valueHex:o})),i-=a.length,n+=a.length;}this.encryptedContent=t;}e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case cu:return p;case uu:return new P;case Za:return new L;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case cu:return t===p;case uu:return t.algorithmId===p&&!("algorithmParams"in t);case Za:return t.isEqual(s.defaultValues(Za));default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.contentType||p}),P.schema(t.contentEncryptionAlgorithm||{}),new We({value:[new A({name:t.encryptedContent||p,idBlock:{tagClass:3,tagNumber:0},value:[new fe({value:new L})]}),new ie({name:t.encryptedContent||p,idBlock:{tagClass:3,tagNumber:0}})]})]})}fromSchema(e){V(e,L9);let t=R(e,e,s.schema({names:{contentType:cu,contentEncryptionAlgorithm:{names:{blockName:uu}},encryptedContent:Za}}));T.assertSchema(t,this.className),this.contentType=t.result.contentType.valueBlock.toString(),this.contentEncryptionAlgorithm=new P({schema:t.result.contentEncryptionAlgorithm}),Za in t.result&&(this.encryptedContent=t.result.encryptedContent,this.encryptedContent.idBlock.tagClass=1,this.encryptedContent.idBlock.tagNumber=4);}toSchema(){let e={isIndefiniteForm:!1},t=[];if(t.push(new G({value:this.contentType})),t.push(this.contentEncryptionAlgorithm.toSchema()),this.encryptedContent){e.isIndefiniteForm=this.encryptedContent.idBlock.isConstructed;let n=this.encryptedContent;n.idBlock.tagClass=3,n.idBlock.tagNumber=0,n.lenBlock.isIndefiniteForm=this.encryptedContent.idBlock.isConstructed,t.push(n);}return new b({lenBlock:e,value:t})}toJSON(){let e={contentType:this.contentType,contentEncryptionAlgorithm:this.contentEncryptionAlgorithm.toJSON()};return this.encryptedContent&&(e.encryptedContent=this.encryptedContent.toJSON()),e}getEncryptedContent(){if(!this.encryptedContent)throw new Error("Parameter 'encryptedContent' is undefined");return L.prototype.getValue.call(this.encryptedContent)}};kt.CLASS_NAME="EncryptedContentInfo";var fi="hashAlgorithm",di="maskGenAlgorithm",mi="saltLength",pi="trailerField",j9=[fi,di,mi,pi],vl=class s extends O{constructor(e={}){super(),this.hashAlgorithm=d(e,fi,s.defaultValues(fi)),this.maskGenAlgorithm=d(e,di,s.defaultValues(di)),this.saltLength=d(e,mi,s.defaultValues(mi)),this.trailerField=d(e,pi,s.defaultValues(pi)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case fi:return new P({algorithmId:"1.3.14.3.2.26",algorithmParams:new Xe});case di:return new P({algorithmId:"1.2.840.113549.1.1.8",algorithmParams:new P({algorithmId:"1.3.14.3.2.26",algorithmParams:new Xe}).toSchema()});case mi:return 20;case pi:return 1;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new A({idBlock:{tagClass:3,tagNumber:0},optional:!0,value:[P.schema(t.hashAlgorithm||{})]}),new A({idBlock:{tagClass:3,tagNumber:1},optional:!0,value:[P.schema(t.maskGenAlgorithm||{})]}),new A({idBlock:{tagClass:3,tagNumber:2},optional:!0,value:[new k({name:t.saltLength||p})]}),new A({idBlock:{tagClass:3,tagNumber:3},optional:!0,value:[new k({name:t.trailerField||p})]})]})}fromSchema(e){V(e,j9);let t=R(e,e,s.schema({names:{hashAlgorithm:{names:{blockName:fi}},maskGenAlgorithm:{names:{blockName:di}},saltLength:mi,trailerField:pi}}));T.assertSchema(t,this.className),fi in t.result&&(this.hashAlgorithm=new P({schema:t.result.hashAlgorithm})),di in t.result&&(this.maskGenAlgorithm=new P({schema:t.result.maskGenAlgorithm})),mi in t.result&&(this.saltLength=t.result.saltLength.valueBlock.valueDec),pi in t.result&&(this.trailerField=t.result.trailerField.valueBlock.valueDec);}toSchema(){let e=[];return this.hashAlgorithm.isEqual(s.defaultValues(fi))||e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[this.hashAlgorithm.toSchema()]})),this.maskGenAlgorithm.isEqual(s.defaultValues(di))||e.push(new A({idBlock:{tagClass:3,tagNumber:1},value:[this.maskGenAlgorithm.toSchema()]})),this.saltLength!==s.defaultValues(mi)&&e.push(new A({idBlock:{tagClass:3,tagNumber:2},value:[new k({value:this.saltLength})]})),this.trailerField!==s.defaultValues(pi)&&e.push(new A({idBlock:{tagClass:3,tagNumber:3},value:[new k({value:this.trailerField})]})),new b({value:e})}toJSON(){let e={};return this.hashAlgorithm.isEqual(s.defaultValues(fi))||(e.hashAlgorithm=this.hashAlgorithm.toJSON()),this.maskGenAlgorithm.isEqual(s.defaultValues(di))||(e.maskGenAlgorithm=this.maskGenAlgorithm.toJSON()),this.saltLength!==s.defaultValues(mi)&&(e.saltLength=this.saltLength),this.trailerField!==s.defaultValues(pi)&&(e.trailerField=this.trailerField),e}};vl.CLASS_NAME="RSASSAPSSParams";var lu="salt",md="iterationCount",Zs="keyLength",nr="prf",U9=[lu,md,Zs,nr],$i=class s extends O{constructor(e={}){super(),this.salt=d(e,lu,s.defaultValues(lu)),this.iterationCount=d(e,md,s.defaultValues(md)),Zs in e&&(this.keyLength=d(e,Zs,s.defaultValues(Zs))),nr in e&&(this.prf=d(e,nr,s.defaultValues(nr))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case lu:return {};case md:return -1;case Zs:return 0;case nr:return new P({algorithmId:"1.3.14.3.2.26",algorithmParams:new Xe});default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new We({value:[new L({name:t.saltPrimitive||p}),P.schema(t.saltConstructed||{})]}),new k({name:t.iterationCount||p}),new k({name:t.keyLength||p,optional:!0}),P.schema(t.prf||{names:{optional:!0}})]})}fromSchema(e){V(e,U9);let t=R(e,e,s.schema({names:{saltPrimitive:lu,saltConstructed:{names:{blockName:lu}},iterationCount:md,keyLength:Zs,prf:{names:{blockName:nr,optional:!0}}}}));T.assertSchema(t,this.className),this.salt=t.result.salt,this.iterationCount=t.result.iterationCount.valueBlock.valueDec,Zs in t.result&&(this.keyLength=t.result.keyLength.valueBlock.valueDec),nr in t.result&&(this.prf=new P({schema:t.result.prf}));}toSchema(){let e=[];return e.push(this.salt),e.push(new k({value:this.iterationCount})),Zs in this&&s.defaultValues(Zs)!==this.keyLength&&e.push(new k({value:this.keyLength})),this.prf&&s.defaultValues(nr).isEqual(this.prf)===!1&&e.push(this.prf.toSchema()),new b({value:e})}toJSON(){let e={salt:this.salt.toJSON(),iterationCount:this.iterationCount};return Zs in this&&s.defaultValues(Zs)!==this.keyLength&&(e.keyLength=this.keyLength),this.prf&&s.defaultValues(nr).isEqual(this.prf)===!1&&(e.prf=this.prf.toJSON()),e}};$i.CLASS_NAME="PBKDF2Params";var pd="keyDerivationFunc",gd="encryptionScheme",H9=[pd,gd],Fm=class s extends O{constructor(e={}){super(),this.keyDerivationFunc=d(e,pd,s.defaultValues(pd)),this.encryptionScheme=d(e,gd,s.defaultValues(gd)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case pd:return new P;case gd:return new P;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.keyDerivationFunc||{}),P.schema(t.encryptionScheme||{})]})}fromSchema(e){V(e,H9);let t=R(e,e,s.schema({names:{keyDerivationFunc:{names:{blockName:pd}},encryptionScheme:{names:{blockName:gd}}}}));T.assertSchema(t,this.className),this.keyDerivationFunc=new P({schema:t.result.keyDerivationFunc}),this.encryptionScheme=new P({schema:t.result.encryptionScheme});}toSchema(){return new b({value:[this.keyDerivationFunc.toSchema(),this.encryptionScheme.toSchema()]})}toJSON(){return {keyDerivationFunc:this.keyDerivationFunc.toJSON(),encryptionScheme:this.encryptionScheme.toJSON()}}};Fm.CLASS_NAME="PBES2Params";var H2=class{constructor(e){this.crypto=e.crypto,this.subtle="webkitSubtle"in e.crypto?e.crypto.webkitSubtle:e.crypto.subtle,this.name=d(e,"name",p);}async encrypt(...e){return this.subtle.encrypt(...e)}async decrypt(...e){return this.subtle.decrypt(...e)}sign(...e){return this.subtle.sign(...e)}async verify(...e){return this.subtle.verify(...e)}async digest(...e){return this.subtle.digest(...e)}async generateKey(...e){return this.subtle.generateKey(...e)}async deriveKey(...e){return this.subtle.deriveKey(...e)}async deriveBits(...e){return this.subtle.deriveBits(...e)}async wrapKey(...e){return this.subtle.wrapKey(...e)}async unwrapKey(...e){return this.subtle.unwrapKey(...e)}exportKey(...e){return this.subtle.exportKey(...e)}importKey(...e){return this.subtle.importKey(...e)}getRandomValues(e){if(e===null)throw new Error('Argument "array" must not be null');return this.crypto.getRandomValues(e)}};async function MN(s,e,t,n,r){let i,a,o;switch(s.toUpperCase()){case"SHA-1":i=20,a=64,o=RN;break;case"SHA-256":i=32,a=64,o=n2;break;case"SHA-384":i=48,a=128,o=o2;break;case"SHA-512":i=64,a=128,o=a2;break;default:throw new Error("Unsupported hashing algorithm")}let c=new Uint8Array(t),u=new TextDecoder().decode(t);new TextEncoder().encode(u).some((v,I)=>v!==c[I])&&(u=String.fromCharCode(...c));let h=new Uint8Array(u.length*2+2),m=new DataView(h.buffer);for(let v=0;v<u.length;v++)m.setUint16(v*2,u.charCodeAt(v),!1);m.setUint16(u.length*2,0,!1);let y=new Uint8Array(a).fill(3),g=new Uint8Array(n),w=new Uint8Array(a*Math.ceil(g.length/a)).map((v,I)=>g[I%g.length]),S=new Uint8Array(a*Math.ceil(h.length/a)).map((v,I)=>h[I%h.length]),C=new Uint8Array(w.length+S.length);C.set(w),C.set(S,w.length);let N=Math.ceil((e>>3)/i),x=[];for(let v=0;v<N;v++){let I=new Uint8Array(y.length+C.length);I.set(y),I.set(C,y.length);for(let W=0;W<r;W++)I=o(I);let D=new Uint8Array(a).map((W,se)=>I[se%I.length]),F=Math.ceil(g.length/a)+Math.ceil(h.length/a),M=[];for(let W=0;W<F;W++){let se=Array.from(C.slice(W*a,(W+1)*a)),q=511;for(let J=D.length-1;J>=0;J--)q>>=8,q+=D[J]+(se[J]||0),se[J]=q&255;M.push(...se);}C=new Uint8Array(M),x.push(...I);}return new Uint8Array(x.slice(0,e>>3)).buffer}function xk(s){let e=typeof s=="string"?{name:s}:s;return "hash"in e?{...e,hash:xk(e.hash)}:e}var kl=class extends H2{async importKey(e,t,n,r,i){var a,o,c,u,l,h;let m={},y=xk(n);switch(e.toLowerCase()){case"raw":return this.subtle.importKey("raw",t,n,r,i);case"spki":{let g=ht(re.toArrayBuffer(t));T.assert(g,"keyData");let w=new As;try{w.fromSchema(g.result);}catch{throw new $e("Incorrect keyData")}switch(y.name.toUpperCase()){case"RSA-PSS":{if(!y.hash)throw new Re("hash","algorithm.hash","Incorrect hash algorithm: Hash algorithm is missed");switch(y.hash.name.toUpperCase()){case"SHA-1":m.alg="PS1";break;case"SHA-256":m.alg="PS256";break;case"SHA-384":m.alg="PS384";break;case"SHA-512":m.alg="PS512";break;default:throw new Error(`Incorrect hash algorithm: ${y.hash.name.toUpperCase()}`)}}case"RSASSA-PKCS1-V1_5":{if(i=["verify"],m.kty="RSA",m.ext=r,m.key_ops=i,w.algorithm.algorithmId!=="1.2.840.113549.1.1.1")throw new Error(`Incorrect public key algorithm: ${w.algorithm.algorithmId}`);if(!m.alg){if(!y.hash)throw new Re("hash","algorithm.hash","Incorrect hash algorithm: Hash algorithm is missed");switch(y.hash.name.toUpperCase()){case"SHA-1":m.alg="RS1";break;case"SHA-256":m.alg="RS256";break;case"SHA-384":m.alg="RS384";break;case"SHA-512":m.alg="RS512";break;default:throw new Error(`Incorrect hash algorithm: ${y.hash.name.toUpperCase()}`)}}let S=w.toJSON();Object.assign(m,S);}break;case"ECDSA":i=["verify"];case"ECDH":{if(m={kty:"EC",ext:r,key_ops:i},w.algorithm.algorithmId!=="1.2.840.10045.2.1")throw new Error(`Incorrect public key algorithm: ${w.algorithm.algorithmId}`);let S=w.toJSON();Object.assign(m,S);}break;case"RSA-OAEP":{if(m.kty="RSA",m.ext=r,m.key_ops=i,this.name.toLowerCase()==="safari")m.alg="RSA-OAEP";else {if(!y.hash)throw new Re("hash","algorithm.hash","Incorrect hash algorithm: Hash algorithm is missed");switch(y.hash.name.toUpperCase()){case"SHA-1":m.alg="RSA-OAEP";break;case"SHA-256":m.alg="RSA-OAEP-256";break;case"SHA-384":m.alg="RSA-OAEP-384";break;case"SHA-512":m.alg="RSA-OAEP-512";break;default:throw new Error(`Incorrect hash algorithm: ${y.hash.name.toUpperCase()}`)}}let S=w.toJSON();Object.assign(m,S);}break;case"RSAES-PKCS1-V1_5":{m.kty="RSA",m.ext=r,m.key_ops=i,m.alg="PS1";let S=w.toJSON();Object.assign(m,S);}break;default:throw new Error(`Incorrect algorithm name: ${y.name.toUpperCase()}`)}}break;case"pkcs8":{let g=new Yo,w=ht(re.toArrayBuffer(t));T.assert(w,"keyData");try{g.fromSchema(w.result);}catch{throw new Error("Incorrect keyData")}if(!g.parsedKey)throw new Error("Incorrect keyData");switch(y.name.toUpperCase()){case"RSA-PSS":switch((a=y.hash)===null||a===void 0?void 0:a.name.toUpperCase()){case"SHA-1":m.alg="PS1";break;case"SHA-256":m.alg="PS256";break;case"SHA-384":m.alg="PS384";break;case"SHA-512":m.alg="PS512";break;default:throw new Error(`Incorrect hash algorithm: ${(o=y.hash)===null||o===void 0?void 0:o.name.toUpperCase()}`)}case"RSASSA-PKCS1-V1_5":{if(i=["sign"],m.kty="RSA",m.ext=r,m.key_ops=i,g.privateKeyAlgorithm.algorithmId!=="1.2.840.113549.1.1.1")throw new Error(`Incorrect private key algorithm: ${g.privateKeyAlgorithm.algorithmId}`);if(!("alg"in m))switch((c=y.hash)===null||c===void 0?void 0:c.name.toUpperCase()){case"SHA-1":m.alg="RS1";break;case"SHA-256":m.alg="RS256";break;case"SHA-384":m.alg="RS384";break;case"SHA-512":m.alg="RS512";break;default:throw new Error(`Incorrect hash algorithm: ${(u=y.hash)===null||u===void 0?void 0:u.name.toUpperCase()}`)}let S=g.toJSON();Object.assign(m,S);}break;case"ECDSA":i=["sign"];case"ECDH":{if(m={kty:"EC",ext:r,key_ops:i},g.privateKeyAlgorithm.algorithmId!=="1.2.840.10045.2.1")throw new Error(`Incorrect algorithm: ${g.privateKeyAlgorithm.algorithmId}`);let S=g.toJSON();Object.assign(m,S);}break;case"RSA-OAEP":{if(m.kty="RSA",m.ext=r,m.key_ops=i,this.name.toLowerCase()==="safari")m.alg="RSA-OAEP";else switch((l=y.hash)===null||l===void 0?void 0:l.name.toUpperCase()){case"SHA-1":m.alg="RSA-OAEP";break;case"SHA-256":m.alg="RSA-OAEP-256";break;case"SHA-384":m.alg="RSA-OAEP-384";break;case"SHA-512":m.alg="RSA-OAEP-512";break;default:throw new Error(`Incorrect hash algorithm: ${(h=y.hash)===null||h===void 0?void 0:h.name.toUpperCase()}`)}let S=g.toJSON();Object.assign(m,S);}break;case"RSAES-PKCS1-V1_5":{i=["decrypt"],m.kty="RSA",m.ext=r,m.key_ops=i,m.alg="PS1";let S=g.toJSON();Object.assign(m,S);}break;default:throw new Error(`Incorrect algorithm name: ${y.name.toUpperCase()}`)}}break;case"jwk":m=t;break;default:throw new Error(`Incorrect format: ${e}`)}if(this.name.toLowerCase()==="safari")try{return this.subtle.importKey("jwk",Pa(JSON.stringify(m)),n,r,i)}catch{return this.subtle.importKey("jwk",m,n,r,i)}return this.subtle.importKey("jwk",m,n,r,i)}async exportKey(e,t){let n=await this.subtle.exportKey("jwk",t);switch(this.name.toLowerCase()==="safari"&&n instanceof ArrayBuffer&&(n=JSON.parse(uf(n))),e.toLowerCase()){case"raw":return this.subtle.exportKey("raw",t);case"spki":{let r=new As;try{r.fromJSON(n);}catch{throw new Error("Incorrect key data")}return r.toSchema().toBER(!1)}case"pkcs8":{let r=new Yo;try{r.fromJSON(n);}catch{throw new Error("Incorrect key data")}return r.toSchema().toBER(!1)}case"jwk":return n;default:throw new Error(`Incorrect format: ${e}`)}}async convert(e,t,n,r,i,a){if(e.toLowerCase()===t.toLowerCase())return n;let o=await this.importKey(e,n,r,i,a);return this.exportKey(t,o)}getAlgorithmByOID(e,t=!1,n){switch(e){case"1.2.840.113549.1.1.1":return {name:"RSAES-PKCS1-v1_5"};case"1.2.840.113549.1.1.5":return {name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case"1.2.840.113549.1.1.11":return {name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"1.2.840.113549.1.1.12":return {name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case"1.2.840.113549.1.1.13":return {name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case"1.2.840.113549.1.1.10":return {name:"RSA-PSS"};case"1.2.840.113549.1.1.7":return {name:"RSA-OAEP"};case"1.2.840.10045.2.1":case"1.2.840.10045.4.1":return {name:"ECDSA",hash:{name:"SHA-1"}};case"1.2.840.10045.4.3.2":return {name:"ECDSA",hash:{name:"SHA-256"}};case"1.2.840.10045.4.3.3":return {name:"ECDSA",hash:{name:"SHA-384"}};case"1.2.840.10045.4.3.4":return {name:"ECDSA",hash:{name:"SHA-512"}};case"1.3.133.16.840.63.0.2":return {name:"ECDH",kdf:"SHA-1"};case"1.3.132.1.11.1":return {name:"ECDH",kdf:"SHA-256"};case"1.3.132.1.11.2":return {name:"ECDH",kdf:"SHA-384"};case"1.3.132.1.11.3":return {name:"ECDH",kdf:"SHA-512"};case"2.16.840.1.101.3.4.1.2":return {name:"AES-CBC",length:128};case"2.16.840.1.101.3.4.1.22":return {name:"AES-CBC",length:192};case"2.16.840.1.101.3.4.1.42":return {name:"AES-CBC",length:256};case"2.16.840.1.101.3.4.1.6":return {name:"AES-GCM",length:128};case"2.16.840.1.101.3.4.1.26":return {name:"AES-GCM",length:192};case"2.16.840.1.101.3.4.1.46":return {name:"AES-GCM",length:256};case"2.16.840.1.101.3.4.1.4":return {name:"AES-CFB",length:128};case"2.16.840.1.101.3.4.1.24":return {name:"AES-CFB",length:192};case"2.16.840.1.101.3.4.1.44":return {name:"AES-CFB",length:256};case"2.16.840.1.101.3.4.1.5":return {name:"AES-KW",length:128};case"2.16.840.1.101.3.4.1.25":return {name:"AES-KW",length:192};case"2.16.840.1.101.3.4.1.45":return {name:"AES-KW",length:256};case"1.2.840.113549.2.7":return {name:"HMAC",hash:{name:"SHA-1"}};case"1.2.840.113549.2.9":return {name:"HMAC",hash:{name:"SHA-256"}};case"1.2.840.113549.2.10":return {name:"HMAC",hash:{name:"SHA-384"}};case"1.2.840.113549.2.11":return {name:"HMAC",hash:{name:"SHA-512"}};case"1.2.840.113549.1.9.16.3.5":return {name:"DH"};case"1.3.14.3.2.26":return {name:"SHA-1"};case"2.16.840.1.101.3.4.2.1":return {name:"SHA-256"};case"2.16.840.1.101.3.4.2.2":return {name:"SHA-384"};case"2.16.840.1.101.3.4.2.3":return {name:"SHA-512"};case"1.2.840.113549.1.5.12":return {name:"PBKDF2"};case"1.2.840.10045.3.1.7":return {name:"P-256"};case"1.3.132.0.34":return {name:"P-384"};case"1.3.132.0.35":return {name:"P-521"}}if(t)throw new Error(`Unsupported algorithm identifier ${n?`for ${n} `:p}: ${e}`);return {}}getOIDByAlgorithm(e,t=!1,n){let r=p;switch(e.name.toUpperCase()){case"RSAES-PKCS1-V1_5":r="1.2.840.113549.1.1.1";break;case"RSASSA-PKCS1-V1_5":switch(e.hash.name.toUpperCase()){case"SHA-1":r="1.2.840.113549.1.1.5";break;case"SHA-256":r="1.2.840.113549.1.1.11";break;case"SHA-384":r="1.2.840.113549.1.1.12";break;case"SHA-512":r="1.2.840.113549.1.1.13";break}break;case"RSA-PSS":r="1.2.840.113549.1.1.10";break;case"RSA-OAEP":r="1.2.840.113549.1.1.7";break;case"ECDSA":switch(e.hash.name.toUpperCase()){case"SHA-1":r="1.2.840.10045.4.1";break;case"SHA-256":r="1.2.840.10045.4.3.2";break;case"SHA-384":r="1.2.840.10045.4.3.3";break;case"SHA-512":r="1.2.840.10045.4.3.4";break}break;case"ECDH":switch(e.kdf.toUpperCase()){case"SHA-1":r="1.3.133.16.840.63.0.2";break;case"SHA-256":r="1.3.132.1.11.1";break;case"SHA-384":r="1.3.132.1.11.2";break;case"SHA-512":r="1.3.132.1.11.3";break}break;case"AES-CTR":break;case"AES-CBC":switch(e.length){case 128:r="2.16.840.1.101.3.4.1.2";break;case 192:r="2.16.840.1.101.3.4.1.22";break;case 256:r="2.16.840.1.101.3.4.1.42";break}break;case"AES-CMAC":break;case"AES-GCM":switch(e.length){case 128:r="2.16.840.1.101.3.4.1.6";break;case 192:r="2.16.840.1.101.3.4.1.26";break;case 256:r="2.16.840.1.101.3.4.1.46";break}break;case"AES-CFB":switch(e.length){case 128:r="2.16.840.1.101.3.4.1.4";break;case 192:r="2.16.840.1.101.3.4.1.24";break;case 256:r="2.16.840.1.101.3.4.1.44";break}break;case"AES-KW":switch(e.length){case 128:r="2.16.840.1.101.3.4.1.5";break;case 192:r="2.16.840.1.101.3.4.1.25";break;case 256:r="2.16.840.1.101.3.4.1.45";break}break;case"HMAC":switch(e.hash.name.toUpperCase()){case"SHA-1":r="1.2.840.113549.2.7";break;case"SHA-256":r="1.2.840.113549.2.9";break;case"SHA-384":r="1.2.840.113549.2.10";break;case"SHA-512":r="1.2.840.113549.2.11";break}break;case"DH":r="1.2.840.113549.1.9.16.3.5";break;case"SHA-1":r="1.3.14.3.2.26";break;case"SHA-256":r="2.16.840.1.101.3.4.2.1";break;case"SHA-384":r="2.16.840.1.101.3.4.2.2";break;case"SHA-512":r="2.16.840.1.101.3.4.2.3";break;case"CONCAT":break;case"HKDF":break;case"PBKDF2":r="1.2.840.113549.1.5.12";break;case"P-256":r="1.2.840.10045.3.1.7";break;case"P-384":r="1.3.132.0.34";break;case"P-521":r="1.3.132.0.35";break}if(!r&&t)throw new Error(`Unsupported algorithm ${n?`for ${n} `:p}: ${e.name}`);return r}getAlgorithmParameters(e,t){let n={algorithm:{},usages:[]};switch(e.toUpperCase()){case"RSAES-PKCS1-V1_5":case"RSASSA-PKCS1-V1_5":switch(t.toLowerCase()){case"generatekey":n={algorithm:{name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},usages:["sign","verify"]};break;case"verify":case"sign":case"importkey":n={algorithm:{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},usages:["verify"]};break;case"exportkey":default:return {algorithm:{name:"RSASSA-PKCS1-v1_5"},usages:[]}}break;case"RSA-PSS":switch(t.toLowerCase()){case"sign":case"verify":n={algorithm:{name:"RSA-PSS",hash:{name:"SHA-1"},saltLength:20},usages:["sign","verify"]};break;case"generatekey":n={algorithm:{name:"RSA-PSS",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-1"}},usages:["sign","verify"]};break;case"importkey":n={algorithm:{name:"RSA-PSS",hash:{name:"SHA-1"}},usages:["verify"]};break;case"exportkey":default:return {algorithm:{name:"RSA-PSS"},usages:[]}}break;case"RSA-OAEP":switch(t.toLowerCase()){case"encrypt":case"decrypt":n={algorithm:{name:"RSA-OAEP"},usages:["encrypt","decrypt"]};break;case"generatekey":n={algorithm:{name:"RSA-OAEP",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;case"importkey":n={algorithm:{name:"RSA-OAEP",hash:{name:"SHA-256"}},usages:["encrypt"]};break;case"exportkey":default:return {algorithm:{name:"RSA-OAEP"},usages:[]}}break;case"ECDSA":switch(t.toLowerCase()){case"generatekey":n={algorithm:{name:"ECDSA",namedCurve:"P-256"},usages:["sign","verify"]};break;case"importkey":n={algorithm:{name:"ECDSA",namedCurve:"P-256"},usages:["verify"]};break;case"verify":case"sign":n={algorithm:{name:"ECDSA",hash:{name:"SHA-256"}},usages:["sign"]};break;default:return {algorithm:{name:"ECDSA"},usages:[]}}break;case"ECDH":switch(t.toLowerCase()){case"exportkey":case"importkey":case"generatekey":n={algorithm:{name:"ECDH",namedCurve:"P-256"},usages:["deriveKey","deriveBits"]};break;case"derivekey":case"derivebits":n={algorithm:{name:"ECDH",namedCurve:"P-256",public:[]},usages:["encrypt","decrypt"]};break;default:return {algorithm:{name:"ECDH"},usages:[]}}break;case"AES-CTR":switch(t.toLowerCase()){case"importkey":case"exportkey":case"generatekey":n={algorithm:{name:"AES-CTR",length:256},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;case"decrypt":case"encrypt":n={algorithm:{name:"AES-CTR",counter:new Uint8Array(16),length:10},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;default:return {algorithm:{name:"AES-CTR"},usages:[]}}break;case"AES-CBC":switch(t.toLowerCase()){case"importkey":case"exportkey":case"generatekey":n={algorithm:{name:"AES-CBC",length:256},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;case"decrypt":case"encrypt":n={algorithm:{name:"AES-CBC",iv:this.getRandomValues(new Uint8Array(16))},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;default:return {algorithm:{name:"AES-CBC"},usages:[]}}break;case"AES-GCM":switch(t.toLowerCase()){case"importkey":case"exportkey":case"generatekey":n={algorithm:{name:"AES-GCM",length:256},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;case"decrypt":case"encrypt":n={algorithm:{name:"AES-GCM",iv:this.getRandomValues(new Uint8Array(16))},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;default:return {algorithm:{name:"AES-GCM"},usages:[]}}break;case"AES-KW":switch(t.toLowerCase()){case"importkey":case"exportkey":case"generatekey":case"wrapkey":case"unwrapkey":n={algorithm:{name:"AES-KW",length:256},usages:["wrapKey","unwrapKey"]};break;default:return {algorithm:{name:"AES-KW"},usages:[]}}break;case"HMAC":switch(t.toLowerCase()){case"sign":case"verify":n={algorithm:{name:"HMAC"},usages:["sign","verify"]};break;case"importkey":case"exportkey":case"generatekey":n={algorithm:{name:"HMAC",length:32,hash:{name:"SHA-256"}},usages:["sign","verify"]};break;default:return {algorithm:{name:"HMAC"},usages:[]}}break;case"HKDF":switch(t.toLowerCase()){case"derivekey":n={algorithm:{name:"HKDF",hash:"SHA-256",salt:new Uint8Array([]),info:new Uint8Array([])},usages:["encrypt","decrypt"]};break;default:return {algorithm:{name:"HKDF"},usages:[]}}break;case"PBKDF2":switch(t.toLowerCase()){case"derivekey":n={algorithm:{name:"PBKDF2",hash:{name:"SHA-256"},salt:new Uint8Array([]),iterations:1e4},usages:["encrypt","decrypt"]};break;default:return {algorithm:{name:"PBKDF2"},usages:[]}}break}return n}getHashAlgorithm(e){let t=p;switch(e.algorithmId){case"1.2.840.10045.4.1":case"1.2.840.113549.1.1.5":t="SHA-1";break;case"1.2.840.10045.4.3.2":case"1.2.840.113549.1.1.11":t="SHA-256";break;case"1.2.840.10045.4.3.3":case"1.2.840.113549.1.1.12":t="SHA-384";break;case"1.2.840.10045.4.3.4":case"1.2.840.113549.1.1.13":t="SHA-512";break;case"1.2.840.113549.1.1.10":try{let n=new vl({schema:e.algorithmParams});if(n.hashAlgorithm){let r=this.getAlgorithmByOID(n.hashAlgorithm.algorithmId);if("name"in r)t=r.name;else return p}else t="SHA-1";}catch{}break}return t}async encryptEncryptedContentInfo(e){Re.assert(e,"password","contentEncryptionAlgorithm","hmacHashAlgorithm","iterationCount","contentToEncrypt","contentToEncrypt","contentType");let t=this.getOIDByAlgorithm(e.contentEncryptionAlgorithm,!0,"contentEncryptionAlgorithm"),n=this.getOIDByAlgorithm({name:"PBKDF2"},!0,"PBKDF2"),r=this.getOIDByAlgorithm({name:"HMAC",hash:{name:e.hmacHashAlgorithm}},!0,"hmacHashAlgorithm"),i=new ArrayBuffer(16),a=new Uint8Array(i);this.getRandomValues(a);let o=new ArrayBuffer(64),c=new Uint8Array(o);this.getRandomValues(c);let u=new Uint8Array(e.contentToEncrypt),l=new $i({salt:new L({valueHex:o}),iterationCount:e.iterationCount,prf:new P({algorithmId:r,algorithmParams:new Xe})}),h=new Uint8Array(e.password),m=await this.importKey("raw",h,"PBKDF2",!1,["deriveKey"]),y=await this.deriveKey({name:"PBKDF2",hash:{name:e.hmacHashAlgorithm},salt:c,iterations:e.iterationCount},m,e.contentEncryptionAlgorithm,!1,["encrypt"]),g=await this.encrypt({name:e.contentEncryptionAlgorithm.name,iv:a},y,u),w=new Fm({keyDerivationFunc:new P({algorithmId:n,algorithmParams:l.toSchema()}),encryptionScheme:new P({algorithmId:t,algorithmParams:new L({valueHex:i})})});return new kt({contentType:e.contentType,contentEncryptionAlgorithm:new P({algorithmId:"1.2.840.113549.1.5.13",algorithmParams:w.toSchema()}),encryptedContent:new L({valueHex:g})})}async decryptEncryptedContentInfo(e){if(Re.assert(e,"password","encryptedContentInfo"),e.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId!=="1.2.840.113549.1.5.13")throw new Error(`Unknown "contentEncryptionAlgorithm": ${e.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId}`);let t;try{t=new Fm({schema:e.encryptedContentInfo.contentEncryptionAlgorithm.algorithmParams});}catch{throw new Error('Incorrectly encoded "pbes2Parameters"')}let n;try{n=new $i({schema:t.keyDerivationFunc.algorithmParams});}catch{throw new Error('Incorrectly encoded "pbkdf2Params"')}let r=this.getAlgorithmByOID(t.encryptionScheme.algorithmId,!0),i=t.encryptionScheme.algorithmParams.valueBlock.valueHex,a=new Uint8Array(i),o=n.salt.valueBlock.valueHex,c=new Uint8Array(o),u=n.iterationCount,l="SHA-1";n.prf&&(l=this.getAlgorithmByOID(n.prf.algorithmId,!0).hash.name);let h=await this.importKey("raw",e.password,"PBKDF2",!1,["deriveKey"]),m=await this.deriveKey({name:"PBKDF2",hash:{name:l},salt:c,iterations:u},h,r,!1,["decrypt"]),y=e.encryptedContentInfo.getEncryptedContent();return this.decrypt({name:r.name,iv:a},m,y)}async stampDataWithPassword(e){if(!(e instanceof Object))throw new Error('Parameters must have type "Object"');Re.assert(e,"password","hashAlgorithm","iterationCount","salt","contentToStamp");let t;switch(e.hashAlgorithm.toLowerCase()){case"sha-1":t=160;break;case"sha-256":t=256;break;case"sha-384":t=384;break;case"sha-512":t=512;break;default:throw new Error(`Incorrect "parameters.hashAlgorithm" parameter: ${e.hashAlgorithm}`)}let n={name:"HMAC",length:t,hash:{name:e.hashAlgorithm}},r=await MN(e.hashAlgorithm,t,e.password,e.salt,e.iterationCount),i=await this.importKey("raw",new Uint8Array(r),n,!1,["sign"]);return this.sign(n,i,new Uint8Array(e.contentToStamp))}async verifyDataStampedWithPassword(e){Re.assert(e,"password","hashAlgorithm","salt","iterationCount","contentToVerify","signatureToVerify");let t=0;switch(e.hashAlgorithm.toLowerCase()){case"sha-1":t=160;break;case"sha-256":t=256;break;case"sha-384":t=384;break;case"sha-512":t=512;break;default:throw new Error(`Incorrect "parameters.hashAlgorithm" parameter: ${e.hashAlgorithm}`)}let n={name:"HMAC",length:t,hash:{name:e.hashAlgorithm}},r=await MN(e.hashAlgorithm,t,e.password,e.salt,e.iterationCount),i=await this.importKey("raw",new Uint8Array(r),n,!1,["verify"]);return this.verify(n,i,new Uint8Array(e.signatureToVerify),new Uint8Array(e.contentToVerify))}async getSignatureParameters(e,t="SHA-1"){this.getOIDByAlgorithm({name:t},!0,"hashAlgorithm");let n=new P,r=this.getAlgorithmParameters(e.algorithm.name,"sign");if(!Object.keys(r.algorithm).length)throw new Error("Parameter 'algorithm' is empty");let i=r.algorithm;switch("hash"in e.algorithm&&e.algorithm.hash&&e.algorithm.hash.name?i.hash.name=e.algorithm.hash.name:i.hash.name=t,e.algorithm.name.toUpperCase()){case"RSASSA-PKCS1-V1_5":case"ECDSA":n.algorithmId=this.getOIDByAlgorithm(i,!0);break;case"RSA-PSS":{switch(i.hash.name.toUpperCase()){case"SHA-256":i.saltLength=32;break;case"SHA-384":i.saltLength=48;break;case"SHA-512":i.saltLength=64;break}let a={};if(i.hash.name.toUpperCase()!=="SHA-1"){let c=this.getOIDByAlgorithm({name:i.hash.name},!0,"hashAlgorithm");a.hashAlgorithm=new P({algorithmId:c,algorithmParams:new Xe}),a.maskGenAlgorithm=new P({algorithmId:"1.2.840.113549.1.1.8",algorithmParams:a.hashAlgorithm.toSchema()});}i.saltLength!==20&&(a.saltLength=i.saltLength);let o=new vl(a);n.algorithmId="1.2.840.113549.1.1.10",n.algorithmParams=o.toSchema();}break;default:throw new Error(`Unsupported signature algorithm: ${e.algorithm.name}`)}return {signatureAlgorithm:n,parameters:r}}async signWithPrivateKey(e,t,n){let r=await this.sign(n.algorithm,t,e);return n.algorithm.name==="ECDSA"?M9(r):r}fillPublicKeyParameters(e,t){let n={},r=this.getHashAlgorithm(t);if(r===p)throw new Error(`Unsupported signature algorithm: ${t.algorithmId}`);let i;t.algorithmId==="1.2.840.113549.1.1.10"?i=t.algorithmId:i=e.algorithm.algorithmId;let a=this.getAlgorithmByOID(i,!0);if(n.algorithm=this.getAlgorithmParameters(a.name,"importKey"),"hash"in n.algorithm.algorithm&&(n.algorithm.algorithm.hash.name=r),a.name==="ECDSA"){let o=e.algorithm;if(!o.algorithmParams)throw new Error("Algorithm parameters for ECDSA public key are missed");let c=o.algorithmParams;if("idBlock"in o.algorithmParams&&!(c.idBlock.tagClass===1&&c.idBlock.tagNumber===6))throw new Error("Incorrect type for ECDSA public key parameters");let u=this.getAlgorithmByOID(c.valueBlock.toString(),!0);n.algorithm.algorithm.namedCurve=u.name;}return n}async getPublicKey(e,t,n){n||(n=this.fillPublicKeyParameters(e,t));let r=e.toSchema().toBER(!1);return this.importKey("spki",r,n.algorithm.algorithm,!0,n.algorithm.usages)}async verifyWithPublicKey(e,t,n,r,i){let a;if(i){let u={},l;r.algorithmId==="1.2.840.113549.1.1.10"?l=r.algorithmId:l=n.algorithm.algorithmId;let h=this.getAlgorithmByOID(l,!0);if(u.algorithm=this.getAlgorithmParameters(h.name,"importKey"),"hash"in u.algorithm.algorithm&&(u.algorithm.algorithm.hash.name=i),h.name==="ECDSA"){let m=!1;if("algorithmParams"in n.algorithm&&"idBlock"in n.algorithm.algorithmParams&&n.algorithm.algorithmParams.idBlock.tagClass===1&&n.algorithm.algorithmParams.idBlock.tagNumber===6&&(m=!0),m===!1)throw new Error("Incorrect type for ECDSA public key parameters");let y=this.getAlgorithmByOID(n.algorithm.algorithmParams.valueBlock.toString(),!0);u.algorithm.algorithm.namedCurve=y.name;}a=await this.getPublicKey(n,null,u);}else {if(i=this.getHashAlgorithm(r),!i)throw new Error(`Unsupported signature algorithm: ${r.algorithmId}`);a=await this.getPublicKey(n,r);}let o=this.getAlgorithmParameters(a.algorithm.name,"verify");"hash"in o.algorithm&&(o.algorithm.hash.name=i);let c=t.valueBlock.valueHexView;if(a.algorithm.name==="ECDSA"){let u=Sn.find(a.algorithm.namedCurve);if(!u)throw new Error("Unsupported named curve in use");let l=ht(c);T.assert(l,"Signature value"),c=$9(l.result,u.size);}if(a.algorithm.name==="RSA-PSS"){let u=new vl({schema:r.algorithmParams});"saltLength"in u?o.algorithm.saltLength=u.saltLength:o.algorithm.saltLength=20;let l="SHA-1";"hashAlgorithm"in u&&(l=this.getAlgorithmByOID(u.hashAlgorithm.algorithmId,!0).name),o.algorithm.hash.name=l;}return this.verify(o.algorithm,a,c,e)}},Ek={name:"none",crypto:null};function $N(s){return !!(s&&typeof s=="object"&&"crypto"in s)}function qN(s,...e){let t=null;if(e.length<2)e.length?t=e[0]:t=typeof self<"u"&&self.crypto?new kl({name:"browser",crypto:self.crypto}):null;else {let n=e[0],r=e[1];$N(r)?t=r:$N(n)?t=n:"subtle"in n&&"getRandomValues"in n&&(t=new kl({crypto:n}));}if(typeof process<"u"&&"pid"in process&&typeof global<"u"&&typeof window>"u"){if(typeof global[process.pid]>"u")global[process.pid]={};else if(typeof global[process.pid]!="object")throw new Error(`Name global.${process.pid} already exists and it is not an object`);if(typeof global[process.pid].pkijs>"u")global[process.pid].pkijs={};else if(typeof global[process.pid].pkijs!="object")throw new Error(`Name global.${process.pid}.pkijs already exists and it is not an object`);global[process.pid].pkijs.engine={name:s,crypto:t};}else Ek={name:s,crypto:t};}function _9(){if(typeof process<"u"&&"pid"in process&&typeof global<"u"&&typeof window>"u"){let s;try{s=global[process.pid].pkijs.engine;}catch{throw new Error("Please call 'setEngine' before call to 'getEngine'")}return s}return Ek}function ve(s=!1){let e=_9();if(!e.crypto&&s)throw new Error("Unable to create WebCrypto object");return e.crypto}function M9(s){if(s.byteLength%2!==0)return ut;let e=s.byteLength/2,t=new ArrayBuffer(e);new Uint8Array(t).set(new Uint8Array(s,0,e));let r=new k({valueHex:t}),i=new ArrayBuffer(e);new Uint8Array(i).set(new Uint8Array(s,e,e));let o=new k({valueHex:i});return new b({value:[r.convertToDER(),o.convertToDER()]}).toBER(!1)}function $9(s,e){if(!(s instanceof b&&s.valueBlock.value.length===2&&s.valueBlock.value[0]instanceof k&&s.valueBlock.value[1]instanceof k))return ut;let t=s.valueBlock.value[0].convertFromDER().valueBlock.valueHexView,n=s.valueBlock.value[1].convertFromDER().valueBlock.valueHexView,r=new Uint8Array(e*2);return r.set(t,e-t.byteLength),r.set(n,2*e-n.byteLength),r.buffer}async function q9(s,e,t,n,r){switch(s.toUpperCase()){case"SHA-1":case"SHA-256":case"SHA-384":case"SHA-512":break;default:throw new $e(`Unknown hash function: ${s}`)}if($e.assert(e,"zBuffer","ArrayBuffer"),e.byteLength===0)throw new $e("'zBuffer' has zero length, error");if($e.assert(n,"SharedInfo","ArrayBuffer"),t>255)throw new $e("Please set 'Counter' argument to value less or equal to 255");let i=new ArrayBuffer(4),a=new Uint8Array(i);a[0]=0,a[1]=0,a[2]=0,a[3]=t;let o=ut;o=ka(o,e),o=ka(o,i),o=ka(o,n);let c=await r.digest({name:s},o);return {counter:t,result:c}}async function FN(s,e,t,n,r=ve(!0)){let i=0,a=1;switch(s.toUpperCase()){case"SHA-1":i=160;break;case"SHA-256":i=256;break;case"SHA-384":i=384;break;case"SHA-512":i=512;break;default:throw new $e(`Unknown hash function: ${s}`)}if($e.assert(e,"Zbuffer","ArrayBuffer"),e.byteLength===0)throw new $e("'Zbuffer' has zero length, error");$e.assert(n,"SharedInfo","ArrayBuffer");let o=t/i;Math.floor(o)>0&&(a=Math.floor(o),o-a>0&&a++);let c=[];for(let m=1;m<=a;m++)c.push(await q9(s,e,m,n,r));let u=ut,l=1,h=!0;for(;h;){h=!1;for(let m of c)if(m.counter===l){u=ka(u,m.result),h=!0;break}l++;}if(t>>=3,u.byteLength>t){let m=new ArrayBuffer(t),y=new Uint8Array(m),g=new Uint8Array(u);for(let w=0;w<t;w++)y[w]=g[w];return m}return u}var h2="version",f2="logID",d2="extensions",m2="timestamp",p2="hashAlgorithm",g2="signatureAlgorithm",y2="signature",KN="none",GN="md5",WN="sha1",JN="sha224",zN="sha256",YN="sha384",ZN="sha512",QN="anonymous",XN="rsa",ek="dsa",tk="ecdsa",uw=class s extends O{constructor(e={}){super(),this.version=d(e,h2,s.defaultValues(h2)),this.logID=d(e,f2,s.defaultValues(f2)),this.timestamp=d(e,m2,s.defaultValues(m2)),this.extensions=d(e,d2,s.defaultValues(d2)),this.hashAlgorithm=d(e,p2,s.defaultValues(p2)),this.signatureAlgorithm=d(e,g2,s.defaultValues(g2)),this.signature=d(e,y2,s.defaultValues(y2)),"stream"in e&&e.stream&&this.fromStream(e.stream),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case h2:return 0;case f2:case d2:return ut;case m2:return new Date(0);case p2:case g2:return p;case y2:return ut;default:return super.defaultValues(e)}}fromSchema(e){if(!(e instanceof Oa))throw new Error("Object's schema was not verified against input data for SignedCertificateTimestamp");let t=new Yn({stream:new Lt({buffer:e.data})});this.fromStream(t);}fromStream(e){let t=e.getUint16();if(this.version=e.getBlock(1)[0],this.version===0){this.logID=new Uint8Array(e.getBlock(32)).buffer.slice(0),this.timestamp=new Date(Fn(new Uint8Array(e.getBlock(8)),8));let n=e.getUint16();switch(this.extensions=new Uint8Array(e.getBlock(n)).buffer.slice(0),e.getBlock(1)[0]){case 0:this.hashAlgorithm=KN;break;case 1:this.hashAlgorithm=GN;break;case 2:this.hashAlgorithm=WN;break;case 3:this.hashAlgorithm=JN;break;case 4:this.hashAlgorithm=zN;break;case 5:this.hashAlgorithm=YN;break;case 6:this.hashAlgorithm=ZN;break;default:throw new Error("Object's stream was not correct for SignedCertificateTimestamp")}switch(e.getBlock(1)[0]){case 0:this.signatureAlgorithm=QN;break;case 1:this.signatureAlgorithm=XN;break;case 2:this.signatureAlgorithm=ek;break;case 3:this.signatureAlgorithm=tk;break;default:throw new Error("Object's stream was not correct for SignedCertificateTimestamp")}let r=e.getUint16();if(this.signature=new Uint8Array(e.getBlock(r)).buffer.slice(0),t!==47+n+r)throw new Error("Object's stream was not correct for SignedCertificateTimestamp")}}toSchema(){let e=this.toStream();return new Oa({data:e.stream.buffer})}toStream(){let e=new Yn;e.appendUint16(47+this.extensions.byteLength+this.signature.byteLength),e.appendChar(this.version),e.appendView(new Uint8Array(this.logID));let t=new ArrayBuffer(8),n=new Uint8Array(t),r=Js(this.timestamp.valueOf(),8);n.set(new Uint8Array(r),8-r.byteLength),e.appendView(n),e.appendUint16(this.extensions.byteLength),this.extensions.byteLength&&e.appendView(new Uint8Array(this.extensions));let i;switch(this.hashAlgorithm.toLowerCase()){case KN:i=0;break;case GN:i=1;break;case WN:i=2;break;case JN:i=3;break;case zN:i=4;break;case YN:i=5;break;case ZN:i=6;break;default:throw new Error(`Incorrect data for hashAlgorithm: ${this.hashAlgorithm}`)}e.appendChar(i);let a;switch(this.signatureAlgorithm.toLowerCase()){case QN:a=0;break;case XN:a=1;break;case ek:a=2;break;case tk:a=3;break;default:throw new Error(`Incorrect data for signatureAlgorithm: ${this.signatureAlgorithm}`)}return e.appendChar(a),e.appendUint16(this.signature.byteLength),e.appendView(new Uint8Array(this.signature)),e}toJSON(){return {version:this.version,logID:w1(this.logID),timestamp:this.timestamp,extensions:w1(this.extensions),hashAlgorithm:this.hashAlgorithm,signatureAlgorithm:this.signatureAlgorithm,signature:w1(this.signature)}}async verify(e,t,n=0,r=ve(!0)){let i=S1(uf(this.logID)),a=null,o=new Yn;for(let y of e)if(y.log_id===i){a=y.key;break}if(!a)throw new Error(`Public key not found for CT with logId: ${i}`);let c=Pa($c(a)),u=As.fromBER(c);o.appendChar(0),o.appendChar(0);let l=new ArrayBuffer(8),h=new Uint8Array(l),m=Js(this.timestamp.valueOf(),8);return h.set(new Uint8Array(m),8-m.byteLength),o.appendView(h),o.appendUint16(n),n===0&&o.appendUint24(t.byteLength),o.appendView(new Uint8Array(t)),o.appendUint16(this.extensions.byteLength),this.extensions.byteLength!==0&&o.appendView(new Uint8Array(this.extensions)),r.verifyWithPublicKey(o.buffer.slice(0,o.length),new L({valueHex:this.signature}),u,{algorithmId:p},"SHA-256")}};uw.CLASS_NAME="SignedCertificateTimestamp";var ry="timestamps",lw=class s extends O{constructor(e={}){super(),this.timestamps=d(e,ry,s.defaultValues(ry)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ry:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ry:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){var t;let n=d(e,"names",{});return (t=n.optional)!==null&&t!==void 0||(n.optional=!1),new L({name:n.blockName||"SignedCertificateTimestampList",optional:n.optional})}fromSchema(e){if(!(e instanceof L))throw new Error("Object's schema was not verified against input data for SignedCertificateTimestampList");let t=new Yn({stream:new Lt({buffer:e.valueBlock.valueHex})});if(t.getUint16()!==t.length)throw new Error("Object's schema was not verified against input data for SignedCertificateTimestampList");for(;t.length;)this.timestamps.push(new uw({stream:t}));}toSchema(){let e=new Yn,t=0,n=[];for(let r of this.timestamps){let i=r.toStream();n.push(i),t+=i.stream.buffer.byteLength;}e.appendUint16(t);for(let r of n)e.appendView(r.stream.view);return new L({valueHex:e.stream.buffer.slice(0)})}toJSON(){return {timestamps:Array.from(this.timestamps,e=>e.toJSON())}}};lw.CLASS_NAME="SignedCertificateTimestampList";var yd="attributes",F9=[yd],hw=class s extends O{constructor(e={}){super(),this.attributes=d(e,yd,s.defaultValues(yd)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case yd:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.attributes||p,value:nt.schema()})]})}fromSchema(e){V(e,F9);let t=R(e,e,s.schema({names:{attributes:yd}}));T.assertSchema(t,this.className),this.attributes=Array.from(t.result.attributes,n=>new nt({schema:n}));}toSchema(){return new b({value:Array.from(this.attributes,e=>e.toSchema())})}toJSON(){return {attributes:Array.from(this.attributes,e=>e.toJSON())}}};hw.CLASS_NAME="SubjectDirectoryAttributes";var _2=class s{static getItems(){return this.types||(this.types={},s.register(ok,"SubjectAltName",Tm),s.register(ck,"IssuerAltName",Tm),s.register(wA,"AuthorityKeyIdentifier",Bm),s.register(gA,"BasicConstraints",Om),s.register(c9,"MicrosoftCaVersion",tw),s.register(dk,"CertificatePolicies",Dm),s.register(s9,"CertificatePoliciesMicrosoft",Dm),s.register(o9,"MicrosoftCertTemplateV2",U2),s.register(fk,"CRLDistributionPoints",jm),s.register(yA,"FreshestCRL",jm),s.register(n9,"ExtKeyUsage",sw),s.register(lk,"CertificateIssuer",bt),s.register(bA,"AuthorityInfoAccess",Um),s.register(i9,"SubjectInfoAccess",Um),s.register(uk,"IssuingDistributionPoint",nw),s.register(hk,"NameConstraints",rw),s.register(pk,"PolicyConstraints",iw),s.register(mk,"PolicyMappings",aw),s.register(Z7,"PrivateKeyUsagePeriod",ow),s.register(u9,"QCStatements",cw),s.register(a9,"SignedCertificateTimestampList",lw),s.register(J7,"SubjectDirectoryAttributes",hw)),this.types}static fromBER(e,t){let n=ht(t);if(n.offset===-1)return null;let r=this.find(e);if(r)try{return new r.type({schema:n.result})}catch{let i=new r.type;return i.parsingError=`Incorrectly formatted value of extension ${r.name} (${e})`,i}return n.result}static find(e){return this.getItems()[e]||null}static register(e,t,n){this.getItems()[e]={name:t,type:n};}},wd="extnID",gi="critical",bd="extnValue",iy="parsedValue",K9=[wd,gi,bd],ds=class s extends O{get parsedValue(){if(this._parsedValue===void 0){let e=_2.fromBER(this.extnID,this.extnValue.valueBlock.valueHexView);this._parsedValue=e;}return this._parsedValue||void 0}set parsedValue(e){this._parsedValue=e;}constructor(e={}){super(),this.extnID=d(e,wd,s.defaultValues(wd)),this.critical=d(e,gi,s.defaultValues(gi)),bd in e?this.extnValue=new L({valueHex:e.extnValue}):this.extnValue=s.defaultValues(bd),iy in e&&(this.parsedValue=d(e,iy,s.defaultValues(iy))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case wd:return p;case gi:return !1;case bd:return new L;case iy:return {};default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.extnID||p}),new xs({name:t.critical||p,optional:!0}),new L({name:t.extnValue||p})]})}fromSchema(e){V(e,K9);let t=R(e,e,s.schema({names:{extnID:wd,critical:gi,extnValue:bd}}));T.assertSchema(t,this.className),this.extnID=t.result.extnID.valueBlock.toString(),gi in t.result&&(this.critical=t.result.critical.valueBlock.value),this.extnValue=t.result.extnValue;}toSchema(){let e=[];return e.push(new G({value:this.extnID})),this.critical!==s.defaultValues(gi)&&e.push(new xs({value:this.critical})),e.push(this.extnValue),new b({value:e})}toJSON(){let e={extnID:this.extnID,extnValue:this.extnValue.toJSON()};return this.critical!==s.defaultValues(gi)&&(e.critical=this.critical),this.parsedValue&&this.parsedValue.toJSON&&(e.parsedValue=this.parsedValue.toJSON()),e}};ds.CLASS_NAME="Extension";var Sd="extensions",G9=[Sd],ft=class s extends O{constructor(e={}){super(),this.extensions=d(e,Sd,s.defaultValues(Sd)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Sd:return [];default:return super.defaultValues(e)}}static schema(e={},t=!1){let n=d(e,"names",{});return new b({optional:t,name:n.blockName||p,value:[new fe({name:n.extensions||p,value:ds.schema(n.extension||{})})]})}fromSchema(e){V(e,G9);let t=R(e,e,s.schema({names:{extensions:Sd}}));T.assertSchema(t,this.className),this.extensions=Array.from(t.result.extensions,n=>new ds({schema:n}));}toSchema(){return new b({value:Array.from(this.extensions,e=>e.toSchema())})}toJSON(){return {extensions:this.extensions.map(e=>e.toJSON())}}};ft.CLASS_NAME="Extensions";var vd="issuer",xd="serialNumber",Qa="issuerUID",W9=[vd,xd,Qa],Ts=class s extends O{constructor(e={}){super(),this.issuer=d(e,vd,s.defaultValues(vd)),this.serialNumber=d(e,xd,s.defaultValues(xd)),Qa in e&&(this.issuerUID=d(e,Qa,s.defaultValues(Qa))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case vd:return new bt;case xd:return new k;case Qa:return new Ae;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[bt.schema(t.issuer||{}),new k({name:t.serialNumber||p}),new Ae({optional:!0,name:t.issuerUID||p})]})}fromSchema(e){V(e,W9);let t=R(e,e,s.schema({names:{issuer:{names:{blockName:vd}},serialNumber:xd,issuerUID:Qa}}));T.assertSchema(t,this.className),this.issuer=new bt({schema:t.result.issuer}),this.serialNumber=t.result.serialNumber,Qa in t.result&&(this.issuerUID=t.result.issuerUID);}toSchema(){let e=new b({value:[this.issuer.toSchema(),this.serialNumber]});return this.issuerUID&&e.valueBlock.value.push(this.issuerUID),e}toJSON(){let e={issuer:this.issuer.toJSON(),serialNumber:this.serialNumber.toJSON()};return this.issuerUID&&(e.issuerUID=this.issuerUID.toJSON()),e}};Ts.CLASS_NAME="IssuerSerial";var Ed="version",Xa="baseCertificateID",eo="subjectName",Ad="issuer",Id="signature",Cd="serialNumber",Nd="attrCertValidityPeriod",kd="attributes",to="issuerUniqueID",so="extensions",J9=[Ed,Xa,eo,Ad,Id,Cd,Nd,kd,to,so],xl=class s extends O{constructor(e={}){super(),this.version=d(e,Ed,s.defaultValues(Ed)),Xa in e&&(this.baseCertificateID=d(e,Xa,s.defaultValues(Xa))),eo in e&&(this.subjectName=d(e,eo,s.defaultValues(eo))),this.issuer=d(e,Ad,s.defaultValues(Ad)),this.signature=d(e,Id,s.defaultValues(Id)),this.serialNumber=d(e,Cd,s.defaultValues(Cd)),this.attrCertValidityPeriod=d(e,Nd,s.defaultValues(Nd)),this.attributes=d(e,kd,s.defaultValues(kd)),to in e&&(this.issuerUniqueID=d(e,to,s.defaultValues(to))),so in e&&(this.extensions=d(e,so,s.defaultValues(so))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ed:return 0;case Xa:return new Ts;case eo:return new bt;case Ad:return new bt;case Id:return new P;case Cd:return new k;case Nd:return new pr;case kd:return [];case to:return new Ae;case so:return new ft;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new k({name:t.version||p}),new We({value:[new A({name:t.baseCertificateID||p,idBlock:{tagClass:3,tagNumber:0},value:Ts.schema().valueBlock.value}),new A({name:t.subjectName||p,idBlock:{tagClass:3,tagNumber:1},value:bt.schema().valueBlock.value})]}),bt.schema({names:{blockName:t.issuer||p}}),P.schema(t.signature||{}),new k({name:t.serialNumber||p}),pr.schema(t.attrCertValidityPeriod||{}),new b({name:t.attributes||p,value:[new fe({value:nt.schema()})]}),new Ae({optional:!0,name:t.issuerUniqueID||p}),ft.schema(t.extensions||{},!0)]})}fromSchema(e){V(e,J9);let t=R(e,e,s.schema({names:{version:Ed,baseCertificateID:Xa,subjectName:eo,issuer:Ad,signature:{names:{blockName:Id}},serialNumber:Cd,attrCertValidityPeriod:{names:{blockName:Nd}},attributes:kd,issuerUniqueID:to,extensions:{names:{blockName:so}}}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,Xa in t.result&&(this.baseCertificateID=new Ts({schema:new b({value:t.result.baseCertificateID.valueBlock.value})})),eo in t.result&&(this.subjectName=new bt({schema:new b({value:t.result.subjectName.valueBlock.value})})),this.issuer=t.result.issuer,this.signature=new P({schema:t.result.signature}),this.serialNumber=t.result.serialNumber,this.attrCertValidityPeriod=new pr({schema:t.result.attrCertValidityPeriod}),this.attributes=Array.from(t.result.attributes.valueBlock.value,n=>new nt({schema:n})),to in t.result&&(this.issuerUniqueID=t.result.issuerUniqueID),so in t.result&&(this.extensions=new ft({schema:t.result.extensions}));}toSchema(){let e=new b({value:[new k({value:this.version})]});return this.baseCertificateID&&e.valueBlock.value.push(new A({idBlock:{tagClass:3,tagNumber:0},value:this.baseCertificateID.toSchema().valueBlock.value})),this.subjectName&&e.valueBlock.value.push(new A({idBlock:{tagClass:3,tagNumber:1},value:this.subjectName.toSchema().valueBlock.value})),e.valueBlock.value.push(this.issuer.toSchema()),e.valueBlock.value.push(this.signature.toSchema()),e.valueBlock.value.push(this.serialNumber),e.valueBlock.value.push(this.attrCertValidityPeriod.toSchema()),e.valueBlock.value.push(new b({value:Array.from(this.attributes,t=>t.toSchema())})),this.issuerUniqueID&&e.valueBlock.value.push(this.issuerUniqueID),this.extensions&&e.valueBlock.value.push(this.extensions.toSchema()),e}toJSON(){let e={version:this.version};return this.baseCertificateID&&(e.baseCertificateID=this.baseCertificateID.toJSON()),this.subjectName&&(e.subjectName=this.subjectName.toJSON()),e.issuer=this.issuer.toJSON(),e.signature=this.signature.toJSON(),e.serialNumber=this.serialNumber.toJSON(),e.attrCertValidityPeriod=this.attrCertValidityPeriod.toJSON(),e.attributes=Array.from(this.attributes,t=>t.toJSON()),this.issuerUniqueID&&(e.issuerUniqueID=this.issuerUniqueID.toJSON()),this.extensions&&(e.extensions=this.extensions.toJSON()),e}};xl.CLASS_NAME="AttributeCertificateInfoV1";var Pd="acinfo",Td="signatureAlgorithm",Bd="signatureValue",z9=[Pd,Bd,Td],Pl=class s extends O{constructor(e={}){super(),this.acinfo=d(e,Pd,s.defaultValues(Pd)),this.signatureAlgorithm=d(e,Td,s.defaultValues(Td)),this.signatureValue=d(e,Bd,s.defaultValues(Bd)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Pd:return new xl;case Td:return new P;case Bd:return new Ae;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[xl.schema(t.acinfo||{}),P.schema(t.signatureAlgorithm||{}),new Ae({name:t.signatureValue||p})]})}fromSchema(e){V(e,z9);let t=R(e,e,s.schema({names:{acinfo:{names:{blockName:Pd}},signatureAlgorithm:{names:{blockName:Td}},signatureValue:Bd}}));T.assertSchema(t,this.className),this.acinfo=new xl({schema:t.result.acinfo}),this.signatureAlgorithm=new P({schema:t.result.signatureAlgorithm}),this.signatureValue=t.result.signatureValue;}toSchema(){return new b({value:[this.acinfo.toSchema(),this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){return {acinfo:this.acinfo.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()}}};Pl.CLASS_NAME="AttributeCertificateV1";var Od="digestedObjectType",no="otherObjectTypeID",Rd="digestAlgorithm",Vd="objectDigest",Y9=[Od,no,Rd,Vd],gr=class s extends O{constructor(e={}){super(),this.digestedObjectType=d(e,Od,s.defaultValues(Od)),no in e&&(this.otherObjectTypeID=d(e,no,s.defaultValues(no))),this.digestAlgorithm=d(e,Rd,s.defaultValues(Rd)),this.objectDigest=d(e,Vd,s.defaultValues(Vd)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Od:return new pn;case no:return new G;case Rd:return new P;case Vd:return new Ae;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new pn({name:t.digestedObjectType||p}),new G({optional:!0,name:t.otherObjectTypeID||p}),P.schema(t.digestAlgorithm||{}),new Ae({name:t.objectDigest||p})]})}fromSchema(e){V(e,Y9);let t=R(e,e,s.schema({names:{digestedObjectType:Od,otherObjectTypeID:no,digestAlgorithm:{names:{blockName:Rd}},objectDigest:Vd}}));T.assertSchema(t,this.className),this.digestedObjectType=t.result.digestedObjectType,no in t.result&&(this.otherObjectTypeID=t.result.otherObjectTypeID),this.digestAlgorithm=new P({schema:t.result.digestAlgorithm}),this.objectDigest=t.result.objectDigest;}toSchema(){let e=new b({value:[this.digestedObjectType]});return this.otherObjectTypeID&&e.valueBlock.value.push(this.otherObjectTypeID),e.valueBlock.value.push(this.digestAlgorithm.toSchema()),e.valueBlock.value.push(this.objectDigest),e}toJSON(){let e={digestedObjectType:this.digestedObjectType.toJSON(),digestAlgorithm:this.digestAlgorithm.toJSON(),objectDigest:this.objectDigest.toJSON()};return this.otherObjectTypeID&&(e.otherObjectTypeID=this.otherObjectTypeID.toJSON()),e}};gr.CLASS_NAME="ObjectDigestInfo";var ro="issuerName",io="baseCertificateID",ao="objectDigestInfo",Z9=[ro,io,ao],Km=class s extends O{constructor(e={}){super(),ro in e&&(this.issuerName=d(e,ro,s.defaultValues(ro))),io in e&&(this.baseCertificateID=d(e,io,s.defaultValues(io))),ao in e&&(this.objectDigestInfo=d(e,ao,s.defaultValues(ao))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ro:return new bt;case io:return new Ts;case ao:return new gr;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[bt.schema({names:{blockName:t.issuerName}},!0),new A({optional:!0,name:t.baseCertificateID||p,idBlock:{tagClass:3,tagNumber:0},value:Ts.schema().valueBlock.value}),new A({optional:!0,name:t.objectDigestInfo||p,idBlock:{tagClass:3,tagNumber:1},value:gr.schema().valueBlock.value})]})}fromSchema(e){V(e,Z9);let t=R(e,e,s.schema({names:{issuerName:ro,baseCertificateID:io,objectDigestInfo:ao}}));T.assertSchema(t,this.className),ro in t.result&&(this.issuerName=new bt({schema:t.result.issuerName})),io in t.result&&(this.baseCertificateID=new Ts({schema:new b({value:t.result.baseCertificateID.valueBlock.value})})),ao in t.result&&(this.objectDigestInfo=new gr({schema:new b({value:t.result.objectDigestInfo.valueBlock.value})}));}toSchema(){let e=new b;return this.issuerName&&e.valueBlock.value.push(this.issuerName.toSchema()),this.baseCertificateID&&e.valueBlock.value.push(new A({idBlock:{tagClass:3,tagNumber:0},value:this.baseCertificateID.toSchema().valueBlock.value})),this.objectDigestInfo&&e.valueBlock.value.push(new A({idBlock:{tagClass:3,tagNumber:1},value:this.objectDigestInfo.toSchema().valueBlock.value})),e}toJSON(){let e={};return this.issuerName&&(e.issuerName=this.issuerName.toJSON()),this.baseCertificateID&&(e.baseCertificateID=this.baseCertificateID.toJSON()),this.objectDigestInfo&&(e.objectDigestInfo=this.objectDigestInfo.toJSON()),e}};Km.CLASS_NAME="V2Form";var oo="baseCertificateID",co="entityName",uo="objectDigestInfo",Q9=[oo,co,uo],El=class s extends O{constructor(e={}){super(),oo in e&&(this.baseCertificateID=d(e,oo,s.defaultValues(oo))),co in e&&(this.entityName=d(e,co,s.defaultValues(co))),uo in e&&(this.objectDigestInfo=d(e,uo,s.defaultValues(uo))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case oo:return new Ts;case co:return new bt;case uo:return new gr;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new A({optional:!0,name:t.baseCertificateID||p,idBlock:{tagClass:3,tagNumber:0},value:Ts.schema().valueBlock.value}),new A({optional:!0,name:t.entityName||p,idBlock:{tagClass:3,tagNumber:1},value:bt.schema().valueBlock.value}),new A({optional:!0,name:t.objectDigestInfo||p,idBlock:{tagClass:3,tagNumber:2},value:gr.schema().valueBlock.value})]})}fromSchema(e){V(e,Q9);let t=R(e,e,s.schema({names:{baseCertificateID:oo,entityName:co,objectDigestInfo:uo}}));T.assertSchema(t,this.className),oo in t.result&&(this.baseCertificateID=new Ts({schema:new b({value:t.result.baseCertificateID.valueBlock.value})})),co in t.result&&(this.entityName=new bt({schema:new b({value:t.result.entityName.valueBlock.value})})),uo in t.result&&(this.objectDigestInfo=new gr({schema:new b({value:t.result.objectDigestInfo.valueBlock.value})}));}toSchema(){let e=new b;return this.baseCertificateID&&e.valueBlock.value.push(new A({idBlock:{tagClass:3,tagNumber:0},value:this.baseCertificateID.toSchema().valueBlock.value})),this.entityName&&e.valueBlock.value.push(new A({idBlock:{tagClass:3,tagNumber:1},value:this.entityName.toSchema().valueBlock.value})),this.objectDigestInfo&&e.valueBlock.value.push(new A({idBlock:{tagClass:3,tagNumber:2},value:this.objectDigestInfo.toSchema().valueBlock.value})),e}toJSON(){let e={};return this.baseCertificateID&&(e.baseCertificateID=this.baseCertificateID.toJSON()),this.entityName&&(e.entityName=this.entityName.toJSON()),this.objectDigestInfo&&(e.objectDigestInfo=this.objectDigestInfo.toJSON()),e}};El.CLASS_NAME="Holder";var Dd="version",Ld="holder",jd="issuer",Ud="signature",Hd="serialNumber",_d="attrCertValidityPeriod",Md="attributes",lo="issuerUniqueID",ho="extensions",X9=[Dd,Ld,jd,Ud,Hd,_d,Md,lo,ho],Al=class s extends O{constructor(e={}){super(),this.version=d(e,Dd,s.defaultValues(Dd)),this.holder=d(e,Ld,s.defaultValues(Ld)),this.issuer=d(e,jd,s.defaultValues(jd)),this.signature=d(e,Ud,s.defaultValues(Ud)),this.serialNumber=d(e,Hd,s.defaultValues(Hd)),this.attrCertValidityPeriod=d(e,_d,s.defaultValues(_d)),this.attributes=d(e,Md,s.defaultValues(Md)),lo in e&&(this.issuerUniqueID=d(e,lo,s.defaultValues(lo))),ho in e&&(this.extensions=d(e,ho,s.defaultValues(ho))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Dd:return 1;case Ld:return new El;case jd:return {};case Ud:return new P;case Hd:return new k;case _d:return new pr;case Md:return [];case lo:return new Ae;case ho:return new ft;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new k({name:t.version||p}),El.schema(t.holder||{}),new We({value:[bt.schema({names:{blockName:t.issuer||p}}),new A({name:t.issuer||p,idBlock:{tagClass:3,tagNumber:0},value:Km.schema().valueBlock.value})]}),P.schema(t.signature||{}),new k({name:t.serialNumber||p}),pr.schema(t.attrCertValidityPeriod||{}),new b({name:t.attributes||p,value:[new fe({value:nt.schema()})]}),new Ae({optional:!0,name:t.issuerUniqueID||p}),ft.schema(t.extensions||{},!0)]})}fromSchema(e){V(e,X9);let t=R(e,e,s.schema({names:{version:Dd,holder:{names:{blockName:Ld}},issuer:jd,signature:{names:{blockName:Ud}},serialNumber:Hd,attrCertValidityPeriod:{names:{blockName:_d}},attributes:Md,issuerUniqueID:lo,extensions:{names:{blockName:ho}}}}));switch(T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.holder=new El({schema:t.result.holder}),t.result.issuer.idBlock.tagClass){case 3:this.issuer=new Km({schema:new b({value:t.result.issuer.valueBlock.value})});break;case 1:default:throw new Error("Incorrect value for 'issuer' in AttributeCertificateInfoV2")}this.signature=new P({schema:t.result.signature}),this.serialNumber=t.result.serialNumber,this.attrCertValidityPeriod=new pr({schema:t.result.attrCertValidityPeriod}),this.attributes=Array.from(t.result.attributes.valueBlock.value,n=>new nt({schema:n})),lo in t.result&&(this.issuerUniqueID=t.result.issuerUniqueID),ho in t.result&&(this.extensions=new ft({schema:t.result.extensions}));}toSchema(){let e=new b({value:[new k({value:this.version}),this.holder.toSchema(),new A({idBlock:{tagClass:3,tagNumber:0},value:this.issuer.toSchema().valueBlock.value}),this.signature.toSchema(),this.serialNumber,this.attrCertValidityPeriod.toSchema(),new b({value:Array.from(this.attributes,t=>t.toSchema())})]});return this.issuerUniqueID&&e.valueBlock.value.push(this.issuerUniqueID),this.extensions&&e.valueBlock.value.push(this.extensions.toSchema()),e}toJSON(){let e={version:this.version,holder:this.holder.toJSON(),issuer:this.issuer.toJSON(),signature:this.signature.toJSON(),serialNumber:this.serialNumber.toJSON(),attrCertValidityPeriod:this.attrCertValidityPeriod.toJSON(),attributes:Array.from(this.attributes,t=>t.toJSON())};return this.issuerUniqueID&&(e.issuerUniqueID=this.issuerUniqueID.toJSON()),this.extensions&&(e.extensions=this.extensions.toJSON()),e}};Al.CLASS_NAME="AttributeCertificateInfoV2";var $d="acinfo",qd="signatureAlgorithm",Fd="signatureValue",eD=[$d,qd,Fd],bn=class s extends O{constructor(e={}){super(),this.acinfo=d(e,$d,s.defaultValues($d)),this.signatureAlgorithm=d(e,qd,s.defaultValues(qd)),this.signatureValue=d(e,Fd,s.defaultValues(Fd)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case $d:return new Al;case qd:return new P;case Fd:return new Ae;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[Al.schema(t.acinfo||{}),P.schema(t.signatureAlgorithm||{}),new Ae({name:t.signatureValue||p})]})}fromSchema(e){V(e,eD);let t=R(e,e,s.schema({names:{acinfo:{names:{blockName:$d}},signatureAlgorithm:{names:{blockName:qd}},signatureValue:Fd}}));T.assertSchema(t,this.className),this.acinfo=new Al({schema:t.result.acinfo}),this.signatureAlgorithm=new P({schema:t.result.signatureAlgorithm}),this.signatureValue=t.result.signatureValue;}toSchema(){return new b({value:[this.acinfo.toSchema(),this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){return {acinfo:this.acinfo.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()}}};bn.CLASS_NAME="AttributeCertificateV2";var fo="contentType",hu="content",tD=[fo,hu],tt=class s extends O{constructor(e={}){super(),this.contentType=d(e,fo,s.defaultValues(fo)),this.content=d(e,hu,s.defaultValues(hu)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case fo:return p;case hu:return new ue;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case fo:return typeof t=="string"&&t===this.defaultValues(fo);case hu:return t instanceof ue;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return "optional"in t||(t.optional=!1),new b({name:t.blockName||"ContentInfo",optional:t.optional,value:[new G({name:t.contentType||fo}),new A({idBlock:{tagClass:3,tagNumber:0},value:[new ue({name:t.content||hu})]})]})}fromSchema(e){V(e,tD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.contentType=t.result.contentType.valueBlock.toString(),this.content=t.result.content;}toSchema(){return new b({value:[new G({value:this.contentType}),new A({idBlock:{tagClass:3,tagNumber:0},value:[this.content]})]})}toJSON(){let e={contentType:this.contentType};return this.content instanceof ue||(e.content=this.content.toJSON()),e}};tt.CLASS_NAME="ContentInfo";tt.DATA=SA;tt.SIGNED_DATA=gk;tt.ENVELOPED_DATA=yk;tt.ENCRYPTED_DATA=wk;var w2="type",b2="value",M2="utcTimeName",$2="generalTimeName",sD=[M2,$2],sk;(function(s){s[s.UTCTime=0]="UTCTime",s[s.GeneralizedTime=1]="GeneralizedTime",s[s.empty=2]="empty";})(sk||(sk={}));var St=class s extends O{constructor(e={}){super(),this.type=d(e,w2,s.defaultValues(w2)),this.value=d(e,b2,s.defaultValues(b2)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case w2:return 0;case b2:return new Date(0,0,0);default:return super.defaultValues(e)}}static schema(e={},t=!1){let n=d(e,"names",{});return new We({optional:t,value:[new Wn({name:n.utcTimeName||p}),new Ge({name:n.generalTimeName||p})]})}fromSchema(e){V(e,sD);let t=R(e,e,s.schema({names:{utcTimeName:M2,generalTimeName:$2}}));T.assertSchema(t,this.className),M2 in t.result&&(this.type=0,this.value=t.result.utcTimeName.toDate()),$2 in t.result&&(this.type=1,this.value=t.result.generalTimeName.toDate());}toSchema(){return this.type===0?new Wn({valueDate:this.value}):this.type===1?new Ge({valueDate:this.value}):{}}toJSON(){return {type:this.type,value:this.value}}};St.CLASS_NAME="Time";var S2="tbs",yi="version",Iy="serialNumber",Cy="signature",Ny="issuer",ky="notBefore",Py="notAfter",Ty="subject",By="subjectPublicKeyInfo",Kd="issuerUniqueID",Gd="subjectUniqueID",Wd="extensions",Jd="signatureAlgorithm",zd="signatureValue",Is="tbsCertificate",fw=`${Is}.${yi}`,xA=`${Is}.${Iy}`,EA=`${Is}.${Cy}`,AA=`${Is}.${Ny}`,dw=`${Is}.${ky}`,mw=`${Is}.${Py}`,IA=`${Is}.${Ty}`,CA=`${Is}.${By}`,pw=`${Is}.${Kd}`,gw=`${Is}.${Gd}`,Nm=`${Is}.${Wd}`,nD=[Is,fw,xA,EA,AA,dw,mw,IA,CA,pw,gw,Nm,Jd,zd];function rD(s={}){let e=d(s,"names",{});return new b({name:e.blockName||Is,value:[new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new k({name:e.tbsCertificateVersion||fw})]}),new k({name:e.tbsCertificateSerialNumber||xA}),P.schema(e.signature||{names:{blockName:EA}}),Je.schema(e.issuer||{names:{blockName:AA}}),new b({name:e.tbsCertificateValidity||"tbsCertificate.validity",value:[St.schema(e.notBefore||{names:{utcTimeName:dw,generalTimeName:dw}}),St.schema(e.notAfter||{names:{utcTimeName:mw,generalTimeName:mw}})]}),Je.schema(e.subject||{names:{blockName:IA}}),As.schema(e.subjectPublicKeyInfo||{names:{blockName:CA}}),new ie({name:e.tbsCertificateIssuerUniqueID||pw,optional:!0,idBlock:{tagClass:3,tagNumber:1}}),new ie({name:e.tbsCertificateSubjectUniqueID||gw,optional:!0,idBlock:{tagClass:3,tagNumber:2}}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:3},value:[ft.schema(e.extensions||{names:{blockName:Nm}})]})]})}var jt=class s extends O{get tbs(){return re.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e);}constructor(e={}){super(),this.tbsView=new Uint8Array(d(e,S2,s.defaultValues(S2))),this.version=d(e,yi,s.defaultValues(yi)),this.serialNumber=d(e,Iy,s.defaultValues(Iy)),this.signature=d(e,Cy,s.defaultValues(Cy)),this.issuer=d(e,Ny,s.defaultValues(Ny)),this.notBefore=d(e,ky,s.defaultValues(ky)),this.notAfter=d(e,Py,s.defaultValues(Py)),this.subject=d(e,Ty,s.defaultValues(Ty)),this.subjectPublicKeyInfo=d(e,By,s.defaultValues(By)),Kd in e&&(this.issuerUniqueID=d(e,Kd,s.defaultValues(Kd))),Gd in e&&(this.subjectUniqueID=d(e,Gd,s.defaultValues(Gd))),Wd in e&&(this.extensions=d(e,Wd,s.defaultValues(Wd))),this.signatureAlgorithm=d(e,Jd,s.defaultValues(Jd)),this.signatureValue=d(e,zd,s.defaultValues(zd)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case S2:return ut;case yi:return 0;case Iy:return new k;case Cy:return new P;case Ny:return new Je;case ky:return new St;case Py:return new St;case Ty:return new Je;case By:return new As;case Kd:return ut;case Gd:return ut;case Wd:return [];case Jd:return new P;case zd:return new Ae;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[rD(t.tbsCertificate),P.schema(t.signatureAlgorithm||{names:{blockName:Jd}}),new Ae({name:t.signatureValue||zd})]})}fromSchema(e){V(e,nD);let t=R(e,e,s.schema({names:{tbsCertificate:{names:{extensions:{names:{extensions:Nm}}}}}}));T.assertSchema(t,this.className),this.tbsView=t.result.tbsCertificate.valueBeforeDecodeView,fw in t.result&&(this.version=t.result[fw].valueBlock.valueDec),this.serialNumber=t.result[xA],this.signature=new P({schema:t.result[EA]}),this.issuer=new Je({schema:t.result[AA]}),this.notBefore=new St({schema:t.result[dw]}),this.notAfter=new St({schema:t.result[mw]}),this.subject=new Je({schema:t.result[IA]}),this.subjectPublicKeyInfo=new As({schema:t.result[CA]}),pw in t.result&&(this.issuerUniqueID=t.result[pw].valueBlock.valueHex),gw in t.result&&(this.subjectUniqueID=t.result[gw].valueBlock.valueHex),Nm in t.result&&(this.extensions=Array.from(t.result[Nm],n=>new ds({schema:n}))),this.signatureAlgorithm=new P({schema:t.result.signatureAlgorithm}),this.signatureValue=t.result.signatureValue;}encodeTBS(){let e=[];return yi in this&&this.version!==s.defaultValues(yi)&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new k({value:this.version})]})),e.push(this.serialNumber),e.push(this.signature.toSchema()),e.push(this.issuer.toSchema()),e.push(new b({value:[this.notBefore.toSchema(),this.notAfter.toSchema()]})),e.push(this.subject.toSchema()),e.push(this.subjectPublicKeyInfo.toSchema()),this.issuerUniqueID&&e.push(new ie({optional:!0,idBlock:{tagClass:3,tagNumber:1},valueHex:this.issuerUniqueID})),this.subjectUniqueID&&e.push(new ie({optional:!0,idBlock:{tagClass:3,tagNumber:2},valueHex:this.subjectUniqueID})),this.extensions&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:3},value:[new b({value:Array.from(this.extensions,t=>t.toSchema())})]})),new b({value:e})}toSchema(e=!1){let t;if(e===!1){if(!this.tbsView.byteLength)return s.schema().value[0];let n=ht(this.tbsView);T.assert(n,"TBS Certificate"),t=n.result;}else t=this.encodeTBS();return new b({value:[t,this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){let e={tbs:he.ToHex(this.tbsView),version:this.version,serialNumber:this.serialNumber.toJSON(),signature:this.signature.toJSON(),issuer:this.issuer.toJSON(),notBefore:this.notBefore.toJSON(),notAfter:this.notAfter.toJSON(),subject:this.subject.toJSON(),subjectPublicKeyInfo:this.subjectPublicKeyInfo.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()};return yi in this&&this.version!==s.defaultValues(yi)&&(e.version=this.version),this.issuerUniqueID&&(e.issuerUniqueID=he.ToHex(this.issuerUniqueID)),this.subjectUniqueID&&(e.subjectUniqueID=he.ToHex(this.subjectUniqueID)),this.extensions&&(e.extensions=Array.from(this.extensions,t=>t.toJSON())),e}async getPublicKey(e,t=ve(!0)){return t.getPublicKey(this.subjectPublicKeyInfo,this.signatureAlgorithm,e)}async getKeyHash(e="SHA-1",t=ve(!0)){return t.digest({name:e},this.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView)}async sign(e,t="SHA-1",n=ve(!0)){if(!e)throw new Error("Need to provide a private key for signing");let r=await n.getSignatureParameters(e,t),i=r.parameters;this.signature=r.signatureAlgorithm,this.signatureAlgorithm=r.signatureAlgorithm,this.tbsView=new Uint8Array(this.encodeTBS().toBER());let a=await n.signWithPrivateKey(this.tbsView,e,i);this.signatureValue=new Ae({valueHex:a});}async verify(e,t=ve(!0)){let n;if(e?n=e.subjectPublicKeyInfo:this.issuer.isEqual(this.subject)&&(n=this.subjectPublicKeyInfo),!(n instanceof As))throw new Error("Please provide issuer certificate as a parameter");return t.verifyWithPublicKey(this.tbsView,this.signatureValue,n,this.signatureAlgorithm)}};jt.CLASS_NAME="Certificate";function Ak(s,e=null){if(e&&s.issuer.isEqual(e.issuer)&&s.serialNumber.isEqual(e.serialNumber))return null;let t=!1;if(s.extensions){for(let n of s.extensions)if(n.extnID===gA&&n.parsedValue instanceof Om&&n.parsedValue.cA){t=!0;break}}return t?s:null}var fu="certId",du="certValue",Wc="parsedValue",iD=[fu,du],yw=class s extends O{constructor(e={}){super(),this.certId=d(e,fu,s.defaultValues(fu)),this.certValue=d(e,du,s.defaultValues(du)),Wc in e&&(this.parsedValue=d(e,Wc,s.defaultValues(Wc))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case fu:return p;case du:return new ue;case Wc:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case fu:return t===p;case du:return t instanceof ue;case Wc:return t instanceof Object&&Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.id||"id"}),new A({idBlock:{tagClass:3,tagNumber:0},value:[new ue({name:t.value||"value"})]})]})}fromSchema(e){V(e,iD);let t=R(e,e,s.schema({names:{id:fu,value:du}}));T.assertSchema(t,this.className),this.certId=t.result.certId.valueBlock.toString(),this.certValue=t.result.certValue;let n=this.certValue.valueBlock.valueHexView;switch(this.certId){case jN:try{this.parsedValue=jt.fromBER(n);}catch{bn.fromBER(n);}break;case UN:this.parsedValue=bn.fromBER(n);break;case h9:default:throw new Error(`Incorrect CERT_ID value in CertBag: ${this.certId}`)}}toSchema(){return Wc in this&&("acinfo"in this.parsedValue?this.certId=UN:this.certId=jN,this.certValue=new L({valueHex:this.parsedValue.toSchema().toBER(!1)})),new b({value:[new G({value:this.certId}),new A({idBlock:{tagClass:3,tagNumber:0},value:["toSchema"in this.certValue?this.certValue.toSchema():this.certValue]})]})}toJSON(){return {certId:this.certId,certValue:this.certValue.toJSON()}}};yw.CLASS_NAME="CertBag";var Yd="userCertificate",mu="revocationDate",mo="crlEntryExtensions",aD=[Yd,mu,mo],ww=class s extends O{constructor(e={}){super(),this.userCertificate=d(e,Yd,s.defaultValues(Yd)),this.revocationDate=d(e,mu,s.defaultValues(mu)),mo in e&&(this.crlEntryExtensions=d(e,mo,s.defaultValues(mo))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Yd:return new k;case mu:return new St;case mo:return new ft;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new k({name:t.userCertificate||Yd}),St.schema({names:{utcTimeName:t.revocationDate||mu,generalTimeName:t.revocationDate||mu}}),ft.schema({names:{blockName:t.crlEntryExtensions||mo}},!0)]})}fromSchema(e){V(e,aD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.userCertificate=t.result.userCertificate,this.revocationDate=new St({schema:t.result.revocationDate}),mo in t.result&&(this.crlEntryExtensions=new ft({schema:t.result.crlEntryExtensions}));}toSchema(){let e=[this.userCertificate,this.revocationDate.toSchema()];return this.crlEntryExtensions&&e.push(this.crlEntryExtensions.toSchema()),new b({value:e})}toJSON(){let e={userCertificate:this.userCertificate.toJSON(),revocationDate:this.revocationDate.toJSON()};return this.crlEntryExtensions&&(e.crlEntryExtensions=this.crlEntryExtensions.toJSON()),e}};ww.CLASS_NAME="RevokedCertificate";var v2="tbs",Ef="version",x2="signature",E2="issuer",A2="thisUpdate",ay="nextUpdate",oy="revokedCertificates",cy="crlExtensions",Zd="signatureAlgorithm",Qd="signatureValue",br="tbsCertList",bw=`${br}.version`,NA=`${br}.signature`,kA=`${br}.issuer`,Sw=`${br}.thisUpdate`,Gm=`${br}.nextUpdate`,vw=`${br}.revokedCertificates`,xw=`${br}.extensions`,oD=[br,bw,NA,kA,Sw,Gm,vw,xw,Zd,Qd];function cD(s={}){let e=d(s,"names",{});return new b({name:e.blockName||br,value:[new k({optional:!0,name:e.tbsCertListVersion||bw,value:2}),P.schema(e.signature||{names:{blockName:NA}}),Je.schema(e.issuer||{names:{blockName:kA}}),St.schema(e.tbsCertListThisUpdate||{names:{utcTimeName:Sw,generalTimeName:Sw}}),St.schema(e.tbsCertListNextUpdate||{names:{utcTimeName:Gm,generalTimeName:Gm}},!0),new b({optional:!0,value:[new fe({name:e.tbsCertListRevokedCertificates||vw,value:new b({value:[new k,St.schema(),ft.schema({},!0)]})})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[ft.schema(e.crlExtensions||{names:{blockName:xw}})]})]})}var uD=[wA,ck,Q7,X7,uk,yA,bA,e9,t9,lk],Zo=class s extends O{get tbs(){return re.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e);}constructor(e={}){super(),this.tbsView=new Uint8Array(d(e,v2,s.defaultValues(v2))),this.version=d(e,Ef,s.defaultValues(Ef)),this.signature=d(e,x2,s.defaultValues(x2)),this.issuer=d(e,E2,s.defaultValues(E2)),this.thisUpdate=d(e,A2,s.defaultValues(A2)),ay in e&&(this.nextUpdate=d(e,ay,s.defaultValues(ay))),oy in e&&(this.revokedCertificates=d(e,oy,s.defaultValues(oy))),cy in e&&(this.crlExtensions=d(e,cy,s.defaultValues(cy))),this.signatureAlgorithm=d(e,Zd,s.defaultValues(Zd)),this.signatureValue=d(e,Qd,s.defaultValues(Qd)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case v2:return ut;case Ef:return 0;case x2:return new P;case E2:return new Je;case A2:return new St;case ay:return new St;case oy:return [];case cy:return new ft;case Zd:return new P;case Qd:return new Ae;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||"CertificateList",value:[cD(e),P.schema(t.signatureAlgorithm||{names:{blockName:Zd}}),new Ae({name:t.signatureValue||Qd})]})}fromSchema(e){V(e,oD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.tbsView=t.result.tbsCertList.valueBeforeDecodeView,bw in t.result&&(this.version=t.result[bw].valueBlock.valueDec),this.signature=new P({schema:t.result[NA]}),this.issuer=new Je({schema:t.result[kA]}),this.thisUpdate=new St({schema:t.result[Sw]}),Gm in t.result&&(this.nextUpdate=new St({schema:t.result[Gm]})),vw in t.result&&(this.revokedCertificates=Array.from(t.result[vw],n=>new ww({schema:n}))),xw in t.result&&(this.crlExtensions=new ft({schema:t.result[xw]})),this.signatureAlgorithm=new P({schema:t.result.signatureAlgorithm}),this.signatureValue=t.result.signatureValue;}encodeTBS(){let e=[];return this.version!==s.defaultValues(Ef)&&e.push(new k({value:this.version})),e.push(this.signature.toSchema()),e.push(this.issuer.toSchema()),e.push(this.thisUpdate.toSchema()),this.nextUpdate&&e.push(this.nextUpdate.toSchema()),this.revokedCertificates&&e.push(new b({value:Array.from(this.revokedCertificates,t=>t.toSchema())})),this.crlExtensions&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[this.crlExtensions.toSchema()]})),new b({value:e})}toSchema(e=!1){let t;if(e)t=this.encodeTBS();else {if(!this.tbsView.byteLength)return s.schema();let n=ht(this.tbsView);T.assert(n,"TBS Certificate Revocation List"),t=n.result;}return new b({value:[t,this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){let e={tbs:he.ToHex(this.tbsView),version:this.version,signature:this.signature.toJSON(),issuer:this.issuer.toJSON(),thisUpdate:this.thisUpdate.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()};return this.version!==s.defaultValues(Ef)&&(e.version=this.version),this.nextUpdate&&(e.nextUpdate=this.nextUpdate.toJSON()),this.revokedCertificates&&(e.revokedCertificates=Array.from(this.revokedCertificates,t=>t.toJSON())),this.crlExtensions&&(e.crlExtensions=this.crlExtensions.toJSON()),e}isCertificateRevoked(e){if(!this.issuer.isEqual(e.issuer)||!this.revokedCertificates)return !1;for(let t of this.revokedCertificates)if(t.userCertificate.isEqual(e.serialNumber))return !0;return !1}async sign(e,t="SHA-1",n=ve(!0)){if(!e)throw new Error("Need to provide a private key for signing");let r=await n.getSignatureParameters(e,t),{parameters:i}=r;this.signature=r.signatureAlgorithm,this.signatureAlgorithm=r.signatureAlgorithm,this.tbsView=new Uint8Array(this.encodeTBS().toBER());let a=await n.signWithPrivateKey(this.tbsView,e,i);this.signatureValue=new Ae({valueHex:a});}async verify(e={},t=ve(!0)){let n;if(e.issuerCertificate&&(n=e.issuerCertificate.subjectPublicKeyInfo,!this.issuer.isEqual(e.issuerCertificate.subject)))return !1;if(e.publicKeyInfo&&(n=e.publicKeyInfo),!n)throw new Error("Issuer's certificate must be provided as an input parameter");if(this.crlExtensions){for(let r of this.crlExtensions.extensions)if(r.critical&&!uD.includes(r.extnID))return !1}return t.verifyWithPublicKey(this.tbsView,this.signatureValue,n,this.signatureAlgorithm)}};Zo.CLASS_NAME="CertificateRevocationList";var pu="crlId",gu="crlValue",Af="parsedValue",lD=[pu,gu],Ew=class s extends O{constructor(e={}){super(),this.crlId=d(e,pu,s.defaultValues(pu)),this.crlValue=d(e,gu,s.defaultValues(gu)),Af in e&&(this.parsedValue=d(e,Af,s.defaultValues(Af))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case pu:return p;case gu:return new ue;case Af:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case pu:return t===p;case gu:return t instanceof ue;case Af:return t instanceof Object&&Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.id||"id"}),new A({idBlock:{tagClass:3,tagNumber:0},value:[new ue({name:t.value||"value"})]})]})}fromSchema(e){V(e,lD);let t=R(e,e,s.schema({names:{id:pu,value:gu}}));switch(T.assertSchema(t,this.className),this.crlId=t.result.crlId.valueBlock.toString(),this.crlValue=t.result.crlValue,this.crlId){case HN:this.parsedValue=Zo.fromBER(this.certValue.valueBlock.valueHex);break;default:throw new Error(`Incorrect CRL_ID value in CRLBag: ${this.crlId}`)}}toSchema(){return this.parsedValue&&(this.crlId=HN,this.crlValue=new L({valueHex:this.parsedValue.toSchema().toBER(!1)})),new b({value:[new G({value:this.crlId}),new A({idBlock:{tagClass:3,tagNumber:0},value:[this.crlValue.toSchema()]})]})}toJSON(){return {crlId:this.crlId,crlValue:this.crlValue.toJSON()}}};Ew.CLASS_NAME="CRLBag";var yu="version",wu="encryptedContentInfo",wi="unprotectedAttrs",hD=[yu,wu,wi],Qo=class s extends O{constructor(e={}){super(),this.version=d(e,yu,s.defaultValues(yu)),this.encryptedContentInfo=d(e,wu,s.defaultValues(wu)),wi in e&&(this.unprotectedAttrs=d(e,wi,s.defaultValues(wi))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case yu:return 0;case wu:return new kt;case wi:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case yu:return t===0;case wu:return kt.compareWithDefault("contentType",t.contentType)&&kt.compareWithDefault("contentEncryptionAlgorithm",t.contentEncryptionAlgorithm)&&kt.compareWithDefault("encryptedContent",t.encryptedContent);case wi:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new k({name:t.version||p}),kt.schema(t.encryptedContentInfo||{}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new fe({name:t.unprotectedAttrs||p,value:nt.schema()})]})]})}fromSchema(e){V(e,hD);let t=R(e,e,s.schema({names:{version:yu,encryptedContentInfo:{names:{blockName:wu}},unprotectedAttrs:wi}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.encryptedContentInfo=new kt({schema:t.result.encryptedContentInfo}),wi in t.result&&(this.unprotectedAttrs=Array.from(t.result.unprotectedAttrs,n=>new nt({schema:n})));}toSchema(){let e=[];return e.push(new k({value:this.version})),e.push(this.encryptedContentInfo.toSchema()),this.unprotectedAttrs&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.unprotectedAttrs,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={version:this.version,encryptedContentInfo:this.encryptedContentInfo.toJSON()};return this.unprotectedAttrs&&(e.unprotectedAttrs=Array.from(this.unprotectedAttrs,t=>t.toJSON())),e}async encrypt(e,t=ve(!0)){$e.assert(e,"parameters","object");let n={...e,contentType:"1.2.840.113549.1.7.1"};this.encryptedContentInfo=await t.encryptEncryptedContentInfo(n);}async decrypt(e,t=ve(!0)){$e.assert(e,"parameters","object");let n={...e,encryptedContentInfo:this.encryptedContentInfo};return t.decryptEncryptedContentInfo(n)}};Qo.CLASS_NAME="EncryptedData";var po="encryptionAlgorithm",bi="encryptedData",If="parsedValue",fD=[po,bi],Aw=class s extends O{constructor(e={}){super(),this.encryptionAlgorithm=d(e,po,s.defaultValues(po)),this.encryptedData=d(e,bi,s.defaultValues(bi)),If in e&&(this.parsedValue=d(e,If,s.defaultValues(If))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case po:return new P;case bi:return new L;case If:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case po:return P.compareWithDefault("algorithmId",t.algorithmId)&&!("algorithmParams"in t);case bi:return t.isEqual(s.defaultValues(e));case If:return t instanceof Object&&Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.encryptionAlgorithm||{names:{blockName:po}}),new We({value:[new L({name:t.encryptedData||bi}),new L({idBlock:{isConstructed:!0},name:t.encryptedData||bi})]})]})}fromSchema(e){V(e,fD);let t=R(e,e,s.schema({names:{encryptionAlgorithm:{names:{blockName:po}},encryptedData:bi}}));T.assertSchema(t,this.className),this.encryptionAlgorithm=new P({schema:t.result.encryptionAlgorithm}),this.encryptedData=t.result.encryptedData;}toSchema(){return new b({value:[this.encryptionAlgorithm.toSchema(),this.encryptedData]})}toJSON(){return {encryptionAlgorithm:this.encryptionAlgorithm.toJSON(),encryptedData:this.encryptedData.toJSON()}}async parseInternalValues(e,t=ve(!0)){let r=await new Qo({encryptedContentInfo:new kt({contentEncryptionAlgorithm:this.encryptionAlgorithm,encryptedContent:this.encryptedData})}).decrypt(e,t);this.parsedValue=Yo.fromBER(r);}async makeInternalValues(e,t=ve(!0)){if(!this.parsedValue)throw new Error('Please initialize "parsedValue" first');let n=new Qo,r={...e,contentToEncrypt:this.parsedValue.toSchema().toBER(!1)};if(await n.encrypt(r,t),!n.encryptedContentInfo.encryptedContent)throw new Error("The filed `encryptedContent` in EncryptedContentInfo is empty");this.encryptionAlgorithm=n.encryptedContentInfo.contentEncryptionAlgorithm,this.encryptedData=n.encryptedContentInfo.encryptedContent;}};Aw.CLASS_NAME="PKCS8ShroudedKeyBag";var bu="secretTypeId",Su="secretValue",dD=[bu,Su],Iw=class s extends O{constructor(e={}){super(),this.secretTypeId=d(e,bu,s.defaultValues(bu)),this.secretValue=d(e,Su,s.defaultValues(Su)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case bu:return p;case Su:return new ue;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case bu:return t===p;case Su:return t instanceof ue;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.id||"id"}),new A({idBlock:{tagClass:3,tagNumber:0},value:[new ue({name:t.value||"value"})]})]})}fromSchema(e){V(e,dD);let t=R(e,e,s.schema({names:{id:bu,value:Su}}));T.assertSchema(t,this.className),this.secretTypeId=t.result.secretTypeId.valueBlock.toString(),this.secretValue=t.result.secretValue;}toSchema(){return new b({value:[new G({value:this.secretTypeId}),new A({idBlock:{tagClass:3,tagNumber:0},value:[this.secretValue.toSchema()]})]})}toJSON(){return {secretTypeId:this.secretTypeId,secretValue:this.secretValue.toJSON()}}};Iw.CLASS_NAME="SecretBag";var q2=class s{static getItems(){return this.items||(this.items={},s.register("1.2.840.113549.1.12.10.1.1",Yo),s.register("1.2.840.113549.1.12.10.1.2",Aw),s.register("1.2.840.113549.1.12.10.1.3",yw),s.register("1.2.840.113549.1.12.10.1.4",Ew),s.register("1.2.840.113549.1.12.10.1.5",Iw),s.register("1.2.840.113549.1.12.10.1.6",Mi)),this.items}static register(e,t){this.getItems()[e]=t;}static find(e){return this.getItems()[e]||null}},go="bagId",yo="bagValue",rr="bagAttributes",mD=[go,yo,rr],Wm=class s extends O{constructor(e={}){super(),this.bagId=d(e,go,s.defaultValues(go)),this.bagValue=d(e,yo,s.defaultValues(yo)),rr in e&&(this.bagAttributes=d(e,rr,s.defaultValues(rr))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case go:return p;case yo:return new ue;case rr:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case go:return t===p;case yo:return t instanceof ue;case rr:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.bagId||go}),new A({idBlock:{tagClass:3,tagNumber:0},value:[new ue({name:t.bagValue||yo})]}),new et({optional:!0,value:[new fe({name:t.bagAttributes||rr,value:nt.schema()})]})]})}fromSchema(e){V(e,mD);let t=R(e,e,s.schema({names:{bagId:go,bagValue:yo,bagAttributes:rr}}));T.assertSchema(t,this.className),this.bagId=t.result.bagId.valueBlock.toString();let n=q2.find(this.bagId);if(!n)throw new Error(`Invalid BAG_ID for SafeBag: ${this.bagId}`);this.bagValue=new n({schema:t.result.bagValue}),rr in t.result&&(this.bagAttributes=Array.from(t.result.bagAttributes,r=>new nt({schema:r})));}toSchema(){let e=[new G({value:this.bagId}),new A({idBlock:{tagClass:3,tagNumber:0},value:[this.bagValue.toSchema()]})];return this.bagAttributes&&e.push(new et({value:Array.from(this.bagAttributes,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={bagId:this.bagId,bagValue:this.bagValue.toJSON()};return this.bagAttributes&&(e.bagAttributes=Array.from(this.bagAttributes,t=>t.toJSON())),e}};Wm.CLASS_NAME="SafeBag";var Jc="safeBags",Mi=class s extends O{constructor(e={}){super(),this.safeBags=d(e,Jc,s.defaultValues(Jc)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Jc:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Jc:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.safeBags||p,value:Wm.schema()})]})}fromSchema(e){V(e,[Jc]);let t=R(e,e,s.schema({names:{safeBags:Jc}}));T.assertSchema(t,this.className),this.safeBags=Array.from(t.result.safeBags,n=>new Wm({schema:n}));}toSchema(){return new b({value:Array.from(this.safeBags,e=>e.toSchema())})}toJSON(){return {safeBags:Array.from(this.safeBags,e=>e.toJSON())}}};Mi.CLASS_NAME="SafeContents";var Xd="otherCertFormat",em="otherCert",pD=[Xd,em],Il=class s extends O{constructor(e={}){super(),this.otherCertFormat=d(e,Xd,s.defaultValues(Xd)),this.otherCert=d(e,em,s.defaultValues(em)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Xd:return p;case em:return new ue;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.otherCertFormat||Xd}),new ue({name:t.otherCert||em})]})}fromSchema(e){V(e,pD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.otherCertFormat=t.result.otherCertFormat.valueBlock.toString(),this.otherCert=t.result.otherCert;}toSchema(){return new b({value:[new G({value:this.otherCertFormat}),this.otherCert]})}toJSON(){let e={otherCertFormat:this.otherCertFormat};return this.otherCert instanceof ue||(e.otherCert=this.otherCert.toJSON()),e}},tm="certificates",gD=[tm],yr=class s extends O{constructor(e={}){super(),this.certificates=d(e,tm,s.defaultValues(tm)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case tm:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new et({name:t.blockName||p,value:[new fe({name:t.certificates||tm,value:new We({value:[jt.schema(),new A({idBlock:{tagClass:3,tagNumber:0},value:[new ue]}),new A({idBlock:{tagClass:3,tagNumber:1},value:[new b]}),new A({idBlock:{tagClass:3,tagNumber:2},value:bn.schema().valueBlock.value}),new A({idBlock:{tagClass:3,tagNumber:3},value:Il.schema().valueBlock.value})]})})]})}fromSchema(e){V(e,gD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.certificates=Array.from(t.result.certificates||[],n=>{let r=n.idBlock.tagNumber;if(n.idBlock.tagClass===1)return new jt({schema:n});let i=new b({value:n.valueBlock.value});switch(r){case 1:return i.valueBlock.value[0].valueBlock.value[0].valueBlock.valueDec===1?new bn({schema:i}):new Pl({schema:i});case 2:return new bn({schema:i});case 3:return new Il({schema:i})}return n});}toSchema(){return new et({value:Array.from(this.certificates,e=>{switch(!0){case e instanceof jt:return e.toSchema();case e instanceof Pl:return new A({idBlock:{tagClass:3,tagNumber:1},value:e.toSchema().valueBlock.value});case e instanceof bn:return new A({idBlock:{tagClass:3,tagNumber:2},value:e.toSchema().valueBlock.value});case e instanceof Il:return new A({idBlock:{tagClass:3,tagNumber:3},value:e.toSchema().valueBlock.value})}return e.toSchema()})})}toJSON(){return {certificates:Array.from(this.certificates,e=>e.toJSON())}}};yr.CLASS_NAME="CertificateSet";var sm="otherRevInfoFormat",nm="otherRevInfo",yD=[sm,nm],Fo=class s extends O{constructor(e={}){super(),this.otherRevInfoFormat=d(e,sm,s.defaultValues(sm)),this.otherRevInfo=d(e,nm,s.defaultValues(nm)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case sm:return p;case nm:return new ue;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.otherRevInfoFormat||sm}),new ue({name:t.otherRevInfo||nm})]})}fromSchema(e){V(e,yD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.otherRevInfoFormat=t.result.otherRevInfoFormat.valueBlock.toString(),this.otherRevInfo=t.result.otherRevInfo;}toSchema(){return new b({value:[new G({value:this.otherRevInfoFormat}),this.otherRevInfo]})}toJSON(){let e={otherRevInfoFormat:this.otherRevInfoFormat};return this.otherRevInfo instanceof ue||(e.otherRevInfo=this.otherRevInfo.toJSON()),e}};Fo.CLASS_NAME="OtherRevocationInfoFormat";var rm="crls",I2="otherRevocationInfos",wD=[rm],Ko=class s extends O{constructor(e={}){super(),this.crls=d(e,rm,s.defaultValues(rm)),this.otherRevocationInfos=d(e,I2,s.defaultValues(I2)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case rm:return [];case I2:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new et({name:t.blockName||p,value:[new fe({name:t.crls||p,value:new We({value:[Zo.schema(),new A({idBlock:{tagClass:3,tagNumber:1},value:[new G,new ue]})]})})]})}fromSchema(e){V(e,wD);let t=R(e,e,s.schema({names:{crls:rm}}));if(T.assertSchema(t,this.className),t.result.crls)for(let n of t.result.crls)n.idBlock.tagClass===1?this.crls.push(new Zo({schema:n})):this.otherRevocationInfos.push(new Fo({schema:n}));}toSchema(){let e=[];return e.push(...Array.from(this.crls,t=>t.toSchema())),e.push(...Array.from(this.otherRevocationInfos,t=>{let n=t.toSchema();return n.idBlock.tagClass=3,n.idBlock.tagNumber=1,n})),new et({value:e})}toJSON(){return {crls:Array.from(this.crls,e=>e.toJSON()),otherRevocationInfos:Array.from(this.otherRevocationInfos,e=>e.toJSON())}}};Ko.CLASS_NAME="RevocationInfoChoices";var im="certs",wo="crls",bD=[im,wo],Cl=class s extends O{constructor(e={}){super(),this.crls=d(e,wo,s.defaultValues(wo)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case im:return new yr;case wo:return new Ko;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case im:return t.certificates.length===0;case wo:return t.crls.length===0&&t.otherRevocationInfos.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new A({name:t.certs||p,optional:!0,idBlock:{tagClass:3,tagNumber:0},value:yr.schema().valueBlock.value}),new A({name:t.crls||p,optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Ko.schema().valueBlock.value})]})}fromSchema(e){V(e,bD);let t=R(e,e,s.schema({names:{certs:im,crls:wo}}));T.assertSchema(t,this.className),im in t.result&&(this.certs=new yr({schema:new et({value:t.result.certs.valueBlock.value})})),wo in t.result&&(this.crls=new Ko({schema:new et({value:t.result.crls.valueBlock.value})}));}toSchema(){let e=[];return this.certs&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:this.certs.toSchema().valueBlock.value})),this.crls&&e.push(new A({idBlock:{tagClass:3,tagNumber:1},value:this.crls.toSchema().valueBlock.value})),new b({value:e})}toJSON(){let e={};return this.certs&&(e.certs=this.certs.toJSON()),this.crls&&(e.crls=this.crls.toJSON()),e}};Cl.CLASS_NAME="OriginatorInfo";var am="issuer",om="serialNumber",SD=[am,om],vt=class s extends O{constructor(e={}){super(),this.issuer=d(e,am,s.defaultValues(am)),this.serialNumber=d(e,om,s.defaultValues(om)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case am:return new Je;case om:return new k;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[Je.schema(t.issuer||{}),new k({name:t.serialNumber||p})]})}fromSchema(e){V(e,SD);let t=R(e,e,s.schema({names:{issuer:{names:{blockName:am}},serialNumber:om}}));T.assertSchema(t,this.className),this.issuer=new Je({schema:t.result.issuer}),this.serialNumber=t.result.serialNumber;}toSchema(){return new b({value:[this.issuer.toSchema(),this.serialNumber]})}toJSON(){return {issuer:this.issuer.toJSON(),serialNumber:this.serialNumber.toJSON()}}};vt.CLASS_NAME="IssuerAndSerialNumber";var uy="variant",Cf="value",vD=["blockName"],Cw=class s extends O{constructor(e={}){super(),this.variant=d(e,uy,s.defaultValues(uy)),Cf in e&&(this.value=d(e,Cf,s.defaultValues(Cf))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case uy:return -1;case Cf:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case uy:return t===-1;case Cf:return Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new We({value:[vt.schema({names:{blockName:t.blockName||p}}),new ie({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:0}})]})}fromSchema(e){V(e,vD);let t=R(e,e,s.schema({names:{blockName:"blockName"}}));T.assertSchema(t,this.className),t.result.blockName.idBlock.tagClass===1?(this.variant=1,this.value=new vt({schema:t.result.blockName})):(this.variant=2,this.value=new L({valueHex:t.result.blockName.valueBlock.valueHex}));}toSchema(){switch(this.variant){case 1:if(!(this.value instanceof vt))throw new Error("Incorrect type of RecipientIdentifier.value. It should be IssuerAndSerialNumber.");return this.value.toSchema();case 2:if(!(this.value instanceof L))throw new Error("Incorrect type of RecipientIdentifier.value. It should be ASN.1 OctetString.");return new ie({idBlock:{tagClass:3,tagNumber:0},valueHex:this.value.valueBlock.valueHexView});default:return new ue}}toJSON(){let e={variant:this.variant};return (this.variant===1||this.variant===2)&&this.value&&(e.value=this.value.toJSON()),e}};Cw.CLASS_NAME="RecipientIdentifier";var bo="version",vu="rid",xu="keyEncryptionAlgorithm",Eu="encryptedKey",ly="recipientCertificate",xD=[bo,vu,xu,Eu],Tl=class s extends O{constructor(e={}){super(),this.version=d(e,bo,s.defaultValues(bo)),this.rid=d(e,vu,s.defaultValues(vu)),this.keyEncryptionAlgorithm=d(e,xu,s.defaultValues(xu)),this.encryptedKey=d(e,Eu,s.defaultValues(Eu)),this.recipientCertificate=d(e,ly,s.defaultValues(ly)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case bo:return -1;case vu:return {};case xu:return new P;case Eu:return new L;case ly:return new jt;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case bo:return t===s.defaultValues(bo);case vu:return Object.keys(t).length===0;case xu:case Eu:return t.isEqual(s.defaultValues(e));case ly:return !1;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new k({name:t.version||p}),Cw.schema(t.rid||{}),P.schema(t.keyEncryptionAlgorithm||{}),new L({name:t.encryptedKey||p})]})}fromSchema(e){V(e,xD);let t=R(e,e,s.schema({names:{version:bo,rid:{names:{blockName:vu}},keyEncryptionAlgorithm:{names:{blockName:xu}},encryptedKey:Eu}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,t.result.rid.idBlock.tagClass===3?this.rid=new L({valueHex:t.result.rid.valueBlock.valueHex}):this.rid=new vt({schema:t.result.rid}),this.keyEncryptionAlgorithm=new P({schema:t.result.keyEncryptionAlgorithm}),this.encryptedKey=t.result.encryptedKey;}toSchema(){let e=[];return this.rid instanceof vt?(this.version=0,e.push(new k({value:this.version})),e.push(this.rid.toSchema())):(this.version=2,e.push(new k({value:this.version})),e.push(new ie({idBlock:{tagClass:3,tagNumber:0},valueHex:this.rid.valueBlock.valueHexView}))),e.push(this.keyEncryptionAlgorithm.toSchema()),e.push(this.encryptedKey),new b({value:e})}toJSON(){return {version:this.version,rid:this.rid.toJSON(),keyEncryptionAlgorithm:this.keyEncryptionAlgorithm.toJSON(),encryptedKey:this.encryptedKey.toJSON()}}};Tl.CLASS_NAME="KeyTransRecipientInfo";var Au="algorithm",Iu="publicKey",ED=[Au,Iu],Bl=class s extends O{constructor(e={}){super(),this.algorithm=d(e,Au,s.defaultValues(Au)),this.publicKey=d(e,Iu,s.defaultValues(Iu)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Au:return new P;case Iu:return new Ae;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Au:case Iu:return t.isEqual(s.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.algorithm||{}),new Ae({name:t.publicKey||p})]})}fromSchema(e){V(e,ED);let t=R(e,e,s.schema({names:{algorithm:{names:{blockName:Au}},publicKey:Iu}}));T.assertSchema(t,this.className),this.algorithm=new P({schema:t.result.algorithm}),this.publicKey=t.result.publicKey;}toSchema(){return new b({value:[this.algorithm.toSchema(),this.publicKey]})}toJSON(){return {algorithm:this.algorithm.toJSON(),publicKey:this.publicKey.toJSON()}}};Bl.CLASS_NAME="OriginatorPublicKey";var hy="variant",Nf="value",AD=["blockName"],Go=class s extends O{constructor(e={}){super(),this.variant=d(e,hy,s.defaultValues(hy)),Nf in e&&(this.value=d(e,Nf,s.defaultValues(Nf))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case hy:return -1;case Nf:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case hy:return t===-1;case Nf:return Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new We({value:[vt.schema({names:{blockName:t.blockName||p}}),new ie({idBlock:{tagClass:3,tagNumber:0},name:t.blockName||p}),new A({idBlock:{tagClass:3,tagNumber:1},name:t.blockName||p,value:Bl.schema().valueBlock.value})]})}fromSchema(e){V(e,AD);let t=R(e,e,s.schema({names:{blockName:"blockName"}}));T.assertSchema(t,this.className),t.result.blockName.idBlock.tagClass===1?(this.variant=1,this.value=new vt({schema:t.result.blockName})):t.result.blockName.idBlock.tagNumber===0?(t.result.blockName.idBlock.tagClass=1,t.result.blockName.idBlock.tagNumber=4,this.variant=2,this.value=t.result.blockName):(this.variant=3,this.value=new Bl({schema:new b({value:t.result.blockName.valueBlock.value})}));}toSchema(){switch(this.variant){case 1:return this.value.toSchema();case 2:return this.value.idBlock.tagClass=3,this.value.idBlock.tagNumber=0,this.value;case 3:{let e=this.value.toSchema();return e.idBlock.tagClass=3,e.idBlock.tagNumber=1,e}default:return new ue}}toJSON(){let e={variant:this.variant};return (this.variant===1||this.variant===2||this.variant===3)&&(e.value=this.value.toJSON()),e}};Go.CLASS_NAME="OriginatorIdentifierOrKey";var Cu="keyAttrId",yn="keyAttr",ID=[Cu,yn],wr=class s extends O{constructor(e={}){super(),this.keyAttrId=d(e,Cu,s.defaultValues(Cu)),yn in e&&(this.keyAttr=d(e,yn,s.defaultValues(yn))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Cu:return p;case yn:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Cu:return typeof t=="string"&&t===p;case yn:return Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({optional:t.optional||!0,name:t.blockName||p,value:[new G({name:t.keyAttrId||p}),new ue({optional:!0,name:t.keyAttr||p})]})}fromSchema(e){V(e,ID);let t=R(e,e,s.schema({names:{keyAttrId:Cu,keyAttr:yn}}));T.assertSchema(t,this.className),this.keyAttrId=t.result.keyAttrId.valueBlock.toString(),yn in t.result&&(this.keyAttr=t.result.keyAttr);}toSchema(){let e=[];return e.push(new G({value:this.keyAttrId})),yn in this&&e.push(this.keyAttr),new b({value:e})}toJSON(){let e={keyAttrId:this.keyAttrId};return yn in this&&(e.keyAttr=this.keyAttr.toJSON()),e}};wr.CLASS_NAME="OtherKeyAttribute";var So="subjectKeyIdentifier",Si="date",vi="other",CD=[So,Si,vi],Ol=class s extends O{constructor(e={}){super(),this.subjectKeyIdentifier=d(e,So,s.defaultValues(So)),Si in e&&(this.date=d(e,Si,s.defaultValues(Si))),vi in e&&(this.other=d(e,vi,s.defaultValues(vi))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case So:return new L;case Si:return new Ge;case vi:return new wr;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case So:return t.isEqual(s.defaultValues(So));case Si:return t.year===0&&t.month===0&&t.day===0&&t.hour===0&&t.minute===0&&t.second===0&&t.millisecond===0;case vi:return t.keyAttrId===p&&!("keyAttr"in t);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new L({name:t.subjectKeyIdentifier||p}),new Ge({optional:!0,name:t.date||p}),wr.schema(t.other||{})]})}fromSchema(e){V(e,CD);let t=R(e,e,s.schema({names:{subjectKeyIdentifier:So,date:Si,other:{names:{blockName:vi}}}}));T.assertSchema(t,this.className),this.subjectKeyIdentifier=t.result.subjectKeyIdentifier,Si in t.result&&(this.date=t.result.date),vi in t.result&&(this.other=new wr({schema:t.result.other}));}toSchema(){let e=[];return e.push(this.subjectKeyIdentifier),this.date&&e.push(this.date),this.other&&e.push(this.other.toSchema()),new b({value:e})}toJSON(){let e={subjectKeyIdentifier:this.subjectKeyIdentifier.toJSON()};return this.date&&(e.date=this.date.toJSON()),this.other&&(e.other=this.other.toJSON()),e}};Ol.CLASS_NAME="RecipientKeyIdentifier";var fy="variant",dy="value",ND=["blockName"],qi=class s extends O{constructor(e={}){super(),this.variant=d(e,fy,s.defaultValues(fy)),this.value=d(e,dy,s.defaultValues(dy)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case fy:return -1;case dy:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case fy:return t===-1;case dy:return Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new We({value:[vt.schema(t.issuerAndSerialNumber||{names:{blockName:t.blockName||p}}),new A({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:0},value:Ol.schema(t.rKeyId||{names:{blockName:t.blockName||p}}).valueBlock.value})]})}fromSchema(e){V(e,ND);let t=R(e,e,s.schema({names:{blockName:"blockName"}}));T.assertSchema(t,this.className),t.result.blockName.idBlock.tagClass===1?(this.variant=1,this.value=new vt({schema:t.result.blockName})):(this.variant=2,this.value=new Ol({schema:new b({value:t.result.blockName.valueBlock.value})}));}toSchema(){switch(this.variant){case 1:return this.value.toSchema();case 2:return new A({idBlock:{tagClass:3,tagNumber:0},value:this.value.toSchema().valueBlock.value});default:return new ue}}toJSON(){let e={variant:this.variant};return (this.variant===1||this.variant===2)&&(e.value=this.value.toJSON()),e}};qi.CLASS_NAME="KeyAgreeRecipientIdentifier";var Nu="rid",vo="encryptedKey",kD=[Nu,vo],Rl=class s extends O{constructor(e={}){super(),this.rid=d(e,Nu,s.defaultValues(Nu)),this.encryptedKey=d(e,vo,s.defaultValues(vo)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Nu:return new qi;case vo:return new L;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Nu:return t.variant===-1&&!("value"in t);case vo:return t.isEqual(s.defaultValues(vo));default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[qi.schema(t.rid||{}),new L({name:t.encryptedKey||p})]})}fromSchema(e){V(e,kD);let t=R(e,e,s.schema({names:{rid:{names:{blockName:Nu}},encryptedKey:vo}}));T.assertSchema(t,this.className),this.rid=new qi({schema:t.result.rid}),this.encryptedKey=t.result.encryptedKey;}toSchema(){return new b({value:[this.rid.toSchema(),this.encryptedKey]})}toJSON(){return {rid:this.rid.toJSON(),encryptedKey:this.encryptedKey.toJSON()}}};Rl.CLASS_NAME="RecipientEncryptedKey";var my="encryptedKeys",Ik="RecipientEncryptedKeys",PD=[Ik],Wo=class s extends O{constructor(e={}){super(),this.encryptedKeys=d(e,my,s.defaultValues(my)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case my:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case my:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.RecipientEncryptedKeys||p,value:Rl.schema()})]})}fromSchema(e){V(e,PD);let t=R(e,e,s.schema({names:{RecipientEncryptedKeys:Ik}}));T.assertSchema(t,this.className),this.encryptedKeys=Array.from(t.result.RecipientEncryptedKeys,n=>new Rl({schema:n}));}toSchema(){return new b({value:Array.from(this.encryptedKeys,e=>e.toSchema())})}toJSON(){return {encryptedKeys:Array.from(this.encryptedKeys,e=>e.toJSON())}}};Wo.CLASS_NAME="RecipientEncryptedKeys";var ku="version",Pu="originator",ir="ukm",Tu="keyEncryptionAlgorithm",Bu="recipientEncryptedKeys",py="recipientCertificate",gy="recipientPublicKey",TD=[ku,Pu,ir,Tu,Bu],Vl=class s extends O{constructor(e={}){super(),this.version=d(e,ku,s.defaultValues(ku)),this.originator=d(e,Pu,s.defaultValues(Pu)),ir in e&&(this.ukm=d(e,ir,s.defaultValues(ir))),this.keyEncryptionAlgorithm=d(e,Tu,s.defaultValues(Tu)),this.recipientEncryptedKeys=d(e,Bu,s.defaultValues(Bu)),this.recipientCertificate=d(e,py,s.defaultValues(py)),this.recipientPublicKey=d(e,gy,s.defaultValues(gy)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ku:return 0;case Pu:return new Go;case ir:return new L;case Tu:return new P;case Bu:return new Wo;case py:return new jt;case gy:return null;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ku:return t===0;case Pu:return t.variant===-1&&!("value"in t);case ir:return t.isEqual(s.defaultValues(ir));case Tu:return t.algorithmId===p&&!("algorithmParams"in t);case Bu:return t.encryptedKeys.length===0;case py:return !1;case gy:return !1;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new k({name:t.version||p}),new A({idBlock:{tagClass:3,tagNumber:0},value:[Go.schema(t.originator||{})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new L({name:t.ukm||p})]}),P.schema(t.keyEncryptionAlgorithm||{}),Wo.schema(t.recipientEncryptedKeys||{})]})}fromSchema(e){V(e,TD);let t=R(e,e,s.schema({names:{version:ku,originator:{names:{blockName:Pu}},ukm:ir,keyEncryptionAlgorithm:{names:{blockName:Tu}},recipientEncryptedKeys:{names:{blockName:Bu}}}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.originator=new Go({schema:t.result.originator}),ir in t.result&&(this.ukm=t.result.ukm),this.keyEncryptionAlgorithm=new P({schema:t.result.keyEncryptionAlgorithm}),this.recipientEncryptedKeys=new Wo({schema:t.result.recipientEncryptedKeys});}toSchema(){let e=[];return e.push(new k({value:this.version})),e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[this.originator.toSchema()]})),this.ukm&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[this.ukm]})),e.push(this.keyEncryptionAlgorithm.toSchema()),e.push(this.recipientEncryptedKeys.toSchema()),new b({value:e})}toJSON(){let e={version:this.version,originator:this.originator.toJSON(),keyEncryptionAlgorithm:this.keyEncryptionAlgorithm.toJSON(),recipientEncryptedKeys:this.recipientEncryptedKeys.toJSON()};return this.ukm&&(e.ukm=this.ukm.toJSON()),e}};Vl.CLASS_NAME="KeyAgreeRecipientInfo";var xo="keyIdentifier",xi="date",Ei="other",BD=[xo,xi,Ei],Jo=class s extends O{constructor(e={}){super(),this.keyIdentifier=d(e,xo,s.defaultValues(xo)),xi in e&&(this.date=d(e,xi,s.defaultValues(xi))),Ei in e&&(this.other=d(e,Ei,s.defaultValues(Ei))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case xo:return new L;case xi:return new Ge;case Ei:return new wr;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case xo:return t.isEqual(s.defaultValues(xo));case xi:return t.year===0&&t.month===0&&t.day===0&&t.hour===0&&t.minute===0&&t.second===0&&t.millisecond===0;case Ei:return t.compareWithDefault("keyAttrId",t.keyAttrId)&&!("keyAttr"in t);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new L({name:t.keyIdentifier||p}),new Ge({optional:!0,name:t.date||p}),wr.schema(t.other||{})]})}fromSchema(e){V(e,BD);let t=R(e,e,s.schema({names:{keyIdentifier:xo,date:xi,other:{names:{blockName:Ei}}}}));T.assertSchema(t,this.className),this.keyIdentifier=t.result.keyIdentifier,xi in t.result&&(this.date=t.result.date),Ei in t.result&&(this.other=new wr({schema:t.result.other}));}toSchema(){let e=[];return e.push(this.keyIdentifier),this.date&&e.push(this.date),this.other&&e.push(this.other.toSchema()),new b({value:e})}toJSON(){let e={keyIdentifier:this.keyIdentifier.toJSON()};return this.date&&(e.date=this.date),this.other&&(e.other=this.other.toJSON()),e}};Jo.CLASS_NAME="KEKIdentifier";var Ou="version",Ru="kekid",Vu="keyEncryptionAlgorithm",Eo="encryptedKey",yy="preDefinedKEK",OD=[Ou,Ru,Vu,Eo],Dl=class s extends O{constructor(e={}){super(),this.version=d(e,Ou,s.defaultValues(Ou)),this.kekid=d(e,Ru,s.defaultValues(Ru)),this.keyEncryptionAlgorithm=d(e,Vu,s.defaultValues(Vu)),this.encryptedKey=d(e,Eo,s.defaultValues(Eo)),this.preDefinedKEK=d(e,yy,s.defaultValues(yy)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ou:return 0;case Ru:return new Jo;case Vu:return new P;case Eo:return new L;case yy:return ut;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case"KEKRecipientInfo":return t===s.defaultValues(Ou);case Ru:return t.compareWithDefault("keyIdentifier",t.keyIdentifier)&&!("date"in t)&&!("other"in t);case Vu:return t.algorithmId===p&&!("algorithmParams"in t);case Eo:return t.isEqual(s.defaultValues(Eo));case yy:return t.byteLength===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new k({name:t.version||p}),Jo.schema(t.kekid||{}),P.schema(t.keyEncryptionAlgorithm||{}),new L({name:t.encryptedKey||p})]})}fromSchema(e){V(e,OD);let t=R(e,e,s.schema({names:{version:Ou,kekid:{names:{blockName:Ru}},keyEncryptionAlgorithm:{names:{blockName:Vu}},encryptedKey:Eo}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.kekid=new Jo({schema:t.result.kekid}),this.keyEncryptionAlgorithm=new P({schema:t.result.keyEncryptionAlgorithm}),this.encryptedKey=t.result.encryptedKey;}toSchema(){return new b({value:[new k({value:this.version}),this.kekid.toSchema(),this.keyEncryptionAlgorithm.toSchema(),this.encryptedKey]})}toJSON(){return {version:this.version,kekid:this.kekid.toJSON(),keyEncryptionAlgorithm:this.keyEncryptionAlgorithm.toJSON(),encryptedKey:this.encryptedKey.toJSON()}}};Dl.CLASS_NAME="KEKRecipientInfo";var Du="version",Ai="keyDerivationAlgorithm",Lu="keyEncryptionAlgorithm",Ao="encryptedKey",wy="password",RD=[Du,Ai,Lu,Ao],Ll=class s extends O{constructor(e={}){super(),this.version=d(e,Du,s.defaultValues(Du)),Ai in e&&(this.keyDerivationAlgorithm=d(e,Ai,s.defaultValues(Ai))),this.keyEncryptionAlgorithm=d(e,Lu,s.defaultValues(Lu)),this.encryptedKey=d(e,Ao,s.defaultValues(Ao)),this.password=d(e,wy,s.defaultValues(wy)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Du:return -1;case Ai:return new P;case Lu:return new P;case Ao:return new L;case wy:return ut;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Du:return t===-1;case Ai:case Lu:return t.algorithmId===p&&!("algorithmParams"in t);case Ao:return t.isEqual(s.defaultValues(Ao));case wy:return t.byteLength===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new k({name:t.version||p}),new A({name:t.keyDerivationAlgorithm||p,optional:!0,idBlock:{tagClass:3,tagNumber:0},value:P.schema().valueBlock.value}),P.schema(t.keyEncryptionAlgorithm||{}),new L({name:t.encryptedKey||p})]})}fromSchema(e){V(e,RD);let t=R(e,e,s.schema({names:{version:Du,keyDerivationAlgorithm:Ai,keyEncryptionAlgorithm:{names:{blockName:Lu}},encryptedKey:Ao}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,Ai in t.result&&(this.keyDerivationAlgorithm=new P({schema:new b({value:t.result.keyDerivationAlgorithm.valueBlock.value})})),this.keyEncryptionAlgorithm=new P({schema:t.result.keyEncryptionAlgorithm}),this.encryptedKey=t.result.encryptedKey;}toSchema(){let e=[];return e.push(new k({value:this.version})),this.keyDerivationAlgorithm&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:this.keyDerivationAlgorithm.toSchema().valueBlock.value})),e.push(this.keyEncryptionAlgorithm.toSchema()),e.push(this.encryptedKey),new b({value:e})}toJSON(){let e={version:this.version,keyEncryptionAlgorithm:this.keyEncryptionAlgorithm.toJSON(),encryptedKey:this.encryptedKey.toJSON()};return this.keyDerivationAlgorithm&&(e.keyDerivationAlgorithm=this.keyDerivationAlgorithm.toJSON()),e}};Ll.CLASS_NAME="PasswordRecipientInfo";var ju="oriType",Io="oriValue",VD=[ju,Io],Jm=class s extends O{constructor(e={}){super(),this.oriType=d(e,ju,s.defaultValues(ju)),this.oriValue=d(e,Io,s.defaultValues(Io)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ju:return p;case Io:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ju:return t===p;case Io:return Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.oriType||p}),new ue({name:t.oriValue||p})]})}fromSchema(e){V(e,VD);let t=R(e,e,s.schema({names:{oriType:ju,oriValue:Io}}));T.assertSchema(t,this.className),this.oriType=t.result.oriType.valueBlock.toString(),this.oriValue=t.result.oriValue;}toSchema(){return new b({value:[new G({value:this.oriType}),this.oriValue]})}toJSON(){let e={oriType:this.oriType};return s.compareWithDefault(Io,this.oriValue)||(e.oriValue=this.oriValue.toJSON()),e}};Jm.CLASS_NAME="OtherRecipientInfo";var by="variant",kf="value",DD=["blockName"],hr=class s extends O{constructor(e={}){super(),this.variant=d(e,by,s.defaultValues(by)),kf in e&&(this.value=d(e,kf,s.defaultValues(kf))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case by:return -1;case kf:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case by:return t===s.defaultValues(e);case kf:return Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new We({value:[Tl.schema({names:{blockName:t.blockName||p}}),new A({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:1},value:Vl.schema().valueBlock.value}),new A({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:2},value:Dl.schema().valueBlock.value}),new A({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:3},value:Ll.schema().valueBlock.value}),new A({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:4},value:Jm.schema().valueBlock.value})]})}fromSchema(e){V(e,DD);let t=R(e,e,s.schema({names:{blockName:"blockName"}}));if(T.assertSchema(t,this.className),t.result.blockName.idBlock.tagClass===1)this.variant=1,this.value=new Tl({schema:t.result.blockName});else {let n=new b({value:t.result.blockName.valueBlock.value});switch(t.result.blockName.idBlock.tagNumber){case 1:this.variant=2,this.value=new Vl({schema:n});break;case 2:this.variant=3,this.value=new Dl({schema:n});break;case 3:this.variant=4,this.value=new Ll({schema:n});break;case 4:this.variant=5,this.value=new Jm({schema:n});break;default:throw new Error("Incorrect structure of RecipientInfo block")}}}toSchema(){Re.assertEmpty(this.value,"value","RecipientInfo");let e=this.value.toSchema();switch(this.variant){case 1:return e;case 2:case 3:case 4:return e.idBlock.tagClass=3,e.idBlock.tagNumber=this.variant-1,e;default:return new ue}}toJSON(){let e={variant:this.variant};return this.value&&this.variant>=1&&this.variant<=4&&(e.value=this.value.toJSON()),e}};hr.CLASS_NAME="RecipientInfo";var Ii="hashAlgorithm",Ci="maskGenAlgorithm",Ni="pSourceAlgorithm",LD=[Ii,Ci,Ni],Nl=class s extends O{constructor(e={}){super(),this.hashAlgorithm=d(e,Ii,s.defaultValues(Ii)),this.maskGenAlgorithm=d(e,Ci,s.defaultValues(Ci)),this.pSourceAlgorithm=d(e,Ni,s.defaultValues(Ni)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ii:return new P({algorithmId:"1.3.14.3.2.26",algorithmParams:new Xe});case Ci:return new P({algorithmId:"1.2.840.113549.1.1.8",algorithmParams:new P({algorithmId:"1.3.14.3.2.26",algorithmParams:new Xe}).toSchema()});case Ni:return new P({algorithmId:"1.2.840.113549.1.1.9",algorithmParams:new L({valueHex:new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer})});default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new A({idBlock:{tagClass:3,tagNumber:0},optional:!0,value:[P.schema(t.hashAlgorithm||{})]}),new A({idBlock:{tagClass:3,tagNumber:1},optional:!0,value:[P.schema(t.maskGenAlgorithm||{})]}),new A({idBlock:{tagClass:3,tagNumber:2},optional:!0,value:[P.schema(t.pSourceAlgorithm||{})]})]})}fromSchema(e){V(e,LD);let t=R(e,e,s.schema({names:{hashAlgorithm:{names:{blockName:Ii}},maskGenAlgorithm:{names:{blockName:Ci}},pSourceAlgorithm:{names:{blockName:Ni}}}}));T.assertSchema(t,this.className),Ii in t.result&&(this.hashAlgorithm=new P({schema:t.result.hashAlgorithm})),Ci in t.result&&(this.maskGenAlgorithm=new P({schema:t.result.maskGenAlgorithm})),Ni in t.result&&(this.pSourceAlgorithm=new P({schema:t.result.pSourceAlgorithm}));}toSchema(){let e=[];return this.hashAlgorithm.isEqual(s.defaultValues(Ii))||e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[this.hashAlgorithm.toSchema()]})),this.maskGenAlgorithm.isEqual(s.defaultValues(Ci))||e.push(new A({idBlock:{tagClass:3,tagNumber:1},value:[this.maskGenAlgorithm.toSchema()]})),this.pSourceAlgorithm.isEqual(s.defaultValues(Ni))||e.push(new A({idBlock:{tagClass:3,tagNumber:2},value:[this.pSourceAlgorithm.toSchema()]})),new b({value:e})}toJSON(){let e={};return this.hashAlgorithm.isEqual(s.defaultValues(Ii))||(e.hashAlgorithm=this.hashAlgorithm.toJSON()),this.maskGenAlgorithm.isEqual(s.defaultValues(Ci))||(e.maskGenAlgorithm=this.maskGenAlgorithm.toJSON()),this.pSourceAlgorithm.isEqual(s.defaultValues(Ni))||(e.pSourceAlgorithm=this.pSourceAlgorithm.toJSON()),e}};Nl.CLASS_NAME="RSAESOAEPParams";var Uu="keyInfo",ki="entityUInfo",Hu="suppPubInfo",jD=[Uu,ki,Hu],zm=class s extends O{constructor(e={}){super(),this.keyInfo=d(e,Uu,s.defaultValues(Uu)),ki in e&&(this.entityUInfo=d(e,ki,s.defaultValues(ki))),this.suppPubInfo=d(e,Hu,s.defaultValues(Hu)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Uu:return new P;case ki:return new L;case Hu:return new L;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Uu:case ki:case Hu:return t.isEqual(s.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.keyInfo||{}),new A({name:t.entityUInfo||p,idBlock:{tagClass:3,tagNumber:0},optional:!0,value:[new L]}),new A({name:t.suppPubInfo||p,idBlock:{tagClass:3,tagNumber:2},value:[new L]})]})}fromSchema(e){V(e,jD);let t=R(e,e,s.schema({names:{keyInfo:{names:{blockName:Uu}},entityUInfo:ki,suppPubInfo:Hu}}));T.assertSchema(t,this.className),this.keyInfo=new P({schema:t.result.keyInfo}),ki in t.result&&(this.entityUInfo=t.result.entityUInfo.valueBlock.value[0]),this.suppPubInfo=t.result.suppPubInfo.valueBlock.value[0];}toSchema(){let e=[];return e.push(this.keyInfo.toSchema()),this.entityUInfo&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[this.entityUInfo]})),e.push(new A({idBlock:{tagClass:3,tagNumber:2},value:[this.suppPubInfo]})),new b({value:e})}toJSON(){let e={keyInfo:this.keyInfo.toJSON(),suppPubInfo:this.suppPubInfo.toJSON()};return this.entityUInfo&&(e.entityUInfo=this.entityUInfo.toJSON()),e}};zm.CLASS_NAME="ECCCMSSharedInfo";var _u="version",Pi="originatorInfo",Mu="recipientInfos",$u="encryptedContentInfo",Ti="unprotectedAttrs",UD=[_u,Pi,Mu,$u,Ti],nk={kdfAlgorithm:"SHA-512",kekEncryptionLength:256},HD={"P-256":256,"P-384":384,"P-521":528},Ym=class s extends O{constructor(e={}){super(),this.version=d(e,_u,s.defaultValues(_u)),Pi in e&&(this.originatorInfo=d(e,Pi,s.defaultValues(Pi))),this.recipientInfos=d(e,Mu,s.defaultValues(Mu)),this.encryptedContentInfo=d(e,$u,s.defaultValues($u)),Ti in e&&(this.unprotectedAttrs=d(e,Ti,s.defaultValues(Ti))),this.policy={disableSplit:!!e.disableSplit},e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case _u:return 0;case Pi:return new Cl;case Mu:return [];case $u:return new kt;case Ti:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case _u:return t===s.defaultValues(e);case Pi:return t.certs.certificates.length===0&&t.crls.crls.length===0;case Mu:case Ti:return t.length===0;case $u:return kt.compareWithDefault("contentType",t.contentType)&&kt.compareWithDefault("contentEncryptionAlgorithm",t.contentEncryptionAlgorithm)&&kt.compareWithDefault("encryptedContent",t.encryptedContent);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new k({name:t.version||p}),new A({name:t.originatorInfo||p,optional:!0,idBlock:{tagClass:3,tagNumber:0},value:Cl.schema().valueBlock.value}),new et({value:[new fe({name:t.recipientInfos||p,value:hr.schema()})]}),kt.schema(t.encryptedContentInfo||{}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new fe({name:t.unprotectedAttrs||p,value:nt.schema()})]})]})}fromSchema(e){V(e,UD);let t=R(e,e,s.schema({names:{version:_u,originatorInfo:Pi,recipientInfos:Mu,encryptedContentInfo:{names:{blockName:$u}},unprotectedAttrs:Ti}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,Pi in t.result&&(this.originatorInfo=new Cl({schema:new b({value:t.result.originatorInfo.valueBlock.value})})),this.recipientInfos=Array.from(t.result.recipientInfos,n=>new hr({schema:n})),this.encryptedContentInfo=new kt({schema:t.result.encryptedContentInfo}),Ti in t.result&&(this.unprotectedAttrs=Array.from(t.result.unprotectedAttrs,n=>new nt({schema:n})));}toSchema(){let e=[];return e.push(new k({value:this.version})),this.originatorInfo&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:this.originatorInfo.toSchema().valueBlock.value})),e.push(new et({value:Array.from(this.recipientInfos,t=>t.toSchema())})),e.push(this.encryptedContentInfo.toSchema()),this.unprotectedAttrs&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.unprotectedAttrs,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={version:this.version,recipientInfos:Array.from(this.recipientInfos,t=>t.toJSON()),encryptedContentInfo:this.encryptedContentInfo.toJSON()};return this.originatorInfo&&(e.originatorInfo=this.originatorInfo.toJSON()),this.unprotectedAttrs&&(e.unprotectedAttrs=Array.from(this.unprotectedAttrs,t=>t.toJSON())),e}addRecipientByCertificate(e,t,n,r=ve(!0)){let i=Object.assign({useOAEP:!0,oaepHashAlgorithm:"SHA-512"},nk,t||{});if(e.subjectPublicKeyInfo.algorithm.algorithmId.indexOf("1.2.840.113549")!==-1)n=1;else if(e.subjectPublicKeyInfo.algorithm.algorithmId.indexOf("1.2.840.10045")!==-1)n=2;else throw new Error(`Unknown type of certificate's public key: ${e.subjectPublicKeyInfo.algorithm.algorithmId}`);switch(n){case 1:{let a,o;if(i.useOAEP===!0){a=r.getOIDByAlgorithm({name:"RSA-OAEP"},!0,"keyEncryptionAlgorithm");let u=r.getOIDByAlgorithm({name:i.oaepHashAlgorithm},!0,"RSAES-OAEP-params"),l=new P({algorithmId:u,algorithmParams:new Xe});o=new Nl({hashAlgorithm:l,maskGenAlgorithm:new P({algorithmId:"1.2.840.113549.1.1.8",algorithmParams:l.toSchema()})}).toSchema();}else {if(a=r.getOIDByAlgorithm({name:"RSAES-PKCS1-v1_5"}),a===p)throw new Error("Can not find OID for RSAES-PKCS1-v1_5");o=new Xe;}let c=new Tl({version:0,rid:new vt({issuer:e.issuer,serialNumber:e.serialNumber}),keyEncryptionAlgorithm:new P({algorithmId:a,algorithmParams:o}),recipientCertificate:e});this.recipientInfos.push(new hr({variant:1,value:c}));}break;case 2:{let a=new qi({variant:1,value:new vt({issuer:e.issuer,serialNumber:e.serialNumber})});this._addKeyAgreeRecipientInfo(a,i,{recipientCertificate:e},r);}break;default:throw new Error(`Unknown "variant" value: ${n}`)}return !0}addRecipientByPreDefinedData(e,t={},n,r=ve(!0)){if($e.assert(e,"preDefinedData","ArrayBuffer"),!e.byteLength)throw new Error("Pre-defined data could have zero length");if(!t.keyIdentifier){let i=new ArrayBuffer(16),a=new Uint8Array(i);r.getRandomValues(a),t.keyIdentifier=i;}switch(t.hmacHashAlgorithm||(t.hmacHashAlgorithm="SHA-512"),t.iterationCount===void 0&&(t.iterationCount=2048),t.keyEncryptionAlgorithm||(t.keyEncryptionAlgorithm={name:"AES-KW",length:256}),t.keyEncryptionAlgorithmParams||(t.keyEncryptionAlgorithmParams=new Xe),n){case 1:{let i=r.getOIDByAlgorithm(t.keyEncryptionAlgorithm,!0,"keyEncryptionAlgorithm"),a=new Dl({version:4,kekid:new Jo({keyIdentifier:new L({valueHex:t.keyIdentifier})}),keyEncryptionAlgorithm:new P({algorithmId:i,algorithmParams:t.keyEncryptionAlgorithmParams}),preDefinedKEK:e});this.recipientInfos.push(new hr({variant:3,value:a}));}break;case 2:{let i=r.getOIDByAlgorithm({name:"PBKDF2"},!0,"keyDerivationAlgorithm"),a=new ArrayBuffer(64),o=new Uint8Array(a);r.getRandomValues(o);let c=r.getOIDByAlgorithm({name:"HMAC",hash:{name:t.hmacHashAlgorithm}},!0,"hmacHashAlgorithm"),u=new $i({salt:new L({valueHex:a}),iterationCount:t.iterationCount,prf:new P({algorithmId:c,algorithmParams:new Xe})}),l=r.getOIDByAlgorithm(t.keyEncryptionAlgorithm,!0,"keyEncryptionAlgorithm"),h=new Ll({version:0,keyDerivationAlgorithm:new P({algorithmId:i,algorithmParams:u.toSchema()}),keyEncryptionAlgorithm:new P({algorithmId:l,algorithmParams:t.keyEncryptionAlgorithmParams}),password:e});this.recipientInfos.push(new hr({variant:4,value:h}));}break;default:throw new Error(`Unknown value for "variant": ${n}`)}}addRecipientByKeyIdentifier(e,t,n,r=ve(!0)){let i=Object.assign({},nk,n||{}),a=new qi({variant:2,value:new Ol({subjectKeyIdentifier:new L({valueHex:t})})});this._addKeyAgreeRecipientInfo(a,i,{recipientPublicKey:e},r);}_addKeyAgreeRecipientInfo(e,t,n,r=ve(!0)){let i=new Rl({rid:e}),a=r.getOIDByAlgorithm({name:"AES-KW",length:t.kekEncryptionLength},!0,"keyEncryptionAlgorithm"),o=new P({algorithmId:a}),c=r.getOIDByAlgorithm({name:"ECDH",kdf:t.kdfAlgorithm},!0,"KeyAgreeRecipientInfo"),u=new ArrayBuffer(64),l=new Uint8Array(u);r.getRandomValues(l);let h={version:3,ukm:new L({valueHex:u}),keyEncryptionAlgorithm:new P({algorithmId:c,algorithmParams:o.toSchema()}),recipientEncryptedKeys:new Wo({encryptedKeys:[i]})},m=new Vl(Object.assign(h,n));this.recipientInfos.push(new hr({variant:2,value:m}));}async encrypt(e,t,n=ve(!0)){let r=new ArrayBuffer(16),i=new Uint8Array(r);n.getRandomValues(i);let a=new Uint8Array(t),o=n.getOIDByAlgorithm(e,!0,"contentEncryptionAlgorithm"),c=await n.generateKey(e,!0,["encrypt"]),u=await n.encrypt({name:e.name,iv:i},c,a),l=await n.exportKey("raw",c);this.version=2,this.encryptedContentInfo=new kt({disableSplit:this.policy.disableSplit,contentType:"1.2.840.113549.1.7.1",contentEncryptionAlgorithm:new P({algorithmId:o,algorithmParams:new L({valueHex:r})}),encryptedContent:new L({valueHex:u})});let h=async S=>{let C=this.recipientInfos[S].value,N,x;if(C.recipientPublicKey)N=C.recipientPublicKey.algorithm.namedCurve,x=C.recipientPublicKey;else if(C.recipientCertificate){let U=C.recipientCertificate.subjectPublicKeyInfo.algorithm.algorithmParams;if(U.constructor.blockName()!==G.blockName())throw new Error(`Incorrect "recipientCertificate" for index ${S}`);switch(U.valueBlock.toString()){case"1.2.840.10045.3.1.7":N="P-256";break;case"1.3.132.0.34":N="P-384";break;case"1.3.132.0.35":N="P-521";break;default:throw new Error(`Incorrect curve OID for index ${S}`)}x=await C.recipientCertificate.getPublicKey({algorithm:{algorithm:{name:"ECDH",namedCurve:N},usages:[]}},n);}else throw new Error("Unsupported RecipientInfo");let v=HD[N],I=await n.generateKey({name:"ECDH",namedCurve:N},!0,["deriveBits"]),D=await n.exportKey("spki",I.publicKey),F=await n.deriveBits({name:"ECDH",public:x},I.privateKey,v),M=new P({schema:C.keyEncryptionAlgorithm.algorithmParams}),W=n.getAlgorithmByOID(M.algorithmId,!0,"aesKWAlgorithm"),se=W.length,q=new ArrayBuffer(4),J=new Uint8Array(q);for(let U=3;U>=0;U--)J[U]=se,se>>=8;let Be=new zm({keyInfo:new P({algorithmId:M.algorithmId}),entityUInfo:C.ukm,suppPubInfo:new L({valueHex:q})}).toSchema().toBER(!1),j=n.getAlgorithmByOID(C.keyEncryptionAlgorithm.algorithmId,!0,"ecdhAlgorithm"),_=await FN(j.kdf,F,W.length,Be,n),Q=await n.importKey("raw",_,{name:"AES-KW"},!0,["wrapKey"]),me=await n.wrapKey("raw",c,Q,{name:"AES-KW"}),X=new Go;return X.variant=3,X.value=Bl.fromBER(D),C.originator=X,C.recipientEncryptedKeys.encryptedKeys[0].encryptedKey=new L({valueHex:me}),{ecdhPrivateKey:I.privateKey}},m=async S=>{let C=this.recipientInfos[S].value,N=n.getAlgorithmByOID(C.keyEncryptionAlgorithm.algorithmId,!0,"keyEncryptionAlgorithm");if(N.name==="RSA-OAEP"){let x=C.keyEncryptionAlgorithm.algorithmParams,v=new Nl({schema:x});if(N.hash=n.getAlgorithmByOID(v.hashAlgorithm.algorithmId),!("name"in N.hash))throw new Error(`Incorrect OID for hash algorithm: ${v.hashAlgorithm.algorithmId}`)}try{let x=await C.recipientCertificate.getPublicKey({algorithm:{algorithm:N,usages:["encrypt","wrapKey"]}},n),v=await n.encrypt(x.algorithm,x,l);C.encryptedKey=new L({valueHex:v});}catch{}},y=async S=>{let C=this.recipientInfos[S].value,N=n.getAlgorithmByOID(C.keyEncryptionAlgorithm.algorithmId,!0,"kekAlgorithm"),x=await n.importKey("raw",new Uint8Array(C.preDefinedKEK),N,!0,["wrapKey"]),v=await n.wrapKey("raw",c,x,N);C.encryptedKey=new L({valueHex:v});},g=async S=>{let C=this.recipientInfos[S].value,N;if(!C.keyDerivationAlgorithm)throw new Error('Please append encoded "keyDerivationAlgorithm"');if(!C.keyDerivationAlgorithm.algorithmParams)throw new Error('Incorrectly encoded "keyDerivationAlgorithm"');try{N=new $i({schema:C.keyDerivationAlgorithm.algorithmParams});}catch{throw new Error('Incorrectly encoded "keyDerivationAlgorithm"')}let x=new Uint8Array(C.password),v=await n.importKey("raw",x,"PBKDF2",!1,["deriveKey"]),I=n.getAlgorithmByOID(C.keyEncryptionAlgorithm.algorithmId,!0,"kekAlgorithm"),D="SHA-1";N.prf&&(D=n.getAlgorithmByOID(N.prf.algorithmId,!0,"prfAlgorithm").hash.name);let F=new Uint8Array(N.salt.valueBlock.valueHex),M=N.iterationCount,W=await n.deriveKey({name:"PBKDF2",hash:{name:D},salt:F,iterations:M},v,I,!0,["wrapKey"]),se=await n.wrapKey("raw",c,W,I);C.encryptedKey=new L({valueHex:se});},w=[];for(let S=0;S<this.recipientInfos.length;S++)switch(this.recipientInfos[S].variant){case 1:w.push(await m(S));break;case 2:w.push(await h(S));break;case 3:w.push(await y(S));break;case 4:w.push(await g(S));break;default:throw new Error(`Unknown recipient type in array with index ${S}`)}return w}async decrypt(e,t,n=ve(!0)){let r=t||{};if(e+1>this.recipientInfos.length)throw new Error(`Maximum value for "index" is: ${this.recipientInfos.length-1}`);let i=async w=>{let S=this.recipientInfos[w].value,C,N,x,v=S.originator;if(r.recipientCertificate){let j=r.recipientCertificate.subjectPublicKeyInfo.algorithm.algorithmParams;if(j.constructor.blockName()!==G.blockName())throw new Error(`Incorrect "recipientCertificate" for index ${w}`);C=j.valueBlock.toString();}else if(v.value.algorithm.algorithmParams){let j=v.value.algorithm.algorithmParams;if(j.constructor.blockName()!==G.blockName())throw new Error(`Incorrect originator for index ${w}`);C=j.valueBlock.toString();}else throw new Error('Parameter "recipientCertificate" is mandatory for "KeyAgreeRecipientInfo" if algorithm params are missing from originator');if(!r.recipientPrivateKey)throw new Error('Parameter "recipientPrivateKey" is mandatory for "KeyAgreeRecipientInfo"');switch(C){case"1.2.840.10045.3.1.7":N="P-256",x=256;break;case"1.3.132.0.34":N="P-384",x=384;break;case"1.3.132.0.35":N="P-521",x=528;break;default:throw new Error(`Incorrect curve OID for index ${w}`)}let I,D=n;re.isBufferSource(r.recipientPrivateKey)?I=await n.importKey("pkcs8",r.recipientPrivateKey,{name:"ECDH",namedCurve:N},!0,["deriveBits"]):(I=r.recipientPrivateKey,"crypto"in r&&r.crypto&&(D=r.crypto.subtle)),"algorithmParams"in v.value.algorithm||(v.value.algorithm.algorithmParams=new G({value:C}));let F=v.value.toSchema().toBER(!1),M=await n.importKey("spki",F,{name:"ECDH",namedCurve:N},!0,[]),W=await D.deriveBits({name:"ECDH",public:M},I,x);async function se(j){j=j||!1;let _=new P({schema:S.keyEncryptionAlgorithm.algorithmParams}),Q=n.getAlgorithmByOID(_.algorithmId,!0,"kwAlgorithm"),me=Q.length,X=new ArrayBuffer(4),U=new Uint8Array(X);for(let Ve=3;Ve>=0;Ve--)U[Ve]=me,me>>=8;let z={algorithmId:_.algorithmId};j&&(z.algorithmParams=new Xe);let pe=new zm({keyInfo:new P(z),entityUInfo:S.ukm,suppPubInfo:new L({valueHex:X})}).toSchema().toBER(!1),xe=n.getAlgorithmByOID(S.keyEncryptionAlgorithm.algorithmId,!0,"ecdhAlgorithm");if(!xe.name)throw new Error(`Incorrect OID for key encryption algorithm: ${S.keyEncryptionAlgorithm.algorithmId}`);return FN(xe.kdf,W,Q.length,pe,n)}let q=await se(),J=async j=>n.importKey("raw",j,{name:"AES-KW"},!0,["unwrapKey"]),ae=await J(q),Be=async j=>{let _=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,Q=n.getAlgorithmByOID(_,!0,"contentEncryptionAlgorithm");return n.unwrapKey("raw",S.recipientEncryptedKeys.encryptedKeys[0].encryptedKey.valueBlock.valueHexView,j,{name:"AES-KW"},Q,!0,["decrypt"])};try{return await Be(ae)}catch{let j=await se(!0),_=await J(j);return Be(_)}},a=async w=>{let S=this.recipientInfos[w].value;if(!r.recipientPrivateKey)throw new Error('Parameter "recipientPrivateKey" is mandatory for "KeyTransRecipientInfo"');let C=n.getAlgorithmByOID(S.keyEncryptionAlgorithm.algorithmId,!0,"keyEncryptionAlgorithm");if(C.name==="RSA-OAEP"){let F=S.keyEncryptionAlgorithm.algorithmParams,M=new Nl({schema:F});if(C.hash=n.getAlgorithmByOID(M.hashAlgorithm.algorithmId),!("name"in C.hash))throw new Error(`Incorrect OID for hash algorithm: ${M.hashAlgorithm.algorithmId}`)}let N,x=n;re.isBufferSource(r.recipientPrivateKey)?N=await n.importKey("pkcs8",r.recipientPrivateKey,C,!0,["decrypt"]):(N=r.recipientPrivateKey,"crypto"in r&&r.crypto&&(x=r.crypto.subtle));let v=await x.decrypt(N.algorithm,N,S.encryptedKey.valueBlock.valueHexView),I=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,D=n.getAlgorithmByOID(I,!0,"contentEncryptionAlgorithm");if(!("name"in D))throw new Error(`Incorrect "contentEncryptionAlgorithm": ${I}`);return n.importKey("raw",v,D,!0,["decrypt"])},o=async w=>{let S=this.recipientInfos[w].value;if(!r.preDefinedData)throw new Error('Parameter "preDefinedData" is mandatory for "KEKRecipientInfo"');let C=n.getAlgorithmByOID(S.keyEncryptionAlgorithm.algorithmId,!0,"kekAlgorithm"),N=await n.importKey("raw",r.preDefinedData,C,!0,["unwrapKey"]),x=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,v=n.getAlgorithmByOID(x,!0,"contentEncryptionAlgorithm");if(!v.name)throw new Error(`Incorrect "contentEncryptionAlgorithm": ${x}`);return n.unwrapKey("raw",S.encryptedKey.valueBlock.valueHexView,N,C,v,!0,["decrypt"])},c=async w=>{let S=this.recipientInfos[w].value,C;if(!r.preDefinedData)throw new Error('Parameter "preDefinedData" is mandatory for "KEKRecipientInfo"');if(!S.keyDerivationAlgorithm)throw new Error('Please append encoded "keyDerivationAlgorithm"');if(!S.keyDerivationAlgorithm.algorithmParams)throw new Error('Incorrectly encoded "keyDerivationAlgorithm"');try{C=new $i({schema:S.keyDerivationAlgorithm.algorithmParams});}catch{throw new Error('Incorrectly encoded "keyDerivationAlgorithm"')}let N=await n.importKey("raw",r.preDefinedData,"PBKDF2",!1,["deriveKey"]),x=n.getAlgorithmByOID(S.keyEncryptionAlgorithm.algorithmId,!0,"keyEncryptionAlgorithm"),v=C.prf?n.getAlgorithmByOID(C.prf.algorithmId,!0,"prfAlgorithm").hash.name:"SHA-1",I=new Uint8Array(C.salt.valueBlock.valueHex),D=C.iterationCount,F=await n.deriveKey({name:"PBKDF2",hash:{name:v},salt:I,iterations:D},N,x,!0,["unwrapKey"]),M=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,W=n.getAlgorithmByOID(M,!0,"contentEncryptionAlgorithm");return n.unwrapKey("raw",S.encryptedKey.valueBlock.valueHexView,F,x,W,!0,["decrypt"])},u;switch(this.recipientInfos[e].variant){case 1:u=await a(e);break;case 2:u=await i(e);break;case 3:u=await o(e);break;case 4:u=await c(e);break;default:throw new Error(`Unknown recipient type in array with index ${e}`)}let l=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,h=n.getAlgorithmByOID(l,!0,"contentEncryptionAlgorithm"),m=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmParams.valueBlock.valueHex,y=new Uint8Array(m);if(!this.encryptedContentInfo.encryptedContent)throw new Error("Required property `encryptedContent` is empty");let g=this.encryptedContentInfo.getEncryptedContent();return n.decrypt({name:h.name,iv:y},u,g)}};Ym.CLASS_NAME="EnvelopedData";var zc="safeContents",Pf="parsedValue",rk="contentInfos",Zm=class s extends O{constructor(e={}){super(),this.safeContents=d(e,zc,s.defaultValues(zc)),Pf in e&&(this.parsedValue=d(e,Pf,s.defaultValues(Pf))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case zc:return [];case Pf:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case zc:return t.length===0;case Pf:return t instanceof Object&&Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.contentInfos||p,value:tt.schema()})]})}fromSchema(e){V(e,[rk]);let t=R(e,e,s.schema({names:{contentInfos:rk}}));T.assertSchema(t,this.className),this.safeContents=Array.from(t.result.contentInfos,n=>new tt({schema:n}));}toSchema(){return new b({value:Array.from(this.safeContents,e=>e.toSchema())})}toJSON(){return {safeContents:Array.from(this.safeContents,e=>e.toJSON())}}async parseInternalValues(e,t=ve(!0)){if(Re.assert(e,zc),$e.assert(e.safeContents,zc,"Array"),e.safeContents.length!==this.safeContents.length)throw new $e('Length of "parameters.safeContents" must be equal to "this.safeContents.length"');this.parsedValue={safeContents:[]};for(let[n,r]of this.safeContents.entries()){let i=e.safeContents[n],a=`parameters.safeContents[${n}]`;switch(r.contentType){case SA:{$e.assert(r.content,"this.safeContents[j].content",L);let o=r.content.getValue();this.parsedValue.safeContents.push({privacyMode:0,value:Mi.fromBER(o)});}break;case yk:{let o=new Ym({schema:r.content});Re.assert(a,i,"recipientCertificate","recipientKey");let c=i,u=c.recipientCertificate,l=c.recipientKey,h=await o.decrypt(0,{recipientCertificate:u,recipientPrivateKey:l},t);this.parsedValue.safeContents.push({privacyMode:2,value:Mi.fromBER(h)});}break;case wk:{let o=new Qo({schema:r.content});Re.assert(a,i,"password");let c=i.password,u=await o.decrypt({password:c},t);this.parsedValue.safeContents.push({privacyMode:1,value:Mi.fromBER(u)});}break;default:throw new Error(`Unknown "contentType" for AuthenticatedSafe: " ${r.contentType}`)}}}async makeInternalValues(e,t=ve(!0)){if(!this.parsedValue)throw new Error('Please run "parseValues" first or add "parsedValue" manually');if($e.assert(this.parsedValue,"this.parsedValue","object"),$e.assert(this.parsedValue.safeContents,"this.parsedValue.safeContents","Array"),$e.assert(e,"parameters","object"),Re.assert(e,"safeContents"),$e.assert(e.safeContents,"parameters.safeContents","Array"),e.safeContents.length!==this.parsedValue.safeContents.length)throw new $e('Length of "parameters.safeContents" must be equal to "this.parsedValue.safeContents"');this.safeContents=[];for(let[n,r]of this.parsedValue.safeContents.entries())switch(Re.assert("content",r,"privacyMode","value"),$e.assert(r.value,"content.value",Mi),r.privacyMode){case 0:{let i=r.value.toSchema().toBER(!1);this.safeContents.push(new tt({contentType:"1.2.840.113549.1.7.1",content:new L({valueHex:i})}));}break;case 1:{let i=new Qo,a=e.safeContents[n];a.contentToEncrypt=r.value.toSchema().toBER(!1),await i.encrypt(a,t),this.safeContents.push(new tt({contentType:"1.2.840.113549.1.7.6",content:i.toSchema()}));}break;case 2:{let i=new Ym,a=r.value.toSchema().toBER(!1),o=e.safeContents[n];switch(Re.assert(`parameters.safeContents[${n}]`,o,"encryptingCertificate","encryptionAlgorithm"),!0){case o.encryptionAlgorithm.name.toLowerCase()==="aes-cbc":case o.encryptionAlgorithm.name.toLowerCase()==="aes-gcm":break;default:throw new Error(`Incorrect parameter "encryptionAlgorithm" in "parameters.safeContents[i]": ${o.encryptionAlgorithm}`)}switch(!0){case o.encryptionAlgorithm.length===128:case o.encryptionAlgorithm.length===192:case o.encryptionAlgorithm.length===256:break;default:throw new Error(`Incorrect parameter "encryptionAlgorithm.length" in "parameters.safeContents[i]": ${o.encryptionAlgorithm.length}`)}let c=o.encryptionAlgorithm;i.addRecipientByCertificate(o.encryptingCertificate,{},void 0,t),await i.encrypt(c,a,t),this.safeContents.push(new tt({contentType:"1.2.840.113549.1.7.3",content:i.toSchema()}));}break;default:throw new Error(`Incorrect value for "content.privacyMode": ${r.privacyMode}`)}return this}};Zm.CLASS_NAME="AuthenticatedSafe";var Co="hashAlgorithm",qu="issuerNameHash",Fu="issuerKeyHash",No="serialNumber",_D=[Co,qu,Fu,No],ns=class s extends O{static async create(e,t,n=ve(!0)){let r=new s;return await r.createForCertificate(e,t,n),r}constructor(e={}){super(),this.hashAlgorithm=d(e,Co,s.defaultValues(Co)),this.issuerNameHash=d(e,qu,s.defaultValues(qu)),this.issuerKeyHash=d(e,Fu,s.defaultValues(Fu)),this.serialNumber=d(e,No,s.defaultValues(No)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Co:return new P;case qu:case Fu:return new L;case No:return new k;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Co:return t.algorithmId===p&&!("algorithmParams"in t);case qu:case Fu:case No:return t.isEqual(s.defaultValues(No));default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.hashAlgorithmObject||{names:{blockName:t.hashAlgorithm||p}}),new L({name:t.issuerNameHash||p}),new L({name:t.issuerKeyHash||p}),new k({name:t.serialNumber||p})]})}fromSchema(e){V(e,_D);let t=R(e,e,s.schema({names:{hashAlgorithm:Co,issuerNameHash:qu,issuerKeyHash:Fu,serialNumber:No}}));T.assertSchema(t,this.className),this.hashAlgorithm=new P({schema:t.result.hashAlgorithm}),this.issuerNameHash=t.result.issuerNameHash,this.issuerKeyHash=t.result.issuerKeyHash,this.serialNumber=t.result.serialNumber;}toSchema(){return new b({value:[this.hashAlgorithm.toSchema(),this.issuerNameHash,this.issuerKeyHash,this.serialNumber]})}toJSON(){return {hashAlgorithm:this.hashAlgorithm.toJSON(),issuerNameHash:this.issuerNameHash.toJSON(),issuerKeyHash:this.issuerKeyHash.toJSON(),serialNumber:this.serialNumber.toJSON()}}isEqual(e){return !(this.hashAlgorithm.algorithmId!==e.hashAlgorithm.algorithmId||!re.isEqual(this.issuerNameHash.valueBlock.valueHexView,e.issuerNameHash.valueBlock.valueHexView)||!re.isEqual(this.issuerKeyHash.valueBlock.valueHexView,e.issuerKeyHash.valueBlock.valueHexView)||!this.serialNumber.isEqual(e.serialNumber))}async createForCertificate(e,t,n=ve(!0)){Re.assert(t,Co,"issuerCertificate");let r=n.getOIDByAlgorithm({name:t.hashAlgorithm},!0,"hashAlgorithm");this.hashAlgorithm=new P({algorithmId:r,algorithmParams:new Xe});let i=t.issuerCertificate;this.serialNumber=e.serialNumber;let a=await n.digest({name:t.hashAlgorithm},i.subject.toSchema().toBER(!1));this.issuerNameHash=new L({valueHex:a});let o=i.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView,c=await n.digest({name:t.hashAlgorithm},o);this.issuerKeyHash=new L({valueHex:c});}};ns.CLASS_NAME="CertID";var Ku="certID",Gu="certStatus",Wu="thisUpdate",Bi="nextUpdate",ko="singleExtensions",MD=[Ku,Gu,Wu,Bi,ko],Qm=class s extends O{constructor(e={}){super(),this.certID=d(e,Ku,s.defaultValues(Ku)),this.certStatus=d(e,Gu,s.defaultValues(Gu)),this.thisUpdate=d(e,Wu,s.defaultValues(Wu)),Bi in e&&(this.nextUpdate=d(e,Bi,s.defaultValues(Bi))),ko in e&&(this.singleExtensions=d(e,ko,s.defaultValues(ko))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ku:return new ns;case Gu:return {};case Wu:case Bi:return new Date(0,0,0);case ko:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Ku:return ns.compareWithDefault("hashAlgorithm",t.hashAlgorithm)&&ns.compareWithDefault("issuerNameHash",t.issuerNameHash)&&ns.compareWithDefault("issuerKeyHash",t.issuerKeyHash)&&ns.compareWithDefault("serialNumber",t.serialNumber);case Gu:return Object.keys(t).length===0;case Wu:case Bi:return t===s.defaultValues(e);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[ns.schema(t.certID||{}),new We({value:[new ie({name:t.certStatus||p,idBlock:{tagClass:3,tagNumber:0}}),new A({name:t.certStatus||p,idBlock:{tagClass:3,tagNumber:1},value:[new Ge,new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new pn]})]}),new ie({name:t.certStatus||p,idBlock:{tagClass:3,tagNumber:2},lenBlock:{length:1}})]}),new Ge({name:t.thisUpdate||p}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new Ge({name:t.nextUpdate||p})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[ft.schema(t.singleExtensions||{})]})]})}fromSchema(e){V(e,MD);let t=R(e,e,s.schema({names:{certID:{names:{blockName:Ku}},certStatus:Gu,thisUpdate:Wu,nextUpdate:Bi,singleExtensions:{names:{blockName:ko}}}}));T.assertSchema(t,this.className),this.certID=new ns({schema:t.result.certID}),this.certStatus=t.result.certStatus,this.thisUpdate=t.result.thisUpdate.toDate(),Bi in t.result&&(this.nextUpdate=t.result.nextUpdate.toDate()),ko in t.result&&(this.singleExtensions=Array.from(t.result.singleExtensions.valueBlock.value,n=>new ds({schema:n})));}toSchema(){let e=[];return e.push(this.certID.toSchema()),e.push(this.certStatus),e.push(new Ge({valueDate:this.thisUpdate})),this.nextUpdate&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[new Ge({valueDate:this.nextUpdate})]})),this.singleExtensions&&e.push(new A({idBlock:{tagClass:3,tagNumber:1},value:[new b({value:Array.from(this.singleExtensions,t=>t.toSchema())})]})),new b({value:e})}toJSON(){let e={certID:this.certID.toJSON(),certStatus:this.certStatus.toJSON(),thisUpdate:this.thisUpdate};return this.nextUpdate&&(e.nextUpdate=this.nextUpdate),this.singleExtensions&&(e.singleExtensions=Array.from(this.singleExtensions,t=>t.toJSON())),e}};Qm.CLASS_NAME="SingleResponse";var Sy="tbs",Po="version",cm="responderID",um="producedAt",lm="responses",Ju="responseExtensions",Xo="ResponseData",Oy=`${Xo}.${Po}`,zu=`${Xo}.${cm}`,F2=`${Xo}.${um}`,K2=`${Xo}.${lm}`,Ry=`${Xo}.${Ju}`,$D=[Xo,Oy,zu,F2,K2,Ry],Xs=class s extends O{get tbs(){return re.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e);}constructor(e={}){super(),this.tbsView=new Uint8Array(d(e,Sy,s.defaultValues(Sy))),Po in e&&(this.version=d(e,Po,s.defaultValues(Po))),this.responderID=d(e,cm,s.defaultValues(cm)),this.producedAt=d(e,um,s.defaultValues(um)),this.responses=d(e,lm,s.defaultValues(lm)),Ju in e&&(this.responseExtensions=d(e,Ju,s.defaultValues(Ju))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Po:return 0;case Sy:return ut;case cm:return {};case um:return new Date(0,0,0);case lm:case Ju:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Sy:return t.byteLength===0;case cm:return Object.keys(t).length===0;case um:return t===s.defaultValues(e);case lm:case Ju:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||Xo,value:[new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new k({name:t.version||Oy})]}),new We({value:[new A({name:t.responderID||zu,idBlock:{tagClass:3,tagNumber:1},value:[Je.schema(t.ResponseDataByName||{names:{blockName:"ResponseData.byName"}})]}),new A({name:t.responderID||zu,idBlock:{tagClass:3,tagNumber:2},value:[new L({name:t.ResponseDataByKey||"ResponseData.byKey"})]})]}),new Ge({name:t.producedAt||F2}),new b({value:[new fe({name:K2,value:Qm.schema(t.response||{})})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[ft.schema(t.extensions||{names:{blockName:Ry}})]})]})}fromSchema(e){V(e,$D);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.tbsView=t.result.ResponseData.valueBeforeDecodeView,Oy in t.result&&(this.version=t.result[Oy].valueBlock.valueDec),t.result[zu].idBlock.tagNumber===1?this.responderID=new Je({schema:t.result[zu].valueBlock.value[0]}):this.responderID=t.result[zu].valueBlock.value[0],this.producedAt=t.result[F2].toDate(),this.responses=Array.from(t.result[K2],n=>new Qm({schema:n})),Ry in t.result&&(this.responseExtensions=Array.from(t.result[Ry].valueBlock.value,n=>new ds({schema:n})));}toSchema(e=!1){let t;if(e===!1){if(!this.tbsView.byteLength)return s.schema();let n=ht(this.tbsView);T.assert(n,"TBS Response Data"),t=n.result;}else {let n=[];Po in this&&n.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[new k({value:this.version})]})),this.responderID instanceof Je?n.push(new A({idBlock:{tagClass:3,tagNumber:1},value:[this.responderID.toSchema()]})):n.push(new A({idBlock:{tagClass:3,tagNumber:2},value:[this.responderID]})),n.push(new Ge({valueDate:this.producedAt})),n.push(new b({value:Array.from(this.responses,r=>r.toSchema())})),this.responseExtensions&&n.push(new A({idBlock:{tagClass:3,tagNumber:1},value:[new b({value:Array.from(this.responseExtensions,r=>r.toSchema())})]})),t=new b({value:n});}return t}toJSON(){let e={};return Po in this&&(e.version=this.version),this.responderID&&(e.responderID=this.responderID),this.producedAt&&(e.producedAt=this.producedAt),this.responses&&(e.responses=Array.from(this.responses,t=>t.toJSON())),this.responseExtensions&&(e.responseExtensions=Array.from(this.responseExtensions,t=>t.toJSON())),e}};Xs.CLASS_NAME="ResponseData";var C2="trustedCerts",N2="certs",k2="crls",P2="ocsps",T2="checkDate",B2="findOrigin",O2="findIssuer",Ho;(function(s){s[s.unknown=-1]="unknown",s[s.success=0]="success",s[s.noRevocation=11]="noRevocation",s[s.noPath=60]="noPath",s[s.noValidPath=97]="noValidPath";})(Ho||(Ho={}));var Hi=class s extends Error{constructor(e,t){super(t),this.name=s.NAME,this.code=e,this.message=t;}};Hi.NAME="ChainValidationError";function qD(s,e){for(let t=0;t<e.length;t++)if(re.isEqual(s.tbsView,e[t].tbsView))return !0;return !1}var Xm=class s{constructor(e={}){this.trustedCerts=d(e,C2,this.defaultValues(C2)),this.certs=d(e,N2,this.defaultValues(N2)),this.crls=d(e,k2,this.defaultValues(k2)),this.ocsps=d(e,P2,this.defaultValues(P2)),this.checkDate=d(e,T2,this.defaultValues(T2)),this.findOrigin=d(e,B2,this.defaultValues(B2)),this.findIssuer=d(e,O2,this.defaultValues(O2));}static defaultFindOrigin(e,t){e.tbsView.byteLength===0&&(e.tbsView=new Uint8Array(e.encodeTBS().toBER()));for(let n of t.certs)if(n.tbsView.byteLength===0&&(n.tbsView=new Uint8Array(n.encodeTBS().toBER())),re.isEqual(e.tbsView,n.tbsView))return "Intermediate Certificates";for(let n of t.trustedCerts)if(n.tbsView.byteLength===0&&(n.tbsView=new Uint8Array(n.encodeTBS().toBER())),re.isEqual(e.tbsView,n.tbsView))return "Trusted Certificates";return "Unknown"}async defaultFindIssuer(e,t,n=ve(!0)){let r=[],i=null,a=null,o=null;if(e.subject.isEqual(e.issuer))try{if(await e.verify(void 0,n))return [e]}catch{}if(e.extensions){for(let u of e.extensions)if(u.extnID===wA&&u.parsedValue instanceof Bm){u.parsedValue.keyIdentifier?i=u.parsedValue.keyIdentifier:(u.parsedValue.authorityCertIssuer&&(a=u.parsedValue.authorityCertIssuer),u.parsedValue.authorityCertSerialNumber&&(o=u.parsedValue.authorityCertSerialNumber));break}}function c(u){if(i!==null&&u.extensions){let h=!1;for(let m of u.extensions)if(m.extnID===z7&&m.parsedValue){h=!0,re.isEqual(m.parsedValue.valueBlock.valueHex,i.valueBlock.valueHexView)&&r.push(u);break}if(h)return}let l=!1;o!==null&&(l=u.serialNumber.isEqual(o)),a!==null?u.subject.isEqual(a)&&l&&r.push(u):e.issuer.isEqual(u.subject)&&r.push(u);}for(let u of t.trustedCerts)c(u);for(let u of t.certs)c(u);for(let u=r.length-1;u>=0;u--)try{await e.verify(r[u],n)===!1&&r.splice(u,1);}catch{r.splice(u,1);}return r}defaultValues(e){switch(e){case C2:return [];case N2:return [];case k2:return [];case P2:return [];case T2:return new Date;case B2:return s.defaultFindOrigin;case O2:return this.defaultFindIssuer;default:throw new Error(`Invalid member name for CertificateChainValidationEngine class: ${e}`)}}async sort(e=!1,t=ve(!0)){let n=[],r=async(g,w)=>{let S=[];function C(x){let v=!0;for(let I=0;I<x.length;I++){for(let D=0;D<x.length;D++)if(D!==I&&x[I]===x[D]){v=!1;break}if(!v)break}return v}if(qD(g,this.trustedCerts))return [[g]];let N=await this.findIssuer(g,this,w);if(N.length===0)throw new Error("No valid certificate paths found");for(let x=0;x<N.length;x++){if(re.isEqual(N[x].tbsView,g.tbsView)){S.push([N[x]]);continue}let v=await r(N[x],w);for(let I=0;I<v.length;I++){let D=v[I].slice();D.splice(0,0,N[x]),C(D)?S.push(D):S.push(v[I]);}}return S},i=async g=>{let w=[],S=[],C=[];if(w.push(...n.filter(N=>g.issuer.isEqual(N.subject))),w.length===0)return {status:1,statusMessage:"No certificate's issuers"};if(S.push(...this.crls.filter(N=>N.issuer.isEqual(g.issuer))),S.length===0)return {status:2,statusMessage:"No CRLs for specific certificate issuer"};for(let N=0;N<S.length;N++){let x=S[N];if(!(x.nextUpdate&&x.nextUpdate.value<this.checkDate))for(let v=0;v<w.length;v++)try{if(await S[N].verify({issuerCertificate:w[v]},t)){C.push({crl:S[N],certificate:w[v]});break}}catch{}}return C.length?{status:0,statusMessage:p,result:C}:{status:3,statusMessage:"No valid CRLs found"}},a=async(g,w)=>{let S=t.getAlgorithmByOID(g.signatureAlgorithm.algorithmId);if(!S.name||!S.hash)return 1;for(let C=0;C<this.ocsps.length;C++){let x=await this.ocsps[C].getCertificateStatus(g,w,t);if(x.isForCertificate)return x.status===0?0:1}return 2};async function o(g,w=!1){let S=!1,C=!1,N=!1,x=!1;if(g.extensions){for(let v=0;v<g.extensions.length;v++){let I=g.extensions[v];if(I.critical&&!I.parsedValue)return {result:!1,resultCode:6,resultMessage:`Unable to parse critical certificate extension: ${I.extnID}`};if(I.extnID===Y7){N=!0;let D=new Uint8Array(I.parsedValue.valueBlock.valueHex);(D[0]&4)===4&&(C=!0),(D[0]&2)===2&&(x=!0);}I.extnID===gA&&"cA"in I.parsedValue&&I.parsedValue.cA===!0&&(S=!0);}if(C===!0&&S===!1)return {result:!1,resultCode:3,resultMessage:'Unable to build certificate chain - using "keyCertSign" flag set without BasicConstraints'};if(N===!0&&S===!0&&C===!1)return {result:!1,resultCode:4,resultMessage:'Unable to build certificate chain - "keyCertSign" flag was not set'};if(S===!0&&N===!0&&w&&x===!1)return {result:!1,resultCode:5,resultMessage:'Unable to build certificate chain - intermediate certificate must have "cRLSign" key usage flag'}}return S===!1?{result:!1,resultCode:7,resultMessage:"Unable to build certificate chain - more than one possible end-user certificate"}:{result:!0,resultCode:0,resultMessage:p}}let c=async(g,w)=>{for(let S=0;S<g.length;S++)if(g[S].notBefore.value>w||g[S].notAfter.value<w)return {result:!1,resultCode:8,resultMessage:"The certificate is either not yet valid or expired"};if(g.length<2)return {result:!1,resultCode:9,resultMessage:"Too short certificate path"};for(let S=g.length-2;S>=0;S--)if(g[S].issuer.isEqual(g[S].subject)===!1&&g[S].issuer.isEqual(g[S+1].subject)===!1)return {result:!1,resultCode:10,resultMessage:"Incorrect name chaining"};if(this.crls.length!==0||this.ocsps.length!==0)for(let S=0;S<g.length-1;S++){let C=2,N={status:0,statusMessage:p};if(this.ocsps.length!==0)switch(C=await a(g[S],g[S+1]),C){case 0:continue;case 1:return {result:!1,resultCode:12,resultMessage:"One of certificates was revoked via OCSP response"}}if(this.crls.length!==0){if(N=await i(g[S]),N.status===0&&N.result)for(let x=0;x<N.result.length;x++){if(N.result[x].crl.isCertificateRevoked(g[S]))return {result:!1,resultCode:12,resultMessage:"One of certificates had been revoked"};if((await o(N.result[x].certificate,!0)).result===!1)return {result:!1,resultCode:13,resultMessage:"CRL issuer certificate is not a CA certificate or does not have crlSign flag"}}else if(e===!1)throw new Hi(Ho.noRevocation,`No revocation values found for one of certificates: ${N.statusMessage}`)}else if(C===2)return {result:!1,resultCode:11,resultMessage:"No revocation values found for one of certificates"};if(C===2&&N.status===2&&e){let x=g[S+1],v=!1;if(x.extensions)for(let I of x.extensions)switch(I.extnID){case fk:case yA:case bA:v=!0;break}if(v)throw new Hi(Ho.noRevocation,`No revocation values found for one of certificates: ${N.statusMessage}`)}}for(let[S,C]of g.entries()){if(!S)continue;if(!(await o(C)).result)return {result:!1,resultCode:14,resultMessage:"One of intermediate certificates is not a CA certificate"}}return {result:!0}};n.push(...this.trustedCerts),n.push(...this.certs);for(let g=0;g<n.length;g++)for(let w=0;w<n.length;w++)if(g!==w&&re.isEqual(n[g].tbsView,n[w].tbsView)){n.splice(w,1),g=0;break}let u=n[n.length-1],l,h=[u];if(l=await r(u,t),l.length===0)throw new Hi(Ho.noPath,"Unable to find certificate path");for(let g=l.length-1;g>=0;g--){let w=!1;for(let S=0;S<l[g].length;S++){let C=l[g][S];for(let N=0;N<this.trustedCerts.length;N++)if(re.isEqual(C.tbsView,this.trustedCerts[N].tbsView)){w=!0;break}if(w)break}w||l.splice(g,1);}if(l.length===0)throw new Hi(Ho.noValidPath,"No valid certificate paths found");let m=l[0].length,y=0;for(let g=0;g<l.length;g++)l[g].length<m&&(m=l[g].length,y=g);for(let g=0;g<l[y].length;g++)h.push(l[y][g]);if(l=await c(h,this.checkDate),l.result===!1)throw l;return h}async verify(e={},t=ve(!0)){function n(c,u){let l=Ui(c),h=Ui(u),m=l.split("."),y=h.split("."),g=m.length,w=y.length;if(g===0||w===0||g<w)return !1;for(let S=0;S<g;S++)if(m[S].length===0)return !1;for(let S=0;S<w;S++)if(y[S].length===0){if(S===0){if(w===1)return !1;continue}return !1}for(let S=0;S<w;S++)if(y[w-1-S].length!==0&&m[g-1-S].localeCompare(y[w-1-S])!==0)return !1;return !0}function r(c,u){let l=Ui(c),h=Ui(u),m=l.split("@"),y=h.split("@");if(m.length===0||y.length===0||m.length<y.length)return !1;if(y.length===1){if(n(m[1],y[0])){let w=m[1].split("."),S=y[0].split(".");return S[0].length===0?!0:w.length===S.length}return !1}return l.localeCompare(h)===0}function i(c,u){let l=Ui(c),h=Ui(u),m=l.split("/");if(h.split("/").length>1)return !1;if(m.length>1){for(let w=0;w<m.length;w++)if(m[w].length>0&&m[w].charAt(m[w].length-1)!==":"){l=m[w].split(":")[0];break}}if(n(l,h)){let w=l.split("."),S=h.split(".");return S[0].length===0?!0:w.length===S.length}return !1}function a(c,u){let l=c.valueBlock.valueHexView,h=u.valueBlock.valueHexView;if(l.length===4&&h.length===8){for(let m=0;m<4;m++)if((l[m]^h[m])&h[m+4])return !1;return !0}if(l.length===16&&h.length===32){for(let m=0;m<16;m++)if((l[m]^h[m])&h[m+16])return !1;return !0}return !1}function o(c,u){if(c.typesAndValues.length===0||u.typesAndValues.length===0)return !0;if(c.typesAndValues.length<u.typesAndValues.length)return !1;let l=!0,h=0;for(let m=0;m<u.typesAndValues.length;m++){let y=!1;for(let g=h;g<c.typesAndValues.length;g++)if(y=c.typesAndValues[g].isEqual(u.typesAndValues[m]),c.typesAndValues[g].type===u.typesAndValues[m].type&&(l=l&&y),y===!0)if(h===0||h===g){h=g+1;break}else return !1;if(y===!1)return !1}return h===0?!1:l}try{if(this.certs.length===0)throw new Error("Empty certificate array");let c=e.passedWhenNotRevValues||!1,u=e.initialPolicySet||[Ps],l=e.initialExplicitPolicy||!1,h=e.initialPolicyMappingInhibit||!1,m=e.initialInhibitPolicy||!1,y=e.initialPermittedSubtreesSet||[],g=e.initialExcludedSubtreesSet||[],w=e.initialRequiredNameForms||[],S=l,C=h,N=m,x=[!1,!1,!1],v=0,I=0,D=0,F=y,M=g,W=w,se=1;this.certs=await this.sort(c,t);let q=[];q.push(Ps);let J=[],ae=new Array(this.certs.length-1);for(let U=0;U<this.certs.length-1;U++)ae[U]=!0;J.push(ae);let Be=new Array(this.certs.length-1),j=new Array(this.certs.length-1),_=S?this.certs.length-1:-1;for(let U=this.certs.length-2;U>=0;U--,se++){let z=this.certs[U];if(z.extensions){for(let Y=0;Y<z.extensions.length;Y++){let pe=z.extensions[Y];if(pe.extnID===dk){j[U]=pe.parsedValue;for(let xe=0;xe<q.length;xe++)if(q[xe]===Ps){delete J[xe][U];break}for(let xe=0;xe<pe.parsedValue.certificatePolicies.length;xe++){let Ve=-1,Ut=pe.parsedValue.certificatePolicies[xe].policyIdentifier;for(let He=0;He<q.length;He++)if(Ut===q[He]){Ve=He;break}if(Ve===-1){q.push(Ut);let He=new Array(this.certs.length-1);He[U]=!0,J.push(He);}else J[Ve][U]=!0;}}if(pe.extnID===mk){if(C)return {result:!1,resultCode:98,resultMessage:"Policy mapping prohibited"};Be[U]=pe.parsedValue;}pe.extnID===pk&&S===!1&&(pe.parsedValue.requireExplicitPolicy===0?(S=!0,_=U):x[0]===!1?(x[0]=!0,v=pe.parsedValue.requireExplicitPolicy):v=v>pe.parsedValue.requireExplicitPolicy?pe.parsedValue.requireExplicitPolicy:v,pe.parsedValue.inhibitPolicyMapping===0?C=!0:x[1]===!1?(x[1]=!0,I=pe.parsedValue.inhibitPolicyMapping+1):I=I>pe.parsedValue.inhibitPolicyMapping+1?pe.parsedValue.inhibitPolicyMapping+1:I),pe.extnID===r9&&N===!1&&(pe.parsedValue.valueBlock.valueDec===0?N=!0:x[2]===!1?(x[2]=!0,D=pe.parsedValue.valueBlock.valueDec):D=D>pe.parsedValue.valueBlock.valueDec?pe.parsedValue.valueBlock.valueDec:D);}if(N===!0){let Y=-1;for(let pe=0;pe<q.length;pe++)if(q[pe]===Ps){Y=pe;break}Y!==-1&&delete J[0][U];}S===!1&&x[0]===!0&&(v--,v===0&&(S=!0,_=U,x[0]=!1)),C===!1&&x[1]===!0&&(I--,I===0&&(C=!0,x[1]=!1)),N===!1&&x[2]===!0&&(D--,D===0&&(N=!0,x[2]=!1));}}for(let U=0;U<this.certs.length-1;U++)if(U<this.certs.length-2&&typeof Be[U+1]<"u")for(let z=0;z<Be[U+1].mappings.length;z++){if(Be[U+1].mappings[z].issuerDomainPolicy===Ps||Be[U+1].mappings[z].subjectDomainPolicy===Ps)return {result:!1,resultCode:99,resultMessage:'The "anyPolicy" should not be a part of policy mapping scheme'};let Y=-1,pe=-1;for(let xe=0;xe<q.length;xe++)q[xe]===Be[U+1].mappings[z].issuerDomainPolicy&&(Y=xe),q[xe]===Be[U+1].mappings[z].subjectDomainPolicy&&(pe=xe);typeof J[Y][U]<"u"&&delete J[Y][U];for(let xe=0;xe<j[U].certificatePolicies.length;xe++)if(Be[U+1].mappings[z].subjectDomainPolicy===j[U].certificatePolicies[xe].policyIdentifier&&Y!==-1&&pe!==-1)for(let Ve=0;Ve<=U;Ve++)typeof J[pe][Ve]<"u"&&(J[Y][Ve]=!0,delete J[pe][Ve]);}for(let U=0;U<q.length;U++)if(q[U]===Ps)for(let z=0;z<_;z++)delete J[U][z];let Q=[];for(let U=0;U<J.length;U++){let z=!0;for(let Y=0;Y<this.certs.length-1;Y++){let pe=!1;if(Y<_&&q[U]===Ps&&q.length>1){z=!1;break}if(typeof J[U][Y]>"u"){if(Y>=_){for(let xe=0;xe<q.length;xe++)if(q[xe]===Ps){J[xe][Y]===!0&&(pe=!0);break}}if(!pe){z=!1;break}}}z===!0&&Q.push(q[U]);}let me=[];if(u.length===1&&u[0]===Ps&&S===!1)me=u;else if(Q.length===1&&Q[0]===Ps)me=u;else for(let U=0;U<Q.length;U++)for(let z=0;z<u.length;z++)if(u[z]===Q[U]||u[z]===Ps){me.push(Q[U]);break}let X={result:me.length>0,resultCode:0,resultMessage:me.length>0?p:'Zero "userConstrPolicies" array, no intersections with "authConstrPolicies"',authConstrPolicies:Q,userConstrPolicies:me,explicitPolicyIndicator:S,policyMappings:Be,certificatePath:this.certs};if(me.length===0||X.result===!1)return X;se=1;for(let U=this.certs.length-2;U>=0;U--,se++){let z=this.certs[U],Y=[],pe=[],xe=[];if(z.extensions)for(let ke=0;ke<z.extensions.length;ke++){let ee=z.extensions[ke];ee.extnID===hk&&("permittedSubtrees"in ee.parsedValue&&(pe=pe.concat(ee.parsedValue.permittedSubtrees)),"excludedSubtrees"in ee.parsedValue&&(xe=xe.concat(ee.parsedValue.excludedSubtrees))),ee.extnID===ok&&(Y=Y.concat(ee.parsedValue.altNames));}let Ve=W.length<=0;for(let ke=0;ke<W.length;ke++)switch(W[ke].base.type){case 4:{if(W[ke].base.value.typesAndValues.length!==z.subject.typesAndValues.length)continue;Ve=!0;for(let ee=0;ee<z.subject.typesAndValues.length;ee++)if(z.subject.typesAndValues[ee].type!==W[ke].base.value.typesAndValues[ee].type){Ve=!1;break}if(Ve===!0)break}break;default:}if(Ve===!1)throw X.result=!1,X.resultCode=21,X.resultMessage="No necessary name form found",X;let Ut=[[],[],[],[],[]];for(let ke=0;ke<F.length;ke++)switch(F[ke].base.type){case 1:Ut[0].push(F[ke]);break;case 2:Ut[1].push(F[ke]);break;case 4:Ut[2].push(F[ke]);break;case 6:Ut[3].push(F[ke]);break;case 7:Ut[4].push(F[ke]);break;default:}for(let ke=0;ke<5;ke++){let ee=!1,rs=!1,Cs=Ut[ke];for(let is=0;is<Cs.length;is++){switch(ke){case 0:if(Y.length>0)for(let De=0;De<Y.length;De++)Y[De].type===1&&(rs=!0,ee=ee||r(Y[De].value,Cs[is].base.value));else for(let De=0;De<z.subject.typesAndValues.length;De++)(z.subject.typesAndValues[De].type==="1.2.840.113549.1.9.1"||z.subject.typesAndValues[De].type==="0.9.2342.19200300.100.1.3")&&(rs=!0,ee=ee||r(z.subject.typesAndValues[De].value.valueBlock.value,Cs[is].base.value));break;case 1:if(Y.length>0)for(let De=0;De<Y.length;De++)Y[De].type===2&&(rs=!0,ee=ee||n(Y[De].value,Cs[is].base.value));break;case 2:rs=!0,ee=o(z.subject,Cs[is].base.value);break;case 3:if(Y.length>0)for(let De=0;De<Y.length;De++)Y[De].type===6&&(rs=!0,ee=ee||i(Y[De].value,Cs[is].base.value));break;case 4:if(Y.length>0)for(let De=0;De<Y.length;De++)Y[De].type===7&&(rs=!0,ee=ee||a(Y[De].value,Cs[is].base.value));break;default:}if(ee)break}if(ee===!1&&Cs.length>0&&rs)throw X.result=!1,X.resultCode=41,X.resultMessage='Failed to meet "permitted sub-trees" name constraint',X}let He=!1;for(let ke=0;ke<M.length;ke++){switch(M[ke].base.type){case 1:if(Y.length>=0)for(let ee=0;ee<Y.length;ee++)Y[ee].type===1&&(He=He||r(Y[ee].value,M[ke].base.value));else for(let ee=0;ee<z.subject.typesAndValues.length;ee++)(z.subject.typesAndValues[ee].type==="1.2.840.113549.1.9.1"||z.subject.typesAndValues[ee].type==="0.9.2342.19200300.100.1.3")&&(He=He||r(z.subject.typesAndValues[ee].value.valueBlock.value,M[ke].base.value));break;case 2:if(Y.length>0)for(let ee=0;ee<Y.length;ee++)Y[ee].type===2&&(He=He||n(Y[ee].value,M[ke].base.value));break;case 4:He=He||o(z.subject,M[ke].base.value);break;case 6:if(Y.length>0)for(let ee=0;ee<Y.length;ee++)Y[ee].type===6&&(He=He||i(Y[ee].value,M[ke].base.value));break;case 7:if(Y.length>0)for(let ee=0;ee<Y.length;ee++)Y[ee].type===7&&(He=He||a(Y[ee].value,M[ke].base.value));break;default:}if(He)break}if(He===!0)throw X.result=!1,X.resultCode=42,X.resultMessage='Failed to meet "excluded sub-trees" name constraint',X;F=F.concat(pe),M=M.concat(xe);}return X}catch(c){return c instanceof Error?c instanceof Hi?{result:!1,resultCode:c.code,resultMessage:c.message,error:c}:{result:!1,resultCode:Ho.unknown,resultMessage:c.message,error:c}:c&&typeof c=="object"&&"resultMessage"in c?c:{result:!1,resultCode:-1,resultMessage:`${c}`}}}},Vy="tbsResponseData",hm="signatureAlgorithm",fm="signature",Yu="certs",e0="BasicOCSPResponse",G2=`${e0}.${Vy}`,W2=`${e0}.${hm}`,J2=`${e0}.${fm}`,Dy=`${e0}.${Yu}`,FD=[G2,W2,J2,Dy],zo=class s extends O{constructor(e={}){super(),this.tbsResponseData=d(e,Vy,s.defaultValues(Vy)),this.signatureAlgorithm=d(e,hm,s.defaultValues(hm)),this.signature=d(e,fm,s.defaultValues(fm)),Yu in e&&(this.certs=d(e,Yu,s.defaultValues(Yu))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Vy:return new Xs;case hm:return new P;case fm:return new Ae;case Yu:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case"type":{let n=Xs.compareWithDefault("tbs",t.tbs)&&Xs.compareWithDefault("responderID",t.responderID)&&Xs.compareWithDefault("producedAt",t.producedAt)&&Xs.compareWithDefault("responses",t.responses);return "responseExtensions"in t&&(n=n&&Xs.compareWithDefault("responseExtensions",t.responseExtensions)),n}case hm:return t.algorithmId===p&&!("algorithmParams"in t);case fm:return t.isEqual(s.defaultValues(e));case Yu:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||e0,value:[Xs.schema(t.tbsResponseData||{names:{blockName:G2}}),P.schema(t.signatureAlgorithm||{names:{blockName:W2}}),new Ae({name:t.signature||J2}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new b({value:[new fe({name:Dy,value:jt.schema(t.certs||{})})]})]})]})}fromSchema(e){V(e,FD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.tbsResponseData=new Xs({schema:t.result[G2]}),this.signatureAlgorithm=new P({schema:t.result[W2]}),this.signature=t.result[J2],Dy in t.result&&(this.certs=Array.from(t.result[Dy],n=>new jt({schema:n})));}toSchema(){let e=[];return e.push(this.tbsResponseData.toSchema()),e.push(this.signatureAlgorithm.toSchema()),e.push(this.signature),this.certs&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[new b({value:Array.from(this.certs,t=>t.toSchema())})]})),new b({value:e})}toJSON(){let e={tbsResponseData:this.tbsResponseData.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signature:this.signature.toJSON()};return this.certs&&(e.certs=Array.from(this.certs,t=>t.toJSON())),e}async getCertificateStatus(e,t,n=ve(!0)){let r={isForCertificate:!1,status:2},i={},a=[];for(let o of this.tbsResponseData.responses){let c=n.getAlgorithmByOID(o.certID.hashAlgorithm.algorithmId,!0,"CertID.hashAlgorithm");if(!i[c.name]){i[c.name]=1;let u=new ns;a.push(u),await u.createForCertificate(e,{hashAlgorithm:c.name,issuerCertificate:t},n);}}for(let o of this.tbsResponseData.responses)for(let c of a)if(o.certID.isEqual(c)){r.isForCertificate=!0;try{switch(o.certStatus.idBlock.isConstructed){case!0:o.certStatus.idBlock.tagNumber===1&&(r.status=1);break;case!1:switch(o.certStatus.idBlock.tagNumber){case 0:r.status=0;break;case 2:r.status=2;break;default:}break;default:}}catch{}return r}return r}async sign(e,t="SHA-1",n=ve(!0)){if(!e)throw new Error("Need to provide a private key for signing");let r=await n.getSignatureParameters(e,t),i=r.parameters.algorithm;if(!("name"in i))throw new Error("Empty algorithm");this.signatureAlgorithm=r.signatureAlgorithm,this.tbsResponseData.tbsView=new Uint8Array(this.tbsResponseData.toSchema(!0).toBER());let a=await n.signWithPrivateKey(this.tbsResponseData.tbsView,e,{algorithm:i});this.signature=new Ae({valueHex:a});}async verify(e={},t=ve(!0)){let n=null,r=-1,i=e.trustedCerts||[];if(!this.certs)throw new Error("No certificates attached to the BasicOCSPResponse");switch(!0){case this.tbsResponseData.responderID instanceof Je:for(let[u,l]of this.certs.entries())if(l.subject.isEqual(this.tbsResponseData.responderID)){r=u;break}break;case this.tbsResponseData.responderID instanceof L:for(let[u,l]of this.certs.entries()){let h=await t.digest({name:"sha-1"},l.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView);if(qr(h,this.tbsResponseData.responderID.valueBlock.valueHex)){r=u;break}}break;default:throw new Error("Wrong value for responderID")}if(r===-1)throw new Error("Correct certificate was not found in OCSP response");n=this.certs[r];let a=[n];for(let u of this.certs){let l=await Ak(u,n);l&&a.push(l);}if(!(await new Xm({certs:a,trustedCerts:i}).verify({},t)).result)throw new Error("Validation of signer's certificate failed");return t.verifyWithPublicKey(this.tbsResponseData.tbsView,this.signature,this.certs[r].subjectPublicKeyInfo,this.signatureAlgorithm)}};zo.CLASS_NAME="BasicOCSPResponse";var R2="tbs",V2="version",D2="subject",L2="subjectPublicKeyInfo",Yc="attributes",dm="signatureAlgorithm",mm="signatureValue",Hl="CertificationRequestInfo",PA=`${Hl}.version`,TA=`${Hl}.subject`,BA=`${Hl}.subjectPublicKeyInfo`,Nw=`${Hl}.attributes`,KD=[Hl,PA,TA,BA,Nw,dm,mm];function GD(s={}){let e=d(s,"names",{});return new b({name:e.CertificationRequestInfo||Hl,value:[new k({name:e.CertificationRequestInfoVersion||PA}),Je.schema(e.subject||{names:{blockName:TA}}),As.schema({names:{blockName:BA}}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new fe({optional:!0,name:e.CertificationRequestInfoAttributes||Nw,value:nt.schema(e.attributes||{})})]})]})}var z2=class s extends O{get tbs(){return re.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e);}constructor(e={}){super(),this.tbsView=new Uint8Array(d(e,R2,s.defaultValues(R2))),this.version=d(e,V2,s.defaultValues(V2)),this.subject=d(e,D2,s.defaultValues(D2)),this.subjectPublicKeyInfo=d(e,L2,s.defaultValues(L2)),Yc in e&&(this.attributes=d(e,Yc,s.defaultValues(Yc))),this.signatureAlgorithm=d(e,dm,s.defaultValues(dm)),this.signatureValue=d(e,mm,s.defaultValues(mm)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case R2:return ut;case V2:return 0;case D2:return new Je;case L2:return new As;case Yc:return [];case dm:return new P;case mm:return new Ae;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({value:[GD(t.certificationRequestInfo||{}),new b({name:t.signatureAlgorithm||dm,value:[new G,new ue({optional:!0})]}),new Ae({name:t.signatureValue||mm})]})}fromSchema(e){V(e,KD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.tbsView=t.result.CertificationRequestInfo.valueBeforeDecodeView,this.version=t.result[PA].valueBlock.valueDec,this.subject=new Je({schema:t.result[TA]}),this.subjectPublicKeyInfo=new As({schema:t.result[BA]}),Nw in t.result&&(this.attributes=Array.from(t.result[Nw],n=>new nt({schema:n}))),this.signatureAlgorithm=new P({schema:t.result.signatureAlgorithm}),this.signatureValue=t.result.signatureValue;}encodeTBS(){let e=[new k({value:this.version}),this.subject.toSchema(),this.subjectPublicKeyInfo.toSchema()];return Yc in this&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.attributes||[],t=>t.toSchema())})),new b({value:e})}toSchema(e=!1){let t;if(e===!1){if(this.tbsView.byteLength===0)return s.schema();let n=ht(this.tbsView);T.assert(n,"PKCS#10 Certificate Request"),t=n.result;}else t=this.encodeTBS();return new b({value:[t,this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){let e={tbs:he.ToHex(this.tbsView),version:this.version,subject:this.subject.toJSON(),subjectPublicKeyInfo:this.subjectPublicKeyInfo.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()};return Yc in this&&(e.attributes=Array.from(this.attributes||[],t=>t.toJSON())),e}async sign(e,t="SHA-1",n=ve(!0)){if(!e)throw new Error("Need to provide a private key for signing");let r=await n.getSignatureParameters(e,t),i=r.parameters;this.signatureAlgorithm=r.signatureAlgorithm,this.tbsView=new Uint8Array(this.encodeTBS().toBER());let a=await n.signWithPrivateKey(this.tbsView,e,i);this.signatureValue=new Ae({valueHex:a});}async verify(e=ve(!0)){return e.verifyWithPublicKey(this.tbsView,this.signatureValue,this.subjectPublicKeyInfo,this.signatureAlgorithm)}async getPublicKey(e,t=ve(!0)){return t.getPublicKey(this.subjectPublicKeyInfo,this.signatureAlgorithm,e)}};z2.CLASS_NAME="CertificationRequest";var To="digestAlgorithm",Bo="digest",WD=[To,Bo],dr=class s extends O{constructor(e={}){super(),this.digestAlgorithm=d(e,To,s.defaultValues(To)),this.digest=d(e,Bo,s.defaultValues(Bo)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case To:return new P;case Bo:return new L;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case To:return P.compareWithDefault("algorithmId",t.algorithmId)&&!("algorithmParams"in t);case Bo:return t.isEqual(s.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.digestAlgorithm||{names:{blockName:To}}),new L({name:t.digest||Bo})]})}fromSchema(e){V(e,WD);let t=R(e,e,s.schema({names:{digestAlgorithm:{names:{blockName:To}},digest:Bo}}));T.assertSchema(t,this.className),this.digestAlgorithm=new P({schema:t.result.digestAlgorithm}),this.digest=t.result.digest;}toSchema(){return new b({value:[this.digestAlgorithm.toSchema(),this.digest]})}toJSON(){return {digestAlgorithm:this.digestAlgorithm.toJSON(),digest:this.digest.toJSON()}}};dr.CLASS_NAME="DigestInfo";var Zu="eContentType",Qs="eContent",JD=[Zu,Qs],mr=class s extends O{constructor(e={}){if(super(),this.eContentType=d(e,Zu,s.defaultValues(Zu)),Qs in e&&(this.eContent=d(e,Qs,s.defaultValues(Qs)),this.eContent.idBlock.tagClass===1&&this.eContent.idBlock.tagNumber===4&&this.eContent.idBlock.isConstructed===!1)){let t=new L({idBlock:{isConstructed:!0},isConstructed:!0}),n=0,r=this.eContent.valueBlock.valueHexView.slice().buffer,i=r.byteLength;for(;i>0;){let a=new Uint8Array(r,n,n+65536>r.byteLength?r.byteLength-n:65536),o=new ArrayBuffer(a.length),c=new Uint8Array(o);for(let u=0;u<c.length;u++)c[u]=a[u];t.valueBlock.value.push(new L({valueHex:o})),i-=a.length,n+=a.length;}this.eContent=t;}e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Zu:return p;case Qs:return new L;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Zu:return t===p;case Qs:return t.idBlock.tagClass===1&&t.idBlock.tagNumber===4?t.isEqual(s.defaultValues(Qs)):!1;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.eContentType||p}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new ue({name:t.eContent||p})]})]})}fromSchema(e){V(e,JD);let t=R(e,e,s.schema({names:{eContentType:Zu,eContent:Qs}}));T.assertSchema(t,this.className),this.eContentType=t.result.eContentType.valueBlock.toString(),Qs in t.result&&(this.eContent=t.result.eContent);}toSchema(){let e=[];return e.push(new G({value:this.eContentType})),this.eContent&&s.compareWithDefault(Qs,this.eContent)===!1&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[this.eContent]})),new b({value:e})}toJSON(){let e={eContentType:this.eContentType};return this.eContent&&s.compareWithDefault(Qs,this.eContent)===!1&&(e.eContent=this.eContent.toJSON()),e}};mr.CLASS_NAME="EncapsulatedContentInfo";var Oo="mac",Ro="macSalt",ar="iterations",zD=[Oo,Ro,ar],wn=class s extends O{constructor(e={}){super(),this.mac=d(e,Oo,s.defaultValues(Oo)),this.macSalt=d(e,Ro,s.defaultValues(Ro)),ar in e&&(this.iterations=d(e,ar,s.defaultValues(ar))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Oo:return new dr;case Ro:return new L;case ar:return 1;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Oo:return dr.compareWithDefault("digestAlgorithm",t.digestAlgorithm)&&dr.compareWithDefault("digest",t.digest);case Ro:return t.isEqual(s.defaultValues(e));case ar:return t===s.defaultValues(e);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,optional:t.optional||!0,value:[dr.schema(t.mac||{names:{blockName:Oo}}),new L({name:t.macSalt||Ro}),new k({optional:!0,name:t.iterations||ar})]})}fromSchema(e){V(e,zD);let t=R(e,e,s.schema({names:{mac:{names:{blockName:Oo}},macSalt:Ro,iterations:ar}}));T.assertSchema(t,this.className),this.mac=new dr({schema:t.result.mac}),this.macSalt=t.result.macSalt,ar in t.result&&(this.iterations=t.result.iterations.valueBlock.valueDec);}toSchema(){let e=[this.mac.toSchema(),this.macSalt];return this.iterations!==void 0&&e.push(new k({value:this.iterations})),new b({value:e})}toJSON(){let e={mac:this.mac.toJSON(),macSalt:this.macSalt.toJSON()};return this.iterations!==void 0&&(e.iterations=this.iterations),e}};wn.CLASS_NAME="MacData";var _o="hashAlgorithm",Mo="hashedMessage",YD=[_o,Mo],Es=class s extends O{static async create(e,t,n=ve(!0)){let r=n.getOIDByAlgorithm({name:e},!0,"hashAlgorithm"),i=await n.digest(e,t);return new s({hashAlgorithm:new P({algorithmId:r,algorithmParams:new Xe}),hashedMessage:new L({valueHex:i})})}constructor(e={}){super(),this.hashAlgorithm=d(e,_o,s.defaultValues(_o)),this.hashedMessage=d(e,Mo,s.defaultValues(Mo)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case _o:return new P;case Mo:return new L;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case _o:return t.algorithmId===p&&!("algorithmParams"in t);case Mo:return t.isEqual(s.defaultValues(e))===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.hashAlgorithm||{}),new L({name:t.hashedMessage||p})]})}fromSchema(e){V(e,YD);let t=R(e,e,s.schema({names:{hashAlgorithm:{names:{blockName:_o}},hashedMessage:Mo}}));T.assertSchema(t,this.className),this.hashAlgorithm=new P({schema:t.result.hashAlgorithm}),this.hashedMessage=t.result.hashedMessage;}toSchema(){return new b({value:[this.hashAlgorithm.toSchema(),this.hashedMessage]})}toJSON(){return {hashAlgorithm:this.hashAlgorithm.toJSON(),hashedMessage:this.hashedMessage.toJSON()}}};Es.CLASS_NAME="MessageImprint";var Qu="reqCert",Oi="singleRequestExtensions",ZD=[Qu,Oi],jl=class s extends O{constructor(e={}){super(),this.reqCert=d(e,Qu,s.defaultValues(Qu)),Oi in e&&(this.singleRequestExtensions=d(e,Oi,s.defaultValues(Oi))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Qu:return new ns;case Oi:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Qu:return t.isEqual(s.defaultValues(e));case Oi:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[ns.schema(t.reqCert||{}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[ft.schema(t.extensions||{names:{blockName:t.singleRequestExtensions||p}})]})]})}fromSchema(e){V(e,ZD);let t=R(e,e,s.schema({names:{reqCert:{names:{blockName:Qu}},extensions:{names:{blockName:Oi}}}}));T.assertSchema(t,this.className),this.reqCert=new ns({schema:t.result.reqCert}),Oi in t.result&&(this.singleRequestExtensions=Array.from(t.result.singleRequestExtensions.valueBlock.value,n=>new ds({schema:n})));}toSchema(){let e=[];return e.push(this.reqCert.toSchema()),this.singleRequestExtensions&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new b({value:Array.from(this.singleRequestExtensions,t=>t.toSchema())})]})),new b({value:e})}toJSON(){let e={reqCert:this.reqCert.toJSON()};return this.singleRequestExtensions&&(e.singleRequestExtensions=Array.from(this.singleRequestExtensions,t=>t.toJSON())),e}};jl.CLASS_NAME="Request";var vy="tbs",Xu="version",el="requestorName",xy="requestList",tl="requestExtensions",_l="TBSRequest",Ly=`${_l}.${Xu}`,jy=`${_l}.${el}`,Y2=`${_l}.requests`,Uy=`${_l}.${tl}`,QD=[_l,Ly,jy,Y2,Uy],en=class s extends O{get tbs(){return re.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e);}constructor(e={}){super(),this.tbsView=new Uint8Array(d(e,vy,s.defaultValues(vy))),Xu in e&&(this.version=d(e,Xu,s.defaultValues(Xu))),el in e&&(this.requestorName=d(e,el,s.defaultValues(el))),this.requestList=d(e,xy,s.defaultValues(xy)),tl in e&&(this.requestExtensions=d(e,tl,s.defaultValues(tl))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case vy:return ut;case Xu:return 0;case el:return new qe;case xy:case tl:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case vy:return t.byteLength===0;case Xu:return t===s.defaultValues(e);case el:return t.type===qe.defaultValues("type")&&Object.keys(t.value).length===0;case xy:case tl:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||_l,value:[new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new k({name:t.TBSRequestVersion||Ly})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[qe.schema(t.requestorName||{names:{blockName:jy}})]}),new b({name:t.requestList||"TBSRequest.requestList",value:[new fe({name:t.requests||Y2,value:jl.schema(t.requestNames||{})})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:2},value:[ft.schema(t.extensions||{names:{blockName:t.requestExtensions||Uy}})]})]})}fromSchema(e){V(e,QD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.tbsView=t.result.TBSRequest.valueBeforeDecodeView,Ly in t.result&&(this.version=t.result[Ly].valueBlock.valueDec),jy in t.result&&(this.requestorName=new qe({schema:t.result[jy]})),this.requestList=Array.from(t.result[Y2],n=>new jl({schema:n})),Uy in t.result&&(this.requestExtensions=Array.from(t.result[Uy].valueBlock.value,n=>new ds({schema:n})));}toSchema(e=!1){let t;if(e===!1){if(this.tbsView.byteLength===0)return s.schema();let n=ht(this.tbsView);if(T.assert(n,"TBS Request"),!(n.result instanceof b))throw new Error("ASN.1 result should be SEQUENCE");t=n.result;}else {let n=[];this.version!==void 0&&n.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[new k({value:this.version})]})),this.requestorName&&n.push(new A({idBlock:{tagClass:3,tagNumber:1},value:[this.requestorName.toSchema()]})),n.push(new b({value:Array.from(this.requestList,r=>r.toSchema())})),this.requestExtensions&&n.push(new A({idBlock:{tagClass:3,tagNumber:2},value:[new b({value:Array.from(this.requestExtensions,r=>r.toSchema())})]})),t=new b({value:n});}return t}toJSON(){let e={};return this.version!=null&&(e.version=this.version),this.requestorName&&(e.requestorName=this.requestorName.toJSON()),e.requestList=Array.from(this.requestList,t=>t.toJSON()),this.requestExtensions&&(e.requestExtensions=Array.from(this.requestExtensions,t=>t.toJSON())),e}};en.CLASS_NAME="TBSRequest";var Zc="signatureAlgorithm",Qc="signature",Xr="certs",fr=class s extends O{constructor(e={}){super(),this.signatureAlgorithm=d(e,Zc,s.defaultValues(Zc)),this.signature=d(e,Qc,s.defaultValues(Qc)),Xr in e&&(this.certs=d(e,Xr,s.defaultValues(Xr))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Zc:return new P;case Qc:return new Ae;case Xr:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Zc:return t.algorithmId===p&&!("algorithmParams"in t);case Qc:return t.isEqual(s.defaultValues(e));case Xr:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.signatureAlgorithm||{}),new Ae({name:t.signature||p}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new b({value:[new fe({name:t.certs||p,value:jt.schema({})})]})]})]})}fromSchema(e){V(e,[Zc,Qc,Xr]);let t=R(e,e,s.schema({names:{signatureAlgorithm:{names:{blockName:Zc}},signature:Qc,certs:Xr}}));T.assertSchema(t,this.className),this.signatureAlgorithm=new P({schema:t.result.signatureAlgorithm}),this.signature=t.result.signature,Xr in t.result&&(this.certs=Array.from(t.result.certs,n=>new jt({schema:n})));}toSchema(){let e=[];return e.push(this.signatureAlgorithm.toSchema()),e.push(this.signature),this.certs&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new b({value:Array.from(this.certs,t=>t.toSchema())})]})),new b({value:e})}toJSON(){let e={signatureAlgorithm:this.signatureAlgorithm.toJSON(),signature:this.signature.toJSON()};return this.certs&&(e.certs=Array.from(this.certs,t=>t.toJSON())),e}};fr.CLASS_NAME="Signature";var sl="tbsRequest",Ri="optionalSignature",XD=[sl,Ri],Z2=class s extends O{constructor(e={}){super(),this.tbsRequest=d(e,sl,s.defaultValues(sl)),Ri in e&&(this.optionalSignature=d(e,Ri,s.defaultValues(Ri))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case sl:return new en;case Ri:return new fr;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case sl:return en.compareWithDefault("tbs",t.tbs)&&en.compareWithDefault("version",t.version)&&en.compareWithDefault("requestorName",t.requestorName)&&en.compareWithDefault("requestList",t.requestList)&&en.compareWithDefault("requestExtensions",t.requestExtensions);case Ri:return fr.compareWithDefault("signatureAlgorithm",t.signatureAlgorithm)&&fr.compareWithDefault("signature",t.signature)&&fr.compareWithDefault("certs",t.certs);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||"OCSPRequest",value:[en.schema(t.tbsRequest||{names:{blockName:sl}}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[fr.schema(t.optionalSignature||{names:{blockName:Ri}})]})]})}fromSchema(e){V(e,XD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.tbsRequest=new en({schema:t.result.tbsRequest}),Ri in t.result&&(this.optionalSignature=new fr({schema:t.result.optionalSignature}));}toSchema(e=!1){let t=[];return t.push(this.tbsRequest.toSchema(e)),this.optionalSignature&&t.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[this.optionalSignature.toSchema()]})),new b({value:t})}toJSON(){let e={tbsRequest:this.tbsRequest.toJSON()};return this.optionalSignature&&(e.optionalSignature=this.optionalSignature.toJSON()),e}async createForCertificate(e,t,n=ve(!0)){let r=new ns;await r.createForCertificate(e,t,n),this.tbsRequest.requestList.push(new jl({reqCert:r}));}async sign(e,t="SHA-1",n=ve(!0)){if(Re.assertEmpty(e,"privateKey","OCSPRequest.sign method"),!this.optionalSignature)throw new Error('Need to create "optionalSignature" field before signing');let r=await n.getSignatureParameters(e,t),i=r.parameters;this.optionalSignature.signatureAlgorithm=r.signatureAlgorithm;let a=this.tbsRequest.toSchema(!0).toBER(!1),o=await n.signWithPrivateKey(a,e,i);this.optionalSignature.signature=new Ae({valueHex:o});}verify(){}};Z2.CLASS_NAME="OCSPRequest";var nl="responseType",rl="response",eL=[nl,rl],_i=class s extends O{constructor(e={}){super(),this.responseType=d(e,nl,s.defaultValues(nl)),this.response=d(e,rl,s.defaultValues(rl)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case nl:return p;case rl:return new L;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case nl:return t===p;case rl:return t.isEqual(s.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.responseType||p}),new L({name:t.response||p})]})}fromSchema(e){V(e,eL);let t=R(e,e,s.schema({names:{responseType:nl,response:rl}}));T.assertSchema(t,this.className),this.responseType=t.result.responseType.valueBlock.toString(),this.response=t.result.response;}toSchema(){return new b({value:[new G({value:this.responseType}),this.response]})}toJSON(){return {responseType:this.responseType,response:this.response.toJSON()}}};_i.CLASS_NAME="ResponseBytes";var Xc="responseStatus",Zn="responseBytes",Q2=class s extends O{constructor(e={}){super(),this.responseStatus=d(e,Xc,s.defaultValues(Xc)),Zn in e&&(this.responseBytes=d(e,Zn,s.defaultValues(Zn))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Xc:return new pn;case Zn:return new _i;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Xc:return t.isEqual(s.defaultValues(e));case Zn:return _i.compareWithDefault("responseType",t.responseType)&&_i.compareWithDefault("response",t.response);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||"OCSPResponse",value:[new pn({name:t.responseStatus||Xc}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[_i.schema(t.responseBytes||{names:{blockName:Zn}})]})]})}fromSchema(e){V(e,[Xc,Zn]);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.responseStatus=t.result.responseStatus,Zn in t.result&&(this.responseBytes=new _i({schema:t.result.responseBytes}));}toSchema(){let e=[];return e.push(this.responseStatus),this.responseBytes&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[this.responseBytes.toSchema()]})),new b({value:e})}toJSON(){let e={responseStatus:this.responseStatus.toJSON()};return this.responseBytes&&(e.responseBytes=this.responseBytes.toJSON()),e}async getCertificateStatus(e,t,n=ve(!0)){let r,i={isForCertificate:!1,status:2};if(!this.responseBytes||this.responseBytes.responseType!==Ay)return i;try{let a=ht(this.responseBytes.response.valueBlock.valueHexView);T.assert(a,"Basic OCSP response"),r=new zo({schema:a.result});}catch{return i}return r.getCertificateStatus(e,t,n)}async sign(e,t,n=ve(!0)){var r;if(this.responseBytes&&this.responseBytes.responseType===Ay)return zo.fromBER(this.responseBytes.response.valueBlock.valueHexView).sign(e,t,n);throw new Error(`Unknown ResponseBytes type: ${((r=this.responseBytes)===null||r===void 0?void 0:r.responseType)||"Unknown"}`)}async verify(e=null,t=ve(!0)){var n;if(!(Zn in this))throw new Error("Empty ResponseBytes field");if(this.responseBytes&&this.responseBytes.responseType===Ay){let r=zo.fromBER(this.responseBytes.response.valueBlock.valueHexView);return e!==null&&(r.certs||(r.certs=[]),r.certs.push(e)),r.verify({},t)}throw new Error(`Unknown ResponseBytes type: ${((n=this.responseBytes)===null||n===void 0?void 0:n.responseType)||"Unknown"}`)}};Q2.CLASS_NAME="OCSPResponse";var ja="type",or="attributes",Ey="encodedValue",tL=[or],Wt=class s extends O{constructor(e={}){super(),this.type=d(e,ja,s.defaultValues(ja)),this.attributes=d(e,or,s.defaultValues(or)),this.encodedValue=d(e,Ey,s.defaultValues(Ey)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ja:return -1;case or:return [];case Ey:return ut;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ja:return t===s.defaultValues(ja);case or:return t.length===0;case Ey:return t.byteLength===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new A({name:t.blockName||p,optional:!0,idBlock:{tagClass:3,tagNumber:t.tagNumber||0},value:[new fe({name:t.attributes||p,value:nt.schema()})]})}fromSchema(e){V(e,tL);let t=R(e,e,s.schema({names:{tagNumber:this.type,attributes:or}}));T.assertSchema(t,this.className),this.type=t.result.idBlock.tagNumber,this.encodedValue=re.toArrayBuffer(t.result.valueBeforeDecodeView);let n=new Uint8Array(this.encodedValue);if(n[0]=49,!(or in t.result)){if(this.type===0)throw new Error("Wrong structure of SignedUnsignedAttributes");return}this.attributes=Array.from(t.result.attributes,r=>new nt({schema:r}));}toSchema(){if(s.compareWithDefault(ja,this.type)||s.compareWithDefault(or,this.attributes))throw new Error('Incorrectly initialized "SignedAndUnsignedAttributes" class');return new A({optional:!0,idBlock:{tagClass:3,tagNumber:this.type},value:Array.from(this.attributes,e=>e.toSchema())})}toJSON(){if(s.compareWithDefault(ja,this.type)||s.compareWithDefault(or,this.attributes))throw new Error('Incorrectly initialized "SignedAndUnsignedAttributes" class');return {type:this.type,attributes:Array.from(this.attributes,e=>e.toJSON())}}};Wt.CLASS_NAME="SignedAndUnsignedAttributes";var il="version",Vo="sid",al="digestAlgorithm",Vi="signedAttrs",ol="signatureAlgorithm",pm="signature",Di="unsignedAttrs",Ki="SignerInfo",X2=`${Ki}.${il}`,gm=`${Ki}.${Vo}`,eA=`${Ki}.${al}`,Hy=`${Ki}.${Vi}`,tA=`${Ki}.${ol}`,sA=`${Ki}.${pm}`,_y=`${Ki}.${Di}`,sL=[X2,gm,eA,Hy,tA,sA,_y],Ul=class s extends O{constructor(e={}){super(),this.version=d(e,il,s.defaultValues(il)),this.sid=d(e,Vo,s.defaultValues(Vo)),this.digestAlgorithm=d(e,al,s.defaultValues(al)),Vi in e&&(this.signedAttrs=d(e,Vi,s.defaultValues(Vi))),this.signatureAlgorithm=d(e,ol,s.defaultValues(ol)),this.signature=d(e,pm,s.defaultValues(pm)),Di in e&&(this.unsignedAttrs=d(e,Di,s.defaultValues(Di))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case il:return 0;case Vo:return new ue;case al:return new P;case Vi:return new Wt({type:0});case ol:return new P;case pm:return new L;case Di:return new Wt({type:1});default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case il:return s.defaultValues(il)===t;case Vo:return t instanceof ue;case al:return t instanceof P?t.isEqual(s.defaultValues(al)):!1;case Vi:return Wt.compareWithDefault("type",t.type)&&Wt.compareWithDefault("attributes",t.attributes)&&Wt.compareWithDefault("encodedValue",t.encodedValue);case ol:return t instanceof P?t.isEqual(s.defaultValues(ol)):!1;case pm:case Di:return Wt.compareWithDefault("type",t.type)&&Wt.compareWithDefault("attributes",t.attributes)&&Wt.compareWithDefault("encodedValue",t.encodedValue);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:Ki,value:[new k({name:t.version||X2}),new We({value:[vt.schema(t.sidSchema||{names:{blockName:gm}}),new We({value:[new A({optional:!0,name:t.sid||gm,idBlock:{tagClass:3,tagNumber:0},value:[new L]}),new ie({optional:!0,name:t.sid||gm,idBlock:{tagClass:3,tagNumber:0}})]})]}),P.schema(t.digestAlgorithm||{names:{blockName:eA}}),Wt.schema(t.signedAttrs||{names:{blockName:Hy,tagNumber:0}}),P.schema(t.signatureAlgorithm||{names:{blockName:tA}}),new L({name:t.signature||sA}),Wt.schema(t.unsignedAttrs||{names:{blockName:_y,tagNumber:1}})]})}fromSchema(e){V(e,sL);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.version=t.result[X2].valueBlock.valueDec;let n=t.result[gm];n.idBlock.tagClass===1?this.sid=new vt({schema:n}):this.sid=n,this.digestAlgorithm=new P({schema:t.result[eA]}),Hy in t.result&&(this.signedAttrs=new Wt({type:0,schema:t.result[Hy]})),this.signatureAlgorithm=new P({schema:t.result[tA]}),this.signature=t.result[sA],_y in t.result&&(this.unsignedAttrs=new Wt({type:1,schema:t.result[_y]}));}toSchema(){if(s.compareWithDefault(Vo,this.sid))throw new Error('Incorrectly initialized "SignerInfo" class');let e=[];return e.push(new k({value:this.version})),this.sid instanceof vt?e.push(this.sid.toSchema()):e.push(this.sid),e.push(this.digestAlgorithm.toSchema()),this.signedAttrs&&s.compareWithDefault(Vi,this.signedAttrs)===!1&&e.push(this.signedAttrs.toSchema()),e.push(this.signatureAlgorithm.toSchema()),e.push(this.signature),this.unsignedAttrs&&s.compareWithDefault(Di,this.unsignedAttrs)===!1&&e.push(this.unsignedAttrs.toSchema()),new b({value:e})}toJSON(){if(s.compareWithDefault(Vo,this.sid))throw new Error('Incorrectly initialized "SignerInfo" class');let e={version:this.version,digestAlgorithm:this.digestAlgorithm.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signature:this.signature.toJSON()};return this.sid instanceof ue||(e.sid=this.sid.toJSON()),this.signedAttrs&&s.compareWithDefault(Vi,this.signedAttrs)===!1&&(e.signedAttrs=this.signedAttrs.toJSON()),this.unsignedAttrs&&s.compareWithDefault(Di,this.unsignedAttrs)===!1&&(e.unsignedAttrs=this.unsignedAttrs.toJSON()),e}};Ul.CLASS_NAME="SignerInfo";var ym="version",wm="policy",bm="messageImprint",Sm="serialNumber",vm="genTime",Do="ordering",Lo="nonce",cl="accuracy",ul="tsa",ll="extensions",sn="TSTInfo",nA=`${sn}.${ym}`,rA=`${sn}.${wm}`,iA=`${sn}.${bm}`,aA=`${sn}.${Sm}`,oA=`${sn}.${vm}`,My=`${sn}.${cl}`,$y=`${sn}.${Do}`,qy=`${sn}.${Lo}`,Fy=`${sn}.${ul}`,Ky=`${sn}.${ll}`,nL=[nA,rA,iA,aA,oA,My,$y,qy,Fy,Ky],kw=class s extends O{constructor(e={}){super(),this.version=d(e,ym,s.defaultValues(ym)),this.policy=d(e,wm,s.defaultValues(wm)),this.messageImprint=d(e,bm,s.defaultValues(bm)),this.serialNumber=d(e,Sm,s.defaultValues(Sm)),this.genTime=d(e,vm,s.defaultValues(vm)),cl in e&&(this.accuracy=d(e,cl,s.defaultValues(cl))),Do in e&&(this.ordering=d(e,Do,s.defaultValues(Do))),Lo in e&&(this.nonce=d(e,Lo,s.defaultValues(Lo))),ul in e&&(this.tsa=d(e,ul,s.defaultValues(ul))),ll in e&&(this.extensions=d(e,ll,s.defaultValues(ll))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ym:return 0;case wm:return p;case bm:return new Es;case Sm:return new k;case vm:return new Date(0,0,0);case cl:return new lr;case Do:return !1;case Lo:return new k;case ul:return new qe;case ll:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ym:case wm:case vm:case Do:return t===s.defaultValues(Do);case bm:return Es.compareWithDefault(_o,t.hashAlgorithm)&&Es.compareWithDefault(Mo,t.hashedMessage);case Sm:case Lo:return t.isEqual(s.defaultValues(Lo));case cl:return lr.compareWithDefault(ei,t.seconds)&&lr.compareWithDefault(ti,t.millis)&&lr.compareWithDefault(si,t.micros);case ul:return qe.compareWithDefault(Of,t.type)&&qe.compareWithDefault(Rf,t.value);case ll:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||sn,value:[new k({name:t.version||nA}),new G({name:t.policy||rA}),Es.schema(t.messageImprint||{names:{blockName:iA}}),new k({name:t.serialNumber||aA}),new Ge({name:t.genTime||oA}),lr.schema(t.accuracy||{names:{blockName:My}}),new xs({name:t.ordering||$y,optional:!0}),new k({name:t.nonce||qy,optional:!0}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[qe.schema(t.tsa||{names:{blockName:Fy}})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new fe({name:t.extensions||Ky,value:ds.schema(t.extension||{})})]})]})}fromSchema(e){V(e,nL);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.version=t.result[nA].valueBlock.valueDec,this.policy=t.result[rA].valueBlock.toString(),this.messageImprint=new Es({schema:t.result[iA]}),this.serialNumber=t.result[aA],this.genTime=t.result[oA].toDate(),My in t.result&&(this.accuracy=new lr({schema:t.result[My]})),$y in t.result&&(this.ordering=t.result[$y].valueBlock.value),qy in t.result&&(this.nonce=t.result[qy]),Fy in t.result&&(this.tsa=new qe({schema:t.result[Fy]})),Ky in t.result&&(this.extensions=Array.from(t.result[Ky],n=>new ds({schema:n})));}toSchema(){let e=[];return e.push(new k({value:this.version})),e.push(new G({value:this.policy})),e.push(this.messageImprint.toSchema()),e.push(this.serialNumber),e.push(new Ge({valueDate:this.genTime})),this.accuracy&&e.push(this.accuracy.toSchema()),this.ordering!==void 0&&e.push(new xs({value:this.ordering})),this.nonce&&e.push(this.nonce),this.tsa&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[this.tsa.toSchema()]})),this.extensions&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.extensions,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={version:this.version,policy:this.policy,messageImprint:this.messageImprint.toJSON(),serialNumber:this.serialNumber.toJSON(),genTime:this.genTime};return this.accuracy&&(e.accuracy=this.accuracy.toJSON()),this.ordering!==void 0&&(e.ordering=this.ordering),this.nonce&&(e.nonce=this.nonce.toJSON()),this.tsa&&(e.tsa=this.tsa.toJSON()),this.extensions&&(e.extensions=Array.from(this.extensions,t=>t.toJSON())),e}async verify(e,t=ve(!0)){if(!e.data)throw new Error('"data" is a mandatory attribute for TST_INFO verification');let n=e.data;if(e.notBefore&&this.genTime<e.notBefore)throw new Error("Generation time for TSTInfo object is less than notBefore value");if(e.notAfter&&this.genTime>e.notAfter)throw new Error("Generation time for TSTInfo object is more than notAfter value");let r=t.getAlgorithmByOID(this.messageImprint.hashAlgorithm.algorithmId,!0,"MessageImprint.hashAlgorithm"),i=await t.digest(r.name,new Uint8Array(n));return re.isEqual(i,this.messageImprint.hashedMessage.valueBlock.valueHexView)}};kw.CLASS_NAME="TSTInfo";var hl="version",xm="digestAlgorithms",Em="encapContentInfo",fl="certificates",dl="crls",Am="signerInfos",Tf="ocsps",ec="SignedData",cA=`${ec}.${hl}`,Gy=`${ec}.${xm}`,uA=`${ec}.${Em}`,Wy=`${ec}.${fl}`,Jy=`${ec}.${dl}`,zy=`${ec}.${Am}`,rL=[cA,Gy,uA,Wy,Jy,zy],Nt=class extends Error{constructor({message:e,code:t=0,date:n=new Date,signatureVerified:r=null,signerCertificate:i=null,signerCertificateVerified:a=null,timestampSerial:o=null,certificatePath:c=[]}){super(e),this.name="SignedDataVerifyError",this.date=n,this.code=t,this.timestampSerial=o,this.signatureVerified=r,this.signerCertificate=i,this.signerCertificateVerified=a,this.certificatePath=c;}},Fi=class s extends O{constructor(e={}){super(),this.version=d(e,hl,s.defaultValues(hl)),this.digestAlgorithms=d(e,xm,s.defaultValues(xm)),this.encapContentInfo=d(e,Em,s.defaultValues(Em)),fl in e&&(this.certificates=d(e,fl,s.defaultValues(fl))),dl in e&&(this.crls=d(e,dl,s.defaultValues(dl))),Tf in e&&(this.ocsps=d(e,Tf,s.defaultValues(Tf))),this.signerInfos=d(e,Am,s.defaultValues(Am)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case hl:return 0;case xm:return [];case Em:return new mr;case fl:return [];case dl:return [];case Tf:return [];case Am:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case hl:return t===s.defaultValues(hl);case Em:return mr.compareWithDefault("eContentType",t.eContentType)&&mr.compareWithDefault("eContent",t.eContent);case xm:case fl:case dl:case Tf:case Am:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return t.optional===void 0&&(t.optional=!1),new b({name:t.blockName||ec,optional:t.optional,value:[new k({name:t.version||cA}),new et({value:[new fe({name:t.digestAlgorithms||Gy,value:P.schema()})]}),mr.schema(t.encapContentInfo||{names:{blockName:uA}}),new A({name:t.certificates||Wy,optional:!0,idBlock:{tagClass:3,tagNumber:0},value:yr.schema().valueBlock.value}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Ko.schema(t.crls||{names:{crls:Jy}}).valueBlock.value}),new et({value:[new fe({name:t.signerInfos||zy,value:Ul.schema()})]})]})}fromSchema(e){V(e,rL);let t=R(e,e,s.schema());if(T.assertSchema(t,this.className),this.version=t.result[cA].valueBlock.valueDec,Gy in t.result&&(this.digestAlgorithms=Array.from(t.result[Gy],n=>new P({schema:n}))),this.encapContentInfo=new mr({schema:t.result[uA]}),Wy in t.result){let n=new yr({schema:new et({value:t.result[Wy].valueBlock.value})});this.certificates=n.certificates.slice(0);}Jy in t.result&&(this.crls=Array.from(t.result[Jy],n=>n.idBlock.tagClass===1?new Zo({schema:n}):(n.idBlock.tagClass=1,n.idBlock.tagNumber=16,new Fo({schema:n})))),zy in t.result&&(this.signerInfos=Array.from(t.result[zy],n=>new Ul({schema:n})));}toSchema(e=!1){let t=[];if(this.certificates&&this.certificates.length&&this.certificates.some(n=>n instanceof Il)||this.crls&&this.crls.length&&this.crls.some(n=>n instanceof Fo)?this.version=5:this.certificates&&this.certificates.length&&this.certificates.some(n=>n instanceof bn)?this.version=4:this.certificates&&this.certificates.length&&this.certificates.some(n=>n instanceof Pl)||this.signerInfos.some(n=>n.version===3)||this.encapContentInfo.eContentType!==s.ID_DATA?this.version=3:this.version=1,t.push(new k({value:this.version})),t.push(new et({value:Array.from(this.digestAlgorithms,n=>n.toSchema())})),t.push(this.encapContentInfo.toSchema()),this.certificates){let r=new yr({certificates:this.certificates}).toSchema();t.push(new A({idBlock:{tagClass:3,tagNumber:0},value:r.valueBlock.value}));}return this.crls&&t.push(new A({idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.crls,n=>{if(n instanceof Fo){let r=n.toSchema();return r.idBlock.tagClass=3,r.idBlock.tagNumber=1,r}return n.toSchema(e)})})),t.push(new et({value:Array.from(this.signerInfos,n=>n.toSchema())})),new b({value:t})}toJSON(){let e={version:this.version,digestAlgorithms:Array.from(this.digestAlgorithms,t=>t.toJSON()),encapContentInfo:this.encapContentInfo.toJSON(),signerInfos:Array.from(this.signerInfos,t=>t.toJSON())};return this.certificates&&(e.certificates=Array.from(this.certificates,t=>t.toJSON())),this.crls&&(e.crls=Array.from(this.crls,t=>t.toJSON())),e}async verify({signer:e=-1,data:t=ut,trustedCerts:n=[],checkDate:r=new Date,checkChain:i=!1,passedWhenNotRevValues:a=!1,extendedMode:o=!1,findOrigin:c=null,findIssuer:u=null}={},l=ve(!0)){let h=null,m=null;try{let y=ut,g=p,w=[],S=this.signerInfos[e];if(!S)throw new Nt({date:r,code:1,message:"Unable to get signer by supplied index"});if(!this.certificates)throw new Nt({date:r,code:2,message:"No certificates attached to this signed data"});if(S.sid instanceof vt){for(let v of this.certificates)if(v instanceof jt&&v.issuer.isEqual(S.sid.issuer)&&v.serialNumber.isEqual(S.sid.serialNumber)){h=v;break}}else {let v=S.sid,I=v.idBlock.isConstructed?v.valueBlock.value[0].valueBlock.valueHex:v.valueBlock.valueHex;for(let D of this.certificates){if(!(D instanceof jt))continue;let F=await l.digest({name:"sha-1"},D.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView);if(qr(F,I)){h=D;break}}}if(!h)throw new Nt({date:r,code:3,message:"Unable to find signer certificate"});if(this.encapContentInfo.eContentType===l9){if(!this.encapContentInfo.eContent)throw new Nt({date:r,code:15,message:"Error during verification: TSTInfo eContent is empty",signatureVerified:null,signerCertificate:h,timestampSerial:m,signerCertificateVerified:!0});let v;try{v=kw.fromBER(this.encapContentInfo.eContent.valueBlock.valueHexView);}catch{throw new Nt({date:r,code:15,message:"Error during verification: TSTInfo wrong ASN.1 schema ",signatureVerified:null,signerCertificate:h,timestampSerial:m,signerCertificateVerified:!0})}if(r=v.genTime,m=v.serialNumber.valueBlock.valueHexView.slice().buffer,t.byteLength===0)throw new Nt({date:r,code:4,message:"Missed detached data input array"});if(!await v.verify({data:t},l))throw new Nt({date:r,code:15,message:"Error during verification: TSTInfo verification is failed",signatureVerified:!1,signerCertificate:h,timestampSerial:m,signerCertificateVerified:!0})}if(i){let v=this.certificates.filter(M=>M instanceof jt&&!!Ak(M,h)),I={checkDate:r,certs:v,trustedCerts:n};u&&(I.findIssuer=u),c&&(I.findOrigin=c);let D=new Xm(I);if(D.certs.push(h),this.crls)for(let M of this.crls)"thisUpdate"in M?D.crls.push(M):M.otherRevInfoFormat===Ay&&D.ocsps.push(new zo({schema:M.otherRevInfo}));this.ocsps&&D.ocsps.push(...this.ocsps);let F=await D.verify({passedWhenNotRevValues:a},l).catch(M=>{throw new Nt({date:r,code:5,message:`Validation of signer's certificate failed with error: ${M instanceof Object?M.resultMessage:M}`,signerCertificate:h,signerCertificateVerified:!1})});if(F.certificatePath&&(w=F.certificatePath),!F.result)throw new Nt({date:r,code:5,message:`Validation of signer's certificate failed: ${F.resultMessage}`,signerCertificate:h,signerCertificateVerified:!1})}let C=l.getAlgorithmByOID(S.digestAlgorithm.algorithmId);if(!("name"in C))throw new Nt({date:r,code:7,message:`Unsupported signature algorithm: ${S.digestAlgorithm.algorithmId}`,signerCertificate:h,signerCertificateVerified:!0});g=C.name;let N=this.encapContentInfo.eContent;if(N)N.idBlock.tagClass===1&&N.idBlock.tagNumber===4?t=N.getValue():t=N.valueBlock.valueBeforeDecodeView.slice().buffer;else if(t.byteLength===0)throw new Nt({date:r,code:8,message:"Missed detached data input array",signerCertificate:h,signerCertificateVerified:!0});if(S.signedAttrs){let v=!1,I=!1;for(let D of S.signedAttrs.attributes)if(D.type==="1.2.840.113549.1.9.3"&&(v=!0),D.type==="1.2.840.113549.1.9.4"&&(I=!0,y=D.values[0].valueBlock.valueHex),v&&I)break;if(v===!1)throw new Nt({date:r,code:9,message:'Attribute "content-type" is a mandatory attribute for "signed attributes"',signerCertificate:h,signerCertificateVerified:!0});if(I===!1)throw new Nt({date:r,code:10,message:'Attribute "message-digest" is a mandatory attribute for "signed attributes"',signatureVerified:null,signerCertificate:h,signerCertificateVerified:!0})}if(S.signedAttrs){let v=await l.digest(g,new Uint8Array(t));if(!qr(v,y))throw new Nt({date:r,code:15,message:"Error during verification: Message digest doesn't match",signatureVerified:null,signerCertificate:h,timestampSerial:m,signerCertificateVerified:!0});t=S.signedAttrs.encodedValue;}let x=S.signatureAlgorithm.algorithmId==="1.2.840.113549.1.1.1"?await l.verifyWithPublicKey(t,S.signature,h.subjectPublicKeyInfo,S.signatureAlgorithm,g):await l.verifyWithPublicKey(t,S.signature,h.subjectPublicKeyInfo,S.signatureAlgorithm);return o?{date:r,code:14,message:p,signatureVerified:x,signerCertificate:h,timestampSerial:m,signerCertificateVerified:!0,certificatePath:w}:x}catch(y){throw y instanceof Nt?y:new Nt({date:r,code:15,message:`Error during verification: ${y instanceof Error?y.message:y}`,signatureVerified:null,signerCertificate:h,timestampSerial:m,signerCertificateVerified:!0})}}async sign(e,t,n="SHA-1",r=ut,i=ve(!0)){var a;if(!e)throw new Error("Need to provide a private key for signing");let o=this.signerInfos[t];if(!o)throw new RangeError("SignerInfo index is out of range");!(!((a=o.signedAttrs)===null||a===void 0)&&a.attributes.length)&&"hash"in e.algorithm&&"hash"in e.algorithm&&e.algorithm.hash&&(n=e.algorithm.hash.name);let c=i.getOIDByAlgorithm({name:n},!0,"hashAlgorithm");this.digestAlgorithms.filter(m=>m.algorithmId===c).length===0&&this.digestAlgorithms.push(new P({algorithmId:c,algorithmParams:new Xe})),o.digestAlgorithm=new P({algorithmId:c,algorithmParams:new Xe});let u=await i.getSignatureParameters(e,n),l=u.parameters;if(o.signatureAlgorithm=u.signatureAlgorithm,o.signedAttrs)if(o.signedAttrs.encodedValue.byteLength!==0)r=o.signedAttrs.encodedValue;else {r=o.signedAttrs.toSchema().toBER();let m=re.toUint8Array(r);m[0]=49;}else {let m=this.encapContentInfo.eContent;if(m)m.idBlock.tagClass===1&&m.idBlock.tagNumber===4?r=m.getValue():r=m.valueBlock.valueBeforeDecodeView.slice().buffer;else if(r.byteLength===0)throw new Error("Missed detached data input array")}let h=await i.signWithPrivateKey(r,e,l);o.signature=new L({valueHex:h});}};Fi.CLASS_NAME="SignedData";Fi.ID_DATA=SA;var jo="version",Uo="authSafe",cr="macData",Bf="parsedValue",iL=[jo,Uo,cr],lA=class s extends O{constructor(e={}){super(),this.version=d(e,jo,s.defaultValues(jo)),this.authSafe=d(e,Uo,s.defaultValues(Uo)),cr in e&&(this.macData=d(e,cr,s.defaultValues(cr))),Bf in e&&(this.parsedValue=d(e,Bf,s.defaultValues(Bf))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case jo:return 3;case Uo:return new tt;case cr:return new wn;case Bf:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case jo:return t===s.defaultValues(e);case Uo:return tt.compareWithDefault("contentType",t.contentType)&&tt.compareWithDefault("content",t.content);case cr:return wn.compareWithDefault("mac",t.mac)&&wn.compareWithDefault("macSalt",t.macSalt)&&wn.compareWithDefault("iterations",t.iterations);case Bf:return t instanceof Object&&Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new k({name:t.version||jo}),tt.schema(t.authSafe||{names:{blockName:Uo}}),wn.schema(t.macData||{names:{blockName:cr,optional:!0}})]})}fromSchema(e){V(e,iL);let t=R(e,e,s.schema({names:{version:jo,authSafe:{names:{blockName:Uo}},macData:{names:{blockName:cr}}}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.authSafe=new tt({schema:t.result.authSafe}),cr in t.result&&(this.macData=new wn({schema:t.result.macData}));}toSchema(){let e=[new k({value:this.version}),this.authSafe.toSchema()];return this.macData&&e.push(this.macData.toSchema()),new b({value:e})}toJSON(){let e={version:this.version,authSafe:this.authSafe.toJSON()};return this.macData&&(e.macData=this.macData.toJSON()),e}async makeInternalValues(e={},t=ve(!0)){if($e.assert(e,"parameters","object"),!this.parsedValue)throw new Error('Please call "parseValues" function first in order to make "parsedValue" data');switch(Re.assertEmpty(this.parsedValue.integrityMode,"integrityMode","parsedValue"),Re.assertEmpty(this.parsedValue.authenticatedSafe,"authenticatedSafe","parsedValue"),this.parsedValue.integrityMode){case 0:{if(!("iterations"in e))throw new Re("iterations");Re.assertEmpty(e.pbkdf2HashAlgorithm,"pbkdf2HashAlgorithm"),Re.assertEmpty(e.hmacHashAlgorithm,"hmacHashAlgorithm"),Re.assertEmpty(e.password,"password");let n=new ArrayBuffer(64),r=new Uint8Array(n);t.getRandomValues(r);let i=this.parsedValue.authenticatedSafe.toSchema().toBER(!1);this.authSafe=new tt({contentType:tt.DATA,content:new L({valueHex:i})});let a=await t.stampDataWithPassword({password:e.password,hashAlgorithm:e.hmacHashAlgorithm,salt:n,iterationCount:e.iterations,contentToStamp:i});this.macData=new wn({mac:new dr({digestAlgorithm:new P({algorithmId:t.getOIDByAlgorithm({name:e.hmacHashAlgorithm},!0,"hmacHashAlgorithm")}),digest:new L({valueHex:a})}),macSalt:new L({valueHex:n}),iterations:e.iterations});}break;case 1:{if(!("signingCertificate"in e))throw new Re("signingCertificate");Re.assertEmpty(e.privateKey,"privateKey"),Re.assertEmpty(e.hashAlgorithm,"hashAlgorithm");let n=this.parsedValue.authenticatedSafe.toSchema().toBER(!1),r=new Fi({version:1,encapContentInfo:new mr({eContentType:"1.2.840.113549.1.7.1",eContent:new L({valueHex:n})}),certificates:[e.signingCertificate]}),i=await t.digest({name:e.hashAlgorithm},new Uint8Array(n)),a=[];a.push(new nt({type:"1.2.840.113549.1.9.3",values:[new G({value:"1.2.840.113549.1.7.1"})]})),a.push(new nt({type:"1.2.840.113549.1.9.5",values:[new Wn({valueDate:new Date})]})),a.push(new nt({type:"1.2.840.113549.1.9.4",values:[new L({valueHex:i})]})),r.signerInfos.push(new Ul({version:1,sid:new vt({issuer:e.signingCertificate.issuer,serialNumber:e.signingCertificate.serialNumber}),signedAttrs:new Wt({type:0,attributes:a})})),await r.sign(e.privateKey,0,e.hashAlgorithm,void 0,t),this.authSafe=new tt({contentType:"1.2.840.113549.1.7.2",content:r.toSchema(!0)});}break;default:throw new Error(`Parameter "integrityMode" has unknown value: ${this.parsedValue.integrityMode}`)}}async parseInternalValues(e,t=ve(!0)){switch($e.assert(e,"parameters","object"),e.checkIntegrity===void 0&&(e.checkIntegrity=!0),this.parsedValue={},this.authSafe.contentType){case tt.DATA:{Re.assertEmpty(e.password,"password"),this.parsedValue.integrityMode=0,$e.assert(this.authSafe.content,"authSafe.content",L);let n=this.authSafe.content.getValue();if(this.parsedValue.authenticatedSafe=Zm.fromBER(n),e.checkIntegrity){if(!this.macData)throw new Error('Absent "macData" value, can not check PKCS#12 data integrity');let r=t.getAlgorithmByOID(this.macData.mac.digestAlgorithm.algorithmId,!0,"digestAlgorithm");if(!await t.verifyDataStampedWithPassword({password:e.password,hashAlgorithm:r.name,salt:re.toArrayBuffer(this.macData.macSalt.valueBlock.valueHexView),iterationCount:this.macData.iterations||1,contentToVerify:n,signatureToVerify:re.toArrayBuffer(this.macData.mac.digest.valueBlock.valueHexView)}))throw new Error("Integrity for the PKCS#12 data is broken!")}}break;case tt.SIGNED_DATA:{this.parsedValue.integrityMode=1;let n=new Fi({schema:this.authSafe.content}),r=n.encapContentInfo.eContent;Re.assert(r,"eContent","cmsSigned.encapContentInfo"),$e.assert(r,"eContent",L);let i=r.getValue();if(this.parsedValue.authenticatedSafe=Zm.fromBER(i),!await n.verify({signer:0,checkChain:!1},t))throw new Error("Integrity for the PKCS#12 data is broken!")}break;default:throw new Error(`Incorrect value for "this.authSafe.contentType": ${this.authSafe.contentType}`)}}};lA.CLASS_NAME="PFX";var ml="status",Li="statusStrings",ji="failInfo",aL=[ml,Li,ji],ik;(function(s){s[s.granted=0]="granted",s[s.grantedWithMods=1]="grantedWithMods",s[s.rejection=2]="rejection",s[s.waiting=3]="waiting",s[s.revocationWarning=4]="revocationWarning",s[s.revocationNotification=5]="revocationNotification";})(ik||(ik={}));var qo=class s extends O{constructor(e={}){super(),this.status=d(e,ml,s.defaultValues(ml)),Li in e&&(this.statusStrings=d(e,Li,s.defaultValues(Li))),ji in e&&(this.failInfo=d(e,ji,s.defaultValues(ji))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ml:return 2;case Li:return [];case ji:return new Ae;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ml:return t===s.defaultValues(e);case Li:return t.length===0;case ji:return t.isEqual(s.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new k({name:t.status||p}),new b({optional:!0,value:[new fe({name:t.statusStrings||p,value:new hs})]}),new Ae({name:t.failInfo||p,optional:!0})]})}fromSchema(e){V(e,aL);let t=R(e,e,s.schema({names:{status:ml,statusStrings:Li,failInfo:ji}}));T.assertSchema(t,this.className);let n=t.result.status;if(n.valueBlock.isHexOnly===!0||n.valueBlock.valueDec<0||n.valueBlock.valueDec>5)throw new Error('PKIStatusInfo "status" has invalid value');this.status=n.valueBlock.valueDec,Li in t.result&&(this.statusStrings=t.result.statusStrings),ji in t.result&&(this.failInfo=t.result.failInfo);}toSchema(){let e=[];return e.push(new k({value:this.status})),this.statusStrings&&e.push(new b({optional:!0,value:this.statusStrings})),this.failInfo&&e.push(this.failInfo),new b({value:e})}toJSON(){let e={status:this.status};return this.statusStrings&&(e.statusStrings=Array.from(this.statusStrings,t=>t.toJSON())),this.failInfo&&(e.failInfo=this.failInfo.toJSON()),e}};qo.CLASS_NAME="PKIStatusInfo";var Im="version",Cm="messageImprint",pl="reqPolicy",gl="nonce",ur="certReq",yl="extensions",tc="TimeStampReq",hA=`${tc}.${Im}`,fA=`${tc}.${Cm}`,Yy=`${tc}.${pl}`,Zy=`${tc}.${gl}`,Qy=`${tc}.${ur}`,Xy=`${tc}.${yl}`,oL=[hA,fA,Yy,Zy,Qy,Xy],dA=class s extends O{constructor(e={}){super(),this.version=d(e,Im,s.defaultValues(Im)),this.messageImprint=d(e,Cm,s.defaultValues(Cm)),pl in e&&(this.reqPolicy=d(e,pl,s.defaultValues(pl))),gl in e&&(this.nonce=d(e,gl,s.defaultValues(gl))),ur in e&&(this.certReq=d(e,ur,s.defaultValues(ur))),yl in e&&(this.extensions=d(e,yl,s.defaultValues(yl))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Im:return 0;case Cm:return new Es;case pl:return p;case gl:return new k;case ur:return !1;case yl:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Im:case pl:case ur:return t===s.defaultValues(e);case Cm:return Es.compareWithDefault("hashAlgorithm",t.hashAlgorithm)&&Es.compareWithDefault("hashedMessage",t.hashedMessage);case gl:return t.isEqual(s.defaultValues(e));case yl:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||tc,value:[new k({name:t.version||hA}),Es.schema(t.messageImprint||{names:{blockName:fA}}),new G({name:t.reqPolicy||Yy,optional:!0}),new k({name:t.nonce||Zy,optional:!0}),new xs({name:t.certReq||Qy,optional:!0}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new fe({name:t.extensions||Xy,value:ds.schema()})]})]})}fromSchema(e){V(e,oL);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.version=t.result[hA].valueBlock.valueDec,this.messageImprint=new Es({schema:t.result[fA]}),Yy in t.result&&(this.reqPolicy=t.result[Yy].valueBlock.toString()),Zy in t.result&&(this.nonce=t.result[Zy]),Qy in t.result&&(this.certReq=t.result[Qy].valueBlock.value),Xy in t.result&&(this.extensions=Array.from(t.result[Xy],n=>new ds({schema:n})));}toSchema(){let e=[];return e.push(new k({value:this.version})),e.push(this.messageImprint.toSchema()),this.reqPolicy&&e.push(new G({value:this.reqPolicy})),this.nonce&&e.push(this.nonce),ur in this&&s.compareWithDefault(ur,this.certReq)===!1&&e.push(new xs({value:this.certReq})),this.extensions&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.extensions,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={version:this.version,messageImprint:this.messageImprint.toJSON()};return this.reqPolicy!==void 0&&(e.reqPolicy=this.reqPolicy),this.nonce!==void 0&&(e.nonce=this.nonce.toJSON()),this.certReq!==void 0&&s.compareWithDefault(ur,this.certReq)===!1&&(e.certReq=this.certReq),this.extensions&&(e.extensions=Array.from(this.extensions,t=>t.toJSON())),e}};dA.CLASS_NAME="TimeStampReq";var wl="status",bl="timeStampToken",OA="TimeStampResp",mA=`${OA}.${wl}`,ew=`${OA}.${bl}`,cL=[mA,ew],pA=class s extends O{constructor(e={}){super(),this.status=d(e,wl,s.defaultValues(wl)),bl in e&&(this.timeStampToken=d(e,bl,s.defaultValues(bl))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case wl:return new qo;case bl:return new tt;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case wl:return qo.compareWithDefault(wl,t.status)&&!("statusStrings"in t)&&!("failInfo"in t);case bl:return t.contentType===p&&t.content instanceof ue;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||OA,value:[qo.schema(t.status||{names:{blockName:mA}}),tt.schema(t.timeStampToken||{names:{blockName:ew,optional:!0}})]})}fromSchema(e){V(e,cL);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.status=new qo({schema:t.result[mA]}),ew in t.result&&(this.timeStampToken=new tt({schema:t.result[ew]}));}toSchema(){let e=[];return e.push(this.status.toSchema()),this.timeStampToken&&e.push(this.timeStampToken.toSchema()),new b({value:e})}toJSON(){let e={status:this.status.toJSON()};return this.timeStampToken&&(e.timeStampToken=this.timeStampToken.toJSON()),e}async sign(e,t,n=ve(!0)){return this.assertContentType(),new Fi({schema:this.timeStampToken.content}).sign(e,0,t,void 0,n)}async verify(e={signer:0,trustedCerts:[],data:ut},t=ve(!0)){return this.assertContentType(),new Fi({schema:this.timeStampToken.content}).verify(e,t)}assertContentType(){if(!this.timeStampToken)throw new Error("timeStampToken is absent in TSP response");if(this.timeStampToken.contentType!==gk)throw new Error(`Wrong format of timeStampToken: ${this.timeStampToken.contentType}`)}};pA.CLASS_NAME="TimeStampResp";function uL(){if(typeof globalThis<"u"&&"crypto"in globalThis){let s="webcrypto";"webkitSubtle"in globalThis.crypto&&(s="safari"),qN(s,new kl({name:s,crypto:globalThis.crypto}));}else if(typeof crypto<"u"&&"webcrypto"in crypto){let s="NodeJS ^15",e=crypto.webcrypto;qN(s,new kl({name:s,crypto:e}));}}uL();var DA=(s,e)=>e.some(t=>s instanceof t),Ck,Nk;function lL(){return Ck||(Ck=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function hL(){return Nk||(Nk=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var LA=new WeakMap,RA=new WeakMap,Pw=new WeakMap;function fL(s){let e=new Promise((t,n)=>{let r=()=>{s.removeEventListener("success",i),s.removeEventListener("error",a);},i=()=>{t(sc(s.result)),r();},a=()=>{n(s.error),r();};s.addEventListener("success",i),s.addEventListener("error",a);});return Pw.set(e,s),e}function dL(s){if(LA.has(s))return;let e=new Promise((t,n)=>{let r=()=>{s.removeEventListener("complete",i),s.removeEventListener("error",a),s.removeEventListener("abort",a);},i=()=>{t(),r();},a=()=>{n(s.error||new DOMException("AbortError","AbortError")),r();};s.addEventListener("complete",i),s.addEventListener("error",a),s.addEventListener("abort",a);});LA.set(s,e);}var jA={get(s,e,t){if(s instanceof IDBTransaction){if(e==="done")return LA.get(s);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return sc(s[e])},set(s,e,t){return s[e]=t,!0},has(s,e){return s instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in s}};function Bk(s){jA=s(jA);}function mL(s){return hL().includes(s)?function(...e){return s.apply(UA(this),e),sc(this.request)}:function(...e){return sc(s.apply(UA(this),e))}}function pL(s){return typeof s=="function"?mL(s):(s instanceof IDBTransaction&&dL(s),DA(s,lL())?new Proxy(s,jA):s)}function sc(s){if(s instanceof IDBRequest)return fL(s);if(RA.has(s))return RA.get(s);let e=pL(s);return e!==s&&(RA.set(s,e),Pw.set(e,s)),e}var UA=s=>Pw.get(s);function Ok(s,e,{blocked:t,upgrade:n,blocking:r,terminated:i}={}){let a=indexedDB.open(s,e),o=sc(a);return n&&a.addEventListener("upgradeneeded",c=>{n(sc(a.result),c.oldVersion,c.newVersion,sc(a.transaction),c);}),t&&a.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),o.then(c=>{i&&c.addEventListener("close",()=>i()),r&&c.addEventListener("versionchange",u=>r(u.oldVersion,u.newVersion,u));}).catch(()=>{}),o}var gL=["get","getKey","getAll","getAllKeys","count"],yL=["put","add","delete","clear"],VA=new Map;function kk(s,e){if(!(s instanceof IDBDatabase&&!(e in s)&&typeof e=="string"))return;if(VA.get(e))return VA.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,r=yL.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(r||gL.includes(t)))return;let i=async function(a,...o){let c=this.transaction(a,r?"readwrite":"readonly"),u=c.store;return n&&(u=u.index(o.shift())),(await Promise.all([u[t](...o),r&&c.done]))[0]};return VA.set(e,i),i}Bk(s=>({...s,get:(e,t,n)=>kk(e,t)||s.get(e,t,n),has:(e,t)=>!!kk(e,t)||s.has(e,t)}));var wL=["continue","continuePrimaryKey","advance"],Pk={},HA=new WeakMap,Rk=new WeakMap,bL={get(s,e){if(!wL.includes(e))return s[e];let t=Pk[e];return t||(t=Pk[e]=function(...n){HA.set(this,Rk.get(this)[e](...n));}),t}};async function*SL(...s){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...s)),!e)return;e=e;let t=new Proxy(e,bL);for(Rk.set(t,e),Pw.set(t,UA(e));e;)yield t,e=await(HA.get(t)||e.continue()),HA.delete(t);}function Tk(s,e){return e===Symbol.asyncIterator&&DA(s,[IDBIndex,IDBObjectStore,IDBCursor])||e==="iterate"&&DA(s,[IDBIndex,IDBObjectStore])}Bk(s=>({...s,get(e,t,n){return Tk(e,t)?SL:s.get(e,t,n)},has(e,t){return Tk(e,t)||s.has(e,t)}}));function Vk(s,e){if(s===e)return !0;if(s===null||e===null||typeof s!="object"||typeof e!="object")return !1;let t=Object.keys(s),n=Object.keys(e);if(t.length!==n.length)return !1;for(let r of t)if(!n.includes(r)||!Vk(s[r],e[r]))return !1;return !0}var xt=class{dbName;storeName;key;migrations;_db=null;listeners=[];broadcastChannel;constructor(e,t,n,r=[]){this.dbName=e,this.storeName=t,this.key=n,this.migrations=r,typeof BroadcastChannel<"u"&&(this.broadcastChannel=new BroadcastChannel(this.dbName+"-observer"),this.broadcastChannel.onmessage=i=>{i.data&&i.data.keyValue!==void 0&&i.data.updateType&&this.listeners.forEach(a=>a(i.data.keyValue,i.data.updateType,i.data.oldItem,i.data.newItem));});}async openDB(){if(this._db)return this._db;let e=this.migrations.length+1;return this._db=await Ok(this.dbName,e,{upgrade:(t,n,r,i,a)=>{if(r!==null)for(let o=n+1;o<=r;o++){let c=o-2;if(c>=0&&c<this.migrations.length){let u=this.migrations[c];if(u)u(t,i,a);else throw new Error(`Migration for schema version ${o} (using migrations[${c}]) not found but expected.`)}}},blocked:()=>{console.error(`IndexedDB ${this.dbName} upgrade blocked.`);},blocking:()=>{console.warn(`IndexedDB ${this.dbName} upgrade is being blocked by other connections. Closing this connection.`),this._db&&(this._db.close(),this._db=null);},terminated:()=>{console.warn(`IndexedDB ${this.dbName} connection terminated.`),this._db=null;}}),await this.handleOpenDB(),this._db}async handleOpenDB(){}async getStore(e){return (await this.openDB()).transaction(this.storeName,e).objectStore(this.storeName)}async get(e){return (await this.getStore("readonly")).get(e)}async list(){return (await this.getStore("readonly")).getAll()}async set(e){let t=await this.openDB(),n=e[this.key],r=t.transaction(this.storeName,"readwrite"),i=r.objectStore(this.storeName),a=await i.get(n);await i.put(e,n),await r.done;let o=null;return a?Vk(a,e)||(o="updated"):o="added",o&&this.notifyUpdate(n,o,a,e),n}async del(e){let t=await this.get(e),r=(await this.openDB()).transaction(this.storeName,"readwrite");await r.objectStore(this.storeName).delete(e),await r.done,t&&this.notifyUpdate(e,"removed",t,void 0);}notifyUpdate(e,t,n,r){this.listeners.forEach(i=>i(e,t,n,r)),this.broadcastChannel&&this.broadcastChannel.postMessage({keyValue:e,updateType:t,oldItem:n,newItem:r});}addListener(e){return this.listeners.push(e),()=>this.removeListener(e)}removeListener(e){this.listeners=this.listeners.filter(t=>t!==e);}async close(){this._db&&(this._db.close(),this._db=null),this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=void 0);}};var _A="auth-commitments",t0=class extends xt{constructor(e="sequence-auth-commitments"){super(e,_A,"id",[(t,n,r)=>{t.objectStoreNames.contains(_A)||t.createObjectStore(_A);}]);}};var MA="auth-keys",s0=class extends xt{expirationTimers=new Map;constructor(e="sequence-auth-keys"){super(e,MA,"address",[(t,n,r)=>{t.objectStoreNames.contains(MA)||t.createObjectStore(MA).createIndex("identitySigner","identitySigner",{unique:!0});}]);}async handleOpenDB(){let e=await this.list();for(let t of e)await this.scheduleExpiration(t);}async set(e){let t=await super.set({...e,address:e.address.toLowerCase(),identitySigner:e.identitySigner.toLowerCase()});return this.scheduleExpiration(e),t}async del(e){let t=await super.del(e.toLowerCase());return this.clearExpiration(e),t}async getBySigner(e,t=1){let n=e.toLowerCase(),r=await this.getStore("readonly"),i=r.index("identitySigner");try{let a=await i.get(n);if(a!==void 0)return a;if(t<2)return await new Promise(o=>setTimeout(o,50)),this.getBySigner(e,t+1);try{let o=await r.getAll();return o&&o.length>0?o.find(u=>u.identitySigner.toLowerCase()===n):void 0}catch(o){throw console.error(`[AuthKeys.getBySigner] Fallback: Error during getAll() for signer ${n}:`,o),o}}catch(a){throw console.error(`[AuthKeys.getBySigner attempt #${t}] Index query error for signer ${n}:`,a),a}}async delBySigner(e){let t=await this.getBySigner(e.toLowerCase());t&&await this.del(t.address.toLowerCase());}async scheduleExpiration(e){this.clearExpiration(e.address.toLowerCase());let t=Date.now(),n=e.expiresAt.getTime()-t;if(n<=0){await this.del(e.address.toLowerCase());return}let r=window.setTimeout(()=>{console.log("removing expired auth key",e),this.del(e.address.toLowerCase());},n);this.expirationTimers.set(e.address.toLowerCase(),r);}clearExpiration(e){let t=this.expirationTimers.get(e.toLowerCase());t&&(window.clearTimeout(t),this.expirationTimers.delete(e.toLowerCase()));}};var $A="messages",n0=class extends xt{constructor(e="sequence-messages"){super(e,$A,"id",[(t,n,r)=>{t.objectStoreNames.contains($A)||t.createObjectStore($A);}]);}};var qA="envelopes",r0=class extends xt{constructor(e="sequence-signature-requests"){super(e,qA,"id",[(t,n,r)=>{t.objectStoreNames.contains(qA)||t.createObjectStore(qA);}]);}};var FA="transactions",i0=class extends xt{constructor(e="sequence-transactions"){super(e,FA,"id",[(t,n,r)=>{t.objectStoreNames.contains(FA)||t.createObjectStore(FA);}]);}};var KA="wallets",a0=class extends xt{constructor(e="sequence-manager"){super(e,KA,"address",[(t,n,r)=>{t.objectStoreNames.contains(KA)||t.createObjectStore(KA);}]);}};var GA="queued-recovery-payloads",o0=class extends xt{constructor(e="sequence-recovery"){super(e,GA,"id",[(t,n,r)=>{t.objectStoreNames.contains(GA)||t.createObjectStore(GA);}]);}};var WA="passkey-credentials",c0=class extends xt{constructor(e="sequence-passkey-credentials"){super(e,WA,"credentialId",[(t,n,r)=>{t.objectStoreNames.contains(WA)||t.createObjectStore(WA);}]);}async getByCredentialId(e){return this.get(e)}async saveCredential(e,t,n){let r=new Date().toISOString(),i={credentialId:e,publicKey:t,walletAddress:n,createdAt:r,lastLoginAt:r};await this.set(i);}async updateCredential(e,{lastLoginAt:t,walletAddress:n}){let r=await this.getByCredentialId(e);if(r){let i={...r,lastLoginAt:t,walletAddress:n};await this.set(i);}}};({verbose:!1,extensions:Ne.Rc5,context:wa.Rc5,context4337:wa.Rc5_4337,guest:_e.DefaultGuestAddress,encryptedPksDb:new Ks.Pk.Encrypted.EncryptedPksDb,managerDb:new a0,signaturesDb:new r0,transactionsDb:new i0,messagesDb:new n0,authCommitmentsDb:new t0,recoveryDb:new o0,authKeysDb:new s0,passkeyCredentialsDb:new c0,dbPruningInterval:1e3*60*60*24,stateProvider:new Hc.Sequence.Provider,networks:Sa.ALL,relayers:()=>typeof window<"u"?[ef.LocalRelayer.createFromWindow(window)].filter(s=>s!==void 0):[],bundlers:[],nonWitnessableSigners:[],guardUrl:"https://guard.sequence.app",guardAddresses:{wallet:"0x26f3D30F41FA897309Ae804A2AFf15CEb1dA5742",sessions:"0xF6Bc87F5F2edAdb66737E32D37b46423901dfEF1"},defaultGuardTopology:{type:"nested",weight:1n,threshold:1n,tree:[{type:"signer",address:_e.PlaceholderAddress,weight:1n},{type:"signer",address:"0x007a47e6BF40C1e0ed5c01aE42fDC75879140bc4",weight:1n}]},defaultSessionsTopology:{type:"sapient-signer",weight:1n},defaultRecoverySettings:{requiredDeltaTime:2592000n,minTimestamp:0n},multiInjectedProviderDiscovery:!0,identity:{url:"https://identity.sequence.app",fetch:typeof window<"u"?window.fetch:void 0,verifyAttestation:!0,email:{enabled:!1},google:{enabled:!1,clientId:""},apple:{enabled:!1,clientId:""}}});var u0=class{#e;#s;#n=null;#t=null;constructor(e,t){this.#e=e,this.#s=t;}async#a(){let e=await this.#e.getUser();if(!e)throw new ze("User not authenticated","NOT_LOGGED_IN_ERROR");return e}async#i(){let e=this.#n;e||(e=await this.#r());let t=await this.#a();return t.profile.sub!==e.userIdentifier&&(e=await this.#r(t)),e}async#r(e){return this.#t?this.#t:(this.#t=(async()=>{try{this.#n=null,await this.#e.forceUserRefresh();let t=e||await this.#a();if(!t.idToken)throw new ze("User idToken not available","NOT_LOGGED_IN_ERROR");let{idToken:n}=t,r=decodeJwtPayload(n),i=r.iss,a=r.aud,o=await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"]),c=await window.crypto.subtle.exportKey("raw",o.publicKey),u={address:E.fromBytes(new Uint8Array(c)),privateKey:o.privateKey,identitySigner:"",expiresAt:new Date(Date.now()+36e5)},l=new Wh(this.#s.identityInstrumentEndpoint,"@14:test"),h=new Pg(i,a,n);await l.commitVerifier(xa.toIdentityAuthKey(u),h);let y=(await l.completeAuth(xa.toIdentityAuthKey(u),h)).signer.address;return u.identitySigner=y,this.#n={userIdentifier:t.profile.sub,signerAddress:y,authKey:u,identityInstrument:l},this.#n}catch(t){let n=`Identity Instrument: Failed to create signer: ${t.message}`;throw new ze(n,"WALLET_CONNECTION_ERROR")}finally{this.#t=null;}})(),this.#t)}async getAddress(){return (await this.#i()).signerAddress}async signPayload(e,t,n){let r=await this.#i();return new xa.IdentitySigner(r.identityInstrument,r.authKey).sign(e,t,n)}async signMessage(e){let t=await this.#i(),n=new xa.IdentitySigner(t.identityInstrument,t.authKey),r=typeof e=="string"?new TextEncoder().encode(e):e,i=hashMessage({raw:r}),a=await n.signDigest(E.toBytes(i)),o=toHex(a.r,{size:32}),c=toHex(a.s,{size:32}),u=toHex(a.yParity+27,{size:1});return concat([o,c,u])}};var l0=class{#e;#s=null;#n=null;constructor(e){this.#e=e;}async#t(){let e=await this.#e.getUser();if(!e)throw new ze("User not authenticated","NOT_LOGGED_IN_ERROR");return e}async#a(){let e=this.#s;e||(e=await this.#i());let t=await this.#t();return t.profile.sub!==e.userIdentifier&&(e=await this.#i(t)),e}async#i(e){return this.#n?this.#n:(this.#n=(async()=>{try{this.#s=null;let t=e||await this.#t(),n=keccak256(toBytes(`${t.profile.sub}-sequence`)),r=new Ks.Pk.Pk(n),i=r.address;return this.#s={userIdentifier:t.profile.sub,signerAddress:i,signer:r,privateKey:n},this.#s}catch(t){let n=`Failed to create private key wallet: ${t.message}`;throw new ze(n,"WALLET_CONNECTION_ERROR")}finally{this.#n=null;}})(),this.#n)}async getAddress(){return (await this.#a()).signerAddress}async signPayload(e,t,n){return (await this.#a()).signer.sign(e,t,n)}async signMessage(e){let t=await this.#a(),n=privateKeyToAccount(t.privateKey),r=typeof e=="string"?e:{raw:e};return await n.signMessage({message:r})}};var jL="https://auth.dev.immutable.com";function _k(s,e,t={}){if(e.authenticationDomain===jL)return new l0(s);if(!t.identityInstrumentEndpoint)throw new Error("identityInstrumentEndpoint is required for non-dev environments");return new u0(s,{identityInstrumentEndpoint:t.identityInstrumentEndpoint})}function FL(s){return s in Sr}function KL(s){if(s.magicPublishableApiKey&&s.magicProviderId)return {magicPublishableApiKey:s.magicPublishableApiKey,magicProviderId:s.magicProviderId};let{chainId:e}=s;if(FL(e))return Sr[e];throw new Error(`No Magic configuration available for chain ${s.chainId}. Please provide magicPublishableApiKey and magicProviderId in ChainConfig.`)}var GL="PtQRK4iRJ8GkXjiz6xfImMAYhPhW0cYk",WL="mjtCL8mt06BtbxSkp2vbrYStKWnXVZfo",JL="openid profile email offline_access transact",zL="platform_api",YL="https://auth.immutable.com/im-logged-in",ZL="https://auth.immutable.com",QL=/(sandbox|testnet)/i,XL=[13371,13473,15003];function ej(s){return XL.includes(s.chainId)}function tj(s){if(s.chainId===13473)return !0;let e=s.apiUrl||s.passportDomain||"";return QL.test(e)}function sj(s){if(s.passportDomain)return s.passportDomain;if(s.apiUrl)try{let e=new URL(s.apiUrl),t=e.hostname.replace("api.","passport.");return `${e.protocol}//${t}`}catch{return s.apiUrl.replace("api.","passport.")}return "https://passport.immutable.com"}function nj(){return ZL}function rj(){return YL}function ij(s){return tj(s)?WL:GL}function aj(s,e){let t=sj(s),n=nj(),r=rj();return new Auth({clientId:ij(s),redirectUri:r,popupRedirectUri:r,logoutRedirectUri:r,scope:JL,audience:zL,authenticationDomain:n,passportDomain:t,popupOverlayOptions:e.popupOverlayOptions,crossSdkBridgeEnabled:e.crossSdkBridgeEnabled})}async function oj(s={}){let e=s.chains&&s.chains.length>0?s.chains:A0,t=s.initialChainId||e[0].chainId,n=e.find(g=>g.chainId===t);if(!n)throw new Error(`Initial chain ${t} not found in chains configuration`);let r=createConfig({basePath:n.apiUrl}),i=new MultiRollupApiClients({indexer:r,orderBook:r,passport:r}),a=s.auth??aj(n,s);!s.auth&&typeof window<"u"&&window.addEventListener("message",async g=>{if(g.data.code&&g.data.state){let w=window.location.search,S=new URLSearchParams(w);S.set("code",g.data.code),S.set("state",g.data.state),window.history.replaceState(null,"",`?${S.toString()}`),await a.loginCallback(),S.delete("code"),S.delete("state"),window.history.replaceState(null,"",`?${S.toString()}`);}});let o=a.getConfig(),c=await a.getUser(),u=new th({passportDomain:n.passportDomain||n.apiUrl.replace("api.","passport."),zkEvmRpcUrl:n.rpcUrl,relayerUrl:n.relayerUrl,indexerMrBasePath:n.apiUrl,jsonRpcReferrer:s.jsonRpcReferrer,forceScwDeployBeforeMessageSignature:s.forceScwDeployBeforeMessageSignature,crossSdkBridgeEnabled:s.crossSdkBridgeEnabled,feeTokenSymbol:s.feeTokenSymbol}),l=s.passportEventEmitter||new TypedEventEmitter,h=new mr$1.GuardianApi(r),m=new cc({config:u,auth:a,guardianApi:h,authConfig:o}),y;if(ej(n)){let g=KL(n),w=n.magicTeeBasePath||"https://tee.express.magiclabs.com",S=new MagicTeeApiClients({basePath:w,timeout:1e4,magicPublishableApiKey:g.magicPublishableApiKey,magicProviderId:g.magicProviderId}),C=new uc(a,S),N=null;n.chainId===13371?N="https://api.immutable.com":n.chainId===13473?N="https://api.sandbox.immutable.com":n.apiUrl&&(N=n.apiUrl),y=new Xl({auth:a,config:u,multiRollupApiClients:i,passportEventEmitter:l,guardianClient:m,ethSigner:C,user:c,sessionActivityApiUrl:N});}else {let g=_k(a,o,{identityInstrumentEndpoint:n.sequenceIdentityInstrumentEndpoint});y=new eh({auth:a,chainConfig:n,multiRollupApiClients:i,guardianClient:m,ethSigner:g,passportEventEmitter:l});}return s.announceProvider!==!1&&Xw({info:Qw,provider:y}),y}function hj(s){return typeof s=="object"&&s!==null&&"code"in s&&"message"in s}async function fj(s,e){let t=await s.getUser();if(!t?.profile.sub)return [];let n={Authorization:`Bearer ${t.accessToken}`},{data:r}=await e.passportProfileApi.getUserInfo({headers:n});return r.linked_addresses}async function dj(s,e,t){let n=trackFlow("wallet","linkExternalWallet");try{let r=await s.getUser();if(!r)throw new ze("User is not logged in","NOT_LOGGED_IN_ERROR");if(!isUserZkEvm(r))throw new ze("User has not been registered on Immutable zkEVM","WALLET_CONNECTION_ERROR");let a={Authorization:`Bearer ${r.accessToken}`},o={type:t.type,wallet_address:t.walletAddress,signature:t.signature,nonce:t.nonce};return {...(await e.passportProfileApi.linkWalletV2({linkWalletV2Request:o},{headers:a})).data}}catch(r){if(r instanceof Error?trackError("wallet","linkExternalWallet",r):n.addEvent("errored"),Ji(r)&&r.response){if(r.response.data&&hj(r.response.data)){let{code:a,message:o}=r.response.data;switch(a){case"ALREADY_LINKED":throw new ze(o,"WALLET_CONNECTION_ERROR");case"MAX_WALLETS_LINKED":throw new ze(o,"WALLET_CONNECTION_ERROR");case"DUPLICATE_NONCE":throw new ze(o,"WALLET_CONNECTION_ERROR");case"VALIDATION_ERROR":throw new ze(o,"WALLET_CONNECTION_ERROR");default:throw new ze(o,"WALLET_CONNECTION_ERROR")}}else if(r.response.status)throw new ze(`Link wallet request failed with status code ${r.response.status}`,"WALLET_CONNECTION_ERROR")}let i="Link wallet request failed";throw r instanceof Error&&(i+=`: ${r.message}`),new ze(i,"WALLET_CONNECTION_ERROR")}finally{n.addEvent("End");}}/*! Bundled license information:
|
|
375
|
+
`)}`:`${t} :`}};tN=A;Z.Constructed=tN;A.NAME="CONSTRUCTED";var I1=class extends Gt{fromBER(e,t,n){return t}toBER(e){return gn}};I1.override="EndOfContentValueBlock";var sN,C1=class extends Dt{constructor(e={}){super(e,I1),this.idBlock.tagClass=1,this.idBlock.tagNumber=0;}};sN=C1;Z.EndOfContent=sN;C1.NAME=df;var nN,Xe=class extends Dt{constructor(e={}){super(e,Gt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5;}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let r=new Uint8Array(n);r[0]=5,r[1]=0;}return t&&t.write(n),n}onAsciiEncoding(){return `${this.constructor.NAME}`}};nN=Xe;Z.Null=nN;Xe.NAME="NULL";var N1=class extends zn(Gt){get value(){for(let e of this.valueHexView)if(e>0)return !0;return !1}set value(e){this.valueHexView[0]=e?255:0;}constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=re.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e);}fromBER(e,t,n){let r=re.toUint8Array(e);return Jn(this,r,t,n)?(this.valueHexView=r.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,WE.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return {...super.toJSON(),value:this.value}}};N1.NAME="BooleanValueBlock";var rN,xs=class extends Dt{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e;}constructor(e={}){super(e,N1),this.idBlock.tagClass=1,this.idBlock.tagNumber=1;}onAsciiEncoding(){return `${this.constructor.NAME} : ${this.getValue}`}};rN=xs;Z.Boolean=rN;xs.NAME="BOOLEAN";var k1=class extends zn(mn){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e;}fromBER(e,t,n){let r=0;if(this.isConstructed){if(this.isHexOnly=!1,r=mn.prototype.fromBER.call(this,e,t,n),r===-1)return r;for(let i=0;i<this.value.length;i++){let a=this.value[i].constructor.NAME;if(a===df){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==Z8)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,r=super.fromBER(e,t,n),this.blockLength=n;return r}toBER(e,t){return this.isConstructed?mn.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return {...super.toJSON(),isConstructed:this.isConstructed}}};k1.NAME="OctetStringValueBlock";var YE,U=class extends Dt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var r,i;(r=n.isConstructed)!==null&&r!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},k1),this.idBlock.tagClass=1,this.idBlock.tagNumber=4;}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let a=yf(i,0,i.byteLength);a.offset!==-1&&a.offset===n&&(this.valueBlock.value=[a.result]);}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return A.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,t=he.ToHex(this.valueBlock.valueHexView);return `${e} : ${t}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof YE&&e.push(t.valueBlock.valueHexView);return re.concat(e)}};YE=U;Z.OctetString=YE;U.NAME=Z8;var P1=class extends zn(mn){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength;}fromBER(e,t,n){if(!n)return t;let r=-1;if(this.isConstructed){if(r=mn.prototype.fromBER.call(this,e,t,n),r===-1)return r;for(let o of this.value){let c=o.constructor.NAME;if(c===df){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Q8)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=o.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits;}return r}let i=re.toUint8Array(e);if(!Jn(this,i,t,n))return -1;let a=i.subarray(t,t+n);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let o=a.subarray(1);try{if(o.byteLength){let c=yf(o,0,o.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result]);}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,t+n}toBER(e,t){if(this.isConstructed)return mn.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let r=new Uint8Array(1);return r[0]=0,r.buffer}let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return {...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};P1.NAME="BitStringValueBlock";var iN,Ae=class extends Dt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var r,i;(r=n.isConstructed)!==null&&r!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},P1),this.idBlock.tagClass=1,this.idBlock.tagNumber=3;}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return A.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let a of t)e.push(a.toString(2).padStart(8,"0"));let n=e.join(""),r=this.constructor.NAME,i=n.substring(0,n.length-this.valueBlock.unusedBits);return `${r} : ${i}`}}};iN=Ae;Z.BitString=iN;Ae.NAME=Q8;var aN;function u7(s,e){let t=new Uint8Array([0]),n=new Uint8Array(s),r=new Uint8Array(e),i=n.slice(0),a=i.length-1,o=r.slice(0),c=o.length-1,u=0,l=c<a?a:c,h=0;for(let m=l;m>=0;m--,h++){switch(!0){case h<o.length:u=i[a-h]+o[c-h]+t[0];break;default:u=i[a-h]+t[0];}switch(t[0]=u/10,!0){case h>=i.length:i=w1(new Uint8Array([u%10]),i);break;default:i[a-h]=u%10;}}return t[0]>0&&(i=w1(t,i)),i}function Y8(s){if(s>=lf.length)for(let e=lf.length;e<=s;e++){let t=new Uint8Array([0]),n=lf[e-1].slice(0);for(let r=n.length-1;r>=0;r--){let i=new Uint8Array([(n[r]<<1)+t[0]]);t[0]=i[0]/10,n[r]=i[0]%10;}t[0]>0&&(n=w1(t,n)),lf.push(n);}return lf[s]}function l7(s,e){let t=0,n=new Uint8Array(s),r=new Uint8Array(e),i=n.slice(0),a=i.length-1,o=r.slice(0),c=o.length-1,u,l=0;for(let h=c;h>=0;h--,l++)switch(u=i[a-l]-o[c-l]-t,!0){case u<0:t=1,i[a-l]=u+10;break;default:t=0,i[a-l]=u;}if(t>0)for(let h=a-c+1;h>=0;h--,l++)if(u=i[a-l]-t,u<0)t=1,i[a-l]=u+10;else {t=0,i[a-l]=u;break}return i.slice()}var mf=class extends zn(Gt){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=WE.call(this)));}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e);}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(q8(e));}get valueDec(){return this._valueDec}fromDER(e,t,n,r=0){let i=this.fromBER(e,t,n);if(i===-1)return i;let a=this.valueHexView;return a[0]===0&&a[1]&128?this.valueHexView=a.subarray(1):r!==0&&a.length<r&&(r-a.length>1&&(r=a.length+1),this.valueHexView=a.subarray(r-a.length)),i}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n;}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let r=super.fromBER(e,t,n);return r===-1||this.setValueHex(),r}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return {...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,r,i=this.valueHexView,a="",o=!1;for(let c=i.byteLength-1;c>=0;c--){r=i[c];for(let u=0;u<8;u++){if((r&1)===1)switch(n){case e:t=l7(Y8(n),t),a="-";break;default:t=u7(t,Y8(n));}n++,r>>=1;}}for(let c=0;c<t.length;c++)t[c]&&(o=!0),o&&(a+=J8.charAt(t[c]));return o===!1&&(a+=J8.charAt(0)),a}};aN=mf;mf.NAME="IntegerValueBlock";Object.defineProperty(aN.prototype,"valueHex",{set:function(s){this.valueHexView=new Uint8Array(s),this.setValueHex();},get:function(){return this.valueHexView.slice().buffer}});var hf,N=class extends Dt{constructor(e={}){super(e,mf),this.idBlock.tagClass=1,this.idBlock.tagNumber=2;}toBigInt(){return S1(),BigInt(this.valueBlock.toString())}static fromBigInt(e){S1();let t=BigInt(e),n=new ff,r=t.toString(16).replace(/^-/,""),i=new Uint8Array(he.FromHex(r));if(t<0){let o=new Uint8Array(i.length+(i[0]&128?1:0));o[0]|=128;let u=BigInt(`0x${he.ToHex(o)}`)+t,l=re.toUint8Array(he.FromHex(u.toString(16)));l[0]|=128,n.write(l);}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new hf({valueHex:n.final()})}convertToDER(){let e=new hf({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new hf({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return `${this.constructor.NAME} : ${this.valueBlock.toString()}`}};hf=N;Z.Integer=hf;N.NAME="INTEGER";var oN,pn=class extends N{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10;}};oN=pn;Z.Enumerated=oN;pn.NAME="ENUMERATED";var pf=class extends zn(Gt){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t;}fromBER(e,t,n){if(!n)return t;let r=re.toUint8Array(e);if(!Jn(this,r,t,n))return -1;let i=r.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let o=0;o<n&&(this.valueHexView[o]=i[o]&127,this.blockLength++,!!(i[o]&128));o++);let a=new Uint8Array(this.blockLength);for(let o=0;o<this.blockLength;o++)a[o]=this.valueHexView[o];return this.valueHexView=a,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Fn(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){S1();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let r=0;r<n.length;r++)n[r]=parseInt(t.slice(r*7,r*7+7),2)+(r+1<n.length?128:0);this.fromBER(n.buffer,0,n.length);}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let r=this.valueHexView,i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength-1;a++)i[a]=r[a]|128;return i[this.blockLength-1]=r[this.blockLength-1],i.buffer}let t=Js(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",gn;let n=new Uint8Array(t.byteLength);if(!e){let r=new Uint8Array(t),i=t.byteLength-1;for(let a=0;a<i;a++)n[a]=r[a]|128;n[i]=r[i];}return n}toString(){let e="";if(this.isHexOnly)e=he.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString();}else e=this.valueDec.toString();return e}toJSON(){return {...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};pf.NAME="sidBlock";var T1=class extends Gt{constructor({value:e=ls,...t}={}){super(t),this.value=[],e&&this.fromString(e);}fromBER(e,t,n){let r=t;for(;n>0;){let i=new pf;if(r=i.fromBER(e,r,n),r===-1)return this.blockLength=0,this.error=i.error,r;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i);}return r}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let r=this.value[n].toBER(e);if(r.byteLength===0)return this.error=this.value[n].error,gn;t.push(r);}return zE(t)}fromString(e){this.value=[];let t=0,n=0,r="",i=!1;do if(n=e.indexOf(".",t),n===-1?r=e.substring(t):r=e.substring(t,n),t=n+1,i){let a=this.value[0],o=0;switch(a.valueDec){case 0:break;case 1:o=40;break;case 2:o=80;break;default:this.value=[];return}let c=parseInt(r,10);if(isNaN(c))return;a.valueDec=c+o,i=!1;}else {let a=new pf;if(r>Number.MAX_SAFE_INTEGER){S1();let o=BigInt(r);a.valueBigInt=o;}else if(a.valueDec=parseInt(r,10),isNaN(a.valueDec))return;this.value.length||(a.isFirstSid=!0,i=!0),this.value.push(a);}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let r=this.value[n].toString();n!==0&&(e=`${e}.`),t?(r=`{${r}}`,this.value[n].isFirstSid?e=`2.{${r} - 80}`:e+=r):e+=r;}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};T1.NAME="ObjectIdentifierValueBlock";var cN,G=class extends Dt{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e);}constructor(e={}){super(e,T1),this.idBlock.tagClass=1,this.idBlock.tagNumber=6;}onAsciiEncoding(){return `${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return {...super.toJSON(),value:this.getValue()}}};cN=G;Z.ObjectIdentifier=cN;G.NAME="OBJECT IDENTIFIER";var gf=class extends zn(Kn){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e;}fromBER(e,t,n){if(n===0)return t;let r=re.toUint8Array(e);if(!Jn(this,r,t,n))return -1;let i=r.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let o=0;o<n&&(this.valueHexView[o]=i[o]&127,this.blockLength++,!!(i[o]&128));o++);let a=new Uint8Array(this.blockLength);for(let o=0;o<this.blockLength;o++)a[o]=this.valueHexView[o];return this.valueHexView=a,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Fn(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let r=this.valueHexView,i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength-1;a++)i[a]=r[a]|128;return i[this.blockLength-1]=r[this.blockLength-1],i.buffer}let t=Js(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",gn;let n=new Uint8Array(t.byteLength);if(!e){let r=new Uint8Array(t),i=t.byteLength-1;for(let a=0;a<i;a++)n[a]=r[a]|128;n[i]=r[i];}return n.buffer}toString(){let e="";return this.isHexOnly?e=he.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return {...super.toJSON(),valueDec:this.valueDec}}};gf.NAME="relativeSidBlock";var B1=class extends Gt{constructor({value:e=ls,...t}={}){super(t),this.value=[],e&&this.fromString(e);}fromBER(e,t,n){let r=t;for(;n>0;){let i=new gf;if(r=i.fromBER(e,r,n),r===-1)return this.blockLength=0,this.error=i.error,r;this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i);}return r}toBER(e,t){let n=[];for(let r=0;r<this.value.length;r++){let i=this.value[r].toBER(e);if(i.byteLength===0)return this.error=this.value[r].error,gn;n.push(i);}return zE(n)}fromString(e){this.value=[];let t=0,n=0,r="";do{n=e.indexOf(".",t),n===-1?r=e.substring(t):r=e.substring(t,n),t=n+1;let i=new gf;if(i.valueDec=parseInt(r,10),isNaN(i.valueDec))return !0;this.value.push(i);}while(n!==-1);return !0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let r=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(r=`{${r}}`),e+=r;}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};B1.NAME="RelativeObjectIdentifierValueBlock";var uN,O1=class extends Dt{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e);}constructor(e={}){super(e,B1),this.idBlock.tagClass=1,this.idBlock.tagNumber=13;}onAsciiEncoding(){return `${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return {...super.toJSON(),value:this.getValue()}}};uN=O1;Z.RelativeObjectIdentifier=uN;O1.NAME="RelativeObjectIdentifier";var lN,b=class extends A{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16;}};lN=b;Z.Sequence=lN;b.NAME="SEQUENCE";var hN,et=class extends A{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17;}};hN=et;Z.Set=hN;et.NAME="SET";var R1=class extends zn(Gt){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ls;}toJSON(){return {...super.toJSON(),value:this.value}}};R1.NAME="StringValueBlock";var V1=class extends R1{};V1.NAME="SimpleStringValueBlock";var ss=class extends E1{constructor({...e}={}){super(e,V1);}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,re.toUint8Array(e));}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);this.valueBlock.value=e;}};ss.NAME="SIMPLE STRING";var D1=class extends ss{fromBuffer(e){this.valueBlock.valueHexView=re.toUint8Array(e);try{this.valueBlock.value=he.ToUtf8String(e);}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=he.ToBinary(e);}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(he.FromUtf8String(e)),this.valueBlock.value=e;}};D1.NAME="Utf8StringValueBlock";var fN,hs=class extends D1{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12;}};fN=hs;Z.Utf8String=fN;hs.NAME="UTF8String";var U1=class extends ss{fromBuffer(e){this.valueBlock.value=he.ToUtf16String(e),this.valueBlock.valueHexView=re.toUint8Array(e);}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(he.FromUtf16String(e));}};U1.NAME="BmpStringValueBlock";var dN,Fr=class extends U1{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30;}};dN=Fr;Z.BmpString=dN;Fr.NAME="BMPString";var L1=class extends ss{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let r=0;r<n.length;r+=4)n[r]=n[r+3],n[r+1]=n[r+2],n[r+2]=0,n[r+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t));}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let r=0;r<t;r++){let i=Js(e.charCodeAt(r),8),a=new Uint8Array(i);if(a.length>4)continue;let o=4-a.length;for(let c=a.length-1;c>=0;c--)n[r*4+c+o]=a[c];}this.valueBlock.value=e;}};L1.NAME="UniversalStringValueBlock";var mN,Kr=class extends L1{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28;}};mN=Kr;Z.UniversalString=mN;Kr.NAME="UniversalString";var pN,Gn=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18;}};pN=Gn;Z.NumericString=pN;Gn.NAME="NumericString";var gN,fs=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19;}};gN=fs;Z.PrintableString=gN;fs.NAME="PrintableString";var yN,Gr=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20;}};yN=Gr;Z.TeletexString=yN;Gr.NAME="TeletexString";var wN,qc=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21;}};wN=qc;Z.VideotexString=wN;qc.NAME="VideotexString";var bN,Ta=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22;}};bN=Ta;Z.IA5String=bN;Ta.NAME="IA5String";var SN,Fc=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25;}};SN=Fc;Z.GraphicString=SN;Fc.NAME="GraphicString";var vN,Ba=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26;}};vN=Ba;Z.VisibleString=vN;Ba.NAME="VisibleString";var xN,Kc=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27;}};xN=Kc;Z.GeneralString=xN;Kc.NAME="GeneralString";var EN,Gc=class extends ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29;}};EN=Gc;Z.CharacterString=EN;Gc.NAME="CharacterString";var AN,Wn=class extends Ba{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let r=0;r<e.length;r++)this.valueBlock.valueHexView[r]=e.charCodeAt(r);}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23;}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,re.toUint8Array(e)));}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds();}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let r=parseInt(n[1],10);r>=50?this.year=1900+r:this.year=2e3+r,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10);}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=us(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=us(this.month,2),t[2]=us(this.day,2),t[3]=us(this.hour,2),t[4]=us(this.minute,2),t[5]=us(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return `${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return {...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};AN=Wn;Z.UTCTime=AN;Wn.NAME="UTCTime";var IN,Ge=class extends Wn{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24;}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds();}toDate(){let e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t=!1,n="",r="",i=0,a,o=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else {let h=new Number(e[e.length-1]);if(isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");n=e;}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else {let h=1,m=n.indexOf("+"),y="";if(m===-1&&(m=n.indexOf("-"),h=-1),m!==-1){if(y=n.substring(m+1),n=n.substring(0,m),y.length!==2&&y.length!==4)throw new Error("Wrong input string for conversion");let g=parseInt(y.substring(0,2),10);if(isNaN(g.valueOf()))throw new Error("Wrong input string for conversion");if(o=h*g,y.length===4){if(g=parseInt(y.substring(2,4),10),isNaN(g.valueOf()))throw new Error("Wrong input string for conversion");c=h*g;}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let h=new Number(`0${n.substring(u)}`);if(isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");i=h.valueOf(),r=n.substring(0,u);}else r=n;switch(!0){case r.length===8:if(a=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case r.length===10:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let h=60*i;this.minute=Math.floor(h),h=60*(h-this.minute),this.second=Math.floor(h),h=1e3*(h-this.second),this.millisecond=Math.floor(h);}break;case r.length===12:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let h=60*i;this.second=Math.floor(h),h=1e3*(h-this.second),this.millisecond=Math.floor(h);}break;case r.length===14:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let h=1e3*i;this.millisecond=Math.floor(h);}break;default:throw new Error("Wrong input string for conversion")}let l=a.exec(r);if(l===null)throw new Error("Wrong input string for conversion");for(let h=1;h<l.length;h++)switch(h){case 1:this.year=parseInt(l[h],10);break;case 2:this.month=parseInt(l[h],10);break;case 3:this.day=parseInt(l[h],10);break;case 4:this.hour=parseInt(l[h],10)+o;break;case 5:this.minute=parseInt(l[h],10)+c;break;case 6:this.second=parseInt(l[h],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let h=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=h.getUTCFullYear(),this.month=h.getUTCMonth(),this.day=h.getUTCDay(),this.hour=h.getUTCHours(),this.minute=h.getUTCMinutes(),this.second=h.getUTCSeconds(),this.millisecond=h.getUTCMilliseconds();}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(us(this.year,4)),t.push(us(this.month,2)),t.push(us(this.day,2)),t.push(us(this.hour,2)),t.push(us(this.minute,2)),t.push(us(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(us(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return {...super.toJSON(),millisecond:this.millisecond}}};IN=Ge;Z.GeneralizedTime=IN;Ge.NAME="GeneralizedTime";var CN,j1=class extends hs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31;}};CN=j1;Z.DATE=CN;j1.NAME="DATE";var NN,H1=class extends hs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32;}};NN=H1;Z.TimeOfDay=NN;H1.NAME="TimeOfDay";var kN,_1=class extends hs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33;}};kN=_1;Z.DateTime=kN;_1.NAME="DateTime";var PN,M1=class extends hs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34;}};PN=M1;Z.Duration=PN;M1.NAME="Duration";var TN,$1=class extends hs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14;}};TN=$1;Z.TIME=TN;$1.NAME="TIME";var ue=class{constructor({name:e=ls,optional:t=!1}={}){this.name=e,this.optional=t;}},We=class extends ue{constructor({value:e=[],...t}={}){super(t),this.value=e;}},fe=class extends ue{constructor({value:e=new ue,local:t=!1,...n}={}){super(n),this.value=e,this.local=t;}},Oa=class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=re.toUint8Array(e);}constructor({data:e=q1}={}){this.dataView=re.toUint8Array(e);}fromBER(e,t,n){let r=t+n;return this.dataView=re.toUint8Array(e).subarray(t,r),r}toBER(e){return this.dataView.slice().buffer}};function R(s,e,t){if(t instanceof We){for(let i of t.value)if(R(s,e,i).verified)return {verified:!0,result:s};{let i={verified:!1,result:{error:"Wrong values for Choice type"}};return t.hasOwnProperty(JE)&&(i.name=t.name),i}}if(t instanceof ue)return t.hasOwnProperty(JE)&&(s[t.name]=e),{verified:!0,result:s};if(!(s instanceof Object))return {verified:!1,result:{error:"Wrong root object"}};if(!(e instanceof Object))return {verified:!1,result:{error:"Wrong ASN.1 data"}};if(!(t instanceof Object))return {verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(e7 in t))return {verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(r7 in t.idBlock))return {verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(i7 in t.idBlock))return {verified:!1,result:{error:"Wrong ASN.1 schema"}};let n=t.idBlock.toBER(!1);if(n.byteLength===0)return {verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(t.idBlock.fromBER(n,0,n.byteLength)===-1)return {verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(t.idBlock.hasOwnProperty(t7)===!1)return {verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.tagClass!==e.idBlock.tagClass)return {verified:!1,result:s};if(t.idBlock.hasOwnProperty(s7)===!1)return {verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.tagNumber!==e.idBlock.tagNumber)return {verified:!1,result:s};if(t.idBlock.hasOwnProperty(n7)===!1)return {verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.isConstructed!==e.idBlock.isConstructed)return {verified:!1,result:s};if(!(XV in t.idBlock))return {verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.isHexOnly!==e.idBlock.isHexOnly)return {verified:!1,result:s};if(t.idBlock.isHexOnly){if(!(z8 in t.idBlock))return {verified:!1,result:{error:"Wrong ASN.1 schema"}};let i=t.idBlock.valueHexView,a=e.idBlock.valueHexView;if(i.length!==a.length)return {verified:!1,result:s};for(let o=0;o<i.length;o++)if(i[o]!==a[1])return {verified:!1,result:s}}if(t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ls),t.name&&(s[t.name]=e)),t instanceof Z.Constructed){let i=0,a={verified:!1,result:{error:"Unknown error"}},o=t.valueBlock.value.length;if(o>0&&t.valueBlock.value[0]instanceof fe&&(o=e.valueBlock.value.length),o===0)return {verified:!0,result:s};if(e.valueBlock.value.length===0&&t.valueBlock.value.length!==0){let c=!0;for(let u=0;u<t.valueBlock.value.length;u++)c=c&&(t.valueBlock.value[u].optional||!1);return c?{verified:!0,result:s}:(t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ls),t.name&&delete s[t.name]),s.error="Inconsistent object length",{verified:!1,result:s})}for(let c=0;c<o;c++)if(c-i>=e.valueBlock.value.length){if(t.valueBlock.value[c].optional===!1){let u={verified:!1,result:s};return s.error="Inconsistent length between ASN.1 data and schema",t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ls),t.name&&(delete s[t.name],u.name=t.name)),u}}else if(t.valueBlock.value[0]instanceof fe){if(a=R(s,e.valueBlock.value[c],t.valueBlock.value[0].value),a.verified===!1)if(t.valueBlock.value[0].optional)i++;else return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ls),t.name&&delete s[t.name]),a;if(JE in t.valueBlock.value[0]&&t.valueBlock.value[0].name.length>0){let u={};a7 in t.valueBlock.value[0]&&t.valueBlock.value[0].local?u=e:u=s,typeof u[t.valueBlock.value[0].name]>"u"&&(u[t.valueBlock.value[0].name]=[]),u[t.valueBlock.value[0].name].push(e.valueBlock.value[c]);}}else if(a=R(s,e.valueBlock.value[c-i],t.valueBlock.value[c]),a.verified===!1)if(t.valueBlock.value[c].optional)i++;else return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ls),t.name&&delete s[t.name]),a;if(a.verified===!1){let c={verified:!1,result:s};return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ls),t.name&&(delete s[t.name],c.name=t.name)),c}return {verified:!0,result:s}}if(t.primitiveSchema&&z8 in e.valueBlock){let i=yf(e.valueBlock.valueHexView);if(i.offset===-1){let a={verified:!1,result:i.result};return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ls),t.name&&(delete s[t.name],a.name=t.name)),a}return R(s,i.result,t.primitiveSchema)}return {verified:!0,result:s}}var Ut=class s{constructor(e={}){if("view"in e)this.fromUint8Array(e.view);else if("buffer"in e)this.fromArrayBuffer(e.buffer);else if("string"in e)this.fromString(e.string);else if("hexstring"in e)this.fromHexString(e.hexstring);else if("length"in e&&e.length>0){if(this.length=e.length,e.stub)for(let t=0;t<this._view.length;t++)this._view[t]=e.stub;}else this.length=0;}set buffer(e){this._buffer=e,this._view=new Uint8Array(this._buffer);}get buffer(){return this._buffer}set view(e){this._buffer=new ArrayBuffer(e.length),this._view=new Uint8Array(this._buffer),this._view.set(e);}get view(){return this._view}get length(){return this.view.byteLength}set length(e){this._buffer=new ArrayBuffer(e),this._view=new Uint8Array(this._buffer);}clear(){this._buffer=new ArrayBuffer(0),this._view=new Uint8Array(this._buffer);}fromArrayBuffer(e){this._buffer=e,this._view=new Uint8Array(this._buffer);}fromUint8Array(e){this.fromArrayBuffer(new Uint8Array(e).buffer);}fromString(e){let t=e.length;this.length=t;for(let n=0;n<t;n++)this.view[n]=e.charCodeAt(n);}toString(e=0,t=this.view.length-e){let n="";(e>=this.view.length||e<0)&&(e=0),(t>=this.view.length||t<0)&&(t=this.view.length-e);for(let r=e;r<e+t;r++)n+=String.fromCharCode(this.view[r]);return n}fromHexString(e){let t=e.length;this.buffer=new ArrayBuffer(t>>1),this.view=new Uint8Array(this.buffer);let n=new Map;n.set("0",0),n.set("1",1),n.set("2",2),n.set("3",3),n.set("4",4),n.set("5",5),n.set("6",6),n.set("7",7),n.set("8",8),n.set("9",9),n.set("A",10),n.set("a",10),n.set("B",11),n.set("b",11),n.set("C",12),n.set("c",12),n.set("D",13),n.set("d",13),n.set("E",14),n.set("e",14),n.set("F",15),n.set("f",15);let r=0,i=0;for(let a=0;a<t;a++)a%2?(i|=n.get(e.charAt(a)),this.view[r]=i,r++):i=n.get(e.charAt(a))<<4;}toHexString(e=0,t=this.view.length-e){let n="";(e>=this.view.length||e<0)&&(e=0),(t>=this.view.length||t<0)&&(t=this.view.length-e);for(let r=e;r<e+t;r++){let i=this.view[r].toString(16).toUpperCase();n=n+(i.length==1?"0":"")+i;}return n}copy(e=0,t=this.length-e){if(!e&&!this.length)return new s;if(e<0||e>this.length-1)throw new Error(`Wrong start position: ${e}`);return new s({buffer:this._buffer.slice(e,e+t)})}slice(e=0,t=this.length){if(!e&&!this.length)return new s;if(e<0||e>this.length-1)throw new Error(`Wrong start position: ${e}`);return new s({buffer:this._buffer.slice(e,t)})}realloc(e){let t=new ArrayBuffer(e),n=new Uint8Array(t);e>this._view.length?n.set(this._view):n.set(new Uint8Array(this._buffer,0,e)),this._buffer=t,this._view=new Uint8Array(this._buffer);}append(e){let t=this.length,n=e.length,r=e._view.subarray();this.realloc(t+n),this._view.set(r,t);}insert(e,t=0,n=this.length-t){return t>this.length-1?!1:(n>this.length-t&&(n=this.length-t),n>e.length&&(n=e.length),n==e.length?this._view.set(e._view,t):this._view.set(e._view.subarray(0,n),t),!0)}isEqual(e){if(this.length!=e.length)return !1;for(let t=0;t<e.length;t++)if(this.view[t]!=e.view[t])return !1;return !0}isEqualView(e){if(e.length!=this.view.length)return !1;for(let t=0;t<e.length;t++)if(this.view[t]!=e[t])return !1;return !0}findPattern(e,t,n,r){let{start:i,length:a,backward:o}=this.prepareFindParameters(t,n,r),c=e.length;if(c>a)return -1;let u=[];for(let l=0;l<c;l++)u.push(e.view[l]);for(let l=0;l<=a-c;l++){let h=!0,m=o?i-c-l:i+l;for(let y=0;y<c;y++)if(this.view[y+m]!=u[y]){h=!1;break}if(h)return o?i-c-l:i+c+l}return -1}findFirstIn(e,t,n,r){let{start:i,length:a,backward:o}=this.prepareFindParameters(t,n,r),c={id:-1,position:o?0:i+a,length:0};for(let u=0;u<e.length;u++){let l=this.findPattern(e[u],i,a,o);if(l!=-1){let h=!1,m=e[u].length;o?l-m>=c.position-c.length&&(h=!0):l-m<=c.position-c.length&&(h=!0),h&&(c.position=l,c.id=u,c.length=m);}}return c}findAllIn(e,t,n){let{start:r,length:i}=this.prepareFindParameters(t,n),a=[],o={id:-1,position:r};do{let c=o.position;if(o=this.findFirstIn(e,o.position,i),o.id==-1)break;i-=o.position-c,a.push({id:o.id,position:o.position});}while(!0);return a}findAllPatternIn(e,t,n){let{start:r,length:i}=this.prepareFindParameters(t,n),a=[],o=e.length;if(o>i)return -1;let c=Array.from(e.view);for(let u=0;u<=i-o;u++){let l=!0,h=r+u;for(let m=0;m<o;m++)if(this.view[m+h]!=c[m]){l=!1;break}l&&(a.push(r+o+u),u+=o-1);}return a}findFirstNotIn(e,t,n,r){let{start:i,length:a,backward:o}=this.prepareFindParameters(t,n,r),c={left:{id:-1,position:i},right:{id:-1,position:0},value:new s},u=a;for(;u>0;){if(c.right=this.findFirstIn(e,o?i-a+u:i+a-u,u,o),c.right.id==-1){a=u,o?i-=a:i=c.left.position,c.value=new s({buffer:this._buffer.slice(i,i+a)});break}if(c.right.position!=(o?c.left.position-e[c.right.id].length:c.left.position+e[c.right.id].length)){o?(i=c.right.position+e[c.right.id].length,a=c.left.position-c.right.position-e[c.right.id].length):(i=c.left.position,a=c.right.position-c.left.position-e[c.right.id].length),c.value=new s({buffer:this._buffer.slice(i,i+a)});break}c.left=c.right,u-=e[c.right.id].length;}if(o){let l=c.right;c.right=c.left,c.left=l;}return c}findAllNotIn(e,t,n){let{start:r,length:i}=this.prepareFindParameters(t,n),a=[],o={left:{id:-1,position:r},right:{id:-1,position:r},value:new s};do{let c=o.right.position;o=this.findFirstNotIn(e,o.right.position,i),i-=o.right.position-c,a.push({left:{id:o.left.id,position:o.left.position},right:{id:o.right.id,position:o.right.position},value:o.value});}while(o.right.id!=-1);return a}findFirstSequence(e,t,n,r){let{start:i,length:a,backward:o}=this.prepareFindParameters(t,n,r),c=this.skipNotPatterns(e,i,a,o);if(c==-1)return {position:-1,value:new s};let u=this.skipPatterns(e,c,a-(o?i-c:c-i),o);o?(i=u,a=c-u):(i=c,a=u-c);let l=new s({buffer:this._buffer.slice(i,i+a)});return {position:u,value:l}}findAllSequences(e,t,n){let{start:r,length:i}=this.prepareFindParameters(t,n),a=[],o={position:r,value:new s};do{let c=o.position;o=this.findFirstSequence(e,o.position,i),o.position!=-1&&(i-=o.position-c,a.push({position:o.position,value:o.value}));}while(o.position!=-1);return a}findPairedPatterns(e,t,n,r){let i=[];if(e.isEqual(t))return i;let{start:a,length:o}=this.prepareFindParameters(n,r),c=0,u=this.findAllPatternIn(e,a,o);if(!Array.isArray(u)||u.length==0)return i;let l=this.findAllPatternIn(t,a,o);if(!Array.isArray(l)||l.length==0)return i;for(;c<u.length&&l.length!=0;){if(u[0]==l[0]){i.push({left:u[0],right:l[0]}),u.splice(0,1),l.splice(0,1);continue}if(u[c]>l[0])break;for(;u[c]<l[0]&&(c++,!(c>=u.length)););i.push({left:u[c-1],right:l[0]}),u.splice(c-1,1),l.splice(0,1),c=0;}return i.sort((h,m)=>h.left-m.left),i}findPairedArrays(e,t,n,r){let{start:i,length:a}=this.prepareFindParameters(n,r),o=[],c=0,u=this.findAllIn(e,i,a);if(u.length==0)return o;let l=this.findAllIn(t,i,a);if(l.length==0)return o;for(;c<u.length&&l.length!=0;){if(u[0].position==l[0].position){o.push({left:u[0],right:l[0]}),u.splice(0,1),l.splice(0,1);continue}if(u[c].position>l[0].position)break;for(;u[c].position<l[0].position&&(c++,!(c>=u.length)););o.push({left:u[c-1],right:l[0]}),u.splice(c-1,1),l.splice(0,1),c=0;}return o.sort((h,m)=>h.left.position-m.left.position),o}replacePattern(e,t,n,r,i=null){let a=[],o,c={status:-1,searchPatternPositions:[],replacePatternPositions:[]},{start:u,length:l}=this.prepareFindParameters(n,r);if(i==null){if(a=this.findAllIn([e],u,l),a.length==0)return c}else a=i;c.searchPatternPositions.push(...Array.from(a,g=>g.position));let h=e.length-t.length,m=new ArrayBuffer(this.view.length-a.length*h),y=new Uint8Array(m);for(y.set(new Uint8Array(this.buffer,0,u)),o=0;o<a.length;o++){let g=o==0?u:a[o-1].position;y.set(new Uint8Array(this.buffer,g,a[o].position-e.length-g),g-o*h),y.set(t.view,a[o].position-e.length-o*h),c.replacePatternPositions.push(a[o].position-e.length-o*h);}return o--,y.set(new Uint8Array(this.buffer,a[o].position,this.length-a[o].position),a[o].position-e.length+t.length-o*h),this.buffer=m,this.view=new Uint8Array(this.buffer),c.status=1,c}skipPatterns(e,t,n,r){let{start:i,length:a,backward:o}=this.prepareFindParameters(t,n,r),c=i;for(let u=0;u<e.length;u++){let l=e[u].length,h=o?c-l:c,m=!0;for(let y=0;y<l;y++)if(this.view[y+h]!=e[u].view[y]){m=!1;break}if(m){if(u=-1,o){if(c-=l,c<=0)return c}else if(c+=l,c>=i+a)return c}}return c}skipNotPatterns(e,t,n,r){let{start:i,length:a,backward:o}=this.prepareFindParameters(t,n,r),c=-1;for(let u=0;u<a;u++){for(let l=0;l<e.length;l++){let h=e[l].length,m=o?i-u-h:i+u,y=!0;for(let g=0;g<h;g++)if(this.view[g+m]!=e[l].view[g]){y=!1;break}if(y){c=o?i-u:i+u;break}}if(c!=-1)break}return c}prepareFindParameters(e=null,t=null,n=!1){return e===null&&(e=n?this.length:0),e>this.length&&(e=this.length),n?(t===null&&(t=e),t>e&&(t=e)):(t===null&&(t=this.length-e),t>this.length-e&&(t=this.length-e)),{start:e,length:t,backward:n}}};var f7=16777216,Yn=class s{constructor(e={}){this._stream=new Ut,this._length=0,this._start=0,this.backward=!1,this.appendBlock=0,this.prevLength=0,this.prevStart=0,"view"in e?this.stream=new Ut({view:e.view}):"buffer"in e?this.stream=new Ut({buffer:e.buffer}):"string"in e?this.stream=new Ut({string:e.string}):"hexstring"in e?this.stream=new Ut({hexstring:e.hexstring}):"stream"in e?this.stream=e.stream.slice():this.stream=new Ut,"backward"in e&&e.backward&&(this.backward=e.backward,this._start=this.stream.length),"length"in e&&e.length>0&&(this._length=e.length),"start"in e&&e.start&&e.start>0&&(this._start=e.start),"appendBlock"in e&&e.appendBlock&&e.appendBlock>0&&(this.appendBlock=e.appendBlock);}set stream(e){this._stream=e,this.prevLength=this._length,this._length=e.length,this.prevStart=this._start,this._start=0;}get stream(){return this._stream}set length(e){this.prevLength=this._length,this._length=e;}get length(){return this.appendBlock?this.start:this._length}set start(e){e>this.stream.length||(this.prevStart=this._start,this.prevLength=this._length,this._length-=this.backward?this._start-e:e-this._start,this._start=e);}get start(){return this._start}get buffer(){return this._stream.buffer.slice(0,this._length)}resetPosition(){this._start=this.prevStart,this._length=this.prevLength;}findPattern(e,t=null){(t==null||t>this.length)&&(t=this.length);let n=this.stream.findPattern(e,this.start,this.length,this.backward);if(n==-1)return n;if(this.backward){if(n<this.start-e.length-t)return -1}else if(n>this.start+e.length+t)return -1;return this.start=n,n}findFirstIn(e,t=null){(t==null||t>this.length)&&(t=this.length);let n=this.stream.findFirstIn(e,this.start,this.length,this.backward);if(n.id==-1)return n;if(this.backward){if(n.position<this.start-e[n.id].length-t)return {id:-1,position:this.backward?0:this.start+this.length}}else if(n.position>this.start+e[n.id].length+t)return {id:-1,position:this.backward?0:this.start+this.length};return this.start=n.position,n}findAllIn(e){let t=this.backward?this.start-this.length:this.start;return this.stream.findAllIn(e,t,this.length)}findFirstNotIn(e,t=null){(t==null||t>this._length)&&(t=this._length);let n=this._stream.findFirstNotIn(e,this._start,this._length,this.backward);if(n.left.id==-1&&n.right.id==-1)return n;if(this.backward){if(n.right.id!=-1&&n.right.position<this._start-e[n.right.id].length-t)return {left:{id:-1,position:this._start},right:{id:-1,position:0},value:new Ut}}else if(n.left.id!=-1&&n.left.position>this._start+e[n.left.id].length+t)return {left:{id:-1,position:this._start},right:{id:-1,position:0},value:new Ut};return this.backward?n.left.id==-1?this.start=0:this.start=n.left.position:n.right.id==-1?this.start=this._start+this._length:this.start=n.right.position,n}findAllNotIn(e){let t=this.backward?this._start-this._length:this._start;return this._stream.findAllNotIn(e,t,this._length)}findFirstSequence(e,t=null,n=null){(t==null||t>this._length)&&(t=this._length),(n==null||n>t)&&(n=t);let r=this._stream.findFirstSequence(e,this._start,t,this.backward);if(r.value.length==0)return r;if(this.backward){if(r.position<this._start-r.value.length-n)return {position:-1,value:new Ut}}else if(r.position>this._start+r.value.length+n)return {position:-1,value:new Ut};return this.start=r.position,r}findAllSequences(e){let t=this.backward?this.start-this.length:this.start;return this.stream.findAllSequences(e,t,this.length)}findPairedPatterns(e,t,n=null){(n==null||n>this.length)&&(n=this.length);let r=this.backward?this.start-this.length:this.start,i=this.stream.findPairedPatterns(e,t,r,this.length);if(i.length){if(this.backward){if(i[0].right<this.start-t.length-n)return []}else if(i[0].left>this.start+e.length+n)return []}return i}findPairedArrays(e,t,n=null){(n==null||n>this.length)&&(n=this.length);let r=this.backward?this.start-this.length:this.start,i=this.stream.findPairedArrays(e,t,r,this.length);if(i.length){if(this.backward){if(i[0].right.position<this.start-t[i[0].right.id].length-n)return []}else if(i[0].left.position>this.start+e[i[0].left.id].length+n)return []}return i}replacePattern(e,t){let n=this.backward?this.start-this.length:this.start;return this.stream.replacePattern(e,t,n,this.length)}skipPatterns(e){let t=this.stream.skipPatterns(e,this.start,this.length,this.backward);return this.start=t,t}skipNotPatterns(e){let t=this.stream.skipNotPatterns(e,this.start,this.length,this.backward);return t==-1?-1:(this.start=t,t)}append(e){this.beforeAppend(e.length),this._stream.view.set(e.view,this._start),this._length+=e.length*2,this.start=this._start+e.length,this.prevLength-=e.length*2;}appendView(e){this.beforeAppend(e.length),this._stream.view.set(e,this._start),this._length+=e.length*2,this.start=this._start+e.length,this.prevLength-=e.length*2;}appendChar(e){this.beforeAppend(1),this._stream.view[this._start]=e,this._length+=2,this.start=this._start+1,this.prevLength-=2;}appendUint16(e){this.beforeAppend(2);let t=new Uint16Array([e]),n=new Uint8Array(t.buffer);this.stream.view[this._start]=n[1],this._stream.view[this._start+1]=n[0],this._length+=4,this.start=this._start+2,this.prevLength-=4;}appendUint24(e){this.beforeAppend(3);let t=new Uint32Array([e]),n=new Uint8Array(t.buffer);this._stream.view[this._start]=n[2],this._stream.view[this._start+1]=n[1],this._stream.view[this._start+2]=n[0],this._length+=6,this.start=this._start+3,this.prevLength-=6;}appendUint32(e){this.beforeAppend(4);let t=new Uint32Array([e]),n=new Uint8Array(t.buffer);this._stream.view[this._start]=n[3],this._stream.view[this._start+1]=n[2],this._stream.view[this._start+2]=n[1],this._stream.view[this._start+3]=n[0],this._length+=8,this.start=this._start+4,this.prevLength-=8;}appendInt16(e){this.beforeAppend(2);let t=new Int16Array([e]),n=new Uint8Array(t.buffer);this._stream.view[this._start]=n[1],this._stream.view[this._start+1]=n[0],this._length+=4,this.start=this._start+2,this.prevLength-=4;}appendInt32(e){this.beforeAppend(4);let t=new Int32Array([e]),n=new Uint8Array(t.buffer);this._stream.view[this._start]=n[3],this._stream.view[this._start+1]=n[2],this._stream.view[this._start+2]=n[1],this._stream.view[this._start+3]=n[0],this._length+=8,this.start=this._start+4,this.prevLength-=8;}getBlock(e,t=!0){if(this._length<=0)return new Uint8Array(0);this._length<e&&(e=this._length);let n;if(this.backward){let r=this._stream.view.subarray(this._length-e,this._length);n=new Uint8Array(e);for(let i=0;i<e;i++)n[e-1-i]=r[i];}else n=this._stream.view.subarray(this._start,this._start+e);return t&&(this.start+=this.backward?-1*e:e),n}getUint16(e=!0){let t=this.getBlock(2,e);return t.length<2?0:t[0]<<8|t[1]}getInt16(e=!0){let t=this.getUint16(e),n=32768;return t&n?-(n-(t^n)):t}getUint24(e=!0){let t=this.getBlock(4,e);return t.length<3?0:t[0]<<16|t[1]<<8|t[2]}getUint32(e=!0){let t=this.getBlock(4,e);return t.length<4?0:t[0]*f7+(t[1]<<16)+(t[2]<<8)+t[3]}getInt32(e=!0){let t=this.getUint32(e),n=2147483648;return t&n?-(n-(t^n)):t}beforeAppend(e){this._start+e>this._stream.length&&(e>this.appendBlock&&(this.appendBlock=e+s.APPEND_BLOCK),this._stream.realloc(this._stream.length+this.appendBlock));}};Yn.APPEND_BLOCK=1e3;function m7(s){return s instanceof Uint8Array||s!=null&&typeof s=="object"&&s.constructor.name==="Uint8Array"}function ZE(s,...e){if(!m7(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${s.length}`)}function QE(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function BN(s,e){ZE(s);let t=e.outputLen;if(s.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var K1=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),zs=(s,e)=>s<<32-e|s>>>e,G1=(s,e)=>s<<e|s>>>32-e>>>0;new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function p7(s){if(typeof s!="string")throw new Error(`utf8ToBytes expected string, got ${typeof s}`);return new Uint8Array(new TextEncoder().encode(s))}function XE(s){return typeof s=="string"&&(s=p7(s)),ZE(s),s}var F1=class{clone(){return this._cloneInto()}};function Ra(s){let e=n=>s().update(XE(n)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function g7(s,e,t,n){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,n);let r=BigInt(32),i=BigInt(4294967295),a=Number(t>>r&i),o=Number(t&i),c=n?4:0,u=n?0:4;s.setUint32(e+c,a,n),s.setUint32(e+u,o,n);}var W1=(s,e,t)=>s&e^~s&t,J1=(s,e,t)=>s&e^s&t^e&t,Wr=class extends F1{constructor(e,t,n,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=K1(this.buffer);}update(e){QE(this);let{view:t,buffer:n,blockLen:r}=this;e=XE(e);let i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let c=K1(e);for(;r<=i-a;a+=r)this.process(c,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){QE(this),BN(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>r-a&&(this.process(n,0),a=0);for(let h=a;h<r;h++)t[h]=0;g7(n,r-8,BigInt(this.length*8),i),this.process(n,0);let o=K1(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)o.setUint32(4*h,l[h],i);}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.length=r,e.pos=o,e.finished=i,e.destroyed=a,r%t&&e.buffer.set(n),e}};var wf=new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),Jr=new Uint32Array(80),e2=class extends Wr{constructor(){super(64,20,8,!1),this.A=wf[0]|0,this.B=wf[1]|0,this.C=wf[2]|0,this.D=wf[3]|0,this.E=wf[4]|0;}get(){let{A:e,B:t,C:n,D:r,E:i}=this;return [e,t,n,r,i]}set(e,t,n,r,i){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0;}process(e,t){for(let c=0;c<16;c++,t+=4)Jr[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)Jr[c]=G1(Jr[c-3]^Jr[c-8]^Jr[c-14]^Jr[c-16],1);let{A:n,B:r,C:i,D:a,E:o}=this;for(let c=0;c<80;c++){let u,l;c<20?(u=W1(r,i,a),l=1518500249):c<40?(u=r^i^a,l=1859775393):c<60?(u=J1(r,i,a),l=2400959708):(u=r^i^a,l=3395469782);let h=G1(n,5)+u+o+l+Jr[c]|0;o=a,a=i,i=G1(r,30),r=n,n=h;}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,this.set(n,r,i,a,o);}roundClean(){Jr.fill(0);}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0);}},ON=Ra(()=>new e2);var y7=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),zr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Yr=new Uint32Array(64),t2=class extends Wr{constructor(){super(64,32,8,!1),this.A=zr[0]|0,this.B=zr[1]|0,this.C=zr[2]|0,this.D=zr[3]|0,this.E=zr[4]|0,this.F=zr[5]|0,this.G=zr[6]|0,this.H=zr[7]|0;}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:c}=this;return [e,t,n,r,i,a,o,c]}set(e,t,n,r,i,a,o,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=c|0;}process(e,t){for(let h=0;h<16;h++,t+=4)Yr[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let m=Yr[h-15],y=Yr[h-2],g=zs(m,7)^zs(m,18)^m>>>3,w=zs(y,17)^zs(y,19)^y>>>10;Yr[h]=w+Yr[h-7]+g+Yr[h-16]|0;}let{A:n,B:r,C:i,D:a,E:o,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){let m=zs(o,6)^zs(o,11)^zs(o,25),y=l+m+W1(o,c,u)+y7[h]+Yr[h]|0,w=(zs(n,2)^zs(n,13)^zs(n,22))+J1(n,r,i)|0;l=u,u=c,c=o,o=a+y|0,a=i,i=r,r=n,n=y+w|0;}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,c,u,l);}roundClean(){Yr.fill(0);}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0);}};var s2=Ra(()=>new t2);var z1=BigInt(4294967295),n2=BigInt(32);function RN(s,e=!1){return e?{h:Number(s&z1),l:Number(s>>n2&z1)}:{h:Number(s>>n2&z1)|0,l:Number(s&z1)|0}}function w7(s,e=!1){let t=new Uint32Array(s.length),n=new Uint32Array(s.length);for(let r=0;r<s.length;r++){let{h:i,l:a}=RN(s[r],e);[t[r],n[r]]=[i,a];}return [t,n]}var b7=(s,e)=>BigInt(s>>>0)<<n2|BigInt(e>>>0),S7=(s,e,t)=>s>>>t,v7=(s,e,t)=>s<<32-t|e>>>t,x7=(s,e,t)=>s>>>t|e<<32-t,E7=(s,e,t)=>s<<32-t|e>>>t,A7=(s,e,t)=>s<<64-t|e>>>t-32,I7=(s,e,t)=>s>>>t-32|e<<64-t,C7=(s,e)=>e,N7=(s,e)=>s,k7=(s,e,t)=>s<<t|e>>>32-t,P7=(s,e,t)=>e<<t|s>>>32-t,T7=(s,e,t)=>e<<t-32|s>>>64-t,B7=(s,e,t)=>s<<t-32|e>>>64-t;function O7(s,e,t,n){let r=(e>>>0)+(n>>>0);return {h:s+t+(r/2**32|0)|0,l:r|0}}var R7=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),V7=(s,e,t,n)=>e+t+n+(s/2**32|0)|0,D7=(s,e,t,n)=>(s>>>0)+(e>>>0)+(t>>>0)+(n>>>0),U7=(s,e,t,n,r)=>e+t+n+r+(s/2**32|0)|0,L7=(s,e,t,n,r)=>(s>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),j7=(s,e,t,n,r,i)=>e+t+n+r+i+(s/2**32|0)|0;var H7={fromBig:RN,split:w7,toBig:b7,shrSH:S7,shrSL:v7,rotrSH:x7,rotrSL:E7,rotrBH:A7,rotrBL:I7,rotr32H:C7,rotr32L:N7,rotlSH:k7,rotlSL:P7,rotlBH:T7,rotlBL:B7,add:O7,add3L:R7,add3H:V7,add4L:D7,add4H:U7,add5H:j7,add5L:L7},Ce=H7;var[_7,M7]=Ce.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(s=>BigInt(s))),Zr=new Uint32Array(80),Qr=new Uint32Array(80),Y1=class extends Wr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209;}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:a,Dh:o,Dl:c,Eh:u,El:l,Fh:h,Fl:m,Gh:y,Gl:g,Hh:w,Hl:S}=this;return [e,t,n,r,i,a,o,c,u,l,h,m,y,g,w,S]}set(e,t,n,r,i,a,o,c,u,l,h,m,y,g,w,S){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=a|0,this.Dh=o|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=m|0,this.Gh=y|0,this.Gl=g|0,this.Hh=w|0,this.Hl=S|0;}process(e,t){for(let x=0;x<16;x++,t+=4)Zr[x]=e.getUint32(t),Qr[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let v=Zr[x-15]|0,I=Qr[x-15]|0,D=Ce.rotrSH(v,I,1)^Ce.rotrSH(v,I,8)^Ce.shrSH(v,I,7),F=Ce.rotrSL(v,I,1)^Ce.rotrSL(v,I,8)^Ce.shrSL(v,I,7),M=Zr[x-2]|0,W=Qr[x-2]|0,ne=Ce.rotrSH(M,W,19)^Ce.rotrBH(M,W,61)^Ce.shrSH(M,W,6),q=Ce.rotrSL(M,W,19)^Ce.rotrBL(M,W,61)^Ce.shrSL(M,W,6),J=Ce.add4L(F,q,Qr[x-7],Qr[x-16]),ae=Ce.add4H(J,D,ne,Zr[x-7],Zr[x-16]);Zr[x]=ae|0,Qr[x]=J|0;}let{Ah:n,Al:r,Bh:i,Bl:a,Ch:o,Cl:c,Dh:u,Dl:l,Eh:h,El:m,Fh:y,Fl:g,Gh:w,Gl:S,Hh:C,Hl:k}=this;for(let x=0;x<80;x++){let v=Ce.rotrSH(h,m,14)^Ce.rotrSH(h,m,18)^Ce.rotrBH(h,m,41),I=Ce.rotrSL(h,m,14)^Ce.rotrSL(h,m,18)^Ce.rotrBL(h,m,41),D=h&y^~h&w,F=m&g^~m&S,M=Ce.add5L(k,I,F,M7[x],Qr[x]),W=Ce.add5H(M,C,v,D,_7[x],Zr[x]),ne=M|0,q=Ce.rotrSH(n,r,28)^Ce.rotrBH(n,r,34)^Ce.rotrBH(n,r,39),J=Ce.rotrSL(n,r,28)^Ce.rotrBL(n,r,34)^Ce.rotrBL(n,r,39),ae=n&i^n&o^i&o,Be=r&a^r&c^a&c;C=w|0,k=S|0,w=y|0,S=g|0,y=h|0,g=m|0,{h,l:m}=Ce.add(u|0,l|0,W|0,ne|0),u=o|0,l=c|0,o=i|0,c=a|0,i=n|0,a=r|0;let L=Ce.add3L(ne,J,Be);n=Ce.add3H(L,W,q,ae),r=L|0;}(({h:n,l:r}=Ce.add(this.Ah|0,this.Al|0,n|0,r|0))),{h:i,l:a}=Ce.add(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:c}=Ce.add(this.Ch|0,this.Cl|0,o|0,c|0),{h:u,l}=Ce.add(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:m}=Ce.add(this.Eh|0,this.El|0,h|0,m|0),{h:y,l:g}=Ce.add(this.Fh|0,this.Fl|0,y|0,g|0),{h:w,l:S}=Ce.add(this.Gh|0,this.Gl|0,w|0,S|0),{h:C,l:k}=Ce.add(this.Hh|0,this.Hl|0,C|0,k|0),this.set(n,r,i,a,o,c,u,l,h,m,y,g,w,S,C,k);}roundClean(){Zr.fill(0),Qr.fill(0);}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}};var r2=class extends Y1{constructor(){super(),this.Ah=-876896931,this.Al=-1056596264,this.Bh=1654270250,this.Bl=914150663,this.Ch=-1856437926,this.Cl=812702999,this.Dh=355462360,this.Dl=-150054599,this.Eh=1731405415,this.El=-4191439,this.Fh=-1900787065,this.Fl=1750603025,this.Gh=-619958771,this.Gl=1694076839,this.Hh=1203062813,this.Hl=-1090891868,this.outputLen=48;}},i2=Ra(()=>new Y1);var a2=Ra(()=>new r2);var ut=new ArrayBuffer(0),p="",$e=class s extends TypeError{constructor(){super(...arguments),this.name=s.NAME;}static isType(e,t){if(typeof t=="string"){if(t==="Array"&&Array.isArray(e))return !0;if(t==="ArrayBuffer"&&e instanceof ArrayBuffer)return !0;if(t==="ArrayBufferView"&&ArrayBuffer.isView(e))return !0;if(typeof e===t)return !0}else if(e instanceof t)return !0;return !1}static assert(e,t,...n){for(let i of n)if(this.isType(e,i))return;let r=n.map(i=>i instanceof Function&&"name"in i?i.name:`${i}`);throw new s(`Parameter '${t}' is not of type ${r.length>1?`(${r.join(" or ")})`:r[0]}`)}};$e.NAME="ArgumentError";var Re=class s extends TypeError{static assert(...e){let t=null,n,r;typeof e[0]=="string"?(t=e[0],n=e[1],r=e.slice(2)):(n=e[0],r=e.slice(1)),$e.assert(n,"parameters","object");for(let i of r){let a=n[i];if(a==null)throw new s(i,t)}}static assertEmpty(e,t,n){if(e==null)throw new s(t,n)}constructor(e,t=null,n){super(),this.name=s.NAME,this.field=e,t&&(this.target=t),n?this.message=n:this.message=`Absent mandatory parameter '${e}' ${t?` in '${t}'`:p}`;}};Re.NAME="ParameterError";var T=class s extends Error{static assertSchema(e,t){if(!e.verified)throw new Error(`Object's schema was not verified against input data for ${t}`)}static assert(e,t){if(e.offset===-1)throw new s(`Error during parsing of ASN.1 data. Data is not correct for '${t}'.`)}constructor(e){super(e),this.name="AsnError";}},O=class{static blockName(){return this.CLASS_NAME}static fromBER(e){let t=ht(e);T.assert(t,this.name);try{return new this({schema:t.result})}catch{throw new T(`Cannot create '${this.CLASS_NAME}' from ASN.1 object`)}}static defaultValues(e){throw new Error(`Invalid member name for ${this.CLASS_NAME} class: ${e}`)}static schema(e={}){throw new Error(`Method '${this.CLASS_NAME}.schema' should be overridden`)}get className(){return this.constructor.CLASS_NAME}toString(e="hex"){let t;try{t=this.toSchema();}catch{t=this.toSchema(!0);}return he.ToString(t.toBER(),e)}};O.CLASS_NAME="PkiObject";function ji(s){let e=!1,t=p,n=s.trim();for(let r=0;r<n.length;r++)n.charCodeAt(r)===32?e===!1&&(e=!0):(e&&(t+=" ",e=!1),t+=n[r]);return t.toLowerCase()}var bf="type",o2="value",km=class s extends O{constructor(e={}){super(),this.type=d(e,bf,s.defaultValues(bf)),this.value=d(e,o2,s.defaultValues(o2)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case bf:return p;case o2:return {};default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.type||p}),new ue({name:t.value||p})]})}fromSchema(e){V(e,[bf,"typeValue"]);let t=R(e,e,s.schema({names:{type:bf,value:"typeValue"}}));T.assertSchema(t,this.className),this.type=t.result.type.valueBlock.toString(),this.value=t.result.typeValue;}toSchema(){return new b({value:[new G({value:this.type}),this.value]})}toJSON(){let e={type:this.type};return Object.keys(this.value).length!==0?e.value=this.value.toJSON():e.value=this.value,e}isEqual(e){let t=[hs.blockName(),Fr.blockName(),Kr.blockName(),Gn.blockName(),fs.blockName(),Gr.blockName(),qc.blockName(),Ta.blockName(),Fc.blockName(),Ba.blockName(),Kc.blockName(),Gc.blockName()];if(e instanceof ArrayBuffer)return re.isEqual(this.value.valueBeforeDecodeView,e);if(e.constructor.blockName()===s.blockName()){if(this.type!==e.type)return !1;let n=[!1,!1],r=this.value.constructor.blockName();for(let a of t)r===a&&(n[0]=!0),e.value.constructor.blockName()===a&&(n[1]=!0);if(n[0]!==n[1])return !1;if(n[0]&&n[1]){let a=ji(this.value.valueBlock.value),o=ji(e.value.valueBlock.value);if(a.localeCompare(o)!==0)return !1}else if(!re.isEqual(this.value.valueBeforeDecodeView,e.value.valueBeforeDecodeView))return !1;return !0}return !1}};km.CLASS_NAME="AttributeTypeAndValue";var Va="typesAndValues",Z1="valueBeforeDecode",VN="RDN",Je=class s extends O{constructor(e={}){super(),this.typesAndValues=d(e,Va,s.defaultValues(Va)),this.valueBeforeDecode=d(e,Z1,s.defaultValues(Z1)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Va:return [];case Z1:return ut;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Va:return t.length===0;case Z1:return t.byteLength===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.repeatedSequence||p,value:new et({value:[new fe({name:t.repeatedSet||p,value:km.schema(t.typeAndValue||{})})]})})]})}fromSchema(e){V(e,[VN,Va]);let t=R(e,e,s.schema({names:{blockName:VN,repeatedSet:Va}}));T.assertSchema(t,this.className),Va in t.result&&(this.typesAndValues=Array.from(t.result.typesAndValues,n=>new km({schema:n}))),this.valueBeforeDecode=t.result.RDN.valueBeforeDecodeView.slice().buffer;}toSchema(){if(this.valueBeforeDecode.byteLength===0)return new b({value:[new et({value:Array.from(this.typesAndValues,t=>t.toSchema())})]});let e=ht(this.valueBeforeDecode);if(T.assert(e,"RelativeDistinguishedNames"),!(e.result instanceof b))throw new Error("ASN.1 result should be SEQUENCE");return e.result}toJSON(){return {typesAndValues:Array.from(this.typesAndValues,e=>e.toJSON())}}isEqual(e){if(e instanceof s){if(this.typesAndValues.length!==e.typesAndValues.length)return !1;for(let[t,n]of this.typesAndValues.entries())if(n.isEqual(e.typesAndValues[t])===!1)return !1;return !0}return e instanceof ArrayBuffer?qr(this.valueBeforeDecode,e):!1}};Je.CLASS_NAME="RelativeDistinguishedNames";var Of="type",Rf="value";function $7(s={},e=!1){let t=d(s,"names",{});return new b({optional:e,value:[new A({optional:!0,idBlock:{tagClass:2,tagNumber:1},name:t.country_name||p,value:[new We({value:[new Gn,new fs]})]}),new A({optional:!0,idBlock:{tagClass:2,tagNumber:2},name:t.administration_domain_name||p,value:[new We({value:[new Gn,new fs]})]}),new ie({optional:!0,idBlock:{tagClass:3,tagNumber:0},name:t.network_address||p,isHexOnly:!0}),new ie({optional:!0,idBlock:{tagClass:3,tagNumber:1},name:t.terminal_identifier||p,isHexOnly:!0}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:2},name:t.private_domain_name||p,value:[new We({value:[new Gn,new fs]})]}),new ie({optional:!0,idBlock:{tagClass:3,tagNumber:3},name:t.organization_name||p,isHexOnly:!0}),new ie({optional:!0,name:t.numeric_user_identifier||p,idBlock:{tagClass:3,tagNumber:4},isHexOnly:!0}),new A({optional:!0,name:t.personal_name||p,idBlock:{tagClass:3,tagNumber:5},value:[new ie({idBlock:{tagClass:3,tagNumber:0},isHexOnly:!0}),new ie({optional:!0,idBlock:{tagClass:3,tagNumber:1},isHexOnly:!0}),new ie({optional:!0,idBlock:{tagClass:3,tagNumber:2},isHexOnly:!0}),new ie({optional:!0,idBlock:{tagClass:3,tagNumber:3},isHexOnly:!0})]}),new A({optional:!0,name:t.organizational_unit_names||p,idBlock:{tagClass:3,tagNumber:6},value:[new fe({value:new fs})]})]})}function q7(s=!1){return new b({optional:s,value:[new fs,new fs]})}function F7(s=!1){return new et({optional:s,value:[new ie({optional:!0,idBlock:{tagClass:3,tagNumber:0},isHexOnly:!0}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new ue]})]})}var qe=class s extends O{constructor(e={}){super(),this.type=d(e,Of,s.defaultValues(Of)),this.value=d(e,Rf,s.defaultValues(Rf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Of:return 9;case Rf:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Of:return t===s.defaultValues(e);case Rf:return Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new We({value:[new A({idBlock:{tagClass:3,tagNumber:0},name:t.blockName||p,value:[new G,new A({idBlock:{tagClass:3,tagNumber:0},value:[new ue]})]}),new ie({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:1}}),new ie({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:2}}),new A({idBlock:{tagClass:3,tagNumber:3},name:t.blockName||p,value:[$7(t.builtInStandardAttributes||{},!1),q7(!0),F7(!0)]}),new A({idBlock:{tagClass:3,tagNumber:4},name:t.blockName||p,value:[Je.schema(t.directoryName||{})]}),new A({idBlock:{tagClass:3,tagNumber:5},name:t.blockName||p,value:[new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new We({value:[new Gr,new fs,new Kr,new hs,new Fr]})]}),new A({idBlock:{tagClass:3,tagNumber:1},value:[new We({value:[new Gr,new fs,new Kr,new hs,new Fr]})]})]}),new ie({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:6}}),new ie({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:7}}),new ie({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:8}})]})}fromSchema(e){V(e,["blockName","otherName","rfc822Name","dNSName","x400Address","directoryName","ediPartyName","uniformResourceIdentifier","iPAddress","registeredID"]);let t=R(e,e,s.schema({names:{blockName:"blockName",otherName:"otherName",rfc822Name:"rfc822Name",dNSName:"dNSName",x400Address:"x400Address",directoryName:{names:{blockName:"directoryName"}},ediPartyName:"ediPartyName",uniformResourceIdentifier:"uniformResourceIdentifier",iPAddress:"iPAddress",registeredID:"registeredID"}}));switch(T.assertSchema(t,this.className),this.type=t.result.blockName.idBlock.tagNumber,this.type){case 0:this.value=t.result.blockName;break;case 1:case 2:case 6:{let n=t.result.blockName;n.idBlock.tagClass=1,n.idBlock.tagNumber=22;let r=n.toBER(!1),i=ht(r);T.assert(i,"GeneralName value"),this.value=i.result.valueBlock.value;}break;case 3:this.value=t.result.blockName;break;case 4:this.value=new Je({schema:t.result.directoryName});break;case 5:this.value=t.result.ediPartyName;break;case 7:this.value=new U({valueHex:t.result.blockName.valueBlock.valueHex});break;case 8:{let n=t.result.blockName;n.idBlock.tagClass=1,n.idBlock.tagNumber=6;let r=n.toBER(!1),i=ht(r);T.assert(i,"GeneralName registeredID"),this.value=i.result.valueBlock.toString();}break}}toSchema(){switch(this.type){case 0:case 3:case 5:return new A({idBlock:{tagClass:3,tagNumber:this.type},value:[this.value]});case 1:case 2:case 6:{let e=new Ta({value:this.value});return e.idBlock.tagClass=3,e.idBlock.tagNumber=this.type,e}case 4:return new A({idBlock:{tagClass:3,tagNumber:4},value:[this.value.toSchema()]});case 7:{let e=this.value;return e.idBlock.tagClass=3,e.idBlock.tagNumber=this.type,e}case 8:{let e=new G({value:this.value});return e.idBlock.tagClass=3,e.idBlock.tagNumber=this.type,e}default:return s.schema()}}toJSON(){let e={type:this.type,value:p};if(typeof this.value=="string")e.value=this.value;else try{e.value=this.value.toJSON();}catch{}return e}};qe.CLASS_NAME="GeneralName";var Vf="accessMethod",Df="accessLocation",K7=[Vf,Df],Pm=class s extends O{constructor(e={}){super(),this.accessMethod=d(e,Vf,s.defaultValues(Vf)),this.accessLocation=d(e,Df,s.defaultValues(Df)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Vf:return p;case Df:return new qe;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.accessMethod||p}),qe.schema(t.accessLocation||{})]})}fromSchema(e){V(e,K7);let t=R(e,e,s.schema({names:{accessMethod:Vf,accessLocation:{names:{blockName:Df}}}}));T.assertSchema(t,this.className),this.accessMethod=t.result.accessMethod.valueBlock.toString(),this.accessLocation=new qe({schema:t.result.accessLocation});}toSchema(){return new b({value:[new G({value:this.accessMethod}),this.accessLocation.toSchema()]})}toJSON(){return {accessMethod:this.accessMethod,accessLocation:this.accessLocation.toJSON()}}};Pm.CLASS_NAME="AccessDescription";var ei="seconds",ti="millis",si="micros",lr=class s extends O{constructor(e={}){super(),ei in e&&(this.seconds=d(e,ei,s.defaultValues(ei))),ti in e&&(this.millis=d(e,ti,s.defaultValues(ti))),si in e&&(this.micros=d(e,si,s.defaultValues(si))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ei:case ti:case si:return 0;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ei:case ti:case si:return t===s.defaultValues(e);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,optional:!0,value:[new N({optional:!0,name:t.seconds||p}),new ie({name:t.millis||p,optional:!0,idBlock:{tagClass:3,tagNumber:0}}),new ie({name:t.micros||p,optional:!0,idBlock:{tagClass:3,tagNumber:1}})]})}fromSchema(e){V(e,[ei,ti,si]);let t=R(e,e,s.schema({names:{seconds:ei,millis:ti,micros:si}}));if(T.assertSchema(t,this.className),"seconds"in t.result&&(this.seconds=t.result.seconds.valueBlock.valueDec),"millis"in t.result){let n=new N({valueHex:t.result.millis.valueBlock.valueHex});this.millis=n.valueBlock.valueDec;}if("micros"in t.result){let n=new N({valueHex:t.result.micros.valueBlock.valueHex});this.micros=n.valueBlock.valueDec;}}toSchema(){let e=[];if(this.seconds!==void 0&&e.push(new N({value:this.seconds})),this.millis!==void 0){let t=new N({value:this.millis});e.push(new ie({idBlock:{tagClass:3,tagNumber:0},valueHex:t.valueBlock.valueHexView}));}if(this.micros!==void 0){let t=new N({value:this.micros});e.push(new ie({idBlock:{tagClass:3,tagNumber:1},valueHex:t.valueBlock.valueHexView}));}return new b({value:e})}toJSON(){let e={};return this.seconds!==void 0&&(e.seconds=this.seconds),this.millis!==void 0&&(e.millis=this.millis),this.micros!==void 0&&(e.micros=this.micros),e}};lr.CLASS_NAME="Accuracy";var Q1="algorithmId",Sf="algorithmParams",ik="algorithm",U2="params",G7=[ik,U2],P=class s extends O{constructor(e={}){super(),this.algorithmId=d(e,Q1,s.defaultValues(Q1)),Sf in e&&(this.algorithmParams=d(e,Sf,s.defaultValues(Sf))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Q1:return p;case Sf:return new ue;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Q1:return t===p;case Sf:return t instanceof ue;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,optional:t.optional||!1,value:[new G({name:t.algorithmIdentifier||p}),new ue({name:t.algorithmParams||p,optional:!0})]})}fromSchema(e){V(e,G7);let t=R(e,e,s.schema({names:{algorithmIdentifier:ik,algorithmParams:U2}}));T.assertSchema(t,this.className),this.algorithmId=t.result.algorithm.valueBlock.toString(),U2 in t.result&&(this.algorithmParams=t.result.params);}toSchema(){let e=[];return e.push(new G({value:this.algorithmId})),this.algorithmParams&&!(this.algorithmParams instanceof ue)&&e.push(this.algorithmParams),new b({value:e})}toJSON(){let e={algorithmId:this.algorithmId};return this.algorithmParams&&!(this.algorithmParams instanceof ue)&&(e.algorithmParams=this.algorithmParams.toJSON()),e}isEqual(e){return !(e instanceof s)||this.algorithmId!==e.algorithmId?!1:this.algorithmParams?e.algorithmParams?JSON.stringify(this.algorithmParams)===JSON.stringify(e.algorithmParams):!1:!e.algorithmParams}};P.CLASS_NAME="AlgorithmIdentifier";var eu="altNames",W7=[eu],Tm=class s extends O{constructor(e={}){super(),this.altNames=d(e,eu,s.defaultValues(eu)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case eu:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.altNames||p,value:qe.schema()})]})}fromSchema(e){V(e,W7);let t=R(e,e,s.schema({names:{altNames:eu}}));T.assertSchema(t,this.className),eu in t.result&&(this.altNames=Array.from(t.result.altNames,n=>new qe({schema:n})));}toSchema(){return new b({value:Array.from(this.altNames,e=>e.toSchema())})}toJSON(){return {altNames:Array.from(this.altNames,e=>e.toJSON())}}};Tm.CLASS_NAME="AltName";var tu="type",su="values",J7=[tu,su],nt=class s extends O{constructor(e={}){super(),this.type=d(e,tu,s.defaultValues(tu)),this.values=d(e,su,s.defaultValues(su)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case tu:return p;case su:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case tu:return t===p;case su:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.type||p}),new et({name:t.setName||p,value:[new fe({name:t.values||p,value:new ue})]})]})}fromSchema(e){V(e,J7);let t=R(e,e,s.schema({names:{type:tu,values:su}}));T.assertSchema(t,this.className),this.type=t.result.type.valueBlock.toString(),this.values=t.result.values;}toSchema(){return new b({value:[new G({value:this.type}),new et({value:this.values})]})}toJSON(){return {type:this.type,values:Array.from(this.values,e=>e.toJSON())}}};nt.CLASS_NAME="Attribute";var Uf="notBeforeTime",Lf="notAfterTime",z7=[Uf,Lf],pr=class s extends O{constructor(e={}){super(),this.notBeforeTime=d(e,Uf,s.defaultValues(Uf)),this.notAfterTime=d(e,Lf,s.defaultValues(Lf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Uf:case Lf:return new Date(0,0,0);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new Ge({name:t.notBeforeTime||p}),new Ge({name:t.notAfterTime||p})]})}fromSchema(e){V(e,z7);let t=R(e,e,s.schema({names:{notBeforeTime:Uf,notAfterTime:Lf}}));T.assertSchema(t,this.className),this.notBeforeTime=t.result.notBeforeTime.toDate(),this.notAfterTime=t.result.notAfterTime.toDate();}toSchema(){return new b({value:[new Ge({valueDate:this.notBeforeTime}),new Ge({valueDate:this.notAfterTime})]})}toJSON(){return {notBeforeTime:this.notBeforeTime,notAfterTime:this.notAfterTime}}};pr.CLASS_NAME="AttCertValidityPeriod";var vf="names",DN="generalNames",bt=class s extends O{constructor(e={}){super(),this.names=d(e,vf,s.defaultValues(vf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case"names":return [];default:return super.defaultValues(e)}}static schema(e={},t=!1){let n=d(e,vf,{});return new b({optional:t,name:n.blockName||p,value:[new fe({name:n.generalNames||p,value:qe.schema()})]})}fromSchema(e){V(e,[vf,DN]);let t=R(e,e,s.schema({names:{blockName:vf,generalNames:DN}}));T.assertSchema(t,this.className),this.names=Array.from(t.result.generalNames,n=>new qe({schema:n}));}toSchema(){return new b({value:Array.from(this.names,e=>e.toSchema())})}toJSON(){return {names:Array.from(this.names,e=>e.toJSON())}}};bt.CLASS_NAME="GeneralNames";var Y7="2.5.29.9",Z7="2.5.29.14",Q7="2.5.29.15",X7="2.5.29.16",ak="2.5.29.17",ok="2.5.29.18",pA="2.5.29.19",e9="2.5.29.20",t9="2.5.29.27",s9="2.5.29.21",n9="2.5.29.24",ck="2.5.29.28",uk="2.5.29.29",lk="2.5.29.30",hk="2.5.29.31",gA="2.5.29.46",fk="2.5.29.32",Ps="2.5.29.32.0",r9="1.3.6.1.4.1.311.21.10",dk="2.5.29.33",yA="2.5.29.35",mk="2.5.29.36",i9="2.5.29.37",a9="2.5.29.54",wA="1.3.6.1.5.5.7.1.1",o9="1.3.6.1.5.5.7.1.11",c9="1.3.6.1.4.1.11129.2.4.2";var u9="1.3.6.1.4.1.311.21.7",l9="1.3.6.1.4.1.311.21.1",h9="1.3.6.1.5.5.7.1.3",bA="1.2.840.113549.1.7.1",pk="1.2.840.113549.1.7.2",gk="1.2.840.113549.1.7.3",yk="1.2.840.113549.1.7.6",f9="1.2.840.113549.1.9.16.1.4",UN="1.2.840.113549.1.9.22.1",d9="1.2.840.113549.1.9.22.2",LN="1.2.840.113549.1.9.22.3",jN="1.2.840.113549.1.9.23.1",m9="1.3.6.1.5.5.7",SA=`${m9}.48`,Ey=`${SA}.1.1`;var ja="keyIdentifier",Ha="authorityCertIssuer",_a="authorityCertSerialNumber",p9=[ja,Ha,_a],Bm=class s extends O{constructor(e={}){super(),ja in e&&(this.keyIdentifier=d(e,ja,s.defaultValues(ja))),Ha in e&&(this.authorityCertIssuer=d(e,Ha,s.defaultValues(Ha))),_a in e&&(this.authorityCertSerialNumber=d(e,_a,s.defaultValues(_a))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ja:return new U;case Ha:return [];case _a:return new N;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new ie({name:t.keyIdentifier||p,optional:!0,idBlock:{tagClass:3,tagNumber:0}}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new fe({name:t.authorityCertIssuer||p,value:qe.schema()})]}),new ie({name:t.authorityCertSerialNumber||p,optional:!0,idBlock:{tagClass:3,tagNumber:2}})]})}fromSchema(e){V(e,p9);let t=R(e,e,s.schema({names:{keyIdentifier:ja,authorityCertIssuer:Ha,authorityCertSerialNumber:_a}}));T.assertSchema(t,this.className),ja in t.result&&(this.keyIdentifier=new U({valueHex:t.result.keyIdentifier.valueBlock.valueHex})),Ha in t.result&&(this.authorityCertIssuer=Array.from(t.result.authorityCertIssuer,n=>new qe({schema:n}))),_a in t.result&&(this.authorityCertSerialNumber=new N({valueHex:t.result.authorityCertSerialNumber.valueBlock.valueHex}));}toSchema(){let e=[];return this.keyIdentifier&&e.push(new ie({idBlock:{tagClass:3,tagNumber:0},valueHex:this.keyIdentifier.valueBlock.valueHexView})),this.authorityCertIssuer&&e.push(new A({idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.authorityCertIssuer,t=>t.toSchema())})),this.authorityCertSerialNumber&&e.push(new ie({idBlock:{tagClass:3,tagNumber:2},valueHex:this.authorityCertSerialNumber.valueBlock.valueHexView})),new b({value:e})}toJSON(){let e={};return this.keyIdentifier&&(e.keyIdentifier=this.keyIdentifier.toJSON()),this.authorityCertIssuer&&(e.authorityCertIssuer=Array.from(this.authorityCertIssuer,t=>t.toJSON())),this.authorityCertSerialNumber&&(e.authorityCertSerialNumber=this.authorityCertSerialNumber.toJSON()),e}};Bm.CLASS_NAME="AuthorityKeyIdentifier";var Da="pathLenConstraint",Ua="cA",Om=class s extends O{constructor(e={}){super(),this.cA=d(e,Ua,!1),Da in e&&(this.pathLenConstraint=d(e,Da,0)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ua:return !1;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new xs({optional:!0,name:t.cA||p}),new N({optional:!0,name:t.pathLenConstraint||p})]})}fromSchema(e){V(e,[Ua,Da]);let t=R(e,e,s.schema({names:{cA:Ua,pathLenConstraint:Da}}));T.assertSchema(t,this.className),Ua in t.result&&(this.cA=t.result.cA.valueBlock.value),Da in t.result&&(t.result.pathLenConstraint.valueBlock.isHexOnly?this.pathLenConstraint=t.result.pathLenConstraint:this.pathLenConstraint=t.result.pathLenConstraint.valueBlock.valueDec);}toSchema(){let e=[];return this.cA!==s.defaultValues(Ua)&&e.push(new xs({value:this.cA})),Da in this&&(this.pathLenConstraint instanceof N?e.push(this.pathLenConstraint):e.push(new N({value:this.pathLenConstraint}))),new b({value:e})}toJSON(){let e={};return this.cA!==s.defaultValues(Ua)&&(e.cA=this.cA),Da in this&&(this.pathLenConstraint instanceof N?e.pathLenConstraint=this.pathLenConstraint.toJSON():e.pathLenConstraint=this.pathLenConstraint),e}};Om.CLASS_NAME="BasicConstraints";var c2="certificateIndex",u2="keyIndex",ew=class s extends O{constructor(e={}){super(),this.certificateIndex=d(e,c2,s.defaultValues(c2)),this.keyIndex=d(e,u2,s.defaultValues(u2)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case c2:case u2:return 0;default:return super.defaultValues(e)}}static schema(){return new N}fromSchema(e){if(e.constructor.blockName()!==N.blockName())throw new Error("Object's schema was not verified against input data for CAVersion");let t=e.valueBlock.valueHex.slice(0),n=new Uint8Array(t);switch(!0){case t.byteLength<4:{let h=new ArrayBuffer(4);new Uint8Array(h).set(n,4-t.byteLength),t=h.slice(0);}break;case t.byteLength>4:{let h=new ArrayBuffer(4);new Uint8Array(h).set(n.slice(0,4)),t=h.slice(0);}break}let r=t.slice(0,2),i=new Uint8Array(r),a=i[0];i[0]=i[1],i[1]=a;let o=new Uint16Array(r);this.keyIndex=o[0];let c=t.slice(2),u=new Uint8Array(c);a=u[0],u[0]=u[1],u[1]=a;let l=new Uint16Array(c);this.certificateIndex=l[0];}toSchema(){let e=new ArrayBuffer(2),t=new Uint16Array(e);t[0]=this.certificateIndex;let n=new Uint8Array(e),r=n[0];n[0]=n[1],n[1]=r;let i=new ArrayBuffer(2),a=new Uint16Array(i);a[0]=this.keyIndex;let o=new Uint8Array(i);return r=o[0],o[0]=o[1],o[1]=r,new N({valueHex:ka(i,e)})}toJSON(){return {certificateIndex:this.certificateIndex,keyIndex:this.keyIndex}}};ew.CLASS_NAME="CAVersion";var jf="policyQualifierId",Hf="qualifier",g9=[jf,Hf],Rm=class s extends O{constructor(e={}){super(),this.policyQualifierId=d(e,jf,s.defaultValues(jf)),this.qualifier=d(e,Hf,s.defaultValues(Hf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case jf:return p;case Hf:return new ue;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.policyQualifierId||p}),new ue({name:t.qualifier||p})]})}fromSchema(e){V(e,g9);let t=R(e,e,s.schema({names:{policyQualifierId:jf,qualifier:Hf}}));T.assertSchema(t,this.className),this.policyQualifierId=t.result.policyQualifierId.valueBlock.toString(),this.qualifier=t.result.qualifier;}toSchema(){return new b({value:[new G({value:this.policyQualifierId}),this.qualifier]})}toJSON(){return {policyQualifierId:this.policyQualifierId,qualifier:this.qualifier.toJSON()}}};Rm.CLASS_NAME="PolicyQualifierInfo";var _f="policyIdentifier",Ma="policyQualifiers",y9=[_f,Ma],Vm=class s extends O{constructor(e={}){super(),this.policyIdentifier=d(e,_f,s.defaultValues(_f)),Ma in e&&(this.policyQualifiers=d(e,Ma,s.defaultValues(Ma))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case _f:return p;case Ma:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.policyIdentifier||p}),new b({optional:!0,value:[new fe({name:t.policyQualifiers||p,value:Rm.schema()})]})]})}fromSchema(e){V(e,y9);let t=R(e,e,s.schema({names:{policyIdentifier:_f,policyQualifiers:Ma}}));T.assertSchema(t,this.className),this.policyIdentifier=t.result.policyIdentifier.valueBlock.toString(),Ma in t.result&&(this.policyQualifiers=Array.from(t.result.policyQualifiers,n=>new Rm({schema:n})));}toSchema(){let e=[];return e.push(new G({value:this.policyIdentifier})),this.policyQualifiers&&e.push(new b({value:Array.from(this.policyQualifiers,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={policyIdentifier:this.policyIdentifier};return this.policyQualifiers&&(e.policyQualifiers=Array.from(this.policyQualifiers,t=>t.toJSON())),e}};Vm.CLASS_NAME="PolicyInformation";var Mf="certificatePolicies",w9=[Mf],Dm=class s extends O{constructor(e={}){super(),this.certificatePolicies=d(e,Mf,s.defaultValues(Mf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Mf:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.certificatePolicies||p,value:Vm.schema()})]})}fromSchema(e){V(e,w9);let t=R(e,e,s.schema({names:{certificatePolicies:Mf}}));T.assertSchema(t,this.className),this.certificatePolicies=Array.from(t.result.certificatePolicies,n=>new Vm({schema:n}));}toSchema(){return new b({value:Array.from(this.certificatePolicies,e=>e.toSchema())})}toJSON(){return {certificatePolicies:Array.from(this.certificatePolicies,e=>e.toJSON())}}};Dm.CLASS_NAME="CertificatePolicies";var $f="templateID",Qn="templateMajorVersion",Xn="templateMinorVersion",b9=[$f,Qn,Xn],L2=class s extends O{constructor(e={}){super(),this.templateID=d(e,$f,s.defaultValues($f)),Qn in e&&(this.templateMajorVersion=d(e,Qn,s.defaultValues(Qn))),Xn in e&&(this.templateMinorVersion=d(e,Xn,s.defaultValues(Xn))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case $f:return p;case Qn:case Xn:return 0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.templateID||p}),new N({name:t.templateMajorVersion||p,optional:!0}),new N({name:t.templateMinorVersion||p,optional:!0})]})}fromSchema(e){V(e,b9);let t=R(e,e,s.schema({names:{templateID:$f,templateMajorVersion:Qn,templateMinorVersion:Xn}}));T.assertSchema(t,this.className),this.templateID=t.result.templateID.valueBlock.toString(),Qn in t.result&&(this.templateMajorVersion=t.result.templateMajorVersion.valueBlock.valueDec),Xn in t.result&&(this.templateMinorVersion=t.result.templateMinorVersion.valueBlock.valueDec);}toSchema(){let e=[];return e.push(new G({value:this.templateID})),Qn in this&&e.push(new N({value:this.templateMajorVersion})),Xn in this&&e.push(new N({value:this.templateMinorVersion})),new b({value:e})}toJSON(){let e={templateID:this.templateID};return Qn in this&&(e.templateMajorVersion=this.templateMajorVersion),Xn in this&&(e.templateMinorVersion=this.templateMinorVersion),e}},$a="distributionPoint",wk="distributionPointNames",qa="reasons",Fa="cRLIssuer",bk="cRLIssuerNames",S9=[$a,wk,qa,Fa,bk],Um=class s extends O{constructor(e={}){super(),$a in e&&(this.distributionPoint=d(e,$a,s.defaultValues($a))),qa in e&&(this.reasons=d(e,qa,s.defaultValues(qa))),Fa in e&&(this.cRLIssuer=d(e,Fa,s.defaultValues(Fa))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case $a:return [];case qa:return new Ae;case Fa:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new We({value:[new A({name:t.distributionPoint||p,optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new fe({name:t.distributionPointNames||p,value:qe.schema()})]}),new A({name:t.distributionPoint||p,optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Je.schema().valueBlock.value})]})]}),new ie({name:t.reasons||p,optional:!0,idBlock:{tagClass:3,tagNumber:1}}),new A({name:t.cRLIssuer||p,optional:!0,idBlock:{tagClass:3,tagNumber:2},value:[new fe({name:t.cRLIssuerNames||p,value:qe.schema()})]})]})}fromSchema(e){V(e,S9);let t=R(e,e,s.schema({names:{distributionPoint:$a,distributionPointNames:wk,reasons:qa,cRLIssuer:Fa,cRLIssuerNames:bk}}));T.assertSchema(t,this.className),$a in t.result&&(t.result.distributionPoint.idBlock.tagNumber===0&&(this.distributionPoint=Array.from(t.result.distributionPointNames,n=>new qe({schema:n}))),t.result.distributionPoint.idBlock.tagNumber===1&&(this.distributionPoint=new Je({schema:new b({value:t.result.distributionPoint.valueBlock.value})}))),qa in t.result&&(this.reasons=new Ae({valueHex:t.result.reasons.valueBlock.valueHex})),Fa in t.result&&(this.cRLIssuer=Array.from(t.result.cRLIssuerNames,n=>new qe({schema:n})));}toSchema(){let e=[];if(this.distributionPoint){let t;this.distributionPoint instanceof Array?t=new A({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.distributionPoint,n=>n.toSchema())}):t=new A({idBlock:{tagClass:3,tagNumber:1},value:[this.distributionPoint.toSchema()]}),e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[t]}));}return this.reasons&&e.push(new ie({idBlock:{tagClass:3,tagNumber:1},valueHex:this.reasons.valueBlock.valueHexView})),this.cRLIssuer&&e.push(new A({idBlock:{tagClass:3,tagNumber:2},value:Array.from(this.cRLIssuer,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={};return this.distributionPoint&&(this.distributionPoint instanceof Array?e.distributionPoint=Array.from(this.distributionPoint,t=>t.toJSON()):e.distributionPoint=this.distributionPoint.toJSON()),this.reasons&&(e.reasons=this.reasons.toJSON()),this.cRLIssuer&&(e.cRLIssuer=Array.from(this.cRLIssuer,t=>t.toJSON())),e}};Um.CLASS_NAME="DistributionPoint";var qf="distributionPoints",v9=[qf],Lm=class s extends O{constructor(e={}){super(),this.distributionPoints=d(e,qf,s.defaultValues(qf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case qf:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.distributionPoints||p,value:Um.schema()})]})}fromSchema(e){V(e,v9);let t=R(e,e,s.schema({names:{distributionPoints:qf}}));T.assertSchema(t,this.className),this.distributionPoints=Array.from(t.result.distributionPoints,n=>new Um({schema:n}));}toSchema(){return new b({value:Array.from(this.distributionPoints,e=>e.toSchema())})}toJSON(){return {distributionPoints:Array.from(this.distributionPoints,e=>e.toJSON())}}};Lm.CLASS_NAME="CRLDistributionPoints";var Ff="keyPurposes",x9=[Ff],tw=class s extends O{constructor(e={}){super(),this.keyPurposes=d(e,Ff,s.defaultValues(Ff)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ff:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.keyPurposes||p,value:new G})]})}fromSchema(e){V(e,x9);let t=R(e,e,s.schema({names:{keyPurposes:Ff}}));T.assertSchema(t,this.className),this.keyPurposes=Array.from(t.result.keyPurposes,n=>n.valueBlock.toString());}toSchema(){return new b({value:Array.from(this.keyPurposes,e=>new G({value:e}))})}toJSON(){return {keyPurposes:Array.from(this.keyPurposes)}}};tw.CLASS_NAME="ExtKeyUsage";var xf="accessDescriptions",jm=class s extends O{constructor(e={}){super(),this.accessDescriptions=d(e,xf,s.defaultValues(xf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case xf:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.accessDescriptions||p,value:Pm.schema()})]})}fromSchema(e){V(e,[xf]);let t=R(e,e,s.schema({names:{accessDescriptions:xf}}));T.assertSchema(t,this.className),this.accessDescriptions=Array.from(t.result.accessDescriptions,n=>new Pm({schema:n}));}toSchema(){return new b({value:Array.from(this.accessDescriptions,e=>e.toSchema())})}toJSON(){return {accessDescriptions:Array.from(this.accessDescriptions,e=>e.toJSON())}}};jm.CLASS_NAME="InfoAccess";var Ka="distributionPoint",Sk="distributionPointNames",ni="onlyContainsUserCerts",ri="onlyContainsCACerts",ii="onlySomeReasons",ai="indirectCRL",oi="onlyContainsAttributeCerts",E9=[Ka,Sk,ni,ri,ii,ai,oi],sw=class s extends O{constructor(e={}){super(),Ka in e&&(this.distributionPoint=d(e,Ka,s.defaultValues(Ka))),this.onlyContainsUserCerts=d(e,ni,s.defaultValues(ni)),this.onlyContainsCACerts=d(e,ri,s.defaultValues(ri)),ii in e&&(this.onlySomeReasons=d(e,ii,s.defaultValues(ii))),this.indirectCRL=d(e,ai,s.defaultValues(ai)),this.onlyContainsAttributeCerts=d(e,oi,s.defaultValues(oi)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ka:return [];case ni:return !1;case ri:return !1;case ii:return 0;case ai:return !1;case oi:return !1;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new We({value:[new A({name:t.distributionPoint||p,idBlock:{tagClass:3,tagNumber:0},value:[new fe({name:t.distributionPointNames||p,value:qe.schema()})]}),new A({name:t.distributionPoint||p,idBlock:{tagClass:3,tagNumber:1},value:Je.schema().valueBlock.value})]})]}),new ie({name:t.onlyContainsUserCerts||p,optional:!0,idBlock:{tagClass:3,tagNumber:1}}),new ie({name:t.onlyContainsCACerts||p,optional:!0,idBlock:{tagClass:3,tagNumber:2}}),new ie({name:t.onlySomeReasons||p,optional:!0,idBlock:{tagClass:3,tagNumber:3}}),new ie({name:t.indirectCRL||p,optional:!0,idBlock:{tagClass:3,tagNumber:4}}),new ie({name:t.onlyContainsAttributeCerts||p,optional:!0,idBlock:{tagClass:3,tagNumber:5}})]})}fromSchema(e){V(e,E9);let t=R(e,e,s.schema({names:{distributionPoint:Ka,distributionPointNames:Sk,onlyContainsUserCerts:ni,onlyContainsCACerts:ri,onlySomeReasons:ii,indirectCRL:ai,onlyContainsAttributeCerts:oi}}));if(T.assertSchema(t,this.className),Ka in t.result)switch(!0){case t.result.distributionPoint.idBlock.tagNumber===0:this.distributionPoint=Array.from(t.result.distributionPointNames,n=>new qe({schema:n}));break;case t.result.distributionPoint.idBlock.tagNumber===1:this.distributionPoint=new Je({schema:new b({value:t.result.distributionPoint.valueBlock.value})});break;default:throw new Error("Unknown tagNumber for distributionPoint: {$asn1.result.distributionPoint.idBlock.tagNumber}")}if(ni in t.result){let n=new Uint8Array(t.result.onlyContainsUserCerts.valueBlock.valueHex);this.onlyContainsUserCerts=n[0]!==0;}if(ri in t.result){let n=new Uint8Array(t.result.onlyContainsCACerts.valueBlock.valueHex);this.onlyContainsCACerts=n[0]!==0;}if(ii in t.result){let n=new Uint8Array(t.result.onlySomeReasons.valueBlock.valueHex);this.onlySomeReasons=n[0];}if(ai in t.result){let n=new Uint8Array(t.result.indirectCRL.valueBlock.valueHex);this.indirectCRL=n[0]!==0;}if(oi in t.result){let n=new Uint8Array(t.result.onlyContainsAttributeCerts.valueBlock.valueHex);this.onlyContainsAttributeCerts=n[0]!==0;}}toSchema(){let e=[];if(this.distributionPoint){let t;this.distributionPoint instanceof Array?t=new A({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.distributionPoint,n=>n.toSchema())}):(t=this.distributionPoint.toSchema(),t.idBlock.tagClass=3,t.idBlock.tagNumber=1),e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[t]}));}if(this.onlyContainsUserCerts!==s.defaultValues(ni)&&e.push(new ie({idBlock:{tagClass:3,tagNumber:1},valueHex:new Uint8Array([255]).buffer})),this.onlyContainsCACerts!==s.defaultValues(ri)&&e.push(new ie({idBlock:{tagClass:3,tagNumber:2},valueHex:new Uint8Array([255]).buffer})),this.onlySomeReasons!==void 0){let t=new ArrayBuffer(1),n=new Uint8Array(t);n[0]=this.onlySomeReasons,e.push(new ie({idBlock:{tagClass:3,tagNumber:3},valueHex:t}));}return this.indirectCRL!==s.defaultValues(ai)&&e.push(new ie({idBlock:{tagClass:3,tagNumber:4},valueHex:new Uint8Array([255]).buffer})),this.onlyContainsAttributeCerts!==s.defaultValues(oi)&&e.push(new ie({idBlock:{tagClass:3,tagNumber:5},valueHex:new Uint8Array([255]).buffer})),new b({value:e})}toJSON(){let e={};return this.distributionPoint&&(this.distributionPoint instanceof Array?e.distributionPoint=Array.from(this.distributionPoint,t=>t.toJSON()):e.distributionPoint=this.distributionPoint.toJSON()),this.onlyContainsUserCerts!==s.defaultValues(ni)&&(e.onlyContainsUserCerts=this.onlyContainsUserCerts),this.onlyContainsCACerts!==s.defaultValues(ri)&&(e.onlyContainsCACerts=this.onlyContainsCACerts),ii in this&&(e.onlySomeReasons=this.onlySomeReasons),this.indirectCRL!==s.defaultValues(ai)&&(e.indirectCRL=this.indirectCRL),this.onlyContainsAttributeCerts!==s.defaultValues(oi)&&(e.onlyContainsAttributeCerts=this.onlyContainsAttributeCerts),e}};sw.CLASS_NAME="IssuingDistributionPoint";var Kf="base",nu="minimum",ci="maximum",A9=[Kf,nu,ci],$o=class s extends O{constructor(e={}){super(),this.base=d(e,Kf,s.defaultValues(Kf)),this.minimum=d(e,nu,s.defaultValues(nu)),ci in e&&(this.maximum=d(e,ci,s.defaultValues(ci))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Kf:return new qe;case nu:return 0;case ci:return 0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[qe.schema(t.base||{}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new N({name:t.minimum||p})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new N({name:t.maximum||p})]})]})}fromSchema(e){V(e,A9);let t=R(e,e,s.schema({names:{base:{names:{blockName:Kf}},minimum:nu,maximum:ci}}));T.assertSchema(t,this.className),this.base=new qe({schema:t.result.base}),nu in t.result&&(t.result.minimum.valueBlock.isHexOnly?this.minimum=t.result.minimum:this.minimum=t.result.minimum.valueBlock.valueDec),ci in t.result&&(t.result.maximum.valueBlock.isHexOnly?this.maximum=t.result.maximum:this.maximum=t.result.maximum.valueBlock.valueDec);}toSchema(){let e=[];if(e.push(this.base.toSchema()),this.minimum!==0){let t=0;this.minimum instanceof N?t=this.minimum:t=new N({value:this.minimum}),e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[t]}));}if(ci in this){let t=0;this.maximum instanceof N?t=this.maximum:t=new N({value:this.maximum}),e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[t]}));}return new b({value:e})}toJSON(){let e={base:this.base.toJSON()};return this.minimum!==0&&(typeof this.minimum=="number"?e.minimum=this.minimum:e.minimum=this.minimum.toJSON()),this.maximum!==void 0&&(typeof this.maximum=="number"?e.maximum=this.maximum:e.maximum=this.maximum.toJSON()),e}};$o.CLASS_NAME="GeneralSubtree";var Ga="permittedSubtrees",Wa="excludedSubtrees",I9=[Ga,Wa],nw=class s extends O{constructor(e={}){super(),Ga in e&&(this.permittedSubtrees=d(e,Ga,s.defaultValues(Ga))),Wa in e&&(this.excludedSubtrees=d(e,Wa,s.defaultValues(Wa))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ga:case Wa:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new fe({name:t.permittedSubtrees||p,value:$o.schema()})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new fe({name:t.excludedSubtrees||p,value:$o.schema()})]})]})}fromSchema(e){V(e,I9);let t=R(e,e,s.schema({names:{permittedSubtrees:Ga,excludedSubtrees:Wa}}));T.assertSchema(t,this.className),Ga in t.result&&(this.permittedSubtrees=Array.from(t.result.permittedSubtrees,n=>new $o({schema:n}))),Wa in t.result&&(this.excludedSubtrees=Array.from(t.result.excludedSubtrees,n=>new $o({schema:n})));}toSchema(){let e=[];return this.permittedSubtrees&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.permittedSubtrees,t=>t.toSchema())})),this.excludedSubtrees&&e.push(new A({idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.excludedSubtrees,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={};return this.permittedSubtrees&&(e.permittedSubtrees=Array.from(this.permittedSubtrees,t=>t.toJSON())),this.excludedSubtrees&&(e.excludedSubtrees=Array.from(this.excludedSubtrees,t=>t.toJSON())),e}};nw.CLASS_NAME="NameConstraints";var er="requireExplicitPolicy",tr="inhibitPolicyMapping",C9=[er,tr],rw=class s extends O{constructor(e={}){super(),er in e&&(this.requireExplicitPolicy=d(e,er,s.defaultValues(er))),tr in e&&(this.inhibitPolicyMapping=d(e,tr,s.defaultValues(tr))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case er:return 0;case tr:return 0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new ie({name:t.requireExplicitPolicy||p,optional:!0,idBlock:{tagClass:3,tagNumber:0}}),new ie({name:t.inhibitPolicyMapping||p,optional:!0,idBlock:{tagClass:3,tagNumber:1}})]})}fromSchema(e){V(e,C9);let t=R(e,e,s.schema({names:{requireExplicitPolicy:er,inhibitPolicyMapping:tr}}));if(T.assertSchema(t,this.className),er in t.result){let n=t.result.requireExplicitPolicy;n.idBlock.tagClass=1,n.idBlock.tagNumber=2;let r=n.toBER(!1),i=ht(r);T.assert(i,"Integer"),this.requireExplicitPolicy=i.result.valueBlock.valueDec;}if(tr in t.result){let n=t.result.inhibitPolicyMapping;n.idBlock.tagClass=1,n.idBlock.tagNumber=2;let r=n.toBER(!1),i=ht(r);T.assert(i,"Integer"),this.inhibitPolicyMapping=i.result.valueBlock.valueDec;}}toSchema(){let e=[];if(er in this){let t=new N({value:this.requireExplicitPolicy});t.idBlock.tagClass=3,t.idBlock.tagNumber=0,e.push(t);}if(tr in this){let t=new N({value:this.inhibitPolicyMapping});t.idBlock.tagClass=3,t.idBlock.tagNumber=1,e.push(t);}return new b({value:e})}toJSON(){let e={};return er in this&&(e.requireExplicitPolicy=this.requireExplicitPolicy),tr in this&&(e.inhibitPolicyMapping=this.inhibitPolicyMapping),e}};rw.CLASS_NAME="PolicyConstraints";var Gf="issuerDomainPolicy",Wf="subjectDomainPolicy",N9=[Gf,Wf],Hm=class s extends O{constructor(e={}){super(),this.issuerDomainPolicy=d(e,Gf,s.defaultValues(Gf)),this.subjectDomainPolicy=d(e,Wf,s.defaultValues(Wf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Gf:return p;case Wf:return p;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.issuerDomainPolicy||p}),new G({name:t.subjectDomainPolicy||p})]})}fromSchema(e){V(e,N9);let t=R(e,e,s.schema({names:{issuerDomainPolicy:Gf,subjectDomainPolicy:Wf}}));T.assertSchema(t,this.className),this.issuerDomainPolicy=t.result.issuerDomainPolicy.valueBlock.toString(),this.subjectDomainPolicy=t.result.subjectDomainPolicy.valueBlock.toString();}toSchema(){return new b({value:[new G({value:this.issuerDomainPolicy}),new G({value:this.subjectDomainPolicy})]})}toJSON(){return {issuerDomainPolicy:this.issuerDomainPolicy,subjectDomainPolicy:this.subjectDomainPolicy}}};Hm.CLASS_NAME="PolicyMapping";var Jf="mappings",k9=[Jf],iw=class s extends O{constructor(e={}){super(),this.mappings=d(e,Jf,s.defaultValues(Jf)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Jf:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.mappings||p,value:Hm.schema()})]})}fromSchema(e){V(e,k9);let t=R(e,e,s.schema({names:{mappings:Jf}}));T.assertSchema(t,this.className),this.mappings=Array.from(t.result.mappings,n=>new Hm({schema:n}));}toSchema(){return new b({value:Array.from(this.mappings,e=>e.toSchema())})}toJSON(){return {mappings:Array.from(this.mappings,e=>e.toJSON())}}};iw.CLASS_NAME="PolicyMappings";var ui="notBefore",li="notAfter",P9=[ui,li],aw=class s extends O{constructor(e={}){super(),ui in e&&(this.notBefore=d(e,ui,s.defaultValues(ui))),li in e&&(this.notAfter=d(e,li,s.defaultValues(li))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ui:return new Date;case li:return new Date;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new ie({name:t.notBefore||p,optional:!0,idBlock:{tagClass:3,tagNumber:0}}),new ie({name:t.notAfter||p,optional:!0,idBlock:{tagClass:3,tagNumber:1}})]})}fromSchema(e){V(e,P9);let t=R(e,e,s.schema({names:{notBefore:ui,notAfter:li}}));if(T.assertSchema(t,this.className),ui in t.result){let n=new Ge;n.fromBuffer(t.result.notBefore.valueBlock.valueHex),this.notBefore=n.toDate();}if(li in t.result){let n=new Ge({valueHex:t.result.notAfter.valueBlock.valueHex});n.fromBuffer(t.result.notAfter.valueBlock.valueHex),this.notAfter=n.toDate();}}toSchema(){let e=[];return ui in this&&e.push(new ie({idBlock:{tagClass:3,tagNumber:0},valueHex:new Ge({valueDate:this.notBefore}).valueBlock.valueHexView})),li in this&&e.push(new ie({idBlock:{tagClass:3,tagNumber:1},valueHex:new Ge({valueDate:this.notAfter}).valueBlock.valueHexView})),new b({value:e})}toJSON(){let e={};return this.notBefore&&(e.notBefore=this.notBefore),this.notAfter&&(e.notAfter=this.notAfter),e}};aw.CLASS_NAME="PrivateKeyUsagePeriod";var ru="id",sr="type",iu="values",T9=[ru,sr],B9=[iu],_m=class s extends O{constructor(e={}){super(),this.id=d(e,ru,s.defaultValues(ru)),sr in e&&(this.type=d(e,sr,s.defaultValues(sr))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ru:return p;case sr:return new Xe;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ru:return t===p;case sr:return t instanceof Xe;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.id||p}),new ue({name:t.type||p,optional:!0})]})}fromSchema(e){V(e,T9);let t=R(e,e,s.schema({names:{id:ru,type:sr}}));T.assertSchema(t,this.className),this.id=t.result.id.valueBlock.toString(),sr in t.result&&(this.type=t.result.type);}toSchema(){let e=[new G({value:this.id})];return sr in this&&e.push(this.type),new b({value:e})}toJSON(){let e={id:this.id};return this.type&&(e.type=this.type.toJSON()),e}};_m.CLASS_NAME="QCStatement";var ow=class s extends O{constructor(e={}){super(),this.values=d(e,iu,s.defaultValues(iu)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case iu:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case iu:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.values||p,value:_m.schema(t.value||{})})]})}fromSchema(e){V(e,B9);let t=R(e,e,s.schema({names:{values:iu}}));T.assertSchema(t,this.className),this.values=Array.from(t.result.values,n=>new _m({schema:n}));}toSchema(){return new b({value:Array.from(this.values,e=>e.toSchema())})}toJSON(){return {values:Array.from(this.values,e=>e.toJSON())}}};ow.CLASS_NAME="QCStatements";var Ja,Sn=class{static register(e,t,n){this.namedCurves[e.toLowerCase()]=this.namedCurves[t]={name:e,id:t,size:n};}static find(e){return this.namedCurves[e.toLowerCase()]||null}};Ja=Sn;Sn.namedCurves={};Ja.register("P-256","1.2.840.10045.3.1.7",32),Ja.register("P-384","1.3.132.0.34",48),Ja.register("P-521","1.3.132.0.35",66),Ja.register("brainpoolP256r1","1.3.36.3.3.2.8.1.1.7",32),Ja.register("brainpoolP384r1","1.3.36.3.3.2.8.1.1.11",48),Ja.register("brainpoolP512r1","1.3.36.3.3.2.8.1.1.13",64);var X1="x",ey="y",ty="namedCurve",tn=class s extends O{constructor(e={}){super(),this.x=d(e,X1,s.defaultValues(X1)),this.y=d(e,ey,s.defaultValues(ey)),this.namedCurve=d(e,ty,s.defaultValues(ty)),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case X1:case ey:return ut;case ty:return p;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case X1:case ey:return t instanceof ArrayBuffer&&qr(t,s.defaultValues(e));case ty:return typeof t=="string"&&t===s.defaultValues(e);default:return super.defaultValues(e)}}static schema(){return new Oa}fromSchema(e){let t=re.toUint8Array(e);if(t[0]!==4)throw new Error("Object's schema was not verified against input data for ECPublicKey");let n=Sn.find(this.namedCurve);if(!n)throw new Error(`Incorrect curve OID: ${this.namedCurve}`);let r=n.size;if(t.byteLength!==r*2+1)throw new Error("Object's schema was not verified against input data for ECPublicKey");this.namedCurve=n.name,this.x=t.slice(1,r+1).buffer,this.y=t.slice(1+r,r*2+1).buffer;}toSchema(){return new Oa({data:ka(new Uint8Array([4]).buffer,this.x,this.y)})}toJSON(){let e=Sn.find(this.namedCurve);return {crv:e?e.name:this.namedCurve,x:b1(uf(this.x),!0,!0,!1),y:b1(uf(this.y),!0,!0,!1)}}fromJSON(e){Re.assert("json",e,"crv","x","y");let t=0,n=Sn.find(e.crv);n&&(this.namedCurve=n.id,t=n.size);let r=Pa($c(e.x,!0));if(r.byteLength<t){this.x=new ArrayBuffer(t);let a=new Uint8Array(this.x),o=new Uint8Array(r);a.set(o,1);}else this.x=r.slice(0,t);let i=Pa($c(e.y,!0));if(i.byteLength<t){this.y=new ArrayBuffer(t);let a=new Uint8Array(this.y),o=new Uint8Array(i);a.set(o,1);}else this.y=i.slice(0,t);}};tn.CLASS_NAME="ECPublicKey";var zf="modulus",Yf="publicExponent",O9=[zf,Yf],Mm=class s extends O{constructor(e={}){super(),this.modulus=d(e,zf,s.defaultValues(zf)),this.publicExponent=d(e,Yf,s.defaultValues(Yf)),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case zf:return new N;case Yf:return new N;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new N({name:t.modulus||p}),new N({name:t.publicExponent||p})]})}fromSchema(e){V(e,O9);let t=R(e,e,s.schema({names:{modulus:zf,publicExponent:Yf}}));T.assertSchema(t,this.className),this.modulus=t.result.modulus.convertFromDER(256),this.publicExponent=t.result.publicExponent;}toSchema(){return new b({value:[this.modulus.convertToDER(),this.publicExponent]})}toJSON(){return {n:he.ToBase64Url(this.modulus.valueBlock.valueHexView),e:he.ToBase64Url(this.publicExponent.valueBlock.valueHexView)}}fromJSON(e){Re.assert("json",e,"n","e");let t=Pa($c(e.n,!0));this.modulus=new N({valueHex:t.slice(0,Math.pow(2,G8(t.byteLength)))}),this.publicExponent=new N({valueHex:Pa($c(e.e,!0)).slice(0,3)});}};Mm.CLASS_NAME="RSAPublicKey";var Zf="algorithm",Qf="subjectPublicKey",R9=[Zf,Qf],As=class s extends O{get parsedKey(){if(this._parsedKey===void 0){switch(this.algorithm.algorithmId){case"1.2.840.10045.2.1":if("algorithmParams"in this.algorithm&&this.algorithm.algorithmParams.constructor.blockName()===G.blockName())try{this._parsedKey=new tn({namedCurve:this.algorithm.algorithmParams.valueBlock.toString(),schema:this.subjectPublicKey.valueBlock.valueHexView});}catch{}break;case"1.2.840.113549.1.1.1":{let e=ht(this.subjectPublicKey.valueBlock.valueHexView);if(e.offset!==-1)try{this._parsedKey=new Mm({schema:e.result});}catch{}}break}this._parsedKey||(this._parsedKey=null);}return this._parsedKey||void 0}set parsedKey(e){this._parsedKey=e;}constructor(e={}){super(),this.algorithm=d(e,Zf,s.defaultValues(Zf)),this.subjectPublicKey=d(e,Qf,s.defaultValues(Qf));let t=d(e,"parsedKey",null);t&&(this.parsedKey=t),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Zf:return new P;case Qf:return new Ae;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.algorithm||{}),new Ae({name:t.subjectPublicKey||p})]})}fromSchema(e){V(e,R9);let t=R(e,e,s.schema({names:{algorithm:{names:{blockName:Zf}},subjectPublicKey:Qf}}));T.assertSchema(t,this.className),this.algorithm=new P({schema:t.result.algorithm}),this.subjectPublicKey=t.result.subjectPublicKey;}toSchema(){return new b({value:[this.algorithm.toSchema(),this.subjectPublicKey]})}toJSON(){if(!this.parsedKey)return {algorithm:this.algorithm.toJSON(),subjectPublicKey:this.subjectPublicKey.toJSON()};let e={};switch(this.algorithm.algorithmId){case"1.2.840.10045.2.1":e.kty="EC";break;case"1.2.840.113549.1.1.1":e.kty="RSA";break}let t=this.parsedKey.toJSON();return Object.assign(e,t),e}fromJSON(e){if("kty"in e){switch(e.kty.toUpperCase()){case"EC":this.parsedKey=new tn({json:e}),this.algorithm=new P({algorithmId:"1.2.840.10045.2.1",algorithmParams:new G({value:this.parsedKey.namedCurve})});break;case"RSA":this.parsedKey=new Mm({json:e}),this.algorithm=new P({algorithmId:"1.2.840.113549.1.1.1",algorithmParams:new Xe});break;default:throw new Error(`Invalid value for "kty" parameter: ${e.kty}`)}this.subjectPublicKey=new Ae({valueHex:this.parsedKey.toSchema().toBER(!1)});}}async importKey(e,t=ve(!0)){try{if(!e)throw new Error("Need to provide publicKey input parameter");let n=await t.exportKey("spki",e),r=ht(n);try{this.fromSchema(r.result);}catch{throw new Error("Error during initializing object from schema")}}catch(n){let r=n instanceof Error?n.message:`${n}`;throw new Error(`Error during exporting public key: ${r}`)}}};As.CLASS_NAME="PublicKeyInfo";var au="version",ou="privateKey",Ys="namedCurve",hi="publicKey",V9=[au,ou,Ys,hi],$m=class s extends O{constructor(e={}){super(),this.version=d(e,au,s.defaultValues(au)),this.privateKey=d(e,ou,s.defaultValues(ou)),Ys in e&&(this.namedCurve=d(e,Ys,s.defaultValues(Ys))),hi in e&&(this.publicKey=d(e,hi,s.defaultValues(hi))),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case au:return 1;case ou:return new U;case Ys:return p;case hi:return new tn;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case au:return t===s.defaultValues(e);case ou:return t.isEqual(s.defaultValues(e));case Ys:return t===p;case hi:return tn.compareWithDefault(Ys,t.namedCurve)&&tn.compareWithDefault("x",t.x)&&tn.compareWithDefault("y",t.y);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new N({name:t.version||p}),new U({name:t.privateKey||p}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new G({name:t.namedCurve||p})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new Ae({name:t.publicKey||p})]})]})}fromSchema(e){V(e,V9);let t=R(e,e,s.schema({names:{version:au,privateKey:ou,namedCurve:Ys,publicKey:hi}}));if(T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.privateKey=t.result.privateKey,Ys in t.result&&(this.namedCurve=t.result.namedCurve.valueBlock.toString()),hi in t.result){let n={schema:t.result.publicKey.valueBlock.valueHex};Ys in this&&(n.namedCurve=this.namedCurve),this.publicKey=new tn(n);}}toSchema(){let e=[new N({value:this.version}),this.privateKey];return this.namedCurve&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[new G({value:this.namedCurve})]})),this.publicKey&&e.push(new A({idBlock:{tagClass:3,tagNumber:1},value:[new Ae({valueHex:this.publicKey.toSchema().toBER(!1)})]})),new b({value:e})}toJSON(){if(!this.namedCurve||s.compareWithDefault(Ys,this.namedCurve))throw new Error('Not enough information for making JSON: absent "namedCurve" value');let e=Sn.find(this.namedCurve),t={crv:e?e.name:this.namedCurve,d:he.ToBase64Url(this.privateKey.valueBlock.valueHexView)};if(this.publicKey){let n=this.publicKey.toJSON();t.x=n.x,t.y=n.y;}return t}fromJSON(e){Re.assert("json",e,"crv","d");let t=0,n=Sn.find(e.crv);n&&(this.namedCurve=n.id,t=n.size);let r=he.FromBase64Url(e.d);if(r.byteLength<t){let i=new ArrayBuffer(t),a=new Uint8Array(i),o=new Uint8Array(r);a.set(o,1),this.privateKey=new U({valueHex:i});}else this.privateKey=new U({valueHex:r.slice(0,t)});e.x&&e.y&&(this.publicKey=new tn({json:e}));}};$m.CLASS_NAME="ECPrivateKey";var Xf="prime",ed="exponent",td="coefficient",D9=[Xf,ed,td],Sl=class s extends O{constructor(e={}){super(),this.prime=d(e,Xf,s.defaultValues(Xf)),this.exponent=d(e,ed,s.defaultValues(ed)),this.coefficient=d(e,td,s.defaultValues(td)),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Xf:return new N;case ed:return new N;case td:return new N;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new N({name:t.prime||p}),new N({name:t.exponent||p}),new N({name:t.coefficient||p})]})}fromSchema(e){V(e,D9);let t=R(e,e,s.schema({names:{prime:Xf,exponent:ed,coefficient:td}}));T.assertSchema(t,this.className),this.prime=t.result.prime.convertFromDER(),this.exponent=t.result.exponent.convertFromDER(),this.coefficient=t.result.coefficient.convertFromDER();}toSchema(){return new b({value:[this.prime.convertToDER(),this.exponent.convertToDER(),this.coefficient.convertToDER()]})}toJSON(){return {r:he.ToBase64Url(this.prime.valueBlock.valueHexView),d:he.ToBase64Url(this.exponent.valueBlock.valueHexView),t:he.ToBase64Url(this.coefficient.valueBlock.valueHexView)}}fromJSON(e){Re.assert("json",e,"r","d","r"),this.prime=new N({valueHex:he.FromBase64Url(e.r)}),this.exponent=new N({valueHex:he.FromBase64Url(e.d)}),this.coefficient=new N({valueHex:he.FromBase64Url(e.t)});}};Sl.CLASS_NAME="OtherPrimeInfo";var sd="version",nd="modulus",rd="publicExponent",id="privateExponent",ad="prime1",od="prime2",cd="exponent1",ud="exponent2",ld="coefficient",za="otherPrimeInfos",U9=[sd,nd,rd,id,ad,od,cd,ud,ld,za],qm=class s extends O{constructor(e={}){super(),this.version=d(e,sd,s.defaultValues(sd)),this.modulus=d(e,nd,s.defaultValues(nd)),this.publicExponent=d(e,rd,s.defaultValues(rd)),this.privateExponent=d(e,id,s.defaultValues(id)),this.prime1=d(e,ad,s.defaultValues(ad)),this.prime2=d(e,od,s.defaultValues(od)),this.exponent1=d(e,cd,s.defaultValues(cd)),this.exponent2=d(e,ud,s.defaultValues(ud)),this.coefficient=d(e,ld,s.defaultValues(ld)),za in e&&(this.otherPrimeInfos=d(e,za,s.defaultValues(za))),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case sd:return 0;case nd:return new N;case rd:return new N;case id:return new N;case ad:return new N;case od:return new N;case cd:return new N;case ud:return new N;case ld:return new N;case za:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new N({name:t.version||p}),new N({name:t.modulus||p}),new N({name:t.publicExponent||p}),new N({name:t.privateExponent||p}),new N({name:t.prime1||p}),new N({name:t.prime2||p}),new N({name:t.exponent1||p}),new N({name:t.exponent2||p}),new N({name:t.coefficient||p}),new b({optional:!0,value:[new fe({name:t.otherPrimeInfosName||p,value:Sl.schema(t.otherPrimeInfo||{})})]})]})}fromSchema(e){V(e,U9);let t=R(e,e,s.schema({names:{version:sd,modulus:nd,publicExponent:rd,privateExponent:id,prime1:ad,prime2:od,exponent1:cd,exponent2:ud,coefficient:ld,otherPrimeInfo:{names:{blockName:za}}}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.modulus=t.result.modulus.convertFromDER(256),this.publicExponent=t.result.publicExponent,this.privateExponent=t.result.privateExponent.convertFromDER(256),this.prime1=t.result.prime1.convertFromDER(128),this.prime2=t.result.prime2.convertFromDER(128),this.exponent1=t.result.exponent1.convertFromDER(128),this.exponent2=t.result.exponent2.convertFromDER(128),this.coefficient=t.result.coefficient.convertFromDER(128),za in t.result&&(this.otherPrimeInfos=Array.from(t.result.otherPrimeInfos,n=>new Sl({schema:n})));}toSchema(){let e=[];return e.push(new N({value:this.version})),e.push(this.modulus.convertToDER()),e.push(this.publicExponent),e.push(this.privateExponent.convertToDER()),e.push(this.prime1.convertToDER()),e.push(this.prime2.convertToDER()),e.push(this.exponent1.convertToDER()),e.push(this.exponent2.convertToDER()),e.push(this.coefficient.convertToDER()),this.otherPrimeInfos&&e.push(new b({value:Array.from(this.otherPrimeInfos,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={n:he.ToBase64Url(this.modulus.valueBlock.valueHexView),e:he.ToBase64Url(this.publicExponent.valueBlock.valueHexView),d:he.ToBase64Url(this.privateExponent.valueBlock.valueHexView),p:he.ToBase64Url(this.prime1.valueBlock.valueHexView),q:he.ToBase64Url(this.prime2.valueBlock.valueHexView),dp:he.ToBase64Url(this.exponent1.valueBlock.valueHexView),dq:he.ToBase64Url(this.exponent2.valueBlock.valueHexView),qi:he.ToBase64Url(this.coefficient.valueBlock.valueHexView)};return this.otherPrimeInfos&&(e.oth=Array.from(this.otherPrimeInfos,t=>t.toJSON())),e}fromJSON(e){Re.assert("json",e,"n","e","d","p","q","dp","dq","qi"),this.modulus=new N({valueHex:he.FromBase64Url(e.n)}),this.publicExponent=new N({valueHex:he.FromBase64Url(e.e)}),this.privateExponent=new N({valueHex:he.FromBase64Url(e.d)}),this.prime1=new N({valueHex:he.FromBase64Url(e.p)}),this.prime2=new N({valueHex:he.FromBase64Url(e.q)}),this.exponent1=new N({valueHex:he.FromBase64Url(e.dp)}),this.exponent2=new N({valueHex:he.FromBase64Url(e.dq)}),this.coefficient=new N({valueHex:he.FromBase64Url(e.qi)}),e.oth&&(this.otherPrimeInfos=Array.from(e.oth,t=>new Sl({json:t})));}};qm.CLASS_NAME="RSAPrivateKey";var hd="version",fd="privateKeyAlgorithm",dd="privateKey",Ya="attributes",sy="parsedKey",L9=[hd,fd,dd,Ya],Yo=class s extends O{constructor(e={}){super(),this.version=d(e,hd,s.defaultValues(hd)),this.privateKeyAlgorithm=d(e,fd,s.defaultValues(fd)),this.privateKey=d(e,dd,s.defaultValues(dd)),Ya in e&&(this.attributes=d(e,Ya,s.defaultValues(Ya))),sy in e&&(this.parsedKey=d(e,sy,s.defaultValues(sy))),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case hd:return 0;case fd:return new P;case dd:return new U;case Ya:return [];case sy:return {};default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new N({name:t.version||p}),P.schema(t.privateKeyAlgorithm||{}),new U({name:t.privateKey||p}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new fe({name:t.attributes||p,value:nt.schema()})]})]})}fromSchema(e){V(e,L9);let t=R(e,e,s.schema({names:{version:hd,privateKeyAlgorithm:{names:{blockName:fd}},privateKey:dd,attributes:Ya}}));switch(T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.privateKeyAlgorithm=new P({schema:t.result.privateKeyAlgorithm}),this.privateKey=t.result.privateKey,Ya in t.result&&(this.attributes=Array.from(t.result.attributes,n=>new nt({schema:n}))),this.privateKeyAlgorithm.algorithmId){case"1.2.840.113549.1.1.1":{let n=ht(this.privateKey.valueBlock.valueHexView);n.offset!==-1&&(this.parsedKey=new qm({schema:n.result}));}break;case"1.2.840.10045.2.1":if("algorithmParams"in this.privateKeyAlgorithm&&this.privateKeyAlgorithm.algorithmParams instanceof G){let n=ht(this.privateKey.valueBlock.valueHexView);n.offset!==-1&&(this.parsedKey=new $m({namedCurve:this.privateKeyAlgorithm.algorithmParams.valueBlock.toString(),schema:n.result}));}break}}toSchema(){let e=[new N({value:this.version}),this.privateKeyAlgorithm.toSchema(),this.privateKey];return this.attributes&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.attributes,t=>t.toSchema())})),new b({value:e})}toJSON(){if(!this.parsedKey){let n={version:this.version,privateKeyAlgorithm:this.privateKeyAlgorithm.toJSON(),privateKey:this.privateKey.toJSON()};return this.attributes&&(n.attributes=Array.from(this.attributes,r=>r.toJSON())),n}let e={};switch(this.privateKeyAlgorithm.algorithmId){case"1.2.840.10045.2.1":e.kty="EC";break;case"1.2.840.113549.1.1.1":e.kty="RSA";break}let t=this.parsedKey.toJSON();return Object.assign(e,t),e}fromJSON(e){if("kty"in e){switch(e.kty.toUpperCase()){case"EC":this.parsedKey=new $m({json:e}),this.privateKeyAlgorithm=new P({algorithmId:"1.2.840.10045.2.1",algorithmParams:new G({value:this.parsedKey.namedCurve})});break;case"RSA":this.parsedKey=new qm({json:e}),this.privateKeyAlgorithm=new P({algorithmId:"1.2.840.113549.1.1.1",algorithmParams:new Xe});break;default:throw new Error(`Invalid value for "kty" parameter: ${e.kty}`)}this.privateKey=new U({valueHex:this.parsedKey.toSchema().toBER(!1)});}}};Yo.CLASS_NAME="PrivateKeyInfo";var cu="contentType",uu="contentEncryptionAlgorithm",Za="encryptedContent",j9=[cu,uu,Za],HN=1024,kt=class s extends O{constructor(e={}){if(super(),this.contentType=d(e,cu,s.defaultValues(cu)),this.contentEncryptionAlgorithm=d(e,uu,s.defaultValues(uu)),Za in e&&e.encryptedContent&&(this.encryptedContent=e.encryptedContent,this.encryptedContent.idBlock.tagClass===1&&this.encryptedContent.idBlock.tagNumber===4&&this.encryptedContent.idBlock.isConstructed===!1&&!e.disableSplit)){let t=new U({idBlock:{isConstructed:!0},isConstructed:!0}),n=0,r=this.encryptedContent.valueBlock.valueHexView.slice().buffer,i=r.byteLength;for(;i>0;){let a=new Uint8Array(r,n,n+HN>r.byteLength?r.byteLength-n:HN),o=new ArrayBuffer(a.length),c=new Uint8Array(o);for(let u=0;u<c.length;u++)c[u]=a[u];t.valueBlock.value.push(new U({valueHex:o})),i-=a.length,n+=a.length;}this.encryptedContent=t;}e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case cu:return p;case uu:return new P;case Za:return new U;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case cu:return t===p;case uu:return t.algorithmId===p&&!("algorithmParams"in t);case Za:return t.isEqual(s.defaultValues(Za));default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.contentType||p}),P.schema(t.contentEncryptionAlgorithm||{}),new We({value:[new A({name:t.encryptedContent||p,idBlock:{tagClass:3,tagNumber:0},value:[new fe({value:new U})]}),new ie({name:t.encryptedContent||p,idBlock:{tagClass:3,tagNumber:0}})]})]})}fromSchema(e){V(e,j9);let t=R(e,e,s.schema({names:{contentType:cu,contentEncryptionAlgorithm:{names:{blockName:uu}},encryptedContent:Za}}));T.assertSchema(t,this.className),this.contentType=t.result.contentType.valueBlock.toString(),this.contentEncryptionAlgorithm=new P({schema:t.result.contentEncryptionAlgorithm}),Za in t.result&&(this.encryptedContent=t.result.encryptedContent,this.encryptedContent.idBlock.tagClass=1,this.encryptedContent.idBlock.tagNumber=4);}toSchema(){let e={isIndefiniteForm:!1},t=[];if(t.push(new G({value:this.contentType})),t.push(this.contentEncryptionAlgorithm.toSchema()),this.encryptedContent){e.isIndefiniteForm=this.encryptedContent.idBlock.isConstructed;let n=this.encryptedContent;n.idBlock.tagClass=3,n.idBlock.tagNumber=0,n.lenBlock.isIndefiniteForm=this.encryptedContent.idBlock.isConstructed,t.push(n);}return new b({lenBlock:e,value:t})}toJSON(){let e={contentType:this.contentType,contentEncryptionAlgorithm:this.contentEncryptionAlgorithm.toJSON()};return this.encryptedContent&&(e.encryptedContent=this.encryptedContent.toJSON()),e}getEncryptedContent(){if(!this.encryptedContent)throw new Error("Parameter 'encryptedContent' is undefined");return U.prototype.getValue.call(this.encryptedContent)}};kt.CLASS_NAME="EncryptedContentInfo";var fi="hashAlgorithm",di="maskGenAlgorithm",mi="saltLength",pi="trailerField",H9=[fi,di,mi,pi],vl=class s extends O{constructor(e={}){super(),this.hashAlgorithm=d(e,fi,s.defaultValues(fi)),this.maskGenAlgorithm=d(e,di,s.defaultValues(di)),this.saltLength=d(e,mi,s.defaultValues(mi)),this.trailerField=d(e,pi,s.defaultValues(pi)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case fi:return new P({algorithmId:"1.3.14.3.2.26",algorithmParams:new Xe});case di:return new P({algorithmId:"1.2.840.113549.1.1.8",algorithmParams:new P({algorithmId:"1.3.14.3.2.26",algorithmParams:new Xe}).toSchema()});case mi:return 20;case pi:return 1;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new A({idBlock:{tagClass:3,tagNumber:0},optional:!0,value:[P.schema(t.hashAlgorithm||{})]}),new A({idBlock:{tagClass:3,tagNumber:1},optional:!0,value:[P.schema(t.maskGenAlgorithm||{})]}),new A({idBlock:{tagClass:3,tagNumber:2},optional:!0,value:[new N({name:t.saltLength||p})]}),new A({idBlock:{tagClass:3,tagNumber:3},optional:!0,value:[new N({name:t.trailerField||p})]})]})}fromSchema(e){V(e,H9);let t=R(e,e,s.schema({names:{hashAlgorithm:{names:{blockName:fi}},maskGenAlgorithm:{names:{blockName:di}},saltLength:mi,trailerField:pi}}));T.assertSchema(t,this.className),fi in t.result&&(this.hashAlgorithm=new P({schema:t.result.hashAlgorithm})),di in t.result&&(this.maskGenAlgorithm=new P({schema:t.result.maskGenAlgorithm})),mi in t.result&&(this.saltLength=t.result.saltLength.valueBlock.valueDec),pi in t.result&&(this.trailerField=t.result.trailerField.valueBlock.valueDec);}toSchema(){let e=[];return this.hashAlgorithm.isEqual(s.defaultValues(fi))||e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[this.hashAlgorithm.toSchema()]})),this.maskGenAlgorithm.isEqual(s.defaultValues(di))||e.push(new A({idBlock:{tagClass:3,tagNumber:1},value:[this.maskGenAlgorithm.toSchema()]})),this.saltLength!==s.defaultValues(mi)&&e.push(new A({idBlock:{tagClass:3,tagNumber:2},value:[new N({value:this.saltLength})]})),this.trailerField!==s.defaultValues(pi)&&e.push(new A({idBlock:{tagClass:3,tagNumber:3},value:[new N({value:this.trailerField})]})),new b({value:e})}toJSON(){let e={};return this.hashAlgorithm.isEqual(s.defaultValues(fi))||(e.hashAlgorithm=this.hashAlgorithm.toJSON()),this.maskGenAlgorithm.isEqual(s.defaultValues(di))||(e.maskGenAlgorithm=this.maskGenAlgorithm.toJSON()),this.saltLength!==s.defaultValues(mi)&&(e.saltLength=this.saltLength),this.trailerField!==s.defaultValues(pi)&&(e.trailerField=this.trailerField),e}};vl.CLASS_NAME="RSASSAPSSParams";var lu="salt",md="iterationCount",Zs="keyLength",nr="prf",_9=[lu,md,Zs,nr],$i=class s extends O{constructor(e={}){super(),this.salt=d(e,lu,s.defaultValues(lu)),this.iterationCount=d(e,md,s.defaultValues(md)),Zs in e&&(this.keyLength=d(e,Zs,s.defaultValues(Zs))),nr in e&&(this.prf=d(e,nr,s.defaultValues(nr))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case lu:return {};case md:return -1;case Zs:return 0;case nr:return new P({algorithmId:"1.3.14.3.2.26",algorithmParams:new Xe});default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new We({value:[new U({name:t.saltPrimitive||p}),P.schema(t.saltConstructed||{})]}),new N({name:t.iterationCount||p}),new N({name:t.keyLength||p,optional:!0}),P.schema(t.prf||{names:{optional:!0}})]})}fromSchema(e){V(e,_9);let t=R(e,e,s.schema({names:{saltPrimitive:lu,saltConstructed:{names:{blockName:lu}},iterationCount:md,keyLength:Zs,prf:{names:{blockName:nr,optional:!0}}}}));T.assertSchema(t,this.className),this.salt=t.result.salt,this.iterationCount=t.result.iterationCount.valueBlock.valueDec,Zs in t.result&&(this.keyLength=t.result.keyLength.valueBlock.valueDec),nr in t.result&&(this.prf=new P({schema:t.result.prf}));}toSchema(){let e=[];return e.push(this.salt),e.push(new N({value:this.iterationCount})),Zs in this&&s.defaultValues(Zs)!==this.keyLength&&e.push(new N({value:this.keyLength})),this.prf&&s.defaultValues(nr).isEqual(this.prf)===!1&&e.push(this.prf.toSchema()),new b({value:e})}toJSON(){let e={salt:this.salt.toJSON(),iterationCount:this.iterationCount};return Zs in this&&s.defaultValues(Zs)!==this.keyLength&&(e.keyLength=this.keyLength),this.prf&&s.defaultValues(nr).isEqual(this.prf)===!1&&(e.prf=this.prf.toJSON()),e}};$i.CLASS_NAME="PBKDF2Params";var pd="keyDerivationFunc",gd="encryptionScheme",M9=[pd,gd],Fm=class s extends O{constructor(e={}){super(),this.keyDerivationFunc=d(e,pd,s.defaultValues(pd)),this.encryptionScheme=d(e,gd,s.defaultValues(gd)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case pd:return new P;case gd:return new P;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.keyDerivationFunc||{}),P.schema(t.encryptionScheme||{})]})}fromSchema(e){V(e,M9);let t=R(e,e,s.schema({names:{keyDerivationFunc:{names:{blockName:pd}},encryptionScheme:{names:{blockName:gd}}}}));T.assertSchema(t,this.className),this.keyDerivationFunc=new P({schema:t.result.keyDerivationFunc}),this.encryptionScheme=new P({schema:t.result.encryptionScheme});}toSchema(){return new b({value:[this.keyDerivationFunc.toSchema(),this.encryptionScheme.toSchema()]})}toJSON(){return {keyDerivationFunc:this.keyDerivationFunc.toJSON(),encryptionScheme:this.encryptionScheme.toJSON()}}};Fm.CLASS_NAME="PBES2Params";var j2=class{constructor(e){this.crypto=e.crypto,this.subtle="webkitSubtle"in e.crypto?e.crypto.webkitSubtle:e.crypto.subtle,this.name=d(e,"name",p);}async encrypt(...e){return this.subtle.encrypt(...e)}async decrypt(...e){return this.subtle.decrypt(...e)}sign(...e){return this.subtle.sign(...e)}async verify(...e){return this.subtle.verify(...e)}async digest(...e){return this.subtle.digest(...e)}async generateKey(...e){return this.subtle.generateKey(...e)}async deriveKey(...e){return this.subtle.deriveKey(...e)}async deriveBits(...e){return this.subtle.deriveBits(...e)}async wrapKey(...e){return this.subtle.wrapKey(...e)}async unwrapKey(...e){return this.subtle.unwrapKey(...e)}exportKey(...e){return this.subtle.exportKey(...e)}importKey(...e){return this.subtle.importKey(...e)}getRandomValues(e){if(e===null)throw new Error('Argument "array" must not be null');return this.crypto.getRandomValues(e)}};async function _N(s,e,t,n,r){let i,a,o;switch(s.toUpperCase()){case"SHA-1":i=20,a=64,o=ON;break;case"SHA-256":i=32,a=64,o=s2;break;case"SHA-384":i=48,a=128,o=a2;break;case"SHA-512":i=64,a=128,o=i2;break;default:throw new Error("Unsupported hashing algorithm")}let c=new Uint8Array(t),u=new TextDecoder().decode(t);new TextEncoder().encode(u).some((v,I)=>v!==c[I])&&(u=String.fromCharCode(...c));let h=new Uint8Array(u.length*2+2),m=new DataView(h.buffer);for(let v=0;v<u.length;v++)m.setUint16(v*2,u.charCodeAt(v),!1);m.setUint16(u.length*2,0,!1);let y=new Uint8Array(a).fill(3),g=new Uint8Array(n),w=new Uint8Array(a*Math.ceil(g.length/a)).map((v,I)=>g[I%g.length]),S=new Uint8Array(a*Math.ceil(h.length/a)).map((v,I)=>h[I%h.length]),C=new Uint8Array(w.length+S.length);C.set(w),C.set(S,w.length);let k=Math.ceil((e>>3)/i),x=[];for(let v=0;v<k;v++){let I=new Uint8Array(y.length+C.length);I.set(y),I.set(C,y.length);for(let W=0;W<r;W++)I=o(I);let D=new Uint8Array(a).map((W,ne)=>I[ne%I.length]),F=Math.ceil(g.length/a)+Math.ceil(h.length/a),M=[];for(let W=0;W<F;W++){let ne=Array.from(C.slice(W*a,(W+1)*a)),q=511;for(let J=D.length-1;J>=0;J--)q>>=8,q+=D[J]+(ne[J]||0),ne[J]=q&255;M.push(...ne);}C=new Uint8Array(M),x.push(...I);}return new Uint8Array(x.slice(0,e>>3)).buffer}function vk(s){let e=typeof s=="string"?{name:s}:s;return "hash"in e?{...e,hash:vk(e.hash)}:e}var kl=class extends j2{async importKey(e,t,n,r,i){var a,o,c,u,l,h;let m={},y=vk(n);switch(e.toLowerCase()){case"raw":return this.subtle.importKey("raw",t,n,r,i);case"spki":{let g=ht(re.toArrayBuffer(t));T.assert(g,"keyData");let w=new As;try{w.fromSchema(g.result);}catch{throw new $e("Incorrect keyData")}switch(y.name.toUpperCase()){case"RSA-PSS":{if(!y.hash)throw new Re("hash","algorithm.hash","Incorrect hash algorithm: Hash algorithm is missed");switch(y.hash.name.toUpperCase()){case"SHA-1":m.alg="PS1";break;case"SHA-256":m.alg="PS256";break;case"SHA-384":m.alg="PS384";break;case"SHA-512":m.alg="PS512";break;default:throw new Error(`Incorrect hash algorithm: ${y.hash.name.toUpperCase()}`)}}case"RSASSA-PKCS1-V1_5":{if(i=["verify"],m.kty="RSA",m.ext=r,m.key_ops=i,w.algorithm.algorithmId!=="1.2.840.113549.1.1.1")throw new Error(`Incorrect public key algorithm: ${w.algorithm.algorithmId}`);if(!m.alg){if(!y.hash)throw new Re("hash","algorithm.hash","Incorrect hash algorithm: Hash algorithm is missed");switch(y.hash.name.toUpperCase()){case"SHA-1":m.alg="RS1";break;case"SHA-256":m.alg="RS256";break;case"SHA-384":m.alg="RS384";break;case"SHA-512":m.alg="RS512";break;default:throw new Error(`Incorrect hash algorithm: ${y.hash.name.toUpperCase()}`)}}let S=w.toJSON();Object.assign(m,S);}break;case"ECDSA":i=["verify"];case"ECDH":{if(m={kty:"EC",ext:r,key_ops:i},w.algorithm.algorithmId!=="1.2.840.10045.2.1")throw new Error(`Incorrect public key algorithm: ${w.algorithm.algorithmId}`);let S=w.toJSON();Object.assign(m,S);}break;case"RSA-OAEP":{if(m.kty="RSA",m.ext=r,m.key_ops=i,this.name.toLowerCase()==="safari")m.alg="RSA-OAEP";else {if(!y.hash)throw new Re("hash","algorithm.hash","Incorrect hash algorithm: Hash algorithm is missed");switch(y.hash.name.toUpperCase()){case"SHA-1":m.alg="RSA-OAEP";break;case"SHA-256":m.alg="RSA-OAEP-256";break;case"SHA-384":m.alg="RSA-OAEP-384";break;case"SHA-512":m.alg="RSA-OAEP-512";break;default:throw new Error(`Incorrect hash algorithm: ${y.hash.name.toUpperCase()}`)}}let S=w.toJSON();Object.assign(m,S);}break;case"RSAES-PKCS1-V1_5":{m.kty="RSA",m.ext=r,m.key_ops=i,m.alg="PS1";let S=w.toJSON();Object.assign(m,S);}break;default:throw new Error(`Incorrect algorithm name: ${y.name.toUpperCase()}`)}}break;case"pkcs8":{let g=new Yo,w=ht(re.toArrayBuffer(t));T.assert(w,"keyData");try{g.fromSchema(w.result);}catch{throw new Error("Incorrect keyData")}if(!g.parsedKey)throw new Error("Incorrect keyData");switch(y.name.toUpperCase()){case"RSA-PSS":switch((a=y.hash)===null||a===void 0?void 0:a.name.toUpperCase()){case"SHA-1":m.alg="PS1";break;case"SHA-256":m.alg="PS256";break;case"SHA-384":m.alg="PS384";break;case"SHA-512":m.alg="PS512";break;default:throw new Error(`Incorrect hash algorithm: ${(o=y.hash)===null||o===void 0?void 0:o.name.toUpperCase()}`)}case"RSASSA-PKCS1-V1_5":{if(i=["sign"],m.kty="RSA",m.ext=r,m.key_ops=i,g.privateKeyAlgorithm.algorithmId!=="1.2.840.113549.1.1.1")throw new Error(`Incorrect private key algorithm: ${g.privateKeyAlgorithm.algorithmId}`);if(!("alg"in m))switch((c=y.hash)===null||c===void 0?void 0:c.name.toUpperCase()){case"SHA-1":m.alg="RS1";break;case"SHA-256":m.alg="RS256";break;case"SHA-384":m.alg="RS384";break;case"SHA-512":m.alg="RS512";break;default:throw new Error(`Incorrect hash algorithm: ${(u=y.hash)===null||u===void 0?void 0:u.name.toUpperCase()}`)}let S=g.toJSON();Object.assign(m,S);}break;case"ECDSA":i=["sign"];case"ECDH":{if(m={kty:"EC",ext:r,key_ops:i},g.privateKeyAlgorithm.algorithmId!=="1.2.840.10045.2.1")throw new Error(`Incorrect algorithm: ${g.privateKeyAlgorithm.algorithmId}`);let S=g.toJSON();Object.assign(m,S);}break;case"RSA-OAEP":{if(m.kty="RSA",m.ext=r,m.key_ops=i,this.name.toLowerCase()==="safari")m.alg="RSA-OAEP";else switch((l=y.hash)===null||l===void 0?void 0:l.name.toUpperCase()){case"SHA-1":m.alg="RSA-OAEP";break;case"SHA-256":m.alg="RSA-OAEP-256";break;case"SHA-384":m.alg="RSA-OAEP-384";break;case"SHA-512":m.alg="RSA-OAEP-512";break;default:throw new Error(`Incorrect hash algorithm: ${(h=y.hash)===null||h===void 0?void 0:h.name.toUpperCase()}`)}let S=g.toJSON();Object.assign(m,S);}break;case"RSAES-PKCS1-V1_5":{i=["decrypt"],m.kty="RSA",m.ext=r,m.key_ops=i,m.alg="PS1";let S=g.toJSON();Object.assign(m,S);}break;default:throw new Error(`Incorrect algorithm name: ${y.name.toUpperCase()}`)}}break;case"jwk":m=t;break;default:throw new Error(`Incorrect format: ${e}`)}if(this.name.toLowerCase()==="safari")try{return this.subtle.importKey("jwk",Pa(JSON.stringify(m)),n,r,i)}catch{return this.subtle.importKey("jwk",m,n,r,i)}return this.subtle.importKey("jwk",m,n,r,i)}async exportKey(e,t){let n=await this.subtle.exportKey("jwk",t);switch(this.name.toLowerCase()==="safari"&&n instanceof ArrayBuffer&&(n=JSON.parse(uf(n))),e.toLowerCase()){case"raw":return this.subtle.exportKey("raw",t);case"spki":{let r=new As;try{r.fromJSON(n);}catch{throw new Error("Incorrect key data")}return r.toSchema().toBER(!1)}case"pkcs8":{let r=new Yo;try{r.fromJSON(n);}catch{throw new Error("Incorrect key data")}return r.toSchema().toBER(!1)}case"jwk":return n;default:throw new Error(`Incorrect format: ${e}`)}}async convert(e,t,n,r,i,a){if(e.toLowerCase()===t.toLowerCase())return n;let o=await this.importKey(e,n,r,i,a);return this.exportKey(t,o)}getAlgorithmByOID(e,t=!1,n){switch(e){case"1.2.840.113549.1.1.1":return {name:"RSAES-PKCS1-v1_5"};case"1.2.840.113549.1.1.5":return {name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case"1.2.840.113549.1.1.11":return {name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"1.2.840.113549.1.1.12":return {name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case"1.2.840.113549.1.1.13":return {name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case"1.2.840.113549.1.1.10":return {name:"RSA-PSS"};case"1.2.840.113549.1.1.7":return {name:"RSA-OAEP"};case"1.2.840.10045.2.1":case"1.2.840.10045.4.1":return {name:"ECDSA",hash:{name:"SHA-1"}};case"1.2.840.10045.4.3.2":return {name:"ECDSA",hash:{name:"SHA-256"}};case"1.2.840.10045.4.3.3":return {name:"ECDSA",hash:{name:"SHA-384"}};case"1.2.840.10045.4.3.4":return {name:"ECDSA",hash:{name:"SHA-512"}};case"1.3.133.16.840.63.0.2":return {name:"ECDH",kdf:"SHA-1"};case"1.3.132.1.11.1":return {name:"ECDH",kdf:"SHA-256"};case"1.3.132.1.11.2":return {name:"ECDH",kdf:"SHA-384"};case"1.3.132.1.11.3":return {name:"ECDH",kdf:"SHA-512"};case"2.16.840.1.101.3.4.1.2":return {name:"AES-CBC",length:128};case"2.16.840.1.101.3.4.1.22":return {name:"AES-CBC",length:192};case"2.16.840.1.101.3.4.1.42":return {name:"AES-CBC",length:256};case"2.16.840.1.101.3.4.1.6":return {name:"AES-GCM",length:128};case"2.16.840.1.101.3.4.1.26":return {name:"AES-GCM",length:192};case"2.16.840.1.101.3.4.1.46":return {name:"AES-GCM",length:256};case"2.16.840.1.101.3.4.1.4":return {name:"AES-CFB",length:128};case"2.16.840.1.101.3.4.1.24":return {name:"AES-CFB",length:192};case"2.16.840.1.101.3.4.1.44":return {name:"AES-CFB",length:256};case"2.16.840.1.101.3.4.1.5":return {name:"AES-KW",length:128};case"2.16.840.1.101.3.4.1.25":return {name:"AES-KW",length:192};case"2.16.840.1.101.3.4.1.45":return {name:"AES-KW",length:256};case"1.2.840.113549.2.7":return {name:"HMAC",hash:{name:"SHA-1"}};case"1.2.840.113549.2.9":return {name:"HMAC",hash:{name:"SHA-256"}};case"1.2.840.113549.2.10":return {name:"HMAC",hash:{name:"SHA-384"}};case"1.2.840.113549.2.11":return {name:"HMAC",hash:{name:"SHA-512"}};case"1.2.840.113549.1.9.16.3.5":return {name:"DH"};case"1.3.14.3.2.26":return {name:"SHA-1"};case"2.16.840.1.101.3.4.2.1":return {name:"SHA-256"};case"2.16.840.1.101.3.4.2.2":return {name:"SHA-384"};case"2.16.840.1.101.3.4.2.3":return {name:"SHA-512"};case"1.2.840.113549.1.5.12":return {name:"PBKDF2"};case"1.2.840.10045.3.1.7":return {name:"P-256"};case"1.3.132.0.34":return {name:"P-384"};case"1.3.132.0.35":return {name:"P-521"}}if(t)throw new Error(`Unsupported algorithm identifier ${n?`for ${n} `:p}: ${e}`);return {}}getOIDByAlgorithm(e,t=!1,n){let r=p;switch(e.name.toUpperCase()){case"RSAES-PKCS1-V1_5":r="1.2.840.113549.1.1.1";break;case"RSASSA-PKCS1-V1_5":switch(e.hash.name.toUpperCase()){case"SHA-1":r="1.2.840.113549.1.1.5";break;case"SHA-256":r="1.2.840.113549.1.1.11";break;case"SHA-384":r="1.2.840.113549.1.1.12";break;case"SHA-512":r="1.2.840.113549.1.1.13";break}break;case"RSA-PSS":r="1.2.840.113549.1.1.10";break;case"RSA-OAEP":r="1.2.840.113549.1.1.7";break;case"ECDSA":switch(e.hash.name.toUpperCase()){case"SHA-1":r="1.2.840.10045.4.1";break;case"SHA-256":r="1.2.840.10045.4.3.2";break;case"SHA-384":r="1.2.840.10045.4.3.3";break;case"SHA-512":r="1.2.840.10045.4.3.4";break}break;case"ECDH":switch(e.kdf.toUpperCase()){case"SHA-1":r="1.3.133.16.840.63.0.2";break;case"SHA-256":r="1.3.132.1.11.1";break;case"SHA-384":r="1.3.132.1.11.2";break;case"SHA-512":r="1.3.132.1.11.3";break}break;case"AES-CTR":break;case"AES-CBC":switch(e.length){case 128:r="2.16.840.1.101.3.4.1.2";break;case 192:r="2.16.840.1.101.3.4.1.22";break;case 256:r="2.16.840.1.101.3.4.1.42";break}break;case"AES-CMAC":break;case"AES-GCM":switch(e.length){case 128:r="2.16.840.1.101.3.4.1.6";break;case 192:r="2.16.840.1.101.3.4.1.26";break;case 256:r="2.16.840.1.101.3.4.1.46";break}break;case"AES-CFB":switch(e.length){case 128:r="2.16.840.1.101.3.4.1.4";break;case 192:r="2.16.840.1.101.3.4.1.24";break;case 256:r="2.16.840.1.101.3.4.1.44";break}break;case"AES-KW":switch(e.length){case 128:r="2.16.840.1.101.3.4.1.5";break;case 192:r="2.16.840.1.101.3.4.1.25";break;case 256:r="2.16.840.1.101.3.4.1.45";break}break;case"HMAC":switch(e.hash.name.toUpperCase()){case"SHA-1":r="1.2.840.113549.2.7";break;case"SHA-256":r="1.2.840.113549.2.9";break;case"SHA-384":r="1.2.840.113549.2.10";break;case"SHA-512":r="1.2.840.113549.2.11";break}break;case"DH":r="1.2.840.113549.1.9.16.3.5";break;case"SHA-1":r="1.3.14.3.2.26";break;case"SHA-256":r="2.16.840.1.101.3.4.2.1";break;case"SHA-384":r="2.16.840.1.101.3.4.2.2";break;case"SHA-512":r="2.16.840.1.101.3.4.2.3";break;case"CONCAT":break;case"HKDF":break;case"PBKDF2":r="1.2.840.113549.1.5.12";break;case"P-256":r="1.2.840.10045.3.1.7";break;case"P-384":r="1.3.132.0.34";break;case"P-521":r="1.3.132.0.35";break}if(!r&&t)throw new Error(`Unsupported algorithm ${n?`for ${n} `:p}: ${e.name}`);return r}getAlgorithmParameters(e,t){let n={algorithm:{},usages:[]};switch(e.toUpperCase()){case"RSAES-PKCS1-V1_5":case"RSASSA-PKCS1-V1_5":switch(t.toLowerCase()){case"generatekey":n={algorithm:{name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},usages:["sign","verify"]};break;case"verify":case"sign":case"importkey":n={algorithm:{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},usages:["verify"]};break;case"exportkey":default:return {algorithm:{name:"RSASSA-PKCS1-v1_5"},usages:[]}}break;case"RSA-PSS":switch(t.toLowerCase()){case"sign":case"verify":n={algorithm:{name:"RSA-PSS",hash:{name:"SHA-1"},saltLength:20},usages:["sign","verify"]};break;case"generatekey":n={algorithm:{name:"RSA-PSS",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-1"}},usages:["sign","verify"]};break;case"importkey":n={algorithm:{name:"RSA-PSS",hash:{name:"SHA-1"}},usages:["verify"]};break;case"exportkey":default:return {algorithm:{name:"RSA-PSS"},usages:[]}}break;case"RSA-OAEP":switch(t.toLowerCase()){case"encrypt":case"decrypt":n={algorithm:{name:"RSA-OAEP"},usages:["encrypt","decrypt"]};break;case"generatekey":n={algorithm:{name:"RSA-OAEP",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;case"importkey":n={algorithm:{name:"RSA-OAEP",hash:{name:"SHA-256"}},usages:["encrypt"]};break;case"exportkey":default:return {algorithm:{name:"RSA-OAEP"},usages:[]}}break;case"ECDSA":switch(t.toLowerCase()){case"generatekey":n={algorithm:{name:"ECDSA",namedCurve:"P-256"},usages:["sign","verify"]};break;case"importkey":n={algorithm:{name:"ECDSA",namedCurve:"P-256"},usages:["verify"]};break;case"verify":case"sign":n={algorithm:{name:"ECDSA",hash:{name:"SHA-256"}},usages:["sign"]};break;default:return {algorithm:{name:"ECDSA"},usages:[]}}break;case"ECDH":switch(t.toLowerCase()){case"exportkey":case"importkey":case"generatekey":n={algorithm:{name:"ECDH",namedCurve:"P-256"},usages:["deriveKey","deriveBits"]};break;case"derivekey":case"derivebits":n={algorithm:{name:"ECDH",namedCurve:"P-256",public:[]},usages:["encrypt","decrypt"]};break;default:return {algorithm:{name:"ECDH"},usages:[]}}break;case"AES-CTR":switch(t.toLowerCase()){case"importkey":case"exportkey":case"generatekey":n={algorithm:{name:"AES-CTR",length:256},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;case"decrypt":case"encrypt":n={algorithm:{name:"AES-CTR",counter:new Uint8Array(16),length:10},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;default:return {algorithm:{name:"AES-CTR"},usages:[]}}break;case"AES-CBC":switch(t.toLowerCase()){case"importkey":case"exportkey":case"generatekey":n={algorithm:{name:"AES-CBC",length:256},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;case"decrypt":case"encrypt":n={algorithm:{name:"AES-CBC",iv:this.getRandomValues(new Uint8Array(16))},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;default:return {algorithm:{name:"AES-CBC"},usages:[]}}break;case"AES-GCM":switch(t.toLowerCase()){case"importkey":case"exportkey":case"generatekey":n={algorithm:{name:"AES-GCM",length:256},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;case"decrypt":case"encrypt":n={algorithm:{name:"AES-GCM",iv:this.getRandomValues(new Uint8Array(16))},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;default:return {algorithm:{name:"AES-GCM"},usages:[]}}break;case"AES-KW":switch(t.toLowerCase()){case"importkey":case"exportkey":case"generatekey":case"wrapkey":case"unwrapkey":n={algorithm:{name:"AES-KW",length:256},usages:["wrapKey","unwrapKey"]};break;default:return {algorithm:{name:"AES-KW"},usages:[]}}break;case"HMAC":switch(t.toLowerCase()){case"sign":case"verify":n={algorithm:{name:"HMAC"},usages:["sign","verify"]};break;case"importkey":case"exportkey":case"generatekey":n={algorithm:{name:"HMAC",length:32,hash:{name:"SHA-256"}},usages:["sign","verify"]};break;default:return {algorithm:{name:"HMAC"},usages:[]}}break;case"HKDF":switch(t.toLowerCase()){case"derivekey":n={algorithm:{name:"HKDF",hash:"SHA-256",salt:new Uint8Array([]),info:new Uint8Array([])},usages:["encrypt","decrypt"]};break;default:return {algorithm:{name:"HKDF"},usages:[]}}break;case"PBKDF2":switch(t.toLowerCase()){case"derivekey":n={algorithm:{name:"PBKDF2",hash:{name:"SHA-256"},salt:new Uint8Array([]),iterations:1e4},usages:["encrypt","decrypt"]};break;default:return {algorithm:{name:"PBKDF2"},usages:[]}}break}return n}getHashAlgorithm(e){let t=p;switch(e.algorithmId){case"1.2.840.10045.4.1":case"1.2.840.113549.1.1.5":t="SHA-1";break;case"1.2.840.10045.4.3.2":case"1.2.840.113549.1.1.11":t="SHA-256";break;case"1.2.840.10045.4.3.3":case"1.2.840.113549.1.1.12":t="SHA-384";break;case"1.2.840.10045.4.3.4":case"1.2.840.113549.1.1.13":t="SHA-512";break;case"1.2.840.113549.1.1.10":try{let n=new vl({schema:e.algorithmParams});if(n.hashAlgorithm){let r=this.getAlgorithmByOID(n.hashAlgorithm.algorithmId);if("name"in r)t=r.name;else return p}else t="SHA-1";}catch{}break}return t}async encryptEncryptedContentInfo(e){Re.assert(e,"password","contentEncryptionAlgorithm","hmacHashAlgorithm","iterationCount","contentToEncrypt","contentToEncrypt","contentType");let t=this.getOIDByAlgorithm(e.contentEncryptionAlgorithm,!0,"contentEncryptionAlgorithm"),n=this.getOIDByAlgorithm({name:"PBKDF2"},!0,"PBKDF2"),r=this.getOIDByAlgorithm({name:"HMAC",hash:{name:e.hmacHashAlgorithm}},!0,"hmacHashAlgorithm"),i=new ArrayBuffer(16),a=new Uint8Array(i);this.getRandomValues(a);let o=new ArrayBuffer(64),c=new Uint8Array(o);this.getRandomValues(c);let u=new Uint8Array(e.contentToEncrypt),l=new $i({salt:new U({valueHex:o}),iterationCount:e.iterationCount,prf:new P({algorithmId:r,algorithmParams:new Xe})}),h=new Uint8Array(e.password),m=await this.importKey("raw",h,"PBKDF2",!1,["deriveKey"]),y=await this.deriveKey({name:"PBKDF2",hash:{name:e.hmacHashAlgorithm},salt:c,iterations:e.iterationCount},m,e.contentEncryptionAlgorithm,!1,["encrypt"]),g=await this.encrypt({name:e.contentEncryptionAlgorithm.name,iv:a},y,u),w=new Fm({keyDerivationFunc:new P({algorithmId:n,algorithmParams:l.toSchema()}),encryptionScheme:new P({algorithmId:t,algorithmParams:new U({valueHex:i})})});return new kt({contentType:e.contentType,contentEncryptionAlgorithm:new P({algorithmId:"1.2.840.113549.1.5.13",algorithmParams:w.toSchema()}),encryptedContent:new U({valueHex:g})})}async decryptEncryptedContentInfo(e){if(Re.assert(e,"password","encryptedContentInfo"),e.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId!=="1.2.840.113549.1.5.13")throw new Error(`Unknown "contentEncryptionAlgorithm": ${e.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId}`);let t;try{t=new Fm({schema:e.encryptedContentInfo.contentEncryptionAlgorithm.algorithmParams});}catch{throw new Error('Incorrectly encoded "pbes2Parameters"')}let n;try{n=new $i({schema:t.keyDerivationFunc.algorithmParams});}catch{throw new Error('Incorrectly encoded "pbkdf2Params"')}let r=this.getAlgorithmByOID(t.encryptionScheme.algorithmId,!0),i=t.encryptionScheme.algorithmParams.valueBlock.valueHex,a=new Uint8Array(i),o=n.salt.valueBlock.valueHex,c=new Uint8Array(o),u=n.iterationCount,l="SHA-1";n.prf&&(l=this.getAlgorithmByOID(n.prf.algorithmId,!0).hash.name);let h=await this.importKey("raw",e.password,"PBKDF2",!1,["deriveKey"]),m=await this.deriveKey({name:"PBKDF2",hash:{name:l},salt:c,iterations:u},h,r,!1,["decrypt"]),y=e.encryptedContentInfo.getEncryptedContent();return this.decrypt({name:r.name,iv:a},m,y)}async stampDataWithPassword(e){if(!(e instanceof Object))throw new Error('Parameters must have type "Object"');Re.assert(e,"password","hashAlgorithm","iterationCount","salt","contentToStamp");let t;switch(e.hashAlgorithm.toLowerCase()){case"sha-1":t=160;break;case"sha-256":t=256;break;case"sha-384":t=384;break;case"sha-512":t=512;break;default:throw new Error(`Incorrect "parameters.hashAlgorithm" parameter: ${e.hashAlgorithm}`)}let n={name:"HMAC",length:t,hash:{name:e.hashAlgorithm}},r=await _N(e.hashAlgorithm,t,e.password,e.salt,e.iterationCount),i=await this.importKey("raw",new Uint8Array(r),n,!1,["sign"]);return this.sign(n,i,new Uint8Array(e.contentToStamp))}async verifyDataStampedWithPassword(e){Re.assert(e,"password","hashAlgorithm","salt","iterationCount","contentToVerify","signatureToVerify");let t=0;switch(e.hashAlgorithm.toLowerCase()){case"sha-1":t=160;break;case"sha-256":t=256;break;case"sha-384":t=384;break;case"sha-512":t=512;break;default:throw new Error(`Incorrect "parameters.hashAlgorithm" parameter: ${e.hashAlgorithm}`)}let n={name:"HMAC",length:t,hash:{name:e.hashAlgorithm}},r=await _N(e.hashAlgorithm,t,e.password,e.salt,e.iterationCount),i=await this.importKey("raw",new Uint8Array(r),n,!1,["verify"]);return this.verify(n,i,new Uint8Array(e.signatureToVerify),new Uint8Array(e.contentToVerify))}async getSignatureParameters(e,t="SHA-1"){this.getOIDByAlgorithm({name:t},!0,"hashAlgorithm");let n=new P,r=this.getAlgorithmParameters(e.algorithm.name,"sign");if(!Object.keys(r.algorithm).length)throw new Error("Parameter 'algorithm' is empty");let i=r.algorithm;switch("hash"in e.algorithm&&e.algorithm.hash&&e.algorithm.hash.name?i.hash.name=e.algorithm.hash.name:i.hash.name=t,e.algorithm.name.toUpperCase()){case"RSASSA-PKCS1-V1_5":case"ECDSA":n.algorithmId=this.getOIDByAlgorithm(i,!0);break;case"RSA-PSS":{switch(i.hash.name.toUpperCase()){case"SHA-256":i.saltLength=32;break;case"SHA-384":i.saltLength=48;break;case"SHA-512":i.saltLength=64;break}let a={};if(i.hash.name.toUpperCase()!=="SHA-1"){let c=this.getOIDByAlgorithm({name:i.hash.name},!0,"hashAlgorithm");a.hashAlgorithm=new P({algorithmId:c,algorithmParams:new Xe}),a.maskGenAlgorithm=new P({algorithmId:"1.2.840.113549.1.1.8",algorithmParams:a.hashAlgorithm.toSchema()});}i.saltLength!==20&&(a.saltLength=i.saltLength);let o=new vl(a);n.algorithmId="1.2.840.113549.1.1.10",n.algorithmParams=o.toSchema();}break;default:throw new Error(`Unsupported signature algorithm: ${e.algorithm.name}`)}return {signatureAlgorithm:n,parameters:r}}async signWithPrivateKey(e,t,n){let r=await this.sign(n.algorithm,t,e);return n.algorithm.name==="ECDSA"?q9(r):r}fillPublicKeyParameters(e,t){let n={},r=this.getHashAlgorithm(t);if(r===p)throw new Error(`Unsupported signature algorithm: ${t.algorithmId}`);let i;t.algorithmId==="1.2.840.113549.1.1.10"?i=t.algorithmId:i=e.algorithm.algorithmId;let a=this.getAlgorithmByOID(i,!0);if(n.algorithm=this.getAlgorithmParameters(a.name,"importKey"),"hash"in n.algorithm.algorithm&&(n.algorithm.algorithm.hash.name=r),a.name==="ECDSA"){let o=e.algorithm;if(!o.algorithmParams)throw new Error("Algorithm parameters for ECDSA public key are missed");let c=o.algorithmParams;if("idBlock"in o.algorithmParams&&!(c.idBlock.tagClass===1&&c.idBlock.tagNumber===6))throw new Error("Incorrect type for ECDSA public key parameters");let u=this.getAlgorithmByOID(c.valueBlock.toString(),!0);n.algorithm.algorithm.namedCurve=u.name;}return n}async getPublicKey(e,t,n){n||(n=this.fillPublicKeyParameters(e,t));let r=e.toSchema().toBER(!1);return this.importKey("spki",r,n.algorithm.algorithm,!0,n.algorithm.usages)}async verifyWithPublicKey(e,t,n,r,i){let a;if(i){let u={},l;r.algorithmId==="1.2.840.113549.1.1.10"?l=r.algorithmId:l=n.algorithm.algorithmId;let h=this.getAlgorithmByOID(l,!0);if(u.algorithm=this.getAlgorithmParameters(h.name,"importKey"),"hash"in u.algorithm.algorithm&&(u.algorithm.algorithm.hash.name=i),h.name==="ECDSA"){let m=!1;if("algorithmParams"in n.algorithm&&"idBlock"in n.algorithm.algorithmParams&&n.algorithm.algorithmParams.idBlock.tagClass===1&&n.algorithm.algorithmParams.idBlock.tagNumber===6&&(m=!0),m===!1)throw new Error("Incorrect type for ECDSA public key parameters");let y=this.getAlgorithmByOID(n.algorithm.algorithmParams.valueBlock.toString(),!0);u.algorithm.algorithm.namedCurve=y.name;}a=await this.getPublicKey(n,null,u);}else {if(i=this.getHashAlgorithm(r),!i)throw new Error(`Unsupported signature algorithm: ${r.algorithmId}`);a=await this.getPublicKey(n,r);}let o=this.getAlgorithmParameters(a.algorithm.name,"verify");"hash"in o.algorithm&&(o.algorithm.hash.name=i);let c=t.valueBlock.valueHexView;if(a.algorithm.name==="ECDSA"){let u=Sn.find(a.algorithm.namedCurve);if(!u)throw new Error("Unsupported named curve in use");let l=ht(c);T.assert(l,"Signature value"),c=F9(l.result,u.size);}if(a.algorithm.name==="RSA-PSS"){let u=new vl({schema:r.algorithmParams});"saltLength"in u?o.algorithm.saltLength=u.saltLength:o.algorithm.saltLength=20;let l="SHA-1";"hashAlgorithm"in u&&(l=this.getAlgorithmByOID(u.hashAlgorithm.algorithmId,!0).name),o.algorithm.hash.name=l;}return this.verify(o.algorithm,a,c,e)}},xk={name:"none",crypto:null};function MN(s){return !!(s&&typeof s=="object"&&"crypto"in s)}function $N(s,...e){let t=null;if(e.length<2)e.length?t=e[0]:t=typeof self<"u"&&self.crypto?new kl({name:"browser",crypto:self.crypto}):null;else {let n=e[0],r=e[1];MN(r)?t=r:MN(n)?t=n:"subtle"in n&&"getRandomValues"in n&&(t=new kl({crypto:n}));}if(typeof process<"u"&&"pid"in process&&typeof global<"u"&&typeof window>"u"){if(typeof global[process.pid]>"u")global[process.pid]={};else if(typeof global[process.pid]!="object")throw new Error(`Name global.${process.pid} already exists and it is not an object`);if(typeof global[process.pid].pkijs>"u")global[process.pid].pkijs={};else if(typeof global[process.pid].pkijs!="object")throw new Error(`Name global.${process.pid}.pkijs already exists and it is not an object`);global[process.pid].pkijs.engine={name:s,crypto:t};}else xk={name:s,crypto:t};}function $9(){if(typeof process<"u"&&"pid"in process&&typeof global<"u"&&typeof window>"u"){let s;try{s=global[process.pid].pkijs.engine;}catch{throw new Error("Please call 'setEngine' before call to 'getEngine'")}return s}return xk}function ve(s=!1){let e=$9();if(!e.crypto&&s)throw new Error("Unable to create WebCrypto object");return e.crypto}function q9(s){if(s.byteLength%2!==0)return ut;let e=s.byteLength/2,t=new ArrayBuffer(e);new Uint8Array(t).set(new Uint8Array(s,0,e));let r=new N({valueHex:t}),i=new ArrayBuffer(e);new Uint8Array(i).set(new Uint8Array(s,e,e));let o=new N({valueHex:i});return new b({value:[r.convertToDER(),o.convertToDER()]}).toBER(!1)}function F9(s,e){if(!(s instanceof b&&s.valueBlock.value.length===2&&s.valueBlock.value[0]instanceof N&&s.valueBlock.value[1]instanceof N))return ut;let t=s.valueBlock.value[0].convertFromDER().valueBlock.valueHexView,n=s.valueBlock.value[1].convertFromDER().valueBlock.valueHexView,r=new Uint8Array(e*2);return r.set(t,e-t.byteLength),r.set(n,2*e-n.byteLength),r.buffer}async function K9(s,e,t,n,r){switch(s.toUpperCase()){case"SHA-1":case"SHA-256":case"SHA-384":case"SHA-512":break;default:throw new $e(`Unknown hash function: ${s}`)}if($e.assert(e,"zBuffer","ArrayBuffer"),e.byteLength===0)throw new $e("'zBuffer' has zero length, error");if($e.assert(n,"SharedInfo","ArrayBuffer"),t>255)throw new $e("Please set 'Counter' argument to value less or equal to 255");let i=new ArrayBuffer(4),a=new Uint8Array(i);a[0]=0,a[1]=0,a[2]=0,a[3]=t;let o=ut;o=ka(o,e),o=ka(o,i),o=ka(o,n);let c=await r.digest({name:s},o);return {counter:t,result:c}}async function qN(s,e,t,n,r=ve(!0)){let i=0,a=1;switch(s.toUpperCase()){case"SHA-1":i=160;break;case"SHA-256":i=256;break;case"SHA-384":i=384;break;case"SHA-512":i=512;break;default:throw new $e(`Unknown hash function: ${s}`)}if($e.assert(e,"Zbuffer","ArrayBuffer"),e.byteLength===0)throw new $e("'Zbuffer' has zero length, error");$e.assert(n,"SharedInfo","ArrayBuffer");let o=t/i;Math.floor(o)>0&&(a=Math.floor(o),o-a>0&&a++);let c=[];for(let m=1;m<=a;m++)c.push(await K9(s,e,m,n,r));let u=ut,l=1,h=!0;for(;h;){h=!1;for(let m of c)if(m.counter===l){u=ka(u,m.result),h=!0;break}l++;}if(t>>=3,u.byteLength>t){let m=new ArrayBuffer(t),y=new Uint8Array(m),g=new Uint8Array(u);for(let w=0;w<t;w++)y[w]=g[w];return m}return u}var l2="version",h2="logID",f2="extensions",d2="timestamp",m2="hashAlgorithm",p2="signatureAlgorithm",g2="signature",FN="none",KN="md5",GN="sha1",WN="sha224",JN="sha256",zN="sha384",YN="sha512",ZN="anonymous",QN="rsa",XN="dsa",ek="ecdsa",cw=class s extends O{constructor(e={}){super(),this.version=d(e,l2,s.defaultValues(l2)),this.logID=d(e,h2,s.defaultValues(h2)),this.timestamp=d(e,d2,s.defaultValues(d2)),this.extensions=d(e,f2,s.defaultValues(f2)),this.hashAlgorithm=d(e,m2,s.defaultValues(m2)),this.signatureAlgorithm=d(e,p2,s.defaultValues(p2)),this.signature=d(e,g2,s.defaultValues(g2)),"stream"in e&&e.stream&&this.fromStream(e.stream),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case l2:return 0;case h2:case f2:return ut;case d2:return new Date(0);case m2:case p2:return p;case g2:return ut;default:return super.defaultValues(e)}}fromSchema(e){if(!(e instanceof Oa))throw new Error("Object's schema was not verified against input data for SignedCertificateTimestamp");let t=new Yn({stream:new Ut({buffer:e.data})});this.fromStream(t);}fromStream(e){let t=e.getUint16();if(this.version=e.getBlock(1)[0],this.version===0){this.logID=new Uint8Array(e.getBlock(32)).buffer.slice(0),this.timestamp=new Date(Fn(new Uint8Array(e.getBlock(8)),8));let n=e.getUint16();switch(this.extensions=new Uint8Array(e.getBlock(n)).buffer.slice(0),e.getBlock(1)[0]){case 0:this.hashAlgorithm=FN;break;case 1:this.hashAlgorithm=KN;break;case 2:this.hashAlgorithm=GN;break;case 3:this.hashAlgorithm=WN;break;case 4:this.hashAlgorithm=JN;break;case 5:this.hashAlgorithm=zN;break;case 6:this.hashAlgorithm=YN;break;default:throw new Error("Object's stream was not correct for SignedCertificateTimestamp")}switch(e.getBlock(1)[0]){case 0:this.signatureAlgorithm=ZN;break;case 1:this.signatureAlgorithm=QN;break;case 2:this.signatureAlgorithm=XN;break;case 3:this.signatureAlgorithm=ek;break;default:throw new Error("Object's stream was not correct for SignedCertificateTimestamp")}let r=e.getUint16();if(this.signature=new Uint8Array(e.getBlock(r)).buffer.slice(0),t!==47+n+r)throw new Error("Object's stream was not correct for SignedCertificateTimestamp")}}toSchema(){let e=this.toStream();return new Oa({data:e.stream.buffer})}toStream(){let e=new Yn;e.appendUint16(47+this.extensions.byteLength+this.signature.byteLength),e.appendChar(this.version),e.appendView(new Uint8Array(this.logID));let t=new ArrayBuffer(8),n=new Uint8Array(t),r=Js(this.timestamp.valueOf(),8);n.set(new Uint8Array(r),8-r.byteLength),e.appendView(n),e.appendUint16(this.extensions.byteLength),this.extensions.byteLength&&e.appendView(new Uint8Array(this.extensions));let i;switch(this.hashAlgorithm.toLowerCase()){case FN:i=0;break;case KN:i=1;break;case GN:i=2;break;case WN:i=3;break;case JN:i=4;break;case zN:i=5;break;case YN:i=6;break;default:throw new Error(`Incorrect data for hashAlgorithm: ${this.hashAlgorithm}`)}e.appendChar(i);let a;switch(this.signatureAlgorithm.toLowerCase()){case ZN:a=0;break;case QN:a=1;break;case XN:a=2;break;case ek:a=3;break;default:throw new Error(`Incorrect data for signatureAlgorithm: ${this.signatureAlgorithm}`)}return e.appendChar(a),e.appendUint16(this.signature.byteLength),e.appendView(new Uint8Array(this.signature)),e}toJSON(){return {version:this.version,logID:y1(this.logID),timestamp:this.timestamp,extensions:y1(this.extensions),hashAlgorithm:this.hashAlgorithm,signatureAlgorithm:this.signatureAlgorithm,signature:y1(this.signature)}}async verify(e,t,n=0,r=ve(!0)){let i=b1(uf(this.logID)),a=null,o=new Yn;for(let y of e)if(y.log_id===i){a=y.key;break}if(!a)throw new Error(`Public key not found for CT with logId: ${i}`);let c=Pa($c(a)),u=As.fromBER(c);o.appendChar(0),o.appendChar(0);let l=new ArrayBuffer(8),h=new Uint8Array(l),m=Js(this.timestamp.valueOf(),8);return h.set(new Uint8Array(m),8-m.byteLength),o.appendView(h),o.appendUint16(n),n===0&&o.appendUint24(t.byteLength),o.appendView(new Uint8Array(t)),o.appendUint16(this.extensions.byteLength),this.extensions.byteLength!==0&&o.appendView(new Uint8Array(this.extensions)),r.verifyWithPublicKey(o.buffer.slice(0,o.length),new U({valueHex:this.signature}),u,{algorithmId:p},"SHA-256")}};cw.CLASS_NAME="SignedCertificateTimestamp";var ny="timestamps",uw=class s extends O{constructor(e={}){super(),this.timestamps=d(e,ny,s.defaultValues(ny)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ny:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ny:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){var t;let n=d(e,"names",{});return (t=n.optional)!==null&&t!==void 0||(n.optional=!1),new U({name:n.blockName||"SignedCertificateTimestampList",optional:n.optional})}fromSchema(e){if(!(e instanceof U))throw new Error("Object's schema was not verified against input data for SignedCertificateTimestampList");let t=new Yn({stream:new Ut({buffer:e.valueBlock.valueHex})});if(t.getUint16()!==t.length)throw new Error("Object's schema was not verified against input data for SignedCertificateTimestampList");for(;t.length;)this.timestamps.push(new cw({stream:t}));}toSchema(){let e=new Yn,t=0,n=[];for(let r of this.timestamps){let i=r.toStream();n.push(i),t+=i.stream.buffer.byteLength;}e.appendUint16(t);for(let r of n)e.appendView(r.stream.view);return new U({valueHex:e.stream.buffer.slice(0)})}toJSON(){return {timestamps:Array.from(this.timestamps,e=>e.toJSON())}}};uw.CLASS_NAME="SignedCertificateTimestampList";var yd="attributes",G9=[yd],lw=class s extends O{constructor(e={}){super(),this.attributes=d(e,yd,s.defaultValues(yd)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case yd:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.attributes||p,value:nt.schema()})]})}fromSchema(e){V(e,G9);let t=R(e,e,s.schema({names:{attributes:yd}}));T.assertSchema(t,this.className),this.attributes=Array.from(t.result.attributes,n=>new nt({schema:n}));}toSchema(){return new b({value:Array.from(this.attributes,e=>e.toSchema())})}toJSON(){return {attributes:Array.from(this.attributes,e=>e.toJSON())}}};lw.CLASS_NAME="SubjectDirectoryAttributes";var H2=class s{static getItems(){return this.types||(this.types={},s.register(ak,"SubjectAltName",Tm),s.register(ok,"IssuerAltName",Tm),s.register(yA,"AuthorityKeyIdentifier",Bm),s.register(pA,"BasicConstraints",Om),s.register(l9,"MicrosoftCaVersion",ew),s.register(fk,"CertificatePolicies",Dm),s.register(r9,"CertificatePoliciesMicrosoft",Dm),s.register(u9,"MicrosoftCertTemplateV2",L2),s.register(hk,"CRLDistributionPoints",Lm),s.register(gA,"FreshestCRL",Lm),s.register(i9,"ExtKeyUsage",tw),s.register(uk,"CertificateIssuer",bt),s.register(wA,"AuthorityInfoAccess",jm),s.register(o9,"SubjectInfoAccess",jm),s.register(ck,"IssuingDistributionPoint",sw),s.register(lk,"NameConstraints",nw),s.register(mk,"PolicyConstraints",rw),s.register(dk,"PolicyMappings",iw),s.register(X7,"PrivateKeyUsagePeriod",aw),s.register(h9,"QCStatements",ow),s.register(c9,"SignedCertificateTimestampList",uw),s.register(Y7,"SubjectDirectoryAttributes",lw)),this.types}static fromBER(e,t){let n=ht(t);if(n.offset===-1)return null;let r=this.find(e);if(r)try{return new r.type({schema:n.result})}catch{let i=new r.type;return i.parsingError=`Incorrectly formatted value of extension ${r.name} (${e})`,i}return n.result}static find(e){return this.getItems()[e]||null}static register(e,t,n){this.getItems()[e]={name:t,type:n};}},wd="extnID",gi="critical",bd="extnValue",ry="parsedValue",W9=[wd,gi,bd],ds=class s extends O{get parsedValue(){if(this._parsedValue===void 0){let e=H2.fromBER(this.extnID,this.extnValue.valueBlock.valueHexView);this._parsedValue=e;}return this._parsedValue||void 0}set parsedValue(e){this._parsedValue=e;}constructor(e={}){super(),this.extnID=d(e,wd,s.defaultValues(wd)),this.critical=d(e,gi,s.defaultValues(gi)),bd in e?this.extnValue=new U({valueHex:e.extnValue}):this.extnValue=s.defaultValues(bd),ry in e&&(this.parsedValue=d(e,ry,s.defaultValues(ry))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case wd:return p;case gi:return !1;case bd:return new U;case ry:return {};default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.extnID||p}),new xs({name:t.critical||p,optional:!0}),new U({name:t.extnValue||p})]})}fromSchema(e){V(e,W9);let t=R(e,e,s.schema({names:{extnID:wd,critical:gi,extnValue:bd}}));T.assertSchema(t,this.className),this.extnID=t.result.extnID.valueBlock.toString(),gi in t.result&&(this.critical=t.result.critical.valueBlock.value),this.extnValue=t.result.extnValue;}toSchema(){let e=[];return e.push(new G({value:this.extnID})),this.critical!==s.defaultValues(gi)&&e.push(new xs({value:this.critical})),e.push(this.extnValue),new b({value:e})}toJSON(){let e={extnID:this.extnID,extnValue:this.extnValue.toJSON()};return this.critical!==s.defaultValues(gi)&&(e.critical=this.critical),this.parsedValue&&this.parsedValue.toJSON&&(e.parsedValue=this.parsedValue.toJSON()),e}};ds.CLASS_NAME="Extension";var Sd="extensions",J9=[Sd],ft=class s extends O{constructor(e={}){super(),this.extensions=d(e,Sd,s.defaultValues(Sd)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Sd:return [];default:return super.defaultValues(e)}}static schema(e={},t=!1){let n=d(e,"names",{});return new b({optional:t,name:n.blockName||p,value:[new fe({name:n.extensions||p,value:ds.schema(n.extension||{})})]})}fromSchema(e){V(e,J9);let t=R(e,e,s.schema({names:{extensions:Sd}}));T.assertSchema(t,this.className),this.extensions=Array.from(t.result.extensions,n=>new ds({schema:n}));}toSchema(){return new b({value:Array.from(this.extensions,e=>e.toSchema())})}toJSON(){return {extensions:this.extensions.map(e=>e.toJSON())}}};ft.CLASS_NAME="Extensions";var vd="issuer",xd="serialNumber",Qa="issuerUID",z9=[vd,xd,Qa],Ts=class s extends O{constructor(e={}){super(),this.issuer=d(e,vd,s.defaultValues(vd)),this.serialNumber=d(e,xd,s.defaultValues(xd)),Qa in e&&(this.issuerUID=d(e,Qa,s.defaultValues(Qa))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case vd:return new bt;case xd:return new N;case Qa:return new Ae;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[bt.schema(t.issuer||{}),new N({name:t.serialNumber||p}),new Ae({optional:!0,name:t.issuerUID||p})]})}fromSchema(e){V(e,z9);let t=R(e,e,s.schema({names:{issuer:{names:{blockName:vd}},serialNumber:xd,issuerUID:Qa}}));T.assertSchema(t,this.className),this.issuer=new bt({schema:t.result.issuer}),this.serialNumber=t.result.serialNumber,Qa in t.result&&(this.issuerUID=t.result.issuerUID);}toSchema(){let e=new b({value:[this.issuer.toSchema(),this.serialNumber]});return this.issuerUID&&e.valueBlock.value.push(this.issuerUID),e}toJSON(){let e={issuer:this.issuer.toJSON(),serialNumber:this.serialNumber.toJSON()};return this.issuerUID&&(e.issuerUID=this.issuerUID.toJSON()),e}};Ts.CLASS_NAME="IssuerSerial";var Ed="version",Xa="baseCertificateID",eo="subjectName",Ad="issuer",Id="signature",Cd="serialNumber",Nd="attrCertValidityPeriod",kd="attributes",to="issuerUniqueID",so="extensions",Y9=[Ed,Xa,eo,Ad,Id,Cd,Nd,kd,to,so],xl=class s extends O{constructor(e={}){super(),this.version=d(e,Ed,s.defaultValues(Ed)),Xa in e&&(this.baseCertificateID=d(e,Xa,s.defaultValues(Xa))),eo in e&&(this.subjectName=d(e,eo,s.defaultValues(eo))),this.issuer=d(e,Ad,s.defaultValues(Ad)),this.signature=d(e,Id,s.defaultValues(Id)),this.serialNumber=d(e,Cd,s.defaultValues(Cd)),this.attrCertValidityPeriod=d(e,Nd,s.defaultValues(Nd)),this.attributes=d(e,kd,s.defaultValues(kd)),to in e&&(this.issuerUniqueID=d(e,to,s.defaultValues(to))),so in e&&(this.extensions=d(e,so,s.defaultValues(so))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ed:return 0;case Xa:return new Ts;case eo:return new bt;case Ad:return new bt;case Id:return new P;case Cd:return new N;case Nd:return new pr;case kd:return [];case to:return new Ae;case so:return new ft;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new N({name:t.version||p}),new We({value:[new A({name:t.baseCertificateID||p,idBlock:{tagClass:3,tagNumber:0},value:Ts.schema().valueBlock.value}),new A({name:t.subjectName||p,idBlock:{tagClass:3,tagNumber:1},value:bt.schema().valueBlock.value})]}),bt.schema({names:{blockName:t.issuer||p}}),P.schema(t.signature||{}),new N({name:t.serialNumber||p}),pr.schema(t.attrCertValidityPeriod||{}),new b({name:t.attributes||p,value:[new fe({value:nt.schema()})]}),new Ae({optional:!0,name:t.issuerUniqueID||p}),ft.schema(t.extensions||{},!0)]})}fromSchema(e){V(e,Y9);let t=R(e,e,s.schema({names:{version:Ed,baseCertificateID:Xa,subjectName:eo,issuer:Ad,signature:{names:{blockName:Id}},serialNumber:Cd,attrCertValidityPeriod:{names:{blockName:Nd}},attributes:kd,issuerUniqueID:to,extensions:{names:{blockName:so}}}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,Xa in t.result&&(this.baseCertificateID=new Ts({schema:new b({value:t.result.baseCertificateID.valueBlock.value})})),eo in t.result&&(this.subjectName=new bt({schema:new b({value:t.result.subjectName.valueBlock.value})})),this.issuer=t.result.issuer,this.signature=new P({schema:t.result.signature}),this.serialNumber=t.result.serialNumber,this.attrCertValidityPeriod=new pr({schema:t.result.attrCertValidityPeriod}),this.attributes=Array.from(t.result.attributes.valueBlock.value,n=>new nt({schema:n})),to in t.result&&(this.issuerUniqueID=t.result.issuerUniqueID),so in t.result&&(this.extensions=new ft({schema:t.result.extensions}));}toSchema(){let e=new b({value:[new N({value:this.version})]});return this.baseCertificateID&&e.valueBlock.value.push(new A({idBlock:{tagClass:3,tagNumber:0},value:this.baseCertificateID.toSchema().valueBlock.value})),this.subjectName&&e.valueBlock.value.push(new A({idBlock:{tagClass:3,tagNumber:1},value:this.subjectName.toSchema().valueBlock.value})),e.valueBlock.value.push(this.issuer.toSchema()),e.valueBlock.value.push(this.signature.toSchema()),e.valueBlock.value.push(this.serialNumber),e.valueBlock.value.push(this.attrCertValidityPeriod.toSchema()),e.valueBlock.value.push(new b({value:Array.from(this.attributes,t=>t.toSchema())})),this.issuerUniqueID&&e.valueBlock.value.push(this.issuerUniqueID),this.extensions&&e.valueBlock.value.push(this.extensions.toSchema()),e}toJSON(){let e={version:this.version};return this.baseCertificateID&&(e.baseCertificateID=this.baseCertificateID.toJSON()),this.subjectName&&(e.subjectName=this.subjectName.toJSON()),e.issuer=this.issuer.toJSON(),e.signature=this.signature.toJSON(),e.serialNumber=this.serialNumber.toJSON(),e.attrCertValidityPeriod=this.attrCertValidityPeriod.toJSON(),e.attributes=Array.from(this.attributes,t=>t.toJSON()),this.issuerUniqueID&&(e.issuerUniqueID=this.issuerUniqueID.toJSON()),this.extensions&&(e.extensions=this.extensions.toJSON()),e}};xl.CLASS_NAME="AttributeCertificateInfoV1";var Pd="acinfo",Td="signatureAlgorithm",Bd="signatureValue",Z9=[Pd,Bd,Td],Pl=class s extends O{constructor(e={}){super(),this.acinfo=d(e,Pd,s.defaultValues(Pd)),this.signatureAlgorithm=d(e,Td,s.defaultValues(Td)),this.signatureValue=d(e,Bd,s.defaultValues(Bd)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Pd:return new xl;case Td:return new P;case Bd:return new Ae;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[xl.schema(t.acinfo||{}),P.schema(t.signatureAlgorithm||{}),new Ae({name:t.signatureValue||p})]})}fromSchema(e){V(e,Z9);let t=R(e,e,s.schema({names:{acinfo:{names:{blockName:Pd}},signatureAlgorithm:{names:{blockName:Td}},signatureValue:Bd}}));T.assertSchema(t,this.className),this.acinfo=new xl({schema:t.result.acinfo}),this.signatureAlgorithm=new P({schema:t.result.signatureAlgorithm}),this.signatureValue=t.result.signatureValue;}toSchema(){return new b({value:[this.acinfo.toSchema(),this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){return {acinfo:this.acinfo.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()}}};Pl.CLASS_NAME="AttributeCertificateV1";var Od="digestedObjectType",no="otherObjectTypeID",Rd="digestAlgorithm",Vd="objectDigest",Q9=[Od,no,Rd,Vd],gr=class s extends O{constructor(e={}){super(),this.digestedObjectType=d(e,Od,s.defaultValues(Od)),no in e&&(this.otherObjectTypeID=d(e,no,s.defaultValues(no))),this.digestAlgorithm=d(e,Rd,s.defaultValues(Rd)),this.objectDigest=d(e,Vd,s.defaultValues(Vd)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Od:return new pn;case no:return new G;case Rd:return new P;case Vd:return new Ae;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new pn({name:t.digestedObjectType||p}),new G({optional:!0,name:t.otherObjectTypeID||p}),P.schema(t.digestAlgorithm||{}),new Ae({name:t.objectDigest||p})]})}fromSchema(e){V(e,Q9);let t=R(e,e,s.schema({names:{digestedObjectType:Od,otherObjectTypeID:no,digestAlgorithm:{names:{blockName:Rd}},objectDigest:Vd}}));T.assertSchema(t,this.className),this.digestedObjectType=t.result.digestedObjectType,no in t.result&&(this.otherObjectTypeID=t.result.otherObjectTypeID),this.digestAlgorithm=new P({schema:t.result.digestAlgorithm}),this.objectDigest=t.result.objectDigest;}toSchema(){let e=new b({value:[this.digestedObjectType]});return this.otherObjectTypeID&&e.valueBlock.value.push(this.otherObjectTypeID),e.valueBlock.value.push(this.digestAlgorithm.toSchema()),e.valueBlock.value.push(this.objectDigest),e}toJSON(){let e={digestedObjectType:this.digestedObjectType.toJSON(),digestAlgorithm:this.digestAlgorithm.toJSON(),objectDigest:this.objectDigest.toJSON()};return this.otherObjectTypeID&&(e.otherObjectTypeID=this.otherObjectTypeID.toJSON()),e}};gr.CLASS_NAME="ObjectDigestInfo";var ro="issuerName",io="baseCertificateID",ao="objectDigestInfo",X9=[ro,io,ao],Km=class s extends O{constructor(e={}){super(),ro in e&&(this.issuerName=d(e,ro,s.defaultValues(ro))),io in e&&(this.baseCertificateID=d(e,io,s.defaultValues(io))),ao in e&&(this.objectDigestInfo=d(e,ao,s.defaultValues(ao))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ro:return new bt;case io:return new Ts;case ao:return new gr;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[bt.schema({names:{blockName:t.issuerName}},!0),new A({optional:!0,name:t.baseCertificateID||p,idBlock:{tagClass:3,tagNumber:0},value:Ts.schema().valueBlock.value}),new A({optional:!0,name:t.objectDigestInfo||p,idBlock:{tagClass:3,tagNumber:1},value:gr.schema().valueBlock.value})]})}fromSchema(e){V(e,X9);let t=R(e,e,s.schema({names:{issuerName:ro,baseCertificateID:io,objectDigestInfo:ao}}));T.assertSchema(t,this.className),ro in t.result&&(this.issuerName=new bt({schema:t.result.issuerName})),io in t.result&&(this.baseCertificateID=new Ts({schema:new b({value:t.result.baseCertificateID.valueBlock.value})})),ao in t.result&&(this.objectDigestInfo=new gr({schema:new b({value:t.result.objectDigestInfo.valueBlock.value})}));}toSchema(){let e=new b;return this.issuerName&&e.valueBlock.value.push(this.issuerName.toSchema()),this.baseCertificateID&&e.valueBlock.value.push(new A({idBlock:{tagClass:3,tagNumber:0},value:this.baseCertificateID.toSchema().valueBlock.value})),this.objectDigestInfo&&e.valueBlock.value.push(new A({idBlock:{tagClass:3,tagNumber:1},value:this.objectDigestInfo.toSchema().valueBlock.value})),e}toJSON(){let e={};return this.issuerName&&(e.issuerName=this.issuerName.toJSON()),this.baseCertificateID&&(e.baseCertificateID=this.baseCertificateID.toJSON()),this.objectDigestInfo&&(e.objectDigestInfo=this.objectDigestInfo.toJSON()),e}};Km.CLASS_NAME="V2Form";var oo="baseCertificateID",co="entityName",uo="objectDigestInfo",eD=[oo,co,uo],El=class s extends O{constructor(e={}){super(),oo in e&&(this.baseCertificateID=d(e,oo,s.defaultValues(oo))),co in e&&(this.entityName=d(e,co,s.defaultValues(co))),uo in e&&(this.objectDigestInfo=d(e,uo,s.defaultValues(uo))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case oo:return new Ts;case co:return new bt;case uo:return new gr;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new A({optional:!0,name:t.baseCertificateID||p,idBlock:{tagClass:3,tagNumber:0},value:Ts.schema().valueBlock.value}),new A({optional:!0,name:t.entityName||p,idBlock:{tagClass:3,tagNumber:1},value:bt.schema().valueBlock.value}),new A({optional:!0,name:t.objectDigestInfo||p,idBlock:{tagClass:3,tagNumber:2},value:gr.schema().valueBlock.value})]})}fromSchema(e){V(e,eD);let t=R(e,e,s.schema({names:{baseCertificateID:oo,entityName:co,objectDigestInfo:uo}}));T.assertSchema(t,this.className),oo in t.result&&(this.baseCertificateID=new Ts({schema:new b({value:t.result.baseCertificateID.valueBlock.value})})),co in t.result&&(this.entityName=new bt({schema:new b({value:t.result.entityName.valueBlock.value})})),uo in t.result&&(this.objectDigestInfo=new gr({schema:new b({value:t.result.objectDigestInfo.valueBlock.value})}));}toSchema(){let e=new b;return this.baseCertificateID&&e.valueBlock.value.push(new A({idBlock:{tagClass:3,tagNumber:0},value:this.baseCertificateID.toSchema().valueBlock.value})),this.entityName&&e.valueBlock.value.push(new A({idBlock:{tagClass:3,tagNumber:1},value:this.entityName.toSchema().valueBlock.value})),this.objectDigestInfo&&e.valueBlock.value.push(new A({idBlock:{tagClass:3,tagNumber:2},value:this.objectDigestInfo.toSchema().valueBlock.value})),e}toJSON(){let e={};return this.baseCertificateID&&(e.baseCertificateID=this.baseCertificateID.toJSON()),this.entityName&&(e.entityName=this.entityName.toJSON()),this.objectDigestInfo&&(e.objectDigestInfo=this.objectDigestInfo.toJSON()),e}};El.CLASS_NAME="Holder";var Dd="version",Ud="holder",Ld="issuer",jd="signature",Hd="serialNumber",_d="attrCertValidityPeriod",Md="attributes",lo="issuerUniqueID",ho="extensions",tD=[Dd,Ud,Ld,jd,Hd,_d,Md,lo,ho],Al=class s extends O{constructor(e={}){super(),this.version=d(e,Dd,s.defaultValues(Dd)),this.holder=d(e,Ud,s.defaultValues(Ud)),this.issuer=d(e,Ld,s.defaultValues(Ld)),this.signature=d(e,jd,s.defaultValues(jd)),this.serialNumber=d(e,Hd,s.defaultValues(Hd)),this.attrCertValidityPeriod=d(e,_d,s.defaultValues(_d)),this.attributes=d(e,Md,s.defaultValues(Md)),lo in e&&(this.issuerUniqueID=d(e,lo,s.defaultValues(lo))),ho in e&&(this.extensions=d(e,ho,s.defaultValues(ho))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Dd:return 1;case Ud:return new El;case Ld:return {};case jd:return new P;case Hd:return new N;case _d:return new pr;case Md:return [];case lo:return new Ae;case ho:return new ft;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new N({name:t.version||p}),El.schema(t.holder||{}),new We({value:[bt.schema({names:{blockName:t.issuer||p}}),new A({name:t.issuer||p,idBlock:{tagClass:3,tagNumber:0},value:Km.schema().valueBlock.value})]}),P.schema(t.signature||{}),new N({name:t.serialNumber||p}),pr.schema(t.attrCertValidityPeriod||{}),new b({name:t.attributes||p,value:[new fe({value:nt.schema()})]}),new Ae({optional:!0,name:t.issuerUniqueID||p}),ft.schema(t.extensions||{},!0)]})}fromSchema(e){V(e,tD);let t=R(e,e,s.schema({names:{version:Dd,holder:{names:{blockName:Ud}},issuer:Ld,signature:{names:{blockName:jd}},serialNumber:Hd,attrCertValidityPeriod:{names:{blockName:_d}},attributes:Md,issuerUniqueID:lo,extensions:{names:{blockName:ho}}}}));switch(T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.holder=new El({schema:t.result.holder}),t.result.issuer.idBlock.tagClass){case 3:this.issuer=new Km({schema:new b({value:t.result.issuer.valueBlock.value})});break;case 1:default:throw new Error("Incorrect value for 'issuer' in AttributeCertificateInfoV2")}this.signature=new P({schema:t.result.signature}),this.serialNumber=t.result.serialNumber,this.attrCertValidityPeriod=new pr({schema:t.result.attrCertValidityPeriod}),this.attributes=Array.from(t.result.attributes.valueBlock.value,n=>new nt({schema:n})),lo in t.result&&(this.issuerUniqueID=t.result.issuerUniqueID),ho in t.result&&(this.extensions=new ft({schema:t.result.extensions}));}toSchema(){let e=new b({value:[new N({value:this.version}),this.holder.toSchema(),new A({idBlock:{tagClass:3,tagNumber:0},value:this.issuer.toSchema().valueBlock.value}),this.signature.toSchema(),this.serialNumber,this.attrCertValidityPeriod.toSchema(),new b({value:Array.from(this.attributes,t=>t.toSchema())})]});return this.issuerUniqueID&&e.valueBlock.value.push(this.issuerUniqueID),this.extensions&&e.valueBlock.value.push(this.extensions.toSchema()),e}toJSON(){let e={version:this.version,holder:this.holder.toJSON(),issuer:this.issuer.toJSON(),signature:this.signature.toJSON(),serialNumber:this.serialNumber.toJSON(),attrCertValidityPeriod:this.attrCertValidityPeriod.toJSON(),attributes:Array.from(this.attributes,t=>t.toJSON())};return this.issuerUniqueID&&(e.issuerUniqueID=this.issuerUniqueID.toJSON()),this.extensions&&(e.extensions=this.extensions.toJSON()),e}};Al.CLASS_NAME="AttributeCertificateInfoV2";var $d="acinfo",qd="signatureAlgorithm",Fd="signatureValue",sD=[$d,qd,Fd],bn=class s extends O{constructor(e={}){super(),this.acinfo=d(e,$d,s.defaultValues($d)),this.signatureAlgorithm=d(e,qd,s.defaultValues(qd)),this.signatureValue=d(e,Fd,s.defaultValues(Fd)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case $d:return new Al;case qd:return new P;case Fd:return new Ae;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[Al.schema(t.acinfo||{}),P.schema(t.signatureAlgorithm||{}),new Ae({name:t.signatureValue||p})]})}fromSchema(e){V(e,sD);let t=R(e,e,s.schema({names:{acinfo:{names:{blockName:$d}},signatureAlgorithm:{names:{blockName:qd}},signatureValue:Fd}}));T.assertSchema(t,this.className),this.acinfo=new Al({schema:t.result.acinfo}),this.signatureAlgorithm=new P({schema:t.result.signatureAlgorithm}),this.signatureValue=t.result.signatureValue;}toSchema(){return new b({value:[this.acinfo.toSchema(),this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){return {acinfo:this.acinfo.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()}}};bn.CLASS_NAME="AttributeCertificateV2";var fo="contentType",hu="content",nD=[fo,hu],tt=class s extends O{constructor(e={}){super(),this.contentType=d(e,fo,s.defaultValues(fo)),this.content=d(e,hu,s.defaultValues(hu)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case fo:return p;case hu:return new ue;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case fo:return typeof t=="string"&&t===this.defaultValues(fo);case hu:return t instanceof ue;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return "optional"in t||(t.optional=!1),new b({name:t.blockName||"ContentInfo",optional:t.optional,value:[new G({name:t.contentType||fo}),new A({idBlock:{tagClass:3,tagNumber:0},value:[new ue({name:t.content||hu})]})]})}fromSchema(e){V(e,nD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.contentType=t.result.contentType.valueBlock.toString(),this.content=t.result.content;}toSchema(){return new b({value:[new G({value:this.contentType}),new A({idBlock:{tagClass:3,tagNumber:0},value:[this.content]})]})}toJSON(){let e={contentType:this.contentType};return this.content instanceof ue||(e.content=this.content.toJSON()),e}};tt.CLASS_NAME="ContentInfo";tt.DATA=bA;tt.SIGNED_DATA=pk;tt.ENVELOPED_DATA=gk;tt.ENCRYPTED_DATA=yk;var y2="type",w2="value",_2="utcTimeName",M2="generalTimeName",rD=[_2,M2],tk;(function(s){s[s.UTCTime=0]="UTCTime",s[s.GeneralizedTime=1]="GeneralizedTime",s[s.empty=2]="empty";})(tk||(tk={}));var St=class s extends O{constructor(e={}){super(),this.type=d(e,y2,s.defaultValues(y2)),this.value=d(e,w2,s.defaultValues(w2)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case y2:return 0;case w2:return new Date(0,0,0);default:return super.defaultValues(e)}}static schema(e={},t=!1){let n=d(e,"names",{});return new We({optional:t,value:[new Wn({name:n.utcTimeName||p}),new Ge({name:n.generalTimeName||p})]})}fromSchema(e){V(e,rD);let t=R(e,e,s.schema({names:{utcTimeName:_2,generalTimeName:M2}}));T.assertSchema(t,this.className),_2 in t.result&&(this.type=0,this.value=t.result.utcTimeName.toDate()),M2 in t.result&&(this.type=1,this.value=t.result.generalTimeName.toDate());}toSchema(){return this.type===0?new Wn({valueDate:this.value}):this.type===1?new Ge({valueDate:this.value}):{}}toJSON(){return {type:this.type,value:this.value}}};St.CLASS_NAME="Time";var b2="tbs",yi="version",Ay="serialNumber",Iy="signature",Cy="issuer",Ny="notBefore",ky="notAfter",Py="subject",Ty="subjectPublicKeyInfo",Kd="issuerUniqueID",Gd="subjectUniqueID",Wd="extensions",Jd="signatureAlgorithm",zd="signatureValue",Is="tbsCertificate",hw=`${Is}.${yi}`,vA=`${Is}.${Ay}`,xA=`${Is}.${Iy}`,EA=`${Is}.${Cy}`,fw=`${Is}.${Ny}`,dw=`${Is}.${ky}`,AA=`${Is}.${Py}`,IA=`${Is}.${Ty}`,mw=`${Is}.${Kd}`,pw=`${Is}.${Gd}`,Nm=`${Is}.${Wd}`,iD=[Is,hw,vA,xA,EA,fw,dw,AA,IA,mw,pw,Nm,Jd,zd];function aD(s={}){let e=d(s,"names",{});return new b({name:e.blockName||Is,value:[new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new N({name:e.tbsCertificateVersion||hw})]}),new N({name:e.tbsCertificateSerialNumber||vA}),P.schema(e.signature||{names:{blockName:xA}}),Je.schema(e.issuer||{names:{blockName:EA}}),new b({name:e.tbsCertificateValidity||"tbsCertificate.validity",value:[St.schema(e.notBefore||{names:{utcTimeName:fw,generalTimeName:fw}}),St.schema(e.notAfter||{names:{utcTimeName:dw,generalTimeName:dw}})]}),Je.schema(e.subject||{names:{blockName:AA}}),As.schema(e.subjectPublicKeyInfo||{names:{blockName:IA}}),new ie({name:e.tbsCertificateIssuerUniqueID||mw,optional:!0,idBlock:{tagClass:3,tagNumber:1}}),new ie({name:e.tbsCertificateSubjectUniqueID||pw,optional:!0,idBlock:{tagClass:3,tagNumber:2}}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:3},value:[ft.schema(e.extensions||{names:{blockName:Nm}})]})]})}var Lt=class s extends O{get tbs(){return re.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e);}constructor(e={}){super(),this.tbsView=new Uint8Array(d(e,b2,s.defaultValues(b2))),this.version=d(e,yi,s.defaultValues(yi)),this.serialNumber=d(e,Ay,s.defaultValues(Ay)),this.signature=d(e,Iy,s.defaultValues(Iy)),this.issuer=d(e,Cy,s.defaultValues(Cy)),this.notBefore=d(e,Ny,s.defaultValues(Ny)),this.notAfter=d(e,ky,s.defaultValues(ky)),this.subject=d(e,Py,s.defaultValues(Py)),this.subjectPublicKeyInfo=d(e,Ty,s.defaultValues(Ty)),Kd in e&&(this.issuerUniqueID=d(e,Kd,s.defaultValues(Kd))),Gd in e&&(this.subjectUniqueID=d(e,Gd,s.defaultValues(Gd))),Wd in e&&(this.extensions=d(e,Wd,s.defaultValues(Wd))),this.signatureAlgorithm=d(e,Jd,s.defaultValues(Jd)),this.signatureValue=d(e,zd,s.defaultValues(zd)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case b2:return ut;case yi:return 0;case Ay:return new N;case Iy:return new P;case Cy:return new Je;case Ny:return new St;case ky:return new St;case Py:return new Je;case Ty:return new As;case Kd:return ut;case Gd:return ut;case Wd:return [];case Jd:return new P;case zd:return new Ae;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[aD(t.tbsCertificate),P.schema(t.signatureAlgorithm||{names:{blockName:Jd}}),new Ae({name:t.signatureValue||zd})]})}fromSchema(e){V(e,iD);let t=R(e,e,s.schema({names:{tbsCertificate:{names:{extensions:{names:{extensions:Nm}}}}}}));T.assertSchema(t,this.className),this.tbsView=t.result.tbsCertificate.valueBeforeDecodeView,hw in t.result&&(this.version=t.result[hw].valueBlock.valueDec),this.serialNumber=t.result[vA],this.signature=new P({schema:t.result[xA]}),this.issuer=new Je({schema:t.result[EA]}),this.notBefore=new St({schema:t.result[fw]}),this.notAfter=new St({schema:t.result[dw]}),this.subject=new Je({schema:t.result[AA]}),this.subjectPublicKeyInfo=new As({schema:t.result[IA]}),mw in t.result&&(this.issuerUniqueID=t.result[mw].valueBlock.valueHex),pw in t.result&&(this.subjectUniqueID=t.result[pw].valueBlock.valueHex),Nm in t.result&&(this.extensions=Array.from(t.result[Nm],n=>new ds({schema:n}))),this.signatureAlgorithm=new P({schema:t.result.signatureAlgorithm}),this.signatureValue=t.result.signatureValue;}encodeTBS(){let e=[];return yi in this&&this.version!==s.defaultValues(yi)&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new N({value:this.version})]})),e.push(this.serialNumber),e.push(this.signature.toSchema()),e.push(this.issuer.toSchema()),e.push(new b({value:[this.notBefore.toSchema(),this.notAfter.toSchema()]})),e.push(this.subject.toSchema()),e.push(this.subjectPublicKeyInfo.toSchema()),this.issuerUniqueID&&e.push(new ie({optional:!0,idBlock:{tagClass:3,tagNumber:1},valueHex:this.issuerUniqueID})),this.subjectUniqueID&&e.push(new ie({optional:!0,idBlock:{tagClass:3,tagNumber:2},valueHex:this.subjectUniqueID})),this.extensions&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:3},value:[new b({value:Array.from(this.extensions,t=>t.toSchema())})]})),new b({value:e})}toSchema(e=!1){let t;if(e===!1){if(!this.tbsView.byteLength)return s.schema().value[0];let n=ht(this.tbsView);T.assert(n,"TBS Certificate"),t=n.result;}else t=this.encodeTBS();return new b({value:[t,this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){let e={tbs:he.ToHex(this.tbsView),version:this.version,serialNumber:this.serialNumber.toJSON(),signature:this.signature.toJSON(),issuer:this.issuer.toJSON(),notBefore:this.notBefore.toJSON(),notAfter:this.notAfter.toJSON(),subject:this.subject.toJSON(),subjectPublicKeyInfo:this.subjectPublicKeyInfo.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()};return yi in this&&this.version!==s.defaultValues(yi)&&(e.version=this.version),this.issuerUniqueID&&(e.issuerUniqueID=he.ToHex(this.issuerUniqueID)),this.subjectUniqueID&&(e.subjectUniqueID=he.ToHex(this.subjectUniqueID)),this.extensions&&(e.extensions=Array.from(this.extensions,t=>t.toJSON())),e}async getPublicKey(e,t=ve(!0)){return t.getPublicKey(this.subjectPublicKeyInfo,this.signatureAlgorithm,e)}async getKeyHash(e="SHA-1",t=ve(!0)){return t.digest({name:e},this.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView)}async sign(e,t="SHA-1",n=ve(!0)){if(!e)throw new Error("Need to provide a private key for signing");let r=await n.getSignatureParameters(e,t),i=r.parameters;this.signature=r.signatureAlgorithm,this.signatureAlgorithm=r.signatureAlgorithm,this.tbsView=new Uint8Array(this.encodeTBS().toBER());let a=await n.signWithPrivateKey(this.tbsView,e,i);this.signatureValue=new Ae({valueHex:a});}async verify(e,t=ve(!0)){let n;if(e?n=e.subjectPublicKeyInfo:this.issuer.isEqual(this.subject)&&(n=this.subjectPublicKeyInfo),!(n instanceof As))throw new Error("Please provide issuer certificate as a parameter");return t.verifyWithPublicKey(this.tbsView,this.signatureValue,n,this.signatureAlgorithm)}};Lt.CLASS_NAME="Certificate";function Ek(s,e=null){if(e&&s.issuer.isEqual(e.issuer)&&s.serialNumber.isEqual(e.serialNumber))return null;let t=!1;if(s.extensions){for(let n of s.extensions)if(n.extnID===pA&&n.parsedValue instanceof Om&&n.parsedValue.cA){t=!0;break}}return t?s:null}var fu="certId",du="certValue",Wc="parsedValue",oD=[fu,du],gw=class s extends O{constructor(e={}){super(),this.certId=d(e,fu,s.defaultValues(fu)),this.certValue=d(e,du,s.defaultValues(du)),Wc in e&&(this.parsedValue=d(e,Wc,s.defaultValues(Wc))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case fu:return p;case du:return new ue;case Wc:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case fu:return t===p;case du:return t instanceof ue;case Wc:return t instanceof Object&&Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.id||"id"}),new A({idBlock:{tagClass:3,tagNumber:0},value:[new ue({name:t.value||"value"})]})]})}fromSchema(e){V(e,oD);let t=R(e,e,s.schema({names:{id:fu,value:du}}));T.assertSchema(t,this.className),this.certId=t.result.certId.valueBlock.toString(),this.certValue=t.result.certValue;let n=this.certValue.valueBlock.valueHexView;switch(this.certId){case UN:try{this.parsedValue=Lt.fromBER(n);}catch{bn.fromBER(n);}break;case LN:this.parsedValue=bn.fromBER(n);break;case d9:default:throw new Error(`Incorrect CERT_ID value in CertBag: ${this.certId}`)}}toSchema(){return Wc in this&&("acinfo"in this.parsedValue?this.certId=LN:this.certId=UN,this.certValue=new U({valueHex:this.parsedValue.toSchema().toBER(!1)})),new b({value:[new G({value:this.certId}),new A({idBlock:{tagClass:3,tagNumber:0},value:["toSchema"in this.certValue?this.certValue.toSchema():this.certValue]})]})}toJSON(){return {certId:this.certId,certValue:this.certValue.toJSON()}}};gw.CLASS_NAME="CertBag";var Yd="userCertificate",mu="revocationDate",mo="crlEntryExtensions",cD=[Yd,mu,mo],yw=class s extends O{constructor(e={}){super(),this.userCertificate=d(e,Yd,s.defaultValues(Yd)),this.revocationDate=d(e,mu,s.defaultValues(mu)),mo in e&&(this.crlEntryExtensions=d(e,mo,s.defaultValues(mo))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Yd:return new N;case mu:return new St;case mo:return new ft;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new N({name:t.userCertificate||Yd}),St.schema({names:{utcTimeName:t.revocationDate||mu,generalTimeName:t.revocationDate||mu}}),ft.schema({names:{blockName:t.crlEntryExtensions||mo}},!0)]})}fromSchema(e){V(e,cD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.userCertificate=t.result.userCertificate,this.revocationDate=new St({schema:t.result.revocationDate}),mo in t.result&&(this.crlEntryExtensions=new ft({schema:t.result.crlEntryExtensions}));}toSchema(){let e=[this.userCertificate,this.revocationDate.toSchema()];return this.crlEntryExtensions&&e.push(this.crlEntryExtensions.toSchema()),new b({value:e})}toJSON(){let e={userCertificate:this.userCertificate.toJSON(),revocationDate:this.revocationDate.toJSON()};return this.crlEntryExtensions&&(e.crlEntryExtensions=this.crlEntryExtensions.toJSON()),e}};yw.CLASS_NAME="RevokedCertificate";var S2="tbs",Ef="version",v2="signature",x2="issuer",E2="thisUpdate",iy="nextUpdate",ay="revokedCertificates",oy="crlExtensions",Zd="signatureAlgorithm",Qd="signatureValue",br="tbsCertList",ww=`${br}.version`,CA=`${br}.signature`,NA=`${br}.issuer`,bw=`${br}.thisUpdate`,Gm=`${br}.nextUpdate`,Sw=`${br}.revokedCertificates`,vw=`${br}.extensions`,uD=[br,ww,CA,NA,bw,Gm,Sw,vw,Zd,Qd];function lD(s={}){let e=d(s,"names",{});return new b({name:e.blockName||br,value:[new N({optional:!0,name:e.tbsCertListVersion||ww,value:2}),P.schema(e.signature||{names:{blockName:CA}}),Je.schema(e.issuer||{names:{blockName:NA}}),St.schema(e.tbsCertListThisUpdate||{names:{utcTimeName:bw,generalTimeName:bw}}),St.schema(e.tbsCertListNextUpdate||{names:{utcTimeName:Gm,generalTimeName:Gm}},!0),new b({optional:!0,value:[new fe({name:e.tbsCertListRevokedCertificates||Sw,value:new b({value:[new N,St.schema(),ft.schema({},!0)]})})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[ft.schema(e.crlExtensions||{names:{blockName:vw}})]})]})}var hD=[yA,ok,e9,t9,ck,gA,wA,s9,n9,uk],Zo=class s extends O{get tbs(){return re.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e);}constructor(e={}){super(),this.tbsView=new Uint8Array(d(e,S2,s.defaultValues(S2))),this.version=d(e,Ef,s.defaultValues(Ef)),this.signature=d(e,v2,s.defaultValues(v2)),this.issuer=d(e,x2,s.defaultValues(x2)),this.thisUpdate=d(e,E2,s.defaultValues(E2)),iy in e&&(this.nextUpdate=d(e,iy,s.defaultValues(iy))),ay in e&&(this.revokedCertificates=d(e,ay,s.defaultValues(ay))),oy in e&&(this.crlExtensions=d(e,oy,s.defaultValues(oy))),this.signatureAlgorithm=d(e,Zd,s.defaultValues(Zd)),this.signatureValue=d(e,Qd,s.defaultValues(Qd)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case S2:return ut;case Ef:return 0;case v2:return new P;case x2:return new Je;case E2:return new St;case iy:return new St;case ay:return [];case oy:return new ft;case Zd:return new P;case Qd:return new Ae;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||"CertificateList",value:[lD(e),P.schema(t.signatureAlgorithm||{names:{blockName:Zd}}),new Ae({name:t.signatureValue||Qd})]})}fromSchema(e){V(e,uD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.tbsView=t.result.tbsCertList.valueBeforeDecodeView,ww in t.result&&(this.version=t.result[ww].valueBlock.valueDec),this.signature=new P({schema:t.result[CA]}),this.issuer=new Je({schema:t.result[NA]}),this.thisUpdate=new St({schema:t.result[bw]}),Gm in t.result&&(this.nextUpdate=new St({schema:t.result[Gm]})),Sw in t.result&&(this.revokedCertificates=Array.from(t.result[Sw],n=>new yw({schema:n}))),vw in t.result&&(this.crlExtensions=new ft({schema:t.result[vw]})),this.signatureAlgorithm=new P({schema:t.result.signatureAlgorithm}),this.signatureValue=t.result.signatureValue;}encodeTBS(){let e=[];return this.version!==s.defaultValues(Ef)&&e.push(new N({value:this.version})),e.push(this.signature.toSchema()),e.push(this.issuer.toSchema()),e.push(this.thisUpdate.toSchema()),this.nextUpdate&&e.push(this.nextUpdate.toSchema()),this.revokedCertificates&&e.push(new b({value:Array.from(this.revokedCertificates,t=>t.toSchema())})),this.crlExtensions&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[this.crlExtensions.toSchema()]})),new b({value:e})}toSchema(e=!1){let t;if(e)t=this.encodeTBS();else {if(!this.tbsView.byteLength)return s.schema();let n=ht(this.tbsView);T.assert(n,"TBS Certificate Revocation List"),t=n.result;}return new b({value:[t,this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){let e={tbs:he.ToHex(this.tbsView),version:this.version,signature:this.signature.toJSON(),issuer:this.issuer.toJSON(),thisUpdate:this.thisUpdate.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()};return this.version!==s.defaultValues(Ef)&&(e.version=this.version),this.nextUpdate&&(e.nextUpdate=this.nextUpdate.toJSON()),this.revokedCertificates&&(e.revokedCertificates=Array.from(this.revokedCertificates,t=>t.toJSON())),this.crlExtensions&&(e.crlExtensions=this.crlExtensions.toJSON()),e}isCertificateRevoked(e){if(!this.issuer.isEqual(e.issuer)||!this.revokedCertificates)return !1;for(let t of this.revokedCertificates)if(t.userCertificate.isEqual(e.serialNumber))return !0;return !1}async sign(e,t="SHA-1",n=ve(!0)){if(!e)throw new Error("Need to provide a private key for signing");let r=await n.getSignatureParameters(e,t),{parameters:i}=r;this.signature=r.signatureAlgorithm,this.signatureAlgorithm=r.signatureAlgorithm,this.tbsView=new Uint8Array(this.encodeTBS().toBER());let a=await n.signWithPrivateKey(this.tbsView,e,i);this.signatureValue=new Ae({valueHex:a});}async verify(e={},t=ve(!0)){let n;if(e.issuerCertificate&&(n=e.issuerCertificate.subjectPublicKeyInfo,!this.issuer.isEqual(e.issuerCertificate.subject)))return !1;if(e.publicKeyInfo&&(n=e.publicKeyInfo),!n)throw new Error("Issuer's certificate must be provided as an input parameter");if(this.crlExtensions){for(let r of this.crlExtensions.extensions)if(r.critical&&!hD.includes(r.extnID))return !1}return t.verifyWithPublicKey(this.tbsView,this.signatureValue,n,this.signatureAlgorithm)}};Zo.CLASS_NAME="CertificateRevocationList";var pu="crlId",gu="crlValue",Af="parsedValue",fD=[pu,gu],xw=class s extends O{constructor(e={}){super(),this.crlId=d(e,pu,s.defaultValues(pu)),this.crlValue=d(e,gu,s.defaultValues(gu)),Af in e&&(this.parsedValue=d(e,Af,s.defaultValues(Af))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case pu:return p;case gu:return new ue;case Af:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case pu:return t===p;case gu:return t instanceof ue;case Af:return t instanceof Object&&Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.id||"id"}),new A({idBlock:{tagClass:3,tagNumber:0},value:[new ue({name:t.value||"value"})]})]})}fromSchema(e){V(e,fD);let t=R(e,e,s.schema({names:{id:pu,value:gu}}));switch(T.assertSchema(t,this.className),this.crlId=t.result.crlId.valueBlock.toString(),this.crlValue=t.result.crlValue,this.crlId){case jN:this.parsedValue=Zo.fromBER(this.certValue.valueBlock.valueHex);break;default:throw new Error(`Incorrect CRL_ID value in CRLBag: ${this.crlId}`)}}toSchema(){return this.parsedValue&&(this.crlId=jN,this.crlValue=new U({valueHex:this.parsedValue.toSchema().toBER(!1)})),new b({value:[new G({value:this.crlId}),new A({idBlock:{tagClass:3,tagNumber:0},value:[this.crlValue.toSchema()]})]})}toJSON(){return {crlId:this.crlId,crlValue:this.crlValue.toJSON()}}};xw.CLASS_NAME="CRLBag";var yu="version",wu="encryptedContentInfo",wi="unprotectedAttrs",dD=[yu,wu,wi],Qo=class s extends O{constructor(e={}){super(),this.version=d(e,yu,s.defaultValues(yu)),this.encryptedContentInfo=d(e,wu,s.defaultValues(wu)),wi in e&&(this.unprotectedAttrs=d(e,wi,s.defaultValues(wi))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case yu:return 0;case wu:return new kt;case wi:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case yu:return t===0;case wu:return kt.compareWithDefault("contentType",t.contentType)&&kt.compareWithDefault("contentEncryptionAlgorithm",t.contentEncryptionAlgorithm)&&kt.compareWithDefault("encryptedContent",t.encryptedContent);case wi:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new N({name:t.version||p}),kt.schema(t.encryptedContentInfo||{}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new fe({name:t.unprotectedAttrs||p,value:nt.schema()})]})]})}fromSchema(e){V(e,dD);let t=R(e,e,s.schema({names:{version:yu,encryptedContentInfo:{names:{blockName:wu}},unprotectedAttrs:wi}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.encryptedContentInfo=new kt({schema:t.result.encryptedContentInfo}),wi in t.result&&(this.unprotectedAttrs=Array.from(t.result.unprotectedAttrs,n=>new nt({schema:n})));}toSchema(){let e=[];return e.push(new N({value:this.version})),e.push(this.encryptedContentInfo.toSchema()),this.unprotectedAttrs&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.unprotectedAttrs,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={version:this.version,encryptedContentInfo:this.encryptedContentInfo.toJSON()};return this.unprotectedAttrs&&(e.unprotectedAttrs=Array.from(this.unprotectedAttrs,t=>t.toJSON())),e}async encrypt(e,t=ve(!0)){$e.assert(e,"parameters","object");let n={...e,contentType:"1.2.840.113549.1.7.1"};this.encryptedContentInfo=await t.encryptEncryptedContentInfo(n);}async decrypt(e,t=ve(!0)){$e.assert(e,"parameters","object");let n={...e,encryptedContentInfo:this.encryptedContentInfo};return t.decryptEncryptedContentInfo(n)}};Qo.CLASS_NAME="EncryptedData";var po="encryptionAlgorithm",bi="encryptedData",If="parsedValue",mD=[po,bi],Ew=class s extends O{constructor(e={}){super(),this.encryptionAlgorithm=d(e,po,s.defaultValues(po)),this.encryptedData=d(e,bi,s.defaultValues(bi)),If in e&&(this.parsedValue=d(e,If,s.defaultValues(If))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case po:return new P;case bi:return new U;case If:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case po:return P.compareWithDefault("algorithmId",t.algorithmId)&&!("algorithmParams"in t);case bi:return t.isEqual(s.defaultValues(e));case If:return t instanceof Object&&Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.encryptionAlgorithm||{names:{blockName:po}}),new We({value:[new U({name:t.encryptedData||bi}),new U({idBlock:{isConstructed:!0},name:t.encryptedData||bi})]})]})}fromSchema(e){V(e,mD);let t=R(e,e,s.schema({names:{encryptionAlgorithm:{names:{blockName:po}},encryptedData:bi}}));T.assertSchema(t,this.className),this.encryptionAlgorithm=new P({schema:t.result.encryptionAlgorithm}),this.encryptedData=t.result.encryptedData;}toSchema(){return new b({value:[this.encryptionAlgorithm.toSchema(),this.encryptedData]})}toJSON(){return {encryptionAlgorithm:this.encryptionAlgorithm.toJSON(),encryptedData:this.encryptedData.toJSON()}}async parseInternalValues(e,t=ve(!0)){let r=await new Qo({encryptedContentInfo:new kt({contentEncryptionAlgorithm:this.encryptionAlgorithm,encryptedContent:this.encryptedData})}).decrypt(e,t);this.parsedValue=Yo.fromBER(r);}async makeInternalValues(e,t=ve(!0)){if(!this.parsedValue)throw new Error('Please initialize "parsedValue" first');let n=new Qo,r={...e,contentToEncrypt:this.parsedValue.toSchema().toBER(!1)};if(await n.encrypt(r,t),!n.encryptedContentInfo.encryptedContent)throw new Error("The filed `encryptedContent` in EncryptedContentInfo is empty");this.encryptionAlgorithm=n.encryptedContentInfo.contentEncryptionAlgorithm,this.encryptedData=n.encryptedContentInfo.encryptedContent;}};Ew.CLASS_NAME="PKCS8ShroudedKeyBag";var bu="secretTypeId",Su="secretValue",pD=[bu,Su],Aw=class s extends O{constructor(e={}){super(),this.secretTypeId=d(e,bu,s.defaultValues(bu)),this.secretValue=d(e,Su,s.defaultValues(Su)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case bu:return p;case Su:return new ue;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case bu:return t===p;case Su:return t instanceof ue;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.id||"id"}),new A({idBlock:{tagClass:3,tagNumber:0},value:[new ue({name:t.value||"value"})]})]})}fromSchema(e){V(e,pD);let t=R(e,e,s.schema({names:{id:bu,value:Su}}));T.assertSchema(t,this.className),this.secretTypeId=t.result.secretTypeId.valueBlock.toString(),this.secretValue=t.result.secretValue;}toSchema(){return new b({value:[new G({value:this.secretTypeId}),new A({idBlock:{tagClass:3,tagNumber:0},value:[this.secretValue.toSchema()]})]})}toJSON(){return {secretTypeId:this.secretTypeId,secretValue:this.secretValue.toJSON()}}};Aw.CLASS_NAME="SecretBag";var $2=class s{static getItems(){return this.items||(this.items={},s.register("1.2.840.113549.1.12.10.1.1",Yo),s.register("1.2.840.113549.1.12.10.1.2",Ew),s.register("1.2.840.113549.1.12.10.1.3",gw),s.register("1.2.840.113549.1.12.10.1.4",xw),s.register("1.2.840.113549.1.12.10.1.5",Aw),s.register("1.2.840.113549.1.12.10.1.6",Mi)),this.items}static register(e,t){this.getItems()[e]=t;}static find(e){return this.getItems()[e]||null}},go="bagId",yo="bagValue",rr="bagAttributes",gD=[go,yo,rr],Wm=class s extends O{constructor(e={}){super(),this.bagId=d(e,go,s.defaultValues(go)),this.bagValue=d(e,yo,s.defaultValues(yo)),rr in e&&(this.bagAttributes=d(e,rr,s.defaultValues(rr))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case go:return p;case yo:return new ue;case rr:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case go:return t===p;case yo:return t instanceof ue;case rr:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.bagId||go}),new A({idBlock:{tagClass:3,tagNumber:0},value:[new ue({name:t.bagValue||yo})]}),new et({optional:!0,value:[new fe({name:t.bagAttributes||rr,value:nt.schema()})]})]})}fromSchema(e){V(e,gD);let t=R(e,e,s.schema({names:{bagId:go,bagValue:yo,bagAttributes:rr}}));T.assertSchema(t,this.className),this.bagId=t.result.bagId.valueBlock.toString();let n=$2.find(this.bagId);if(!n)throw new Error(`Invalid BAG_ID for SafeBag: ${this.bagId}`);this.bagValue=new n({schema:t.result.bagValue}),rr in t.result&&(this.bagAttributes=Array.from(t.result.bagAttributes,r=>new nt({schema:r})));}toSchema(){let e=[new G({value:this.bagId}),new A({idBlock:{tagClass:3,tagNumber:0},value:[this.bagValue.toSchema()]})];return this.bagAttributes&&e.push(new et({value:Array.from(this.bagAttributes,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={bagId:this.bagId,bagValue:this.bagValue.toJSON()};return this.bagAttributes&&(e.bagAttributes=Array.from(this.bagAttributes,t=>t.toJSON())),e}};Wm.CLASS_NAME="SafeBag";var Jc="safeBags",Mi=class s extends O{constructor(e={}){super(),this.safeBags=d(e,Jc,s.defaultValues(Jc)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Jc:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Jc:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.safeBags||p,value:Wm.schema()})]})}fromSchema(e){V(e,[Jc]);let t=R(e,e,s.schema({names:{safeBags:Jc}}));T.assertSchema(t,this.className),this.safeBags=Array.from(t.result.safeBags,n=>new Wm({schema:n}));}toSchema(){return new b({value:Array.from(this.safeBags,e=>e.toSchema())})}toJSON(){return {safeBags:Array.from(this.safeBags,e=>e.toJSON())}}};Mi.CLASS_NAME="SafeContents";var Xd="otherCertFormat",em="otherCert",yD=[Xd,em],Il=class s extends O{constructor(e={}){super(),this.otherCertFormat=d(e,Xd,s.defaultValues(Xd)),this.otherCert=d(e,em,s.defaultValues(em)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Xd:return p;case em:return new ue;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.otherCertFormat||Xd}),new ue({name:t.otherCert||em})]})}fromSchema(e){V(e,yD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.otherCertFormat=t.result.otherCertFormat.valueBlock.toString(),this.otherCert=t.result.otherCert;}toSchema(){return new b({value:[new G({value:this.otherCertFormat}),this.otherCert]})}toJSON(){let e={otherCertFormat:this.otherCertFormat};return this.otherCert instanceof ue||(e.otherCert=this.otherCert.toJSON()),e}},tm="certificates",wD=[tm],yr=class s extends O{constructor(e={}){super(),this.certificates=d(e,tm,s.defaultValues(tm)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case tm:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new et({name:t.blockName||p,value:[new fe({name:t.certificates||tm,value:new We({value:[Lt.schema(),new A({idBlock:{tagClass:3,tagNumber:0},value:[new ue]}),new A({idBlock:{tagClass:3,tagNumber:1},value:[new b]}),new A({idBlock:{tagClass:3,tagNumber:2},value:bn.schema().valueBlock.value}),new A({idBlock:{tagClass:3,tagNumber:3},value:Il.schema().valueBlock.value})]})})]})}fromSchema(e){V(e,wD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.certificates=Array.from(t.result.certificates||[],n=>{let r=n.idBlock.tagNumber;if(n.idBlock.tagClass===1)return new Lt({schema:n});let i=new b({value:n.valueBlock.value});switch(r){case 1:return i.valueBlock.value[0].valueBlock.value[0].valueBlock.valueDec===1?new bn({schema:i}):new Pl({schema:i});case 2:return new bn({schema:i});case 3:return new Il({schema:i})}return n});}toSchema(){return new et({value:Array.from(this.certificates,e=>{switch(!0){case e instanceof Lt:return e.toSchema();case e instanceof Pl:return new A({idBlock:{tagClass:3,tagNumber:1},value:e.toSchema().valueBlock.value});case e instanceof bn:return new A({idBlock:{tagClass:3,tagNumber:2},value:e.toSchema().valueBlock.value});case e instanceof Il:return new A({idBlock:{tagClass:3,tagNumber:3},value:e.toSchema().valueBlock.value})}return e.toSchema()})})}toJSON(){return {certificates:Array.from(this.certificates,e=>e.toJSON())}}};yr.CLASS_NAME="CertificateSet";var sm="otherRevInfoFormat",nm="otherRevInfo",bD=[sm,nm],Fo=class s extends O{constructor(e={}){super(),this.otherRevInfoFormat=d(e,sm,s.defaultValues(sm)),this.otherRevInfo=d(e,nm,s.defaultValues(nm)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case sm:return p;case nm:return new ue;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.otherRevInfoFormat||sm}),new ue({name:t.otherRevInfo||nm})]})}fromSchema(e){V(e,bD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.otherRevInfoFormat=t.result.otherRevInfoFormat.valueBlock.toString(),this.otherRevInfo=t.result.otherRevInfo;}toSchema(){return new b({value:[new G({value:this.otherRevInfoFormat}),this.otherRevInfo]})}toJSON(){let e={otherRevInfoFormat:this.otherRevInfoFormat};return this.otherRevInfo instanceof ue||(e.otherRevInfo=this.otherRevInfo.toJSON()),e}};Fo.CLASS_NAME="OtherRevocationInfoFormat";var rm="crls",A2="otherRevocationInfos",SD=[rm],Ko=class s extends O{constructor(e={}){super(),this.crls=d(e,rm,s.defaultValues(rm)),this.otherRevocationInfos=d(e,A2,s.defaultValues(A2)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case rm:return [];case A2:return [];default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new et({name:t.blockName||p,value:[new fe({name:t.crls||p,value:new We({value:[Zo.schema(),new A({idBlock:{tagClass:3,tagNumber:1},value:[new G,new ue]})]})})]})}fromSchema(e){V(e,SD);let t=R(e,e,s.schema({names:{crls:rm}}));if(T.assertSchema(t,this.className),t.result.crls)for(let n of t.result.crls)n.idBlock.tagClass===1?this.crls.push(new Zo({schema:n})):this.otherRevocationInfos.push(new Fo({schema:n}));}toSchema(){let e=[];return e.push(...Array.from(this.crls,t=>t.toSchema())),e.push(...Array.from(this.otherRevocationInfos,t=>{let n=t.toSchema();return n.idBlock.tagClass=3,n.idBlock.tagNumber=1,n})),new et({value:e})}toJSON(){return {crls:Array.from(this.crls,e=>e.toJSON()),otherRevocationInfos:Array.from(this.otherRevocationInfos,e=>e.toJSON())}}};Ko.CLASS_NAME="RevocationInfoChoices";var im="certs",wo="crls",vD=[im,wo],Cl=class s extends O{constructor(e={}){super(),this.crls=d(e,wo,s.defaultValues(wo)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case im:return new yr;case wo:return new Ko;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case im:return t.certificates.length===0;case wo:return t.crls.length===0&&t.otherRevocationInfos.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new A({name:t.certs||p,optional:!0,idBlock:{tagClass:3,tagNumber:0},value:yr.schema().valueBlock.value}),new A({name:t.crls||p,optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Ko.schema().valueBlock.value})]})}fromSchema(e){V(e,vD);let t=R(e,e,s.schema({names:{certs:im,crls:wo}}));T.assertSchema(t,this.className),im in t.result&&(this.certs=new yr({schema:new et({value:t.result.certs.valueBlock.value})})),wo in t.result&&(this.crls=new Ko({schema:new et({value:t.result.crls.valueBlock.value})}));}toSchema(){let e=[];return this.certs&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:this.certs.toSchema().valueBlock.value})),this.crls&&e.push(new A({idBlock:{tagClass:3,tagNumber:1},value:this.crls.toSchema().valueBlock.value})),new b({value:e})}toJSON(){let e={};return this.certs&&(e.certs=this.certs.toJSON()),this.crls&&(e.crls=this.crls.toJSON()),e}};Cl.CLASS_NAME="OriginatorInfo";var am="issuer",om="serialNumber",xD=[am,om],vt=class s extends O{constructor(e={}){super(),this.issuer=d(e,am,s.defaultValues(am)),this.serialNumber=d(e,om,s.defaultValues(om)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case am:return new Je;case om:return new N;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[Je.schema(t.issuer||{}),new N({name:t.serialNumber||p})]})}fromSchema(e){V(e,xD);let t=R(e,e,s.schema({names:{issuer:{names:{blockName:am}},serialNumber:om}}));T.assertSchema(t,this.className),this.issuer=new Je({schema:t.result.issuer}),this.serialNumber=t.result.serialNumber;}toSchema(){return new b({value:[this.issuer.toSchema(),this.serialNumber]})}toJSON(){return {issuer:this.issuer.toJSON(),serialNumber:this.serialNumber.toJSON()}}};vt.CLASS_NAME="IssuerAndSerialNumber";var cy="variant",Cf="value",ED=["blockName"],Iw=class s extends O{constructor(e={}){super(),this.variant=d(e,cy,s.defaultValues(cy)),Cf in e&&(this.value=d(e,Cf,s.defaultValues(Cf))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case cy:return -1;case Cf:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case cy:return t===-1;case Cf:return Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new We({value:[vt.schema({names:{blockName:t.blockName||p}}),new ie({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:0}})]})}fromSchema(e){V(e,ED);let t=R(e,e,s.schema({names:{blockName:"blockName"}}));T.assertSchema(t,this.className),t.result.blockName.idBlock.tagClass===1?(this.variant=1,this.value=new vt({schema:t.result.blockName})):(this.variant=2,this.value=new U({valueHex:t.result.blockName.valueBlock.valueHex}));}toSchema(){switch(this.variant){case 1:if(!(this.value instanceof vt))throw new Error("Incorrect type of RecipientIdentifier.value. It should be IssuerAndSerialNumber.");return this.value.toSchema();case 2:if(!(this.value instanceof U))throw new Error("Incorrect type of RecipientIdentifier.value. It should be ASN.1 OctetString.");return new ie({idBlock:{tagClass:3,tagNumber:0},valueHex:this.value.valueBlock.valueHexView});default:return new ue}}toJSON(){let e={variant:this.variant};return (this.variant===1||this.variant===2)&&this.value&&(e.value=this.value.toJSON()),e}};Iw.CLASS_NAME="RecipientIdentifier";var bo="version",vu="rid",xu="keyEncryptionAlgorithm",Eu="encryptedKey",uy="recipientCertificate",AD=[bo,vu,xu,Eu],Tl=class s extends O{constructor(e={}){super(),this.version=d(e,bo,s.defaultValues(bo)),this.rid=d(e,vu,s.defaultValues(vu)),this.keyEncryptionAlgorithm=d(e,xu,s.defaultValues(xu)),this.encryptedKey=d(e,Eu,s.defaultValues(Eu)),this.recipientCertificate=d(e,uy,s.defaultValues(uy)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case bo:return -1;case vu:return {};case xu:return new P;case Eu:return new U;case uy:return new Lt;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case bo:return t===s.defaultValues(bo);case vu:return Object.keys(t).length===0;case xu:case Eu:return t.isEqual(s.defaultValues(e));case uy:return !1;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new N({name:t.version||p}),Iw.schema(t.rid||{}),P.schema(t.keyEncryptionAlgorithm||{}),new U({name:t.encryptedKey||p})]})}fromSchema(e){V(e,AD);let t=R(e,e,s.schema({names:{version:bo,rid:{names:{blockName:vu}},keyEncryptionAlgorithm:{names:{blockName:xu}},encryptedKey:Eu}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,t.result.rid.idBlock.tagClass===3?this.rid=new U({valueHex:t.result.rid.valueBlock.valueHex}):this.rid=new vt({schema:t.result.rid}),this.keyEncryptionAlgorithm=new P({schema:t.result.keyEncryptionAlgorithm}),this.encryptedKey=t.result.encryptedKey;}toSchema(){let e=[];return this.rid instanceof vt?(this.version=0,e.push(new N({value:this.version})),e.push(this.rid.toSchema())):(this.version=2,e.push(new N({value:this.version})),e.push(new ie({idBlock:{tagClass:3,tagNumber:0},valueHex:this.rid.valueBlock.valueHexView}))),e.push(this.keyEncryptionAlgorithm.toSchema()),e.push(this.encryptedKey),new b({value:e})}toJSON(){return {version:this.version,rid:this.rid.toJSON(),keyEncryptionAlgorithm:this.keyEncryptionAlgorithm.toJSON(),encryptedKey:this.encryptedKey.toJSON()}}};Tl.CLASS_NAME="KeyTransRecipientInfo";var Au="algorithm",Iu="publicKey",ID=[Au,Iu],Bl=class s extends O{constructor(e={}){super(),this.algorithm=d(e,Au,s.defaultValues(Au)),this.publicKey=d(e,Iu,s.defaultValues(Iu)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Au:return new P;case Iu:return new Ae;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Au:case Iu:return t.isEqual(s.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.algorithm||{}),new Ae({name:t.publicKey||p})]})}fromSchema(e){V(e,ID);let t=R(e,e,s.schema({names:{algorithm:{names:{blockName:Au}},publicKey:Iu}}));T.assertSchema(t,this.className),this.algorithm=new P({schema:t.result.algorithm}),this.publicKey=t.result.publicKey;}toSchema(){return new b({value:[this.algorithm.toSchema(),this.publicKey]})}toJSON(){return {algorithm:this.algorithm.toJSON(),publicKey:this.publicKey.toJSON()}}};Bl.CLASS_NAME="OriginatorPublicKey";var ly="variant",Nf="value",CD=["blockName"],Go=class s extends O{constructor(e={}){super(),this.variant=d(e,ly,s.defaultValues(ly)),Nf in e&&(this.value=d(e,Nf,s.defaultValues(Nf))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ly:return -1;case Nf:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ly:return t===-1;case Nf:return Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new We({value:[vt.schema({names:{blockName:t.blockName||p}}),new ie({idBlock:{tagClass:3,tagNumber:0},name:t.blockName||p}),new A({idBlock:{tagClass:3,tagNumber:1},name:t.blockName||p,value:Bl.schema().valueBlock.value})]})}fromSchema(e){V(e,CD);let t=R(e,e,s.schema({names:{blockName:"blockName"}}));T.assertSchema(t,this.className),t.result.blockName.idBlock.tagClass===1?(this.variant=1,this.value=new vt({schema:t.result.blockName})):t.result.blockName.idBlock.tagNumber===0?(t.result.blockName.idBlock.tagClass=1,t.result.blockName.idBlock.tagNumber=4,this.variant=2,this.value=t.result.blockName):(this.variant=3,this.value=new Bl({schema:new b({value:t.result.blockName.valueBlock.value})}));}toSchema(){switch(this.variant){case 1:return this.value.toSchema();case 2:return this.value.idBlock.tagClass=3,this.value.idBlock.tagNumber=0,this.value;case 3:{let e=this.value.toSchema();return e.idBlock.tagClass=3,e.idBlock.tagNumber=1,e}default:return new ue}}toJSON(){let e={variant:this.variant};return (this.variant===1||this.variant===2||this.variant===3)&&(e.value=this.value.toJSON()),e}};Go.CLASS_NAME="OriginatorIdentifierOrKey";var Cu="keyAttrId",yn="keyAttr",ND=[Cu,yn],wr=class s extends O{constructor(e={}){super(),this.keyAttrId=d(e,Cu,s.defaultValues(Cu)),yn in e&&(this.keyAttr=d(e,yn,s.defaultValues(yn))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Cu:return p;case yn:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Cu:return typeof t=="string"&&t===p;case yn:return Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({optional:t.optional||!0,name:t.blockName||p,value:[new G({name:t.keyAttrId||p}),new ue({optional:!0,name:t.keyAttr||p})]})}fromSchema(e){V(e,ND);let t=R(e,e,s.schema({names:{keyAttrId:Cu,keyAttr:yn}}));T.assertSchema(t,this.className),this.keyAttrId=t.result.keyAttrId.valueBlock.toString(),yn in t.result&&(this.keyAttr=t.result.keyAttr);}toSchema(){let e=[];return e.push(new G({value:this.keyAttrId})),yn in this&&e.push(this.keyAttr),new b({value:e})}toJSON(){let e={keyAttrId:this.keyAttrId};return yn in this&&(e.keyAttr=this.keyAttr.toJSON()),e}};wr.CLASS_NAME="OtherKeyAttribute";var So="subjectKeyIdentifier",Si="date",vi="other",kD=[So,Si,vi],Ol=class s extends O{constructor(e={}){super(),this.subjectKeyIdentifier=d(e,So,s.defaultValues(So)),Si in e&&(this.date=d(e,Si,s.defaultValues(Si))),vi in e&&(this.other=d(e,vi,s.defaultValues(vi))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case So:return new U;case Si:return new Ge;case vi:return new wr;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case So:return t.isEqual(s.defaultValues(So));case Si:return t.year===0&&t.month===0&&t.day===0&&t.hour===0&&t.minute===0&&t.second===0&&t.millisecond===0;case vi:return t.keyAttrId===p&&!("keyAttr"in t);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new U({name:t.subjectKeyIdentifier||p}),new Ge({optional:!0,name:t.date||p}),wr.schema(t.other||{})]})}fromSchema(e){V(e,kD);let t=R(e,e,s.schema({names:{subjectKeyIdentifier:So,date:Si,other:{names:{blockName:vi}}}}));T.assertSchema(t,this.className),this.subjectKeyIdentifier=t.result.subjectKeyIdentifier,Si in t.result&&(this.date=t.result.date),vi in t.result&&(this.other=new wr({schema:t.result.other}));}toSchema(){let e=[];return e.push(this.subjectKeyIdentifier),this.date&&e.push(this.date),this.other&&e.push(this.other.toSchema()),new b({value:e})}toJSON(){let e={subjectKeyIdentifier:this.subjectKeyIdentifier.toJSON()};return this.date&&(e.date=this.date.toJSON()),this.other&&(e.other=this.other.toJSON()),e}};Ol.CLASS_NAME="RecipientKeyIdentifier";var hy="variant",fy="value",PD=["blockName"],qi=class s extends O{constructor(e={}){super(),this.variant=d(e,hy,s.defaultValues(hy)),this.value=d(e,fy,s.defaultValues(fy)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case hy:return -1;case fy:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case hy:return t===-1;case fy:return Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new We({value:[vt.schema(t.issuerAndSerialNumber||{names:{blockName:t.blockName||p}}),new A({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:0},value:Ol.schema(t.rKeyId||{names:{blockName:t.blockName||p}}).valueBlock.value})]})}fromSchema(e){V(e,PD);let t=R(e,e,s.schema({names:{blockName:"blockName"}}));T.assertSchema(t,this.className),t.result.blockName.idBlock.tagClass===1?(this.variant=1,this.value=new vt({schema:t.result.blockName})):(this.variant=2,this.value=new Ol({schema:new b({value:t.result.blockName.valueBlock.value})}));}toSchema(){switch(this.variant){case 1:return this.value.toSchema();case 2:return new A({idBlock:{tagClass:3,tagNumber:0},value:this.value.toSchema().valueBlock.value});default:return new ue}}toJSON(){let e={variant:this.variant};return (this.variant===1||this.variant===2)&&(e.value=this.value.toJSON()),e}};qi.CLASS_NAME="KeyAgreeRecipientIdentifier";var Nu="rid",vo="encryptedKey",TD=[Nu,vo],Rl=class s extends O{constructor(e={}){super(),this.rid=d(e,Nu,s.defaultValues(Nu)),this.encryptedKey=d(e,vo,s.defaultValues(vo)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Nu:return new qi;case vo:return new U;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Nu:return t.variant===-1&&!("value"in t);case vo:return t.isEqual(s.defaultValues(vo));default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[qi.schema(t.rid||{}),new U({name:t.encryptedKey||p})]})}fromSchema(e){V(e,TD);let t=R(e,e,s.schema({names:{rid:{names:{blockName:Nu}},encryptedKey:vo}}));T.assertSchema(t,this.className),this.rid=new qi({schema:t.result.rid}),this.encryptedKey=t.result.encryptedKey;}toSchema(){return new b({value:[this.rid.toSchema(),this.encryptedKey]})}toJSON(){return {rid:this.rid.toJSON(),encryptedKey:this.encryptedKey.toJSON()}}};Rl.CLASS_NAME="RecipientEncryptedKey";var dy="encryptedKeys",Ak="RecipientEncryptedKeys",BD=[Ak],Wo=class s extends O{constructor(e={}){super(),this.encryptedKeys=d(e,dy,s.defaultValues(dy)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case dy:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case dy:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.RecipientEncryptedKeys||p,value:Rl.schema()})]})}fromSchema(e){V(e,BD);let t=R(e,e,s.schema({names:{RecipientEncryptedKeys:Ak}}));T.assertSchema(t,this.className),this.encryptedKeys=Array.from(t.result.RecipientEncryptedKeys,n=>new Rl({schema:n}));}toSchema(){return new b({value:Array.from(this.encryptedKeys,e=>e.toSchema())})}toJSON(){return {encryptedKeys:Array.from(this.encryptedKeys,e=>e.toJSON())}}};Wo.CLASS_NAME="RecipientEncryptedKeys";var ku="version",Pu="originator",ir="ukm",Tu="keyEncryptionAlgorithm",Bu="recipientEncryptedKeys",my="recipientCertificate",py="recipientPublicKey",OD=[ku,Pu,ir,Tu,Bu],Vl=class s extends O{constructor(e={}){super(),this.version=d(e,ku,s.defaultValues(ku)),this.originator=d(e,Pu,s.defaultValues(Pu)),ir in e&&(this.ukm=d(e,ir,s.defaultValues(ir))),this.keyEncryptionAlgorithm=d(e,Tu,s.defaultValues(Tu)),this.recipientEncryptedKeys=d(e,Bu,s.defaultValues(Bu)),this.recipientCertificate=d(e,my,s.defaultValues(my)),this.recipientPublicKey=d(e,py,s.defaultValues(py)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ku:return 0;case Pu:return new Go;case ir:return new U;case Tu:return new P;case Bu:return new Wo;case my:return new Lt;case py:return null;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ku:return t===0;case Pu:return t.variant===-1&&!("value"in t);case ir:return t.isEqual(s.defaultValues(ir));case Tu:return t.algorithmId===p&&!("algorithmParams"in t);case Bu:return t.encryptedKeys.length===0;case my:return !1;case py:return !1;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new N({name:t.version||p}),new A({idBlock:{tagClass:3,tagNumber:0},value:[Go.schema(t.originator||{})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new U({name:t.ukm||p})]}),P.schema(t.keyEncryptionAlgorithm||{}),Wo.schema(t.recipientEncryptedKeys||{})]})}fromSchema(e){V(e,OD);let t=R(e,e,s.schema({names:{version:ku,originator:{names:{blockName:Pu}},ukm:ir,keyEncryptionAlgorithm:{names:{blockName:Tu}},recipientEncryptedKeys:{names:{blockName:Bu}}}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.originator=new Go({schema:t.result.originator}),ir in t.result&&(this.ukm=t.result.ukm),this.keyEncryptionAlgorithm=new P({schema:t.result.keyEncryptionAlgorithm}),this.recipientEncryptedKeys=new Wo({schema:t.result.recipientEncryptedKeys});}toSchema(){let e=[];return e.push(new N({value:this.version})),e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[this.originator.toSchema()]})),this.ukm&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[this.ukm]})),e.push(this.keyEncryptionAlgorithm.toSchema()),e.push(this.recipientEncryptedKeys.toSchema()),new b({value:e})}toJSON(){let e={version:this.version,originator:this.originator.toJSON(),keyEncryptionAlgorithm:this.keyEncryptionAlgorithm.toJSON(),recipientEncryptedKeys:this.recipientEncryptedKeys.toJSON()};return this.ukm&&(e.ukm=this.ukm.toJSON()),e}};Vl.CLASS_NAME="KeyAgreeRecipientInfo";var xo="keyIdentifier",xi="date",Ei="other",RD=[xo,xi,Ei],Jo=class s extends O{constructor(e={}){super(),this.keyIdentifier=d(e,xo,s.defaultValues(xo)),xi in e&&(this.date=d(e,xi,s.defaultValues(xi))),Ei in e&&(this.other=d(e,Ei,s.defaultValues(Ei))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case xo:return new U;case xi:return new Ge;case Ei:return new wr;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case xo:return t.isEqual(s.defaultValues(xo));case xi:return t.year===0&&t.month===0&&t.day===0&&t.hour===0&&t.minute===0&&t.second===0&&t.millisecond===0;case Ei:return t.compareWithDefault("keyAttrId",t.keyAttrId)&&!("keyAttr"in t);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new U({name:t.keyIdentifier||p}),new Ge({optional:!0,name:t.date||p}),wr.schema(t.other||{})]})}fromSchema(e){V(e,RD);let t=R(e,e,s.schema({names:{keyIdentifier:xo,date:xi,other:{names:{blockName:Ei}}}}));T.assertSchema(t,this.className),this.keyIdentifier=t.result.keyIdentifier,xi in t.result&&(this.date=t.result.date),Ei in t.result&&(this.other=new wr({schema:t.result.other}));}toSchema(){let e=[];return e.push(this.keyIdentifier),this.date&&e.push(this.date),this.other&&e.push(this.other.toSchema()),new b({value:e})}toJSON(){let e={keyIdentifier:this.keyIdentifier.toJSON()};return this.date&&(e.date=this.date),this.other&&(e.other=this.other.toJSON()),e}};Jo.CLASS_NAME="KEKIdentifier";var Ou="version",Ru="kekid",Vu="keyEncryptionAlgorithm",Eo="encryptedKey",gy="preDefinedKEK",VD=[Ou,Ru,Vu,Eo],Dl=class s extends O{constructor(e={}){super(),this.version=d(e,Ou,s.defaultValues(Ou)),this.kekid=d(e,Ru,s.defaultValues(Ru)),this.keyEncryptionAlgorithm=d(e,Vu,s.defaultValues(Vu)),this.encryptedKey=d(e,Eo,s.defaultValues(Eo)),this.preDefinedKEK=d(e,gy,s.defaultValues(gy)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ou:return 0;case Ru:return new Jo;case Vu:return new P;case Eo:return new U;case gy:return ut;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case"KEKRecipientInfo":return t===s.defaultValues(Ou);case Ru:return t.compareWithDefault("keyIdentifier",t.keyIdentifier)&&!("date"in t)&&!("other"in t);case Vu:return t.algorithmId===p&&!("algorithmParams"in t);case Eo:return t.isEqual(s.defaultValues(Eo));case gy:return t.byteLength===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new N({name:t.version||p}),Jo.schema(t.kekid||{}),P.schema(t.keyEncryptionAlgorithm||{}),new U({name:t.encryptedKey||p})]})}fromSchema(e){V(e,VD);let t=R(e,e,s.schema({names:{version:Ou,kekid:{names:{blockName:Ru}},keyEncryptionAlgorithm:{names:{blockName:Vu}},encryptedKey:Eo}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.kekid=new Jo({schema:t.result.kekid}),this.keyEncryptionAlgorithm=new P({schema:t.result.keyEncryptionAlgorithm}),this.encryptedKey=t.result.encryptedKey;}toSchema(){return new b({value:[new N({value:this.version}),this.kekid.toSchema(),this.keyEncryptionAlgorithm.toSchema(),this.encryptedKey]})}toJSON(){return {version:this.version,kekid:this.kekid.toJSON(),keyEncryptionAlgorithm:this.keyEncryptionAlgorithm.toJSON(),encryptedKey:this.encryptedKey.toJSON()}}};Dl.CLASS_NAME="KEKRecipientInfo";var Du="version",Ai="keyDerivationAlgorithm",Uu="keyEncryptionAlgorithm",Ao="encryptedKey",yy="password",DD=[Du,Ai,Uu,Ao],Ul=class s extends O{constructor(e={}){super(),this.version=d(e,Du,s.defaultValues(Du)),Ai in e&&(this.keyDerivationAlgorithm=d(e,Ai,s.defaultValues(Ai))),this.keyEncryptionAlgorithm=d(e,Uu,s.defaultValues(Uu)),this.encryptedKey=d(e,Ao,s.defaultValues(Ao)),this.password=d(e,yy,s.defaultValues(yy)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Du:return -1;case Ai:return new P;case Uu:return new P;case Ao:return new U;case yy:return ut;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Du:return t===-1;case Ai:case Uu:return t.algorithmId===p&&!("algorithmParams"in t);case Ao:return t.isEqual(s.defaultValues(Ao));case yy:return t.byteLength===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new N({name:t.version||p}),new A({name:t.keyDerivationAlgorithm||p,optional:!0,idBlock:{tagClass:3,tagNumber:0},value:P.schema().valueBlock.value}),P.schema(t.keyEncryptionAlgorithm||{}),new U({name:t.encryptedKey||p})]})}fromSchema(e){V(e,DD);let t=R(e,e,s.schema({names:{version:Du,keyDerivationAlgorithm:Ai,keyEncryptionAlgorithm:{names:{blockName:Uu}},encryptedKey:Ao}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,Ai in t.result&&(this.keyDerivationAlgorithm=new P({schema:new b({value:t.result.keyDerivationAlgorithm.valueBlock.value})})),this.keyEncryptionAlgorithm=new P({schema:t.result.keyEncryptionAlgorithm}),this.encryptedKey=t.result.encryptedKey;}toSchema(){let e=[];return e.push(new N({value:this.version})),this.keyDerivationAlgorithm&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:this.keyDerivationAlgorithm.toSchema().valueBlock.value})),e.push(this.keyEncryptionAlgorithm.toSchema()),e.push(this.encryptedKey),new b({value:e})}toJSON(){let e={version:this.version,keyEncryptionAlgorithm:this.keyEncryptionAlgorithm.toJSON(),encryptedKey:this.encryptedKey.toJSON()};return this.keyDerivationAlgorithm&&(e.keyDerivationAlgorithm=this.keyDerivationAlgorithm.toJSON()),e}};Ul.CLASS_NAME="PasswordRecipientInfo";var Lu="oriType",Io="oriValue",UD=[Lu,Io],Jm=class s extends O{constructor(e={}){super(),this.oriType=d(e,Lu,s.defaultValues(Lu)),this.oriValue=d(e,Io,s.defaultValues(Io)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Lu:return p;case Io:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Lu:return t===p;case Io:return Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.oriType||p}),new ue({name:t.oriValue||p})]})}fromSchema(e){V(e,UD);let t=R(e,e,s.schema({names:{oriType:Lu,oriValue:Io}}));T.assertSchema(t,this.className),this.oriType=t.result.oriType.valueBlock.toString(),this.oriValue=t.result.oriValue;}toSchema(){return new b({value:[new G({value:this.oriType}),this.oriValue]})}toJSON(){let e={oriType:this.oriType};return s.compareWithDefault(Io,this.oriValue)||(e.oriValue=this.oriValue.toJSON()),e}};Jm.CLASS_NAME="OtherRecipientInfo";var wy="variant",kf="value",LD=["blockName"],hr=class s extends O{constructor(e={}){super(),this.variant=d(e,wy,s.defaultValues(wy)),kf in e&&(this.value=d(e,kf,s.defaultValues(kf))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case wy:return -1;case kf:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case wy:return t===s.defaultValues(e);case kf:return Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new We({value:[Tl.schema({names:{blockName:t.blockName||p}}),new A({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:1},value:Vl.schema().valueBlock.value}),new A({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:2},value:Dl.schema().valueBlock.value}),new A({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:3},value:Ul.schema().valueBlock.value}),new A({name:t.blockName||p,idBlock:{tagClass:3,tagNumber:4},value:Jm.schema().valueBlock.value})]})}fromSchema(e){V(e,LD);let t=R(e,e,s.schema({names:{blockName:"blockName"}}));if(T.assertSchema(t,this.className),t.result.blockName.idBlock.tagClass===1)this.variant=1,this.value=new Tl({schema:t.result.blockName});else {let n=new b({value:t.result.blockName.valueBlock.value});switch(t.result.blockName.idBlock.tagNumber){case 1:this.variant=2,this.value=new Vl({schema:n});break;case 2:this.variant=3,this.value=new Dl({schema:n});break;case 3:this.variant=4,this.value=new Ul({schema:n});break;case 4:this.variant=5,this.value=new Jm({schema:n});break;default:throw new Error("Incorrect structure of RecipientInfo block")}}}toSchema(){Re.assertEmpty(this.value,"value","RecipientInfo");let e=this.value.toSchema();switch(this.variant){case 1:return e;case 2:case 3:case 4:return e.idBlock.tagClass=3,e.idBlock.tagNumber=this.variant-1,e;default:return new ue}}toJSON(){let e={variant:this.variant};return this.value&&this.variant>=1&&this.variant<=4&&(e.value=this.value.toJSON()),e}};hr.CLASS_NAME="RecipientInfo";var Ii="hashAlgorithm",Ci="maskGenAlgorithm",Ni="pSourceAlgorithm",jD=[Ii,Ci,Ni],Nl=class s extends O{constructor(e={}){super(),this.hashAlgorithm=d(e,Ii,s.defaultValues(Ii)),this.maskGenAlgorithm=d(e,Ci,s.defaultValues(Ci)),this.pSourceAlgorithm=d(e,Ni,s.defaultValues(Ni)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ii:return new P({algorithmId:"1.3.14.3.2.26",algorithmParams:new Xe});case Ci:return new P({algorithmId:"1.2.840.113549.1.1.8",algorithmParams:new P({algorithmId:"1.3.14.3.2.26",algorithmParams:new Xe}).toSchema()});case Ni:return new P({algorithmId:"1.2.840.113549.1.1.9",algorithmParams:new U({valueHex:new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer})});default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new A({idBlock:{tagClass:3,tagNumber:0},optional:!0,value:[P.schema(t.hashAlgorithm||{})]}),new A({idBlock:{tagClass:3,tagNumber:1},optional:!0,value:[P.schema(t.maskGenAlgorithm||{})]}),new A({idBlock:{tagClass:3,tagNumber:2},optional:!0,value:[P.schema(t.pSourceAlgorithm||{})]})]})}fromSchema(e){V(e,jD);let t=R(e,e,s.schema({names:{hashAlgorithm:{names:{blockName:Ii}},maskGenAlgorithm:{names:{blockName:Ci}},pSourceAlgorithm:{names:{blockName:Ni}}}}));T.assertSchema(t,this.className),Ii in t.result&&(this.hashAlgorithm=new P({schema:t.result.hashAlgorithm})),Ci in t.result&&(this.maskGenAlgorithm=new P({schema:t.result.maskGenAlgorithm})),Ni in t.result&&(this.pSourceAlgorithm=new P({schema:t.result.pSourceAlgorithm}));}toSchema(){let e=[];return this.hashAlgorithm.isEqual(s.defaultValues(Ii))||e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[this.hashAlgorithm.toSchema()]})),this.maskGenAlgorithm.isEqual(s.defaultValues(Ci))||e.push(new A({idBlock:{tagClass:3,tagNumber:1},value:[this.maskGenAlgorithm.toSchema()]})),this.pSourceAlgorithm.isEqual(s.defaultValues(Ni))||e.push(new A({idBlock:{tagClass:3,tagNumber:2},value:[this.pSourceAlgorithm.toSchema()]})),new b({value:e})}toJSON(){let e={};return this.hashAlgorithm.isEqual(s.defaultValues(Ii))||(e.hashAlgorithm=this.hashAlgorithm.toJSON()),this.maskGenAlgorithm.isEqual(s.defaultValues(Ci))||(e.maskGenAlgorithm=this.maskGenAlgorithm.toJSON()),this.pSourceAlgorithm.isEqual(s.defaultValues(Ni))||(e.pSourceAlgorithm=this.pSourceAlgorithm.toJSON()),e}};Nl.CLASS_NAME="RSAESOAEPParams";var ju="keyInfo",ki="entityUInfo",Hu="suppPubInfo",HD=[ju,ki,Hu],zm=class s extends O{constructor(e={}){super(),this.keyInfo=d(e,ju,s.defaultValues(ju)),ki in e&&(this.entityUInfo=d(e,ki,s.defaultValues(ki))),this.suppPubInfo=d(e,Hu,s.defaultValues(Hu)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ju:return new P;case ki:return new U;case Hu:return new U;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ju:case ki:case Hu:return t.isEqual(s.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.keyInfo||{}),new A({name:t.entityUInfo||p,idBlock:{tagClass:3,tagNumber:0},optional:!0,value:[new U]}),new A({name:t.suppPubInfo||p,idBlock:{tagClass:3,tagNumber:2},value:[new U]})]})}fromSchema(e){V(e,HD);let t=R(e,e,s.schema({names:{keyInfo:{names:{blockName:ju}},entityUInfo:ki,suppPubInfo:Hu}}));T.assertSchema(t,this.className),this.keyInfo=new P({schema:t.result.keyInfo}),ki in t.result&&(this.entityUInfo=t.result.entityUInfo.valueBlock.value[0]),this.suppPubInfo=t.result.suppPubInfo.valueBlock.value[0];}toSchema(){let e=[];return e.push(this.keyInfo.toSchema()),this.entityUInfo&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[this.entityUInfo]})),e.push(new A({idBlock:{tagClass:3,tagNumber:2},value:[this.suppPubInfo]})),new b({value:e})}toJSON(){let e={keyInfo:this.keyInfo.toJSON(),suppPubInfo:this.suppPubInfo.toJSON()};return this.entityUInfo&&(e.entityUInfo=this.entityUInfo.toJSON()),e}};zm.CLASS_NAME="ECCCMSSharedInfo";var _u="version",Pi="originatorInfo",Mu="recipientInfos",$u="encryptedContentInfo",Ti="unprotectedAttrs",_D=[_u,Pi,Mu,$u,Ti],sk={kdfAlgorithm:"SHA-512",kekEncryptionLength:256},MD={"P-256":256,"P-384":384,"P-521":528},Ym=class s extends O{constructor(e={}){super(),this.version=d(e,_u,s.defaultValues(_u)),Pi in e&&(this.originatorInfo=d(e,Pi,s.defaultValues(Pi))),this.recipientInfos=d(e,Mu,s.defaultValues(Mu)),this.encryptedContentInfo=d(e,$u,s.defaultValues($u)),Ti in e&&(this.unprotectedAttrs=d(e,Ti,s.defaultValues(Ti))),this.policy={disableSplit:!!e.disableSplit},e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case _u:return 0;case Pi:return new Cl;case Mu:return [];case $u:return new kt;case Ti:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case _u:return t===s.defaultValues(e);case Pi:return t.certs.certificates.length===0&&t.crls.crls.length===0;case Mu:case Ti:return t.length===0;case $u:return kt.compareWithDefault("contentType",t.contentType)&&kt.compareWithDefault("contentEncryptionAlgorithm",t.contentEncryptionAlgorithm)&&kt.compareWithDefault("encryptedContent",t.encryptedContent);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new N({name:t.version||p}),new A({name:t.originatorInfo||p,optional:!0,idBlock:{tagClass:3,tagNumber:0},value:Cl.schema().valueBlock.value}),new et({value:[new fe({name:t.recipientInfos||p,value:hr.schema()})]}),kt.schema(t.encryptedContentInfo||{}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new fe({name:t.unprotectedAttrs||p,value:nt.schema()})]})]})}fromSchema(e){V(e,_D);let t=R(e,e,s.schema({names:{version:_u,originatorInfo:Pi,recipientInfos:Mu,encryptedContentInfo:{names:{blockName:$u}},unprotectedAttrs:Ti}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,Pi in t.result&&(this.originatorInfo=new Cl({schema:new b({value:t.result.originatorInfo.valueBlock.value})})),this.recipientInfos=Array.from(t.result.recipientInfos,n=>new hr({schema:n})),this.encryptedContentInfo=new kt({schema:t.result.encryptedContentInfo}),Ti in t.result&&(this.unprotectedAttrs=Array.from(t.result.unprotectedAttrs,n=>new nt({schema:n})));}toSchema(){let e=[];return e.push(new N({value:this.version})),this.originatorInfo&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:this.originatorInfo.toSchema().valueBlock.value})),e.push(new et({value:Array.from(this.recipientInfos,t=>t.toSchema())})),e.push(this.encryptedContentInfo.toSchema()),this.unprotectedAttrs&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.unprotectedAttrs,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={version:this.version,recipientInfos:Array.from(this.recipientInfos,t=>t.toJSON()),encryptedContentInfo:this.encryptedContentInfo.toJSON()};return this.originatorInfo&&(e.originatorInfo=this.originatorInfo.toJSON()),this.unprotectedAttrs&&(e.unprotectedAttrs=Array.from(this.unprotectedAttrs,t=>t.toJSON())),e}addRecipientByCertificate(e,t,n,r=ve(!0)){let i=Object.assign({useOAEP:!0,oaepHashAlgorithm:"SHA-512"},sk,t||{});if(e.subjectPublicKeyInfo.algorithm.algorithmId.indexOf("1.2.840.113549")!==-1)n=1;else if(e.subjectPublicKeyInfo.algorithm.algorithmId.indexOf("1.2.840.10045")!==-1)n=2;else throw new Error(`Unknown type of certificate's public key: ${e.subjectPublicKeyInfo.algorithm.algorithmId}`);switch(n){case 1:{let a,o;if(i.useOAEP===!0){a=r.getOIDByAlgorithm({name:"RSA-OAEP"},!0,"keyEncryptionAlgorithm");let u=r.getOIDByAlgorithm({name:i.oaepHashAlgorithm},!0,"RSAES-OAEP-params"),l=new P({algorithmId:u,algorithmParams:new Xe});o=new Nl({hashAlgorithm:l,maskGenAlgorithm:new P({algorithmId:"1.2.840.113549.1.1.8",algorithmParams:l.toSchema()})}).toSchema();}else {if(a=r.getOIDByAlgorithm({name:"RSAES-PKCS1-v1_5"}),a===p)throw new Error("Can not find OID for RSAES-PKCS1-v1_5");o=new Xe;}let c=new Tl({version:0,rid:new vt({issuer:e.issuer,serialNumber:e.serialNumber}),keyEncryptionAlgorithm:new P({algorithmId:a,algorithmParams:o}),recipientCertificate:e});this.recipientInfos.push(new hr({variant:1,value:c}));}break;case 2:{let a=new qi({variant:1,value:new vt({issuer:e.issuer,serialNumber:e.serialNumber})});this._addKeyAgreeRecipientInfo(a,i,{recipientCertificate:e},r);}break;default:throw new Error(`Unknown "variant" value: ${n}`)}return !0}addRecipientByPreDefinedData(e,t={},n,r=ve(!0)){if($e.assert(e,"preDefinedData","ArrayBuffer"),!e.byteLength)throw new Error("Pre-defined data could have zero length");if(!t.keyIdentifier){let i=new ArrayBuffer(16),a=new Uint8Array(i);r.getRandomValues(a),t.keyIdentifier=i;}switch(t.hmacHashAlgorithm||(t.hmacHashAlgorithm="SHA-512"),t.iterationCount===void 0&&(t.iterationCount=2048),t.keyEncryptionAlgorithm||(t.keyEncryptionAlgorithm={name:"AES-KW",length:256}),t.keyEncryptionAlgorithmParams||(t.keyEncryptionAlgorithmParams=new Xe),n){case 1:{let i=r.getOIDByAlgorithm(t.keyEncryptionAlgorithm,!0,"keyEncryptionAlgorithm"),a=new Dl({version:4,kekid:new Jo({keyIdentifier:new U({valueHex:t.keyIdentifier})}),keyEncryptionAlgorithm:new P({algorithmId:i,algorithmParams:t.keyEncryptionAlgorithmParams}),preDefinedKEK:e});this.recipientInfos.push(new hr({variant:3,value:a}));}break;case 2:{let i=r.getOIDByAlgorithm({name:"PBKDF2"},!0,"keyDerivationAlgorithm"),a=new ArrayBuffer(64),o=new Uint8Array(a);r.getRandomValues(o);let c=r.getOIDByAlgorithm({name:"HMAC",hash:{name:t.hmacHashAlgorithm}},!0,"hmacHashAlgorithm"),u=new $i({salt:new U({valueHex:a}),iterationCount:t.iterationCount,prf:new P({algorithmId:c,algorithmParams:new Xe})}),l=r.getOIDByAlgorithm(t.keyEncryptionAlgorithm,!0,"keyEncryptionAlgorithm"),h=new Ul({version:0,keyDerivationAlgorithm:new P({algorithmId:i,algorithmParams:u.toSchema()}),keyEncryptionAlgorithm:new P({algorithmId:l,algorithmParams:t.keyEncryptionAlgorithmParams}),password:e});this.recipientInfos.push(new hr({variant:4,value:h}));}break;default:throw new Error(`Unknown value for "variant": ${n}`)}}addRecipientByKeyIdentifier(e,t,n,r=ve(!0)){let i=Object.assign({},sk,n||{}),a=new qi({variant:2,value:new Ol({subjectKeyIdentifier:new U({valueHex:t})})});this._addKeyAgreeRecipientInfo(a,i,{recipientPublicKey:e},r);}_addKeyAgreeRecipientInfo(e,t,n,r=ve(!0)){let i=new Rl({rid:e}),a=r.getOIDByAlgorithm({name:"AES-KW",length:t.kekEncryptionLength},!0,"keyEncryptionAlgorithm"),o=new P({algorithmId:a}),c=r.getOIDByAlgorithm({name:"ECDH",kdf:t.kdfAlgorithm},!0,"KeyAgreeRecipientInfo"),u=new ArrayBuffer(64),l=new Uint8Array(u);r.getRandomValues(l);let h={version:3,ukm:new U({valueHex:u}),keyEncryptionAlgorithm:new P({algorithmId:c,algorithmParams:o.toSchema()}),recipientEncryptedKeys:new Wo({encryptedKeys:[i]})},m=new Vl(Object.assign(h,n));this.recipientInfos.push(new hr({variant:2,value:m}));}async encrypt(e,t,n=ve(!0)){let r=new ArrayBuffer(16),i=new Uint8Array(r);n.getRandomValues(i);let a=new Uint8Array(t),o=n.getOIDByAlgorithm(e,!0,"contentEncryptionAlgorithm"),c=await n.generateKey(e,!0,["encrypt"]),u=await n.encrypt({name:e.name,iv:i},c,a),l=await n.exportKey("raw",c);this.version=2,this.encryptedContentInfo=new kt({disableSplit:this.policy.disableSplit,contentType:"1.2.840.113549.1.7.1",contentEncryptionAlgorithm:new P({algorithmId:o,algorithmParams:new U({valueHex:r})}),encryptedContent:new U({valueHex:u})});let h=async S=>{let C=this.recipientInfos[S].value,k,x;if(C.recipientPublicKey)k=C.recipientPublicKey.algorithm.namedCurve,x=C.recipientPublicKey;else if(C.recipientCertificate){let j=C.recipientCertificate.subjectPublicKeyInfo.algorithm.algorithmParams;if(j.constructor.blockName()!==G.blockName())throw new Error(`Incorrect "recipientCertificate" for index ${S}`);switch(j.valueBlock.toString()){case"1.2.840.10045.3.1.7":k="P-256";break;case"1.3.132.0.34":k="P-384";break;case"1.3.132.0.35":k="P-521";break;default:throw new Error(`Incorrect curve OID for index ${S}`)}x=await C.recipientCertificate.getPublicKey({algorithm:{algorithm:{name:"ECDH",namedCurve:k},usages:[]}},n);}else throw new Error("Unsupported RecipientInfo");let v=MD[k],I=await n.generateKey({name:"ECDH",namedCurve:k},!0,["deriveBits"]),D=await n.exportKey("spki",I.publicKey),F=await n.deriveBits({name:"ECDH",public:x},I.privateKey,v),M=new P({schema:C.keyEncryptionAlgorithm.algorithmParams}),W=n.getAlgorithmByOID(M.algorithmId,!0,"aesKWAlgorithm"),ne=W.length,q=new ArrayBuffer(4),J=new Uint8Array(q);for(let j=3;j>=0;j--)J[j]=ne,ne>>=8;let Be=new zm({keyInfo:new P({algorithmId:M.algorithmId}),entityUInfo:C.ukm,suppPubInfo:new U({valueHex:q})}).toSchema().toBER(!1),L=n.getAlgorithmByOID(C.keyEncryptionAlgorithm.algorithmId,!0,"ecdhAlgorithm"),_=await qN(L.kdf,F,W.length,Be,n),Q=await n.importKey("raw",_,{name:"AES-KW"},!0,["wrapKey"]),me=await n.wrapKey("raw",c,Q,{name:"AES-KW"}),X=new Go;return X.variant=3,X.value=Bl.fromBER(D),C.originator=X,C.recipientEncryptedKeys.encryptedKeys[0].encryptedKey=new U({valueHex:me}),{ecdhPrivateKey:I.privateKey}},m=async S=>{let C=this.recipientInfos[S].value,k=n.getAlgorithmByOID(C.keyEncryptionAlgorithm.algorithmId,!0,"keyEncryptionAlgorithm");if(k.name==="RSA-OAEP"){let x=C.keyEncryptionAlgorithm.algorithmParams,v=new Nl({schema:x});if(k.hash=n.getAlgorithmByOID(v.hashAlgorithm.algorithmId),!("name"in k.hash))throw new Error(`Incorrect OID for hash algorithm: ${v.hashAlgorithm.algorithmId}`)}try{let x=await C.recipientCertificate.getPublicKey({algorithm:{algorithm:k,usages:["encrypt","wrapKey"]}},n),v=await n.encrypt(x.algorithm,x,l);C.encryptedKey=new U({valueHex:v});}catch{}},y=async S=>{let C=this.recipientInfos[S].value,k=n.getAlgorithmByOID(C.keyEncryptionAlgorithm.algorithmId,!0,"kekAlgorithm"),x=await n.importKey("raw",new Uint8Array(C.preDefinedKEK),k,!0,["wrapKey"]),v=await n.wrapKey("raw",c,x,k);C.encryptedKey=new U({valueHex:v});},g=async S=>{let C=this.recipientInfos[S].value,k;if(!C.keyDerivationAlgorithm)throw new Error('Please append encoded "keyDerivationAlgorithm"');if(!C.keyDerivationAlgorithm.algorithmParams)throw new Error('Incorrectly encoded "keyDerivationAlgorithm"');try{k=new $i({schema:C.keyDerivationAlgorithm.algorithmParams});}catch{throw new Error('Incorrectly encoded "keyDerivationAlgorithm"')}let x=new Uint8Array(C.password),v=await n.importKey("raw",x,"PBKDF2",!1,["deriveKey"]),I=n.getAlgorithmByOID(C.keyEncryptionAlgorithm.algorithmId,!0,"kekAlgorithm"),D="SHA-1";k.prf&&(D=n.getAlgorithmByOID(k.prf.algorithmId,!0,"prfAlgorithm").hash.name);let F=new Uint8Array(k.salt.valueBlock.valueHex),M=k.iterationCount,W=await n.deriveKey({name:"PBKDF2",hash:{name:D},salt:F,iterations:M},v,I,!0,["wrapKey"]),ne=await n.wrapKey("raw",c,W,I);C.encryptedKey=new U({valueHex:ne});},w=[];for(let S=0;S<this.recipientInfos.length;S++)switch(this.recipientInfos[S].variant){case 1:w.push(await m(S));break;case 2:w.push(await h(S));break;case 3:w.push(await y(S));break;case 4:w.push(await g(S));break;default:throw new Error(`Unknown recipient type in array with index ${S}`)}return w}async decrypt(e,t,n=ve(!0)){let r=t||{};if(e+1>this.recipientInfos.length)throw new Error(`Maximum value for "index" is: ${this.recipientInfos.length-1}`);let i=async w=>{let S=this.recipientInfos[w].value,C,k,x,v=S.originator;if(r.recipientCertificate){let L=r.recipientCertificate.subjectPublicKeyInfo.algorithm.algorithmParams;if(L.constructor.blockName()!==G.blockName())throw new Error(`Incorrect "recipientCertificate" for index ${w}`);C=L.valueBlock.toString();}else if(v.value.algorithm.algorithmParams){let L=v.value.algorithm.algorithmParams;if(L.constructor.blockName()!==G.blockName())throw new Error(`Incorrect originator for index ${w}`);C=L.valueBlock.toString();}else throw new Error('Parameter "recipientCertificate" is mandatory for "KeyAgreeRecipientInfo" if algorithm params are missing from originator');if(!r.recipientPrivateKey)throw new Error('Parameter "recipientPrivateKey" is mandatory for "KeyAgreeRecipientInfo"');switch(C){case"1.2.840.10045.3.1.7":k="P-256",x=256;break;case"1.3.132.0.34":k="P-384",x=384;break;case"1.3.132.0.35":k="P-521",x=528;break;default:throw new Error(`Incorrect curve OID for index ${w}`)}let I,D=n;re.isBufferSource(r.recipientPrivateKey)?I=await n.importKey("pkcs8",r.recipientPrivateKey,{name:"ECDH",namedCurve:k},!0,["deriveBits"]):(I=r.recipientPrivateKey,"crypto"in r&&r.crypto&&(D=r.crypto.subtle)),"algorithmParams"in v.value.algorithm||(v.value.algorithm.algorithmParams=new G({value:C}));let F=v.value.toSchema().toBER(!1),M=await n.importKey("spki",F,{name:"ECDH",namedCurve:k},!0,[]),W=await D.deriveBits({name:"ECDH",public:M},I,x);async function ne(L){L=L||!1;let _=new P({schema:S.keyEncryptionAlgorithm.algorithmParams}),Q=n.getAlgorithmByOID(_.algorithmId,!0,"kwAlgorithm"),me=Q.length,X=new ArrayBuffer(4),j=new Uint8Array(X);for(let Ve=3;Ve>=0;Ve--)j[Ve]=me,me>>=8;let z={algorithmId:_.algorithmId};L&&(z.algorithmParams=new Xe);let pe=new zm({keyInfo:new P(z),entityUInfo:S.ukm,suppPubInfo:new U({valueHex:X})}).toSchema().toBER(!1),xe=n.getAlgorithmByOID(S.keyEncryptionAlgorithm.algorithmId,!0,"ecdhAlgorithm");if(!xe.name)throw new Error(`Incorrect OID for key encryption algorithm: ${S.keyEncryptionAlgorithm.algorithmId}`);return qN(xe.kdf,W,Q.length,pe,n)}let q=await ne(),J=async L=>n.importKey("raw",L,{name:"AES-KW"},!0,["unwrapKey"]),ae=await J(q),Be=async L=>{let _=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,Q=n.getAlgorithmByOID(_,!0,"contentEncryptionAlgorithm");return n.unwrapKey("raw",S.recipientEncryptedKeys.encryptedKeys[0].encryptedKey.valueBlock.valueHexView,L,{name:"AES-KW"},Q,!0,["decrypt"])};try{return await Be(ae)}catch{let L=await ne(!0),_=await J(L);return Be(_)}},a=async w=>{let S=this.recipientInfos[w].value;if(!r.recipientPrivateKey)throw new Error('Parameter "recipientPrivateKey" is mandatory for "KeyTransRecipientInfo"');let C=n.getAlgorithmByOID(S.keyEncryptionAlgorithm.algorithmId,!0,"keyEncryptionAlgorithm");if(C.name==="RSA-OAEP"){let F=S.keyEncryptionAlgorithm.algorithmParams,M=new Nl({schema:F});if(C.hash=n.getAlgorithmByOID(M.hashAlgorithm.algorithmId),!("name"in C.hash))throw new Error(`Incorrect OID for hash algorithm: ${M.hashAlgorithm.algorithmId}`)}let k,x=n;re.isBufferSource(r.recipientPrivateKey)?k=await n.importKey("pkcs8",r.recipientPrivateKey,C,!0,["decrypt"]):(k=r.recipientPrivateKey,"crypto"in r&&r.crypto&&(x=r.crypto.subtle));let v=await x.decrypt(k.algorithm,k,S.encryptedKey.valueBlock.valueHexView),I=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,D=n.getAlgorithmByOID(I,!0,"contentEncryptionAlgorithm");if(!("name"in D))throw new Error(`Incorrect "contentEncryptionAlgorithm": ${I}`);return n.importKey("raw",v,D,!0,["decrypt"])},o=async w=>{let S=this.recipientInfos[w].value;if(!r.preDefinedData)throw new Error('Parameter "preDefinedData" is mandatory for "KEKRecipientInfo"');let C=n.getAlgorithmByOID(S.keyEncryptionAlgorithm.algorithmId,!0,"kekAlgorithm"),k=await n.importKey("raw",r.preDefinedData,C,!0,["unwrapKey"]),x=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,v=n.getAlgorithmByOID(x,!0,"contentEncryptionAlgorithm");if(!v.name)throw new Error(`Incorrect "contentEncryptionAlgorithm": ${x}`);return n.unwrapKey("raw",S.encryptedKey.valueBlock.valueHexView,k,C,v,!0,["decrypt"])},c=async w=>{let S=this.recipientInfos[w].value,C;if(!r.preDefinedData)throw new Error('Parameter "preDefinedData" is mandatory for "KEKRecipientInfo"');if(!S.keyDerivationAlgorithm)throw new Error('Please append encoded "keyDerivationAlgorithm"');if(!S.keyDerivationAlgorithm.algorithmParams)throw new Error('Incorrectly encoded "keyDerivationAlgorithm"');try{C=new $i({schema:S.keyDerivationAlgorithm.algorithmParams});}catch{throw new Error('Incorrectly encoded "keyDerivationAlgorithm"')}let k=await n.importKey("raw",r.preDefinedData,"PBKDF2",!1,["deriveKey"]),x=n.getAlgorithmByOID(S.keyEncryptionAlgorithm.algorithmId,!0,"keyEncryptionAlgorithm"),v=C.prf?n.getAlgorithmByOID(C.prf.algorithmId,!0,"prfAlgorithm").hash.name:"SHA-1",I=new Uint8Array(C.salt.valueBlock.valueHex),D=C.iterationCount,F=await n.deriveKey({name:"PBKDF2",hash:{name:v},salt:I,iterations:D},k,x,!0,["unwrapKey"]),M=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,W=n.getAlgorithmByOID(M,!0,"contentEncryptionAlgorithm");return n.unwrapKey("raw",S.encryptedKey.valueBlock.valueHexView,F,x,W,!0,["decrypt"])},u;switch(this.recipientInfos[e].variant){case 1:u=await a(e);break;case 2:u=await i(e);break;case 3:u=await o(e);break;case 4:u=await c(e);break;default:throw new Error(`Unknown recipient type in array with index ${e}`)}let l=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,h=n.getAlgorithmByOID(l,!0,"contentEncryptionAlgorithm"),m=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmParams.valueBlock.valueHex,y=new Uint8Array(m);if(!this.encryptedContentInfo.encryptedContent)throw new Error("Required property `encryptedContent` is empty");let g=this.encryptedContentInfo.getEncryptedContent();return n.decrypt({name:h.name,iv:y},u,g)}};Ym.CLASS_NAME="EnvelopedData";var zc="safeContents",Pf="parsedValue",nk="contentInfos",Zm=class s extends O{constructor(e={}){super(),this.safeContents=d(e,zc,s.defaultValues(zc)),Pf in e&&(this.parsedValue=d(e,Pf,s.defaultValues(Pf))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case zc:return [];case Pf:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case zc:return t.length===0;case Pf:return t instanceof Object&&Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new fe({name:t.contentInfos||p,value:tt.schema()})]})}fromSchema(e){V(e,[nk]);let t=R(e,e,s.schema({names:{contentInfos:nk}}));T.assertSchema(t,this.className),this.safeContents=Array.from(t.result.contentInfos,n=>new tt({schema:n}));}toSchema(){return new b({value:Array.from(this.safeContents,e=>e.toSchema())})}toJSON(){return {safeContents:Array.from(this.safeContents,e=>e.toJSON())}}async parseInternalValues(e,t=ve(!0)){if(Re.assert(e,zc),$e.assert(e.safeContents,zc,"Array"),e.safeContents.length!==this.safeContents.length)throw new $e('Length of "parameters.safeContents" must be equal to "this.safeContents.length"');this.parsedValue={safeContents:[]};for(let[n,r]of this.safeContents.entries()){let i=e.safeContents[n],a=`parameters.safeContents[${n}]`;switch(r.contentType){case bA:{$e.assert(r.content,"this.safeContents[j].content",U);let o=r.content.getValue();this.parsedValue.safeContents.push({privacyMode:0,value:Mi.fromBER(o)});}break;case gk:{let o=new Ym({schema:r.content});Re.assert(a,i,"recipientCertificate","recipientKey");let c=i,u=c.recipientCertificate,l=c.recipientKey,h=await o.decrypt(0,{recipientCertificate:u,recipientPrivateKey:l},t);this.parsedValue.safeContents.push({privacyMode:2,value:Mi.fromBER(h)});}break;case yk:{let o=new Qo({schema:r.content});Re.assert(a,i,"password");let c=i.password,u=await o.decrypt({password:c},t);this.parsedValue.safeContents.push({privacyMode:1,value:Mi.fromBER(u)});}break;default:throw new Error(`Unknown "contentType" for AuthenticatedSafe: " ${r.contentType}`)}}}async makeInternalValues(e,t=ve(!0)){if(!this.parsedValue)throw new Error('Please run "parseValues" first or add "parsedValue" manually');if($e.assert(this.parsedValue,"this.parsedValue","object"),$e.assert(this.parsedValue.safeContents,"this.parsedValue.safeContents","Array"),$e.assert(e,"parameters","object"),Re.assert(e,"safeContents"),$e.assert(e.safeContents,"parameters.safeContents","Array"),e.safeContents.length!==this.parsedValue.safeContents.length)throw new $e('Length of "parameters.safeContents" must be equal to "this.parsedValue.safeContents"');this.safeContents=[];for(let[n,r]of this.parsedValue.safeContents.entries())switch(Re.assert("content",r,"privacyMode","value"),$e.assert(r.value,"content.value",Mi),r.privacyMode){case 0:{let i=r.value.toSchema().toBER(!1);this.safeContents.push(new tt({contentType:"1.2.840.113549.1.7.1",content:new U({valueHex:i})}));}break;case 1:{let i=new Qo,a=e.safeContents[n];a.contentToEncrypt=r.value.toSchema().toBER(!1),await i.encrypt(a,t),this.safeContents.push(new tt({contentType:"1.2.840.113549.1.7.6",content:i.toSchema()}));}break;case 2:{let i=new Ym,a=r.value.toSchema().toBER(!1),o=e.safeContents[n];switch(Re.assert(`parameters.safeContents[${n}]`,o,"encryptingCertificate","encryptionAlgorithm"),!0){case o.encryptionAlgorithm.name.toLowerCase()==="aes-cbc":case o.encryptionAlgorithm.name.toLowerCase()==="aes-gcm":break;default:throw new Error(`Incorrect parameter "encryptionAlgorithm" in "parameters.safeContents[i]": ${o.encryptionAlgorithm}`)}switch(!0){case o.encryptionAlgorithm.length===128:case o.encryptionAlgorithm.length===192:case o.encryptionAlgorithm.length===256:break;default:throw new Error(`Incorrect parameter "encryptionAlgorithm.length" in "parameters.safeContents[i]": ${o.encryptionAlgorithm.length}`)}let c=o.encryptionAlgorithm;i.addRecipientByCertificate(o.encryptingCertificate,{},void 0,t),await i.encrypt(c,a,t),this.safeContents.push(new tt({contentType:"1.2.840.113549.1.7.3",content:i.toSchema()}));}break;default:throw new Error(`Incorrect value for "content.privacyMode": ${r.privacyMode}`)}return this}};Zm.CLASS_NAME="AuthenticatedSafe";var Co="hashAlgorithm",qu="issuerNameHash",Fu="issuerKeyHash",No="serialNumber",$D=[Co,qu,Fu,No],ns=class s extends O{static async create(e,t,n=ve(!0)){let r=new s;return await r.createForCertificate(e,t,n),r}constructor(e={}){super(),this.hashAlgorithm=d(e,Co,s.defaultValues(Co)),this.issuerNameHash=d(e,qu,s.defaultValues(qu)),this.issuerKeyHash=d(e,Fu,s.defaultValues(Fu)),this.serialNumber=d(e,No,s.defaultValues(No)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Co:return new P;case qu:case Fu:return new U;case No:return new N;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Co:return t.algorithmId===p&&!("algorithmParams"in t);case qu:case Fu:case No:return t.isEqual(s.defaultValues(No));default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.hashAlgorithmObject||{names:{blockName:t.hashAlgorithm||p}}),new U({name:t.issuerNameHash||p}),new U({name:t.issuerKeyHash||p}),new N({name:t.serialNumber||p})]})}fromSchema(e){V(e,$D);let t=R(e,e,s.schema({names:{hashAlgorithm:Co,issuerNameHash:qu,issuerKeyHash:Fu,serialNumber:No}}));T.assertSchema(t,this.className),this.hashAlgorithm=new P({schema:t.result.hashAlgorithm}),this.issuerNameHash=t.result.issuerNameHash,this.issuerKeyHash=t.result.issuerKeyHash,this.serialNumber=t.result.serialNumber;}toSchema(){return new b({value:[this.hashAlgorithm.toSchema(),this.issuerNameHash,this.issuerKeyHash,this.serialNumber]})}toJSON(){return {hashAlgorithm:this.hashAlgorithm.toJSON(),issuerNameHash:this.issuerNameHash.toJSON(),issuerKeyHash:this.issuerKeyHash.toJSON(),serialNumber:this.serialNumber.toJSON()}}isEqual(e){return !(this.hashAlgorithm.algorithmId!==e.hashAlgorithm.algorithmId||!re.isEqual(this.issuerNameHash.valueBlock.valueHexView,e.issuerNameHash.valueBlock.valueHexView)||!re.isEqual(this.issuerKeyHash.valueBlock.valueHexView,e.issuerKeyHash.valueBlock.valueHexView)||!this.serialNumber.isEqual(e.serialNumber))}async createForCertificate(e,t,n=ve(!0)){Re.assert(t,Co,"issuerCertificate");let r=n.getOIDByAlgorithm({name:t.hashAlgorithm},!0,"hashAlgorithm");this.hashAlgorithm=new P({algorithmId:r,algorithmParams:new Xe});let i=t.issuerCertificate;this.serialNumber=e.serialNumber;let a=await n.digest({name:t.hashAlgorithm},i.subject.toSchema().toBER(!1));this.issuerNameHash=new U({valueHex:a});let o=i.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView,c=await n.digest({name:t.hashAlgorithm},o);this.issuerKeyHash=new U({valueHex:c});}};ns.CLASS_NAME="CertID";var Ku="certID",Gu="certStatus",Wu="thisUpdate",Bi="nextUpdate",ko="singleExtensions",qD=[Ku,Gu,Wu,Bi,ko],Qm=class s extends O{constructor(e={}){super(),this.certID=d(e,Ku,s.defaultValues(Ku)),this.certStatus=d(e,Gu,s.defaultValues(Gu)),this.thisUpdate=d(e,Wu,s.defaultValues(Wu)),Bi in e&&(this.nextUpdate=d(e,Bi,s.defaultValues(Bi))),ko in e&&(this.singleExtensions=d(e,ko,s.defaultValues(ko))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ku:return new ns;case Gu:return {};case Wu:case Bi:return new Date(0,0,0);case ko:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Ku:return ns.compareWithDefault("hashAlgorithm",t.hashAlgorithm)&&ns.compareWithDefault("issuerNameHash",t.issuerNameHash)&&ns.compareWithDefault("issuerKeyHash",t.issuerKeyHash)&&ns.compareWithDefault("serialNumber",t.serialNumber);case Gu:return Object.keys(t).length===0;case Wu:case Bi:return t===s.defaultValues(e);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[ns.schema(t.certID||{}),new We({value:[new ie({name:t.certStatus||p,idBlock:{tagClass:3,tagNumber:0}}),new A({name:t.certStatus||p,idBlock:{tagClass:3,tagNumber:1},value:[new Ge,new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new pn]})]}),new ie({name:t.certStatus||p,idBlock:{tagClass:3,tagNumber:2},lenBlock:{length:1}})]}),new Ge({name:t.thisUpdate||p}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new Ge({name:t.nextUpdate||p})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[ft.schema(t.singleExtensions||{})]})]})}fromSchema(e){V(e,qD);let t=R(e,e,s.schema({names:{certID:{names:{blockName:Ku}},certStatus:Gu,thisUpdate:Wu,nextUpdate:Bi,singleExtensions:{names:{blockName:ko}}}}));T.assertSchema(t,this.className),this.certID=new ns({schema:t.result.certID}),this.certStatus=t.result.certStatus,this.thisUpdate=t.result.thisUpdate.toDate(),Bi in t.result&&(this.nextUpdate=t.result.nextUpdate.toDate()),ko in t.result&&(this.singleExtensions=Array.from(t.result.singleExtensions.valueBlock.value,n=>new ds({schema:n})));}toSchema(){let e=[];return e.push(this.certID.toSchema()),e.push(this.certStatus),e.push(new Ge({valueDate:this.thisUpdate})),this.nextUpdate&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[new Ge({valueDate:this.nextUpdate})]})),this.singleExtensions&&e.push(new A({idBlock:{tagClass:3,tagNumber:1},value:[new b({value:Array.from(this.singleExtensions,t=>t.toSchema())})]})),new b({value:e})}toJSON(){let e={certID:this.certID.toJSON(),certStatus:this.certStatus.toJSON(),thisUpdate:this.thisUpdate};return this.nextUpdate&&(e.nextUpdate=this.nextUpdate),this.singleExtensions&&(e.singleExtensions=Array.from(this.singleExtensions,t=>t.toJSON())),e}};Qm.CLASS_NAME="SingleResponse";var by="tbs",Po="version",cm="responderID",um="producedAt",lm="responses",Ju="responseExtensions",Xo="ResponseData",By=`${Xo}.${Po}`,zu=`${Xo}.${cm}`,q2=`${Xo}.${um}`,F2=`${Xo}.${lm}`,Oy=`${Xo}.${Ju}`,FD=[Xo,By,zu,q2,F2,Oy],Xs=class s extends O{get tbs(){return re.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e);}constructor(e={}){super(),this.tbsView=new Uint8Array(d(e,by,s.defaultValues(by))),Po in e&&(this.version=d(e,Po,s.defaultValues(Po))),this.responderID=d(e,cm,s.defaultValues(cm)),this.producedAt=d(e,um,s.defaultValues(um)),this.responses=d(e,lm,s.defaultValues(lm)),Ju in e&&(this.responseExtensions=d(e,Ju,s.defaultValues(Ju))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Po:return 0;case by:return ut;case cm:return {};case um:return new Date(0,0,0);case lm:case Ju:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case by:return t.byteLength===0;case cm:return Object.keys(t).length===0;case um:return t===s.defaultValues(e);case lm:case Ju:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||Xo,value:[new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new N({name:t.version||By})]}),new We({value:[new A({name:t.responderID||zu,idBlock:{tagClass:3,tagNumber:1},value:[Je.schema(t.ResponseDataByName||{names:{blockName:"ResponseData.byName"}})]}),new A({name:t.responderID||zu,idBlock:{tagClass:3,tagNumber:2},value:[new U({name:t.ResponseDataByKey||"ResponseData.byKey"})]})]}),new Ge({name:t.producedAt||q2}),new b({value:[new fe({name:F2,value:Qm.schema(t.response||{})})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[ft.schema(t.extensions||{names:{blockName:Oy}})]})]})}fromSchema(e){V(e,FD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.tbsView=t.result.ResponseData.valueBeforeDecodeView,By in t.result&&(this.version=t.result[By].valueBlock.valueDec),t.result[zu].idBlock.tagNumber===1?this.responderID=new Je({schema:t.result[zu].valueBlock.value[0]}):this.responderID=t.result[zu].valueBlock.value[0],this.producedAt=t.result[q2].toDate(),this.responses=Array.from(t.result[F2],n=>new Qm({schema:n})),Oy in t.result&&(this.responseExtensions=Array.from(t.result[Oy].valueBlock.value,n=>new ds({schema:n})));}toSchema(e=!1){let t;if(e===!1){if(!this.tbsView.byteLength)return s.schema();let n=ht(this.tbsView);T.assert(n,"TBS Response Data"),t=n.result;}else {let n=[];Po in this&&n.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[new N({value:this.version})]})),this.responderID instanceof Je?n.push(new A({idBlock:{tagClass:3,tagNumber:1},value:[this.responderID.toSchema()]})):n.push(new A({idBlock:{tagClass:3,tagNumber:2},value:[this.responderID]})),n.push(new Ge({valueDate:this.producedAt})),n.push(new b({value:Array.from(this.responses,r=>r.toSchema())})),this.responseExtensions&&n.push(new A({idBlock:{tagClass:3,tagNumber:1},value:[new b({value:Array.from(this.responseExtensions,r=>r.toSchema())})]})),t=new b({value:n});}return t}toJSON(){let e={};return Po in this&&(e.version=this.version),this.responderID&&(e.responderID=this.responderID),this.producedAt&&(e.producedAt=this.producedAt),this.responses&&(e.responses=Array.from(this.responses,t=>t.toJSON())),this.responseExtensions&&(e.responseExtensions=Array.from(this.responseExtensions,t=>t.toJSON())),e}};Xs.CLASS_NAME="ResponseData";var I2="trustedCerts",C2="certs",N2="crls",k2="ocsps",P2="checkDate",T2="findOrigin",B2="findIssuer",Ho;(function(s){s[s.unknown=-1]="unknown",s[s.success=0]="success",s[s.noRevocation=11]="noRevocation",s[s.noPath=60]="noPath",s[s.noValidPath=97]="noValidPath";})(Ho||(Ho={}));var Hi=class s extends Error{constructor(e,t){super(t),this.name=s.NAME,this.code=e,this.message=t;}};Hi.NAME="ChainValidationError";function KD(s,e){for(let t=0;t<e.length;t++)if(re.isEqual(s.tbsView,e[t].tbsView))return !0;return !1}var Xm=class s{constructor(e={}){this.trustedCerts=d(e,I2,this.defaultValues(I2)),this.certs=d(e,C2,this.defaultValues(C2)),this.crls=d(e,N2,this.defaultValues(N2)),this.ocsps=d(e,k2,this.defaultValues(k2)),this.checkDate=d(e,P2,this.defaultValues(P2)),this.findOrigin=d(e,T2,this.defaultValues(T2)),this.findIssuer=d(e,B2,this.defaultValues(B2));}static defaultFindOrigin(e,t){e.tbsView.byteLength===0&&(e.tbsView=new Uint8Array(e.encodeTBS().toBER()));for(let n of t.certs)if(n.tbsView.byteLength===0&&(n.tbsView=new Uint8Array(n.encodeTBS().toBER())),re.isEqual(e.tbsView,n.tbsView))return "Intermediate Certificates";for(let n of t.trustedCerts)if(n.tbsView.byteLength===0&&(n.tbsView=new Uint8Array(n.encodeTBS().toBER())),re.isEqual(e.tbsView,n.tbsView))return "Trusted Certificates";return "Unknown"}async defaultFindIssuer(e,t,n=ve(!0)){let r=[],i=null,a=null,o=null;if(e.subject.isEqual(e.issuer))try{if(await e.verify(void 0,n))return [e]}catch{}if(e.extensions){for(let u of e.extensions)if(u.extnID===yA&&u.parsedValue instanceof Bm){u.parsedValue.keyIdentifier?i=u.parsedValue.keyIdentifier:(u.parsedValue.authorityCertIssuer&&(a=u.parsedValue.authorityCertIssuer),u.parsedValue.authorityCertSerialNumber&&(o=u.parsedValue.authorityCertSerialNumber));break}}function c(u){if(i!==null&&u.extensions){let h=!1;for(let m of u.extensions)if(m.extnID===Z7&&m.parsedValue){h=!0,re.isEqual(m.parsedValue.valueBlock.valueHex,i.valueBlock.valueHexView)&&r.push(u);break}if(h)return}let l=!1;o!==null&&(l=u.serialNumber.isEqual(o)),a!==null?u.subject.isEqual(a)&&l&&r.push(u):e.issuer.isEqual(u.subject)&&r.push(u);}for(let u of t.trustedCerts)c(u);for(let u of t.certs)c(u);for(let u=r.length-1;u>=0;u--)try{await e.verify(r[u],n)===!1&&r.splice(u,1);}catch{r.splice(u,1);}return r}defaultValues(e){switch(e){case I2:return [];case C2:return [];case N2:return [];case k2:return [];case P2:return new Date;case T2:return s.defaultFindOrigin;case B2:return this.defaultFindIssuer;default:throw new Error(`Invalid member name for CertificateChainValidationEngine class: ${e}`)}}async sort(e=!1,t=ve(!0)){let n=[],r=async(g,w)=>{let S=[];function C(x){let v=!0;for(let I=0;I<x.length;I++){for(let D=0;D<x.length;D++)if(D!==I&&x[I]===x[D]){v=!1;break}if(!v)break}return v}if(KD(g,this.trustedCerts))return [[g]];let k=await this.findIssuer(g,this,w);if(k.length===0)throw new Error("No valid certificate paths found");for(let x=0;x<k.length;x++){if(re.isEqual(k[x].tbsView,g.tbsView)){S.push([k[x]]);continue}let v=await r(k[x],w);for(let I=0;I<v.length;I++){let D=v[I].slice();D.splice(0,0,k[x]),C(D)?S.push(D):S.push(v[I]);}}return S},i=async g=>{let w=[],S=[],C=[];if(w.push(...n.filter(k=>g.issuer.isEqual(k.subject))),w.length===0)return {status:1,statusMessage:"No certificate's issuers"};if(S.push(...this.crls.filter(k=>k.issuer.isEqual(g.issuer))),S.length===0)return {status:2,statusMessage:"No CRLs for specific certificate issuer"};for(let k=0;k<S.length;k++){let x=S[k];if(!(x.nextUpdate&&x.nextUpdate.value<this.checkDate))for(let v=0;v<w.length;v++)try{if(await S[k].verify({issuerCertificate:w[v]},t)){C.push({crl:S[k],certificate:w[v]});break}}catch{}}return C.length?{status:0,statusMessage:p,result:C}:{status:3,statusMessage:"No valid CRLs found"}},a=async(g,w)=>{let S=t.getAlgorithmByOID(g.signatureAlgorithm.algorithmId);if(!S.name||!S.hash)return 1;for(let C=0;C<this.ocsps.length;C++){let x=await this.ocsps[C].getCertificateStatus(g,w,t);if(x.isForCertificate)return x.status===0?0:1}return 2};async function o(g,w=!1){let S=!1,C=!1,k=!1,x=!1;if(g.extensions){for(let v=0;v<g.extensions.length;v++){let I=g.extensions[v];if(I.critical&&!I.parsedValue)return {result:!1,resultCode:6,resultMessage:`Unable to parse critical certificate extension: ${I.extnID}`};if(I.extnID===Q7){k=!0;let D=new Uint8Array(I.parsedValue.valueBlock.valueHex);(D[0]&4)===4&&(C=!0),(D[0]&2)===2&&(x=!0);}I.extnID===pA&&"cA"in I.parsedValue&&I.parsedValue.cA===!0&&(S=!0);}if(C===!0&&S===!1)return {result:!1,resultCode:3,resultMessage:'Unable to build certificate chain - using "keyCertSign" flag set without BasicConstraints'};if(k===!0&&S===!0&&C===!1)return {result:!1,resultCode:4,resultMessage:'Unable to build certificate chain - "keyCertSign" flag was not set'};if(S===!0&&k===!0&&w&&x===!1)return {result:!1,resultCode:5,resultMessage:'Unable to build certificate chain - intermediate certificate must have "cRLSign" key usage flag'}}return S===!1?{result:!1,resultCode:7,resultMessage:"Unable to build certificate chain - more than one possible end-user certificate"}:{result:!0,resultCode:0,resultMessage:p}}let c=async(g,w)=>{for(let S=0;S<g.length;S++)if(g[S].notBefore.value>w||g[S].notAfter.value<w)return {result:!1,resultCode:8,resultMessage:"The certificate is either not yet valid or expired"};if(g.length<2)return {result:!1,resultCode:9,resultMessage:"Too short certificate path"};for(let S=g.length-2;S>=0;S--)if(g[S].issuer.isEqual(g[S].subject)===!1&&g[S].issuer.isEqual(g[S+1].subject)===!1)return {result:!1,resultCode:10,resultMessage:"Incorrect name chaining"};if(this.crls.length!==0||this.ocsps.length!==0)for(let S=0;S<g.length-1;S++){let C=2,k={status:0,statusMessage:p};if(this.ocsps.length!==0)switch(C=await a(g[S],g[S+1]),C){case 0:continue;case 1:return {result:!1,resultCode:12,resultMessage:"One of certificates was revoked via OCSP response"}}if(this.crls.length!==0){if(k=await i(g[S]),k.status===0&&k.result)for(let x=0;x<k.result.length;x++){if(k.result[x].crl.isCertificateRevoked(g[S]))return {result:!1,resultCode:12,resultMessage:"One of certificates had been revoked"};if((await o(k.result[x].certificate,!0)).result===!1)return {result:!1,resultCode:13,resultMessage:"CRL issuer certificate is not a CA certificate or does not have crlSign flag"}}else if(e===!1)throw new Hi(Ho.noRevocation,`No revocation values found for one of certificates: ${k.statusMessage}`)}else if(C===2)return {result:!1,resultCode:11,resultMessage:"No revocation values found for one of certificates"};if(C===2&&k.status===2&&e){let x=g[S+1],v=!1;if(x.extensions)for(let I of x.extensions)switch(I.extnID){case hk:case gA:case wA:v=!0;break}if(v)throw new Hi(Ho.noRevocation,`No revocation values found for one of certificates: ${k.statusMessage}`)}}for(let[S,C]of g.entries()){if(!S)continue;if(!(await o(C)).result)return {result:!1,resultCode:14,resultMessage:"One of intermediate certificates is not a CA certificate"}}return {result:!0}};n.push(...this.trustedCerts),n.push(...this.certs);for(let g=0;g<n.length;g++)for(let w=0;w<n.length;w++)if(g!==w&&re.isEqual(n[g].tbsView,n[w].tbsView)){n.splice(w,1),g=0;break}let u=n[n.length-1],l,h=[u];if(l=await r(u,t),l.length===0)throw new Hi(Ho.noPath,"Unable to find certificate path");for(let g=l.length-1;g>=0;g--){let w=!1;for(let S=0;S<l[g].length;S++){let C=l[g][S];for(let k=0;k<this.trustedCerts.length;k++)if(re.isEqual(C.tbsView,this.trustedCerts[k].tbsView)){w=!0;break}if(w)break}w||l.splice(g,1);}if(l.length===0)throw new Hi(Ho.noValidPath,"No valid certificate paths found");let m=l[0].length,y=0;for(let g=0;g<l.length;g++)l[g].length<m&&(m=l[g].length,y=g);for(let g=0;g<l[y].length;g++)h.push(l[y][g]);if(l=await c(h,this.checkDate),l.result===!1)throw l;return h}async verify(e={},t=ve(!0)){function n(c,u){let l=ji(c),h=ji(u),m=l.split("."),y=h.split("."),g=m.length,w=y.length;if(g===0||w===0||g<w)return !1;for(let S=0;S<g;S++)if(m[S].length===0)return !1;for(let S=0;S<w;S++)if(y[S].length===0){if(S===0){if(w===1)return !1;continue}return !1}for(let S=0;S<w;S++)if(y[w-1-S].length!==0&&m[g-1-S].localeCompare(y[w-1-S])!==0)return !1;return !0}function r(c,u){let l=ji(c),h=ji(u),m=l.split("@"),y=h.split("@");if(m.length===0||y.length===0||m.length<y.length)return !1;if(y.length===1){if(n(m[1],y[0])){let w=m[1].split("."),S=y[0].split(".");return S[0].length===0?!0:w.length===S.length}return !1}return l.localeCompare(h)===0}function i(c,u){let l=ji(c),h=ji(u),m=l.split("/");if(h.split("/").length>1)return !1;if(m.length>1){for(let w=0;w<m.length;w++)if(m[w].length>0&&m[w].charAt(m[w].length-1)!==":"){l=m[w].split(":")[0];break}}if(n(l,h)){let w=l.split("."),S=h.split(".");return S[0].length===0?!0:w.length===S.length}return !1}function a(c,u){let l=c.valueBlock.valueHexView,h=u.valueBlock.valueHexView;if(l.length===4&&h.length===8){for(let m=0;m<4;m++)if((l[m]^h[m])&h[m+4])return !1;return !0}if(l.length===16&&h.length===32){for(let m=0;m<16;m++)if((l[m]^h[m])&h[m+16])return !1;return !0}return !1}function o(c,u){if(c.typesAndValues.length===0||u.typesAndValues.length===0)return !0;if(c.typesAndValues.length<u.typesAndValues.length)return !1;let l=!0,h=0;for(let m=0;m<u.typesAndValues.length;m++){let y=!1;for(let g=h;g<c.typesAndValues.length;g++)if(y=c.typesAndValues[g].isEqual(u.typesAndValues[m]),c.typesAndValues[g].type===u.typesAndValues[m].type&&(l=l&&y),y===!0)if(h===0||h===g){h=g+1;break}else return !1;if(y===!1)return !1}return h===0?!1:l}try{if(this.certs.length===0)throw new Error("Empty certificate array");let c=e.passedWhenNotRevValues||!1,u=e.initialPolicySet||[Ps],l=e.initialExplicitPolicy||!1,h=e.initialPolicyMappingInhibit||!1,m=e.initialInhibitPolicy||!1,y=e.initialPermittedSubtreesSet||[],g=e.initialExcludedSubtreesSet||[],w=e.initialRequiredNameForms||[],S=l,C=h,k=m,x=[!1,!1,!1],v=0,I=0,D=0,F=y,M=g,W=w,ne=1;this.certs=await this.sort(c,t);let q=[];q.push(Ps);let J=[],ae=new Array(this.certs.length-1);for(let j=0;j<this.certs.length-1;j++)ae[j]=!0;J.push(ae);let Be=new Array(this.certs.length-1),L=new Array(this.certs.length-1),_=S?this.certs.length-1:-1;for(let j=this.certs.length-2;j>=0;j--,ne++){let z=this.certs[j];if(z.extensions){for(let Y=0;Y<z.extensions.length;Y++){let pe=z.extensions[Y];if(pe.extnID===fk){L[j]=pe.parsedValue;for(let xe=0;xe<q.length;xe++)if(q[xe]===Ps){delete J[xe][j];break}for(let xe=0;xe<pe.parsedValue.certificatePolicies.length;xe++){let Ve=-1,jt=pe.parsedValue.certificatePolicies[xe].policyIdentifier;for(let He=0;He<q.length;He++)if(jt===q[He]){Ve=He;break}if(Ve===-1){q.push(jt);let He=new Array(this.certs.length-1);He[j]=!0,J.push(He);}else J[Ve][j]=!0;}}if(pe.extnID===dk){if(C)return {result:!1,resultCode:98,resultMessage:"Policy mapping prohibited"};Be[j]=pe.parsedValue;}pe.extnID===mk&&S===!1&&(pe.parsedValue.requireExplicitPolicy===0?(S=!0,_=j):x[0]===!1?(x[0]=!0,v=pe.parsedValue.requireExplicitPolicy):v=v>pe.parsedValue.requireExplicitPolicy?pe.parsedValue.requireExplicitPolicy:v,pe.parsedValue.inhibitPolicyMapping===0?C=!0:x[1]===!1?(x[1]=!0,I=pe.parsedValue.inhibitPolicyMapping+1):I=I>pe.parsedValue.inhibitPolicyMapping+1?pe.parsedValue.inhibitPolicyMapping+1:I),pe.extnID===a9&&k===!1&&(pe.parsedValue.valueBlock.valueDec===0?k=!0:x[2]===!1?(x[2]=!0,D=pe.parsedValue.valueBlock.valueDec):D=D>pe.parsedValue.valueBlock.valueDec?pe.parsedValue.valueBlock.valueDec:D);}if(k===!0){let Y=-1;for(let pe=0;pe<q.length;pe++)if(q[pe]===Ps){Y=pe;break}Y!==-1&&delete J[0][j];}S===!1&&x[0]===!0&&(v--,v===0&&(S=!0,_=j,x[0]=!1)),C===!1&&x[1]===!0&&(I--,I===0&&(C=!0,x[1]=!1)),k===!1&&x[2]===!0&&(D--,D===0&&(k=!0,x[2]=!1));}}for(let j=0;j<this.certs.length-1;j++)if(j<this.certs.length-2&&typeof Be[j+1]<"u")for(let z=0;z<Be[j+1].mappings.length;z++){if(Be[j+1].mappings[z].issuerDomainPolicy===Ps||Be[j+1].mappings[z].subjectDomainPolicy===Ps)return {result:!1,resultCode:99,resultMessage:'The "anyPolicy" should not be a part of policy mapping scheme'};let Y=-1,pe=-1;for(let xe=0;xe<q.length;xe++)q[xe]===Be[j+1].mappings[z].issuerDomainPolicy&&(Y=xe),q[xe]===Be[j+1].mappings[z].subjectDomainPolicy&&(pe=xe);typeof J[Y][j]<"u"&&delete J[Y][j];for(let xe=0;xe<L[j].certificatePolicies.length;xe++)if(Be[j+1].mappings[z].subjectDomainPolicy===L[j].certificatePolicies[xe].policyIdentifier&&Y!==-1&&pe!==-1)for(let Ve=0;Ve<=j;Ve++)typeof J[pe][Ve]<"u"&&(J[Y][Ve]=!0,delete J[pe][Ve]);}for(let j=0;j<q.length;j++)if(q[j]===Ps)for(let z=0;z<_;z++)delete J[j][z];let Q=[];for(let j=0;j<J.length;j++){let z=!0;for(let Y=0;Y<this.certs.length-1;Y++){let pe=!1;if(Y<_&&q[j]===Ps&&q.length>1){z=!1;break}if(typeof J[j][Y]>"u"){if(Y>=_){for(let xe=0;xe<q.length;xe++)if(q[xe]===Ps){J[xe][Y]===!0&&(pe=!0);break}}if(!pe){z=!1;break}}}z===!0&&Q.push(q[j]);}let me=[];if(u.length===1&&u[0]===Ps&&S===!1)me=u;else if(Q.length===1&&Q[0]===Ps)me=u;else for(let j=0;j<Q.length;j++)for(let z=0;z<u.length;z++)if(u[z]===Q[j]||u[z]===Ps){me.push(Q[j]);break}let X={result:me.length>0,resultCode:0,resultMessage:me.length>0?p:'Zero "userConstrPolicies" array, no intersections with "authConstrPolicies"',authConstrPolicies:Q,userConstrPolicies:me,explicitPolicyIndicator:S,policyMappings:Be,certificatePath:this.certs};if(me.length===0||X.result===!1)return X;ne=1;for(let j=this.certs.length-2;j>=0;j--,ne++){let z=this.certs[j],Y=[],pe=[],xe=[];if(z.extensions)for(let ke=0;ke<z.extensions.length;ke++){let ee=z.extensions[ke];ee.extnID===lk&&("permittedSubtrees"in ee.parsedValue&&(pe=pe.concat(ee.parsedValue.permittedSubtrees)),"excludedSubtrees"in ee.parsedValue&&(xe=xe.concat(ee.parsedValue.excludedSubtrees))),ee.extnID===ak&&(Y=Y.concat(ee.parsedValue.altNames));}let Ve=W.length<=0;for(let ke=0;ke<W.length;ke++)switch(W[ke].base.type){case 4:{if(W[ke].base.value.typesAndValues.length!==z.subject.typesAndValues.length)continue;Ve=!0;for(let ee=0;ee<z.subject.typesAndValues.length;ee++)if(z.subject.typesAndValues[ee].type!==W[ke].base.value.typesAndValues[ee].type){Ve=!1;break}if(Ve===!0)break}break;default:}if(Ve===!1)throw X.result=!1,X.resultCode=21,X.resultMessage="No necessary name form found",X;let jt=[[],[],[],[],[]];for(let ke=0;ke<F.length;ke++)switch(F[ke].base.type){case 1:jt[0].push(F[ke]);break;case 2:jt[1].push(F[ke]);break;case 4:jt[2].push(F[ke]);break;case 6:jt[3].push(F[ke]);break;case 7:jt[4].push(F[ke]);break;default:}for(let ke=0;ke<5;ke++){let ee=!1,rs=!1,Cs=jt[ke];for(let is=0;is<Cs.length;is++){switch(ke){case 0:if(Y.length>0)for(let De=0;De<Y.length;De++)Y[De].type===1&&(rs=!0,ee=ee||r(Y[De].value,Cs[is].base.value));else for(let De=0;De<z.subject.typesAndValues.length;De++)(z.subject.typesAndValues[De].type==="1.2.840.113549.1.9.1"||z.subject.typesAndValues[De].type==="0.9.2342.19200300.100.1.3")&&(rs=!0,ee=ee||r(z.subject.typesAndValues[De].value.valueBlock.value,Cs[is].base.value));break;case 1:if(Y.length>0)for(let De=0;De<Y.length;De++)Y[De].type===2&&(rs=!0,ee=ee||n(Y[De].value,Cs[is].base.value));break;case 2:rs=!0,ee=o(z.subject,Cs[is].base.value);break;case 3:if(Y.length>0)for(let De=0;De<Y.length;De++)Y[De].type===6&&(rs=!0,ee=ee||i(Y[De].value,Cs[is].base.value));break;case 4:if(Y.length>0)for(let De=0;De<Y.length;De++)Y[De].type===7&&(rs=!0,ee=ee||a(Y[De].value,Cs[is].base.value));break;default:}if(ee)break}if(ee===!1&&Cs.length>0&&rs)throw X.result=!1,X.resultCode=41,X.resultMessage='Failed to meet "permitted sub-trees" name constraint',X}let He=!1;for(let ke=0;ke<M.length;ke++){switch(M[ke].base.type){case 1:if(Y.length>=0)for(let ee=0;ee<Y.length;ee++)Y[ee].type===1&&(He=He||r(Y[ee].value,M[ke].base.value));else for(let ee=0;ee<z.subject.typesAndValues.length;ee++)(z.subject.typesAndValues[ee].type==="1.2.840.113549.1.9.1"||z.subject.typesAndValues[ee].type==="0.9.2342.19200300.100.1.3")&&(He=He||r(z.subject.typesAndValues[ee].value.valueBlock.value,M[ke].base.value));break;case 2:if(Y.length>0)for(let ee=0;ee<Y.length;ee++)Y[ee].type===2&&(He=He||n(Y[ee].value,M[ke].base.value));break;case 4:He=He||o(z.subject,M[ke].base.value);break;case 6:if(Y.length>0)for(let ee=0;ee<Y.length;ee++)Y[ee].type===6&&(He=He||i(Y[ee].value,M[ke].base.value));break;case 7:if(Y.length>0)for(let ee=0;ee<Y.length;ee++)Y[ee].type===7&&(He=He||a(Y[ee].value,M[ke].base.value));break;default:}if(He)break}if(He===!0)throw X.result=!1,X.resultCode=42,X.resultMessage='Failed to meet "excluded sub-trees" name constraint',X;F=F.concat(pe),M=M.concat(xe);}return X}catch(c){return c instanceof Error?c instanceof Hi?{result:!1,resultCode:c.code,resultMessage:c.message,error:c}:{result:!1,resultCode:Ho.unknown,resultMessage:c.message,error:c}:c&&typeof c=="object"&&"resultMessage"in c?c:{result:!1,resultCode:-1,resultMessage:`${c}`}}}},Ry="tbsResponseData",hm="signatureAlgorithm",fm="signature",Yu="certs",e0="BasicOCSPResponse",K2=`${e0}.${Ry}`,G2=`${e0}.${hm}`,W2=`${e0}.${fm}`,Vy=`${e0}.${Yu}`,GD=[K2,G2,W2,Vy],zo=class s extends O{constructor(e={}){super(),this.tbsResponseData=d(e,Ry,s.defaultValues(Ry)),this.signatureAlgorithm=d(e,hm,s.defaultValues(hm)),this.signature=d(e,fm,s.defaultValues(fm)),Yu in e&&(this.certs=d(e,Yu,s.defaultValues(Yu))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Ry:return new Xs;case hm:return new P;case fm:return new Ae;case Yu:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case"type":{let n=Xs.compareWithDefault("tbs",t.tbs)&&Xs.compareWithDefault("responderID",t.responderID)&&Xs.compareWithDefault("producedAt",t.producedAt)&&Xs.compareWithDefault("responses",t.responses);return "responseExtensions"in t&&(n=n&&Xs.compareWithDefault("responseExtensions",t.responseExtensions)),n}case hm:return t.algorithmId===p&&!("algorithmParams"in t);case fm:return t.isEqual(s.defaultValues(e));case Yu:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||e0,value:[Xs.schema(t.tbsResponseData||{names:{blockName:K2}}),P.schema(t.signatureAlgorithm||{names:{blockName:G2}}),new Ae({name:t.signature||W2}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new b({value:[new fe({name:Vy,value:Lt.schema(t.certs||{})})]})]})]})}fromSchema(e){V(e,GD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.tbsResponseData=new Xs({schema:t.result[K2]}),this.signatureAlgorithm=new P({schema:t.result[G2]}),this.signature=t.result[W2],Vy in t.result&&(this.certs=Array.from(t.result[Vy],n=>new Lt({schema:n})));}toSchema(){let e=[];return e.push(this.tbsResponseData.toSchema()),e.push(this.signatureAlgorithm.toSchema()),e.push(this.signature),this.certs&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[new b({value:Array.from(this.certs,t=>t.toSchema())})]})),new b({value:e})}toJSON(){let e={tbsResponseData:this.tbsResponseData.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signature:this.signature.toJSON()};return this.certs&&(e.certs=Array.from(this.certs,t=>t.toJSON())),e}async getCertificateStatus(e,t,n=ve(!0)){let r={isForCertificate:!1,status:2},i={},a=[];for(let o of this.tbsResponseData.responses){let c=n.getAlgorithmByOID(o.certID.hashAlgorithm.algorithmId,!0,"CertID.hashAlgorithm");if(!i[c.name]){i[c.name]=1;let u=new ns;a.push(u),await u.createForCertificate(e,{hashAlgorithm:c.name,issuerCertificate:t},n);}}for(let o of this.tbsResponseData.responses)for(let c of a)if(o.certID.isEqual(c)){r.isForCertificate=!0;try{switch(o.certStatus.idBlock.isConstructed){case!0:o.certStatus.idBlock.tagNumber===1&&(r.status=1);break;case!1:switch(o.certStatus.idBlock.tagNumber){case 0:r.status=0;break;case 2:r.status=2;break;default:}break;default:}}catch{}return r}return r}async sign(e,t="SHA-1",n=ve(!0)){if(!e)throw new Error("Need to provide a private key for signing");let r=await n.getSignatureParameters(e,t),i=r.parameters.algorithm;if(!("name"in i))throw new Error("Empty algorithm");this.signatureAlgorithm=r.signatureAlgorithm,this.tbsResponseData.tbsView=new Uint8Array(this.tbsResponseData.toSchema(!0).toBER());let a=await n.signWithPrivateKey(this.tbsResponseData.tbsView,e,{algorithm:i});this.signature=new Ae({valueHex:a});}async verify(e={},t=ve(!0)){let n=null,r=-1,i=e.trustedCerts||[];if(!this.certs)throw new Error("No certificates attached to the BasicOCSPResponse");switch(!0){case this.tbsResponseData.responderID instanceof Je:for(let[u,l]of this.certs.entries())if(l.subject.isEqual(this.tbsResponseData.responderID)){r=u;break}break;case this.tbsResponseData.responderID instanceof U:for(let[u,l]of this.certs.entries()){let h=await t.digest({name:"sha-1"},l.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView);if(qr(h,this.tbsResponseData.responderID.valueBlock.valueHex)){r=u;break}}break;default:throw new Error("Wrong value for responderID")}if(r===-1)throw new Error("Correct certificate was not found in OCSP response");n=this.certs[r];let a=[n];for(let u of this.certs){let l=await Ek(u,n);l&&a.push(l);}if(!(await new Xm({certs:a,trustedCerts:i}).verify({},t)).result)throw new Error("Validation of signer's certificate failed");return t.verifyWithPublicKey(this.tbsResponseData.tbsView,this.signature,this.certs[r].subjectPublicKeyInfo,this.signatureAlgorithm)}};zo.CLASS_NAME="BasicOCSPResponse";var O2="tbs",R2="version",V2="subject",D2="subjectPublicKeyInfo",Yc="attributes",dm="signatureAlgorithm",mm="signatureValue",Hl="CertificationRequestInfo",kA=`${Hl}.version`,PA=`${Hl}.subject`,TA=`${Hl}.subjectPublicKeyInfo`,Cw=`${Hl}.attributes`,WD=[Hl,kA,PA,TA,Cw,dm,mm];function JD(s={}){let e=d(s,"names",{});return new b({name:e.CertificationRequestInfo||Hl,value:[new N({name:e.CertificationRequestInfoVersion||kA}),Je.schema(e.subject||{names:{blockName:PA}}),As.schema({names:{blockName:TA}}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new fe({optional:!0,name:e.CertificationRequestInfoAttributes||Cw,value:nt.schema(e.attributes||{})})]})]})}var J2=class s extends O{get tbs(){return re.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e);}constructor(e={}){super(),this.tbsView=new Uint8Array(d(e,O2,s.defaultValues(O2))),this.version=d(e,R2,s.defaultValues(R2)),this.subject=d(e,V2,s.defaultValues(V2)),this.subjectPublicKeyInfo=d(e,D2,s.defaultValues(D2)),Yc in e&&(this.attributes=d(e,Yc,s.defaultValues(Yc))),this.signatureAlgorithm=d(e,dm,s.defaultValues(dm)),this.signatureValue=d(e,mm,s.defaultValues(mm)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case O2:return ut;case R2:return 0;case V2:return new Je;case D2:return new As;case Yc:return [];case dm:return new P;case mm:return new Ae;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({value:[JD(t.certificationRequestInfo||{}),new b({name:t.signatureAlgorithm||dm,value:[new G,new ue({optional:!0})]}),new Ae({name:t.signatureValue||mm})]})}fromSchema(e){V(e,WD);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.tbsView=t.result.CertificationRequestInfo.valueBeforeDecodeView,this.version=t.result[kA].valueBlock.valueDec,this.subject=new Je({schema:t.result[PA]}),this.subjectPublicKeyInfo=new As({schema:t.result[TA]}),Cw in t.result&&(this.attributes=Array.from(t.result[Cw],n=>new nt({schema:n}))),this.signatureAlgorithm=new P({schema:t.result.signatureAlgorithm}),this.signatureValue=t.result.signatureValue;}encodeTBS(){let e=[new N({value:this.version}),this.subject.toSchema(),this.subjectPublicKeyInfo.toSchema()];return Yc in this&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.attributes||[],t=>t.toSchema())})),new b({value:e})}toSchema(e=!1){let t;if(e===!1){if(this.tbsView.byteLength===0)return s.schema();let n=ht(this.tbsView);T.assert(n,"PKCS#10 Certificate Request"),t=n.result;}else t=this.encodeTBS();return new b({value:[t,this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){let e={tbs:he.ToHex(this.tbsView),version:this.version,subject:this.subject.toJSON(),subjectPublicKeyInfo:this.subjectPublicKeyInfo.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()};return Yc in this&&(e.attributes=Array.from(this.attributes||[],t=>t.toJSON())),e}async sign(e,t="SHA-1",n=ve(!0)){if(!e)throw new Error("Need to provide a private key for signing");let r=await n.getSignatureParameters(e,t),i=r.parameters;this.signatureAlgorithm=r.signatureAlgorithm,this.tbsView=new Uint8Array(this.encodeTBS().toBER());let a=await n.signWithPrivateKey(this.tbsView,e,i);this.signatureValue=new Ae({valueHex:a});}async verify(e=ve(!0)){return e.verifyWithPublicKey(this.tbsView,this.signatureValue,this.subjectPublicKeyInfo,this.signatureAlgorithm)}async getPublicKey(e,t=ve(!0)){return t.getPublicKey(this.subjectPublicKeyInfo,this.signatureAlgorithm,e)}};J2.CLASS_NAME="CertificationRequest";var To="digestAlgorithm",Bo="digest",zD=[To,Bo],dr=class s extends O{constructor(e={}){super(),this.digestAlgorithm=d(e,To,s.defaultValues(To)),this.digest=d(e,Bo,s.defaultValues(Bo)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case To:return new P;case Bo:return new U;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case To:return P.compareWithDefault("algorithmId",t.algorithmId)&&!("algorithmParams"in t);case Bo:return t.isEqual(s.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.digestAlgorithm||{names:{blockName:To}}),new U({name:t.digest||Bo})]})}fromSchema(e){V(e,zD);let t=R(e,e,s.schema({names:{digestAlgorithm:{names:{blockName:To}},digest:Bo}}));T.assertSchema(t,this.className),this.digestAlgorithm=new P({schema:t.result.digestAlgorithm}),this.digest=t.result.digest;}toSchema(){return new b({value:[this.digestAlgorithm.toSchema(),this.digest]})}toJSON(){return {digestAlgorithm:this.digestAlgorithm.toJSON(),digest:this.digest.toJSON()}}};dr.CLASS_NAME="DigestInfo";var Zu="eContentType",Qs="eContent",YD=[Zu,Qs],mr=class s extends O{constructor(e={}){if(super(),this.eContentType=d(e,Zu,s.defaultValues(Zu)),Qs in e&&(this.eContent=d(e,Qs,s.defaultValues(Qs)),this.eContent.idBlock.tagClass===1&&this.eContent.idBlock.tagNumber===4&&this.eContent.idBlock.isConstructed===!1)){let t=new U({idBlock:{isConstructed:!0},isConstructed:!0}),n=0,r=this.eContent.valueBlock.valueHexView.slice().buffer,i=r.byteLength;for(;i>0;){let a=new Uint8Array(r,n,n+65536>r.byteLength?r.byteLength-n:65536),o=new ArrayBuffer(a.length),c=new Uint8Array(o);for(let u=0;u<c.length;u++)c[u]=a[u];t.valueBlock.value.push(new U({valueHex:o})),i-=a.length,n+=a.length;}this.eContent=t;}e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Zu:return p;case Qs:return new U;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Zu:return t===p;case Qs:return t.idBlock.tagClass===1&&t.idBlock.tagNumber===4?t.isEqual(s.defaultValues(Qs)):!1;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.eContentType||p}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new ue({name:t.eContent||p})]})]})}fromSchema(e){V(e,YD);let t=R(e,e,s.schema({names:{eContentType:Zu,eContent:Qs}}));T.assertSchema(t,this.className),this.eContentType=t.result.eContentType.valueBlock.toString(),Qs in t.result&&(this.eContent=t.result.eContent);}toSchema(){let e=[];return e.push(new G({value:this.eContentType})),this.eContent&&s.compareWithDefault(Qs,this.eContent)===!1&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[this.eContent]})),new b({value:e})}toJSON(){let e={eContentType:this.eContentType};return this.eContent&&s.compareWithDefault(Qs,this.eContent)===!1&&(e.eContent=this.eContent.toJSON()),e}};mr.CLASS_NAME="EncapsulatedContentInfo";var Oo="mac",Ro="macSalt",ar="iterations",ZD=[Oo,Ro,ar],wn=class s extends O{constructor(e={}){super(),this.mac=d(e,Oo,s.defaultValues(Oo)),this.macSalt=d(e,Ro,s.defaultValues(Ro)),ar in e&&(this.iterations=d(e,ar,s.defaultValues(ar))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Oo:return new dr;case Ro:return new U;case ar:return 1;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Oo:return dr.compareWithDefault("digestAlgorithm",t.digestAlgorithm)&&dr.compareWithDefault("digest",t.digest);case Ro:return t.isEqual(s.defaultValues(e));case ar:return t===s.defaultValues(e);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,optional:t.optional||!0,value:[dr.schema(t.mac||{names:{blockName:Oo}}),new U({name:t.macSalt||Ro}),new N({optional:!0,name:t.iterations||ar})]})}fromSchema(e){V(e,ZD);let t=R(e,e,s.schema({names:{mac:{names:{blockName:Oo}},macSalt:Ro,iterations:ar}}));T.assertSchema(t,this.className),this.mac=new dr({schema:t.result.mac}),this.macSalt=t.result.macSalt,ar in t.result&&(this.iterations=t.result.iterations.valueBlock.valueDec);}toSchema(){let e=[this.mac.toSchema(),this.macSalt];return this.iterations!==void 0&&e.push(new N({value:this.iterations})),new b({value:e})}toJSON(){let e={mac:this.mac.toJSON(),macSalt:this.macSalt.toJSON()};return this.iterations!==void 0&&(e.iterations=this.iterations),e}};wn.CLASS_NAME="MacData";var _o="hashAlgorithm",Mo="hashedMessage",QD=[_o,Mo],Es=class s extends O{static async create(e,t,n=ve(!0)){let r=n.getOIDByAlgorithm({name:e},!0,"hashAlgorithm"),i=await n.digest(e,t);return new s({hashAlgorithm:new P({algorithmId:r,algorithmParams:new Xe}),hashedMessage:new U({valueHex:i})})}constructor(e={}){super(),this.hashAlgorithm=d(e,_o,s.defaultValues(_o)),this.hashedMessage=d(e,Mo,s.defaultValues(Mo)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case _o:return new P;case Mo:return new U;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case _o:return t.algorithmId===p&&!("algorithmParams"in t);case Mo:return t.isEqual(s.defaultValues(e))===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.hashAlgorithm||{}),new U({name:t.hashedMessage||p})]})}fromSchema(e){V(e,QD);let t=R(e,e,s.schema({names:{hashAlgorithm:{names:{blockName:_o}},hashedMessage:Mo}}));T.assertSchema(t,this.className),this.hashAlgorithm=new P({schema:t.result.hashAlgorithm}),this.hashedMessage=t.result.hashedMessage;}toSchema(){return new b({value:[this.hashAlgorithm.toSchema(),this.hashedMessage]})}toJSON(){return {hashAlgorithm:this.hashAlgorithm.toJSON(),hashedMessage:this.hashedMessage.toJSON()}}};Es.CLASS_NAME="MessageImprint";var Qu="reqCert",Oi="singleRequestExtensions",XD=[Qu,Oi],Ll=class s extends O{constructor(e={}){super(),this.reqCert=d(e,Qu,s.defaultValues(Qu)),Oi in e&&(this.singleRequestExtensions=d(e,Oi,s.defaultValues(Oi))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Qu:return new ns;case Oi:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Qu:return t.isEqual(s.defaultValues(e));case Oi:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[ns.schema(t.reqCert||{}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[ft.schema(t.extensions||{names:{blockName:t.singleRequestExtensions||p}})]})]})}fromSchema(e){V(e,XD);let t=R(e,e,s.schema({names:{reqCert:{names:{blockName:Qu}},extensions:{names:{blockName:Oi}}}}));T.assertSchema(t,this.className),this.reqCert=new ns({schema:t.result.reqCert}),Oi in t.result&&(this.singleRequestExtensions=Array.from(t.result.singleRequestExtensions.valueBlock.value,n=>new ds({schema:n})));}toSchema(){let e=[];return e.push(this.reqCert.toSchema()),this.singleRequestExtensions&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new b({value:Array.from(this.singleRequestExtensions,t=>t.toSchema())})]})),new b({value:e})}toJSON(){let e={reqCert:this.reqCert.toJSON()};return this.singleRequestExtensions&&(e.singleRequestExtensions=Array.from(this.singleRequestExtensions,t=>t.toJSON())),e}};Ll.CLASS_NAME="Request";var Sy="tbs",Xu="version",el="requestorName",vy="requestList",tl="requestExtensions",_l="TBSRequest",Dy=`${_l}.${Xu}`,Uy=`${_l}.${el}`,z2=`${_l}.requests`,Ly=`${_l}.${tl}`,eU=[_l,Dy,Uy,z2,Ly],en=class s extends O{get tbs(){return re.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e);}constructor(e={}){super(),this.tbsView=new Uint8Array(d(e,Sy,s.defaultValues(Sy))),Xu in e&&(this.version=d(e,Xu,s.defaultValues(Xu))),el in e&&(this.requestorName=d(e,el,s.defaultValues(el))),this.requestList=d(e,vy,s.defaultValues(vy)),tl in e&&(this.requestExtensions=d(e,tl,s.defaultValues(tl))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Sy:return ut;case Xu:return 0;case el:return new qe;case vy:case tl:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Sy:return t.byteLength===0;case Xu:return t===s.defaultValues(e);case el:return t.type===qe.defaultValues("type")&&Object.keys(t.value).length===0;case vy:case tl:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||_l,value:[new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new N({name:t.TBSRequestVersion||Dy})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[qe.schema(t.requestorName||{names:{blockName:Uy}})]}),new b({name:t.requestList||"TBSRequest.requestList",value:[new fe({name:t.requests||z2,value:Ll.schema(t.requestNames||{})})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:2},value:[ft.schema(t.extensions||{names:{blockName:t.requestExtensions||Ly}})]})]})}fromSchema(e){V(e,eU);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.tbsView=t.result.TBSRequest.valueBeforeDecodeView,Dy in t.result&&(this.version=t.result[Dy].valueBlock.valueDec),Uy in t.result&&(this.requestorName=new qe({schema:t.result[Uy]})),this.requestList=Array.from(t.result[z2],n=>new Ll({schema:n})),Ly in t.result&&(this.requestExtensions=Array.from(t.result[Ly].valueBlock.value,n=>new ds({schema:n})));}toSchema(e=!1){let t;if(e===!1){if(this.tbsView.byteLength===0)return s.schema();let n=ht(this.tbsView);if(T.assert(n,"TBS Request"),!(n.result instanceof b))throw new Error("ASN.1 result should be SEQUENCE");t=n.result;}else {let n=[];this.version!==void 0&&n.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[new N({value:this.version})]})),this.requestorName&&n.push(new A({idBlock:{tagClass:3,tagNumber:1},value:[this.requestorName.toSchema()]})),n.push(new b({value:Array.from(this.requestList,r=>r.toSchema())})),this.requestExtensions&&n.push(new A({idBlock:{tagClass:3,tagNumber:2},value:[new b({value:Array.from(this.requestExtensions,r=>r.toSchema())})]})),t=new b({value:n});}return t}toJSON(){let e={};return this.version!=null&&(e.version=this.version),this.requestorName&&(e.requestorName=this.requestorName.toJSON()),e.requestList=Array.from(this.requestList,t=>t.toJSON()),this.requestExtensions&&(e.requestExtensions=Array.from(this.requestExtensions,t=>t.toJSON())),e}};en.CLASS_NAME="TBSRequest";var Zc="signatureAlgorithm",Qc="signature",Xr="certs",fr=class s extends O{constructor(e={}){super(),this.signatureAlgorithm=d(e,Zc,s.defaultValues(Zc)),this.signature=d(e,Qc,s.defaultValues(Qc)),Xr in e&&(this.certs=d(e,Xr,s.defaultValues(Xr))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Zc:return new P;case Qc:return new Ae;case Xr:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Zc:return t.algorithmId===p&&!("algorithmParams"in t);case Qc:return t.isEqual(s.defaultValues(e));case Xr:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[P.schema(t.signatureAlgorithm||{}),new Ae({name:t.signature||p}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new b({value:[new fe({name:t.certs||p,value:Lt.schema({})})]})]})]})}fromSchema(e){V(e,[Zc,Qc,Xr]);let t=R(e,e,s.schema({names:{signatureAlgorithm:{names:{blockName:Zc}},signature:Qc,certs:Xr}}));T.assertSchema(t,this.className),this.signatureAlgorithm=new P({schema:t.result.signatureAlgorithm}),this.signature=t.result.signature,Xr in t.result&&(this.certs=Array.from(t.result.certs,n=>new Lt({schema:n})));}toSchema(){let e=[];return e.push(this.signatureAlgorithm.toSchema()),e.push(this.signature),this.certs&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new b({value:Array.from(this.certs,t=>t.toSchema())})]})),new b({value:e})}toJSON(){let e={signatureAlgorithm:this.signatureAlgorithm.toJSON(),signature:this.signature.toJSON()};return this.certs&&(e.certs=Array.from(this.certs,t=>t.toJSON())),e}};fr.CLASS_NAME="Signature";var sl="tbsRequest",Ri="optionalSignature",tU=[sl,Ri],Y2=class s extends O{constructor(e={}){super(),this.tbsRequest=d(e,sl,s.defaultValues(sl)),Ri in e&&(this.optionalSignature=d(e,Ri,s.defaultValues(Ri))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case sl:return new en;case Ri:return new fr;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case sl:return en.compareWithDefault("tbs",t.tbs)&&en.compareWithDefault("version",t.version)&&en.compareWithDefault("requestorName",t.requestorName)&&en.compareWithDefault("requestList",t.requestList)&&en.compareWithDefault("requestExtensions",t.requestExtensions);case Ri:return fr.compareWithDefault("signatureAlgorithm",t.signatureAlgorithm)&&fr.compareWithDefault("signature",t.signature)&&fr.compareWithDefault("certs",t.certs);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||"OCSPRequest",value:[en.schema(t.tbsRequest||{names:{blockName:sl}}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[fr.schema(t.optionalSignature||{names:{blockName:Ri}})]})]})}fromSchema(e){V(e,tU);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.tbsRequest=new en({schema:t.result.tbsRequest}),Ri in t.result&&(this.optionalSignature=new fr({schema:t.result.optionalSignature}));}toSchema(e=!1){let t=[];return t.push(this.tbsRequest.toSchema(e)),this.optionalSignature&&t.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[this.optionalSignature.toSchema()]})),new b({value:t})}toJSON(){let e={tbsRequest:this.tbsRequest.toJSON()};return this.optionalSignature&&(e.optionalSignature=this.optionalSignature.toJSON()),e}async createForCertificate(e,t,n=ve(!0)){let r=new ns;await r.createForCertificate(e,t,n),this.tbsRequest.requestList.push(new Ll({reqCert:r}));}async sign(e,t="SHA-1",n=ve(!0)){if(Re.assertEmpty(e,"privateKey","OCSPRequest.sign method"),!this.optionalSignature)throw new Error('Need to create "optionalSignature" field before signing');let r=await n.getSignatureParameters(e,t),i=r.parameters;this.optionalSignature.signatureAlgorithm=r.signatureAlgorithm;let a=this.tbsRequest.toSchema(!0).toBER(!1),o=await n.signWithPrivateKey(a,e,i);this.optionalSignature.signature=new Ae({valueHex:o});}verify(){}};Y2.CLASS_NAME="OCSPRequest";var nl="responseType",rl="response",sU=[nl,rl],_i=class s extends O{constructor(e={}){super(),this.responseType=d(e,nl,s.defaultValues(nl)),this.response=d(e,rl,s.defaultValues(rl)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case nl:return p;case rl:return new U;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case nl:return t===p;case rl:return t.isEqual(s.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new G({name:t.responseType||p}),new U({name:t.response||p})]})}fromSchema(e){V(e,sU);let t=R(e,e,s.schema({names:{responseType:nl,response:rl}}));T.assertSchema(t,this.className),this.responseType=t.result.responseType.valueBlock.toString(),this.response=t.result.response;}toSchema(){return new b({value:[new G({value:this.responseType}),this.response]})}toJSON(){return {responseType:this.responseType,response:this.response.toJSON()}}};_i.CLASS_NAME="ResponseBytes";var Xc="responseStatus",Zn="responseBytes",Z2=class s extends O{constructor(e={}){super(),this.responseStatus=d(e,Xc,s.defaultValues(Xc)),Zn in e&&(this.responseBytes=d(e,Zn,s.defaultValues(Zn))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Xc:return new pn;case Zn:return new _i;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Xc:return t.isEqual(s.defaultValues(e));case Zn:return _i.compareWithDefault("responseType",t.responseType)&&_i.compareWithDefault("response",t.response);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||"OCSPResponse",value:[new pn({name:t.responseStatus||Xc}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[_i.schema(t.responseBytes||{names:{blockName:Zn}})]})]})}fromSchema(e){V(e,[Xc,Zn]);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.responseStatus=t.result.responseStatus,Zn in t.result&&(this.responseBytes=new _i({schema:t.result.responseBytes}));}toSchema(){let e=[];return e.push(this.responseStatus),this.responseBytes&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:[this.responseBytes.toSchema()]})),new b({value:e})}toJSON(){let e={responseStatus:this.responseStatus.toJSON()};return this.responseBytes&&(e.responseBytes=this.responseBytes.toJSON()),e}async getCertificateStatus(e,t,n=ve(!0)){let r,i={isForCertificate:!1,status:2};if(!this.responseBytes||this.responseBytes.responseType!==Ey)return i;try{let a=ht(this.responseBytes.response.valueBlock.valueHexView);T.assert(a,"Basic OCSP response"),r=new zo({schema:a.result});}catch{return i}return r.getCertificateStatus(e,t,n)}async sign(e,t,n=ve(!0)){var r;if(this.responseBytes&&this.responseBytes.responseType===Ey)return zo.fromBER(this.responseBytes.response.valueBlock.valueHexView).sign(e,t,n);throw new Error(`Unknown ResponseBytes type: ${((r=this.responseBytes)===null||r===void 0?void 0:r.responseType)||"Unknown"}`)}async verify(e=null,t=ve(!0)){var n;if(!(Zn in this))throw new Error("Empty ResponseBytes field");if(this.responseBytes&&this.responseBytes.responseType===Ey){let r=zo.fromBER(this.responseBytes.response.valueBlock.valueHexView);return e!==null&&(r.certs||(r.certs=[]),r.certs.push(e)),r.verify({},t)}throw new Error(`Unknown ResponseBytes type: ${((n=this.responseBytes)===null||n===void 0?void 0:n.responseType)||"Unknown"}`)}};Z2.CLASS_NAME="OCSPResponse";var La="type",or="attributes",xy="encodedValue",nU=[or],Wt=class s extends O{constructor(e={}){super(),this.type=d(e,La,s.defaultValues(La)),this.attributes=d(e,or,s.defaultValues(or)),this.encodedValue=d(e,xy,s.defaultValues(xy)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case La:return -1;case or:return [];case xy:return ut;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case La:return t===s.defaultValues(La);case or:return t.length===0;case xy:return t.byteLength===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new A({name:t.blockName||p,optional:!0,idBlock:{tagClass:3,tagNumber:t.tagNumber||0},value:[new fe({name:t.attributes||p,value:nt.schema()})]})}fromSchema(e){V(e,nU);let t=R(e,e,s.schema({names:{tagNumber:this.type,attributes:or}}));T.assertSchema(t,this.className),this.type=t.result.idBlock.tagNumber,this.encodedValue=re.toArrayBuffer(t.result.valueBeforeDecodeView);let n=new Uint8Array(this.encodedValue);if(n[0]=49,!(or in t.result)){if(this.type===0)throw new Error("Wrong structure of SignedUnsignedAttributes");return}this.attributes=Array.from(t.result.attributes,r=>new nt({schema:r}));}toSchema(){if(s.compareWithDefault(La,this.type)||s.compareWithDefault(or,this.attributes))throw new Error('Incorrectly initialized "SignedAndUnsignedAttributes" class');return new A({optional:!0,idBlock:{tagClass:3,tagNumber:this.type},value:Array.from(this.attributes,e=>e.toSchema())})}toJSON(){if(s.compareWithDefault(La,this.type)||s.compareWithDefault(or,this.attributes))throw new Error('Incorrectly initialized "SignedAndUnsignedAttributes" class');return {type:this.type,attributes:Array.from(this.attributes,e=>e.toJSON())}}};Wt.CLASS_NAME="SignedAndUnsignedAttributes";var il="version",Vo="sid",al="digestAlgorithm",Vi="signedAttrs",ol="signatureAlgorithm",pm="signature",Di="unsignedAttrs",Ki="SignerInfo",Q2=`${Ki}.${il}`,gm=`${Ki}.${Vo}`,X2=`${Ki}.${al}`,jy=`${Ki}.${Vi}`,eA=`${Ki}.${ol}`,tA=`${Ki}.${pm}`,Hy=`${Ki}.${Di}`,rU=[Q2,gm,X2,jy,eA,tA,Hy],jl=class s extends O{constructor(e={}){super(),this.version=d(e,il,s.defaultValues(il)),this.sid=d(e,Vo,s.defaultValues(Vo)),this.digestAlgorithm=d(e,al,s.defaultValues(al)),Vi in e&&(this.signedAttrs=d(e,Vi,s.defaultValues(Vi))),this.signatureAlgorithm=d(e,ol,s.defaultValues(ol)),this.signature=d(e,pm,s.defaultValues(pm)),Di in e&&(this.unsignedAttrs=d(e,Di,s.defaultValues(Di))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case il:return 0;case Vo:return new ue;case al:return new P;case Vi:return new Wt({type:0});case ol:return new P;case pm:return new U;case Di:return new Wt({type:1});default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case il:return s.defaultValues(il)===t;case Vo:return t instanceof ue;case al:return t instanceof P?t.isEqual(s.defaultValues(al)):!1;case Vi:return Wt.compareWithDefault("type",t.type)&&Wt.compareWithDefault("attributes",t.attributes)&&Wt.compareWithDefault("encodedValue",t.encodedValue);case ol:return t instanceof P?t.isEqual(s.defaultValues(ol)):!1;case pm:case Di:return Wt.compareWithDefault("type",t.type)&&Wt.compareWithDefault("attributes",t.attributes)&&Wt.compareWithDefault("encodedValue",t.encodedValue);default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:Ki,value:[new N({name:t.version||Q2}),new We({value:[vt.schema(t.sidSchema||{names:{blockName:gm}}),new We({value:[new A({optional:!0,name:t.sid||gm,idBlock:{tagClass:3,tagNumber:0},value:[new U]}),new ie({optional:!0,name:t.sid||gm,idBlock:{tagClass:3,tagNumber:0}})]})]}),P.schema(t.digestAlgorithm||{names:{blockName:X2}}),Wt.schema(t.signedAttrs||{names:{blockName:jy,tagNumber:0}}),P.schema(t.signatureAlgorithm||{names:{blockName:eA}}),new U({name:t.signature||tA}),Wt.schema(t.unsignedAttrs||{names:{blockName:Hy,tagNumber:1}})]})}fromSchema(e){V(e,rU);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.version=t.result[Q2].valueBlock.valueDec;let n=t.result[gm];n.idBlock.tagClass===1?this.sid=new vt({schema:n}):this.sid=n,this.digestAlgorithm=new P({schema:t.result[X2]}),jy in t.result&&(this.signedAttrs=new Wt({type:0,schema:t.result[jy]})),this.signatureAlgorithm=new P({schema:t.result[eA]}),this.signature=t.result[tA],Hy in t.result&&(this.unsignedAttrs=new Wt({type:1,schema:t.result[Hy]}));}toSchema(){if(s.compareWithDefault(Vo,this.sid))throw new Error('Incorrectly initialized "SignerInfo" class');let e=[];return e.push(new N({value:this.version})),this.sid instanceof vt?e.push(this.sid.toSchema()):e.push(this.sid),e.push(this.digestAlgorithm.toSchema()),this.signedAttrs&&s.compareWithDefault(Vi,this.signedAttrs)===!1&&e.push(this.signedAttrs.toSchema()),e.push(this.signatureAlgorithm.toSchema()),e.push(this.signature),this.unsignedAttrs&&s.compareWithDefault(Di,this.unsignedAttrs)===!1&&e.push(this.unsignedAttrs.toSchema()),new b({value:e})}toJSON(){if(s.compareWithDefault(Vo,this.sid))throw new Error('Incorrectly initialized "SignerInfo" class');let e={version:this.version,digestAlgorithm:this.digestAlgorithm.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signature:this.signature.toJSON()};return this.sid instanceof ue||(e.sid=this.sid.toJSON()),this.signedAttrs&&s.compareWithDefault(Vi,this.signedAttrs)===!1&&(e.signedAttrs=this.signedAttrs.toJSON()),this.unsignedAttrs&&s.compareWithDefault(Di,this.unsignedAttrs)===!1&&(e.unsignedAttrs=this.unsignedAttrs.toJSON()),e}};jl.CLASS_NAME="SignerInfo";var ym="version",wm="policy",bm="messageImprint",Sm="serialNumber",vm="genTime",Do="ordering",Uo="nonce",cl="accuracy",ul="tsa",ll="extensions",sn="TSTInfo",sA=`${sn}.${ym}`,nA=`${sn}.${wm}`,rA=`${sn}.${bm}`,iA=`${sn}.${Sm}`,aA=`${sn}.${vm}`,_y=`${sn}.${cl}`,My=`${sn}.${Do}`,$y=`${sn}.${Uo}`,qy=`${sn}.${ul}`,Fy=`${sn}.${ll}`,iU=[sA,nA,rA,iA,aA,_y,My,$y,qy,Fy],Nw=class s extends O{constructor(e={}){super(),this.version=d(e,ym,s.defaultValues(ym)),this.policy=d(e,wm,s.defaultValues(wm)),this.messageImprint=d(e,bm,s.defaultValues(bm)),this.serialNumber=d(e,Sm,s.defaultValues(Sm)),this.genTime=d(e,vm,s.defaultValues(vm)),cl in e&&(this.accuracy=d(e,cl,s.defaultValues(cl))),Do in e&&(this.ordering=d(e,Do,s.defaultValues(Do))),Uo in e&&(this.nonce=d(e,Uo,s.defaultValues(Uo))),ul in e&&(this.tsa=d(e,ul,s.defaultValues(ul))),ll in e&&(this.extensions=d(e,ll,s.defaultValues(ll))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ym:return 0;case wm:return p;case bm:return new Es;case Sm:return new N;case vm:return new Date(0,0,0);case cl:return new lr;case Do:return !1;case Uo:return new N;case ul:return new qe;case ll:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ym:case wm:case vm:case Do:return t===s.defaultValues(Do);case bm:return Es.compareWithDefault(_o,t.hashAlgorithm)&&Es.compareWithDefault(Mo,t.hashedMessage);case Sm:case Uo:return t.isEqual(s.defaultValues(Uo));case cl:return lr.compareWithDefault(ei,t.seconds)&&lr.compareWithDefault(ti,t.millis)&&lr.compareWithDefault(si,t.micros);case ul:return qe.compareWithDefault(Of,t.type)&&qe.compareWithDefault(Rf,t.value);case ll:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||sn,value:[new N({name:t.version||sA}),new G({name:t.policy||nA}),Es.schema(t.messageImprint||{names:{blockName:rA}}),new N({name:t.serialNumber||iA}),new Ge({name:t.genTime||aA}),lr.schema(t.accuracy||{names:{blockName:_y}}),new xs({name:t.ordering||My,optional:!0}),new N({name:t.nonce||$y,optional:!0}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[qe.schema(t.tsa||{names:{blockName:qy}})]}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new fe({name:t.extensions||Fy,value:ds.schema(t.extension||{})})]})]})}fromSchema(e){V(e,iU);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.version=t.result[sA].valueBlock.valueDec,this.policy=t.result[nA].valueBlock.toString(),this.messageImprint=new Es({schema:t.result[rA]}),this.serialNumber=t.result[iA],this.genTime=t.result[aA].toDate(),_y in t.result&&(this.accuracy=new lr({schema:t.result[_y]})),My in t.result&&(this.ordering=t.result[My].valueBlock.value),$y in t.result&&(this.nonce=t.result[$y]),qy in t.result&&(this.tsa=new qe({schema:t.result[qy]})),Fy in t.result&&(this.extensions=Array.from(t.result[Fy],n=>new ds({schema:n})));}toSchema(){let e=[];return e.push(new N({value:this.version})),e.push(new G({value:this.policy})),e.push(this.messageImprint.toSchema()),e.push(this.serialNumber),e.push(new Ge({valueDate:this.genTime})),this.accuracy&&e.push(this.accuracy.toSchema()),this.ordering!==void 0&&e.push(new xs({value:this.ordering})),this.nonce&&e.push(this.nonce),this.tsa&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[this.tsa.toSchema()]})),this.extensions&&e.push(new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.extensions,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={version:this.version,policy:this.policy,messageImprint:this.messageImprint.toJSON(),serialNumber:this.serialNumber.toJSON(),genTime:this.genTime};return this.accuracy&&(e.accuracy=this.accuracy.toJSON()),this.ordering!==void 0&&(e.ordering=this.ordering),this.nonce&&(e.nonce=this.nonce.toJSON()),this.tsa&&(e.tsa=this.tsa.toJSON()),this.extensions&&(e.extensions=Array.from(this.extensions,t=>t.toJSON())),e}async verify(e,t=ve(!0)){if(!e.data)throw new Error('"data" is a mandatory attribute for TST_INFO verification');let n=e.data;if(e.notBefore&&this.genTime<e.notBefore)throw new Error("Generation time for TSTInfo object is less than notBefore value");if(e.notAfter&&this.genTime>e.notAfter)throw new Error("Generation time for TSTInfo object is more than notAfter value");let r=t.getAlgorithmByOID(this.messageImprint.hashAlgorithm.algorithmId,!0,"MessageImprint.hashAlgorithm"),i=await t.digest(r.name,new Uint8Array(n));return re.isEqual(i,this.messageImprint.hashedMessage.valueBlock.valueHexView)}};Nw.CLASS_NAME="TSTInfo";var hl="version",xm="digestAlgorithms",Em="encapContentInfo",fl="certificates",dl="crls",Am="signerInfos",Tf="ocsps",ec="SignedData",oA=`${ec}.${hl}`,Ky=`${ec}.${xm}`,cA=`${ec}.${Em}`,Gy=`${ec}.${fl}`,Wy=`${ec}.${dl}`,Jy=`${ec}.${Am}`,aU=[oA,Ky,cA,Gy,Wy,Jy],Nt=class extends Error{constructor({message:e,code:t=0,date:n=new Date,signatureVerified:r=null,signerCertificate:i=null,signerCertificateVerified:a=null,timestampSerial:o=null,certificatePath:c=[]}){super(e),this.name="SignedDataVerifyError",this.date=n,this.code=t,this.timestampSerial=o,this.signatureVerified=r,this.signerCertificate=i,this.signerCertificateVerified=a,this.certificatePath=c;}},Fi=class s extends O{constructor(e={}){super(),this.version=d(e,hl,s.defaultValues(hl)),this.digestAlgorithms=d(e,xm,s.defaultValues(xm)),this.encapContentInfo=d(e,Em,s.defaultValues(Em)),fl in e&&(this.certificates=d(e,fl,s.defaultValues(fl))),dl in e&&(this.crls=d(e,dl,s.defaultValues(dl))),Tf in e&&(this.ocsps=d(e,Tf,s.defaultValues(Tf))),this.signerInfos=d(e,Am,s.defaultValues(Am)),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case hl:return 0;case xm:return [];case Em:return new mr;case fl:return [];case dl:return [];case Tf:return [];case Am:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case hl:return t===s.defaultValues(hl);case Em:return mr.compareWithDefault("eContentType",t.eContentType)&&mr.compareWithDefault("eContent",t.eContent);case xm:case fl:case dl:case Tf:case Am:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return t.optional===void 0&&(t.optional=!1),new b({name:t.blockName||ec,optional:t.optional,value:[new N({name:t.version||oA}),new et({value:[new fe({name:t.digestAlgorithms||Ky,value:P.schema()})]}),mr.schema(t.encapContentInfo||{names:{blockName:cA}}),new A({name:t.certificates||Gy,optional:!0,idBlock:{tagClass:3,tagNumber:0},value:yr.schema().valueBlock.value}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Ko.schema(t.crls||{names:{crls:Wy}}).valueBlock.value}),new et({value:[new fe({name:t.signerInfos||Jy,value:jl.schema()})]})]})}fromSchema(e){V(e,aU);let t=R(e,e,s.schema());if(T.assertSchema(t,this.className),this.version=t.result[oA].valueBlock.valueDec,Ky in t.result&&(this.digestAlgorithms=Array.from(t.result[Ky],n=>new P({schema:n}))),this.encapContentInfo=new mr({schema:t.result[cA]}),Gy in t.result){let n=new yr({schema:new et({value:t.result[Gy].valueBlock.value})});this.certificates=n.certificates.slice(0);}Wy in t.result&&(this.crls=Array.from(t.result[Wy],n=>n.idBlock.tagClass===1?new Zo({schema:n}):(n.idBlock.tagClass=1,n.idBlock.tagNumber=16,new Fo({schema:n})))),Jy in t.result&&(this.signerInfos=Array.from(t.result[Jy],n=>new jl({schema:n})));}toSchema(e=!1){let t=[];if(this.certificates&&this.certificates.length&&this.certificates.some(n=>n instanceof Il)||this.crls&&this.crls.length&&this.crls.some(n=>n instanceof Fo)?this.version=5:this.certificates&&this.certificates.length&&this.certificates.some(n=>n instanceof bn)?this.version=4:this.certificates&&this.certificates.length&&this.certificates.some(n=>n instanceof Pl)||this.signerInfos.some(n=>n.version===3)||this.encapContentInfo.eContentType!==s.ID_DATA?this.version=3:this.version=1,t.push(new N({value:this.version})),t.push(new et({value:Array.from(this.digestAlgorithms,n=>n.toSchema())})),t.push(this.encapContentInfo.toSchema()),this.certificates){let r=new yr({certificates:this.certificates}).toSchema();t.push(new A({idBlock:{tagClass:3,tagNumber:0},value:r.valueBlock.value}));}return this.crls&&t.push(new A({idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.crls,n=>{if(n instanceof Fo){let r=n.toSchema();return r.idBlock.tagClass=3,r.idBlock.tagNumber=1,r}return n.toSchema(e)})})),t.push(new et({value:Array.from(this.signerInfos,n=>n.toSchema())})),new b({value:t})}toJSON(){let e={version:this.version,digestAlgorithms:Array.from(this.digestAlgorithms,t=>t.toJSON()),encapContentInfo:this.encapContentInfo.toJSON(),signerInfos:Array.from(this.signerInfos,t=>t.toJSON())};return this.certificates&&(e.certificates=Array.from(this.certificates,t=>t.toJSON())),this.crls&&(e.crls=Array.from(this.crls,t=>t.toJSON())),e}async verify({signer:e=-1,data:t=ut,trustedCerts:n=[],checkDate:r=new Date,checkChain:i=!1,passedWhenNotRevValues:a=!1,extendedMode:o=!1,findOrigin:c=null,findIssuer:u=null}={},l=ve(!0)){let h=null,m=null;try{let y=ut,g=p,w=[],S=this.signerInfos[e];if(!S)throw new Nt({date:r,code:1,message:"Unable to get signer by supplied index"});if(!this.certificates)throw new Nt({date:r,code:2,message:"No certificates attached to this signed data"});if(S.sid instanceof vt){for(let v of this.certificates)if(v instanceof Lt&&v.issuer.isEqual(S.sid.issuer)&&v.serialNumber.isEqual(S.sid.serialNumber)){h=v;break}}else {let v=S.sid,I=v.idBlock.isConstructed?v.valueBlock.value[0].valueBlock.valueHex:v.valueBlock.valueHex;for(let D of this.certificates){if(!(D instanceof Lt))continue;let F=await l.digest({name:"sha-1"},D.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView);if(qr(F,I)){h=D;break}}}if(!h)throw new Nt({date:r,code:3,message:"Unable to find signer certificate"});if(this.encapContentInfo.eContentType===f9){if(!this.encapContentInfo.eContent)throw new Nt({date:r,code:15,message:"Error during verification: TSTInfo eContent is empty",signatureVerified:null,signerCertificate:h,timestampSerial:m,signerCertificateVerified:!0});let v;try{v=Nw.fromBER(this.encapContentInfo.eContent.valueBlock.valueHexView);}catch{throw new Nt({date:r,code:15,message:"Error during verification: TSTInfo wrong ASN.1 schema ",signatureVerified:null,signerCertificate:h,timestampSerial:m,signerCertificateVerified:!0})}if(r=v.genTime,m=v.serialNumber.valueBlock.valueHexView.slice().buffer,t.byteLength===0)throw new Nt({date:r,code:4,message:"Missed detached data input array"});if(!await v.verify({data:t},l))throw new Nt({date:r,code:15,message:"Error during verification: TSTInfo verification is failed",signatureVerified:!1,signerCertificate:h,timestampSerial:m,signerCertificateVerified:!0})}if(i){let v=this.certificates.filter(M=>M instanceof Lt&&!!Ek(M,h)),I={checkDate:r,certs:v,trustedCerts:n};u&&(I.findIssuer=u),c&&(I.findOrigin=c);let D=new Xm(I);if(D.certs.push(h),this.crls)for(let M of this.crls)"thisUpdate"in M?D.crls.push(M):M.otherRevInfoFormat===Ey&&D.ocsps.push(new zo({schema:M.otherRevInfo}));this.ocsps&&D.ocsps.push(...this.ocsps);let F=await D.verify({passedWhenNotRevValues:a},l).catch(M=>{throw new Nt({date:r,code:5,message:`Validation of signer's certificate failed with error: ${M instanceof Object?M.resultMessage:M}`,signerCertificate:h,signerCertificateVerified:!1})});if(F.certificatePath&&(w=F.certificatePath),!F.result)throw new Nt({date:r,code:5,message:`Validation of signer's certificate failed: ${F.resultMessage}`,signerCertificate:h,signerCertificateVerified:!1})}let C=l.getAlgorithmByOID(S.digestAlgorithm.algorithmId);if(!("name"in C))throw new Nt({date:r,code:7,message:`Unsupported signature algorithm: ${S.digestAlgorithm.algorithmId}`,signerCertificate:h,signerCertificateVerified:!0});g=C.name;let k=this.encapContentInfo.eContent;if(k)k.idBlock.tagClass===1&&k.idBlock.tagNumber===4?t=k.getValue():t=k.valueBlock.valueBeforeDecodeView.slice().buffer;else if(t.byteLength===0)throw new Nt({date:r,code:8,message:"Missed detached data input array",signerCertificate:h,signerCertificateVerified:!0});if(S.signedAttrs){let v=!1,I=!1;for(let D of S.signedAttrs.attributes)if(D.type==="1.2.840.113549.1.9.3"&&(v=!0),D.type==="1.2.840.113549.1.9.4"&&(I=!0,y=D.values[0].valueBlock.valueHex),v&&I)break;if(v===!1)throw new Nt({date:r,code:9,message:'Attribute "content-type" is a mandatory attribute for "signed attributes"',signerCertificate:h,signerCertificateVerified:!0});if(I===!1)throw new Nt({date:r,code:10,message:'Attribute "message-digest" is a mandatory attribute for "signed attributes"',signatureVerified:null,signerCertificate:h,signerCertificateVerified:!0})}if(S.signedAttrs){let v=await l.digest(g,new Uint8Array(t));if(!qr(v,y))throw new Nt({date:r,code:15,message:"Error during verification: Message digest doesn't match",signatureVerified:null,signerCertificate:h,timestampSerial:m,signerCertificateVerified:!0});t=S.signedAttrs.encodedValue;}let x=S.signatureAlgorithm.algorithmId==="1.2.840.113549.1.1.1"?await l.verifyWithPublicKey(t,S.signature,h.subjectPublicKeyInfo,S.signatureAlgorithm,g):await l.verifyWithPublicKey(t,S.signature,h.subjectPublicKeyInfo,S.signatureAlgorithm);return o?{date:r,code:14,message:p,signatureVerified:x,signerCertificate:h,timestampSerial:m,signerCertificateVerified:!0,certificatePath:w}:x}catch(y){throw y instanceof Nt?y:new Nt({date:r,code:15,message:`Error during verification: ${y instanceof Error?y.message:y}`,signatureVerified:null,signerCertificate:h,timestampSerial:m,signerCertificateVerified:!0})}}async sign(e,t,n="SHA-1",r=ut,i=ve(!0)){var a;if(!e)throw new Error("Need to provide a private key for signing");let o=this.signerInfos[t];if(!o)throw new RangeError("SignerInfo index is out of range");!(!((a=o.signedAttrs)===null||a===void 0)&&a.attributes.length)&&"hash"in e.algorithm&&"hash"in e.algorithm&&e.algorithm.hash&&(n=e.algorithm.hash.name);let c=i.getOIDByAlgorithm({name:n},!0,"hashAlgorithm");this.digestAlgorithms.filter(m=>m.algorithmId===c).length===0&&this.digestAlgorithms.push(new P({algorithmId:c,algorithmParams:new Xe})),o.digestAlgorithm=new P({algorithmId:c,algorithmParams:new Xe});let u=await i.getSignatureParameters(e,n),l=u.parameters;if(o.signatureAlgorithm=u.signatureAlgorithm,o.signedAttrs)if(o.signedAttrs.encodedValue.byteLength!==0)r=o.signedAttrs.encodedValue;else {r=o.signedAttrs.toSchema().toBER();let m=re.toUint8Array(r);m[0]=49;}else {let m=this.encapContentInfo.eContent;if(m)m.idBlock.tagClass===1&&m.idBlock.tagNumber===4?r=m.getValue():r=m.valueBlock.valueBeforeDecodeView.slice().buffer;else if(r.byteLength===0)throw new Error("Missed detached data input array")}let h=await i.signWithPrivateKey(r,e,l);o.signature=new U({valueHex:h});}};Fi.CLASS_NAME="SignedData";Fi.ID_DATA=bA;var Lo="version",jo="authSafe",cr="macData",Bf="parsedValue",oU=[Lo,jo,cr],uA=class s extends O{constructor(e={}){super(),this.version=d(e,Lo,s.defaultValues(Lo)),this.authSafe=d(e,jo,s.defaultValues(jo)),cr in e&&(this.macData=d(e,cr,s.defaultValues(cr))),Bf in e&&(this.parsedValue=d(e,Bf,s.defaultValues(Bf))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Lo:return 3;case jo:return new tt;case cr:return new wn;case Bf:return {};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Lo:return t===s.defaultValues(e);case jo:return tt.compareWithDefault("contentType",t.contentType)&&tt.compareWithDefault("content",t.content);case cr:return wn.compareWithDefault("mac",t.mac)&&wn.compareWithDefault("macSalt",t.macSalt)&&wn.compareWithDefault("iterations",t.iterations);case Bf:return t instanceof Object&&Object.keys(t).length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new N({name:t.version||Lo}),tt.schema(t.authSafe||{names:{blockName:jo}}),wn.schema(t.macData||{names:{blockName:cr,optional:!0}})]})}fromSchema(e){V(e,oU);let t=R(e,e,s.schema({names:{version:Lo,authSafe:{names:{blockName:jo}},macData:{names:{blockName:cr}}}}));T.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.authSafe=new tt({schema:t.result.authSafe}),cr in t.result&&(this.macData=new wn({schema:t.result.macData}));}toSchema(){let e=[new N({value:this.version}),this.authSafe.toSchema()];return this.macData&&e.push(this.macData.toSchema()),new b({value:e})}toJSON(){let e={version:this.version,authSafe:this.authSafe.toJSON()};return this.macData&&(e.macData=this.macData.toJSON()),e}async makeInternalValues(e={},t=ve(!0)){if($e.assert(e,"parameters","object"),!this.parsedValue)throw new Error('Please call "parseValues" function first in order to make "parsedValue" data');switch(Re.assertEmpty(this.parsedValue.integrityMode,"integrityMode","parsedValue"),Re.assertEmpty(this.parsedValue.authenticatedSafe,"authenticatedSafe","parsedValue"),this.parsedValue.integrityMode){case 0:{if(!("iterations"in e))throw new Re("iterations");Re.assertEmpty(e.pbkdf2HashAlgorithm,"pbkdf2HashAlgorithm"),Re.assertEmpty(e.hmacHashAlgorithm,"hmacHashAlgorithm"),Re.assertEmpty(e.password,"password");let n=new ArrayBuffer(64),r=new Uint8Array(n);t.getRandomValues(r);let i=this.parsedValue.authenticatedSafe.toSchema().toBER(!1);this.authSafe=new tt({contentType:tt.DATA,content:new U({valueHex:i})});let a=await t.stampDataWithPassword({password:e.password,hashAlgorithm:e.hmacHashAlgorithm,salt:n,iterationCount:e.iterations,contentToStamp:i});this.macData=new wn({mac:new dr({digestAlgorithm:new P({algorithmId:t.getOIDByAlgorithm({name:e.hmacHashAlgorithm},!0,"hmacHashAlgorithm")}),digest:new U({valueHex:a})}),macSalt:new U({valueHex:n}),iterations:e.iterations});}break;case 1:{if(!("signingCertificate"in e))throw new Re("signingCertificate");Re.assertEmpty(e.privateKey,"privateKey"),Re.assertEmpty(e.hashAlgorithm,"hashAlgorithm");let n=this.parsedValue.authenticatedSafe.toSchema().toBER(!1),r=new Fi({version:1,encapContentInfo:new mr({eContentType:"1.2.840.113549.1.7.1",eContent:new U({valueHex:n})}),certificates:[e.signingCertificate]}),i=await t.digest({name:e.hashAlgorithm},new Uint8Array(n)),a=[];a.push(new nt({type:"1.2.840.113549.1.9.3",values:[new G({value:"1.2.840.113549.1.7.1"})]})),a.push(new nt({type:"1.2.840.113549.1.9.5",values:[new Wn({valueDate:new Date})]})),a.push(new nt({type:"1.2.840.113549.1.9.4",values:[new U({valueHex:i})]})),r.signerInfos.push(new jl({version:1,sid:new vt({issuer:e.signingCertificate.issuer,serialNumber:e.signingCertificate.serialNumber}),signedAttrs:new Wt({type:0,attributes:a})})),await r.sign(e.privateKey,0,e.hashAlgorithm,void 0,t),this.authSafe=new tt({contentType:"1.2.840.113549.1.7.2",content:r.toSchema(!0)});}break;default:throw new Error(`Parameter "integrityMode" has unknown value: ${this.parsedValue.integrityMode}`)}}async parseInternalValues(e,t=ve(!0)){switch($e.assert(e,"parameters","object"),e.checkIntegrity===void 0&&(e.checkIntegrity=!0),this.parsedValue={},this.authSafe.contentType){case tt.DATA:{Re.assertEmpty(e.password,"password"),this.parsedValue.integrityMode=0,$e.assert(this.authSafe.content,"authSafe.content",U);let n=this.authSafe.content.getValue();if(this.parsedValue.authenticatedSafe=Zm.fromBER(n),e.checkIntegrity){if(!this.macData)throw new Error('Absent "macData" value, can not check PKCS#12 data integrity');let r=t.getAlgorithmByOID(this.macData.mac.digestAlgorithm.algorithmId,!0,"digestAlgorithm");if(!await t.verifyDataStampedWithPassword({password:e.password,hashAlgorithm:r.name,salt:re.toArrayBuffer(this.macData.macSalt.valueBlock.valueHexView),iterationCount:this.macData.iterations||1,contentToVerify:n,signatureToVerify:re.toArrayBuffer(this.macData.mac.digest.valueBlock.valueHexView)}))throw new Error("Integrity for the PKCS#12 data is broken!")}}break;case tt.SIGNED_DATA:{this.parsedValue.integrityMode=1;let n=new Fi({schema:this.authSafe.content}),r=n.encapContentInfo.eContent;Re.assert(r,"eContent","cmsSigned.encapContentInfo"),$e.assert(r,"eContent",U);let i=r.getValue();if(this.parsedValue.authenticatedSafe=Zm.fromBER(i),!await n.verify({signer:0,checkChain:!1},t))throw new Error("Integrity for the PKCS#12 data is broken!")}break;default:throw new Error(`Incorrect value for "this.authSafe.contentType": ${this.authSafe.contentType}`)}}};uA.CLASS_NAME="PFX";var ml="status",Ui="statusStrings",Li="failInfo",cU=[ml,Ui,Li],rk;(function(s){s[s.granted=0]="granted",s[s.grantedWithMods=1]="grantedWithMods",s[s.rejection=2]="rejection",s[s.waiting=3]="waiting",s[s.revocationWarning=4]="revocationWarning",s[s.revocationNotification=5]="revocationNotification";})(rk||(rk={}));var qo=class s extends O{constructor(e={}){super(),this.status=d(e,ml,s.defaultValues(ml)),Ui in e&&(this.statusStrings=d(e,Ui,s.defaultValues(Ui))),Li in e&&(this.failInfo=d(e,Li,s.defaultValues(Li))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case ml:return 2;case Ui:return [];case Li:return new Ae;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ml:return t===s.defaultValues(e);case Ui:return t.length===0;case Li:return t.isEqual(s.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||p,value:[new N({name:t.status||p}),new b({optional:!0,value:[new fe({name:t.statusStrings||p,value:new hs})]}),new Ae({name:t.failInfo||p,optional:!0})]})}fromSchema(e){V(e,cU);let t=R(e,e,s.schema({names:{status:ml,statusStrings:Ui,failInfo:Li}}));T.assertSchema(t,this.className);let n=t.result.status;if(n.valueBlock.isHexOnly===!0||n.valueBlock.valueDec<0||n.valueBlock.valueDec>5)throw new Error('PKIStatusInfo "status" has invalid value');this.status=n.valueBlock.valueDec,Ui in t.result&&(this.statusStrings=t.result.statusStrings),Li in t.result&&(this.failInfo=t.result.failInfo);}toSchema(){let e=[];return e.push(new N({value:this.status})),this.statusStrings&&e.push(new b({optional:!0,value:this.statusStrings})),this.failInfo&&e.push(this.failInfo),new b({value:e})}toJSON(){let e={status:this.status};return this.statusStrings&&(e.statusStrings=Array.from(this.statusStrings,t=>t.toJSON())),this.failInfo&&(e.failInfo=this.failInfo.toJSON()),e}};qo.CLASS_NAME="PKIStatusInfo";var Im="version",Cm="messageImprint",pl="reqPolicy",gl="nonce",ur="certReq",yl="extensions",tc="TimeStampReq",lA=`${tc}.${Im}`,hA=`${tc}.${Cm}`,zy=`${tc}.${pl}`,Yy=`${tc}.${gl}`,Zy=`${tc}.${ur}`,Qy=`${tc}.${yl}`,uU=[lA,hA,zy,Yy,Zy,Qy],fA=class s extends O{constructor(e={}){super(),this.version=d(e,Im,s.defaultValues(Im)),this.messageImprint=d(e,Cm,s.defaultValues(Cm)),pl in e&&(this.reqPolicy=d(e,pl,s.defaultValues(pl))),gl in e&&(this.nonce=d(e,gl,s.defaultValues(gl))),ur in e&&(this.certReq=d(e,ur,s.defaultValues(ur))),yl in e&&(this.extensions=d(e,yl,s.defaultValues(yl))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case Im:return 0;case Cm:return new Es;case pl:return p;case gl:return new N;case ur:return !1;case yl:return [];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Im:case pl:case ur:return t===s.defaultValues(e);case Cm:return Es.compareWithDefault("hashAlgorithm",t.hashAlgorithm)&&Es.compareWithDefault("hashedMessage",t.hashedMessage);case gl:return t.isEqual(s.defaultValues(e));case yl:return t.length===0;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||tc,value:[new N({name:t.version||lA}),Es.schema(t.messageImprint||{names:{blockName:hA}}),new G({name:t.reqPolicy||zy,optional:!0}),new N({name:t.nonce||Yy,optional:!0}),new xs({name:t.certReq||Zy,optional:!0}),new A({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new fe({name:t.extensions||Qy,value:ds.schema()})]})]})}fromSchema(e){V(e,uU);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.version=t.result[lA].valueBlock.valueDec,this.messageImprint=new Es({schema:t.result[hA]}),zy in t.result&&(this.reqPolicy=t.result[zy].valueBlock.toString()),Yy in t.result&&(this.nonce=t.result[Yy]),Zy in t.result&&(this.certReq=t.result[Zy].valueBlock.value),Qy in t.result&&(this.extensions=Array.from(t.result[Qy],n=>new ds({schema:n})));}toSchema(){let e=[];return e.push(new N({value:this.version})),e.push(this.messageImprint.toSchema()),this.reqPolicy&&e.push(new G({value:this.reqPolicy})),this.nonce&&e.push(this.nonce),ur in this&&s.compareWithDefault(ur,this.certReq)===!1&&e.push(new xs({value:this.certReq})),this.extensions&&e.push(new A({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.extensions,t=>t.toSchema())})),new b({value:e})}toJSON(){let e={version:this.version,messageImprint:this.messageImprint.toJSON()};return this.reqPolicy!==void 0&&(e.reqPolicy=this.reqPolicy),this.nonce!==void 0&&(e.nonce=this.nonce.toJSON()),this.certReq!==void 0&&s.compareWithDefault(ur,this.certReq)===!1&&(e.certReq=this.certReq),this.extensions&&(e.extensions=Array.from(this.extensions,t=>t.toJSON())),e}};fA.CLASS_NAME="TimeStampReq";var wl="status",bl="timeStampToken",BA="TimeStampResp",dA=`${BA}.${wl}`,Xy=`${BA}.${bl}`,lU=[dA,Xy],mA=class s extends O{constructor(e={}){super(),this.status=d(e,wl,s.defaultValues(wl)),bl in e&&(this.timeStampToken=d(e,bl,s.defaultValues(bl))),e.schema&&this.fromSchema(e.schema);}static defaultValues(e){switch(e){case wl:return new qo;case bl:return new tt;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case wl:return qo.compareWithDefault(wl,t.status)&&!("statusStrings"in t)&&!("failInfo"in t);case bl:return t.contentType===p&&t.content instanceof ue;default:return super.defaultValues(e)}}static schema(e={}){let t=d(e,"names",{});return new b({name:t.blockName||BA,value:[qo.schema(t.status||{names:{blockName:dA}}),tt.schema(t.timeStampToken||{names:{blockName:Xy,optional:!0}})]})}fromSchema(e){V(e,lU);let t=R(e,e,s.schema());T.assertSchema(t,this.className),this.status=new qo({schema:t.result[dA]}),Xy in t.result&&(this.timeStampToken=new tt({schema:t.result[Xy]}));}toSchema(){let e=[];return e.push(this.status.toSchema()),this.timeStampToken&&e.push(this.timeStampToken.toSchema()),new b({value:e})}toJSON(){let e={status:this.status.toJSON()};return this.timeStampToken&&(e.timeStampToken=this.timeStampToken.toJSON()),e}async sign(e,t,n=ve(!0)){return this.assertContentType(),new Fi({schema:this.timeStampToken.content}).sign(e,0,t,void 0,n)}async verify(e={signer:0,trustedCerts:[],data:ut},t=ve(!0)){return this.assertContentType(),new Fi({schema:this.timeStampToken.content}).verify(e,t)}assertContentType(){if(!this.timeStampToken)throw new Error("timeStampToken is absent in TSP response");if(this.timeStampToken.contentType!==pk)throw new Error(`Wrong format of timeStampToken: ${this.timeStampToken.contentType}`)}};mA.CLASS_NAME="TimeStampResp";function hU(){if(typeof globalThis<"u"&&"crypto"in globalThis){let s="webcrypto";"webkitSubtle"in globalThis.crypto&&(s="safari"),$N(s,new kl({name:s,crypto:globalThis.crypto}));}else if(typeof crypto<"u"&&"webcrypto"in crypto){let s="NodeJS ^15",e=crypto.webcrypto;$N(s,new kl({name:s,crypto:e}));}}hU();var VA=(s,e)=>e.some(t=>s instanceof t),Ik,Ck;function fU(){return Ik||(Ik=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function dU(){return Ck||(Ck=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var DA=new WeakMap,OA=new WeakMap,kw=new WeakMap;function mU(s){let e=new Promise((t,n)=>{let r=()=>{s.removeEventListener("success",i),s.removeEventListener("error",a);},i=()=>{t(sc(s.result)),r();},a=()=>{n(s.error),r();};s.addEventListener("success",i),s.addEventListener("error",a);});return kw.set(e,s),e}function pU(s){if(DA.has(s))return;let e=new Promise((t,n)=>{let r=()=>{s.removeEventListener("complete",i),s.removeEventListener("error",a),s.removeEventListener("abort",a);},i=()=>{t(),r();},a=()=>{n(s.error||new DOMException("AbortError","AbortError")),r();};s.addEventListener("complete",i),s.addEventListener("error",a),s.addEventListener("abort",a);});DA.set(s,e);}var UA={get(s,e,t){if(s instanceof IDBTransaction){if(e==="done")return DA.get(s);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return sc(s[e])},set(s,e,t){return s[e]=t,!0},has(s,e){return s instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in s}};function Tk(s){UA=s(UA);}function gU(s){return dU().includes(s)?function(...e){return s.apply(LA(this),e),sc(this.request)}:function(...e){return sc(s.apply(LA(this),e))}}function yU(s){return typeof s=="function"?gU(s):(s instanceof IDBTransaction&&pU(s),VA(s,fU())?new Proxy(s,UA):s)}function sc(s){if(s instanceof IDBRequest)return mU(s);if(OA.has(s))return OA.get(s);let e=yU(s);return e!==s&&(OA.set(s,e),kw.set(e,s)),e}var LA=s=>kw.get(s);function Bk(s,e,{blocked:t,upgrade:n,blocking:r,terminated:i}={}){let a=indexedDB.open(s,e),o=sc(a);return n&&a.addEventListener("upgradeneeded",c=>{n(sc(a.result),c.oldVersion,c.newVersion,sc(a.transaction),c);}),t&&a.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),o.then(c=>{i&&c.addEventListener("close",()=>i()),r&&c.addEventListener("versionchange",u=>r(u.oldVersion,u.newVersion,u));}).catch(()=>{}),o}var wU=["get","getKey","getAll","getAllKeys","count"],bU=["put","add","delete","clear"],RA=new Map;function Nk(s,e){if(!(s instanceof IDBDatabase&&!(e in s)&&typeof e=="string"))return;if(RA.get(e))return RA.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,r=bU.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(r||wU.includes(t)))return;let i=async function(a,...o){let c=this.transaction(a,r?"readwrite":"readonly"),u=c.store;return n&&(u=u.index(o.shift())),(await Promise.all([u[t](...o),r&&c.done]))[0]};return RA.set(e,i),i}Tk(s=>({...s,get:(e,t,n)=>Nk(e,t)||s.get(e,t,n),has:(e,t)=>!!Nk(e,t)||s.has(e,t)}));var SU=["continue","continuePrimaryKey","advance"],kk={},jA=new WeakMap,Ok=new WeakMap,vU={get(s,e){if(!SU.includes(e))return s[e];let t=kk[e];return t||(t=kk[e]=function(...n){jA.set(this,Ok.get(this)[e](...n));}),t}};async function*xU(...s){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...s)),!e)return;e=e;let t=new Proxy(e,vU);for(Ok.set(t,e),kw.set(t,LA(e));e;)yield t,e=await(jA.get(t)||e.continue()),jA.delete(t);}function Pk(s,e){return e===Symbol.asyncIterator&&VA(s,[IDBIndex,IDBObjectStore,IDBCursor])||e==="iterate"&&VA(s,[IDBIndex,IDBObjectStore])}Tk(s=>({...s,get(e,t,n){return Pk(e,t)?xU:s.get(e,t,n)},has(e,t){return Pk(e,t)||s.has(e,t)}}));function Rk(s,e){if(s===e)return !0;if(s===null||e===null||typeof s!="object"||typeof e!="object")return !1;let t=Object.keys(s),n=Object.keys(e);if(t.length!==n.length)return !1;for(let r of t)if(!n.includes(r)||!Rk(s[r],e[r]))return !1;return !0}var xt=class{dbName;storeName;key;migrations;_db=null;listeners=[];broadcastChannel;constructor(e,t,n,r=[]){this.dbName=e,this.storeName=t,this.key=n,this.migrations=r,typeof BroadcastChannel<"u"&&(this.broadcastChannel=new BroadcastChannel(this.dbName+"-observer"),this.broadcastChannel.onmessage=i=>{i.data&&i.data.keyValue!==void 0&&i.data.updateType&&this.listeners.forEach(a=>a(i.data.keyValue,i.data.updateType,i.data.oldItem,i.data.newItem));});}async openDB(){if(this._db)return this._db;let e=this.migrations.length+1;return this._db=await Bk(this.dbName,e,{upgrade:(t,n,r,i,a)=>{if(r!==null)for(let o=n+1;o<=r;o++){let c=o-2;if(c>=0&&c<this.migrations.length){let u=this.migrations[c];if(u)u(t,i,a);else throw new Error(`Migration for schema version ${o} (using migrations[${c}]) not found but expected.`)}}},blocked:()=>{console.error(`IndexedDB ${this.dbName} upgrade blocked.`);},blocking:()=>{console.warn(`IndexedDB ${this.dbName} upgrade is being blocked by other connections. Closing this connection.`),this._db&&(this._db.close(),this._db=null);},terminated:()=>{console.warn(`IndexedDB ${this.dbName} connection terminated.`),this._db=null;}}),await this.handleOpenDB(),this._db}async handleOpenDB(){}async getStore(e){return (await this.openDB()).transaction(this.storeName,e).objectStore(this.storeName)}async get(e){return (await this.getStore("readonly")).get(e)}async list(){return (await this.getStore("readonly")).getAll()}async set(e){let t=await this.openDB(),n=e[this.key],r=t.transaction(this.storeName,"readwrite"),i=r.objectStore(this.storeName),a=await i.get(n);await i.put(e,n),await r.done;let o=null;return a?Rk(a,e)||(o="updated"):o="added",o&&this.notifyUpdate(n,o,a,e),n}async del(e){let t=await this.get(e),r=(await this.openDB()).transaction(this.storeName,"readwrite");await r.objectStore(this.storeName).delete(e),await r.done,t&&this.notifyUpdate(e,"removed",t,void 0);}notifyUpdate(e,t,n,r){this.listeners.forEach(i=>i(e,t,n,r)),this.broadcastChannel&&this.broadcastChannel.postMessage({keyValue:e,updateType:t,oldItem:n,newItem:r});}addListener(e){return this.listeners.push(e),()=>this.removeListener(e)}removeListener(e){this.listeners=this.listeners.filter(t=>t!==e);}async close(){this._db&&(this._db.close(),this._db=null),this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=void 0);}};var HA="auth-commitments",t0=class extends xt{constructor(e="sequence-auth-commitments"){super(e,HA,"id",[(t,n,r)=>{t.objectStoreNames.contains(HA)||t.createObjectStore(HA);}]);}};var _A="auth-keys",s0=class extends xt{expirationTimers=new Map;constructor(e="sequence-auth-keys"){super(e,_A,"address",[(t,n,r)=>{t.objectStoreNames.contains(_A)||t.createObjectStore(_A).createIndex("identitySigner","identitySigner",{unique:!0});}]);}async handleOpenDB(){let e=await this.list();for(let t of e)await this.scheduleExpiration(t);}async set(e){let t=await super.set({...e,address:e.address.toLowerCase(),identitySigner:e.identitySigner.toLowerCase()});return this.scheduleExpiration(e),t}async del(e){let t=await super.del(e.toLowerCase());return this.clearExpiration(e),t}async getBySigner(e,t=1){let n=e.toLowerCase(),r=await this.getStore("readonly"),i=r.index("identitySigner");try{let a=await i.get(n);if(a!==void 0)return a;if(t<2)return await new Promise(o=>setTimeout(o,50)),this.getBySigner(e,t+1);try{let o=await r.getAll();return o&&o.length>0?o.find(u=>u.identitySigner.toLowerCase()===n):void 0}catch(o){throw console.error(`[AuthKeys.getBySigner] Fallback: Error during getAll() for signer ${n}:`,o),o}}catch(a){throw console.error(`[AuthKeys.getBySigner attempt #${t}] Index query error for signer ${n}:`,a),a}}async delBySigner(e){let t=await this.getBySigner(e.toLowerCase());t&&await this.del(t.address.toLowerCase());}async scheduleExpiration(e){this.clearExpiration(e.address.toLowerCase());let t=Date.now(),n=e.expiresAt.getTime()-t;if(n<=0){await this.del(e.address.toLowerCase());return}let r=window.setTimeout(()=>{console.log("removing expired auth key",e),this.del(e.address.toLowerCase());},n);this.expirationTimers.set(e.address.toLowerCase(),r);}clearExpiration(e){let t=this.expirationTimers.get(e.toLowerCase());t&&(window.clearTimeout(t),this.expirationTimers.delete(e.toLowerCase()));}};var MA="messages",n0=class extends xt{constructor(e="sequence-messages"){super(e,MA,"id",[(t,n,r)=>{t.objectStoreNames.contains(MA)||t.createObjectStore(MA);}]);}};var $A="envelopes",r0=class extends xt{constructor(e="sequence-signature-requests"){super(e,$A,"id",[(t,n,r)=>{t.objectStoreNames.contains($A)||t.createObjectStore($A);}]);}};var qA="transactions",i0=class extends xt{constructor(e="sequence-transactions"){super(e,qA,"id",[(t,n,r)=>{t.objectStoreNames.contains(qA)||t.createObjectStore(qA);}]);}};var FA="wallets",a0=class extends xt{constructor(e="sequence-manager"){super(e,FA,"address",[(t,n,r)=>{t.objectStoreNames.contains(FA)||t.createObjectStore(FA);}]);}};var KA="queued-recovery-payloads",o0=class extends xt{constructor(e="sequence-recovery"){super(e,KA,"id",[(t,n,r)=>{t.objectStoreNames.contains(KA)||t.createObjectStore(KA);}]);}};var GA="passkey-credentials",c0=class extends xt{constructor(e="sequence-passkey-credentials"){super(e,GA,"credentialId",[(t,n,r)=>{t.objectStoreNames.contains(GA)||t.createObjectStore(GA);}]);}async getByCredentialId(e){return this.get(e)}async saveCredential(e,t,n){let r=new Date().toISOString(),i={credentialId:e,publicKey:t,walletAddress:n,createdAt:r,lastLoginAt:r};await this.set(i);}async updateCredential(e,{lastLoginAt:t,walletAddress:n}){let r=await this.getByCredentialId(e);if(r){let i={...r,lastLoginAt:t,walletAddress:n};await this.set(i);}}};({verbose:!1,extensions:Ne.Rc5,context:wa.Rc5,context4337:wa.Rc5_4337,guest:_e.DefaultGuestAddress,encryptedPksDb:new Ks.Pk.Encrypted.EncryptedPksDb,managerDb:new a0,signaturesDb:new r0,transactionsDb:new i0,messagesDb:new n0,authCommitmentsDb:new t0,recoveryDb:new o0,authKeysDb:new s0,passkeyCredentialsDb:new c0,dbPruningInterval:1e3*60*60*24,stateProvider:new Hc.Sequence.Provider,networks:Sa.ALL,relayers:()=>typeof window<"u"?[ef.LocalRelayer.createFromWindow(window)].filter(s=>s!==void 0):[],bundlers:[],nonWitnessableSigners:[],guardUrl:"https://guard.sequence.app",guardAddresses:{wallet:"0x26f3D30F41FA897309Ae804A2AFf15CEb1dA5742",sessions:"0xF6Bc87F5F2edAdb66737E32D37b46423901dfEF1"},defaultGuardTopology:{type:"nested",weight:1n,threshold:1n,tree:[{type:"signer",address:_e.PlaceholderAddress,weight:1n},{type:"signer",address:"0x007a47e6BF40C1e0ed5c01aE42fDC75879140bc4",weight:1n}]},defaultSessionsTopology:{type:"sapient-signer",weight:1n},defaultRecoverySettings:{requiredDeltaTime:2592000n,minTimestamp:0n},multiInjectedProviderDiscovery:!0,identity:{url:"https://identity.sequence.app",fetch:typeof window<"u"?window.fetch:void 0,verifyAttestation:!0,email:{enabled:!1},google:{enabled:!1,clientId:""},apple:{enabled:!1,clientId:""}}});var u0=class{#e;#s;#n=null;#t=null;constructor(e,t){this.#e=e,this.#s=t;}async#a(){let e=await this.#e();if(!e)throw new ze("User not authenticated","NOT_LOGGED_IN_ERROR");return e}async#i(){let e=this.#n;e||(e=await this.#r());let t=await this.#a();return t.profile.sub!==e.userIdentifier&&(e=await this.#r(t)),e}async#r(e){return this.#t?this.#t:(this.#t=(async()=>{try{this.#n=null,await this.#e(!0);let t=e||await this.#a();if(!t.idToken)throw new ze("User idToken not available","NOT_LOGGED_IN_ERROR");let{idToken:n}=t,r=decodeJwtPayload(n),i=r.iss,a=r.aud,o=await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"]),c=await window.crypto.subtle.exportKey("raw",o.publicKey),u={address:E.fromBytes(new Uint8Array(c)),privateKey:o.privateKey,identitySigner:"",expiresAt:new Date(Date.now()+36e5)},l=new Wh(this.#s.identityInstrumentEndpoint,"@14:test"),h=new kg(i,a,n);await l.commitVerifier(xa.toIdentityAuthKey(u),h);let y=(await l.completeAuth(xa.toIdentityAuthKey(u),h)).signer.address;return u.identitySigner=y,this.#n={userIdentifier:t.profile.sub,signerAddress:y,authKey:u,identityInstrument:l},this.#n}catch(t){let n=`Identity Instrument: Failed to create signer: ${t.message}`;throw new ze(n,"WALLET_CONNECTION_ERROR")}finally{this.#t=null;}})(),this.#t)}async getAddress(){return (await this.#i()).signerAddress}async signPayload(e,t,n){let r=await this.#i();return new xa.IdentitySigner(r.identityInstrument,r.authKey).sign(e,t,n)}async signMessage(e){let t=await this.#i(),n=new xa.IdentitySigner(t.identityInstrument,t.authKey),r=typeof e=="string"?new TextEncoder().encode(e):e,i=hashMessage({raw:r}),a=await n.signDigest(E.toBytes(i)),o=toHex(a.r,{size:32}),c=toHex(a.s,{size:32}),u=toHex(a.yParity+27,{size:1});return concat([o,c,u])}};var l0=class{#e;#s=null;#n=null;constructor(e){this.#e=e;}async#t(){let e=await this.#e();if(!e)throw new ze("User not authenticated","NOT_LOGGED_IN_ERROR");return e}async#a(){let e=this.#s;e||(e=await this.#i());let t=await this.#t();return t.profile.sub!==e.userIdentifier&&(e=await this.#i(t)),e}async#i(e){return this.#n?this.#n:(this.#n=(async()=>{try{this.#s=null;let t=e||await this.#t(),n=keccak256(toBytes(`${t.profile.sub}-sequence`)),r=new Ks.Pk.Pk(n),i=r.address;return this.#s={userIdentifier:t.profile.sub,signerAddress:i,signer:r,privateKey:n},this.#s}catch(t){let n=`Failed to create private key wallet: ${t.message}`;throw new ze(n,"WALLET_CONNECTION_ERROR")}finally{this.#n=null;}})(),this.#n)}async getAddress(){return (await this.#a()).signerAddress}async signPayload(e,t,n){return (await this.#a()).signer.sign(e,t,n)}async signMessage(e){let t=await this.#a(),n=privateKeyToAccount(t.privateKey),r=typeof e=="string"?e:{raw:e};return await n.signMessage({message:r})}};function Hk(s,e={}){if(e.isDevEnvironment)return new l0(s);if(!e.identityInstrumentEndpoint)throw new Error("identityInstrumentEndpoint is required for non-dev environments");return new u0(s,{identityInstrumentEndpoint:e.identityInstrumentEndpoint})}function KU(s){return s in Sr}function GU(s){if(s.magicPublishableApiKey&&s.magicProviderId)return {magicPublishableApiKey:s.magicPublishableApiKey,magicProviderId:s.magicProviderId};let{chainId:e}=s;if(KU(e))return Sr[e];throw new Error(`No Magic configuration available for chain ${s.chainId}. Please provide magicPublishableApiKey and magicProviderId in ChainConfig.`)}var WU="PtQRK4iRJ8GkXjiz6xfImMAYhPhW0cYk",JU="mjtCL8mt06BtbxSkp2vbrYStKWnXVZfo",zU="openid profile email offline_access transact",YU="platform_api",ZU="https://auth.immutable.com/im-logged-in",QU="https://auth.immutable.com",XU=/(sandbox|testnet)/i,eL=[13371,13473,15003];function tL(s){return eL.includes(s.chainId)}function sL(s){if(s.chainId===13473)return !0;let e=s.apiUrl||s.passportDomain||"";return XU.test(e)}function nL(s){if(s.passportDomain)return s.passportDomain;if(s.apiUrl)try{let e=new URL(s.apiUrl),t=e.hostname.replace("api.","passport.");return `${e.protocol}//${t}`}catch{return s.apiUrl.replace("api.","passport.")}return "https://passport.immutable.com"}function rL(){return QU}function iL(){return ZU}function _k(s){return sL(s)?JU:WU}function aL(s,e){let t=nL(s),n=rL(),r=iL(),i=e.clientId||_k(s),a=new Auth({clientId:i,redirectUri:r,popupRedirectUri:r,logoutRedirectUri:r,scope:zU,audience:YU,authenticationDomain:n,passportDomain:t,popupOverlayOptions:e.popupOverlayOptions,crossSdkBridgeEnabled:e.crossSdkBridgeEnabled});return typeof window<"u"&&window.addEventListener("message",async o=>{if(o.data.code&&o.data.state){let c=window.location.search,u=new URLSearchParams(c);u.set("code",o.data.code),u.set("state",o.data.state),window.history.replaceState(null,"",`?${u.toString()}`),await a.loginCallback(),u.delete("code"),u.delete("state"),window.history.replaceState(null,"",`?${u.toString()}`);}}),{getUser:async()=>a.getUserOrLogin(),clientId:i}}async function oL(s={}){let e=s.chains&&s.chains.length>0?s.chains:A0,t=s.initialChainId||e[0].chainId,n=e.find(w=>w.chainId===t);if(!n)throw new Error(`Initial chain ${t} not found in chains configuration`);let r=createConfig({basePath:n.apiUrl}),i=new MultiRollupApiClients({indexer:r,orderBook:r,passport:r}),a,o;if(s.getUser)a=s.getUser,o=s.clientId||_k(n);else {let w=aL(n,s);a=w.getUser,o=w.clientId;}let c=await a().catch(()=>null),u=n.passportDomain||n.apiUrl.replace("api.","passport."),l=new th({passportDomain:u,zkEvmRpcUrl:n.rpcUrl,relayerUrl:n.relayerUrl,indexerMrBasePath:n.apiUrl,jsonRpcReferrer:s.jsonRpcReferrer,forceScwDeployBeforeMessageSignature:s.forceScwDeployBeforeMessageSignature,crossSdkBridgeEnabled:s.crossSdkBridgeEnabled,feeTokenSymbol:s.feeTokenSymbol}),h=s.passportEventEmitter||new TypedEventEmitter,m=new mr$1.GuardianApi(r),y=new cc({config:l,getUser:a,guardianApi:m,passportDomain:u,clientId:o}),g;if(tL(n)){let w=GU(n),S=n.magicTeeBasePath||"https://tee.express.magiclabs.com",C=new MagicTeeApiClients({basePath:S,timeout:1e4,magicPublishableApiKey:w.magicPublishableApiKey,magicProviderId:w.magicProviderId}),k=new uc(a,C),x=null;n.chainId===13371?x="https://api.immutable.com":n.chainId===13473?x="https://api.sandbox.immutable.com":n.apiUrl&&(x=n.apiUrl),g=new Xl({getUser:a,clientId:o,config:l,multiRollupApiClients:i,walletEventEmitter:h,guardianClient:y,ethSigner:k,user:c,sessionActivityApiUrl:x});}else {let w=u.includes(".dev.")||n.apiUrl.includes(".dev."),S=Hk(a,{identityInstrumentEndpoint:n.sequenceIdentityInstrumentEndpoint,isDevEnvironment:w});g=new eh({getUser:a,chainConfig:n,multiRollupApiClients:i,guardianClient:y,ethSigner:S,passportEventEmitter:h});}return s.announceProvider!==!1&&Qw({info:Zw,provider:g}),g}function hL(s){return typeof s=="object"&&s!==null&&"code"in s&&"message"in s}async function fL(s,e){let t=await s.getUser();if(!t?.profile.sub)return [];let n={Authorization:`Bearer ${t.accessToken}`},{data:r}=await e.passportProfileApi.getUserInfo({headers:n});return r.linked_addresses}async function dL(s,e,t){let n=trackFlow("wallet","linkExternalWallet");try{let r=await s.getUser();if(!r)throw new ze("User is not logged in","NOT_LOGGED_IN_ERROR");if(!isUserZkEvm(r))throw new ze("User has not been registered on Immutable zkEVM","WALLET_CONNECTION_ERROR");let a={Authorization:`Bearer ${r.accessToken}`},o={type:t.type,wallet_address:t.walletAddress,signature:t.signature,nonce:t.nonce};return {...(await e.passportProfileApi.linkWalletV2({linkWalletV2Request:o},{headers:a})).data}}catch(r){if(r instanceof Error?trackError("wallet","linkExternalWallet",r):n.addEvent("errored"),Ji(r)&&r.response){if(r.response.data&&hL(r.response.data)){let{code:a,message:o}=r.response.data;switch(a){case"ALREADY_LINKED":throw new ze(o,"WALLET_CONNECTION_ERROR");case"MAX_WALLETS_LINKED":throw new ze(o,"WALLET_CONNECTION_ERROR");case"DUPLICATE_NONCE":throw new ze(o,"WALLET_CONNECTION_ERROR");case"VALIDATION_ERROR":throw new ze(o,"WALLET_CONNECTION_ERROR");default:throw new ze(o,"WALLET_CONNECTION_ERROR")}}else if(r.response.status)throw new ze(`Link wallet request failed with status code ${r.response.status}`,"WALLET_CONNECTION_ERROR")}let i="Link wallet request failed";throw r instanceof Error&&(i+=`: ${r.message}`),new ze(i,"WALLET_CONNECTION_ERROR")}finally{n.addEvent("End");}}/*! Bundled license information:
|
|
376
376
|
|
|
377
377
|
@noble/hashes/esm/utils.js:
|
|
378
378
|
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
@@ -506,4 +506,4 @@ pkijs/build/index.es.js:
|
|
|
506
506
|
*)
|
|
507
507
|
*/
|
|
508
508
|
|
|
509
|
-
export {
|
|
509
|
+
export { mP as ARBITRUM_ONE, x0 as ARBITRUM_ONE_CHAIN, jw as ARBITRUM_ONE_CHAIN_ID, pP as ARBITRUM_SEPOLIA, E0 as ARBITRUM_SEPOLIA_CHAIN, Hw as ARBITRUM_SEPOLIA_CHAIN_ID, oc as ConfirmationScreen, A0 as DEFAULT_CHAINS, h0 as EvmChain, cc as GuardianClient, hP as IMMUTABLE_ZKEVM_MAINNET, zl as IMMUTABLE_ZKEVM_MAINNET_CHAIN, Jl as IMMUTABLE_ZKEVM_MAINNET_CHAIN_ID, dP as IMMUTABLE_ZKEVM_MULTICHAIN, fP as IMMUTABLE_ZKEVM_TESTNET, Yl as IMMUTABLE_ZKEVM_TESTNET_CHAIN, Gi as IMMUTABLE_ZKEVM_TESTNET_CHAIN_ID, te as JsonRpcError, uc as MagicTEESigner, Kl as ProviderErrorCode, ZA as ProviderEvent, Fl as RelayerClient, $k as RelayerTransactionStatus, Os as RpcErrorCode, eh as SequenceProvider, th as WalletConfiguration, ze as WalletError, Wi as WalletErrorType, YA as WalletEvents, Xl as ZkEvmProvider, Qw as announceProvider, oL as connectWallet, bP as getChainConfig, ac as getEvmChainFromChainId, fL as getLinkedAddresses, dL as linkExternalWallet, Zw as passportProviderInfo, C0 as retryWithDelay, cI as walletHelpers };
|