@authsignal/browser 1.12.6 → 1.13.0-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/dist/api/digital-credential-api-client.d.ts +12 -0
- package/dist/api/types/digital-credential.d.ts +27 -0
- package/dist/api/types/shared.d.ts +7 -3
- package/dist/authsignal.d.ts +4 -1
- package/dist/digital-credential.d.ts +43 -0
- package/dist/email-magic-link.d.ts +3 -1
- package/dist/email.d.ts +3 -1
- package/dist/handlers/popup-handler.d.ts +4 -2
- package/dist/helpers.d.ts +18 -4
- package/dist/index.d.ts +3 -0
- package/dist/index.js +25577 -150
- package/dist/index.min.js +64 -1
- package/dist/passkey.d.ts +3 -1
- package/dist/push.d.ts +3 -1
- package/dist/qr-code/rest-qr-handler.d.ts +3 -1
- package/dist/qr-code/websocket-qr-handler.d.ts +3 -1
- package/dist/qr-code.d.ts +3 -1
- package/dist/security-key.d.ts +3 -1
- package/dist/sms.d.ts +3 -1
- package/dist/token-cache.d.ts +6 -2
- package/dist/totp.d.ts +3 -1
- package/dist/types.d.ts +16 -6
- package/dist/utils.d.ts +1 -0
- package/dist/whatsapp.d.ts +3 -1
- package/package.json +7 -2
package/dist/index.min.js
CHANGED
|
@@ -1 +1,64 @@
|
|
|
1
|
-
var authsignal=function(e){"use strict";let t;const n=new Uint8Array(16);function r(){if(!t&&(t="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!t))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return t(n)}const o=[];for(let e=0;e<256;++e)o.push((e+256).toString(16).slice(1));var i={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function s(e,t,n){if(i.randomUUID&&!t&&!e)return i.randomUUID();const s=(e=e||{}).random||(e.rng||r)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){n=n||0;for(let e=0;e<16;++e)t[n+e]=s[e];return t}return function(e,t=0){return(o[e[t+0]]+o[e[t+1]]+o[e[t+2]]+o[e[t+3]]+"-"+o[e[t+4]]+o[e[t+5]]+"-"+o[e[t+6]]+o[e[t+7]]+"-"+o[e[t+8]]+o[e[t+9]]+"-"+o[e[t+10]]+o[e[t+11]]+o[e[t+12]]+o[e[t+13]]+o[e[t+14]]+o[e[t+15]]).toLowerCase()}(s)}var a=function(e,t){return a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},a(e,t)};function c(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}a(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var l=function(){return l=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},l.apply(this,arguments)};function h(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}function u(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))}function d(e,t){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}}function p(e){const t=new Uint8Array(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function f(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4,r=t.padEnd(t.length+n,"="),o=atob(r),i=new ArrayBuffer(o.length),s=new Uint8Array(i);for(let e=0;e<o.length;e++)s[e]=o.charCodeAt(e);return i}function v(){return g.stubThis(void 0!==globalThis?.PublicKeyCredential&&"function"==typeof globalThis.PublicKeyCredential)}const g={stubThis:e=>e};function y(e){const{id:t}=e;return{...e,id:f(t),transports:e.transports}}function b(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}class m extends Error{constructor({message:e,code:t,cause:n,name:r}){super(e,{cause:n}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=r??n.name,this.code=t}}const k=new class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},w=["cross-platform","platform"];function E(e){if(e&&!(w.indexOf(e)<0))return e}async function I(e){!e.optionsJSON&&e.challenge&&(console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});const{optionsJSON:t,useAutoRegister:n=!1}=e;if(!v())throw new Error("WebAuthn is not supported in this browser");const r={...t,challenge:f(t.challenge),user:{...t.user,id:f(t.user.id)},excludeCredentials:t.excludeCredentials?.map(y)},o={};let i;n&&(o.mediation="conditional"),o.publicKey=r,o.signal=k.createNewAbortSignal();try{i=await navigator.credentials.create(o)}catch(e){throw function({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new m({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===n.authenticatorSelection?.requireResidentKey)return new m({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===n.authenticatorSelection?.userVerification)return new m({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===n.authenticatorSelection?.userVerification)return new m({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new m({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new m({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name)return 0===n.pubKeyCredParams.filter((e=>"public-key"===e.type)).length?new m({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new m({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if("SecurityError"===e.name){const t=globalThis.location.hostname;if(!b(t))return new m({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rp.id!==t)return new m({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new m({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new m({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}({error:e,options:o})}if(!i)throw new Error("Registration was not completed");const{id:s,rawId:a,response:c,type:l}=i;let h,u,d,g;if("function"==typeof c.getTransports&&(h=c.getTransports()),"function"==typeof c.getPublicKeyAlgorithm)try{u=c.getPublicKeyAlgorithm()}catch(e){T("getPublicKeyAlgorithm()",e)}if("function"==typeof c.getPublicKey)try{const e=c.getPublicKey();null!==e&&(d=p(e))}catch(e){T("getPublicKey()",e)}if("function"==typeof c.getAuthenticatorData)try{g=p(c.getAuthenticatorData())}catch(e){T("getAuthenticatorData()",e)}return{id:s,rawId:p(a),response:{attestationObject:p(c.attestationObject),clientDataJSON:p(c.clientDataJSON),transports:h,publicKeyAlgorithm:u,publicKey:d,authenticatorData:g},type:l,clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:E(i.authenticatorAttachment)}}function T(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.\n`,t)}const C={stubThis:e=>e};async function S(e){!e.optionsJSON&&e.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});const{optionsJSON:t,useBrowserAutofill:n=!1,verifyBrowserAutofillInput:r=!0}=e;if(!v())throw new Error("WebAuthn is not supported in this browser");let o;0!==t.allowCredentials?.length&&(o=t.allowCredentials?.map(y));const i={...t,challenge:f(t.challenge),allowCredentials:o},s={};if(n){if(!await function(){if(!v())return C.stubThis(new Promise((e=>e(!1))));const e=globalThis.PublicKeyCredential;return void 0===e?.isConditionalMediationAvailable?C.stubThis(new Promise((e=>e(!1)))):C.stubThis(e.isConditionalMediationAvailable())}())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&r)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');s.mediation="conditional",i.allowCredentials=[]}let a;s.publicKey=i,s.signal=k.createNewAbortSignal();try{a=await navigator.credentials.get(s)}catch(e){throw function({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new m({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new m({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=globalThis.location.hostname;if(!b(t))return new m({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rpId!==t)return new m({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new m({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}({error:e,options:s})}if(!a)throw new Error("Authentication was not completed");const{id:c,rawId:l,response:h,type:u}=a;let d;return h.userHandle&&(d=p(h.userHandle)),{id:c,rawId:p(l),response:{authenticatorData:p(h.authenticatorData),clientDataJSON:p(h.clientDataJSON),signature:p(h.signature),userHandle:d},type:u,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:E(a.authenticatorAttachment)}}function A(e){var t=e.name,n=e.value,r=e.expire,o=e.domain,i=e.secure,s=r===1/0?" expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+r;document.cookie=encodeURIComponent(t)+"="+n+"; path=/;"+s+(o?"; domain="+o:"")+(i?"; secure":"")}function R(e){var t,n=null!==(t=e.errorDescription)&&void 0!==t?t:e.error;return console.error(n),{error:n}}function O(e){var t;if(e&&"object"==typeof e&&"error"in e){var n=null!==(t=e.errorDescription)&&void 0!==t?t:e.error;return console.error(n),{error:n}}if(e&&"object"==typeof e&&"accessToken"in e&&"string"==typeof e.accessToken){var r=e.accessToken,o=h(e,["accessToken"]);return{data:l(l({},o),{token:r})}}return{data:e}}function x(e){var t,n;if(e instanceof m&&"ERROR_INVALID_RP_ID"===e.code){var r=(null===(n=null===(t=e.message)||void 0===t?void 0:t.match(/"([^"]*)"/))||void 0===n?void 0:n[1])||"";console.error('[Authsignal] The Relying Party ID "'.concat(r,'" is invalid for this domain.\n To learn more, visit https://docs.authsignal.com/scenarios/passkeys-prebuilt-ui#defining-the-relying-party'))}}function U(e){var t=e.token,n=e.tenantId;return{"Content-Type":"application/json",Authorization:t?"Bearer ".concat(t):"Basic ".concat(window.btoa(encodeURIComponent(n)))}}function P(e){var t=e.response,n=e.onTokenExpired;"error"in t&&"expired_token"===t.errorCode&&n&&n()}e.AuthsignalWindowMessage=void 0,(e.AuthsignalWindowMessage||(e.AuthsignalWindowMessage={})).AUTHSIGNAL_CLOSE_POPUP="AUTHSIGNAL_CLOSE_POPUP";var N=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.registrationOptions=function(e){return u(this,arguments,void 0,(function(e){var t,n,r,o,i=e.token,s=e.username,a=e.authenticatorAttachment,c=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return t=Boolean(a)?{username:s,authenticatorAttachment:a}:{username:s},n="".concat(this.baseUrl,c?"/client/user-authenticators/passkey/registration-options/web":"/client/user-authenticators/passkey/registration-options"),r=c?"include":"same-origin",[4,fetch(n,{method:"POST",headers:U({token:i,tenantId:this.tenantId}),body:JSON.stringify(t),credentials:r})];case 1:return[4,e.sent().json()];case 2:return P({response:o=e.sent(),onTokenExpired:this.onTokenExpired}),[2,o]}}))}))},e.prototype.authenticationOptions=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token,r=e.challengeId,o=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey/authentication-options"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify({challengeId:r}),credentials:o?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.authenticationOptionsWeb=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey/authentication-options/web"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify({}),credentials:"include"})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.addAuthenticator=function(e){return u(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.registrationCredential,i=e.conditionalCreate,s=e.challengeId,a=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return t={registrationCredential:o,conditionalCreate:i,challengeId:s},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey"),{method:"POST",headers:U({token:r,tenantId:this.tenantId}),body:JSON.stringify(t),credentials:a?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,r=e.authenticationCredential,o=e.token,i=e.deviceId,s=e.challengeId,a=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return t={authenticationCredential:r,deviceId:i,challengeId:s},[4,fetch("".concat(this.baseUrl,"/client/verify/passkey"),{method:"POST",headers:U({token:o,tenantId:this.tenantId}),body:JSON.stringify(t),credentials:a?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.getPasskeyAuthenticator=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.credentialIds;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey?credentialIds=").concat(n),{method:"GET",headers:U({tenantId:this.tenantId})})];case 1:if(!(t=e.sent()).ok)throw new Error(t.statusText);return[2,t.json()]}}))}))},e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n,r=e.action,o=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return t="".concat(this.baseUrl,o?"/client/challenge/web":"/client/challenge"),[4,fetch(t,{method:"POST",headers:U({tenantId:this.tenantId}),body:JSON.stringify({action:r}),credentials:o?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),_=function(){function e(){this.token=null}return e.prototype.handleTokenNotSetError=function(){var e="A token has not been set. Call 'setToken' first.";return console.error("Error: ".concat(e)),{error:"TOKEN_NOT_SET",errorDescription:e}},e.shared=new e,e}(),$=!1,D=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.anonymousId,o=e.onTokenExpired;this.passkeyLocalStorageKey="as_user_passkey_map",this.cache=_.shared,this.api=new N({baseUrl:t,tenantId:n,onTokenExpired:o}),this.anonymousId=r}return e.prototype.signUp=function(e){return u(this,arguments,void 0,(function(e){var t,n,r,o,i,s,a=e.username,c=e.displayName,h=e.token,u=e.authenticatorAttachment,p=void 0===u?"platform":u,f=e.useAutoRegister,v=void 0!==f&&f,g=e.useCookies,y=void 0!==g&&g;return d(this,(function(e){switch(e.label){case 0:return(t=null!=h?h:this.cache.token)?v?[4,this.doesBrowserSupportConditionalCreate()]:[3,2]:[2,this.cache.handleTokenNotSetError()];case 1:if(!e.sent())throw new Error("CONDITIONAL_CREATE_NOT_SUPPORTED");e.label=2;case 2:return n={username:a,displayName:c,token:t,authenticatorAttachment:p,useCookies:y},[4,this.api.registrationOptions(n)];case 3:if("error"in(r=e.sent()))return[2,R(r)];e.label=4;case 4:return e.trys.push([4,7,,8]),[4,I({optionsJSON:r.options,useAutoRegister:v})];case 5:return o=e.sent(),[4,this.api.addAuthenticator({registrationCredential:o,token:t,conditionalCreate:v,challengeId:r.challengeId,useCookies:y})];case 6:return"error"in(i=e.sent())?[2,R(i)]:(i.isVerified&&this.storeCredentialAgainstDevice(l(l({},o),{userId:i.userId})),i.accessToken&&(this.cache.token=i.accessToken),[2,{data:{token:i.accessToken,userAuthenticator:i.userAuthenticator,registrationResponse:o}}]);case 7:throw s=e.sent(),$=!1,x(s),s;case 8:return[2]}}))}))},e.prototype.signIn=function(e){return u(this,void 0,void 0,(function(){var t,n,r,o,i,s,a,c,h,u,p,f,v;return d(this,(function(d){switch(d.label){case 0:if((null==e?void 0:e.token)&&e.autofill)throw new Error("autofill is not supported when providing a token");if((null==e?void 0:e.action)&&e.token)throw new Error("action is not supported when providing a token");if(null==e?void 0:e.autofill){if($)return[2,{}];$=!0}return(null==e?void 0:e.action)?[4,this.api.challenge({action:null==e?void 0:e.action,useCookies:null==e?void 0:e.useCookies})]:[3,2];case 1:return n=d.sent(),[3,3];case 2:n=null,d.label=3;case 3:return(t=n)&&"error"in t?($=!1,[2,R(t)]):!(null==e?void 0:e.action)&&(null==e?void 0:e.useCookies)?[3,5]:[4,this.api.authenticationOptions({token:null==e?void 0:e.token,challengeId:null==t?void 0:t.challengeId,useCookies:null==e?void 0:e.useCookies})];case 4:return o=d.sent(),[3,7];case 5:return[4,this.api.authenticationOptionsWeb({token:null==e?void 0:e.token})];case 6:o=d.sent(),d.label=7;case 7:if("error"in(r=o))return $=!1,[2,R(r)];d.label=8;case 8:return d.trys.push([8,11,,12]),[4,S({optionsJSON:r.options,useBrowserAutofill:null==e?void 0:e.autofill})];case 9:return i=d.sent(),(null==e?void 0:e.onVerificationStarted)&&e.onVerificationStarted(),[4,this.api.verify({authenticationCredential:i,token:null==e?void 0:e.token,deviceId:this.anonymousId,challengeId:r.challengeId,useCookies:null==e?void 0:e.useCookies})];case 10:return"error"in(s=d.sent())?($=!1,[2,R(s)]):(s.isVerified&&this.storeCredentialAgainstDevice(l(l({},i),{userId:s.userId})),s.accessToken&&(this.cache.token=s.accessToken),a=s.accessToken,c=s.userId,h=s.userAuthenticatorId,u=s.username,p=s.userDisplayName,f=s.isVerified,$=!1,[2,{data:{isVerified:f,token:a,userId:c,userAuthenticatorId:h,username:u,displayName:p,authenticationResponse:i}}]);case 11:throw v=d.sent(),$=!1,x(v),v;case 12:return[2]}}))}))},e.prototype.isAvailableOnDevice=function(e){return u(this,arguments,void 0,(function(e){var t,n,r,o,i=e.userId;return d(this,(function(e){switch(e.label){case 0:if(!i)throw new Error("userId is required");if(!(t=localStorage.getItem(this.passkeyLocalStorageKey)))return[2,!1];if(n=JSON.parse(t),0===(r=null!==(o=n[i])&&void 0!==o?o:[]).length)return[2,!1];e.label=1;case 1:return e.trys.push([1,3,,4]),[4,this.api.getPasskeyAuthenticator({credentialIds:r})];case 2:return e.sent(),[2,!0];case 3:return e.sent(),[2,!1];case 4:return[2]}}))}))},e.prototype.storeCredentialAgainstDevice=function(e){var t=e.id,n=e.authenticatorAttachment,r=e.userId,o=void 0===r?"":r;if("cross-platform"!==n){var i=localStorage.getItem(this.passkeyLocalStorageKey),s=i?JSON.parse(i):{};s[o]?s[o].includes(t)||s[o].push(t):s[o]=[t],localStorage.setItem(this.passkeyLocalStorageKey,JSON.stringify(s))}},e.prototype.doesBrowserSupportConditionalCreate=function(){return u(this,void 0,void 0,(function(){return d(this,(function(e){switch(e.label){case 0:return window.PublicKeyCredential&&PublicKeyCredential.getClientCapabilities?[4,PublicKeyCredential.getClientCapabilities()]:[3,2];case 1:if(e.sent().conditionalCreate)return[2,!0];e.label=2;case 2:return[2,!1]}}))}))},e}(),L=function(){function e(){this.windowRef=null}return e.prototype.show=function(e){var t=e.url,n=e.width,r=void 0===n?400:n,o=e.height,i=function(e){var t=e.url,n=e.width,r=e.height,o=e.win;if(!o.top)return null;var i=o.top.outerHeight/2+o.top.screenY-r/2,s=o.top.outerWidth/2+o.top.screenX-n/2;return window.open(t,"","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=".concat(n,", height=").concat(r,", top=").concat(i,", left=").concat(s))}({url:t,width:r,height:void 0===o?500:o,win:window});if(!i)throw new Error("Window is not initialized");return this.windowRef=i,i},e.prototype.close=function(){if(!this.windowRef)throw new Error("Window is not initialized");this.windowRef.close()},e}();const j=":not([inert]):not([inert] *)",J=':not([tabindex^="-"])',K=":not(:disabled)";var W=[`a[href]${j}${J}`,`area[href]${j}${J}`,`input:not([type="hidden"]):not([type="radio"])${j}${J}${K}`,`input[type="radio"]${j}${J}${K}`,`select${j}${J}${K}`,`textarea${j}${J}${K}`,`button${j}${J}${K}`,`details${j} > summary:first-of-type${J}`,`iframe${j}${J}`,`audio[controls]${j}${J}`,`video[controls]${j}${J}`,`[contenteditable]${j}${J}`,`[tabindex]${j}${J}`];function H(e){(e.querySelector("[autofocus]")||e).focus()}function M(e,t){if(t&&G(e))return e;if(!((n=e).shadowRoot&&"-1"===n.getAttribute("tabindex")||n.matches(":disabled,[hidden],[inert]")))if(e.shadowRoot){let n=V(e.shadowRoot,t);for(;n;){const e=M(n,t);if(e)return e;n=q(n,t)}}else if("slot"===e.localName){const n=e.assignedElements({flatten:!0});t||n.reverse();for(const e of n){const n=M(e,t);if(n)return n}}else{let n=V(e,t);for(;n;){const e=M(n,t);if(e)return e;n=q(n,t)}}var n;return!t&&G(e)?e:null}function V(e,t){return t?e.firstElementChild:e.lastElementChild}function q(e,t){return t?e.nextElementSibling:e.previousElementSibling}const G=e=>!e.shadowRoot?.delegatesFocus&&(e.matches(W.join(","))&&!(e=>!(!e.matches("details:not([open]) *")||e.matches("details>summary:first-of-type"))||!(e.offsetWidth||e.offsetHeight||e.getClientRects().length))(e));function F(e=document){const t=e.activeElement;return t?t.shadowRoot?F(t.shadowRoot)||document.activeElement:t:null}function B(e,t){const[n,r]=function(e){const t=M(e,!0);return[t,t?M(e,!1)||t:null]}(e);if(!n)return t.preventDefault();const o=F();t.shiftKey&&o===n?(r.focus(),t.preventDefault()):t.shiftKey||o!==r||(n.focus(),t.preventDefault())}class z{$el;id;previouslyFocused;shown;constructor(e){this.$el=e,this.id=this.$el.getAttribute("data-a11y-dialog")||this.$el.id,this.previouslyFocused=null,this.shown=!1,this.maintainFocus=this.maintainFocus.bind(this),this.bindKeypress=this.bindKeypress.bind(this),this.handleTriggerClicks=this.handleTriggerClicks.bind(this),this.show=this.show.bind(this),this.hide=this.hide.bind(this),this.$el.setAttribute("aria-hidden","true"),this.$el.setAttribute("aria-modal","true"),this.$el.setAttribute("tabindex","-1"),this.$el.hasAttribute("role")||this.$el.setAttribute("role","dialog"),document.addEventListener("click",this.handleTriggerClicks,!0)}destroy(){return this.hide(),document.removeEventListener("click",this.handleTriggerClicks,!0),this.$el.replaceWith(this.$el.cloneNode(!0)),this.fire("destroy"),this}show(e){return this.shown||(this.shown=!0,this.$el.removeAttribute("aria-hidden"),this.previouslyFocused=F(),"BODY"===this.previouslyFocused?.tagName&&e?.target&&(this.previouslyFocused=e.target),"focus"===e?.type?this.maintainFocus(e):H(this.$el),document.body.addEventListener("focus",this.maintainFocus,!0),this.$el.addEventListener("keydown",this.bindKeypress,!0),this.fire("show",e)),this}hide(e){return this.shown?(this.shown=!1,this.$el.setAttribute("aria-hidden","true"),this.previouslyFocused?.focus?.(),document.body.removeEventListener("focus",this.maintainFocus,!0),this.$el.removeEventListener("keydown",this.bindKeypress,!0),this.fire("hide",e),this):this}on(e,t,n){return this.$el.addEventListener(e,t,n),this}off(e,t,n){return this.$el.removeEventListener(e,t,n),this}fire(e,t){this.$el.dispatchEvent(new CustomEvent(e,{detail:t,cancelable:!0}))}handleTriggerClicks(e){const t=e.target;t.closest(`[data-a11y-dialog-show="${this.id}"]`)&&this.show(e),(t.closest(`[data-a11y-dialog-hide="${this.id}"]`)||t.closest("[data-a11y-dialog-hide]")&&t.closest('[aria-modal="true"]')===this.$el)&&this.hide(e)}bindKeypress(e){if(document.activeElement?.closest('[aria-modal="true"]')!==this.$el)return;let t=!1;try{t=!!this.$el.querySelector('[popover]:not([popover="manual"]):popover-open')}catch{}"Escape"!==e.key||"alertdialog"===this.$el.getAttribute("role")||t||(e.preventDefault(),this.hide(e)),"Tab"===e.key&&B(this.$el,e)}maintainFocus(e){e.target.closest('[aria-modal="true"], [data-a11y-dialog-ignore-focus-trap]')||H(this.$el)}}function Y(){for(const e of document.querySelectorAll("[data-a11y-dialog]"))new z(e)}"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",Y):Y());var Q="__authsignal-popup-container",X="__authsignal-popup-content",Z="__authsignal-popup-overlay",ee="__authsignal-popup-style",te="__authsignal-popup-iframe",ne="385px",re=function(){function e(e){var t=e.width,n=e.isClosable;if(this.popup=null,document.querySelector("#".concat(Q)))throw new Error("Multiple instances of Authsignal popup is not supported.");this.create({width:t,isClosable:n})}return e.prototype.create=function(e){var t=this,n=e.width,r=void 0===n?ne:n,o=e.isClosable,i=void 0===o||o,s=r;CSS.supports("width",r)||(console.warn("Invalid CSS value for `popupOptions.width`. Using default value instead."),s=ne);var a=document.createElement("div");a.setAttribute("id",Q),a.setAttribute("aria-hidden","true"),i||a.setAttribute("role","alertdialog");var c=document.createElement("div");c.setAttribute("id",Z),i&&c.setAttribute("data-a11y-dialog-hide","true");var l=document.createElement("div");l.setAttribute("id",X),document.body.appendChild(a);var h=document.createElement("style");h.setAttribute("id",ee),h.textContent="\n #".concat(Q,",\n #").concat(Z," {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n }\n\n #").concat(Q," {\n z-index: 2147483647;\n display: flex;\n }\n\n #").concat(Q,"[aria-hidden='true'] {\n display: none;\n }\n\n #").concat(Z," {\n background-color: rgba(0, 0, 0, 0.18);\n }\n\n #").concat(X," {\n margin: auto;\n z-index: 2147483647;\n position: relative;\n background-color: transparent;\n border-radius: 8px;\n width: ").concat(s,";\n }\n\n #").concat(X," iframe {\n width: 1px;\n min-width: 100%;\n border-radius: inherit;\n max-height: 95vh;\n height: ").concat("384px",";\n }\n "),document.head.insertAdjacentElement("beforeend",h),a.appendChild(c),a.appendChild(l),this.popup=new z(a),a.focus(),this.popup.on("hide",(function(){t.destroy()}))},e.prototype.destroy=function(){var e=document.querySelector("#".concat(Q)),t=document.querySelector("#".concat(ee));e&&t&&(document.body.removeChild(e),document.head.removeChild(t)),window.removeEventListener("message",oe)},e.prototype.show=function(e){var t,n=e.url;if(!this.popup)throw new Error("Popup is not initialized");var r=document.createElement("iframe");r.setAttribute("id",te),r.setAttribute("name","authsignal"),r.setAttribute("title","Authsignal multi-factor authentication"),r.setAttribute("src",n),r.setAttribute("frameborder","0"),r.setAttribute("allow","publickey-credentials-get *; publickey-credentials-create *; clipboard-write");var o=document.querySelector("#".concat(X));o&&o.appendChild(r),window.addEventListener("message",oe),null===(t=this.popup)||void 0===t||t.show()},e.prototype.close=function(){if(!this.popup)throw new Error("Popup is not initialized");this.popup.hide()},e.prototype.on=function(e,t){if(!this.popup)throw new Error("Popup is not initialized");this.popup.on(e,t)},e}();function oe(e){var t=document.querySelector("#".concat(te));t&&e.data.height&&(t.style.height=e.data.height+"px")}var ie=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/totp"),{method:"POST",headers:U({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.code;return d(this,(function(e){switch(e.label){case 0:return t={verificationCode:o},[4,fetch("".concat(this.baseUrl,"/client/verify/totp"),{method:"POST",headers:U({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),se=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.cache=_.shared,this.api=new ie({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.enroll=function(){return u(this,void 0,void 0,(function(){return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,O(e.sent())]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.code;return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:n})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,O(t)]}}))}))},e}(),ae=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.email;return d(this,(function(e){switch(e.label){case 0:return t={email:o},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/email-otp"),{method:"POST",headers:U({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/email-otp"),{method:"POST",headers:U({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.code;return d(this,(function(e){switch(e.label){case 0:return t={verificationCode:o},[4,fetch("".concat(this.baseUrl,"/client/verify/email-otp"),{method:"POST",headers:U({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),ce=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.cache=_.shared,this.api=new ae({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t=e.email;return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token,email:t})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,O(e.sent())]}}))}))},e.prototype.challenge=function(){return u(this,void 0,void 0,(function(){return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,O(e.sent())]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.code;return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:n})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,O(t)]}}))}))},e}(),le=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.phoneNumber;return d(this,(function(e){switch(e.label){case 0:return t={phoneNumber:o},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/sms"),{method:"POST",headers:U({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/sms"),{method:"POST",headers:U({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.code;return d(this,(function(e){switch(e.label){case 0:return t={verificationCode:o},[4,fetch("".concat(this.baseUrl,"/client/verify/sms"),{method:"POST",headers:U({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),he=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.cache=_.shared,this.api=new le({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t=e.phoneNumber;return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token,phoneNumber:t})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,O(e.sent())]}}))}))},e.prototype.challenge=function(){return u(this,void 0,void 0,(function(){return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,O(e.sent())]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.code;return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:n})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,O(t)]}}))}))},e}(),ue=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.email;return d(this,(function(e){switch(e.label){case 0:return t={email:o},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/email-magic-link"),{method:"POST",headers:U({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/email-magic-link"),{method:"POST",headers:U({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.checkVerificationStatus=function(e){return u(this,arguments,void 0,(function(e){var t,n=this,r=e.token;return d(this,(function(e){switch(e.label){case 0:return t=function(){return u(n,void 0,void 0,(function(){var e,n=this;return d(this,(function(o){switch(o.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/verify/email-magic-link/finalize"),{method:"POST",headers:U({token:r,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,o.sent().json()];case 2:return P({response:e=o.sent(),onTokenExpired:this.onTokenExpired}),e.isVerified?[2,e]:[2,new Promise((function(e){setTimeout((function(){return u(n,void 0,void 0,(function(){var n;return d(this,(function(r){switch(r.label){case 0:return n=e,[4,t()];case 1:return n.apply(void 0,[r.sent()]),[2]}}))}))}),1e3)}))]}}))}))},[4,t()];case 1:return[2,e.sent()]}}))}))},e}(),de=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.cache=_.shared,this.api=new ue({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t=e.email;return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token,email:t})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,O(e.sent())]}}))}))},e.prototype.challenge=function(){return u(this,void 0,void 0,(function(){return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,O(e.sent())]}}))}))},e.prototype.checkVerificationStatus=function(){return u(this,void 0,void 0,(function(){var e;return d(this,(function(t){switch(t.label){case 0:return this.cache.token?[4,this.api.checkVerificationStatus({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(e=t.sent())&&e.accessToken&&(this.cache.token=e.accessToken),[2,O(e)]}}))}))},e}(),pe=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.registrationOptions=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key/registration-options"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.authenticationOptions=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key/authentication-options"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.addAuthenticator=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token,r=e.registrationCredential;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify(r)})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token,r=e.authenticationCredential;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/verify/security-key"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify(r)})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e}(),fe=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.cache=_.shared,this.api=new pe({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.enroll=function(){return u(this,void 0,void 0,(function(){var e,t,n,r,o;return d(this,(function(i){switch(i.label){case 0:return this.cache.token?(e={token:this.cache.token},[4,this.api.registrationOptions(e)]):[2,this.cache.handleTokenNotSetError()];case 1:if("error"in(t=i.sent()))return[2,R(t)];i.label=2;case 2:return i.trys.push([2,5,,6]),[4,I({optionsJSON:t})];case 3:return n=i.sent(),[4,this.api.addAuthenticator({registrationCredential:n,token:this.cache.token})];case 4:return"error"in(r=i.sent())?[2,R(r)]:(r.accessToken&&(this.cache.token=r.accessToken),[2,{data:{token:r.accessToken,registrationResponse:n}}]);case 5:throw x(o=i.sent()),o;case 6:return[2]}}))}))},e.prototype.verify=function(){return u(this,void 0,void 0,(function(){var e,t,n,r,o;return d(this,(function(i){switch(i.label){case 0:return this.cache.token?[4,this.api.authenticationOptions({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:if("error"in(e=i.sent()))return[2,R(e)];i.label=2;case 2:return i.trys.push([2,5,,6]),[4,S({optionsJSON:e})];case 3:return t=i.sent(),[4,this.api.verify({authenticationCredential:t,token:this.cache.token})];case 4:return"error"in(n=i.sent())?[2,R(n)]:(n.accessToken&&(this.cache.token=n.accessToken),r=n.accessToken,[2,{data:{isVerified:n.isVerified,token:r,authenticationResponse:t}}]);case 5:throw x(o=i.sent()),o;case 6:return[2]}}))}))},e}(),ve=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.tenantId=n,this.baseUrl=t}return e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.action,r=e.token,o=e.custom;return d(this,(function(e){switch(e.label){case 0:return t={action:n,custom:o},[4,fetch("".concat(this.baseUrl,"/client/challenge/qr-code"),{method:"POST",headers:U({tenantId:this.tenantId,token:r}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.challengeId,r=e.deviceCode;return d(this,(function(e){switch(e.label){case 0:return t={challengeId:n,deviceCode:r},[4,fetch("".concat(this.baseUrl,"/client/verify/qr-code"),{method:"POST",headers:U({tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}}))}))},e}(),ge=function(){},ye=54e4,be=3e3,me=function(e){function t(t){var n=t.baseUrl,r=t.tenantId,o=e.call(this)||this;return o.cache=_.shared,o.api=new ve({baseUrl:n,tenantId:r}),o}return c(t,e),t.prototype.challenge=function(e){return u(this,void 0,void 0,(function(){var t,n,r,o,i,s=this;return d(this,(function(a){switch(a.label){case 0:return[4,this.api.challenge({token:this.cache.token||void 0,action:e.action,custom:e.custom})];case 1:return t=a.sent(),(n=O(t)).data&&(this.currentChallengeParams=e,this.clearPolling(),r=e.pollInterval||be,o=e.refreshInterval||ye,n.data.deviceCode&&this.startPolling({challengeId:n.data.challengeId,deviceCode:n.data.deviceCode,onStateChange:e.onStateChange,pollInterval:r}),e.onRefresh&&(i=e.onRefresh,this.startRefreshTimer((function(){return s.performRefresh({action:e.action,custom:e.custom,onRefresh:i,onStateChange:e.onStateChange,pollInterval:r})}),o))),[2,n]}}))}))},t.prototype.refresh=function(){return u(this,arguments,void 0,(function(e){var t,n,r,o,i,s,a,c,l,h=this,u=(void 0===e?{}:e).custom;return d(this,(function(e){switch(e.label){case 0:return this.currentChallengeParams?[4,this.api.challenge({token:this.cache.token||void 0,action:this.currentChallengeParams.action,custom:u||this.currentChallengeParams.custom})]:[2];case 1:return t=e.sent(),(n=O(t)).data&&(this.clearPolling(),this.currentChallengeParams.onRefresh&&this.currentChallengeParams.onRefresh(n.data.challengeId,n.data.expiresAt),n.data.deviceCode&&this.startPolling({challengeId:n.data.challengeId,deviceCode:n.data.deviceCode,onStateChange:this.currentChallengeParams.onStateChange,pollInterval:this.currentChallengeParams.pollInterval||be}),this.currentChallengeParams.onRefresh&&(r=this.currentChallengeParams.refreshInterval||ye,o=this.currentChallengeParams,i=o.action,s=o.custom,a=o.onRefresh,c=o.onStateChange,l=o.pollInterval,this.startRefreshTimer((function(){return h.performRefresh({action:i,custom:s,onRefresh:a,onStateChange:c,pollInterval:l||be})}),r))),[2]}}))}))},t.prototype.disconnect=function(){this.clearPolling(),this.clearRefreshTimer(),this.currentChallengeParams=void 0},t.prototype.startRefreshTimer=function(e,t){var n=this;this.clearRefreshTimer(),this.refreshTimeout=setTimeout((function(){return u(n,void 0,void 0,(function(){return d(this,(function(n){switch(n.label){case 0:return[4,e()];case 1:return n.sent(),this.startRefreshTimer(e,t),[2]}}))}))}),t)},t.prototype.clearRefreshTimer=function(){this.refreshTimeout&&(clearTimeout(this.refreshTimeout),this.refreshTimeout=void 0)},t.prototype.performRefresh=function(e){return u(this,arguments,void 0,(function(e){var t,n,r=e.action,o=e.custom,i=e.onRefresh,s=e.onStateChange,a=e.pollInterval;return d(this,(function(e){switch(e.label){case 0:return[4,this.api.challenge({token:this.cache.token||void 0,action:r,custom:o})];case 1:return t=e.sent(),(n=O(t)).data&&(this.clearPolling(),i(n.data.challengeId,n.data.expiresAt),n.data.deviceCode&&this.startPolling({challengeId:n.data.challengeId,deviceCode:n.data.deviceCode,onStateChange:s,pollInterval:a})),[2]}}))}))},t.prototype.startPolling=function(e){var t=this,n=e.challengeId,r=e.deviceCode,o=e.onStateChange,i=e.pollInterval;this.pollingInterval=setInterval((function(){return u(t,void 0,void 0,(function(){var e,t;return d(this,(function(i){switch(i.label){case 0:return[4,this.api.verify({challengeId:n,deviceCode:r})];case 1:return e=i.sent(),(t=O(e)).data&&(t.data.isVerified?(o("approved",t.data.token),this.clearPolling()):t.data.isClaimed&&!t.data.isConsumed?o("claimed"):t.data.isClaimed&&t.data.isConsumed&&(o("rejected"),this.clearPolling())),[2]}}))}))}),i)},t.prototype.clearPolling=function(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=void 0)},t}(ge),ke="CHALLENGE_CREATED_HANDLER",we=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.ws=null,this.messageHandlers=new Map,this.options=null,this.refreshInterval=null,this.tokenCache=_.shared;var r=t.replace("https://","wss://").replace("http://","ws://").replace("v1","ws-v1-challenge").replace("api","api-ws");this.baseUrl=r,this.tenantId=n}return e.prototype.connect=function(){return u(this,void 0,void 0,(function(){var e=this;return d(this,(function(t){return[2,new Promise((function(t,n){try{var r=["authsignal-ws"];e.tokenCache.token?r.push("x.authsignal.token.".concat(e.tokenCache.token)):r.push("x.authsignal.tenant.".concat(e.tenantId)),e.ws=new WebSocket(e.baseUrl,r),e.ws.onopen=function(){t()},e.ws.onerror=function(e){n(new Error("WebSocket connection error: ".concat(e)))},e.ws.onclose=function(){e.refreshInterval&&(clearInterval(e.refreshInterval),e.refreshInterval=null),e.messageHandlers.clear(),e.ws=null},e.ws.onmessage=function(t){try{var n=JSON.parse(t.data);e.handleMessage(n)}catch(e){console.error("Failed to parse WebSocket message:",e)}}}catch(e){n(e)}}))]}))}))},e.prototype.handleMessage=function(e){if("CHALLENGE_CREATED"===e.type){if(!(t=this.messageHandlers.get(ke)))throw new Error("Challenge created handler not found");t(e)}else if("STATE_CHANGE"===e.type){var t;(t=this.messageHandlers.get(e.data.challengeId))&&t(e)}},e.prototype.createQrCodeChallenge=function(e){return u(this,void 0,void 0,(function(){var t=this;return d(this,(function(n){switch(n.label){case 0:return this.ws&&this.ws.readyState===WebSocket.OPEN?[3,2]:[4,this.connect()];case 1:n.sent(),n.label=2;case 2:return this.refreshInterval&&clearInterval(this.refreshInterval),this.options=e,[2,new Promise((function(n,r){t.messageHandlers.set(ke,(function(r){if("CHALLENGE_CREATED"===r.type){var o=r;t.messageHandlers.delete(ke),t.monitorChallengeState(o.data.challengeId,e),t.startRefreshCycle(o.data.challengeId,e),n({challengeId:o.data.challengeId,expiresAt:o.data.expiresAt,state:o.data.state})}})),t.sendChallengeRequest(e).catch(r)}))]}}))}))},e.prototype.monitorChallengeState=function(e,t){var n=this;this.messageHandlers.set(e,(function(r){var o;if("STATE_CHANGE"===r.type){var i=r;null===(o=t.onStateChange)||void 0===o||o.call(t,i.data.state,i.data.accessToken),"approved"!==i.data.state&&"rejected"!==i.data.state||n.messageHandlers.delete(e)}}))},e.prototype.startRefreshCycle=function(e,t){var n=this,r=t.refreshInterval||54e4,o=e;this.refreshInterval=setInterval((function(){return u(n,void 0,void 0,(function(){var e,n,r;return d(this,(function(i){switch(i.label){case 0:this.messageHandlers.delete(o),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,this.createQrCodeChallenge(t)];case 2:return e=i.sent(),o=e.challengeId,null===(r=t.onRefresh)||void 0===r||r.call(t,e.challengeId,e.expiresAt),[3,4];case 3:return n=i.sent(),console.error("Failed to refresh QR code challenge:",n),this.refreshInterval&&(clearInterval(this.refreshInterval),this.refreshInterval=null),[3,4];case 4:return[2]}}))}))}),r)},e.prototype.sendChallengeRequest=function(e){return u(this,void 0,void 0,(function(){return d(this,(function(t){switch(t.label){case 0:return this.ws&&this.ws.readyState===WebSocket.OPEN?[3,2]:[4,this.connect()];case 1:t.sent(),t.label=2;case 2:if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket connection could not be established");return this.sendMessage({type:"CREATE_CHALLENGE",data:{challengeType:"QR_CODE",actionCode:e.action,custom:e.custom}}),[2]}}))}))},e.prototype.sendMessage=function(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");this.ws.send(JSON.stringify(e))},e.prototype.refreshQrCodeChallenge=function(e){return u(this,arguments,void 0,(function(e){var t,n,r,o=e.custom;return d(this,(function(e){switch(e.label){case 0:if(!this.options)throw new Error("Call createQrCodeChallenge first");return[4,this.createQrCodeChallenge(l(l({},this.options),void 0!==o&&{custom:o}))];case 1:return t=e.sent(),null===(r=(n=this.options).onRefresh)||void 0===r||r.call(n,t.challengeId,t.expiresAt),[2,t]}}))}))},e.prototype.disconnect=function(){this.ws&&this.ws.close()},e}(),Ee=function(e){function t(t){var n=t.baseUrl,r=t.tenantId,o=e.call(this)||this;return o.cache=_.shared,o.wsClient=new we({baseUrl:n,tenantId:r}),o}return c(t,e),t.prototype.challenge=function(e){return u(this,void 0,void 0,(function(){var t;return d(this,(function(n){switch(n.label){case 0:return[4,this.wsClient.createQrCodeChallenge({token:this.cache.token||void 0,action:e.action,custom:e.custom,refreshInterval:e.refreshInterval,onRefresh:e.onRefresh,onStateChange:e.onStateChange})];case 1:return[2,{data:{challengeId:(t=n.sent()).challengeId,expiresAt:t.expiresAt}}]}}))}))},t.prototype.refresh=function(){return u(this,arguments,void 0,(function(e){var t=(void 0===e?{}:e).custom;return d(this,(function(e){switch(e.label){case 0:return[4,this.wsClient.refreshQrCodeChallenge({custom:t})];case 1:return e.sent(),[2]}}))}))},t.prototype.disconnect=function(){this.wsClient.disconnect()},t}(ge),Ie=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.handler=null,this.baseUrl=t,this.tenantId=n}return e.prototype.challenge=function(e){return u(this,void 0,void 0,(function(){var t,n,r;return d(this,(function(o){return t=e.polling,n=void 0!==t&&t,r=h(e,["polling"]),this.handler&&this.handler.disconnect(),this.handler=n?new me({baseUrl:this.baseUrl,tenantId:this.tenantId}):new Ee({baseUrl:this.baseUrl,tenantId:this.tenantId}),[2,this.handler.challenge(r)]}))}))},e.prototype.refresh=function(){return u(this,arguments,void 0,(function(e){var t=(void 0===e?{}:e).custom;return d(this,(function(e){if(!this.handler)throw new Error("challenge() must be called before refresh()");return[2,this.handler.refresh({custom:t})]}))}))},e.prototype.disconnect=function(){this.handler&&(this.handler.disconnect(),this.handler=null)},e}(),Te=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n,r=e.action,o=e.token;return d(this,(function(e){switch(e.label){case 0:return t={action:r},[4,fetch("".concat(this.baseUrl,"/client/challenge/push"),{method:"POST",headers:U({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,r=e.challengeId,o=e.token;return d(this,(function(e){switch(e.label){case 0:return t={challengeId:r},[4,fetch("".concat(this.baseUrl,"/client/verify/push"),{method:"POST",headers:U({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),Ce=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.cache=_.shared,this.api=new Te({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t=e.action;return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({action:t,token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,O(e.sent())]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t=e.challengeId;return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({challengeId:t,token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,O(e.sent())]}}))}))},e}(),Se=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/whatsapp"),{method:"POST",headers:U({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.code;return d(this,(function(e){switch(e.label){case 0:return t={verificationCode:o},[4,fetch("".concat(this.baseUrl,"/client/verify/whatsapp"),{method:"POST",headers:U({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),Ae=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.cache=_.shared,this.api=new Se({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.challenge=function(){return u(this,void 0,void 0,(function(){return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,O(e.sent())]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.code;return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:n})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,O(t)]}}))}))},e}(),Re="4a08uqve",Oe=function(){function t(e){var t=e.cookieDomain,n=e.cookieName,r=void 0===n?"__as_aid":n,o=e.baseUrl,i=void 0===o?"https://api.authsignal.com/v1":o,a=e.tenantId,c=e.onTokenExpired;if(this.anonymousId="",this.profilingId="",this.cookieDomain="",this.anonymousIdCookieName="",this.cookieDomain=t||document.location.hostname.replace("www.",""),this.anonymousIdCookieName=r,!a)throw new Error("tenantId is required");var l,h=(l=this.anonymousIdCookieName)&&decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(l).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null;h?this.anonymousId=h:(this.anonymousId=s(),A({name:this.anonymousIdCookieName,value:this.anonymousId,expire:1/0,domain:this.cookieDomain,secure:"http:"!==document.location.protocol})),this.passkey=new D({tenantId:a,baseUrl:i,anonymousId:this.anonymousId,onTokenExpired:c}),this.totp=new se({tenantId:a,baseUrl:i,onTokenExpired:c}),this.email=new ce({tenantId:a,baseUrl:i,onTokenExpired:c}),this.emailML=new de({tenantId:a,baseUrl:i,onTokenExpired:c}),this.sms=new he({tenantId:a,baseUrl:i,onTokenExpired:c}),this.securityKey=new fe({tenantId:a,baseUrl:i,onTokenExpired:c}),this.qrCode=new Ie({tenantId:a,baseUrl:i}),this.push=new Ce({tenantId:a,baseUrl:i,onTokenExpired:c}),this.whatsapp=new Ae({tenantId:a,baseUrl:i,onTokenExpired:c})}return t.prototype.setToken=function(e){_.shared.token=e},t.prototype.launch=function(e,t){switch(null==t?void 0:t.mode){case"window":return this.launchWithWindow(e,t);case"popup":return this.launchWithPopup(e,t);default:this.launchWithRedirect(e)}},t.prototype.initAdvancedProfiling=function(e){var t=s();this.profilingId=t,A({name:"__as_pid",value:t,expire:1/0,domain:this.cookieDomain,secure:"http:"!==document.location.protocol});var n=e?"".concat(e,"/fp/tags.js?org_id=").concat(Re,"&session_id=").concat(t):"https://h.online-metrix.net/fp/tags.js?org_id=".concat(Re,"&session_id=").concat(t),r=document.createElement("script");r.src=n,r.async=!1,r.id="as_adv_profile",document.head.appendChild(r);var o=document.createElement("noscript");o.setAttribute("id","as_adv_profile_pixel"),o.setAttribute("aria-hidden","true");var i=document.createElement("iframe"),a=e?"".concat(e,"/fp/tags?org_id=").concat(Re,"&session_id=").concat(t):"https://h.online-metrix.net/fp/tags?org_id=".concat(Re,"&session_id=").concat(t);i.setAttribute("id","as_adv_profile_pixel"),i.setAttribute("src",a),i.setAttribute("style","width: 100px; height: 100px; border: 0; position: absolute; top: -5000px;"),o&&(o.appendChild(i),document.body.prepend(o))},t.prototype.launchWithRedirect=function(e){window.location.href=e},t.prototype.launchWithPopup=function(t,n){var r=n.popupOptions,o=new re({width:null==r?void 0:r.width,isClosable:null==r?void 0:r.isClosable}),i="".concat(t,"&mode=popup");return o.show({url:i}),new Promise((function(t){var n=void 0;o.on("hide",(function(){t({token:n})})),window.addEventListener("message",(function(t){var r=null;try{r=JSON.parse(t.data)}catch(e){}(null==r?void 0:r.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(n=r.token,o.close())}),!1)}))},t.prototype.launchWithWindow=function(t,n){var r=n.windowOptions,o=new L,i="".concat(t,"&mode=popup");return o.show({url:i,width:null==r?void 0:r.width,height:null==r?void 0:r.height}),new Promise((function(t){window.addEventListener("message",(function(n){var r=null;try{r=JSON.parse(n.data)}catch(e){}(null==r?void 0:r.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(o.close(),t({token:r.token}))}),!1)}))},t}();return e.Authsignal=Oe,e.WebAuthnError=m,e.Whatsapp=Ae,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
|
|
1
|
+
var authsignal=function(e){"use strict";let t;const s=new Uint8Array(16);function r(){if(!t&&(t="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!t))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return t(s)}const n=[];for(let e=0;e<256;++e)n.push((e+256).toString(16).slice(1));var a={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function i(e,t,s){if(a.randomUUID&&!t&&!e)return a.randomUUID();const i=(e=e||{}).random||(e.rng||r)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){s=s||0;for(let e=0;e<16;++e)t[s+e]=i[e];return t}return function(e,t=0){return(n[e[t+0]]+n[e[t+1]]+n[e[t+2]]+n[e[t+3]]+"-"+n[e[t+4]]+n[e[t+5]]+"-"+n[e[t+6]]+n[e[t+7]]+"-"+n[e[t+8]]+n[e[t+9]]+"-"+n[e[t+10]]+n[e[t+11]]+n[e[t+12]]+n[e[t+13]]+n[e[t+14]]+n[e[t+15]]).toLowerCase()}(i)}var o=function(e,t){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s])},o(e,t)};function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function s(){this.constructor=e}o(e,t),e.prototype=null===t?Object.create(t):(s.prototype=t.prototype,new s)}var c=function(){return c=Object.assign||function(e){for(var t,s=1,r=arguments.length;s<r;s++)for(var n in t=arguments[s])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},c.apply(this,arguments)};function u(e,t){var s={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(s[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(e);n<r.length;n++)t.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(s[r[n]]=e[r[n]])}return s}function h(e,t,s,r){return new(s||(s=Promise))((function(n,a){function i(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(i,o)}l((r=r.apply(e,t||[])).next())}))}function m(e,t){var s,r,n,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=o(0),i.throw=o(1),i.return=o(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function o(o){return function(l){return function(o){if(s)throw new TypeError("Generator is already executing.");for(;i&&(i=0,o[0]&&(a=0)),a;)try{if(s=1,r&&(n=2&o[0]?r.return:o[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,o[1])).done)return n;switch(r=0,n&&(o=[2&o[0],n.value]),o[0]){case 0:case 1:n=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(n=a.trys,(n=n.length>0&&n[n.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!n||o[1]>n[0]&&o[1]<n[3])){a.label=o[1];break}if(6===o[0]&&a.label<n[1]){a.label=n[1],n=o;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(o);break}n[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{s=n=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}function f(e){const t=new Uint8Array(e);let s="";for(const e of t)s+=String.fromCharCode(e);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function d(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),s=(4-t.length%4)%4,r=t.padEnd(t.length+s,"="),n=atob(r),a=new ArrayBuffer(n.length),i=new Uint8Array(a);for(let e=0;e<n.length;e++)i[e]=n.charCodeAt(e);return a}function g(){return p.stubThis(void 0!==globalThis?.PublicKeyCredential&&"function"==typeof globalThis.PublicKeyCredential)}"function"==typeof SuppressedError&&SuppressedError;const p={stubThis:e=>e};function w(e){const{id:t}=e;return{...e,id:d(t),transports:e.transports}}function y(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}class v extends Error{constructor({message:e,code:t,cause:s,name:r}){super(e,{cause:s}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=r??s.name,this.code=t}}const b=new class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},S=["cross-platform","platform"];function k(e){if(e&&!(S.indexOf(e)<0))return e}async function A(e){!e.optionsJSON&&e.challenge&&(console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});const{optionsJSON:t,useAutoRegister:s=!1}=e;if(!g())throw new Error("WebAuthn is not supported in this browser");const r={...t,challenge:d(t.challenge),user:{...t.user,id:d(t.user.id)},excludeCredentials:t.excludeCredentials?.map(w)},n={};let a;s&&(n.mediation="conditional"),n.publicKey=r,n.signal=b.createNewAbortSignal();try{a=await navigator.credentials.create(n)}catch(e){throw function({error:e,options:t}){const{publicKey:s}=t;if(!s)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new v({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===s.authenticatorSelection?.requireResidentKey)return new v({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===s.authenticatorSelection?.userVerification)return new v({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===s.authenticatorSelection?.userVerification)return new v({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new v({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new v({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name)return 0===s.pubKeyCredParams.filter((e=>"public-key"===e.type)).length?new v({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new v({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if("SecurityError"===e.name){const t=globalThis.location.hostname;if(!y(t))return new v({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(s.rp.id!==t)return new v({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new v({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new v({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}({error:e,options:n})}if(!a)throw new Error("Registration was not completed");const{id:i,rawId:o,response:l,type:c}=a;let u,h,m,p;if("function"==typeof l.getTransports&&(u=l.getTransports()),"function"==typeof l.getPublicKeyAlgorithm)try{h=l.getPublicKeyAlgorithm()}catch(e){N("getPublicKeyAlgorithm()",e)}if("function"==typeof l.getPublicKey)try{const e=l.getPublicKey();null!==e&&(m=f(e))}catch(e){N("getPublicKey()",e)}if("function"==typeof l.getAuthenticatorData)try{p=f(l.getAuthenticatorData())}catch(e){N("getAuthenticatorData()",e)}return{id:i,rawId:f(o),response:{attestationObject:f(l.attestationObject),clientDataJSON:f(l.clientDataJSON),transports:u,publicKeyAlgorithm:h,publicKey:m,authenticatorData:p},type:c,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:k(a.authenticatorAttachment)}}function N(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.\n`,t)}const E={stubThis:e=>e};async function C(e){!e.optionsJSON&&e.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});const{optionsJSON:t,useBrowserAutofill:s=!1,verifyBrowserAutofillInput:r=!0}=e;if(!g())throw new Error("WebAuthn is not supported in this browser");let n;0!==t.allowCredentials?.length&&(n=t.allowCredentials?.map(w));const a={...t,challenge:d(t.challenge),allowCredentials:n},i={};if(s){if(!await function(){if(!g())return E.stubThis(new Promise((e=>e(!1))));const e=globalThis.PublicKeyCredential;return void 0===e?.isConditionalMediationAvailable?E.stubThis(new Promise((e=>e(!1)))):E.stubThis(e.isConditionalMediationAvailable())}())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&r)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');i.mediation="conditional",a.allowCredentials=[]}let o;i.publicKey=a,i.signal=b.createNewAbortSignal();try{o=await navigator.credentials.get(i)}catch(e){throw function({error:e,options:t}){const{publicKey:s}=t;if(!s)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new v({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new v({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=globalThis.location.hostname;if(!y(t))return new v({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(s.rpId!==t)return new v({message:`The RP ID "${s.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new v({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}({error:e,options:i})}if(!o)throw new Error("Authentication was not completed");const{id:l,rawId:c,response:u,type:h}=o;let m;return u.userHandle&&(m=f(u.userHandle)),{id:l,rawId:f(c),response:{authenticatorData:f(u.authenticatorData),clientDataJSON:f(u.clientDataJSON),signature:f(u.signature),userHandle:m},type:h,clientExtensionResults:o.getClientExtensionResults(),authenticatorAttachment:k(o.authenticatorAttachment)}}function I(e){var t=e.name,s=e.value,r=e.expire,n=e.domain,a=e.secure,i=r===1/0?" expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+r;document.cookie=encodeURIComponent(t)+"="+s+"; path=/;"+i+(n?"; domain="+n:"")+(a?"; secure":"")}function B(e){var t,s=e.errorResponse;return e.enableLogging&&console.error("[Authsignal] ".concat(s.errorCode).concat(s.errorDescription?": ".concat(s.errorDescription):"")),{error:null!==(t=s.errorDescription)&&void 0!==t?t:s.error,errorCode:s.errorCode,errorDescription:s.errorDescription}}function V(e){var t,s=e.response,r=e.enableLogging;if(s&&"object"==typeof s&&"error"in s){var n=null!==(t=s.errorDescription)&&void 0!==t?t:s.error;return r&&console.error("[Authsignal] ".concat(s.errorCode).concat(s.errorDescription?": ".concat(s.errorDescription):"")),{error:n,errorCode:s.errorCode,errorDescription:s.errorDescription}}if(s&&"object"==typeof s&&"accessToken"in s&&"string"==typeof s.accessToken){var a=s.accessToken,i=u(s,["accessToken"]);return{data:c(c({},i),{token:a})}}return{data:s}}function x(e){var t,s;if(e instanceof v&&"ERROR_INVALID_RP_ID"===e.code){var r=(null===(s=null===(t=e.message)||void 0===t?void 0:t.match(/"([^"]*)"/))||void 0===s?void 0:s[1])||"";console.error('[Authsignal] The Relying Party ID "'.concat(r,'" is invalid for this domain.\n To learn more, visit https://docs.authsignal.com/scenarios/passkeys-prebuilt-ui#defining-the-relying-party'))}}var D;function O(e){var t=e.token,s=e.tenantId;return{"Content-Type":"application/json",Authorization:t?"Bearer ".concat(t):"Basic ".concat(window.btoa(encodeURIComponent(s)))}}function T(e){var t=e.response,s=e.onTokenExpired;"error"in t&&"expired_token"===t.errorCode&&s&&s()}e.AuthsignalWindowMessage=void 0,(e.AuthsignalWindowMessage||(e.AuthsignalWindowMessage={})).AUTHSIGNAL_CLOSE_POPUP="AUTHSIGNAL_CLOSE_POPUP",e.ErrorCode=void 0,(D=e.ErrorCode||(e.ErrorCode={})).token_not_set="token_not_set",D.expired_token="expired_token",D.network_error="network_error",D.too_many_requests="too_many_requests",D.invalid_credential="invalid_credential";var P=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired;this.tenantId=s,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.registrationOptions=function(e){return h(this,arguments,void 0,(function(e){var t,s,r,n,a=e.token,i=e.username,o=e.authenticatorAttachment,l=e.useCookies;return m(this,(function(e){switch(e.label){case 0:return t=Boolean(o)?{username:i,authenticatorAttachment:o}:{username:i},s="".concat(this.baseUrl,l?"/client/user-authenticators/passkey/registration-options/web":"/client/user-authenticators/passkey/registration-options"),r=l?"include":"same-origin",[4,fetch(s,{method:"POST",headers:O({token:a,tenantId:this.tenantId}),body:JSON.stringify(t),credentials:r})];case 1:return[4,e.sent().json()];case 2:return T({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.authenticationOptions=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.token,r=e.challengeId,n=e.useCookies;return m(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey/authentication-options"),{method:"POST",headers:O({token:s,tenantId:this.tenantId}),body:JSON.stringify({challengeId:r}),credentials:n?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return T({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.authenticationOptionsWeb=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.token;return m(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey/authentication-options/web"),{method:"POST",headers:O({token:s,tenantId:this.tenantId}),body:JSON.stringify({}),credentials:"include"})];case 1:return[4,e.sent().json()];case 2:return T({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.addAuthenticator=function(e){return h(this,arguments,void 0,(function(e){var t,s,r=e.token,n=e.registrationCredential,a=e.conditionalCreate,i=e.challengeId,o=e.useCookies;return m(this,(function(e){switch(e.label){case 0:return t={registrationCredential:n,conditionalCreate:a,challengeId:i},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey"),{method:"POST",headers:O({token:r,tenantId:this.tenantId}),body:JSON.stringify(t),credentials:o?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return T({response:s=e.sent(),onTokenExpired:this.onTokenExpired}),[2,s]}}))}))},e.prototype.verify=function(e){return h(this,arguments,void 0,(function(e){var t,s,r=e.authenticationCredential,n=e.token,a=e.deviceId,i=e.challengeId,o=e.useCookies;return m(this,(function(e){switch(e.label){case 0:return t={authenticationCredential:r,deviceId:a,challengeId:i},[4,fetch("".concat(this.baseUrl,"/client/verify/passkey"),{method:"POST",headers:O({token:n,tenantId:this.tenantId}),body:JSON.stringify(t),credentials:o?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return T({response:s=e.sent(),onTokenExpired:this.onTokenExpired}),[2,s]}}))}))},e.prototype.getPasskeyAuthenticator=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.credentialIds;return m(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey?credentialIds=").concat(s),{method:"GET",headers:O({tenantId:this.tenantId})})];case 1:if(!(t=e.sent()).ok)throw new Error(t.statusText);return[2,t.json()]}}))}))},e.prototype.challenge=function(e){return h(this,arguments,void 0,(function(e){var t,s,r=e.action,n=e.useCookies;return m(this,(function(e){switch(e.label){case 0:return t="".concat(this.baseUrl,n?"/client/challenge/web":"/client/challenge"),[4,fetch(t,{method:"POST",headers:O({tenantId:this.tenantId}),body:JSON.stringify({action:r}),credentials:n?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return T({response:s=e.sent(),onTokenExpired:this.onTokenExpired}),[2,s]}}))}))},e}(),U=function(){function t(){this.token=null}return t.prototype.handleTokenNotSetError=function(){var t=e.ErrorCode.token_not_set,s="A token has not been set. Call 'setToken' first.";return console.error("Error: ".concat(s)),{error:t,errorCode:t,errorDescription:s}},t.shared=new t,t}(),L=!1,R=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.anonymousId,n=e.onTokenExpired,a=e.enableLogging;this.passkeyLocalStorageKey="as_user_passkey_map",this.cache=U.shared,this.enableLogging=!1,this.api=new P({baseUrl:t,tenantId:s,onTokenExpired:n}),this.anonymousId=r,this.enableLogging=a}return e.prototype.signUp=function(e){return h(this,arguments,void 0,(function(e){var t,s,r,n,a,i,o=e.username,l=e.displayName,u=e.token,h=e.authenticatorAttachment,f=void 0===h?"platform":h,d=e.useAutoRegister,g=void 0!==d&&d,p=e.useCookies,w=void 0!==p&&p;return m(this,(function(e){switch(e.label){case 0:return(t=null!=u?u:this.cache.token)?g?[4,this.doesBrowserSupportConditionalCreate()]:[3,2]:[2,this.cache.handleTokenNotSetError()];case 1:if(!e.sent())throw new Error("CONDITIONAL_CREATE_NOT_SUPPORTED");e.label=2;case 2:return s={username:o,displayName:l,token:t,authenticatorAttachment:f,useCookies:w},[4,this.api.registrationOptions(s)];case 3:if("error"in(r=e.sent()))return[2,B({errorResponse:r,enableLogging:this.enableLogging})];e.label=4;case 4:return e.trys.push([4,7,,8]),[4,A({optionsJSON:r.options,useAutoRegister:g})];case 5:return n=e.sent(),[4,this.api.addAuthenticator({registrationCredential:n,token:t,conditionalCreate:g,challengeId:r.challengeId,useCookies:w})];case 6:return"error"in(a=e.sent())?[2,B({errorResponse:a,enableLogging:this.enableLogging})]:(a.isVerified&&this.storeCredentialAgainstDevice(c(c({},n),{userId:a.userId})),a.accessToken&&(this.cache.token=a.accessToken),[2,{data:{token:a.accessToken,userAuthenticator:a.userAuthenticator,registrationResponse:n}}]);case 7:throw i=e.sent(),L=!1,x(i),i;case 8:return[2]}}))}))},e.prototype.signIn=function(e){return h(this,void 0,void 0,(function(){var t,s,r,n,a,i,o,l,u,h,f,d,g;return m(this,(function(m){switch(m.label){case 0:if((null==e?void 0:e.token)&&e.autofill)throw new Error("autofill is not supported when providing a token");if((null==e?void 0:e.action)&&e.token)throw new Error("action is not supported when providing a token");if(null==e?void 0:e.autofill){if(L)return[2,{}];L=!0}return(null==e?void 0:e.action)?[4,this.api.challenge({action:null==e?void 0:e.action,useCookies:null==e?void 0:e.useCookies})]:[3,2];case 1:return s=m.sent(),[3,3];case 2:s=null,m.label=3;case 3:return(t=s)&&"error"in t?(L=!1,[2,B({errorResponse:t,enableLogging:this.enableLogging})]):!(null==e?void 0:e.action)&&(null==e?void 0:e.useCookies)?[3,5]:[4,this.api.authenticationOptions({token:null==e?void 0:e.token,challengeId:null==t?void 0:t.challengeId,useCookies:null==e?void 0:e.useCookies})];case 4:return n=m.sent(),[3,7];case 5:return[4,this.api.authenticationOptionsWeb({token:null==e?void 0:e.token})];case 6:n=m.sent(),m.label=7;case 7:if("error"in(r=n))return L=!1,[2,B({errorResponse:r,enableLogging:this.enableLogging})];m.label=8;case 8:return m.trys.push([8,11,,12]),[4,C({optionsJSON:r.options,useBrowserAutofill:null==e?void 0:e.autofill})];case 9:return a=m.sent(),(null==e?void 0:e.onVerificationStarted)&&e.onVerificationStarted(),[4,this.api.verify({authenticationCredential:a,token:null==e?void 0:e.token,deviceId:this.anonymousId,challengeId:r.challengeId,useCookies:null==e?void 0:e.useCookies})];case 10:return"error"in(i=m.sent())?(L=!1,[2,B({errorResponse:i,enableLogging:this.enableLogging})]):(i.isVerified&&this.storeCredentialAgainstDevice(c(c({},a),{userId:i.userId})),i.accessToken&&(this.cache.token=i.accessToken),o=i.accessToken,l=i.userId,u=i.userAuthenticatorId,h=i.username,f=i.userDisplayName,d=i.isVerified,L=!1,[2,{data:{isVerified:d,token:o,userId:l,userAuthenticatorId:u,username:h,displayName:f,authenticationResponse:a}}]);case 11:throw g=m.sent(),L=!1,x(g),g;case 12:return[2]}}))}))},e.prototype.isAvailableOnDevice=function(e){return h(this,arguments,void 0,(function(e){var t,s,r,n,a=e.userId;return m(this,(function(e){switch(e.label){case 0:if(!a)throw new Error("userId is required");if(!(t=localStorage.getItem(this.passkeyLocalStorageKey)))return[2,!1];if(s=JSON.parse(t),0===(r=null!==(n=s[a])&&void 0!==n?n:[]).length)return[2,!1];e.label=1;case 1:return e.trys.push([1,3,,4]),[4,this.api.getPasskeyAuthenticator({credentialIds:r})];case 2:return e.sent(),[2,!0];case 3:return e.sent(),[2,!1];case 4:return[2]}}))}))},e.prototype.storeCredentialAgainstDevice=function(e){var t=e.id,s=e.authenticatorAttachment,r=e.userId,n=void 0===r?"":r;if("cross-platform"!==s){var a=localStorage.getItem(this.passkeyLocalStorageKey),i=a?JSON.parse(a):{};i[n]?i[n].includes(t)||i[n].push(t):i[n]=[t],localStorage.setItem(this.passkeyLocalStorageKey,JSON.stringify(i))}},e.prototype.doesBrowserSupportConditionalCreate=function(){return h(this,void 0,void 0,(function(){return m(this,(function(e){switch(e.label){case 0:return window.PublicKeyCredential&&PublicKeyCredential.getClientCapabilities?[4,PublicKeyCredential.getClientCapabilities()]:[3,2];case 1:if(e.sent().conditionalCreate)return[2,!0];e.label=2;case 2:return[2,!1]}}))}))},e}(),_=function(){function e(){this.windowRef=null}return e.prototype.show=function(e){var t=e.url,s=e.width,r=void 0===s?400:s,n=e.height,a=function(e){var t=e.url,s=e.width,r=e.height,n=e.win;if(!n.top)return null;var a=n.top.outerHeight/2+n.top.screenY-r/2,i=n.top.outerWidth/2+n.top.screenX-s/2;return window.open(t,"","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=".concat(s,", height=").concat(r,", top=").concat(a,", left=").concat(i))}({url:t,width:r,height:void 0===n?500:n,win:window});if(!a)throw new Error("Window is not initialized");return this.windowRef=a,a},e.prototype.close=function(){if(!this.windowRef)throw new Error("Window is not initialized");this.windowRef.close()},e}();const H=":not([inert]):not([inert] *)",K=':not([tabindex^="-"])',M=":not(:disabled)";var j=[`a[href]${H}${K}`,`area[href]${H}${K}`,`input:not([type="hidden"]):not([type="radio"])${H}${K}${M}`,`input[type="radio"]${H}${K}${M}`,`select${H}${K}${M}`,`textarea${H}${K}${M}`,`button${H}${K}${M}`,`details${H} > summary:first-of-type${K}`,`iframe${H}${K}`,`audio[controls]${H}${K}`,`video[controls]${H}${K}`,`[contenteditable]${H}${K}`,`[tabindex]${H}${K}`];function J(e){(e.querySelector("[autofocus]")||e).focus()}function $(e,t){if(t&&W(e))return e;if(!((s=e).shadowRoot&&"-1"===s.getAttribute("tabindex")||s.matches(":disabled,[hidden],[inert]")))if(e.shadowRoot){let s=F(e.shadowRoot,t);for(;s;){const e=$(s,t);if(e)return e;s=q(s,t)}}else if("slot"===e.localName){const s=e.assignedElements({flatten:!0});t||s.reverse();for(const e of s){const s=$(e,t);if(s)return s}}else{let s=F(e,t);for(;s;){const e=$(s,t);if(e)return e;s=q(s,t)}}var s;return!t&&W(e)?e:null}function F(e,t){return t?e.firstElementChild:e.lastElementChild}function q(e,t){return t?e.nextElementSibling:e.previousElementSibling}const W=e=>!e.shadowRoot?.delegatesFocus&&(e.matches(j.join(","))&&!(e=>!(!e.matches("details:not([open]) *")||e.matches("details>summary:first-of-type"))||!(e.offsetWidth||e.offsetHeight||e.getClientRects().length))(e));function G(e=document){const t=e.activeElement;return t?t.shadowRoot?G(t.shadowRoot)||document.activeElement:t:null}function z(e,t){const[s,r]=function(e){const t=$(e,!0);return[t,t?$(e,!1)||t:null]}(e);if(!s)return t.preventDefault();const n=G();t.shiftKey&&n===s?(r.focus(),t.preventDefault()):t.shiftKey||n!==r||(s.focus(),t.preventDefault())}class Y{$el;id;previouslyFocused;shown;constructor(e){this.$el=e,this.id=this.$el.getAttribute("data-a11y-dialog")||this.$el.id,this.previouslyFocused=null,this.shown=!1,this.maintainFocus=this.maintainFocus.bind(this),this.bindKeypress=this.bindKeypress.bind(this),this.handleTriggerClicks=this.handleTriggerClicks.bind(this),this.show=this.show.bind(this),this.hide=this.hide.bind(this),this.$el.setAttribute("aria-hidden","true"),this.$el.setAttribute("aria-modal","true"),this.$el.setAttribute("tabindex","-1"),this.$el.hasAttribute("role")||this.$el.setAttribute("role","dialog"),document.addEventListener("click",this.handleTriggerClicks,!0)}destroy(){return this.hide(),document.removeEventListener("click",this.handleTriggerClicks,!0),this.$el.replaceWith(this.$el.cloneNode(!0)),this.fire("destroy"),this}show(e){return this.shown||(this.shown=!0,this.$el.removeAttribute("aria-hidden"),this.previouslyFocused=G(),"BODY"===this.previouslyFocused?.tagName&&e?.target&&(this.previouslyFocused=e.target),"focus"===e?.type?this.maintainFocus(e):J(this.$el),document.body.addEventListener("focus",this.maintainFocus,!0),this.$el.addEventListener("keydown",this.bindKeypress,!0),this.fire("show",e)),this}hide(e){return this.shown?(this.shown=!1,this.$el.setAttribute("aria-hidden","true"),this.previouslyFocused?.focus?.(),document.body.removeEventListener("focus",this.maintainFocus,!0),this.$el.removeEventListener("keydown",this.bindKeypress,!0),this.fire("hide",e),this):this}on(e,t,s){return this.$el.addEventListener(e,t,s),this}off(e,t,s){return this.$el.removeEventListener(e,t,s),this}fire(e,t){this.$el.dispatchEvent(new CustomEvent(e,{detail:t,cancelable:!0}))}handleTriggerClicks(e){const t=e.target;t.closest(`[data-a11y-dialog-show="${this.id}"]`)&&this.show(e),(t.closest(`[data-a11y-dialog-hide="${this.id}"]`)||t.closest("[data-a11y-dialog-hide]")&&t.closest('[aria-modal="true"]')===this.$el)&&this.hide(e)}bindKeypress(e){if(document.activeElement?.closest('[aria-modal="true"]')!==this.$el)return;let t=!1;try{t=!!this.$el.querySelector('[popover]:not([popover="manual"]):popover-open')}catch{}"Escape"!==e.key||"alertdialog"===this.$el.getAttribute("role")||t||(e.preventDefault(),this.hide(e)),"Tab"===e.key&&z(this.$el,e)}maintainFocus(e){e.target.closest('[aria-modal="true"], [data-a11y-dialog-ignore-focus-trap]')||J(this.$el)}}function Q(){for(const e of document.querySelectorAll("[data-a11y-dialog]"))new Y(e)}"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",Q):Q());var Z="__authsignal-popup-container",X="__authsignal-popup-content",ee="__authsignal-popup-overlay",te="__authsignal-popup-style",se="__authsignal-popup-iframe",re="385px",ne=function(){function e(e){var t=e.width,s=e.height,r=e.isClosable;if(this.popup=null,document.querySelector("#".concat(Z)))throw new Error("Multiple instances of Authsignal popup is not supported.");this.height=s,this.create({width:t,height:s,isClosable:r})}return e.prototype.create=function(e){var t=this,s=e.width,r=void 0===s?re:s,n=e.height,a=e.isClosable,i=void 0===a||a,o=r;CSS.supports("width",r)||(console.warn("Invalid CSS value for `popupOptions.width`. Using default value instead."),o=re);var l=document.createElement("div");l.setAttribute("id",Z),l.setAttribute("aria-hidden","true"),i||l.setAttribute("role","alertdialog");var c=document.createElement("div");c.setAttribute("id",ee),i&&c.setAttribute("data-a11y-dialog-hide","true");var u=document.createElement("div");u.setAttribute("id",X),document.body.appendChild(l);var h=document.createElement("style");h.setAttribute("id",te),h.textContent="\n #".concat(Z,",\n #").concat(ee," {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n }\n\n #").concat(Z," {\n z-index: 2147483647;\n display: flex;\n }\n\n #").concat(Z,"[aria-hidden='true'] {\n display: none;\n }\n\n #").concat(ee," {\n background-color: rgba(0, 0, 0, 0.18);\n }\n\n #").concat(X," {\n margin: auto;\n z-index: 2147483647;\n position: relative;\n background-color: transparent;\n border-radius: 8px;\n width: ").concat(o,";\n }\n\n #").concat(X," iframe {\n width: 1px;\n min-width: 100%;\n border-radius: inherit;\n max-height: ").concat(n?"100%":"95vh",";\n height: ").concat(null!=n?n:"384px",";\n }\n "),document.head.insertAdjacentElement("beforeend",h),l.appendChild(c),l.appendChild(u),this.popup=new Y(l),l.focus(),this.popup.on("hide",(function(){t.destroy()}))},e.prototype.destroy=function(){var e=document.querySelector("#".concat(Z)),t=document.querySelector("#".concat(te));e&&t&&(document.body.removeChild(e),document.head.removeChild(t)),window.removeEventListener("message",ae)},e.prototype.show=function(e){var t,s=e.url;if(!this.popup)throw new Error("Popup is not initialized");var r=document.createElement("iframe");r.setAttribute("id",se),r.setAttribute("name","authsignal"),r.setAttribute("title","Authsignal multi-factor authentication"),r.setAttribute("src",s),r.setAttribute("frameborder","0"),r.setAttribute("allow","publickey-credentials-get *; publickey-credentials-create *; clipboard-write");var n=document.querySelector("#".concat(X));n&&n.appendChild(r),this.height||window.addEventListener("message",ae),null===(t=this.popup)||void 0===t||t.show()},e.prototype.close=function(){if(!this.popup)throw new Error("Popup is not initialized");this.popup.hide()},e.prototype.on=function(e,t){if(!this.popup)throw new Error("Popup is not initialized");this.popup.on(e,t)},e}();function ae(e){var t=document.querySelector("#".concat(se));t&&e.data.height&&(t.style.height=e.data.height+"px")}var ie=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired;this.tenantId=s,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.enroll=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.token;return m(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/totp"),{method:"POST",headers:O({token:s,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return T({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return h(this,arguments,void 0,(function(e){var t,s,r=e.token,n=e.code;return m(this,(function(e){switch(e.label){case 0:return t={verificationCode:n},[4,fetch("".concat(this.baseUrl,"/client/verify/totp"),{method:"POST",headers:O({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return T({response:s=e.sent(),onTokenExpired:this.onTokenExpired}),[2,s]}}))}))},e}(),oe=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired,n=e.enableLogging;this.cache=U.shared,this.enableLogging=!1,this.enableLogging=n,this.api=new ie({baseUrl:t,tenantId:s,onTokenExpired:r})}return e.prototype.enroll=function(){return h(this,void 0,void 0,(function(){return m(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,V({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.verify=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.code;return m(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:s})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,V({response:t,enableLogging:this.enableLogging})]}}))}))},e}(),le=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired;this.tenantId=s,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.enroll=function(e){return h(this,arguments,void 0,(function(e){var t,s,r=e.token,n=e.email;return m(this,(function(e){switch(e.label){case 0:return t={email:n},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/email-otp"),{method:"POST",headers:O({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return T({response:s=e.sent(),onTokenExpired:this.onTokenExpired}),[2,s]}}))}))},e.prototype.challenge=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.token;return m(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/email-otp"),{method:"POST",headers:O({token:s,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return T({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return h(this,arguments,void 0,(function(e){var t,s,r=e.token,n=e.code;return m(this,(function(e){switch(e.label){case 0:return t={verificationCode:n},[4,fetch("".concat(this.baseUrl,"/client/verify/email-otp"),{method:"POST",headers:O({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return T({response:s=e.sent(),onTokenExpired:this.onTokenExpired}),[2,s]}}))}))},e}(),ce=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired,n=e.enableLogging;this.cache=U.shared,this.enableLogging=!1,this.enableLogging=n,this.api=new le({baseUrl:t,tenantId:s,onTokenExpired:r})}return e.prototype.enroll=function(e){return h(this,arguments,void 0,(function(e){var t=e.email;return m(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token,email:t})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,V({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.challenge=function(){return h(this,void 0,void 0,(function(){return m(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,V({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.verify=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.code;return m(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:s})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,V({response:t,enableLogging:this.enableLogging})]}}))}))},e}(),ue=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired;this.tenantId=s,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.enroll=function(e){return h(this,arguments,void 0,(function(e){var t,s,r=e.token,n=e.phoneNumber;return m(this,(function(e){switch(e.label){case 0:return t={phoneNumber:n},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/sms"),{method:"POST",headers:O({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return T({response:s=e.sent(),onTokenExpired:this.onTokenExpired}),[2,s]}}))}))},e.prototype.challenge=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.token;return m(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/sms"),{method:"POST",headers:O({token:s,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return T({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return h(this,arguments,void 0,(function(e){var t,s,r=e.token,n=e.code;return m(this,(function(e){switch(e.label){case 0:return t={verificationCode:n},[4,fetch("".concat(this.baseUrl,"/client/verify/sms"),{method:"POST",headers:O({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return T({response:s=e.sent(),onTokenExpired:this.onTokenExpired}),[2,s]}}))}))},e}(),he=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired,n=e.enableLogging;this.cache=U.shared,this.enableLogging=!1,this.enableLogging=n,this.api=new ue({baseUrl:t,tenantId:s,onTokenExpired:r})}return e.prototype.enroll=function(e){return h(this,arguments,void 0,(function(e){var t=e.phoneNumber;return m(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token,phoneNumber:t})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,V({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.challenge=function(){return h(this,void 0,void 0,(function(){return m(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,V({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.verify=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.code;return m(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:s})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,V({response:t,enableLogging:this.enableLogging})]}}))}))},e}(),me=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired;this.tenantId=s,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.enroll=function(e){return h(this,arguments,void 0,(function(e){var t,s,r=e.token,n=e.email;return m(this,(function(e){switch(e.label){case 0:return t={email:n},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/email-magic-link"),{method:"POST",headers:O({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return T({response:s=e.sent(),onTokenExpired:this.onTokenExpired}),[2,s]}}))}))},e.prototype.challenge=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.token;return m(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/email-magic-link"),{method:"POST",headers:O({token:s,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return T({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.checkVerificationStatus=function(e){return h(this,arguments,void 0,(function(e){var t,s=this,r=e.token;return m(this,(function(e){switch(e.label){case 0:return t=function(){return h(s,void 0,void 0,(function(){var e,s=this;return m(this,(function(n){switch(n.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/verify/email-magic-link/finalize"),{method:"POST",headers:O({token:r,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,n.sent().json()];case 2:return T({response:e=n.sent(),onTokenExpired:this.onTokenExpired}),e.isVerified?[2,e]:[2,new Promise((function(e){setTimeout((function(){return h(s,void 0,void 0,(function(){var s;return m(this,(function(r){switch(r.label){case 0:return s=e,[4,t()];case 1:return s.apply(void 0,[r.sent()]),[2]}}))}))}),1e3)}))]}}))}))},[4,t()];case 1:return[2,e.sent()]}}))}))},e}(),fe=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired,n=e.enableLogging;this.cache=U.shared,this.enableLogging=!1,this.enableLogging=n,this.api=new me({baseUrl:t,tenantId:s,onTokenExpired:r})}return e.prototype.enroll=function(e){return h(this,arguments,void 0,(function(e){var t=e.email;return m(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token,email:t})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,V({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.challenge=function(){return h(this,void 0,void 0,(function(){return m(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,V({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.checkVerificationStatus=function(){return h(this,void 0,void 0,(function(){var e;return m(this,(function(t){switch(t.label){case 0:return this.cache.token?[4,this.api.checkVerificationStatus({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(e=t.sent())&&e.accessToken&&(this.cache.token=e.accessToken),[2,V({response:e,enableLogging:this.enableLogging})]}}))}))},e}(),de=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired;this.tenantId=s,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.registrationOptions=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.token;return m(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key/registration-options"),{method:"POST",headers:O({token:s,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,e.sent().json()];case 2:return T({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.authenticationOptions=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.token;return m(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key/authentication-options"),{method:"POST",headers:O({token:s,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,e.sent().json()];case 2:return T({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.addAuthenticator=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.token,r=e.registrationCredential;return m(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key"),{method:"POST",headers:O({token:s,tenantId:this.tenantId}),body:JSON.stringify(r)})];case 1:return[4,e.sent().json()];case 2:return T({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.token,r=e.authenticationCredential;return m(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/verify/security-key"),{method:"POST",headers:O({token:s,tenantId:this.tenantId}),body:JSON.stringify(r)})];case 1:return[4,e.sent().json()];case 2:return T({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e}(),ge=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired,n=e.enableLogging;this.cache=U.shared,this.enableLogging=!1,this.api=new de({baseUrl:t,tenantId:s,onTokenExpired:r}),this.enableLogging=n}return e.prototype.enroll=function(){return h(this,void 0,void 0,(function(){var e,t,s,r,n;return m(this,(function(a){switch(a.label){case 0:return this.cache.token?(e={token:this.cache.token},[4,this.api.registrationOptions(e)]):[2,this.cache.handleTokenNotSetError()];case 1:if("error"in(t=a.sent()))return[2,B({errorResponse:t,enableLogging:this.enableLogging})];a.label=2;case 2:return a.trys.push([2,5,,6]),[4,A({optionsJSON:t})];case 3:return s=a.sent(),[4,this.api.addAuthenticator({registrationCredential:s,token:this.cache.token})];case 4:return"error"in(r=a.sent())?[2,B({errorResponse:r,enableLogging:this.enableLogging})]:(r.accessToken&&(this.cache.token=r.accessToken),[2,{data:{token:r.accessToken,registrationResponse:s}}]);case 5:throw x(n=a.sent()),n;case 6:return[2]}}))}))},e.prototype.verify=function(){return h(this,void 0,void 0,(function(){var e,t,s,r,n;return m(this,(function(a){switch(a.label){case 0:return this.cache.token?[4,this.api.authenticationOptions({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:if("error"in(e=a.sent()))return[2,B({errorResponse:e,enableLogging:this.enableLogging})];a.label=2;case 2:return a.trys.push([2,5,,6]),[4,C({optionsJSON:e})];case 3:return t=a.sent(),[4,this.api.verify({authenticationCredential:t,token:this.cache.token})];case 4:return"error"in(s=a.sent())?[2,B({errorResponse:s,enableLogging:this.enableLogging})]:(s.accessToken&&(this.cache.token=s.accessToken),r=s.accessToken,[2,{data:{isVerified:s.isVerified,token:r,authenticationResponse:t}}]);case 5:throw x(n=a.sent()),n;case 6:return[2]}}))}))},e}(),pe=function(){function e(e){var t=e.baseUrl,s=e.tenantId;this.tenantId=s,this.baseUrl=t}return e.prototype.challenge=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.action,r=e.token,n=e.custom;return m(this,(function(e){switch(e.label){case 0:return t={action:s,custom:n},[4,fetch("".concat(this.baseUrl,"/client/challenge/qr-code"),{method:"POST",headers:O({tenantId:this.tenantId,token:r}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}}))}))},e.prototype.verify=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.challengeId,r=e.deviceCode;return m(this,(function(e){switch(e.label){case 0:return t={challengeId:s,deviceCode:r},[4,fetch("".concat(this.baseUrl,"/client/verify/qr-code"),{method:"POST",headers:O({tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}}))}))},e}(),we=function(){},ye=54e4,ve=3e3,be=function(e){function t(t){var s=t.baseUrl,r=t.tenantId,n=t.enableLogging,a=e.call(this)||this;return a.cache=U.shared,a.enableLogging=!1,a.enableLogging=n,a.api=new pe({baseUrl:s,tenantId:r}),a}return l(t,e),t.prototype.challenge=function(e){return h(this,void 0,void 0,(function(){var t,s,r,n,a,i=this;return m(this,(function(o){switch(o.label){case 0:return[4,this.api.challenge({token:this.cache.token||void 0,action:e.action,custom:e.custom})];case 1:return t=o.sent(),(s=V({response:t,enableLogging:this.enableLogging})).data&&(this.currentChallengeParams=e,this.clearPolling(),r=e.pollInterval||ve,n=e.refreshInterval||ye,s.data.deviceCode&&this.startPolling({challengeId:s.data.challengeId,deviceCode:s.data.deviceCode,onStateChange:e.onStateChange,pollInterval:r}),e.onRefresh&&(a=e.onRefresh,this.startRefreshTimer((function(){return i.performRefresh({action:e.action,custom:e.custom,onRefresh:a,onStateChange:e.onStateChange,pollInterval:r})}),n))),[2,s]}}))}))},t.prototype.refresh=function(){return h(this,arguments,void 0,(function(e){var t,s,r,n,a,i,o,l,c,u=this,h=(void 0===e?{}:e).custom;return m(this,(function(e){switch(e.label){case 0:return this.currentChallengeParams?[4,this.api.challenge({token:this.cache.token||void 0,action:this.currentChallengeParams.action,custom:h||this.currentChallengeParams.custom})]:[2];case 1:return t=e.sent(),(s=V({response:t,enableLogging:this.enableLogging})).data&&(this.clearPolling(),this.currentChallengeParams.onRefresh&&this.currentChallengeParams.onRefresh(s.data.challengeId,s.data.expiresAt),s.data.deviceCode&&this.startPolling({challengeId:s.data.challengeId,deviceCode:s.data.deviceCode,onStateChange:this.currentChallengeParams.onStateChange,pollInterval:this.currentChallengeParams.pollInterval||ve}),this.currentChallengeParams.onRefresh&&(r=this.currentChallengeParams.refreshInterval||ye,n=this.currentChallengeParams,a=n.action,i=n.custom,o=n.onRefresh,l=n.onStateChange,c=n.pollInterval,this.startRefreshTimer((function(){return u.performRefresh({action:a,custom:i,onRefresh:o,onStateChange:l,pollInterval:c||ve})}),r))),[2]}}))}))},t.prototype.disconnect=function(){this.clearPolling(),this.clearRefreshTimer(),this.currentChallengeParams=void 0},t.prototype.startRefreshTimer=function(e,t){var s=this;this.clearRefreshTimer(),this.refreshTimeout=setTimeout((function(){return h(s,void 0,void 0,(function(){return m(this,(function(s){switch(s.label){case 0:return[4,e()];case 1:return s.sent(),this.startRefreshTimer(e,t),[2]}}))}))}),t)},t.prototype.clearRefreshTimer=function(){this.refreshTimeout&&(clearTimeout(this.refreshTimeout),this.refreshTimeout=void 0)},t.prototype.performRefresh=function(e){return h(this,arguments,void 0,(function(e){var t,s,r=e.action,n=e.custom,a=e.onRefresh,i=e.onStateChange,o=e.pollInterval;return m(this,(function(e){switch(e.label){case 0:return[4,this.api.challenge({token:this.cache.token||void 0,action:r,custom:n})];case 1:return t=e.sent(),(s=V({response:t,enableLogging:this.enableLogging})).data&&(this.clearPolling(),a(s.data.challengeId,s.data.expiresAt),s.data.deviceCode&&this.startPolling({challengeId:s.data.challengeId,deviceCode:s.data.deviceCode,onStateChange:i,pollInterval:o})),[2]}}))}))},t.prototype.startPolling=function(e){var t=this,s=e.challengeId,r=e.deviceCode,n=e.onStateChange,a=e.pollInterval;this.pollingInterval=setInterval((function(){return h(t,void 0,void 0,(function(){var e,t;return m(this,(function(a){switch(a.label){case 0:return[4,this.api.verify({challengeId:s,deviceCode:r})];case 1:return e=a.sent(),(t=V({response:e,enableLogging:this.enableLogging})).data&&(t.data.isVerified?(n("approved",t.data.token),this.clearPolling()):t.data.isClaimed&&!t.data.isConsumed?n("claimed"):t.data.isClaimed&&t.data.isConsumed&&(n("rejected"),this.clearPolling())),[2]}}))}))}),a)},t.prototype.clearPolling=function(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=void 0)},t}(we),Se="CHALLENGE_CREATED_HANDLER",ke=function(){function e(e){var t=e.baseUrl,s=e.tenantId;this.ws=null,this.messageHandlers=new Map,this.options=null,this.refreshInterval=null,this.tokenCache=U.shared;var r=t.replace("https://","wss://").replace("http://","ws://").replace("v1","ws-v1-challenge").replace("api","api-ws");this.baseUrl=r,this.tenantId=s}return e.prototype.connect=function(){return h(this,void 0,void 0,(function(){var e=this;return m(this,(function(t){return[2,new Promise((function(t,s){try{var r=["authsignal-ws"];e.tokenCache.token?r.push("x.authsignal.token.".concat(e.tokenCache.token)):r.push("x.authsignal.tenant.".concat(e.tenantId)),e.ws=new WebSocket(e.baseUrl,r),e.ws.onopen=function(){t()},e.ws.onerror=function(e){s(new Error("WebSocket connection error: ".concat(e)))},e.ws.onclose=function(){e.refreshInterval&&(clearInterval(e.refreshInterval),e.refreshInterval=null),e.messageHandlers.clear(),e.ws=null},e.ws.onmessage=function(t){try{var s=JSON.parse(t.data);e.handleMessage(s)}catch(e){console.error("Failed to parse WebSocket message:",e)}}}catch(e){s(e)}}))]}))}))},e.prototype.handleMessage=function(e){if("CHALLENGE_CREATED"===e.type){if(!(t=this.messageHandlers.get(Se)))throw new Error("Challenge created handler not found");t(e)}else if("STATE_CHANGE"===e.type){var t;(t=this.messageHandlers.get(e.data.challengeId))&&t(e)}},e.prototype.createQrCodeChallenge=function(e){return h(this,void 0,void 0,(function(){var t=this;return m(this,(function(s){switch(s.label){case 0:return this.ws&&this.ws.readyState===WebSocket.OPEN?[3,2]:[4,this.connect()];case 1:s.sent(),s.label=2;case 2:return this.refreshInterval&&clearInterval(this.refreshInterval),this.options=e,[2,new Promise((function(s,r){t.messageHandlers.set(Se,(function(r){if("CHALLENGE_CREATED"===r.type){var n=r;t.messageHandlers.delete(Se),t.monitorChallengeState(n.data.challengeId,e),t.startRefreshCycle(n.data.challengeId,e),s({challengeId:n.data.challengeId,expiresAt:n.data.expiresAt,state:n.data.state})}})),t.sendChallengeRequest(e).catch(r)}))]}}))}))},e.prototype.monitorChallengeState=function(e,t){var s=this;this.messageHandlers.set(e,(function(r){var n;if("STATE_CHANGE"===r.type){var a=r;null===(n=t.onStateChange)||void 0===n||n.call(t,a.data.state,a.data.accessToken),"approved"!==a.data.state&&"rejected"!==a.data.state||s.messageHandlers.delete(e)}}))},e.prototype.startRefreshCycle=function(e,t){var s=this,r=t.refreshInterval||54e4,n=e;this.refreshInterval=setInterval((function(){return h(s,void 0,void 0,(function(){var e,s,r;return m(this,(function(a){switch(a.label){case 0:this.messageHandlers.delete(n),a.label=1;case 1:return a.trys.push([1,3,,4]),[4,this.createQrCodeChallenge(t)];case 2:return e=a.sent(),n=e.challengeId,null===(r=t.onRefresh)||void 0===r||r.call(t,e.challengeId,e.expiresAt),[3,4];case 3:return s=a.sent(),console.error("Failed to refresh QR code challenge:",s),this.refreshInterval&&(clearInterval(this.refreshInterval),this.refreshInterval=null),[3,4];case 4:return[2]}}))}))}),r)},e.prototype.sendChallengeRequest=function(e){return h(this,void 0,void 0,(function(){return m(this,(function(t){switch(t.label){case 0:return this.ws&&this.ws.readyState===WebSocket.OPEN?[3,2]:[4,this.connect()];case 1:t.sent(),t.label=2;case 2:if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket connection could not be established");return this.sendMessage({type:"CREATE_CHALLENGE",data:{challengeType:"QR_CODE",actionCode:e.action,custom:e.custom}}),[2]}}))}))},e.prototype.sendMessage=function(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");this.ws.send(JSON.stringify(e))},e.prototype.refreshQrCodeChallenge=function(e){return h(this,arguments,void 0,(function(e){var t,s,r,n=e.custom;return m(this,(function(e){switch(e.label){case 0:if(!this.options)throw new Error("Call createQrCodeChallenge first");return[4,this.createQrCodeChallenge(c(c({},this.options),void 0!==n&&{custom:n}))];case 1:return t=e.sent(),null===(r=(s=this.options).onRefresh)||void 0===r||r.call(s,t.challengeId,t.expiresAt),[2,t]}}))}))},e.prototype.disconnect=function(){this.ws&&this.ws.close()},e}(),Ae=function(e){function t(t){var s=t.baseUrl,r=t.tenantId,n=t.enableLogging,a=e.call(this)||this;return a.cache=U.shared,a.enableLogging=!1,a.enableLogging=n,a.wsClient=new ke({baseUrl:s,tenantId:r}),a}return l(t,e),t.prototype.challenge=function(e){return h(this,void 0,void 0,(function(){var t;return m(this,(function(s){switch(s.label){case 0:return[4,this.wsClient.createQrCodeChallenge({token:this.cache.token||void 0,action:e.action,custom:e.custom,refreshInterval:e.refreshInterval,onRefresh:e.onRefresh,onStateChange:e.onStateChange})];case 1:return[2,{data:{challengeId:(t=s.sent()).challengeId,expiresAt:t.expiresAt}}]}}))}))},t.prototype.refresh=function(){return h(this,arguments,void 0,(function(e){var t=(void 0===e?{}:e).custom;return m(this,(function(e){switch(e.label){case 0:return[4,this.wsClient.refreshQrCodeChallenge({custom:t})];case 1:return e.sent(),[2]}}))}))},t.prototype.disconnect=function(){this.wsClient.disconnect()},t}(we),Ne=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.enableLogging;this.handler=null,this.enableLogging=!1,this.baseUrl=t,this.tenantId=s,this.enableLogging=r}return e.prototype.challenge=function(e){return h(this,void 0,void 0,(function(){var t,s,r;return m(this,(function(n){return t=e.polling,s=void 0!==t&&t,r=u(e,["polling"]),this.handler&&this.handler.disconnect(),this.handler=s?new be({baseUrl:this.baseUrl,tenantId:this.tenantId,enableLogging:this.enableLogging}):new Ae({baseUrl:this.baseUrl,tenantId:this.tenantId,enableLogging:this.enableLogging}),[2,this.handler.challenge(r)]}))}))},e.prototype.refresh=function(){return h(this,arguments,void 0,(function(e){var t=(void 0===e?{}:e).custom;return m(this,(function(e){if(!this.handler)throw new Error("challenge() must be called before refresh()");return[2,this.handler.refresh({custom:t})]}))}))},e.prototype.disconnect=function(){this.handler&&(this.handler.disconnect(),this.handler=null)},e}(),Ee=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired;this.tenantId=s,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.challenge=function(e){return h(this,arguments,void 0,(function(e){var t,s,r=e.action,n=e.token;return m(this,(function(e){switch(e.label){case 0:return t={action:r},[4,fetch("".concat(this.baseUrl,"/client/challenge/push"),{method:"POST",headers:O({token:n,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return T({response:s=e.sent(),onTokenExpired:this.onTokenExpired}),[2,s]}}))}))},e.prototype.verify=function(e){return h(this,arguments,void 0,(function(e){var t,s,r=e.challengeId,n=e.token;return m(this,(function(e){switch(e.label){case 0:return t={challengeId:r},[4,fetch("".concat(this.baseUrl,"/client/verify/push"),{method:"POST",headers:O({token:n,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return T({response:s=e.sent(),onTokenExpired:this.onTokenExpired}),[2,s]}}))}))},e}(),Ce=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired,n=e.enableLogging;this.cache=U.shared,this.enableLogging=!1,this.enableLogging=n,this.api=new Ee({baseUrl:t,tenantId:s,onTokenExpired:r})}return e.prototype.challenge=function(e){return h(this,arguments,void 0,(function(e){var t=e.action;return m(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({action:t,token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,V({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.verify=function(e){return h(this,arguments,void 0,(function(e){var t=e.challengeId;return m(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({challengeId:t,token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,V({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e}(),Ie=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired;this.tenantId=s,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.challenge=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.token;return m(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/whatsapp"),{method:"POST",headers:O({token:s,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return T({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return h(this,arguments,void 0,(function(e){var t,s,r=e.token,n=e.code;return m(this,(function(e){switch(e.label){case 0:return t={verificationCode:n},[4,fetch("".concat(this.baseUrl,"/client/verify/whatsapp"),{method:"POST",headers:O({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return T({response:s=e.sent(),onTokenExpired:this.onTokenExpired}),[2,s]}}))}))},e}(),Be=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired,n=e.enableLogging;this.cache=U.shared,this.enableLogging=!1,this.enableLogging=n,this.api=new Ie({baseUrl:t,tenantId:s,onTokenExpired:r})}return e.prototype.challenge=function(){return h(this,void 0,void 0,(function(){return m(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,V({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.verify=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.code;return m(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:s})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,V({response:t,enableLogging:this.enableLogging})]}}))}))},e}(),Ve=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired;this.tenantId=s,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.presentationOptions=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.action,r=e.challengeId,n=e.anonymous,a=e.token,i=e.documentTypes,o=e.claims;return m(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/digital-credential/presentation-options"),{method:"POST",headers:O({token:a,tenantId:this.tenantId}),body:JSON.stringify({action:s,challengeId:r,anonymous:n,documentTypes:i,claims:o})})];case 1:return[4,e.sent().json()];case 2:return T({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verifyPresentation=function(e){return h(this,arguments,void 0,(function(e){var t,s=e.token,r=e.data,n=e.challengeId,a=e.redirectUrl;return m(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/digital-credential/verify-presentation"),{method:"POST",headers:O({token:s,tenantId:this.tenantId}),body:JSON.stringify({data:r,challengeId:n,redirectUrl:a})})];case 1:return[4,e.sent().json()];case 2:return T({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.challenge=function(e){return h(this,void 0,void 0,(function(){var t;return m(this,(function(s){switch(s.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge"),{method:"POST",headers:O({tenantId:this.tenantId}),body:JSON.stringify({action:e})})];case 1:return[4,s.sent().json()];case 2:return T({response:t=s.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e}();function xe(){return"undefined"!=typeof window&&"DigitalCredential"in window&&"function"==typeof window.DigitalCredential}
|
|
2
|
+
/*!
|
|
3
|
+
* MIT License
|
|
4
|
+
*
|
|
5
|
+
* Copyright (c) 2017-2024 Peculiar Ventures, LLC
|
|
6
|
+
*
|
|
7
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
9
|
+
* in the Software without restriction, including without limitation the rights
|
|
10
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
12
|
+
* furnished to do so, subject to the following conditions:
|
|
13
|
+
*
|
|
14
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
15
|
+
* copies or substantial portions of the Software.
|
|
16
|
+
*
|
|
17
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
23
|
+
* SOFTWARE.
|
|
24
|
+
*
|
|
25
|
+
*/class De{static isArrayBuffer(e){return"[object ArrayBuffer]"===Object.prototype.toString.call(e)}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||0===e.byteOffset&&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){const s=De.toUint8Array(e),r=De.toUint8Array(t);if(s.length!==r.byteLength)return!1;for(let e=0;e<s.length;e++)if(s[e]!==r[e])return!1;return!0}static concat(...e){let t;t=!Array.isArray(e[0])||e[1]instanceof Function?Array.isArray(e[0])&&e[1]instanceof Function?e[0]:e[e.length-1]instanceof Function?e.slice(0,e.length-1):e:e[0];let s=0;for(const e of t)s+=e.byteLength;const r=new Uint8Array(s);let n=0;for(const e of t){const t=this.toUint8Array(e);r.set(t,n),n+=t.length}return e[e.length-1]instanceof Function?this.toView(r,e[e.length-1]):r.buffer}}const Oe="string",Te=/^[0-9a-f\s]+$/i,Pe=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Ue=/^[a-zA-Z0-9-_]+$/;class Le{static fromString(e){const t=unescape(encodeURIComponent(e)),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}static toString(e){const t=De.toUint8Array(e);let s="";for(let e=0;e<t.length;e++)s+=String.fromCharCode(t[e]);return decodeURIComponent(escape(s))}}class Re{static toString(e,t=!1){const s=De.toArrayBuffer(e),r=new DataView(s);let n="";for(let e=0;e<s.byteLength;e+=2){const s=r.getUint16(e,t);n+=String.fromCharCode(s)}return n}static fromString(e,t=!1){const s=new ArrayBuffer(2*e.length),r=new DataView(s);for(let s=0;s<e.length;s++)r.setUint16(2*s,e.charCodeAt(s),t);return s}}class _e{static isHex(e){return typeof e===Oe&&Te.test(e)}static isBase64(e){return typeof e===Oe&&Pe.test(e)}static isBase64Url(e){return typeof e===Oe&&Ue.test(e)}static ToString(e,t="utf8"){const s=De.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(s);case"binary":return this.ToBinary(s);case"hex":return this.ToHex(s);case"base64":return this.ToBase64(s);case"base64url":return this.ToBase64Url(s);case"utf16le":return Re.toString(s,!0);case"utf16":case"utf16be":return Re.toString(s);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 Re.fromString(e,!0);case"utf16":case"utf16be":return Re.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){const t=De.toUint8Array(e);if("undefined"!=typeof btoa){const e=this.ToString(t,"binary");return btoa(e)}return Buffer.from(t).toString("base64")}static FromBase64(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!_e.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return"undefined"!=typeof atob?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!_e.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=_e.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return Le.fromString(e);case"utf16":case"utf16be":return Re.fromString(e);case"utf16le":case"usc2":return Re.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=_e.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return Le.toString(e);case"utf16":case"utf16be":return Re.toString(e);case"utf16le":case"usc2":return Re.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){const t=e.length,s=new Uint8Array(t);for(let r=0;r<t;r++)s[r]=e.charCodeAt(r);return s.buffer}static ToBinary(e){const t=De.toUint8Array(e);let s="";for(let e=0;e<t.length;e++)s+=String.fromCharCode(t[e]);return s}static ToHex(e){const t=De.toUint8Array(e);let s="";const r=t.length;for(let e=0;e<r;e++){const r=t[e];r<16&&(s+="0"),s+=r.toString(16)}return s}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!_e.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);const s=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2){const r=t.slice(e,e+2);s[e/2]=parseInt(r,16)}return s.buffer}static ToUtf16String(e,t=!1){return Re.toString(e,t)}static FromUtf16String(e,t=!1){return Re.fromString(e,t)}static Base64Padding(e){const t=4-e.length%4;if(t<4)for(let s=0;s<t;s++)e+="=";return e}static formatString(e){return(null==e?void 0:e.replace(/[\n\r\t ]/g,""))||""}}
|
|
26
|
+
/*!
|
|
27
|
+
Copyright (c) Peculiar Ventures, LLC
|
|
28
|
+
*/
|
|
29
|
+
function He(e,t,s){var r;return e instanceof Object==!1?s:null!==(r=e[t])&&void 0!==r?r:s}function Ke(e,t=0,s=e.byteLength-t,r=!1){let n="";for(const a of new Uint8Array(e,t,s)){const e=a.toString(16).toUpperCase();1===e.length&&(n+="0"),n+=e,r&&(n+=" ")}return n.trim()}function Me(e,t){let s=0;if(1===e.length)return e[0];for(let r=e.length-1;r>=0;r--)s+=e[e.length-1-r]*Math.pow(2,t*r);return s}function je(e,t,s=-1){const r=s;let n=e,a=0,i=Math.pow(2,t);for(let s=1;s<8;s++){if(e<i){let e;if(r<0)e=new ArrayBuffer(s),a=s;else{if(r<s)return new ArrayBuffer(0);e=new ArrayBuffer(r),a=r}const i=new Uint8Array(e);for(let e=s-1;e>=0;e--){const s=Math.pow(2,e*t);i[a-e-1]=Math.floor(n/s),n-=i[a-e-1]*s}return e}i*=Math.pow(2,t)}return new ArrayBuffer(0)}function Je(...e){let t=0,s=0;for(const s of e)t+=s.byteLength;const r=new ArrayBuffer(t),n=new Uint8Array(r);for(const t of e)n.set(new Uint8Array(t),s),s+=t.byteLength;return r}function $e(...e){let t=0,s=0;for(const s of e)t+=s.length;const r=new ArrayBuffer(t),n=new Uint8Array(r);for(const t of e)n.set(t,s),s+=t.length;return n}function Fe(){const e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const t=255===e[0]&&128&e[1],s=0===e[0]&&0==(128&e[1]);(t||s)&&this.warnings.push("Needlessly long format")}const t=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(t);for(let e=0;e<this.valueHex.byteLength;e++)s[e]=0;s[0]=128&e[0];const r=Me(s,8),n=new ArrayBuffer(this.valueHex.byteLength),a=new Uint8Array(n);for(let t=0;t<this.valueHex.byteLength;t++)a[t]=e[t];a[0]&=127;return Me(a,8)-r}function qe(e,t){if(e.byteLength!==t.byteLength)return!1;const s=new Uint8Array(e),r=new Uint8Array(t);for(let e=0;e<s.length;e++)if(s[e]!==r[e])return!1;return!0}function We(e,t){const s=e.toString(10);if(t<s.length)return"";const r=t-s.length,n=new Array(r);for(let e=0;e<r;e++)n[e]="0";return n.join("").concat(s)}_e.DEFAULT_UTF8_ENCODING="utf8";const Ge="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",ze="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=";function Ye(e,t=!1,s=!1,r=!1){let n=0,a=0,i=0,o="";const l=t?ze:Ge;if(r){let t=0;for(let s=0;s<e.length;s++)if(0!==e.charCodeAt(s)){t=s;break}e=e.slice(t)}for(;n<e.length;){const t=e.charCodeAt(n++);n>=e.length&&(a=1);const r=e.charCodeAt(n++);n>=e.length&&(i=1);const c=e.charCodeAt(n++),u=t>>2,h=(3&t)<<4|r>>4;let m=(15&r)<<2|c>>6,f=63&c;1===a?m=f=64:1===i&&(f=64),o+=s?64===m?`${l.charAt(u)}${l.charAt(h)}`:64===f?`${l.charAt(u)}${l.charAt(h)}${l.charAt(m)}`:`${l.charAt(u)}${l.charAt(h)}${l.charAt(m)}${l.charAt(f)}`:`${l.charAt(u)}${l.charAt(h)}${l.charAt(m)}${l.charAt(f)}`}return o}function Qe(e,t=!1,s=!1){const r=t?ze:Ge;function n(e){for(let t=0;t<64;t++)if(r.charAt(t)===e)return t;return 64}function a(e){return 64===e?0:e}let i=0,o="";for(;i<e.length;){const t=n(e.charAt(i++)),s=i>=e.length?0:n(e.charAt(i++)),r=i>=e.length?0:n(e.charAt(i++)),l=i>=e.length?0:n(e.charAt(i++)),c=a(t)<<2|a(s)>>4,u=(15&a(s))<<4|a(r)>>2,h=(3&a(r))<<6|a(l);o+=String.fromCharCode(c),64!==r&&(o+=String.fromCharCode(u)),64!==l&&(o+=String.fromCharCode(h))}if(s){let e=-1;for(let t=o.length-1;t>=0;t--)if(0!==o.charCodeAt(t)){e=t;break}o=-1!==e?o.slice(0,e+1):""}return o}function Ze(e){let t="";const s=new Uint8Array(e);for(const e of s)t+=String.fromCharCode(e);return t}function Xe(e){const t=e.length,s=new ArrayBuffer(t),r=new Uint8Array(s);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);return s}const et=Math.log(2);function tt(e){const t=Math.log(e)/et,s=Math.floor(t),r=Math.round(t);return s===r?s:r}function st(e,t){for(const s of t)delete e[s]}
|
|
30
|
+
/*!
|
|
31
|
+
* Copyright (c) 2014, GMO GlobalSign
|
|
32
|
+
* Copyright (c) 2015-2022, Peculiar Ventures
|
|
33
|
+
* All rights reserved.
|
|
34
|
+
*
|
|
35
|
+
* Author 2014-2019, Yury Strozhevsky
|
|
36
|
+
*
|
|
37
|
+
* Redistribution and use in source and binary forms, with or without modification,
|
|
38
|
+
* are permitted provided that the following conditions are met:
|
|
39
|
+
*
|
|
40
|
+
* * Redistributions of source code must retain the above copyright notice, this
|
|
41
|
+
* list of conditions and the following disclaimer.
|
|
42
|
+
*
|
|
43
|
+
* * Redistributions in binary form must reproduce the above copyright notice, this
|
|
44
|
+
* list of conditions and the following disclaimer in the documentation and/or
|
|
45
|
+
* other materials provided with the distribution.
|
|
46
|
+
*
|
|
47
|
+
* * Neither the name of the copyright holder nor the names of its
|
|
48
|
+
* contributors may be used to endorse or promote products derived from
|
|
49
|
+
* this software without specific prior written permission.
|
|
50
|
+
*
|
|
51
|
+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
52
|
+
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
53
|
+
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
54
|
+
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
|
55
|
+
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
|
56
|
+
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
|
57
|
+
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
|
58
|
+
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
59
|
+
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
|
60
|
+
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
61
|
+
*
|
|
62
|
+
*/function rt(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function nt(e){let t=0,s=0;for(let s=0;s<e.length;s++){t+=e[s].byteLength}const r=new Uint8Array(t);for(let t=0;t<e.length;t++){const n=e[t];r.set(new Uint8Array(n),s),s+=n.byteLength}return r.buffer}function at(e,t,s,r){return t instanceof Uint8Array?t.byteLength?s<0?(e.error="Wrong parameter: inputOffset less than zero",!1):r<0?(e.error="Wrong parameter: inputLength less than zero",!1):!(t.byteLength-s-r<0)||(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class it{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return nt(this.items)}}const ot=[new Uint8Array([1])],lt="0123456789",ct="name",ut="valueHexView",ht="",mt=new ArrayBuffer(0),ft=new Uint8Array(0),dt="EndOfContent",gt="OCTET STRING",pt="BIT STRING";function wt(e){var t;return(t=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}constructor(...e){var t;super(...e);const s=e[0]||{};this.isHexOnly=null!==(t=s.isHexOnly)&&void 0!==t&&t,this.valueHexView=s.valueHex?De.toUint8Array(s.valueHex):ft}fromBER(e,t,s){const r=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!at(this,r,t,s))return-1;const n=t+s;return this.valueHexView=r.subarray(t,n),this.valueHexView.length?(this.blockLength=s,n):(this.warnings.push("Zero buffer length"),t)}toBER(e=!1){return this.isHexOnly?e?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",mt)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:_e.ToHex(this.valueHexView)}}}).NAME="hexBlock",t}class yt{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="",warnings:s=[],valueBeforeDecode:r=ft}={}){this.blockLength=e,this.error=t,this.warnings=s,this.valueBeforeDecodeView=De.toUint8Array(r)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:_e.ToHex(this.valueBeforeDecodeView)}}}yt.NAME="baseBlock";class vt extends yt{fromBER(e,t,s){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'")}}vt.NAME="valueBlock";class bt extends(wt(yt)){constructor({idBlock:e={}}={}){var t,s,r,n;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?De.toUint8Array(e.valueHex):ft,this.tagClass=null!==(s=e.tagClass)&&void 0!==s?s:-1,this.tagNumber=null!==(r=e.tagNumber)&&void 0!==r?r:-1,this.isConstructed=null!==(n=e.isConstructed)&&void 0!==n&&n):(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",mt}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){const s=new Uint8Array(1);if(!e){let e=this.tagNumber;e&=31,t|=e,s[0]=t}return s.buffer}if(!this.isHexOnly){const s=je(this.tagNumber,7),r=new Uint8Array(s),n=s.byteLength,a=new Uint8Array(n+1);if(a[0]=31|t,!e){for(let e=0;e<n-1;e++)a[e+1]=128|r[e];a[n]=r[n-1]}return a.buffer}const s=new Uint8Array(this.valueHexView.byteLength+1);if(s[0]=31|t,!e){const e=this.valueHexView;for(let t=0;t<e.length-1;t++)s[t+1]=128|e[t];s[this.valueHexView.byteLength]=e[e.length-1]}return s.buffer}fromBER(e,t,s){const r=De.toUint8Array(e);if(!at(this,r,t,s))return-1;const n=r.subarray(t,t+s);if(0===n.length)return this.error="Zero buffer length",-1;switch(192&n[0]){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=32==(32&n[0]),this.isHexOnly=!1;const a=31&n[0];if(31!==a)this.tagNumber=a,this.blockLength=1;else{let e=1,t=this.valueHexView=new Uint8Array(255),s=255;for(;128&n[e];){if(t[e-1]=127&n[e],e++,e>=n.length)return this.error="End of input reached before message was fully decoded",-1;if(e===s){s+=255;const e=new Uint8Array(s);for(let s=0;s<t.length;s++)e[s]=t[s];t=this.valueHexView=new Uint8Array(s)}}this.blockLength=e+1,t[e-1]=127&n[e];const r=new Uint8Array(e);for(let s=0;s<e;s++)r[s]=t[s];t=this.valueHexView=new Uint8Array(e),t.set(r),this.blockLength<=9?this.tagNumber=Me(t,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(1===this.tagClass&&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}}}bt.NAME="identificationBlock";class St extends yt{constructor({lenBlock:e={}}={}){var t,s,r;super(),this.isIndefiniteForm=null!==(t=e.isIndefiniteForm)&&void 0!==t&&t,this.longFormUsed=null!==(s=e.longFormUsed)&&void 0!==s&&s,this.length=null!==(r=e.length)&&void 0!==r?r:0}fromBER(e,t,s){const r=De.toUint8Array(e);if(!at(this,r,t,s))return-1;const n=r.subarray(t,t+s);if(0===n.length)return this.error="Zero buffer length",-1;if(255===n[0])return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=128===n[0],this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(128&n[0]),!1===this.longFormUsed)return this.length=n[0],this.blockLength=1,t+this.blockLength;const a=127&n[0];if(a>8)return this.error="Too big integer",-1;if(a+1>n.length)return this.error="End of input reached before message was fully decoded",-1;const i=t+1,o=r.subarray(i,i+a);return 0===o[a-1]&&this.warnings.push("Needlessly long encoded length"),this.length=Me(o,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,s;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),!1===e&&(s=new Uint8Array(t),s[0]=128),t;if(this.longFormUsed){const r=je(this.length,8);if(r.byteLength>127)return this.error="Too big length",mt;if(t=new ArrayBuffer(r.byteLength+1),e)return t;const n=new Uint8Array(r);s=new Uint8Array(t),s[0]=128|r.byteLength;for(let e=0;e<r.byteLength;e++)s[e+1]=n[e];return t}return t=new ArrayBuffer(1),!1===e&&(s=new Uint8Array(t),s[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}St.NAME="lengthBlock";const kt={};class At extends yt{constructor({name:e="",optional:t=!1,primitiveSchema:s,...r}={},n){super(r),this.name=e,this.optional=t,s&&(this.primitiveSchema=s),this.idBlock=new bt(r),this.lenBlock=new St(r),this.valueBlock=n?new n(r):new vt(r)}fromBER(e,t,s){const r=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?s:this.lenBlock.length);return-1===r?(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){const s=t||new it;t||Nt(this);const r=this.idBlock.toBER(e);if(s.write(r),this.lenBlock.isIndefiniteForm)s.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,s),s.write(new ArrayBuffer(2));else{const t=this.valueBlock.toBER(e);this.lenBlock.length=t.byteLength;const r=this.lenBlock.toBER(e);s.write(r),s.write(t)}return t?mt:s.final()}toJSON(){const 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"ascii"===e?this.onAsciiEncoding():_e.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${_e.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;return qe(this.toBER(),e.toBER())}}function Nt(e){var t;if(e instanceof kt.Constructed)for(const t of e.valueBlock.value)Nt(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!(null===(t=e.lenBlock)||void 0===t?void 0:t.isIndefiniteForm)}At.NAME="BaseBlock";class Et extends At{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e="",...t}={},s){super(t,s),e&&this.fromString(e)}fromBER(e,t,s){const r=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?s:this.lenBlock.length);return-1===r?(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}'`}}Et.NAME="BaseStringBlock";class Ct extends(wt(vt)){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}}var It,Bt,Vt,xt,Dt,Ot,Tt,Pt,Ut,Lt,Rt,_t,Ht,Kt,Mt,jt,Jt,$t,Ft,qt,Wt,Gt,zt,Yt,Qt,Zt,Xt,es,ts,ss,rs,ns,as;Ct.NAME="PrimitiveValueBlock";class is extends At{constructor(e={}){super(e,Ct),this.idBlock.isConstructed=!1}}function os(e,t=0,s=e.length){const r=t;let n=new At({},vt);const a=new yt;if(!at(a,e,t,s))return n.error=a.error,{offset:-1,result:n};if(!e.subarray(t,t+s).length)return n.error="Zero buffer length",{offset:-1,result:n};let i=n.idBlock.fromBER(e,t,s);if(n.idBlock.warnings.length&&n.warnings.concat(n.idBlock.warnings),-1===i)return n.error=n.idBlock.error,{offset:-1,result:n};if(t=i,s-=n.idBlock.blockLength,i=n.lenBlock.fromBER(e,t,s),n.lenBlock.warnings.length&&n.warnings.concat(n.lenBlock.warnings),-1===i)return n.error=n.lenBlock.error,{offset:-1,result:n};if(t=i,s-=n.lenBlock.blockLength,!n.idBlock.isConstructed&&n.lenBlock.isIndefiniteForm)return n.error="Indefinite length form used for primitive encoding form",{offset:-1,result:n};let o=At;if(1===n.idBlock.tagClass){if(n.idBlock.tagNumber>=37&&!1===n.idBlock.isHexOnly)return n.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:n};switch(n.idBlock.tagNumber){case 0:if(n.idBlock.isConstructed&&n.lenBlock.length>0)return n.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:n};o=kt.EndOfContent;break;case 1:o=kt.Boolean;break;case 2:o=kt.Integer;break;case 3:o=kt.BitString;break;case 4:o=kt.OctetString;break;case 5:o=kt.Null;break;case 6:o=kt.ObjectIdentifier;break;case 10:o=kt.Enumerated;break;case 12:o=kt.Utf8String;break;case 13:o=kt.RelativeObjectIdentifier;break;case 14:o=kt.TIME;break;case 15:return n.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:n};case 16:o=kt.Sequence;break;case 17:o=kt.Set;break;case 18:o=kt.NumericString;break;case 19:o=kt.PrintableString;break;case 20:o=kt.TeletexString;break;case 21:o=kt.VideotexString;break;case 22:o=kt.IA5String;break;case 23:o=kt.UTCTime;break;case 24:o=kt.GeneralizedTime;break;case 25:o=kt.GraphicString;break;case 26:o=kt.VisibleString;break;case 27:o=kt.GeneralString;break;case 28:o=kt.UniversalString;break;case 29:o=kt.CharacterString;break;case 30:o=kt.BmpString;break;case 31:o=kt.DATE;break;case 32:o=kt.TimeOfDay;break;case 33:o=kt.DateTime;break;case 34:o=kt.Duration;break;default:{const e=n.idBlock.isConstructed?new kt.Constructed:new kt.Primitive;e.idBlock=n.idBlock,e.lenBlock=n.lenBlock,e.warnings=n.warnings,n=e}}}else o=n.idBlock.isConstructed?kt.Constructed:kt.Primitive;return n=function(e,t){if(e instanceof t)return e;const s=new t;return s.idBlock=e.idBlock,s.lenBlock=e.lenBlock,s.warnings=e.warnings,s.valueBeforeDecodeView=e.valueBeforeDecodeView,s}(n,o),i=n.fromBER(e,t,n.lenBlock.isIndefiniteForm?s:n.lenBlock.length),n.valueBeforeDecodeView=e.subarray(r,r+n.blockLength),{offset:i,result:n}}function ls(e){if(!e.byteLength){const e=new At({},vt);return e.error="Input buffer has zero length",{offset:-1,result:e}}return os(De.toUint8Array(e).slice(),0,e.byteLength)}It=is,kt.Primitive=It,is.NAME="PRIMITIVE";class cs extends vt{constructor({value:e=[],isIndefiniteForm:t=!1,...s}={}){super(s),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,s){const r=De.toUint8Array(e);if(!at(this,r,t,s))return-1;if(this.valueBeforeDecodeView=r.subarray(t,t+s),0===this.valueBeforeDecodeView.length)return this.warnings.push("Zero buffer length"),t;let n=t;for(;a=this.isIndefiniteForm,i=s,(a?1:i)>0;){const e=os(r,n,s);if(-1===e.offset)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(n=e.offset,this.blockLength+=e.result.blockLength,s-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===dt)break}var a,i;return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===dt?this.value.pop():this.warnings.push("No EndOfContent block encoded")),n}toBER(e,t){const s=t||new it;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,s);return t?mt:s.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const t of this.value)e.value.push(t.toJSON());return e}}cs.NAME="ConstructedValueBlock";class us extends At{constructor(e={}){super(e,cs),this.idBlock.isConstructed=!0}fromBER(e,t,s){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const r=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?s:this.lenBlock.length);return-1===r?(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(){const e=[];for(const t of this.valueBlock.value)e.push(t.toString("ascii").split("\n").map((e=>` ${e}`)).join("\n"));const t=3===this.idBlock.tagClass?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :\n${e.join("\n")}`:`${t} :`}}Bt=us,kt.Constructed=Bt,us.NAME="CONSTRUCTED";class hs extends vt{fromBER(e,t,s){return t}toBER(e){return mt}}hs.override="EndOfContentValueBlock";class ms extends At{constructor(e={}){super(e,hs),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Vt=ms,kt.EndOfContent=Vt,ms.NAME=dt;class fs extends At{constructor(e={}){super(e,vt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,s){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+=s,t+s>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+s}toBER(e,t){const s=new ArrayBuffer(2);if(!e){const e=new Uint8Array(s);e[0]=5,e[1]=0}return t&&t.write(s),s}onAsciiEncoding(){return`${this.constructor.NAME}`}}xt=fs,kt.Null=xt,fs.NAME="NULL";class ds extends(wt(vt)){get value(){for(const 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=De.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,s){const r=De.toUint8Array(e);return at(this,r,t,s)?(this.valueHexView=r.subarray(t,t+s),s>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Fe.call(this),this.blockLength=s,t+s):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}ds.NAME="BooleanValueBlock";class gs extends At{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,ds),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}Dt=gs,kt.Boolean=Dt,gs.NAME="BOOLEAN";class ps extends(wt(cs)){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,s){let r=0;if(this.isConstructed){if(this.isHexOnly=!1,r=cs.prototype.fromBER.call(this,e,t,s),-1===r)return r;for(let e=0;e<this.value.length;e++){const t=this.value[e].constructor.NAME;if(t===dt){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(t!==gt)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,r=super.fromBER(e,t,s),this.blockLength=s;return r}toBER(e,t){return this.isConstructed?cs.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}ps.NAME="OctetStringValueBlock";class ws extends At{constructor({idBlock:e={},lenBlock:t={},...s}={}){var r,n;null!==(r=s.isConstructed)&&void 0!==r||(s.isConstructed=!!(null===(n=s.value)||void 0===n?void 0:n.length)),super({idBlock:{isConstructed:s.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!s.isIndefiniteForm},...s},ps),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,s){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,0===s)return 0===this.idBlock.error.length&&(this.blockLength+=this.idBlock.blockLength),0===this.lenBlock.error.length&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){const r=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+s);try{if(r.byteLength){const e=os(r,0,r.byteLength);-1!==e.offset&&e.offset===s&&(this.valueBlock.value=[e.result])}}catch{}}return super.fromBER(e,t,s)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return us.prototype.onAsciiEncoding.call(this);return`${this.constructor.NAME} : ${_e.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;const e=[];for(const t of this.valueBlock.value)t instanceof Ot&&e.push(t.valueBlock.valueHexView);return De.concat(e)}}Ot=ws,kt.OctetString=Ot,ws.NAME=gt;class ys extends(wt(cs)){constructor({unusedBits:e=0,isConstructed:t=!1,...s}={}){super(s),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,s){if(!s)return t;let r=-1;if(this.isConstructed){if(r=cs.prototype.fromBER.call(this,e,t,s),-1===r)return r;for(const e of this.value){const t=e.constructor.NAME;if(t===dt){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(t!==pt)return this.error="BIT STRING may consists of BIT STRINGs only",-1;const s=e.valueBlock;if(this.unusedBits>0&&s.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=s.unusedBits}return r}const n=De.toUint8Array(e);if(!at(this,n,t,s))return-1;const a=n.subarray(t,t+s);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){const e=a.subarray(1);try{if(e.byteLength){const t=os(e,0,e.byteLength);-1!==t.offset&&t.offset===s-1&&(this.value=[t.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,t+s}toBER(e,t){if(this.isConstructed)return cs.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){const e=new Uint8Array(1);return e[0]=0,e.buffer}const s=new Uint8Array(this.valueHexView.length+1);return s[0]=this.unusedBits,s.set(this.valueHexView,1),s.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}ys.NAME="BitStringValueBlock";class vs extends At{constructor({idBlock:e={},lenBlock:t={},...s}={}){var r,n;null!==(r=s.isConstructed)&&void 0!==r||(s.isConstructed=!!(null===(n=s.value)||void 0===n?void 0:n.length)),super({idBlock:{isConstructed:s.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!s.isIndefiniteForm},...s},ys),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,s){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,s)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return us.prototype.onAsciiEncoding.call(this);{const e=[],t=this.valueBlock.valueHexView;for(const s of t)e.push(s.toString(2).padStart(8,"0"));const s=e.join("");return`${this.constructor.NAME} : ${s.substring(0,s.length-this.valueBlock.unusedBits)}`}}}function bs(e,t){const s=new Uint8Array([0]),r=new Uint8Array(e),n=new Uint8Array(t);let a=r.slice(0);const i=a.length-1,o=n.slice(0),l=o.length-1;let c=0;let u=0;for(let e=l<i?i:l;e>=0;e--,u++){if(!0==u<o.length)c=a[i-u]+o[l-u]+s[0];else c=a[i-u]+s[0];if(s[0]=c/10,!0==u>=a.length)a=$e(new Uint8Array([c%10]),a);else a[i-u]=c%10}return s[0]>0&&(a=$e(s,a)),a}function Ss(e){if(e>=ot.length)for(let t=ot.length;t<=e;t++){const e=new Uint8Array([0]);let s=ot[t-1].slice(0);for(let t=s.length-1;t>=0;t--){const r=new Uint8Array([(s[t]<<1)+e[0]]);e[0]=r[0]/10,s[t]=r[0]%10}e[0]>0&&(s=$e(e,s)),ot.push(s)}return ot[e]}function ks(e,t){let s=0;const r=new Uint8Array(e),n=new Uint8Array(t),a=r.slice(0),i=a.length-1,o=n.slice(0),l=o.length-1;let c,u=0;for(let e=l;e>=0;e--,u++)if(c=a[i-u]-o[l-u]-s,!0==c<0)s=1,a[i-u]=c+10;else s=0,a[i-u]=c;if(s>0)for(let e=i-l+1;e>=0;e--,u++){if(c=a[i-u]-s,!(c<0)){s=0,a[i-u]=c;break}s=1,a[i-u]=c+10}return a.slice()}Tt=vs,kt.BitString=Tt,vs.NAME=pt;class As extends(wt(vt)){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=Fe.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),void 0!==e&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(function(e){const t=e<0?-1*e:e;let s=128;for(let r=1;r<8;r++){if(t<=s){if(e<0){const e=je(s-t,8,r);return new Uint8Array(e)[0]|=128,e}let n=je(t,8,r),a=new Uint8Array(n);if(128&a[0]){const e=n.slice(0),t=new Uint8Array(e);n=new ArrayBuffer(n.byteLength+1),a=new Uint8Array(n);for(let s=0;s<e.byteLength;s++)a[s+1]=t[s];a[0]=0}return n}s*=Math.pow(2,8)}return new ArrayBuffer(0)}(e))}get valueDec(){return this._valueDec}fromDER(e,t,s,r=0){const n=this.fromBER(e,t,s);if(-1===n)return n;const a=this.valueHexView;return 0===a[0]&&0!=(128&a[1])?this.valueHexView=a.subarray(1):0!==r&&a.length<r&&(r-a.length>1&&(r=a.length+1),this.valueHexView=a.subarray(r-a.length)),n}toDER(e=!1){const t=this.valueHexView;switch(!0){case 0!=(128&t[0]):{const e=new Uint8Array(this.valueHexView.length+1);e[0]=0,e.set(t,1),this.valueHexView=e}break;case 0===t[0]&&0==(128&t[1]):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,s){const r=super.fromBER(e,t,s);return-1===r||this.setValueHex(),r}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){const e=8*this.valueHexView.length-1;let t,s=new Uint8Array(8*this.valueHexView.length/3),r=0;const n=this.valueHexView;let a="",i=!1;for(let i=n.byteLength-1;i>=0;i--){t=n[i];for(let n=0;n<8;n++){if(1==(1&t))if(r===e)s=ks(Ss(r),s),a="-";else s=bs(s,Ss(r));r++,t>>=1}}for(let e=0;e<s.length;e++)s[e]&&(i=!0),i&&(a+=lt.charAt(s[e]));return!1===i&&(a+=lt.charAt(0)),a}}Pt=As,As.NAME="IntegerValueBlock",Object.defineProperty(Pt.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class Ns extends At{constructor(e={}){super(e,As),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return rt(),BigInt(this.valueBlock.toString())}static fromBigInt(e){rt();const t=BigInt(e),s=new it,r=t.toString(16).replace(/^-/,""),n=new Uint8Array(_e.FromHex(r));if(t<0){const e=new Uint8Array(n.length+(128&n[0]?1:0));e[0]|=128;const r=BigInt(`0x${_e.ToHex(e)}`)+t,a=De.toUint8Array(_e.FromHex(r.toString(16)));a[0]|=128,s.write(a)}else 128&n[0]&&s.write(new Uint8Array([0])),s.write(n);return new Ut({valueHex:s.final()})}convertToDER(){const e=new Ut({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Ut({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}Ut=Ns,kt.Integer=Ut,Ns.NAME="INTEGER";class Es extends Ns{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}Lt=Es,kt.Enumerated=Lt,Es.NAME="ENUMERATED";class Cs extends(wt(vt)){constructor({valueDec:e=-1,isFirstSid:t=!1,...s}={}){super(s),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,s){if(!s)return t;const r=De.toUint8Array(e);if(!at(this,r,t,s))return-1;const n=r.subarray(t,t+s);this.valueHexView=new Uint8Array(s);for(let e=0;e<s&&(this.valueHexView[e]=127&n[e],this.blockLength++,0!=(128&n[e]));e++);const a=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)a[e]=this.valueHexView[e];return this.valueHexView=a,0!=(128&n[this.blockLength-1])?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Me(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){rt();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;const s=new Uint8Array(t.length/7);for(let e=0;e<s.length;e++)s[e]=parseInt(t.slice(7*e,7*e+7),2)+(e+1<s.length?128:0);this.fromBER(s.buffer,0,s.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const t=this.valueHexView,s=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)s[e]=128|t[e];return s[this.blockLength-1]=t[this.blockLength-1],s.buffer}const t=je(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",mt;const s=new Uint8Array(t.byteLength);if(!e){const e=new Uint8Array(t),r=t.byteLength-1;for(let t=0;t<r;t++)s[t]=128|e[t];s[r]=e[r]}return s}toString(){let e="";if(this.isHexOnly)e=_e.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}}}Cs.NAME="sidBlock";class Is extends vt{constructor({value:e="",...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,s){let r=t;for(;s>0;){const t=new Cs;if(r=t.fromBER(e,r,s),-1===r)return this.blockLength=0,this.error=t.error,r;0===this.value.length&&(t.isFirstSid=!0),this.blockLength+=t.blockLength,s-=t.blockLength,this.value.push(t)}return r}toBER(e){const t=[];for(let s=0;s<this.value.length;s++){const r=this.value[s].toBER(e);if(0===r.byteLength)return this.error=this.value[s].error,mt;t.push(r)}return nt(t)}fromString(e){this.value=[];let t=0,s=0,r="",n=!1;do{if(s=e.indexOf(".",t),r=-1===s?e.substring(t):e.substring(t,s),t=s+1,n){const e=this.value[0];let t=0;switch(e.valueDec){case 0:break;case 1:t=40;break;case 2:t=80;break;default:return void(this.value=[])}const s=parseInt(r,10);if(isNaN(s))return;e.valueDec=s+t,n=!1}else{const e=new Cs;if(r>Number.MAX_SAFE_INTEGER){rt();const t=BigInt(r);e.valueBigInt=t}else if(e.valueDec=parseInt(r,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,n=!0),this.value.push(e)}}while(-1!==s)}toString(){let e="",t=!1;for(let s=0;s<this.value.length;s++){t=this.value[s].isHexOnly;let r=this.value[s].toString();0!==s&&(e=`${e}.`),t?(r=`{${r}}`,this.value[s].isFirstSid?e=`2.{${r} - 80}`:e+=r):e+=r}return e}toJSON(){const 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}}Is.NAME="ObjectIdentifierValueBlock";class Bs extends At{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Is),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Rt=Bs,kt.ObjectIdentifier=Rt,Bs.NAME="OBJECT IDENTIFIER";class Vs extends(wt(yt)){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,s){if(0===s)return t;const r=De.toUint8Array(e);if(!at(this,r,t,s))return-1;const n=r.subarray(t,t+s);this.valueHexView=new Uint8Array(s);for(let e=0;e<s&&(this.valueHexView[e]=127&n[e],this.blockLength++,0!=(128&n[e]));e++);const a=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)a[e]=this.valueHexView[e];return this.valueHexView=a,0!=(128&n[this.blockLength-1])?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Me(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);const t=this.valueHexView,s=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)s[e]=128|t[e];return s[this.blockLength-1]=t[this.blockLength-1],s.buffer}const t=je(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",mt;const s=new Uint8Array(t.byteLength);if(!e){const e=new Uint8Array(t),r=t.byteLength-1;for(let t=0;t<r;t++)s[t]=128|e[t];s[r]=e[r]}return s.buffer}toString(){let e="";return e=this.isHexOnly?_e.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Vs.NAME="relativeSidBlock";class xs extends vt{constructor({value:e="",...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,s){let r=t;for(;s>0;){const t=new Vs;if(r=t.fromBER(e,r,s),-1===r)return this.blockLength=0,this.error=t.error,r;this.blockLength+=t.blockLength,s-=t.blockLength,this.value.push(t)}return r}toBER(e,t){const s=[];for(let t=0;t<this.value.length;t++){const r=this.value[t].toBER(e);if(0===r.byteLength)return this.error=this.value[t].error,mt;s.push(r)}return nt(s)}fromString(e){this.value=[];let t=0,s=0,r="";do{s=e.indexOf(".",t),r=-1===s?e.substring(t):e.substring(t,s),t=s+1;const n=new Vs;if(n.valueDec=parseInt(r,10),isNaN(n.valueDec))return!0;this.value.push(n)}while(-1!==s);return!0}toString(){let e="",t=!1;for(let s=0;s<this.value.length;s++){t=this.value[s].isHexOnly;let r=this.value[s].toString();0!==s&&(e=`${e}.`),t?(r=`{${r}}`,e+=r):e+=r}return e}toJSON(){const 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}}xs.NAME="RelativeObjectIdentifierValueBlock";class Ds extends At{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,xs),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}_t=Ds,kt.RelativeObjectIdentifier=_t,Ds.NAME="RelativeObjectIdentifier";class Os extends us{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}Ht=Os,kt.Sequence=Ht,Os.NAME="SEQUENCE";class Ts extends us{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}Kt=Ts,kt.Set=Kt,Ts.NAME="SET";class Ps extends(wt(vt)){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ht}toJSON(){return{...super.toJSON(),value:this.value}}}Ps.NAME="StringValueBlock";class Us extends Ps{}Us.NAME="SimpleStringValueBlock";class Ls extends Et{constructor({...e}={}){super(e,Us)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,De.toUint8Array(e))}fromString(e){const t=e.length,s=this.valueBlock.valueHexView=new Uint8Array(t);for(let r=0;r<t;r++)s[r]=e.charCodeAt(r);this.valueBlock.value=e}}Ls.NAME="SIMPLE STRING";class Rs extends Ls{fromBuffer(e){this.valueBlock.valueHexView=De.toUint8Array(e);try{this.valueBlock.value=_e.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=_e.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(_e.FromUtf8String(e)),this.valueBlock.value=e}}Rs.NAME="Utf8StringValueBlock";class _s extends Rs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}Mt=_s,kt.Utf8String=Mt,_s.NAME="UTF8String";class Hs extends Ls{fromBuffer(e){this.valueBlock.value=_e.ToUtf16String(e),this.valueBlock.valueHexView=De.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(_e.FromUtf16String(e))}}Hs.NAME="BmpStringValueBlock";class Ks extends Hs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}jt=Ks,kt.BmpString=jt,Ks.NAME="BMPString";class Ms extends Ls{fromBuffer(e){const t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),s=new Uint8Array(t);for(let e=0;e<s.length;e+=4)s[e]=s[e+3],s[e+1]=s[e+2],s[e+2]=0,s[e+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){const t=e.length,s=this.valueBlock.valueHexView=new Uint8Array(4*t);for(let r=0;r<t;r++){const t=je(e.charCodeAt(r),8),n=new Uint8Array(t);if(n.length>4)continue;const a=4-n.length;for(let e=n.length-1;e>=0;e--)s[4*r+e+a]=n[e]}this.valueBlock.value=e}}Ms.NAME="UniversalStringValueBlock";class js extends Ms{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}Jt=js,kt.UniversalString=Jt,js.NAME="UniversalString";class Js extends Ls{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}$t=Js,kt.NumericString=$t,Js.NAME="NumericString";class $s extends Ls{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}Ft=$s,kt.PrintableString=Ft,$s.NAME="PrintableString";class Fs extends Ls{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}qt=Fs,kt.TeletexString=qt,Fs.NAME="TeletexString";class qs extends Ls{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}Wt=qs,kt.VideotexString=Wt,qs.NAME="VideotexString";class Ws extends Ls{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}Gt=Ws,kt.IA5String=Gt,Ws.NAME="IA5String";class Gs extends Ls{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}zt=Gs,kt.GraphicString=zt,Gs.NAME="GraphicString";class zs extends Ls{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}Yt=zs,kt.VisibleString=Yt,zs.NAME="VisibleString";class Ys extends Ls{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}Qt=Ys,kt.GeneralString=Qt,Ys.NAME="GeneralString";class Qs extends Ls{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}Zt=Qs,kt.CharacterString=Zt,Qs.NAME="CharacterString";class Zs extends zs{constructor({value:e,valueDate:t,...s}={}){if(super(s),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 t=0;t<e.length;t++)this.valueBlock.valueHexView[t]=e.charCodeAt(t)}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,De.toUint8Array(e)))}toBuffer(){const e=this.toString(),t=new ArrayBuffer(e.length),s=new Uint8Array(t);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);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){const t=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/gi.exec(e);if(null===t)return void(this.error="Wrong input string for conversion");const s=parseInt(t[1],10);this.year=s>=50?1900+s:2e3+s,this.month=parseInt(t[2],10),this.day=parseInt(t[3],10),this.hour=parseInt(t[4],10),this.minute=parseInt(t[5],10),this.second=parseInt(t[6],10)}toString(e="iso"){if("iso"===e){const e=new Array(7);return e[0]=We(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=We(this.month,2),e[2]=We(this.day,2),e[3]=We(this.hour,2),e[4]=We(this.minute,2),e[5]=We(this.second,2),e[6]="Z",e.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}}}Xt=Zs,kt.UTCTime=Xt,Zs.NAME="UTCTime";class Xs extends Zs{constructor(e={}){var t;super(e),null!==(t=this.millisecond)&&void 0!==t||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){const 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,s=!1,r="",n="",a=0,i=0,o=0;if("Z"===e[e.length-1])r=e.substring(0,e.length-1),s=!0;else{const t=new Number(e[e.length-1]);if(isNaN(t.valueOf()))throw new Error("Wrong input string for conversion");r=e}if(s){if(-1!==r.indexOf("+"))throw new Error("Wrong input string for conversion");if(-1!==r.indexOf("-"))throw new Error("Wrong input string for conversion")}else{let e=1,t=r.indexOf("+"),s="";if(-1===t&&(t=r.indexOf("-"),e=-1),-1!==t){if(s=r.substring(t+1),r=r.substring(0,t),2!==s.length&&4!==s.length)throw new Error("Wrong input string for conversion");let n=parseInt(s.substring(0,2),10);if(isNaN(n.valueOf()))throw new Error("Wrong input string for conversion");if(i=e*n,4===s.length){if(n=parseInt(s.substring(2,4),10),isNaN(n.valueOf()))throw new Error("Wrong input string for conversion");o=e*n}}}let l=r.indexOf(".");if(-1===l&&(l=r.indexOf(",")),-1!==l){const e=new Number(`0${r.substring(l)}`);if(isNaN(e.valueOf()))throw new Error("Wrong input string for conversion");a=e.valueOf(),n=r.substring(0,l)}else n=r;switch(!0){case 8===n.length:if(t=/(\d{4})(\d{2})(\d{2})/gi,-1!==l)throw new Error("Wrong input string for conversion");break;case 10===n.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,-1!==l){let e=60*a;this.minute=Math.floor(e),e=60*(e-this.minute),this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 12===n.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==l){let e=60*a;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 14===n.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==l){const e=1e3*a;this.millisecond=Math.floor(e)}break;default:throw new Error("Wrong input string for conversion")}const c=t.exec(n);if(null===c)throw new Error("Wrong input string for conversion");for(let e=1;e<c.length;e++)switch(e){case 1:this.year=parseInt(c[e],10);break;case 2:this.month=parseInt(c[e],10);break;case 3:this.day=parseInt(c[e],10);break;case 4:this.hour=parseInt(c[e],10)+i;break;case 5:this.minute=parseInt(c[e],10)+o;break;case 6:this.second=parseInt(c[e],10);break;default:throw new Error("Wrong input string for conversion")}if(!1===s){const e=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=e.getUTCFullYear(),this.month=e.getUTCMonth(),this.day=e.getUTCDay(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds(),this.millisecond=e.getUTCMilliseconds()}}toString(e="iso"){if("iso"===e){const e=[];return e.push(We(this.year,4)),e.push(We(this.month,2)),e.push(We(this.day,2)),e.push(We(this.hour,2)),e.push(We(this.minute,2)),e.push(We(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(We(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}es=Xs,kt.GeneralizedTime=es,Xs.NAME="GeneralizedTime";class er extends _s{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}ts=er,kt.DATE=ts,er.NAME="DATE";class tr extends _s{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}ss=tr,kt.TimeOfDay=ss,tr.NAME="TimeOfDay";class sr extends _s{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}rs=sr,kt.DateTime=rs,sr.NAME="DateTime";class rr extends _s{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}ns=rr,kt.Duration=ns,rr.NAME="Duration";class nr extends _s{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}as=nr,kt.TIME=as,nr.NAME="TIME";class ar{constructor({name:e="",optional:t=!1}={}){this.name=e,this.optional=t}}class ir extends ar{constructor({value:e=[],...t}={}){super(t),this.value=e}}class or extends ar{constructor({value:e=new ar,local:t=!1,...s}={}){super(s),this.value=e,this.local=t}}class lr{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=De.toUint8Array(e)}constructor({data:e=ft}={}){this.dataView=De.toUint8Array(e)}fromBER(e,t,s){const r=t+s;return this.dataView=De.toUint8Array(e).subarray(t,r),r}toBER(e){return this.dataView.slice().buffer}}function cr(e,t,s){if(s instanceof ir){for(const r of s.value){if(cr(e,t,r).verified)return{verified:!0,result:e}}{const e={verified:!1,result:{error:"Wrong values for Choice type"}};return s.hasOwnProperty(ct)&&(e.name=s.name),e}}if(s instanceof ar)return s.hasOwnProperty(ct)&&(e[s.name]=t),{verified:!0,result:e};if(e instanceof Object==!1)return{verified:!1,result:{error:"Wrong root object"}};if(t instanceof Object==!1)return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(s instanceof Object==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if("idBlock"in s==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if("fromBER"in s.idBlock==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if("toBER"in s.idBlock==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const r=s.idBlock.toBER(!1);if(0===r.byteLength)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(-1===s.idBlock.fromBER(r,0,r.byteLength))return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(!1===s.idBlock.hasOwnProperty("tagClass"))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(s.idBlock.tagClass!==t.idBlock.tagClass)return{verified:!1,result:e};if(!1===s.idBlock.hasOwnProperty("tagNumber"))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(s.idBlock.tagNumber!==t.idBlock.tagNumber)return{verified:!1,result:e};if(!1===s.idBlock.hasOwnProperty("isConstructed"))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(s.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!("isHexOnly"in s.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(s.idBlock.isHexOnly!==t.idBlock.isHexOnly)return{verified:!1,result:e};if(s.idBlock.isHexOnly){if(ut in s.idBlock==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const r=s.idBlock.valueHexView,n=t.idBlock.valueHexView;if(r.length!==n.length)return{verified:!1,result:e};for(let t=0;t<r.length;t++)if(r[t]!==n[1])return{verified:!1,result:e}}if(s.name&&(s.name=s.name.replace(/^\s+|\s+$/g,ht),s.name&&(e[s.name]=t)),s instanceof kt.Constructed){let r=0,n={verified:!1,result:{error:"Unknown error"}},a=s.valueBlock.value.length;if(a>0&&s.valueBlock.value[0]instanceof or&&(a=t.valueBlock.value.length),0===a)return{verified:!0,result:e};if(0===t.valueBlock.value.length&&0!==s.valueBlock.value.length){let t=!0;for(let e=0;e<s.valueBlock.value.length;e++)t=t&&(s.valueBlock.value[e].optional||!1);return t?{verified:!0,result:e}:(s.name&&(s.name=s.name.replace(/^\s+|\s+$/g,ht),s.name&&delete e[s.name]),e.error="Inconsistent object length",{verified:!1,result:e})}for(let i=0;i<a;i++)if(i-r>=t.valueBlock.value.length){if(!1===s.valueBlock.value[i].optional){const t={verified:!1,result:e};return e.error="Inconsistent length between ASN.1 data and schema",s.name&&(s.name=s.name.replace(/^\s+|\s+$/g,ht),s.name&&(delete e[s.name],t.name=s.name)),t}}else if(s.valueBlock.value[0]instanceof or){if(n=cr(e,t.valueBlock.value[i],s.valueBlock.value[0].value),!1===n.verified){if(!s.valueBlock.value[0].optional)return s.name&&(s.name=s.name.replace(/^\s+|\s+$/g,ht),s.name&&delete e[s.name]),n;r++}if(ct in s.valueBlock.value[0]&&s.valueBlock.value[0].name.length>0){let r={};r="local"in s.valueBlock.value[0]&&s.valueBlock.value[0].local?t:e,void 0===r[s.valueBlock.value[0].name]&&(r[s.valueBlock.value[0].name]=[]),r[s.valueBlock.value[0].name].push(t.valueBlock.value[i])}}else if(n=cr(e,t.valueBlock.value[i-r],s.valueBlock.value[i]),!1===n.verified){if(!s.valueBlock.value[i].optional)return s.name&&(s.name=s.name.replace(/^\s+|\s+$/g,ht),s.name&&delete e[s.name]),n;r++}if(!1===n.verified){const t={verified:!1,result:e};return s.name&&(s.name=s.name.replace(/^\s+|\s+$/g,ht),s.name&&(delete e[s.name],t.name=s.name)),t}return{verified:!0,result:e}}if(s.primitiveSchema&&ut in t.valueBlock){const r=os(t.valueBlock.valueHexView);if(-1===r.offset){const t={verified:!1,result:r.result};return s.name&&(s.name=s.name.replace(/^\s+|\s+$/g,ht),s.name&&(delete e[s.name],t.name=s.name)),t}return cr(e,r.result,s.primitiveSchema)}return{verified:!0,result:e}}class ur{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){const t=e.length;this.length=t;for(let s=0;s<t;s++)this.view[s]=e.charCodeAt(s)}toString(e=0,t=this.view.length-e){let s="";(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++)s+=String.fromCharCode(this.view[r]);return s}fromHexString(e){const t=e.length;this.buffer=new ArrayBuffer(t>>1),this.view=new Uint8Array(this.buffer);const s=new Map;s.set("0",0),s.set("1",1),s.set("2",2),s.set("3",3),s.set("4",4),s.set("5",5),s.set("6",6),s.set("7",7),s.set("8",8),s.set("9",9),s.set("A",10),s.set("a",10),s.set("B",11),s.set("b",11),s.set("C",12),s.set("c",12),s.set("D",13),s.set("d",13),s.set("E",14),s.set("e",14),s.set("F",15),s.set("f",15);let r=0,n=0;for(let a=0;a<t;a++)a%2?(n|=s.get(e.charAt(a)),this.view[r]=n,r++):n=s.get(e.charAt(a))<<4}toHexString(e=0,t=this.view.length-e){let s="";(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++){const e=this.view[r].toString(16).toUpperCase();s=s+(1==e.length?"0":"")+e}return s}copy(e=0,t=this.length-e){if(!e&&!this.length)return new ur;if(e<0||e>this.length-1)throw new Error(`Wrong start position: ${e}`);return new ur({buffer:this._buffer.slice(e,e+t)})}slice(e=0,t=this.length){if(!e&&!this.length)return new ur;if(e<0||e>this.length-1)throw new Error(`Wrong start position: ${e}`);return new ur({buffer:this._buffer.slice(e,t)})}realloc(e){const t=new ArrayBuffer(e),s=new Uint8Array(t);e>this._view.length?s.set(this._view):s.set(new Uint8Array(this._buffer,0,e)),this._buffer=t,this._view=new Uint8Array(this._buffer)}append(e){const t=this.length,s=e.length,r=e._view.subarray();this.realloc(t+s),this._view.set(r,t)}insert(e,t=0,s=this.length-t){return!(t>this.length-1)&&(s>this.length-t&&(s=this.length-t),s>e.length&&(s=e.length),s==e.length?this._view.set(e._view,t):this._view.set(e._view.subarray(0,s),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,s,r){const{start:n,length:a,backward:i}=this.prepareFindParameters(t,s,r),o=e.length;if(o>a)return-1;const l=[];for(let t=0;t<o;t++)l.push(e.view[t]);for(let e=0;e<=a-o;e++){let t=!0;const s=i?n-o-e:n+e;for(let e=0;e<o;e++)if(this.view[e+s]!=l[e]){t=!1;break}if(t)return i?n-o-e:n+o+e}return-1}findFirstIn(e,t,s,r){const{start:n,length:a,backward:i}=this.prepareFindParameters(t,s,r),o={id:-1,position:i?0:n+a,length:0};for(let t=0;t<e.length;t++){const s=this.findPattern(e[t],n,a,i);if(-1!=s){let r=!1;const n=e[t].length;i?s-n>=o.position-o.length&&(r=!0):s-n<=o.position-o.length&&(r=!0),r&&(o.position=s,o.id=t,o.length=n)}}return o}findAllIn(e,t,s){let{start:r,length:n}=this.prepareFindParameters(t,s);const a=[];let i={id:-1,position:r};for(;;){const t=i.position;if(i=this.findFirstIn(e,i.position,n),-1==i.id)break;n-=i.position-t,a.push({id:i.id,position:i.position})}return a}findAllPatternIn(e,t,s){const{start:r,length:n}=this.prepareFindParameters(t,s),a=[],i=e.length;if(i>n)return-1;const o=Array.from(e.view);for(let e=0;e<=n-i;e++){let t=!0;const s=r+e;for(let e=0;e<i;e++)if(this.view[e+s]!=o[e]){t=!1;break}t&&(a.push(r+i+e),e+=i-1)}return a}findFirstNotIn(e,t,s,r){let{start:n,length:a,backward:i}=this.prepareFindParameters(t,s,r);const o={left:{id:-1,position:n},right:{id:-1,position:0},value:new ur};let l=a;for(;l>0;){if(o.right=this.findFirstIn(e,i?n-a+l:n+a-l,l,i),-1==o.right.id){a=l,i?n-=a:n=o.left.position,o.value=new ur({buffer:this._buffer.slice(n,n+a)});break}if(o.right.position!=(i?o.left.position-e[o.right.id].length:o.left.position+e[o.right.id].length)){i?(n=o.right.position+e[o.right.id].length,a=o.left.position-o.right.position-e[o.right.id].length):(n=o.left.position,a=o.right.position-o.left.position-e[o.right.id].length),o.value=new ur({buffer:this._buffer.slice(n,n+a)});break}o.left=o.right,l-=e[o.right.id].length}if(i){const e=o.right;o.right=o.left,o.left=e}return o}findAllNotIn(e,t,s){let{start:r,length:n}=this.prepareFindParameters(t,s);const a=[];let i={left:{id:-1,position:r},right:{id:-1,position:r},value:new ur};do{const t=i.right.position;i=this.findFirstNotIn(e,i.right.position,n),n-=i.right.position-t,a.push({left:{id:i.left.id,position:i.left.position},right:{id:i.right.id,position:i.right.position},value:i.value})}while(-1!=i.right.id);return a}findFirstSequence(e,t,s,r){let{start:n,length:a,backward:i}=this.prepareFindParameters(t,s,r);const o=this.skipNotPatterns(e,n,a,i);if(-1==o)return{position:-1,value:new ur};const l=this.skipPatterns(e,o,a-(i?n-o:o-n),i);i?(n=l,a=o-l):(n=o,a=l-o);return{position:l,value:new ur({buffer:this._buffer.slice(n,n+a)})}}findAllSequences(e,t,s){let{start:r,length:n}=this.prepareFindParameters(t,s);const a=[];let i={position:r,value:new ur};do{const t=i.position;i=this.findFirstSequence(e,i.position,n),-1!=i.position&&(n-=i.position-t,a.push({position:i.position,value:i.value}))}while(-1!=i.position);return a}findPairedPatterns(e,t,s,r){const n=[];if(e.isEqual(t))return n;const{start:a,length:i}=this.prepareFindParameters(s,r);let o=0;const l=this.findAllPatternIn(e,a,i);if(!Array.isArray(l)||0==l.length)return n;const c=this.findAllPatternIn(t,a,i);if(!Array.isArray(c)||0==c.length)return n;for(;o<l.length&&0!=c.length;)if(l[0]!=c[0]){if(l[o]>c[0])break;for(;l[o]<c[0]&&(o++,!(o>=l.length)););n.push({left:l[o-1],right:c[0]}),l.splice(o-1,1),c.splice(0,1),o=0}else n.push({left:l[0],right:c[0]}),l.splice(0,1),c.splice(0,1);return n.sort(((e,t)=>e.left-t.left)),n}findPairedArrays(e,t,s,r){const{start:n,length:a}=this.prepareFindParameters(s,r),i=[];let o=0;const l=this.findAllIn(e,n,a);if(0==l.length)return i;const c=this.findAllIn(t,n,a);if(0==c.length)return i;for(;o<l.length&&0!=c.length;)if(l[0].position!=c[0].position){if(l[o].position>c[0].position)break;for(;l[o].position<c[0].position&&(o++,!(o>=l.length)););i.push({left:l[o-1],right:c[0]}),l.splice(o-1,1),c.splice(0,1),o=0}else i.push({left:l[0],right:c[0]}),l.splice(0,1),c.splice(0,1);return i.sort(((e,t)=>e.left.position-t.left.position)),i}replacePattern(e,t,s,r,n=null){let a,i=[];const o={status:-1,searchPatternPositions:[],replacePatternPositions:[]},{start:l,length:c}=this.prepareFindParameters(s,r);if(null==n){if(i=this.findAllIn([e],l,c),0==i.length)return o}else i=n;o.searchPatternPositions.push(...Array.from(i,(e=>e.position)));const u=e.length-t.length,h=new ArrayBuffer(this.view.length-i.length*u),m=new Uint8Array(h);for(m.set(new Uint8Array(this.buffer,0,l)),a=0;a<i.length;a++){const s=0==a?l:i[a-1].position;m.set(new Uint8Array(this.buffer,s,i[a].position-e.length-s),s-a*u),m.set(t.view,i[a].position-e.length-a*u),o.replacePatternPositions.push(i[a].position-e.length-a*u)}return a--,m.set(new Uint8Array(this.buffer,i[a].position,this.length-i[a].position),i[a].position-e.length+t.length-a*u),this.buffer=h,this.view=new Uint8Array(this.buffer),o.status=1,o}skipPatterns(e,t,s,r){const{start:n,length:a,backward:i}=this.prepareFindParameters(t,s,r);let o=n;for(let t=0;t<e.length;t++){const s=e[t].length,r=i?o-s:o;let l=!0;for(let n=0;n<s;n++)if(this.view[n+r]!=e[t].view[n]){l=!1;break}if(l)if(t=-1,i){if(o-=s,o<=0)return o}else if(o+=s,o>=n+a)return o}return o}skipNotPatterns(e,t,s,r){const{start:n,length:a,backward:i}=this.prepareFindParameters(t,s,r);let o=-1;for(let t=0;t<a;t++){for(let s=0;s<e.length;s++){const r=e[s].length,a=i?n-t-r:n+t;let l=!0;for(let t=0;t<r;t++)if(this.view[t+a]!=e[s].view[t]){l=!1;break}if(l){o=i?n-t:n+t;break}}if(-1!=o)break}return o}prepareFindParameters(e=null,t=null,s=!1){return null===e&&(e=s?this.length:0),e>this.length&&(e=this.length),s?(null===t&&(t=e),t>e&&(t=e)):(null===t&&(t=this.length-e),t>this.length-e&&(t=this.length-e)),{start:e,length:t,backward:s}}}class hr{constructor(e={}){this._stream=new ur,this._length=0,this._start=0,this.backward=!1,this.appendBlock=0,this.prevLength=0,this.prevStart=0,this.stream="view"in e?new ur({view:e.view}):"buffer"in e?new ur({buffer:e.buffer}):"string"in e?new ur({string:e.string}):"hexstring"in e?new ur({hexstring:e.hexstring}):"stream"in e?e.stream.slice():new ur,"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){(null==t||t>this.length)&&(t=this.length);const s=this.stream.findPattern(e,this.start,this.length,this.backward);if(-1==s)return s;if(this.backward){if(s<this.start-e.length-t)return-1}else if(s>this.start+e.length+t)return-1;return this.start=s,s}findFirstIn(e,t=null){(null==t||t>this.length)&&(t=this.length);const s=this.stream.findFirstIn(e,this.start,this.length,this.backward);if(-1==s.id)return s;if(this.backward){if(s.position<this.start-e[s.id].length-t)return{id:-1,position:this.backward?0:this.start+this.length}}else if(s.position>this.start+e[s.id].length+t)return{id:-1,position:this.backward?0:this.start+this.length};return this.start=s.position,s}findAllIn(e){const t=this.backward?this.start-this.length:this.start;return this.stream.findAllIn(e,t,this.length)}findFirstNotIn(e,t=null){(null==t||t>this._length)&&(t=this._length);const s=this._stream.findFirstNotIn(e,this._start,this._length,this.backward);if(-1==s.left.id&&-1==s.right.id)return s;if(this.backward){if(-1!=s.right.id&&s.right.position<this._start-e[s.right.id].length-t)return{left:{id:-1,position:this._start},right:{id:-1,position:0},value:new ur}}else if(-1!=s.left.id&&s.left.position>this._start+e[s.left.id].length+t)return{left:{id:-1,position:this._start},right:{id:-1,position:0},value:new ur};return this.backward?-1==s.left.id?this.start=0:this.start=s.left.position:-1==s.right.id?this.start=this._start+this._length:this.start=s.right.position,s}findAllNotIn(e){const t=this.backward?this._start-this._length:this._start;return this._stream.findAllNotIn(e,t,this._length)}findFirstSequence(e,t=null,s=null){(null==t||t>this._length)&&(t=this._length),(null==s||s>t)&&(s=t);const r=this._stream.findFirstSequence(e,this._start,t,this.backward);if(0==r.value.length)return r;if(this.backward){if(r.position<this._start-r.value.length-s)return{position:-1,value:new ur}}else if(r.position>this._start+r.value.length+s)return{position:-1,value:new ur};return this.start=r.position,r}findAllSequences(e){const t=this.backward?this.start-this.length:this.start;return this.stream.findAllSequences(e,t,this.length)}findPairedPatterns(e,t,s=null){(null==s||s>this.length)&&(s=this.length);const r=this.backward?this.start-this.length:this.start,n=this.stream.findPairedPatterns(e,t,r,this.length);if(n.length)if(this.backward){if(n[0].right<this.start-t.length-s)return[]}else if(n[0].left>this.start+e.length+s)return[];return n}findPairedArrays(e,t,s=null){(null==s||s>this.length)&&(s=this.length);const r=this.backward?this.start-this.length:this.start,n=this.stream.findPairedArrays(e,t,r,this.length);if(n.length)if(this.backward){if(n[0].right.position<this.start-t[n[0].right.id].length-s)return[]}else if(n[0].left.position>this.start+e[n[0].left.id].length+s)return[];return n}replacePattern(e,t){const s=this.backward?this.start-this.length:this.start;return this.stream.replacePattern(e,t,s,this.length)}skipPatterns(e){const t=this.stream.skipPatterns(e,this.start,this.length,this.backward);return this.start=t,t}skipNotPatterns(e){const t=this.stream.skipNotPatterns(e,this.start,this.length,this.backward);return-1==t?-1:(this.start=t,t)}append(e){this.beforeAppend(e.length),this._stream.view.set(e.view,this._start),this._length+=2*e.length,this.start=this._start+e.length,this.prevLength-=2*e.length}appendView(e){this.beforeAppend(e.length),this._stream.view.set(e,this._start),this._length+=2*e.length,this.start=this._start+e.length,this.prevLength-=2*e.length}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);const t=new Uint16Array([e]),s=new Uint8Array(t.buffer);this.stream.view[this._start]=s[1],this._stream.view[this._start+1]=s[0],this._length+=4,this.start=this._start+2,this.prevLength-=4}appendUint24(e){this.beforeAppend(3);const t=new Uint32Array([e]),s=new Uint8Array(t.buffer);this._stream.view[this._start]=s[2],this._stream.view[this._start+1]=s[1],this._stream.view[this._start+2]=s[0],this._length+=6,this.start=this._start+3,this.prevLength-=6}appendUint32(e){this.beforeAppend(4);const t=new Uint32Array([e]),s=new Uint8Array(t.buffer);this._stream.view[this._start]=s[3],this._stream.view[this._start+1]=s[2],this._stream.view[this._start+2]=s[1],this._stream.view[this._start+3]=s[0],this._length+=8,this.start=this._start+4,this.prevLength-=8}appendInt16(e){this.beforeAppend(2);const t=new Int16Array([e]),s=new Uint8Array(t.buffer);this._stream.view[this._start]=s[1],this._stream.view[this._start+1]=s[0],this._length+=4,this.start=this._start+2,this.prevLength-=4}appendInt32(e){this.beforeAppend(4);const t=new Int32Array([e]),s=new Uint8Array(t.buffer);this._stream.view[this._start]=s[3],this._stream.view[this._start+1]=s[2],this._stream.view[this._start+2]=s[1],this._stream.view[this._start+3]=s[0],this._length+=8,this.start=this._start+4,this.prevLength-=8}getBlock(e,t=!0){if(this._length<=0)return new Uint8Array(0);let s;if(this._length<e&&(e=this._length),this.backward){const t=this._stream.view.subarray(this._length-e,this._length);s=new Uint8Array(e);for(let r=0;r<e;r++)s[e-1-r]=t[r]}else s=this._stream.view.subarray(this._start,this._start+e);return t&&(this.start+=this.backward?-1*e:e),s}getUint16(e=!0){const t=this.getBlock(2,e);return t.length<2?0:t[0]<<8|t[1]}getInt16(e=!0){const t=this.getUint16(e),s=32768;return t&s?-(s-(t^s)):t}getUint24(e=!0){const t=this.getBlock(4,e);return t.length<3?0:t[0]<<16|t[1]<<8|t[2]}getUint32(e=!0){const t=this.getBlock(4,e);return t.length<4?0:16777216*t[0]+(t[1]<<16)+(t[2]<<8)+t[3]}getInt32(e=!0){const t=this.getUint32(e),s=2147483648;return t&s?-(s-(t^s)):t}beforeAppend(e){this._start+e>this._stream.length&&(e>this.appendBlock&&(this.appendBlock=e+hr.APPEND_BLOCK),this._stream.realloc(this._stream.length+this.appendBlock))}}function mr(e,...t){if(!function(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function fr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}hr.APPEND_BLOCK=1e3;
|
|
63
|
+
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
64
|
+
const dr=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),gr=(e,t)=>e<<32-t|e>>>t,pr=(e,t)=>e<<t|e>>>32-t>>>0;function wr(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),mr(e),e}new Uint8Array(new Uint32Array([287454020]).buffer)[0];class yr{clone(){return this._cloneInto()}}function vr(e){const t=t=>e().update(wr(t)).digest(),s=e();return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=()=>e(),t}const br=(e,t,s)=>e&t^~e&s,Sr=(e,t,s)=>e&t^e&s^t&s;class kr extends yr{constructor(e,t,s,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=dr(this.buffer)}update(e){fr(this);const{view:t,buffer:s,blockLen:r}=this,n=(e=wr(e)).length;for(let a=0;a<n;){const i=Math.min(r-this.pos,n-a);if(i!==r)s.set(e.subarray(a,a+i),this.pos),this.pos+=i,a+=i,this.pos===r&&(this.process(t,0),this.pos=0);else{const t=dr(e);for(;r<=n-a;a+=r)this.process(t,a)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){fr(this),function(e,t){mr(e);const s=t.outputLen;if(e.length<s)throw new Error(`digestInto() expects output buffer of length at least ${s}`)}(e,this),this.finished=!0;const{buffer:t,view:s,blockLen:r,isLE:n}=this;let{pos:a}=this;t[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>r-a&&(this.process(s,0),a=0);for(let e=a;e<r;e++)t[e]=0;!function(e,t,s,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,s,r);const n=BigInt(32),a=BigInt(4294967295),i=Number(s>>n&a),o=Number(s&a),l=r?4:0,c=r?0:4;e.setUint32(t+l,i,r),e.setUint32(t+c,o,r)}(s,r-8,BigInt(8*this.length),n),this.process(s,0);const i=dr(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=o/4,c=this.get();if(l>c.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<l;e++)i.setUint32(4*e,c[e],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:s,length:r,finished:n,destroyed:a,pos:i}=this;return e.length=r,e.pos=i,e.finished=n,e.destroyed=a,r%t&&e.buffer.set(s),e}}const Ar=new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),Nr=new Uint32Array(80);class Er extends kr{constructor(){super(64,20,8,!1),this.A=0|Ar[0],this.B=0|Ar[1],this.C=0|Ar[2],this.D=0|Ar[3],this.E=0|Ar[4]}get(){const{A:e,B:t,C:s,D:r,E:n}=this;return[e,t,s,r,n]}set(e,t,s,r,n){this.A=0|e,this.B=0|t,this.C=0|s,this.D=0|r,this.E=0|n}process(e,t){for(let s=0;s<16;s++,t+=4)Nr[s]=e.getUint32(t,!1);for(let e=16;e<80;e++)Nr[e]=pr(Nr[e-3]^Nr[e-8]^Nr[e-14]^Nr[e-16],1);let{A:s,B:r,C:n,D:a,E:i}=this;for(let e=0;e<80;e++){let t,o;e<20?(t=br(r,n,a),o=1518500249):e<40?(t=r^n^a,o=1859775393):e<60?(t=Sr(r,n,a),o=2400959708):(t=r^n^a,o=3395469782);const l=pr(s,5)+t+i+o+Nr[e]|0;i=a,a=n,n=pr(r,30),r=s,s=l}s=s+this.A|0,r=r+this.B|0,n=n+this.C|0,a=a+this.D|0,i=i+this.E|0,this.set(s,r,n,a,i)}roundClean(){Nr.fill(0)}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0)}}const Cr=vr((()=>new Er)),Ir=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]),Br=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Vr=new Uint32Array(64);class xr extends kr{constructor(){super(64,32,8,!1),this.A=0|Br[0],this.B=0|Br[1],this.C=0|Br[2],this.D=0|Br[3],this.E=0|Br[4],this.F=0|Br[5],this.G=0|Br[6],this.H=0|Br[7]}get(){const{A:e,B:t,C:s,D:r,E:n,F:a,G:i,H:o}=this;return[e,t,s,r,n,a,i,o]}set(e,t,s,r,n,a,i,o){this.A=0|e,this.B=0|t,this.C=0|s,this.D=0|r,this.E=0|n,this.F=0|a,this.G=0|i,this.H=0|o}process(e,t){for(let s=0;s<16;s++,t+=4)Vr[s]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Vr[e-15],s=Vr[e-2],r=gr(t,7)^gr(t,18)^t>>>3,n=gr(s,17)^gr(s,19)^s>>>10;Vr[e]=n+Vr[e-7]+r+Vr[e-16]|0}let{A:s,B:r,C:n,D:a,E:i,F:o,G:l,H:c}=this;for(let e=0;e<64;e++){const t=c+(gr(i,6)^gr(i,11)^gr(i,25))+br(i,o,l)+Ir[e]+Vr[e]|0,u=(gr(s,2)^gr(s,13)^gr(s,22))+Sr(s,r,n)|0;c=l,l=o,o=i,i=a+t|0,a=n,n=r,r=s,s=t+u|0}s=s+this.A|0,r=r+this.B|0,n=n+this.C|0,a=a+this.D|0,i=i+this.E|0,o=o+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(s,r,n,a,i,o,l,c)}roundClean(){Vr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Dr=vr((()=>new xr)),Or=BigInt(2**32-1),Tr=BigInt(32);function Pr(e,t=!1){return t?{h:Number(e&Or),l:Number(e>>Tr&Or)}:{h:0|Number(e>>Tr&Or),l:0|Number(e&Or)}}const Ur={fromBig:Pr,split:function(e,t=!1){let s=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let n=0;n<e.length;n++){const{h:a,l:i}=Pr(e[n],t);[s[n],r[n]]=[a,i]}return[s,r]},toBig:(e,t)=>BigInt(e>>>0)<<Tr|BigInt(t>>>0),shrSH:(e,t,s)=>e>>>s,shrSL:(e,t,s)=>e<<32-s|t>>>s,rotrSH:(e,t,s)=>e>>>s|t<<32-s,rotrSL:(e,t,s)=>e<<32-s|t>>>s,rotrBH:(e,t,s)=>e<<64-s|t>>>s-32,rotrBL:(e,t,s)=>e>>>s-32|t<<64-s,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:(e,t,s)=>e<<s|t>>>32-s,rotlSL:(e,t,s)=>t<<s|e>>>32-s,rotlBH:(e,t,s)=>t<<s-32|e>>>64-s,rotlBL:(e,t,s)=>e<<s-32|t>>>64-s,add:function(e,t,s,r){const n=(t>>>0)+(r>>>0);return{h:e+s+(n/2**32|0)|0,l:0|n}},add3L:(e,t,s)=>(e>>>0)+(t>>>0)+(s>>>0),add3H:(e,t,s,r)=>t+s+r+(e/2**32|0)|0,add4L:(e,t,s,r)=>(e>>>0)+(t>>>0)+(s>>>0)+(r>>>0),add4H:(e,t,s,r,n)=>t+s+r+n+(e/2**32|0)|0,add5H:(e,t,s,r,n,a)=>t+s+r+n+a+(e/2**32|0)|0,add5L:(e,t,s,r,n)=>(e>>>0)+(t>>>0)+(s>>>0)+(r>>>0)+(n>>>0)},[Lr,Rr]=(()=>Ur.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((e=>BigInt(e)))))(),_r=new Uint32Array(80),Hr=new Uint32Array(80);class Kr extends kr{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(){const{Ah:e,Al:t,Bh:s,Bl:r,Ch:n,Cl:a,Dh:i,Dl:o,Eh:l,El:c,Fh:u,Fl:h,Gh:m,Gl:f,Hh:d,Hl:g}=this;return[e,t,s,r,n,a,i,o,l,c,u,h,m,f,d,g]}set(e,t,s,r,n,a,i,o,l,c,u,h,m,f,d,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|s,this.Bl=0|r,this.Ch=0|n,this.Cl=0|a,this.Dh=0|i,this.Dl=0|o,this.Eh=0|l,this.El=0|c,this.Fh=0|u,this.Fl=0|h,this.Gh=0|m,this.Gl=0|f,this.Hh=0|d,this.Hl=0|g}process(e,t){for(let s=0;s<16;s++,t+=4)_r[s]=e.getUint32(t),Hr[s]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|_r[e-15],s=0|Hr[e-15],r=Ur.rotrSH(t,s,1)^Ur.rotrSH(t,s,8)^Ur.shrSH(t,s,7),n=Ur.rotrSL(t,s,1)^Ur.rotrSL(t,s,8)^Ur.shrSL(t,s,7),a=0|_r[e-2],i=0|Hr[e-2],o=Ur.rotrSH(a,i,19)^Ur.rotrBH(a,i,61)^Ur.shrSH(a,i,6),l=Ur.rotrSL(a,i,19)^Ur.rotrBL(a,i,61)^Ur.shrSL(a,i,6),c=Ur.add4L(n,l,Hr[e-7],Hr[e-16]),u=Ur.add4H(c,r,o,_r[e-7],_r[e-16]);_r[e]=0|u,Hr[e]=0|c}let{Ah:s,Al:r,Bh:n,Bl:a,Ch:i,Cl:o,Dh:l,Dl:c,Eh:u,El:h,Fh:m,Fl:f,Gh:d,Gl:g,Hh:p,Hl:w}=this;for(let e=0;e<80;e++){const t=Ur.rotrSH(u,h,14)^Ur.rotrSH(u,h,18)^Ur.rotrBH(u,h,41),y=Ur.rotrSL(u,h,14)^Ur.rotrSL(u,h,18)^Ur.rotrBL(u,h,41),v=u&m^~u&d,b=h&f^~h&g,S=Ur.add5L(w,y,b,Rr[e],Hr[e]),k=Ur.add5H(S,p,t,v,Lr[e],_r[e]),A=0|S,N=Ur.rotrSH(s,r,28)^Ur.rotrBH(s,r,34)^Ur.rotrBH(s,r,39),E=Ur.rotrSL(s,r,28)^Ur.rotrBL(s,r,34)^Ur.rotrBL(s,r,39),C=s&n^s&i^n&i,I=r&a^r&o^a&o;p=0|d,w=0|g,d=0|m,g=0|f,m=0|u,f=0|h,({h:u,l:h}=Ur.add(0|l,0|c,0|k,0|A)),l=0|i,c=0|o,i=0|n,o=0|a,n=0|s,a=0|r;const B=Ur.add3L(A,E,I);s=Ur.add3H(B,k,N,C),r=0|B}({h:s,l:r}=Ur.add(0|this.Ah,0|this.Al,0|s,0|r)),({h:n,l:a}=Ur.add(0|this.Bh,0|this.Bl,0|n,0|a)),({h:i,l:o}=Ur.add(0|this.Ch,0|this.Cl,0|i,0|o)),({h:l,l:c}=Ur.add(0|this.Dh,0|this.Dl,0|l,0|c)),({h:u,l:h}=Ur.add(0|this.Eh,0|this.El,0|u,0|h)),({h:m,l:f}=Ur.add(0|this.Fh,0|this.Fl,0|m,0|f)),({h:d,l:g}=Ur.add(0|this.Gh,0|this.Gl,0|d,0|g)),({h:p,l:w}=Ur.add(0|this.Hh,0|this.Hl,0|p,0|w)),this.set(s,r,n,a,i,o,l,c,u,h,m,f,d,g,p,w)}roundClean(){_r.fill(0),Hr.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)}}class Mr extends Kr{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}}const jr=vr((()=>new Kr)),Jr=vr((()=>new Mr)),$r=new ArrayBuffer(0),Fr="";class qr extends TypeError{constructor(){super(...arguments),this.name=qr.NAME}static isType(e,t){if("string"==typeof t){if("Array"===t&&Array.isArray(e))return!0;if("ArrayBuffer"===t&&e instanceof ArrayBuffer)return!0;if("ArrayBufferView"===t&&ArrayBuffer.isView(e))return!0;if(typeof e===t)return!0}else if(e instanceof t)return!0;return!1}static assert(e,t,...s){for(const t of s)if(this.isType(e,t))return;const r=s.map((e=>e instanceof Function&&"name"in e?e.name:`${e}`));throw new qr(`Parameter '${t}' is not of type ${r.length>1?`(${r.join(" or ")})`:r[0]}`)}}qr.NAME="ArgumentError";class Wr extends TypeError{static assert(...e){let t,s,r=null;"string"==typeof e[0]?(r=e[0],t=e[1],s=e.slice(2)):(t=e[0],s=e.slice(1)),qr.assert(t,"parameters","object");for(const e of s){const s=t[e];if(null==s)throw new Wr(e,r)}}static assertEmpty(e,t,s){if(null==e)throw new Wr(t,s)}constructor(e,t=null,s){super(),this.name=Wr.NAME,this.field=e,t&&(this.target=t),this.message=s||`Absent mandatory parameter '${e}' ${t?` in '${t}'`:Fr}`}}Wr.NAME="ParameterError";class Gr 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(-1===e.offset)throw new Gr(`Error during parsing of ASN.1 data. Data is not correct for '${t}'.`)}constructor(e){super(e),this.name="AsnError"}}class zr{static blockName(){return this.CLASS_NAME}static fromBER(e){const t=ls(e);Gr.assert(t,this.name);try{return new this({schema:t.result})}catch(e){throw new Gr(`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 _e.ToString(t.toBER(),e)}}function Yr(e){let t=!1,s=Fr;const r=e.trim();for(let e=0;e<r.length;e++)32===r.charCodeAt(e)?!1===t&&(t=!0):(t&&(s+=" ",t=!1),s+=r[e]);return s.toLowerCase()}zr.CLASS_NAME="PkiObject";const Qr="type",Zr="value";class Xr extends zr{constructor(e={}){super(),this.type=He(e,Qr,Xr.defaultValues(Qr)),this.value=He(e,Zr,Xr.defaultValues(Zr)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Qr:return Fr;case Zr:return{};default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.type||Fr}),new ar({name:t.value||Fr})]})}fromSchema(e){st(e,[Qr,"typeValue"]);const t=cr(e,e,Xr.schema({names:{type:Qr,value:"typeValue"}}));Gr.assertSchema(t,this.className),this.type=t.result.type.valueBlock.toString(),this.value=t.result.typeValue}toSchema(){return new Os({value:[new Bs({value:this.type}),this.value]})}toJSON(){const e={type:this.type};return 0!==Object.keys(this.value).length?e.value=this.value.toJSON():e.value=this.value,e}isEqual(e){const t=[_s.blockName(),Ks.blockName(),js.blockName(),Js.blockName(),$s.blockName(),Fs.blockName(),qs.blockName(),Ws.blockName(),Gs.blockName(),zs.blockName(),Ys.blockName(),Qs.blockName()];if(e instanceof ArrayBuffer)return De.isEqual(this.value.valueBeforeDecodeView,e);if(e.constructor.blockName()===Xr.blockName()){if(this.type!==e.type)return!1;const s=[!1,!1],r=this.value.constructor.blockName();for(const n of t)r===n&&(s[0]=!0),e.value.constructor.blockName()===n&&(s[1]=!0);if(s[0]!==s[1])return!1;if(s[0]&&s[1]){const t=Yr(this.value.valueBlock.value),s=Yr(e.value.valueBlock.value);if(0!==t.localeCompare(s))return!1}else if(!De.isEqual(this.value.valueBeforeDecodeView,e.value.valueBeforeDecodeView))return!1;return!0}return!1}}Xr.CLASS_NAME="AttributeTypeAndValue";const en="typesAndValues",tn="valueBeforeDecode";class sn extends zr{constructor(e={}){super(),this.typesAndValues=He(e,en,sn.defaultValues(en)),this.valueBeforeDecode=He(e,tn,sn.defaultValues(tn)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case en:return[];case tn:return $r;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case en:return 0===t.length;case tn:return 0===t.byteLength;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new or({name:t.repeatedSequence||Fr,value:new Ts({value:[new or({name:t.repeatedSet||Fr,value:Xr.schema(t.typeAndValue||{})})]})})]})}fromSchema(e){st(e,["RDN",en]);const t=cr(e,e,sn.schema({names:{blockName:"RDN",repeatedSet:en}}));Gr.assertSchema(t,this.className),en in t.result&&(this.typesAndValues=Array.from(t.result.typesAndValues,(e=>new Xr({schema:e})))),this.valueBeforeDecode=t.result.RDN.valueBeforeDecodeView.slice().buffer}toSchema(){if(0===this.valueBeforeDecode.byteLength)return new Os({value:[new Ts({value:Array.from(this.typesAndValues,(e=>e.toSchema()))})]});const e=ls(this.valueBeforeDecode);if(Gr.assert(e,"RelativeDistinguishedNames"),!(e.result instanceof Os))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 sn){if(this.typesAndValues.length!==e.typesAndValues.length)return!1;for(const[t,s]of this.typesAndValues.entries())if(!1===s.isEqual(e.typesAndValues[t]))return!1;return!0}return e instanceof ArrayBuffer&&qe(this.valueBeforeDecode,e)}}sn.CLASS_NAME="RelativeDistinguishedNames";const rn="type",nn="value";function an(e={},t=!1){const s=He(e,"names",{});return new Os({optional:t,value:[new us({optional:!0,idBlock:{tagClass:2,tagNumber:1},name:s.country_name||Fr,value:[new ir({value:[new Js,new $s]})]}),new us({optional:!0,idBlock:{tagClass:2,tagNumber:2},name:s.administration_domain_name||Fr,value:[new ir({value:[new Js,new $s]})]}),new is({optional:!0,idBlock:{tagClass:3,tagNumber:0},name:s.network_address||Fr,isHexOnly:!0}),new is({optional:!0,idBlock:{tagClass:3,tagNumber:1},name:s.terminal_identifier||Fr,isHexOnly:!0}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:2},name:s.private_domain_name||Fr,value:[new ir({value:[new Js,new $s]})]}),new is({optional:!0,idBlock:{tagClass:3,tagNumber:3},name:s.organization_name||Fr,isHexOnly:!0}),new is({optional:!0,name:s.numeric_user_identifier||Fr,idBlock:{tagClass:3,tagNumber:4},isHexOnly:!0}),new us({optional:!0,name:s.personal_name||Fr,idBlock:{tagClass:3,tagNumber:5},value:[new is({idBlock:{tagClass:3,tagNumber:0},isHexOnly:!0}),new is({optional:!0,idBlock:{tagClass:3,tagNumber:1},isHexOnly:!0}),new is({optional:!0,idBlock:{tagClass:3,tagNumber:2},isHexOnly:!0}),new is({optional:!0,idBlock:{tagClass:3,tagNumber:3},isHexOnly:!0})]}),new us({optional:!0,name:s.organizational_unit_names||Fr,idBlock:{tagClass:3,tagNumber:6},value:[new or({value:new $s})]})]})}function on(e=!1){return new Os({optional:e,value:[new $s,new $s]})}function ln(e=!1){return new Ts({optional:e,value:[new is({optional:!0,idBlock:{tagClass:3,tagNumber:0},isHexOnly:!0}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new ar]})]})}class cn extends zr{constructor(e={}){super(),this.type=He(e,rn,cn.defaultValues(rn)),this.value=He(e,nn,cn.defaultValues(nn)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case rn:return 9;case nn:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case rn:return t===cn.defaultValues(e);case nn:return 0===Object.keys(t).length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new ir({value:[new us({idBlock:{tagClass:3,tagNumber:0},name:t.blockName||Fr,value:[new Bs,new us({idBlock:{tagClass:3,tagNumber:0},value:[new ar]})]}),new is({name:t.blockName||Fr,idBlock:{tagClass:3,tagNumber:1}}),new is({name:t.blockName||Fr,idBlock:{tagClass:3,tagNumber:2}}),new us({idBlock:{tagClass:3,tagNumber:3},name:t.blockName||Fr,value:[an(t.builtInStandardAttributes||{},!1),on(!0),ln(!0)]}),new us({idBlock:{tagClass:3,tagNumber:4},name:t.blockName||Fr,value:[sn.schema(t.directoryName||{})]}),new us({idBlock:{tagClass:3,tagNumber:5},name:t.blockName||Fr,value:[new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new ir({value:[new Fs,new $s,new js,new _s,new Ks]})]}),new us({idBlock:{tagClass:3,tagNumber:1},value:[new ir({value:[new Fs,new $s,new js,new _s,new Ks]})]})]}),new is({name:t.blockName||Fr,idBlock:{tagClass:3,tagNumber:6}}),new is({name:t.blockName||Fr,idBlock:{tagClass:3,tagNumber:7}}),new is({name:t.blockName||Fr,idBlock:{tagClass:3,tagNumber:8}})]})}fromSchema(e){st(e,["blockName","otherName","rfc822Name","dNSName","x400Address","directoryName","ediPartyName","uniformResourceIdentifier","iPAddress","registeredID"]);const t=cr(e,e,cn.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(Gr.assertSchema(t,this.className),this.type=t.result.blockName.idBlock.tagNumber,this.type){case 0:case 3:this.value=t.result.blockName;break;case 1:case 2:case 6:{const e=t.result.blockName;e.idBlock.tagClass=1,e.idBlock.tagNumber=22;const s=ls(e.toBER(!1));Gr.assert(s,"GeneralName value"),this.value=s.result.valueBlock.value}break;case 4:this.value=new sn({schema:t.result.directoryName});break;case 5:this.value=t.result.ediPartyName;break;case 7:this.value=new ws({valueHex:t.result.blockName.valueBlock.valueHex});break;case 8:{const e=t.result.blockName;e.idBlock.tagClass=1,e.idBlock.tagNumber=6;const s=ls(e.toBER(!1));Gr.assert(s,"GeneralName registeredID"),this.value=s.result.valueBlock.toString()}}}toSchema(){switch(this.type){case 0:case 3:case 5:return new us({idBlock:{tagClass:3,tagNumber:this.type},value:[this.value]});case 1:case 2:case 6:{const e=new Ws({value:this.value});return e.idBlock.tagClass=3,e.idBlock.tagNumber=this.type,e}case 4:return new us({idBlock:{tagClass:3,tagNumber:4},value:[this.value.toSchema()]});case 7:{const e=this.value;return e.idBlock.tagClass=3,e.idBlock.tagNumber=this.type,e}case 8:{const e=new Bs({value:this.value});return e.idBlock.tagClass=3,e.idBlock.tagNumber=this.type,e}default:return cn.schema()}}toJSON(){const e={type:this.type,value:Fr};if("string"==typeof this.value)e.value=this.value;else try{e.value=this.value.toJSON()}catch{}return e}}cn.CLASS_NAME="GeneralName";const un="accessMethod",hn="accessLocation",mn=[un,hn];class fn extends zr{constructor(e={}){super(),this.accessMethod=He(e,un,fn.defaultValues(un)),this.accessLocation=He(e,hn,fn.defaultValues(hn)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case un:return Fr;case hn:return new cn;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.accessMethod||Fr}),cn.schema(t.accessLocation||{})]})}fromSchema(e){st(e,mn);const t=cr(e,e,fn.schema({names:{accessMethod:un,accessLocation:{names:{blockName:hn}}}}));Gr.assertSchema(t,this.className),this.accessMethod=t.result.accessMethod.valueBlock.toString(),this.accessLocation=new cn({schema:t.result.accessLocation})}toSchema(){return new Os({value:[new Bs({value:this.accessMethod}),this.accessLocation.toSchema()]})}toJSON(){return{accessMethod:this.accessMethod,accessLocation:this.accessLocation.toJSON()}}}fn.CLASS_NAME="AccessDescription";const dn="seconds",gn="millis",pn="micros";class wn extends zr{constructor(e={}){super(),dn in e&&(this.seconds=He(e,dn,wn.defaultValues(dn))),gn in e&&(this.millis=He(e,gn,wn.defaultValues(gn))),pn in e&&(this.micros=He(e,pn,wn.defaultValues(pn))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case dn:case gn:case pn:return 0;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case dn:case gn:case pn:return t===wn.defaultValues(e);default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,optional:!0,value:[new Ns({optional:!0,name:t.seconds||Fr}),new is({name:t.millis||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:0}}),new is({name:t.micros||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:1}})]})}fromSchema(e){st(e,[dn,gn,pn]);const t=cr(e,e,wn.schema({names:{seconds:dn,millis:gn,micros:pn}}));if(Gr.assertSchema(t,this.className),"seconds"in t.result&&(this.seconds=t.result.seconds.valueBlock.valueDec),"millis"in t.result){const e=new Ns({valueHex:t.result.millis.valueBlock.valueHex});this.millis=e.valueBlock.valueDec}if("micros"in t.result){const e=new Ns({valueHex:t.result.micros.valueBlock.valueHex});this.micros=e.valueBlock.valueDec}}toSchema(){const e=[];if(void 0!==this.seconds&&e.push(new Ns({value:this.seconds})),void 0!==this.millis){const t=new Ns({value:this.millis});e.push(new is({idBlock:{tagClass:3,tagNumber:0},valueHex:t.valueBlock.valueHexView}))}if(void 0!==this.micros){const t=new Ns({value:this.micros});e.push(new is({idBlock:{tagClass:3,tagNumber:1},valueHex:t.valueBlock.valueHexView}))}return new Os({value:e})}toJSON(){const e={};return void 0!==this.seconds&&(e.seconds=this.seconds),void 0!==this.millis&&(e.millis=this.millis),void 0!==this.micros&&(e.micros=this.micros),e}}wn.CLASS_NAME="Accuracy";const yn="algorithmId",vn="algorithmParams",bn="algorithm",Sn="params",kn=[bn,Sn];class An extends zr{constructor(e={}){super(),this.algorithmId=He(e,yn,An.defaultValues(yn)),vn in e&&(this.algorithmParams=He(e,vn,An.defaultValues(vn))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case yn:return Fr;case vn:return new ar;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case yn:return t===Fr;case vn:return t instanceof ar;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,optional:t.optional||!1,value:[new Bs({name:t.algorithmIdentifier||Fr}),new ar({name:t.algorithmParams||Fr,optional:!0})]})}fromSchema(e){st(e,kn);const t=cr(e,e,An.schema({names:{algorithmIdentifier:bn,algorithmParams:Sn}}));Gr.assertSchema(t,this.className),this.algorithmId=t.result.algorithm.valueBlock.toString(),Sn in t.result&&(this.algorithmParams=t.result.params)}toSchema(){const e=[];return e.push(new Bs({value:this.algorithmId})),!this.algorithmParams||this.algorithmParams instanceof ar||e.push(this.algorithmParams),new Os({value:e})}toJSON(){const e={algorithmId:this.algorithmId};return!this.algorithmParams||this.algorithmParams instanceof ar||(e.algorithmParams=this.algorithmParams.toJSON()),e}isEqual(e){return e instanceof An&&(this.algorithmId===e.algorithmId&&(this.algorithmParams?!!e.algorithmParams&&JSON.stringify(this.algorithmParams)===JSON.stringify(e.algorithmParams):!e.algorithmParams))}}An.CLASS_NAME="AlgorithmIdentifier";const Nn="altNames",En=[Nn];class Cn extends zr{constructor(e={}){super(),this.altNames=He(e,Nn,Cn.defaultValues(Nn)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===Nn?[]:super.defaultValues(e)}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new or({name:t.altNames||Fr,value:cn.schema()})]})}fromSchema(e){st(e,En);const t=cr(e,e,Cn.schema({names:{altNames:Nn}}));Gr.assertSchema(t,this.className),Nn in t.result&&(this.altNames=Array.from(t.result.altNames,(e=>new cn({schema:e}))))}toSchema(){return new Os({value:Array.from(this.altNames,(e=>e.toSchema()))})}toJSON(){return{altNames:Array.from(this.altNames,(e=>e.toJSON()))}}}Cn.CLASS_NAME="AltName";const In="type",Bn="values",Vn=[In,Bn];class xn extends zr{constructor(e={}){super(),this.type=He(e,In,xn.defaultValues(In)),this.values=He(e,Bn,xn.defaultValues(Bn)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case In:return Fr;case Bn:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case In:return t===Fr;case Bn:return 0===t.length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.type||Fr}),new Ts({name:t.setName||Fr,value:[new or({name:t.values||Fr,value:new ar})]})]})}fromSchema(e){st(e,Vn);const t=cr(e,e,xn.schema({names:{type:In,values:Bn}}));Gr.assertSchema(t,this.className),this.type=t.result.type.valueBlock.toString(),this.values=t.result.values}toSchema(){return new Os({value:[new Bs({value:this.type}),new Ts({value:this.values})]})}toJSON(){return{type:this.type,values:Array.from(this.values,(e=>e.toJSON()))}}}xn.CLASS_NAME="Attribute";const Dn="notBeforeTime",On="notAfterTime",Tn=[Dn,On];class Pn extends zr{constructor(e={}){super(),this.notBeforeTime=He(e,Dn,Pn.defaultValues(Dn)),this.notAfterTime=He(e,On,Pn.defaultValues(On)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Dn:case On:return new Date(0,0,0);default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Xs({name:t.notBeforeTime||Fr}),new Xs({name:t.notAfterTime||Fr})]})}fromSchema(e){st(e,Tn);const t=cr(e,e,Pn.schema({names:{notBeforeTime:Dn,notAfterTime:On}}));Gr.assertSchema(t,this.className),this.notBeforeTime=t.result.notBeforeTime.toDate(),this.notAfterTime=t.result.notAfterTime.toDate()}toSchema(){return new Os({value:[new Xs({valueDate:this.notBeforeTime}),new Xs({valueDate:this.notAfterTime})]})}toJSON(){return{notBeforeTime:this.notBeforeTime,notAfterTime:this.notAfterTime}}}Pn.CLASS_NAME="AttCertValidityPeriod";const Un="names",Ln="generalNames";class Rn extends zr{constructor(e={}){super(),this.names=He(e,Un,Rn.defaultValues(Un)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return"names"===e?[]:super.defaultValues(e)}static schema(e={},t=!1){const s=He(e,Un,{});return new Os({optional:t,name:s.blockName||Fr,value:[new or({name:s.generalNames||Fr,value:cn.schema()})]})}fromSchema(e){st(e,[Un,Ln]);const t=cr(e,e,Rn.schema({names:{blockName:Un,generalNames:Ln}}));Gr.assertSchema(t,this.className),this.names=Array.from(t.result.generalNames,(e=>new cn({schema:e})))}toSchema(){return new Os({value:Array.from(this.names,(e=>e.toSchema()))})}toJSON(){return{names:Array.from(this.names,(e=>e.toJSON()))}}}Rn.CLASS_NAME="GeneralNames";const _n="2.5.29.17",Hn="2.5.29.18",Kn="2.5.29.19",Mn="2.5.29.28",jn="2.5.29.29",Jn="2.5.29.30",$n="2.5.29.31",Fn="2.5.29.46",qn="2.5.29.32",Wn="2.5.29.32.0",Gn="2.5.29.33",zn="2.5.29.35",Yn="2.5.29.36",Qn="1.3.6.1.5.5.7.1.1",Zn="1.2.840.113549.1.7.1",Xn="1.2.840.113549.1.7.2",ea="1.2.840.113549.1.7.3",ta="1.2.840.113549.1.7.6",sa="1.2.840.113549.1.9.22.1",ra="1.2.840.113549.1.9.22.3",na="1.2.840.113549.1.9.23.1",aa="1.3.6.1.5.5.7.48.1.1",ia="keyIdentifier",oa="authorityCertIssuer",la="authorityCertSerialNumber",ca=[ia,oa,la];class ua extends zr{constructor(e={}){super(),ia in e&&(this.keyIdentifier=He(e,ia,ua.defaultValues(ia))),oa in e&&(this.authorityCertIssuer=He(e,oa,ua.defaultValues(oa))),la in e&&(this.authorityCertSerialNumber=He(e,la,ua.defaultValues(la))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case ia:return new ws;case oa:return[];case la:return new Ns;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new is({name:t.keyIdentifier||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:0}}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new or({name:t.authorityCertIssuer||Fr,value:cn.schema()})]}),new is({name:t.authorityCertSerialNumber||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:2}})]})}fromSchema(e){st(e,ca);const t=cr(e,e,ua.schema({names:{keyIdentifier:ia,authorityCertIssuer:oa,authorityCertSerialNumber:la}}));Gr.assertSchema(t,this.className),ia in t.result&&(this.keyIdentifier=new ws({valueHex:t.result.keyIdentifier.valueBlock.valueHex})),oa in t.result&&(this.authorityCertIssuer=Array.from(t.result.authorityCertIssuer,(e=>new cn({schema:e})))),la in t.result&&(this.authorityCertSerialNumber=new Ns({valueHex:t.result.authorityCertSerialNumber.valueBlock.valueHex}))}toSchema(){const e=[];return this.keyIdentifier&&e.push(new is({idBlock:{tagClass:3,tagNumber:0},valueHex:this.keyIdentifier.valueBlock.valueHexView})),this.authorityCertIssuer&&e.push(new us({idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.authorityCertIssuer,(e=>e.toSchema()))})),this.authorityCertSerialNumber&&e.push(new is({idBlock:{tagClass:3,tagNumber:2},valueHex:this.authorityCertSerialNumber.valueBlock.valueHexView})),new Os({value:e})}toJSON(){const e={};return this.keyIdentifier&&(e.keyIdentifier=this.keyIdentifier.toJSON()),this.authorityCertIssuer&&(e.authorityCertIssuer=Array.from(this.authorityCertIssuer,(e=>e.toJSON()))),this.authorityCertSerialNumber&&(e.authorityCertSerialNumber=this.authorityCertSerialNumber.toJSON()),e}}ua.CLASS_NAME="AuthorityKeyIdentifier";const ha="pathLenConstraint",ma="cA";class fa extends zr{constructor(e={}){super(),this.cA=He(e,ma,!1),ha in e&&(this.pathLenConstraint=He(e,ha,0)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e!==ma&&super.defaultValues(e)}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new gs({optional:!0,name:t.cA||Fr}),new Ns({optional:!0,name:t.pathLenConstraint||Fr})]})}fromSchema(e){st(e,[ma,ha]);const t=cr(e,e,fa.schema({names:{cA:ma,pathLenConstraint:ha}}));Gr.assertSchema(t,this.className),ma in t.result&&(this.cA=t.result.cA.valueBlock.value),ha in t.result&&(t.result.pathLenConstraint.valueBlock.isHexOnly?this.pathLenConstraint=t.result.pathLenConstraint:this.pathLenConstraint=t.result.pathLenConstraint.valueBlock.valueDec)}toSchema(){const e=[];return this.cA!==fa.defaultValues(ma)&&e.push(new gs({value:this.cA})),ha in this&&(this.pathLenConstraint instanceof Ns?e.push(this.pathLenConstraint):e.push(new Ns({value:this.pathLenConstraint}))),new Os({value:e})}toJSON(){const e={};return this.cA!==fa.defaultValues(ma)&&(e.cA=this.cA),ha in this&&(this.pathLenConstraint instanceof Ns?e.pathLenConstraint=this.pathLenConstraint.toJSON():e.pathLenConstraint=this.pathLenConstraint),e}}fa.CLASS_NAME="BasicConstraints";const da="certificateIndex",ga="keyIndex";class pa extends zr{constructor(e={}){super(),this.certificateIndex=He(e,da,pa.defaultValues(da)),this.keyIndex=He(e,ga,pa.defaultValues(ga)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case da:case ga:return 0;default:return super.defaultValues(e)}}static schema(){return new Ns}fromSchema(e){if(e.constructor.blockName()!==Ns.blockName())throw new Error("Object's schema was not verified against input data for CAVersion");let t=e.valueBlock.valueHex.slice(0);const s=new Uint8Array(t);switch(!0){case t.byteLength<4:{const e=new ArrayBuffer(4);new Uint8Array(e).set(s,4-t.byteLength),t=e.slice(0)}break;case t.byteLength>4:{const e=new ArrayBuffer(4);new Uint8Array(e).set(s.slice(0,4)),t=e.slice(0)}}const r=t.slice(0,2),n=new Uint8Array(r);let a=n[0];n[0]=n[1],n[1]=a;const i=new Uint16Array(r);this.keyIndex=i[0];const o=t.slice(2),l=new Uint8Array(o);a=l[0],l[0]=l[1],l[1]=a;const c=new Uint16Array(o);this.certificateIndex=c[0]}toSchema(){const e=new ArrayBuffer(2);new Uint16Array(e)[0]=this.certificateIndex;const t=new Uint8Array(e);let s=t[0];t[0]=t[1],t[1]=s;const r=new ArrayBuffer(2);new Uint16Array(r)[0]=this.keyIndex;const n=new Uint8Array(r);return s=n[0],n[0]=n[1],n[1]=s,new Ns({valueHex:Je(r,e)})}toJSON(){return{certificateIndex:this.certificateIndex,keyIndex:this.keyIndex}}}pa.CLASS_NAME="CAVersion";const wa="policyQualifierId",ya="qualifier",va=[wa,ya];class ba extends zr{constructor(e={}){super(),this.policyQualifierId=He(e,wa,ba.defaultValues(wa)),this.qualifier=He(e,ya,ba.defaultValues(ya)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case wa:return Fr;case ya:return new ar;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.policyQualifierId||Fr}),new ar({name:t.qualifier||Fr})]})}fromSchema(e){st(e,va);const t=cr(e,e,ba.schema({names:{policyQualifierId:wa,qualifier:ya}}));Gr.assertSchema(t,this.className),this.policyQualifierId=t.result.policyQualifierId.valueBlock.toString(),this.qualifier=t.result.qualifier}toSchema(){return new Os({value:[new Bs({value:this.policyQualifierId}),this.qualifier]})}toJSON(){return{policyQualifierId:this.policyQualifierId,qualifier:this.qualifier.toJSON()}}}ba.CLASS_NAME="PolicyQualifierInfo";const Sa="policyIdentifier",ka="policyQualifiers",Aa=[Sa,ka];class Na extends zr{constructor(e={}){super(),this.policyIdentifier=He(e,Sa,Na.defaultValues(Sa)),ka in e&&(this.policyQualifiers=He(e,ka,Na.defaultValues(ka))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Sa:return Fr;case ka:return[];default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.policyIdentifier||Fr}),new Os({optional:!0,value:[new or({name:t.policyQualifiers||Fr,value:ba.schema()})]})]})}fromSchema(e){st(e,Aa);const t=cr(e,e,Na.schema({names:{policyIdentifier:Sa,policyQualifiers:ka}}));Gr.assertSchema(t,this.className),this.policyIdentifier=t.result.policyIdentifier.valueBlock.toString(),ka in t.result&&(this.policyQualifiers=Array.from(t.result.policyQualifiers,(e=>new ba({schema:e}))))}toSchema(){const e=[];return e.push(new Bs({value:this.policyIdentifier})),this.policyQualifiers&&e.push(new Os({value:Array.from(this.policyQualifiers,(e=>e.toSchema()))})),new Os({value:e})}toJSON(){const e={policyIdentifier:this.policyIdentifier};return this.policyQualifiers&&(e.policyQualifiers=Array.from(this.policyQualifiers,(e=>e.toJSON()))),e}}Na.CLASS_NAME="PolicyInformation";const Ea="certificatePolicies",Ca=[Ea];class Ia extends zr{constructor(e={}){super(),this.certificatePolicies=He(e,Ea,Ia.defaultValues(Ea)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===Ea?[]:super.defaultValues(e)}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new or({name:t.certificatePolicies||Fr,value:Na.schema()})]})}fromSchema(e){st(e,Ca);const t=cr(e,e,Ia.schema({names:{certificatePolicies:Ea}}));Gr.assertSchema(t,this.className),this.certificatePolicies=Array.from(t.result.certificatePolicies,(e=>new Na({schema:e})))}toSchema(){return new Os({value:Array.from(this.certificatePolicies,(e=>e.toSchema()))})}toJSON(){return{certificatePolicies:Array.from(this.certificatePolicies,(e=>e.toJSON()))}}}Ia.CLASS_NAME="CertificatePolicies";const Ba="templateID",Va="templateMajorVersion",xa="templateMinorVersion",Da=[Ba,Va,xa];class Oa extends zr{constructor(e={}){super(),this.templateID=He(e,Ba,Oa.defaultValues(Ba)),Va in e&&(this.templateMajorVersion=He(e,Va,Oa.defaultValues(Va))),xa in e&&(this.templateMinorVersion=He(e,xa,Oa.defaultValues(xa))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Ba:return Fr;case Va:case xa:return 0;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.templateID||Fr}),new Ns({name:t.templateMajorVersion||Fr,optional:!0}),new Ns({name:t.templateMinorVersion||Fr,optional:!0})]})}fromSchema(e){st(e,Da);const t=cr(e,e,Oa.schema({names:{templateID:Ba,templateMajorVersion:Va,templateMinorVersion:xa}}));Gr.assertSchema(t,this.className),this.templateID=t.result.templateID.valueBlock.toString(),Va in t.result&&(this.templateMajorVersion=t.result.templateMajorVersion.valueBlock.valueDec),xa in t.result&&(this.templateMinorVersion=t.result.templateMinorVersion.valueBlock.valueDec)}toSchema(){const e=[];return e.push(new Bs({value:this.templateID})),Va in this&&e.push(new Ns({value:this.templateMajorVersion})),xa in this&&e.push(new Ns({value:this.templateMinorVersion})),new Os({value:e})}toJSON(){const e={templateID:this.templateID};return Va in this&&(e.templateMajorVersion=this.templateMajorVersion),xa in this&&(e.templateMinorVersion=this.templateMinorVersion),e}}const Ta="distributionPoint",Pa="distributionPointNames",Ua="reasons",La="cRLIssuer",Ra="cRLIssuerNames",_a=[Ta,Pa,Ua,La,Ra];class Ha extends zr{constructor(e={}){super(),Ta in e&&(this.distributionPoint=He(e,Ta,Ha.defaultValues(Ta))),Ua in e&&(this.reasons=He(e,Ua,Ha.defaultValues(Ua))),La in e&&(this.cRLIssuer=He(e,La,Ha.defaultValues(La))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Ta:return[];case Ua:return new vs;case La:return[];default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new ir({value:[new us({name:t.distributionPoint||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new or({name:t.distributionPointNames||Fr,value:cn.schema()})]}),new us({name:t.distributionPoint||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:1},value:sn.schema().valueBlock.value})]})]}),new is({name:t.reasons||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:1}}),new us({name:t.cRLIssuer||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:2},value:[new or({name:t.cRLIssuerNames||Fr,value:cn.schema()})]})]})}fromSchema(e){st(e,_a);const t=cr(e,e,Ha.schema({names:{distributionPoint:Ta,distributionPointNames:Pa,reasons:Ua,cRLIssuer:La,cRLIssuerNames:Ra}}));Gr.assertSchema(t,this.className),Ta in t.result&&(0===t.result.distributionPoint.idBlock.tagNumber&&(this.distributionPoint=Array.from(t.result.distributionPointNames,(e=>new cn({schema:e})))),1===t.result.distributionPoint.idBlock.tagNumber&&(this.distributionPoint=new sn({schema:new Os({value:t.result.distributionPoint.valueBlock.value})}))),Ua in t.result&&(this.reasons=new vs({valueHex:t.result.reasons.valueBlock.valueHex})),La in t.result&&(this.cRLIssuer=Array.from(t.result.cRLIssuerNames,(e=>new cn({schema:e}))))}toSchema(){const e=[];if(this.distributionPoint){let t;t=this.distributionPoint instanceof Array?new us({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.distributionPoint,(e=>e.toSchema()))}):new us({idBlock:{tagClass:3,tagNumber:1},value:[this.distributionPoint.toSchema()]}),e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:[t]}))}return this.reasons&&e.push(new is({idBlock:{tagClass:3,tagNumber:1},valueHex:this.reasons.valueBlock.valueHexView})),this.cRLIssuer&&e.push(new us({idBlock:{tagClass:3,tagNumber:2},value:Array.from(this.cRLIssuer,(e=>e.toSchema()))})),new Os({value:e})}toJSON(){const e={};return this.distributionPoint&&(this.distributionPoint instanceof Array?e.distributionPoint=Array.from(this.distributionPoint,(e=>e.toJSON())):e.distributionPoint=this.distributionPoint.toJSON()),this.reasons&&(e.reasons=this.reasons.toJSON()),this.cRLIssuer&&(e.cRLIssuer=Array.from(this.cRLIssuer,(e=>e.toJSON()))),e}}Ha.CLASS_NAME="DistributionPoint";const Ka="distributionPoints",Ma=[Ka];class ja extends zr{constructor(e={}){super(),this.distributionPoints=He(e,Ka,ja.defaultValues(Ka)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===Ka?[]:super.defaultValues(e)}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new or({name:t.distributionPoints||Fr,value:Ha.schema()})]})}fromSchema(e){st(e,Ma);const t=cr(e,e,ja.schema({names:{distributionPoints:Ka}}));Gr.assertSchema(t,this.className),this.distributionPoints=Array.from(t.result.distributionPoints,(e=>new Ha({schema:e})))}toSchema(){return new Os({value:Array.from(this.distributionPoints,(e=>e.toSchema()))})}toJSON(){return{distributionPoints:Array.from(this.distributionPoints,(e=>e.toJSON()))}}}ja.CLASS_NAME="CRLDistributionPoints";const Ja="keyPurposes",$a=[Ja];class Fa extends zr{constructor(e={}){super(),this.keyPurposes=He(e,Ja,Fa.defaultValues(Ja)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===Ja?[]:super.defaultValues(e)}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new or({name:t.keyPurposes||Fr,value:new Bs})]})}fromSchema(e){st(e,$a);const t=cr(e,e,Fa.schema({names:{keyPurposes:Ja}}));Gr.assertSchema(t,this.className),this.keyPurposes=Array.from(t.result.keyPurposes,(e=>e.valueBlock.toString()))}toSchema(){return new Os({value:Array.from(this.keyPurposes,(e=>new Bs({value:e})))})}toJSON(){return{keyPurposes:Array.from(this.keyPurposes)}}}Fa.CLASS_NAME="ExtKeyUsage";const qa="accessDescriptions";class Wa extends zr{constructor(e={}){super(),this.accessDescriptions=He(e,qa,Wa.defaultValues(qa)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===qa?[]:super.defaultValues(e)}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new or({name:t.accessDescriptions||Fr,value:fn.schema()})]})}fromSchema(e){st(e,[qa]);const t=cr(e,e,Wa.schema({names:{accessDescriptions:qa}}));Gr.assertSchema(t,this.className),this.accessDescriptions=Array.from(t.result.accessDescriptions,(e=>new fn({schema:e})))}toSchema(){return new Os({value:Array.from(this.accessDescriptions,(e=>e.toSchema()))})}toJSON(){return{accessDescriptions:Array.from(this.accessDescriptions,(e=>e.toJSON()))}}}Wa.CLASS_NAME="InfoAccess";const Ga="distributionPoint",za="distributionPointNames",Ya="onlyContainsUserCerts",Qa="onlyContainsCACerts",Za="onlySomeReasons",Xa="indirectCRL",ei="onlyContainsAttributeCerts",ti=[Ga,za,Ya,Qa,Za,Xa,ei];class si extends zr{constructor(e={}){super(),Ga in e&&(this.distributionPoint=He(e,Ga,si.defaultValues(Ga))),this.onlyContainsUserCerts=He(e,Ya,si.defaultValues(Ya)),this.onlyContainsCACerts=He(e,Qa,si.defaultValues(Qa)),Za in e&&(this.onlySomeReasons=He(e,Za,si.defaultValues(Za))),this.indirectCRL=He(e,Xa,si.defaultValues(Xa)),this.onlyContainsAttributeCerts=He(e,ei,si.defaultValues(ei)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Ga:return[];case Ya:case Qa:return!1;case Za:return 0;case Xa:case ei:return!1;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new ir({value:[new us({name:t.distributionPoint||Fr,idBlock:{tagClass:3,tagNumber:0},value:[new or({name:t.distributionPointNames||Fr,value:cn.schema()})]}),new us({name:t.distributionPoint||Fr,idBlock:{tagClass:3,tagNumber:1},value:sn.schema().valueBlock.value})]})]}),new is({name:t.onlyContainsUserCerts||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:1}}),new is({name:t.onlyContainsCACerts||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:2}}),new is({name:t.onlySomeReasons||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:3}}),new is({name:t.indirectCRL||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:4}}),new is({name:t.onlyContainsAttributeCerts||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:5}})]})}fromSchema(e){st(e,ti);const t=cr(e,e,si.schema({names:{distributionPoint:Ga,distributionPointNames:za,onlyContainsUserCerts:Ya,onlyContainsCACerts:Qa,onlySomeReasons:Za,indirectCRL:Xa,onlyContainsAttributeCerts:ei}}));if(Gr.assertSchema(t,this.className),Ga in t.result)switch(!0){case 0===t.result.distributionPoint.idBlock.tagNumber:this.distributionPoint=Array.from(t.result.distributionPointNames,(e=>new cn({schema:e})));break;case 1===t.result.distributionPoint.idBlock.tagNumber:this.distributionPoint=new sn({schema:new Os({value:t.result.distributionPoint.valueBlock.value})});break;default:throw new Error("Unknown tagNumber for distributionPoint: {$asn1.result.distributionPoint.idBlock.tagNumber}")}if(Ya in t.result){const e=new Uint8Array(t.result.onlyContainsUserCerts.valueBlock.valueHex);this.onlyContainsUserCerts=0!==e[0]}if(Qa in t.result){const e=new Uint8Array(t.result.onlyContainsCACerts.valueBlock.valueHex);this.onlyContainsCACerts=0!==e[0]}if(Za in t.result){const e=new Uint8Array(t.result.onlySomeReasons.valueBlock.valueHex);this.onlySomeReasons=e[0]}if(Xa in t.result){const e=new Uint8Array(t.result.indirectCRL.valueBlock.valueHex);this.indirectCRL=0!==e[0]}if(ei in t.result){const e=new Uint8Array(t.result.onlyContainsAttributeCerts.valueBlock.valueHex);this.onlyContainsAttributeCerts=0!==e[0]}}toSchema(){const e=[];if(this.distributionPoint){let t;this.distributionPoint instanceof Array?t=new us({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.distributionPoint,(e=>e.toSchema()))}):(t=this.distributionPoint.toSchema(),t.idBlock.tagClass=3,t.idBlock.tagNumber=1),e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:[t]}))}if(this.onlyContainsUserCerts!==si.defaultValues(Ya)&&e.push(new is({idBlock:{tagClass:3,tagNumber:1},valueHex:new Uint8Array([255]).buffer})),this.onlyContainsCACerts!==si.defaultValues(Qa)&&e.push(new is({idBlock:{tagClass:3,tagNumber:2},valueHex:new Uint8Array([255]).buffer})),void 0!==this.onlySomeReasons){const t=new ArrayBuffer(1);new Uint8Array(t)[0]=this.onlySomeReasons,e.push(new is({idBlock:{tagClass:3,tagNumber:3},valueHex:t}))}return this.indirectCRL!==si.defaultValues(Xa)&&e.push(new is({idBlock:{tagClass:3,tagNumber:4},valueHex:new Uint8Array([255]).buffer})),this.onlyContainsAttributeCerts!==si.defaultValues(ei)&&e.push(new is({idBlock:{tagClass:3,tagNumber:5},valueHex:new Uint8Array([255]).buffer})),new Os({value:e})}toJSON(){const e={};return this.distributionPoint&&(this.distributionPoint instanceof Array?e.distributionPoint=Array.from(this.distributionPoint,(e=>e.toJSON())):e.distributionPoint=this.distributionPoint.toJSON()),this.onlyContainsUserCerts!==si.defaultValues(Ya)&&(e.onlyContainsUserCerts=this.onlyContainsUserCerts),this.onlyContainsCACerts!==si.defaultValues(Qa)&&(e.onlyContainsCACerts=this.onlyContainsCACerts),Za in this&&(e.onlySomeReasons=this.onlySomeReasons),this.indirectCRL!==si.defaultValues(Xa)&&(e.indirectCRL=this.indirectCRL),this.onlyContainsAttributeCerts!==si.defaultValues(ei)&&(e.onlyContainsAttributeCerts=this.onlyContainsAttributeCerts),e}}si.CLASS_NAME="IssuingDistributionPoint";const ri="base",ni="minimum",ai="maximum",ii=[ri,ni,ai];class oi extends zr{constructor(e={}){super(),this.base=He(e,ri,oi.defaultValues(ri)),this.minimum=He(e,ni,oi.defaultValues(ni)),ai in e&&(this.maximum=He(e,ai,oi.defaultValues(ai))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case ri:return new cn;case ni:case ai:return 0;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[cn.schema(t.base||{}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new Ns({name:t.minimum||Fr})]}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new Ns({name:t.maximum||Fr})]})]})}fromSchema(e){st(e,ii);const t=cr(e,e,oi.schema({names:{base:{names:{blockName:ri}},minimum:ni,maximum:ai}}));Gr.assertSchema(t,this.className),this.base=new cn({schema:t.result.base}),ni in t.result&&(t.result.minimum.valueBlock.isHexOnly?this.minimum=t.result.minimum:this.minimum=t.result.minimum.valueBlock.valueDec),ai in t.result&&(t.result.maximum.valueBlock.isHexOnly?this.maximum=t.result.maximum:this.maximum=t.result.maximum.valueBlock.valueDec)}toSchema(){const e=[];if(e.push(this.base.toSchema()),0!==this.minimum){let t=0;t=this.minimum instanceof Ns?this.minimum:new Ns({value:this.minimum}),e.push(new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[t]}))}if(ai in this){let t=0;t=this.maximum instanceof Ns?this.maximum:new Ns({value:this.maximum}),e.push(new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[t]}))}return new Os({value:e})}toJSON(){const e={base:this.base.toJSON()};return 0!==this.minimum&&("number"==typeof this.minimum?e.minimum=this.minimum:e.minimum=this.minimum.toJSON()),void 0!==this.maximum&&("number"==typeof this.maximum?e.maximum=this.maximum:e.maximum=this.maximum.toJSON()),e}}oi.CLASS_NAME="GeneralSubtree";const li="permittedSubtrees",ci="excludedSubtrees",ui=[li,ci];class hi extends zr{constructor(e={}){super(),li in e&&(this.permittedSubtrees=He(e,li,hi.defaultValues(li))),ci in e&&(this.excludedSubtrees=He(e,ci,hi.defaultValues(ci))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case li:case ci:return[];default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new or({name:t.permittedSubtrees||Fr,value:oi.schema()})]}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new or({name:t.excludedSubtrees||Fr,value:oi.schema()})]})]})}fromSchema(e){st(e,ui);const t=cr(e,e,hi.schema({names:{permittedSubtrees:li,excludedSubtrees:ci}}));Gr.assertSchema(t,this.className),li in t.result&&(this.permittedSubtrees=Array.from(t.result.permittedSubtrees,(e=>new oi({schema:e})))),ci in t.result&&(this.excludedSubtrees=Array.from(t.result.excludedSubtrees,(e=>new oi({schema:e}))))}toSchema(){const e=[];return this.permittedSubtrees&&e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.permittedSubtrees,(e=>e.toSchema()))})),this.excludedSubtrees&&e.push(new us({idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.excludedSubtrees,(e=>e.toSchema()))})),new Os({value:e})}toJSON(){const e={};return this.permittedSubtrees&&(e.permittedSubtrees=Array.from(this.permittedSubtrees,(e=>e.toJSON()))),this.excludedSubtrees&&(e.excludedSubtrees=Array.from(this.excludedSubtrees,(e=>e.toJSON()))),e}}hi.CLASS_NAME="NameConstraints";const mi="requireExplicitPolicy",fi="inhibitPolicyMapping",di=[mi,fi];class gi extends zr{constructor(e={}){super(),mi in e&&(this.requireExplicitPolicy=He(e,mi,gi.defaultValues(mi))),fi in e&&(this.inhibitPolicyMapping=He(e,fi,gi.defaultValues(fi))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case mi:case fi:return 0;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new is({name:t.requireExplicitPolicy||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:0}}),new is({name:t.inhibitPolicyMapping||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:1}})]})}fromSchema(e){st(e,di);const t=cr(e,e,gi.schema({names:{requireExplicitPolicy:mi,inhibitPolicyMapping:fi}}));if(Gr.assertSchema(t,this.className),mi in t.result){const e=t.result.requireExplicitPolicy;e.idBlock.tagClass=1,e.idBlock.tagNumber=2;const s=ls(e.toBER(!1));Gr.assert(s,"Integer"),this.requireExplicitPolicy=s.result.valueBlock.valueDec}if(fi in t.result){const e=t.result.inhibitPolicyMapping;e.idBlock.tagClass=1,e.idBlock.tagNumber=2;const s=ls(e.toBER(!1));Gr.assert(s,"Integer"),this.inhibitPolicyMapping=s.result.valueBlock.valueDec}}toSchema(){const e=[];if(mi in this){const t=new Ns({value:this.requireExplicitPolicy});t.idBlock.tagClass=3,t.idBlock.tagNumber=0,e.push(t)}if(fi in this){const t=new Ns({value:this.inhibitPolicyMapping});t.idBlock.tagClass=3,t.idBlock.tagNumber=1,e.push(t)}return new Os({value:e})}toJSON(){const e={};return mi in this&&(e.requireExplicitPolicy=this.requireExplicitPolicy),fi in this&&(e.inhibitPolicyMapping=this.inhibitPolicyMapping),e}}gi.CLASS_NAME="PolicyConstraints";const pi="issuerDomainPolicy",wi="subjectDomainPolicy",yi=[pi,wi];class vi extends zr{constructor(e={}){super(),this.issuerDomainPolicy=He(e,pi,vi.defaultValues(pi)),this.subjectDomainPolicy=He(e,wi,vi.defaultValues(wi)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case pi:case wi:return Fr;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.issuerDomainPolicy||Fr}),new Bs({name:t.subjectDomainPolicy||Fr})]})}fromSchema(e){st(e,yi);const t=cr(e,e,vi.schema({names:{issuerDomainPolicy:pi,subjectDomainPolicy:wi}}));Gr.assertSchema(t,this.className),this.issuerDomainPolicy=t.result.issuerDomainPolicy.valueBlock.toString(),this.subjectDomainPolicy=t.result.subjectDomainPolicy.valueBlock.toString()}toSchema(){return new Os({value:[new Bs({value:this.issuerDomainPolicy}),new Bs({value:this.subjectDomainPolicy})]})}toJSON(){return{issuerDomainPolicy:this.issuerDomainPolicy,subjectDomainPolicy:this.subjectDomainPolicy}}}vi.CLASS_NAME="PolicyMapping";const bi="mappings",Si=[bi];class ki extends zr{constructor(e={}){super(),this.mappings=He(e,bi,ki.defaultValues(bi)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===bi?[]:super.defaultValues(e)}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new or({name:t.mappings||Fr,value:vi.schema()})]})}fromSchema(e){st(e,Si);const t=cr(e,e,ki.schema({names:{mappings:bi}}));Gr.assertSchema(t,this.className),this.mappings=Array.from(t.result.mappings,(e=>new vi({schema:e})))}toSchema(){return new Os({value:Array.from(this.mappings,(e=>e.toSchema()))})}toJSON(){return{mappings:Array.from(this.mappings,(e=>e.toJSON()))}}}ki.CLASS_NAME="PolicyMappings";const Ai="notBefore",Ni="notAfter",Ei=[Ai,Ni];class Ci extends zr{constructor(e={}){super(),Ai in e&&(this.notBefore=He(e,Ai,Ci.defaultValues(Ai))),Ni in e&&(this.notAfter=He(e,Ni,Ci.defaultValues(Ni))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Ai:case Ni:return new Date;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new is({name:t.notBefore||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:0}}),new is({name:t.notAfter||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:1}})]})}fromSchema(e){st(e,Ei);const t=cr(e,e,Ci.schema({names:{notBefore:Ai,notAfter:Ni}}));if(Gr.assertSchema(t,this.className),Ai in t.result){const e=new Xs;e.fromBuffer(t.result.notBefore.valueBlock.valueHex),this.notBefore=e.toDate()}if(Ni in t.result){const e=new Xs({valueHex:t.result.notAfter.valueBlock.valueHex});e.fromBuffer(t.result.notAfter.valueBlock.valueHex),this.notAfter=e.toDate()}}toSchema(){const e=[];return Ai in this&&e.push(new is({idBlock:{tagClass:3,tagNumber:0},valueHex:new Xs({valueDate:this.notBefore}).valueBlock.valueHexView})),Ni in this&&e.push(new is({idBlock:{tagClass:3,tagNumber:1},valueHex:new Xs({valueDate:this.notAfter}).valueBlock.valueHexView})),new Os({value:e})}toJSON(){const e={};return this.notBefore&&(e.notBefore=this.notBefore),this.notAfter&&(e.notAfter=this.notAfter),e}}Ci.CLASS_NAME="PrivateKeyUsagePeriod";const Ii="id",Bi="type",Vi="values",xi=[Ii,Bi],Di=[Vi];class Oi extends zr{constructor(e={}){super(),this.id=He(e,Ii,Oi.defaultValues(Ii)),Bi in e&&(this.type=He(e,Bi,Oi.defaultValues(Bi))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Ii:return Fr;case Bi:return new fs;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Ii:return t===Fr;case Bi:return t instanceof fs;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.id||Fr}),new ar({name:t.type||Fr,optional:!0})]})}fromSchema(e){st(e,xi);const t=cr(e,e,Oi.schema({names:{id:Ii,type:Bi}}));Gr.assertSchema(t,this.className),this.id=t.result.id.valueBlock.toString(),Bi in t.result&&(this.type=t.result.type)}toSchema(){const e=[new Bs({value:this.id})];return Bi in this&&e.push(this.type),new Os({value:e})}toJSON(){const e={id:this.id};return this.type&&(e.type=this.type.toJSON()),e}}Oi.CLASS_NAME="QCStatement";class Ti extends zr{constructor(e={}){super(),this.values=He(e,Vi,Ti.defaultValues(Vi)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===Vi?[]:super.defaultValues(e)}static compareWithDefault(e,t){return e===Vi?0===t.length:super.defaultValues(e)}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new or({name:t.values||Fr,value:Oi.schema(t.value||{})})]})}fromSchema(e){st(e,Di);const t=cr(e,e,Ti.schema({names:{values:Vi}}));Gr.assertSchema(t,this.className),this.values=Array.from(t.result.values,(e=>new Oi({schema:e})))}toSchema(){return new Os({value:Array.from(this.values,(e=>e.toSchema()))})}toJSON(){return{values:Array.from(this.values,(e=>e.toJSON()))}}}var Pi;Ti.CLASS_NAME="QCStatements";class Ui{static register(e,t,s){this.namedCurves[e.toLowerCase()]=this.namedCurves[t]={name:e,id:t,size:s}}static find(e){return this.namedCurves[e.toLowerCase()]||null}}Pi=Ui,Ui.namedCurves={},Pi.register("P-256","1.2.840.10045.3.1.7",32),Pi.register("P-384","1.3.132.0.34",48),Pi.register("P-521","1.3.132.0.35",66),Pi.register("brainpoolP256r1","1.3.36.3.3.2.8.1.1.7",32),Pi.register("brainpoolP384r1","1.3.36.3.3.2.8.1.1.11",48),Pi.register("brainpoolP512r1","1.3.36.3.3.2.8.1.1.13",64);const Li="x",Ri="y",_i="namedCurve";class Hi extends zr{constructor(e={}){super(),this.x=He(e,Li,Hi.defaultValues(Li)),this.y=He(e,Ri,Hi.defaultValues(Ri)),this.namedCurve=He(e,_i,Hi.defaultValues(_i)),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Li:case Ri:return $r;case _i:return Fr;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Li:case Ri:return t instanceof ArrayBuffer&&qe(t,Hi.defaultValues(e));case _i:return"string"==typeof t&&t===Hi.defaultValues(e);default:return super.defaultValues(e)}}static schema(){return new lr}fromSchema(e){const t=De.toUint8Array(e);if(4!==t[0])throw new Error("Object's schema was not verified against input data for ECPublicKey");const s=Ui.find(this.namedCurve);if(!s)throw new Error(`Incorrect curve OID: ${this.namedCurve}`);const r=s.size;if(t.byteLength!==2*r+1)throw new Error("Object's schema was not verified against input data for ECPublicKey");this.namedCurve=s.name,this.x=t.slice(1,r+1).buffer,this.y=t.slice(1+r,2*r+1).buffer}toSchema(){return new lr({data:Je(new Uint8Array([4]).buffer,this.x,this.y)})}toJSON(){const e=Ui.find(this.namedCurve);return{crv:e?e.name:this.namedCurve,x:Ye(Ze(this.x),!0,!0,!1),y:Ye(Ze(this.y),!0,!0,!1)}}fromJSON(e){Wr.assert("json",e,"crv","x","y");let t=0;const s=Ui.find(e.crv);s&&(this.namedCurve=s.id,t=s.size);const r=Xe(Qe(e.x,!0));if(r.byteLength<t){this.x=new ArrayBuffer(t);const e=new Uint8Array(this.x),s=new Uint8Array(r);e.set(s,1)}else this.x=r.slice(0,t);const n=Xe(Qe(e.y,!0));if(n.byteLength<t){this.y=new ArrayBuffer(t);const e=new Uint8Array(this.y),s=new Uint8Array(n);e.set(s,1)}else this.y=n.slice(0,t)}}Hi.CLASS_NAME="ECPublicKey";const Ki="modulus",Mi="publicExponent",ji=[Ki,Mi];class Ji extends zr{constructor(e={}){super(),this.modulus=He(e,Ki,Ji.defaultValues(Ki)),this.publicExponent=He(e,Mi,Ji.defaultValues(Mi)),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Ki:case Mi:return new Ns;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Ns({name:t.modulus||Fr}),new Ns({name:t.publicExponent||Fr})]})}fromSchema(e){st(e,ji);const t=cr(e,e,Ji.schema({names:{modulus:Ki,publicExponent:Mi}}));Gr.assertSchema(t,this.className),this.modulus=t.result.modulus.convertFromDER(256),this.publicExponent=t.result.publicExponent}toSchema(){return new Os({value:[this.modulus.convertToDER(),this.publicExponent]})}toJSON(){return{n:_e.ToBase64Url(this.modulus.valueBlock.valueHexView),e:_e.ToBase64Url(this.publicExponent.valueBlock.valueHexView)}}fromJSON(e){Wr.assert("json",e,"n","e");const t=Xe(Qe(e.n,!0));this.modulus=new Ns({valueHex:t.slice(0,Math.pow(2,tt(t.byteLength)))}),this.publicExponent=new Ns({valueHex:Xe(Qe(e.e,!0)).slice(0,3)})}}Ji.CLASS_NAME="RSAPublicKey";const $i="algorithm",Fi="subjectPublicKey",qi=[$i,Fi];class Wi extends zr{get parsedKey(){if(void 0===this._parsedKey){switch(this.algorithm.algorithmId){case"1.2.840.10045.2.1":if("algorithmParams"in this.algorithm&&this.algorithm.algorithmParams.constructor.blockName()===Bs.blockName())try{this._parsedKey=new Hi({namedCurve:this.algorithm.algorithmParams.valueBlock.toString(),schema:this.subjectPublicKey.valueBlock.valueHexView})}catch{}break;case"1.2.840.113549.1.1.1":{const e=ls(this.subjectPublicKey.valueBlock.valueHexView);if(-1!==e.offset)try{this._parsedKey=new Ji({schema:e.result})}catch{}}}this._parsedKey||(this._parsedKey=null)}return this._parsedKey||void 0}set parsedKey(e){this._parsedKey=e}constructor(e={}){super(),this.algorithm=He(e,$i,Wi.defaultValues($i)),this.subjectPublicKey=He(e,Fi,Wi.defaultValues(Fi));const t=He(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 $i:return new An;case Fi:return new vs;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[An.schema(t.algorithm||{}),new vs({name:t.subjectPublicKey||Fr})]})}fromSchema(e){st(e,qi);const t=cr(e,e,Wi.schema({names:{algorithm:{names:{blockName:$i}},subjectPublicKey:Fi}}));Gr.assertSchema(t,this.className),this.algorithm=new An({schema:t.result.algorithm}),this.subjectPublicKey=t.result.subjectPublicKey}toSchema(){return new Os({value:[this.algorithm.toSchema(),this.subjectPublicKey]})}toJSON(){if(!this.parsedKey)return{algorithm:this.algorithm.toJSON(),subjectPublicKey:this.subjectPublicKey.toJSON()};const 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"}const 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 Hi({json:e}),this.algorithm=new An({algorithmId:"1.2.840.10045.2.1",algorithmParams:new Bs({value:this.parsedKey.namedCurve})});break;case"RSA":this.parsedKey=new Ji({json:e}),this.algorithm=new An({algorithmId:"1.2.840.113549.1.1.1",algorithmParams:new fs});break;default:throw new Error(`Invalid value for "kty" parameter: ${e.kty}`)}this.subjectPublicKey=new vs({valueHex:this.parsedKey.toSchema().toBER(!1)})}}async importKey(e,t=Xo(!0)){try{if(!e)throw new Error("Need to provide publicKey input parameter");const s=ls(await t.exportKey("spki",e));try{this.fromSchema(s.result)}catch{throw new Error("Error during initializing object from schema")}}catch(e){const t=e instanceof Error?e.message:`${e}`;throw new Error(`Error during exporting public key: ${t}`)}}}Wi.CLASS_NAME="PublicKeyInfo";const Gi="version",zi="privateKey",Yi="namedCurve",Qi="publicKey",Zi=[Gi,zi,Yi,Qi];class Xi extends zr{constructor(e={}){super(),this.version=He(e,Gi,Xi.defaultValues(Gi)),this.privateKey=He(e,zi,Xi.defaultValues(zi)),Yi in e&&(this.namedCurve=He(e,Yi,Xi.defaultValues(Yi))),Qi in e&&(this.publicKey=He(e,Qi,Xi.defaultValues(Qi))),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Gi:return 1;case zi:return new ws;case Yi:return Fr;case Qi:return new Hi;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Gi:return t===Xi.defaultValues(e);case zi:return t.isEqual(Xi.defaultValues(e));case Yi:return t===Fr;case Qi:return Hi.compareWithDefault(Yi,t.namedCurve)&&Hi.compareWithDefault("x",t.x)&&Hi.compareWithDefault("y",t.y);default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Ns({name:t.version||Fr}),new ws({name:t.privateKey||Fr}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new Bs({name:t.namedCurve||Fr})]}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new vs({name:t.publicKey||Fr})]})]})}fromSchema(e){st(e,Zi);const t=cr(e,e,Xi.schema({names:{version:Gi,privateKey:zi,namedCurve:Yi,publicKey:Qi}}));if(Gr.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.privateKey=t.result.privateKey,Yi in t.result&&(this.namedCurve=t.result.namedCurve.valueBlock.toString()),Qi in t.result){const e={schema:t.result.publicKey.valueBlock.valueHex};Yi in this&&(e.namedCurve=this.namedCurve),this.publicKey=new Hi(e)}}toSchema(){const e=[new Ns({value:this.version}),this.privateKey];return this.namedCurve&&e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:[new Bs({value:this.namedCurve})]})),this.publicKey&&e.push(new us({idBlock:{tagClass:3,tagNumber:1},value:[new vs({valueHex:this.publicKey.toSchema().toBER(!1)})]})),new Os({value:e})}toJSON(){if(!this.namedCurve||Xi.compareWithDefault(Yi,this.namedCurve))throw new Error('Not enough information for making JSON: absent "namedCurve" value');const e=Ui.find(this.namedCurve),t={crv:e?e.name:this.namedCurve,d:_e.ToBase64Url(this.privateKey.valueBlock.valueHexView)};if(this.publicKey){const e=this.publicKey.toJSON();t.x=e.x,t.y=e.y}return t}fromJSON(e){Wr.assert("json",e,"crv","d");let t=0;const s=Ui.find(e.crv);s&&(this.namedCurve=s.id,t=s.size);const r=_e.FromBase64Url(e.d);if(r.byteLength<t){const e=new ArrayBuffer(t),s=new Uint8Array(e),n=new Uint8Array(r);s.set(n,1),this.privateKey=new ws({valueHex:e})}else this.privateKey=new ws({valueHex:r.slice(0,t)});e.x&&e.y&&(this.publicKey=new Hi({json:e}))}}Xi.CLASS_NAME="ECPrivateKey";const eo="prime",to="exponent",so="coefficient",ro=[eo,to,so];class no extends zr{constructor(e={}){super(),this.prime=He(e,eo,no.defaultValues(eo)),this.exponent=He(e,to,no.defaultValues(to)),this.coefficient=He(e,so,no.defaultValues(so)),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case eo:case to:case so:return new Ns;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Ns({name:t.prime||Fr}),new Ns({name:t.exponent||Fr}),new Ns({name:t.coefficient||Fr})]})}fromSchema(e){st(e,ro);const t=cr(e,e,no.schema({names:{prime:eo,exponent:to,coefficient:so}}));Gr.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 Os({value:[this.prime.convertToDER(),this.exponent.convertToDER(),this.coefficient.convertToDER()]})}toJSON(){return{r:_e.ToBase64Url(this.prime.valueBlock.valueHexView),d:_e.ToBase64Url(this.exponent.valueBlock.valueHexView),t:_e.ToBase64Url(this.coefficient.valueBlock.valueHexView)}}fromJSON(e){Wr.assert("json",e,"r","d","r"),this.prime=new Ns({valueHex:_e.FromBase64Url(e.r)}),this.exponent=new Ns({valueHex:_e.FromBase64Url(e.d)}),this.coefficient=new Ns({valueHex:_e.FromBase64Url(e.t)})}}no.CLASS_NAME="OtherPrimeInfo";const ao="version",io="modulus",oo="publicExponent",lo="privateExponent",co="prime1",uo="prime2",ho="exponent1",mo="exponent2",fo="coefficient",go="otherPrimeInfos",po=[ao,io,oo,lo,co,uo,ho,mo,fo,go];class wo extends zr{constructor(e={}){super(),this.version=He(e,ao,wo.defaultValues(ao)),this.modulus=He(e,io,wo.defaultValues(io)),this.publicExponent=He(e,oo,wo.defaultValues(oo)),this.privateExponent=He(e,lo,wo.defaultValues(lo)),this.prime1=He(e,co,wo.defaultValues(co)),this.prime2=He(e,uo,wo.defaultValues(uo)),this.exponent1=He(e,ho,wo.defaultValues(ho)),this.exponent2=He(e,mo,wo.defaultValues(mo)),this.coefficient=He(e,fo,wo.defaultValues(fo)),go in e&&(this.otherPrimeInfos=He(e,go,wo.defaultValues(go))),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case ao:return 0;case io:case oo:case lo:case co:case uo:case ho:case mo:case fo:return new Ns;case go:return[];default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Ns({name:t.version||Fr}),new Ns({name:t.modulus||Fr}),new Ns({name:t.publicExponent||Fr}),new Ns({name:t.privateExponent||Fr}),new Ns({name:t.prime1||Fr}),new Ns({name:t.prime2||Fr}),new Ns({name:t.exponent1||Fr}),new Ns({name:t.exponent2||Fr}),new Ns({name:t.coefficient||Fr}),new Os({optional:!0,value:[new or({name:t.otherPrimeInfosName||Fr,value:no.schema(t.otherPrimeInfo||{})})]})]})}fromSchema(e){st(e,po);const t=cr(e,e,wo.schema({names:{version:ao,modulus:io,publicExponent:oo,privateExponent:lo,prime1:co,prime2:uo,exponent1:ho,exponent2:mo,coefficient:fo,otherPrimeInfo:{names:{blockName:go}}}}));Gr.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),go in t.result&&(this.otherPrimeInfos=Array.from(t.result.otherPrimeInfos,(e=>new no({schema:e}))))}toSchema(){const e=[];return e.push(new Ns({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 Os({value:Array.from(this.otherPrimeInfos,(e=>e.toSchema()))})),new Os({value:e})}toJSON(){const e={n:_e.ToBase64Url(this.modulus.valueBlock.valueHexView),e:_e.ToBase64Url(this.publicExponent.valueBlock.valueHexView),d:_e.ToBase64Url(this.privateExponent.valueBlock.valueHexView),p:_e.ToBase64Url(this.prime1.valueBlock.valueHexView),q:_e.ToBase64Url(this.prime2.valueBlock.valueHexView),dp:_e.ToBase64Url(this.exponent1.valueBlock.valueHexView),dq:_e.ToBase64Url(this.exponent2.valueBlock.valueHexView),qi:_e.ToBase64Url(this.coefficient.valueBlock.valueHexView)};return this.otherPrimeInfos&&(e.oth=Array.from(this.otherPrimeInfos,(e=>e.toJSON()))),e}fromJSON(e){Wr.assert("json",e,"n","e","d","p","q","dp","dq","qi"),this.modulus=new Ns({valueHex:_e.FromBase64Url(e.n)}),this.publicExponent=new Ns({valueHex:_e.FromBase64Url(e.e)}),this.privateExponent=new Ns({valueHex:_e.FromBase64Url(e.d)}),this.prime1=new Ns({valueHex:_e.FromBase64Url(e.p)}),this.prime2=new Ns({valueHex:_e.FromBase64Url(e.q)}),this.exponent1=new Ns({valueHex:_e.FromBase64Url(e.dp)}),this.exponent2=new Ns({valueHex:_e.FromBase64Url(e.dq)}),this.coefficient=new Ns({valueHex:_e.FromBase64Url(e.qi)}),e.oth&&(this.otherPrimeInfos=Array.from(e.oth,(e=>new no({json:e}))))}}wo.CLASS_NAME="RSAPrivateKey";const yo="version",vo="privateKeyAlgorithm",bo="privateKey",So="attributes",ko="parsedKey",Ao=[yo,vo,bo,So];class No extends zr{constructor(e={}){super(),this.version=He(e,yo,No.defaultValues(yo)),this.privateKeyAlgorithm=He(e,vo,No.defaultValues(vo)),this.privateKey=He(e,bo,No.defaultValues(bo)),So in e&&(this.attributes=He(e,So,No.defaultValues(So))),ko in e&&(this.parsedKey=He(e,ko,No.defaultValues(ko))),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case yo:return 0;case vo:return new An;case bo:return new ws;case So:return[];case ko:return{};default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Ns({name:t.version||Fr}),An.schema(t.privateKeyAlgorithm||{}),new ws({name:t.privateKey||Fr}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new or({name:t.attributes||Fr,value:xn.schema()})]})]})}fromSchema(e){st(e,Ao);const t=cr(e,e,No.schema({names:{version:yo,privateKeyAlgorithm:{names:{blockName:vo}},privateKey:bo,attributes:So}}));switch(Gr.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.privateKeyAlgorithm=new An({schema:t.result.privateKeyAlgorithm}),this.privateKey=t.result.privateKey,So in t.result&&(this.attributes=Array.from(t.result.attributes,(e=>new xn({schema:e})))),this.privateKeyAlgorithm.algorithmId){case"1.2.840.113549.1.1.1":{const e=ls(this.privateKey.valueBlock.valueHexView);-1!==e.offset&&(this.parsedKey=new wo({schema:e.result}))}break;case"1.2.840.10045.2.1":if("algorithmParams"in this.privateKeyAlgorithm&&this.privateKeyAlgorithm.algorithmParams instanceof Bs){const e=ls(this.privateKey.valueBlock.valueHexView);-1!==e.offset&&(this.parsedKey=new Xi({namedCurve:this.privateKeyAlgorithm.algorithmParams.valueBlock.toString(),schema:e.result}))}}}toSchema(){const e=[new Ns({value:this.version}),this.privateKeyAlgorithm.toSchema(),this.privateKey];return this.attributes&&e.push(new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.attributes,(e=>e.toSchema()))})),new Os({value:e})}toJSON(){if(!this.parsedKey){const e={version:this.version,privateKeyAlgorithm:this.privateKeyAlgorithm.toJSON(),privateKey:this.privateKey.toJSON()};return this.attributes&&(e.attributes=Array.from(this.attributes,(e=>e.toJSON()))),e}const 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"}const 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 Xi({json:e}),this.privateKeyAlgorithm=new An({algorithmId:"1.2.840.10045.2.1",algorithmParams:new Bs({value:this.parsedKey.namedCurve})});break;case"RSA":this.parsedKey=new wo({json:e}),this.privateKeyAlgorithm=new An({algorithmId:"1.2.840.113549.1.1.1",algorithmParams:new fs});break;default:throw new Error(`Invalid value for "kty" parameter: ${e.kty}`)}this.privateKey=new ws({valueHex:this.parsedKey.toSchema().toBER(!1)})}}}No.CLASS_NAME="PrivateKeyInfo";const Eo="contentType",Co="contentEncryptionAlgorithm",Io="encryptedContent",Bo=[Eo,Co,Io];class Vo extends zr{constructor(e={}){if(super(),this.contentType=He(e,Eo,Vo.defaultValues(Eo)),this.contentEncryptionAlgorithm=He(e,Co,Vo.defaultValues(Co)),Io in e&&e.encryptedContent&&(this.encryptedContent=e.encryptedContent,1===this.encryptedContent.idBlock.tagClass&&4===this.encryptedContent.idBlock.tagNumber&&!1===this.encryptedContent.idBlock.isConstructed&&!e.disableSplit)){const e=new ws({idBlock:{isConstructed:!0},isConstructed:!0});let t=0;const s=this.encryptedContent.valueBlock.valueHexView.slice().buffer;let r=s.byteLength;for(;r>0;){const n=new Uint8Array(s,t,t+1024>s.byteLength?s.byteLength-t:1024),a=new ArrayBuffer(n.length),i=new Uint8Array(a);for(let e=0;e<i.length;e++)i[e]=n[e];e.valueBlock.value.push(new ws({valueHex:a})),r-=n.length,t+=n.length}this.encryptedContent=e}e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Eo:return Fr;case Co:return new An;case Io:return new ws;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Eo:return t===Fr;case Co:return t.algorithmId===Fr&&"algorithmParams"in t==!1;case Io:return t.isEqual(Vo.defaultValues(Io));default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.contentType||Fr}),An.schema(t.contentEncryptionAlgorithm||{}),new ir({value:[new us({name:t.encryptedContent||Fr,idBlock:{tagClass:3,tagNumber:0},value:[new or({value:new ws})]}),new is({name:t.encryptedContent||Fr,idBlock:{tagClass:3,tagNumber:0}})]})]})}fromSchema(e){st(e,Bo);const t=cr(e,e,Vo.schema({names:{contentType:Eo,contentEncryptionAlgorithm:{names:{blockName:Co}},encryptedContent:Io}}));Gr.assertSchema(t,this.className),this.contentType=t.result.contentType.valueBlock.toString(),this.contentEncryptionAlgorithm=new An({schema:t.result.contentEncryptionAlgorithm}),Io in t.result&&(this.encryptedContent=t.result.encryptedContent,this.encryptedContent.idBlock.tagClass=1,this.encryptedContent.idBlock.tagNumber=4)}toSchema(){const e={isIndefiniteForm:!1},t=[];if(t.push(new Bs({value:this.contentType})),t.push(this.contentEncryptionAlgorithm.toSchema()),this.encryptedContent){e.isIndefiniteForm=this.encryptedContent.idBlock.isConstructed;const s=this.encryptedContent;s.idBlock.tagClass=3,s.idBlock.tagNumber=0,s.lenBlock.isIndefiniteForm=this.encryptedContent.idBlock.isConstructed,t.push(s)}return new Os({lenBlock:e,value:t})}toJSON(){const 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 ws.prototype.getValue.call(this.encryptedContent)}}Vo.CLASS_NAME="EncryptedContentInfo";const xo="hashAlgorithm",Do="maskGenAlgorithm",Oo="saltLength",To="trailerField",Po=[xo,Do,Oo,To];class Uo extends zr{constructor(e={}){super(),this.hashAlgorithm=He(e,xo,Uo.defaultValues(xo)),this.maskGenAlgorithm=He(e,Do,Uo.defaultValues(Do)),this.saltLength=He(e,Oo,Uo.defaultValues(Oo)),this.trailerField=He(e,To,Uo.defaultValues(To)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case xo:return new An({algorithmId:"1.3.14.3.2.26",algorithmParams:new fs});case Do:return new An({algorithmId:"1.2.840.113549.1.1.8",algorithmParams:new An({algorithmId:"1.3.14.3.2.26",algorithmParams:new fs}).toSchema()});case Oo:return 20;case To:return 1;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new us({idBlock:{tagClass:3,tagNumber:0},optional:!0,value:[An.schema(t.hashAlgorithm||{})]}),new us({idBlock:{tagClass:3,tagNumber:1},optional:!0,value:[An.schema(t.maskGenAlgorithm||{})]}),new us({idBlock:{tagClass:3,tagNumber:2},optional:!0,value:[new Ns({name:t.saltLength||Fr})]}),new us({idBlock:{tagClass:3,tagNumber:3},optional:!0,value:[new Ns({name:t.trailerField||Fr})]})]})}fromSchema(e){st(e,Po);const t=cr(e,e,Uo.schema({names:{hashAlgorithm:{names:{blockName:xo}},maskGenAlgorithm:{names:{blockName:Do}},saltLength:Oo,trailerField:To}}));Gr.assertSchema(t,this.className),xo in t.result&&(this.hashAlgorithm=new An({schema:t.result.hashAlgorithm})),Do in t.result&&(this.maskGenAlgorithm=new An({schema:t.result.maskGenAlgorithm})),Oo in t.result&&(this.saltLength=t.result.saltLength.valueBlock.valueDec),To in t.result&&(this.trailerField=t.result.trailerField.valueBlock.valueDec)}toSchema(){const e=[];return this.hashAlgorithm.isEqual(Uo.defaultValues(xo))||e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:[this.hashAlgorithm.toSchema()]})),this.maskGenAlgorithm.isEqual(Uo.defaultValues(Do))||e.push(new us({idBlock:{tagClass:3,tagNumber:1},value:[this.maskGenAlgorithm.toSchema()]})),this.saltLength!==Uo.defaultValues(Oo)&&e.push(new us({idBlock:{tagClass:3,tagNumber:2},value:[new Ns({value:this.saltLength})]})),this.trailerField!==Uo.defaultValues(To)&&e.push(new us({idBlock:{tagClass:3,tagNumber:3},value:[new Ns({value:this.trailerField})]})),new Os({value:e})}toJSON(){const e={};return this.hashAlgorithm.isEqual(Uo.defaultValues(xo))||(e.hashAlgorithm=this.hashAlgorithm.toJSON()),this.maskGenAlgorithm.isEqual(Uo.defaultValues(Do))||(e.maskGenAlgorithm=this.maskGenAlgorithm.toJSON()),this.saltLength!==Uo.defaultValues(Oo)&&(e.saltLength=this.saltLength),this.trailerField!==Uo.defaultValues(To)&&(e.trailerField=this.trailerField),e}}Uo.CLASS_NAME="RSASSAPSSParams";const Lo="salt",Ro="iterationCount",_o="keyLength",Ho="prf",Ko=[Lo,Ro,_o,Ho];class Mo extends zr{constructor(e={}){super(),this.salt=He(e,Lo,Mo.defaultValues(Lo)),this.iterationCount=He(e,Ro,Mo.defaultValues(Ro)),_o in e&&(this.keyLength=He(e,_o,Mo.defaultValues(_o))),Ho in e&&(this.prf=He(e,Ho,Mo.defaultValues(Ho))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Lo:return{};case Ro:return-1;case _o:return 0;case Ho:return new An({algorithmId:"1.3.14.3.2.26",algorithmParams:new fs});default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new ir({value:[new ws({name:t.saltPrimitive||Fr}),An.schema(t.saltConstructed||{})]}),new Ns({name:t.iterationCount||Fr}),new Ns({name:t.keyLength||Fr,optional:!0}),An.schema(t.prf||{names:{optional:!0}})]})}fromSchema(e){st(e,Ko);const t=cr(e,e,Mo.schema({names:{saltPrimitive:Lo,saltConstructed:{names:{blockName:Lo}},iterationCount:Ro,keyLength:_o,prf:{names:{blockName:Ho,optional:!0}}}}));Gr.assertSchema(t,this.className),this.salt=t.result.salt,this.iterationCount=t.result.iterationCount.valueBlock.valueDec,_o in t.result&&(this.keyLength=t.result.keyLength.valueBlock.valueDec),Ho in t.result&&(this.prf=new An({schema:t.result.prf}))}toSchema(){const e=[];return e.push(this.salt),e.push(new Ns({value:this.iterationCount})),_o in this&&Mo.defaultValues(_o)!==this.keyLength&&e.push(new Ns({value:this.keyLength})),this.prf&&!1===Mo.defaultValues(Ho).isEqual(this.prf)&&e.push(this.prf.toSchema()),new Os({value:e})}toJSON(){const e={salt:this.salt.toJSON(),iterationCount:this.iterationCount};return _o in this&&Mo.defaultValues(_o)!==this.keyLength&&(e.keyLength=this.keyLength),this.prf&&!1===Mo.defaultValues(Ho).isEqual(this.prf)&&(e.prf=this.prf.toJSON()),e}}Mo.CLASS_NAME="PBKDF2Params";const jo="keyDerivationFunc",Jo="encryptionScheme",$o=[jo,Jo];class Fo extends zr{constructor(e={}){super(),this.keyDerivationFunc=He(e,jo,Fo.defaultValues(jo)),this.encryptionScheme=He(e,Jo,Fo.defaultValues(Jo)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case jo:case Jo:return new An;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[An.schema(t.keyDerivationFunc||{}),An.schema(t.encryptionScheme||{})]})}fromSchema(e){st(e,$o);const t=cr(e,e,Fo.schema({names:{keyDerivationFunc:{names:{blockName:jo}},encryptionScheme:{names:{blockName:Jo}}}}));Gr.assertSchema(t,this.className),this.keyDerivationFunc=new An({schema:t.result.keyDerivationFunc}),this.encryptionScheme=new An({schema:t.result.encryptionScheme})}toSchema(){return new Os({value:[this.keyDerivationFunc.toSchema(),this.encryptionScheme.toSchema()]})}toJSON(){return{keyDerivationFunc:this.keyDerivationFunc.toJSON(),encryptionScheme:this.encryptionScheme.toJSON()}}}Fo.CLASS_NAME="PBES2Params";class qo{constructor(e){this.crypto=e.crypto,this.subtle="webkitSubtle"in e.crypto?e.crypto.webkitSubtle:e.crypto.subtle,this.name=He(e,"name",Fr)}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(null===e)throw new Error('Argument "array" must not be null');return this.crypto.getRandomValues(e)}}async function Wo(e,t,s,r,n){let a,i,o;switch(e.toUpperCase()){case"SHA-1":a=20,i=64,o=Cr;break;case"SHA-256":a=32,i=64,o=Dr;break;case"SHA-384":a=48,i=128,o=Jr;break;case"SHA-512":a=64,i=128,o=jr;break;default:throw new Error("Unsupported hashing algorithm")}const l=new Uint8Array(s);let c=(new TextDecoder).decode(s);(new TextEncoder).encode(c).some(((e,t)=>e!==l[t]))&&(c=String.fromCharCode(...l));const u=new Uint8Array(2*c.length+2),h=new DataView(u.buffer);for(let e=0;e<c.length;e++)h.setUint16(2*e,c.charCodeAt(e),!1);h.setUint16(2*c.length,0,!1);const m=new Uint8Array(i).fill(3),f=new Uint8Array(r),d=new Uint8Array(i*Math.ceil(f.length/i)).map(((e,t)=>f[t%f.length])),g=new Uint8Array(i*Math.ceil(u.length/i)).map(((e,t)=>u[t%u.length]));let p=new Uint8Array(d.length+g.length);p.set(d),p.set(g,d.length);const w=Math.ceil((t>>3)/a),y=[];for(let e=0;e<w;e++){let e=new Uint8Array(m.length+p.length);e.set(m),e.set(p,m.length);for(let t=0;t<n;t++)e=o(e);const t=new Uint8Array(i).map(((t,s)=>e[s%e.length])),s=Math.ceil(f.length/i)+Math.ceil(u.length/i),r=[];for(let e=0;e<s;e++){const s=Array.from(p.slice(e*i,(e+1)*i));let n=511;for(let e=t.length-1;e>=0;e--)n>>=8,n+=t[e]+(s[e]||0),s[e]=255&n;r.push(...s)}p=new Uint8Array(r),y.push(...e)}return new Uint8Array(y.slice(0,t>>3)).buffer}function Go(e){const t="string"==typeof e?{name:e}:e;return"hash"in t?{...t,hash:Go(t.hash)}:t}class zo extends qo{async importKey(e,t,s,r,n){var a,i,o,l,c,u;let h={};const m=Go(s);switch(e.toLowerCase()){case"raw":return this.subtle.importKey("raw",t,s,r,n);case"spki":{const e=ls(De.toArrayBuffer(t));Gr.assert(e,"keyData");const s=new Wi;try{s.fromSchema(e.result)}catch{throw new qr("Incorrect keyData")}switch(m.name.toUpperCase()){case"RSA-PSS":if(!m.hash)throw new Wr("hash","algorithm.hash","Incorrect hash algorithm: Hash algorithm is missed");switch(m.hash.name.toUpperCase()){case"SHA-1":h.alg="PS1";break;case"SHA-256":h.alg="PS256";break;case"SHA-384":h.alg="PS384";break;case"SHA-512":h.alg="PS512";break;default:throw new Error(`Incorrect hash algorithm: ${m.hash.name.toUpperCase()}`)}case"RSASSA-PKCS1-V1_5":{if(n=["verify"],h.kty="RSA",h.ext=r,h.key_ops=n,"1.2.840.113549.1.1.1"!==s.algorithm.algorithmId)throw new Error(`Incorrect public key algorithm: ${s.algorithm.algorithmId}`);if(!h.alg){if(!m.hash)throw new Wr("hash","algorithm.hash","Incorrect hash algorithm: Hash algorithm is missed");switch(m.hash.name.toUpperCase()){case"SHA-1":h.alg="RS1";break;case"SHA-256":h.alg="RS256";break;case"SHA-384":h.alg="RS384";break;case"SHA-512":h.alg="RS512";break;default:throw new Error(`Incorrect hash algorithm: ${m.hash.name.toUpperCase()}`)}}const e=s.toJSON();Object.assign(h,e)}break;case"ECDSA":n=["verify"];case"ECDH":{if(h={kty:"EC",ext:r,key_ops:n},"1.2.840.10045.2.1"!==s.algorithm.algorithmId)throw new Error(`Incorrect public key algorithm: ${s.algorithm.algorithmId}`);const e=s.toJSON();Object.assign(h,e)}break;case"RSA-OAEP":{if(h.kty="RSA",h.ext=r,h.key_ops=n,"safari"===this.name.toLowerCase())h.alg="RSA-OAEP";else{if(!m.hash)throw new Wr("hash","algorithm.hash","Incorrect hash algorithm: Hash algorithm is missed");switch(m.hash.name.toUpperCase()){case"SHA-1":h.alg="RSA-OAEP";break;case"SHA-256":h.alg="RSA-OAEP-256";break;case"SHA-384":h.alg="RSA-OAEP-384";break;case"SHA-512":h.alg="RSA-OAEP-512";break;default:throw new Error(`Incorrect hash algorithm: ${m.hash.name.toUpperCase()}`)}}const e=s.toJSON();Object.assign(h,e)}break;case"RSAES-PKCS1-V1_5":{h.kty="RSA",h.ext=r,h.key_ops=n,h.alg="PS1";const e=s.toJSON();Object.assign(h,e)}break;default:throw new Error(`Incorrect algorithm name: ${m.name.toUpperCase()}`)}}break;case"pkcs8":{const e=new No,s=ls(De.toArrayBuffer(t));Gr.assert(s,"keyData");try{e.fromSchema(s.result)}catch{throw new Error("Incorrect keyData")}if(!e.parsedKey)throw new Error("Incorrect keyData");switch(m.name.toUpperCase()){case"RSA-PSS":switch(null===(a=m.hash)||void 0===a?void 0:a.name.toUpperCase()){case"SHA-1":h.alg="PS1";break;case"SHA-256":h.alg="PS256";break;case"SHA-384":h.alg="PS384";break;case"SHA-512":h.alg="PS512";break;default:throw new Error(`Incorrect hash algorithm: ${null===(i=m.hash)||void 0===i?void 0:i.name.toUpperCase()}`)}case"RSASSA-PKCS1-V1_5":{if(n=["sign"],h.kty="RSA",h.ext=r,h.key_ops=n,"1.2.840.113549.1.1.1"!==e.privateKeyAlgorithm.algorithmId)throw new Error(`Incorrect private key algorithm: ${e.privateKeyAlgorithm.algorithmId}`);if("alg"in h==!1)switch(null===(o=m.hash)||void 0===o?void 0:o.name.toUpperCase()){case"SHA-1":h.alg="RS1";break;case"SHA-256":h.alg="RS256";break;case"SHA-384":h.alg="RS384";break;case"SHA-512":h.alg="RS512";break;default:throw new Error(`Incorrect hash algorithm: ${null===(l=m.hash)||void 0===l?void 0:l.name.toUpperCase()}`)}const t=e.toJSON();Object.assign(h,t)}break;case"ECDSA":n=["sign"];case"ECDH":{if(h={kty:"EC",ext:r,key_ops:n},"1.2.840.10045.2.1"!==e.privateKeyAlgorithm.algorithmId)throw new Error(`Incorrect algorithm: ${e.privateKeyAlgorithm.algorithmId}`);const t=e.toJSON();Object.assign(h,t)}break;case"RSA-OAEP":{if(h.kty="RSA",h.ext=r,h.key_ops=n,"safari"===this.name.toLowerCase())h.alg="RSA-OAEP";else switch(null===(c=m.hash)||void 0===c?void 0:c.name.toUpperCase()){case"SHA-1":h.alg="RSA-OAEP";break;case"SHA-256":h.alg="RSA-OAEP-256";break;case"SHA-384":h.alg="RSA-OAEP-384";break;case"SHA-512":h.alg="RSA-OAEP-512";break;default:throw new Error(`Incorrect hash algorithm: ${null===(u=m.hash)||void 0===u?void 0:u.name.toUpperCase()}`)}const t=e.toJSON();Object.assign(h,t)}break;case"RSAES-PKCS1-V1_5":{n=["decrypt"],h.kty="RSA",h.ext=r,h.key_ops=n,h.alg="PS1";const t=e.toJSON();Object.assign(h,t)}break;default:throw new Error(`Incorrect algorithm name: ${m.name.toUpperCase()}`)}}break;case"jwk":h=t;break;default:throw new Error(`Incorrect format: ${e}`)}if("safari"===this.name.toLowerCase())try{return this.subtle.importKey("jwk",Xe(JSON.stringify(h)),s,r,n)}catch{return this.subtle.importKey("jwk",h,s,r,n)}return this.subtle.importKey("jwk",h,s,r,n)}async exportKey(e,t){let s=await this.subtle.exportKey("jwk",t);switch("safari"===this.name.toLowerCase()&&s instanceof ArrayBuffer&&(s=JSON.parse(Ze(s))),e.toLowerCase()){case"raw":return this.subtle.exportKey("raw",t);case"spki":{const e=new Wi;try{e.fromJSON(s)}catch{throw new Error("Incorrect key data")}return e.toSchema().toBER(!1)}case"pkcs8":{const e=new No;try{e.fromJSON(s)}catch{throw new Error("Incorrect key data")}return e.toSchema().toBER(!1)}case"jwk":return s;default:throw new Error(`Incorrect format: ${e}`)}}async convert(e,t,s,r,n,a){if(e.toLowerCase()===t.toLowerCase())return s;const i=await this.importKey(e,s,r,n,a);return this.exportKey(t,i)}getAlgorithmByOID(e,t=!1,s){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 ${s?`for ${s} `:Fr}: ${e}`);return{}}getOIDByAlgorithm(e,t=!1,s){let r=Fr;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;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;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;case"AES-CTR":case"AES-CMAC":case"CONCAT":case"HKDF":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;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;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;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;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;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"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"}if(!r&&t)throw new Error(`Unsupported algorithm ${s?`for ${s} `:Fr}: ${e.name}`);return r}getAlgorithmParameters(e,t){let s={algorithm:{},usages:[]};switch(e.toUpperCase()){case"RSAES-PKCS1-V1_5":case"RSASSA-PKCS1-V1_5":switch(t.toLowerCase()){case"generatekey":s={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":s={algorithm:{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},usages:["verify"]};break;default:return{algorithm:{name:"RSASSA-PKCS1-v1_5"},usages:[]}}break;case"RSA-PSS":switch(t.toLowerCase()){case"sign":case"verify":s={algorithm:{name:"RSA-PSS",hash:{name:"SHA-1"},saltLength:20},usages:["sign","verify"]};break;case"generatekey":s={algorithm:{name:"RSA-PSS",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-1"}},usages:["sign","verify"]};break;case"importkey":s={algorithm:{name:"RSA-PSS",hash:{name:"SHA-1"}},usages:["verify"]};break;default:return{algorithm:{name:"RSA-PSS"},usages:[]}}break;case"RSA-OAEP":switch(t.toLowerCase()){case"encrypt":case"decrypt":s={algorithm:{name:"RSA-OAEP"},usages:["encrypt","decrypt"]};break;case"generatekey":s={algorithm:{name:"RSA-OAEP",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;case"importkey":s={algorithm:{name:"RSA-OAEP",hash:{name:"SHA-256"}},usages:["encrypt"]};break;default:return{algorithm:{name:"RSA-OAEP"},usages:[]}}break;case"ECDSA":switch(t.toLowerCase()){case"generatekey":s={algorithm:{name:"ECDSA",namedCurve:"P-256"},usages:["sign","verify"]};break;case"importkey":s={algorithm:{name:"ECDSA",namedCurve:"P-256"},usages:["verify"]};break;case"verify":case"sign":s={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":s={algorithm:{name:"ECDH",namedCurve:"P-256"},usages:["deriveKey","deriveBits"]};break;case"derivekey":case"derivebits":s={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":s={algorithm:{name:"AES-CTR",length:256},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;case"decrypt":case"encrypt":s={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":s={algorithm:{name:"AES-CBC",length:256},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;case"decrypt":case"encrypt":s={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":s={algorithm:{name:"AES-GCM",length:256},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;case"decrypt":case"encrypt":s={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":s={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":s={algorithm:{name:"HMAC"},usages:["sign","verify"]};break;case"importkey":case"exportkey":case"generatekey":s={algorithm:{name:"HMAC",length:32,hash:{name:"SHA-256"}},usages:["sign","verify"]};break;default:return{algorithm:{name:"HMAC"},usages:[]}}break;case"HKDF":if("derivekey"!==t.toLowerCase())return{algorithm:{name:"HKDF"},usages:[]};s={algorithm:{name:"HKDF",hash:"SHA-256",salt:new Uint8Array([]),info:new Uint8Array([])},usages:["encrypt","decrypt"]};break;case"PBKDF2":if("derivekey"!==t.toLowerCase())return{algorithm:{name:"PBKDF2"},usages:[]};s={algorithm:{name:"PBKDF2",hash:{name:"SHA-256"},salt:new Uint8Array([]),iterations:1e4},usages:["encrypt","decrypt"]}}return s}getHashAlgorithm(e){let t=Fr;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{const s=new Uo({schema:e.algorithmParams});if(s.hashAlgorithm){const e=this.getAlgorithmByOID(s.hashAlgorithm.algorithmId);if(!("name"in e))return Fr;t=e.name}else t="SHA-1"}catch{}}return t}async encryptEncryptedContentInfo(e){Wr.assert(e,"password","contentEncryptionAlgorithm","hmacHashAlgorithm","iterationCount","contentToEncrypt","contentToEncrypt","contentType");const t=this.getOIDByAlgorithm(e.contentEncryptionAlgorithm,!0,"contentEncryptionAlgorithm"),s=this.getOIDByAlgorithm({name:"PBKDF2"},!0,"PBKDF2"),r=this.getOIDByAlgorithm({name:"HMAC",hash:{name:e.hmacHashAlgorithm}},!0,"hmacHashAlgorithm"),n=new ArrayBuffer(16),a=new Uint8Array(n);this.getRandomValues(a);const i=new ArrayBuffer(64),o=new Uint8Array(i);this.getRandomValues(o);const l=new Uint8Array(e.contentToEncrypt),c=new Mo({salt:new ws({valueHex:i}),iterationCount:e.iterationCount,prf:new An({algorithmId:r,algorithmParams:new fs})}),u=new Uint8Array(e.password),h=await this.importKey("raw",u,"PBKDF2",!1,["deriveKey"]),m=await this.deriveKey({name:"PBKDF2",hash:{name:e.hmacHashAlgorithm},salt:o,iterations:e.iterationCount},h,e.contentEncryptionAlgorithm,!1,["encrypt"]),f=await this.encrypt({name:e.contentEncryptionAlgorithm.name,iv:a},m,l),d=new Fo({keyDerivationFunc:new An({algorithmId:s,algorithmParams:c.toSchema()}),encryptionScheme:new An({algorithmId:t,algorithmParams:new ws({valueHex:n})})});return new Vo({contentType:e.contentType,contentEncryptionAlgorithm:new An({algorithmId:"1.2.840.113549.1.5.13",algorithmParams:d.toSchema()}),encryptedContent:new ws({valueHex:f})})}async decryptEncryptedContentInfo(e){if(Wr.assert(e,"password","encryptedContentInfo"),"1.2.840.113549.1.5.13"!==e.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId)throw new Error(`Unknown "contentEncryptionAlgorithm": ${e.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId}`);let t,s;try{t=new Fo({schema:e.encryptedContentInfo.contentEncryptionAlgorithm.algorithmParams})}catch{throw new Error('Incorrectly encoded "pbes2Parameters"')}try{s=new Mo({schema:t.keyDerivationFunc.algorithmParams})}catch{throw new Error('Incorrectly encoded "pbkdf2Params"')}const r=this.getAlgorithmByOID(t.encryptionScheme.algorithmId,!0),n=t.encryptionScheme.algorithmParams.valueBlock.valueHex,a=new Uint8Array(n),i=s.salt.valueBlock.valueHex,o=new Uint8Array(i),l=s.iterationCount;let c="SHA-1";if(s.prf){c=this.getAlgorithmByOID(s.prf.algorithmId,!0).hash.name}const u=await this.importKey("raw",e.password,"PBKDF2",!1,["deriveKey"]),h=await this.deriveKey({name:"PBKDF2",hash:{name:c},salt:o,iterations:l},u,r,!1,["decrypt"]),m=e.encryptedContentInfo.getEncryptedContent();return this.decrypt({name:r.name,iv:a},h,m)}async stampDataWithPassword(e){if(e instanceof Object==!1)throw new Error('Parameters must have type "Object"');let t;switch(Wr.assert(e,"password","hashAlgorithm","iterationCount","salt","contentToStamp"),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}`)}const s={name:"HMAC",length:t,hash:{name:e.hashAlgorithm}},r=await Wo(e.hashAlgorithm,t,e.password,e.salt,e.iterationCount),n=await this.importKey("raw",new Uint8Array(r),s,!1,["sign"]);return this.sign(s,n,new Uint8Array(e.contentToStamp))}async verifyDataStampedWithPassword(e){Wr.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}`)}const s={name:"HMAC",length:t,hash:{name:e.hashAlgorithm}},r=await Wo(e.hashAlgorithm,t,e.password,e.salt,e.iterationCount),n=await this.importKey("raw",new Uint8Array(r),s,!1,["verify"]);return this.verify(s,n,new Uint8Array(e.signatureToVerify),new Uint8Array(e.contentToVerify))}async getSignatureParameters(e,t="SHA-1"){this.getOIDByAlgorithm({name:t},!0,"hashAlgorithm");const s=new An,r=this.getAlgorithmParameters(e.algorithm.name,"sign");if(!Object.keys(r.algorithm).length)throw new Error("Parameter 'algorithm' is empty");const n=r.algorithm;switch("hash"in e.algorithm&&e.algorithm.hash&&e.algorithm.hash.name?n.hash.name=e.algorithm.hash.name:n.hash.name=t,e.algorithm.name.toUpperCase()){case"RSASSA-PKCS1-V1_5":case"ECDSA":s.algorithmId=this.getOIDByAlgorithm(n,!0);break;case"RSA-PSS":{switch(n.hash.name.toUpperCase()){case"SHA-256":n.saltLength=32;break;case"SHA-384":n.saltLength=48;break;case"SHA-512":n.saltLength=64}const e={};if("SHA-1"!==n.hash.name.toUpperCase()){const t=this.getOIDByAlgorithm({name:n.hash.name},!0,"hashAlgorithm");e.hashAlgorithm=new An({algorithmId:t,algorithmParams:new fs}),e.maskGenAlgorithm=new An({algorithmId:"1.2.840.113549.1.1.8",algorithmParams:e.hashAlgorithm.toSchema()})}20!==n.saltLength&&(e.saltLength=n.saltLength);const t=new Uo(e);s.algorithmId="1.2.840.113549.1.1.10",s.algorithmParams=t.toSchema()}break;default:throw new Error(`Unsupported signature algorithm: ${e.algorithm.name}`)}return{signatureAlgorithm:s,parameters:r}}async signWithPrivateKey(e,t,s){const r=await this.sign(s.algorithm,t,e);return"ECDSA"===s.algorithm.name?function(e){if(e.byteLength%2!=0)return $r;const t=e.byteLength/2,s=new ArrayBuffer(t);new Uint8Array(s).set(new Uint8Array(e,0,t));const r=new Ns({valueHex:s}),n=new ArrayBuffer(t);new Uint8Array(n).set(new Uint8Array(e,t,t));const a=new Ns({valueHex:n});return new Os({value:[r.convertToDER(),a.convertToDER()]}).toBER(!1)}(r):r}fillPublicKeyParameters(e,t){const s={},r=this.getHashAlgorithm(t);if(r===Fr)throw new Error(`Unsupported signature algorithm: ${t.algorithmId}`);let n;n="1.2.840.113549.1.1.10"===t.algorithmId?t.algorithmId:e.algorithm.algorithmId;const a=this.getAlgorithmByOID(n,!0);if(s.algorithm=this.getAlgorithmParameters(a.name,"importKey"),"hash"in s.algorithm.algorithm&&(s.algorithm.algorithm.hash.name=r),"ECDSA"===a.name){const t=e.algorithm;if(!t.algorithmParams)throw new Error("Algorithm parameters for ECDSA public key are missed");const r=t.algorithmParams;if("idBlock"in t.algorithmParams&&(1!==r.idBlock.tagClass||6!==r.idBlock.tagNumber))throw new Error("Incorrect type for ECDSA public key parameters");const n=this.getAlgorithmByOID(r.valueBlock.toString(),!0);s.algorithm.algorithm.namedCurve=n.name}return s}async getPublicKey(e,t,s){s||(s=this.fillPublicKeyParameters(e,t));const r=e.toSchema().toBER(!1);return this.importKey("spki",r,s.algorithm.algorithm,!0,s.algorithm.usages)}async verifyWithPublicKey(e,t,s,r,n){let a;if(n){const e={};let t;t="1.2.840.113549.1.1.10"===r.algorithmId?r.algorithmId:s.algorithm.algorithmId;const i=this.getAlgorithmByOID(t,!0);if(e.algorithm=this.getAlgorithmParameters(i.name,"importKey"),"hash"in e.algorithm.algorithm&&(e.algorithm.algorithm.hash.name=n),"ECDSA"===i.name){let t=!1;if("algorithmParams"in s.algorithm==!0&&"idBlock"in s.algorithm.algorithmParams&&1===s.algorithm.algorithmParams.idBlock.tagClass&&6===s.algorithm.algorithmParams.idBlock.tagNumber&&(t=!0),!1===t)throw new Error("Incorrect type for ECDSA public key parameters");const r=this.getAlgorithmByOID(s.algorithm.algorithmParams.valueBlock.toString(),!0);e.algorithm.algorithm.namedCurve=r.name}a=await this.getPublicKey(s,null,e)}else{if(!(n=this.getHashAlgorithm(r)))throw new Error(`Unsupported signature algorithm: ${r.algorithmId}`);a=await this.getPublicKey(s,r)}const i=this.getAlgorithmParameters(a.algorithm.name,"verify");"hash"in i.algorithm&&(i.algorithm.hash.name=n);let o=t.valueBlock.valueHexView;if("ECDSA"===a.algorithm.name){const e=Ui.find(a.algorithm.namedCurve);if(!e)throw new Error("Unsupported named curve in use");const t=ls(o);Gr.assert(t,"Signature value"),o=function(e,t){if(!(e instanceof Os&&2===e.valueBlock.value.length&&e.valueBlock.value[0]instanceof Ns&&e.valueBlock.value[1]instanceof Ns))return $r;const s=e.valueBlock.value[0].convertFromDER().valueBlock.valueHexView,r=e.valueBlock.value[1].convertFromDER().valueBlock.valueHexView,n=new Uint8Array(2*t);return n.set(s,t-s.byteLength),n.set(r,2*t-r.byteLength),n.buffer}(t.result,e.size)}if("RSA-PSS"===a.algorithm.name){const e=new Uo({schema:r.algorithmParams});i.algorithm.saltLength="saltLength"in e?e.saltLength:20;let t="SHA-1";if("hashAlgorithm"in e){t=this.getAlgorithmByOID(e.hashAlgorithm.algorithmId,!0).name}i.algorithm.hash.name=t}return this.verify(i.algorithm,a,o,e)}}let Yo={name:"none",crypto:null};function Qo(e){return!(!e||"object"!=typeof e||!("crypto"in e))}function Zo(e,...t){let s=null;if(t.length<2)s=t.length?t[0]:"undefined"!=typeof self&&self.crypto?new zo({name:"browser",crypto:self.crypto}):null;else{const e=t[0],r=t[1];Qo(r)?s=r:Qo(e)?s=e:"subtle"in e&&"getRandomValues"in e&&(s=new zo({crypto:e}))}if("undefined"!=typeof process&&"pid"in process&&"undefined"!=typeof global&&"undefined"==typeof window){if(void 0===global[process.pid])global[process.pid]={};else if("object"!=typeof global[process.pid])throw new Error(`Name global.${process.pid} already exists and it is not an object`);if(void 0===global[process.pid].pkijs)global[process.pid].pkijs={};else if("object"!=typeof global[process.pid].pkijs)throw new Error(`Name global.${process.pid}.pkijs already exists and it is not an object`);global[process.pid].pkijs.engine={name:e,crypto:s}}else Yo={name:e,crypto:s}}function Xo(e=!1){const t=function(){if("undefined"!=typeof process&&"pid"in process&&"undefined"!=typeof global&&"undefined"==typeof window){let e;try{e=global[process.pid].pkijs.engine}catch{throw new Error("Please call 'setEngine' before call to 'getEngine'")}return e}return Yo}();if(!t.crypto&&e)throw new Error("Unable to create WebCrypto object");return t.crypto}async function el(e,t,s,r,n){switch(e.toUpperCase()){case"SHA-1":case"SHA-256":case"SHA-384":case"SHA-512":break;default:throw new qr(`Unknown hash function: ${e}`)}if(qr.assert(t,"zBuffer","ArrayBuffer"),0===t.byteLength)throw new qr("'zBuffer' has zero length, error");if(qr.assert(r,"SharedInfo","ArrayBuffer"),s>255)throw new qr("Please set 'Counter' argument to value less or equal to 255");const a=new ArrayBuffer(4),i=new Uint8Array(a);i[0]=0,i[1]=0,i[2]=0,i[3]=s;let o=$r;o=Je(o,t),o=Je(o,a),o=Je(o,r);return{counter:s,result:await n.digest({name:e},o)}}async function tl(e,t,s,r,n=Xo(!0)){let a=0,i=1;switch(e.toUpperCase()){case"SHA-1":a=160;break;case"SHA-256":a=256;break;case"SHA-384":a=384;break;case"SHA-512":a=512;break;default:throw new qr(`Unknown hash function: ${e}`)}if(qr.assert(t,"Zbuffer","ArrayBuffer"),0===t.byteLength)throw new qr("'Zbuffer' has zero length, error");qr.assert(r,"SharedInfo","ArrayBuffer");const o=s/a;Math.floor(o)>0&&(i=Math.floor(o),o-i>0&&i++);const l=[];for(let s=1;s<=i;s++)l.push(await el(e,t,s,r,n));let c=$r,u=1,h=!0;for(;h;){h=!1;for(const e of l)if(e.counter===u){c=Je(c,e.result),h=!0;break}u++}if(s>>=3,c.byteLength>s){const e=new ArrayBuffer(s),t=new Uint8Array(e),r=new Uint8Array(c);for(let e=0;e<s;e++)t[e]=r[e];return e}return c}const sl="version",rl="logID",nl="extensions",al="timestamp",il="hashAlgorithm",ol="signatureAlgorithm",ll="signature",cl="none",ul="sha1",hl="sha224",ml="sha256",fl="sha384",dl="sha512",gl="anonymous",pl="ecdsa";class wl extends zr{constructor(e={}){super(),this.version=He(e,sl,wl.defaultValues(sl)),this.logID=He(e,rl,wl.defaultValues(rl)),this.timestamp=He(e,al,wl.defaultValues(al)),this.extensions=He(e,nl,wl.defaultValues(nl)),this.hashAlgorithm=He(e,il,wl.defaultValues(il)),this.signatureAlgorithm=He(e,ol,wl.defaultValues(ol)),this.signature=He(e,ll,wl.defaultValues(ll)),"stream"in e&&e.stream&&this.fromStream(e.stream),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case sl:return 0;case rl:case nl:return $r;case al:return new Date(0);case il:case ol:return Fr;case ll:return $r;default:return super.defaultValues(e)}}fromSchema(e){if(e instanceof lr==!1)throw new Error("Object's schema was not verified against input data for SignedCertificateTimestamp");const t=new hr({stream:new ur({buffer:e.data})});this.fromStream(t)}fromStream(e){const t=e.getUint16();if(this.version=e.getBlock(1)[0],0===this.version){this.logID=new Uint8Array(e.getBlock(32)).buffer.slice(0),this.timestamp=new Date(Me(new Uint8Array(e.getBlock(8)),8));const s=e.getUint16();switch(this.extensions=new Uint8Array(e.getBlock(s)).buffer.slice(0),e.getBlock(1)[0]){case 0:this.hashAlgorithm=cl;break;case 1:this.hashAlgorithm="md5";break;case 2:this.hashAlgorithm=ul;break;case 3:this.hashAlgorithm=hl;break;case 4:this.hashAlgorithm=ml;break;case 5:this.hashAlgorithm=fl;break;case 6:this.hashAlgorithm=dl;break;default:throw new Error("Object's stream was not correct for SignedCertificateTimestamp")}switch(e.getBlock(1)[0]){case 0:this.signatureAlgorithm=gl;break;case 1:this.signatureAlgorithm="rsa";break;case 2:this.signatureAlgorithm="dsa";break;case 3:this.signatureAlgorithm=pl;break;default:throw new Error("Object's stream was not correct for SignedCertificateTimestamp")}const r=e.getUint16();if(this.signature=new Uint8Array(e.getBlock(r)).buffer.slice(0),t!==47+s+r)throw new Error("Object's stream was not correct for SignedCertificateTimestamp")}}toSchema(){const e=this.toStream();return new lr({data:e.stream.buffer})}toStream(){const e=new hr;e.appendUint16(47+this.extensions.byteLength+this.signature.byteLength),e.appendChar(this.version),e.appendView(new Uint8Array(this.logID));const t=new ArrayBuffer(8),s=new Uint8Array(t),r=je(this.timestamp.valueOf(),8);let n,a;switch(s.set(new Uint8Array(r),8-r.byteLength),e.appendView(s),e.appendUint16(this.extensions.byteLength),this.extensions.byteLength&&e.appendView(new Uint8Array(this.extensions)),this.hashAlgorithm.toLowerCase()){case cl:n=0;break;case"md5":n=1;break;case ul:n=2;break;case hl:n=3;break;case ml:n=4;break;case fl:n=5;break;case dl:n=6;break;default:throw new Error(`Incorrect data for hashAlgorithm: ${this.hashAlgorithm}`)}switch(e.appendChar(n),this.signatureAlgorithm.toLowerCase()){case gl:a=0;break;case"rsa":a=1;break;case"dsa":a=2;break;case pl: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:Ke(this.logID),timestamp:this.timestamp,extensions:Ke(this.extensions),hashAlgorithm:this.hashAlgorithm,signatureAlgorithm:this.signatureAlgorithm,signature:Ke(this.signature)}}async verify(e,t,s=0,r=Xo(!0)){const n=Ye(Ze(this.logID));let a=null;const i=new hr;for(const t of e)if(t.log_id===n){a=t.key;break}if(!a)throw new Error(`Public key not found for CT with logId: ${n}`);const o=Xe(Qe(a)),l=Wi.fromBER(o);i.appendChar(0),i.appendChar(0);const c=new ArrayBuffer(8),u=new Uint8Array(c),h=je(this.timestamp.valueOf(),8);return u.set(new Uint8Array(h),8-h.byteLength),i.appendView(u),i.appendUint16(s),0===s&&i.appendUint24(t.byteLength),i.appendView(new Uint8Array(t)),i.appendUint16(this.extensions.byteLength),0!==this.extensions.byteLength&&i.appendView(new Uint8Array(this.extensions)),r.verifyWithPublicKey(i.buffer.slice(0,i.length),new ws({valueHex:this.signature}),l,{algorithmId:Fr},"SHA-256")}}wl.CLASS_NAME="SignedCertificateTimestamp";const yl="timestamps";class vl extends zr{constructor(e={}){super(),this.timestamps=He(e,yl,vl.defaultValues(yl)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===yl?[]:super.defaultValues(e)}static compareWithDefault(e,t){return e===yl?0===t.length:super.defaultValues(e)}static schema(e={}){var t;const s=He(e,"names",{});return null!==(t=s.optional)&&void 0!==t||(s.optional=!1),new ws({name:s.blockName||"SignedCertificateTimestampList",optional:s.optional})}fromSchema(e){if(e instanceof ws==!1)throw new Error("Object's schema was not verified against input data for SignedCertificateTimestampList");const t=new hr({stream:new ur({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 wl({stream:t}))}toSchema(){const e=new hr;let t=0;const s=[];for(const e of this.timestamps){const r=e.toStream();s.push(r),t+=r.stream.buffer.byteLength}e.appendUint16(t);for(const t of s)e.appendView(t.stream.view);return new ws({valueHex:e.stream.buffer.slice(0)})}toJSON(){return{timestamps:Array.from(this.timestamps,(e=>e.toJSON()))}}}vl.CLASS_NAME="SignedCertificateTimestampList";const bl="attributes",Sl=[bl];class kl extends zr{constructor(e={}){super(),this.attributes=He(e,bl,kl.defaultValues(bl)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===bl?[]:super.defaultValues(e)}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new or({name:t.attributes||Fr,value:xn.schema()})]})}fromSchema(e){st(e,Sl);const t=cr(e,e,kl.schema({names:{attributes:bl}}));Gr.assertSchema(t,this.className),this.attributes=Array.from(t.result.attributes,(e=>new xn({schema:e})))}toSchema(){return new Os({value:Array.from(this.attributes,(e=>e.toSchema()))})}toJSON(){return{attributes:Array.from(this.attributes,(e=>e.toJSON()))}}}kl.CLASS_NAME="SubjectDirectoryAttributes";class Al{static getItems(){return this.types||(this.types={},Al.register(_n,"SubjectAltName",Cn),Al.register(Hn,"IssuerAltName",Cn),Al.register(zn,"AuthorityKeyIdentifier",ua),Al.register(Kn,"BasicConstraints",fa),Al.register("1.3.6.1.4.1.311.21.1","MicrosoftCaVersion",pa),Al.register(qn,"CertificatePolicies",Ia),Al.register("1.3.6.1.4.1.311.21.10","CertificatePoliciesMicrosoft",Ia),Al.register("1.3.6.1.4.1.311.21.7","MicrosoftCertTemplateV2",Oa),Al.register($n,"CRLDistributionPoints",ja),Al.register(Fn,"FreshestCRL",ja),Al.register("2.5.29.37","ExtKeyUsage",Fa),Al.register(jn,"CertificateIssuer",Rn),Al.register(Qn,"AuthorityInfoAccess",Wa),Al.register("1.3.6.1.5.5.7.1.11","SubjectInfoAccess",Wa),Al.register(Mn,"IssuingDistributionPoint",si),Al.register(Jn,"NameConstraints",hi),Al.register(Yn,"PolicyConstraints",gi),Al.register(Gn,"PolicyMappings",ki),Al.register("2.5.29.16","PrivateKeyUsagePeriod",Ci),Al.register("1.3.6.1.5.5.7.1.3","QCStatements",Ti),Al.register("1.3.6.1.4.1.11129.2.4.2","SignedCertificateTimestampList",vl),Al.register("2.5.29.9","SubjectDirectoryAttributes",kl)),this.types}static fromBER(e,t){const s=ls(t);if(-1===s.offset)return null;const r=this.find(e);if(r)try{return new r.type({schema:s.result})}catch{const t=new r.type;return t.parsingError=`Incorrectly formatted value of extension ${r.name} (${e})`,t}return s.result}static find(e){return this.getItems()[e]||null}static register(e,t,s){this.getItems()[e]={name:t,type:s}}}const Nl="extnID",El="critical",Cl="extnValue",Il="parsedValue",Bl=[Nl,El,Cl];class Vl extends zr{get parsedValue(){if(void 0===this._parsedValue){const e=Al.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=He(e,Nl,Vl.defaultValues(Nl)),this.critical=He(e,El,Vl.defaultValues(El)),this.extnValue=Cl in e?new ws({valueHex:e.extnValue}):Vl.defaultValues(Cl),Il in e&&(this.parsedValue=He(e,Il,Vl.defaultValues(Il))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Nl:return Fr;case El:return!1;case Cl:return new ws;case Il:return{};default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.extnID||Fr}),new gs({name:t.critical||Fr,optional:!0}),new ws({name:t.extnValue||Fr})]})}fromSchema(e){st(e,Bl);const t=cr(e,e,Vl.schema({names:{extnID:Nl,critical:El,extnValue:Cl}}));Gr.assertSchema(t,this.className),this.extnID=t.result.extnID.valueBlock.toString(),El in t.result&&(this.critical=t.result.critical.valueBlock.value),this.extnValue=t.result.extnValue}toSchema(){const e=[];return e.push(new Bs({value:this.extnID})),this.critical!==Vl.defaultValues(El)&&e.push(new gs({value:this.critical})),e.push(this.extnValue),new Os({value:e})}toJSON(){const e={extnID:this.extnID,extnValue:this.extnValue.toJSON()};return this.critical!==Vl.defaultValues(El)&&(e.critical=this.critical),this.parsedValue&&this.parsedValue.toJSON&&(e.parsedValue=this.parsedValue.toJSON()),e}}Vl.CLASS_NAME="Extension";const xl="extensions",Dl=[xl];class Ol extends zr{constructor(e={}){super(),this.extensions=He(e,xl,Ol.defaultValues(xl)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===xl?[]:super.defaultValues(e)}static schema(e={},t=!1){const s=He(e,"names",{});return new Os({optional:t,name:s.blockName||Fr,value:[new or({name:s.extensions||Fr,value:Vl.schema(s.extension||{})})]})}fromSchema(e){st(e,Dl);const t=cr(e,e,Ol.schema({names:{extensions:xl}}));Gr.assertSchema(t,this.className),this.extensions=Array.from(t.result.extensions,(e=>new Vl({schema:e})))}toSchema(){return new Os({value:Array.from(this.extensions,(e=>e.toSchema()))})}toJSON(){return{extensions:this.extensions.map((e=>e.toJSON()))}}}Ol.CLASS_NAME="Extensions";const Tl="issuer",Pl="serialNumber",Ul="issuerUID",Ll=[Tl,Pl,Ul];class Rl extends zr{constructor(e={}){super(),this.issuer=He(e,Tl,Rl.defaultValues(Tl)),this.serialNumber=He(e,Pl,Rl.defaultValues(Pl)),Ul in e&&(this.issuerUID=He(e,Ul,Rl.defaultValues(Ul))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Tl:return new Rn;case Pl:return new Ns;case Ul:return new vs;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[Rn.schema(t.issuer||{}),new Ns({name:t.serialNumber||Fr}),new vs({optional:!0,name:t.issuerUID||Fr})]})}fromSchema(e){st(e,Ll);const t=cr(e,e,Rl.schema({names:{issuer:{names:{blockName:Tl}},serialNumber:Pl,issuerUID:Ul}}));Gr.assertSchema(t,this.className),this.issuer=new Rn({schema:t.result.issuer}),this.serialNumber=t.result.serialNumber,Ul in t.result&&(this.issuerUID=t.result.issuerUID)}toSchema(){const e=new Os({value:[this.issuer.toSchema(),this.serialNumber]});return this.issuerUID&&e.valueBlock.value.push(this.issuerUID),e}toJSON(){const e={issuer:this.issuer.toJSON(),serialNumber:this.serialNumber.toJSON()};return this.issuerUID&&(e.issuerUID=this.issuerUID.toJSON()),e}}Rl.CLASS_NAME="IssuerSerial";const _l="version",Hl="baseCertificateID",Kl="subjectName",Ml="issuer",jl="signature",Jl="serialNumber",$l="attrCertValidityPeriod",Fl="attributes",ql="issuerUniqueID",Wl="extensions",Gl=[_l,Hl,Kl,Ml,jl,Jl,$l,Fl,ql,Wl];class zl extends zr{constructor(e={}){super(),this.version=He(e,_l,zl.defaultValues(_l)),Hl in e&&(this.baseCertificateID=He(e,Hl,zl.defaultValues(Hl))),Kl in e&&(this.subjectName=He(e,Kl,zl.defaultValues(Kl))),this.issuer=He(e,Ml,zl.defaultValues(Ml)),this.signature=He(e,jl,zl.defaultValues(jl)),this.serialNumber=He(e,Jl,zl.defaultValues(Jl)),this.attrCertValidityPeriod=He(e,$l,zl.defaultValues($l)),this.attributes=He(e,Fl,zl.defaultValues(Fl)),ql in e&&(this.issuerUniqueID=He(e,ql,zl.defaultValues(ql))),Wl in e&&(this.extensions=He(e,Wl,zl.defaultValues(Wl))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case _l:return 0;case Hl:return new Rl;case Kl:case Ml:return new Rn;case jl:return new An;case Jl:return new Ns;case $l:return new Pn;case Fl:return[];case ql:return new vs;case Wl:return new Ol;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Ns({name:t.version||Fr}),new ir({value:[new us({name:t.baseCertificateID||Fr,idBlock:{tagClass:3,tagNumber:0},value:Rl.schema().valueBlock.value}),new us({name:t.subjectName||Fr,idBlock:{tagClass:3,tagNumber:1},value:Rn.schema().valueBlock.value})]}),Rn.schema({names:{blockName:t.issuer||Fr}}),An.schema(t.signature||{}),new Ns({name:t.serialNumber||Fr}),Pn.schema(t.attrCertValidityPeriod||{}),new Os({name:t.attributes||Fr,value:[new or({value:xn.schema()})]}),new vs({optional:!0,name:t.issuerUniqueID||Fr}),Ol.schema(t.extensions||{},!0)]})}fromSchema(e){st(e,Gl);const t=cr(e,e,zl.schema({names:{version:_l,baseCertificateID:Hl,subjectName:Kl,issuer:Ml,signature:{names:{blockName:jl}},serialNumber:Jl,attrCertValidityPeriod:{names:{blockName:$l}},attributes:Fl,issuerUniqueID:ql,extensions:{names:{blockName:Wl}}}}));Gr.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,Hl in t.result&&(this.baseCertificateID=new Rl({schema:new Os({value:t.result.baseCertificateID.valueBlock.value})})),Kl in t.result&&(this.subjectName=new Rn({schema:new Os({value:t.result.subjectName.valueBlock.value})})),this.issuer=t.result.issuer,this.signature=new An({schema:t.result.signature}),this.serialNumber=t.result.serialNumber,this.attrCertValidityPeriod=new Pn({schema:t.result.attrCertValidityPeriod}),this.attributes=Array.from(t.result.attributes.valueBlock.value,(e=>new xn({schema:e}))),ql in t.result&&(this.issuerUniqueID=t.result.issuerUniqueID),Wl in t.result&&(this.extensions=new Ol({schema:t.result.extensions}))}toSchema(){const e=new Os({value:[new Ns({value:this.version})]});return this.baseCertificateID&&e.valueBlock.value.push(new us({idBlock:{tagClass:3,tagNumber:0},value:this.baseCertificateID.toSchema().valueBlock.value})),this.subjectName&&e.valueBlock.value.push(new us({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 Os({value:Array.from(this.attributes,(e=>e.toSchema()))})),this.issuerUniqueID&&e.valueBlock.value.push(this.issuerUniqueID),this.extensions&&e.valueBlock.value.push(this.extensions.toSchema()),e}toJSON(){const 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,(e=>e.toJSON())),this.issuerUniqueID&&(e.issuerUniqueID=this.issuerUniqueID.toJSON()),this.extensions&&(e.extensions=this.extensions.toJSON()),e}}zl.CLASS_NAME="AttributeCertificateInfoV1";const Yl="acinfo",Ql="signatureAlgorithm",Zl="signatureValue",Xl=[Yl,Zl,Ql];class ec extends zr{constructor(e={}){super(),this.acinfo=He(e,Yl,ec.defaultValues(Yl)),this.signatureAlgorithm=He(e,Ql,ec.defaultValues(Ql)),this.signatureValue=He(e,Zl,ec.defaultValues(Zl)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Yl:return new zl;case Ql:return new An;case Zl:return new vs;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[zl.schema(t.acinfo||{}),An.schema(t.signatureAlgorithm||{}),new vs({name:t.signatureValue||Fr})]})}fromSchema(e){st(e,Xl);const t=cr(e,e,ec.schema({names:{acinfo:{names:{blockName:Yl}},signatureAlgorithm:{names:{blockName:Ql}},signatureValue:Zl}}));Gr.assertSchema(t,this.className),this.acinfo=new zl({schema:t.result.acinfo}),this.signatureAlgorithm=new An({schema:t.result.signatureAlgorithm}),this.signatureValue=t.result.signatureValue}toSchema(){return new Os({value:[this.acinfo.toSchema(),this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){return{acinfo:this.acinfo.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()}}}ec.CLASS_NAME="AttributeCertificateV1";const tc="digestedObjectType",sc="otherObjectTypeID",rc="digestAlgorithm",nc="objectDigest",ac=[tc,sc,rc,nc];class ic extends zr{constructor(e={}){super(),this.digestedObjectType=He(e,tc,ic.defaultValues(tc)),sc in e&&(this.otherObjectTypeID=He(e,sc,ic.defaultValues(sc))),this.digestAlgorithm=He(e,rc,ic.defaultValues(rc)),this.objectDigest=He(e,nc,ic.defaultValues(nc)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case tc:return new Es;case sc:return new Bs;case rc:return new An;case nc:return new vs;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Es({name:t.digestedObjectType||Fr}),new Bs({optional:!0,name:t.otherObjectTypeID||Fr}),An.schema(t.digestAlgorithm||{}),new vs({name:t.objectDigest||Fr})]})}fromSchema(e){st(e,ac);const t=cr(e,e,ic.schema({names:{digestedObjectType:tc,otherObjectTypeID:sc,digestAlgorithm:{names:{blockName:rc}},objectDigest:nc}}));Gr.assertSchema(t,this.className),this.digestedObjectType=t.result.digestedObjectType,sc in t.result&&(this.otherObjectTypeID=t.result.otherObjectTypeID),this.digestAlgorithm=new An({schema:t.result.digestAlgorithm}),this.objectDigest=t.result.objectDigest}toSchema(){const e=new Os({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(){const e={digestedObjectType:this.digestedObjectType.toJSON(),digestAlgorithm:this.digestAlgorithm.toJSON(),objectDigest:this.objectDigest.toJSON()};return this.otherObjectTypeID&&(e.otherObjectTypeID=this.otherObjectTypeID.toJSON()),e}}ic.CLASS_NAME="ObjectDigestInfo";const oc="issuerName",lc="baseCertificateID",cc="objectDigestInfo",uc=[oc,lc,cc];class hc extends zr{constructor(e={}){super(),oc in e&&(this.issuerName=He(e,oc,hc.defaultValues(oc))),lc in e&&(this.baseCertificateID=He(e,lc,hc.defaultValues(lc))),cc in e&&(this.objectDigestInfo=He(e,cc,hc.defaultValues(cc))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case oc:return new Rn;case lc:return new Rl;case cc:return new ic;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[Rn.schema({names:{blockName:t.issuerName}},!0),new us({optional:!0,name:t.baseCertificateID||Fr,idBlock:{tagClass:3,tagNumber:0},value:Rl.schema().valueBlock.value}),new us({optional:!0,name:t.objectDigestInfo||Fr,idBlock:{tagClass:3,tagNumber:1},value:ic.schema().valueBlock.value})]})}fromSchema(e){st(e,uc);const t=cr(e,e,hc.schema({names:{issuerName:oc,baseCertificateID:lc,objectDigestInfo:cc}}));Gr.assertSchema(t,this.className),oc in t.result&&(this.issuerName=new Rn({schema:t.result.issuerName})),lc in t.result&&(this.baseCertificateID=new Rl({schema:new Os({value:t.result.baseCertificateID.valueBlock.value})})),cc in t.result&&(this.objectDigestInfo=new ic({schema:new Os({value:t.result.objectDigestInfo.valueBlock.value})}))}toSchema(){const e=new Os;return this.issuerName&&e.valueBlock.value.push(this.issuerName.toSchema()),this.baseCertificateID&&e.valueBlock.value.push(new us({idBlock:{tagClass:3,tagNumber:0},value:this.baseCertificateID.toSchema().valueBlock.value})),this.objectDigestInfo&&e.valueBlock.value.push(new us({idBlock:{tagClass:3,tagNumber:1},value:this.objectDigestInfo.toSchema().valueBlock.value})),e}toJSON(){const e={};return this.issuerName&&(e.issuerName=this.issuerName.toJSON()),this.baseCertificateID&&(e.baseCertificateID=this.baseCertificateID.toJSON()),this.objectDigestInfo&&(e.objectDigestInfo=this.objectDigestInfo.toJSON()),e}}hc.CLASS_NAME="V2Form";const mc="baseCertificateID",fc="entityName",dc="objectDigestInfo",gc=[mc,fc,dc];class pc extends zr{constructor(e={}){super(),mc in e&&(this.baseCertificateID=He(e,mc,pc.defaultValues(mc))),fc in e&&(this.entityName=He(e,fc,pc.defaultValues(fc))),dc in e&&(this.objectDigestInfo=He(e,dc,pc.defaultValues(dc))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case mc:return new Rl;case fc:return new Rn;case dc:return new ic;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new us({optional:!0,name:t.baseCertificateID||Fr,idBlock:{tagClass:3,tagNumber:0},value:Rl.schema().valueBlock.value}),new us({optional:!0,name:t.entityName||Fr,idBlock:{tagClass:3,tagNumber:1},value:Rn.schema().valueBlock.value}),new us({optional:!0,name:t.objectDigestInfo||Fr,idBlock:{tagClass:3,tagNumber:2},value:ic.schema().valueBlock.value})]})}fromSchema(e){st(e,gc);const t=cr(e,e,pc.schema({names:{baseCertificateID:mc,entityName:fc,objectDigestInfo:dc}}));Gr.assertSchema(t,this.className),mc in t.result&&(this.baseCertificateID=new Rl({schema:new Os({value:t.result.baseCertificateID.valueBlock.value})})),fc in t.result&&(this.entityName=new Rn({schema:new Os({value:t.result.entityName.valueBlock.value})})),dc in t.result&&(this.objectDigestInfo=new ic({schema:new Os({value:t.result.objectDigestInfo.valueBlock.value})}))}toSchema(){const e=new Os;return this.baseCertificateID&&e.valueBlock.value.push(new us({idBlock:{tagClass:3,tagNumber:0},value:this.baseCertificateID.toSchema().valueBlock.value})),this.entityName&&e.valueBlock.value.push(new us({idBlock:{tagClass:3,tagNumber:1},value:this.entityName.toSchema().valueBlock.value})),this.objectDigestInfo&&e.valueBlock.value.push(new us({idBlock:{tagClass:3,tagNumber:2},value:this.objectDigestInfo.toSchema().valueBlock.value})),e}toJSON(){const e={};return this.baseCertificateID&&(e.baseCertificateID=this.baseCertificateID.toJSON()),this.entityName&&(e.entityName=this.entityName.toJSON()),this.objectDigestInfo&&(e.objectDigestInfo=this.objectDigestInfo.toJSON()),e}}pc.CLASS_NAME="Holder";const wc="version",yc="holder",vc="issuer",bc="signature",Sc="serialNumber",kc="attrCertValidityPeriod",Ac="attributes",Nc="issuerUniqueID",Ec="extensions",Cc=[wc,yc,vc,bc,Sc,kc,Ac,Nc,Ec];class Ic extends zr{constructor(e={}){super(),this.version=He(e,wc,Ic.defaultValues(wc)),this.holder=He(e,yc,Ic.defaultValues(yc)),this.issuer=He(e,vc,Ic.defaultValues(vc)),this.signature=He(e,bc,Ic.defaultValues(bc)),this.serialNumber=He(e,Sc,Ic.defaultValues(Sc)),this.attrCertValidityPeriod=He(e,kc,Ic.defaultValues(kc)),this.attributes=He(e,Ac,Ic.defaultValues(Ac)),Nc in e&&(this.issuerUniqueID=He(e,Nc,Ic.defaultValues(Nc))),Ec in e&&(this.extensions=He(e,Ec,Ic.defaultValues(Ec))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case wc:return 1;case yc:return new pc;case vc:return{};case bc:return new An;case Sc:return new Ns;case kc:return new Pn;case Ac:return[];case Nc:return new vs;case Ec:return new Ol;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Ns({name:t.version||Fr}),pc.schema(t.holder||{}),new ir({value:[Rn.schema({names:{blockName:t.issuer||Fr}}),new us({name:t.issuer||Fr,idBlock:{tagClass:3,tagNumber:0},value:hc.schema().valueBlock.value})]}),An.schema(t.signature||{}),new Ns({name:t.serialNumber||Fr}),Pn.schema(t.attrCertValidityPeriod||{}),new Os({name:t.attributes||Fr,value:[new or({value:xn.schema()})]}),new vs({optional:!0,name:t.issuerUniqueID||Fr}),Ol.schema(t.extensions||{},!0)]})}fromSchema(e){st(e,Cc);const t=cr(e,e,Ic.schema({names:{version:wc,holder:{names:{blockName:yc}},issuer:vc,signature:{names:{blockName:bc}},serialNumber:Sc,attrCertValidityPeriod:{names:{blockName:kc}},attributes:Ac,issuerUniqueID:Nc,extensions:{names:{blockName:Ec}}}}));if(Gr.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.holder=new pc({schema:t.result.holder}),3!==t.result.issuer.idBlock.tagClass)throw new Error("Incorrect value for 'issuer' in AttributeCertificateInfoV2");this.issuer=new hc({schema:new Os({value:t.result.issuer.valueBlock.value})}),this.signature=new An({schema:t.result.signature}),this.serialNumber=t.result.serialNumber,this.attrCertValidityPeriod=new Pn({schema:t.result.attrCertValidityPeriod}),this.attributes=Array.from(t.result.attributes.valueBlock.value,(e=>new xn({schema:e}))),Nc in t.result&&(this.issuerUniqueID=t.result.issuerUniqueID),Ec in t.result&&(this.extensions=new Ol({schema:t.result.extensions}))}toSchema(){const e=new Os({value:[new Ns({value:this.version}),this.holder.toSchema(),new us({idBlock:{tagClass:3,tagNumber:0},value:this.issuer.toSchema().valueBlock.value}),this.signature.toSchema(),this.serialNumber,this.attrCertValidityPeriod.toSchema(),new Os({value:Array.from(this.attributes,(e=>e.toSchema()))})]});return this.issuerUniqueID&&e.valueBlock.value.push(this.issuerUniqueID),this.extensions&&e.valueBlock.value.push(this.extensions.toSchema()),e}toJSON(){const 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,(e=>e.toJSON()))};return this.issuerUniqueID&&(e.issuerUniqueID=this.issuerUniqueID.toJSON()),this.extensions&&(e.extensions=this.extensions.toJSON()),e}}Ic.CLASS_NAME="AttributeCertificateInfoV2";const Bc="acinfo",Vc="signatureAlgorithm",xc="signatureValue",Dc=[Bc,Vc,xc];class Oc extends zr{constructor(e={}){super(),this.acinfo=He(e,Bc,Oc.defaultValues(Bc)),this.signatureAlgorithm=He(e,Vc,Oc.defaultValues(Vc)),this.signatureValue=He(e,xc,Oc.defaultValues(xc)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Bc:return new Ic;case Vc:return new An;case xc:return new vs;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[Ic.schema(t.acinfo||{}),An.schema(t.signatureAlgorithm||{}),new vs({name:t.signatureValue||Fr})]})}fromSchema(e){st(e,Dc);const t=cr(e,e,Oc.schema({names:{acinfo:{names:{blockName:Bc}},signatureAlgorithm:{names:{blockName:Vc}},signatureValue:xc}}));Gr.assertSchema(t,this.className),this.acinfo=new Ic({schema:t.result.acinfo}),this.signatureAlgorithm=new An({schema:t.result.signatureAlgorithm}),this.signatureValue=t.result.signatureValue}toSchema(){return new Os({value:[this.acinfo.toSchema(),this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){return{acinfo:this.acinfo.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()}}}Oc.CLASS_NAME="AttributeCertificateV2";const Tc="contentType",Pc="content",Uc=[Tc,Pc];class Lc extends zr{constructor(e={}){super(),this.contentType=He(e,Tc,Lc.defaultValues(Tc)),this.content=He(e,Pc,Lc.defaultValues(Pc)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Tc:return Fr;case Pc:return new ar;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Tc:return"string"==typeof t&&t===this.defaultValues(Tc);case Pc:return t instanceof ar;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return"optional"in t==!1&&(t.optional=!1),new Os({name:t.blockName||"ContentInfo",optional:t.optional,value:[new Bs({name:t.contentType||Tc}),new us({idBlock:{tagClass:3,tagNumber:0},value:[new ar({name:t.content||Pc})]})]})}fromSchema(e){st(e,Uc);const t=cr(e,e,Lc.schema());Gr.assertSchema(t,this.className),this.contentType=t.result.contentType.valueBlock.toString(),this.content=t.result.content}toSchema(){return new Os({value:[new Bs({value:this.contentType}),new us({idBlock:{tagClass:3,tagNumber:0},value:[this.content]})]})}toJSON(){const e={contentType:this.contentType};return this.content instanceof ar||(e.content=this.content.toJSON()),e}}Lc.CLASS_NAME="ContentInfo",Lc.DATA=Zn,Lc.SIGNED_DATA=Xn,Lc.ENVELOPED_DATA=ea,Lc.ENCRYPTED_DATA=ta;const Rc="type",_c="value",Hc="utcTimeName",Kc="generalTimeName",Mc=[Hc,Kc];var jc;!function(e){e[e.UTCTime=0]="UTCTime",e[e.GeneralizedTime=1]="GeneralizedTime",e[e.empty=2]="empty"}(jc||(jc={}));class Jc extends zr{constructor(e={}){super(),this.type=He(e,Rc,Jc.defaultValues(Rc)),this.value=He(e,_c,Jc.defaultValues(_c)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Rc:return 0;case _c:return new Date(0,0,0);default:return super.defaultValues(e)}}static schema(e={},t=!1){const s=He(e,"names",{});return new ir({optional:t,value:[new Zs({name:s.utcTimeName||Fr}),new Xs({name:s.generalTimeName||Fr})]})}fromSchema(e){st(e,Mc);const t=cr(e,e,Jc.schema({names:{utcTimeName:Hc,generalTimeName:Kc}}));Gr.assertSchema(t,this.className),Hc in t.result&&(this.type=0,this.value=t.result.utcTimeName.toDate()),Kc in t.result&&(this.type=1,this.value=t.result.generalTimeName.toDate())}toSchema(){return 0===this.type?new Zs({valueDate:this.value}):1===this.type?new Xs({valueDate:this.value}):{}}toJSON(){return{type:this.type,value:this.value}}}Jc.CLASS_NAME="Time";const $c="tbs",Fc="version",qc="serialNumber",Wc="signature",Gc="issuer",zc="notBefore",Yc="notAfter",Qc="subject",Zc="subjectPublicKeyInfo",Xc="issuerUniqueID",eu="subjectUniqueID",tu="extensions",su="signatureAlgorithm",ru="signatureValue",nu="tbsCertificate",au=`${nu}.${Fc}`,iu=`${nu}.${qc}`,ou=`${nu}.${Wc}`,lu=`${nu}.${Gc}`,cu=`${nu}.${zc}`,uu=`${nu}.${Yc}`,hu=`${nu}.${Qc}`,mu=`${nu}.${Zc}`,fu=`${nu}.${Xc}`,du=`${nu}.${eu}`,gu=`${nu}.${tu}`,pu=[nu,au,iu,ou,lu,cu,uu,hu,mu,fu,du,gu,su,ru];function wu(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||nu,value:[new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new Ns({name:t.tbsCertificateVersion||au})]}),new Ns({name:t.tbsCertificateSerialNumber||iu}),An.schema(t.signature||{names:{blockName:ou}}),sn.schema(t.issuer||{names:{blockName:lu}}),new Os({name:t.tbsCertificateValidity||"tbsCertificate.validity",value:[Jc.schema(t.notBefore||{names:{utcTimeName:cu,generalTimeName:cu}}),Jc.schema(t.notAfter||{names:{utcTimeName:uu,generalTimeName:uu}})]}),sn.schema(t.subject||{names:{blockName:hu}}),Wi.schema(t.subjectPublicKeyInfo||{names:{blockName:mu}}),new is({name:t.tbsCertificateIssuerUniqueID||fu,optional:!0,idBlock:{tagClass:3,tagNumber:1}}),new is({name:t.tbsCertificateSubjectUniqueID||du,optional:!0,idBlock:{tagClass:3,tagNumber:2}}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:3},value:[Ol.schema(t.extensions||{names:{blockName:gu}})]})]})}class yu extends zr{get tbs(){return De.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e)}constructor(e={}){super(),this.tbsView=new Uint8Array(He(e,$c,yu.defaultValues($c))),this.version=He(e,Fc,yu.defaultValues(Fc)),this.serialNumber=He(e,qc,yu.defaultValues(qc)),this.signature=He(e,Wc,yu.defaultValues(Wc)),this.issuer=He(e,Gc,yu.defaultValues(Gc)),this.notBefore=He(e,zc,yu.defaultValues(zc)),this.notAfter=He(e,Yc,yu.defaultValues(Yc)),this.subject=He(e,Qc,yu.defaultValues(Qc)),this.subjectPublicKeyInfo=He(e,Zc,yu.defaultValues(Zc)),Xc in e&&(this.issuerUniqueID=He(e,Xc,yu.defaultValues(Xc))),eu in e&&(this.subjectUniqueID=He(e,eu,yu.defaultValues(eu))),tu in e&&(this.extensions=He(e,tu,yu.defaultValues(tu))),this.signatureAlgorithm=He(e,su,yu.defaultValues(su)),this.signatureValue=He(e,ru,yu.defaultValues(ru)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case $c:return $r;case Fc:return 0;case qc:return new Ns;case Wc:return new An;case Gc:return new sn;case zc:case Yc:return new Jc;case Qc:return new sn;case Zc:return new Wi;case Xc:case eu:return $r;case tu:return[];case su:return new An;case ru:return new vs;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[wu(t.tbsCertificate),An.schema(t.signatureAlgorithm||{names:{blockName:su}}),new vs({name:t.signatureValue||ru})]})}fromSchema(e){st(e,pu);const t=cr(e,e,yu.schema({names:{tbsCertificate:{names:{extensions:{names:{extensions:gu}}}}}}));Gr.assertSchema(t,this.className),this.tbsView=t.result.tbsCertificate.valueBeforeDecodeView,au in t.result&&(this.version=t.result[au].valueBlock.valueDec),this.serialNumber=t.result[iu],this.signature=new An({schema:t.result[ou]}),this.issuer=new sn({schema:t.result[lu]}),this.notBefore=new Jc({schema:t.result[cu]}),this.notAfter=new Jc({schema:t.result[uu]}),this.subject=new sn({schema:t.result[hu]}),this.subjectPublicKeyInfo=new Wi({schema:t.result[mu]}),fu in t.result&&(this.issuerUniqueID=t.result[fu].valueBlock.valueHex),du in t.result&&(this.subjectUniqueID=t.result[du].valueBlock.valueHex),gu in t.result&&(this.extensions=Array.from(t.result[gu],(e=>new Vl({schema:e})))),this.signatureAlgorithm=new An({schema:t.result.signatureAlgorithm}),this.signatureValue=t.result.signatureValue}encodeTBS(){const e=[];return Fc in this&&this.version!==yu.defaultValues(Fc)&&e.push(new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new Ns({value:this.version})]})),e.push(this.serialNumber),e.push(this.signature.toSchema()),e.push(this.issuer.toSchema()),e.push(new Os({value:[this.notBefore.toSchema(),this.notAfter.toSchema()]})),e.push(this.subject.toSchema()),e.push(this.subjectPublicKeyInfo.toSchema()),this.issuerUniqueID&&e.push(new is({optional:!0,idBlock:{tagClass:3,tagNumber:1},valueHex:this.issuerUniqueID})),this.subjectUniqueID&&e.push(new is({optional:!0,idBlock:{tagClass:3,tagNumber:2},valueHex:this.subjectUniqueID})),this.extensions&&e.push(new us({optional:!0,idBlock:{tagClass:3,tagNumber:3},value:[new Os({value:Array.from(this.extensions,(e=>e.toSchema()))})]})),new Os({value:e})}toSchema(e=!1){let t;if(!1===e){if(!this.tbsView.byteLength)return yu.schema().value[0];const e=ls(this.tbsView);Gr.assert(e,"TBS Certificate"),t=e.result}else t=this.encodeTBS();return new Os({value:[t,this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){const e={tbs:_e.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 Fc in this&&this.version!==yu.defaultValues(Fc)&&(e.version=this.version),this.issuerUniqueID&&(e.issuerUniqueID=_e.ToHex(this.issuerUniqueID)),this.subjectUniqueID&&(e.subjectUniqueID=_e.ToHex(this.subjectUniqueID)),this.extensions&&(e.extensions=Array.from(this.extensions,(e=>e.toJSON()))),e}async getPublicKey(e,t=Xo(!0)){return t.getPublicKey(this.subjectPublicKeyInfo,this.signatureAlgorithm,e)}async getKeyHash(e="SHA-1",t=Xo(!0)){return t.digest({name:e},this.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView)}async sign(e,t="SHA-1",s=Xo(!0)){if(!e)throw new Error("Need to provide a private key for signing");const r=await s.getSignatureParameters(e,t),n=r.parameters;this.signature=r.signatureAlgorithm,this.signatureAlgorithm=r.signatureAlgorithm,this.tbsView=new Uint8Array(this.encodeTBS().toBER());const a=await s.signWithPrivateKey(this.tbsView,e,n);this.signatureValue=new vs({valueHex:a})}async verify(e,t=Xo(!0)){let s;if(e?s=e.subjectPublicKeyInfo:this.issuer.isEqual(this.subject)&&(s=this.subjectPublicKeyInfo),!(s instanceof Wi))throw new Error("Please provide issuer certificate as a parameter");return t.verifyWithPublicKey(this.tbsView,this.signatureValue,s,this.signatureAlgorithm)}}function vu(e,t=null){if(t&&e.issuer.isEqual(t.issuer)&&e.serialNumber.isEqual(t.serialNumber))return null;let s=!1;if(e.extensions)for(const t of e.extensions)if(t.extnID===Kn&&t.parsedValue instanceof fa&&t.parsedValue.cA){s=!0;break}return s?e:null}yu.CLASS_NAME="Certificate";const bu="certId",Su="certValue",ku="parsedValue",Au=[bu,Su];class Nu extends zr{constructor(e={}){super(),this.certId=He(e,bu,Nu.defaultValues(bu)),this.certValue=He(e,Su,Nu.defaultValues(Su)),ku in e&&(this.parsedValue=He(e,ku,Nu.defaultValues(ku))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case bu:return Fr;case Su:return new ar;case ku:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case bu:return t===Fr;case Su:return t instanceof ar;case ku:return t instanceof Object&&0===Object.keys(t).length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.id||"id"}),new us({idBlock:{tagClass:3,tagNumber:0},value:[new ar({name:t.value||"value"})]})]})}fromSchema(e){st(e,Au);const t=cr(e,e,Nu.schema({names:{id:bu,value:Su}}));Gr.assertSchema(t,this.className),this.certId=t.result.certId.valueBlock.toString(),this.certValue=t.result.certValue;const s=this.certValue.valueBlock.valueHexView;switch(this.certId){case sa:try{this.parsedValue=yu.fromBER(s)}catch{Oc.fromBER(s)}break;case ra:this.parsedValue=Oc.fromBER(s);break;default:throw new Error(`Incorrect CERT_ID value in CertBag: ${this.certId}`)}}toSchema(){return ku in this&&("acinfo"in this.parsedValue?this.certId=ra:this.certId=sa,this.certValue=new ws({valueHex:this.parsedValue.toSchema().toBER(!1)})),new Os({value:[new Bs({value:this.certId}),new us({idBlock:{tagClass:3,tagNumber:0},value:["toSchema"in this.certValue?this.certValue.toSchema():this.certValue]})]})}toJSON(){return{certId:this.certId,certValue:this.certValue.toJSON()}}}Nu.CLASS_NAME="CertBag";const Eu="userCertificate",Cu="revocationDate",Iu="crlEntryExtensions",Bu=[Eu,Cu,Iu];class Vu extends zr{constructor(e={}){super(),this.userCertificate=He(e,Eu,Vu.defaultValues(Eu)),this.revocationDate=He(e,Cu,Vu.defaultValues(Cu)),Iu in e&&(this.crlEntryExtensions=He(e,Iu,Vu.defaultValues(Iu))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Eu:return new Ns;case Cu:return new Jc;case Iu:return new Ol;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Ns({name:t.userCertificate||Eu}),Jc.schema({names:{utcTimeName:t.revocationDate||Cu,generalTimeName:t.revocationDate||Cu}}),Ol.schema({names:{blockName:t.crlEntryExtensions||Iu}},!0)]})}fromSchema(e){st(e,Bu);const t=cr(e,e,Vu.schema());Gr.assertSchema(t,this.className),this.userCertificate=t.result.userCertificate,this.revocationDate=new Jc({schema:t.result.revocationDate}),Iu in t.result&&(this.crlEntryExtensions=new Ol({schema:t.result.crlEntryExtensions}))}toSchema(){const e=[this.userCertificate,this.revocationDate.toSchema()];return this.crlEntryExtensions&&e.push(this.crlEntryExtensions.toSchema()),new Os({value:e})}toJSON(){const e={userCertificate:this.userCertificate.toJSON(),revocationDate:this.revocationDate.toJSON()};return this.crlEntryExtensions&&(e.crlEntryExtensions=this.crlEntryExtensions.toJSON()),e}}Vu.CLASS_NAME="RevokedCertificate";const xu="tbs",Du="version",Ou="signature",Tu="issuer",Pu="thisUpdate",Uu="nextUpdate",Lu="revokedCertificates",Ru="crlExtensions",_u="signatureAlgorithm",Hu="signatureValue",Ku="tbsCertList",Mu=`${Ku}.version`,ju=`${Ku}.signature`,Ju=`${Ku}.issuer`,$u=`${Ku}.thisUpdate`,Fu=`${Ku}.nextUpdate`,qu=`${Ku}.revokedCertificates`,Wu=`${Ku}.extensions`,Gu=[Ku,Mu,ju,Ju,$u,Fu,qu,Wu,_u,Hu];function zu(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Ku,value:[new Ns({optional:!0,name:t.tbsCertListVersion||Mu,value:2}),An.schema(t.signature||{names:{blockName:ju}}),sn.schema(t.issuer||{names:{blockName:Ju}}),Jc.schema(t.tbsCertListThisUpdate||{names:{utcTimeName:$u,generalTimeName:$u}}),Jc.schema(t.tbsCertListNextUpdate||{names:{utcTimeName:Fu,generalTimeName:Fu}},!0),new Os({optional:!0,value:[new or({name:t.tbsCertListRevokedCertificates||qu,value:new Os({value:[new Ns,Jc.schema(),Ol.schema({},!0)]})})]}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[Ol.schema(t.crlExtensions||{names:{blockName:Wu}})]})]})}const Yu=[zn,Hn,"2.5.29.20","2.5.29.27",Mn,Fn,Qn,"2.5.29.21","2.5.29.24",jn];class Qu extends zr{get tbs(){return De.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e)}constructor(e={}){super(),this.tbsView=new Uint8Array(He(e,xu,Qu.defaultValues(xu))),this.version=He(e,Du,Qu.defaultValues(Du)),this.signature=He(e,Ou,Qu.defaultValues(Ou)),this.issuer=He(e,Tu,Qu.defaultValues(Tu)),this.thisUpdate=He(e,Pu,Qu.defaultValues(Pu)),Uu in e&&(this.nextUpdate=He(e,Uu,Qu.defaultValues(Uu))),Lu in e&&(this.revokedCertificates=He(e,Lu,Qu.defaultValues(Lu))),Ru in e&&(this.crlExtensions=He(e,Ru,Qu.defaultValues(Ru))),this.signatureAlgorithm=He(e,_u,Qu.defaultValues(_u)),this.signatureValue=He(e,Hu,Qu.defaultValues(Hu)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case xu:return $r;case Du:return 0;case Ou:return new An;case Tu:return new sn;case Pu:case Uu:return new Jc;case Lu:return[];case Ru:return new Ol;case _u:return new An;case Hu:return new vs;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||"CertificateList",value:[zu(e),An.schema(t.signatureAlgorithm||{names:{blockName:_u}}),new vs({name:t.signatureValue||Hu})]})}fromSchema(e){st(e,Gu);const t=cr(e,e,Qu.schema());Gr.assertSchema(t,this.className),this.tbsView=t.result.tbsCertList.valueBeforeDecodeView,Mu in t.result&&(this.version=t.result[Mu].valueBlock.valueDec),this.signature=new An({schema:t.result[ju]}),this.issuer=new sn({schema:t.result[Ju]}),this.thisUpdate=new Jc({schema:t.result[$u]}),Fu in t.result&&(this.nextUpdate=new Jc({schema:t.result[Fu]})),qu in t.result&&(this.revokedCertificates=Array.from(t.result[qu],(e=>new Vu({schema:e})))),Wu in t.result&&(this.crlExtensions=new Ol({schema:t.result[Wu]})),this.signatureAlgorithm=new An({schema:t.result.signatureAlgorithm}),this.signatureValue=t.result.signatureValue}encodeTBS(){const e=[];return this.version!==Qu.defaultValues(Du)&&e.push(new Ns({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 Os({value:Array.from(this.revokedCertificates,(e=>e.toSchema()))})),this.crlExtensions&&e.push(new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[this.crlExtensions.toSchema()]})),new Os({value:e})}toSchema(e=!1){let t;if(e)t=this.encodeTBS();else{if(!this.tbsView.byteLength)return Qu.schema();const e=ls(this.tbsView);Gr.assert(e,"TBS Certificate Revocation List"),t=e.result}return new Os({value:[t,this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){const e={tbs:_e.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!==Qu.defaultValues(Du)&&(e.version=this.version),this.nextUpdate&&(e.nextUpdate=this.nextUpdate.toJSON()),this.revokedCertificates&&(e.revokedCertificates=Array.from(this.revokedCertificates,(e=>e.toJSON()))),this.crlExtensions&&(e.crlExtensions=this.crlExtensions.toJSON()),e}isCertificateRevoked(e){if(!this.issuer.isEqual(e.issuer))return!1;if(!this.revokedCertificates)return!1;for(const t of this.revokedCertificates)if(t.userCertificate.isEqual(e.serialNumber))return!0;return!1}async sign(e,t="SHA-1",s=Xo(!0)){if(!e)throw new Error("Need to provide a private key for signing");const r=await s.getSignatureParameters(e,t),{parameters:n}=r;this.signature=r.signatureAlgorithm,this.signatureAlgorithm=r.signatureAlgorithm,this.tbsView=new Uint8Array(this.encodeTBS().toBER());const a=await s.signWithPrivateKey(this.tbsView,e,n);this.signatureValue=new vs({valueHex:a})}async verify(e={},t=Xo(!0)){let s;if(e.issuerCertificate&&(s=e.issuerCertificate.subjectPublicKeyInfo,!this.issuer.isEqual(e.issuerCertificate.subject)))return!1;if(e.publicKeyInfo&&(s=e.publicKeyInfo),!s)throw new Error("Issuer's certificate must be provided as an input parameter");if(this.crlExtensions)for(const e of this.crlExtensions.extensions)if(e.critical&&!Yu.includes(e.extnID))return!1;return t.verifyWithPublicKey(this.tbsView,this.signatureValue,s,this.signatureAlgorithm)}}Qu.CLASS_NAME="CertificateRevocationList";const Zu="crlId",Xu="crlValue",eh="parsedValue",th=[Zu,Xu];class sh extends zr{constructor(e={}){super(),this.crlId=He(e,Zu,sh.defaultValues(Zu)),this.crlValue=He(e,Xu,sh.defaultValues(Xu)),eh in e&&(this.parsedValue=He(e,eh,sh.defaultValues(eh))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Zu:return Fr;case Xu:return new ar;case eh:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Zu:return t===Fr;case Xu:return t instanceof ar;case eh:return t instanceof Object&&0===Object.keys(t).length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.id||"id"}),new us({idBlock:{tagClass:3,tagNumber:0},value:[new ar({name:t.value||"value"})]})]})}fromSchema(e){st(e,th);const t=cr(e,e,sh.schema({names:{id:Zu,value:Xu}}));if(Gr.assertSchema(t,this.className),this.crlId=t.result.crlId.valueBlock.toString(),this.crlValue=t.result.crlValue,this.crlId!==na)throw new Error(`Incorrect CRL_ID value in CRLBag: ${this.crlId}`);this.parsedValue=Qu.fromBER(this.certValue.valueBlock.valueHex)}toSchema(){return this.parsedValue&&(this.crlId=na,this.crlValue=new ws({valueHex:this.parsedValue.toSchema().toBER(!1)})),new Os({value:[new Bs({value:this.crlId}),new us({idBlock:{tagClass:3,tagNumber:0},value:[this.crlValue.toSchema()]})]})}toJSON(){return{crlId:this.crlId,crlValue:this.crlValue.toJSON()}}}sh.CLASS_NAME="CRLBag";const rh="version",nh="encryptedContentInfo",ah="unprotectedAttrs",ih=[rh,nh,ah];class oh extends zr{constructor(e={}){super(),this.version=He(e,rh,oh.defaultValues(rh)),this.encryptedContentInfo=He(e,nh,oh.defaultValues(nh)),ah in e&&(this.unprotectedAttrs=He(e,ah,oh.defaultValues(ah))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case rh:return 0;case nh:return new Vo;case ah:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case rh:return 0===t;case nh:return Vo.compareWithDefault("contentType",t.contentType)&&Vo.compareWithDefault("contentEncryptionAlgorithm",t.contentEncryptionAlgorithm)&&Vo.compareWithDefault("encryptedContent",t.encryptedContent);case ah:return 0===t.length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Ns({name:t.version||Fr}),Vo.schema(t.encryptedContentInfo||{}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new or({name:t.unprotectedAttrs||Fr,value:xn.schema()})]})]})}fromSchema(e){st(e,ih);const t=cr(e,e,oh.schema({names:{version:rh,encryptedContentInfo:{names:{blockName:nh}},unprotectedAttrs:ah}}));Gr.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.encryptedContentInfo=new Vo({schema:t.result.encryptedContentInfo}),ah in t.result&&(this.unprotectedAttrs=Array.from(t.result.unprotectedAttrs,(e=>new xn({schema:e}))))}toSchema(){const e=[];return e.push(new Ns({value:this.version})),e.push(this.encryptedContentInfo.toSchema()),this.unprotectedAttrs&&e.push(new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.unprotectedAttrs,(e=>e.toSchema()))})),new Os({value:e})}toJSON(){const e={version:this.version,encryptedContentInfo:this.encryptedContentInfo.toJSON()};return this.unprotectedAttrs&&(e.unprotectedAttrs=Array.from(this.unprotectedAttrs,(e=>e.toJSON()))),e}async encrypt(e,t=Xo(!0)){qr.assert(e,"parameters","object");const s={...e,contentType:"1.2.840.113549.1.7.1"};this.encryptedContentInfo=await t.encryptEncryptedContentInfo(s)}async decrypt(e,t=Xo(!0)){qr.assert(e,"parameters","object");const s={...e,encryptedContentInfo:this.encryptedContentInfo};return t.decryptEncryptedContentInfo(s)}}oh.CLASS_NAME="EncryptedData";const lh="encryptionAlgorithm",ch="encryptedData",uh="parsedValue",hh=[lh,ch];class mh extends zr{constructor(e={}){super(),this.encryptionAlgorithm=He(e,lh,mh.defaultValues(lh)),this.encryptedData=He(e,ch,mh.defaultValues(ch)),uh in e&&(this.parsedValue=He(e,uh,mh.defaultValues(uh))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case lh:return new An;case ch:return new ws;case uh:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case lh:return An.compareWithDefault("algorithmId",t.algorithmId)&&"algorithmParams"in t==!1;case ch:return t.isEqual(mh.defaultValues(e));case uh:return t instanceof Object&&0===Object.keys(t).length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[An.schema(t.encryptionAlgorithm||{names:{blockName:lh}}),new ir({value:[new ws({name:t.encryptedData||ch}),new ws({idBlock:{isConstructed:!0},name:t.encryptedData||ch})]})]})}fromSchema(e){st(e,hh);const t=cr(e,e,mh.schema({names:{encryptionAlgorithm:{names:{blockName:lh}},encryptedData:ch}}));Gr.assertSchema(t,this.className),this.encryptionAlgorithm=new An({schema:t.result.encryptionAlgorithm}),this.encryptedData=t.result.encryptedData}toSchema(){return new Os({value:[this.encryptionAlgorithm.toSchema(),this.encryptedData]})}toJSON(){return{encryptionAlgorithm:this.encryptionAlgorithm.toJSON(),encryptedData:this.encryptedData.toJSON()}}async parseInternalValues(e,t=Xo(!0)){const s=new oh({encryptedContentInfo:new Vo({contentEncryptionAlgorithm:this.encryptionAlgorithm,encryptedContent:this.encryptedData})}),r=await s.decrypt(e,t);this.parsedValue=No.fromBER(r)}async makeInternalValues(e,t=Xo(!0)){if(!this.parsedValue)throw new Error('Please initialize "parsedValue" first');const s=new oh,r={...e,contentToEncrypt:this.parsedValue.toSchema().toBER(!1)};if(await s.encrypt(r,t),!s.encryptedContentInfo.encryptedContent)throw new Error("The filed `encryptedContent` in EncryptedContentInfo is empty");this.encryptionAlgorithm=s.encryptedContentInfo.contentEncryptionAlgorithm,this.encryptedData=s.encryptedContentInfo.encryptedContent}}mh.CLASS_NAME="PKCS8ShroudedKeyBag";const fh="secretTypeId",dh="secretValue",gh=[fh,dh];class ph extends zr{constructor(e={}){super(),this.secretTypeId=He(e,fh,ph.defaultValues(fh)),this.secretValue=He(e,dh,ph.defaultValues(dh)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case fh:return Fr;case dh:return new ar;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case fh:return t===Fr;case dh:return t instanceof ar;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.id||"id"}),new us({idBlock:{tagClass:3,tagNumber:0},value:[new ar({name:t.value||"value"})]})]})}fromSchema(e){st(e,gh);const t=cr(e,e,ph.schema({names:{id:fh,value:dh}}));Gr.assertSchema(t,this.className),this.secretTypeId=t.result.secretTypeId.valueBlock.toString(),this.secretValue=t.result.secretValue}toSchema(){return new Os({value:[new Bs({value:this.secretTypeId}),new us({idBlock:{tagClass:3,tagNumber:0},value:[this.secretValue.toSchema()]})]})}toJSON(){return{secretTypeId:this.secretTypeId,secretValue:this.secretValue.toJSON()}}}ph.CLASS_NAME="SecretBag";class wh{static getItems(){return this.items||(this.items={},wh.register("1.2.840.113549.1.12.10.1.1",No),wh.register("1.2.840.113549.1.12.10.1.2",mh),wh.register("1.2.840.113549.1.12.10.1.3",Nu),wh.register("1.2.840.113549.1.12.10.1.4",sh),wh.register("1.2.840.113549.1.12.10.1.5",ph),wh.register("1.2.840.113549.1.12.10.1.6",Nh)),this.items}static register(e,t){this.getItems()[e]=t}static find(e){return this.getItems()[e]||null}}const yh="bagId",vh="bagValue",bh="bagAttributes",Sh=[yh,vh,bh];class kh extends zr{constructor(e={}){super(),this.bagId=He(e,yh,kh.defaultValues(yh)),this.bagValue=He(e,vh,kh.defaultValues(vh)),bh in e&&(this.bagAttributes=He(e,bh,kh.defaultValues(bh))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case yh:return Fr;case vh:return new ar;case bh:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case yh:return t===Fr;case vh:return t instanceof ar;case bh:return 0===t.length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.bagId||yh}),new us({idBlock:{tagClass:3,tagNumber:0},value:[new ar({name:t.bagValue||vh})]}),new Ts({optional:!0,value:[new or({name:t.bagAttributes||bh,value:xn.schema()})]})]})}fromSchema(e){st(e,Sh);const t=cr(e,e,kh.schema({names:{bagId:yh,bagValue:vh,bagAttributes:bh}}));Gr.assertSchema(t,this.className),this.bagId=t.result.bagId.valueBlock.toString();const s=wh.find(this.bagId);if(!s)throw new Error(`Invalid BAG_ID for SafeBag: ${this.bagId}`);this.bagValue=new s({schema:t.result.bagValue}),bh in t.result&&(this.bagAttributes=Array.from(t.result.bagAttributes,(e=>new xn({schema:e}))))}toSchema(){const e=[new Bs({value:this.bagId}),new us({idBlock:{tagClass:3,tagNumber:0},value:[this.bagValue.toSchema()]})];return this.bagAttributes&&e.push(new Ts({value:Array.from(this.bagAttributes,(e=>e.toSchema()))})),new Os({value:e})}toJSON(){const e={bagId:this.bagId,bagValue:this.bagValue.toJSON()};return this.bagAttributes&&(e.bagAttributes=Array.from(this.bagAttributes,(e=>e.toJSON()))),e}}kh.CLASS_NAME="SafeBag";const Ah="safeBags";class Nh extends zr{constructor(e={}){super(),this.safeBags=He(e,Ah,Nh.defaultValues(Ah)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===Ah?[]:super.defaultValues(e)}static compareWithDefault(e,t){return e===Ah?0===t.length:super.defaultValues(e)}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new or({name:t.safeBags||Fr,value:kh.schema()})]})}fromSchema(e){st(e,[Ah]);const t=cr(e,e,Nh.schema({names:{safeBags:Ah}}));Gr.assertSchema(t,this.className),this.safeBags=Array.from(t.result.safeBags,(e=>new kh({schema:e})))}toSchema(){return new Os({value:Array.from(this.safeBags,(e=>e.toSchema()))})}toJSON(){return{safeBags:Array.from(this.safeBags,(e=>e.toJSON()))}}}Nh.CLASS_NAME="SafeContents";const Eh="otherCertFormat",Ch="otherCert",Ih=[Eh,Ch];class Bh extends zr{constructor(e={}){super(),this.otherCertFormat=He(e,Eh,Bh.defaultValues(Eh)),this.otherCert=He(e,Ch,Bh.defaultValues(Ch)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Eh:return Fr;case Ch:return new ar;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.otherCertFormat||Eh}),new ar({name:t.otherCert||Ch})]})}fromSchema(e){st(e,Ih);const t=cr(e,e,Bh.schema());Gr.assertSchema(t,this.className),this.otherCertFormat=t.result.otherCertFormat.valueBlock.toString(),this.otherCert=t.result.otherCert}toSchema(){return new Os({value:[new Bs({value:this.otherCertFormat}),this.otherCert]})}toJSON(){const e={otherCertFormat:this.otherCertFormat};return this.otherCert instanceof ar||(e.otherCert=this.otherCert.toJSON()),e}}const Vh="certificates",xh=[Vh];class Dh extends zr{constructor(e={}){super(),this.certificates=He(e,Vh,Dh.defaultValues(Vh)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===Vh?[]:super.defaultValues(e)}static schema(e={}){const t=He(e,"names",{});return new Ts({name:t.blockName||Fr,value:[new or({name:t.certificates||Vh,value:new ir({value:[yu.schema(),new us({idBlock:{tagClass:3,tagNumber:0},value:[new ar]}),new us({idBlock:{tagClass:3,tagNumber:1},value:[new Os]}),new us({idBlock:{tagClass:3,tagNumber:2},value:Oc.schema().valueBlock.value}),new us({idBlock:{tagClass:3,tagNumber:3},value:Bh.schema().valueBlock.value})]})})]})}fromSchema(e){st(e,xh);const t=cr(e,e,Dh.schema());Gr.assertSchema(t,this.className),this.certificates=Array.from(t.result.certificates||[],(e=>{const t=e.idBlock.tagNumber;if(1===e.idBlock.tagClass)return new yu({schema:e});const s=new Os({value:e.valueBlock.value});switch(t){case 1:return 1===s.valueBlock.value[0].valueBlock.value[0].valueBlock.valueDec?new Oc({schema:s}):new ec({schema:s});case 2:return new Oc({schema:s});case 3:return new Bh({schema:s})}return e}))}toSchema(){return new Ts({value:Array.from(this.certificates,(e=>{switch(!0){case e instanceof yu:return e.toSchema();case e instanceof ec:return new us({idBlock:{tagClass:3,tagNumber:1},value:e.toSchema().valueBlock.value});case e instanceof Oc:return new us({idBlock:{tagClass:3,tagNumber:2},value:e.toSchema().valueBlock.value});case e instanceof Bh:return new us({idBlock:{tagClass:3,tagNumber:3},value:e.toSchema().valueBlock.value})}return e.toSchema()}))})}toJSON(){return{certificates:Array.from(this.certificates,(e=>e.toJSON()))}}}Dh.CLASS_NAME="CertificateSet";const Oh="otherRevInfoFormat",Th="otherRevInfo",Ph=[Oh,Th];class Uh extends zr{constructor(e={}){super(),this.otherRevInfoFormat=He(e,Oh,Uh.defaultValues(Oh)),this.otherRevInfo=He(e,Th,Uh.defaultValues(Th)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Oh:return Fr;case Th:return new ar;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.otherRevInfoFormat||Oh}),new ar({name:t.otherRevInfo||Th})]})}fromSchema(e){st(e,Ph);const t=cr(e,e,Uh.schema());Gr.assertSchema(t,this.className),this.otherRevInfoFormat=t.result.otherRevInfoFormat.valueBlock.toString(),this.otherRevInfo=t.result.otherRevInfo}toSchema(){return new Os({value:[new Bs({value:this.otherRevInfoFormat}),this.otherRevInfo]})}toJSON(){const e={otherRevInfoFormat:this.otherRevInfoFormat};return this.otherRevInfo instanceof ar||(e.otherRevInfo=this.otherRevInfo.toJSON()),e}}Uh.CLASS_NAME="OtherRevocationInfoFormat";const Lh="crls",Rh="otherRevocationInfos",_h=[Lh];class Hh extends zr{constructor(e={}){super(),this.crls=He(e,Lh,Hh.defaultValues(Lh)),this.otherRevocationInfos=He(e,Rh,Hh.defaultValues(Rh)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Lh:case Rh:return[];default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Ts({name:t.blockName||Fr,value:[new or({name:t.crls||Fr,value:new ir({value:[Qu.schema(),new us({idBlock:{tagClass:3,tagNumber:1},value:[new Bs,new ar]})]})})]})}fromSchema(e){st(e,_h);const t=cr(e,e,Hh.schema({names:{crls:Lh}}));if(Gr.assertSchema(t,this.className),t.result.crls)for(const e of t.result.crls)1===e.idBlock.tagClass?this.crls.push(new Qu({schema:e})):this.otherRevocationInfos.push(new Uh({schema:e}))}toSchema(){const e=[];return e.push(...Array.from(this.crls,(e=>e.toSchema()))),e.push(...Array.from(this.otherRevocationInfos,(e=>{const t=e.toSchema();return t.idBlock.tagClass=3,t.idBlock.tagNumber=1,t}))),new Ts({value:e})}toJSON(){return{crls:Array.from(this.crls,(e=>e.toJSON())),otherRevocationInfos:Array.from(this.otherRevocationInfos,(e=>e.toJSON()))}}}Hh.CLASS_NAME="RevocationInfoChoices";const Kh="certs",Mh="crls",jh=[Kh,Mh];class Jh extends zr{constructor(e={}){super(),this.crls=He(e,Mh,Jh.defaultValues(Mh)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Kh:return new Dh;case Mh:return new Hh;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Kh:return 0===t.certificates.length;case Mh:return 0===t.crls.length&&0===t.otherRevocationInfos.length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new us({name:t.certs||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:0},value:Dh.schema().valueBlock.value}),new us({name:t.crls||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Hh.schema().valueBlock.value})]})}fromSchema(e){st(e,jh);const t=cr(e,e,Jh.schema({names:{certs:Kh,crls:Mh}}));Gr.assertSchema(t,this.className),Kh in t.result&&(this.certs=new Dh({schema:new Ts({value:t.result.certs.valueBlock.value})})),Mh in t.result&&(this.crls=new Hh({schema:new Ts({value:t.result.crls.valueBlock.value})}))}toSchema(){const e=[];return this.certs&&e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:this.certs.toSchema().valueBlock.value})),this.crls&&e.push(new us({idBlock:{tagClass:3,tagNumber:1},value:this.crls.toSchema().valueBlock.value})),new Os({value:e})}toJSON(){const e={};return this.certs&&(e.certs=this.certs.toJSON()),this.crls&&(e.crls=this.crls.toJSON()),e}}Jh.CLASS_NAME="OriginatorInfo";const $h="issuer",Fh="serialNumber",qh=[$h,Fh];class Wh extends zr{constructor(e={}){super(),this.issuer=He(e,$h,Wh.defaultValues($h)),this.serialNumber=He(e,Fh,Wh.defaultValues(Fh)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case $h:return new sn;case Fh:return new Ns;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[sn.schema(t.issuer||{}),new Ns({name:t.serialNumber||Fr})]})}fromSchema(e){st(e,qh);const t=cr(e,e,Wh.schema({names:{issuer:{names:{blockName:$h}},serialNumber:Fh}}));Gr.assertSchema(t,this.className),this.issuer=new sn({schema:t.result.issuer}),this.serialNumber=t.result.serialNumber}toSchema(){return new Os({value:[this.issuer.toSchema(),this.serialNumber]})}toJSON(){return{issuer:this.issuer.toJSON(),serialNumber:this.serialNumber.toJSON()}}}Wh.CLASS_NAME="IssuerAndSerialNumber";const Gh="variant",zh="value",Yh=["blockName"];class Qh extends zr{constructor(e={}){super(),this.variant=He(e,Gh,Qh.defaultValues(Gh)),zh in e&&(this.value=He(e,zh,Qh.defaultValues(zh))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Gh:return-1;case zh:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Gh:return-1===t;case zh:return 0===Object.keys(t).length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new ir({value:[Wh.schema({names:{blockName:t.blockName||Fr}}),new is({name:t.blockName||Fr,idBlock:{tagClass:3,tagNumber:0}})]})}fromSchema(e){st(e,Yh);const t=cr(e,e,Qh.schema({names:{blockName:"blockName"}}));Gr.assertSchema(t,this.className),1===t.result.blockName.idBlock.tagClass?(this.variant=1,this.value=new Wh({schema:t.result.blockName})):(this.variant=2,this.value=new ws({valueHex:t.result.blockName.valueBlock.valueHex}))}toSchema(){switch(this.variant){case 1:if(!(this.value instanceof Wh))throw new Error("Incorrect type of RecipientIdentifier.value. It should be IssuerAndSerialNumber.");return this.value.toSchema();case 2:if(!(this.value instanceof ws))throw new Error("Incorrect type of RecipientIdentifier.value. It should be ASN.1 OctetString.");return new is({idBlock:{tagClass:3,tagNumber:0},valueHex:this.value.valueBlock.valueHexView});default:return new ar}}toJSON(){const e={variant:this.variant};return 1!==this.variant&&2!==this.variant||!this.value||(e.value=this.value.toJSON()),e}}Qh.CLASS_NAME="RecipientIdentifier";const Zh="version",Xh="rid",em="keyEncryptionAlgorithm",tm="encryptedKey",sm="recipientCertificate",rm=[Zh,Xh,em,tm];class nm extends zr{constructor(e={}){super(),this.version=He(e,Zh,nm.defaultValues(Zh)),this.rid=He(e,Xh,nm.defaultValues(Xh)),this.keyEncryptionAlgorithm=He(e,em,nm.defaultValues(em)),this.encryptedKey=He(e,tm,nm.defaultValues(tm)),this.recipientCertificate=He(e,sm,nm.defaultValues(sm)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Zh:return-1;case Xh:return{};case em:return new An;case tm:return new ws;case sm:return new yu;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Zh:return t===nm.defaultValues(Zh);case Xh:return 0===Object.keys(t).length;case em:case tm:return t.isEqual(nm.defaultValues(e));case sm:return!1;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Ns({name:t.version||Fr}),Qh.schema(t.rid||{}),An.schema(t.keyEncryptionAlgorithm||{}),new ws({name:t.encryptedKey||Fr})]})}fromSchema(e){st(e,rm);const t=cr(e,e,nm.schema({names:{version:Zh,rid:{names:{blockName:Xh}},keyEncryptionAlgorithm:{names:{blockName:em}},encryptedKey:tm}}));Gr.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,3===t.result.rid.idBlock.tagClass?this.rid=new ws({valueHex:t.result.rid.valueBlock.valueHex}):this.rid=new Wh({schema:t.result.rid}),this.keyEncryptionAlgorithm=new An({schema:t.result.keyEncryptionAlgorithm}),this.encryptedKey=t.result.encryptedKey}toSchema(){const e=[];return this.rid instanceof Wh?(this.version=0,e.push(new Ns({value:this.version})),e.push(this.rid.toSchema())):(this.version=2,e.push(new Ns({value:this.version})),e.push(new is({idBlock:{tagClass:3,tagNumber:0},valueHex:this.rid.valueBlock.valueHexView}))),e.push(this.keyEncryptionAlgorithm.toSchema()),e.push(this.encryptedKey),new Os({value:e})}toJSON(){return{version:this.version,rid:this.rid.toJSON(),keyEncryptionAlgorithm:this.keyEncryptionAlgorithm.toJSON(),encryptedKey:this.encryptedKey.toJSON()}}}nm.CLASS_NAME="KeyTransRecipientInfo";const am="algorithm",im="publicKey",om=[am,im];class lm extends zr{constructor(e={}){super(),this.algorithm=He(e,am,lm.defaultValues(am)),this.publicKey=He(e,im,lm.defaultValues(im)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case am:return new An;case im:return new vs;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case am:case im:return t.isEqual(lm.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[An.schema(t.algorithm||{}),new vs({name:t.publicKey||Fr})]})}fromSchema(e){st(e,om);const t=cr(e,e,lm.schema({names:{algorithm:{names:{blockName:am}},publicKey:im}}));Gr.assertSchema(t,this.className),this.algorithm=new An({schema:t.result.algorithm}),this.publicKey=t.result.publicKey}toSchema(){return new Os({value:[this.algorithm.toSchema(),this.publicKey]})}toJSON(){return{algorithm:this.algorithm.toJSON(),publicKey:this.publicKey.toJSON()}}}lm.CLASS_NAME="OriginatorPublicKey";const cm="variant",um="value",hm=["blockName"];class mm extends zr{constructor(e={}){super(),this.variant=He(e,cm,mm.defaultValues(cm)),um in e&&(this.value=He(e,um,mm.defaultValues(um))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case cm:return-1;case um:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case cm:return-1===t;case um:return 0===Object.keys(t).length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new ir({value:[Wh.schema({names:{blockName:t.blockName||Fr}}),new is({idBlock:{tagClass:3,tagNumber:0},name:t.blockName||Fr}),new us({idBlock:{tagClass:3,tagNumber:1},name:t.blockName||Fr,value:lm.schema().valueBlock.value})]})}fromSchema(e){st(e,hm);const t=cr(e,e,mm.schema({names:{blockName:"blockName"}}));Gr.assertSchema(t,this.className),1===t.result.blockName.idBlock.tagClass?(this.variant=1,this.value=new Wh({schema:t.result.blockName})):0===t.result.blockName.idBlock.tagNumber?(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 lm({schema:new Os({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:{const e=this.value.toSchema();return e.idBlock.tagClass=3,e.idBlock.tagNumber=1,e}default:return new ar}}toJSON(){const e={variant:this.variant};return 1!==this.variant&&2!==this.variant&&3!==this.variant||(e.value=this.value.toJSON()),e}}mm.CLASS_NAME="OriginatorIdentifierOrKey";const fm="keyAttrId",dm="keyAttr",gm=[fm,dm];class pm extends zr{constructor(e={}){super(),this.keyAttrId=He(e,fm,pm.defaultValues(fm)),dm in e&&(this.keyAttr=He(e,dm,pm.defaultValues(dm))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case fm:return Fr;case dm:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case fm:return"string"==typeof t&&t===Fr;case dm:return 0===Object.keys(t).length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({optional:t.optional||!0,name:t.blockName||Fr,value:[new Bs({name:t.keyAttrId||Fr}),new ar({optional:!0,name:t.keyAttr||Fr})]})}fromSchema(e){st(e,gm);const t=cr(e,e,pm.schema({names:{keyAttrId:fm,keyAttr:dm}}));Gr.assertSchema(t,this.className),this.keyAttrId=t.result.keyAttrId.valueBlock.toString(),dm in t.result&&(this.keyAttr=t.result.keyAttr)}toSchema(){const e=[];return e.push(new Bs({value:this.keyAttrId})),dm in this&&e.push(this.keyAttr),new Os({value:e})}toJSON(){const e={keyAttrId:this.keyAttrId};return dm in this&&(e.keyAttr=this.keyAttr.toJSON()),e}}pm.CLASS_NAME="OtherKeyAttribute";const wm="subjectKeyIdentifier",ym="date",vm="other",bm=[wm,ym,vm];class Sm extends zr{constructor(e={}){super(),this.subjectKeyIdentifier=He(e,wm,Sm.defaultValues(wm)),ym in e&&(this.date=He(e,ym,Sm.defaultValues(ym))),vm in e&&(this.other=He(e,vm,Sm.defaultValues(vm))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case wm:return new ws;case ym:return new Xs;case vm:return new pm;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case wm:return t.isEqual(Sm.defaultValues(wm));case ym:return 0===t.year&&0===t.month&&0===t.day&&0===t.hour&&0===t.minute&&0===t.second&&0===t.millisecond;case vm:return t.keyAttrId===Fr&&"keyAttr"in t==!1;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new ws({name:t.subjectKeyIdentifier||Fr}),new Xs({optional:!0,name:t.date||Fr}),pm.schema(t.other||{})]})}fromSchema(e){st(e,bm);const t=cr(e,e,Sm.schema({names:{subjectKeyIdentifier:wm,date:ym,other:{names:{blockName:vm}}}}));Gr.assertSchema(t,this.className),this.subjectKeyIdentifier=t.result.subjectKeyIdentifier,ym in t.result&&(this.date=t.result.date),vm in t.result&&(this.other=new pm({schema:t.result.other}))}toSchema(){const e=[];return e.push(this.subjectKeyIdentifier),this.date&&e.push(this.date),this.other&&e.push(this.other.toSchema()),new Os({value:e})}toJSON(){const e={subjectKeyIdentifier:this.subjectKeyIdentifier.toJSON()};return this.date&&(e.date=this.date.toJSON()),this.other&&(e.other=this.other.toJSON()),e}}Sm.CLASS_NAME="RecipientKeyIdentifier";const km="variant",Am="value",Nm=["blockName"];class Em extends zr{constructor(e={}){super(),this.variant=He(e,km,Em.defaultValues(km)),this.value=He(e,Am,Em.defaultValues(Am)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case km:return-1;case Am:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case km:return-1===t;case Am:return 0===Object.keys(t).length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new ir({value:[Wh.schema(t.issuerAndSerialNumber||{names:{blockName:t.blockName||Fr}}),new us({name:t.blockName||Fr,idBlock:{tagClass:3,tagNumber:0},value:Sm.schema(t.rKeyId||{names:{blockName:t.blockName||Fr}}).valueBlock.value})]})}fromSchema(e){st(e,Nm);const t=cr(e,e,Em.schema({names:{blockName:"blockName"}}));Gr.assertSchema(t,this.className),1===t.result.blockName.idBlock.tagClass?(this.variant=1,this.value=new Wh({schema:t.result.blockName})):(this.variant=2,this.value=new Sm({schema:new Os({value:t.result.blockName.valueBlock.value})}))}toSchema(){switch(this.variant){case 1:return this.value.toSchema();case 2:return new us({idBlock:{tagClass:3,tagNumber:0},value:this.value.toSchema().valueBlock.value});default:return new ar}}toJSON(){const e={variant:this.variant};return 1!==this.variant&&2!==this.variant||(e.value=this.value.toJSON()),e}}Em.CLASS_NAME="KeyAgreeRecipientIdentifier";const Cm="rid",Im="encryptedKey",Bm=[Cm,Im];class Vm extends zr{constructor(e={}){super(),this.rid=He(e,Cm,Vm.defaultValues(Cm)),this.encryptedKey=He(e,Im,Vm.defaultValues(Im)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Cm:return new Em;case Im:return new ws;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Cm:return-1===t.variant&&"value"in t==!1;case Im:return t.isEqual(Vm.defaultValues(Im));default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[Em.schema(t.rid||{}),new ws({name:t.encryptedKey||Fr})]})}fromSchema(e){st(e,Bm);const t=cr(e,e,Vm.schema({names:{rid:{names:{blockName:Cm}},encryptedKey:Im}}));Gr.assertSchema(t,this.className),this.rid=new Em({schema:t.result.rid}),this.encryptedKey=t.result.encryptedKey}toSchema(){return new Os({value:[this.rid.toSchema(),this.encryptedKey]})}toJSON(){return{rid:this.rid.toJSON(),encryptedKey:this.encryptedKey.toJSON()}}}Vm.CLASS_NAME="RecipientEncryptedKey";const xm="encryptedKeys",Dm="RecipientEncryptedKeys",Om=[Dm];class Tm extends zr{constructor(e={}){super(),this.encryptedKeys=He(e,xm,Tm.defaultValues(xm)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===xm?[]:super.defaultValues(e)}static compareWithDefault(e,t){return e===xm?0===t.length:super.defaultValues(e)}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new or({name:t.RecipientEncryptedKeys||Fr,value:Vm.schema()})]})}fromSchema(e){st(e,Om);const t=cr(e,e,Tm.schema({names:{RecipientEncryptedKeys:Dm}}));Gr.assertSchema(t,this.className),this.encryptedKeys=Array.from(t.result.RecipientEncryptedKeys,(e=>new Vm({schema:e})))}toSchema(){return new Os({value:Array.from(this.encryptedKeys,(e=>e.toSchema()))})}toJSON(){return{encryptedKeys:Array.from(this.encryptedKeys,(e=>e.toJSON()))}}}Tm.CLASS_NAME="RecipientEncryptedKeys";const Pm="version",Um="originator",Lm="ukm",Rm="keyEncryptionAlgorithm",_m="recipientEncryptedKeys",Hm="recipientCertificate",Km="recipientPublicKey",Mm=[Pm,Um,Lm,Rm,_m];class jm extends zr{constructor(e={}){super(),this.version=He(e,Pm,jm.defaultValues(Pm)),this.originator=He(e,Um,jm.defaultValues(Um)),Lm in e&&(this.ukm=He(e,Lm,jm.defaultValues(Lm))),this.keyEncryptionAlgorithm=He(e,Rm,jm.defaultValues(Rm)),this.recipientEncryptedKeys=He(e,_m,jm.defaultValues(_m)),this.recipientCertificate=He(e,Hm,jm.defaultValues(Hm)),this.recipientPublicKey=He(e,Km,jm.defaultValues(Km)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Pm:return 0;case Um:return new mm;case Lm:return new ws;case Rm:return new An;case _m:return new Tm;case Hm:return new yu;case Km:return null;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Pm:return 0===t;case Um:return-1===t.variant&&"value"in t==!1;case Lm:return t.isEqual(jm.defaultValues(Lm));case Rm:return t.algorithmId===Fr&&"algorithmParams"in t==!1;case _m:return 0===t.encryptedKeys.length;case Hm:case Km:return!1;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Ns({name:t.version||Fr}),new us({idBlock:{tagClass:3,tagNumber:0},value:[mm.schema(t.originator||{})]}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new ws({name:t.ukm||Fr})]}),An.schema(t.keyEncryptionAlgorithm||{}),Tm.schema(t.recipientEncryptedKeys||{})]})}fromSchema(e){st(e,Mm);const t=cr(e,e,jm.schema({names:{version:Pm,originator:{names:{blockName:Um}},ukm:Lm,keyEncryptionAlgorithm:{names:{blockName:Rm}},recipientEncryptedKeys:{names:{blockName:_m}}}}));Gr.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.originator=new mm({schema:t.result.originator}),Lm in t.result&&(this.ukm=t.result.ukm),this.keyEncryptionAlgorithm=new An({schema:t.result.keyEncryptionAlgorithm}),this.recipientEncryptedKeys=new Tm({schema:t.result.recipientEncryptedKeys})}toSchema(){const e=[];return e.push(new Ns({value:this.version})),e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:[this.originator.toSchema()]})),this.ukm&&e.push(new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[this.ukm]})),e.push(this.keyEncryptionAlgorithm.toSchema()),e.push(this.recipientEncryptedKeys.toSchema()),new Os({value:e})}toJSON(){const 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}}jm.CLASS_NAME="KeyAgreeRecipientInfo";const Jm="keyIdentifier",$m="date",Fm="other",qm=[Jm,$m,Fm];class Wm extends zr{constructor(e={}){super(),this.keyIdentifier=He(e,Jm,Wm.defaultValues(Jm)),$m in e&&(this.date=He(e,$m,Wm.defaultValues($m))),Fm in e&&(this.other=He(e,Fm,Wm.defaultValues(Fm))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Jm:return new ws;case $m:return new Xs;case Fm:return new pm;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Jm:return t.isEqual(Wm.defaultValues(Jm));case $m:return 0===t.year&&0===t.month&&0===t.day&&0===t.hour&&0===t.minute&&0===t.second&&0===t.millisecond;case Fm:return t.compareWithDefault("keyAttrId",t.keyAttrId)&&"keyAttr"in t==!1;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new ws({name:t.keyIdentifier||Fr}),new Xs({optional:!0,name:t.date||Fr}),pm.schema(t.other||{})]})}fromSchema(e){st(e,qm);const t=cr(e,e,Wm.schema({names:{keyIdentifier:Jm,date:$m,other:{names:{blockName:Fm}}}}));Gr.assertSchema(t,this.className),this.keyIdentifier=t.result.keyIdentifier,$m in t.result&&(this.date=t.result.date),Fm in t.result&&(this.other=new pm({schema:t.result.other}))}toSchema(){const e=[];return e.push(this.keyIdentifier),this.date&&e.push(this.date),this.other&&e.push(this.other.toSchema()),new Os({value:e})}toJSON(){const e={keyIdentifier:this.keyIdentifier.toJSON()};return this.date&&(e.date=this.date),this.other&&(e.other=this.other.toJSON()),e}}Wm.CLASS_NAME="KEKIdentifier";const Gm="version",zm="kekid",Ym="keyEncryptionAlgorithm",Qm="encryptedKey",Zm="preDefinedKEK",Xm=[Gm,zm,Ym,Qm];class ef extends zr{constructor(e={}){super(),this.version=He(e,Gm,ef.defaultValues(Gm)),this.kekid=He(e,zm,ef.defaultValues(zm)),this.keyEncryptionAlgorithm=He(e,Ym,ef.defaultValues(Ym)),this.encryptedKey=He(e,Qm,ef.defaultValues(Qm)),this.preDefinedKEK=He(e,Zm,ef.defaultValues(Zm)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Gm:return 0;case zm:return new Wm;case Ym:return new An;case Qm:return new ws;case Zm:return $r;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case"KEKRecipientInfo":return t===ef.defaultValues(Gm);case zm:return t.compareWithDefault("keyIdentifier",t.keyIdentifier)&&"date"in t==!1&&"other"in t==!1;case Ym:return t.algorithmId===Fr&&"algorithmParams"in t==!1;case Qm:return t.isEqual(ef.defaultValues(Qm));case Zm:return 0===t.byteLength;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Ns({name:t.version||Fr}),Wm.schema(t.kekid||{}),An.schema(t.keyEncryptionAlgorithm||{}),new ws({name:t.encryptedKey||Fr})]})}fromSchema(e){st(e,Xm);const t=cr(e,e,ef.schema({names:{version:Gm,kekid:{names:{blockName:zm}},keyEncryptionAlgorithm:{names:{blockName:Ym}},encryptedKey:Qm}}));Gr.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.kekid=new Wm({schema:t.result.kekid}),this.keyEncryptionAlgorithm=new An({schema:t.result.keyEncryptionAlgorithm}),this.encryptedKey=t.result.encryptedKey}toSchema(){return new Os({value:[new Ns({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()}}}ef.CLASS_NAME="KEKRecipientInfo";const tf="version",sf="keyDerivationAlgorithm",rf="keyEncryptionAlgorithm",nf="encryptedKey",af="password",of=[tf,sf,rf,nf];class lf extends zr{constructor(e={}){super(),this.version=He(e,tf,lf.defaultValues(tf)),sf in e&&(this.keyDerivationAlgorithm=He(e,sf,lf.defaultValues(sf))),this.keyEncryptionAlgorithm=He(e,rf,lf.defaultValues(rf)),this.encryptedKey=He(e,nf,lf.defaultValues(nf)),this.password=He(e,af,lf.defaultValues(af)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case tf:return-1;case sf:case rf:return new An;case nf:return new ws;case af:return $r;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case tf:return-1===t;case sf:case rf:return t.algorithmId===Fr&&"algorithmParams"in t==!1;case nf:return t.isEqual(lf.defaultValues(nf));case af:return 0===t.byteLength;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Ns({name:t.version||Fr}),new us({name:t.keyDerivationAlgorithm||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:0},value:An.schema().valueBlock.value}),An.schema(t.keyEncryptionAlgorithm||{}),new ws({name:t.encryptedKey||Fr})]})}fromSchema(e){st(e,of);const t=cr(e,e,lf.schema({names:{version:tf,keyDerivationAlgorithm:sf,keyEncryptionAlgorithm:{names:{blockName:rf}},encryptedKey:nf}}));Gr.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,sf in t.result&&(this.keyDerivationAlgorithm=new An({schema:new Os({value:t.result.keyDerivationAlgorithm.valueBlock.value})})),this.keyEncryptionAlgorithm=new An({schema:t.result.keyEncryptionAlgorithm}),this.encryptedKey=t.result.encryptedKey}toSchema(){const e=[];return e.push(new Ns({value:this.version})),this.keyDerivationAlgorithm&&e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:this.keyDerivationAlgorithm.toSchema().valueBlock.value})),e.push(this.keyEncryptionAlgorithm.toSchema()),e.push(this.encryptedKey),new Os({value:e})}toJSON(){const e={version:this.version,keyEncryptionAlgorithm:this.keyEncryptionAlgorithm.toJSON(),encryptedKey:this.encryptedKey.toJSON()};return this.keyDerivationAlgorithm&&(e.keyDerivationAlgorithm=this.keyDerivationAlgorithm.toJSON()),e}}lf.CLASS_NAME="PasswordRecipientInfo";const cf="oriType",uf="oriValue",hf=[cf,uf];class mf extends zr{constructor(e={}){super(),this.oriType=He(e,cf,mf.defaultValues(cf)),this.oriValue=He(e,uf,mf.defaultValues(uf)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case cf:return Fr;case uf:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case cf:return t===Fr;case uf:return 0===Object.keys(t).length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.oriType||Fr}),new ar({name:t.oriValue||Fr})]})}fromSchema(e){st(e,hf);const t=cr(e,e,mf.schema({names:{oriType:cf,oriValue:uf}}));Gr.assertSchema(t,this.className),this.oriType=t.result.oriType.valueBlock.toString(),this.oriValue=t.result.oriValue}toSchema(){return new Os({value:[new Bs({value:this.oriType}),this.oriValue]})}toJSON(){const e={oriType:this.oriType};return mf.compareWithDefault(uf,this.oriValue)||(e.oriValue=this.oriValue.toJSON()),e}}mf.CLASS_NAME="OtherRecipientInfo";const ff="variant",df="value",gf=["blockName"];class pf extends zr{constructor(e={}){super(),this.variant=He(e,ff,pf.defaultValues(ff)),df in e&&(this.value=He(e,df,pf.defaultValues(df))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case ff:return-1;case df:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case ff:return t===pf.defaultValues(e);case df:return 0===Object.keys(t).length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new ir({value:[nm.schema({names:{blockName:t.blockName||Fr}}),new us({name:t.blockName||Fr,idBlock:{tagClass:3,tagNumber:1},value:jm.schema().valueBlock.value}),new us({name:t.blockName||Fr,idBlock:{tagClass:3,tagNumber:2},value:ef.schema().valueBlock.value}),new us({name:t.blockName||Fr,idBlock:{tagClass:3,tagNumber:3},value:lf.schema().valueBlock.value}),new us({name:t.blockName||Fr,idBlock:{tagClass:3,tagNumber:4},value:mf.schema().valueBlock.value})]})}fromSchema(e){st(e,gf);const t=cr(e,e,pf.schema({names:{blockName:"blockName"}}));if(Gr.assertSchema(t,this.className),1===t.result.blockName.idBlock.tagClass)this.variant=1,this.value=new nm({schema:t.result.blockName});else{const e=new Os({value:t.result.blockName.valueBlock.value});switch(t.result.blockName.idBlock.tagNumber){case 1:this.variant=2,this.value=new jm({schema:e});break;case 2:this.variant=3,this.value=new ef({schema:e});break;case 3:this.variant=4,this.value=new lf({schema:e});break;case 4:this.variant=5,this.value=new mf({schema:e});break;default:throw new Error("Incorrect structure of RecipientInfo block")}}}toSchema(){Wr.assertEmpty(this.value,"value","RecipientInfo");const 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 ar}}toJSON(){const e={variant:this.variant};return this.value&&this.variant>=1&&this.variant<=4&&(e.value=this.value.toJSON()),e}}pf.CLASS_NAME="RecipientInfo";const wf="hashAlgorithm",yf="maskGenAlgorithm",vf="pSourceAlgorithm",bf=[wf,yf,vf];class Sf extends zr{constructor(e={}){super(),this.hashAlgorithm=He(e,wf,Sf.defaultValues(wf)),this.maskGenAlgorithm=He(e,yf,Sf.defaultValues(yf)),this.pSourceAlgorithm=He(e,vf,Sf.defaultValues(vf)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case wf:return new An({algorithmId:"1.3.14.3.2.26",algorithmParams:new fs});case yf:return new An({algorithmId:"1.2.840.113549.1.1.8",algorithmParams:new An({algorithmId:"1.3.14.3.2.26",algorithmParams:new fs}).toSchema()});case vf:return new An({algorithmId:"1.2.840.113549.1.1.9",algorithmParams:new ws({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={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new us({idBlock:{tagClass:3,tagNumber:0},optional:!0,value:[An.schema(t.hashAlgorithm||{})]}),new us({idBlock:{tagClass:3,tagNumber:1},optional:!0,value:[An.schema(t.maskGenAlgorithm||{})]}),new us({idBlock:{tagClass:3,tagNumber:2},optional:!0,value:[An.schema(t.pSourceAlgorithm||{})]})]})}fromSchema(e){st(e,bf);const t=cr(e,e,Sf.schema({names:{hashAlgorithm:{names:{blockName:wf}},maskGenAlgorithm:{names:{blockName:yf}},pSourceAlgorithm:{names:{blockName:vf}}}}));Gr.assertSchema(t,this.className),wf in t.result&&(this.hashAlgorithm=new An({schema:t.result.hashAlgorithm})),yf in t.result&&(this.maskGenAlgorithm=new An({schema:t.result.maskGenAlgorithm})),vf in t.result&&(this.pSourceAlgorithm=new An({schema:t.result.pSourceAlgorithm}))}toSchema(){const e=[];return this.hashAlgorithm.isEqual(Sf.defaultValues(wf))||e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:[this.hashAlgorithm.toSchema()]})),this.maskGenAlgorithm.isEqual(Sf.defaultValues(yf))||e.push(new us({idBlock:{tagClass:3,tagNumber:1},value:[this.maskGenAlgorithm.toSchema()]})),this.pSourceAlgorithm.isEqual(Sf.defaultValues(vf))||e.push(new us({idBlock:{tagClass:3,tagNumber:2},value:[this.pSourceAlgorithm.toSchema()]})),new Os({value:e})}toJSON(){const e={};return this.hashAlgorithm.isEqual(Sf.defaultValues(wf))||(e.hashAlgorithm=this.hashAlgorithm.toJSON()),this.maskGenAlgorithm.isEqual(Sf.defaultValues(yf))||(e.maskGenAlgorithm=this.maskGenAlgorithm.toJSON()),this.pSourceAlgorithm.isEqual(Sf.defaultValues(vf))||(e.pSourceAlgorithm=this.pSourceAlgorithm.toJSON()),e}}Sf.CLASS_NAME="RSAESOAEPParams";const kf="keyInfo",Af="entityUInfo",Nf="suppPubInfo",Ef=[kf,Af,Nf];class Cf extends zr{constructor(e={}){super(),this.keyInfo=He(e,kf,Cf.defaultValues(kf)),Af in e&&(this.entityUInfo=He(e,Af,Cf.defaultValues(Af))),this.suppPubInfo=He(e,Nf,Cf.defaultValues(Nf)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case kf:return new An;case Af:case Nf:return new ws;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case kf:case Af:case Nf:return t.isEqual(Cf.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[An.schema(t.keyInfo||{}),new us({name:t.entityUInfo||Fr,idBlock:{tagClass:3,tagNumber:0},optional:!0,value:[new ws]}),new us({name:t.suppPubInfo||Fr,idBlock:{tagClass:3,tagNumber:2},value:[new ws]})]})}fromSchema(e){st(e,Ef);const t=cr(e,e,Cf.schema({names:{keyInfo:{names:{blockName:kf}},entityUInfo:Af,suppPubInfo:Nf}}));Gr.assertSchema(t,this.className),this.keyInfo=new An({schema:t.result.keyInfo}),Af in t.result&&(this.entityUInfo=t.result.entityUInfo.valueBlock.value[0]),this.suppPubInfo=t.result.suppPubInfo.valueBlock.value[0]}toSchema(){const e=[];return e.push(this.keyInfo.toSchema()),this.entityUInfo&&e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:[this.entityUInfo]})),e.push(new us({idBlock:{tagClass:3,tagNumber:2},value:[this.suppPubInfo]})),new Os({value:e})}toJSON(){const e={keyInfo:this.keyInfo.toJSON(),suppPubInfo:this.suppPubInfo.toJSON()};return this.entityUInfo&&(e.entityUInfo=this.entityUInfo.toJSON()),e}}Cf.CLASS_NAME="ECCCMSSharedInfo";const If="version",Bf="originatorInfo",Vf="recipientInfos",xf="encryptedContentInfo",Df="unprotectedAttrs",Of=[If,Bf,Vf,xf,Df],Tf={kdfAlgorithm:"SHA-512",kekEncryptionLength:256},Pf={"P-256":256,"P-384":384,"P-521":528};class Uf extends zr{constructor(e={}){super(),this.version=He(e,If,Uf.defaultValues(If)),Bf in e&&(this.originatorInfo=He(e,Bf,Uf.defaultValues(Bf))),this.recipientInfos=He(e,Vf,Uf.defaultValues(Vf)),this.encryptedContentInfo=He(e,xf,Uf.defaultValues(xf)),Df in e&&(this.unprotectedAttrs=He(e,Df,Uf.defaultValues(Df))),this.policy={disableSplit:!!e.disableSplit},e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case If:return 0;case Bf:return new Jh;case Vf:return[];case xf:return new Vo;case Df:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case If:return t===Uf.defaultValues(e);case Bf:return 0===t.certs.certificates.length&&0===t.crls.crls.length;case Vf:case Df:return 0===t.length;case xf:return Vo.compareWithDefault("contentType",t.contentType)&&Vo.compareWithDefault("contentEncryptionAlgorithm",t.contentEncryptionAlgorithm)&&Vo.compareWithDefault("encryptedContent",t.encryptedContent);default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Ns({name:t.version||Fr}),new us({name:t.originatorInfo||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:0},value:Jh.schema().valueBlock.value}),new Ts({value:[new or({name:t.recipientInfos||Fr,value:pf.schema()})]}),Vo.schema(t.encryptedContentInfo||{}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new or({name:t.unprotectedAttrs||Fr,value:xn.schema()})]})]})}fromSchema(e){st(e,Of);const t=cr(e,e,Uf.schema({names:{version:If,originatorInfo:Bf,recipientInfos:Vf,encryptedContentInfo:{names:{blockName:xf}},unprotectedAttrs:Df}}));Gr.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,Bf in t.result&&(this.originatorInfo=new Jh({schema:new Os({value:t.result.originatorInfo.valueBlock.value})})),this.recipientInfos=Array.from(t.result.recipientInfos,(e=>new pf({schema:e}))),this.encryptedContentInfo=new Vo({schema:t.result.encryptedContentInfo}),Df in t.result&&(this.unprotectedAttrs=Array.from(t.result.unprotectedAttrs,(e=>new xn({schema:e}))))}toSchema(){const e=[];return e.push(new Ns({value:this.version})),this.originatorInfo&&e.push(new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:this.originatorInfo.toSchema().valueBlock.value})),e.push(new Ts({value:Array.from(this.recipientInfos,(e=>e.toSchema()))})),e.push(this.encryptedContentInfo.toSchema()),this.unprotectedAttrs&&e.push(new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.unprotectedAttrs,(e=>e.toSchema()))})),new Os({value:e})}toJSON(){const e={version:this.version,recipientInfos:Array.from(this.recipientInfos,(e=>e.toJSON())),encryptedContentInfo:this.encryptedContentInfo.toJSON()};return this.originatorInfo&&(e.originatorInfo=this.originatorInfo.toJSON()),this.unprotectedAttrs&&(e.unprotectedAttrs=Array.from(this.unprotectedAttrs,(e=>e.toJSON()))),e}addRecipientByCertificate(e,t,s,r=Xo(!0)){const n=Object.assign({useOAEP:!0,oaepHashAlgorithm:"SHA-512"},Tf,t||{});if(-1!==e.subjectPublicKeyInfo.algorithm.algorithmId.indexOf("1.2.840.113549"))s=1;else{if(-1===e.subjectPublicKeyInfo.algorithm.algorithmId.indexOf("1.2.840.10045"))throw new Error(`Unknown type of certificate's public key: ${e.subjectPublicKeyInfo.algorithm.algorithmId}`);s=2}switch(s){case 1:{let t,s;if(!0===n.useOAEP){t=r.getOIDByAlgorithm({name:"RSA-OAEP"},!0,"keyEncryptionAlgorithm");const e=r.getOIDByAlgorithm({name:n.oaepHashAlgorithm},!0,"RSAES-OAEP-params"),a=new An({algorithmId:e,algorithmParams:new fs});s=new Sf({hashAlgorithm:a,maskGenAlgorithm:new An({algorithmId:"1.2.840.113549.1.1.8",algorithmParams:a.toSchema()})}).toSchema()}else{if(t=r.getOIDByAlgorithm({name:"RSAES-PKCS1-v1_5"}),t===Fr)throw new Error("Can not find OID for RSAES-PKCS1-v1_5");s=new fs}const a=new nm({version:0,rid:new Wh({issuer:e.issuer,serialNumber:e.serialNumber}),keyEncryptionAlgorithm:new An({algorithmId:t,algorithmParams:s}),recipientCertificate:e});this.recipientInfos.push(new pf({variant:1,value:a}))}break;case 2:{const t=new Em({variant:1,value:new Wh({issuer:e.issuer,serialNumber:e.serialNumber})});this._addKeyAgreeRecipientInfo(t,n,{recipientCertificate:e},r)}break;default:throw new Error(`Unknown "variant" value: ${s}`)}return!0}addRecipientByPreDefinedData(e,t={},s,r=Xo(!0)){if(qr.assert(e,"preDefinedData","ArrayBuffer"),!e.byteLength)throw new Error("Pre-defined data could have zero length");if(!t.keyIdentifier){const e=new ArrayBuffer(16),s=new Uint8Array(e);r.getRandomValues(s),t.keyIdentifier=e}switch(t.hmacHashAlgorithm||(t.hmacHashAlgorithm="SHA-512"),void 0===t.iterationCount&&(t.iterationCount=2048),t.keyEncryptionAlgorithm||(t.keyEncryptionAlgorithm={name:"AES-KW",length:256}),t.keyEncryptionAlgorithmParams||(t.keyEncryptionAlgorithmParams=new fs),s){case 1:{const s=r.getOIDByAlgorithm(t.keyEncryptionAlgorithm,!0,"keyEncryptionAlgorithm"),n=new ef({version:4,kekid:new Wm({keyIdentifier:new ws({valueHex:t.keyIdentifier})}),keyEncryptionAlgorithm:new An({algorithmId:s,algorithmParams:t.keyEncryptionAlgorithmParams}),preDefinedKEK:e});this.recipientInfos.push(new pf({variant:3,value:n}))}break;case 2:{const s=r.getOIDByAlgorithm({name:"PBKDF2"},!0,"keyDerivationAlgorithm"),n=new ArrayBuffer(64),a=new Uint8Array(n);r.getRandomValues(a);const i=r.getOIDByAlgorithm({name:"HMAC",hash:{name:t.hmacHashAlgorithm}},!0,"hmacHashAlgorithm"),o=new Mo({salt:new ws({valueHex:n}),iterationCount:t.iterationCount,prf:new An({algorithmId:i,algorithmParams:new fs})}),l=r.getOIDByAlgorithm(t.keyEncryptionAlgorithm,!0,"keyEncryptionAlgorithm"),c=new lf({version:0,keyDerivationAlgorithm:new An({algorithmId:s,algorithmParams:o.toSchema()}),keyEncryptionAlgorithm:new An({algorithmId:l,algorithmParams:t.keyEncryptionAlgorithmParams}),password:e});this.recipientInfos.push(new pf({variant:4,value:c}))}break;default:throw new Error(`Unknown value for "variant": ${s}`)}}addRecipientByKeyIdentifier(e,t,s,r=Xo(!0)){const n=Object.assign({},Tf,s||{}),a=new Em({variant:2,value:new Sm({subjectKeyIdentifier:new ws({valueHex:t})})});this._addKeyAgreeRecipientInfo(a,n,{recipientPublicKey:e},r)}_addKeyAgreeRecipientInfo(e,t,s,r=Xo(!0)){const n=new Vm({rid:e}),a=r.getOIDByAlgorithm({name:"AES-KW",length:t.kekEncryptionLength},!0,"keyEncryptionAlgorithm"),i=new An({algorithmId:a}),o=r.getOIDByAlgorithm({name:"ECDH",kdf:t.kdfAlgorithm},!0,"KeyAgreeRecipientInfo"),l=new ArrayBuffer(64),c=new Uint8Array(l);r.getRandomValues(c);const u={version:3,ukm:new ws({valueHex:l}),keyEncryptionAlgorithm:new An({algorithmId:o,algorithmParams:i.toSchema()}),recipientEncryptedKeys:new Tm({encryptedKeys:[n]})},h=new jm(Object.assign(u,s));this.recipientInfos.push(new pf({variant:2,value:h}))}async encrypt(e,t,s=Xo(!0)){const r=new ArrayBuffer(16),n=new Uint8Array(r);s.getRandomValues(n);const a=new Uint8Array(t),i=s.getOIDByAlgorithm(e,!0,"contentEncryptionAlgorithm"),o=await s.generateKey(e,!0,["encrypt"]),l=await s.encrypt({name:e.name,iv:n},o,a),c=await s.exportKey("raw",o);this.version=2,this.encryptedContentInfo=new Vo({disableSplit:this.policy.disableSplit,contentType:"1.2.840.113549.1.7.1",contentEncryptionAlgorithm:new An({algorithmId:i,algorithmParams:new ws({valueHex:r})}),encryptedContent:new ws({valueHex:l})});const u=async e=>{const t=this.recipientInfos[e].value;let r,n;if(t.recipientPublicKey)r=t.recipientPublicKey.algorithm.namedCurve,n=t.recipientPublicKey;else{if(!t.recipientCertificate)throw new Error("Unsupported RecipientInfo");{const a=t.recipientCertificate.subjectPublicKeyInfo.algorithm.algorithmParams;if(a.constructor.blockName()!==Bs.blockName())throw new Error(`Incorrect "recipientCertificate" for index ${e}`);switch(a.valueBlock.toString()){case"1.2.840.10045.3.1.7":r="P-256";break;case"1.3.132.0.34":r="P-384";break;case"1.3.132.0.35":r="P-521";break;default:throw new Error(`Incorrect curve OID for index ${e}`)}n=await t.recipientCertificate.getPublicKey({algorithm:{algorithm:{name:"ECDH",namedCurve:r},usages:[]}},s)}}const a=Pf[r],i=await s.generateKey({name:"ECDH",namedCurve:r},!0,["deriveBits"]),l=await s.exportKey("spki",i.publicKey),c=await s.deriveBits({name:"ECDH",public:n},i.privateKey,a),u=new An({schema:t.keyEncryptionAlgorithm.algorithmParams}),h=s.getAlgorithmByOID(u.algorithmId,!0,"aesKWAlgorithm");let m=h.length;const f=new ArrayBuffer(4),d=new Uint8Array(f);for(let e=3;e>=0;e--)d[e]=m,m>>=8;const g=new Cf({keyInfo:new An({algorithmId:u.algorithmId}),entityUInfo:t.ukm,suppPubInfo:new ws({valueHex:f})}).toSchema().toBER(!1),p=s.getAlgorithmByOID(t.keyEncryptionAlgorithm.algorithmId,!0,"ecdhAlgorithm"),w=await tl(p.kdf,c,h.length,g,s),y=await s.importKey("raw",w,{name:"AES-KW"},!0,["wrapKey"]),v=await s.wrapKey("raw",o,y,{name:"AES-KW"}),b=new mm;return b.variant=3,b.value=lm.fromBER(l),t.originator=b,t.recipientEncryptedKeys.encryptedKeys[0].encryptedKey=new ws({valueHex:v}),{ecdhPrivateKey:i.privateKey}},h=async e=>{const t=this.recipientInfos[e].value,r=s.getAlgorithmByOID(t.keyEncryptionAlgorithm.algorithmId,!0,"keyEncryptionAlgorithm");if("RSA-OAEP"===r.name){const e=t.keyEncryptionAlgorithm.algorithmParams,n=new Sf({schema:e});if(r.hash=s.getAlgorithmByOID(n.hashAlgorithm.algorithmId),"name"in r.hash==!1)throw new Error(`Incorrect OID for hash algorithm: ${n.hashAlgorithm.algorithmId}`)}try{const e=await t.recipientCertificate.getPublicKey({algorithm:{algorithm:r,usages:["encrypt","wrapKey"]}},s),n=await s.encrypt(e.algorithm,e,c);t.encryptedKey=new ws({valueHex:n})}catch{}},m=async e=>{const t=this.recipientInfos[e].value,r=s.getAlgorithmByOID(t.keyEncryptionAlgorithm.algorithmId,!0,"kekAlgorithm"),n=await s.importKey("raw",new Uint8Array(t.preDefinedKEK),r,!0,["wrapKey"]),a=await s.wrapKey("raw",o,n,r);t.encryptedKey=new ws({valueHex:a})},f=async e=>{const t=this.recipientInfos[e].value;let r;if(!t.keyDerivationAlgorithm)throw new Error('Please append encoded "keyDerivationAlgorithm"');if(!t.keyDerivationAlgorithm.algorithmParams)throw new Error('Incorrectly encoded "keyDerivationAlgorithm"');try{r=new Mo({schema:t.keyDerivationAlgorithm.algorithmParams})}catch{throw new Error('Incorrectly encoded "keyDerivationAlgorithm"')}const n=new Uint8Array(t.password),a=await s.importKey("raw",n,"PBKDF2",!1,["deriveKey"]),i=s.getAlgorithmByOID(t.keyEncryptionAlgorithm.algorithmId,!0,"kekAlgorithm");let l="SHA-1";if(r.prf){l=s.getAlgorithmByOID(r.prf.algorithmId,!0,"prfAlgorithm").hash.name}const c=new Uint8Array(r.salt.valueBlock.valueHex),u=r.iterationCount,h=await s.deriveKey({name:"PBKDF2",hash:{name:l},salt:c,iterations:u},a,i,!0,["wrapKey"]),m=await s.wrapKey("raw",o,h,i);t.encryptedKey=new ws({valueHex:m})},d=[];for(let e=0;e<this.recipientInfos.length;e++)switch(this.recipientInfos[e].variant){case 1:d.push(await h(e));break;case 2:d.push(await u(e));break;case 3:d.push(await m(e));break;case 4:d.push(await f(e));break;default:throw new Error(`Unknown recipient type in array with index ${e}`)}return d}async decrypt(e,t,s=Xo(!0)){const r=t||{};if(e+1>this.recipientInfos.length)throw new Error('Maximum value for "index" is: '+(this.recipientInfos.length-1));const n=async e=>{const t=this.recipientInfos[e].value;let n,a,i;const o=t.originator;if(r.recipientCertificate){const t=r.recipientCertificate.subjectPublicKeyInfo.algorithm.algorithmParams;if(t.constructor.blockName()!==Bs.blockName())throw new Error(`Incorrect "recipientCertificate" for index ${e}`);n=t.valueBlock.toString()}else{if(!o.value.algorithm.algorithmParams)throw new Error('Parameter "recipientCertificate" is mandatory for "KeyAgreeRecipientInfo" if algorithm params are missing from originator');{const t=o.value.algorithm.algorithmParams;if(t.constructor.blockName()!==Bs.blockName())throw new Error(`Incorrect originator for index ${e}`);n=t.valueBlock.toString()}}if(!r.recipientPrivateKey)throw new Error('Parameter "recipientPrivateKey" is mandatory for "KeyAgreeRecipientInfo"');switch(n){case"1.2.840.10045.3.1.7":a="P-256",i=256;break;case"1.3.132.0.34":a="P-384",i=384;break;case"1.3.132.0.35":a="P-521",i=528;break;default:throw new Error(`Incorrect curve OID for index ${e}`)}let l,c=s;De.isBufferSource(r.recipientPrivateKey)?l=await s.importKey("pkcs8",r.recipientPrivateKey,{name:"ECDH",namedCurve:a},!0,["deriveBits"]):(l=r.recipientPrivateKey,"crypto"in r&&r.crypto&&(c=r.crypto.subtle)),"algorithmParams"in o.value.algorithm==!1&&(o.value.algorithm.algorithmParams=new Bs({value:n}));const u=o.value.toSchema().toBER(!1),h=await s.importKey("spki",u,{name:"ECDH",namedCurve:a},!0,[]),m=await c.deriveBits({name:"ECDH",public:h},l,i);async function f(e){e=e||!1;const r=new An({schema:t.keyEncryptionAlgorithm.algorithmParams}),n=s.getAlgorithmByOID(r.algorithmId,!0,"kwAlgorithm");let a=n.length;const i=new ArrayBuffer(4),o=new Uint8Array(i);for(let e=3;e>=0;e--)o[e]=a,a>>=8;const l={algorithmId:r.algorithmId};e&&(l.algorithmParams=new fs);const c=new Cf({keyInfo:new An(l),entityUInfo:t.ukm,suppPubInfo:new ws({valueHex:i})}).toSchema().toBER(!1),u=s.getAlgorithmByOID(t.keyEncryptionAlgorithm.algorithmId,!0,"ecdhAlgorithm");if(!u.name)throw new Error(`Incorrect OID for key encryption algorithm: ${t.keyEncryptionAlgorithm.algorithmId}`);return tl(u.kdf,m,n.length,c,s)}const d=await f(),g=async e=>s.importKey("raw",e,{name:"AES-KW"},!0,["unwrapKey"]),p=await g(d),w=async e=>{const r=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,n=s.getAlgorithmByOID(r,!0,"contentEncryptionAlgorithm");return s.unwrapKey("raw",t.recipientEncryptedKeys.encryptedKeys[0].encryptedKey.valueBlock.valueHexView,e,{name:"AES-KW"},n,!0,["decrypt"])};try{return await w(p)}catch{const e=await f(!0);return w(await g(e))}},a=async e=>{const t=this.recipientInfos[e].value;if(!r.recipientPrivateKey)throw new Error('Parameter "recipientPrivateKey" is mandatory for "KeyTransRecipientInfo"');const n=s.getAlgorithmByOID(t.keyEncryptionAlgorithm.algorithmId,!0,"keyEncryptionAlgorithm");if("RSA-OAEP"===n.name){const e=t.keyEncryptionAlgorithm.algorithmParams,r=new Sf({schema:e});if(n.hash=s.getAlgorithmByOID(r.hashAlgorithm.algorithmId),"name"in n.hash==!1)throw new Error(`Incorrect OID for hash algorithm: ${r.hashAlgorithm.algorithmId}`)}let a,i=s;De.isBufferSource(r.recipientPrivateKey)?a=await s.importKey("pkcs8",r.recipientPrivateKey,n,!0,["decrypt"]):(a=r.recipientPrivateKey,"crypto"in r&&r.crypto&&(i=r.crypto.subtle));const o=await i.decrypt(a.algorithm,a,t.encryptedKey.valueBlock.valueHexView),l=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,c=s.getAlgorithmByOID(l,!0,"contentEncryptionAlgorithm");if("name"in c==!1)throw new Error(`Incorrect "contentEncryptionAlgorithm": ${l}`);return s.importKey("raw",o,c,!0,["decrypt"])},i=async e=>{const t=this.recipientInfos[e].value;if(!r.preDefinedData)throw new Error('Parameter "preDefinedData" is mandatory for "KEKRecipientInfo"');const n=s.getAlgorithmByOID(t.keyEncryptionAlgorithm.algorithmId,!0,"kekAlgorithm"),a=await s.importKey("raw",r.preDefinedData,n,!0,["unwrapKey"]),i=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,o=s.getAlgorithmByOID(i,!0,"contentEncryptionAlgorithm");if(!o.name)throw new Error(`Incorrect "contentEncryptionAlgorithm": ${i}`);return s.unwrapKey("raw",t.encryptedKey.valueBlock.valueHexView,a,n,o,!0,["decrypt"])},o=async e=>{const t=this.recipientInfos[e].value;let n;if(!r.preDefinedData)throw new Error('Parameter "preDefinedData" is mandatory for "KEKRecipientInfo"');if(!t.keyDerivationAlgorithm)throw new Error('Please append encoded "keyDerivationAlgorithm"');if(!t.keyDerivationAlgorithm.algorithmParams)throw new Error('Incorrectly encoded "keyDerivationAlgorithm"');try{n=new Mo({schema:t.keyDerivationAlgorithm.algorithmParams})}catch{throw new Error('Incorrectly encoded "keyDerivationAlgorithm"')}const a=await s.importKey("raw",r.preDefinedData,"PBKDF2",!1,["deriveKey"]),i=s.getAlgorithmByOID(t.keyEncryptionAlgorithm.algorithmId,!0,"keyEncryptionAlgorithm"),o=n.prf?s.getAlgorithmByOID(n.prf.algorithmId,!0,"prfAlgorithm").hash.name:"SHA-1",l=new Uint8Array(n.salt.valueBlock.valueHex),c=n.iterationCount,u=await s.deriveKey({name:"PBKDF2",hash:{name:o},salt:l,iterations:c},a,i,!0,["unwrapKey"]),h=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,m=s.getAlgorithmByOID(h,!0,"contentEncryptionAlgorithm");return s.unwrapKey("raw",t.encryptedKey.valueBlock.valueHexView,u,i,m,!0,["decrypt"])};let l;switch(this.recipientInfos[e].variant){case 1:l=await a(e);break;case 2:l=await n(e);break;case 3:l=await i(e);break;case 4:l=await o(e);break;default:throw new Error(`Unknown recipient type in array with index ${e}`)}const c=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,u=s.getAlgorithmByOID(c,!0,"contentEncryptionAlgorithm"),h=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmParams.valueBlock.valueHex,m=new Uint8Array(h);if(!this.encryptedContentInfo.encryptedContent)throw new Error("Required property `encryptedContent` is empty");const f=this.encryptedContentInfo.getEncryptedContent();return s.decrypt({name:u.name,iv:m},l,f)}}Uf.CLASS_NAME="EnvelopedData";const Lf="safeContents",Rf="parsedValue",_f="contentInfos";class Hf extends zr{constructor(e={}){super(),this.safeContents=He(e,Lf,Hf.defaultValues(Lf)),Rf in e&&(this.parsedValue=He(e,Rf,Hf.defaultValues(Rf))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Lf:return[];case Rf:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Lf:return 0===t.length;case Rf:return t instanceof Object&&0===Object.keys(t).length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new or({name:t.contentInfos||Fr,value:Lc.schema()})]})}fromSchema(e){st(e,[_f]);const t=cr(e,e,Hf.schema({names:{contentInfos:_f}}));Gr.assertSchema(t,this.className),this.safeContents=Array.from(t.result.contentInfos,(e=>new Lc({schema:e})))}toSchema(){return new Os({value:Array.from(this.safeContents,(e=>e.toSchema()))})}toJSON(){return{safeContents:Array.from(this.safeContents,(e=>e.toJSON()))}}async parseInternalValues(e,t=Xo(!0)){if(Wr.assert(e,Lf),qr.assert(e.safeContents,Lf,"Array"),e.safeContents.length!==this.safeContents.length)throw new qr('Length of "parameters.safeContents" must be equal to "this.safeContents.length"');this.parsedValue={safeContents:[]};for(const[s,r]of this.safeContents.entries()){const n=e.safeContents[s],a=`parameters.safeContents[${s}]`;switch(r.contentType){case Zn:{qr.assert(r.content,"this.safeContents[j].content",ws);const e=r.content.getValue();this.parsedValue.safeContents.push({privacyMode:0,value:Nh.fromBER(e)})}break;case ea:{const e=new Uf({schema:r.content});Wr.assert(a,n,"recipientCertificate","recipientKey");const s=n,i=s.recipientCertificate,o=s.recipientKey,l=await e.decrypt(0,{recipientCertificate:i,recipientPrivateKey:o},t);this.parsedValue.safeContents.push({privacyMode:2,value:Nh.fromBER(l)})}break;case ta:{const e=new oh({schema:r.content});Wr.assert(a,n,"password");const s=n.password,i=await e.decrypt({password:s},t);this.parsedValue.safeContents.push({privacyMode:1,value:Nh.fromBER(i)})}break;default:throw new Error(`Unknown "contentType" for AuthenticatedSafe: " ${r.contentType}`)}}}async makeInternalValues(e,t=Xo(!0)){if(!this.parsedValue)throw new Error('Please run "parseValues" first or add "parsedValue" manually');if(qr.assert(this.parsedValue,"this.parsedValue","object"),qr.assert(this.parsedValue.safeContents,"this.parsedValue.safeContents","Array"),qr.assert(e,"parameters","object"),Wr.assert(e,"safeContents"),qr.assert(e.safeContents,"parameters.safeContents","Array"),e.safeContents.length!==this.parsedValue.safeContents.length)throw new qr('Length of "parameters.safeContents" must be equal to "this.parsedValue.safeContents"');this.safeContents=[];for(const[s,r]of this.parsedValue.safeContents.entries())switch(Wr.assert("content",r,"privacyMode","value"),qr.assert(r.value,"content.value",Nh),r.privacyMode){case 0:{const e=r.value.toSchema().toBER(!1);this.safeContents.push(new Lc({contentType:"1.2.840.113549.1.7.1",content:new ws({valueHex:e})}))}break;case 1:{const n=new oh,a=e.safeContents[s];a.contentToEncrypt=r.value.toSchema().toBER(!1),await n.encrypt(a,t),this.safeContents.push(new Lc({contentType:"1.2.840.113549.1.7.6",content:n.toSchema()}))}break;case 2:{const n=new Uf,a=r.value.toSchema().toBER(!1),i=e.safeContents[s];switch(Wr.assert(`parameters.safeContents[${s}]`,i,"encryptingCertificate","encryptionAlgorithm"),!0){case"aes-cbc"===i.encryptionAlgorithm.name.toLowerCase():case"aes-gcm"===i.encryptionAlgorithm.name.toLowerCase():break;default:throw new Error(`Incorrect parameter "encryptionAlgorithm" in "parameters.safeContents[i]": ${i.encryptionAlgorithm}`)}switch(!0){case 128===i.encryptionAlgorithm.length:case 192===i.encryptionAlgorithm.length:case 256===i.encryptionAlgorithm.length:break;default:throw new Error(`Incorrect parameter "encryptionAlgorithm.length" in "parameters.safeContents[i]": ${i.encryptionAlgorithm.length}`)}const o=i.encryptionAlgorithm;n.addRecipientByCertificate(i.encryptingCertificate,{},void 0,t),await n.encrypt(o,a,t),this.safeContents.push(new Lc({contentType:"1.2.840.113549.1.7.3",content:n.toSchema()}))}break;default:throw new Error(`Incorrect value for "content.privacyMode": ${r.privacyMode}`)}return this}}Hf.CLASS_NAME="AuthenticatedSafe";const Kf="hashAlgorithm",Mf="issuerNameHash",jf="issuerKeyHash",Jf="serialNumber",$f=[Kf,Mf,jf,Jf];class Ff extends zr{static async create(e,t,s=Xo(!0)){const r=new Ff;return await r.createForCertificate(e,t,s),r}constructor(e={}){super(),this.hashAlgorithm=He(e,Kf,Ff.defaultValues(Kf)),this.issuerNameHash=He(e,Mf,Ff.defaultValues(Mf)),this.issuerKeyHash=He(e,jf,Ff.defaultValues(jf)),this.serialNumber=He(e,Jf,Ff.defaultValues(Jf)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Kf:return new An;case Mf:case jf:return new ws;case Jf:return new Ns;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Kf:return t.algorithmId===Fr&&"algorithmParams"in t==!1;case Mf:case jf:case Jf:return t.isEqual(Ff.defaultValues(Jf));default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[An.schema(t.hashAlgorithmObject||{names:{blockName:t.hashAlgorithm||Fr}}),new ws({name:t.issuerNameHash||Fr}),new ws({name:t.issuerKeyHash||Fr}),new Ns({name:t.serialNumber||Fr})]})}fromSchema(e){st(e,$f);const t=cr(e,e,Ff.schema({names:{hashAlgorithm:Kf,issuerNameHash:Mf,issuerKeyHash:jf,serialNumber:Jf}}));Gr.assertSchema(t,this.className),this.hashAlgorithm=new An({schema:t.result.hashAlgorithm}),this.issuerNameHash=t.result.issuerNameHash,this.issuerKeyHash=t.result.issuerKeyHash,this.serialNumber=t.result.serialNumber}toSchema(){return new Os({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&&(!!De.isEqual(this.issuerNameHash.valueBlock.valueHexView,e.issuerNameHash.valueBlock.valueHexView)&&(!!De.isEqual(this.issuerKeyHash.valueBlock.valueHexView,e.issuerKeyHash.valueBlock.valueHexView)&&!!this.serialNumber.isEqual(e.serialNumber)))}async createForCertificate(e,t,s=Xo(!0)){Wr.assert(t,Kf,"issuerCertificate");const r=s.getOIDByAlgorithm({name:t.hashAlgorithm},!0,"hashAlgorithm");this.hashAlgorithm=new An({algorithmId:r,algorithmParams:new fs});const n=t.issuerCertificate;this.serialNumber=e.serialNumber;const a=await s.digest({name:t.hashAlgorithm},n.subject.toSchema().toBER(!1));this.issuerNameHash=new ws({valueHex:a});const i=n.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView,o=await s.digest({name:t.hashAlgorithm},i);this.issuerKeyHash=new ws({valueHex:o})}}Ff.CLASS_NAME="CertID";const qf="certID",Wf="certStatus",Gf="thisUpdate",zf="nextUpdate",Yf="singleExtensions",Qf=[qf,Wf,Gf,zf,Yf];class Zf extends zr{constructor(e={}){super(),this.certID=He(e,qf,Zf.defaultValues(qf)),this.certStatus=He(e,Wf,Zf.defaultValues(Wf)),this.thisUpdate=He(e,Gf,Zf.defaultValues(Gf)),zf in e&&(this.nextUpdate=He(e,zf,Zf.defaultValues(zf))),Yf in e&&(this.singleExtensions=He(e,Yf,Zf.defaultValues(Yf))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case qf:return new Ff;case Wf:return{};case Gf:case zf:return new Date(0,0,0);case Yf:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case qf:return Ff.compareWithDefault("hashAlgorithm",t.hashAlgorithm)&&Ff.compareWithDefault("issuerNameHash",t.issuerNameHash)&&Ff.compareWithDefault("issuerKeyHash",t.issuerKeyHash)&&Ff.compareWithDefault("serialNumber",t.serialNumber);case Wf:return 0===Object.keys(t).length;case Gf:case zf:return t===Zf.defaultValues(e);default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[Ff.schema(t.certID||{}),new ir({value:[new is({name:t.certStatus||Fr,idBlock:{tagClass:3,tagNumber:0}}),new us({name:t.certStatus||Fr,idBlock:{tagClass:3,tagNumber:1},value:[new Xs,new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new Es]})]}),new is({name:t.certStatus||Fr,idBlock:{tagClass:3,tagNumber:2},lenBlock:{length:1}})]}),new Xs({name:t.thisUpdate||Fr}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new Xs({name:t.nextUpdate||Fr})]}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[Ol.schema(t.singleExtensions||{})]})]})}fromSchema(e){st(e,Qf);const t=cr(e,e,Zf.schema({names:{certID:{names:{blockName:qf}},certStatus:Wf,thisUpdate:Gf,nextUpdate:zf,singleExtensions:{names:{blockName:Yf}}}}));Gr.assertSchema(t,this.className),this.certID=new Ff({schema:t.result.certID}),this.certStatus=t.result.certStatus,this.thisUpdate=t.result.thisUpdate.toDate(),zf in t.result&&(this.nextUpdate=t.result.nextUpdate.toDate()),Yf in t.result&&(this.singleExtensions=Array.from(t.result.singleExtensions.valueBlock.value,(e=>new Vl({schema:e}))))}toSchema(){const e=[];return e.push(this.certID.toSchema()),e.push(this.certStatus),e.push(new Xs({valueDate:this.thisUpdate})),this.nextUpdate&&e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:[new Xs({valueDate:this.nextUpdate})]})),this.singleExtensions&&e.push(new us({idBlock:{tagClass:3,tagNumber:1},value:[new Os({value:Array.from(this.singleExtensions,(e=>e.toSchema()))})]})),new Os({value:e})}toJSON(){const 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,(e=>e.toJSON()))),e}}Zf.CLASS_NAME="SingleResponse";const Xf="tbs",ed="version",td="responderID",sd="producedAt",rd="responses",nd="responseExtensions",ad="ResponseData",id=`${ad}.${ed}`,od=`${ad}.${td}`,ld=`${ad}.${sd}`,cd=`${ad}.${rd}`,ud=`${ad}.${nd}`,hd=[ad,id,od,ld,cd,ud];class md extends zr{get tbs(){return De.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e)}constructor(e={}){super(),this.tbsView=new Uint8Array(He(e,Xf,md.defaultValues(Xf))),ed in e&&(this.version=He(e,ed,md.defaultValues(ed))),this.responderID=He(e,td,md.defaultValues(td)),this.producedAt=He(e,sd,md.defaultValues(sd)),this.responses=He(e,rd,md.defaultValues(rd)),nd in e&&(this.responseExtensions=He(e,nd,md.defaultValues(nd))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case ed:return 0;case Xf:return $r;case td:return{};case sd:return new Date(0,0,0);case rd:case nd:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Xf:return 0===t.byteLength;case td:return 0===Object.keys(t).length;case sd:return t===md.defaultValues(e);case rd:case nd:return 0===t.length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||ad,value:[new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new Ns({name:t.version||id})]}),new ir({value:[new us({name:t.responderID||od,idBlock:{tagClass:3,tagNumber:1},value:[sn.schema(t.ResponseDataByName||{names:{blockName:"ResponseData.byName"}})]}),new us({name:t.responderID||od,idBlock:{tagClass:3,tagNumber:2},value:[new ws({name:t.ResponseDataByKey||"ResponseData.byKey"})]})]}),new Xs({name:t.producedAt||ld}),new Os({value:[new or({name:cd,value:Zf.schema(t.response||{})})]}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[Ol.schema(t.extensions||{names:{blockName:ud}})]})]})}fromSchema(e){st(e,hd);const t=cr(e,e,md.schema());Gr.assertSchema(t,this.className),this.tbsView=t.result.ResponseData.valueBeforeDecodeView,id in t.result&&(this.version=t.result[id].valueBlock.valueDec),1===t.result[od].idBlock.tagNumber?this.responderID=new sn({schema:t.result[od].valueBlock.value[0]}):this.responderID=t.result[od].valueBlock.value[0],this.producedAt=t.result[ld].toDate(),this.responses=Array.from(t.result[cd],(e=>new Zf({schema:e}))),ud in t.result&&(this.responseExtensions=Array.from(t.result[ud].valueBlock.value,(e=>new Vl({schema:e}))))}toSchema(e=!1){let t;if(!1===e){if(!this.tbsView.byteLength)return md.schema();const e=ls(this.tbsView);Gr.assert(e,"TBS Response Data"),t=e.result}else{const e=[];ed in this&&e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:[new Ns({value:this.version})]})),this.responderID instanceof sn?e.push(new us({idBlock:{tagClass:3,tagNumber:1},value:[this.responderID.toSchema()]})):e.push(new us({idBlock:{tagClass:3,tagNumber:2},value:[this.responderID]})),e.push(new Xs({valueDate:this.producedAt})),e.push(new Os({value:Array.from(this.responses,(e=>e.toSchema()))})),this.responseExtensions&&e.push(new us({idBlock:{tagClass:3,tagNumber:1},value:[new Os({value:Array.from(this.responseExtensions,(e=>e.toSchema()))})]})),t=new Os({value:e})}return t}toJSON(){const e={};return ed 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,(e=>e.toJSON()))),this.responseExtensions&&(e.responseExtensions=Array.from(this.responseExtensions,(e=>e.toJSON()))),e}}md.CLASS_NAME="ResponseData";const fd="trustedCerts",dd="certs",gd="crls",pd="ocsps",wd="checkDate",yd="findOrigin",vd="findIssuer";var bd;!function(e){e[e.unknown=-1]="unknown",e[e.success=0]="success",e[e.noRevocation=11]="noRevocation",e[e.noPath=60]="noPath",e[e.noValidPath=97]="noValidPath"}(bd||(bd={}));class Sd extends Error{constructor(e,t){super(t),this.name=Sd.NAME,this.code=e,this.message=t}}Sd.NAME="ChainValidationError";class kd{constructor(e={}){this.trustedCerts=He(e,fd,this.defaultValues(fd)),this.certs=He(e,dd,this.defaultValues(dd)),this.crls=He(e,gd,this.defaultValues(gd)),this.ocsps=He(e,pd,this.defaultValues(pd)),this.checkDate=He(e,wd,this.defaultValues(wd)),this.findOrigin=He(e,yd,this.defaultValues(yd)),this.findIssuer=He(e,vd,this.defaultValues(vd))}static defaultFindOrigin(e,t){0===e.tbsView.byteLength&&(e.tbsView=new Uint8Array(e.encodeTBS().toBER()));for(const s of t.certs)if(0===s.tbsView.byteLength&&(s.tbsView=new Uint8Array(s.encodeTBS().toBER())),De.isEqual(e.tbsView,s.tbsView))return"Intermediate Certificates";for(const s of t.trustedCerts)if(0===s.tbsView.byteLength&&(s.tbsView=new Uint8Array(s.encodeTBS().toBER())),De.isEqual(e.tbsView,s.tbsView))return"Trusted Certificates";return"Unknown"}async defaultFindIssuer(e,t,s=Xo(!0)){const r=[];let n=null,a=null,i=null;if(e.subject.isEqual(e.issuer))try{if(await e.verify(void 0,s))return[e]}catch{}if(e.extensions)for(const t of e.extensions)if(t.extnID===zn&&t.parsedValue instanceof ua){t.parsedValue.keyIdentifier?n=t.parsedValue.keyIdentifier:(t.parsedValue.authorityCertIssuer&&(a=t.parsedValue.authorityCertIssuer),t.parsedValue.authorityCertSerialNumber&&(i=t.parsedValue.authorityCertSerialNumber));break}function o(t){if(null!==n&&t.extensions){let e=!1;for(const s of t.extensions)if("2.5.29.14"===s.extnID&&s.parsedValue){e=!0,De.isEqual(s.parsedValue.valueBlock.valueHex,n.valueBlock.valueHexView)&&r.push(t);break}if(e)return}let s=!1;null!==i&&(s=t.serialNumber.isEqual(i)),null!==a?t.subject.isEqual(a)&&s&&r.push(t):e.issuer.isEqual(t.subject)&&r.push(t)}for(const e of t.trustedCerts)o(e);for(const e of t.certs)o(e);for(let t=r.length-1;t>=0;t--)try{!1===await e.verify(r[t],s)&&r.splice(t,1)}catch{r.splice(t,1)}return r}defaultValues(e){switch(e){case fd:case dd:case gd:case pd:return[];case wd:return new Date;case yd:return kd.defaultFindOrigin;case vd:return this.defaultFindIssuer;default:throw new Error(`Invalid member name for CertificateChainValidationEngine class: ${e}`)}}async sort(e=!1,t=Xo(!0)){const s=[],r=async(e,t)=>{const s=[];function n(e){let t=!0;for(let s=0;s<e.length;s++){for(let r=0;r<e.length;r++)if(r!==s&&e[s]===e[r]){t=!1;break}if(!t)break}return t}if(function(e,t){for(let s=0;s<t.length;s++)if(De.isEqual(e.tbsView,t[s].tbsView))return!0;return!1}(e,this.trustedCerts))return[[e]];const a=await this.findIssuer(e,this,t);if(0===a.length)throw new Error("No valid certificate paths found");for(let i=0;i<a.length;i++){if(De.isEqual(a[i].tbsView,e.tbsView)){s.push([a[i]]);continue}const o=await r(a[i],t);for(let e=0;e<o.length;e++){const t=o[e].slice();t.splice(0,0,a[i]),n(t)?s.push(t):s.push(o[e])}}return s},n=async e=>{const r=[],n=[],a=[];if(r.push(...s.filter((t=>e.issuer.isEqual(t.subject)))),0===r.length)return{status:1,statusMessage:"No certificate's issuers"};if(n.push(...this.crls.filter((t=>t.issuer.isEqual(e.issuer)))),0===n.length)return{status:2,statusMessage:"No CRLs for specific certificate issuer"};for(let e=0;e<n.length;e++){const s=n[e];if(!(s.nextUpdate&&s.nextUpdate.value<this.checkDate))for(let s=0;s<r.length;s++)try{if(await n[e].verify({issuerCertificate:r[s]},t)){a.push({crl:n[e],certificate:r[s]});break}}catch{}}return a.length?{status:0,statusMessage:Fr,result:a}:{status:3,statusMessage:"No valid CRLs found"}},a=async(e,s)=>{const r=t.getAlgorithmByOID(e.signatureAlgorithm.algorithmId);if(!r.name)return 1;if(!r.hash)return 1;for(let r=0;r<this.ocsps.length;r++){const n=this.ocsps[r],a=await n.getCertificateStatus(e,s,t);if(a.isForCertificate)return 0===a.status?0:1}return 2};async function i(e,t=!1){let s=!1,r=!1,n=!1,a=!1;if(e.extensions){for(let t=0;t<e.extensions.length;t++){const i=e.extensions[t];if(i.critical&&!i.parsedValue)return{result:!1,resultCode:6,resultMessage:`Unable to parse critical certificate extension: ${i.extnID}`};if("2.5.29.15"===i.extnID){n=!0;const e=new Uint8Array(i.parsedValue.valueBlock.valueHex);4==(4&e[0])&&(r=!0),2==(2&e[0])&&(a=!0)}i.extnID===Kn&&"cA"in i.parsedValue&&!0===i.parsedValue.cA&&(s=!0)}if(!0===r&&!1===s)return{result:!1,resultCode:3,resultMessage:'Unable to build certificate chain - using "keyCertSign" flag set without BasicConstraints'};if(!0===n&&!0===s&&!1===r)return{result:!1,resultCode:4,resultMessage:'Unable to build certificate chain - "keyCertSign" flag was not set'};if(!0===s&&!0===n&&t&&!1===a)return{result:!1,resultCode:5,resultMessage:'Unable to build certificate chain - intermediate certificate must have "cRLSign" key usage flag'}}return!1===s?{result:!1,resultCode:7,resultMessage:"Unable to build certificate chain - more than one possible end-user certificate"}:{result:!0,resultCode:0,resultMessage:Fr}}s.push(...this.trustedCerts),s.push(...this.certs);for(let e=0;e<s.length;e++)for(let t=0;t<s.length;t++)if(e!==t&&De.isEqual(s[e].tbsView,s[t].tbsView)){s.splice(t,1),e=0;break}const o=s[s.length-1];let l;const c=[o];if(l=await r(o,t),0===l.length)throw new Sd(bd.noPath,"Unable to find certificate path");for(let e=l.length-1;e>=0;e--){let t=!1;for(let s=0;s<l[e].length;s++){const r=l[e][s];for(let e=0;e<this.trustedCerts.length;e++)if(De.isEqual(r.tbsView,this.trustedCerts[e].tbsView)){t=!0;break}if(t)break}t||l.splice(e,1)}if(0===l.length)throw new Sd(bd.noValidPath,"No valid certificate paths found");let u=l[0].length,h=0;for(let e=0;e<l.length;e++)l[e].length<u&&(u=l[e].length,h=e);for(let e=0;e<l[h].length;e++)c.push(l[h][e]);if(l=await(async(t,s)=>{for(let e=0;e<t.length;e++)if(t[e].notBefore.value>s||t[e].notAfter.value<s)return{result:!1,resultCode:8,resultMessage:"The certificate is either not yet valid or expired"};if(t.length<2)return{result:!1,resultCode:9,resultMessage:"Too short certificate path"};for(let e=t.length-2;e>=0;e--)if(!1===t[e].issuer.isEqual(t[e].subject)&&!1===t[e].issuer.isEqual(t[e+1].subject))return{result:!1,resultCode:10,resultMessage:"Incorrect name chaining"};if(0!==this.crls.length||0!==this.ocsps.length)for(let s=0;s<t.length-1;s++){let r=2,o={status:0,statusMessage:Fr};if(0!==this.ocsps.length)switch(r=await a(t[s],t[s+1]),r){case 0:continue;case 1:return{result:!1,resultCode:12,resultMessage:"One of certificates was revoked via OCSP response"}}if(0!==this.crls.length){if(o=await n(t[s]),0===o.status&&o.result)for(let e=0;e<o.result.length;e++){if(o.result[e].crl.isCertificateRevoked(t[s]))return{result:!1,resultCode:12,resultMessage:"One of certificates had been revoked"};if(!1===(await i(o.result[e].certificate,!0)).result)return{result:!1,resultCode:13,resultMessage:"CRL issuer certificate is not a CA certificate or does not have crlSign flag"}}else if(!1===e)throw new Sd(bd.noRevocation,`No revocation values found for one of certificates: ${o.statusMessage}`)}else if(2===r)return{result:!1,resultCode:11,resultMessage:"No revocation values found for one of certificates"};if(2===r&&2===o.status&&e){const e=t[s+1];let r=!1;if(e.extensions)for(const t of e.extensions)switch(t.extnID){case $n:case Fn:case Qn:r=!0}if(r)throw new Sd(bd.noRevocation,`No revocation values found for one of certificates: ${o.statusMessage}`)}}for(const[e,s]of t.entries()){if(!e)continue;if(!(await i(s)).result)return{result:!1,resultCode:14,resultMessage:"One of intermediate certificates is not a CA certificate"}}return{result:!0}})(c,this.checkDate),!1===l.result)throw l;return c}async verify(e={},t=Xo(!0)){function s(e,t){const s=Yr(e),r=Yr(t),n=s.split("."),a=r.split("."),i=n.length,o=a.length;if(0===i||0===o||i<o)return!1;for(let e=0;e<i;e++)if(0===n[e].length)return!1;for(let e=0;e<o;e++)if(0===a[e].length){if(0===e){if(1===o)return!1;continue}return!1}for(let e=0;e<o;e++)if(0!==a[o-1-e].length&&0!==n[i-1-e].localeCompare(a[o-1-e]))return!1;return!0}function r(e,t){const r=Yr(e),n=Yr(t),a=r.split("@"),i=n.split("@");if(0===a.length||0===i.length||a.length<i.length)return!1;if(1===i.length){if(s(a[1],i[0])){const e=a[1].split("."),t=i[0].split(".");return 0===t[0].length||e.length===t.length}return!1}return 0===r.localeCompare(n)}function n(e,t){let r=Yr(e);const n=Yr(t),a=r.split("/");if(n.split("/").length>1)return!1;if(a.length>1)for(let e=0;e<a.length;e++)if(a[e].length>0&&":"!==a[e].charAt(a[e].length-1)){r=a[e].split(":")[0];break}if(s(r,n)){const e=r.split("."),t=n.split(".");return 0===t[0].length||e.length===t.length}return!1}function a(e,t){const s=e.valueBlock.valueHexView,r=t.valueBlock.valueHexView;if(4===s.length&&8===r.length){for(let e=0;e<4;e++)if((s[e]^r[e])&r[e+4])return!1;return!0}if(16===s.length&&32===r.length){for(let e=0;e<16;e++)if((s[e]^r[e])&r[e+16])return!1;return!0}return!1}function i(e,t){if(0===e.typesAndValues.length||0===t.typesAndValues.length)return!0;if(e.typesAndValues.length<t.typesAndValues.length)return!1;let s=!0,r=0;for(let n=0;n<t.typesAndValues.length;n++){let a=!1;for(let i=r;i<e.typesAndValues.length;i++)if(a=e.typesAndValues[i].isEqual(t.typesAndValues[n]),e.typesAndValues[i].type===t.typesAndValues[n].type&&(s=s&&a),!0===a){if(0===r||r===i){r=i+1;break}return!1}if(!1===a)return!1}return 0!==r&&s}try{if(0===this.certs.length)throw new Error("Empty certificate array");const o=e.passedWhenNotRevValues||!1,l=e.initialPolicySet||[Wn],c=e.initialExplicitPolicy||!1,u=e.initialPolicyMappingInhibit||!1,h=e.initialInhibitPolicy||!1,m=e.initialPermittedSubtreesSet||[],f=e.initialExcludedSubtreesSet||[],d=e.initialRequiredNameForms||[];let g=c,p=u,w=h;const y=[!1,!1,!1];let v=0,b=0,S=0,k=m,A=f;const N=d;let E=1;this.certs=await this.sort(o,t);const C=[];C.push(Wn);const I=[],B=new Array(this.certs.length-1);for(let e=0;e<this.certs.length-1;e++)B[e]=!0;I.push(B);const V=new Array(this.certs.length-1),x=new Array(this.certs.length-1);let D=g?this.certs.length-1:-1;for(let e=this.certs.length-2;e>=0;e--,E++){const t=this.certs[e];if(t.extensions){for(let s=0;s<t.extensions.length;s++){const r=t.extensions[s];if(r.extnID===qn){x[e]=r.parsedValue;for(let t=0;t<C.length;t++)if(C[t]===Wn){delete I[t][e];break}for(let t=0;t<r.parsedValue.certificatePolicies.length;t++){let s=-1;const n=r.parsedValue.certificatePolicies[t].policyIdentifier;for(let e=0;e<C.length;e++)if(n===C[e]){s=e;break}if(-1===s){C.push(n);const t=new Array(this.certs.length-1);t[e]=!0,I.push(t)}else I[s][e]=!0}}if(r.extnID===Gn){if(p)return{result:!1,resultCode:98,resultMessage:"Policy mapping prohibited"};V[e]=r.parsedValue}r.extnID===Yn&&!1===g&&(0===r.parsedValue.requireExplicitPolicy?(g=!0,D=e):!1===y[0]?(y[0]=!0,v=r.parsedValue.requireExplicitPolicy):v=v>r.parsedValue.requireExplicitPolicy?r.parsedValue.requireExplicitPolicy:v,0===r.parsedValue.inhibitPolicyMapping?p=!0:!1===y[1]?(y[1]=!0,b=r.parsedValue.inhibitPolicyMapping+1):b=b>r.parsedValue.inhibitPolicyMapping+1?r.parsedValue.inhibitPolicyMapping+1:b),"2.5.29.54"===r.extnID&&!1===w&&(0===r.parsedValue.valueBlock.valueDec?w=!0:!1===y[2]?(y[2]=!0,S=r.parsedValue.valueBlock.valueDec):S=S>r.parsedValue.valueBlock.valueDec?r.parsedValue.valueBlock.valueDec:S)}if(!0===w){let t=-1;for(let e=0;e<C.length;e++)if(C[e]===Wn){t=e;break}-1!==t&&delete I[0][e]}!1===g&&!0===y[0]&&(v--,0===v&&(g=!0,D=e,y[0]=!1)),!1===p&&!0===y[1]&&(b--,0===b&&(p=!0,y[1]=!1)),!1===w&&!0===y[2]&&(S--,0===S&&(w=!0,y[2]=!1))}}for(let e=0;e<this.certs.length-1;e++)if(e<this.certs.length-2&&void 0!==V[e+1])for(let t=0;t<V[e+1].mappings.length;t++){if(V[e+1].mappings[t].issuerDomainPolicy===Wn||V[e+1].mappings[t].subjectDomainPolicy===Wn)return{result:!1,resultCode:99,resultMessage:'The "anyPolicy" should not be a part of policy mapping scheme'};let s=-1,r=-1;for(let n=0;n<C.length;n++)C[n]===V[e+1].mappings[t].issuerDomainPolicy&&(s=n),C[n]===V[e+1].mappings[t].subjectDomainPolicy&&(r=n);void 0!==I[s][e]&&delete I[s][e];for(let n=0;n<x[e].certificatePolicies.length;n++)if(V[e+1].mappings[t].subjectDomainPolicy===x[e].certificatePolicies[n].policyIdentifier&&-1!==s&&-1!==r)for(let t=0;t<=e;t++)void 0!==I[r][t]&&(I[s][t]=!0,delete I[r][t])}for(let e=0;e<C.length;e++)if(C[e]===Wn)for(let t=0;t<D;t++)delete I[e][t];const O=[];for(let e=0;e<I.length;e++){let t=!0;for(let s=0;s<this.certs.length-1;s++){let r=!1;if(s<D&&C[e]===Wn&&C.length>1){t=!1;break}if(void 0===I[e][s]){if(s>=D)for(let e=0;e<C.length;e++)if(C[e]===Wn){!0===I[e][s]&&(r=!0);break}if(!r){t=!1;break}}}!0===t&&O.push(C[e])}let T=[];if(1===l.length&&l[0]===Wn&&!1===g)T=l;else if(1===O.length&&O[0]===Wn)T=l;else for(let e=0;e<O.length;e++)for(let t=0;t<l.length;t++)if(l[t]===O[e]||l[t]===Wn){T.push(O[e]);break}const P={result:T.length>0,resultCode:0,resultMessage:T.length>0?Fr:'Zero "userConstrPolicies" array, no intersections with "authConstrPolicies"',authConstrPolicies:O,userConstrPolicies:T,explicitPolicyIndicator:g,policyMappings:V,certificatePath:this.certs};if(0===T.length)return P;if(!1===P.result)return P;E=1;for(let e=this.certs.length-2;e>=0;e--,E++){const t=this.certs[e];let o=[],l=[],c=[];if(t.extensions)for(let e=0;e<t.extensions.length;e++){const s=t.extensions[e];s.extnID===Jn&&("permittedSubtrees"in s.parsedValue&&(l=l.concat(s.parsedValue.permittedSubtrees)),"excludedSubtrees"in s.parsedValue&&(c=c.concat(s.parsedValue.excludedSubtrees))),s.extnID===_n&&(o=o.concat(s.parsedValue.altNames))}let u=N.length<=0;for(let e=0;e<N.length;e++)switch(N[e].base.type){case 4:if(N[e].base.value.typesAndValues.length!==t.subject.typesAndValues.length)continue;u=!0;for(let s=0;s<t.subject.typesAndValues.length;s++)if(t.subject.typesAndValues[s].type!==N[e].base.value.typesAndValues[s].type){u=!1;break}if(!0===u)break}if(!1===u)throw P.result=!1,P.resultCode=21,P.resultMessage="No necessary name form found",P;const h=[[],[],[],[],[]];for(let e=0;e<k.length;e++)switch(k[e].base.type){case 1:h[0].push(k[e]);break;case 2:h[1].push(k[e]);break;case 4:h[2].push(k[e]);break;case 6:h[3].push(k[e]);break;case 7:h[4].push(k[e])}for(let e=0;e<5;e++){let l=!1,c=!1;const u=h[e];for(let h=0;h<u.length;h++){switch(e){case 0:if(o.length>0)for(let e=0;e<o.length;e++)1===o[e].type&&(c=!0,l=l||r(o[e].value,u[h].base.value));else for(let e=0;e<t.subject.typesAndValues.length;e++)"1.2.840.113549.1.9.1"!==t.subject.typesAndValues[e].type&&"0.9.2342.19200300.100.1.3"!==t.subject.typesAndValues[e].type||(c=!0,l=l||r(t.subject.typesAndValues[e].value.valueBlock.value,u[h].base.value));break;case 1:if(o.length>0)for(let e=0;e<o.length;e++)2===o[e].type&&(c=!0,l=l||s(o[e].value,u[h].base.value));break;case 2:c=!0,l=i(t.subject,u[h].base.value);break;case 3:if(o.length>0)for(let e=0;e<o.length;e++)6===o[e].type&&(c=!0,l=l||n(o[e].value,u[h].base.value));break;case 4:if(o.length>0)for(let e=0;e<o.length;e++)7===o[e].type&&(c=!0,l=l||a(o[e].value,u[h].base.value))}if(l)break}if(!1===l&&u.length>0&&c)throw P.result=!1,P.resultCode=41,P.resultMessage='Failed to meet "permitted sub-trees" name constraint',P}let m=!1;for(let e=0;e<A.length;e++){switch(A[e].base.type){case 1:if(o.length>=0)for(let t=0;t<o.length;t++)1===o[t].type&&(m=m||r(o[t].value,A[e].base.value));else for(let s=0;s<t.subject.typesAndValues.length;s++)"1.2.840.113549.1.9.1"!==t.subject.typesAndValues[s].type&&"0.9.2342.19200300.100.1.3"!==t.subject.typesAndValues[s].type||(m=m||r(t.subject.typesAndValues[s].value.valueBlock.value,A[e].base.value));break;case 2:if(o.length>0)for(let t=0;t<o.length;t++)2===o[t].type&&(m=m||s(o[t].value,A[e].base.value));break;case 4:m=m||i(t.subject,A[e].base.value);break;case 6:if(o.length>0)for(let t=0;t<o.length;t++)6===o[t].type&&(m=m||n(o[t].value,A[e].base.value));break;case 7:if(o.length>0)for(let t=0;t<o.length;t++)7===o[t].type&&(m=m||a(o[t].value,A[e].base.value))}if(m)break}if(!0===m)throw P.result=!1,P.resultCode=42,P.resultMessage='Failed to meet "excluded sub-trees" name constraint',P;k=k.concat(l),A=A.concat(c)}return P}catch(e){return e instanceof Error?e instanceof Sd?{result:!1,resultCode:e.code,resultMessage:e.message,error:e}:{result:!1,resultCode:bd.unknown,resultMessage:e.message,error:e}:e&&"object"==typeof e&&"resultMessage"in e?e:{result:!1,resultCode:-1,resultMessage:`${e}`}}}}const Ad="tbsResponseData",Nd="signatureAlgorithm",Ed="signature",Cd="certs",Id="BasicOCSPResponse",Bd=`${Id}.${Ad}`,Vd=`${Id}.${Nd}`,xd=`${Id}.${Ed}`,Dd=`${Id}.${Cd}`,Od=[Bd,Vd,xd,Dd];class Td extends zr{constructor(e={}){super(),this.tbsResponseData=He(e,Ad,Td.defaultValues(Ad)),this.signatureAlgorithm=He(e,Nd,Td.defaultValues(Nd)),this.signature=He(e,Ed,Td.defaultValues(Ed)),Cd in e&&(this.certs=He(e,Cd,Td.defaultValues(Cd))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Ad:return new md;case Nd:return new An;case Ed:return new vs;case Cd:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case"type":{let e=md.compareWithDefault("tbs",t.tbs)&&md.compareWithDefault("responderID",t.responderID)&&md.compareWithDefault("producedAt",t.producedAt)&&md.compareWithDefault("responses",t.responses);return"responseExtensions"in t&&(e=e&&md.compareWithDefault("responseExtensions",t.responseExtensions)),e}case Nd:return t.algorithmId===Fr&&"algorithmParams"in t==!1;case Ed:return t.isEqual(Td.defaultValues(e));case Cd:return 0===t.length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Id,value:[md.schema(t.tbsResponseData||{names:{blockName:Bd}}),An.schema(t.signatureAlgorithm||{names:{blockName:Vd}}),new vs({name:t.signature||xd}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new Os({value:[new or({name:Dd,value:yu.schema(t.certs||{})})]})]})]})}fromSchema(e){st(e,Od);const t=cr(e,e,Td.schema());Gr.assertSchema(t,this.className),this.tbsResponseData=new md({schema:t.result[Bd]}),this.signatureAlgorithm=new An({schema:t.result[Vd]}),this.signature=t.result[xd],Dd in t.result&&(this.certs=Array.from(t.result[Dd],(e=>new yu({schema:e}))))}toSchema(){const e=[];return e.push(this.tbsResponseData.toSchema()),e.push(this.signatureAlgorithm.toSchema()),e.push(this.signature),this.certs&&e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:[new Os({value:Array.from(this.certs,(e=>e.toSchema()))})]})),new Os({value:e})}toJSON(){const e={tbsResponseData:this.tbsResponseData.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signature:this.signature.toJSON()};return this.certs&&(e.certs=Array.from(this.certs,(e=>e.toJSON()))),e}async getCertificateStatus(e,t,s=Xo(!0)){const r={isForCertificate:!1,status:2},n={},a=[];for(const r of this.tbsResponseData.responses){const i=s.getAlgorithmByOID(r.certID.hashAlgorithm.algorithmId,!0,"CertID.hashAlgorithm");if(!n[i.name]){n[i.name]=1;const r=new Ff;a.push(r),await r.createForCertificate(e,{hashAlgorithm:i.name,issuerCertificate:t},s)}}for(const e of this.tbsResponseData.responses)for(const t of a)if(e.certID.isEqual(t)){r.isForCertificate=!0;try{switch(e.certStatus.idBlock.isConstructed){case!0:1===e.certStatus.idBlock.tagNumber&&(r.status=1);break;case!1:switch(e.certStatus.idBlock.tagNumber){case 0:r.status=0;break;case 2:r.status=2}}}catch{}return r}return r}async sign(e,t="SHA-1",s=Xo(!0)){if(!e)throw new Error("Need to provide a private key for signing");const r=await s.getSignatureParameters(e,t),n=r.parameters.algorithm;if(!("name"in n))throw new Error("Empty algorithm");this.signatureAlgorithm=r.signatureAlgorithm,this.tbsResponseData.tbsView=new Uint8Array(this.tbsResponseData.toSchema(!0).toBER());const a=await s.signWithPrivateKey(this.tbsResponseData.tbsView,e,{algorithm:n});this.signature=new vs({valueHex:a})}async verify(e={},t=Xo(!0)){let s=null,r=-1;const n=e.trustedCerts||[];if(!this.certs)throw new Error("No certificates attached to the BasicOCSPResponse");switch(!0){case this.tbsResponseData.responderID instanceof sn:for(const[e,t]of this.certs.entries())if(t.subject.isEqual(this.tbsResponseData.responderID)){r=e;break}break;case this.tbsResponseData.responderID instanceof ws:for(const[e,s]of this.certs.entries()){if(qe(await t.digest({name:"sha-1"},s.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView),this.tbsResponseData.responderID.valueBlock.valueHex)){r=e;break}}break;default:throw new Error("Wrong value for responderID")}if(-1===r)throw new Error("Correct certificate was not found in OCSP response");s=this.certs[r];const a=[s];for(const e of this.certs){const t=await vu(e,s);t&&a.push(t)}const i=new kd({certs:a,trustedCerts:n});if(!(await 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)}}Td.CLASS_NAME="BasicOCSPResponse";const Pd="tbs",Ud="version",Ld="subject",Rd="subjectPublicKeyInfo",_d="attributes",Hd="signatureAlgorithm",Kd="signatureValue",Md="CertificationRequestInfo",jd=`${Md}.version`,Jd=`${Md}.subject`,$d=`${Md}.subjectPublicKeyInfo`,Fd=`${Md}.attributes`,qd=[Md,jd,Jd,$d,Fd,Hd,Kd];function Wd(e={}){const t=He(e,"names",{});return new Os({name:t.CertificationRequestInfo||Md,value:[new Ns({name:t.CertificationRequestInfoVersion||jd}),sn.schema(t.subject||{names:{blockName:Jd}}),Wi.schema({names:{blockName:$d}}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new or({optional:!0,name:t.CertificationRequestInfoAttributes||Fd,value:xn.schema(t.attributes||{})})]})]})}class Gd extends zr{get tbs(){return De.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e)}constructor(e={}){super(),this.tbsView=new Uint8Array(He(e,Pd,Gd.defaultValues(Pd))),this.version=He(e,Ud,Gd.defaultValues(Ud)),this.subject=He(e,Ld,Gd.defaultValues(Ld)),this.subjectPublicKeyInfo=He(e,Rd,Gd.defaultValues(Rd)),_d in e&&(this.attributes=He(e,_d,Gd.defaultValues(_d))),this.signatureAlgorithm=He(e,Hd,Gd.defaultValues(Hd)),this.signatureValue=He(e,Kd,Gd.defaultValues(Kd)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Pd:return $r;case Ud:return 0;case Ld:return new sn;case Rd:return new Wi;case _d:return[];case Hd:return new An;case Kd:return new vs;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({value:[Wd(t.certificationRequestInfo||{}),new Os({name:t.signatureAlgorithm||Hd,value:[new Bs,new ar({optional:!0})]}),new vs({name:t.signatureValue||Kd})]})}fromSchema(e){st(e,qd);const t=cr(e,e,Gd.schema());Gr.assertSchema(t,this.className),this.tbsView=t.result.CertificationRequestInfo.valueBeforeDecodeView,this.version=t.result[jd].valueBlock.valueDec,this.subject=new sn({schema:t.result[Jd]}),this.subjectPublicKeyInfo=new Wi({schema:t.result[$d]}),Fd in t.result&&(this.attributes=Array.from(t.result[Fd],(e=>new xn({schema:e})))),this.signatureAlgorithm=new An({schema:t.result.signatureAlgorithm}),this.signatureValue=t.result.signatureValue}encodeTBS(){const e=[new Ns({value:this.version}),this.subject.toSchema(),this.subjectPublicKeyInfo.toSchema()];return _d in this&&e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.attributes||[],(e=>e.toSchema()))})),new Os({value:e})}toSchema(e=!1){let t;if(!1===e){if(0===this.tbsView.byteLength)return Gd.schema();const e=ls(this.tbsView);Gr.assert(e,"PKCS#10 Certificate Request"),t=e.result}else t=this.encodeTBS();return new Os({value:[t,this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){const e={tbs:_e.ToHex(this.tbsView),version:this.version,subject:this.subject.toJSON(),subjectPublicKeyInfo:this.subjectPublicKeyInfo.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()};return _d in this&&(e.attributes=Array.from(this.attributes||[],(e=>e.toJSON()))),e}async sign(e,t="SHA-1",s=Xo(!0)){if(!e)throw new Error("Need to provide a private key for signing");const r=await s.getSignatureParameters(e,t),n=r.parameters;this.signatureAlgorithm=r.signatureAlgorithm,this.tbsView=new Uint8Array(this.encodeTBS().toBER());const a=await s.signWithPrivateKey(this.tbsView,e,n);this.signatureValue=new vs({valueHex:a})}async verify(e=Xo(!0)){return e.verifyWithPublicKey(this.tbsView,this.signatureValue,this.subjectPublicKeyInfo,this.signatureAlgorithm)}async getPublicKey(e,t=Xo(!0)){return t.getPublicKey(this.subjectPublicKeyInfo,this.signatureAlgorithm,e)}}Gd.CLASS_NAME="CertificationRequest";const zd="digestAlgorithm",Yd="digest",Qd=[zd,Yd];class Zd extends zr{constructor(e={}){super(),this.digestAlgorithm=He(e,zd,Zd.defaultValues(zd)),this.digest=He(e,Yd,Zd.defaultValues(Yd)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case zd:return new An;case Yd:return new ws;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case zd:return An.compareWithDefault("algorithmId",t.algorithmId)&&"algorithmParams"in t==!1;case Yd:return t.isEqual(Zd.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[An.schema(t.digestAlgorithm||{names:{blockName:zd}}),new ws({name:t.digest||Yd})]})}fromSchema(e){st(e,Qd);const t=cr(e,e,Zd.schema({names:{digestAlgorithm:{names:{blockName:zd}},digest:Yd}}));Gr.assertSchema(t,this.className),this.digestAlgorithm=new An({schema:t.result.digestAlgorithm}),this.digest=t.result.digest}toSchema(){return new Os({value:[this.digestAlgorithm.toSchema(),this.digest]})}toJSON(){return{digestAlgorithm:this.digestAlgorithm.toJSON(),digest:this.digest.toJSON()}}}Zd.CLASS_NAME="DigestInfo";const Xd="eContentType",eg="eContent",tg=[Xd,eg];class sg extends zr{constructor(e={}){if(super(),this.eContentType=He(e,Xd,sg.defaultValues(Xd)),eg in e&&(this.eContent=He(e,eg,sg.defaultValues(eg)),1===this.eContent.idBlock.tagClass&&4===this.eContent.idBlock.tagNumber&&!1===this.eContent.idBlock.isConstructed)){const e=new ws({idBlock:{isConstructed:!0},isConstructed:!0});let t=0;const s=this.eContent.valueBlock.valueHexView.slice().buffer;let r=s.byteLength;for(;r>0;){const n=new Uint8Array(s,t,t+65536>s.byteLength?s.byteLength-t:65536),a=new ArrayBuffer(n.length),i=new Uint8Array(a);for(let e=0;e<i.length;e++)i[e]=n[e];e.valueBlock.value.push(new ws({valueHex:a})),r-=n.length,t+=n.length}this.eContent=e}e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Xd:return Fr;case eg:return new ws;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Xd:return t===Fr;case eg:return 1===t.idBlock.tagClass&&4===t.idBlock.tagNumber&&t.isEqual(sg.defaultValues(eg));default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.eContentType||Fr}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new ar({name:t.eContent||Fr})]})]})}fromSchema(e){st(e,tg);const t=cr(e,e,sg.schema({names:{eContentType:Xd,eContent:eg}}));Gr.assertSchema(t,this.className),this.eContentType=t.result.eContentType.valueBlock.toString(),eg in t.result&&(this.eContent=t.result.eContent)}toSchema(){const e=[];return e.push(new Bs({value:this.eContentType})),this.eContent&&!1===sg.compareWithDefault(eg,this.eContent)&&e.push(new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[this.eContent]})),new Os({value:e})}toJSON(){const e={eContentType:this.eContentType};return this.eContent&&!1===sg.compareWithDefault(eg,this.eContent)&&(e.eContent=this.eContent.toJSON()),e}}sg.CLASS_NAME="EncapsulatedContentInfo";const rg="mac",ng="macSalt",ag="iterations",ig=[rg,ng,ag];class og extends zr{constructor(e={}){super(),this.mac=He(e,rg,og.defaultValues(rg)),this.macSalt=He(e,ng,og.defaultValues(ng)),ag in e&&(this.iterations=He(e,ag,og.defaultValues(ag))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case rg:return new Zd;case ng:return new ws;case ag:return 1;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case rg:return Zd.compareWithDefault("digestAlgorithm",t.digestAlgorithm)&&Zd.compareWithDefault("digest",t.digest);case ng:return t.isEqual(og.defaultValues(e));case ag:return t===og.defaultValues(e);default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,optional:t.optional||!0,value:[Zd.schema(t.mac||{names:{blockName:rg}}),new ws({name:t.macSalt||ng}),new Ns({optional:!0,name:t.iterations||ag})]})}fromSchema(e){st(e,ig);const t=cr(e,e,og.schema({names:{mac:{names:{blockName:rg}},macSalt:ng,iterations:ag}}));Gr.assertSchema(t,this.className),this.mac=new Zd({schema:t.result.mac}),this.macSalt=t.result.macSalt,ag in t.result&&(this.iterations=t.result.iterations.valueBlock.valueDec)}toSchema(){const e=[this.mac.toSchema(),this.macSalt];return void 0!==this.iterations&&e.push(new Ns({value:this.iterations})),new Os({value:e})}toJSON(){const e={mac:this.mac.toJSON(),macSalt:this.macSalt.toJSON()};return void 0!==this.iterations&&(e.iterations=this.iterations),e}}og.CLASS_NAME="MacData";const lg="hashAlgorithm",cg="hashedMessage",ug=[lg,cg];class hg extends zr{static async create(e,t,s=Xo(!0)){const r=s.getOIDByAlgorithm({name:e},!0,"hashAlgorithm"),n=await s.digest(e,t);return new hg({hashAlgorithm:new An({algorithmId:r,algorithmParams:new fs}),hashedMessage:new ws({valueHex:n})})}constructor(e={}){super(),this.hashAlgorithm=He(e,lg,hg.defaultValues(lg)),this.hashedMessage=He(e,cg,hg.defaultValues(cg)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case lg:return new An;case cg:return new ws;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case lg:return t.algorithmId===Fr&&"algorithmParams"in t==!1;case cg:return 0===t.isEqual(hg.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[An.schema(t.hashAlgorithm||{}),new ws({name:t.hashedMessage||Fr})]})}fromSchema(e){st(e,ug);const t=cr(e,e,hg.schema({names:{hashAlgorithm:{names:{blockName:lg}},hashedMessage:cg}}));Gr.assertSchema(t,this.className),this.hashAlgorithm=new An({schema:t.result.hashAlgorithm}),this.hashedMessage=t.result.hashedMessage}toSchema(){return new Os({value:[this.hashAlgorithm.toSchema(),this.hashedMessage]})}toJSON(){return{hashAlgorithm:this.hashAlgorithm.toJSON(),hashedMessage:this.hashedMessage.toJSON()}}}hg.CLASS_NAME="MessageImprint";const mg="reqCert",fg="singleRequestExtensions",dg=[mg,fg];class gg extends zr{constructor(e={}){super(),this.reqCert=He(e,mg,gg.defaultValues(mg)),fg in e&&(this.singleRequestExtensions=He(e,fg,gg.defaultValues(fg))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case mg:return new Ff;case fg:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case mg:return t.isEqual(gg.defaultValues(e));case fg:return 0===t.length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[Ff.schema(t.reqCert||{}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[Ol.schema(t.extensions||{names:{blockName:t.singleRequestExtensions||Fr}})]})]})}fromSchema(e){st(e,dg);const t=cr(e,e,gg.schema({names:{reqCert:{names:{blockName:mg}},extensions:{names:{blockName:fg}}}}));Gr.assertSchema(t,this.className),this.reqCert=new Ff({schema:t.result.reqCert}),fg in t.result&&(this.singleRequestExtensions=Array.from(t.result.singleRequestExtensions.valueBlock.value,(e=>new Vl({schema:e}))))}toSchema(){const e=[];return e.push(this.reqCert.toSchema()),this.singleRequestExtensions&&e.push(new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new Os({value:Array.from(this.singleRequestExtensions,(e=>e.toSchema()))})]})),new Os({value:e})}toJSON(){const e={reqCert:this.reqCert.toJSON()};return this.singleRequestExtensions&&(e.singleRequestExtensions=Array.from(this.singleRequestExtensions,(e=>e.toJSON()))),e}}gg.CLASS_NAME="Request";const pg="tbs",wg="version",yg="requestorName",vg="requestList",bg="requestExtensions",Sg="TBSRequest",kg=`${Sg}.${wg}`,Ag=`${Sg}.${yg}`,Ng=`${Sg}.requests`,Eg=`${Sg}.${bg}`,Cg=[Sg,kg,Ag,Ng,Eg];class Ig extends zr{get tbs(){return De.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e)}constructor(e={}){super(),this.tbsView=new Uint8Array(He(e,pg,Ig.defaultValues(pg))),wg in e&&(this.version=He(e,wg,Ig.defaultValues(wg))),yg in e&&(this.requestorName=He(e,yg,Ig.defaultValues(yg))),this.requestList=He(e,vg,Ig.defaultValues(vg)),bg in e&&(this.requestExtensions=He(e,bg,Ig.defaultValues(bg))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case pg:return $r;case wg:return 0;case yg:return new cn;case vg:case bg:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case pg:return 0===t.byteLength;case wg:return t===Ig.defaultValues(e);case yg:return t.type===cn.defaultValues("type")&&0===Object.keys(t.value).length;case vg:case bg:return 0===t.length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Sg,value:[new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new Ns({name:t.TBSRequestVersion||kg})]}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[cn.schema(t.requestorName||{names:{blockName:Ag}})]}),new Os({name:t.requestList||"TBSRequest.requestList",value:[new or({name:t.requests||Ng,value:gg.schema(t.requestNames||{})})]}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:2},value:[Ol.schema(t.extensions||{names:{blockName:t.requestExtensions||Eg}})]})]})}fromSchema(e){st(e,Cg);const t=cr(e,e,Ig.schema());Gr.assertSchema(t,this.className),this.tbsView=t.result.TBSRequest.valueBeforeDecodeView,kg in t.result&&(this.version=t.result[kg].valueBlock.valueDec),Ag in t.result&&(this.requestorName=new cn({schema:t.result[Ag]})),this.requestList=Array.from(t.result[Ng],(e=>new gg({schema:e}))),Eg in t.result&&(this.requestExtensions=Array.from(t.result[Eg].valueBlock.value,(e=>new Vl({schema:e}))))}toSchema(e=!1){let t;if(!1===e){if(0===this.tbsView.byteLength)return Ig.schema();const e=ls(this.tbsView);if(Gr.assert(e,"TBS Request"),!(e.result instanceof Os))throw new Error("ASN.1 result should be SEQUENCE");t=e.result}else{const e=[];void 0!==this.version&&e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:[new Ns({value:this.version})]})),this.requestorName&&e.push(new us({idBlock:{tagClass:3,tagNumber:1},value:[this.requestorName.toSchema()]})),e.push(new Os({value:Array.from(this.requestList,(e=>e.toSchema()))})),this.requestExtensions&&e.push(new us({idBlock:{tagClass:3,tagNumber:2},value:[new Os({value:Array.from(this.requestExtensions,(e=>e.toSchema()))})]})),t=new Os({value:e})}return t}toJSON(){const e={};return null!=this.version&&(e.version=this.version),this.requestorName&&(e.requestorName=this.requestorName.toJSON()),e.requestList=Array.from(this.requestList,(e=>e.toJSON())),this.requestExtensions&&(e.requestExtensions=Array.from(this.requestExtensions,(e=>e.toJSON()))),e}}Ig.CLASS_NAME="TBSRequest";const Bg="signatureAlgorithm",Vg="signature",xg="certs";class Dg extends zr{constructor(e={}){super(),this.signatureAlgorithm=He(e,Bg,Dg.defaultValues(Bg)),this.signature=He(e,Vg,Dg.defaultValues(Vg)),xg in e&&(this.certs=He(e,xg,Dg.defaultValues(xg))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Bg:return new An;case Vg:return new vs;case xg:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Bg:return t.algorithmId===Fr&&"algorithmParams"in t==!1;case Vg:return t.isEqual(Dg.defaultValues(e));case xg:return 0===t.length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[An.schema(t.signatureAlgorithm||{}),new vs({name:t.signature||Fr}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new Os({value:[new or({name:t.certs||Fr,value:yu.schema({})})]})]})]})}fromSchema(e){st(e,[Bg,Vg,xg]);const t=cr(e,e,Dg.schema({names:{signatureAlgorithm:{names:{blockName:Bg}},signature:Vg,certs:xg}}));Gr.assertSchema(t,this.className),this.signatureAlgorithm=new An({schema:t.result.signatureAlgorithm}),this.signature=t.result.signature,xg in t.result&&(this.certs=Array.from(t.result.certs,(e=>new yu({schema:e}))))}toSchema(){const e=[];return e.push(this.signatureAlgorithm.toSchema()),e.push(this.signature),this.certs&&e.push(new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new Os({value:Array.from(this.certs,(e=>e.toSchema()))})]})),new Os({value:e})}toJSON(){const e={signatureAlgorithm:this.signatureAlgorithm.toJSON(),signature:this.signature.toJSON()};return this.certs&&(e.certs=Array.from(this.certs,(e=>e.toJSON()))),e}}Dg.CLASS_NAME="Signature";const Og="tbsRequest",Tg="optionalSignature",Pg=[Og,Tg];class Ug extends zr{constructor(e={}){super(),this.tbsRequest=He(e,Og,Ug.defaultValues(Og)),Tg in e&&(this.optionalSignature=He(e,Tg,Ug.defaultValues(Tg))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Og:return new Ig;case Tg:return new Dg;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Og:return Ig.compareWithDefault("tbs",t.tbs)&&Ig.compareWithDefault("version",t.version)&&Ig.compareWithDefault("requestorName",t.requestorName)&&Ig.compareWithDefault("requestList",t.requestList)&&Ig.compareWithDefault("requestExtensions",t.requestExtensions);case Tg:return Dg.compareWithDefault("signatureAlgorithm",t.signatureAlgorithm)&&Dg.compareWithDefault("signature",t.signature)&&Dg.compareWithDefault("certs",t.certs);default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||"OCSPRequest",value:[Ig.schema(t.tbsRequest||{names:{blockName:Og}}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[Dg.schema(t.optionalSignature||{names:{blockName:Tg}})]})]})}fromSchema(e){st(e,Pg);const t=cr(e,e,Ug.schema());Gr.assertSchema(t,this.className),this.tbsRequest=new Ig({schema:t.result.tbsRequest}),Tg in t.result&&(this.optionalSignature=new Dg({schema:t.result.optionalSignature}))}toSchema(e=!1){const t=[];return t.push(this.tbsRequest.toSchema(e)),this.optionalSignature&&t.push(new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[this.optionalSignature.toSchema()]})),new Os({value:t})}toJSON(){const e={tbsRequest:this.tbsRequest.toJSON()};return this.optionalSignature&&(e.optionalSignature=this.optionalSignature.toJSON()),e}async createForCertificate(e,t,s=Xo(!0)){const r=new Ff;await r.createForCertificate(e,t,s),this.tbsRequest.requestList.push(new gg({reqCert:r}))}async sign(e,t="SHA-1",s=Xo(!0)){if(Wr.assertEmpty(e,"privateKey","OCSPRequest.sign method"),!this.optionalSignature)throw new Error('Need to create "optionalSignature" field before signing');const r=await s.getSignatureParameters(e,t),n=r.parameters;this.optionalSignature.signatureAlgorithm=r.signatureAlgorithm;const a=this.tbsRequest.toSchema(!0).toBER(!1),i=await s.signWithPrivateKey(a,e,n);this.optionalSignature.signature=new vs({valueHex:i})}verify(){}}Ug.CLASS_NAME="OCSPRequest";const Lg="responseType",Rg="response",_g=[Lg,Rg];class Hg extends zr{constructor(e={}){super(),this.responseType=He(e,Lg,Hg.defaultValues(Lg)),this.response=He(e,Rg,Hg.defaultValues(Rg)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Lg:return Fr;case Rg:return new ws;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Lg:return t===Fr;case Rg:return t.isEqual(Hg.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Bs({name:t.responseType||Fr}),new ws({name:t.response||Fr})]})}fromSchema(e){st(e,_g);const t=cr(e,e,Hg.schema({names:{responseType:Lg,response:Rg}}));Gr.assertSchema(t,this.className),this.responseType=t.result.responseType.valueBlock.toString(),this.response=t.result.response}toSchema(){return new Os({value:[new Bs({value:this.responseType}),this.response]})}toJSON(){return{responseType:this.responseType,response:this.response.toJSON()}}}Hg.CLASS_NAME="ResponseBytes";const Kg="responseStatus",Mg="responseBytes";class jg extends zr{constructor(e={}){super(),this.responseStatus=He(e,Kg,jg.defaultValues(Kg)),Mg in e&&(this.responseBytes=He(e,Mg,jg.defaultValues(Mg))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Kg:return new Es;case Mg:return new Hg;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Kg:return t.isEqual(jg.defaultValues(e));case Mg:return Hg.compareWithDefault("responseType",t.responseType)&&Hg.compareWithDefault("response",t.response);default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||"OCSPResponse",value:[new Es({name:t.responseStatus||Kg}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[Hg.schema(t.responseBytes||{names:{blockName:Mg}})]})]})}fromSchema(e){st(e,[Kg,Mg]);const t=cr(e,e,jg.schema());Gr.assertSchema(t,this.className),this.responseStatus=t.result.responseStatus,Mg in t.result&&(this.responseBytes=new Hg({schema:t.result.responseBytes}))}toSchema(){const e=[];return e.push(this.responseStatus),this.responseBytes&&e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:[this.responseBytes.toSchema()]})),new Os({value:e})}toJSON(){const e={responseStatus:this.responseStatus.toJSON()};return this.responseBytes&&(e.responseBytes=this.responseBytes.toJSON()),e}async getCertificateStatus(e,t,s=Xo(!0)){let r;const n={isForCertificate:!1,status:2};if(!this.responseBytes)return n;if(this.responseBytes.responseType!==aa)return n;try{const e=ls(this.responseBytes.response.valueBlock.valueHexView);Gr.assert(e,"Basic OCSP response"),r=new Td({schema:e.result})}catch{return n}return r.getCertificateStatus(e,t,s)}async sign(e,t,s=Xo(!0)){var r;if(this.responseBytes&&this.responseBytes.responseType===aa){return Td.fromBER(this.responseBytes.response.valueBlock.valueHexView).sign(e,t,s)}throw new Error(`Unknown ResponseBytes type: ${(null===(r=this.responseBytes)||void 0===r?void 0:r.responseType)||"Unknown"}`)}async verify(e=null,t=Xo(!0)){var s;if(Mg in this==!1)throw new Error("Empty ResponseBytes field");if(this.responseBytes&&this.responseBytes.responseType===aa){const s=Td.fromBER(this.responseBytes.response.valueBlock.valueHexView);return null!==e&&(s.certs||(s.certs=[]),s.certs.push(e)),s.verify({},t)}throw new Error(`Unknown ResponseBytes type: ${(null===(s=this.responseBytes)||void 0===s?void 0:s.responseType)||"Unknown"}`)}}jg.CLASS_NAME="OCSPResponse";const Jg="type",$g="attributes",Fg="encodedValue",qg=[$g];class Wg extends zr{constructor(e={}){super(),this.type=He(e,Jg,Wg.defaultValues(Jg)),this.attributes=He(e,$g,Wg.defaultValues($g)),this.encodedValue=He(e,Fg,Wg.defaultValues(Fg)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Jg:return-1;case $g:return[];case Fg:return $r;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Jg:return t===Wg.defaultValues(Jg);case $g:return 0===t.length;case Fg:return 0===t.byteLength;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new us({name:t.blockName||Fr,optional:!0,idBlock:{tagClass:3,tagNumber:t.tagNumber||0},value:[new or({name:t.attributes||Fr,value:xn.schema()})]})}fromSchema(e){st(e,qg);const t=cr(e,e,Wg.schema({names:{tagNumber:this.type,attributes:$g}}));Gr.assertSchema(t,this.className),this.type=t.result.idBlock.tagNumber,this.encodedValue=De.toArrayBuffer(t.result.valueBeforeDecodeView);if(new Uint8Array(this.encodedValue)[0]=49,$g in t.result!=!1)this.attributes=Array.from(t.result.attributes,(e=>new xn({schema:e})));else if(0===this.type)throw new Error("Wrong structure of SignedUnsignedAttributes")}toSchema(){if(Wg.compareWithDefault(Jg,this.type)||Wg.compareWithDefault($g,this.attributes))throw new Error('Incorrectly initialized "SignedAndUnsignedAttributes" class');return new us({optional:!0,idBlock:{tagClass:3,tagNumber:this.type},value:Array.from(this.attributes,(e=>e.toSchema()))})}toJSON(){if(Wg.compareWithDefault(Jg,this.type)||Wg.compareWithDefault($g,this.attributes))throw new Error('Incorrectly initialized "SignedAndUnsignedAttributes" class');return{type:this.type,attributes:Array.from(this.attributes,(e=>e.toJSON()))}}}Wg.CLASS_NAME="SignedAndUnsignedAttributes";const Gg="version",zg="sid",Yg="digestAlgorithm",Qg="signedAttrs",Zg="signatureAlgorithm",Xg="signature",ep="unsignedAttrs",tp="SignerInfo",sp=`${tp}.${Gg}`,rp=`${tp}.${zg}`,np=`${tp}.${Yg}`,ap=`${tp}.${Qg}`,ip=`${tp}.${Zg}`,op=`${tp}.${Xg}`,lp=`${tp}.${ep}`,cp=[sp,rp,np,ap,ip,op,lp];class up extends zr{constructor(e={}){super(),this.version=He(e,Gg,up.defaultValues(Gg)),this.sid=He(e,zg,up.defaultValues(zg)),this.digestAlgorithm=He(e,Yg,up.defaultValues(Yg)),Qg in e&&(this.signedAttrs=He(e,Qg,up.defaultValues(Qg))),this.signatureAlgorithm=He(e,Zg,up.defaultValues(Zg)),this.signature=He(e,Xg,up.defaultValues(Xg)),ep in e&&(this.unsignedAttrs=He(e,ep,up.defaultValues(ep))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Gg:return 0;case zg:return new ar;case Yg:return new An;case Qg:return new Wg({type:0});case Zg:return new An;case Xg:return new ws;case ep:return new Wg({type:1});default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Gg:return up.defaultValues(Gg)===t;case zg:return t instanceof ar;case Yg:return t instanceof An!=!1&&t.isEqual(up.defaultValues(Yg));case Qg:return Wg.compareWithDefault("type",t.type)&&Wg.compareWithDefault("attributes",t.attributes)&&Wg.compareWithDefault("encodedValue",t.encodedValue);case Zg:return t instanceof An!=!1&&t.isEqual(up.defaultValues(Zg));case Xg:case ep:return Wg.compareWithDefault("type",t.type)&&Wg.compareWithDefault("attributes",t.attributes)&&Wg.compareWithDefault("encodedValue",t.encodedValue);default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:tp,value:[new Ns({name:t.version||sp}),new ir({value:[Wh.schema(t.sidSchema||{names:{blockName:rp}}),new ir({value:[new us({optional:!0,name:t.sid||rp,idBlock:{tagClass:3,tagNumber:0},value:[new ws]}),new is({optional:!0,name:t.sid||rp,idBlock:{tagClass:3,tagNumber:0}})]})]}),An.schema(t.digestAlgorithm||{names:{blockName:np}}),Wg.schema(t.signedAttrs||{names:{blockName:ap,tagNumber:0}}),An.schema(t.signatureAlgorithm||{names:{blockName:ip}}),new ws({name:t.signature||op}),Wg.schema(t.unsignedAttrs||{names:{blockName:lp,tagNumber:1}})]})}fromSchema(e){st(e,cp);const t=cr(e,e,up.schema());Gr.assertSchema(t,this.className),this.version=t.result[sp].valueBlock.valueDec;const s=t.result[rp];1===s.idBlock.tagClass?this.sid=new Wh({schema:s}):this.sid=s,this.digestAlgorithm=new An({schema:t.result[np]}),ap in t.result&&(this.signedAttrs=new Wg({type:0,schema:t.result[ap]})),this.signatureAlgorithm=new An({schema:t.result[ip]}),this.signature=t.result[op],lp in t.result&&(this.unsignedAttrs=new Wg({type:1,schema:t.result[lp]}))}toSchema(){if(up.compareWithDefault(zg,this.sid))throw new Error('Incorrectly initialized "SignerInfo" class');const e=[];return e.push(new Ns({value:this.version})),this.sid instanceof Wh?e.push(this.sid.toSchema()):e.push(this.sid),e.push(this.digestAlgorithm.toSchema()),this.signedAttrs&&!1===up.compareWithDefault(Qg,this.signedAttrs)&&e.push(this.signedAttrs.toSchema()),e.push(this.signatureAlgorithm.toSchema()),e.push(this.signature),this.unsignedAttrs&&!1===up.compareWithDefault(ep,this.unsignedAttrs)&&e.push(this.unsignedAttrs.toSchema()),new Os({value:e})}toJSON(){if(up.compareWithDefault(zg,this.sid))throw new Error('Incorrectly initialized "SignerInfo" class');const e={version:this.version,digestAlgorithm:this.digestAlgorithm.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signature:this.signature.toJSON()};return this.sid instanceof ar||(e.sid=this.sid.toJSON()),this.signedAttrs&&!1===up.compareWithDefault(Qg,this.signedAttrs)&&(e.signedAttrs=this.signedAttrs.toJSON()),this.unsignedAttrs&&!1===up.compareWithDefault(ep,this.unsignedAttrs)&&(e.unsignedAttrs=this.unsignedAttrs.toJSON()),e}}up.CLASS_NAME="SignerInfo";const hp="version",mp="policy",fp="messageImprint",dp="serialNumber",gp="genTime",pp="ordering",wp="nonce",yp="accuracy",vp="tsa",bp="extensions",Sp="TSTInfo",kp=`${Sp}.${hp}`,Ap=`${Sp}.${mp}`,Np=`${Sp}.${fp}`,Ep=`${Sp}.${dp}`,Cp=`${Sp}.${gp}`,Ip=`${Sp}.${yp}`,Bp=`${Sp}.${pp}`,Vp=`${Sp}.${wp}`,xp=`${Sp}.${vp}`,Dp=`${Sp}.${bp}`,Op=[kp,Ap,Np,Ep,Cp,Ip,Bp,Vp,xp,Dp];class Tp extends zr{constructor(e={}){super(),this.version=He(e,hp,Tp.defaultValues(hp)),this.policy=He(e,mp,Tp.defaultValues(mp)),this.messageImprint=He(e,fp,Tp.defaultValues(fp)),this.serialNumber=He(e,dp,Tp.defaultValues(dp)),this.genTime=He(e,gp,Tp.defaultValues(gp)),yp in e&&(this.accuracy=He(e,yp,Tp.defaultValues(yp))),pp in e&&(this.ordering=He(e,pp,Tp.defaultValues(pp))),wp in e&&(this.nonce=He(e,wp,Tp.defaultValues(wp))),vp in e&&(this.tsa=He(e,vp,Tp.defaultValues(vp))),bp in e&&(this.extensions=He(e,bp,Tp.defaultValues(bp))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case hp:return 0;case mp:return Fr;case fp:return new hg;case dp:return new Ns;case gp:return new Date(0,0,0);case yp:return new wn;case pp:return!1;case wp:return new Ns;case vp:return new cn;case bp:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case hp:case mp:case gp:case pp:return t===Tp.defaultValues(pp);case fp:return hg.compareWithDefault(lg,t.hashAlgorithm)&&hg.compareWithDefault(cg,t.hashedMessage);case dp:case wp:return t.isEqual(Tp.defaultValues(wp));case yp:return wn.compareWithDefault(dn,t.seconds)&&wn.compareWithDefault(gn,t.millis)&&wn.compareWithDefault(pn,t.micros);case vp:return cn.compareWithDefault(rn,t.type)&&cn.compareWithDefault(nn,t.value);case bp:return 0===t.length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Sp,value:[new Ns({name:t.version||kp}),new Bs({name:t.policy||Ap}),hg.schema(t.messageImprint||{names:{blockName:Np}}),new Ns({name:t.serialNumber||Ep}),new Xs({name:t.genTime||Cp}),wn.schema(t.accuracy||{names:{blockName:Ip}}),new gs({name:t.ordering||Bp,optional:!0}),new Ns({name:t.nonce||Vp,optional:!0}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[cn.schema(t.tsa||{names:{blockName:xp}})]}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new or({name:t.extensions||Dp,value:Vl.schema(t.extension||{})})]})]})}fromSchema(e){st(e,Op);const t=cr(e,e,Tp.schema());Gr.assertSchema(t,this.className),this.version=t.result[kp].valueBlock.valueDec,this.policy=t.result[Ap].valueBlock.toString(),this.messageImprint=new hg({schema:t.result[Np]}),this.serialNumber=t.result[Ep],this.genTime=t.result[Cp].toDate(),Ip in t.result&&(this.accuracy=new wn({schema:t.result[Ip]})),Bp in t.result&&(this.ordering=t.result[Bp].valueBlock.value),Vp in t.result&&(this.nonce=t.result[Vp]),xp in t.result&&(this.tsa=new cn({schema:t.result[xp]})),Dp in t.result&&(this.extensions=Array.from(t.result[Dp],(e=>new Vl({schema:e}))))}toSchema(){const e=[];return e.push(new Ns({value:this.version})),e.push(new Bs({value:this.policy})),e.push(this.messageImprint.toSchema()),e.push(this.serialNumber),e.push(new Xs({valueDate:this.genTime})),this.accuracy&&e.push(this.accuracy.toSchema()),void 0!==this.ordering&&e.push(new gs({value:this.ordering})),this.nonce&&e.push(this.nonce),this.tsa&&e.push(new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[this.tsa.toSchema()]})),this.extensions&&e.push(new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.extensions,(e=>e.toSchema()))})),new Os({value:e})}toJSON(){const 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()),void 0!==this.ordering&&(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,(e=>e.toJSON()))),e}async verify(e,t=Xo(!0)){if(!e.data)throw new Error('"data" is a mandatory attribute for TST_INFO verification');const s=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");const r=t.getAlgorithmByOID(this.messageImprint.hashAlgorithm.algorithmId,!0,"MessageImprint.hashAlgorithm"),n=await t.digest(r.name,new Uint8Array(s));return De.isEqual(n,this.messageImprint.hashedMessage.valueBlock.valueHexView)}}Tp.CLASS_NAME="TSTInfo";const Pp="version",Up="digestAlgorithms",Lp="encapContentInfo",Rp="certificates",_p="crls",Hp="signerInfos",Kp="ocsps",Mp="SignedData",jp=`${Mp}.${Pp}`,Jp=`${Mp}.${Up}`,$p=`${Mp}.${Lp}`,Fp=`${Mp}.${Rp}`,qp=`${Mp}.${_p}`,Wp=`${Mp}.${Hp}`,Gp=[jp,Jp,$p,Fp,qp,Wp];class zp extends Error{constructor({message:e,code:t=0,date:s=new Date,signatureVerified:r=null,signerCertificate:n=null,signerCertificateVerified:a=null,timestampSerial:i=null,certificatePath:o=[]}){super(e),this.name="SignedDataVerifyError",this.date=s,this.code=t,this.timestampSerial=i,this.signatureVerified=r,this.signerCertificate=n,this.signerCertificateVerified=a,this.certificatePath=o}}class Yp extends zr{constructor(e={}){super(),this.version=He(e,Pp,Yp.defaultValues(Pp)),this.digestAlgorithms=He(e,Up,Yp.defaultValues(Up)),this.encapContentInfo=He(e,Lp,Yp.defaultValues(Lp)),Rp in e&&(this.certificates=He(e,Rp,Yp.defaultValues(Rp))),_p in e&&(this.crls=He(e,_p,Yp.defaultValues(_p))),Kp in e&&(this.ocsps=He(e,Kp,Yp.defaultValues(Kp))),this.signerInfos=He(e,Hp,Yp.defaultValues(Hp)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Pp:return 0;case Up:return[];case Lp:return new sg;case Rp:case _p:case Kp:case Hp:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Pp:return t===Yp.defaultValues(Pp);case Lp:return sg.compareWithDefault("eContentType",t.eContentType)&&sg.compareWithDefault("eContent",t.eContent);case Up:case Rp:case _p:case Kp:case Hp:return 0===t.length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return void 0===t.optional&&(t.optional=!1),new Os({name:t.blockName||Mp,optional:t.optional,value:[new Ns({name:t.version||jp}),new Ts({value:[new or({name:t.digestAlgorithms||Jp,value:An.schema()})]}),sg.schema(t.encapContentInfo||{names:{blockName:$p}}),new us({name:t.certificates||Fp,optional:!0,idBlock:{tagClass:3,tagNumber:0},value:Dh.schema().valueBlock.value}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Hh.schema(t.crls||{names:{crls:qp}}).valueBlock.value}),new Ts({value:[new or({name:t.signerInfos||Wp,value:up.schema()})]})]})}fromSchema(e){st(e,Gp);const t=cr(e,e,Yp.schema());if(Gr.assertSchema(t,this.className),this.version=t.result[jp].valueBlock.valueDec,Jp in t.result&&(this.digestAlgorithms=Array.from(t.result[Jp],(e=>new An({schema:e})))),this.encapContentInfo=new sg({schema:t.result[$p]}),Fp in t.result){const e=new Dh({schema:new Ts({value:t.result[Fp].valueBlock.value})});this.certificates=e.certificates.slice(0)}qp in t.result&&(this.crls=Array.from(t.result[qp],(e=>1===e.idBlock.tagClass?new Qu({schema:e}):(e.idBlock.tagClass=1,e.idBlock.tagNumber=16,new Uh({schema:e}))))),Wp in t.result&&(this.signerInfos=Array.from(t.result[Wp],(e=>new up({schema:e}))))}toSchema(e=!1){const t=[];if(this.certificates&&this.certificates.length&&this.certificates.some((e=>e instanceof Bh))||this.crls&&this.crls.length&&this.crls.some((e=>e instanceof Uh))?this.version=5:this.certificates&&this.certificates.length&&this.certificates.some((e=>e instanceof Oc))?this.version=4:this.certificates&&this.certificates.length&&this.certificates.some((e=>e instanceof ec))||this.signerInfos.some((e=>3===e.version))||this.encapContentInfo.eContentType!==Yp.ID_DATA?this.version=3:this.version=1,t.push(new Ns({value:this.version})),t.push(new Ts({value:Array.from(this.digestAlgorithms,(e=>e.toSchema()))})),t.push(this.encapContentInfo.toSchema()),this.certificates){const e=new Dh({certificates:this.certificates}).toSchema();t.push(new us({idBlock:{tagClass:3,tagNumber:0},value:e.valueBlock.value}))}return this.crls&&t.push(new us({idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.crls,(t=>{if(t instanceof Uh){const e=t.toSchema();return e.idBlock.tagClass=3,e.idBlock.tagNumber=1,e}return t.toSchema(e)}))})),t.push(new Ts({value:Array.from(this.signerInfos,(e=>e.toSchema()))})),new Os({value:t})}toJSON(){const e={version:this.version,digestAlgorithms:Array.from(this.digestAlgorithms,(e=>e.toJSON())),encapContentInfo:this.encapContentInfo.toJSON(),signerInfos:Array.from(this.signerInfos,(e=>e.toJSON()))};return this.certificates&&(e.certificates=Array.from(this.certificates,(e=>e.toJSON()))),this.crls&&(e.crls=Array.from(this.crls,(e=>e.toJSON()))),e}async verify({signer:e=-1,data:t=$r,trustedCerts:s=[],checkDate:r=new Date,checkChain:n=!1,passedWhenNotRevValues:a=!1,extendedMode:i=!1,findOrigin:o=null,findIssuer:l=null}={},c=Xo(!0)){let u=null,h=null;try{let m=$r,f=Fr,d=[];const g=this.signerInfos[e];if(!g)throw new zp({date:r,code:1,message:"Unable to get signer by supplied index"});if(!this.certificates)throw new zp({date:r,code:2,message:"No certificates attached to this signed data"});if(g.sid instanceof Wh){for(const e of this.certificates)if(e instanceof yu&&e.issuer.isEqual(g.sid.issuer)&&e.serialNumber.isEqual(g.sid.serialNumber)){u=e;break}}else{const e=g.sid,t=e.idBlock.isConstructed?e.valueBlock.value[0].valueBlock.valueHex:e.valueBlock.valueHex;for(const e of this.certificates){if(!(e instanceof yu))continue;if(qe(await c.digest({name:"sha-1"},e.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView),t)){u=e;break}}}if(!u)throw new zp({date:r,code:3,message:"Unable to find signer certificate"});if("1.2.840.113549.1.9.16.1.4"===this.encapContentInfo.eContentType){if(!this.encapContentInfo.eContent)throw new zp({date:r,code:15,message:"Error during verification: TSTInfo eContent is empty",signatureVerified:null,signerCertificate:u,timestampSerial:h,signerCertificateVerified:!0});let e;try{e=Tp.fromBER(this.encapContentInfo.eContent.valueBlock.valueHexView)}catch{throw new zp({date:r,code:15,message:"Error during verification: TSTInfo wrong ASN.1 schema ",signatureVerified:null,signerCertificate:u,timestampSerial:h,signerCertificateVerified:!0})}if(r=e.genTime,h=e.serialNumber.valueBlock.valueHexView.slice().buffer,0===t.byteLength)throw new zp({date:r,code:4,message:"Missed detached data input array"});if(!await e.verify({data:t},c))throw new zp({date:r,code:15,message:"Error during verification: TSTInfo verification is failed",signatureVerified:!1,signerCertificate:u,timestampSerial:h,signerCertificateVerified:!0})}if(n){const e=this.certificates.filter((e=>e instanceof yu&&!!vu(e,u))),t={checkDate:r,certs:e,trustedCerts:s};l&&(t.findIssuer=l),o&&(t.findOrigin=o);const n=new kd(t);if(n.certs.push(u),this.crls)for(const e of this.crls)"thisUpdate"in e?n.crls.push(e):e.otherRevInfoFormat===aa&&n.ocsps.push(new Td({schema:e.otherRevInfo}));this.ocsps&&n.ocsps.push(...this.ocsps);const i=await n.verify({passedWhenNotRevValues:a},c).catch((e=>{throw new zp({date:r,code:5,message:`Validation of signer's certificate failed with error: ${e instanceof Object?e.resultMessage:e}`,signerCertificate:u,signerCertificateVerified:!1})}));if(i.certificatePath&&(d=i.certificatePath),!i.result)throw new zp({date:r,code:5,message:`Validation of signer's certificate failed: ${i.resultMessage}`,signerCertificate:u,signerCertificateVerified:!1})}const p=c.getAlgorithmByOID(g.digestAlgorithm.algorithmId);if(!("name"in p))throw new zp({date:r,code:7,message:`Unsupported signature algorithm: ${g.digestAlgorithm.algorithmId}`,signerCertificate:u,signerCertificateVerified:!0});f=p.name;const w=this.encapContentInfo.eContent;if(w)t=1===w.idBlock.tagClass&&4===w.idBlock.tagNumber?w.getValue():w.valueBlock.valueBeforeDecodeView.slice().buffer;else if(0===t.byteLength)throw new zp({date:r,code:8,message:"Missed detached data input array",signerCertificate:u,signerCertificateVerified:!0});if(g.signedAttrs){let e=!1,t=!1;for(const s of g.signedAttrs.attributes)if("1.2.840.113549.1.9.3"===s.type&&(e=!0),"1.2.840.113549.1.9.4"===s.type&&(t=!0,m=s.values[0].valueBlock.valueHex),e&&t)break;if(!1===e)throw new zp({date:r,code:9,message:'Attribute "content-type" is a mandatory attribute for "signed attributes"',signerCertificate:u,signerCertificateVerified:!0});if(!1===t)throw new zp({date:r,code:10,message:'Attribute "message-digest" is a mandatory attribute for "signed attributes"',signatureVerified:null,signerCertificate:u,signerCertificateVerified:!0})}if(g.signedAttrs){if(!qe(await c.digest(f,new Uint8Array(t)),m))throw new zp({date:r,code:15,message:"Error during verification: Message digest doesn't match",signatureVerified:null,signerCertificate:u,timestampSerial:h,signerCertificateVerified:!0});t=g.signedAttrs.encodedValue}const y="1.2.840.113549.1.1.1"===g.signatureAlgorithm.algorithmId?await c.verifyWithPublicKey(t,g.signature,u.subjectPublicKeyInfo,g.signatureAlgorithm,f):await c.verifyWithPublicKey(t,g.signature,u.subjectPublicKeyInfo,g.signatureAlgorithm);return i?{date:r,code:14,message:Fr,signatureVerified:y,signerCertificate:u,timestampSerial:h,signerCertificateVerified:!0,certificatePath:d}:y}catch(e){if(e instanceof zp)throw e;throw new zp({date:r,code:15,message:`Error during verification: ${e instanceof Error?e.message:e}`,signatureVerified:null,signerCertificate:u,timestampSerial:h,signerCertificateVerified:!0})}}async sign(e,t,s="SHA-1",r=$r,n=Xo(!0)){var a;if(!e)throw new Error("Need to provide a private key for signing");const i=this.signerInfos[t];if(!i)throw new RangeError("SignerInfo index is out of range");!(null===(a=i.signedAttrs)||void 0===a?void 0:a.attributes.length)&&"hash"in e.algorithm&&"hash"in e.algorithm&&e.algorithm.hash&&(s=e.algorithm.hash.name);const o=n.getOIDByAlgorithm({name:s},!0,"hashAlgorithm");0===this.digestAlgorithms.filter((e=>e.algorithmId===o)).length&&this.digestAlgorithms.push(new An({algorithmId:o,algorithmParams:new fs})),i.digestAlgorithm=new An({algorithmId:o,algorithmParams:new fs});const l=await n.getSignatureParameters(e,s),c=l.parameters;if(i.signatureAlgorithm=l.signatureAlgorithm,i.signedAttrs)if(0!==i.signedAttrs.encodedValue.byteLength)r=i.signedAttrs.encodedValue;else{r=i.signedAttrs.toSchema().toBER();De.toUint8Array(r)[0]=49}else{const e=this.encapContentInfo.eContent;if(e)r=1===e.idBlock.tagClass&&4===e.idBlock.tagNumber?e.getValue():e.valueBlock.valueBeforeDecodeView.slice().buffer;else if(0===r.byteLength)throw new Error("Missed detached data input array")}const u=await n.signWithPrivateKey(r,e,c);i.signature=new ws({valueHex:u})}}Yp.CLASS_NAME="SignedData",Yp.ID_DATA=Zn;const Qp="version",Zp="authSafe",Xp="macData",ew="parsedValue",tw=[Qp,Zp,Xp];class sw extends zr{constructor(e={}){super(),this.version=He(e,Qp,sw.defaultValues(Qp)),this.authSafe=He(e,Zp,sw.defaultValues(Zp)),Xp in e&&(this.macData=He(e,Xp,sw.defaultValues(Xp))),ew in e&&(this.parsedValue=He(e,ew,sw.defaultValues(ew))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Qp:return 3;case Zp:return new Lc;case Xp:return new og;case ew:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Qp:return t===sw.defaultValues(e);case Zp:return Lc.compareWithDefault("contentType",t.contentType)&&Lc.compareWithDefault("content",t.content);case Xp:return og.compareWithDefault("mac",t.mac)&&og.compareWithDefault("macSalt",t.macSalt)&&og.compareWithDefault("iterations",t.iterations);case ew:return t instanceof Object&&0===Object.keys(t).length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Ns({name:t.version||Qp}),Lc.schema(t.authSafe||{names:{blockName:Zp}}),og.schema(t.macData||{names:{blockName:Xp,optional:!0}})]})}fromSchema(e){st(e,tw);const t=cr(e,e,sw.schema({names:{version:Qp,authSafe:{names:{blockName:Zp}},macData:{names:{blockName:Xp}}}}));Gr.assertSchema(t,this.className),this.version=t.result.version.valueBlock.valueDec,this.authSafe=new Lc({schema:t.result.authSafe}),Xp in t.result&&(this.macData=new og({schema:t.result.macData}))}toSchema(){const e=[new Ns({value:this.version}),this.authSafe.toSchema()];return this.macData&&e.push(this.macData.toSchema()),new Os({value:e})}toJSON(){const e={version:this.version,authSafe:this.authSafe.toJSON()};return this.macData&&(e.macData=this.macData.toJSON()),e}async makeInternalValues(e={},t=Xo(!0)){if(qr.assert(e,"parameters","object"),!this.parsedValue)throw new Error('Please call "parseValues" function first in order to make "parsedValue" data');switch(Wr.assertEmpty(this.parsedValue.integrityMode,"integrityMode","parsedValue"),Wr.assertEmpty(this.parsedValue.authenticatedSafe,"authenticatedSafe","parsedValue"),this.parsedValue.integrityMode){case 0:{if(!("iterations"in e))throw new Wr("iterations");Wr.assertEmpty(e.pbkdf2HashAlgorithm,"pbkdf2HashAlgorithm"),Wr.assertEmpty(e.hmacHashAlgorithm,"hmacHashAlgorithm"),Wr.assertEmpty(e.password,"password");const s=new ArrayBuffer(64),r=new Uint8Array(s);t.getRandomValues(r);const n=this.parsedValue.authenticatedSafe.toSchema().toBER(!1);this.authSafe=new Lc({contentType:Lc.DATA,content:new ws({valueHex:n})});const a=await t.stampDataWithPassword({password:e.password,hashAlgorithm:e.hmacHashAlgorithm,salt:s,iterationCount:e.iterations,contentToStamp:n});this.macData=new og({mac:new Zd({digestAlgorithm:new An({algorithmId:t.getOIDByAlgorithm({name:e.hmacHashAlgorithm},!0,"hmacHashAlgorithm")}),digest:new ws({valueHex:a})}),macSalt:new ws({valueHex:s}),iterations:e.iterations})}break;case 1:{if(!("signingCertificate"in e))throw new Wr("signingCertificate");Wr.assertEmpty(e.privateKey,"privateKey"),Wr.assertEmpty(e.hashAlgorithm,"hashAlgorithm");const s=this.parsedValue.authenticatedSafe.toSchema().toBER(!1),r=new Yp({version:1,encapContentInfo:new sg({eContentType:"1.2.840.113549.1.7.1",eContent:new ws({valueHex:s})}),certificates:[e.signingCertificate]}),n=await t.digest({name:e.hashAlgorithm},new Uint8Array(s)),a=[];a.push(new xn({type:"1.2.840.113549.1.9.3",values:[new Bs({value:"1.2.840.113549.1.7.1"})]})),a.push(new xn({type:"1.2.840.113549.1.9.5",values:[new Zs({valueDate:new Date})]})),a.push(new xn({type:"1.2.840.113549.1.9.4",values:[new ws({valueHex:n})]})),r.signerInfos.push(new up({version:1,sid:new Wh({issuer:e.signingCertificate.issuer,serialNumber:e.signingCertificate.serialNumber}),signedAttrs:new Wg({type:0,attributes:a})})),await r.sign(e.privateKey,0,e.hashAlgorithm,void 0,t),this.authSafe=new Lc({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=Xo(!0)){switch(qr.assert(e,"parameters","object"),void 0===e.checkIntegrity&&(e.checkIntegrity=!0),this.parsedValue={},this.authSafe.contentType){case Lc.DATA:{Wr.assertEmpty(e.password,"password"),this.parsedValue.integrityMode=0,qr.assert(this.authSafe.content,"authSafe.content",ws);const s=this.authSafe.content.getValue();if(this.parsedValue.authenticatedSafe=Hf.fromBER(s),e.checkIntegrity){if(!this.macData)throw new Error('Absent "macData" value, can not check PKCS#12 data integrity');const r=t.getAlgorithmByOID(this.macData.mac.digestAlgorithm.algorithmId,!0,"digestAlgorithm");if(!await t.verifyDataStampedWithPassword({password:e.password,hashAlgorithm:r.name,salt:De.toArrayBuffer(this.macData.macSalt.valueBlock.valueHexView),iterationCount:this.macData.iterations||1,contentToVerify:s,signatureToVerify:De.toArrayBuffer(this.macData.mac.digest.valueBlock.valueHexView)}))throw new Error("Integrity for the PKCS#12 data is broken!")}}break;case Lc.SIGNED_DATA:{this.parsedValue.integrityMode=1;const e=new Yp({schema:this.authSafe.content}),s=e.encapContentInfo.eContent;Wr.assert(s,"eContent","cmsSigned.encapContentInfo"),qr.assert(s,"eContent",ws);const r=s.getValue();this.parsedValue.authenticatedSafe=Hf.fromBER(r);if(!await e.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}`)}}}sw.CLASS_NAME="PFX";const rw="status",nw="statusStrings",aw="failInfo",iw=[rw,nw,aw];var ow;!function(e){e[e.granted=0]="granted",e[e.grantedWithMods=1]="grantedWithMods",e[e.rejection=2]="rejection",e[e.waiting=3]="waiting",e[e.revocationWarning=4]="revocationWarning",e[e.revocationNotification=5]="revocationNotification"}(ow||(ow={}));class lw extends zr{constructor(e={}){super(),this.status=He(e,rw,lw.defaultValues(rw)),nw in e&&(this.statusStrings=He(e,nw,lw.defaultValues(nw))),aw in e&&(this.failInfo=He(e,aw,lw.defaultValues(aw))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case rw:return 2;case nw:return[];case aw:return new vs;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case rw:return t===lw.defaultValues(e);case nw:return 0===t.length;case aw:return t.isEqual(lw.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Fr,value:[new Ns({name:t.status||Fr}),new Os({optional:!0,value:[new or({name:t.statusStrings||Fr,value:new _s})]}),new vs({name:t.failInfo||Fr,optional:!0})]})}fromSchema(e){st(e,iw);const t=cr(e,e,lw.schema({names:{status:rw,statusStrings:nw,failInfo:aw}}));Gr.assertSchema(t,this.className);const s=t.result.status;if(!0===s.valueBlock.isHexOnly||s.valueBlock.valueDec<0||s.valueBlock.valueDec>5)throw new Error('PKIStatusInfo "status" has invalid value');this.status=s.valueBlock.valueDec,nw in t.result&&(this.statusStrings=t.result.statusStrings),aw in t.result&&(this.failInfo=t.result.failInfo)}toSchema(){const e=[];return e.push(new Ns({value:this.status})),this.statusStrings&&e.push(new Os({optional:!0,value:this.statusStrings})),this.failInfo&&e.push(this.failInfo),new Os({value:e})}toJSON(){const e={status:this.status};return this.statusStrings&&(e.statusStrings=Array.from(this.statusStrings,(e=>e.toJSON()))),this.failInfo&&(e.failInfo=this.failInfo.toJSON()),e}}lw.CLASS_NAME="PKIStatusInfo";const cw="version",uw="messageImprint",hw="reqPolicy",mw="nonce",fw="certReq",dw="extensions",gw="TimeStampReq",pw=`${gw}.${cw}`,ww=`${gw}.${uw}`,yw=`${gw}.${hw}`,vw=`${gw}.${mw}`,bw=`${gw}.${fw}`,Sw=`${gw}.${dw}`,kw=[pw,ww,yw,vw,bw,Sw];class Aw extends zr{constructor(e={}){super(),this.version=He(e,cw,Aw.defaultValues(cw)),this.messageImprint=He(e,uw,Aw.defaultValues(uw)),hw in e&&(this.reqPolicy=He(e,hw,Aw.defaultValues(hw))),mw in e&&(this.nonce=He(e,mw,Aw.defaultValues(mw))),fw in e&&(this.certReq=He(e,fw,Aw.defaultValues(fw))),dw in e&&(this.extensions=He(e,dw,Aw.defaultValues(dw))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case cw:return 0;case uw:return new hg;case hw:return Fr;case mw:return new Ns;case fw:return!1;case dw:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case cw:case hw:case fw:return t===Aw.defaultValues(e);case uw:return hg.compareWithDefault("hashAlgorithm",t.hashAlgorithm)&&hg.compareWithDefault("hashedMessage",t.hashedMessage);case mw:return t.isEqual(Aw.defaultValues(e));case dw:return 0===t.length;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||gw,value:[new Ns({name:t.version||pw}),hg.schema(t.messageImprint||{names:{blockName:ww}}),new Bs({name:t.reqPolicy||yw,optional:!0}),new Ns({name:t.nonce||vw,optional:!0}),new gs({name:t.certReq||bw,optional:!0}),new us({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new or({name:t.extensions||Sw,value:Vl.schema()})]})]})}fromSchema(e){st(e,kw);const t=cr(e,e,Aw.schema());Gr.assertSchema(t,this.className),this.version=t.result[pw].valueBlock.valueDec,this.messageImprint=new hg({schema:t.result[ww]}),yw in t.result&&(this.reqPolicy=t.result[yw].valueBlock.toString()),vw in t.result&&(this.nonce=t.result[vw]),bw in t.result&&(this.certReq=t.result[bw].valueBlock.value),Sw in t.result&&(this.extensions=Array.from(t.result[Sw],(e=>new Vl({schema:e}))))}toSchema(){const e=[];return e.push(new Ns({value:this.version})),e.push(this.messageImprint.toSchema()),this.reqPolicy&&e.push(new Bs({value:this.reqPolicy})),this.nonce&&e.push(this.nonce),fw in this&&!1===Aw.compareWithDefault(fw,this.certReq)&&e.push(new gs({value:this.certReq})),this.extensions&&e.push(new us({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.extensions,(e=>e.toSchema()))})),new Os({value:e})}toJSON(){const e={version:this.version,messageImprint:this.messageImprint.toJSON()};return void 0!==this.reqPolicy&&(e.reqPolicy=this.reqPolicy),void 0!==this.nonce&&(e.nonce=this.nonce.toJSON()),void 0!==this.certReq&&!1===Aw.compareWithDefault(fw,this.certReq)&&(e.certReq=this.certReq),this.extensions&&(e.extensions=Array.from(this.extensions,(e=>e.toJSON()))),e}}Aw.CLASS_NAME="TimeStampReq";const Nw="status",Ew="timeStampToken",Cw="TimeStampResp",Iw=`${Cw}.${Nw}`,Bw=`${Cw}.${Ew}`,Vw=[Iw,Bw];class xw extends zr{constructor(e={}){super(),this.status=He(e,Nw,xw.defaultValues(Nw)),Ew in e&&(this.timeStampToken=He(e,Ew,xw.defaultValues(Ew))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Nw:return new lw;case Ew:return new Lc;default:return super.defaultValues(e)}}static compareWithDefault(e,t){switch(e){case Nw:return lw.compareWithDefault(Nw,t.status)&&"statusStrings"in t==!1&&"failInfo"in t==!1;case Ew:return t.contentType===Fr&&t.content instanceof ar;default:return super.defaultValues(e)}}static schema(e={}){const t=He(e,"names",{});return new Os({name:t.blockName||Cw,value:[lw.schema(t.status||{names:{blockName:Iw}}),Lc.schema(t.timeStampToken||{names:{blockName:Bw,optional:!0}})]})}fromSchema(e){st(e,Vw);const t=cr(e,e,xw.schema());Gr.assertSchema(t,this.className),this.status=new lw({schema:t.result[Iw]}),Bw in t.result&&(this.timeStampToken=new Lc({schema:t.result[Bw]}))}toSchema(){const e=[];return e.push(this.status.toSchema()),this.timeStampToken&&e.push(this.timeStampToken.toSchema()),new Os({value:e})}toJSON(){const e={status:this.status.toJSON()};return this.timeStampToken&&(e.timeStampToken=this.timeStampToken.toJSON()),e}async sign(e,t,s=Xo(!0)){this.assertContentType();return new Yp({schema:this.timeStampToken.content}).sign(e,0,t,void 0,s)}async verify(e={signer:0,trustedCerts:[],data:$r},t=Xo(!0)){this.assertContentType();return new Yp({schema:this.timeStampToken.content}).verify(e,t)}assertContentType(){if(!this.timeStampToken)throw new Error("timeStampToken is absent in TSP response");if(this.timeStampToken.contentType!==Xn)throw new Error(`Wrong format of timeStampToken: ${this.timeStampToken.contentType}`)}}xw.CLASS_NAME="TimeStampResp",function(){if("undefined"!=typeof globalThis&&"crypto"in globalThis){let e="webcrypto";"webkitSubtle"in globalThis.crypto&&(e="safari"),Zo(e,new zo({name:e,crypto:globalThis.crypto}))}else if("undefined"!=typeof crypto&&"webcrypto"in crypto){const e="NodeJS ^15",t=crypto.webcrypto;Zo(e,new zo({name:e,crypto:t}))}}();let Dw,Ow,Tw="",Pw="";const Uw=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,Lw={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function Rw(e){return Uw.lastIndex=0,Uw.test(e)?'"'+e.replace(Uw,(e=>Lw[e]||"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)))+'"':'"'+e+'"'}function _w(e,t){let s=t[e];switch(s&&"object"==typeof s&&"function"==typeof s.toJSON&&(s=s.toJSON(e)),"function"==typeof Dw&&(s=Dw.call(t,e,s)),typeof s){case"string":return Rw(s);case"number":return isFinite(s)?String(s):"null";case"boolean":case"undefined":case"object":if(null===s)return"null";const e=Tw;Tw+=Pw;const t=[];if(Array.isArray(s))for(let e=0;e<s.length;e++)t[e]=_w(e,s)||"null";else{const e=Object.keys(s).sort(Ow);for(const r of e)if(Object.prototype.hasOwnProperty.call(s,r)){const e=_w(r,s);e&&t.push(Rw(r)+(Tw?": ":":")+e)}}let r;return r=Array.isArray(s)?0===t.length?"[]":Tw?"[\n"+Tw+t.join(",\n"+Tw)+"\n"+e+"]":"["+t.join(",")+"]":0===t.length?"{}":Tw?"{\n"+Tw+t.join(",\n"+Tw)+"\n"+e+"}":"{"+t.join(",")+"}",Tw=e,r;default:return String(s)}}function Hw(e,t,s,r){return Tw="",Pw="",Dw=t,Ow="function"==typeof r?r:void 0,"number"==typeof s?Pw=" ".repeat(s):"string"==typeof s&&(Pw=s),_w("",{"":e})}const Kw="0.1",Mw=`https://cdn.jsdelivr.net/npm/trusted-issuer-registry@${Kw}`,jw=`${Mw}/test`,Jw=async(e,t,s)=>{try{const r=e.replace(/-----BEGIN [^-]+-----/,"").replace(/-----END [^-]+-----/,"").replace(/\s+/g,""),n=ls($w(r).buffer),a=new yu({schema:n.result}).subjectPublicKeyInfo;if(!a||!a.algorithm||!a.algorithm.algorithmId)throw console.error("Parsed publicKeyInfo:",a),new Error("Could not extract algorithm information from public key");const i=function(e){const t=e.algorithm.algorithmId,s=e.algorithm.algorithmParams;let r;if(t&&"object"==typeof t&&t.valueBlock&&"function"==typeof t.valueBlock.toString)r=t.valueBlock.toString();else{if("string"!=typeof t)throw new Error("Unsupported algorithmOid format");r=t}switch(r){case"1.2.840.10045.2.1":let e;switch(e=s&&"object"==typeof s&&s.valueBlock&&"function"==typeof s.valueBlock.toString?s.valueBlock.toString():"string"==typeof s?s:void 0,e){case"1.2.840.10045.3.1.7":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};case"1.3.132.0.34":return{name:"ECDSA",namedCurve:"P-384",hash:{name:"SHA-384"}};case"1.3.132.0.35":return{name:"ECDSA",namedCurve:"P-521",hash:{name:"SHA-512"}};case void 0:return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error(`Unsupported EC curve: ${e}`)}case"1.2.840.113549.1.1.1":return{name:"RSASSA-PKCS1-v1_5"};case"1.2.840.113549.1.1.10":return{name:"RSA-PSS"};default:throw new Error(`Unsupported algorithm OID: ${r}`)}}(a),o=a.toSchema().toBER(),l=await crypto.subtle.importKey("spki",o,i,!1,["verify"]);let c;if("ECDSA"===i.name){let e=32;"P-384"===i.namedCurve&&(e=48),"P-521"===i.namedCurve&&(e=66),c=function(e,t){try{const s=ls($w(e).buffer);if(2!==s.result.valueBlock.value.length)throw new Error("Invalid DER signature structure");const r=s.result.valueBlock.value[0],n=s.result.valueBlock.value[1],a=new Uint8Array(r.valueBlock.valueHex),i=new Uint8Array(n.valueBlock.valueHex),o=Fw(a,t),l=Fw(i,t),c=new Uint8Array(2*t);return c.set(o,0),c.set(l,t),c.buffer}catch(e){throw console.error("Error converting DER signature to raw:",e),e}}(t,e)}else c=$w(t).buffer;return await crypto.subtle.verify(i,l,c,s)}catch(e){throw console.error("Error converting PEM to SPKI key:",e),e}};function $w(e){if("function"==typeof Buffer)return new Uint8Array(Buffer.from(e,"base64"));{const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}}function Fw(e,t){if(e.length===t)return e;if(e.length>t)return e.slice(e.length-t);const s=new Uint8Array(t);return s.set(e,t-e.length),s}class qw{constructor(e={}){this._cacheEnabled=e.cacheEnabled??!0,this._cacheTTL=e.cacheTTL??864e5,this._urlBase=e.useTestData?jw:Mw,this._cache={}}async getEndOfLifeDate(){const e=await fetch(`${this._urlBase}/deprecation_notice.json`);if(e.ok){const t=await e.json();if(!t.version)return null;const[s,r]=t.version.split(".").map(Number),[n,a]=Kw.split(".").map(Number);return s<n||s===n&&r<a?null:new Date(1e3*t.end_of_life)}return null}async getIssuerFromX509AKI(e){if(this._cacheEnabled&&e in this._cache&&this._cache[e].expiresAt>Date.now())return this._deepCopy(this._cache[e].issuer);const t=await fetch(`${this._urlBase}/issuers/x509_aki/${e}.json`);if(t.ok){const s=await t.json();return await this._verifyIssuer(s)?(this._cacheEnabled&&(this._cache[e]={issuer:s,expiresAt:Date.now()+this._cacheTTL}),this._deepCopy(s)):null}return this._cacheEnabled&&(this._cache[e]={issuer:null,expiresAt:Date.now()+this._cacheTTL}),null}async _verifyIssuer(e){const t={...e},s=t.signature;delete t.signature;const r=Hw(t);let n=!1;try{const e=(new TextEncoder).encode(r).buffer;n=await Jw("-----BEGIN CERTIFICATE-----\nMIIBnDCCAUGgAwIBAgIUekpHX8hoNIrffOfU7MBBNgLJQ2IwCgYIKoZIzj0EAwIw\nIzEhMB8GA1UEAwwYVW5pdmVyc2FsIFZlcmlmeSBSb290IENBMB4XDTI1MDgwNzE4\nMDMwOVoXDTM1MDgwNTE4MDMwOVowIzEhMB8GA1UEAwwYVW5pdmVyc2FsIFZlcmlm\neSBSb290IENBMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE/dMNQXfYuLMvGYfU\nz/j1jj0GsmT3ysLcxNbN/fJ9JPjgfRPrq3XxbbgT0evxBBp0s124xGQw3rohL9+B\nt6JahqNTMFEwHQYDVR0OBBYEFHPcZW9gI99hWaLBRZUgX+TbICyCMB8GA1UdIwQY\nMBaAFHPcZW9gI99hWaLBRZUgX+TbICyCMA8GA1UdEwEB/wQFMAMBAf8wCgYIKoZI\nzj0EAwIDSQAwRgIhAKVKMO3AAWQsCUSQUbhBipi9bTJCBBqF65I8BmfSyqGNAiEA\n7GWs56atbaun83KIokEG9xXhPXGkH6/XWk+eioyyoFo=\n-----END CERTIFICATE-----",s,e)}catch(e){console.error("Issuer signature verification failed",e)}return n}_deepCopy(e){return JSON.parse(JSON.stringify(e))}static minorVersion=Kw}qw.verifySignatureWithPem=Jw;const Ww={POS_INT:0,NEG_INT:1,BYTE_STRING:2,UTF8_STRING:3,ARRAY:4,MAP:5,TAG:6,SIMPLE_FLOAT:7},Gw={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,WTF8:273,REGEXP:21066,SELF_DESCRIBED:55799,INVALID_16:65535,INVALID_32:4294967295,INVALID_64:0xffffffffffffffffn},zw={ZERO:0,ONE:24,TWO:25,FOUR:26,EIGHT:27,INDEFINITE:31},Yw=20,Qw=21,Zw=22,Xw=23;class ey{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")}const ty={MIN:-(2n**63n),MAX:2n**64n-1n};class sy{static#e=new Map;tag;contents;constructor(e,t=void 0){this.tag=e,this.contents=t}get noChildren(){return!!sy.#e.get(this.tag)?.noChildren}static registerDecoder(e,t,s){const 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)),s&&!t.comment&&(t.comment=()=>`(${s})`),r}static clearDecoder(e){const 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){const t=e?.tags?.get(this.tag)??sy.#e.get(this.tag);return t?t(this,e):this}comment(e,t){const s=e?.tags?.get(this.tag)??sy.#e.get(this.tag);if(s?.comment)return s.comment(this,e,t)}toCBOR(){return[this.tag,this.contents]}[Symbol.for("nodejs.util.inspect.custom")](e,t,s){return`${this.tag}(${s(this.contents,t)})`}}function ry(e){if(null!=e&&"object"==typeof e)return e[ey.ENCODED]}function ny(e,t){Object.defineProperty(e,ey.ENCODED,{configurable:!0,enumerable:!1,value:t})}function ay(e,t){const s=Object(e);return ny(s,t),s}const iy=Symbol("CBOR_RANGES");function oy(e,t){Object.defineProperty(e,iy,{configurable:!1,enumerable:!1,writable:!1,value:t})}function ly(e){return e[iy]}function cy(e,t=0,s=e.length-1){const r=e.subarray(t,s),n=ly(e);if(n){const e=[];for(const r of n)if(r[0]>=t&&r[0]+r[1]<=s){const s=[...r];s[0]-=t,e.push(s)}e.length&&oy(r,e)}return r}function uy(e){let t=Math.ceil(e.length/2);const s=new Uint8Array(t);t--;for(let r=e.length,n=r-2;r>=0;r=n,n-=2,t--)s[t]=parseInt(e.substring(n,r),16);return s}function hy(e){return e.reduce(((e,t)=>e+t.toString(16).padStart(2,"0")),"")}function my(e){const t=e.reduce(((e,t)=>e+t.length),0),s=e.some((e=>function(e){return void 0!==ly(e)}(e))),r=[],n=new Uint8Array(t);let a=0;for(const t of e){if(!(t instanceof Uint8Array))throw new TypeError(`Invalid array: ${t}`);if(n.set(t,a),s){const e=t[iy]??[[0,t.length]];for(const t of e)t[0]+=a;r.push(...e)}a+=t.length}return s&&oy(n,r),n}function fy(e){const t=atob(e);return Uint8Array.from(t,(e=>e.codePointAt(0)))}const dy={"-":"+",_:"/"};function gy(e){let t="";for(const s of e){const e=s.codePointAt(0)?.toString(16).padStart(4,"0");t&&(t+=", "),t+=`U+${e}`}return t}function py(e,t){const[s,r,n]=e,[a,i,o]=t,l=Math.min(n.length,o.length);for(let e=0;e<l;e++){const t=n[e]-o[e];if(0!==t)return t}return 0}class wy{static defaultOptions={chunkSize:4096};#t;#s=[];#r=null;#n=0;#a=0;constructor(e={}){if(this.#t={...wy.defaultOptions,...e},this.#t.chunkSize<8)throw new RangeError(`Expected size >= 8, got ${this.#t.chunkSize}`);this.#i()}get length(){return this.#a}read(){this.#o();const e=new Uint8Array(this.#a);let t=0;for(const s of this.#s)e.set(s,t),t+=s.length;return this.#i(),e}write(e){const t=e.length;t>this.#l()?(this.#o(),t>this.#t.chunkSize?(this.#s.push(e),this.#i()):(this.#i(),this.#s[this.#s.length-1].set(e),this.#n=t)):(this.#s[this.#s.length-1].set(e,this.#n),this.#n+=t),this.#a+=t}writeUint8(e){this.#e(1),this.#r.setUint8(this.#n,e),this.#c(1)}writeUint16(e,t=!1){this.#e(2),this.#r.setUint16(this.#n,e,t),this.#c(2)}writeUint32(e,t=!1){this.#e(4),this.#r.setUint32(this.#n,e,t),this.#c(4)}writeBigUint64(e,t=!1){this.#e(8),this.#r.setBigUint64(this.#n,e,t),this.#c(8)}writeInt16(e,t=!1){this.#e(2),this.#r.setInt16(this.#n,e,t),this.#c(2)}writeInt32(e,t=!1){this.#e(4),this.#r.setInt32(this.#n,e,t),this.#c(4)}writeBigInt64(e,t=!1){this.#e(8),this.#r.setBigInt64(this.#n,e,t),this.#c(8)}writeFloat32(e,t=!1){this.#e(4),this.#r.setFloat32(this.#n,e,t),this.#c(4)}writeFloat64(e,t=!1){this.#e(8),this.#r.setFloat64(this.#n,e,t),this.#c(8)}clear(){this.#a=0,this.#s=[],this.#i()}#i(){const e=new Uint8Array(this.#t.chunkSize);this.#s.push(e),this.#n=0,this.#r=new DataView(e.buffer,e.byteOffset,e.byteLength)}#o(){if(0===this.#n)return void this.#s.pop();const e=this.#s.length-1;this.#s[e]=this.#s[e].subarray(0,this.#n),this.#n=0,this.#r=null}#l(){const e=this.#s.length-1;return this.#s[e].length-this.#n}#e(e){this.#l()<e&&(this.#o(),this.#i())}#c(e){this.#n+=e,this.#a+=e}}function yy(e,t=0,s=!1){const r=128&e[t]?-1:1,n=(124&e[t])>>2,a=(3&e[t])<<8|e[t+1];if(0===n){if(s&&0!==a)throw new Error("Unwanted subnormal: "+5.960464477539063e-8*r*a);return 5.960464477539063e-8*r*a}return 31===n?a?NaN:r*(1/0):r*2**(n-25)*(1024+a)}function vy(e){const t=new DataView(new ArrayBuffer(4));t.setFloat32(0,e,!1);const s=t.getUint32(0,!1);if(0!=(8191&s))return null;let r=s>>16&32768;const n=s>>23&255,a=8388607&s;if(0!==n||0!==a)if(n>=113&&n<=142)r+=(n-112<<10)+(a>>13);else if(n>=103&&n<113){if(a&(1<<126-n)-1)return null;r+=a+8388608>>126-n}else{if(255!==n)return null;r|=31744,r|=a>>13}return r}class by extends TypeError{code="ERR_ENCODING_INVALID_ENCODED_DATA";constructor(){super("The encoded data was not valid for encoding wtf-8")}}class Sy extends RangeError{code="ERR_ENCODING_NOT_SUPPORTED";constructor(e){super(`Invalid encoding: "${e}"`)}}const ky=new Uint8Array(0),Ay="wtf-8";function Ny(e){return e?e instanceof Uint8Array?e:function(e){return e&&!(e instanceof ArrayBuffer)&&e.buffer instanceof ArrayBuffer}(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e):ky}const Ey=[0,0,0,0,0,0,0,0,-1,-1,-1,-1,1,1,2,3];class Cy{static DEFAULT_BUFFERSIZE=4096;encoding=Ay;fatal;ignoreBOM;bufferSize;#u=0;#h=0;#m=0;#f=!0;#d;constructor(e="wtf8",t=void 0){if("wtf8"!==e.toLowerCase().replace("-",""))throw new Sy(e);if(this.fatal=Boolean(t?.fatal),this.ignoreBOM=Boolean(t?.ignoreBOM),this.bufferSize=Math.floor(t?.bufferSize??Cy.DEFAULT_BUFFERSIZE),isNaN(this.bufferSize)||this.bufferSize<1)throw new RangeError(`Invalid buffer size: ${t?.bufferSize}`);this.#d=new Uint16Array(this.bufferSize)}decode(e,t){const s=Boolean(t?.stream),r=Ny(e),n=[],a=this.#d,i=this.bufferSize-3;let o=0;const l=()=>{if(this.#h=0,this.#u=0,this.#m=0,this.fatal)throw new by;a[o++]=65533},c=()=>{const e=this.#m;for(let t=0;t<e;t++)l()},u=e=>{if(0===this.#u){switch(Ey[e>>4]){case-1:l();break;case 0:a[o++]=e;break;case 1:this.#h=31&e,0==(30&this.#h)?l():(this.#u=1,this.#m=1);break;case 2:this.#h=15&e,this.#u=2,this.#m=1;break;case 3:8&e?l():(this.#h=7&e,this.#u=3,this.#m=1)}}else{if(128!=(192&e))return c(),u(e);if(1===this.#m&&2===this.#u&&0===this.#h&&0==(32&e))return c(),u(e);if(3===this.#u&&0===this.#h&&0==(48&e))return c(),u(e);if(this.#h=this.#h<<6|63&e,this.#m++,0==--this.#u){if(this.ignoreBOM||!this.#f||65279!==this.#h)if(this.#h<65536)a[o++]=this.#h;else{const e=this.#h-65536;a[o++]=e>>>10&1023|55296,a[o++]=1023&e|56320}this.#h=0,this.#m=0,this.#f=!1}}};for(const e of r)o>=i&&(n.push(String.fromCharCode.apply(null,a.subarray(0,o))),o=0),u(e);return s||(this.#f=!0,(this.#h||this.#u)&&c()),o>0&&n.push(String.fromCharCode.apply(null,a.subarray(0,o))),n.join("")}}const Iy=Ww.SIMPLE_FLOAT<<5|zw.TWO,By=Ww.SIMPLE_FLOAT<<5|zw.FOUR,Vy=Ww.SIMPLE_FLOAT<<5|zw.EIGHT,xy=Ww.SIMPLE_FLOAT<<5|Qw,Dy=Ww.SIMPLE_FLOAT<<5|Yw,Oy=Ww.SIMPLE_FLOAT<<5|Xw,Ty=Ww.SIMPLE_FLOAT<<5|Zw,Py=new TextEncoder,Uy=new class{encoding=Ay;encode(e){if(!e)return ky;const t=new Uint8Array(function(e){let t=0;for(const s of e){const e=s.codePointAt(0);e<128?t++:t+=e<2048?2:e<65536?3:4}return t}(String(e)));return this.encodeInto(e,t),t}encodeInto(e,t){const s=String(e),r=s.length,n=t.length;let a=0,i=0;for(i=0;i<r;i++){const e=s.codePointAt(i);if(e<128){if(a>=n)break;t[a++]=e}else if(e<2048){if(a>=n-1)break;t[a++]=192|e>>6,t[a++]=128|63&e}else if(e<65536){if(a>=n-2)break;t[a++]=224|e>>12,t[a++]=128|e>>6&63,t[a++]=128|63&e}else{if(a>=n-3)break;t[a++]=240|e>>18,t[a++]=128|e>>12&63,t[a++]=128|e>>6&63,t[a++]=128|63&e,i++}}return{read:i,written:a}}},Ly={...wy.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,types:null,wtf8:!1},Ry={cde:!0,ignoreOriginalEncoding:!0,sortKeys:py},_y={...Ry,dcbor:!0,largeNegativeAsBigInt:!0,reduceUnsafeNumbers:!0,rejectCustomSimples:!0,rejectDuplicateKeys:!0,rejectUndefined:!0,simplifyNegativeZero:!0,stringNormalization:"NFC"};function Hy(e){const t=e<0;return"bigint"==typeof e?[t?-e-1n:e,t]:[t?-e-1:e,t]}function Ky(e,t,s){if(s.rejectFloats)throw new Error(`Attempt to encode an unwanted floating point number: ${e}`);if(isNaN(e))t.writeUint8(Iy),t.writeUint16(32256);else if(s.float64||Math.fround(e)!==e)t.writeUint8(Vy),t.writeFloat64(e);else{const s=vy(e);null===s?(t.writeUint8(By),t.writeFloat32(e)):(t.writeUint8(Iy),t.writeUint16(s))}}function My(e,t,s){const[r,n]=Hy(e);if(n&&s)throw new TypeError(`Negative size: ${e}`);s??=n?Ww.NEG_INT:Ww.POS_INT,s<<=5,r<24?t.writeUint8(s|r):r<=255?(t.writeUint8(s|zw.ONE),t.writeUint8(r)):r<=65535?(t.writeUint8(s|zw.TWO),t.writeUint16(r)):r<=4294967295?(t.writeUint8(s|zw.FOUR),t.writeUint32(r)):(t.writeUint8(s|zw.EIGHT),t.writeBigUint64(BigInt(r)))}function jy(e,t,s){"number"==typeof e?My(e,t,Ww.TAG):"object"==typeof e&&!s.ignoreOriginalEncoding&&ey.ENCODED in e?t.write(e[ey.ENCODED]):e<=Number.MAX_SAFE_INTEGER?My(Number(e),t,Ww.TAG):(t.writeUint8(Ww.TAG<<5|zw.EIGHT),t.writeBigUint64(BigInt(e)))}function Jy(e,t,s){const[r,n]=Hy(e);if(s.collapseBigInts&&(!s.largeNegativeAsBigInt||e>=-0x8000000000000000n)){if(r<=0xffffffffn)return void My(Number(e),t);if(r<=0xffffffffffffffffn){const e=(n?Ww.NEG_INT:Ww.POS_INT)<<5;return t.writeUint8(e|zw.EIGHT),void t.writeBigUint64(r)}}if(s.rejectBigInts)throw new Error(`Attempt to encode unwanted bigint: ${e}`);const a=n?Gw.NEG_BIGINT:Gw.POS_BIGINT,i=r.toString(16),o=i.length%2?"0":"";jy(a,t,s);const l=uy(o+i);My(l.length,t,Ww.BYTE_STRING),t.write(l)}function $y(e,t,s){s.flushToZero&&(e=function(e){if(0!==e){const t=new ArrayBuffer(8),s=new DataView(t);s.setFloat64(0,e,!1);const r=s.getBigUint64(0,!1);if(0n===(0x7ff0000000000000n&r))return 0x8000000000000000n&r?-0:0}return e}(e)),Object.is(e,-0)?s.simplifyNegativeZero?s.avoidInts?Ky(0,t,s):My(0,t):Ky(e,t,s):!s.avoidInts&&Number.isSafeInteger(e)?My(e,t):s.reduceUnsafeNumbers&&Math.floor(e)===e&&e>=ty.MIN&&e<=ty.MAX?Jy(BigInt(e),t,s):Ky(e,t,s)}const Fy=new class{#e=new Map;registerEncoder(e,t){const s=this.#e.get(e);return this.#e.set(e,t),s}get(e){return this.#e.get(e)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}};function qy(e,t){return Fy.registerEncoder(e,t)}function Wy(e,t,s,r,n){const a=function(e){if(null!=e&&"object"==typeof e)return e[ey.LENGTH]}(e);a&&!n.ignoreOriginalEncoding?r.write(a):My(t,r,s)}function Gy(e,t,s){switch(typeof e){case"number":$y(e,t,s);break;case"bigint":Jy(e,t,s);break;case"string":!function(e,t,s){const r=s.stringNormalization?e.normalize(s.stringNormalization):e;if(s.wtf8&&!e.isWellFormed()){const e=Uy.encode(r);jy(Gw.WTF8,t,s),My(e.length,t,Ww.BYTE_STRING),t.write(e)}else{const e=Py.encode(r);My(e.length,t,Ww.UTF8_STRING),t.write(e)}}(e,t,s);break;case"boolean":t.writeUint8(e?xy:Dy);break;case"undefined":if(s.rejectUndefined)throw new Error("Attempt to encode unwanted undefined.");t.writeUint8(Oy);break;case"object":!function(e,t,s){if(null===e)return void t.writeUint8(Ty);if(!s.ignoreOriginalEncoding&&ey.ENCODED in e)return void t.write(e[ey.ENCODED]);const r=e.constructor;if(r){const n=s.types?.get(r)??Fy.get(r);if(n){const r=n(e,t,s);if(void 0!==r){if(!Array.isArray(r)||2!==r.length)throw new Error("Invalid encoder return value");("bigint"==typeof r[0]||isFinite(Number(r[0])))&&jy(r[0],t,s),Gy(r[1],t,s)}return}}if("function"==typeof e.toCBOR){const r=e.toCBOR(t,s);return void(r&&(("bigint"==typeof r[0]||isFinite(Number(r[0])))&&jy(r[0],t,s),Gy(r[1],t,s)))}if("function"==typeof e.toJSON)return void Gy(e.toJSON(),t,s);const n=Object.entries(e).map((e=>[e[0],e[1],zy(e[0],s)]));s.sortKeys&&n.sort(s.sortKeys),Wy(e,n.length,Ww.MAP,t,s);for(const[e,r,a]of n)t.write(a),Gy(r,t,s)}(e,t,s);break;case"symbol":throw new TypeError(`Unknown symbol: ${e.toString()}`);default:throw new TypeError(`Unknown type: ${typeof e}, ${String(e)}`)}}function zy(e,t={}){const s={...Ly};t.dcbor?Object.assign(s,_y):t.cde&&Object.assign(s,Ry),Object.assign(s,t);const r=new wy(s);return Gy(e,r,s),r.read()}Fy.registerEncoder(Array,(function(e,t,s){const r=e;Wy(r,r.length,Ww.ARRAY,t,s);for(const e of r)Gy(e,t,s)})),Fy.registerEncoder(Uint8Array,(function(e,t){My(e.length,t,Ww.BYTE_STRING),t.write(e)}));var Yy=(e=>(e[e.NEVER=-1]="NEVER",e[e.PREFERRED=0]="PREFERRED",e[e.ALWAYS=1]="ALWAYS",e))(Yy||{});class Qy{static KnownSimple=new Map([[Yw,!1],[Qw,!0],[Zw,null],[Xw,void 0]]);value;constructor(e){this.value=e}static create(e){return Qy.KnownSimple.has(e)?Qy.KnownSimple.get(e):new Qy(e)}toCBOR(e,t){if(t.rejectCustomSimples)throw new Error(`Cannot encode non-standard Simple value: ${this.value}`);My(this.value,e,Ww.SIMPLE_FLOAT)}toString(){return`simple(${this.value})`}decode(){return Qy.KnownSimple.has(this.value)?Qy.KnownSimple.get(this.value):this}[Symbol.for("nodejs.util.inspect.custom")](e,t,s){return`simple(${s(this.value,t)})`}}const Zy=new TextDecoder("utf8",{fatal:!0,ignoreBOM:!0});class Xy{static defaultOptions={maxDepth:1024,encoding:"hex",requirePreferred:!1};#n;#t;#e=0;#s;constructor(e,t){if(this.#s={...Xy.defaultOptions,...t},"string"==typeof e)switch(this.#s.encoding){case"hex":this.#n=uy(e);break;case"base64":this.#n=fy(e);break;default:throw new TypeError(`Encoding not implemented: "${this.#s.encoding}"`)}else this.#n=e;this.#t=new DataView(this.#n.buffer,this.#n.byteOffset,this.#n.byteLength)}toHere(e){return cy(this.#n,e,this.#e)}*[Symbol.iterator](){if(yield*this.#i(0),this.#e!==this.#n.length)throw new Error("Extra data in input")}*seq(){for(;this.#e<this.#n.length;)yield*this.#i(0)}*#i(e){if(e++>this.#s.maxDepth)throw new Error(`Maximum depth ${this.#s.maxDepth} exceeded`);const t=this.#e,s=this.#t.getUint8(this.#e++),r=s>>5,n=31&s;let a=n,i=!1,o=0;switch(n){case zw.ONE:if(o=1,a=this.#t.getUint8(this.#e),r===Ww.SIMPLE_FLOAT){if(a<32)throw new Error(`Invalid simple encoding in extra byte: ${a}`);i=!0}else if(this.#s.requirePreferred&&a<24)throw new Error(`Unexpectedly long integer encoding (1) for ${a}`);break;case zw.TWO:if(o=2,r===Ww.SIMPLE_FLOAT)a=yy(this.#n,this.#e);else if(a=this.#t.getUint16(this.#e,!1),this.#s.requirePreferred&&a<=255)throw new Error(`Unexpectedly long integer encoding (2) for ${a}`);break;case zw.FOUR:if(o=4,r===Ww.SIMPLE_FLOAT)a=this.#t.getFloat32(this.#e,!1);else if(a=this.#t.getUint32(this.#e,!1),this.#s.requirePreferred&&a<=65535)throw new Error(`Unexpectedly long integer encoding (4) for ${a}`);break;case zw.EIGHT:if(o=8,r===Ww.SIMPLE_FLOAT)a=this.#t.getFloat64(this.#e,!1);else if(a=this.#t.getBigUint64(this.#e,!1),a<=Number.MAX_SAFE_INTEGER&&(a=Number(a)),this.#s.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: ${n}`);case zw.INDEFINITE:switch(r){case Ww.POS_INT:case Ww.NEG_INT:case Ww.TAG:throw new Error(`Invalid indefinite encoding for MT ${r}`);case Ww.SIMPLE_FLOAT:return void(yield[r,n,ey.BREAK,t,0])}a=1/0;break;default:i=!0}switch(this.#e+=o,r){case Ww.POS_INT:yield[r,n,a,t,o];break;case Ww.NEG_INT:yield[r,n,"bigint"==typeof a?-1n-a:-1-Number(a),t,o];break;case Ww.BYTE_STRING:a===1/0?yield*this.#r(r,e,t):yield[r,n,this.#a(a),t,a];break;case Ww.UTF8_STRING:a===1/0?yield*this.#r(r,e,t):yield[r,n,Zy.decode(this.#a(a)),t,a];break;case Ww.ARRAY:if(a===1/0)yield*this.#r(r,e,t,!1);else{const s=Number(a);yield[r,n,s,t,o];for(let t=0;t<s;t++)yield*this.#i(e+1)}break;case Ww.MAP:if(a===1/0)yield*this.#r(r,e,t,!1);else{const s=Number(a);yield[r,n,s,t,o];for(let t=0;t<s;t++)yield*this.#i(e),yield*this.#i(e)}break;case Ww.TAG:yield[r,n,a,t,o],yield*this.#i(e);break;case Ww.SIMPLE_FLOAT:{const e=a;i&&(a=Qy.create(Number(a))),yield[r,n,a,t,e];break}}}#a(e){const t=cy(this.#n,this.#e,this.#e+=e);if(t.length!==e)throw new Error(`Unexpected end of stream reading ${e} bytes, got ${t.length}`);return t}*#r(e,t,s,r=!0){for(yield[e,zw.INDEFINITE,1/0,s,1/0];;){const s=this.#i(t),n=s.next(),[a,i,o]=n.value;if(o===ey.BREAK)return yield n.value,void s.next();if(r){if(a!==e)throw new Error(`Unmatched major type. Expected ${e}, got ${a}.`);if(i===zw.INDEFINITE)throw new Error("New stream started in typed stream")}yield n.value,yield*s}}}const ev=new Map([[zw.ZERO,1],[zw.ONE,2],[zw.TWO,3],[zw.FOUR,5],[zw.EIGHT,9]]),tv=new Uint8Array(0);function sv(e,t){return t.boxed||t.preferMap||!e.every((([e])=>"string"==typeof e))?new Map(e):Object.fromEntries(e)}class rv{static defaultDecodeOptions={...Xy.defaultOptions,ParentType:rv,boxed:!1,cde:!1,dcbor:!1,diagnosticSizes:Yy.PREFERRED,convertUnsafeIntsToFloat:!1,createObject:sv,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,tags:null};static cdeDecodeOptions={cde:!0,rejectStreaming:!0,requirePreferred:!0,sortKeys:py};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;#n=null;constructor(e,t,s,r){if([this.mt,this.ai,,this.offset]=e,this.left=t,this.parent=s,this.#e=r,s&&(this.depth=s.depth+1),this.mt===Ww.MAP&&(this.#e.sortKeys||this.#e.rejectDuplicateKeys)&&(this.#n=[]),this.#e.rejectStreaming&&this.ai===zw.INDEFINITE)throw new Error("Streaming not supported")}get isStreaming(){return this.left===1/0}get done(){return 0===this.left}static create(e,t,s,r){const[n,a,i,o]=e;switch(n){case Ww.POS_INT:case Ww.NEG_INT:{if(s.rejectInts)throw new Error(`Unexpected integer: ${i}`);if(s.rejectLargeNegatives&&i<-0x8000000000000000n)throw new Error(`Invalid 65bit negative number: ${i}`);let e=i;return s.convertUnsafeIntsToFloat&&e>=ty.MIN&&e<=ty.MAX&&(e=Number(i)),s.boxed?ay(e,r.toHere(o)):e}case Ww.SIMPLE_FLOAT:if(a>zw.ONE){if(s.rejectFloats)throw new Error(`Decoding unwanted floating point number: ${i}`);if(s.rejectNegativeZero&&Object.is(i,-0))throw new Error("Decoding negative zero");if(s.rejectLongLoundNaN&&isNaN(i)){const e=r.toHere(o);if(3!==e.length||126!==e[1]||0!==e[2])throw new Error(`Invalid NaN encoding: "${hy(e)}"`)}if(s.rejectSubnormals&&function(e){switch(e.length){case 2:yy(e,0,!0);break;case 4:{const t=new DataView(e.buffer,e.byteOffset,e.byteLength),s=t.getUint32(0,!1);if(0==(2139095040&s)&&8388607&s)throw new Error(`Unwanted subnormal: ${t.getFloat32(0,!1)}`);break}case 8:{const t=new DataView(e.buffer,e.byteOffset,e.byteLength),s=t.getBigUint64(0,!1);if(0n===(0x7ff0000000000000n&s)&&0x000fffffffffffn&s)throw new Error(`Unwanted subnormal: ${t.getFloat64(0,!1)}`);break}default:throw new TypeError(`Bad input to isSubnormal: ${e}`)}}(r.toHere(o+1)),s.rejectLongFloats){const e=zy(i,{chunkSize:9,reduceUnsafeNumbers:s.rejectUnsafeFloatInts});if(e[0]>>5!==n)throw new Error(`Should have been encoded as int, not float: ${i}`);if(e.length<ev.get(a))throw new Error(`Number should have been encoded shorter: ${i}`)}if("number"==typeof i&&s.boxed)return ay(i,r.toHere(o))}else{if(s.rejectSimple&&i instanceof Qy)throw new Error(`Invalid simple value: ${i}`);if(s.rejectUndefined&&void 0===i)throw new Error("Unexpected undefined")}return i;case Ww.BYTE_STRING:case Ww.UTF8_STRING:if(i===1/0)return new s.ParentType(e,1/0,t,s);if(s.rejectStringsNotNormalizedAs&&"string"==typeof i){const e=i.normalize(s.rejectStringsNotNormalizedAs);if(i!==e)throw new Error(`String not normalized as "${s.rejectStringsNotNormalizedAs}", got [${gy(i)}] instead of [${gy(e)}]`)}return s.boxed?ay(i,r.toHere(o)):i;case Ww.ARRAY:return new s.ParentType(e,i,t,s);case Ww.MAP:return new s.ParentType(e,2*i,t,s);case Ww.TAG:{const r=new s.ParentType(e,1,t,s);return r.children=new sy(i),r}}throw new TypeError(`Invalid major type: ${n}`)}static decodeToEncodeOpts(e){return{...Ly,avoidInts:e.rejectInts,float64:!e.rejectLongFloats,flushToZero:e.rejectSubnormals,largeNegativeAsBigInt:e.rejectLargeNegatives,sortKeys:e.sortKeys}}push(e,t,s){if(this.children.push(e),this.#n){const r=ry(e)||t.toHere(s);this.#n.push(r)}return--this.left}replaceLast(e,t,s){let r,n=-1/0;if(this.children instanceof sy?(n=0,r=this.children.contents,this.children.contents=e):(n=this.children.length-1,r=this.children[n],this.children[n]=e),this.#n){const r=ry(e)||s.toHere(t.offset);this.#n[n]=r}return r}convert(e){let t;switch(this.mt){case Ww.ARRAY:t=this.children;break;case Ww.MAP:{const e=this.#t();if(this.#e.sortKeys){let t;for(const s of e){if(t&&this.#e.sortKeys(t,s)>=0)throw new Error(`Duplicate or out of order key: "0x${s[2]}"`);t=s}}else if(this.#e.rejectDuplicateKeys){const t=new Set;for(const[s,r,n]of e){const e=hy(n);if(t.has(e))throw new Error(`Duplicate key: "0x${e}"`);t.add(e)}}t=this.#e.createObject(e,this.#e);break}case Ww.BYTE_STRING:return my(this.children);case Ww.UTF8_STRING:{const s=this.children.join("");t=this.#e.boxed?ay(s,e.toHere(this.offset)):s;break}case Ww.TAG:t=this.children.decode(this.#e);break;default:throw new TypeError(`Invalid mt on convert: ${this.mt}`)}return this.#e.saveOriginal&&t&&"object"==typeof t&&ny(t,e.toHere(this.offset)),t}#t(){const e=this.children,t=e.length;if(t%2)throw new Error("Missing map value");const s=new Array(t/2);if(this.#n)for(let r=0;r<t;r+=2)s[r>>1]=[e[r],e[r+1],this.#n[r]];else for(let r=0;r<t;r+=2)s[r>>1]=[e[r],e[r+1],tv];return s}}const nv=" ",av=new TextEncoder;class iv extends rv{close="";quote='"';get isEmptyStream(){return(this.mt===Ww.UTF8_STRING||this.mt===Ww.BYTE_STRING)&&0===this.count}}function ov(e,t,s,r){let n="";if(t===zw.INDEFINITE)n+="_";else{if(r.diagnosticSizes===Yy.NEVER)return"";{let a=r.diagnosticSizes===Yy.ALWAYS;if(!a){let r=zw.ZERO;if(Object.is(s,-0))r=zw.TWO;else if(e===Ww.POS_INT||e===Ww.NEG_INT){const e=s<0?-s-("bigint"==typeof s?1n:1):s;r=e<=23?Number(e):e<=255?zw.ONE:e<=65535?zw.TWO:e<=4294967295?zw.FOUR:zw.EIGHT}else r=isFinite(s)?Math.fround(s)===s?null==vy(s)?zw.FOUR:zw.TWO:zw.EIGHT:zw.TWO;a=r!==t}a&&(n+="_",t<zw.ONE?n+="i":n+=String(t-24))}}return n}function lv(e,t){const s={...rv.defaultDecodeOptions,...t,ParentType:iv},r=new Xy(e,s);let n,a,i="";for(const e of r){const[t,o,l]=e;switch(n&&(n.count>0&&l!==ey.BREAK&&(n.mt===Ww.MAP&&n.count%2?i+=": ":(i+=",",s.pretty||(i+=" "))),s.pretty&&(n.mt!==Ww.MAP||n.count%2==0)&&(i+=`\n${nv.repeat(n.depth+1)}`)),a=rv.create(e,n,s,r),t){case Ww.POS_INT:case Ww.NEG_INT:i+=String(l),i+=ov(t,o,l,s);break;case Ww.SIMPLE_FLOAT:if(l!==ey.BREAK)if("number"==typeof l){const e=Object.is(l,-0)?"-0.0":String(l);i+=e,isFinite(l)&&!/[.e]/.test(e)&&(i+=".0"),i+=ov(t,o,l,s)}else l instanceof Qy?(i+="simple(",i+=String(l.value),i+=ov(Ww.POS_INT,o,l.value,s),i+=")"):i+=String(l);break;case Ww.BYTE_STRING:l===1/0?(i+="(_ ",a.close=")",a.quote="'"):(i+="h'",i+=hy(l),i+="'",i+=ov(Ww.POS_INT,o,l.length,s));break;case Ww.UTF8_STRING:l===1/0?(i+="(_ ",a.close=")"):(i+=JSON.stringify(l),i+=ov(Ww.POS_INT,o,av.encode(l).length,s));break;case Ww.ARRAY:{i+="[";const e=ov(Ww.POS_INT,o,l,s);i+=e,e&&(i+=" "),s.pretty&&l?a.close=`\n${nv.repeat(a.depth)}]`:a.close="]";break}case Ww.MAP:{i+="{";const e=ov(Ww.POS_INT,o,l,s);i+=e,e&&(i+=" "),s.pretty&&l?a.close=`\n${nv.repeat(a.depth)}}`:a.close="}";break}case Ww.TAG:i+=String(l),i+=ov(Ww.POS_INT,o,l,s),i+="(",a.close=")"}if(a===ey.BREAK){if(!n?.isStreaming)throw new Error("Unexpected BREAK");n.left=0}else n&&(n.count++,n.left--);for(a instanceof iv&&(n=a);n?.done;){if(n.isEmptyStream)i=i.slice(0,-3),i+=`${n.quote}${n.quote}_`;else{if(n.mt===Ww.MAP&&n.count%2!=0)throw new Error(`Odd streaming map size: ${n.count}`);i+=n.close}n=n.parent}}return i}const cv=new TextDecoder;class uv extends rv{depth=0;leaf=!1;value;length;[ey.ENCODED];constructor(e,t,s,r){super(e,t,s,r),this.parent?this.depth=this.parent.depth+1:this.depth=r.initialDepth,[,,this.value,,this.length]=e}numBytes(){switch(this.ai){case zw.ONE:return 1;case zw.TWO:return 2;case zw.FOUR:return 4;case zw.EIGHT:return 8}return 0}}function hv(e){return e instanceof uv}function mv(e,t){return e===1/0?"Indefinite":t?`${e} ${t}${1!==e&&1n!==e?"s":""}`:String(e)}function fv(e){return"".padStart(e," ")}function dv(e,t,s){let r="";r+=fv(2*e.depth);const n=ry(e);r+=hy(n.subarray(0,1));const a=e.numBytes();a&&(r+=" ",r+=hy(n.subarray(1,a+1))),r=r.padEnd(t.minCol+1," "),r+="-- ",void 0!==s&&(r+=fv(2*e.depth),""!==s&&(r+=`[${s}] `));let i=!1;const[o]=e.children;switch(e.mt){case Ww.POS_INT:r+=`Unsigned: ${o}`,"bigint"==typeof o&&(r+="n");break;case Ww.NEG_INT:r+=`Negative: ${o}`,"bigint"==typeof o&&(r+="n");break;case Ww.BYTE_STRING:r+=`Bytes (Length: ${mv(e.length)})`;break;case Ww.UTF8_STRING:r+=`UTF8 (Length: ${mv(e.length)})`,e.length!==1/0&&(r+=`: ${JSON.stringify(o)}`);break;case Ww.ARRAY:r+=`Array (Length: ${mv(e.value,"item")})`;break;case Ww.MAP:r+=`Map (Length: ${mv(e.value,"pair")})`;break;case Ww.TAG:{r+=`Tag #${e.value}`;const s=e.children,[a]=s.contents.children,o=new sy(s.tag,a);ny(o,n);const l=o.comment(t,e.depth);l&&(r+=": ",r+=l),i||=o.noChildren;break}case Ww.SIMPLE_FLOAT:o===ey.BREAK?r+="BREAK":e.ai>zw.ONE?Object.is(o,-0)?r+="Float: -0":r+=`Float: ${o}`:(r+="Simple: ",r+=o instanceof Qy?o.value:o)}if(!i)if(e.leaf){if(r+="\n",n.length>a+1){const s=fv(2*(e.depth+1)),i=ly(n);if(i?.length){i.sort(((e,t)=>e[0]-t[0]||t[1]-e[1]));let o=0;for(const[l,c,u]of i)if(!(l<o)){if(o=l+c,"<<"===u){r+=fv(t.minCol+1),r+="--",r+=s,r+="<< ";const a=cy(n,l,l+c),i=ly(a);if(i){const e=i.findIndex((([e,t,s])=>0===e&&t===c&&"<<"===s));e>=0&&i.splice(e,1)}r+=lv(a),r+=" >>\n",r+=pv(a,{initialDepth:e.depth+1,minCol:t.minCol,noPrefixHex:!0});continue}if("'"===u&&(r+=fv(t.minCol+1),r+="--",r+=s,r+="'",r+=cv.decode(n.subarray(l,l+c)),r+="'\n"),l>a)for(let e=l;e<l+c;e+=8){const t=Math.min(e+8,l+c);r+=s,r+=hy(n.subarray(e,t)),r+="\n"}}}else for(let e=a+1;e<n.length;e+=8)r+=s,r+=hy(n.subarray(e,e+8)),r+="\n"}}else{r+="\n";let s=0;for(const n of e.children){if(hv(n)){let a=String(s);e.mt===Ww.MAP?a=s%2?"val "+(s-1)/2:"key "+s/2:e.mt===Ww.TAG&&(a=""),r+=dv(n,t,a)}s++}}return r}const gv={...rv.defaultDecodeOptions,initialDepth:0,noPrefixHex:!1,minCol:0};function pv(e,t){const s={...gv,...t,ParentType:uv,saveOriginal:!0},r=new Xy(e,s);let n,a;for(const e of r){if(a=rv.create(e,n,s,r),e[2]===ey.BREAK){if(!n?.isStreaming)throw new Error("Unexpected BREAK");n.left=1}if(!hv(a)){const t=new uv(e,0,n,s);t.leaf=!0,t.children.push(a),ny(t,r.toHere(e[3])),a=t}let t=2*(a.depth+1);const i=a.numBytes();for(i&&(t+=1,t+=2*i),s.minCol=Math.max(s.minCol,t),n&&n.push(a,r,e[3]),n=a;n?.done;)a=n,a.leaf||ny(a,r.toHere(a.offset)),({parent:n}=n)}t&&(t.minCol=s.minCol);let i=s.noPrefixHex?"":`0x${hy(r.toHere(0))}\n`;return i+=dv(a,s),i}const wv=!function(){const e=new Uint8Array(4);return!((new Uint32Array(e.buffer)[0]=1)&e[0])}();function yv(e){if("object"==typeof e&&e){if(e.constructor!==Number)throw new Error(`Expected number: ${e}`)}else if("number"!=typeof e)throw new Error(`Expected number: ${e}`)}function vv(e){if("object"==typeof e&&e){if(e.constructor!==String)throw new Error(`Expected string: ${e}`)}else if("string"!=typeof e)throw new Error(`Expected string: ${e}`)}function bv(e){if(!(e instanceof Uint8Array))throw new Error(`Expected Uint8Array: ${e}`)}function Sv(e){if(!Array.isArray(e))throw new Error(`Expected Array: ${e}`)}function kv(e){return vv(e.contents),new Date(e.contents)}function Av(e){return yv(e.contents),new Date(1e3*e.contents)}function Nv(e,t,s){if(bv(t.contents),s.rejectBigInts)throw new Error(`Decoding unwanted big integer: ${t}(h'${hy(t.contents)}')`);if(s.requirePreferred&&0===t.contents[0])throw new Error(`Decoding overly-large bigint: ${t.tag}(h'${hy(t.contents)})`);let r=t.contents.reduce(((e,t)=>e<<8n|BigInt(t)),0n);if(e&&(r=-1n-r),s.requirePreferred&&r>=Number.MIN_SAFE_INTEGER&&r<=Number.MAX_SAFE_INTEGER)throw new Error(`Decoding bigint that could have been int: ${r}n`);return s.boxed?ay(r,t.contents):r}qy(Map,((e,t,s)=>{const r=[...e.entries()].map((e=>[e[0],e[1],zy(e[0],s)]));if(s.rejectDuplicateKeys){const e=new Set;for(const[t,s,n]of r){const t=hy(n);if(e.has(t))throw new Error(`Duplicate map key: 0x${t}`);e.add(t)}}s.sortKeys&&r.sort(s.sortKeys),Wy(e,e.size,Ww.MAP,t,s);for(const[e,n,a]of r)t.write(a),Gy(n,t,s)})),kv.comment=e=>(vv(e.contents),`(String Date) ${new Date(e.contents).toISOString()}`),sy.registerDecoder(Gw.DATE_STRING,kv),Av.comment=e=>(yv(e.contents),`(Epoch Date) ${new Date(1e3*e.contents).toISOString()}`),sy.registerDecoder(Gw.DATE_EPOCH,Av),qy(Date,(e=>[Gw.DATE_EPOCH,e.valueOf()/1e3]));const Ev=Nv.bind(null,!1),Cv=Nv.bind(null,!0);function Iv(e,t){return bv(e.contents),e}function Bv(e,t,s){bv(e.contents);let r=e.contents.length;if(r%t.BYTES_PER_ELEMENT!=0)throw new Error(`Number of bytes must be divisible by ${t.BYTES_PER_ELEMENT}, got: ${r}`);r/=t.BYTES_PER_ELEMENT;const n=new t(r),a=new DataView(e.contents.buffer,e.contents.byteOffset,e.contents.byteLength),i=a[`get${t.name.replace(/Array/,"")}`].bind(a);for(let e=0;e<r;e++)n[e]=i(e*t.BYTES_PER_ELEMENT,s);return n}function Vv(e,t,s,r,n){const a=n.forceEndian??wv;if(jy(a?t:s,e,n),My(r.byteLength,e,Ww.BYTE_STRING),wv===a)e.write(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));else{const t=e[`write${r.constructor.name.replace(/Array/,"")}`].bind(e);for(const e of r)t(e,a)}}function xv(e){return bv(e.contents),(new Cy).decode(e.contents)}function Dv(e){throw new Error(`Encoding ${e.constructor.name} intentionally unimplmented. It is not concrete enough to interoperate. Convert to Uint8Array first.`)}function Ov(e){return[NaN,e.valueOf()]}Ev.comment=(e,t)=>`(Positive BigInt) ${Nv(!1,e,t)}n`,Cv.comment=(e,t)=>`(Negative BigInt) ${Nv(!0,e,t)}n`,sy.registerDecoder(Gw.POS_BIGINT,Ev),sy.registerDecoder(Gw.NEG_BIGINT,Cv),Iv.comment=(e,t,s)=>{bv(e.contents);const r={...t,initialDepth:s+2,noPrefixHex:!0},n=ry(e);let a=2**((31&n[0])-24)+1;const i=31&n[a];let o=hy(n.subarray(a,++a));i>=24&&(o+=" ",o+=hy(n.subarray(a,a+2**(i-24)))),r.minCol=Math.max(r.minCol,2*(s+1)+o.length);const l=pv(e.contents,r);let c="Embedded CBOR\n";return c+=`${"".padStart(2*(s+1)," ")}${o}`.padEnd(r.minCol+1," "),c+=`-- Bytes (Length: ${e.contents.length})\n`,c+=l,c},Iv.noChildren=!0,sy.registerDecoder(Gw.CBOR,Iv),sy.registerDecoder(Gw.URI,(e=>(vv(e.contents),new URL(e.contents))),"URI"),qy(URL,(e=>[Gw.URI,e.toString()])),sy.registerDecoder(Gw.BASE64URL,(e=>(vv(e.contents),function(e){const t=e.replace(/[_-]/g,(e=>dy[e]));return fy(t.padEnd(4*Math.ceil(t.length/4),"="))}(e.contents))),"Base64url-encoded"),sy.registerDecoder(Gw.BASE64,(e=>(vv(e.contents),fy(e.contents))),"Base64-encoded"),sy.registerDecoder(35,(e=>(vv(e.contents),new RegExp(e.contents))),"RegExp"),sy.registerDecoder(21065,(e=>{vv(e.contents);const t=`^(?:${e.contents})$`;return new RegExp(t,"u")}),"I-RegExp"),sy.registerDecoder(Gw.REGEXP,(e=>{if(Sv(e.contents),e.contents.length<1||e.contents.length>2)throw new Error(`Invalid RegExp Array: ${e.contents}`);return new RegExp(e.contents[0],e.contents[1])}),"RegExp"),qy(RegExp,(e=>[Gw.REGEXP,[e.source,e.flags]])),sy.registerDecoder(64,(e=>(bv(e.contents),e.contents)),"uint8 Typed Array"),sy.registerDecoder(65,(e=>Bv(e,Uint16Array,!1)),"uint16, big endian, Typed Array"),sy.registerDecoder(66,(e=>Bv(e,Uint32Array,!1)),"uint32, big endian, Typed Array"),sy.registerDecoder(67,(e=>Bv(e,BigUint64Array,!1)),"uint64, big endian, Typed Array"),sy.registerDecoder(68,(e=>(bv(e.contents),new Uint8ClampedArray(e.contents))),"uint8 Typed Array, clamped arithmetic"),qy(Uint8ClampedArray,(e=>[68,new Uint8Array(e.buffer,e.byteOffset,e.byteLength)])),sy.registerDecoder(69,(e=>Bv(e,Uint16Array,!0)),"uint16, little endian, Typed Array"),qy(Uint16Array,((e,t,s)=>Vv(t,69,65,e,s))),sy.registerDecoder(70,(e=>Bv(e,Uint32Array,!0)),"uint32, little endian, Typed Array"),qy(Uint32Array,((e,t,s)=>Vv(t,70,66,e,s))),sy.registerDecoder(71,(e=>Bv(e,BigUint64Array,!0)),"uint64, little endian, Typed Array"),qy(BigUint64Array,((e,t,s)=>Vv(t,71,67,e,s))),sy.registerDecoder(72,(e=>(bv(e.contents),new Int8Array(e.contents))),"sint8 Typed Array"),qy(Int8Array,(e=>[72,new Uint8Array(e.buffer,e.byteOffset,e.byteLength)])),sy.registerDecoder(73,(e=>Bv(e,Int16Array,!1)),"sint16, big endian, Typed Array"),sy.registerDecoder(74,(e=>Bv(e,Int32Array,!1)),"sint32, big endian, Typed Array"),sy.registerDecoder(75,(e=>Bv(e,BigInt64Array,!1)),"sint64, big endian, Typed Array"),sy.registerDecoder(77,(e=>Bv(e,Int16Array,!0)),"sint16, little endian, Typed Array"),qy(Int16Array,((e,t,s)=>Vv(t,77,73,e,s))),sy.registerDecoder(78,(e=>Bv(e,Int32Array,!0)),"sint32, little endian, Typed Array"),qy(Int32Array,((e,t,s)=>Vv(t,78,74,e,s))),sy.registerDecoder(79,(e=>Bv(e,BigInt64Array,!0)),"sint64, little endian, Typed Array"),qy(BigInt64Array,((e,t,s)=>Vv(t,79,75,e,s))),sy.registerDecoder(81,(e=>Bv(e,Float32Array,!1)),"IEEE 754 binary32, big endian, Typed Array"),sy.registerDecoder(82,(e=>Bv(e,Float64Array,!1)),"IEEE 754 binary64, big endian, Typed Array"),sy.registerDecoder(85,(e=>Bv(e,Float32Array,!0)),"IEEE 754 binary32, little endian, Typed Array"),qy(Float32Array,((e,t,s)=>Vv(t,85,81,e,s))),sy.registerDecoder(86,(e=>Bv(e,Float64Array,!0)),"IEEE 754 binary64, big endian, Typed Array"),qy(Float64Array,((e,t,s)=>Vv(t,86,82,e,s))),sy.registerDecoder(Gw.SET,((e,t)=>{if(Sv(e.contents),t.sortKeys){const s=rv.decodeToEncodeOpts(t);let r=null;for(const n of e.contents){const e=[n,void 0,zy(n,s)];if(r&&t.sortKeys(r,e)>=0)throw new Error(`Set items out of order in tag #${Gw.SET}`);r=e}}return new Set(e.contents)}),"Set"),qy(Set,((e,t,s)=>{let r=[...e];if(s.sortKeys){const e=r.map((e=>[e,void 0,zy(e,s)]));e.sort(s.sortKeys),r=e.map((([e])=>e))}return[Gw.SET,r]})),sy.registerDecoder(Gw.JSON,(e=>(vv(e.contents),JSON.parse(e.contents))),"JSON-encoded"),xv.comment=e=>{bv(e.contents);const t=new Cy;return`(WTF8 string): ${JSON.stringify(t.decode(e.contents))}`},sy.registerDecoder(Gw.WTF8,xv),sy.registerDecoder(Gw.SELF_DESCRIBED,(e=>e.contents),"Self-Described"),sy.registerDecoder(Gw.INVALID_16,(()=>{throw new Error(`Tag always invalid: ${Gw.INVALID_16}`)}),"Invalid"),sy.registerDecoder(Gw.INVALID_32,(()=>{throw new Error(`Tag always invalid: ${Gw.INVALID_32}`)}),"Invalid"),sy.registerDecoder(Gw.INVALID_64,(()=>{throw new Error(`Tag always invalid: ${Gw.INVALID_64}`)}),"Invalid"),qy(ArrayBuffer,Dv),qy(DataView,Dv),typeof SharedArrayBuffer<"u"&&qy(SharedArrayBuffer,Dv),qy(Boolean,Ov),qy(Number,Ov),qy(String,Ov),qy(BigInt,Ov);const Tv="openid4vp-v1-unsigned",Pv="org-iso-mdoc",Uv="age",Lv="age_over_18",Rv="age_over_21",_v="birth_date",Hv="birth_year",Kv="family_name",Mv="given_name",jv="sex",Jv="address",$v="city",Fv="state",qv="postal_code",Wv="country",Gv="nationality",zv="place_of_birth",Yv="document_number",Qv="issuing_authority",Zv="issuing_country",Xv="issuing_jurisdiction",eb="issue_date",tb="expiry_date",sb="portrait",rb={mso_mdoc:{["org.iso.23220.photoid.1"]:{[Mv]:["org.iso.23220.1","given_name_unicode"],[Kv]:["org.iso.23220.1","family_name_unicode"],[_v]:["org.iso.23220.1","birth_date"],[Hv]:["org.iso.23220.1","age_birth_year"],[Uv]:["org.iso.23220.1","age_in_years"],[Lv]:["org.iso.23220.1","age_over_18"],[Rv]:["org.iso.23220.1","age_over_21"],[Jv]:["org.iso.23220.1","resident_address_unicode"],[$v]:["org.iso.23220.1","resident_city_unicode"],[Fv]:["org.iso.23220.photoid.1","resident_state"],[qv]:["org.iso.23220.1","resident_postal_code"],[Wv]:["org.iso.23220.1","resident_country"],[Gv]:["org.iso.23220.1","nationality"],[jv]:["org.iso.23220.1","sex"],[zv]:["org.iso.23220.1","birthplace"],[Yv]:["org.iso.23220.1","document_number"],[Qv]:["org.iso.23220.1","issuing_authority_unicode"],[Zv]:["org.iso.23220.1","issuing_country"],[Xv]:["org.iso.23220.1","issuing_subdivision"],[eb]:["org.iso.23220.1","issue_date"],[tb]:["org.iso.23220.1","expiry_date"],[sb]:["org.iso.23220.1","portrait"]},["eu.europa.ec.eudi.pid.1"]:{[Mv]:["eu.europa.ec.eudi.pid.1","given_name"],[Kv]:["eu.europa.ec.eudi.pid.1","family_name"],[_v]:["eu.europa.ec.eudi.pid.1","birth_date"],[Hv]:["eu.europa.ec.eudi.pid.1","age_birth_year"],[Uv]:["eu.europa.ec.eudi.pid.1","age_in_years"],[Lv]:["eu.europa.ec.eudi.pid.1","age_over_18"],[Rv]:["eu.europa.ec.eudi.pid.1","age_over_21"],[Jv]:["eu.europa.ec.eudi.pid.1","resident_address"],[$v]:["eu.europa.ec.eudi.pid.1","resident_city"],[Fv]:["eu.europa.ec.eudi.pid.1","resident_state"],[qv]:["eu.europa.ec.eudi.pid.1","resident_postal_code"],[Wv]:["eu.europa.ec.eudi.pid.1","resident_country"],[Gv]:["eu.europa.ec.eudi.pid.1","nationality"],[jv]:["eu.europa.ec.eudi.pid.1","sex"],[zv]:["eu.europa.ec.eudi.pid.1","birth_place"],[Yv]:["eu.europa.ec.eudi.pid.1","document_number"],[Qv]:["eu.europa.ec.eudi.pid.1","issuing_authority"],[Zv]:["eu.europa.ec.eudi.pid.1","issuing_country"],[Xv]:["eu.europa.ec.eudi.pid.1","issuing_jurisdiction"],[eb]:["eu.europa.ec.eudi.pid.1","issuance_date"],[tb]:["eu.europa.ec.eudi.pid.1","expiry_date"],[sb]:["eu.europa.ec.eudi.pid.1","portrait"]},["org.iso.23220.1.jp.mnc"]:{[Mv]:["org.iso.23220.1","given_name_unicode"],[Kv]:["org.iso.23220.1","family_name_unicode"],[_v]:["org.iso.23220.1","birth_date"],[Hv]:["org.iso.23220.1","age_birth_year"],[Uv]:["org.iso.23220.1","age_in_years"],[Lv]:["org.iso.23220.1","age_over_18"],[Rv]:["org.iso.23220.1","age_over_21"],[Jv]:["org.iso.23220.1.jp","resident_address_unicode"],[$v]:["org.iso.23220.1","resident_city_unicode"],[qv]:["org.iso.23220.1","resident_postal_code"],[Wv]:["org.iso.23220.1","resident_country"],[Gv]:["org.iso.23220.1","nationality"],[jv]:["org.iso.23220.1","sex"],[zv]:["org.iso.23220.1","birthplace"],[Yv]:["org.iso.23220.1","document_number"],[Qv]:["org.iso.23220.1","issuing_authority_unicode"],[Zv]:["org.iso.23220.1","issuing_country"],[Xv]:["org.iso.23220.1","issuing_subdivision"],[eb]:["org.iso.23220.1","issue_date"],[tb]:["org.iso.23220.1","expiry_date"],[sb]:["org.iso.23220.1","portrait"]},["org.iso.18013.5.1.mDL"]:{[Mv]:["org.iso.18013.5.1","given_name"],[Kv]:["org.iso.18013.5.1","family_name"],[_v]:["org.iso.18013.5.1","birth_date"],[Hv]:["org.iso.18013.5.1","age_birth_year"],[Uv]:["org.iso.18013.5.1","age_in_years"],[Lv]:["org.iso.18013.5.1","age_over_18"],[Rv]:["org.iso.18013.5.1","age_over_21"],["height"]:["org.iso.18013.5.1","height"],["weight"]:["org.iso.18013.5.1","weight"],["eye_color"]:["org.iso.18013.5.1","eye_colour"],["hair_color"]:["org.iso.18013.5.1","hair_colour"],[Jv]:["org.iso.18013.5.1","resident_address"],[$v]:["org.iso.18013.5.1","resident_city"],[Fv]:["org.iso.18013.5.1","resident_state"],[qv]:["org.iso.18013.5.1","resident_postal_code"],[Wv]:["org.iso.18013.5.1","resident_country"],[Gv]:["org.iso.18013.5.1","nationality"],[jv]:["org.iso.18013.5.1","sex"],[zv]:["org.iso.18013.5.1","birth_place"],[Yv]:["org.iso.18013.5.1","document_number"],[Qv]:["org.iso.18013.5.1","issuing_authority"],[Zv]:["org.iso.18013.5.1","issuing_country"],[Xv]:["org.iso.18013.5.1","issuing_jurisdiction"],[eb]:["org.iso.18013.5.1","issue_date"],[tb]:["org.iso.18013.5.1","expiry_date"],["driving_privileges"]:["org.iso.18013.5.1","driving_privileges"],[sb]:["org.iso.18013.5.1","portrait"],["signature"]:["org.iso.18013.5.1","signature_usual_mark"]}}},nb={};for(const e in rb){nb[e]={};for(const t in rb[e]){nb[e][t]={};for(const s in rb[e][t]){let r=rb[e][t][s];r=r[r.length-1],nb[e][t][r]=s}}}new qw;const ab=async(e,t={})=>{const{timeout:s=3e5}=t;if("undefined"==typeof window)throw new Error("getCredentials can only be called in a browser environment");if(!navigator.credentials)throw new Error("Digital Credentials API not supported in this browser");e.digital.requests=e.digital.requests.filter((e=>{const t=navigator.userAgent.includes("Safari")?Pv:Tv;return e.protocol===t})).slice(0,1);try{const t={...e,mediation:"required",signal:AbortSignal.timeout(s)},r=await navigator.credentials.get(t);if(!r)throw new Error("No credential was provided by the user");return{id:r.id,type:r.type,data:r.data,protocol:r.protocol,timestamp:(new Date).toISOString()}}catch(e){throw console.error("Error getting credentials",e),e}};var ib=function(){function e(e){var t=e.baseUrl,s=e.tenantId,r=e.onTokenExpired,n=e.enableLogging;this.cache=U.shared,this.enableLogging=!1,this.api=new Ve({baseUrl:t,tenantId:s,onTokenExpired:r}),this.enableLogging=n}return e.prototype.verify=function(e){return h(this,void 0,void 0,(function(){var t,s,r,n,a,i,o;return m(this,(function(l){switch(l.label){case 0:if(!xe())throw new Error("Digital Credential API is not supported in this browser");return(null==e?void 0:e.action)?[4,this.api.challenge(e.action)]:[3,2];case 1:return s=l.sent(),[3,3];case 2:s=null,l.label=3;case 3:return(t=s)&&"error"in t?[2,B({errorResponse:t,enableLogging:this.enableLogging})]:[4,this.api.presentationOptions({token:(null==e?void 0:e.token)||void 0,challengeId:null==t?void 0:t.challengeId,action:(null==e?void 0:e.action)||void 0})];case 4:return"error"in(r=l.sent())?[2,B({errorResponse:r,enableLogging:this.enableLogging})]:(n=r.dcapiOptions,a=r.challengeId,[4,ab(n)]);case 5:if(!(i=l.sent()))throw new Error("No credential was provided");return[4,this.api.verifyPresentation({token:(null==e?void 0:e.token)||void 0,data:i,challengeId:a,redirectUrl:null==e?void 0:e.redirectUrl})];case 6:return"error"in(o=l.sent())?[2,B({errorResponse:o,enableLogging:this.enableLogging})]:(o.accessToken&&(this.cache.token=o.accessToken),[2,{data:{isVerified:o.isVerified,token:o.accessToken,username:o.username,userId:o.userId,requireUserVerification:o.requireUserVerification,url:o.url,claims:o.claims}}])}}))}))},e.prototype.verifyClaims=function(e){return h(this,void 0,void 0,(function(){var t,s,r,n,a;return m(this,(function(i){switch(i.label){case 0:if(!xe())throw new Error("Digital Credential API is not supported in this browser");return[4,this.api.presentationOptions({action:(null==e?void 0:e.action)||void 0,anonymous:!0,documentTypes:null==e?void 0:e.documentTypes,claims:null==e?void 0:e.claims})];case 1:return"error"in(t=i.sent())?[2,B({errorResponse:t,enableLogging:this.enableLogging})]:(s=t.dcapiOptions,r=t.challengeId,[4,ab(s)]);case 2:if(!(n=i.sent()))throw new Error("No credential was provided");return[4,this.api.verifyPresentation({data:n,challengeId:r,redirectUrl:null==e?void 0:e.redirectUrl})];case 3:return"error"in(a=i.sent())?[2,B({errorResponse:a,enableLogging:this.enableLogging})]:[2,{data:{isVerified:a.isVerified,claims:a.claims,requireUserVerification:a.requireUserVerification,url:a.url}}]}}))}))},e}(),ob="4a08uqve",lb=function(){function t(e){var t=e.cookieDomain,s=e.cookieName,r=void 0===s?"__as_aid":s,n=e.baseUrl,a=void 0===n?"https://api.authsignal.com/v1":n,o=e.tenantId,l=e.onTokenExpired,c=e.enableLogging,u=void 0!==c&&c;if(this.anonymousId="",this.profilingId="",this.cookieDomain="",this.anonymousIdCookieName="",this.enableLogging=!1,this.cookieDomain=t||document.location.hostname.replace("www.",""),this.anonymousIdCookieName=r,!o)throw new Error("tenantId is required");var h,m=(h=this.anonymousIdCookieName)&&decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(h).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null;m?this.anonymousId=m:(this.anonymousId=i(),I({name:this.anonymousIdCookieName,value:this.anonymousId,expire:1/0,domain:this.cookieDomain,secure:"http:"!==document.location.protocol})),this.enableLogging=u,this.passkey=new R({tenantId:o,baseUrl:a,anonymousId:this.anonymousId,onTokenExpired:l,enableLogging:this.enableLogging}),this.totp=new oe({tenantId:o,baseUrl:a,onTokenExpired:l,enableLogging:this.enableLogging}),this.email=new ce({tenantId:o,baseUrl:a,onTokenExpired:l,enableLogging:this.enableLogging}),this.emailML=new fe({tenantId:o,baseUrl:a,onTokenExpired:l,enableLogging:this.enableLogging}),this.sms=new he({tenantId:o,baseUrl:a,onTokenExpired:l,enableLogging:this.enableLogging}),this.securityKey=new ge({tenantId:o,baseUrl:a,onTokenExpired:l,enableLogging:this.enableLogging}),this.qrCode=new Ne({tenantId:o,baseUrl:a,enableLogging:this.enableLogging}),this.push=new Ce({tenantId:o,baseUrl:a,onTokenExpired:l,enableLogging:this.enableLogging}),this.whatsapp=new Be({tenantId:o,baseUrl:a,onTokenExpired:l,enableLogging:this.enableLogging}),this.digitalCredential=new ib({tenantId:o,baseUrl:a,onTokenExpired:l,enableLogging:this.enableLogging})}return t.prototype.setToken=function(e){U.shared.token=e},t.prototype.launch=function(e,t){switch(null==t?void 0:t.mode){case"window":return this.launchWithWindow(e,t);case"popup":return this.launchWithPopup(e,t);default:this.launchWithRedirect(e)}},t.prototype.initAdvancedProfiling=function(e){var t=i();this.profilingId=t,I({name:"__as_pid",value:t,expire:1/0,domain:this.cookieDomain,secure:"http:"!==document.location.protocol});var s=e?"".concat(e,"/fp/tags.js?org_id=").concat(ob,"&session_id=").concat(t):"https://h.online-metrix.net/fp/tags.js?org_id=".concat(ob,"&session_id=").concat(t),r=document.createElement("script");r.src=s,r.async=!1,r.id="as_adv_profile",document.head.appendChild(r);var n=document.createElement("noscript");n.setAttribute("id","as_adv_profile_pixel"),n.setAttribute("aria-hidden","true");var a=document.createElement("iframe"),o=e?"".concat(e,"/fp/tags?org_id=").concat(ob,"&session_id=").concat(t):"https://h.online-metrix.net/fp/tags?org_id=".concat(ob,"&session_id=").concat(t);a.setAttribute("id","as_adv_profile_pixel"),a.setAttribute("src",o),a.setAttribute("style","width: 100px; height: 100px; border: 0; position: absolute; top: -5000px;"),n&&(n.appendChild(a),document.body.prepend(n))},t.prototype.launchWithRedirect=function(e){window.location.href=e},t.prototype.launchWithPopup=function(t,s){var r=s.popupOptions,n=new ne({width:null==r?void 0:r.width,height:null==r?void 0:r.height,isClosable:null==r?void 0:r.isClosable}),a="".concat(t,"&mode=popup");return n.show({url:a}),new Promise((function(t){var s=void 0;n.on("hide",(function(){t({token:s})})),window.addEventListener("message",(function(t){var r=null;try{r=JSON.parse(t.data)}catch(e){}(null==r?void 0:r.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(s=r.token,n.close())}),!1)}))},t.prototype.launchWithWindow=function(t,s){var r=s.windowOptions,n=new _,a="".concat(t,"&mode=popup");return n.show({url:a,width:null==r?void 0:r.width,height:null==r?void 0:r.height}),new Promise((function(t){window.addEventListener("message",(function(s){var r=null;try{r=JSON.parse(s.data)}catch(e){}(null==r?void 0:r.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(n.close(),t({token:r.token}))}),!1)}))},t}();return e.Authsignal=lb,e.DigitalCredential=ib,e.WebAuthnError=v,e.Whatsapp=Be,e.browserSupportsDigitalCredential=xe,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
|