@decaf-ts/for-fabric 0.1.65 → 0.1.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import{Repository as t,PreparedStatementKeys as e,PersistenceKeys as r,Paginator as i,pk as s,column as n,table as a,BaseModel as o,Sequence as c,Context as l,oneToOne as d,Cascade as h,index as u,normalizeImport as p,AuthorizationError as g,createdAt as f,updatedAt as m,createdBy as y,updatedBy as w,UnsupportedError as b,ClientBasedService as C,Statement as A,QueryClause as v,Adapter as S,QueryError as E,PagingError as x,MigrationError as N,ObserverError as T,ForbiddenError as I,ConnectionError as O,Dispatch as R}from"@decaf-ts/core";import{Model as $,required as k,model as F,JSONSerializer as B,ModelKeys as _,stringFormat as P,minlength as j,min as K}from"@decaf-ts/decorator-validation";import{OperationKeys as L,enforceDBDecorators as z,reduceErrorsToPrint as M,ValidationError as H,SerializationError as U,InternalError as Y,BaseError as G,ConflictError as V,NotFoundError as J,version as q,DBKeys as W,readonly as X,onCreate as Q,onUpdate as Z,afterCreate as tt,afterUpdate as et,afterDelete as rt,transient as it,onRead as st,onDelete as nt,BulkCrudOperationKeys as at,BadRequestError as ot}from"@decaf-ts/db-decorators";import{CouchDBKeys as ct}from"@decaf-ts/for-couchdb";import{__decorate as lt,__metadata as dt}from"tslib";import{Metadata as ht,description as ut,uses as pt,Decoration as gt,apply as ft,propMetadata as mt,metadata as yt,prop as wt}from"@decaf-ts/decoration";import bt from"fabric-ca-client";import{MiniLogger as Ct,isBrowser as At,LoggedClass as vt,Logging as St,toPascalCase as Et,toCamelCase as xt,debug as Nt,final as Tt}from"@decaf-ts/logging";import{signers as It,connect as Ot}from"@hyperledger/fabric-gateway";import{User as Rt}from"fabric-common";import $t,{X509Certificate as kt}from"crypto";import*as Ft from"@peculiar/x509";import{Crypto as Dt}from"@peculiar/webcrypto";import*as Bt from"@grpc/grpc-js";import{Client as _t}from"@grpc/grpc-js";import Pt from"pkcs11js";import jt from"fs";import Kt from"path";import{p256 as Lt}from"@noble/curves/nist";class zt extends t{constructor(t,e){super(t,e),this._overrides=Object.assign({},super._overrides,{ignoreValidation:!0,ignoreHandlers:!0,allowRawStatements:!1,forcePrepareSimpleQueries:!0,forcePrepareComplexQueries:!0,allowGenerationOverride:!1})}async paginateBy(t,r,i={offset:1,limit:10},...s){const{log:n,ctxArgs:a}=(await this.logCtx(s,e.PAGE_BY,!0)).for(this.paginateBy);return n.verbose(`paginating ${$.tableName(this.class)} with page size ${i.limit}`),this.statement(this.paginateBy.name,t,r,{limit:i.limit,offset:i.offset,bookmark:i.bookmark},...a)}async listBy(t,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,e.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${$.tableName(this.class)} by ${t} ${r}`),await this.statement(this.listBy.name,t,r,...n)}async findBy(t,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,e.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding all ${$.tableName(this.class)} with ${t} ${r}`),await this.statement(this.findBy.name,t,r,...n)}async findOneBy(t,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,e.FIND_ONE_BY,!0)).for(this.findOneBy);return s.verbose(`finding One ${$.tableName(this.class)} with ${t} ${r}`),await this.statement(this.findOneBy.name,t,r,...n)}async statement(t,...e){const{log:s,ctx:n,ctxArgs:a}=(await this.logCtx(e,r.STATEMENT,!0)).for(this.statement);s.verbose("Executing prepared statement "+t);const o=a.slice(0,-1),c=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(n,r.STATEMENT,[t,JSON.stringify(o)],void 0,void 0,this.class.name)));return Array.isArray(c)?c.map(t=>t[ct.TABLE]&&t[ct.TABLE]===$.tableName(this.class)?new this.class(t):t):c[ct.TABLE]&&c[ct.TABLE]===$.tableName(this.class)?new this.class(c):i.isSerializedPage(c)?Object.assign(c,{data:c.data.map(t=>new this.class(t))}):c}async create(t,...e){const{ctx:r,log:i,ctxArgs:s}=this.logCtx(e,this.create);i.debug(`Creating new ${this.class.name} in table ${$.tableName(this.class)}`);let{record:n,id:a,transient:o}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,a,n,o,...s),this.adapter.revert(n,this.class,a,o,r)}async update(t,...e){const{ctxArgs:r,log:i,ctx:s}=this.logCtx(e,this.update);let{record:n,id:a,transient:o}=this.adapter.prepare(t,s);return i.debug(`updating ${this.class.name} in table ${$.tableName(this.class)} with id ${a}`),n=await this.adapter.update(this.class,a,n,o,...r),this.adapter.revert(n,this.class,a,o,s)}async createAllPrefix(t,...e){const{ctx:r,ctxArgs:i}=(await this.logCtx(e,L.CREATE,!0)).for(this.createAllPrefix),s=r.get("ignoreHandlers"),n=r.get("ignoreValidation");if(!t.length)return[t,...i];if(t=await Promise.all(t.map(async t=>(t=new this.class(t),s||await z(this,r,t,L.CREATE,L.ON),t))),!n){const e=r.get("ignoredValidationProperties")||[],i=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),s=M(i);if(s)throw new H(s)}return[t,...i]}async createAll(t,...e){if(!t.length)return t;const{ctx:r,log:i,ctxArgs:s}=this.logCtx(e,this.createAll);i.debug(`Creating ${t.length} new ${this.class.name} in table ${$.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r)),a=n.map(t=>t.id);let o=n.map(t=>t.record);const c=n.map(t=>t.transient);return o=await this.adapter.createAll(this.class,a,o,c,...s),o.map((t,e)=>this.adapter.revert(t,this.class,a[e],r.get("rebuildWithTransient")?n[e].transient:void 0,r))}async updateAll(t,...e){const{ctx:r,log:i,ctxArgs:s}=this.logCtx(e,this.updateAll);i.debug(`Updating ${t.length} new ${this.class.name} in table ${$.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r));return(await this.adapter.updateAll(this.class,n.map(t=>t.id),n.map(t=>t.record),n.map(t=>t.transient),...s)).map((t,e)=>this.adapter.revert(t,this.class,n[e].id,r.get("rebuildWithTransient")?n[e].transient:void 0,r))}}let Mt=class extends o{constructor(t){super(t)}};lt([s({type:String}),dt("design:type",String)],Mt.prototype,"name",void 0),lt([n(),k(),dt("design:type",String)],Mt.prototype,"owner",void 0),lt([n(),k(),dt("design:type",String)],Mt.prototype,"symbol",void 0),lt([n(),k(),dt("design:type",Number)],Mt.prototype,"decimals",void 0),Mt=lt([a("erc20_tokens"),F(),dt("design:paramtypes",[Object])],Mt);let Ht=class extends o{constructor(t){super(t)}};lt([s({type:String}),dt("design:type",String)],Ht.prototype,"id",void 0),lt([n(),k(),dt("design:type",String)],Ht.prototype,"token",void 0),lt([n(),k(),dt("design:type",Number)],Ht.prototype,"balance",void 0),lt([n(),dt("design:type",String)],Ht.prototype,"captive",void 0),Ht=lt([a("erc20_wallets"),F(),dt("design:paramtypes",[Object])],Ht);let Ut=class extends o{constructor(t){super(t)}};lt([s({type:String}),n(),k(),dt("design:type",String)],Ut.prototype,"owner",void 0),lt([n(),k(),dt("design:type",String)],Ut.prototype,"spender",void 0),lt([n(),k(),dt("design:type",Number)],Ut.prototype,"value",void 0),Ut=lt([a("erc20_allowances"),F(),dt("design:paramtypes",[Object])],Ut);class Yt extends B{constructor(){super()}preSerialize(t,e){const r=Object.assign({},t);let i=ht.modelName(t.constructor);if(!i||"Object"===i){if(!e)throw new U("Could not find metadata for "+t.constructor.name);i=e}return r[_.ANCHOR]=i,r}deserialize(t){const e=JSON.parse(t),r=e[_.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return $.build(e,r)}serialize(t,e){return JSON.stringify(this.preSerialize(t,e))}}class Gt extends zt{static{this.serializer=new Yt}static{this.decoder=new TextDecoder("utf8")}async updateObservers(t,e,r,...i){if(!this.observerHandler)throw new Y("ObserverHandler not initialized. Did you register any observables?");const{log:s,ctxArgs:n}=this.logCtx(i,this.updateObservers);let a;s.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),t="string"==typeof t?$.get(t):t,a=void 0===r?void 0:Array.isArray(r)?r.map(e=>c.parseValue($.sequenceFor(t).type,e)):c.parseValue($.sequenceFor(t).type,r),await this.observerHandler.updateObservers(t,e,a,...n)}decode(t){return Gt.decoder.decode(t)}constructor(t){super(t,Ht),this.serializer=Gt.serializer}async tokenName(...t){const{ctx:e}=(await this.logCtx(t,"tokenName",!0)).for(this.tokenName),r=await this.adapter.evaluateTransaction(e,"TokenName");return this.decode(r)}async symbol(...t){const{ctx:e}=(await this.logCtx(t,"symbol",!0)).for(this.symbol),r=await this.adapter.evaluateTransaction(e,"Symbol");return this.decode(r)}async decimals(...t){const{ctx:e}=(await this.logCtx(t,"decimals",!0)).for(this.decimals),r=await this.adapter.evaluateTransaction(e,"Decimals");return Number(this.decode(r))}async totalSupply(...t){const{ctx:e}=(await this.logCtx(t,"totalSupply",!0)).for(this.totalSupply),r=await this.adapter.evaluateTransaction(e,"TotalSupply");return Number(this.decode(r))}async balanceOf(t,...e){const{ctx:r}=(await this.logCtx(e,"balance",!0)).for(this.balanceOf),i=await this.adapter.evaluateTransaction(r,"BalanceOf",[t]);return Number(this.decode(i))}async transfer(t,e,...r){const{ctx:i}=(await this.logCtx(r,"transfer",!0)).for(this.transfer),s=await this.adapter.submitTransaction(i,"Transfer",[t,e.toString()]);return"true"===this.decode(s)}async transferFrom(t,e,r){const i=await l.args("transferFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:s}=this.logCtx(i.args,this.transferFrom),n=await this.adapter.submitTransaction(s,"TransferFrom",[t,e,r.toString()]);return"true"===this.decode(n)}async approve(t,e){const r=await l.args("approve",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.approve),s=await this.adapter.submitTransaction(i,"Approve",[t,e.toString()]);return"true"===this.decode(s)}async allowance(t,e){const r=await l.args("allowance",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.allowance),s=await this.adapter.submitTransaction(i,"Allowance",[t,e]);return Number(this.decode(s))}async initialize(t){const e=await l.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.initialize),i=await this.adapter.submitTransaction(r,"Initialize",[Gt.serializer.serialize(t)]);return"true"===this.decode(i)}async checkInitialized(){const t=await l.args("checkInitialized",this.class,[],this.adapter,this._overrides||{}),{ctx:e}=this.logCtx(t.args,this.checkInitialized);await this.adapter.evaluateTransaction(e,"CheckInitialized")}async mint(t){const e=await l.args("mint",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.mint);await this.adapter.submitTransaction(r,"Mint",[t.toString()])}async burn(t){const e=await l.args("burn",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.burn);await this.adapter.submitTransaction(r,"Burn",[t.toString()])}async burnFrom(t,e){const r=await l.args("burnFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.burnFrom);await this.adapter.submitTransaction(i,"BurnFrom",[t,e.toString()])}async clientAccountBalance(){const t=await l.args("accountBalance",this.class,[],this.adapter,this._overrides||{}),{ctx:e}=this.logCtx(t.args,this.clientAccountBalance),r=await this.adapter.evaluateTransaction(e,"ClientAccountBalance");return Number(this.decode(r))}async clientAccountID(){const t=await l.args("accountId",this.class,[],this.adapter,this._overrides||{}),{ctx:e}=this.logCtx(t.args,this.clientAccountID),r=await this.adapter.evaluateTransaction(e,"ClientAccountID");return this.decode(r)}}function Vt(t,e,r){return[...t.map(t=>t===ct.TABLE?"table":t),...r||[],...e?[e]:[],"index"].join(ht.splitter)}function Jt(t,e,r,i){const s=e.pop();s&&s!==ct.TABLE?e.push(s):s===ct.TABLE&&e.unshift(s);const n=Vt(e,r,i);let a=[...e,...i||[]];r&&(a=a.reduce((t,e)=>{const i={};return i[e]=r,t.push(i),t},[]));const o={index:{fields:a},name:n,ddoc:n,type:"json"};t[n]=o}function qt(t,e){const r=Vt([ct.TABLE]),i=e||{};i[r]={index:{fields:[ct.TABLE]},name:r,ddoc:r,type:"json"};const s={},n=$.indexes(t);for(const t of Object.keys(n))for(const[,e]of Object.entries(n[t])){const r=e.directions,i=e.compositions,n=[t,ct.TABLE];Jt(s,n),i&&i.length&&Jt(s,n,void 0,i),r&&r.length&&r.forEach(t=>{Jt(s,n,t),i&&i.length&&Jt(s,n,t,i)})}return Object.entries(s).forEach(([t,e])=>{i[t]=e}),Object.values(s)}function Wt(t){const e=require("path"),r=require(e.join(process.cwd(),t.parentPath,t.name));return Object.values(r).filter(t=>{try{return new t instanceof $}catch(t){return!1}})}async function Xt(...t){const e=require("fs"),r=[];for(const i of t){const t=e.readdirSync(i,{withFileTypes:!0,recursive:!0}).filter(t=>t.isFile()&&t.name.endsWith("js"));for(const e of t)r.push(...Wt(e))}return r}function Qt(t,e=process.cwd(),r){const i=require("fs"),s=require("path");function n(t){const e=s.dirname(t);if(i.existsSync(e))return!0;n(e),i.mkdirSync(e)}t.forEach(t=>{const a=s.resolve(s.join(e,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}indexes/${t.name}.json`));n(a),i.writeFileSync(a,JSON.stringify(t,void 0,2))})}let Zt=class extends o{constructor(t){super(t)}};var te,ee;lt([ut("Unique identifier of the credentials record"),n(),s(),dt("design:type",String)],Zt.prototype,"id",void 0),lt([ut("PEM-encoded X.509 certificate for the identity"),n(),k(),dt("design:type",String)],Zt.prototype,"certificate",void 0),lt([ut("PEM-encoded root or intermediate certificate"),n(),k(),dt("design:type",String)],Zt.prototype,"rootCertificate",void 0),lt([ut("PEM-encoded private key"),n(),k(),dt("design:type",String)],Zt.prototype,"privateKey",void 0),Zt=lt([F(),dt("design:paramtypes",[Object])],Zt),(t=>{t.PRIVATE="private",t.SHARED="shared",t.FABRIC="fabric",t.OWNED_BY="owned-by",t.TRANSACTION_ID="transaction-id",t.MIRROR="mirror"})(te||(te={})),(t=>{t.X509="X.509"})(ee||(ee={}));const re="hlf-fabric";let ie=class extends o{constructor(t){super(t),this.type=ee.X509}};lt([ut("Unique identifier of the identity"),s(),dt("design:type",String)],ie.prototype,"id",void 0),lt([d(Zt,{update:h.CASCADE,delete:h.CASCADE}),dt("design:type",Zt)],ie.prototype,"credentials",void 0),lt([n(),k(),u(),dt("design:type",String)],ie.prototype,"mspId",void 0),lt([n(),k(),dt("design:type",String)],ie.prototype,"type",void 0),ie=lt([F(),dt("design:paramtypes",[Object])],ie);class se{static{this.logger=new Ct(se.name)}constructor(){}static async contentOfLoadFile(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}static async readFile(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await p(import("fs"));return await e.readFile(t)})(t)}static async getCAUser(t,e,r,i,s){this.logger.debug(P("Creating CA {0} user {1} with certificate {2}",i,t,r));const n=new Rt(t),a=s?.hsm?{software:!1,lib:s.hsm.library,slot:s.hsm.slot,label:s.hsm.tokenLabel,pin:s.hsm.pin+""}:void 0,o=this.getCryptoSuite(a);n.setCryptoSuite(o);const c=s?.hsm?await this.getHSMEnrollmentKey(o,r,s.hsm):this.getSoftwareEnrollmentKey(o,e);return await n.setEnrollment(c,r,i),n}static getCryptoSuite(t){return t?(se.cryptoSuite||(se.cryptoSuite=Rt.newCryptoSuite(t)),se.cryptoSuite):Rt.newCryptoSuite()}static getSoftwareEnrollmentKey(t,e){if(!e)throw Error("Private key must be provided when HSM configuration is not supplied");return t.createKeyFromRaw(e)}static async getHSMEnrollmentKey(t,e,r){const i=r.keyIdHex&&r.keyIdHex.trim().length>0?Buffer.from(r.keyIdHex,"hex"):await this.getCertificateSKI(e),s=await t.getKey(i);if(!s||"function"==typeof s.isPrivate&&!s.isPrivate())throw Error("Unable to resolve private key from HSM");return s}static async getCertificateSKI(t){const e=new kt(t).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(e.x||"","base64url"),s=Buffer.from(e.y||"","base64url");return $t.createHash("sha256").update(Buffer.concat([r,i,s])).digest()}static async getIdentity(t,e){const r=await this.contentOfLoadFile(e,async t=>{const{promises:e}=await p(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)});return{mspId:t,credentials:r}}static async getFirstDirFileName(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path"));return r(t,(await e.readdir(t))[0])}static async getFirstDirFileNameContent(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}static async getFileContent(t){const{promises:e}=await p(import("fs"));return(await e.readFile(t)).toString()}static async getSigner(t){const e=await this.contentOfLoadFile(t,async t=>{const{promises:e}=await p(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)}),r=await this.extractPrivateKey(e),i=r[Object.getOwnPropertySymbols(r)[0]];return It.newPrivateKeySigner(i)}static async extractPrivateKey(t){let e;if(globalThis.window&&globalThis.window.Crypto)e=globalThis.Crypto.subtle;else{const t=await p(import("crypto"));e=t.subtle||t.webcrypto.subtle}if(!e)throw Error("Could not load SubtleCrypto module");const r=t.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),i=(t=>{const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e})(Buffer.from(r,"base64").toString("binary"));return await e.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}}const ne=new Dt;var ae,oe,ce,le,de;Ft.cryptoProvider.set(ne),(t=>{t.BASE2="01",t.BASE8="01234567",t.BASE11="0123456789a",t.BASE16="0123456789abcdef",t.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",t.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",t.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",t.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",t.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",t.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~"})(ae||(ae={})),(t=>{t.HASH="SHA-256",t[t.ITERATIONS=1e3]="ITERATIONS",t[t.KEYLENGTH=48]="KEYLENGTH",t[t.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",t[t.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",t.ALGORYTHM="AES-GCM",t.KEY_ALGORYTHM="PBKDF2"})(oe||(oe={}));class he{constructor(t){if(this.alphabet=t,this.baseMap=new Uint8Array(256),this.alphabet.length>=255)throw Error("Alphabet too long");for(let t=0;t<this.baseMap.length;t++)this.baseMap[t]=255;for(let e=0;e<t.length;e++){const r=t.charAt(e),i=r.charCodeAt(0);if(255!==this.baseMap[i])throw Error(r+" is ambiguous");this.baseMap[i]=e}this.base=this.alphabet.length,this.leader=this.alphabet.charAt(0),this.factor=Math.log(this.base)/Math.log(256),this.iFactor=Math.log(256)/Math.log(this.base)}encode(t){if("string"==typeof t?t=Buffer.from(t):ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t)),0===t.length)return"";let e=0,r=0,i=0;const s=t.length;for(;i!==s&&0===t[i];)i++,e++;const n=(s-i)*this.iFactor+1>>>0,a=new Uint8Array(n);for(;i!==s;){let e=t[i],s=0;for(let t=n-1;(0!==e||r>s)&&-1!==t;t--,s++)e+=256*a[t]>>>0,a[t]=e%this.base>>>0,e=e/this.base>>>0;if(0!==e)throw Error("Non-zero carry");r=s,i++}let o=n-r;for(;o!==n&&0===a[o];)o++;let c=this.leader.repeat(e);for(;n>o;++o)c+=this.alphabet.charAt(a[o]);return c}decodeUnsafe(t){if(0===t.length)return new Uint8Array(0);let e=0,r=0,i=0;for(;t[e]===this.leader;)r++,e++;const s=(t.length-e)*this.factor+1>>>0,n=new Uint8Array(s);for(;t[e];){let r=this.baseMap[t.charCodeAt(e)];if(255===r)return;let a=0;for(let t=s-1;(0!==r||i>a)&&-1!==t;t--,a++)r+=this.base*n[t]>>>0,n[t]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");i=a,e++}let a=s-i;for(;a!==s&&0===n[a];)a++;const o=new Uint8Array(r+(s-a));let c=r;for(;a!==s;)o[c++]=n[a++];return o}decode(t){const e=this.decodeUnsafe(t);if(e)return e;throw Error("Non-base"+this.base+" character")}}class ue{static{this.b58encoder=new he(ae.BASE58)}static{this.logger=new Ct(ue.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(P("Parsing certificate: {0}",t));const e=new Ft.X509Certificate(t),{subject:r,issuer:i}=e;return this.logger.debug(P("Certificate parsed with subject {0} and issuer {1}",r,i)),`x509::/${r.replaceAll(", ","/")}::/${i.replaceAll(", ","/")}`}static encode(t){return this.b58encoder.encode(t)}static decode(t){const e=this.b58encoder.decode(t);return(new TextDecoder).decode(e)}static stringToArrayBuffer(t){const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e}static async extractKey(t,e,r){const i=ne.subtle,s=e.toString("utf8").replace(RegExp(`-----BEGIN (${t.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${t.toUpperCase()} KEY|CERTIFICATE)-----`),""),n=Buffer.from(s,"base64").toString("binary"),a=this.stringToArrayBuffer(n);return await i.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!0,r||["sign"])}static async extractPrivateKey(t,e){return this.extractKey("private",t,e)}static async extractPublicKey(t,e){return this.extractKey("public",t,e)}static async sign(t,e){const r=await this.extractPrivateKey(t),i=await ne.subtle.sign({name:"ECDSA",hash:"SHA-256"},r,e);return Array.from(new Uint8Array(i)).map(t=>t.toString(16).padStart(2,"0")).join("")}static async verify(t,e,r){const i=new Ft.X509Certificate(t),s=await i.publicKey.export();return e="string"==typeof e?Buffer.from(e,"hex"):e,r="string"==typeof r?Buffer.from(r):r,ne.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,e,r)}static async encrypt(t,e){const r=new Ft.X509Certificate(t),i=await r.publicKey.export();e="string"==typeof e?Buffer.from(e):e;const s=await this.getSubtleCrypto().encrypt({name:"ECDSA"},i,e);return Array.from(new Uint8Array(s)).map(t=>t.toString(16).padStart(2,"0")).join("")}static getSubtleCrypto(){return At()?globalThis.window.crypto.subtle:ne.subtle}static async decrypt(t,e){const r=await this.extractPrivateKey(t);return e="string"==typeof e?Buffer.from(e,"hex"):e,this.getSubtleCrypto().decrypt({name:"ECDSA"},r,e)}static async getMaster(t){const e=new TextEncoder;if(void 0===t){const r=ne.randomUUID();t=e.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,oe.KEY_ALGORYTHM,!1,["deriveBits"]),iv:t}}static async getDerivationKey(t,e){const r=(new TextEncoder).encode(t),i=await this.getSubtleCrypto().digest("SHA-256",r),s={name:oe.KEY_ALGORYTHM,hash:oe.HASH,salt:i,iterations:oe.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,e,8*oe.KEYLENGTH);return this.getKey(n)}static async getKey(t){const e=t.slice(0,32),r=t.slice(32);return{key:await this.getSubtleCrypto().importKey("raw",e,{name:oe.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:oe.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:oe.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}class pe extends Y{constructor(t){super(t,pe.name)}}class ge extends Y{constructor(t){super(t,ge.name)}}class fe extends Y{constructor(t){super(t,fe.name)}}class me extends g{constructor(t){super(t,me.name)}}class ye extends Y{constructor(t){super(t,ye.name,500)}}class we extends G{constructor(t="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(we.name,t,403)}}class be extends G{constructor(t){super(be.name,t,409)}}class Ce extends Y{constructor(t){super(t,Ce.name,500)}}class Ae extends Y{constructor(t){super(t,Ae.name,500)}}class ve extends Y{constructor(t){super(t,ve.name,500)}}class Se extends Y{constructor(t){super(t,Se.name,500)}}class Ee extends Y{constructor(t){super(t,Ee.name,500)}}(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(ce||(ce={})),(t=>{t.HFREGISTRARROLES="hf.Registrar.Roles",t.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",t.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",t.HFINTERMEDIATECA="hf.IntermediateCA",t.HFREVOKER="hf.Revoker",t.HFAFFILIATIONMGR="hf.AffiliationMgr",t.HFGENCRL="hf.GenCRL"})(le||(le={}));class xe extends vt{constructor(t){se.getCryptoSuite(t.hsm?{software:!1,lib:t.hsm.library,slot:t.hsm.slot,label:t.hsm.tokenLabel,pin:t.hsm.pin+""}:void 0),super(),this.caConfig=t}async User(){if(this.user)return this.user;const{caName:t,caCert:e,caKey:r,url:i,hsm:s}=this.caConfig,n=this.log.for(this.User);n.debug(`Creating CA user for ${t} at ${i}`),n.debug("Retrieving CA certificate from "+e);const a=await se.getFirstDirFileNameContent(e);let o;if(s)n.debug(`Using HSM configuration for CA ${t} with library ${s.library}`);else{if(!r)throw new Y(`Missing caKey configuration for CA ${t}. Provide a key directory or configure HSM support.`);n.debug("Retrieving CA key from "+r),o=await se.getFirstDirFileNameContent(r)}return n.debug("Loading Admin user for ca "+t),this.user=await se.getCAUser("admin",o,a,t,{hsm:s}),this.user}async CA(){if(this.ca)return this.ca;const t=this.log.for(this.CA),{url:e,tls:r,caName:i}=this.caConfig;let{trustedRoots:s,verify:n}=r;const a=s[0];t.debug(`Retrieving CA certificate from ${a}. cwd: ${process.cwd()}`);const o=await se.getFileContent(a);return t.debug(`Creating CA Client for CA ${i} under ${e}`),this.ca=new bt(e,{trustedRoots:Buffer.from(o),verify:n},i),this.ca}async Client(){if(this.client)return this.client;const t=await this.CA();return this.client=t._FabricCAServices,this.client}async Certificate(){return this.certificateService||(this.certificateService=(await this.Client()).newCertificateService()),this.certificateService}async Affiliations(){return this.affiliationService||(this.affiliationService=(await this.CA()).newAffiliationService()),this.affiliationService}async Identities(){return this.identityService||(this.identityService=(await this.CA()).newIdentityService()),this.identityService}async getCertificates(t,e=!0){const r=await this.Certificate(),i=await this.User(),s=this.log.for(this.getCertificates);s.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.caConfig.caName}`);const n=(await r.getCertificates(t||{},i)).result;return s.debug(`Found ${n.certs.length} certificates: ${JSON.stringify(n)}`),e?n.certs.map(t=>t.PEM):n}async getIdentities(){const t=await this.Identities(),e=this.log.for(this.getIdentities);e.debug("Retrieving Identities under CA "+this.caConfig.caName);const r=(await t.getAll(await this.User())).result;return e.debug(`Found ${r.identities.length} Identities: ${JSON.stringify(r)}`),r.identities}parseError(t){const e=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(t.message);if(!e)return new me(t);const[,r,i]=e;switch(r){case"74":case"71":return new V(i);case"20":return new g(i);default:return new me(i)}}async getAffiliations(){const t=await this.Affiliations(),e=this.log.for(this.getAffiliations);e.debug("Retrieving Affiliations under CA "+this.caConfig.caName);const r=(await t.getAll(await this.User())).result;return e.debug(`Found ${r.a.length} Affiliations: ${JSON.stringify(r)}`),r}async read(t){const e=await this.CA(),r=await this.User();let i;try{i=await e.newIdentityService().getOne(t,r)}catch(e){throw new J(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new J(`Couldn't find enrollment with id ${t}: ${i.errors.join("\n")}`);return i.result}async register(t,e=!1,r="",i,s,n){let a;const o=this.log.for(this.register);try{const{userName:c,password:l}=t,d=await this.CA(),h=await this.User(),u={enrollmentID:c,enrollmentSecret:l,affiliation:r,userRole:i,attrs:s,maxEnrollments:n};a=await d.register(u,h),o.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${e?"as super user":""}`)}catch(t){throw this.parseError(t)}return a}static identityFromEnrollment(t,e){const{certificate:r,key:i,rootCertificate:s}=t,n=St.for(xe,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${r} in msp ${e}`);const a=ue.fabricIdFromCertificate(r),o=ue.encode(a);n.debug(`Identity ${a} and encodedId ${o}`);const c=new Date;return new ie({id:o,credentials:{id:o,certificate:r,privateKey:i.toBytes(),rootCertificate:s,createdOn:c,updatedOn:c},mspId:e,createdOn:c,updatedOn:c})}async enroll(t,e){let r;const i=this.log.for(this.enroll);try{const s=await this.CA();i.debug("Enrolling "+t);const n=await s.enroll({enrollmentID:t,enrollmentSecret:e});r=xe.identityFromEnrollment(n,this.caConfig.caName),i.info(`Successfully enrolled ${t} under ${this.caConfig.caName} as ${r.id}`)}catch(t){throw this.parseError(t)}return r}async registerAndEnroll(t,e=!1,r="",i,s,n){const a=await this.register(t,e,r,i,s,n),{userName:o}=t;return this.enroll(o,a)}async revoke(t){const e=await this.CA(),r=await this.User(),i=await this.read(t);if(!i)throw new J("Could not find enrollment with id "+t);let s;try{s=await e.revoke({enrollmentID:i.id,reason:"User Deletation"},r)}catch(e){throw new Y(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new Y(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}class Ne extends ${constructor(){super(...arguments),this.affiliation=""}build(){const t=this.hasErrors();if(t)throw new H(t.toString());const e={enrollmentID:this.enrollmentID,enrollmentSecret:this.enrollmentSecret,role:this.role,affiliation:this.affiliation};return void 0!==this.maxEnrollments&&(e.maxEnrollments=this.maxEnrollments),this.attrs&&(e.attrs=this.attrs),e}setAffiliation(t){return this.affiliation=t,this}addAttr(t){return this.attrs=this.attrs||[],this.attrs.push(t),this}setAttrs(t){return this.attrs=t,this}setEnrollmentID(t){return this.enrollmentID=t,this}setEnrollmentSecret(t){return this.enrollmentSecret=t,this}setMaxEnrollments(t){return this.maxEnrollments=t,this}setRole(t){return this.role=t,this}}lt([k(),dt("design:type",String)],Ne.prototype,"affiliation",void 0),lt([j(1),dt("design:type",Array)],Ne.prototype,"attrs",void 0),lt([k(),dt("design:type",String)],Ne.prototype,"enrollmentID",void 0),lt([k(),dt("design:type",String)],Ne.prototype,"enrollmentSecret",void 0),lt([K(0),dt("design:type",Number)],Ne.prototype,"maxEnrollments",void 0),lt([k(),dt("design:type",String)],Ne.prototype,"role",void 0),(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(de||(de={}));let Te=class extends ${constructor(t){super(t)}};lt([ut("Stores the original timestamp of creation"),n(),f(),dt("design:type",Date)],Te.prototype,"createdAt",void 0),lt([ut("Stores the timestamp of the last update"),n(),m(),dt("design:type",Date)],Te.prototype,"updatedAt",void 0),lt([ut("Stores the version of the model"),n(),q(),dt("design:type",Number)],Te.prototype,"version",void 0),Te=lt([pt(re),dt("design:paramtypes",[Object])],Te);let Ie=class extends Te{constructor(t){super(t)}};function Oe(){return function(t,e,r){const i=r.value;return r.value=async function(...t){const r=t[0],s=r.clientIdentity.getID(),n=await this.tokenRepository.select(),a=await n.execute(r);if(0==a.length)throw new J("No tokens avaialble");if(a.length>1)throw new J("To many token available : "+a.length);if(a[0].owner!=s)throw new g(`User not authorized to run ${e} on the token`);return await i.apply(this,t)},r}}async function Re(t,e,r,i){const{stub:s}=t,n=(await s.getCreator()).mspid;Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:n})}function $e(){return gt.for(te.OWNED_BY).define({decorator:()=>(t,e)=>ft(k(),X(),Q(Re),mt(ht.key(te.FABRIC,te.OWNED_BY),e))(t,e),args:[]}).apply()}async function ke(t,e,r,i){const{stub:s}=t;i[r]=s.getTxID()}function Fe(){return gt.for(te.TRANSACTION_ID).define({decorator:()=>(t,e)=>ft(k(),X(),Q(ke),Z(ke),mt(ht.key(te.FABRIC,e,te.TRANSACTION_ID),e))(t,e),args:[]}).apply()}async function De(t,e,r){let i=e;if("string"!=typeof i)try{const s=$.ownerOf(t)||r.get("stub").getCreator().toString();e&&"function"==typeof e&&(i=await e(t,s,r))}catch(t){throw new Y("Failed to resolve collection mirror name: "+t)}if(!i||"string"!=typeof i)throw new Y("No collection found model "+t.constructor.name);return i}async function Be(t,e,r,i){const s=await De(i,e.resolver,t),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),a=await n.create(i,t);t.logger.info(`Mirror for ${$.tableName(this.class)} created with ${$.pk(i)}: ${a[$.pk(i)]}`)}async function _e(t,e,r,i){const s=await De(i,e.resolver,t),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),a=await n.update(i,t);t.logger.info(`Mirror for ${$.tableName(this.class)} updated with ${$.pk(i)}: ${a[$.pk(i)]}`)}async function Pe(t,e,r,i){const s=await De(i,e.resolver,t),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),a=await n.delete($.pk(i),t);t.logger.info(`Mirror for ${$.tableName(this.class)} deleted with ${$.pk(i)}: ${a[$.pk(i)]}`)}function je(t,e){return gt.for(te.MIRROR).define({decorator:(e,r)=>{const i={condition:r,resolver:e};return ft(yt(ht.key(te.FABRIC,te.MIRROR),i),Ge(t),tt(Be,i,{priority:95}),et(_e,i,{priority:95}),rt(Pe,i,{priority:95}))},args:[t,e]}).apply()}lt([ut("Stores the creator"),n(),y(),dt("design:type",String)],Ie.prototype,"createdBy",void 0),lt([ut("Stores the user that last updated the model"),n(),w(),dt("design:type",String)],Ie.prototype,"updatedBy",void 0),Ie=lt([pt(re),dt("design:paramtypes",[Object])],Ie),$.prototype.isShared=function(){return $.isShared(this.constructor)},$.prototype.isPrivate=function(){return $.isPrivate(this.constructor)},$.prototype.segregate=function(){return $.segregate(this)},$.segregate=(t=>{if(!$.isTransient(t))return{model:t};const e=ht.validatableProperties(t.constructor),r=ht.get(t.constructor,W.TRANSIENT),i=ht.get(t.constructor,te.PRIVATE),s=ht.get(t.constructor,te.PRIVATE),n={model:{},transient:{},private:{},shared:{}},a=Object.keys(r),o=Object.keys(i),c=Object.keys(s);for(const r of e){const e=a.includes(r),i=o.includes(r),s=c.includes(r);e?(n.transient=n.transient||{},n.transient[r]=t[r],i&&(n.private=n.private||{},n.private[r]=t[r]),s&&(n.shared=n.shared||{},n.shared[r]=t[r])):(n.model=n.model||{},n.model[r]=t[r])}return n.model=$.build(n.model,t.constructor.name),n}).bind($),$.isPrivate=(t=>!!ht.get("function"!=typeof t?t.constructor:t,te.PRIVATE)).bind($),$.isShared=(t=>!!ht.get("function"!=typeof t?t.constructor:t,te.SHARED)).bind($),$.mirrored=(t=>ht.get("function"!=typeof t?t.constructor:t,ht.key(te.FABRIC,te.MIRROR))).bind($),$.ownerOf=(t=>{const e=ht.get(t.constructor,ht.key(te.FABRIC,te.OWNED_BY));if(e)return t[e]}).bind($),$.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,ht.get(t,ht.key(te.FABRIC,te.MIRROR)))).bind($),$.collectionsFor=(t=>{const e=[te.PRIVATE],r=[te.SHARED],i=ht.key(...e),s=ht.key(...r),n="function"==typeof t?t:t.constructor,a=ht.get(n,i),o=ht.get(n,s);return{privateCols:a?.collections||[],sharedCols:o?.collections||[]}}).bind($);const Ke=(t,e)=>{const r=e||("function"!=typeof t?$.ownerOf(t):void 0),i="function"==typeof t?t:t.constructor;if(!r)throw new Y(`Model ${i.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${Et(i.name)}${e?Et(e):""}`},Le=(t,e)=>{const r=e||("function"!=typeof t?$.ownerOf(t):void 0);if(!r)throw new Y(`Model ${t.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${Et(r)}PrivateCollection`};async function ze(t,e,r,i){if(r.length!==e.length)throw new Y("Segregated data keys and metadata length mismatch");const s=$.ownerOf(i);if(!s)throw new H("There's no assigned organization for model "+i.constructor.name);const n=e[0].collections,a="string"==typeof n?n:n(i,s,t),o=r.reduce((r,n,o)=>{const c="string"==typeof e[o].collections?e[o].collections:e[o].collections(i,s,t);if(c!==a)throw new b(`Segregated data collection mismatch: ${c} vs ${a}`);return r[n]=i[n],r},{}),c=new this.class(o),l=await this.override({segregated:a,mergeModel:!1,ignoreHandlers:!0,ignoreValidation:!0}).create(c,t);Object.assign(i,l)}async function Me(t,e,r,i){if(r.length!==e.length)throw new Y("Segregated data keys and metadata length mismatch");const s=$.ownerOf(i);if(!s)throw new H("There's no assigned organization for model "+i.constructor.name);const n=e[0].collections,a="string"==typeof n?n:await n(i,s,t);r.reduce((r,n,o)=>(("string"==typeof e[o].collections?e[o].collections:e[o].collections(i,s,t))!==a||(r[n]=i[n]),r),{})}async function He(t,e,r,i,s){}async function Ue(t,e,r,i){}function Ye(t,e,r){return(i,s)=>{const n=[];return s?n.push(wt(),it(),(r,i)=>{const s=ht.key(e,i),n=r.constructor,a=ht.get(n,s)||{},o=new Set(a.collections||[]);o.add(t),a.collections=[...o],ht.set(n,s,a);const c=ht.get(n,e)||{};new Set(c.collections||[]).add(t),a.collections=[...o],ht.set(n,e,a)},Q(ze,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),st(Me,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),Z(He,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),nt(Ue,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()})):ht.properties(i)?.forEach(s=>{r&&!r(s)||Ye(t,e)(i.prototype,s)}),ft(...n)(i,s)}}function Ge(t=Le){return gt.for(te.PRIVATE).define({decorator:t=>Ye(t,te.PRIVATE),args:[t]}).apply()}function Ve(t){return gt.for(te.SHARED).define({decorator:t=>Ye(t,te.SHARED),args:[t]}).apply()}class Je extends B{constructor(){super()}preSerialize(t){const e=Object.assign({},t);let r;try{r=ht.modelName(t.constructor)}catch(t){r=void 0}e[_.ANCHOR]=r||t.constructor.name;const i=function t(e){const r=this;return"object"!=typeof e?e:Array.isArray(e)?e.map(e=>t.call(r,e)):this.preSerialize.call(this,e)}.bind(this);return $.relations(t).forEach(t=>{e[t]=i(e[t])}),e}deserialize(t){const e=JSON.parse(t),r=e[_.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return $.build(e,r)}serialize(t){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t)))}}function qe(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function We(t){const e=t.split("_");return 2>e.length||e.length>3?{table:void 0,event:t,owner:void 0}:{table:e[0],event:e[1],owner:e[2]}}function Xe(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new pe(`Addition overflow: ${t} + ${e}`);return r}function Qe(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new pe(`Subtraction overflow: ${t} - ${e}`);return r}function Ze(t){if(!/^\d+$/.test(t))throw new H(P("Failed to parse: {0}","string contains digits"));const e=parseInt(t);if(isNaN(e))throw new H(P("Failed to parse: {0}","string is not a parsable integer"));return e}class tr extends B{constructor(){super()}deserialize(t,e){return JSON.parse(t)}serialize(t,e=!0){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t,e)))}preSerialize(t,e=!0){const r=Object.assign({},t);let i;try{i=ht.modelName(t.constructor)}catch(t){i=void 0}function s(t){return"object"!=typeof t?t:Array.isArray(t)?t.map(s):this.preSerialize(t)}return e&&(r[_.ANCHOR]=i||t.constructor.name),$.relations(t).forEach(t=>{r[t]=s.call(this,r[t])}),r}}class er extends C{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new Y("Fabric identity service not properly setup: missing user");return this._user}get certificates(){return this.rootClient.newCertificateService()}get affiliations(){return this.client.newAffiliationService()}get identities(){return this.client.newIdentityService()}async getUser(t,e){const r=e.logger.for(this.getUser),{caName:i,caCert:s,caKey:n,url:a,hsm:o}=t;r.info(`Creating CA user for ${i} at ${a}`),r.verbose("Retrieving CA certificate from "+s);const c=await se.getFirstDirFileNameContent(s);let l;if(o)r.debug(`Using HSM configuration for CA ${i} with library ${o.library}`);else{if(!n)throw new Y(`Missing caKey configuration for CA ${i}. Provide a key directory or configure HSM support.`);r.debug("Retrieving CA key from "+n),l=await se.getFirstDirFileNameContent(n)}return r.debug("Loading Admin user for ca "+i),this._user=await se.getCAUser("admin",l,c,i,{hsm:o}),this._user}async initialize(...t){const{log:e,ctx:r}=await this.logCtx(t,this.initialize,!0),[i]=t;if(!i)throw new Y("Missing Fabric CA configuration");const{url:s,tls:n,caName:a}=i;e.info(`Initializing CA Client for CA ${i.caName} at ${i.url}`);const{trustedRoots:o,verify:c}=n,l=o[0];e.debug(`Retrieving CA certificate from ${l}. cwd: ${process.cwd()}`);const d=await se.getFileContent(l);e.debug("CA Certificate: "+d.toString());const h=new bt(s,{trustedRoots:Buffer.from(d),verify:c},a),u=await this.getUser(i,r);return e.debug("CA user loaded: "+u.getName()),{config:i,client:h}}async getCertificates(t,e=!0,...r){t instanceof l?(r=[t],e=!0,t=void 0):"boolean"==typeof t?(e=t,t=void 0):"boolean"!=typeof e&&(r=[e,...r],e=!0);const{log:i}=await this.logCtx(r,this.getCertificates,!0);i.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.config.caName}`);const s=(await this.certificates.getCertificates(t||{},this.user)).result;return i.verbose(`Found ${s.certs.length} certificates`),i.debug(s.certs),e?s.certs.map(t=>t.PEM):s}async getIdentities(t){const e=t.logger.for(this.getIdentities);e.verbose("Retrieving Identities under CA "+this.config.caName);const r=(await this.identities.getAll(this.user)).result;return e.verbose(`Found ${r.identities.length} Identities`),e.debug(r.identities),r.identities}async getAffiliations(t){const e=t.logger.for(this.getAffiliations);e.verbose("Retrieving Affiliations under CA "+this.config.caName);const r=(await this.affiliations.getAll(this.user)).result;return e.verbose(`Found ${r.a.length} Affiliations`),e.debug(JSON.stringify(r)),r}parseError(t){const e=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(t.message);if(!e)return new me(t);const[,r,i]=e;switch(r){case"74":case"71":return new V(i);case"20":return new g(i);default:return new me(i)}}async read(t,...e){const{log:r}=await this.logCtx(e,this.read,!0);let i;r.verbose("Retrieving identity with enrollment ID "+t);try{i=await this.identities.getOne(t,this.user)}catch(e){throw new J(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new J(`Couldn't find enrollment with id ${t}: ${i.errors.join("\n")}`);return i.result}async register(t,e=!1,r="",i,s,n,...a){const{log:o}=await this.logCtx(a,this.register,!0);let c;try{const{userName:a,password:l}=t,d={enrollmentID:a,enrollmentSecret:l,affiliation:r,userRole:i,attrs:s,maxEnrollments:n};c=await this.client.register(d,this.user),o.info(`Registration for ${a} created with user type ${i??"Undefined Role"} ${e?"as super user":""}`)}catch(t){throw this.parseError(t)}return c}static identityFromEnrollment(t,e,r){const i=r.logger.for(this.identityFromEnrollment),{certificate:s,key:n,rootCertificate:a}=t;i.verbose(`Generating Identity from certificate ${s} in msp ${e}`);const o=ue.fabricIdFromCertificate(s),c=ue.encode(o);return i.debug(`Identity ${o} and encodedId ${c}`),new ie({id:c,credentials:{id:c,certificate:s,privateKey:n.toBytes(),rootCertificate:a},mspId:e})}async enroll(t,e,...r){const{log:i,ctx:s}=await this.logCtx(r,this.enroll,!0);let n;try{i.debug("Enrolling "+t);const r=await this.client.enroll({enrollmentID:t,enrollmentSecret:e});n=er.identityFromEnrollment(r,this.config.caName,s),i.info(`Successfully enrolled ${t} under ${this.config.caName} as ${n.id}`)}catch(t){throw this.parseError(t)}return n}async registerAndEnroll(t,e=!1,r="",i,s,n,...a){const{ctx:o}=await this.logCtx(a,this.registerAndEnroll,!0),c=await this.register(t,e,r,i,s,n,o),{userName:l}=t;return this.enroll(l,c,o)}async revoke(t,...e){const{log:r}=await this.logCtx(e,this.revoke,!0);r.verbose("Revoking identity with enrollment ID "+t);const i=await this.read(t);if(!i)throw new J("Could not find enrollment with id "+t);let s;try{s=await this.client.revoke({enrollmentID:i.id,reason:"User Deletion"},this.user)}catch(e){throw new Y(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new Y(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}const rr=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60}),ir=new Ct("fabric-fs");async function sr(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}async function nr(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await p(import("fs"));return await e.readFile(t)})(t)}async function ar(t,e,r,i){ir.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const s=new Rt(t),n=Rt.newCryptoSuite();s.setCryptoSuite(n);const a=n.createKeyFromRaw(e);return await s.setEnrollment(a,r,i),s}async function or(t,e){const r=await sr(e,async t=>{const{promises:e}=await p(import("fs")),r=await cr(t);return await e.readFile(r)});return{mspId:t,credentials:r}}async function cr(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path"));return r(t,(await e.readdir(t))[0])}async function lr(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}async function dr(t){const e=await sr(t,async t=>{const{promises:e}=await p(import("fs")),r=await cr(t);return await e.readFile(r)}),r=await hr(e),i=r[Object.getOwnPropertySymbols(r)[0]];return It.newPrivateKeySigner(i)}async function hr(t){let e;if(At())e=globalThis.crypto.subtle;else{const t=await p(import("crypto"));e=t.subtle||t.webcrypto.subtle}if(!e)throw Error("Could not load SubtleCrypto module");const r=t.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),i=(t=>{const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e})(Buffer.from(r,"base64").toString("binary"));try{return await e.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}catch(t){throw new Y(t)}}class ur{static#t=null;static#e=!1;constructor(t){if(ur.#t||(ur.#t=new Pt.PKCS11,ur.#t.load(this.findHSMPKCS11Lib(t))),!ur.#e){try{ur.#t.C_Initialize()}catch(t){if(t.code!==Pt.CKR_CRYPTOKI_ALREADY_INITIALIZED)throw t}ur.#e=!0}}findHSMPKCS11Lib(t){const e=["/usr/lib/softhsm/libsofthsm2.so","/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so","/usr/local/lib/softhsm/libsofthsm2.so","/usr/lib/libacsp-pkcs11.so","/opt/homebrew/lib/softhsm/libsofthsm2.so"];t&&e.push(t);for(const t of e)if(jt.existsSync(t))return t;throw new Ce("Unable to find PKCS11 library")}dispose(){ur.#t.C_Finalize()}sanitizeOptions(t){const e=Object.assign({userType:Pt.CKU_USER},t);return this.assertNotEmpty(e.label,"label"),this.assertNotEmpty(e.pin,"pin"),this.assertNotEmpty(e.identifier,"identifier"),e}assertNotEmpty(t,e){if(!t||0===t.toString().trim().length)throw Error(e+" property must be provided")}findSlotForLabel(t){const e=ur.#t.C_GetSlotList(!0);if(0===e.length)throw Error("No pkcs11 slots can be found");const r=e.find(e=>ur.#t.C_GetTokenInfo(e).label.trim()===t);if(!r)throw Error(`label ${t} cannot be found in the pkcs11 slot list`);return r}login(t,e,r){try{ur.#t.C_Login(t,e,r)}catch(t){if(t.code!==Pt.CKR_USER_ALREADY_LOGGED_IN)throw t}}findObjectInHSM(t,e,r){const i=[{type:Pt.CKA_ID,value:r},{type:Pt.CKA_CLASS,value:e},{type:Pt.CKA_KEY_TYPE,value:Pt.CKK_EC}];ur.#t.C_FindObjectsInit(t,i);const s=ur.#t.C_FindObjects(t,1)[0];if(!s)throw ur.#t.C_FindObjectsFinal(t),Error("Unable to find object in HSM with ID "+r.toString());return ur.#t.C_FindObjectsFinal(t),s}newSigner(t){const e=this.sanitizeOptions(t),r=ur.#t,i=this.findSlotForLabel(e.label),s=r.C_OpenSession(i,Pt.CKF_SERIAL_SESSION);let n;try{this.login(s,e.userType,e.pin),n=this.findObjectInHSM(s,Pt.CKO_PRIVATE_KEY,e.identifier)}catch(t){throw ur.#t.C_CloseSession(s),t}return{signer:async t=>{ur.#t.C_SignInit(s,{mechanism:Pt.CKM_ECDSA},n);const e=await ur.#t.C_SignAsync(s,Buffer.from(t),Buffer.alloc(2*Lt.Point.Fn.BYTES));return Lt.Signature.fromBytes(e,"compact").normalizeS().toBytes("der")},close:()=>{ur.#t.C_CloseSession(s)}}}assertDefined(t){if(void 0===t)throw Error("required value was undefined");return t}getUncompressedPointOnCurve(t){const e=t.export({format:"jwk"}),r=Buffer.from(this.assertDefined(e.x),"base64url"),i=Buffer.from(this.assertDefined(e.y),"base64url"),s=Buffer.from("04","hex");return Buffer.concat([s,r,i])}getSKIFromCertificatePath(t){const e=t.endsWith(".pem")?t:Kt.join(t,"cert.pem"),r=jt.readFileSync(e);return this.getSKIFromCertificate(r)}getSKIFromCertificate(t){const e=new $t.X509Certificate(t),r=this.getUncompressedPointOnCurve(e.publicKey);return $t.createHash("sha256").update(r).digest()}}class pr extends A{constructor(t,e){super(t,e)}squash(t){const r=super.squash(t);if(!r)return r;const{method:i,params:s,args:n}=r,{direction:a,limit:o}=s;switch(i){case e.FIND_BY:break;case e.LIST_BY:n.push(a);break;case e.PAGE_BY:n.push(a,o);break;case e.FIND_ONE_BY:break;default:throw new Y("Unsupported method "+i)}return r}async executePrepared(...e){const r=t.forModel(this.fromSelector,this.adapter.alias),{method:i,args:s}=this.prepared;return r.statement(i,...s,...e)}async prepare(t){if(t=t||await this.adapter.context(r.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],i={},s={class:this.fromSelector,args:e,params:i},n=[v.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);n.push(r.method),r.args&&r.args.length&&e.push(...r.args)}return this.selectSelector&&n.push(v.SELECT,this.selectSelector.join(` ${v.AND.toLowerCase()} `)),this.orderBySelector&&(n.push(v.ORDER_BY,this.orderBySelector[0]),e.push(this.orderBySelector[1])),s.method=xt(n.join(" ")),s.params=i,this.prepared=s,this}build(){throw new b("This method is only called is prepared statements are not used. If so, a dedicated implementation for the native queries used is required")}parseCondition(t,...e){throw new b("This method is only called is prepared statements are not used. Is so, a dedicated implementation for the native queries used is required")}}class gr extends i{constructor(t,e,r,i){super(t,e,r,i)}prepare(t){throw new b("Raw query access must be implemented by a subclass. only prepared statements are natively available")}page(t=1,...e){return super.page(t,...e)}}var fr;class mr extends S{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new Yt}static{this.log=St.for(mr)}constructor(t,e){super(t,re,e),this.serializer=mr.serializer}Statement(t){return new pr(this,t)}Paginator(t,e,r){return new gr(this,t,e,r)}async flags(t,e,r,...i){return Object.assign(await super.flags(t,e,Object.assign({},this.config,r),...i))}decode(t){return mr.decoder.decode(t)}repository(){return zt}createPrefix(t,e,r,...i){const{ctxArgs:s}=this.logCtx(i,this.createPrefix),n=$.tableName(t),a={};return a[ct.TABLE]=n,Object.assign(a,r),[t,e,a,...s]}createAllPrefix(t,e,r,...i){const s=$.tableName(t);if(e.length!==r.length)throw new Y("Ids and models must have the same length");const{ctxArgs:n}=this.logCtx(i,this.createAllPrefix),a=e.map((t,e)=>{const i={};return i[ct.TABLE]=s,Object.assign(i,r[e]),i});return[t,e,a,...n]}updateAllPrefix(t,e,r,...i){const s=$.tableName(t);if(e.length!==r.length)throw new Y("Ids and models must have the same length");const{ctxArgs:n}=this.logCtx(i,this.updateAllPrefix),a=e.map(()=>{const t={};return t[ct.TABLE]=s,t});return[t,e,a,...n]}async createAll(t,e,r,...i){if(e.length!==r.length)throw new Y("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.createAll),c=$.tableName(t);a.info(`adding ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=await this.submitTransaction(o,at.CREATE_ALL,[JSON.stringify(r.map(e=>this.serializer.serialize(e,t.name)))],n,void 0,t.name);try{return JSON.parse(this.decode(l)).map(t=>JSON.parse(t))}catch(t){throw new U(t)}}async readAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.readAll),n=$.tableName(t);i.info(`reading ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.evaluateTransaction(s,at.READ_ALL,[JSON.stringify(e)],void 0,void 0,t.name);try{return JSON.parse(this.decode(a)).map(t=>JSON.parse(t))}catch(t){throw new U(t)}}async updateAll(t,e,r,...i){if(e.length!==r.length)throw new Y("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.updateAll),c=$.tableName(t);a.info(`updating ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=await this.submitTransaction(o,at.UPDATE_ALL,[JSON.stringify(r.map(e=>this.serializer.serialize(e,t.name)))],n,void 0,t.name);try{return JSON.parse(this.decode(l)).map(t=>JSON.parse(t))}catch(t){throw new U(t)}}async deleteAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.deleteAll),n=$.tableName(t);i.info(`deleting ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.submitTransaction(s,at.DELETE_ALL,[JSON.stringify(e)],void 0,void 0,t.name);try{return JSON.parse(this.decode(a)).map(t=>JSON.parse(t))}catch(t){throw new U(t)}}prepare(t,...e){const{log:i}=this.logCtx(e,this.prepare),s=$.segregate(t);return t[r.METADATA]&&(i.silly("Passing along persistence metadata for "+t[r.METADATA]),Object.defineProperty(s.model,r.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:t[r.METADATA]})),{record:s.model,model:s.model,id:t[$.pk(t.constructor)],transient:s.transient,private:s.private,shared:s.shared}}revert(t,e,r,i,...s){const{log:n}=this.logCtx(s,this.revert);return i&&(n.verbose("re-adding transient properties: "+Object.keys(i).join(", ")),Object.entries(i).forEach(([r,i])=>{if(r in t)throw new Y(`Transient property ${r} already exists on model ${"string"==typeof e?e:e.name}. should be impossible`);t[r]=i})),new e(t)}async create(t,e,r,i={},...s){const n=[...s],{log:a,ctx:o}=this.logCtx(n,this.create),c=$.tableName(t);a.verbose(`adding entry to ${c} table`),a.debug("pk: "+e);const l=await this.submitTransaction(o,L.CREATE,[this.serializer.serialize(r,t.name)],i,void 0,t.name);return this.serializer.deserialize(this.decode(l))}async read(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.readAll),n=$.tableName(t);i.verbose(`reading entry from ${n} table`),i.debug("pk: "+e);const a=await this.evaluateTransaction(s,L.READ,[e.toString()],void 0,void 0,t.name);return this.serializer.deserialize(this.decode(a))}updatePrefix(t,e,r,...i){const s=$.tableName(t),{ctxArgs:n}=this.logCtx(i,this.updatePrefix),a={};return a[ct.TABLE]=s,Object.assign(a,r),[t,e,a,...n]}async update(t,e,r,i={},...s){const n=[...s],{log:a,ctx:o}=this.logCtx(n,this.updateAll);a.info("CLIENT UPDATE class : "+typeof t);const c=$.tableName(t);a.verbose(`updating entry to ${c} table`),a.debug("pk: "+e);const l=await this.submitTransaction(o,L.UPDATE,[this.serializer.serialize(r,t.name||t)],i,void 0,t.name);return this.serializer.deserialize(this.decode(l))}async delete(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.delete),n=$.tableName(t);i.verbose(`deleting entry from ${n} table`),i.debug("pk: "+e);const a=await this.submitTransaction(s,L.DELETE,[e.toString()],void 0,void 0,t.name);return this.serializer.deserialize(this.decode(a))}async raw(t,e=!0,r,...i){const{log:s,ctx:n}=this.logCtx(i,this.raw),a=r.name;let o,c;s.info("Performing raw statement on table "+$.tableName(r));try{o=await this.evaluateTransaction(n,"raw",[JSON.stringify(t),e],void 0,void 0,a)}catch(t){throw this.parseError(t)}try{c=JSON.parse(this.decode(o))}catch(t){throw new U("Failed to process result: "+t)}if(Array.isArray(c)){if(!c.length)return c;const t=c[0];return $.isModel(t)?c.map(t=>$.build(t)):c}return l=c,$.isModel(l)?$.build(l):l;var l}getClient(){return this._client||(this._client=mr.getClient(this.config)),this._client}async Gateway(t){return mr.getGateway(t,this.config,this.client)}getContractName(t){if(t)return t+"Contract"}async Contract(t,e){return mr.getContract(await this.Gateway(t),this.config,e)}async transaction(t,e,r=!0,i,s,n,a){const o=this.log.for(this.transaction),c=await this.Gateway(t);try{const c=await this.Contract(t,this.getContractName(a));o.verbose(`${r?"Submit":"Evaluate"}ting transaction ${this.getContractName(a)||this.config.contractName}.${e}`),o.debug("args: "+(i?.map(t=>t.toString()).join("\n")||"none"));const l=r?c.submit:c.evaluate;n=n?.length?n:void 0;const d={arguments:i||[],transientData:s};return await l.call(c,e,d)}catch(t){if(10===t.code)throw Error(""+t.details[0].message);throw this.parseError(t)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}parseError(t){return mr.parseError(t)}async submitTransaction(t,e,r,i,s,n){return this.transaction(t,e,!0,r,i,s,n)}async evaluateTransaction(t,e,r,i,s,n){return this.transaction(t,e,!1,r,i,s,n)}async close(){this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static getContract(t,e,r){const i=this.log.for(this.getContract),s=this.getNetwork(t,e.channel);let n;try{i.debug(`Retrieving chaincode ${e.chaincodeName} contract ${r||e.contractName} from network ${e.channel}`),r=r||e.contractName,n=s.getContract(e.chaincodeName,r)}catch(t){throw this.parseError(t)}return n}static getNetwork(t,e){const r=St.for(this.getNetwork);let i;try{r.debug("Connecting to channel "+e),i=t.getNetwork(e)}catch(t){throw this.parseError(t)}return i}static async getGateway(t,e,r){return await this.getConnection(r||await this.getClient(e),e,t)}static getClient(t){const e=this.log.for(this.getClient);e.debug("generating TLS credentials for msp "+t.mspId);let r=t.tlsCert;if("string"==typeof r)if(r.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms))r=Buffer.from(r,"utf8");else try{r=Buffer.from(jt.readFileSync(r,"utf8"))}catch(t){throw new Y(`Failed to read the tls certificate from ${r}: ${t}`)}const i=Bt.credentials.createSsl(r);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new _t(t.peerEndpoint,i,{"grpc.max_receive_message_length":1024*(t.sizeLimit||15)*1024,"grpc.max_send_message_length":1024*(t.sizeLimit||15)*1024})}static async getConnection(t,e,r){const i=St.for(this.getConnection);i.debug(`Retrieving Peer Identity for ${e.mspId} under ${e.certCertOrDirectoryPath}`);const s=await or(e.mspId,e.certCertOrDirectoryPath);i.debug("Retrieving signer key from "+e.keyCertOrDirectoryPath);let n,a=()=>{};if(e.hsm){const t=new ur(e.hsm.library),r=t.getSKIFromCertificatePath(e.certCertOrDirectoryPath),i=t.newSigner({label:e.hsm.tokenLabel,pin:e.hsm.pin+"",identifier:r});n=i.signer,a=i.close}else n=await dr(e.keyCertOrDirectoryPath);const o={client:t,identity:s,signer:n,evaluateOptions:()=>({deadline:Date.now()+1e3*r.get("evaluateTimeout")}),endorseOptions:()=>({deadline:Date.now()+1e3*r.get("endorseTimeout")}),submitOptions:()=>({deadline:Date.now()+1e3*r.get("submitTimeout")}),commitStatusOptions:()=>({deadline:Date.now()+1e3*r.get("commitTimeout")})};i.debug("Connecting to "+e.mspId);const c=Ot(o);return e.hsm&&(c.close=new Proxy(c.close,{apply(t,e,r){Reflect.apply(t,e,r),a()}})),c}Dispatch(){return new mr._baseDispatch}static parseError(t){const e="string"==typeof t?t:t.message;return e.includes("MVCC_READ_CONFLICT")?new ve(t):e.includes("ENDORSEMENT_POLICY_FAILURE")?new Ee(t):e.includes("PHANTOM_READ_CONFLICT")?new Se(t):t instanceof Error&&t.code&&9===t.code?new Ae(t):e.includes(J.name)?new J(t):e.includes(V.name)?new V(t):e.includes(ot.name)?new ot(t):e.includes(E.name)?new E(t):e.includes(x.name)?new x(t):e.includes(b.name)?new b(t):e.includes(N.name)?new N(t):e.includes(T.name)?new T(t):e.includes(g.name)?new g(t):e.includes(I.name)?new I(t):e.includes(O.name)?new O(t):e.includes(U.name)?new U(t):new Y(t)}}lt([Nt(),Tt(),dt("design:type",Function),dt("design:paramtypes",[Object,Object,Object,Object,l]),dt("design:returntype",Promise)],mr.prototype,"create",null),lt([Nt(),Tt(),dt("design:type",Function),dt("design:paramtypes",[Object,Object,l]),dt("design:returntype",Promise)],mr.prototype,"read",null),lt([Nt(),Tt(),dt("design:type",Function),dt("design:paramtypes",[Object,Object,Object,Object,l]),dt("design:returntype",Promise)],mr.prototype,"update",null),lt([Nt(),Tt(),dt("design:type",Function),dt("design:paramtypes",[Object,Object,l]),dt("design:returntype",Promise)],mr.prototype,"delete",null),lt([Nt(),dt("design:type",Function),dt("design:paramtypes",[Object,"function"==typeof(fr="undefined"!=typeof D&&D)?fr:Object,Object,l]),dt("design:returntype",Promise)],mr.prototype,"raw",null),mr.decoration(),S.setCurrent(re);class yr extends R{constructor(t){super(),this.client=t,this.decoder=new TextDecoder("utf8")}async close(){this.listeningStack&&this.listeningStack.close()}parsePayload(t){const e=this.decoder.decode(t);return JSON.parse(e)}observe(t){if(!(t instanceof mr))throw new b("Only FabricClientAdapter can be observed by dispatch");return super.observe(t),()=>this.unObserve(t)}async updateObservers(t,e,r,...i){const{log:s,ctxArgs:n}=S.logCtx(this.updateObservers,e,!1,...i);if(this.adapter)try{await this.adapter.refresh(t,e,r,...n)}catch(t){throw new Y("Failed to refresh dispatch: "+t)}else s.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof t?t:$.tableName(t)}:${e}`)}async handleEvents(t){if(!this.listeningStack)throw new Y('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new Y("No adapter found. should be impossible");const e=t||await this.adapter.context(L.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||$),r=this.log.for(this.handleEvents);r.info(`Listening for incoming events on chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}"...`);try{for await(const t of this.listeningStack){const{table:i,event:s,owner:n}=We(t.eventName);if(n&&n!==this.adapter.config?.mspId)continue;const a=this.parsePayload(t.payload);try{const t=(i?$.get(i):$.get(this.models[0].name))??(i||this.models[0]?.name);await this.updateObservers(t,s,a.id,e)}catch(t){r.error(`Failed update observables for table ${i} event ${s} id: ${a.id}: ${t}`)}}}catch(t){r.error(`Failed to read event for chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}": ${t}`),await this.close()}}async initialize(){if(!this.adapter)throw new Y("No adapter or config observed for dispatch");const t=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},$),{ctx:e}=this.logCtx([t],this.initialize),r=(await mr.getGateway(e,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new Y("No adapter observed for dispatch");this.listeningStack=await r.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(e)}}mr&&(mr._baseDispatch=yr);const wr="##VERSION##",br="##PACKAGE##";ht.registerLibrary(br,wr);export{fe as AllowanceError,ae as BASE_ALPHABET,ge as BalanceError,he as BaseEncoder,oe as CRYPTO,Yt as ClientSerializer,se as CoreUtils,ue as CryptoUtils,rr as DefaultFabricClientFlags,Je as DeterministicSerializer,de as ERC20Events,Ae as EndorsementError,Ee as EndorsementPolicyError,Te as FabricBaseModel,mr as FabricClientAdapter,yr as FabricClientDispatch,zt as FabricClientRepository,Gt as FabricERC20ClientRepository,xe as FabricEnrollmentService,re as FabricFlavour,Ie as FabricIdentifiedBaseModel,er as FabricIdentityService,te as FabricModelKeys,le as HFCAIdentityAttributes,ce as HFCAIdentityType,ie as Identity,Zt as IdentityCredentials,ee as IdentityType,Le as ImplicitPrivateCollection,ye as MissingContextError,Ce as MissingPKCSS11Lib,Ke as ModelCollection,ve as MvccReadConflictError,be as NotInitializedError,pe as OverflowError,Oe as Owner,br as PACKAGE_NAME,Se as PhantomReadConflictError,me as RegistrationError,Ne as RegistrationRequestBuilder,tr as SimpleDeterministicSerializer,we as UnauthorizedPrivateDataAccess,wr as VERSION,Xe as add,sr as contentOfLoadFile,Be as createMirrorHandler,Pe as deleteMirrorHandler,De as evalMirrorMetadata,hr as extractPrivateKey,qe as generateFabricEventName,qt as generateModelIndexes,ar as getCAUser,cr as getFirstDirFileName,lr as getFirstDirFileNameContent,or as getIdentity,dr as getSigner,je as mirror,$e as ownedBy,Re as ownedByOnCreate,We as parseEventName,Ge as privateData,nr as readFile,Wt as readModelFile,Xt as readModelFolders,Ze as safeParseInt,ze as segregatedDataOnCreate,Ue as segregatedDataOnDelete,Me as segregatedDataOnRead,He as segregatedDataOnUpdate,Ve as sharedData,Qe as sub,Fe as transactionId,ke as transactionIdOnCreate,_e as updateMirrorHandler,Qt as writeIndexes};
1
+ import{Repository as t,PreparedStatementKeys as e,PersistenceKeys as r,Paginator as i,pk as s,column as n,table as a,BaseModel as o,Sequence as c,Context as l,oneToOne as d,Cascade as h,index as u,normalizeImport as p,AuthorizationError as g,createdAt as f,updatedAt as m,createdBy as y,updatedBy as w,UnsupportedError as b,ClientBasedService as A,Statement as C,QueryClause as v,Adapter as E,QueryError as S,PagingError as x,MigrationError as N,ObserverError as I,ForbiddenError as T,ConnectionError as O,Dispatch as R}from"@decaf-ts/core";import{Model as $,required as k,model as F,JSONSerializer as B,ModelKeys as _,stringFormat as P,minlength as j,min as K}from"@decaf-ts/decorator-validation";import{OperationKeys as L,enforceDBDecorators as z,reduceErrorsToPrint as M,ValidationError as H,SerializationError as U,InternalError as Y,BaseError as G,ConflictError as V,NotFoundError as J,version as q,DBKeys as W,readonly as X,onCreate as Q,onUpdate as Z,afterCreate as tt,afterUpdate as et,afterDelete as rt,transient as it,onRead as st,onDelete as nt,BulkCrudOperationKeys as at,BadRequestError as ot}from"@decaf-ts/db-decorators";import{CouchDBKeys as ct}from"@decaf-ts/for-couchdb";import{__decorate as lt,__metadata as dt}from"tslib";import{Metadata as ht,description as ut,uses as pt,Decoration as gt,apply as ft,propMetadata as mt,metadata as yt,prop as wt}from"@decaf-ts/decoration";import bt from"fabric-ca-client";import{MiniLogger as At,isBrowser as Ct,LoggedClass as vt,Logging as Et,toPascalCase as St,toCamelCase as xt,debug as Nt,final as It}from"@decaf-ts/logging";import{signers as Tt,connect as Ot}from"@hyperledger/fabric-gateway";import{User as Rt}from"fabric-common";import $t,{X509Certificate as kt}from"crypto";import*as Ft from"@peculiar/x509";import{Crypto as Dt}from"@peculiar/webcrypto";import*as Bt from"@grpc/grpc-js";import{Client as _t}from"@grpc/grpc-js";import Pt from"pkcs11js";import jt from"fs";import Kt from"path";import{p256 as Lt}from"@noble/curves/nist";class zt extends t{constructor(t,e){super(t,e),this._overrides=Object.assign({},super._overrides,{ignoreValidation:!0,ignoreHandlers:!0,allowRawStatements:!1,forcePrepareSimpleQueries:!0,forcePrepareComplexQueries:!0,allowGenerationOverride:!1})}async paginateBy(t,r,i={offset:1,limit:10},...s){const{log:n,ctxArgs:a}=(await this.logCtx(s,e.PAGE_BY,!0)).for(this.paginateBy);return n.verbose(`paginating ${$.tableName(this.class)} with page size ${i.limit}`),this.statement(this.paginateBy.name,t,r,{limit:i.limit,offset:i.offset,bookmark:i.bookmark},...a)}async listBy(t,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,e.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${$.tableName(this.class)} by ${t} ${r}`),await this.statement(this.listBy.name,t,r,...n)}async findBy(t,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,e.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding all ${$.tableName(this.class)} with ${t} ${r}`),await this.statement(this.findBy.name,t,r,...n)}async findOneBy(t,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,e.FIND_ONE_BY,!0)).for(this.findOneBy);return s.verbose(`finding One ${$.tableName(this.class)} with ${t} ${r}`),await this.statement(this.findOneBy.name,t,r,...n)}async statement(t,...e){const{log:s,ctx:n,ctxArgs:a}=(await this.logCtx(e,r.STATEMENT,!0)).for(this.statement);s.verbose("Executing prepared statement "+t);const o=a.slice(0,-1),c=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(n,r.STATEMENT,[t,JSON.stringify(o)],void 0,void 0,this.class.name)));return Array.isArray(c)?c.map(t=>t[ct.TABLE]&&t[ct.TABLE]===$.tableName(this.class)?new this.class(t):t):c[ct.TABLE]&&c[ct.TABLE]===$.tableName(this.class)?new this.class(c):i.isSerializedPage(c)?Object.assign(c,{data:c.data.map(t=>new this.class(t))}):c}async create(t,...e){const{ctx:r,log:i,ctxArgs:s}=this.logCtx(e,this.create);i.debug(`Creating new ${this.class.name} in table ${$.tableName(this.class)}`);let{record:n,id:a,transient:o}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,a,n,o,...s),this.adapter.revert(n,this.class,a,o,r)}async update(t,...e){const{ctxArgs:r,log:i,ctx:s}=this.logCtx(e,this.update);let{record:n,id:a,transient:o}=this.adapter.prepare(t,s);return i.debug(`updating ${this.class.name} in table ${$.tableName(this.class)} with id ${a}`),n=await this.adapter.update(this.class,a,n,o,...r),this.adapter.revert(n,this.class,a,o,s)}async createAllPrefix(t,...e){const{ctx:r,ctxArgs:i}=(await this.logCtx(e,L.CREATE,!0)).for(this.createAllPrefix),s=r.get("ignoreHandlers"),n=r.get("ignoreValidation");if(!t.length)return[t,...i];if(t=await Promise.all(t.map(async t=>(t=new this.class(t),s||await z(this,r,t,L.CREATE,L.ON),t))),!n){const e=r.get("ignoredValidationProperties")||[],i=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),s=M(i);if(s)throw new H(s)}return[t,...i]}async createAll(t,...e){if(!t.length)return t;const{ctx:r,log:i,ctxArgs:s}=this.logCtx(e,this.createAll);i.debug(`Creating ${t.length} new ${this.class.name} in table ${$.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r)),a=n.map(t=>t.id);let o=n.map(t=>t.record);const c=n.map(t=>t.transient);return o=await this.adapter.createAll(this.class,a,o,c,...s),o.map((t,e)=>this.adapter.revert(t,this.class,a[e],r.get("rebuildWithTransient")?n[e].transient:void 0,r))}async updateAll(t,...e){const{ctx:r,log:i,ctxArgs:s}=this.logCtx(e,this.updateAll);i.debug(`Updating ${t.length} new ${this.class.name} in table ${$.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r));return(await this.adapter.updateAll(this.class,n.map(t=>t.id),n.map(t=>t.record),n.map(t=>t.transient),...s)).map((t,e)=>this.adapter.revert(t,this.class,n[e].id,r.get("rebuildWithTransient")?n[e].transient:void 0,r))}}let Mt=class extends o{constructor(t){super(t)}};lt([s({type:String}),dt("design:type",String)],Mt.prototype,"name",void 0),lt([n(),k(),dt("design:type",String)],Mt.prototype,"owner",void 0),lt([n(),k(),dt("design:type",String)],Mt.prototype,"symbol",void 0),lt([n(),k(),dt("design:type",Number)],Mt.prototype,"decimals",void 0),Mt=lt([a("erc20_tokens"),F(),dt("design:paramtypes",[Object])],Mt);let Ht=class extends o{constructor(t){super(t)}};lt([s({type:String}),dt("design:type",String)],Ht.prototype,"id",void 0),lt([n(),k(),dt("design:type",String)],Ht.prototype,"token",void 0),lt([n(),k(),dt("design:type",Number)],Ht.prototype,"balance",void 0),lt([n(),dt("design:type",String)],Ht.prototype,"captive",void 0),Ht=lt([a("erc20_wallets"),F(),dt("design:paramtypes",[Object])],Ht);let Ut=class extends o{constructor(t){super(t)}};lt([s({type:String}),n(),k(),dt("design:type",String)],Ut.prototype,"owner",void 0),lt([n(),k(),dt("design:type",String)],Ut.prototype,"spender",void 0),lt([n(),k(),dt("design:type",Number)],Ut.prototype,"value",void 0),Ut=lt([a("erc20_allowances"),F(),dt("design:paramtypes",[Object])],Ut);class Yt extends B{constructor(){super()}preSerialize(t,e){const r=Object.assign({},t);let i=ht.modelName(t.constructor);if(!i||"Object"===i){if(!e)throw new U("Could not find metadata for "+t.constructor.name);i=e}return r[_.ANCHOR]=i,r}deserialize(t){const e=JSON.parse(t),r=e[_.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return $.build(e,r)}serialize(t,e){return JSON.stringify(this.preSerialize(t,e))}}class Gt extends zt{static{this.serializer=new Yt}static{this.decoder=new TextDecoder("utf8")}async updateObservers(t,e,r,...i){if(!this.observerHandler)throw new Y("ObserverHandler not initialized. Did you register any observables?");const{log:s,ctxArgs:n}=this.logCtx(i,this.updateObservers);let a;s.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),t="string"==typeof t?$.get(t):t,a=void 0===r?void 0:Array.isArray(r)?r.map(e=>c.parseValue($.sequenceFor(t).type,e)):c.parseValue($.sequenceFor(t).type,r),await this.observerHandler.updateObservers(t,e,a,...n)}decode(t){return Gt.decoder.decode(t)}constructor(t){super(t,Ht),this.serializer=Gt.serializer}async tokenName(...t){const{ctx:e}=(await this.logCtx(t,"tokenName",!0)).for(this.tokenName),r=await this.adapter.evaluateTransaction(e,"TokenName");return this.decode(r)}async symbol(...t){const{ctx:e}=(await this.logCtx(t,"symbol",!0)).for(this.symbol),r=await this.adapter.evaluateTransaction(e,"Symbol");return this.decode(r)}async decimals(...t){const{ctx:e}=(await this.logCtx(t,"decimals",!0)).for(this.decimals),r=await this.adapter.evaluateTransaction(e,"Decimals");return Number(this.decode(r))}async totalSupply(...t){const{ctx:e}=(await this.logCtx(t,"totalSupply",!0)).for(this.totalSupply),r=await this.adapter.evaluateTransaction(e,"TotalSupply");return Number(this.decode(r))}async balanceOf(t,...e){const{ctx:r}=(await this.logCtx(e,"balance",!0)).for(this.balanceOf),i=await this.adapter.evaluateTransaction(r,"BalanceOf",[t]);return Number(this.decode(i))}async transfer(t,e,...r){const{ctx:i}=(await this.logCtx(r,"transfer",!0)).for(this.transfer),s=await this.adapter.submitTransaction(i,"Transfer",[t,e.toString()]);return"true"===this.decode(s)}async transferFrom(t,e,r){const i=await l.args("transferFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:s}=this.logCtx(i.args,this.transferFrom),n=await this.adapter.submitTransaction(s,"TransferFrom",[t,e,r.toString()]);return"true"===this.decode(n)}async approve(t,e){const r=await l.args("approve",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.approve),s=await this.adapter.submitTransaction(i,"Approve",[t,e.toString()]);return"true"===this.decode(s)}async allowance(t,e){const r=await l.args("allowance",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.allowance),s=await this.adapter.submitTransaction(i,"Allowance",[t,e]);return Number(this.decode(s))}async initialize(t){const e=await l.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.initialize),i=await this.adapter.submitTransaction(r,"Initialize",[Gt.serializer.serialize(t)]);return"true"===this.decode(i)}async checkInitialized(){const t=await l.args("checkInitialized",this.class,[],this.adapter,this._overrides||{}),{ctx:e}=this.logCtx(t.args,this.checkInitialized);await this.adapter.evaluateTransaction(e,"CheckInitialized")}async mint(t){const e=await l.args("mint",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.mint);await this.adapter.submitTransaction(r,"Mint",[t.toString()])}async burn(t){const e=await l.args("burn",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.burn);await this.adapter.submitTransaction(r,"Burn",[t.toString()])}async burnFrom(t,e){const r=await l.args("burnFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.burnFrom);await this.adapter.submitTransaction(i,"BurnFrom",[t,e.toString()])}async clientAccountBalance(){const t=await l.args("accountBalance",this.class,[],this.adapter,this._overrides||{}),{ctx:e}=this.logCtx(t.args,this.clientAccountBalance),r=await this.adapter.evaluateTransaction(e,"ClientAccountBalance");return Number(this.decode(r))}async clientAccountID(){const t=await l.args("accountId",this.class,[],this.adapter,this._overrides||{}),{ctx:e}=this.logCtx(t.args,this.clientAccountID),r=await this.adapter.evaluateTransaction(e,"ClientAccountID");return this.decode(r)}}function Vt(t,e,r){return[...t.map(t=>t===ct.TABLE?"table":t),...r||[],...e?[e]:[],"index"].join(ht.splitter)}function Jt(t,e,r,i){const s=e.pop();s&&s!==ct.TABLE?e.push(s):s===ct.TABLE&&e.unshift(s);const n=Vt(e,r,i);let a=[...e,...i||[]];r&&(a=a.reduce((t,e)=>{const i={};return i[e]=r,t.push(i),t},[]));const o={index:{fields:a},name:n,ddoc:n,type:"json"};t[n]=o}function qt(t,e){const r=Vt([ct.TABLE]),i=e||{};i[r]={index:{fields:[ct.TABLE]},name:r,ddoc:r,type:"json"};const s={},n=$.indexes(t);for(const t of Object.keys(n))for(const[,e]of Object.entries(n[t])){const r=e.directions,i=e.compositions,n=[t,ct.TABLE];Jt(s,n),i&&i.length&&Jt(s,n,void 0,i),r&&r.length&&r.forEach(t=>{Jt(s,n,t),i&&i.length&&Jt(s,n,t,i)})}return Object.entries(s).forEach(([t,e])=>{i[t]=e}),Object.values(s)}function Wt(t){const e=require("path"),r=require(e.join(process.cwd(),t.parentPath,t.name));return Object.values(r).filter(t=>{try{return new t instanceof $}catch(t){return!1}})}async function Xt(...t){const e=require("fs"),r=[];for(const i of t){const t=e.readdirSync(i,{withFileTypes:!0,recursive:!0}).filter(t=>t.isFile()&&t.name.endsWith("js"));for(const e of t)r.push(...Wt(e))}return r}function Qt(t,e=process.cwd(),r){const i=require("fs"),s=require("path");function n(t){const e=s.dirname(t);if(i.existsSync(e))return!0;n(e),i.mkdirSync(e)}t.forEach(t=>{const a=s.resolve(s.join(e,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}indexes/${t.name}.json`));n(a),i.writeFileSync(a,JSON.stringify(t,void 0,2))})}let Zt=class extends o{constructor(t){super(t)}};var te,ee;lt([ut("Unique identifier of the credentials record"),n(),s(),dt("design:type",String)],Zt.prototype,"id",void 0),lt([ut("PEM-encoded X.509 certificate for the identity"),n(),k(),dt("design:type",String)],Zt.prototype,"certificate",void 0),lt([ut("PEM-encoded root or intermediate certificate"),n(),k(),dt("design:type",String)],Zt.prototype,"rootCertificate",void 0),lt([ut("PEM-encoded private key"),n(),k(),dt("design:type",String)],Zt.prototype,"privateKey",void 0),Zt=lt([F(),dt("design:paramtypes",[Object])],Zt),(t=>{t.PRIVATE="private",t.SHARED="shared",t.FABRIC="fabric",t.OWNED_BY="owned-by",t.TRANSACTION_ID="transaction-id",t.MIRROR="mirror"})(te||(te={})),(t=>{t.X509="X.509"})(ee||(ee={}));const re="hlf-fabric";let ie=class extends o{constructor(t){super(t),this.type=ee.X509}};lt([ut("Unique identifier of the identity"),s(),dt("design:type",String)],ie.prototype,"id",void 0),lt([d(Zt,{update:h.CASCADE,delete:h.CASCADE}),dt("design:type",Zt)],ie.prototype,"credentials",void 0),lt([n(),k(),u(),dt("design:type",String)],ie.prototype,"mspId",void 0),lt([n(),k(),dt("design:type",String)],ie.prototype,"type",void 0),ie=lt([F(),dt("design:paramtypes",[Object])],ie);class se{static{this.logger=new At(se.name)}constructor(){}static async contentOfLoadFile(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}static async readFile(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await p(import("fs"));return await e.readFile(t)})(t)}static async getCAUser(t,e,r,i,s){this.logger.debug(P("Creating CA {0} user {1} with certificate {2}",i,t,r));const n=new Rt(t),a=s?.hsm?{software:!1,lib:s.hsm.library,slot:s.hsm.slot,label:s.hsm.tokenLabel,pin:s.hsm.pin+""}:void 0,o=this.getCryptoSuite(a);n.setCryptoSuite(o);const c=s?.hsm?await this.getHSMEnrollmentKey(o,r,s.hsm):this.getSoftwareEnrollmentKey(o,e);return await n.setEnrollment(c,r,i),n}static getCryptoSuite(t){return t?(se.cryptoSuite||(se.cryptoSuite=Rt.newCryptoSuite(t)),se.cryptoSuite):Rt.newCryptoSuite()}static getSoftwareEnrollmentKey(t,e){if(!e)throw Error("Private key must be provided when HSM configuration is not supplied");return t.createKeyFromRaw(e)}static async getHSMEnrollmentKey(t,e,r){const i=r.keyIdHex&&r.keyIdHex.trim().length>0?Buffer.from(r.keyIdHex,"hex"):await this.getCertificateSKI(e),s=await t.getKey(i);if(!s||"function"==typeof s.isPrivate&&!s.isPrivate())throw Error("Unable to resolve private key from HSM");return s}static async getCertificateSKI(t){const e=new kt(t).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(e.x||"","base64url"),s=Buffer.from(e.y||"","base64url");return $t.createHash("sha256").update(Buffer.concat([r,i,s])).digest()}static async getIdentity(t,e){const r=await this.contentOfLoadFile(e,async t=>{const{promises:e}=await p(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)});return{mspId:t,credentials:r}}static async getFirstDirFileName(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path"));return r(t,(await e.readdir(t))[0])}static async getFirstDirFileNameContent(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}static async getFileContent(t){const{promises:e}=await p(import("fs"));return(await e.readFile(t)).toString()}static async getSigner(t){const e=await this.contentOfLoadFile(t,async t=>{const{promises:e}=await p(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)}),r=await this.extractPrivateKey(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Tt.newPrivateKeySigner(i)}static async extractPrivateKey(t){let e;if(globalThis.window&&globalThis.window.Crypto)e=globalThis.Crypto.subtle;else{const t=await p(import("crypto"));e=t.subtle||t.webcrypto.subtle}if(!e)throw Error("Could not load SubtleCrypto module");const r=t.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),i=(t=>{const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e})(Buffer.from(r,"base64").toString("binary"));return await e.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}}const ne=new Dt;var ae,oe,ce,le,de;Ft.cryptoProvider.set(ne),(t=>{t.BASE2="01",t.BASE8="01234567",t.BASE11="0123456789a",t.BASE16="0123456789abcdef",t.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",t.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",t.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",t.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",t.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",t.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~"})(ae||(ae={})),(t=>{t.HASH="SHA-256",t[t.ITERATIONS=1e3]="ITERATIONS",t[t.KEYLENGTH=48]="KEYLENGTH",t[t.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",t[t.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",t.ALGORYTHM="AES-GCM",t.KEY_ALGORYTHM="PBKDF2"})(oe||(oe={}));class he{constructor(t){if(this.alphabet=t,this.baseMap=new Uint8Array(256),this.alphabet.length>=255)throw Error("Alphabet too long");for(let t=0;t<this.baseMap.length;t++)this.baseMap[t]=255;for(let e=0;e<t.length;e++){const r=t.charAt(e),i=r.charCodeAt(0);if(255!==this.baseMap[i])throw Error(r+" is ambiguous");this.baseMap[i]=e}this.base=this.alphabet.length,this.leader=this.alphabet.charAt(0),this.factor=Math.log(this.base)/Math.log(256),this.iFactor=Math.log(256)/Math.log(this.base)}encode(t){if("string"==typeof t?t=Buffer.from(t):ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t)),0===t.length)return"";let e=0,r=0,i=0;const s=t.length;for(;i!==s&&0===t[i];)i++,e++;const n=(s-i)*this.iFactor+1>>>0,a=new Uint8Array(n);for(;i!==s;){let e=t[i],s=0;for(let t=n-1;(0!==e||r>s)&&-1!==t;t--,s++)e+=256*a[t]>>>0,a[t]=e%this.base>>>0,e=e/this.base>>>0;if(0!==e)throw Error("Non-zero carry");r=s,i++}let o=n-r;for(;o!==n&&0===a[o];)o++;let c=this.leader.repeat(e);for(;n>o;++o)c+=this.alphabet.charAt(a[o]);return c}decodeUnsafe(t){if(0===t.length)return new Uint8Array(0);let e=0,r=0,i=0;for(;t[e]===this.leader;)r++,e++;const s=(t.length-e)*this.factor+1>>>0,n=new Uint8Array(s);for(;t[e];){let r=this.baseMap[t.charCodeAt(e)];if(255===r)return;let a=0;for(let t=s-1;(0!==r||i>a)&&-1!==t;t--,a++)r+=this.base*n[t]>>>0,n[t]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");i=a,e++}let a=s-i;for(;a!==s&&0===n[a];)a++;const o=new Uint8Array(r+(s-a));let c=r;for(;a!==s;)o[c++]=n[a++];return o}decode(t){const e=this.decodeUnsafe(t);if(e)return e;throw Error("Non-base"+this.base+" character")}}class ue{static{this.b58encoder=new he(ae.BASE58)}static{this.logger=new At(ue.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(P("Parsing certificate: {0}",t));const e=new Ft.X509Certificate(t),{subject:r,issuer:i}=e;return this.logger.debug(P("Certificate parsed with subject {0} and issuer {1}",r,i)),`x509::/${r.replaceAll(", ","/")}::/${i.replaceAll(", ","/")}`}static encode(t){return this.b58encoder.encode(t)}static decode(t){const e=this.b58encoder.decode(t);return(new TextDecoder).decode(e)}static stringToArrayBuffer(t){const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e}static async extractKey(t,e,r){const i=ne.subtle,s=e.toString("utf8").replace(RegExp(`-----BEGIN (${t.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${t.toUpperCase()} KEY|CERTIFICATE)-----`),""),n=Buffer.from(s,"base64").toString("binary"),a=this.stringToArrayBuffer(n);return await i.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!0,r||["sign"])}static async extractPrivateKey(t,e){return this.extractKey("private",t,e)}static async extractPublicKey(t,e){return this.extractKey("public",t,e)}static async sign(t,e){const r=await this.extractPrivateKey(t),i=await ne.subtle.sign({name:"ECDSA",hash:"SHA-256"},r,e);return Array.from(new Uint8Array(i)).map(t=>t.toString(16).padStart(2,"0")).join("")}static async verify(t,e,r){const i=new Ft.X509Certificate(t),s=await i.publicKey.export();return e="string"==typeof e?Buffer.from(e,"hex"):e,r="string"==typeof r?Buffer.from(r):r,ne.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,e,r)}static async encrypt(t,e){const r=new Ft.X509Certificate(t),i=await r.publicKey.export();e="string"==typeof e?Buffer.from(e):e;const s=await this.getSubtleCrypto().encrypt({name:"ECDSA"},i,e);return Array.from(new Uint8Array(s)).map(t=>t.toString(16).padStart(2,"0")).join("")}static getSubtleCrypto(){return Ct()?globalThis.window.crypto.subtle:ne.subtle}static async decrypt(t,e){const r=await this.extractPrivateKey(t);return e="string"==typeof e?Buffer.from(e,"hex"):e,this.getSubtleCrypto().decrypt({name:"ECDSA"},r,e)}static async getMaster(t){const e=new TextEncoder;if(void 0===t){const r=ne.randomUUID();t=e.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,oe.KEY_ALGORYTHM,!1,["deriveBits"]),iv:t}}static async getDerivationKey(t,e){const r=(new TextEncoder).encode(t),i=await this.getSubtleCrypto().digest("SHA-256",r),s={name:oe.KEY_ALGORYTHM,hash:oe.HASH,salt:i,iterations:oe.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,e,8*oe.KEYLENGTH);return this.getKey(n)}static async getKey(t){const e=t.slice(0,32),r=t.slice(32);return{key:await this.getSubtleCrypto().importKey("raw",e,{name:oe.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:oe.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:oe.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}class pe extends Y{constructor(t){super(t,pe.name)}}class ge extends Y{constructor(t){super(t,ge.name)}}class fe extends Y{constructor(t){super(t,fe.name)}}class me extends g{constructor(t){super(t,me.name)}}class ye extends Y{constructor(t){super(t,ye.name,500)}}class we extends G{constructor(t="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(we.name,t,403)}}class be extends G{constructor(t){super(be.name,t,409)}}class Ae extends Y{constructor(t){super(t,Ae.name,500)}}class Ce extends Y{constructor(t){super(t,Ce.name,500)}}class ve extends Y{constructor(t){super(t,ve.name,500)}}class Ee extends Y{constructor(t){super(t,Ee.name,500)}}class Se extends Y{constructor(t){super(t,Se.name,500)}}(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(ce||(ce={})),(t=>{t.HFREGISTRARROLES="hf.Registrar.Roles",t.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",t.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",t.HFINTERMEDIATECA="hf.IntermediateCA",t.HFREVOKER="hf.Revoker",t.HFAFFILIATIONMGR="hf.AffiliationMgr",t.HFGENCRL="hf.GenCRL"})(le||(le={}));class xe extends vt{constructor(t){se.getCryptoSuite(t.hsm?{software:!1,lib:t.hsm.library,slot:t.hsm.slot,label:t.hsm.tokenLabel,pin:t.hsm.pin+""}:void 0),super(),this.caConfig=t}async User(){if(this.user)return this.user;const{caName:t,caCert:e,caKey:r,url:i,hsm:s}=this.caConfig,n=this.log.for(this.User);n.debug(`Creating CA user for ${t} at ${i}`),n.debug("Retrieving CA certificate from "+e);const a=await se.getFirstDirFileNameContent(e);let o;if(s)n.debug(`Using HSM configuration for CA ${t} with library ${s.library}`);else{if(!r)throw new Y(`Missing caKey configuration for CA ${t}. Provide a key directory or configure HSM support.`);n.debug("Retrieving CA key from "+r),o=await se.getFirstDirFileNameContent(r)}return n.debug("Loading Admin user for ca "+t),this.user=await se.getCAUser("admin",o,a,t,{hsm:s}),this.user}async CA(){if(this.ca)return this.ca;const t=this.log.for(this.CA),{url:e,tls:r,caName:i}=this.caConfig;let{trustedRoots:s,verify:n}=r;const a=s[0];t.debug(`Retrieving CA certificate from ${a}. cwd: ${process.cwd()}`);const o=await se.getFileContent(a);return t.debug(`Creating CA Client for CA ${i} under ${e}`),this.ca=new bt(e,{trustedRoots:Buffer.from(o),verify:n},i),this.ca}async Client(){if(this.client)return this.client;const t=await this.CA();return this.client=t._FabricCAServices,this.client}async Certificate(){return this.certificateService||(this.certificateService=(await this.Client()).newCertificateService()),this.certificateService}async Affiliations(){return this.affiliationService||(this.affiliationService=(await this.CA()).newAffiliationService()),this.affiliationService}async Identities(){return this.identityService||(this.identityService=(await this.CA()).newIdentityService()),this.identityService}async getCertificates(t,e=!0){const r=await this.Certificate(),i=await this.User(),s=this.log.for(this.getCertificates);s.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.caConfig.caName}`);const n=(await r.getCertificates(t||{},i)).result;return s.debug(`Found ${n.certs.length} certificates: ${JSON.stringify(n)}`),e?n.certs.map(t=>t.PEM):n}async getIdentities(){const t=await this.Identities(),e=this.log.for(this.getIdentities);e.debug("Retrieving Identities under CA "+this.caConfig.caName);const r=(await t.getAll(await this.User())).result;return e.debug(`Found ${r.identities.length} Identities: ${JSON.stringify(r)}`),r.identities}parseError(t){const e=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(t.message);if(!e)return new me(t);const[,r,i]=e;switch(r){case"74":case"71":return new V(i);case"20":return new g(i);default:return new me(i)}}async getAffiliations(){const t=await this.Affiliations(),e=this.log.for(this.getAffiliations);e.debug("Retrieving Affiliations under CA "+this.caConfig.caName);const r=(await t.getAll(await this.User())).result;return e.debug(`Found ${r.a.length} Affiliations: ${JSON.stringify(r)}`),r}async read(t){const e=await this.CA(),r=await this.User();let i;try{i=await e.newIdentityService().getOne(t,r)}catch(e){throw new J(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new J(`Couldn't find enrollment with id ${t}: ${i.errors.join("\n")}`);return i.result}async register(t,e=!1,r="",i,s,n){let a;const o=this.log.for(this.register);try{const{userName:c,password:l}=t,d=await this.CA(),h=await this.User(),u={enrollmentID:c,enrollmentSecret:l,affiliation:r,userRole:i,attrs:s,maxEnrollments:n};a=await d.register(u,h),o.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${e?"as super user":""}`)}catch(t){throw this.parseError(t)}return a}static identityFromEnrollment(t,e){const{certificate:r,key:i,rootCertificate:s}=t,n=Et.for(xe,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${r} in msp ${e}`);const a=ue.fabricIdFromCertificate(r),o=ue.encode(a);n.debug(`Identity ${a} and encodedId ${o}`);const c=new Date;return new ie({id:o,credentials:{id:o,certificate:r,privateKey:i.toBytes(),rootCertificate:s,createdOn:c,updatedOn:c},mspId:e,createdOn:c,updatedOn:c})}async enroll(t,e){let r;const i=this.log.for(this.enroll);try{const s=await this.CA();i.debug("Enrolling "+t);const n=await s.enroll({enrollmentID:t,enrollmentSecret:e});r=xe.identityFromEnrollment(n,this.caConfig.caName),i.info(`Successfully enrolled ${t} under ${this.caConfig.caName} as ${r.id}`)}catch(t){throw this.parseError(t)}return r}async registerAndEnroll(t,e=!1,r="",i,s,n){const a=await this.register(t,e,r,i,s,n),{userName:o}=t;return this.enroll(o,a)}async revoke(t){const e=await this.CA(),r=await this.User(),i=await this.read(t);if(!i)throw new J("Could not find enrollment with id "+t);let s;try{s=await e.revoke({enrollmentID:i.id,reason:"User Deletation"},r)}catch(e){throw new Y(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new Y(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}class Ne extends ${constructor(){super(...arguments),this.affiliation=""}build(){const t=this.hasErrors();if(t)throw new H(t.toString());const e={enrollmentID:this.enrollmentID,enrollmentSecret:this.enrollmentSecret,role:this.role,affiliation:this.affiliation};return void 0!==this.maxEnrollments&&(e.maxEnrollments=this.maxEnrollments),this.attrs&&(e.attrs=this.attrs),e}setAffiliation(t){return this.affiliation=t,this}addAttr(t){return this.attrs=this.attrs||[],this.attrs.push(t),this}setAttrs(t){return this.attrs=t,this}setEnrollmentID(t){return this.enrollmentID=t,this}setEnrollmentSecret(t){return this.enrollmentSecret=t,this}setMaxEnrollments(t){return this.maxEnrollments=t,this}setRole(t){return this.role=t,this}}lt([k(),dt("design:type",String)],Ne.prototype,"affiliation",void 0),lt([j(1),dt("design:type",Array)],Ne.prototype,"attrs",void 0),lt([k(),dt("design:type",String)],Ne.prototype,"enrollmentID",void 0),lt([k(),dt("design:type",String)],Ne.prototype,"enrollmentSecret",void 0),lt([K(0),dt("design:type",Number)],Ne.prototype,"maxEnrollments",void 0),lt([k(),dt("design:type",String)],Ne.prototype,"role",void 0),(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(de||(de={}));let Ie=class extends ${constructor(t){super(t)}};lt([ut("Stores the original timestamp of creation"),n(),f(),dt("design:type",Date)],Ie.prototype,"createdAt",void 0),lt([ut("Stores the timestamp of the last update"),n(),m(),dt("design:type",Date)],Ie.prototype,"updatedAt",void 0),lt([ut("Stores the version of the model"),n(),q(),dt("design:type",Number)],Ie.prototype,"version",void 0),Ie=lt([pt(re),dt("design:paramtypes",[Object])],Ie);let Te=class extends Ie{constructor(t){super(t)}};function Oe(){return function(t,e,r){const i=r.value;return r.value=async function(...t){const r=t[0],s=r.clientIdentity.getID(),n=await this.tokenRepository.select(),a=await n.execute(r);if(0==a.length)throw new J("No tokens avaialble");if(a.length>1)throw new J("To many token available : "+a.length);if(a[0].owner!=s)throw new g(`User not authorized to run ${e} on the token`);return await i.apply(this,t)},r}}async function Re(t,e,r,i){const{stub:s}=t,n=(await s.getCreator()).mspid;Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:n})}function $e(){return gt.for(te.OWNED_BY).define({decorator:()=>(t,e)=>ft(k(),X(),Q(Re),mt(ht.key(te.FABRIC,te.OWNED_BY),e))(t,e),args:[]}).apply()}async function ke(t,e,r,i){const{stub:s}=t;i[r]=s.getTxID()}function Fe(){return gt.for(te.TRANSACTION_ID).define({decorator:()=>(t,e)=>ft(k(),X(),Q(ke),Z(ke),mt(ht.key(te.FABRIC,e,te.TRANSACTION_ID),e))(t,e),args:[]}).apply()}async function De(t,e,r){let i=e;if("string"!=typeof i)try{const s=$.ownerOf(t)||r.get("stub").getCreator().toString();e&&"function"==typeof e&&(i=await e(t,s,r))}catch(t){throw new Y("Failed to resolve collection mirror name: "+t)}if(!i||"string"!=typeof i)throw new Y("No collection found model "+t.constructor.name);return i}async function Be(t,e,r,i){const s=await De(i,e.resolver,t),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),a=await n.create(i,t);t.logger.info(`Mirror for ${$.tableName(this.class)} created with ${$.pk(i)}: ${a[$.pk(i)]}`)}async function _e(t,e,r,i){const s=await De(i,e.resolver,t),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),a=await n.update(i,t);t.logger.info(`Mirror for ${$.tableName(this.class)} updated with ${$.pk(i)}: ${a[$.pk(i)]}`)}async function Pe(t,e,r,i){const s=await De(i,e.resolver,t),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),a=await n.delete($.pk(i),t);t.logger.info(`Mirror for ${$.tableName(this.class)} deleted with ${$.pk(i)}: ${a[$.pk(i)]}`)}function je(t,e){return gt.for(te.MIRROR).define({decorator:(e,r)=>{const i={condition:r,resolver:e};return ft(yt(ht.key(te.FABRIC,te.MIRROR),i),Ge(t),tt(Be,i,{priority:95}),et(_e,i,{priority:95}),rt(Pe,i,{priority:95}))},args:[t,e]}).apply()}lt([ut("Stores the creator"),n(),y(),dt("design:type",String)],Te.prototype,"createdBy",void 0),lt([ut("Stores the user that last updated the model"),n(),w(),dt("design:type",String)],Te.prototype,"updatedBy",void 0),Te=lt([pt(re),dt("design:paramtypes",[Object])],Te),$.prototype.isShared=function(){return $.isShared(this.constructor)},$.prototype.isPrivate=function(){return $.isPrivate(this.constructor)},$.prototype.segregate=function(){return $.segregate(this)},$.segregate=(t=>{if(!$.isTransient(t))return{model:t};const e=ht.validatableProperties(t.constructor),r=ht.get(t.constructor,W.TRANSIENT),i=ht.get(t.constructor,te.PRIVATE),s=ht.get(t.constructor,te.PRIVATE),n={model:{},transient:{},private:{},shared:{}},a=Object.keys(r),o=Object.keys(i),c=Object.keys(s);for(const r of e){const e=a.includes(r),i=o.includes(r),s=c.includes(r);e?(n.transient=n.transient||{},n.transient[r]=t[r],i&&(n.private=n.private||{},n.private[r]=t[r]),s&&(n.shared=n.shared||{},n.shared[r]=t[r])):(n.model=n.model||{},n.model[r]=t[r])}return n.model=$.build(n.model,t.constructor.name),n}).bind($),$.isPrivate=(t=>!!ht.get("function"!=typeof t?t.constructor:t,te.PRIVATE)).bind($),$.isShared=(t=>!!ht.get("function"!=typeof t?t.constructor:t,te.SHARED)).bind($),$.mirrored=(t=>ht.get("function"!=typeof t?t.constructor:t,ht.key(te.FABRIC,te.MIRROR))).bind($),$.ownerOf=(t=>{const e=ht.get(t.constructor,ht.key(te.FABRIC,te.OWNED_BY));if(e)return t[e]}).bind($),$.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,ht.get(t,ht.key(te.FABRIC,te.MIRROR)))).bind($),$.collectionsFor=(t=>{const e=[te.PRIVATE],r=[te.SHARED],i=ht.key(...e),s=ht.key(...r),n="function"==typeof t?t:t.constructor,a=ht.get(n,i),o=ht.get(n,s);return{privateCols:a?.collections||[],sharedCols:o?.collections||[]}}).bind($);const Ke=(t,e)=>{const r=e||("function"!=typeof t?$.ownerOf(t):void 0),i="function"==typeof t?t:t.constructor;if(!r)throw new Y(`Model ${i.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${St(i.name)}${e?St(e):""}`},Le=(t,e)=>{const r=e||("function"!=typeof t?$.ownerOf(t):void 0);if(!r)throw new Y(`Model ${t.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${St(r)}PrivateCollection`};async function ze(t,e,r,i){if(r.length!==e.length)throw new Y("Segregated data keys and metadata length mismatch");const s=$.ownerOf(i);if(!s)throw new H("There's no assigned organization for model "+i.constructor.name);const n=e[0].collections,a="string"==typeof n?n:n(i,s,t),o=r.reduce((r,n,o)=>{const c="string"==typeof e[o].collections?e[o].collections:e[o].collections(i,s,t);if(c!==a)throw new b(`Segregated data collection mismatch: ${c} vs ${a}`);return r[n]=i[n],r},{}),c=new this.class(o),l=await this.override({segregated:a,mergeModel:!1,ignoreHandlers:!0,ignoreValidation:!0}).create(c,t);Object.assign(i,l)}async function Me(t,e,r,i){if(r.length!==e.length)throw new Y("Segregated data keys and metadata length mismatch");const s=$.ownerOf(i);if(!s)throw new H("There's no assigned organization for model "+i.constructor.name);const n=e[0].collections,a="string"==typeof n?n:await n(i,s,t);r.reduce((r,n,o)=>(("string"==typeof e[o].collections?e[o].collections:e[o].collections(i,s,t))!==a||(r[n]=i[n]),r),{})}async function He(t,e,r,i,s){}async function Ue(t,e,r,i){}function Ye(t,e,r){return(i,s)=>{const n=[];return s?n.push(wt(),it(),(r,i)=>{const s=ht.key(e,i),n=r.constructor,a=ht.get(n,s)||{},o=new Set(a.collections||[]);o.add(t),a.collections=[...o],ht.set(n,s,a);const c=ht.get(n,e)||{};new Set(c.collections||[]).add(t),a.collections=[...o],ht.set(n,e,a)},Q(ze,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),st(Me,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),Z(He,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),nt(Ue,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()})):ht.properties(i)?.forEach(s=>{r&&!r(s)||Ye(t,e)(i.prototype,s)}),ft(...n)(i,s)}}function Ge(t=Le){return gt.for(te.PRIVATE).define({decorator:t=>Ye(t,te.PRIVATE),args:[t]}).apply()}function Ve(t){return gt.for(te.SHARED).define({decorator:t=>Ye(t,te.SHARED),args:[t]}).apply()}class Je extends B{constructor(){super()}preSerialize(t){const e=Object.assign({},t);let r;try{r=ht.modelName(t.constructor)}catch(t){r=void 0}e[_.ANCHOR]=r||t.constructor.name;const i=function t(e){const r=this;return"object"!=typeof e?e:Array.isArray(e)?e.map(e=>t.call(r,e)):this.preSerialize.call(this,e)}.bind(this);return $.relations(t).forEach(t=>{e[t]=i(e[t])}),e}deserialize(t){const e=JSON.parse(t),r=e[_.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return $.build(e,r)}serialize(t){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t)))}}function qe(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function We(t){const e=t.split("_");return 2>e.length||e.length>3?{table:void 0,event:t,owner:void 0}:{table:e[0],event:e[1],owner:e[2]}}function Xe(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new pe(`Addition overflow: ${t} + ${e}`);return r}function Qe(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new pe(`Subtraction overflow: ${t} - ${e}`);return r}function Ze(t){if(!/^\d+$/.test(t))throw new H(P("Failed to parse: {0}","string contains digits"));const e=parseInt(t);if(isNaN(e))throw new H(P("Failed to parse: {0}","string is not a parsable integer"));return e}class tr extends B{constructor(){super()}deserialize(t,e){return JSON.parse(t)}serialize(t,e=!0){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t,e)))}preSerialize(t,e=!0){const r=Object.assign({},t);let i;try{i=ht.modelName(t.constructor)}catch(t){i=void 0}function s(t){return"object"!=typeof t?t:Array.isArray(t)?t.map(s):this.preSerialize(t)}return e&&(r[_.ANCHOR]=i||t.constructor.name),$.relations(t).forEach(t=>{r[t]=s.call(this,r[t])}),r}}class er extends A{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new Y("Fabric identity service not properly setup: missing user");return this._user}get certificates(){return this.rootClient.newCertificateService()}get affiliations(){return this.client.newAffiliationService()}get identities(){return this.client.newIdentityService()}async getUser(t,e){const r=e.logger.for(this.getUser),{caName:i,caCert:s,caKey:n,url:a,hsm:o}=t;r.info(`Creating CA user for ${i} at ${a}`),r.verbose("Retrieving CA certificate from "+s);const c=await se.getFirstDirFileNameContent(s);let l;if(o)r.debug(`Using HSM configuration for CA ${i} with library ${o.library}`);else{if(!n)throw new Y(`Missing caKey configuration for CA ${i}. Provide a key directory or configure HSM support.`);r.debug("Retrieving CA key from "+n),l=await se.getFirstDirFileNameContent(n)}return r.debug("Loading Admin user for ca "+i),this._user=await se.getCAUser("admin",l,c,i,{hsm:o}),this._user}async initialize(...t){const{log:e,ctx:i}=(await this.logCtx(t,r.INITIALIZATION,!0)).for(this.initialize),[s]=t;if(!s)throw new Y("Missing Fabric CA configuration");const{url:n,tls:a,caName:o}=s;e.info(`Initializing CA Client for CA ${s.caName} at ${s.url}`);const{trustedRoots:c,verify:l}=a,d=c[0];e.debug(`Retrieving CA certificate from ${d}. cwd: ${process.cwd()}`);const h=await se.getFileContent(d);e.debug("CA Certificate: "+h.toString());const u=new bt(n,{trustedRoots:Buffer.from(h),verify:l},o),p=await this.getUser(s,i);return e.debug("CA user loaded: "+p.getName()),{config:s,client:u}}async getCertificates(t,e=!0,...r){t instanceof l?(r=[t],e=!0,t=void 0):"boolean"==typeof t?(e=t,t=void 0):"boolean"!=typeof e&&(r=[e,...r],e=!0);const{log:i}=(await this.logCtx(r,L.READ,!0)).for(this.getCertificates);i.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.config.caName}`);const s=(await this.certificates.getCertificates(t||{},this.user)).result;return i.verbose(`Found ${s.certs.length} certificates`),i.debug(s.certs),e?s.certs.map(t=>t.PEM):s}async getIdentities(t){const e=t.logger.for(this.getIdentities);e.verbose("Retrieving Identities under CA "+this.config.caName);const r=(await this.identities.getAll(this.user)).result;return e.verbose(`Found ${r.identities.length} Identities`),e.debug(r.identities),r.identities}async getAffiliations(t){const e=t.logger.for(this.getAffiliations);e.verbose("Retrieving Affiliations under CA "+this.config.caName);const r=(await this.affiliations.getAll(this.user)).result;return e.verbose(`Found ${r.a.length} Affiliations`),e.debug(JSON.stringify(r)),r}parseError(t){const e=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(t.message);if(!e)return new me(t);const[,r,i]=e;switch(r){case"74":case"71":return new V(i);case"20":return new g(i);default:return new me(i)}}async read(t,...e){const{log:r}=(await this.logCtx(e,L.READ,!0)).for(this.read);let i;r.verbose("Retrieving identity with enrollment ID "+t);try{i=await this.identities.getOne(t,this.user)}catch(e){throw new J(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new J(`Couldn't find enrollment with id ${t}: ${i.errors.join("\n")}`);return i.result}async register(t,e=!1,r="",i,s,n,...a){const{log:o}=(await this.logCtx(a,"register",!0)).for(this.register);let c;try{const{userName:a,password:l}=t,d={enrollmentID:a,enrollmentSecret:l,affiliation:r,userRole:i,attrs:s,maxEnrollments:n};c=await this.client.register(d,this.user),o.info(`Registration for ${a} created with user type ${i??"Undefined Role"} ${e?"as super user":""}`)}catch(t){throw this.parseError(t)}return c}static identityFromEnrollment(t,e,r){const i=r.logger.for(this.identityFromEnrollment),{certificate:s,key:n,rootCertificate:a}=t;i.verbose(`Generating Identity from certificate ${s} in msp ${e}`);const o=ue.fabricIdFromCertificate(s),c=ue.encode(o);return i.debug(`Identity ${o} and encodedId ${c}`),new ie({id:c,credentials:{id:c,certificate:s,privateKey:n.toBytes(),rootCertificate:a},mspId:e})}async enroll(t,e,...r){const{log:i,ctx:s}=(await this.logCtx(r,"enroll",!0)).for(this.enroll);let n;try{i.debug("Enrolling "+t);const r=await this.client.enroll({enrollmentID:t,enrollmentSecret:e});n=er.identityFromEnrollment(r,this.config.caName,s),i.info(`Successfully enrolled ${t} under ${this.config.caName} as ${n.id}`)}catch(t){throw this.parseError(t)}return n}async registerAndEnroll(t,e=!1,r="",i,s,n,...a){const{ctx:o}=(await this.logCtx(a,"register-enroll",!0)).for(this.registerAndEnroll),c=await this.register(t,e,r,i,s,n,o),{userName:l}=t;return this.enroll(l,c,o)}async revoke(t,...e){const{log:r}=(await this.logCtx(e,"revoke",!0)).for(this.revoke);r.verbose("Revoking identity with enrollment ID "+t);const i=await this.read(t);if(!i)throw new J("Could not find enrollment with id "+t);let s;try{s=await this.client.revoke({enrollmentID:i.id,reason:"User Deletion"},this.user)}catch(e){throw new Y(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new Y(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}const rr=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60}),ir=new At("fabric-fs");async function sr(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}async function nr(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await p(import("fs"));return await e.readFile(t)})(t)}async function ar(t,e,r,i){ir.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const s=new Rt(t),n=Rt.newCryptoSuite();s.setCryptoSuite(n);const a=n.createKeyFromRaw(e);return await s.setEnrollment(a,r,i),s}async function or(t,e){const r=await sr(e,async t=>{const{promises:e}=await p(import("fs")),r=await cr(t);return await e.readFile(r)});return{mspId:t,credentials:r}}async function cr(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path"));return r(t,(await e.readdir(t))[0])}async function lr(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}async function dr(t){const e=await sr(t,async t=>{const{promises:e}=await p(import("fs")),r=await cr(t);return await e.readFile(r)}),r=await hr(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Tt.newPrivateKeySigner(i)}async function hr(t){let e;if(Ct())e=globalThis.crypto.subtle;else{const t=await p(import("crypto"));e=t.subtle||t.webcrypto.subtle}if(!e)throw Error("Could not load SubtleCrypto module");const r=t.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),i=(t=>{const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e})(Buffer.from(r,"base64").toString("binary"));try{return await e.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}catch(t){throw new Y(t)}}class ur{static#t=null;static#e=!1;constructor(t){if(ur.#t||(ur.#t=new Pt.PKCS11,ur.#t.load(this.findHSMPKCS11Lib(t))),!ur.#e){try{ur.#t.C_Initialize()}catch(t){if(t.code!==Pt.CKR_CRYPTOKI_ALREADY_INITIALIZED)throw t}ur.#e=!0}}findHSMPKCS11Lib(t){const e=["/usr/lib/softhsm/libsofthsm2.so","/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so","/usr/local/lib/softhsm/libsofthsm2.so","/usr/lib/libacsp-pkcs11.so","/opt/homebrew/lib/softhsm/libsofthsm2.so"];t&&e.push(t);for(const t of e)if(jt.existsSync(t))return t;throw new Ae("Unable to find PKCS11 library")}dispose(){ur.#t.C_Finalize()}sanitizeOptions(t){const e=Object.assign({userType:Pt.CKU_USER},t);return this.assertNotEmpty(e.label,"label"),this.assertNotEmpty(e.pin,"pin"),this.assertNotEmpty(e.identifier,"identifier"),e}assertNotEmpty(t,e){if(!t||0===t.toString().trim().length)throw Error(e+" property must be provided")}findSlotForLabel(t){const e=ur.#t.C_GetSlotList(!0);if(0===e.length)throw Error("No pkcs11 slots can be found");const r=e.find(e=>ur.#t.C_GetTokenInfo(e).label.trim()===t);if(!r)throw Error(`label ${t} cannot be found in the pkcs11 slot list`);return r}login(t,e,r){try{ur.#t.C_Login(t,e,r)}catch(t){if(t.code!==Pt.CKR_USER_ALREADY_LOGGED_IN)throw t}}findObjectInHSM(t,e,r){const i=[{type:Pt.CKA_ID,value:r},{type:Pt.CKA_CLASS,value:e},{type:Pt.CKA_KEY_TYPE,value:Pt.CKK_EC}];ur.#t.C_FindObjectsInit(t,i);const s=ur.#t.C_FindObjects(t,1)[0];if(!s)throw ur.#t.C_FindObjectsFinal(t),Error("Unable to find object in HSM with ID "+r.toString());return ur.#t.C_FindObjectsFinal(t),s}newSigner(t){const e=this.sanitizeOptions(t),r=ur.#t,i=this.findSlotForLabel(e.label),s=r.C_OpenSession(i,Pt.CKF_SERIAL_SESSION);let n;try{this.login(s,e.userType,e.pin),n=this.findObjectInHSM(s,Pt.CKO_PRIVATE_KEY,e.identifier)}catch(t){throw ur.#t.C_CloseSession(s),t}return{signer:async t=>{ur.#t.C_SignInit(s,{mechanism:Pt.CKM_ECDSA},n);const e=await ur.#t.C_SignAsync(s,Buffer.from(t),Buffer.alloc(2*Lt.Point.Fn.BYTES));return Lt.Signature.fromBytes(e,"compact").normalizeS().toBytes("der")},close:()=>{ur.#t.C_CloseSession(s)}}}assertDefined(t){if(void 0===t)throw Error("required value was undefined");return t}getUncompressedPointOnCurve(t){const e=t.export({format:"jwk"}),r=Buffer.from(this.assertDefined(e.x),"base64url"),i=Buffer.from(this.assertDefined(e.y),"base64url"),s=Buffer.from("04","hex");return Buffer.concat([s,r,i])}getSKIFromCertificatePath(t){const e=t.endsWith(".pem")?t:Kt.join(t,"cert.pem"),r=jt.readFileSync(e);return this.getSKIFromCertificate(r)}getSKIFromCertificate(t){const e=new $t.X509Certificate(t),r=this.getUncompressedPointOnCurve(e.publicKey);return $t.createHash("sha256").update(r).digest()}}class pr extends C{constructor(t,e){super(t,e)}squash(t){const r=super.squash(t);if(!r)return r;const{method:i,params:s,args:n}=r,{direction:a,limit:o}=s;switch(i){case e.FIND_BY:break;case e.LIST_BY:n.push(a);break;case e.PAGE_BY:n.push(a,o);break;case e.FIND_ONE_BY:break;default:throw new Y("Unsupported method "+i)}return r}async executePrepared(...e){const r=t.forModel(this.fromSelector,this.adapter.alias),{method:i,args:s}=this.prepared;return r.statement(i,...s,...e)}async prepare(t){if(t=t||await this.adapter.context(r.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],i={},s={class:this.fromSelector,args:e,params:i},n=[v.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);n.push(r.method),r.args&&r.args.length&&e.push(...r.args)}return this.selectSelector&&n.push(v.SELECT,this.selectSelector.join(` ${v.AND.toLowerCase()} `)),this.orderBySelector&&(n.push(v.ORDER_BY,this.orderBySelector[0]),e.push(this.orderBySelector[1])),s.method=xt(n.join(" ")),s.params=i,this.prepared=s,this}build(){throw new b("This method is only called is prepared statements are not used. If so, a dedicated implementation for the native queries used is required")}parseCondition(t,...e){throw new b("This method is only called is prepared statements are not used. Is so, a dedicated implementation for the native queries used is required")}}class gr extends i{constructor(t,e,r,i){super(t,e,r,i)}prepare(t){throw new b("Raw query access must be implemented by a subclass. only prepared statements are natively available")}page(t=1,...e){return super.page(t,...e)}}var fr;class mr extends E{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new Yt}static{this.log=Et.for(mr)}constructor(t,e){super(t,re,e),this.serializer=mr.serializer}Statement(t){return new pr(this,t)}Paginator(t,e,r){return new gr(this,t,e,r)}async flags(t,e,r,...i){return Object.assign(await super.flags(t,e,Object.assign({},this.config,r),...i))}decode(t){return mr.decoder.decode(t)}repository(){return zt}createPrefix(t,e,r,...i){const{ctxArgs:s}=this.logCtx(i,this.createPrefix),n=$.tableName(t),a={};return a[ct.TABLE]=n,Object.assign(a,r),[t,e,a,...s]}createAllPrefix(t,e,r,...i){const s=$.tableName(t);if(e.length!==r.length)throw new Y("Ids and models must have the same length");const{ctxArgs:n}=this.logCtx(i,this.createAllPrefix),a=e.map((t,e)=>{const i={};return i[ct.TABLE]=s,Object.assign(i,r[e]),i});return[t,e,a,...n]}updateAllPrefix(t,e,r,...i){const s=$.tableName(t);if(e.length!==r.length)throw new Y("Ids and models must have the same length");const{ctxArgs:n}=this.logCtx(i,this.updateAllPrefix),a=e.map(()=>{const t={};return t[ct.TABLE]=s,t});return[t,e,a,...n]}async createAll(t,e,r,...i){if(e.length!==r.length)throw new Y("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.createAll),c=$.tableName(t);a.info(`adding ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=await this.submitTransaction(o,at.CREATE_ALL,[JSON.stringify(r.map(e=>this.serializer.serialize(e,t.name)))],n,void 0,t.name);try{return JSON.parse(this.decode(l)).map(t=>JSON.parse(t))}catch(t){throw new U(t)}}async readAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.readAll),n=$.tableName(t);i.info(`reading ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.evaluateTransaction(s,at.READ_ALL,[JSON.stringify(e)],void 0,void 0,t.name);try{return JSON.parse(this.decode(a)).map(t=>JSON.parse(t))}catch(t){throw new U(t)}}async updateAll(t,e,r,...i){if(e.length!==r.length)throw new Y("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.updateAll),c=$.tableName(t);a.info(`updating ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=await this.submitTransaction(o,at.UPDATE_ALL,[JSON.stringify(r.map(e=>this.serializer.serialize(e,t.name)))],n,void 0,t.name);try{return JSON.parse(this.decode(l)).map(t=>JSON.parse(t))}catch(t){throw new U(t)}}async deleteAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.deleteAll),n=$.tableName(t);i.info(`deleting ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.submitTransaction(s,at.DELETE_ALL,[JSON.stringify(e)],void 0,void 0,t.name);try{return JSON.parse(this.decode(a)).map(t=>JSON.parse(t))}catch(t){throw new U(t)}}prepare(t,...e){const{log:i}=this.logCtx(e,this.prepare),s=$.segregate(t);return t[r.METADATA]&&(i.silly("Passing along persistence metadata for "+t[r.METADATA]),Object.defineProperty(s.model,r.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:t[r.METADATA]})),{record:s.model,model:s.model,id:t[$.pk(t.constructor)],transient:s.transient,private:s.private,shared:s.shared}}revert(t,e,r,i,...s){const{log:n}=this.logCtx(s,this.revert);return i&&(n.verbose("re-adding transient properties: "+Object.keys(i).join(", ")),Object.entries(i).forEach(([r,i])=>{if(r in t)throw new Y(`Transient property ${r} already exists on model ${"string"==typeof e?e:e.name}. should be impossible`);t[r]=i})),new e(t)}async create(t,e,r,i={},...s){const n=[...s],{log:a,ctx:o}=this.logCtx(n,this.create),c=$.tableName(t);a.verbose(`adding entry to ${c} table`),a.debug("pk: "+e);const l=await this.submitTransaction(o,L.CREATE,[this.serializer.serialize(r,t.name)],i,void 0,t.name);return this.serializer.deserialize(this.decode(l))}async read(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.readAll),n=$.tableName(t);i.verbose(`reading entry from ${n} table`),i.debug("pk: "+e);const a=await this.evaluateTransaction(s,L.READ,[e.toString()],void 0,void 0,t.name);return this.serializer.deserialize(this.decode(a))}updatePrefix(t,e,r,...i){const s=$.tableName(t),{ctxArgs:n}=this.logCtx(i,this.updatePrefix),a={};return a[ct.TABLE]=s,Object.assign(a,r),[t,e,a,...n]}async update(t,e,r,i={},...s){const n=[...s],{log:a,ctx:o}=this.logCtx(n,this.updateAll);a.info("CLIENT UPDATE class : "+typeof t);const c=$.tableName(t);a.verbose(`updating entry to ${c} table`),a.debug("pk: "+e);const l=await this.submitTransaction(o,L.UPDATE,[this.serializer.serialize(r,t.name||t)],i,void 0,t.name);return this.serializer.deserialize(this.decode(l))}async delete(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.delete),n=$.tableName(t);i.verbose(`deleting entry from ${n} table`),i.debug("pk: "+e);const a=await this.submitTransaction(s,L.DELETE,[e.toString()],void 0,void 0,t.name);return this.serializer.deserialize(this.decode(a))}async raw(t,e=!0,r,...i){const{log:s,ctx:n}=this.logCtx(i,this.raw),a=r.name;let o,c;s.info("Performing raw statement on table "+$.tableName(r));try{o=await this.evaluateTransaction(n,"raw",[JSON.stringify(t),e],void 0,void 0,a)}catch(t){throw this.parseError(t)}try{c=JSON.parse(this.decode(o))}catch(t){throw new U("Failed to process result: "+t)}if(Array.isArray(c)){if(!c.length)return c;const t=c[0];return $.isModel(t)?c.map(t=>$.build(t)):c}return l=c,$.isModel(l)?$.build(l):l;var l}getClient(){return this._client||(this._client=mr.getClient(this.config)),this._client}async Gateway(t){return mr.getGateway(t,this.config,this.client)}getContractName(t){if(t)return t+"Contract"}async Contract(t,e){return mr.getContract(await this.Gateway(t),this.config,e)}async transaction(t,e,r=!0,i,s,n,a){const o=this.log.for(this.transaction),c=await this.Gateway(t);try{const c=await this.Contract(t,this.getContractName(a));o.verbose(`${r?"Submit":"Evaluate"}ting transaction ${this.getContractName(a)||this.config.contractName}.${e}`),o.debug("args: "+(i?.map(t=>t.toString()).join("\n")||"none"));const l=r?c.submit:c.evaluate;n=n?.length?n:void 0;const d={arguments:i||[],transientData:s};return await l.call(c,e,d)}catch(t){if(10===t.code)throw Error(""+t.details[0].message);throw this.parseError(t)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}parseError(t){return mr.parseError(t)}async submitTransaction(t,e,r,i,s,n){return this.transaction(t,e,!0,r,i,s,n)}async evaluateTransaction(t,e,r,i,s,n){return this.transaction(t,e,!1,r,i,s,n)}async close(){this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static getContract(t,e,r){const i=this.log.for(this.getContract),s=this.getNetwork(t,e.channel);let n;try{i.debug(`Retrieving chaincode ${e.chaincodeName} contract ${r||e.contractName} from network ${e.channel}`),r=r||e.contractName,n=s.getContract(e.chaincodeName,r)}catch(t){throw this.parseError(t)}return n}static getNetwork(t,e){const r=Et.for(this.getNetwork);let i;try{r.debug("Connecting to channel "+e),i=t.getNetwork(e)}catch(t){throw this.parseError(t)}return i}static async getGateway(t,e,r){return await this.getConnection(r||await this.getClient(e),e,t)}static getClient(t){const e=this.log.for(this.getClient);e.debug("generating TLS credentials for msp "+t.mspId);let r=t.tlsCert;if("string"==typeof r)if(r.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms))r=Buffer.from(r,"utf8");else try{r=Buffer.from(jt.readFileSync(r,"utf8"))}catch(t){throw new Y(`Failed to read the tls certificate from ${r}: ${t}`)}const i=Bt.credentials.createSsl(r);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new _t(t.peerEndpoint,i,{"grpc.max_receive_message_length":1024*(t.sizeLimit||15)*1024,"grpc.max_send_message_length":1024*(t.sizeLimit||15)*1024})}static async getConnection(t,e,r){const i=Et.for(this.getConnection);i.debug(`Retrieving Peer Identity for ${e.mspId} under ${e.certCertOrDirectoryPath}`);const s=await or(e.mspId,e.certCertOrDirectoryPath);i.debug("Retrieving signer key from "+e.keyCertOrDirectoryPath);let n,a=()=>{};if(e.hsm){const t=new ur(e.hsm.library),r=t.getSKIFromCertificatePath(e.certCertOrDirectoryPath),i=t.newSigner({label:e.hsm.tokenLabel,pin:e.hsm.pin+"",identifier:r});n=i.signer,a=i.close}else n=await dr(e.keyCertOrDirectoryPath);const o={client:t,identity:s,signer:n,evaluateOptions:()=>({deadline:Date.now()+1e3*r.get("evaluateTimeout")}),endorseOptions:()=>({deadline:Date.now()+1e3*r.get("endorseTimeout")}),submitOptions:()=>({deadline:Date.now()+1e3*r.get("submitTimeout")}),commitStatusOptions:()=>({deadline:Date.now()+1e3*r.get("commitTimeout")})};i.debug("Connecting to "+e.mspId);const c=Ot(o);return e.hsm&&(c.close=new Proxy(c.close,{apply(t,e,r){Reflect.apply(t,e,r),a()}})),c}Dispatch(){return new mr._baseDispatch}static parseError(t){const e="string"==typeof t?t:t.message;return e.includes("MVCC_READ_CONFLICT")?new ve(t):e.includes("ENDORSEMENT_POLICY_FAILURE")?new Se(t):e.includes("PHANTOM_READ_CONFLICT")?new Ee(t):t instanceof Error&&t.code&&9===t.code?new Ce(t):e.includes(J.name)?new J(t):e.includes(V.name)?new V(t):e.includes(ot.name)?new ot(t):e.includes(S.name)?new S(t):e.includes(x.name)?new x(t):e.includes(b.name)?new b(t):e.includes(N.name)?new N(t):e.includes(I.name)?new I(t):e.includes(g.name)?new g(t):e.includes(T.name)?new T(t):e.includes(O.name)?new O(t):e.includes(U.name)?new U(t):new Y(t)}}lt([Nt(),It(),dt("design:type",Function),dt("design:paramtypes",[Object,Object,Object,Object,l]),dt("design:returntype",Promise)],mr.prototype,"create",null),lt([Nt(),It(),dt("design:type",Function),dt("design:paramtypes",[Object,Object,l]),dt("design:returntype",Promise)],mr.prototype,"read",null),lt([Nt(),It(),dt("design:type",Function),dt("design:paramtypes",[Object,Object,Object,Object,l]),dt("design:returntype",Promise)],mr.prototype,"update",null),lt([Nt(),It(),dt("design:type",Function),dt("design:paramtypes",[Object,Object,l]),dt("design:returntype",Promise)],mr.prototype,"delete",null),lt([Nt(),dt("design:type",Function),dt("design:paramtypes",[Object,"function"==typeof(fr="undefined"!=typeof D&&D)?fr:Object,Object,l]),dt("design:returntype",Promise)],mr.prototype,"raw",null),mr.decoration(),E.setCurrent(re);class yr extends R{constructor(t){super(),this.client=t,this.decoder=new TextDecoder("utf8")}async close(){this.listeningStack&&this.listeningStack.close()}parsePayload(t){const e=this.decoder.decode(t);return JSON.parse(e)}observe(t){if(!(t instanceof mr))throw new b("Only FabricClientAdapter can be observed by dispatch");return super.observe(t),()=>this.unObserve(t)}async updateObservers(t,e,r,...i){const{log:s,ctxArgs:n}=E.logCtx(this.updateObservers,e,!1,...i);if(this.adapter)try{await this.adapter.refresh(t,e,r,...n)}catch(t){throw new Y("Failed to refresh dispatch: "+t)}else s.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof t?t:$.tableName(t)}:${e}`)}async handleEvents(t){if(!this.listeningStack)throw new Y('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new Y("No adapter found. should be impossible");const e=t||await this.adapter.context(L.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||$),r=this.log.for(this.handleEvents);r.info(`Listening for incoming events on chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}"...`);try{for await(const t of this.listeningStack){const{table:i,event:s,owner:n}=We(t.eventName);if(n&&n!==this.adapter.config?.mspId)continue;const a=this.parsePayload(t.payload);try{const t=(i?$.get(i):$.get(this.models[0].name))??(i||this.models[0]?.name);await this.updateObservers(t,s,a.id,e)}catch(t){r.error(`Failed update observables for table ${i} event ${s} id: ${a.id}: ${t}`)}}}catch(t){r.error(`Failed to read event for chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}": ${t}`),await this.close()}}async initialize(){if(!this.adapter)throw new Y("No adapter or config observed for dispatch");const t=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},$),{ctx:e}=this.logCtx([t],this.initialize),r=(await mr.getGateway(e,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new Y("No adapter observed for dispatch");this.listeningStack=await r.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(e)}}mr&&(mr._baseDispatch=yr);const wr="##VERSION##",br="##PACKAGE##";ht.registerLibrary(br,wr);export{fe as AllowanceError,ae as BASE_ALPHABET,ge as BalanceError,he as BaseEncoder,oe as CRYPTO,Yt as ClientSerializer,se as CoreUtils,ue as CryptoUtils,rr as DefaultFabricClientFlags,Je as DeterministicSerializer,de as ERC20Events,Ce as EndorsementError,Se as EndorsementPolicyError,Ie as FabricBaseModel,mr as FabricClientAdapter,yr as FabricClientDispatch,zt as FabricClientRepository,Gt as FabricERC20ClientRepository,xe as FabricEnrollmentService,re as FabricFlavour,Te as FabricIdentifiedBaseModel,er as FabricIdentityService,te as FabricModelKeys,le as HFCAIdentityAttributes,ce as HFCAIdentityType,ie as Identity,Zt as IdentityCredentials,ee as IdentityType,Le as ImplicitPrivateCollection,ye as MissingContextError,Ae as MissingPKCSS11Lib,Ke as ModelCollection,ve as MvccReadConflictError,be as NotInitializedError,pe as OverflowError,Oe as Owner,br as PACKAGE_NAME,Ee as PhantomReadConflictError,me as RegistrationError,Ne as RegistrationRequestBuilder,tr as SimpleDeterministicSerializer,we as UnauthorizedPrivateDataAccess,wr as VERSION,Xe as add,sr as contentOfLoadFile,Be as createMirrorHandler,Pe as deleteMirrorHandler,De as evalMirrorMetadata,hr as extractPrivateKey,qe as generateFabricEventName,qt as generateModelIndexes,ar as getCAUser,cr as getFirstDirFileName,lr as getFirstDirFileNameContent,or as getIdentity,dr as getSigner,je as mirror,$e as ownedBy,Re as ownedByOnCreate,We as parseEventName,Ge as privateData,nr as readFile,Wt as readModelFile,Xt as readModelFolders,Ze as safeParseInt,ze as segregatedDataOnCreate,Ue as segregatedDataOnDelete,Me as segregatedDataOnRead,He as segregatedDataOnUpdate,Ve as sharedData,Qe as sub,Fe as transactionId,ke as transactionIdOnCreate,_e as updateMirrorHandler,Qt as writeIndexes};
2
2
  //# sourceMappingURL=for-fabric.js.map