@decaf-ts/for-fabric 0.1.61 → 0.1.62

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.
Files changed (131) hide show
  1. package/dist/for-fabric.cjs +1 -1
  2. package/dist/for-fabric.cjs.map +1 -1
  3. package/dist/for-fabric.js +1 -1
  4. package/dist/for-fabric.js.map +1 -1
  5. package/lib/cli-module.cjs +101 -10
  6. package/lib/cli-module.js.map +1 -1
  7. package/lib/client/FabricClientDispatch.cjs +1 -0
  8. package/lib/client/FabricClientDispatch.d.ts +1 -1
  9. package/lib/client/FabricClientDispatch.js.map +1 -1
  10. package/lib/client/collections/generation.cjs +75 -107
  11. package/lib/client/collections/generation.d.ts +24 -5
  12. package/lib/client/collections/generation.js.map +1 -1
  13. package/lib/client/indexes/generation.cjs +9 -6
  14. package/lib/client/indexes/generation.d.ts +1 -1
  15. package/lib/client/indexes/generation.js.map +1 -1
  16. package/lib/contract/OtherProductContract.cjs +30 -0
  17. package/lib/contract/OtherProductContract.d.ts +5 -0
  18. package/lib/contract/OtherProductContract.js.map +1 -0
  19. package/lib/contract/OtherProductSharedContract.cjs +30 -0
  20. package/lib/contract/OtherProductSharedContract.d.ts +5 -0
  21. package/lib/contract/OtherProductSharedContract.js.map +1 -0
  22. package/lib/contract/index.cjs +2 -0
  23. package/lib/contract/index.js.map +1 -1
  24. package/lib/contract/models/Audit.cjs +20 -2
  25. package/lib/contract/models/Audit.d.ts +2 -1
  26. package/lib/contract/models/Audit.js.map +1 -1
  27. package/lib/contract/models/Batch.cjs +2 -2
  28. package/lib/contract/models/Batch.js.map +1 -1
  29. package/lib/contract/models/Leaflet.cjs +2 -2
  30. package/lib/contract/models/Leaflet.js.map +1 -1
  31. package/lib/contract/models/OtherProduct.cjs +74 -0
  32. package/lib/contract/models/OtherProduct.d.ts +12 -0
  33. package/lib/contract/models/OtherProduct.js.map +1 -0
  34. package/lib/contract/models/OtherProductShared.cjs +75 -0
  35. package/lib/contract/models/OtherProductShared.d.ts +12 -0
  36. package/lib/contract/models/OtherProductShared.js.map +1 -0
  37. package/lib/contract/models/Product.cjs +4 -4
  38. package/lib/contract/models/Product.js.map +1 -1
  39. package/lib/contract/models/decorators.cjs +15 -8
  40. package/lib/contract/models/decorators.d.ts +8 -5
  41. package/lib/contract/models/decorators.js.map +1 -1
  42. package/lib/contracts/FabricConstruction.cjs +1 -1
  43. package/lib/contracts/FabricConstruction.js.map +1 -1
  44. package/lib/contracts/FabricContractRepository.d.ts +3 -1
  45. package/lib/contracts/FabricContractSequence.cjs +4 -4
  46. package/lib/contracts/FabricContractSequence.js.map +1 -1
  47. package/lib/contracts/index.cjs +7 -6
  48. package/lib/contracts/index.d.ts +1 -0
  49. package/lib/contracts/index.js.map +1 -1
  50. package/lib/contracts/overrides.cjs +8 -0
  51. package/lib/contracts/overrides.d.ts +1 -0
  52. package/lib/contracts/overrides.js.map +1 -0
  53. package/lib/contracts/types.d.ts +1 -0
  54. package/lib/contracts/uuid.cjs +75 -0
  55. package/lib/contracts/uuid.d.ts +2 -0
  56. package/lib/contracts/uuid.js.map +1 -0
  57. package/lib/esm/cli-module.js +102 -11
  58. package/lib/esm/cli-module.js.map +1 -1
  59. package/lib/esm/client/FabricClientDispatch.d.ts +1 -1
  60. package/lib/esm/client/FabricClientDispatch.js +1 -0
  61. package/lib/esm/client/FabricClientDispatch.js.map +1 -1
  62. package/lib/esm/client/collections/generation.d.ts +24 -5
  63. package/lib/esm/client/collections/generation.js +70 -103
  64. package/lib/esm/client/collections/generation.js.map +1 -1
  65. package/lib/esm/client/indexes/generation.d.ts +1 -1
  66. package/lib/esm/client/indexes/generation.js +9 -6
  67. package/lib/esm/client/indexes/generation.js.map +1 -1
  68. package/lib/esm/contract/OtherProductContract.d.ts +5 -0
  69. package/lib/esm/contract/OtherProductContract.js +27 -0
  70. package/lib/esm/contract/OtherProductContract.js.map +1 -0
  71. package/lib/esm/contract/OtherProductSharedContract.d.ts +5 -0
  72. package/lib/esm/contract/OtherProductSharedContract.js +27 -0
  73. package/lib/esm/contract/OtherProductSharedContract.js.map +1 -0
  74. package/lib/esm/contract/index.js +2 -0
  75. package/lib/esm/contract/index.js.map +1 -1
  76. package/lib/esm/contract/models/Audit.d.ts +2 -1
  77. package/lib/esm/contract/models/Audit.js +22 -4
  78. package/lib/esm/contract/models/Audit.js.map +1 -1
  79. package/lib/esm/contract/models/Batch.js +2 -2
  80. package/lib/esm/contract/models/Batch.js.map +1 -1
  81. package/lib/esm/contract/models/Leaflet.js +2 -2
  82. package/lib/esm/contract/models/Leaflet.js.map +1 -1
  83. package/lib/esm/contract/models/OtherProduct.d.ts +12 -0
  84. package/lib/esm/contract/models/OtherProduct.js +71 -0
  85. package/lib/esm/contract/models/OtherProduct.js.map +1 -0
  86. package/lib/esm/contract/models/OtherProductShared.d.ts +12 -0
  87. package/lib/esm/contract/models/OtherProductShared.js +72 -0
  88. package/lib/esm/contract/models/OtherProductShared.js.map +1 -0
  89. package/lib/esm/contract/models/Product.js +4 -4
  90. package/lib/esm/contract/models/Product.js.map +1 -1
  91. package/lib/esm/contract/models/decorators.d.ts +8 -5
  92. package/lib/esm/contract/models/decorators.js +15 -8
  93. package/lib/esm/contract/models/decorators.js.map +1 -1
  94. package/lib/esm/contracts/FabricConstruction.js +1 -1
  95. package/lib/esm/contracts/FabricConstruction.js.map +1 -1
  96. package/lib/esm/contracts/FabricContractRepository.d.ts +3 -1
  97. package/lib/esm/contracts/FabricContractSequence.js +4 -4
  98. package/lib/esm/contracts/FabricContractSequence.js.map +1 -1
  99. package/lib/esm/contracts/index.d.ts +1 -0
  100. package/lib/esm/contracts/index.js +1 -0
  101. package/lib/esm/contracts/index.js.map +1 -1
  102. package/lib/esm/contracts/overrides.d.ts +1 -0
  103. package/lib/esm/contracts/overrides.js +6 -0
  104. package/lib/esm/contracts/overrides.js.map +1 -0
  105. package/lib/esm/contracts/types.d.ts +1 -0
  106. package/lib/esm/contracts/uuid.d.ts +2 -0
  107. package/lib/esm/contracts/uuid.js +38 -0
  108. package/lib/esm/contracts/uuid.js.map +1 -0
  109. package/lib/esm/shared/constants.d.ts +4 -3
  110. package/lib/esm/shared/constants.js +3 -2
  111. package/lib/esm/shared/constants.js.map +1 -1
  112. package/lib/esm/shared/decorators.d.ts +15 -2
  113. package/lib/esm/shared/decorators.js +114 -69
  114. package/lib/esm/shared/decorators.js.map +1 -1
  115. package/lib/esm/shared/overrides/Model.d.ts +7 -0
  116. package/lib/esm/shared/overrides/overrides.js +28 -15
  117. package/lib/esm/shared/overrides/overrides.js.map +1 -1
  118. package/lib/esm/version.d.ts +1 -1
  119. package/lib/esm/version.js +1 -1
  120. package/lib/shared/constants.cjs +3 -2
  121. package/lib/shared/constants.d.ts +4 -3
  122. package/lib/shared/constants.js.map +1 -1
  123. package/lib/shared/decorators.cjs +118 -68
  124. package/lib/shared/decorators.d.ts +15 -2
  125. package/lib/shared/decorators.js.map +1 -1
  126. package/lib/shared/overrides/Model.d.ts +7 -0
  127. package/lib/shared/overrides/overrides.cjs +28 -15
  128. package/lib/shared/overrides/overrides.js.map +1 -1
  129. package/lib/version.cjs +1 -1
  130. package/lib/version.d.ts +1 -1
  131. package/package.json +2 -1
@@ -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,DefaultAdapterFlags as A,Statement as v,QueryClause as S,Adapter as E,QueryError as x,PagingError as N,MigrationError as T,ObserverError as I,ForbiddenError as O,ConnectionError as $,Dispatch as R}from"@decaf-ts/core";import{Model as F,required as k,model as B,JSONSerializer as P,ModelKeys as _,stringFormat as j,minlength as K,min as L}from"@decaf-ts/decorator-validation";import{OperationKeys as z,enforceDBDecorators as H,reduceErrorsToPrint as M,ValidationError as U,SerializationError as Y,InternalError as G,BaseError as V,ConflictError as J,NotFoundError as q,version as X,DBKeys as W,readonly as Q,onCreate as Z,onUpdate as tt,transient as et,onRead as rt,onDelete as it,BulkCrudOperationKeys as st,BadRequestError as nt}from"@decaf-ts/db-decorators";import{CouchDBKeys as at}from"@decaf-ts/for-couchdb";import{__decorate as ot,__metadata as ct}from"tslib";import{Metadata as lt,description as dt,uses as ht,Decoration as ut,apply as pt,propMetadata as gt,metadata as ft}from"@decaf-ts/decoration";import mt from"fabric-ca-client";import{MiniLogger as yt,isBrowser as wt,LoggedClass as bt,Logging as Ct,toCamelCase as At,debug as vt,final as St}from"@decaf-ts/logging";import{signers as Et,connect as xt}from"@hyperledger/fabric-gateway";import{User as Nt}from"fabric-common";import Tt,{X509Certificate as It}from"crypto";import*as Ot from"@peculiar/x509";import{Crypto as $t}from"@peculiar/webcrypto";import*as Rt from"@grpc/grpc-js";import{Client as Dt}from"@grpc/grpc-js";import Ft from"pkcs11js";import kt from"fs";import Bt from"path";import{p256 as Pt}from"@noble/curves/nist";class _t 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 ${F.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 ${F.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 ${F.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 ${F.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[at.TABLE]&&t[at.TABLE]===F.tableName(this.class)?new this.class(t):t):c[at.TABLE]&&c[at.TABLE]===F.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 ${F.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 ${F.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,z.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 H(this,r,t,z.CREATE,z.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 U(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 ${F.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 ${F.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 jt=class extends o{constructor(t){super(t)}};ot([s({type:String}),ct("design:type",String)],jt.prototype,"name",void 0),ot([n(),k(),ct("design:type",String)],jt.prototype,"owner",void 0),ot([n(),k(),ct("design:type",String)],jt.prototype,"symbol",void 0),ot([n(),k(),ct("design:type",Number)],jt.prototype,"decimals",void 0),jt=ot([a("erc20_tokens"),B(),ct("design:paramtypes",[Object])],jt);let Kt=class extends o{constructor(t){super(t)}};ot([s({type:String}),ct("design:type",String)],Kt.prototype,"id",void 0),ot([n(),k(),ct("design:type",String)],Kt.prototype,"token",void 0),ot([n(),k(),ct("design:type",Number)],Kt.prototype,"balance",void 0),ot([n(),ct("design:type",String)],Kt.prototype,"captive",void 0),Kt=ot([a("erc20_wallets"),B(),ct("design:paramtypes",[Object])],Kt);let Lt=class extends o{constructor(t){super(t)}};ot([s({type:String}),n(),k(),ct("design:type",String)],Lt.prototype,"owner",void 0),ot([n(),k(),ct("design:type",String)],Lt.prototype,"spender",void 0),ot([n(),k(),ct("design:type",Number)],Lt.prototype,"value",void 0),Lt=ot([a("erc20_allowances"),B(),ct("design:paramtypes",[Object])],Lt);class zt extends P{constructor(){super()}preSerialize(t,e){const r=Object.assign({},t);let i=lt.modelName(t.constructor);if(!i||"Object"===i){if(!e)throw new Y("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 F.build(e,r)}serialize(t,e){return JSON.stringify(this.preSerialize(t,e))}}class Ht extends _t{static{this.serializer=new zt}static{this.decoder=new TextDecoder("utf8")}async updateObservers(t,e,r,...i){if(!this.observerHandler)throw new G("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?F.get(t):t,a=void 0===r?void 0:Array.isArray(r)?r.map(e=>c.parseValue(F.sequenceFor(t).type,e)):c.parseValue(F.sequenceFor(t).type,r),await this.observerHandler.updateObservers(t,e,a,...n)}decode(t){return Ht.decoder.decode(t)}constructor(t){super(t,Kt),this.serializer=Ht.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",[Ht.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 Mt(t,e,r){return[...t.map(t=>t===at.TABLE?"table":t),...r||[],...e?[e]:[],"index"].join(lt.splitter)}function Ut(t,e,r,i){const s=Mt(e,r,i);let n=[...e,...i||[]];r&&(n=n.reduce((t,e)=>{const i={};return i[e]=r,t.push(i),t},[]));const a={index:{fields:n},name:s,ddoc:s,type:"json"};t[s]=a}function Yt(t,e){const r=Mt([at.TABLE]),i=e||{};i[r]={index:{fields:[at.TABLE]},name:r,ddoc:r,type:"json"};const s={},n=F.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,at.TABLE];Ut(s,n),i&&i.length&&Ut(s,n,void 0,i),r&&r.length&&r.forEach(t=>{Ut(s,n,t),i&&i.length&&Ut(s,n,t,i)})}return Object.entries(s).forEach(([t,e])=>{i[t]=e}),Object.values(s)}function Gt(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 F}catch(t){return!1}})}async function Vt(...t){const e=require("fs");require("path");const 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(...Gt(e))}return r}function Jt(t,e=process.cwd()){const r=require("fs"),i=require("path");function s(t){const e=i.dirname(t);if(r.existsSync(e))return!0;s(e),r.mkdirSync(e)}t.forEach(t=>{const n=i.resolve(i.join(e,`./META-INF/statedb/couchdb/indexes/${t.name}.json`));s(n),r.writeFileSync(n,JSON.stringify(t,void 0,2))})}let qt=class extends o{constructor(t){super(t)}};var Xt,Wt;ot([dt("Unique identifier of the credentials record"),n(),s(),ct("design:type",String)],qt.prototype,"id",void 0),ot([dt("PEM-encoded X.509 certificate for the identity"),n(),k(),ct("design:type",String)],qt.prototype,"certificate",void 0),ot([dt("PEM-encoded root or intermediate certificate"),n(),k(),ct("design:type",String)],qt.prototype,"rootCertificate",void 0),ot([dt("PEM-encoded private key"),n(),k(),ct("design:type",String)],qt.prototype,"privateKey",void 0),qt=ot([B(),ct("design:paramtypes",[Object])],qt),(t=>{t.PRIVATE="private",t.SHARED="shared",t.FABRIC="fabric.",t.OWNEDBY="owned-by",t.TRANSACTION_ID="transaction-id"})(Xt||(Xt={})),(t=>{t.X509="X.509"})(Wt||(Wt={}));const Qt="hlf-fabric";let Zt=class extends o{constructor(t){super(t),this.type=Wt.X509}};ot([dt("Unique identifier of the identity"),s(),ct("design:type",String)],Zt.prototype,"id",void 0),ot([d(qt,{update:h.CASCADE,delete:h.CASCADE}),ct("design:type",qt)],Zt.prototype,"credentials",void 0),ot([n(),k(),u(),ct("design:type",String)],Zt.prototype,"mspId",void 0),ot([n(),k(),ct("design:type",String)],Zt.prototype,"type",void 0),Zt=ot([B(),ct("design:paramtypes",[Object])],Zt);class te{static{this.logger=new yt(te.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(j("Creating CA {0} user {1} with certificate {2}",i,t,r));const n=new Nt(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?(te.cryptoSuite||(te.cryptoSuite=Nt.newCryptoSuite(t)),te.cryptoSuite):Nt.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 It(t).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(e.x||"","base64url"),s=Buffer.from(e.y||"","base64url");return Tt.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 Et.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 ee=new $t;var re,ie,se,ne,ae;Ot.cryptoProvider.set(ee),(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-_.!~"})(re||(re={})),(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"})(ie||(ie={}));class oe{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 ce{static{this.b58encoder=new oe(re.BASE58)}static{this.logger=new yt(ce.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(j("Parsing certificate: {0}",t));const e=new Ot.X509Certificate(t),{subject:r,issuer:i}=e;return this.logger.debug(j("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=ee.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 ee.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 Ot.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,ee.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,e,r)}static async encrypt(t,e){const r=new Ot.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 wt()?globalThis.window.crypto.subtle:ee.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=ee.randomUUID();t=e.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,ie.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:ie.KEY_ALGORYTHM,hash:ie.HASH,salt:i,iterations:ie.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,e,8*ie.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:ie.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:ie.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:ie.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}class le extends G{constructor(t){super(t,le.name)}}class de extends G{constructor(t){super(t,de.name)}}class he extends G{constructor(t){super(t,he.name)}}class ue extends g{constructor(t){super(t,ue.name)}}class pe extends G{constructor(t){super(t,pe.name,500)}}class ge extends V{constructor(t="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(ge.name,t,403)}}class fe extends V{constructor(t){super(fe.name,t,409)}}class me extends G{constructor(t){super(t,me.name,500)}}class ye extends G{constructor(t){super(t,ye.name,500)}}class we extends G{constructor(t){super(t,we.name,500)}}class be extends G{constructor(t){super(t,be.name,500)}}class Ce extends G{constructor(t){super(t,Ce.name,500)}}(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(se||(se={})),(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"})(ne||(ne={}));class Ae extends bt{constructor(t){te.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 te.getFirstDirFileNameContent(e);let o;if(s)n.debug(`Using HSM configuration for CA ${t} with library ${s.library}`);else{if(!r)throw new G(`Missing caKey configuration for CA ${t}. Provide a key directory or configure HSM support.`);n.debug("Retrieving CA key from "+r),o=await te.getFirstDirFileNameContent(r)}return n.debug("Loading Admin user for ca "+t),this.user=await te.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 te.getFileContent(a);return t.debug(`Creating CA Client for CA ${i} under ${e}`),this.ca=new mt(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 ue(t);const[,r,i]=e;switch(r){case"74":case"71":return new J(i);case"20":return new g(i);default:return new ue(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 q(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new q(`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=Ct.for(Ae,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${r} in msp ${e}`);const a=ce.fabricIdFromCertificate(r),o=ce.encode(a);n.debug(`Identity ${a} and encodedId ${o}`);const c=new Date;return new Zt({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=Ae.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 q("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 G(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new G(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}class ve extends F{constructor(){super(...arguments),this.affiliation=""}build(){const t=this.hasErrors();if(t)throw new U(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}}ot([k(),ct("design:type",String)],ve.prototype,"affiliation",void 0),ot([K(1),ct("design:type",Array)],ve.prototype,"attrs",void 0),ot([k(),ct("design:type",String)],ve.prototype,"enrollmentID",void 0),ot([k(),ct("design:type",String)],ve.prototype,"enrollmentSecret",void 0),ot([L(0),ct("design:type",Number)],ve.prototype,"maxEnrollments",void 0),ot([k(),ct("design:type",String)],ve.prototype,"role",void 0),(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(ae||(ae={}));let Se=class extends F{constructor(t){super(t)}};ot([dt("Stores the original timestamp of creation"),n(),f(),ct("design:type",Date)],Se.prototype,"createdAt",void 0),ot([dt("Stores the timestamp of the last update"),n(),m(),ct("design:type",Date)],Se.prototype,"updatedAt",void 0),ot([dt("Stores the version of the model"),n(),X(),ct("design:type",Number)],Se.prototype,"version",void 0),Se=ot([ht(Qt),ct("design:paramtypes",[Object])],Se);let Ee=class extends Se{constructor(t){super(t)}};function xe(){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 q("No tokens avaialble");if(a.length>1)throw new q("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 Ne(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 Te(){const t=$e(Xt.OWNEDBY);return ut.for(t).define({decorator:()=>(t,e)=>pt(k(),Q(),Z(Ne),gt($e(Xt.OWNEDBY),e))(t,e),args:[]}).apply()}async function Ie(t,e,r,i){const{stub:s}=t;i[r]=s.getTxID()}function Oe(){return ut.for(Xt.TRANSACTION_ID).define({decorator:()=>(t,e)=>pt(k(),Q(),Z(Ie),tt(Ie),gt(lt.key(Xt.FABRIC,e,Xt.TRANSACTION_ID),e))(t,e),args:[]}).apply()}function $e(t){return lt.key(Xt.FABRIC+t)}ot([dt("Stores the creator"),n(),y(),ct("design:type",String)],Ee.prototype,"createdBy",void 0),ot([dt("Stores the user that last updated the model"),n(),w(),ct("design:type",String)],Ee.prototype,"updatedBy",void 0),Ee=ot([ht(Qt),ct("design:paramtypes",[Object])],Ee),F.prototype.isShared=function(){return F.isShared(this.constructor)},F.prototype.isPrivate=function(){return F.isPrivate(this.constructor)},F.prototype.segregate=function(){return F.segregate(this)},F.segregate=(t=>{if(!F.isTransient(t))return{model:t};const e=lt.validatableProperties(t.constructor),r=lt.get(t.constructor,W.TRANSIENT),i=lt.get(t.constructor,Xt.PRIVATE),s=lt.get(t.constructor,Xt.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=F.build(n.model,t.constructor.name),n}).bind(F),F.tableName=t=>{const e=t instanceof F?t.constructor:t;return lt.get(e,r.TABLE)||(t instanceof F?t.constructor.name:t.name)},F.isPrivate=(t=>!!lt.get("function"!=typeof t?t.constructor:t,Xt.PRIVATE)).bind(F),lt.isShared=(t=>!!lt.get("function"!=typeof t?t.constructor:t,Xt.SHARED)).bind(lt);const Re=t=>`__${t.constructor.name}PrivateCollection`;async function De(t,e,r,i){if(r.length!==e.length)throw new G("Segregated data keys and metadata length mismatch");const s=e[0].collections,n="string"==typeof s?s:s(i),a=r.reduce((t,r,s)=>{const a="string"==typeof e[s].collections?e[s].collections:e[s].collections(i);if(a!==n)throw new b(`Segregated data collection mismatch: ${a} vs ${n}`);return t[r]=i[r],t},{}),o=new this.class(a),c=await this.override({segregated:n}).create(o,t);Object.assign(i,c)}async function Fe(t,e,r,i){if(r.length!==e.length)throw new G("Segregated data keys and metadata length mismatch");const s=e[0].collections,n="string"==typeof s?s:s(i),a=r.reduce((t,r,s)=>{const a="string"==typeof e[s].collections?e[s].collections:e[s].collections(i);if(a!==n)throw new b(`Segregated data collection mismatch: ${a} vs ${n}`);return t[r]=i[r],t},{}),o=new this.class(a),c=await this.override({segregated:n}).create(o,t);Object.assign(i,c)}async function ke(t,e,r,i,s){}async function Be(t,e,r,i){}function Pe(t,e){return(r,i)=>{const s=[];return i?(s.push(et(),(r,i)=>{if(!i){const i=lt.properties(r)||[];for(const s of i)Pe(t,e)(r,s);return r}const s=lt.key(e,i),n=r.constructor,a=lt.get(n,s)||{},o=new Set(a.collections||[]);o.add(t),a.collections=[...o],lt.set(n,s,a)},Z(De,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),rt(Fe,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),tt(ke,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),it(Be,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()})),pt(...s)(r,i)):(lt.properties(r)?.forEach(i=>Pe(t,e)(r,i)),ft(e,!0)(r))}}function _e(t=Re){return ut.for(Xt.PRIVATE).define({decorator:t=>Pe(t,Xt.PRIVATE),args:[t]}).apply()}function je(t){return ut.for(Xt.SHARED).define({decorator:t=>Pe(t,Xt.SHARED),args:[t]}).apply()}class Ke extends P{constructor(){super()}preSerialize(t){const e=Object.assign({},t);let r;try{r=lt.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 F.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 F.build(e,r)}serialize(t){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t)))}}function Le(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function ze(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 He(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new le(`Addition overflow: ${t} + ${e}`);return r}function Me(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new le(`Subtraction overflow: ${t} - ${e}`);return r}function Ue(t){if(!/^\d+$/.test(t))throw new U(j("Failed to parse: {0}","string contains digits"));const e=parseInt(t);if(isNaN(e))throw new U(j("Failed to parse: {0}","string is not a parsable integer"));return e}class Ye extends P{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=lt.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),F.relations(t).forEach(t=>{r[t]=s.call(this,r[t])}),r}}class Ge extends C{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new G("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 te.getFirstDirFileNameContent(s);let l;if(o)r.debug(`Using HSM configuration for CA ${i} with library ${o.library}`);else{if(!n)throw new G(`Missing caKey configuration for CA ${i}. Provide a key directory or configure HSM support.`);r.debug("Retrieving CA key from "+n),l=await te.getFirstDirFileNameContent(n)}return r.debug("Loading Admin user for ca "+i),this._user=await te.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 G("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 te.getFileContent(l);e.debug("CA Certificate: "+d.toString());const h=new mt(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 ue(t);const[,r,i]=e;switch(r){case"74":case"71":return new J(i);case"20":return new g(i);default:return new ue(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 q(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new q(`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=ce.fabricIdFromCertificate(s),c=ce.encode(o);return i.debug(`Identity ${o} and encodedId ${c}`),new Zt({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=Ge.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 q("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 G(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new G(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}const Ve=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60},A),Je=new yt("fabric-fs");async function qe(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}async function Xe(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await p(import("fs"));return await e.readFile(t)})(t)}async function We(t,e,r,i){Je.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const s=new Nt(t),n=Nt.newCryptoSuite();s.setCryptoSuite(n);const a=n.createKeyFromRaw(e);return await s.setEnrollment(a,r,i),s}async function Qe(t,e){const r=await qe(e,async t=>{const{promises:e}=await p(import("fs")),r=await Ze(t);return await e.readFile(r)});return{mspId:t,credentials:r}}async function Ze(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path"));return r(t,(await e.readdir(t))[0])}async function tr(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 er(t){const e=await qe(t,async t=>{const{promises:e}=await p(import("fs")),r=await Ze(t);return await e.readFile(r)}),r=await rr(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Et.newPrivateKeySigner(i)}async function rr(t){let e;if(wt())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 G(t)}}class ir{static#t=null;static#e=!1;constructor(t){if(ir.#t||(ir.#t=new Ft.PKCS11,ir.#t.load(this.findHSMPKCS11Lib(t))),!ir.#e){try{ir.#t.C_Initialize()}catch(t){if(t.code!==Ft.CKR_CRYPTOKI_ALREADY_INITIALIZED)throw t}ir.#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(kt.existsSync(t))return t;throw new me("Unable to find PKCS11 library")}dispose(){ir.#t.C_Finalize()}sanitizeOptions(t){const e=Object.assign({userType:Ft.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=ir.#t.C_GetSlotList(!0);if(0===e.length)throw Error("No pkcs11 slots can be found");const r=e.find(e=>ir.#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{ir.#t.C_Login(t,e,r)}catch(t){if(t.code!==Ft.CKR_USER_ALREADY_LOGGED_IN)throw t}}findObjectInHSM(t,e,r){const i=[{type:Ft.CKA_ID,value:r},{type:Ft.CKA_CLASS,value:e},{type:Ft.CKA_KEY_TYPE,value:Ft.CKK_EC}];ir.#t.C_FindObjectsInit(t,i);const s=ir.#t.C_FindObjects(t,1)[0];if(!s)throw ir.#t.C_FindObjectsFinal(t),Error("Unable to find object in HSM with ID "+r.toString());return ir.#t.C_FindObjectsFinal(t),s}newSigner(t){const e=this.sanitizeOptions(t),r=ir.#t,i=this.findSlotForLabel(e.label),s=r.C_OpenSession(i,Ft.CKF_SERIAL_SESSION);let n;try{this.login(s,e.userType,e.pin),n=this.findObjectInHSM(s,Ft.CKO_PRIVATE_KEY,e.identifier)}catch(t){throw ir.#t.C_CloseSession(s),t}return{signer:async t=>{ir.#t.C_SignInit(s,{mechanism:Ft.CKM_ECDSA},n);const e=await ir.#t.C_SignAsync(s,Buffer.from(t),Buffer.alloc(2*Pt.Point.Fn.BYTES));return Pt.Signature.fromBytes(e,"compact").normalizeS().toBytes("der")},close:()=>{ir.#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:Bt.join(t,"cert.pem"),r=kt.readFileSync(e);return this.getSKIFromCertificate(r)}getSKIFromCertificate(t){const e=new Tt.X509Certificate(t),r=this.getUncompressedPointOnCurve(e.publicKey);return Tt.createHash("sha256").update(r).digest()}}class sr extends v{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 G("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=[S.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(S.SELECT,this.selectSelector.join(` ${S.AND.toLowerCase()} `)),this.orderBySelector&&(n.push(S.ORDER_BY,this.orderBySelector[0]),e.push(this.orderBySelector[1])),s.method=At(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 nr 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 ar;class or extends E{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new zt}static{this.log=Ct.for(or)}constructor(t,e){super(t,Qt,e),this.serializer=or.serializer}Statement(t){return new sr(this,t)}Paginator(t,e,r){return new nr(this,t,e,r)}flags(t,e,r,...i){return super.flags(t,e,r,...i)}async context(t,e,r,...i){this.log.for(this.context).silly(`creating new context for ${t} operation on ${r?Array.isArray(r)?r.map(t=>F.tableName(t)):F.tableName(r):"no"} table ${e&&Object.keys(e)?Object.keys(e).length:"no"} with flag overrides`);let s=i.pop();void 0===s||s instanceof l||(i.push(s),s=void 0),e=s?Object.assign({},e,s.toOverrides()):e;const n=await this.flags("string"==typeof t?t:t.name,r,e,...i,s);if(s){if(!(s instanceof this.Context))return(new this.Context).accumulate({...s.cache,...n,parentContext:s});const e=s.get("operation"),i=s.get("affectedTables");return e!==t||r!==i?(new this.Context).accumulate({...s.cache,...n,parentContext:s}):s.accumulate(n)}return(new this.Context).accumulate({...Ve,...n})}decode(t){return or.decoder.decode(t)}repository(){return _t}createPrefix(t,e,r,...i){const{ctxArgs:s}=this.logCtx(i,this.createPrefix),n=F.tableName(t),a={};return a[at.TABLE]=n,Object.assign(a,r),[t,e,a,...s]}createAllPrefix(t,e,r,...i){const s=F.tableName(t);if(e.length!==r.length)throw new G("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[at.TABLE]=s,Object.assign(i,r[e]),i});return[t,e,a,...n]}updateAllPrefix(t,e,r,...i){const s=F.tableName(t);if(e.length!==r.length)throw new G("Ids and models must have the same length");const{ctxArgs:n}=this.logCtx(i,this.updateAllPrefix),a=e.map(()=>{const t={};return t[at.TABLE]=s,t});return[t,e,a,...n]}async createAll(t,e,r,...i){if(e.length!==r.length)throw new G("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.createAll),c=F.tableName(t);a.info(`adding ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=await this.submitTransaction(o,st.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 Y(t)}}async readAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.readAll),n=F.tableName(t);i.info(`reading ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.evaluateTransaction(s,st.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 Y(t)}}async updateAll(t,e,r,...i){if(e.length!==r.length)throw new G("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.updateAll),c=F.tableName(t);a.info(`updating ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=await this.submitTransaction(o,st.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 Y(t)}}async deleteAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.deleteAll),n=F.tableName(t);i.info(`deleting ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.submitTransaction(s,st.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 Y(t)}}prepare(t,...e){const{log:i}=this.logCtx(e,this.prepare),s=F.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[F.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 G(`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=F.tableName(t);a.verbose(`adding entry to ${c} table`),a.debug("pk: "+e);const l=await this.submitTransaction(o,z.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=F.tableName(t);i.verbose(`reading entry from ${n} table`),i.debug("pk: "+e);const a=await this.evaluateTransaction(s,z.READ,[e.toString()],void 0,void 0,t.name);return this.serializer.deserialize(this.decode(a))}updatePrefix(t,e,r,...i){const s=F.tableName(t),{ctxArgs:n}=this.logCtx(i,this.updatePrefix),a={};return a[at.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=F.tableName(t);a.verbose(`updating entry to ${c} table`),a.debug("pk: "+e);const l=await this.submitTransaction(o,z.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=F.tableName(t);i.verbose(`deleting entry from ${n} table`),i.debug("pk: "+e);const a=await this.submitTransaction(s,z.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 "+F.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 Y("Failed to process result: "+t)}if(Array.isArray(c)){if(!c.length)return c;const t=c[0];return F.isModel(t)?c.map(t=>F.build(t)):c}return l=c,F.isModel(l)?F.build(l):l;var l}getClient(){return this._client||(this._client=or.getClient(this.config)),this._client}async Gateway(t){return or.getGateway(t,this.config,this.client)}getContractName(t){if(t)return t+"Contract"}async Contract(t,e){return or.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 or.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=Ct.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(kt.readFileSync(r,"utf8"))}catch(t){throw new G(`Failed to read the tls certificate from ${r}: ${t}`)}const i=Rt.credentials.createSsl(r);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new Dt(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=Ct.for(this.getConnection);i.debug(`Retrieving Peer Identity for ${e.mspId} under ${e.certCertOrDirectoryPath}`);const s=await Qe(e.mspId,e.certCertOrDirectoryPath);i.debug("Retrieving signer key from "+e.keyCertOrDirectoryPath);let n,a=()=>{};if(e.hsm){const t=new ir(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 er(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=xt(o);return e.hsm&&(c.close=new Proxy(c.close,{apply(t,e,r){Reflect.apply(t,e,r),a()}})),c}Dispatch(){return new or._baseDispatch}static parseError(t){const e="string"==typeof t?t:t.message;return e.includes("MVCC_READ_CONFLICT")?new we(t):e.includes("ENDORSEMENT_POLICY_FAILURE")?new Ce(t):e.includes("PHANTOM_READ_CONFLICT")?new be(t):t instanceof Error&&t.code&&9===t.code?new ye(t):e.includes(q.name)?new q(t):e.includes(J.name)?new J(t):e.includes(nt.name)?new nt(t):e.includes(x.name)?new x(t):e.includes(N.name)?new N(t):e.includes(b.name)?new b(t):e.includes(T.name)?new T(t):e.includes(I.name)?new I(t):e.includes(g.name)?new g(t):e.includes(O.name)?new O(t):e.includes($.name)?new $(t):e.includes(Y.name)?new Y(t):new G(t)}}ot([vt(),St(),ct("design:type",Function),ct("design:paramtypes",[Object,Object,Object,Object,l]),ct("design:returntype",Promise)],or.prototype,"create",null),ot([vt(),St(),ct("design:type",Function),ct("design:paramtypes",[Object,Object,l]),ct("design:returntype",Promise)],or.prototype,"read",null),ot([vt(),St(),ct("design:type",Function),ct("design:paramtypes",[Object,Object,Object,Object,l]),ct("design:returntype",Promise)],or.prototype,"update",null),ot([vt(),St(),ct("design:type",Function),ct("design:paramtypes",[Object,Object,l]),ct("design:returntype",Promise)],or.prototype,"delete",null),ot([vt(),ct("design:type",Function),ct("design:paramtypes",[Object,"function"==typeof(ar="undefined"!=typeof D&&D)?ar:Object,Object,l]),ct("design:returntype",Promise)],or.prototype,"raw",null),or.decoration(),E.setCurrent(Qt);class cr 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 or))throw new b("Only FabricClientAdapter can be observed by dispatch");super.observe(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 G("Failed to refresh dispatch: "+t)}else s.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof t?t:F.tableName(t)}:${e}`)}async handleEvents(t){if(!this.listeningStack)throw new G('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new G("No adapter found. should be impossible");const e=t||await this.adapter.context(z.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||F),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}=ze(t.eventName);if(n&&n!==this.adapter.config?.mspId)continue;const a=this.parsePayload(t.payload);try{const t=(i?F.get(i):F.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 G("No adapter or config observed for dispatch");const t=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},F),{ctx:e}=this.logCtx([t],this.initialize),r=(await or.getGateway(e,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new G("No adapter observed for dispatch");this.listeningStack=await r.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(e)}}or&&(or._baseDispatch=cr);const lr="##VERSION##",dr="##PACKAGE##";lt.registerLibrary(dr,lr);export{he as AllowanceError,re as BASE_ALPHABET,de as BalanceError,oe as BaseEncoder,ie as CRYPTO,zt as ClientSerializer,te as CoreUtils,ce as CryptoUtils,Ve as DefaultFabricClientFlags,Ke as DeterministicSerializer,ae as ERC20Events,ye as EndorsementError,Ce as EndorsementPolicyError,Se as FabricBaseModel,or as FabricClientAdapter,cr as FabricClientDispatch,_t as FabricClientRepository,Ht as FabricERC20ClientRepository,Ae as FabricEnrollmentService,Qt as FabricFlavour,Ee as FabricIdentifiedBaseModel,Ge as FabricIdentityService,Xt as FabricModelKeys,ne as HFCAIdentityAttributes,se as HFCAIdentityType,Zt as Identity,qt as IdentityCredentials,Wt as IdentityType,Re as ImplicitPrivateCollection,pe as MissingContextError,me as MissingPKCSS11Lib,we as MvccReadConflictError,fe as NotInitializedError,le as OverflowError,xe as Owner,dr as PACKAGE_NAME,be as PhantomReadConflictError,ue as RegistrationError,ve as RegistrationRequestBuilder,Ye as SimpleDeterministicSerializer,ge as UnauthorizedPrivateDataAccess,lr as VERSION,He as add,qe as contentOfLoadFile,rr as extractPrivateKey,Le as generateFabricEventName,Yt as generateModelIndexes,We as getCAUser,$e as getFabricModelKey,Ze as getFirstDirFileName,tr as getFirstDirFileNameContent,Qe as getIdentity,er as getSigner,Te as ownedBy,Ne as ownedByOnCreate,ze as parseEventName,_e as privateData,Xe as readFile,Gt as readModelFile,Vt as readModelFolders,Ue as safeParseInt,De as segregatedDataOnCreate,Be as segregatedDataOnDelete,Fe as segregatedDataOnRead,ke as segregatedDataOnUpdate,je as sharedData,Me as sub,Oe as transactionId,Ie as transactionIdOnCreate,Jt 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 C,DefaultAdapterFlags as A,Statement as v,QueryClause as S,Adapter as E,QueryError as x,PagingError as N,MigrationError as T,ObserverError as I,ForbiddenError as O,ConnectionError as R,Dispatch as $}from"@decaf-ts/core";import{Model as k,required as F,model as B,JSONSerializer as _,ModelKeys as P,stringFormat as j,minlength as K,min as L}from"@decaf-ts/decorator-validation";import{OperationKeys as z,enforceDBDecorators as M,reduceErrorsToPrint as H,ValidationError as U,SerializationError as Y,InternalError as G,BaseError as V,ConflictError as J,NotFoundError as q,version as W,DBKeys as X,readonly as Q,onCreate as Z,onUpdate as tt,afterCreate as et,afterUpdate as rt,afterDelete as it,transient as st,onRead as nt,onDelete as at,BulkCrudOperationKeys as ot,BadRequestError as ct}from"@decaf-ts/db-decorators";import{CouchDBKeys as lt}from"@decaf-ts/for-couchdb";import{__decorate as dt,__metadata as ht}from"tslib";import{Metadata as ut,description as pt,uses as gt,Decoration as ft,apply as mt,propMetadata as yt,metadata as wt,prop as bt}from"@decaf-ts/decoration";import Ct from"fabric-ca-client";import{MiniLogger as At,isBrowser as vt,LoggedClass as St,Logging as Et,toPascalCase as xt,toCamelCase as Nt,debug as Tt,final as It}from"@decaf-ts/logging";import{signers as Ot,connect as Rt}from"@hyperledger/fabric-gateway";import{User as $t}from"fabric-common";import kt,{X509Certificate as Ft}from"crypto";import*as Dt from"@peculiar/x509";import{Crypto as Bt}from"@peculiar/webcrypto";import*as _t from"@grpc/grpc-js";import{Client as Pt}from"@grpc/grpc-js";import jt from"pkcs11js";import Kt from"fs";import Lt from"path";import{p256 as zt}from"@noble/curves/nist";class Mt 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 ${k.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 ${k.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 ${k.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 ${k.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[lt.TABLE]&&t[lt.TABLE]===k.tableName(this.class)?new this.class(t):t):c[lt.TABLE]&&c[lt.TABLE]===k.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 ${k.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 ${k.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,z.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 M(this,r,t,z.CREATE,z.ON),t))),!n){const e=r.get("ignoredValidationProperties")||[],i=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),s=H(i);if(s)throw new U(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 ${k.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 ${k.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 Ht=class extends o{constructor(t){super(t)}};dt([s({type:String}),ht("design:type",String)],Ht.prototype,"name",void 0),dt([n(),F(),ht("design:type",String)],Ht.prototype,"owner",void 0),dt([n(),F(),ht("design:type",String)],Ht.prototype,"symbol",void 0),dt([n(),F(),ht("design:type",Number)],Ht.prototype,"decimals",void 0),Ht=dt([a("erc20_tokens"),B(),ht("design:paramtypes",[Object])],Ht);let Ut=class extends o{constructor(t){super(t)}};dt([s({type:String}),ht("design:type",String)],Ut.prototype,"id",void 0),dt([n(),F(),ht("design:type",String)],Ut.prototype,"token",void 0),dt([n(),F(),ht("design:type",Number)],Ut.prototype,"balance",void 0),dt([n(),ht("design:type",String)],Ut.prototype,"captive",void 0),Ut=dt([a("erc20_wallets"),B(),ht("design:paramtypes",[Object])],Ut);let Yt=class extends o{constructor(t){super(t)}};dt([s({type:String}),n(),F(),ht("design:type",String)],Yt.prototype,"owner",void 0),dt([n(),F(),ht("design:type",String)],Yt.prototype,"spender",void 0),dt([n(),F(),ht("design:type",Number)],Yt.prototype,"value",void 0),Yt=dt([a("erc20_allowances"),B(),ht("design:paramtypes",[Object])],Yt);class Gt extends _{constructor(){super()}preSerialize(t,e){const r=Object.assign({},t);let i=ut.modelName(t.constructor);if(!i||"Object"===i){if(!e)throw new Y("Could not find metadata for "+t.constructor.name);i=e}return r[P.ANCHOR]=i,r}deserialize(t){const e=JSON.parse(t),r=e[P.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return k.build(e,r)}serialize(t,e){return JSON.stringify(this.preSerialize(t,e))}}class Vt extends Mt{static{this.serializer=new Gt}static{this.decoder=new TextDecoder("utf8")}async updateObservers(t,e,r,...i){if(!this.observerHandler)throw new G("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?k.get(t):t,a=void 0===r?void 0:Array.isArray(r)?r.map(e=>c.parseValue(k.sequenceFor(t).type,e)):c.parseValue(k.sequenceFor(t).type,r),await this.observerHandler.updateObservers(t,e,a,...n)}decode(t){return Vt.decoder.decode(t)}constructor(t){super(t,Ut),this.serializer=Vt.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",[Vt.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 Jt(t,e,r){return[...t.map(t=>t===lt.TABLE?"table":t),...r||[],...e?[e]:[],"index"].join(ut.splitter)}function qt(t,e,r,i){const s=e.pop();s&&s!==lt.TABLE?e.push(s):s===lt.TABLE&&e.unshift(s);const n=Jt(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 Wt(t,e){const r=Jt([lt.TABLE]),i=e||{};i[r]={index:{fields:[lt.TABLE]},name:r,ddoc:r,type:"json"};const s={},n=k.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,lt.TABLE];qt(s,n),i&&i.length&&qt(s,n,void 0,i),r&&r.length&&r.forEach(t=>{qt(s,n,t),i&&i.length&&qt(s,n,t,i)})}return Object.entries(s).forEach(([t,e])=>{i[t]=e}),Object.values(s)}function Xt(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 k}catch(t){return!1}})}async function Qt(...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(...Xt(e))}return r}function Zt(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 te=class extends o{constructor(t){super(t)}};var ee,re;dt([pt("Unique identifier of the credentials record"),n(),s(),ht("design:type",String)],te.prototype,"id",void 0),dt([pt("PEM-encoded X.509 certificate for the identity"),n(),F(),ht("design:type",String)],te.prototype,"certificate",void 0),dt([pt("PEM-encoded root or intermediate certificate"),n(),F(),ht("design:type",String)],te.prototype,"rootCertificate",void 0),dt([pt("PEM-encoded private key"),n(),F(),ht("design:type",String)],te.prototype,"privateKey",void 0),te=dt([B(),ht("design:paramtypes",[Object])],te),(t=>{t.PRIVATE="private",t.SHARED="shared",t.FABRIC="fabric",t.OWNED_BY="owned-by",t.TRANSACTION_ID="transaction-id",t.MIRROR="mirror"})(ee||(ee={})),(t=>{t.X509="X.509"})(re||(re={}));const ie="hlf-fabric";let se=class extends o{constructor(t){super(t),this.type=re.X509}};dt([pt("Unique identifier of the identity"),s(),ht("design:type",String)],se.prototype,"id",void 0),dt([d(te,{update:h.CASCADE,delete:h.CASCADE}),ht("design:type",te)],se.prototype,"credentials",void 0),dt([n(),F(),u(),ht("design:type",String)],se.prototype,"mspId",void 0),dt([n(),F(),ht("design:type",String)],se.prototype,"type",void 0),se=dt([B(),ht("design:paramtypes",[Object])],se);class ne{static{this.logger=new At(ne.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(j("Creating CA {0} user {1} with certificate {2}",i,t,r));const n=new $t(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?(ne.cryptoSuite||(ne.cryptoSuite=$t.newCryptoSuite(t)),ne.cryptoSuite):$t.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 Ft(t).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(e.x||"","base64url"),s=Buffer.from(e.y||"","base64url");return kt.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 Ot.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 ae=new Bt;var oe,ce,le,de,he;Dt.cryptoProvider.set(ae),(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-_.!~"})(oe||(oe={})),(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"})(ce||(ce={}));class ue{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 pe{static{this.b58encoder=new ue(oe.BASE58)}static{this.logger=new At(pe.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(j("Parsing certificate: {0}",t));const e=new Dt.X509Certificate(t),{subject:r,issuer:i}=e;return this.logger.debug(j("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=ae.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 ae.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 Dt.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,ae.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,e,r)}static async encrypt(t,e){const r=new Dt.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 vt()?globalThis.window.crypto.subtle:ae.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=ae.randomUUID();t=e.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,ce.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:ce.KEY_ALGORYTHM,hash:ce.HASH,salt:i,iterations:ce.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,e,8*ce.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:ce.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:ce.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:ce.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}class ge extends G{constructor(t){super(t,ge.name)}}class fe extends G{constructor(t){super(t,fe.name)}}class me extends G{constructor(t){super(t,me.name)}}class ye extends g{constructor(t){super(t,ye.name)}}class we extends G{constructor(t){super(t,we.name,500)}}class be extends V{constructor(t="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(be.name,t,403)}}class Ce extends V{constructor(t){super(Ce.name,t,409)}}class Ae extends G{constructor(t){super(t,Ae.name,500)}}class ve extends G{constructor(t){super(t,ve.name,500)}}class Se extends G{constructor(t){super(t,Se.name,500)}}class Ee extends G{constructor(t){super(t,Ee.name,500)}}class xe extends G{constructor(t){super(t,xe.name,500)}}(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(le||(le={})),(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"})(de||(de={}));class Ne extends St{constructor(t){ne.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 ne.getFirstDirFileNameContent(e);let o;if(s)n.debug(`Using HSM configuration for CA ${t} with library ${s.library}`);else{if(!r)throw new G(`Missing caKey configuration for CA ${t}. Provide a key directory or configure HSM support.`);n.debug("Retrieving CA key from "+r),o=await ne.getFirstDirFileNameContent(r)}return n.debug("Loading Admin user for ca "+t),this.user=await ne.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 ne.getFileContent(a);return t.debug(`Creating CA Client for CA ${i} under ${e}`),this.ca=new Ct(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 ye(t);const[,r,i]=e;switch(r){case"74":case"71":return new J(i);case"20":return new g(i);default:return new ye(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 q(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new q(`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(Ne,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${r} in msp ${e}`);const a=pe.fabricIdFromCertificate(r),o=pe.encode(a);n.debug(`Identity ${a} and encodedId ${o}`);const c=new Date;return new se({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=Ne.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 q("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 G(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new G(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}class Te extends k{constructor(){super(...arguments),this.affiliation=""}build(){const t=this.hasErrors();if(t)throw new U(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}}dt([F(),ht("design:type",String)],Te.prototype,"affiliation",void 0),dt([K(1),ht("design:type",Array)],Te.prototype,"attrs",void 0),dt([F(),ht("design:type",String)],Te.prototype,"enrollmentID",void 0),dt([F(),ht("design:type",String)],Te.prototype,"enrollmentSecret",void 0),dt([L(0),ht("design:type",Number)],Te.prototype,"maxEnrollments",void 0),dt([F(),ht("design:type",String)],Te.prototype,"role",void 0),(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(he||(he={}));let Ie=class extends k{constructor(t){super(t)}};dt([pt("Stores the original timestamp of creation"),n(),f(),ht("design:type",Date)],Ie.prototype,"createdAt",void 0),dt([pt("Stores the timestamp of the last update"),n(),m(),ht("design:type",Date)],Ie.prototype,"updatedAt",void 0),dt([pt("Stores the version of the model"),n(),W(),ht("design:type",Number)],Ie.prototype,"version",void 0),Ie=dt([gt(ie),ht("design:paramtypes",[Object])],Ie);let Oe=class extends Ie{constructor(t){super(t)}};function Re(){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 q("No tokens avaialble");if(a.length>1)throw new q("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 $e(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 ke(){return ft.for(ee.OWNED_BY).define({decorator:()=>(t,e)=>mt(F(),Q(),Z($e),yt(ut.key(ee.FABRIC,ee.OWNED_BY),e))(t,e),args:[]}).apply()}async function Fe(t,e,r,i){const{stub:s}=t;i[r]=s.getTxID()}function De(){return ft.for(ee.TRANSACTION_ID).define({decorator:()=>(t,e)=>mt(F(),Q(),Z(Fe),tt(Fe),yt(ut.key(ee.FABRIC,e,ee.TRANSACTION_ID),e))(t,e),args:[]}).apply()}async function Be(t,e,r){let i=e;if("string"!=typeof i)try{const s=k.ownerOf(t)||r.get("stub").getCreator().toString();e&&"function"==typeof e&&(i=await e(t,s,r))}catch(t){throw new G("Failed to resolve collection mirror name: "+t)}if(!i||"string"!=typeof i)throw new G("No collection found model "+t.constructor.name);return i}async function _e(t,e,r,i){const s=await Be(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 ${k.tableName(this.class)} created with ${k.pk(i)}: ${a[k.pk(i)]}`)}async function Pe(t,e,r,i){const s=await Be(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 ${k.tableName(this.class)} updated with ${k.pk(i)}: ${a[k.pk(i)]}`)}async function je(t,e,r,i){const s=await Be(i,e.resolver,t),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),a=await n.delete(k.pk(i),t);t.logger.info(`Mirror for ${k.tableName(this.class)} deleted with ${k.pk(i)}: ${a[k.pk(i)]}`)}function Ke(t,e){return ft.for(ee.MIRROR).define({decorator:(e,r)=>{const i={condition:r,resolver:e};return mt(wt(ut.key(ee.FABRIC,ee.MIRROR),i),Ve(t),et(_e,i,{priority:95}),rt(Pe,i,{priority:95}),it(je,i,{priority:95}))},args:[t,e]}).apply()}dt([pt("Stores the creator"),n(),y(),ht("design:type",String)],Oe.prototype,"createdBy",void 0),dt([pt("Stores the user that last updated the model"),n(),w(),ht("design:type",String)],Oe.prototype,"updatedBy",void 0),Oe=dt([gt(ie),ht("design:paramtypes",[Object])],Oe),k.prototype.isShared=function(){return k.isShared(this.constructor)},k.prototype.isPrivate=function(){return k.isPrivate(this.constructor)},k.prototype.segregate=function(){return k.segregate(this)},k.segregate=(t=>{if(!k.isTransient(t))return{model:t};const e=ut.validatableProperties(t.constructor),r=ut.get(t.constructor,X.TRANSIENT),i=ut.get(t.constructor,ee.PRIVATE),s=ut.get(t.constructor,ee.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=k.build(n.model,t.constructor.name),n}).bind(k),k.isPrivate=(t=>!!ut.get("function"!=typeof t?t.constructor:t,ee.PRIVATE)).bind(k),k.isShared=(t=>!!ut.get("function"!=typeof t?t.constructor:t,ee.SHARED)).bind(k),k.mirrored=(t=>ut.get("function"!=typeof t?t.constructor:t,ut.key(ee.FABRIC,ee.MIRROR))).bind(k),k.ownerOf=(t=>{const e=ut.get(t.constructor,ut.key(ee.FABRIC,ee.OWNED_BY));if(e)return t[e]}).bind(k),k.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,ut.get(t,ut.key(ee.FABRIC,ee.MIRROR)))).bind(k),k.collectionsFor=(t=>{const e=[ee.PRIVATE],r=[ee.SHARED],i=ut.key(...e),s=ut.key(...r),n="function"==typeof t?t:t.constructor,a=ut.get(n,i),o=ut.get(n,s);return{privateCols:a?.collections||[],sharedCols:o?.collections||[]}}).bind(k);const Le=(t,e)=>{const r=e||("function"!=typeof t?k.ownerOf(t):void 0),i="function"==typeof t?t:t.constructor;if(!r)throw new G(`Model ${i.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${xt(i.name)}${e?xt(e):""}`},ze=(t,e)=>{const r=e||("function"!=typeof t?k.ownerOf(t):void 0);if(!r)throw new G(`Model ${t.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${xt(r)}PrivateCollection`};async function Me(t,e,r,i){if(r.length!==e.length)throw new G("Segregated data keys and metadata length mismatch");const s=k.ownerOf(i);if(!s)throw new U("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 He(t,e,r,i){if(r.length!==e.length)throw new G("Segregated data keys and metadata length mismatch");const s=k.ownerOf(i);if(!s)throw new U("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 Ue(t,e,r,i,s){}async function Ye(t,e,r,i){}function Ge(t,e,r){return(i,s)=>{const n=[];return s?n.push(bt(),st(),(r,i)=>{const s=ut.key(e,i),n=r.constructor,a=ut.get(n,s)||{},o=new Set(a.collections||[]);o.add(t),a.collections=[...o],ut.set(n,s,a);const c=ut.get(n,e)||{};new Set(c.collections||[]).add(t),a.collections=[...o],ut.set(n,e,a)},Z(Me,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),nt(He,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),tt(Ue,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),at(Ye,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()})):ut.properties(i)?.forEach(s=>{r&&!r(s)||Ge(t,e)(i.prototype,s)}),mt(...n)(i,s)}}function Ve(t=ze){return ft.for(ee.PRIVATE).define({decorator:t=>Ge(t,ee.PRIVATE),args:[t]}).apply()}function Je(t){return ft.for(ee.SHARED).define({decorator:t=>Ge(t,ee.SHARED),args:[t]}).apply()}class qe extends _{constructor(){super()}preSerialize(t){const e=Object.assign({},t);let r;try{r=ut.modelName(t.constructor)}catch(t){r=void 0}e[P.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 k.relations(t).forEach(t=>{e[t]=i(e[t])}),e}deserialize(t){const e=JSON.parse(t),r=e[P.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return k.build(e,r)}serialize(t){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t)))}}function We(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function Xe(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 Qe(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new ge(`Addition overflow: ${t} + ${e}`);return r}function Ze(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new ge(`Subtraction overflow: ${t} - ${e}`);return r}function tr(t){if(!/^\d+$/.test(t))throw new U(j("Failed to parse: {0}","string contains digits"));const e=parseInt(t);if(isNaN(e))throw new U(j("Failed to parse: {0}","string is not a parsable integer"));return e}class er extends _{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=ut.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[P.ANCHOR]=i||t.constructor.name),k.relations(t).forEach(t=>{r[t]=s.call(this,r[t])}),r}}class rr extends C{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new G("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 ne.getFirstDirFileNameContent(s);let l;if(o)r.debug(`Using HSM configuration for CA ${i} with library ${o.library}`);else{if(!n)throw new G(`Missing caKey configuration for CA ${i}. Provide a key directory or configure HSM support.`);r.debug("Retrieving CA key from "+n),l=await ne.getFirstDirFileNameContent(n)}return r.debug("Loading Admin user for ca "+i),this._user=await ne.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 G("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 ne.getFileContent(l);e.debug("CA Certificate: "+d.toString());const h=new Ct(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 ye(t);const[,r,i]=e;switch(r){case"74":case"71":return new J(i);case"20":return new g(i);default:return new ye(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 q(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new q(`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=pe.fabricIdFromCertificate(s),c=pe.encode(o);return i.debug(`Identity ${o} and encodedId ${c}`),new se({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=rr.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 q("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 G(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new G(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}const ir=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60},A),sr=new At("fabric-fs");async function nr(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}async function ar(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await p(import("fs"));return await e.readFile(t)})(t)}async function or(t,e,r,i){sr.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const s=new $t(t),n=$t.newCryptoSuite();s.setCryptoSuite(n);const a=n.createKeyFromRaw(e);return await s.setEnrollment(a,r,i),s}async function cr(t,e){const r=await nr(e,async t=>{const{promises:e}=await p(import("fs")),r=await lr(t);return await e.readFile(r)});return{mspId:t,credentials:r}}async function lr(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path"));return r(t,(await e.readdir(t))[0])}async function dr(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 hr(t){const e=await nr(t,async t=>{const{promises:e}=await p(import("fs")),r=await lr(t);return await e.readFile(r)}),r=await ur(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Ot.newPrivateKeySigner(i)}async function ur(t){let e;if(vt())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 G(t)}}class pr{static#t=null;static#e=!1;constructor(t){if(pr.#t||(pr.#t=new jt.PKCS11,pr.#t.load(this.findHSMPKCS11Lib(t))),!pr.#e){try{pr.#t.C_Initialize()}catch(t){if(t.code!==jt.CKR_CRYPTOKI_ALREADY_INITIALIZED)throw t}pr.#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(Kt.existsSync(t))return t;throw new Ae("Unable to find PKCS11 library")}dispose(){pr.#t.C_Finalize()}sanitizeOptions(t){const e=Object.assign({userType:jt.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=pr.#t.C_GetSlotList(!0);if(0===e.length)throw Error("No pkcs11 slots can be found");const r=e.find(e=>pr.#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{pr.#t.C_Login(t,e,r)}catch(t){if(t.code!==jt.CKR_USER_ALREADY_LOGGED_IN)throw t}}findObjectInHSM(t,e,r){const i=[{type:jt.CKA_ID,value:r},{type:jt.CKA_CLASS,value:e},{type:jt.CKA_KEY_TYPE,value:jt.CKK_EC}];pr.#t.C_FindObjectsInit(t,i);const s=pr.#t.C_FindObjects(t,1)[0];if(!s)throw pr.#t.C_FindObjectsFinal(t),Error("Unable to find object in HSM with ID "+r.toString());return pr.#t.C_FindObjectsFinal(t),s}newSigner(t){const e=this.sanitizeOptions(t),r=pr.#t,i=this.findSlotForLabel(e.label),s=r.C_OpenSession(i,jt.CKF_SERIAL_SESSION);let n;try{this.login(s,e.userType,e.pin),n=this.findObjectInHSM(s,jt.CKO_PRIVATE_KEY,e.identifier)}catch(t){throw pr.#t.C_CloseSession(s),t}return{signer:async t=>{pr.#t.C_SignInit(s,{mechanism:jt.CKM_ECDSA},n);const e=await pr.#t.C_SignAsync(s,Buffer.from(t),Buffer.alloc(2*zt.Point.Fn.BYTES));return zt.Signature.fromBytes(e,"compact").normalizeS().toBytes("der")},close:()=>{pr.#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:Lt.join(t,"cert.pem"),r=Kt.readFileSync(e);return this.getSKIFromCertificate(r)}getSKIFromCertificate(t){const e=new kt.X509Certificate(t),r=this.getUncompressedPointOnCurve(e.publicKey);return kt.createHash("sha256").update(r).digest()}}class gr extends v{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 G("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=[S.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(S.SELECT,this.selectSelector.join(` ${S.AND.toLowerCase()} `)),this.orderBySelector&&(n.push(S.ORDER_BY,this.orderBySelector[0]),e.push(this.orderBySelector[1])),s.method=Nt(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 fr 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 mr;class yr extends E{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new Gt}static{this.log=Et.for(yr)}constructor(t,e){super(t,ie,e),this.serializer=yr.serializer}Statement(t){return new gr(this,t)}Paginator(t,e,r){return new fr(this,t,e,r)}flags(t,e,r,...i){return super.flags(t,e,r,...i)}async context(t,e,r,...i){this.log.for(this.context).silly(`creating new context for ${t} operation on ${r?Array.isArray(r)?r.map(t=>k.tableName(t)):k.tableName(r):"no"} table ${e&&Object.keys(e)?Object.keys(e).length:"no"} with flag overrides`);let s=i.pop();void 0===s||s instanceof l||(i.push(s),s=void 0),e=s?Object.assign({},e,s.toOverrides()):e;const n=await this.flags("string"==typeof t?t:t.name,r,e,...i,s);if(s){if(!(s instanceof this.Context))return(new this.Context).accumulate({...s.cache,...n,parentContext:s});const e=s.get("operation"),i=s.get("affectedTables");return e!==t||r!==i?(new this.Context).accumulate({...s.cache,...n,parentContext:s}):s.accumulate(n)}return(new this.Context).accumulate({...ir,...n})}decode(t){return yr.decoder.decode(t)}repository(){return Mt}createPrefix(t,e,r,...i){const{ctxArgs:s}=this.logCtx(i,this.createPrefix),n=k.tableName(t),a={};return a[lt.TABLE]=n,Object.assign(a,r),[t,e,a,...s]}createAllPrefix(t,e,r,...i){const s=k.tableName(t);if(e.length!==r.length)throw new G("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[lt.TABLE]=s,Object.assign(i,r[e]),i});return[t,e,a,...n]}updateAllPrefix(t,e,r,...i){const s=k.tableName(t);if(e.length!==r.length)throw new G("Ids and models must have the same length");const{ctxArgs:n}=this.logCtx(i,this.updateAllPrefix),a=e.map(()=>{const t={};return t[lt.TABLE]=s,t});return[t,e,a,...n]}async createAll(t,e,r,...i){if(e.length!==r.length)throw new G("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.createAll),c=k.tableName(t);a.info(`adding ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=await this.submitTransaction(o,ot.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 Y(t)}}async readAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.readAll),n=k.tableName(t);i.info(`reading ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.evaluateTransaction(s,ot.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 Y(t)}}async updateAll(t,e,r,...i){if(e.length!==r.length)throw new G("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.updateAll),c=k.tableName(t);a.info(`updating ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=await this.submitTransaction(o,ot.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 Y(t)}}async deleteAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.deleteAll),n=k.tableName(t);i.info(`deleting ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.submitTransaction(s,ot.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 Y(t)}}prepare(t,...e){const{log:i}=this.logCtx(e,this.prepare),s=k.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[k.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 G(`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=k.tableName(t);a.verbose(`adding entry to ${c} table`),a.debug("pk: "+e);const l=await this.submitTransaction(o,z.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=k.tableName(t);i.verbose(`reading entry from ${n} table`),i.debug("pk: "+e);const a=await this.evaluateTransaction(s,z.READ,[e.toString()],void 0,void 0,t.name);return this.serializer.deserialize(this.decode(a))}updatePrefix(t,e,r,...i){const s=k.tableName(t),{ctxArgs:n}=this.logCtx(i,this.updatePrefix),a={};return a[lt.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=k.tableName(t);a.verbose(`updating entry to ${c} table`),a.debug("pk: "+e);const l=await this.submitTransaction(o,z.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=k.tableName(t);i.verbose(`deleting entry from ${n} table`),i.debug("pk: "+e);const a=await this.submitTransaction(s,z.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 "+k.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 Y("Failed to process result: "+t)}if(Array.isArray(c)){if(!c.length)return c;const t=c[0];return k.isModel(t)?c.map(t=>k.build(t)):c}return l=c,k.isModel(l)?k.build(l):l;var l}getClient(){return this._client||(this._client=yr.getClient(this.config)),this._client}async Gateway(t){return yr.getGateway(t,this.config,this.client)}getContractName(t){if(t)return t+"Contract"}async Contract(t,e){return yr.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 yr.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(Kt.readFileSync(r,"utf8"))}catch(t){throw new G(`Failed to read the tls certificate from ${r}: ${t}`)}const i=_t.credentials.createSsl(r);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new Pt(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 cr(e.mspId,e.certCertOrDirectoryPath);i.debug("Retrieving signer key from "+e.keyCertOrDirectoryPath);let n,a=()=>{};if(e.hsm){const t=new pr(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 hr(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=Rt(o);return e.hsm&&(c.close=new Proxy(c.close,{apply(t,e,r){Reflect.apply(t,e,r),a()}})),c}Dispatch(){return new yr._baseDispatch}static parseError(t){const e="string"==typeof t?t:t.message;return e.includes("MVCC_READ_CONFLICT")?new Se(t):e.includes("ENDORSEMENT_POLICY_FAILURE")?new xe(t):e.includes("PHANTOM_READ_CONFLICT")?new Ee(t):t instanceof Error&&t.code&&9===t.code?new ve(t):e.includes(q.name)?new q(t):e.includes(J.name)?new J(t):e.includes(ct.name)?new ct(t):e.includes(x.name)?new x(t):e.includes(N.name)?new N(t):e.includes(b.name)?new b(t):e.includes(T.name)?new T(t):e.includes(I.name)?new I(t):e.includes(g.name)?new g(t):e.includes(O.name)?new O(t):e.includes(R.name)?new R(t):e.includes(Y.name)?new Y(t):new G(t)}}dt([Tt(),It(),ht("design:type",Function),ht("design:paramtypes",[Object,Object,Object,Object,l]),ht("design:returntype",Promise)],yr.prototype,"create",null),dt([Tt(),It(),ht("design:type",Function),ht("design:paramtypes",[Object,Object,l]),ht("design:returntype",Promise)],yr.prototype,"read",null),dt([Tt(),It(),ht("design:type",Function),ht("design:paramtypes",[Object,Object,Object,Object,l]),ht("design:returntype",Promise)],yr.prototype,"update",null),dt([Tt(),It(),ht("design:type",Function),ht("design:paramtypes",[Object,Object,l]),ht("design:returntype",Promise)],yr.prototype,"delete",null),dt([Tt(),ht("design:type",Function),ht("design:paramtypes",[Object,"function"==typeof(mr="undefined"!=typeof D&&D)?mr:Object,Object,l]),ht("design:returntype",Promise)],yr.prototype,"raw",null),yr.decoration(),E.setCurrent(ie);class wr extends ${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 yr))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 G("Failed to refresh dispatch: "+t)}else s.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof t?t:k.tableName(t)}:${e}`)}async handleEvents(t){if(!this.listeningStack)throw new G('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new G("No adapter found. should be impossible");const e=t||await this.adapter.context(z.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||k),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}=Xe(t.eventName);if(n&&n!==this.adapter.config?.mspId)continue;const a=this.parsePayload(t.payload);try{const t=(i?k.get(i):k.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 G("No adapter or config observed for dispatch");const t=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},k),{ctx:e}=this.logCtx([t],this.initialize),r=(await yr.getGateway(e,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new G("No adapter observed for dispatch");this.listeningStack=await r.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(e)}}yr&&(yr._baseDispatch=wr);const br="##VERSION##",Cr="##PACKAGE##";ut.registerLibrary(Cr,br);export{me as AllowanceError,oe as BASE_ALPHABET,fe as BalanceError,ue as BaseEncoder,ce as CRYPTO,Gt as ClientSerializer,ne as CoreUtils,pe as CryptoUtils,ir as DefaultFabricClientFlags,qe as DeterministicSerializer,he as ERC20Events,ve as EndorsementError,xe as EndorsementPolicyError,Ie as FabricBaseModel,yr as FabricClientAdapter,wr as FabricClientDispatch,Mt as FabricClientRepository,Vt as FabricERC20ClientRepository,Ne as FabricEnrollmentService,ie as FabricFlavour,Oe as FabricIdentifiedBaseModel,rr as FabricIdentityService,ee as FabricModelKeys,de as HFCAIdentityAttributes,le as HFCAIdentityType,se as Identity,te as IdentityCredentials,re as IdentityType,ze as ImplicitPrivateCollection,we as MissingContextError,Ae as MissingPKCSS11Lib,Le as ModelCollection,Se as MvccReadConflictError,Ce as NotInitializedError,ge as OverflowError,Re as Owner,Cr as PACKAGE_NAME,Ee as PhantomReadConflictError,ye as RegistrationError,Te as RegistrationRequestBuilder,er as SimpleDeterministicSerializer,be as UnauthorizedPrivateDataAccess,br as VERSION,Qe as add,nr as contentOfLoadFile,_e as createMirrorHandler,je as deleteMirrorHandler,Be as evalMirrorMetadata,ur as extractPrivateKey,We as generateFabricEventName,Wt as generateModelIndexes,or as getCAUser,lr as getFirstDirFileName,dr as getFirstDirFileNameContent,cr as getIdentity,hr as getSigner,Ke as mirror,ke as ownedBy,$e as ownedByOnCreate,Xe as parseEventName,Ve as privateData,ar as readFile,Xt as readModelFile,Qt as readModelFolders,tr as safeParseInt,Me as segregatedDataOnCreate,Ye as segregatedDataOnDelete,He as segregatedDataOnRead,Ue as segregatedDataOnUpdate,Je as sharedData,Ze as sub,De as transactionId,Fe as transactionIdOnCreate,Pe as updateMirrorHandler,Zt as writeIndexes};
2
2
  //# sourceMappingURL=for-fabric.js.map