@decaf-ts/for-fabric 0.3.3 → 0.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/for-fabric.cjs +1 -1
- package/dist/for-fabric.cjs.map +1 -1
- package/dist/for-fabric.js +1 -1
- package/dist/for-fabric.js.map +1 -1
- package/lib/client/FabricClientAdapter.cjs +7 -0
- package/lib/client/FabricClientAdapter.js.map +1 -1
- package/lib/contract/models/OtherProductShared.cjs +2 -2
- package/lib/contract/models/OtherProductShared.js.map +1 -1
- package/lib/contract/models/Product.cjs +2 -2
- package/lib/contract/models/Product.js.map +1 -1
- package/lib/contract/models/decorators.cjs +1 -0
- package/lib/contract/models/decorators.js.map +1 -1
- package/lib/contracts/ContractAdapter.cjs +6 -5
- package/lib/contracts/ContractAdapter.js.map +1 -1
- package/lib/contracts/ContractContext.cjs +11 -0
- package/lib/contracts/ContractContext.d.ts +1 -0
- package/lib/contracts/ContractContext.js.map +1 -1
- package/lib/contracts/types.d.ts +1 -0
- package/lib/esm/client/FabricClientAdapter.js +7 -0
- package/lib/esm/client/FabricClientAdapter.js.map +1 -1
- package/lib/esm/contract/models/OtherProductShared.js +2 -2
- package/lib/esm/contract/models/OtherProductShared.js.map +1 -1
- package/lib/esm/contract/models/Product.js +2 -2
- package/lib/esm/contract/models/Product.js.map +1 -1
- package/lib/esm/contract/models/decorators.js +1 -0
- package/lib/esm/contract/models/decorators.js.map +1 -1
- package/lib/esm/contracts/ContractAdapter.js +6 -5
- package/lib/esm/contracts/ContractAdapter.js.map +1 -1
- package/lib/esm/contracts/ContractContext.d.ts +1 -0
- package/lib/esm/contracts/ContractContext.js +11 -0
- package/lib/esm/contracts/ContractContext.js.map +1 -1
- package/lib/esm/contracts/types.d.ts +1 -0
- package/lib/esm/shared/DeterministicSerializer.d.ts +6 -0
- package/lib/esm/shared/DeterministicSerializer.js +20 -2
- package/lib/esm/shared/DeterministicSerializer.js.map +1 -1
- package/lib/esm/shared/SimpleDeterministicSerializer.js +2 -3
- package/lib/esm/shared/SimpleDeterministicSerializer.js.map +1 -1
- package/lib/esm/shared/decorators.js +20 -3
- package/lib/esm/shared/decorators.js.map +1 -1
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.js +1 -1
- package/lib/shared/DeterministicSerializer.cjs +21 -2
- package/lib/shared/DeterministicSerializer.d.ts +6 -0
- package/lib/shared/DeterministicSerializer.js.map +1 -1
- package/lib/shared/SimpleDeterministicSerializer.cjs +2 -3
- package/lib/shared/SimpleDeterministicSerializer.js.map +1 -1
- package/lib/shared/decorators.cjs +20 -3
- package/lib/shared/decorators.js.map +1 -1
- package/lib/version.cjs +1 -1
- package/lib/version.d.ts +1 -1
- package/package.json +1 -1
package/dist/for-fabric.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e,t;e=this,t=function(e,t,r,i,a,s,n,o,c,l,d,u,h,g,p,f){"use strict";function y(e){var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var m=y(h),w=y(p);class b extends t.Repository{constructor(e,t){super(e,t),this._overrides=Object.assign({},super._overrides,{ignoreValidation:!0,ignoreHandlers:!0,allowRawStatements:!1,forcePrepareSimpleQueries:!0,forcePrepareComplexQueries:!0,allowGenerationOverride:!1})}override(e){return super.override(Object.assign({},e,this._overrides)).for(e)}ObserverHandler(){return super.ObserverHandler()}async paginateBy(e,i,a={offset:1,limit:10},...s){const{log:n,ctxArgs:o}=(await this.logCtx(s,t.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return n.verbose(`paginating ${r.Model.tableName(this.class)} with page size ${a.limit}`),this.statement(this.paginateBy.name,e,i,{limit:a.limit,offset:a.offset,bookmark:a.bookmark},...o)}async listBy(e,i,...a){const{log:s,ctxArgs:n}=(await this.logCtx(a,t.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${r.Model.tableName(this.class)} by ${e} ${i}`),await this.statement(this.listBy.name,e,i,...n)}async findBy(e,i,...a){const{log:s,ctxArgs:n}=(await this.logCtx(a,t.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding all ${r.Model.tableName(this.class)} with ${e} ${i}`),await this.statement(this.findBy.name,e,i,...n)}async findOneBy(e,i,...a){const{log:s,ctxArgs:n}=(await this.logCtx(a,t.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return s.verbose(`finding One ${r.Model.tableName(this.class)} with ${e} ${i}`),await this.statement(this.findOneBy.name,e,i,...n)}async find(e,i=t.OrderDirection.ASC,...a){const{log:s,ctxArgs:n}=(await this.logCtx(a,t.PreparedStatementKeys.FIND,!0)).for(this.find);return s.verbose(`finding ${r.Model.tableName(this.class)} by default query attributes`),await this.statement(this.find.name,e,i,...n)}async page(e,i=t.OrderDirection.ASC,a={offset:1,limit:10},...s){const{log:n,ctxArgs:o}=(await this.logCtx(s,t.PreparedStatementKeys.PAGE,!0)).for(this.page);return n.verbose(`paging ${r.Model.tableName(this.class)} by default query attributes`),await this.statement(this.page.name,e,i,a,...o)}async statement(e,...i){const{log:s,ctx:n,ctxArgs:o}=(await this.logCtx(i,t.PersistenceKeys.STATEMENT,!0)).for(this.statement);s.verbose("Executing prepared statement "+e);const c=o.slice(0,-1),l=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(n,t.PersistenceKeys.STATEMENT,[e,JSON.stringify(c)],void 0,void 0,this.class.name)));return Array.isArray(l)?l.map(e=>e[a.CouchDBKeys.TABLE]&&e[a.CouchDBKeys.TABLE]===r.Model.tableName(this.class)?new this.class(e):e):l[a.CouchDBKeys.TABLE]&&l[a.CouchDBKeys.TABLE]===r.Model.tableName(this.class)?new this.class(l):t.Paginator.isSerializedPage(l)?Object.assign(l,{data:l.data.map(e=>new this.class(e))}):l}async countOf(e,...i){const{log:a,ctxArgs:s}=(await this.logCtx(i,t.PreparedStatementKeys.COUNT_OF,!0)).for(this.countOf);a.verbose(`counting ${r.Model.tableName(this.class)}${e?" by "+e:""}`);const n=e?[e,...s]:s;return this.statement(t.PreparedStatementKeys.COUNT_OF,...n)}async maxOf(e,...i){const{log:a,ctxArgs:s}=(await this.logCtx(i,t.PreparedStatementKeys.MAX_OF,!0)).for(this.maxOf);return a.verbose(`finding max of ${e} in ${r.Model.tableName(this.class)}`),this.statement(t.PreparedStatementKeys.MAX_OF,e,...s)}async minOf(e,...i){const{log:a,ctxArgs:s}=(await this.logCtx(i,t.PreparedStatementKeys.MIN_OF,!0)).for(this.minOf);return a.verbose(`finding min of ${e} in ${r.Model.tableName(this.class)}`),this.statement(t.PreparedStatementKeys.MIN_OF,e,...s)}async avgOf(e,...i){const{log:a,ctxArgs:s}=(await this.logCtx(i,t.PreparedStatementKeys.AVG_OF,!0)).for(this.avgOf);return a.verbose(`calculating avg of ${e} in ${r.Model.tableName(this.class)}`),this.statement(t.PreparedStatementKeys.AVG_OF,e,...s)}async sumOf(e,...i){const{log:a,ctxArgs:s}=(await this.logCtx(i,t.PreparedStatementKeys.SUM_OF,!0)).for(this.sumOf);return a.verbose(`calculating sum of ${e} in ${r.Model.tableName(this.class)}`),this.statement(t.PreparedStatementKeys.SUM_OF,e,...s)}async distinctOf(e,...i){const{log:a,ctxArgs:s}=(await this.logCtx(i,t.PreparedStatementKeys.DISTINCT_OF,!0)).for(this.distinctOf);return a.verbose(`finding distinct values of ${e} in ${r.Model.tableName(this.class)}`),this.statement(t.PreparedStatementKeys.DISTINCT_OF,e,...s)}async groupOf(e,...i){const{log:a,ctxArgs:s}=(await this.logCtx(i,t.PreparedStatementKeys.GROUP_OF,!0)).for(this.groupOf);return a.verbose(`grouping ${r.Model.tableName(this.class)} by ${e}`),this.statement(t.PreparedStatementKeys.GROUP_OF,e,...s)}async healthcheck(...e){const{log:t,ctxArgs:r}=this.logCtx(e,this.healthcheck);return await this.adapter.healthcheck(this.class,...r)}async create(e,...t){const{ctx:i,log:a,ctxArgs:s}=this.logCtx(t,this.create);a.debug(`Creating new ${this.class.name} in table ${r.Model.tableName(this.class)}`),this.ensureLegacyMirrorFlag(i,e);const n=this.adapter.prepare(e,i),{record:o,id:c,transient:l}=n,d=await this.adapter.create(this.class,c,o,l,...s);if(this.shouldRefreshAfterWrite(n,i)&&null!=c){const e=await this.adapter.read(this.class,c,i);return this.adapter.revert(e,this.class,c,i.get("rebuildWithTransient")?n.transient:void 0,i)}return this.adapter.revert(d,this.class,c,l,i)}async update(e,...t){const{ctxArgs:i,log:a,ctx:s}=this.logCtx(t,this.update);this.ensureLegacyMirrorFlag(s,e);const n=this.adapter.prepare(e,s),{id:o,transient:c}=n;let l=n.record;if(a.debug(`updating ${this.class.name} in table ${r.Model.tableName(this.class)} with id ${o}`),l=await this.adapter.update(this.class,o,l,c,...i),this.shouldRefreshAfterWrite(n,s)&&null!=o){const e=await this.adapter.read(this.class,o,s);return this.adapter.revert(e,this.class,o,s.get("rebuildWithTransient")?n.transient:void 0,s)}return this.adapter.revert(l,this.class,o,c,s)}async createAllPrefix(e,...t){const{ctx:r,ctxArgs:a}=(await this.logCtx(t,i.OperationKeys.CREATE,!0)).for(this.createAllPrefix),s=r.get("ignoreHandlers"),n=r.get("ignoreValidation");if(!e.length)return[e,...a];if(e=await Promise.all(e.map(async e=>(e=new this.class(e),s||await i.enforceDBDecorators(this,r,e,i.OperationKeys.CREATE,i.OperationKeys.ON),e))),!n){const t=r.get("ignoredValidationProperties")||[],a=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),s=i.reduceErrorsToPrint(a);if(s)throw new i.ValidationError(s)}return[e,...a]}async createAll(e,...t){if(!e.length)return e;const{ctx:i,log:a,ctxArgs:s}=this.logCtx(t,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${r.Model.tableName(this.class)}`),e.forEach(e=>this.ensureLegacyMirrorFlag(i,e));const n=e.map(e=>this.adapter.prepare(e,i)),o=n.map(e=>e.id),c=n.map(e=>e.record),l=n.map(e=>e.transient),d=await this.adapter.createAll(this.class,o,c,l,...s);return Promise.all(d.map(async(e,t)=>{const r=o[t];if(this.shouldRefreshAfterWrite(n[t],i)&&null!=r){const e=await this.adapter.read(this.class,r,i);return this.adapter.revert(e,this.class,r,i.get("rebuildWithTransient")?n[t].transient:void 0,i)}return this.adapter.revert(e,this.class,r,l[t],i)}))}async updateAll(e,...t){const{ctx:i,log:a,ctxArgs:s}=this.logCtx(t,this.updateAll);a.debug(`Updating ${e.length} new ${this.class.name} in table ${r.Model.tableName(this.class)}`),e.forEach(e=>this.ensureLegacyMirrorFlag(i,e));const n=e.map(e=>this.adapter.prepare(e,i)),o=n.map(e=>e.id),c=await this.adapter.updateAll(this.class,o,n.map(e=>e.record),n.map(e=>e.transient),...s);return Promise.all(c.map(async(e,t)=>{const r=o[t];if(this.shouldRefreshAfterWrite(n[t],i)&&null!=r){const e=await this.adapter.read(this.class,r,i);return this.adapter.revert(e,this.class,r,i.get("rebuildWithTransient")?n[t].transient:void 0,i)}return this.adapter.revert(e,this.class,r,n[t].transient,i)}))}shouldRefreshAfterWrite(e,t){const r=e.privates&&Object.keys(e.privates).length>0,i=e.shared&&Object.keys(e.shared).length>0;return r||i||!!t.getOrUndefined("segregated")||!!t.getOrUndefined("mirror")}ensureLegacyMirrorFlag(e,t){r.Model.mirroredAt(t)&&e.accumulate({legacy:!0})}}let E=class extends t.BaseModel{constructor(e){super(e)}};s.__decorate([t.pk({type:String}),s.__metadata("design:type",String)],E.prototype,"name",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],E.prototype,"owner",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],E.prototype,"symbol",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",Number)],E.prototype,"decimals",void 0),E=s.__decorate([t.table("erc20_tokens"),r.model(),s.__metadata("design:paramtypes",[Object])],E);let C=class extends t.BaseModel{constructor(e){super(e)}};s.__decorate([t.pk({type:String}),s.__metadata("design:type",String)],C.prototype,"id",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],C.prototype,"token",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",Number)],C.prototype,"balance",void 0),s.__decorate([t.column(),s.__metadata("design:type",String)],C.prototype,"captive",void 0),C=s.__decorate([t.table("erc20_wallets"),r.model(),s.__metadata("design:paramtypes",[Object])],C);let A=class extends t.BaseModel{constructor(e){super(e)}};s.__decorate([t.pk({type:String}),t.column(),r.required(),s.__metadata("design:type",String)],A.prototype,"owner",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],A.prototype,"spender",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",Number)],A.prototype,"value",void 0),A=s.__decorate([t.table("erc20_allowances"),r.model(),s.__metadata("design:paramtypes",[Object])],A);class v extends r.JSONSerializer{constructor(){super()}preSerialize(e,t){const a=Object.assign({},e);let s=n.Metadata.modelName(e.constructor);if(!s||"Object"===s){if(!t)throw new i.SerializationError("Could not find metadata for "+e.constructor.name);s=t}return a[r.ModelKeys.ANCHOR]=s,a}deserialize(e){const t=JSON.parse(e),i=t[r.ModelKeys.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return r.Model.build(t,i)}serialize(e,t){return JSON.stringify(this.preSerialize(e,t))}}class S extends b{static{this.serializer=new v}static{this.decoder=new TextDecoder("utf8")}async updateObservers(e,a,s,...n){if(!this.observerHandler)throw new i.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:o,ctxArgs:c}=this.logCtx(n,this.updateObservers);let l;o.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),e="string"==typeof e?r.Model.get(e):e,l=void 0===s?void 0:Array.isArray(s)?s.map(i=>t.Sequence.parseValue(r.Model.sequenceFor(e).type,i)):t.Sequence.parseValue(r.Model.sequenceFor(e).type,s),await this.observerHandler.updateObservers(e,a,l,...c)}decode(e){return S.decoder.decode(e)}constructor(e){super(e,C),this.serializer=S.serializer}async tokenName(...e){const{ctx:t}=(await this.logCtx(e,"tokenName",!0)).for(this.tokenName),r=await this.adapter.evaluateTransaction(t,"TokenName");return this.decode(r)}async symbol(...e){const{ctx:t}=(await this.logCtx(e,"symbol",!0)).for(this.symbol),r=await this.adapter.evaluateTransaction(t,"Symbol");return this.decode(r)}async decimals(...e){const{ctx:t}=(await this.logCtx(e,"decimals",!0)).for(this.decimals),r=await this.adapter.evaluateTransaction(t,"Decimals");return Number(this.decode(r))}async totalSupply(...e){const{ctx:t}=(await this.logCtx(e,"totalSupply",!0)).for(this.totalSupply),r=await this.adapter.evaluateTransaction(t,"TotalSupply");return Number(this.decode(r))}async balanceOf(e,...t){const{ctx:r}=(await this.logCtx(t,"balance",!0)).for(this.balanceOf),i=await this.adapter.evaluateTransaction(r,"BalanceOf",[e]);return Number(this.decode(i))}async transfer(e,t,...r){const{ctx:i}=(await this.logCtx(r,"transfer",!0)).for(this.transfer),a=await this.adapter.submitTransaction(i,"Transfer",[e,t.toString()]);return"true"===this.decode(a)}async transferFrom(e,r,i){const a=await t.Context.args("transferFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:s}=this.logCtx(a.args,this.transferFrom),n=await this.adapter.submitTransaction(s,"TransferFrom",[e,r,i.toString()]);return"true"===this.decode(n)}async approve(e,r){const i=await t.Context.args("approve",this.class,[],this.adapter,this._overrides||{}),{ctx:a}=this.logCtx(i.args,this.approve),s=await this.adapter.submitTransaction(a,"Approve",[e,r.toString()]);return"true"===this.decode(s)}async allowance(e,r){const i=await t.Context.args("allowance",this.class,[],this.adapter,this._overrides||{}),{ctx:a}=this.logCtx(i.args,this.allowance),s=await this.adapter.submitTransaction(a,"Allowance",[e,r]);return Number(this.decode(s))}async initialize(e){const r=await t.Context.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.initialize),a=await this.adapter.submitTransaction(i,"Initialize",[S.serializer.serialize(e)]);return"true"===this.decode(a)}async checkInitialized(){const e=await t.Context.args("checkInitialized",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.checkInitialized);await this.adapter.evaluateTransaction(r,"CheckInitialized")}async mint(e){const r=await t.Context.args("mint",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.mint);await this.adapter.submitTransaction(i,"Mint",[e.toString()])}async burn(e){const r=await t.Context.args("burn",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.burn);await this.adapter.submitTransaction(i,"Burn",[e.toString()])}async burnFrom(e,r){const i=await t.Context.args("burnFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:a}=this.logCtx(i.args,this.burnFrom);await this.adapter.submitTransaction(a,"BurnFrom",[e,r.toString()])}async clientAccountBalance(){const e=await t.Context.args("accountBalance",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.clientAccountBalance),i=await this.adapter.evaluateTransaction(r,"ClientAccountBalance");return Number(this.decode(i))}async clientAccountID(){const e=await t.Context.args("accountId",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.clientAccountID),i=await this.adapter.evaluateTransaction(r,"ClientAccountID");return this.decode(i)}}function O(e){const t=require("fs"),r=require("path").dirname(e);if(t.existsSync(r))return!0;O(r),t.mkdirSync(r)}function _(e){const t=require("path"),i=require(t.join(process.cwd(),e.parentPath,e.name));return Object.values(i).filter(e=>{try{return new e instanceof r.Model}catch(e){return!1}})}var I;e.IdentityCredentials=class extends t.BaseModel{constructor(e){super(e)}},s.__decorate([n.description("Unique identifier of the credentials record"),t.column(),t.pk(),s.__metadata("design:type",String)],e.IdentityCredentials.prototype,"id",void 0),s.__decorate([n.description("PEM-encoded X.509 certificate for the identity"),t.column(),r.required(),s.__metadata("design:type",String)],e.IdentityCredentials.prototype,"certificate",void 0),s.__decorate([n.description("PEM-encoded root or intermediate certificate"),t.column(),r.required(),s.__metadata("design:type",String)],e.IdentityCredentials.prototype,"rootCertificate",void 0),s.__decorate([n.description("PEM-encoded private key"),t.column(),r.required(),s.__metadata("design:type",String)],e.IdentityCredentials.prototype,"privateKey",void 0),e.IdentityCredentials=s.__decorate([r.model(),s.__metadata("design:paramtypes",[Object])],e.IdentityCredentials),e.FabricModelKeys=void 0,(I=e.FabricModelKeys||(e.FabricModelKeys={})).PRIVATE="private",I.SHARED="shared",I.FABRIC="fabric",I.OWNED_BY="owned-by",I.TRANSACTION_ID="transaction-id",I.MIRROR="mirror",e.IdentityType=void 0,(e.IdentityType||(e.IdentityType={})).X509="X.509";const M="hlf-fabric";e.Identity=class extends t.BaseModel{constructor(t){super(t),this.type=e.IdentityType.X509}},s.__decorate([n.description("Unique identifier of the identity"),t.pk(),s.__metadata("design:type",String)],e.Identity.prototype,"id",void 0),s.__decorate([t.oneToOne(e.IdentityCredentials,{update:t.Cascade.CASCADE,delete:t.Cascade.CASCADE}),s.__metadata("design:type",e.IdentityCredentials)],e.Identity.prototype,"credentials",void 0),s.__decorate([t.column(),r.required(),t.index(),s.__metadata("design:type",String)],e.Identity.prototype,"mspId",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],e.Identity.prototype,"type",void 0),e.Identity=s.__decorate([r.model(),s.__metadata("design:paramtypes",[Object])],e.Identity);class x{static{this.logger=new c.MiniLogger(x.name)}constructor(){}static async contentOfLoadFile(e,t){return e instanceof Uint8Array||e.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?e:await t(e)}static async readFile(e){return"string"!=typeof e?e:await(async e=>{const{promises:r}=await t.normalizeImport(import("fs"));return await r.readFile(e)})(e)}static async getCAUser(e,t,i,a,s){this.logger.debug(r.stringFormat("Creating CA {0} user {1} with certificate {2}",a,e,i));const n=new d.User(e),o=s?.hsm?{software:!1,lib:s.hsm.library,slot:s.hsm.slot,label:s.hsm.tokenLabel,pin:s.hsm.pin+""}:void 0,c=this.getCryptoSuite(o);n.setCryptoSuite(c);const l=s?.hsm?await this.getHSMEnrollmentKey(c,i,s.hsm):this.getSoftwareEnrollmentKey(c,t);return await n.setEnrollment(l,i,a),n}static getCryptoSuite(e){return e?(x.cryptoSuite||(x.cryptoSuite=d.User.newCryptoSuite(e)),x.cryptoSuite):d.User.newCryptoSuite()}static getSoftwareEnrollmentKey(e,t){if(!t)throw Error("Private key must be provided when HSM configuration is not supplied");return e.createKeyFromRaw(t)}static async getHSMEnrollmentKey(e,t,r){const i=r.keyIdHex&&r.keyIdHex.trim().length>0?Buffer.from(r.keyIdHex,"hex"):await this.getCertificateSKI(t),a=await e.getKey(i);if(!a||"function"==typeof a.isPrivate&&!a.isPrivate())throw Error("Unable to resolve private key from HSM");return a}static async getCertificateSKI(e){const t=new u.X509Certificate(e).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(t.x||"","base64url"),a=Buffer.from(t.y||"","base64url");return u.createHash("sha256").update(Buffer.concat([r,i,a])).digest()}static async getIdentity(e,r){return{mspId:e,credentials:await this.contentOfLoadFile(r,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await this.getFirstDirFileName(e);return await r.readFile(i)})}}static async getFirstDirFileName(e){const{promises:r}=await t.normalizeImport(import("fs")),{join:i}=await t.normalizeImport(import("path"));return i(e,(await r.readdir(e))[0])}static async getFirstDirFileNameContent(e){const{promises:r}=await t.normalizeImport(import("fs")),{join:i}=await t.normalizeImport(import("path")),a=await r.readdir(e);return(await r.readFile(i(e,a[0]))).toString()}static async getFileContent(e){const{promises:r}=await t.normalizeImport(import("fs"));return(await r.readFile(e)).toString()}static async getSigner(e){const r=await this.contentOfLoadFile(e,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await this.getFirstDirFileName(e);return await r.readFile(i)}),i=await this.extractPrivateKey(r),a=i[Object.getOwnPropertySymbols(i)[0]];return l.signers.newPrivateKeySigner(a)}static async extractPrivateKey(e){let r;if(globalThis.window&&globalThis.window.Crypto)r=globalThis.Crypto.subtle;else{const e=await t.normalizeImport(import("crypto"));r=e.subtle||e.webcrypto.subtle}if(!r)throw Error("Could not load SubtleCrypto module");const i=e.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),a=(e=>{const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t})(Buffer.from(i,"base64").toString("binary"));return await r.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}}function N(e){const t=new h.X509Certificate(e),r=t.extensions?.find(e=>"2.5.29.35"===e.type);if(!r)throw Error("Authority Key Identifier (AKI) extension not found in certificate.");let i=Buffer.from(new Uint8Array(r.value)).toString("hex").toUpperCase();return i.startsWith("30168014")&&i.length>=48&&(i=i.slice(8,48)),{aki:i,serial:t.serialNumber}}const T=new g.Crypto;var F,R,$,B,P;m.cryptoProvider.set(T),e.BASE_ALPHABET=void 0,(F=e.BASE_ALPHABET||(e.BASE_ALPHABET={})).BASE2="01",F.BASE8="01234567",F.BASE11="0123456789a",F.BASE16="0123456789abcdef",F.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",F.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",F.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",F.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",F.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",F.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",F.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~",e.CRYPTO=void 0,(R=e.CRYPTO||(e.CRYPTO={})).HASH="SHA-256",R[R.ITERATIONS=1e3]="ITERATIONS",R[R.KEYLENGTH=48]="KEYLENGTH",R[R.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",R[R.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",R.ALGORYTHM="AES-GCM",R.KEY_ALGORYTHM="PBKDF2";class K{constructor(e){if(this.alphabet=e,this.baseMap=new Uint8Array(256),this.alphabet.length>=255)throw Error("Alphabet too long");for(let e=0;e<this.baseMap.length;e++)this.baseMap[e]=255;for(let t=0;t<e.length;t++){const r=e.charAt(t),i=r.charCodeAt(0);if(255!==this.baseMap[i])throw Error(r+" is ambiguous");this.baseMap[i]=t}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(e){if("string"==typeof e?e=Buffer.from(e):ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)&&(e=Uint8Array.from(e)),0===e.length)return"";let t=0,r=0,i=0;const a=e.length;for(;i!==a&&0===e[i];)i++,t++;const s=(a-i)*this.iFactor+1>>>0,n=new Uint8Array(s);for(;i!==a;){let t=e[i],a=0;for(let e=s-1;(0!==t||r>a)&&-1!==e;e--,a++)t+=256*n[e]>>>0,n[e]=t%this.base>>>0,t=t/this.base>>>0;if(0!==t)throw Error("Non-zero carry");r=a,i++}let o=s-r;for(;o!==s&&0===n[o];)o++;let c=this.leader.repeat(t);for(;s>o;++o)c+=this.alphabet.charAt(n[o]);return c}decodeUnsafe(e){if(0===e.length)return new Uint8Array(0);let t=0,r=0,i=0;for(;e[t]===this.leader;)r++,t++;const a=(e.length-t)*this.factor+1>>>0,s=new Uint8Array(a);for(;e[t];){let r=this.baseMap[e.charCodeAt(t)];if(255===r)return;let n=0;for(let e=a-1;(0!==r||i>n)&&-1!==e;e--,n++)r+=this.base*s[e]>>>0,s[e]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");i=n,t++}let n=a-i;for(;n!==a&&0===s[n];)n++;const o=new Uint8Array(r+(a-n));let c=r;for(;n!==a;)o[c++]=s[n++];return o}decode(e){const t=this.decodeUnsafe(e);if(t)return t;throw Error("Non-base"+this.base+" character")}}class k{static{this.b58encoder=new K(e.BASE_ALPHABET.BASE58)}static{this.logger=new c.MiniLogger(k.name)}constructor(){}static fabricIdFromCertificate(e){this.logger.debug(r.stringFormat("Parsing certificate: {0}",e));const t=new m.X509Certificate(e),{subject:i,issuer:a}=t;return this.logger.debug(r.stringFormat("Certificate parsed with subject {0} and issuer {1}",i,a)),`x509::/${i.replaceAll(", ","/")}::/${a.replaceAll(", ","/")}`}static encode(e){return this.b58encoder.encode(e)}static decode(e){const t=this.b58encoder.decode(e);return(new TextDecoder).decode(t)}static stringToArrayBuffer(e){const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t}static async extractKey(e,t,r){const i=T.subtle,a=t.toString("utf8").replace(RegExp(`-----BEGIN (${e.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${e.toUpperCase()} KEY|CERTIFICATE)-----`),""),s=Buffer.from(a,"base64").toString("binary"),n=this.stringToArrayBuffer(s);return await i.importKey("pkcs8",n,{name:"ECDSA",namedCurve:"P-256"},!0,r||["sign"])}static async extractPrivateKey(e,t){return this.extractKey("private",e,t)}static async extractPublicKey(e,t){return this.extractKey("public",e,t)}static async sign(e,t){const r=await this.extractPrivateKey(e),i=await T.subtle.sign({name:"ECDSA",hash:"SHA-256"},r,t);return Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join("")}static async verify(e,t,r){const i=new m.X509Certificate(e),a=await i.publicKey.export();return t="string"==typeof t?Buffer.from(t,"hex"):t,r="string"==typeof r?Buffer.from(r):r,T.subtle.verify({name:"ECDSA",hash:"SHA-256"},a,t,r)}static async encrypt(e,t){const r=new m.X509Certificate(e),i=await r.publicKey.export();t="string"==typeof t?Buffer.from(t):t;const a=await this.getSubtleCrypto().encrypt({name:"ECDSA"},i,t);return Array.from(new Uint8Array(a)).map(e=>e.toString(16).padStart(2,"0")).join("")}static getSubtleCrypto(){return c.isBrowser()?globalThis.window.crypto.subtle:T.subtle}static async decrypt(e,t){const r=await this.extractPrivateKey(e);return t="string"==typeof t?Buffer.from(t,"hex"):t,this.getSubtleCrypto().decrypt({name:"ECDSA"},r,t)}static async getMaster(t){const r=new TextEncoder;if(void 0===t){const e=T.randomUUID();t=r.encode(e).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,e.CRYPTO.KEY_ALGORYTHM,!1,["deriveBits"]),iv:t}}static async getDerivationKey(t,r){const i=(new TextEncoder).encode(t),a=await this.getSubtleCrypto().digest("SHA-256",i),s={name:e.CRYPTO.KEY_ALGORYTHM,hash:e.CRYPTO.HASH,salt:a,iterations:e.CRYPTO.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,r,8*e.CRYPTO.KEYLENGTH);return this.getKey(n)}static async getKey(t){const r=t.slice(0,32),i=t.slice(32);return{key:await this.getSubtleCrypto().importKey("raw",r,{name:e.CRYPTO.ALGORYTHM},!1,["encrypt","decrypt"]),iv:i}}static async encryptPin(t,r){const i=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:e.CRYPTO.ALGORYTHM,iv:r.iv},r.key,i)}static async decryptPin(t,r){const i=new TextDecoder,a=await this.getSubtleCrypto().decrypt({name:e.CRYPTO.ALGORYTHM,iv:r.iv},r.key,t);return i.decode(a)}}class z extends i.InternalError{constructor(e){super(e,z.name)}}class L extends i.InternalError{constructor(e){super(e,L.name)}}class j extends i.InternalError{constructor(e){super(e,j.name)}}class U extends t.AuthorizationError{constructor(e){super(e,U.name)}}class H extends i.InternalError{constructor(e){super(e,H.name,500)}}class G extends i.BaseError{constructor(e="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(G.name,e,403)}}class q extends i.BaseError{constructor(e){super(q.name,e,409)}}class V extends i.InternalError{constructor(e){super(e,V.name,500)}}class Y extends i.InternalError{constructor(e){super(e,Y.name,500)}}class J extends i.InternalError{constructor(e){super(e,J.name,500)}}class W extends i.InternalError{constructor(e){super(e,W.name,500)}}class Q extends i.InternalError{constructor(e){super(e,Q.name,500)}}class X extends i.InternalError{constructor(e,t=X.name,r=590){super(e,t,r)}}class Z extends i.InternalError{constructor(e){super(e,Z.name,591)}}class ee extends i.InternalError{constructor(e){super(e,ee.name,592)}}e.HFCAIdentityType=void 0,($=e.HFCAIdentityType||(e.HFCAIdentityType={})).PEER="peer",$.ORDERER="orderer",$.CLIENT="client",$.USER="user",$.ADMIN="admin",e.HFCAIdentityAttributes=void 0,(B=e.HFCAIdentityAttributes||(e.HFCAIdentityAttributes={})).HFREGISTRARROLES="hf.Registrar.Roles",B.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",B.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",B.HFINTERMEDIATECA="hf.IntermediateCA",B.HFREVOKER="hf.Revoker",B.HFAFFILIATIONMGR="hf.AffiliationMgr",B.HFGENCRL="hf.GenCRL";class te extends c.LoggedClass{constructor(e){x.getCryptoSuite(e.hsm?{software:!1,lib:e.hsm.library,slot:e.hsm.slot,label:e.hsm.tokenLabel,pin:e.hsm.pin+""}:void 0),super(),this.caConfig=e}async User(){if(this.user)return this.user;const{caName:e,caCert:t,caKey:r,url:a,hsm:s}=this.caConfig,n=this.log.for(this.User);n.debug(`Creating CA user for ${e} at ${a}`),n.debug("Retrieving CA certificate from "+t);const o=await x.getFirstDirFileNameContent(t);let c;if(s)n.debug(`Using HSM configuration for CA ${e} with library ${s.library}`);else{if(!r)throw new i.InternalError(`Missing caKey configuration for CA ${e}. Provide a key directory or configure HSM support.`);n.debug("Retrieving CA key from "+r),c=await x.getFirstDirFileNameContent(r)}return n.debug("Loading Admin user for ca "+e),this.user=await x.getCAUser("admin",c,o,e,{hsm:s}),this.user}async CA(){if(this.ca)return this.ca;const e=this.log.for(this.CA),{url:t,tls:r,caName:i}=this.caConfig;let{trustedRoots:a,verify:s}=r;const n=a[0];e.debug(`Retrieving CA certificate from ${n}. cwd: ${process.cwd()}`);const c=await x.getFileContent(n);return e.debug(`Creating CA Client for CA ${i} under ${t}`),this.ca=new o(t,{trustedRoots:Buffer.from(c),verify:s},i),this.ca}async Client(){if(this.client)return this.client;const e=await this.CA();return this.client=e._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(e,t=!0){const r=await this.Certificate(),i=await this.User(),a=this.log.for(this.getCertificates);a.debug(`Retrieving certificates${e?" for "+e.id:""} for CA ${this.caConfig.caName}`);const s=(await r.getCertificates(e||{},i)).result;return a.debug(`Found ${s.certs.length} certificates: ${JSON.stringify(s)}`),t?s.certs.map(e=>e.PEM):s}async getIdentities(){const e=await this.Identities(),t=this.log.for(this.getIdentities);t.debug("Retrieving Identities under CA "+this.caConfig.caName);const r=(await e.getAll(await this.User())).result;return t.debug(`Found ${r.identities.length} Identities: ${JSON.stringify(r)}`),r.identities}parseError(e){const r=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(e.message);if(!r)return new U(e);const[,a,s]=r;switch(a){case"74":case"71":return new i.ConflictError(s);case"20":return new t.AuthorizationError(s);default:return new U(s)}}async getAffiliations(){const e=await this.Affiliations(),t=this.log.for(this.getAffiliations);t.debug("Retrieving Affiliations under CA "+this.caConfig.caName);const r=(await e.getAll(await this.User())).result;return t.debug(`Found ${r.a.length} Affiliations: ${JSON.stringify(r)}`),r}async read(e){const t=await this.CA(),r=await this.User();let a;try{a=await t.newIdentityService().getOne(e,r)}catch(t){throw new i.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new i.NotFoundError(`Couldn't find enrollment with id ${e}: ${a.errors.join("\n")}`);return a.result}async register(e,t=!1,r="",i,a,s){let n;const o=this.log.for(this.register);try{const{userName:c,password:l}=e,d=await this.CA(),u=await this.User(),h={enrollmentID:c,enrollmentSecret:l,affiliation:r,userRole:i,attrs:a,maxEnrollments:s};n=await d.register(h,u),o.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${t?"as super user":""}`)}catch(e){throw this.parseError(e)}return n}static identityFromEnrollment(t,r){const{certificate:i,key:a,rootCertificate:s}=t,n=c.Logging.for(te,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${i} in msp ${r}`);const o=k.fabricIdFromCertificate(i),l=k.encode(o);n.debug(`Identity ${o} and encodedId ${l}`);const d=new Date;return new e.Identity({id:l,credentials:{id:l,certificate:i,privateKey:a.toBytes(),rootCertificate:s,createdOn:d,updatedOn:d},mspId:r,createdOn:d,updatedOn:d})}async enroll(e,t){let r;const i=this.log.for(this.enroll);try{const a=await this.CA();i.debug("Enrolling "+e);const s=await a.enroll({enrollmentID:e,enrollmentSecret:t});r=te.identityFromEnrollment(s,this.caConfig.caName),i.info(`Successfully enrolled ${e} under ${this.caConfig.caName} as ${r.id}`)}catch(e){throw this.parseError(e)}return r}async registerAndEnroll(e,t=!1,r="",i,a,s){const n=await this.register(e,t,r,i,a,s),{userName:o}=e;return this.enroll(o,n)}async revoke(e){const t=await this.CA(),r=await this.User(),a=await this.read(e);if(!a)throw new i.NotFoundError("Could not find enrollment with id "+e);let s;try{s=await t.revoke({enrollmentID:a.id,reason:"User Deletation"},r)}catch(t){throw new i.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!s.success)throw new i.InternalError(`Could not revoke enrollment with id ${e}: ${s.errors.join("\n")}`);return s}}class re extends r.Model{constructor(){super(...arguments),this.affiliation=""}build(){const e=this.hasErrors();if(e)throw new i.ValidationError(e.toString());const t={enrollmentID:this.enrollmentID,enrollmentSecret:this.enrollmentSecret,role:this.role,affiliation:this.affiliation};return void 0!==this.maxEnrollments&&(t.maxEnrollments=this.maxEnrollments),this.attrs&&(t.attrs=this.attrs),t}setAffiliation(e){return this.affiliation=e,this}addAttr(e){return this.attrs=this.attrs||[],this.attrs.push(e),this}setAttrs(e){return this.attrs=e,this}setEnrollmentID(e){return this.enrollmentID=e,this}setEnrollmentSecret(e){return this.enrollmentSecret=e,this}setMaxEnrollments(e){return this.maxEnrollments=e,this}setRole(e){return this.role=e,this}}function ie(e){if(e)return"string"==typeof e?e:e.getMSPID()}async function ae(e,t,r,i){const{stub:a}=e,s=(await a.getCreator()).mspid;Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:s})}async function se(e,t,r,i){const{stub:a}=e;i[r]=a.getTxID()}async function ne(e,t,a){let s=t;if("string"!=typeof s)try{const i=r.Model.ownerOf(e)||a.get("stub").getCreator().toString();t&&"function"==typeof t&&(s=await t(e,i,a))}catch(e){throw new i.InternalError("Failed to resolve collection mirror name: "+e)}if(!s||"string"!=typeof s)throw new i.InternalError("No collection found model "+e.constructor.name);return s}async function oe(e,t,i,a){const s=await ne(a,t.resolver,e),n=e;n.put("mirror",!0),n.put("mirrorCollection",s);try{const t=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:s,ignoreValidation:!0,ignoreHandlers:!0})),i=await t.create(a,e);e.logger.info(`Mirror for ${r.Model.tableName(this.class)} created with ${r.Model.pk(a)}: ${i[r.Model.pk(a)]}`)}finally{n.put("mirror",void 0),n.put("mirrorCollection",void 0)}}async function ce(e,t,i,a){const s=await ne(a,t.resolver,e),n=e;n.put("mirror",!0),n.put("mirrorCollection",s);try{const t=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:s,ignoreValidation:!0,ignoreHandlers:!0,applyUpdateValidation:!1,mergeForUpdate:!1}));await t.update(a,e),e.logger.info(`Mirror for ${r.Model.tableName(this.class)} updated: ${a[r.Model.pk(a)]}`)}finally{n.put("mirror",void 0),n.put("mirrorCollection",void 0)}}async function le(e,t,i,a){const s=await ne(a,t.resolver,e),n=e;n.put("mirror",!0),n.put("segregated",s);try{const t=a[r.Model.pk(a)],i=this.override(Object.assign({},this._overrides,{segregated:s,mirror:!0,ignoreValidation:!0,ignoreHandlers:!0}));try{await i.delete(t,e)}catch{}e.logger.info(`Mirror for ${r.Model.tableName(this.class)} deleted: ${t+""}`)}finally{n.put("mirror",void 0),n.put("segregated",void 0)}}async function de(e,r,i,a){const s=ie(e.get("identity"));if(s&&(s===r.mspId||r.condition&&r.condition(s)))throw new t.AuthorizationError(`Organization ${s} is not authorized to modify mirrored data`)}async function ue(e,t,r,i){const a=ie(e.get("identity"));if(!a)return;const s=await ne(i,t.resolver,e),n=e;(a===t.mspId||t.condition&&t.condition(a))&&(e.logger.info(`Mirror read: MSP ${a} matches, routing reads to mirror collection ${s}`),n.put("fullySegregated",!0),n.readFrom(s))}s.__decorate([r.required(),s.__metadata("design:type",String)],re.prototype,"affiliation",void 0),s.__decorate([r.minlength(1),s.__metadata("design:type",Array)],re.prototype,"attrs",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],re.prototype,"enrollmentID",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],re.prototype,"enrollmentSecret",void 0),s.__decorate([r.min(0),s.__metadata("design:type",Number)],re.prototype,"maxEnrollments",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],re.prototype,"role",void 0),e.ERC20Events=void 0,(P=e.ERC20Events||(e.ERC20Events={})).TRANSFER="Transfer",P.APPROVAL="Approval",e.FabricBaseModel=class extends r.Model{constructor(e){super(e)}},s.__decorate([n.description("Stores the original timestamp of creation"),t.column(),t.createdAt(),s.__metadata("design:type",Date)],e.FabricBaseModel.prototype,"createdAt",void 0),s.__decorate([n.description("Stores the timestamp of the last update"),t.column(),t.updatedAt(),s.__metadata("design:type",Date)],e.FabricBaseModel.prototype,"updatedAt",void 0),s.__decorate([n.description("Stores the version of the model"),t.column(),i.version(),s.__metadata("design:type",Number)],e.FabricBaseModel.prototype,"version",void 0),e.FabricBaseModel=s.__decorate([n.uses(M),s.__metadata("design:paramtypes",[Object])],e.FabricBaseModel),e.FabricIdentifiedBaseModel=class extends e.FabricBaseModel{constructor(e){super(e)}},s.__decorate([n.description("Stores the creator"),t.column(),t.createdBy(),s.__metadata("design:type",String)],e.FabricIdentifiedBaseModel.prototype,"createdBy",void 0),s.__decorate([n.description("Stores the user that last updated the model"),t.column(),t.updatedBy(),s.__metadata("design:type",String)],e.FabricIdentifiedBaseModel.prototype,"updatedBy",void 0),e.FabricIdentifiedBaseModel=s.__decorate([n.uses(M),s.__metadata("design:paramtypes",[Object])],e.FabricIdentifiedBaseModel),r.Model.prototype.isShared=function(){return r.Model.isShared(this.constructor)},r.Model.prototype.isPrivate=function(){return r.Model.isPrivate(this.constructor)},r.Model.prototype.segregate=function(){return r.Model.segregate(this)},r.Model.segregate=(t=>{if(!r.Model.isTransient(t))return{model:t};const a=n.Metadata.getAttributes(t.constructor)||[],s=n.Metadata.get(t.constructor,i.DBKeys.TRANSIENT),o=n.Metadata.get(t.constructor,e.FabricModelKeys.PRIVATE),c=n.Metadata.get(t.constructor,e.FabricModelKeys.SHARED),l={model:{},public:{},transient:{},privates:{},shared:{}},d=Object.keys(s||{}),u=Object.keys(o||{}),h=Object.keys(c||{});for(const e of a){const r=t[e],i=d.includes(e),a=!i,s=u.includes(e),n=h.includes(e);(i||s||n)&&(l.transient=l.transient||{},l.transient[e]=r),s&&(l.privates=l.privates||{},l.privates[e]=r),n&&(l.shared=l.shared||{},l.shared[e]=r),a&&(l.public=l.public||{},l.public[e]=r)}return l.model=r.Model.build(l.public,t.constructor.name),l}).bind(r.Model),r.Model.isPrivate=(t=>!!n.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.PRIVATE)).bind(r.Model),r.Model.isShared=(t=>!!n.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.SHARED)).bind(r.Model),r.Model.mirrored=(t=>n.Metadata.get("function"!=typeof t?t.constructor:t,n.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR))).bind(r.Model),r.Model.ownerOf=(t=>{const r=n.Metadata.get(t.constructor,n.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.OWNED_BY));if(r)return t[r]}).bind(r.Model),r.Model.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,n.Metadata.get(t,n.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR)))).bind(r.Model),r.Model.collectionsFor=(t=>{const r=[e.FabricModelKeys.PRIVATE],i=[e.FabricModelKeys.SHARED],a=n.Metadata.key(...r),s=n.Metadata.key(...i),o="function"==typeof t?t:t.constructor,c=n.Metadata.get(o,a),l=n.Metadata.get(o,s);return{privateCols:c?.collections||[],sharedCols:l?.collections||[]}}).bind(r.Model);const he=(e,t)=>{const a=t||("function"!=typeof e?r.Model.ownerOf(e):void 0);if(!a)throw new i.InternalError(`Model ${e.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${c.toPascalCase(a)}PrivateCollection`};function ge(e,t,i){if(t.length>0&&i.readFrom(t),!i.isFullySegregated&&t.length){const t=r.Model.segregate(e).public||{};Object.keys(t).length||i.markFullySegregated()}}async function pe(e,t,i,a){const s=Array.isArray(t)?t:[t],n=r.Model.ownerOf(a)||ie(e.get("identity"));if(!n)return;const o=[];for(const t of s){const r=t.collections,i="string"==typeof r?r:r(a,n,e);i&&!o.includes(i)&&o.push(i)}ge(a,o,e);const c=r.Model.sequenceName(a,"pk");e.setSequenceSegregation(c,e.isFullySegregated,o)}async function fe(e,a,s,n){const o=Array.isArray(a)?a:[a],c=Array.isArray(s)?s:[s];if(c.length!==o.length)throw new i.InternalError("Segregated data keys and metadata length mismatch");const l=r.Model.ownerOf(n)||ie(e.get("identity"));if(!l)throw new i.ValidationError("There's no assigned organization for model "+n.constructor.name);const d=o[0].collections,u="string"==typeof d?d:d(n,l,e);c.forEach((r,i)=>{const a="string"==typeof o[i].collections?o[i].collections:o[i].collections(n,l,e);if(a!==u)throw new t.UnsupportedError(`Segregated data collection mismatch: ${a} vs ${u}`)});const h=c.map(e=>e+"");e.writeTo(u,h)}async function ye(e,t,a,s){const n=Array.isArray(t)?t:[t];if((Array.isArray(a)?a:[a]).length!==n.length)throw new i.InternalError("Segregated data keys and metadata length mismatch");const o=r.Model.ownerOf(s)||ie(e.get("identity"));if(!o)throw new i.ValidationError("There's no assigned organization for model "+s.constructor.name);const c=n[0].collections,l="string"==typeof c?c:await c(s,o,e);e.readFrom(l)}async function me(e,a,s,n,o){const c=Array.isArray(a)?a:[a],l=Array.isArray(s)?s:[s];if(l.length!==c.length)throw new i.InternalError("Segregated data keys and metadata length mismatch");const d=r.Model.ownerOf(n)||ie(e.get("identity"));if(!d)throw new i.ValidationError("There's no assigned organization for model "+n.constructor.name);const u=c[0].collections,h="string"==typeof u?u:u(n,d,e);l.forEach((r,i)=>{const a="string"==typeof c[i].collections?c[i].collections:c[i].collections(n,d,e);if(a!==h)throw new t.UnsupportedError(`Segregated data collection mismatch: ${a} vs ${h}`)});const g=l.map(e=>e+"");e.writeTo(h,g)}async function we(e,t,a,s){const n=Array.isArray(t)?t:[t];if((Array.isArray(a)?a:[a]).length!==n.length)throw new i.InternalError("Segregated data keys and metadata length mismatch");const o=r.Model.ownerOf(s)||ie(e.get("identity"));if(!o)throw new i.ValidationError("There's no assigned organization for model "+s.constructor.name);const c=n[0].collections,l="string"==typeof c?c:c(s,o,e);e.readFrom(l)}function be(e,t,r){return(r,a)=>{const s=[];if(!a){const i=n.Metadata.getAttributes(r);return i?.forEach(i=>{be(e,t)(r.prototype,i)}),r}{const r="string"==typeof e?e:e.toString(),a=r+":data",o={collections:e},c={priority:35,group:r+":extract"};s.push(n.prop(),i.transient(),(r,a)=>{const s=n.Metadata.key(t,a),o=r.constructor,c=n.Metadata.get(o,s)||{},l=new Set(c.collections||[]);l.add(e),c.collections=[...l],n.Metadata.set(o,s,c);const d=n.Metadata.get(o,t)||{},u=new Set(d.collections||[]);u.add(e),d.collections=[...u],n.Metadata.set(o,t,d);const h={...n.Metadata.get(o,i.DBKeys.TRANSIENT)||{},[a]:{}};n.Metadata.set(o,i.DBKeys.TRANSIENT,h)},i.on(i.DBOperations.ALL,pe,o,c),i.onCreate(fe,{collections:e},{priority:95,group:a}),i.onRead(ye,{collections:e},{priority:95,group:a}),i.onUpdate(me,{collections:e},{priority:95,group:a}),i.onDelete(we,{collections:e},{priority:95,group:a}))}return n.apply(...s)(r,a)}}class Ee extends r.JSONSerializer{constructor(){super()}preSerialize(e){const t=Object.assign({},e);let i;try{i=n.Metadata.modelName(e.constructor)}catch(e){i=void 0}t[r.ModelKeys.ANCHOR]=i||e.constructor.name;const a=function e(t){const r=this;return"object"!=typeof t?t:Array.isArray(t)?t.map(t=>e.call(r,t)):this.preSerialize.call(this,t)}.bind(this);return r.Model.relations(e).forEach(e=>{t[e]=a(t[e])}),t}deserialize(e){const t=JSON.parse(e),i=t[r.ModelKeys.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return r.Model.build(t,i)}serialize(e){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(e)))}}function Ce(e){const t=e.split("_");return 2>t.length||t.length>3?{table:void 0,event:e,owner:void 0}:{table:t[0],event:t[1],owner:t[2]}}class Ae extends r.JSONSerializer{constructor(){super()}deserialize(e,t){return JSON.parse(e)}serialize(e,t=!0){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(e,t)))}preSerialize(e,t=!0){const i=Object.assign({},e);let a;try{a=n.Metadata.modelName(e.constructor)}catch(e){a=void 0}function s(e){return"object"!=typeof e?e:Array.isArray(e)?e.map(s):this.preSerialize(e)}return t&&(i[r.ModelKeys.ANCHOR]=a||e.constructor.name),r.Model.relations(e).forEach(e=>{i[e]=s.call(this,i[e])}),i}}class ve extends t.ClientBasedService{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new i.InternalError("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(e,t){const r=t.logger.for(this.getUser),{caName:a,caCert:s,caKey:n,url:o,hsm:c}=e;r.info(`Creating CA user for ${a} at ${o}`),r.verbose("Retrieving CA certificate from "+s);const l=await x.getFirstDirFileNameContent(s);let d;if(c)r.debug(`Using HSM configuration for CA ${a} with library ${c.library}`);else{if(!n)throw new i.InternalError(`Missing caKey configuration for CA ${a}. Provide a key directory or configure HSM support.`);r.debug("Retrieving CA key from "+n),d=await x.getFirstDirFileNameContent(n)}return r.debug("Loading Admin user for ca "+a),this._user=await x.getCAUser("admin",d,l,a,{hsm:c}),this._user}async initialize(...e){const{log:r,ctx:a}=(await this.logCtx(e,t.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize),[s]=e;if(!s)throw new i.InternalError("Missing Fabric CA configuration");const{url:n,tls:c,caName:l}=s;r.info(`Initializing CA Client for CA ${s.caName} at ${s.url}`);const{trustedRoots:d,verify:u}=c,h=d[0];r.debug(`Retrieving CA certificate from ${h}. cwd: ${process.cwd()}`);const g=await x.getFileContent(h);r.debug("CA Certificate: "+g.toString());const p=new o(n,{trustedRoots:Buffer.from(g),verify:u},l),f=await this.getUser(s,a);return r.debug("CA user loaded: "+f.getName()),{config:s,client:p}}async getCertificates(e,r=!0,...a){e instanceof t.Context?(a=[e],r=!0,e=void 0):"boolean"==typeof e?(r=e,e=void 0):"boolean"!=typeof r&&(a=[r,...a],r=!0);const{log:s}=(await this.logCtx(a,i.OperationKeys.READ,!0)).for(this.getCertificates);s.debug(`Retrieving certificates${e?" for "+e.id:""} for CA ${this.config.caName}`);const n=(await this.certificates.getCertificates(e||{},this.user)).result;return s.verbose(`Found ${n.certs.length} certificates`),s.debug(n.certs),r?n.certs.map(e=>e.PEM):n}async getIdentities(e){const t=e.logger.for(this.getIdentities);t.verbose("Retrieving Identities under CA "+this.config.caName);const r=(await this.identities.getAll(this.user)).result;return t.verbose(`Found ${r.identities.length} Identities`),t.debug(r.identities),r.identities}async getAffiliations(e){const t=e.logger.for(this.getAffiliations);t.verbose("Retrieving Affiliations under CA "+this.config.caName);const r=(await this.affiliations.getAll(this.user)).result;return t.verbose(`Found ${r.a.length} Affiliations`),t.debug(JSON.stringify(r)),r}parseError(e){const r=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(e.message);if(!r)return new U(e);const[,a,s]=r;switch(a){case"74":case"71":return new i.ConflictError(s);case"20":return new t.AuthorizationError(s);default:return new U(s)}}async read(e,...t){const{log:r}=(await this.logCtx(t,i.OperationKeys.READ,!0)).for(this.read);let a;r.verbose("Retrieving identity with enrollment ID "+e);try{a=await this.identities.getOne(e,this.user)}catch(t){throw new i.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new i.NotFoundError(`Couldn't find enrollment with id ${e}: ${a.errors.join("\n")}`);return a.result}async register(e,t=!1,r="",i,a,s,...n){const{log:o}=(await this.logCtx(n,"register",!0)).for(this.register);let c;try{const{userName:n,password:l}=e,d={enrollmentID:n,enrollmentSecret:l,affiliation:r,userRole:i,attrs:a,maxEnrollments:s};c=await this.client.register(d,this.user),o.info(`Registration for ${n} created with user type ${i??"Undefined Role"} ${t?"as super user":""}`)}catch(e){throw this.parseError(e)}return c}static identityFromEnrollment(t,r,i){const a=i.logger.for(this.identityFromEnrollment),{certificate:s,key:n,rootCertificate:o}=t;a.verbose(`Generating Identity from certificate ${s} in msp ${r}`);const c=k.fabricIdFromCertificate(s),l=k.encode(c);return a.debug(`Identity ${c} and encodedId ${l}`),new e.Identity({id:l,credentials:{id:l,certificate:s,privateKey:n.toBytes(),rootCertificate:o},mspId:r})}async enroll(e,t,...r){const{log:i,ctx:a}=(await this.logCtx(r,"enroll",!0)).for(this.enroll);let s;try{i.debug("Enrolling "+e);const r=await this.client.enroll({enrollmentID:e,enrollmentSecret:t});s=ve.identityFromEnrollment(r,this.config.caName,a),i.info(`Successfully enrolled ${e} under ${this.config.caName} as ${s.id}`)}catch(e){throw this.parseError(e)}return s}async registerAndEnroll(e,t=!1,r="",i,a,s,...n){const{ctx:o}=(await this.logCtx(n,"register-enroll",!0)).for(this.registerAndEnroll),c=await this.register(e,t,r,i,a,s,o),{userName:l}=e;return this.enroll(l,c,o)}async updateIdentity(e,t,r,...i){const{log:a,ctx:s}=(await this.logCtx(i,"reenroll",!0)).for(this.updateIdentity);try{a.info("Renewing identity for "+e);const n=this.client.newIdentityService(),o=await n.getOne(e,this.user);await n.update(e,r,this.user);const c=d.User.createUser(e,"",this.user.getMspid(),t.certificate,t.privateKey);c.setCryptoSuite(this.user.getCryptoSuite());const l=(o.result.attrs||[]).map(({name:e})=>({name:e,optional:!1})),u=await this.client.reenroll(c,l),h=ve.identityFromEnrollment(u,this.config.caName,s);a.debug("Revoking previous certificates for "+e);const{aki:g,serial:p}=N(t.certificate);return await this.revoke(e,{aki:g,serial:p},i),a.debug("Renew identity successful for "+e),h}catch(e){throw this.parseError(e)}}async revoke(e,t,...r){const{log:a}=(await this.logCtx(r,"revoke",!0)).for(this.revoke);a.verbose("Revoking identity with enrollment ID "+e);const s=await this.read(e);if(!s)throw new i.NotFoundError("Could not find enrollment with id "+e);let n;try{const e={reason:t.serial||t.aki?"Revoke User Certificate":"User Deletion",...t,enrollmentID:s.id};n=await this.client.revoke(e,this.user)}catch(t){throw new i.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!n.success)throw new i.InternalError(`Could not revoke enrollment with id ${e}: ${n.errors.join("\n")}`);return n}}var Se;e.CA_ROLE=void 0,(Se=e.CA_ROLE||(e.CA_ROLE={})).ADMIN="admin",Se.USER="user",Se.CLIENT="client";const Oe=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60,legacy:!1,allowManualEndorsingOrgs:!1,allowGatewayOverride:!1,rebuildWithTransient:!0,encryptTransient:!1}),_e=new c.MiniLogger("fabric-fs");async function Ie(e,t){return e instanceof Uint8Array||e.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?e:await t(e)}async function Me(e,r){return{mspId:e,credentials:await Ie(r,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await xe(e);return await r.readFile(i)})}}async function xe(e){const{promises:r}=await t.normalizeImport(import("fs")),{join:i}=await t.normalizeImport(import("path"));return i(e,(await r.readdir(e))[0])}async function Ne(e){const r=await Ie(e,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await xe(e);return await r.readFile(i)}),i=await Te(r),a=i[Object.getOwnPropertySymbols(i)[0]];return l.signers.newPrivateKeySigner(a)}async function Te(e){let r;if(c.isBrowser())r=globalThis.crypto.subtle;else{const e=await t.normalizeImport(import("crypto"));r=e.subtle||e.webcrypto.subtle}if(!r)throw Error("Could not load SubtleCrypto module");const a=e.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),s=(e=>{const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t})(Buffer.from(a,"base64").toString("binary"));try{return await r.importKey("pkcs8",s,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}catch(e){throw new i.InternalError(e)}}function Fe(e){if(!e)return"\0";const t=Array.from(e);for(let e=t.length-1;e>=0;e-=1){const r=t[e].codePointAt(0);if(void 0!==r&&1114111>r)return t[e]=String.fromCodePoint(r+1),t.slice(0,e+1).join("")}return e+"\0"}class De extends t.Statement{constructor(e,t){super(e,t)}squash(e){const r=super.squash(e);if(!r)return r;const{method:a,params:s,args:n}=r,{direction:o,limit:c}=s;switch(a){case t.PreparedStatementKeys.FIND:break;case t.PreparedStatementKeys.PAGE:n.push(o,c);break;case t.PreparedStatementKeys.FIND_BY:break;case t.PreparedStatementKeys.LIST_BY:n.push(o);break;case t.PreparedStatementKeys.PAGE_BY:n.push(o,c);break;case t.PreparedStatementKeys.FIND_ONE_BY:break;default:throw new i.InternalError("Unsupported method "+a)}return r}async executePrepared(...e){const r=t.Repository.forModel(this.fromSelector,this.adapter.alias),{method:i,args:a}=this.prepared;return r.statement(i,...a,...e)}async prepare(e){if(e=e||await this.adapter.context(t.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&e.get("forcePrepareSimpleQueries")){const t=this.squash(e);if(t)return this.prepared=t,this}const r=[],i={},a={class:this.fromSelector,args:r,params:i},s=[t.QueryClause.FIND_BY];if(this.whereCondition){const t=this.prepareCondition(this.whereCondition,e);s.push(t.method),t.args&&t.args.length&&r.push(...t.args)}return this.selectSelector&&s.push(t.QueryClause.SELECT,this.selectSelector.join(` ${t.QueryClause.AND.toLowerCase()} `)),this.orderBySelectors?.length&&(s.push(t.QueryClause.ORDER_BY,this.orderBySelectors[0][0]),r.push(this.orderBySelectors[0][1])),a.method=c.toCamelCase(s.join(" ")),a.params=i,this.prepared=a,this}processRecord(e,r,i,s){if(e[a.CouchDBKeys.ID]){const[,...r]=e[a.CouchDBKeys.ID].split(a.CouchDBKeys.SEPARATOR),n=r.join("_");return this.adapter.revert(e,this.fromSelector,t.Sequence.parseValue(i,n),void 0,s)}return e}async raw(e,...t){const{ctx:a}=this.logCtx(t,this.raw),s=e?.aggregateInfo;if(e?.aggregate&&s)return this.executeAggregate(s,a);const o=await this.adapter.raw(e,!0,this.fromSelector,a),c=r.Model.pk(this.fromSelector),l=n.Metadata.get(this.fromSelector,n.Metadata.key(i.DBKeys.ID,c))?.type;return this.selectSelector?o:o.map(e=>this.processRecord(e,c,l,a))}build(){const e=this.log.for(this.build),i=this.buildAggregateQuery();if(i)return i;const s={};s[a.CouchDBKeys.TABLE]={},s[a.CouchDBKeys.TABLE]=r.Model.tableName(this.fromSelector);const n={selector:s};if(this.selectSelector&&(n.fields=this.selectSelector),this.whereCondition){const r=this.parseCondition(t.Condition.and(this.whereCondition,t.Condition.attribute(a.CouchDBKeys.TABLE).eq(n.selector[a.CouchDBKeys.TABLE]))).selector,i=Object.keys(r);if(1===i.length&&-1!==Object.values(a.CouchDBGroupOperator).indexOf(i[0]))switch(i[0]){case a.CouchDBGroupOperator.AND:r[a.CouchDBGroupOperator.AND]=[...Object.values(r[a.CouchDBGroupOperator.AND]).reduce((e,t)=>{const r=Object.keys(t);if(1!==r.length)throw Error("Too many keys in query selector. should be one");const i=r[0];return i===a.CouchDBGroupOperator.AND?e.push(...t[i]):e.push(t),e},[])],n.selector=r;break;case a.CouchDBGroupOperator.OR:{const e={};e[a.CouchDBGroupOperator.AND]=[r,...Object.entries(n.selector).map(([e,t])=>{const r={};return r[e]=t,r})],n.selector=e;break}default:throw Error("This should be impossible")}else Object.entries(r).forEach(([t,r])=>{n.selector[t]&&e.warn(`A ${t} query param is about to be overridden: ${n.selector[t]} by ${r}`),n.selector[t]=r})}if(this.orderBySelectors?.length){n.sort=n.sort||[],n.selector=n.selector||{};for(const[e,t]of this.orderBySelectors){const r=e,i={};i[r]=t,n.sort.push(i),n.selector[r]||(n.selector[r]={},n.selector[r][a.CouchDBOperator.BIGGER]=null)}}return this.limitSelector?n.limit=this.limitSelector:(e.warn("No limit selector defined. Using default couchdb limit of "+a.CouchDBQueryLimit),n.limit=a.CouchDBQueryLimit),this.offsetSelector&&(n.skip=this.offsetSelector),n}parseCondition(e){const{attr1:r,operator:i,comparison:s}=e;if(i===t.Operator.STARTS_WITH){if("string"!=typeof r)throw new t.QueryError("STARTS_WITH requires an attribute name");if("string"!=typeof s)throw new t.QueryError("STARTS_WITH requires a string comparison");const e={start:n=s,end:Fe(n)},i={};return i[r]={},i[r][a.CouchDBOperator.BIGGER_EQ]=e.start,i[r][a.CouchDBOperator.SMALLER]=e.end,{selector:i}}var n,o;if(i===t.Operator.ENDS_WITH){if("string"!=typeof r)throw new t.QueryError("ENDS_WITH requires an attribute name");if("string"!=typeof s)throw new t.QueryError("ENDS_WITH requires a string comparison");const e={};return e[r]={[a.CouchDBOperator.REGEXP]:(o=s,o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"$")},{selector:e}}if(i===t.Operator.BETWEEN){const e=r;if(!Array.isArray(s)||2!==s.length)throw new t.QueryError("BETWEEN operator requires [min, max] comparison");const[i,n]=s,o={};return o[e]={},o[e][a.translateOperators(t.Operator.BIGGER_EQ)]=i,o[e][a.translateOperators(t.Operator.SMALLER_EQ)]=n,{selector:o}}let c={};if(-1===[t.GroupOperator.AND,t.GroupOperator.OR,t.Operator.NOT].indexOf(i))c[r]={},c[r][a.translateOperators(i)]=s;else if(i===t.Operator.NOT)c=this.parseCondition(r).selector,c[a.translateOperators(t.Operator.NOT)]={},c[a.translateOperators(t.Operator.NOT)][r.attr1]=s;else{const e=this.parseCondition(r).selector,t=this.parseCondition(s).selector;c=((e,t,r)=>{const i={selector:{}};return i.selector[e]=[t,r],i})(a.translateOperators(i),e,t).selector}return{selector:c}}buildAggregateQuery(){if(!this.fromSelector)return;if(this.avgSelector){const e=this.avgSelector+"",r=this.createAggregateDescriptor("sum",e),i=this.createAggregateDescriptor("count",e);if(!r||!i)throw new t.QueryError("Avg operation requires sum and count views for attribute "+e);return this.createAggregateQuery({kind:"avg",attribute:e,sumDescriptor:r.descriptor,countDescriptor:i.descriptor})}if(void 0!==this.countDistinctSelector){const e=null==this.countDistinctSelector?void 0:this.countDistinctSelector+"",t=this.createAggregateDescriptor("distinct",e);if(t)return t.countDistinct=!0,this.createAggregateQuery(t)}const e=!!(void 0!==this.countSelector||void 0!==this.countDistinctSelector||this.minSelector||this.maxSelector||this.sumSelector||this.distinctSelector),i=[["count",this.countSelector??void 0],["max",this.maxSelector],["min",this.minSelector],["sum",this.sumSelector],["distinct",this.distinctSelector]];for(const[e,t]of i){const r=t?t+"":void 0,i=this.createAggregateDescriptor(e,r);if(i)return this.createAggregateQuery(i)}if(e)throw new t.QueryError(`No CouchDB view metadata found for table ${r.Model.tableName(this.fromSelector)} aggregator`)}createAggregateDescriptor(e,t){if(!this.fromSelector)return;const i=a.findViewMetadata(this.fromSelector,e,t);if(!i.length)return;const s=i[0],n=r.Model.tableName(this.fromSelector),o=a.generateViewName(n,s.attribute,e,s),c=s.ddoc||a.generateDesignDocName(n,o),l={reduce:void 0!==s.reduce||!s.returnDocs};return"distinct"!==e&&"groupBy"!==e||(l.group=!0),{kind:e,meta:s,descriptor:{ddoc:c,view:o,options:l}}}createAggregateQuery(e){return{selector:{},aggregate:!0,aggregateInfo:e}}getFabricAdapter(){return this.adapter}async executeAggregate(e,t){if(!this.isViewAggregate(e))return this.handleAverage(e,t);const r=this.getFabricAdapter(),i=e,a=await r.view(i.descriptor.ddoc,i.descriptor.view,i.descriptor.options,t);return this.processViewResponse(e,a)}async handleAverage(e,r){if("avg"!==e.kind)throw new t.QueryError("Average descriptor is not valid");const i=this.getFabricAdapter(),[a,s]=[e.sumDescriptor,e.countDescriptor],[n,o]=await Promise.all([i.view(a.ddoc,a.view,a.options,r),i.view(s.ddoc,s.view,s.options,r)]),c=n.rows?.[0]?.value??0,l=o.rows?.[0]?.value??0;return l?c/l:0}processViewResponse(e,r){if("avg"===e.kind)throw new t.QueryError("Average results should be handled before processing rows");const i=r.rows||[],a=e,s=a.meta;return a.countDistinct?i.length||0:"distinct"===a.kind||"groupBy"===a.kind?i.map(e=>e.key??e.value):s.returnDocs?i.map(e=>e.value??e.doc??e):i.length?i[0].value??i[0].key??null:"count"===a.kind?0:null}isViewAggregate(e){return"avg"!==e.kind}}class Re extends t.Paginator{constructor(e,t,r,i){super(e,t,r,i)}prepare(e){throw new t.UnsupportedError("Raw query access must be implemented by a subclass. only prepared statements are natively available")}page(e=1,...t){return super.page(e,...t)}}var $e;class Be extends t.Adapter{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new v}static{this.log=c.Logging.for(Be)}constructor(e,t){super(Object.assign({},Oe,e),M,t),this.serializer=Be.serializer}Statement(e){return new De(this,e)}Paginator(e,t,r){return new Re(this,e,t,r)}async flags(e,t,r,...i){const a=Object.assign({},this.config,r);return Object.assign(await super.flags(e,t,a,...i))}async context(e,i,a,...s){this.log.for(this.context).silly(`creating new context for ${e} operation on ${a?Array.isArray(a)?a.map(e=>r.Model.tableName(e)):r.Model.tableName(a):"no"} table ${i&&Object.keys(i)?Object.keys(i).length:"no"} with flag overrides`);let n=s.pop();void 0===n||n instanceof t.Context||(s.push(n),n=void 0),i=n?Object.assign({},n.toOverrides(),i):i;const o=await this.flags("string"==typeof e?e:e.name,a,i,...[...s,n].filter(Boolean));if(n){if(!(n instanceof this.Context)){const e=(new this.Context).accumulate({...n.cache,...o,parentContext:n});return n.accumulate({childContexts:[...n.getOrUndefined("childContexts")||[],e]}),e}const t=n.getOrUndefined("operation"),r=n.getOrUndefined("affectedTables");if(!t||t!==e||a&&a!==r){const e=(new this.Context).accumulate({...n.cache,...o,parentContext:n});return n.accumulate({childContexts:[...n.getOrUndefined("childContexts")||[],e]}),e}return n.accumulate(o)}return(new this.Context).accumulate({...o})}decode(e){return Be.decoder.decode(e)}repository(){return b}createPrefix(e,t,i,...s){const{ctxArgs:n}=this.logCtx(s,this.createPrefix),o=r.Model.tableName(e),c={};return c[a.CouchDBKeys.TABLE]=o,Object.assign(c,i),[e,t,c,...n]}createAllPrefix(e,t,s,...n){const o=r.Model.tableName(e);if(t.length!==s.length)throw new i.InternalError("Ids and models must have the same length");const{ctxArgs:c}=this.logCtx(n,this.createAllPrefix),l=t.map((e,t)=>{const r={};return r[a.CouchDBKeys.TABLE]=o,Object.assign(r,s[t]),r});return[e,t,l,...c]}updateAllPrefix(e,t,s,...n){const o=r.Model.tableName(e);if(t.length!==s.length)throw new i.InternalError("Ids and models must have the same length");const{ctxArgs:c}=this.logCtx(n,this.updateAllPrefix),l=t.map(()=>{const e={};return e[a.CouchDBKeys.TABLE]=o,e});return[e,t,l,...c]}async createAll(e,t,a,...s){if(t.length!==a.length)throw new i.InternalError("Ids and models must have the same length");const n=[...s],o=n.shift(),{log:c,ctx:l}=this.logCtx(n,this.createAll),d=r.Model.tableName(e);c.info(`adding ${t.length} entries to ${d} table`),c.verbose("pks: "+t);const u=o&&Object.keys(o).length>0?{[d]:o}:{},h=await this.submitTransaction(l,i.BulkCrudOperationKeys.CREATE_ALL,[JSON.stringify(a.map(t=>this.serializer.serialize(t,e.name)))],u,this.getEndorsingOrganizations(l),e.name);try{return JSON.parse(this.decode(h)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}async readAll(e,t,...a){const{log:s,ctx:n}=this.logCtx(a,this.readAll),o=r.Model.tableName(e);s.info(`reading ${t.length} entries to ${o} table`),s.verbose("pks: "+t);const c=await this.evaluateTransaction(n,i.BulkCrudOperationKeys.READ_ALL,[JSON.stringify(t)],void 0,void 0,e.name);try{return JSON.parse(this.decode(c)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}async updateAll(e,t,a,...s){if(t.length!==a.length)throw new i.InternalError("Ids and models must have the same length");const n=[...s];let o=n.shift();const{log:c,ctx:l}=this.logCtx(n,this.updateAll),d=r.Model.tableName(e);c.info(`updating ${t.length} entries to ${d} table`),c.verbose("pks: "+t),o=o&&(Array.isArray(o)?o:Object.keys(o)).length?{[d]:o}:{};const u=await this.submitTransaction(l,i.BulkCrudOperationKeys.UPDATE_ALL,[JSON.stringify(a.map(t=>this.serializer.serialize(t,e.name)))],o,this.getEndorsingOrganizations(l),e.name);try{return JSON.parse(this.decode(u)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}async deleteAll(e,t,...a){const{log:s,ctx:n}=this.logCtx(a,this.deleteAll),o=r.Model.tableName(e);s.info(`deleting ${t.length} entries to ${o} table`),s.verbose("pks: "+t);const c=await this.submitTransaction(n,i.BulkCrudOperationKeys.DELETE_ALL,[JSON.stringify(t)],void 0,this.getEndorsingOrganizations(n),e.name);try{return JSON.parse(this.decode(c)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}prepare(e,...a){const{log:s,ctx:n}=this.logCtx(a,this.prepare),o=r.Model.segregate(e);e[t.PersistenceKeys.METADATA]&&(s.silly("Passing along persistence metadata for "+e[t.PersistenceKeys.METADATA]),Object.defineProperty(o.model,t.PersistenceKeys.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[t.PersistenceKeys.METADATA]}));const c=r.Model.mirroredAt(e);if(c){const e=c.mspId;if(!e)throw new i.InternalError("No mirror MSP could be found");const t=this.getEndorsingOrganizations(n)||[],r=[...new Set([...t,e])];n.accumulate({endorsingOrgs:r,endorsingOrganizations:r,legacy:!0})}return{record:o.model,model:o.model,id:e[r.Model.pk(e.constructor)],transient:o.transient,privates:o.privates,shared:o.shared}}revert(e,t,r,i,...a){const{log:s,ctx:n}=this.logCtx(a,this.revert);return i&&this.shouldRebuildWithTransient(n,n.getOrUndefined("operation"))&&(s.verbose("re-adding transient properties: "+Object.keys(i).join(", ")),Object.entries(i).filter(([,e])=>void 0!==e).forEach(([t,r])=>{t in e&&void 0!==e[t]&&s.warn(`overwriting existing ${t}. if this is not a default value, this may pose a problem`),e[t]=r})),new t(e)}shouldRebuildWithTransient(e,t){if(!e)return!1;if(e.getOrUndefined("rebuildWithTransient"))return!0;if("function"==typeof e.getFromChildren?e.getFromChildren("rebuildWithTransient"):void 0)return!0;const r=this.resolveOperation(e,t);if(!r)return!1;const i=r.toString().toLowerCase();return i.includes("read")||i.includes("find")||i.includes("query")||i.includes("statement")||i.includes("page")}resolveOperation(e,t){return t||("function"==typeof e.getFromChildren?e.getFromChildren("operation"):void 0)}shouldRefreshAfterWrite(e,t,r){return!!t&&null!=r&&!e.getOrUndefined("mirror")}getEndorsingOrganizations(e){const t=e.getOrUndefined("endorsingOrgs")||e.getOrUndefined("endorsingOrgs");return t&&t.length?t:e.getFromChildren("endorsingOrgs")||e.getFromChildren("endorsingOrgs")}async create(e,t,a,s={},...n){const o=[...n],{log:c,ctx:l}=this.logCtx(o,this.create),d=r.Model.tableName(e);c.verbose(`adding entry to ${d} table`),c.debug("pk: "+t);const u=s&&Object.keys(s).length>0,h=u?{[d]:s}:{},g=await this.submitTransaction(l,i.OperationKeys.CREATE,[this.serializer.serialize(a,e.name)],h,this.getEndorsingOrganizations(l),e.name),p=this.serializer.deserialize(this.decode(g));return this.shouldRefreshAfterWrite(l,u,t)?this.read(e,t,l):p}async healthcheck(e,...t){const{log:i,ctx:a}=this.logCtx(t,this.healthcheck),s=r.Model.tableName(e);i.verbose(`reading entry from ${s} table`);const n=await this.evaluateTransaction(a,"healthcheck",[],void 0,void 0,e.name);return JSON.parse(this.decode(n))}async read(e,t,...a){const{log:s,ctx:n}=this.logCtx(a,this.read),o=r.Model.tableName(e);s.verbose(`reading entry from ${o} table`),s.debug("pk: "+t);const c=await this.evaluateTransaction(n,i.OperationKeys.READ,[t.toString()],void 0,void 0,e.name);return this.serializer.deserialize(this.decode(c))}updatePrefix(e,t,i,...s){const n=r.Model.tableName(e),{ctxArgs:o}=this.logCtx(s,this.updatePrefix),c={};return c[a.CouchDBKeys.TABLE]=n,Object.assign(c,i),[e,t,c,...o]}async update(e,t,a,s={},...n){const o=[...n],{log:c,ctx:l}=this.logCtx(o,this.update);c.info("CLIENT UPDATE class : "+typeof e);const d=r.Model.tableName(e);c.verbose(`updating entry to ${d} table`),c.debug("pk: "+t);const u=s&&Object.keys(s).length>0,h=u?{[d]:s}:{},g=await this.submitTransaction(l,i.OperationKeys.UPDATE,[this.serializer.serialize(a,e.name||e)],h,this.getEndorsingOrganizations(l),e.name),p=this.serializer.deserialize(this.decode(g));return this.shouldRefreshAfterWrite(l,u,t)?this.read(e,t,l):p}async delete(e,t,...a){const{log:s,ctx:n}=this.logCtx(a,this.delete),o=r.Model.tableName(e);s.verbose(`deleting entry from ${o} table`),s.debug("pk: "+t);const c=await this.submitTransaction(n,i.OperationKeys.DELETE,[t.toString()],void 0,this.getEndorsingOrganizations(n),e.name);return this.serializer.deserialize(this.decode(c))}async raw(e,t=!0,a,...s){const{log:n,ctx:o}=this.logCtx(s,this.raw),c=a.name;let l,d;n.info("Performing raw statement on table "+r.Model.tableName(a));try{l=await this.evaluateTransaction(o,"raw",[JSON.stringify(e),t],void 0,void 0,c)}catch(e){throw this.parseError(e)}try{d=JSON.parse(this.decode(l))}catch(e){throw new i.SerializationError("Failed to process result: "+e)}if(Array.isArray(d)){if(!d.length)return d;const e=d[0];return r.Model.isModel(e)?d.map(e=>r.Model.build(e)):d}return u=d,r.Model.isModel(u)?r.Model.build(u):u;var u}async view(e,t,r,...a){const{log:s,ctx:n}=this.logCtx(a,this.view);let o,c;s.info(`Querying view ${e}/${t}`);try{o=await this.evaluateTransaction(n,"view",[e,t,JSON.stringify(r)],void 0,void 0,void 0)}catch(e){throw this.parseError(e)}try{c=JSON.parse(this.decode(o))}catch(e){throw new i.SerializationError("Failed to process view result: "+e)}return c}getClient(){return this._client||(this._client=Be.getClient(this.config)),this._client}async Gateway(e){return Be.getGateway(e,this.config,this.client)}getContractName(e){if(e)return e+"Contract"}async Contract(e,t){return Be.getContract(await this.Gateway(e),this.config,t)}async transaction(e,t,r=!0,i,a={},s,n){const o=this.log.for(this.transaction),c=await this.Gateway(e);try{const c=await this.Contract(e,this.getContractName(n));o.verbose(`${r?"Submit":"Evaluate"}ting transaction ${this.getContractName(n)||this.config.contractName}.${t}`),o.debug("args: "+(i?.map(e=>e.toString()).join("\n")||"none"));const l=r?c.submit:c.evaluate;s=s?.length?s:void 0;const d={arguments:i||[],transientData:Object.entries(a).reduce((e,[t,r])=>(e[t]=JSON.stringify(r),e),{}),endorsingOrganizations:e.getOrUndefined("allowManualEndorsingOrgs")&&s||void 0};return await l.call(c,t,d)}catch(e){throw this.parseError(e)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}shouldUseLegacyGateway(e){return!!e.getOrUndefined("legacy")&&!!e.getOrUndefined("allowGatewayOverride")}prepareLegacyArgs(e){return(e||[]).map(e=>"string"==typeof e?e:JSON.stringify(e))}buildLegacyTransient(e){if(!e)return;const t=Object.entries(e);if(!t.length)return;const r={};for(const[e,i]of t)r[e]=Buffer.from(JSON.stringify(i));return r}buildLegacyPeerConfigs(){return[{peerEndpoint:this.config.peerEndpoint,tlsCert:this.config.tlsCert,peerHostAlias:this.config.peerHostAlias}]}async submitLegacyWithExplicitEndorsers(e,t,r,i,a,s){const n=this.log.for(this.submitLegacyWithExplicitEndorsers),o=await this.Gateway(e);try{const c=Be.getContract(o,this.config,this.getContractName(s));n.verbose(`Legacy submitting ${this.getContractName(s)||this.config.contractName}.${t}`),n.debug("Explicit peers: "+a.map(e=>e.peerEndpoint));const l=new Set;this.config.mspId&&l.add(this.config.mspId),(this.getEndorsingOrganizations(e)||[]).forEach(e=>l.add(e));const d={arguments:r,transientData:i,endorsingOrganizations:l.size>0?Array.from(l):void 0},u=c.newProposal(t,d),h=await u.endorse(),g=await h.submit(),p=await g.getStatus();if(!p.successful)throw Error(`Legacy endorsement failed for ${h.getTransactionId()}: ${p.code}`);return h.getResult()}catch(e){throw this.parseError(e)}finally{o.close()}}parseError(e){return Be.parseError(e)}async submitTransaction(e,t,r,i,a,s){if(this.shouldUseLegacyGateway(e)){const a=this.prepareLegacyArgs(r),n=this.buildLegacyTransient(i),o=this.buildLegacyPeerConfigs();return this.submitLegacyWithExplicitEndorsers(e,t,a,n,o,s)}return this.transaction(e,t,!0,r,i,a,s)}async evaluateTransaction(e,t,r,i,a,s){return this.transaction(e,t,!1,r,i,a,s)}async close(){this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static getContract(e,t,r){const i=this.log.for(this.getContract),a=this.getNetwork(e,t.channel);let s;try{i.debug(`Retrieving chaincode ${t.chaincodeName} contract ${r||t.contractName} from network ${t.channel}`),r=r||t.contractName,s=a.getContract(t.chaincodeName,r)}catch(e){throw this.parseError(e)}return s}static getNetwork(e,t){const r=c.Logging.for(this.getNetwork);let i;try{r.debug("Connecting to channel "+t),i=e.getNetwork(t)}catch(e){throw this.parseError(e)}return i}static async getGateway(e,t,r){return await this.getConnection(r||await this.getClient(t),t,e)}static getClient(e){const t=this.log.for(this.getClient);t.debug("generating TLS credentials for msp "+e.mspId);let r=e.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(f.readFileSync(r,"utf8"))}catch(e){throw new i.InternalError(`Failed to read the tls certificate from ${r}: ${e}`)}const a=w.credentials.createSsl(r);return t.debug("generating Gateway Client for url "+e.peerEndpoint),new p.Client(e.peerEndpoint,a,{"grpc.max_receive_message_length":1024*(e.sizeLimit||15)*1024,"grpc.max_send_message_length":1024*(e.sizeLimit||15)*1024})}static async getConnection(e,r,i){const a=c.Logging.for(this.getConnection);a.debug(`Retrieving Peer Identity for ${r.mspId} under ${r.certCertOrDirectoryPath}`);const s=await Me(r.mspId,r.certCertOrDirectoryPath);try{a.debug("preparing transaction signer for "+k.fabricIdFromCertificate(s.credentials.toString()))}catch(e){a.error("Failed to extract Fabric ID from certificate",e)}let n;if(r.hsm)throw new t.UnsupportedError("HSM NOT IMPLEMENTED");n=await Ne(r.keyCertOrDirectoryPath);const o={client:e,identity:s,signer:n,evaluateOptions:()=>({deadline:Date.now()+1e3*i.get("evaluateTimeout")}),endorseOptions:()=>({deadline:Date.now()+1e3*i.get("endorseTimeout")}),submitOptions:()=>({deadline:Date.now()+1e3*i.get("submitTimeout")}),commitStatusOptions:()=>({deadline:Date.now()+1e3*i.get("commitTimeout")})};a.debug("Connecting to "+r.mspId);const d=l.connect(o);return r.hsm&&(d.close=new Proxy(d.close,{apply(e,t,r){Reflect.apply(e,t,r)}})),d}Dispatch(){return new Be._baseDispatch}static parseError(e){let r="string"==typeof e?e:e.message;return e instanceof l.GatewayError&&e.details.length&&10===e.code&&(r=""+e.details[0].message),r.includes("MVCC_READ_CONFLICT")?new J(e):r.includes("DEADLINE_EXCEEDED")?new Z(e):r.includes("ENDORSEMENT_POLICY_FAILURE")?new Q(e):r.includes("PHANTOM_READ_CONFLICT")?new W(e):e instanceof Error&&e.code&&9===e.code?new Y(e):r.includes(i.ValidationError.name)?new i.ValidationError(e):r.includes(i.NotFoundError.name)?new i.NotFoundError(e):r.includes(i.ConflictError.name)?new i.ConflictError(e):r.includes(i.BadRequestError.name)?new i.BadRequestError(e):r.includes(t.QueryError.name)?new t.QueryError(e):r.includes(t.PagingError.name)?new t.PagingError(e):r.includes(t.UnsupportedError.name)?new t.UnsupportedError(e):r.includes(t.MigrationError.name)?new t.MigrationError(e):r.includes(t.ObserverError.name)?new t.ObserverError(e):r.includes(t.AuthorizationError.name)?new t.AuthorizationError(e):r.includes(t.ForbiddenError.name)?new t.ForbiddenError(e):r.includes(t.ConnectionError.name)?new t.ConnectionError(e):r.includes(i.SerializationError.name)?new i.SerializationError(e):new i.InternalError(e)}}s.__decorate([c.debug(),c.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,Object,Object,t.Context]),s.__metadata("design:returntype",Promise)],Be.prototype,"create",null),s.__decorate([c.debug(),c.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,t.Context]),s.__metadata("design:returntype",Promise)],Be.prototype,"healthcheck",null),s.__decorate([c.debug(),c.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,t.Context]),s.__metadata("design:returntype",Promise)],Be.prototype,"read",null),s.__decorate([c.debug(),c.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,Object,Object,t.Context]),s.__metadata("design:returntype",Promise)],Be.prototype,"update",null),s.__decorate([c.debug(),c.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,t.Context]),s.__metadata("design:returntype",Promise)],Be.prototype,"delete",null),s.__decorate([c.debug(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,"function"==typeof($e="undefined"!=typeof D&&D)?$e:Object,Object,t.Context]),s.__metadata("design:returntype",Promise)],Be.prototype,"raw",null),s.__decorate([c.debug(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[String,String,Object,t.Context]),s.__metadata("design:returntype",Promise)],Be.prototype,"view",null),Be.decoration(),t.Adapter.setCurrent(M);class Pe extends t.Dispatch{constructor(e){super(),this.client=e,this.decoder=new TextDecoder("utf8")}async close(){this.listeningStack&&this.listeningStack.close()}parsePayload(e){const t=this.decoder.decode(e);return JSON.parse(t)}observe(e){if(!(e instanceof Be))throw new t.UnsupportedError("Only FabricClientAdapter can be observed by dispatch");return super.observe(e),()=>this.unObserve(e)}async updateObservers(e,a,s,...n){const{log:o,ctxArgs:c}=t.Adapter.logCtx(this.updateObservers,a,!1,...n);if(this.adapter)try{await this.adapter.refresh(e,a,s,...c)}catch(e){throw new i.InternalError("Failed to refresh dispatch: "+e)}else o.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof e?e:r.Model.tableName(e)}:${a}`)}async handleEvents(e){if(!this.listeningStack)throw new i.InternalError('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new i.InternalError("No adapter found. should be impossible");const t=e||await this.adapter.context(i.OperationKeys.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||r.Model),a=this.log.for(this.handleEvents);a.info(`Listening for incoming events on chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}"...`);try{for await(const e of this.listeningStack){const{table:i,event:s,owner:n}=Ce(e.eventName);if(n&&n!==this.adapter.config?.mspId)continue;const o=this.parsePayload(e.payload);try{const e=(i?r.Model.get(i):r.Model.get(this.models[0].name))??(i||this.models[0]?.name);await this.updateObservers(e,s,o.id,t)}catch(e){a.error(`Failed update observables for table ${i} event ${s} id: ${o.id}: ${e}`)}}}catch(e){a.error(`Failed to read event for chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}": ${e}`),await this.close()}}async initialize(){if(!this.adapter)throw new i.InternalError("No adapter or config observed for dispatch");const e=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},r.Model),{ctx:t}=this.logCtx([e],this.initialize),a=(await Be.getGateway(t,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new i.InternalError("No adapter observed for dispatch");this.listeningStack=await a.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(t)}}Be&&(Be._baseDispatch=Pe);const Ke="##VERSION##",ke="##PACKAGE##";n.Metadata.registerLibrary(ke,Ke),e.AllowanceError=j,e.BalanceError=L,e.BaseEncoder=K,e.ClientSerializer=v,e.CoreUtils=x,e.CryptoUtils=k,e.DefaultFabricClientFlags=Oe,e.DeterministicSerializer=Ee,e.EndorsementError=Y,e.EndorsementPolicyError=Q,e.FabricClientAdapter=Be,e.FabricClientDispatch=Pe,e.FabricClientRepository=b,e.FabricERC20ClientRepository=S,e.FabricEnrollmentService=te,e.FabricFlavour=M,e.FabricIdentityService=ve,e.ImplicitPrivateCollection=he,e.MissingContextError=H,e.MissingPKCSS11Lib=V,e.ModelCollection=(e,t)=>{const a=t||("function"!=typeof e?r.Model.ownerOf(e):void 0),s="function"==typeof e?e:e.constructor;if(!a)throw new i.InternalError(`Model ${s.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${c.toPascalCase(s.name)}${a?c.toPascalCase(a):""}`},e.MvccReadConflictError=J,e.NamespaceCollection=e=>(t,a)=>{const s=a||("function"!=typeof t?r.Model.ownerOf(t):void 0),n="function"==typeof t?t:t.constructor;if(!s)throw new i.InternalError(`Model ${n.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${e}${s?c.toPascalCase(s):""}`},e.NotInitializedError=q,e.OverflowError=z,e.Owner=function(){return function(e,r,a){const s=a.value;return a.value=async function(...e){const a=e[0],n=a.clientIdentity.getID(),o=await this.tokenRepository.select(),c=await o.execute(a);if(0==c.length)throw new i.NotFoundError("No tokens avaialble");if(c.length>1)throw new i.NotFoundError("To many token available : "+c.length);if(c[0].owner!=n)throw new t.AuthorizationError(`User not authorized to run ${r} on the token`);return await s.apply(this,e)},a}},e.PACKAGE_NAME=ke,e.PhantomReadConflictError=W,e.RegistrationError=U,e.RegistrationRequestBuilder=re,e.SEGREGATED_COLLECTION_EXTRACTION_PRIORITY=35,e.SimpleDeterministicSerializer=Ae,e.TransactionBufferSizeError=ee,e.TransactionLimitsError=X,e.TransactionTimeoutError=Z,e.UnauthorizedPrivateDataAccess=G,e.VERSION=Ke,e.add=(e,t)=>{const r=e+t;if(e!==r-t||t!==r-e)throw new z(`Addition overflow: ${e} + ${t}`);return r},e.applySegregationFlags=ge,e.contentOfLoadFile=Ie,e.createMirrorHandler=oe,e.deleteMirrorHandler=le,e.evalMirrorMetadata=ne,e.extractMspId=ie,e.extractPrivateKey=Te,e.extractSegregatedCollections=pe,e.generateFabricEventName=(e,t,r)=>{const i=[e,t];return r&&i.push(r),i.join("_")},e.generateModelDesignDocs=(e,t)=>{const r=a.generateViews([e]),i=t||{};return r.forEach(e=>{i[e._id]=e}),r},e.generateModelIndexes=e=>a.generateIndexes([e]),e.getAkiAndSerialFromCert=N,e.getCAUser=async(e,t,r,i)=>{_e.debug(`Creating a CA ${i} user ${e} with certificate ${r}`);const a=new d.User(e),s=d.User.newCryptoSuite();a.setCryptoSuite(s);const n=s.createKeyFromRaw(t);return await a.setEnrollment(n,r,i),a},e.getFirstDirFileName=xe,e.getFirstDirFileNameContent=async e=>{const{promises:r}=await t.normalizeImport(import("fs")),{join:i}=await t.normalizeImport(import("path")),a=await r.readdir(e);return(await r.readFile(i(e,a[0]))).toString()},e.getIdentity=Me,e.getSigner=Ne,e.mirror=(t,r,a)=>{const s="string"!=typeof r&&!!r,o=s?void 0:r,c=s?r:a;return n.Decoration.for(e.FabricModelKeys.MIRROR).define({decorator:(t,r,a)=>{const s={condition:a,mspId:r,resolver:t};return n.apply(n.metadata(n.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR),s),i.onRead(ue,s,{priority:30}),i.onCreate(de,s,{priority:20}),i.onUpdate(de,s,{priority:20}),i.onDelete(de,s,{priority:20}),i.afterCreate(oe,s,{priority:95}),i.afterUpdate(ce,s,{priority:95}),i.afterDelete(le,s,{priority:95}))},args:[t,o,c]}).apply()},e.mirrorWriteGuard=de,e.ownedBy=()=>n.Decoration.for(e.FabricModelKeys.OWNED_BY).define({decorator:()=>(t,a)=>n.apply(r.required(),i.generated(),i.readonly(),i.onCreate(ae),n.propMetadata(n.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.OWNED_BY),a))(t,a),args:[]}).apply(),e.ownedByOnCreate=ae,e.parseEventName=Ce,e.privateData=(t=he)=>n.Decoration.for(e.FabricModelKeys.PRIVATE).define({decorator:t=>be(t,e.FabricModelKeys.PRIVATE),args:[t]}).apply(),e.readFile=async e=>"string"!=typeof e?e:await(async e=>{const{promises:r}=await t.normalizeImport(import("fs"));return await r.readFile(e)})(e),e.readMirrorHandler=ue,e.readModelFile=_,e.readModelFolders=async(...e)=>{const t=require("fs"),r=[];for(const i of e){const e=t.readdirSync(i,{withFileTypes:!0,recursive:!0}).filter(e=>e.isFile()&&e.name.endsWith("js"));for(const t of e)r.push(..._(t))}return r},e.safeParseInt=e=>{if(!/^\d+$/.test(e))throw new i.ValidationError(r.stringFormat("Failed to parse: {0}","string contains digits"));const t=parseInt(e);if(isNaN(t))throw new i.ValidationError(r.stringFormat("Failed to parse: {0}","string is not a parsable integer"));return t},e.segregatedDataOnCreate=fe,e.segregatedDataOnDelete=we,e.segregatedDataOnRead=ye,e.segregatedDataOnUpdate=me,e.sharedData=t=>n.Decoration.for(e.FabricModelKeys.SHARED).define({decorator:t=>be(t,e.FabricModelKeys.SHARED),args:[t]}).apply(),e.sub=(e,t)=>{const r=e-t;if(e!==r+t||t!==e-r)throw new z(`Subtraction overflow: ${e} - ${t}`);return r},e.transactionId=()=>n.Decoration.for(e.FabricModelKeys.TRANSACTION_ID).define({decorator:()=>(t,a)=>n.apply(r.required(),i.readonly(),i.onCreate(se),i.onUpdate(se),n.propMetadata(n.Metadata.key(e.FabricModelKeys.FABRIC,a,e.FabricModelKeys.TRANSACTION_ID),a))(t,a),args:[]}).apply(),e.transactionIdOnCreate=se,e.updateMirrorHandler=ce,e.writeDesignDocs=(e,t=process.cwd(),r)=>{if(!e.length)return;const i=require("fs"),a=require("path");e.forEach(e=>{const s=e._id.replace(/^_design\//,""),n=a.resolve(a.join(t,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}design_docs/${s}.json`));O(n);const o={...e};delete o._rev,i.writeFileSync(n,JSON.stringify(o,void 0,2))})},e.writeIndexes=(e,t=process.cwd(),r)=>{const i=require("fs"),a=require("path");e.forEach(e=>{const s=a.resolve(a.join(t,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}indexes/${e.name}.json`));O(s),i.writeFileSync(s,JSON.stringify(e,void 0,2))})}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/core"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/db-decorators"),require("@decaf-ts/for-couchdb"),require("tslib"),require("@decaf-ts/decoration"),require("fabric-ca-client"),require("@decaf-ts/logging"),require("@hyperledger/fabric-gateway"),require("fabric-common"),require("crypto"),require("@peculiar/x509"),require("@peculiar/webcrypto"),require("@grpc/grpc-js"),require("fs")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/core","@decaf-ts/decorator-validation","@decaf-ts/db-decorators","@decaf-ts/for-couchdb","tslib","@decaf-ts/decoration","fabric-ca-client","@decaf-ts/logging","@hyperledger/fabric-gateway","fabric-common","crypto","@peculiar/x509","@peculiar/webcrypto","@grpc/grpc-js","fs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-fabric"]={},e.decafTsCore,e.decafTsDecoratorValidation,e.decafTsDbDecorators,e.decafTsForCouchdb,e.tslib,e.decafTsDecoration,e.fabricCaClient,e.decafTsLogging,e.hyperledgerFabricGateway,e.fabricCommon,e.crypto,e.peculiarX509,e.peculiarWebcrypto,e.grpcGrpcJs,e.fs);
|
|
1
|
+
var e,t;e=this,t=function(e,t,r,i,a,s,n,o,c,l,d,u,h,g,p,f){"use strict";function y(e){var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var m=y(h),w=y(p);class b extends t.Repository{constructor(e,t){super(e,t),this._overrides=Object.assign({},super._overrides,{ignoreValidation:!0,ignoreHandlers:!0,allowRawStatements:!1,forcePrepareSimpleQueries:!0,forcePrepareComplexQueries:!0,allowGenerationOverride:!1})}override(e){return super.override(Object.assign({},e,this._overrides)).for(e)}ObserverHandler(){return super.ObserverHandler()}async paginateBy(e,i,a={offset:1,limit:10},...s){const{log:n,ctxArgs:o}=(await this.logCtx(s,t.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return n.verbose(`paginating ${r.Model.tableName(this.class)} with page size ${a.limit}`),this.statement(this.paginateBy.name,e,i,{limit:a.limit,offset:a.offset,bookmark:a.bookmark},...o)}async listBy(e,i,...a){const{log:s,ctxArgs:n}=(await this.logCtx(a,t.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${r.Model.tableName(this.class)} by ${e} ${i}`),await this.statement(this.listBy.name,e,i,...n)}async findBy(e,i,...a){const{log:s,ctxArgs:n}=(await this.logCtx(a,t.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding all ${r.Model.tableName(this.class)} with ${e} ${i}`),await this.statement(this.findBy.name,e,i,...n)}async findOneBy(e,i,...a){const{log:s,ctxArgs:n}=(await this.logCtx(a,t.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return s.verbose(`finding One ${r.Model.tableName(this.class)} with ${e} ${i}`),await this.statement(this.findOneBy.name,e,i,...n)}async find(e,i=t.OrderDirection.ASC,...a){const{log:s,ctxArgs:n}=(await this.logCtx(a,t.PreparedStatementKeys.FIND,!0)).for(this.find);return s.verbose(`finding ${r.Model.tableName(this.class)} by default query attributes`),await this.statement(this.find.name,e,i,...n)}async page(e,i=t.OrderDirection.ASC,a={offset:1,limit:10},...s){const{log:n,ctxArgs:o}=(await this.logCtx(s,t.PreparedStatementKeys.PAGE,!0)).for(this.page);return n.verbose(`paging ${r.Model.tableName(this.class)} by default query attributes`),await this.statement(this.page.name,e,i,a,...o)}async statement(e,...i){const{log:s,ctx:n,ctxArgs:o}=(await this.logCtx(i,t.PersistenceKeys.STATEMENT,!0)).for(this.statement);s.verbose("Executing prepared statement "+e);const c=o.slice(0,-1),l=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(n,t.PersistenceKeys.STATEMENT,[e,JSON.stringify(c)],void 0,void 0,this.class.name)));return Array.isArray(l)?l.map(e=>e[a.CouchDBKeys.TABLE]&&e[a.CouchDBKeys.TABLE]===r.Model.tableName(this.class)?new this.class(e):e):l[a.CouchDBKeys.TABLE]&&l[a.CouchDBKeys.TABLE]===r.Model.tableName(this.class)?new this.class(l):t.Paginator.isSerializedPage(l)?Object.assign(l,{data:l.data.map(e=>new this.class(e))}):l}async countOf(e,...i){const{log:a,ctxArgs:s}=(await this.logCtx(i,t.PreparedStatementKeys.COUNT_OF,!0)).for(this.countOf);a.verbose(`counting ${r.Model.tableName(this.class)}${e?" by "+e:""}`);const n=e?[e,...s]:s;return this.statement(t.PreparedStatementKeys.COUNT_OF,...n)}async maxOf(e,...i){const{log:a,ctxArgs:s}=(await this.logCtx(i,t.PreparedStatementKeys.MAX_OF,!0)).for(this.maxOf);return a.verbose(`finding max of ${e} in ${r.Model.tableName(this.class)}`),this.statement(t.PreparedStatementKeys.MAX_OF,e,...s)}async minOf(e,...i){const{log:a,ctxArgs:s}=(await this.logCtx(i,t.PreparedStatementKeys.MIN_OF,!0)).for(this.minOf);return a.verbose(`finding min of ${e} in ${r.Model.tableName(this.class)}`),this.statement(t.PreparedStatementKeys.MIN_OF,e,...s)}async avgOf(e,...i){const{log:a,ctxArgs:s}=(await this.logCtx(i,t.PreparedStatementKeys.AVG_OF,!0)).for(this.avgOf);return a.verbose(`calculating avg of ${e} in ${r.Model.tableName(this.class)}`),this.statement(t.PreparedStatementKeys.AVG_OF,e,...s)}async sumOf(e,...i){const{log:a,ctxArgs:s}=(await this.logCtx(i,t.PreparedStatementKeys.SUM_OF,!0)).for(this.sumOf);return a.verbose(`calculating sum of ${e} in ${r.Model.tableName(this.class)}`),this.statement(t.PreparedStatementKeys.SUM_OF,e,...s)}async distinctOf(e,...i){const{log:a,ctxArgs:s}=(await this.logCtx(i,t.PreparedStatementKeys.DISTINCT_OF,!0)).for(this.distinctOf);return a.verbose(`finding distinct values of ${e} in ${r.Model.tableName(this.class)}`),this.statement(t.PreparedStatementKeys.DISTINCT_OF,e,...s)}async groupOf(e,...i){const{log:a,ctxArgs:s}=(await this.logCtx(i,t.PreparedStatementKeys.GROUP_OF,!0)).for(this.groupOf);return a.verbose(`grouping ${r.Model.tableName(this.class)} by ${e}`),this.statement(t.PreparedStatementKeys.GROUP_OF,e,...s)}async healthcheck(...e){const{log:t,ctxArgs:r}=this.logCtx(e,this.healthcheck);return await this.adapter.healthcheck(this.class,...r)}async create(e,...t){const{ctx:i,log:a,ctxArgs:s}=this.logCtx(t,this.create);a.debug(`Creating new ${this.class.name} in table ${r.Model.tableName(this.class)}`),this.ensureLegacyMirrorFlag(i,e);const n=this.adapter.prepare(e,i),{record:o,id:c,transient:l}=n,d=await this.adapter.create(this.class,c,o,l,...s);if(this.shouldRefreshAfterWrite(n,i)&&null!=c){const e=await this.adapter.read(this.class,c,i);return this.adapter.revert(e,this.class,c,i.get("rebuildWithTransient")?n.transient:void 0,i)}return this.adapter.revert(d,this.class,c,l,i)}async update(e,...t){const{ctxArgs:i,log:a,ctx:s}=this.logCtx(t,this.update);this.ensureLegacyMirrorFlag(s,e);const n=this.adapter.prepare(e,s),{id:o,transient:c}=n;let l=n.record;if(a.debug(`updating ${this.class.name} in table ${r.Model.tableName(this.class)} with id ${o}`),l=await this.adapter.update(this.class,o,l,c,...i),this.shouldRefreshAfterWrite(n,s)&&null!=o){const e=await this.adapter.read(this.class,o,s);return this.adapter.revert(e,this.class,o,s.get("rebuildWithTransient")?n.transient:void 0,s)}return this.adapter.revert(l,this.class,o,c,s)}async createAllPrefix(e,...t){const{ctx:r,ctxArgs:a}=(await this.logCtx(t,i.OperationKeys.CREATE,!0)).for(this.createAllPrefix),s=r.get("ignoreHandlers"),n=r.get("ignoreValidation");if(!e.length)return[e,...a];if(e=await Promise.all(e.map(async e=>(e=new this.class(e),s||await i.enforceDBDecorators(this,r,e,i.OperationKeys.CREATE,i.OperationKeys.ON),e))),!n){const t=r.get("ignoredValidationProperties")||[],a=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),s=i.reduceErrorsToPrint(a);if(s)throw new i.ValidationError(s)}return[e,...a]}async createAll(e,...t){if(!e.length)return e;const{ctx:i,log:a,ctxArgs:s}=this.logCtx(t,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${r.Model.tableName(this.class)}`),e.forEach(e=>this.ensureLegacyMirrorFlag(i,e));const n=e.map(e=>this.adapter.prepare(e,i)),o=n.map(e=>e.id),c=n.map(e=>e.record),l=n.map(e=>e.transient),d=await this.adapter.createAll(this.class,o,c,l,...s);return Promise.all(d.map(async(e,t)=>{const r=o[t];if(this.shouldRefreshAfterWrite(n[t],i)&&null!=r){const e=await this.adapter.read(this.class,r,i);return this.adapter.revert(e,this.class,r,i.get("rebuildWithTransient")?n[t].transient:void 0,i)}return this.adapter.revert(e,this.class,r,l[t],i)}))}async updateAll(e,...t){const{ctx:i,log:a,ctxArgs:s}=this.logCtx(t,this.updateAll);a.debug(`Updating ${e.length} new ${this.class.name} in table ${r.Model.tableName(this.class)}`),e.forEach(e=>this.ensureLegacyMirrorFlag(i,e));const n=e.map(e=>this.adapter.prepare(e,i)),o=n.map(e=>e.id),c=await this.adapter.updateAll(this.class,o,n.map(e=>e.record),n.map(e=>e.transient),...s);return Promise.all(c.map(async(e,t)=>{const r=o[t];if(this.shouldRefreshAfterWrite(n[t],i)&&null!=r){const e=await this.adapter.read(this.class,r,i);return this.adapter.revert(e,this.class,r,i.get("rebuildWithTransient")?n[t].transient:void 0,i)}return this.adapter.revert(e,this.class,r,n[t].transient,i)}))}shouldRefreshAfterWrite(e,t){const r=e.privates&&Object.keys(e.privates).length>0,i=e.shared&&Object.keys(e.shared).length>0;return r||i||!!t.getOrUndefined("segregated")||!!t.getOrUndefined("mirror")}ensureLegacyMirrorFlag(e,t){r.Model.mirroredAt(t)&&e.accumulate({legacy:!0})}}let E=class extends t.BaseModel{constructor(e){super(e)}};s.__decorate([t.pk({type:String}),s.__metadata("design:type",String)],E.prototype,"name",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],E.prototype,"owner",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],E.prototype,"symbol",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",Number)],E.prototype,"decimals",void 0),E=s.__decorate([t.table("erc20_tokens"),r.model(),s.__metadata("design:paramtypes",[Object])],E);let C=class extends t.BaseModel{constructor(e){super(e)}};s.__decorate([t.pk({type:String}),s.__metadata("design:type",String)],C.prototype,"id",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],C.prototype,"token",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",Number)],C.prototype,"balance",void 0),s.__decorate([t.column(),s.__metadata("design:type",String)],C.prototype,"captive",void 0),C=s.__decorate([t.table("erc20_wallets"),r.model(),s.__metadata("design:paramtypes",[Object])],C);let A=class extends t.BaseModel{constructor(e){super(e)}};s.__decorate([t.pk({type:String}),t.column(),r.required(),s.__metadata("design:type",String)],A.prototype,"owner",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],A.prototype,"spender",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",Number)],A.prototype,"value",void 0),A=s.__decorate([t.table("erc20_allowances"),r.model(),s.__metadata("design:paramtypes",[Object])],A);class v extends r.JSONSerializer{constructor(){super()}preSerialize(e,t){const a=Object.assign({},e);let s=n.Metadata.modelName(e.constructor);if(!s||"Object"===s){if(!t)throw new i.SerializationError("Could not find metadata for "+e.constructor.name);s=t}return a[r.ModelKeys.ANCHOR]=s,a}deserialize(e){const t=JSON.parse(e),i=t[r.ModelKeys.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return r.Model.build(t,i)}serialize(e,t){return JSON.stringify(this.preSerialize(e,t))}}class S extends b{static{this.serializer=new v}static{this.decoder=new TextDecoder("utf8")}async updateObservers(e,a,s,...n){if(!this.observerHandler)throw new i.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:o,ctxArgs:c}=this.logCtx(n,this.updateObservers);let l;o.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),e="string"==typeof e?r.Model.get(e):e,l=void 0===s?void 0:Array.isArray(s)?s.map(i=>t.Sequence.parseValue(r.Model.sequenceFor(e).type,i)):t.Sequence.parseValue(r.Model.sequenceFor(e).type,s),await this.observerHandler.updateObservers(e,a,l,...c)}decode(e){return S.decoder.decode(e)}constructor(e){super(e,C),this.serializer=S.serializer}async tokenName(...e){const{ctx:t}=(await this.logCtx(e,"tokenName",!0)).for(this.tokenName),r=await this.adapter.evaluateTransaction(t,"TokenName");return this.decode(r)}async symbol(...e){const{ctx:t}=(await this.logCtx(e,"symbol",!0)).for(this.symbol),r=await this.adapter.evaluateTransaction(t,"Symbol");return this.decode(r)}async decimals(...e){const{ctx:t}=(await this.logCtx(e,"decimals",!0)).for(this.decimals),r=await this.adapter.evaluateTransaction(t,"Decimals");return Number(this.decode(r))}async totalSupply(...e){const{ctx:t}=(await this.logCtx(e,"totalSupply",!0)).for(this.totalSupply),r=await this.adapter.evaluateTransaction(t,"TotalSupply");return Number(this.decode(r))}async balanceOf(e,...t){const{ctx:r}=(await this.logCtx(t,"balance",!0)).for(this.balanceOf),i=await this.adapter.evaluateTransaction(r,"BalanceOf",[e]);return Number(this.decode(i))}async transfer(e,t,...r){const{ctx:i}=(await this.logCtx(r,"transfer",!0)).for(this.transfer),a=await this.adapter.submitTransaction(i,"Transfer",[e,t.toString()]);return"true"===this.decode(a)}async transferFrom(e,r,i){const a=await t.Context.args("transferFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:s}=this.logCtx(a.args,this.transferFrom),n=await this.adapter.submitTransaction(s,"TransferFrom",[e,r,i.toString()]);return"true"===this.decode(n)}async approve(e,r){const i=await t.Context.args("approve",this.class,[],this.adapter,this._overrides||{}),{ctx:a}=this.logCtx(i.args,this.approve),s=await this.adapter.submitTransaction(a,"Approve",[e,r.toString()]);return"true"===this.decode(s)}async allowance(e,r){const i=await t.Context.args("allowance",this.class,[],this.adapter,this._overrides||{}),{ctx:a}=this.logCtx(i.args,this.allowance),s=await this.adapter.submitTransaction(a,"Allowance",[e,r]);return Number(this.decode(s))}async initialize(e){const r=await t.Context.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.initialize),a=await this.adapter.submitTransaction(i,"Initialize",[S.serializer.serialize(e)]);return"true"===this.decode(a)}async checkInitialized(){const e=await t.Context.args("checkInitialized",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.checkInitialized);await this.adapter.evaluateTransaction(r,"CheckInitialized")}async mint(e){const r=await t.Context.args("mint",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.mint);await this.adapter.submitTransaction(i,"Mint",[e.toString()])}async burn(e){const r=await t.Context.args("burn",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.burn);await this.adapter.submitTransaction(i,"Burn",[e.toString()])}async burnFrom(e,r){const i=await t.Context.args("burnFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:a}=this.logCtx(i.args,this.burnFrom);await this.adapter.submitTransaction(a,"BurnFrom",[e,r.toString()])}async clientAccountBalance(){const e=await t.Context.args("accountBalance",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.clientAccountBalance),i=await this.adapter.evaluateTransaction(r,"ClientAccountBalance");return Number(this.decode(i))}async clientAccountID(){const e=await t.Context.args("accountId",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.clientAccountID),i=await this.adapter.evaluateTransaction(r,"ClientAccountID");return this.decode(i)}}function O(e){const t=require("fs"),r=require("path").dirname(e);if(t.existsSync(r))return!0;O(r),t.mkdirSync(r)}function _(e){const t=require("path"),i=require(t.join(process.cwd(),e.parentPath,e.name));return Object.values(i).filter(e=>{try{return new e instanceof r.Model}catch(e){return!1}})}var I;e.IdentityCredentials=class extends t.BaseModel{constructor(e){super(e)}},s.__decorate([n.description("Unique identifier of the credentials record"),t.column(),t.pk(),s.__metadata("design:type",String)],e.IdentityCredentials.prototype,"id",void 0),s.__decorate([n.description("PEM-encoded X.509 certificate for the identity"),t.column(),r.required(),s.__metadata("design:type",String)],e.IdentityCredentials.prototype,"certificate",void 0),s.__decorate([n.description("PEM-encoded root or intermediate certificate"),t.column(),r.required(),s.__metadata("design:type",String)],e.IdentityCredentials.prototype,"rootCertificate",void 0),s.__decorate([n.description("PEM-encoded private key"),t.column(),r.required(),s.__metadata("design:type",String)],e.IdentityCredentials.prototype,"privateKey",void 0),e.IdentityCredentials=s.__decorate([r.model(),s.__metadata("design:paramtypes",[Object])],e.IdentityCredentials),e.FabricModelKeys=void 0,(I=e.FabricModelKeys||(e.FabricModelKeys={})).PRIVATE="private",I.SHARED="shared",I.FABRIC="fabric",I.OWNED_BY="owned-by",I.TRANSACTION_ID="transaction-id",I.MIRROR="mirror",e.IdentityType=void 0,(e.IdentityType||(e.IdentityType={})).X509="X.509";const M="hlf-fabric";e.Identity=class extends t.BaseModel{constructor(t){super(t),this.type=e.IdentityType.X509}},s.__decorate([n.description("Unique identifier of the identity"),t.pk(),s.__metadata("design:type",String)],e.Identity.prototype,"id",void 0),s.__decorate([t.oneToOne(e.IdentityCredentials,{update:t.Cascade.CASCADE,delete:t.Cascade.CASCADE}),s.__metadata("design:type",e.IdentityCredentials)],e.Identity.prototype,"credentials",void 0),s.__decorate([t.column(),r.required(),t.index(),s.__metadata("design:type",String)],e.Identity.prototype,"mspId",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],e.Identity.prototype,"type",void 0),e.Identity=s.__decorate([r.model(),s.__metadata("design:paramtypes",[Object])],e.Identity);class x{static{this.logger=new c.MiniLogger(x.name)}constructor(){}static async contentOfLoadFile(e,t){return e instanceof Uint8Array||e.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?e:await t(e)}static async readFile(e){return"string"!=typeof e?e:await(async e=>{const{promises:r}=await t.normalizeImport(import("fs"));return await r.readFile(e)})(e)}static async getCAUser(e,t,i,a,s){this.logger.debug(r.stringFormat("Creating CA {0} user {1} with certificate {2}",a,e,i));const n=new d.User(e),o=s?.hsm?{software:!1,lib:s.hsm.library,slot:s.hsm.slot,label:s.hsm.tokenLabel,pin:s.hsm.pin+""}:void 0,c=this.getCryptoSuite(o);n.setCryptoSuite(c);const l=s?.hsm?await this.getHSMEnrollmentKey(c,i,s.hsm):this.getSoftwareEnrollmentKey(c,t);return await n.setEnrollment(l,i,a),n}static getCryptoSuite(e){return e?(x.cryptoSuite||(x.cryptoSuite=d.User.newCryptoSuite(e)),x.cryptoSuite):d.User.newCryptoSuite()}static getSoftwareEnrollmentKey(e,t){if(!t)throw Error("Private key must be provided when HSM configuration is not supplied");return e.createKeyFromRaw(t)}static async getHSMEnrollmentKey(e,t,r){const i=r.keyIdHex&&r.keyIdHex.trim().length>0?Buffer.from(r.keyIdHex,"hex"):await this.getCertificateSKI(t),a=await e.getKey(i);if(!a||"function"==typeof a.isPrivate&&!a.isPrivate())throw Error("Unable to resolve private key from HSM");return a}static async getCertificateSKI(e){const t=new u.X509Certificate(e).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(t.x||"","base64url"),a=Buffer.from(t.y||"","base64url");return u.createHash("sha256").update(Buffer.concat([r,i,a])).digest()}static async getIdentity(e,r){return{mspId:e,credentials:await this.contentOfLoadFile(r,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await this.getFirstDirFileName(e);return await r.readFile(i)})}}static async getFirstDirFileName(e){const{promises:r}=await t.normalizeImport(import("fs")),{join:i}=await t.normalizeImport(import("path"));return i(e,(await r.readdir(e))[0])}static async getFirstDirFileNameContent(e){const{promises:r}=await t.normalizeImport(import("fs")),{join:i}=await t.normalizeImport(import("path")),a=await r.readdir(e);return(await r.readFile(i(e,a[0]))).toString()}static async getFileContent(e){const{promises:r}=await t.normalizeImport(import("fs"));return(await r.readFile(e)).toString()}static async getSigner(e){const r=await this.contentOfLoadFile(e,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await this.getFirstDirFileName(e);return await r.readFile(i)}),i=await this.extractPrivateKey(r),a=i[Object.getOwnPropertySymbols(i)[0]];return l.signers.newPrivateKeySigner(a)}static async extractPrivateKey(e){let r;if(globalThis.window&&globalThis.window.Crypto)r=globalThis.Crypto.subtle;else{const e=await t.normalizeImport(import("crypto"));r=e.subtle||e.webcrypto.subtle}if(!r)throw Error("Could not load SubtleCrypto module");const i=e.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),a=(e=>{const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t})(Buffer.from(i,"base64").toString("binary"));return await r.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}}function N(e){const t=new h.X509Certificate(e),r=t.extensions?.find(e=>"2.5.29.35"===e.type);if(!r)throw Error("Authority Key Identifier (AKI) extension not found in certificate.");let i=Buffer.from(new Uint8Array(r.value)).toString("hex").toUpperCase();return i.startsWith("30168014")&&i.length>=48&&(i=i.slice(8,48)),{aki:i,serial:t.serialNumber}}const T=new g.Crypto;var F,R,$,B,P;m.cryptoProvider.set(T),e.BASE_ALPHABET=void 0,(F=e.BASE_ALPHABET||(e.BASE_ALPHABET={})).BASE2="01",F.BASE8="01234567",F.BASE11="0123456789a",F.BASE16="0123456789abcdef",F.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",F.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",F.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",F.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",F.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",F.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",F.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~",e.CRYPTO=void 0,(R=e.CRYPTO||(e.CRYPTO={})).HASH="SHA-256",R[R.ITERATIONS=1e3]="ITERATIONS",R[R.KEYLENGTH=48]="KEYLENGTH",R[R.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",R[R.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",R.ALGORYTHM="AES-GCM",R.KEY_ALGORYTHM="PBKDF2";class K{constructor(e){if(this.alphabet=e,this.baseMap=new Uint8Array(256),this.alphabet.length>=255)throw Error("Alphabet too long");for(let e=0;e<this.baseMap.length;e++)this.baseMap[e]=255;for(let t=0;t<e.length;t++){const r=e.charAt(t),i=r.charCodeAt(0);if(255!==this.baseMap[i])throw Error(r+" is ambiguous");this.baseMap[i]=t}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(e){if("string"==typeof e?e=Buffer.from(e):ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)&&(e=Uint8Array.from(e)),0===e.length)return"";let t=0,r=0,i=0;const a=e.length;for(;i!==a&&0===e[i];)i++,t++;const s=(a-i)*this.iFactor+1>>>0,n=new Uint8Array(s);for(;i!==a;){let t=e[i],a=0;for(let e=s-1;(0!==t||r>a)&&-1!==e;e--,a++)t+=256*n[e]>>>0,n[e]=t%this.base>>>0,t=t/this.base>>>0;if(0!==t)throw Error("Non-zero carry");r=a,i++}let o=s-r;for(;o!==s&&0===n[o];)o++;let c=this.leader.repeat(t);for(;s>o;++o)c+=this.alphabet.charAt(n[o]);return c}decodeUnsafe(e){if(0===e.length)return new Uint8Array(0);let t=0,r=0,i=0;for(;e[t]===this.leader;)r++,t++;const a=(e.length-t)*this.factor+1>>>0,s=new Uint8Array(a);for(;e[t];){let r=this.baseMap[e.charCodeAt(t)];if(255===r)return;let n=0;for(let e=a-1;(0!==r||i>n)&&-1!==e;e--,n++)r+=this.base*s[e]>>>0,s[e]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");i=n,t++}let n=a-i;for(;n!==a&&0===s[n];)n++;const o=new Uint8Array(r+(a-n));let c=r;for(;n!==a;)o[c++]=s[n++];return o}decode(e){const t=this.decodeUnsafe(e);if(t)return t;throw Error("Non-base"+this.base+" character")}}class k{static{this.b58encoder=new K(e.BASE_ALPHABET.BASE58)}static{this.logger=new c.MiniLogger(k.name)}constructor(){}static fabricIdFromCertificate(e){this.logger.debug(r.stringFormat("Parsing certificate: {0}",e));const t=new m.X509Certificate(e),{subject:i,issuer:a}=t;return this.logger.debug(r.stringFormat("Certificate parsed with subject {0} and issuer {1}",i,a)),`x509::/${i.replaceAll(", ","/")}::/${a.replaceAll(", ","/")}`}static encode(e){return this.b58encoder.encode(e)}static decode(e){const t=this.b58encoder.decode(e);return(new TextDecoder).decode(t)}static stringToArrayBuffer(e){const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t}static async extractKey(e,t,r){const i=T.subtle,a=t.toString("utf8").replace(RegExp(`-----BEGIN (${e.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${e.toUpperCase()} KEY|CERTIFICATE)-----`),""),s=Buffer.from(a,"base64").toString("binary"),n=this.stringToArrayBuffer(s);return await i.importKey("pkcs8",n,{name:"ECDSA",namedCurve:"P-256"},!0,r||["sign"])}static async extractPrivateKey(e,t){return this.extractKey("private",e,t)}static async extractPublicKey(e,t){return this.extractKey("public",e,t)}static async sign(e,t){const r=await this.extractPrivateKey(e),i=await T.subtle.sign({name:"ECDSA",hash:"SHA-256"},r,t);return Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join("")}static async verify(e,t,r){const i=new m.X509Certificate(e),a=await i.publicKey.export();return t="string"==typeof t?Buffer.from(t,"hex"):t,r="string"==typeof r?Buffer.from(r):r,T.subtle.verify({name:"ECDSA",hash:"SHA-256"},a,t,r)}static async encrypt(e,t){const r=new m.X509Certificate(e),i=await r.publicKey.export();t="string"==typeof t?Buffer.from(t):t;const a=await this.getSubtleCrypto().encrypt({name:"ECDSA"},i,t);return Array.from(new Uint8Array(a)).map(e=>e.toString(16).padStart(2,"0")).join("")}static getSubtleCrypto(){return c.isBrowser()?globalThis.window.crypto.subtle:T.subtle}static async decrypt(e,t){const r=await this.extractPrivateKey(e);return t="string"==typeof t?Buffer.from(t,"hex"):t,this.getSubtleCrypto().decrypt({name:"ECDSA"},r,t)}static async getMaster(t){const r=new TextEncoder;if(void 0===t){const e=T.randomUUID();t=r.encode(e).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,e.CRYPTO.KEY_ALGORYTHM,!1,["deriveBits"]),iv:t}}static async getDerivationKey(t,r){const i=(new TextEncoder).encode(t),a=await this.getSubtleCrypto().digest("SHA-256",i),s={name:e.CRYPTO.KEY_ALGORYTHM,hash:e.CRYPTO.HASH,salt:a,iterations:e.CRYPTO.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,r,8*e.CRYPTO.KEYLENGTH);return this.getKey(n)}static async getKey(t){const r=t.slice(0,32),i=t.slice(32);return{key:await this.getSubtleCrypto().importKey("raw",r,{name:e.CRYPTO.ALGORYTHM},!1,["encrypt","decrypt"]),iv:i}}static async encryptPin(t,r){const i=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:e.CRYPTO.ALGORYTHM,iv:r.iv},r.key,i)}static async decryptPin(t,r){const i=new TextDecoder,a=await this.getSubtleCrypto().decrypt({name:e.CRYPTO.ALGORYTHM,iv:r.iv},r.key,t);return i.decode(a)}}class z extends i.InternalError{constructor(e){super(e,z.name)}}class L extends i.InternalError{constructor(e){super(e,L.name)}}class j extends i.InternalError{constructor(e){super(e,j.name)}}class U extends t.AuthorizationError{constructor(e){super(e,U.name)}}class H extends i.InternalError{constructor(e){super(e,H.name,500)}}class G extends i.BaseError{constructor(e="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(G.name,e,403)}}class q extends i.BaseError{constructor(e){super(q.name,e,409)}}class V extends i.InternalError{constructor(e){super(e,V.name,500)}}class Y extends i.InternalError{constructor(e){super(e,Y.name,500)}}class W extends i.InternalError{constructor(e){super(e,W.name,500)}}class J extends i.InternalError{constructor(e){super(e,J.name,500)}}class Q extends i.InternalError{constructor(e){super(e,Q.name,500)}}class X extends i.InternalError{constructor(e,t=X.name,r=590){super(e,t,r)}}class Z extends i.InternalError{constructor(e){super(e,Z.name,591)}}class ee extends i.InternalError{constructor(e){super(e,ee.name,592)}}e.HFCAIdentityType=void 0,($=e.HFCAIdentityType||(e.HFCAIdentityType={})).PEER="peer",$.ORDERER="orderer",$.CLIENT="client",$.USER="user",$.ADMIN="admin",e.HFCAIdentityAttributes=void 0,(B=e.HFCAIdentityAttributes||(e.HFCAIdentityAttributes={})).HFREGISTRARROLES="hf.Registrar.Roles",B.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",B.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",B.HFINTERMEDIATECA="hf.IntermediateCA",B.HFREVOKER="hf.Revoker",B.HFAFFILIATIONMGR="hf.AffiliationMgr",B.HFGENCRL="hf.GenCRL";class te extends c.LoggedClass{constructor(e){x.getCryptoSuite(e.hsm?{software:!1,lib:e.hsm.library,slot:e.hsm.slot,label:e.hsm.tokenLabel,pin:e.hsm.pin+""}:void 0),super(),this.caConfig=e}async User(){if(this.user)return this.user;const{caName:e,caCert:t,caKey:r,url:a,hsm:s}=this.caConfig,n=this.log.for(this.User);n.debug(`Creating CA user for ${e} at ${a}`),n.debug("Retrieving CA certificate from "+t);const o=await x.getFirstDirFileNameContent(t);let c;if(s)n.debug(`Using HSM configuration for CA ${e} with library ${s.library}`);else{if(!r)throw new i.InternalError(`Missing caKey configuration for CA ${e}. Provide a key directory or configure HSM support.`);n.debug("Retrieving CA key from "+r),c=await x.getFirstDirFileNameContent(r)}return n.debug("Loading Admin user for ca "+e),this.user=await x.getCAUser("admin",c,o,e,{hsm:s}),this.user}async CA(){if(this.ca)return this.ca;const e=this.log.for(this.CA),{url:t,tls:r,caName:i}=this.caConfig;let{trustedRoots:a,verify:s}=r;const n=a[0];e.debug(`Retrieving CA certificate from ${n}. cwd: ${process.cwd()}`);const c=await x.getFileContent(n);return e.debug(`Creating CA Client for CA ${i} under ${t}`),this.ca=new o(t,{trustedRoots:Buffer.from(c),verify:s},i),this.ca}async Client(){if(this.client)return this.client;const e=await this.CA();return this.client=e._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(e,t=!0){const r=await this.Certificate(),i=await this.User(),a=this.log.for(this.getCertificates);a.debug(`Retrieving certificates${e?" for "+e.id:""} for CA ${this.caConfig.caName}`);const s=(await r.getCertificates(e||{},i)).result;return a.debug(`Found ${s.certs.length} certificates: ${JSON.stringify(s)}`),t?s.certs.map(e=>e.PEM):s}async getIdentities(){const e=await this.Identities(),t=this.log.for(this.getIdentities);t.debug("Retrieving Identities under CA "+this.caConfig.caName);const r=(await e.getAll(await this.User())).result;return t.debug(`Found ${r.identities.length} Identities: ${JSON.stringify(r)}`),r.identities}parseError(e){const r=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(e.message);if(!r)return new U(e);const[,a,s]=r;switch(a){case"74":case"71":return new i.ConflictError(s);case"20":return new t.AuthorizationError(s);default:return new U(s)}}async getAffiliations(){const e=await this.Affiliations(),t=this.log.for(this.getAffiliations);t.debug("Retrieving Affiliations under CA "+this.caConfig.caName);const r=(await e.getAll(await this.User())).result;return t.debug(`Found ${r.a.length} Affiliations: ${JSON.stringify(r)}`),r}async read(e){const t=await this.CA(),r=await this.User();let a;try{a=await t.newIdentityService().getOne(e,r)}catch(t){throw new i.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new i.NotFoundError(`Couldn't find enrollment with id ${e}: ${a.errors.join("\n")}`);return a.result}async register(e,t=!1,r="",i,a,s){let n;const o=this.log.for(this.register);try{const{userName:c,password:l}=e,d=await this.CA(),u=await this.User(),h={enrollmentID:c,enrollmentSecret:l,affiliation:r,userRole:i,attrs:a,maxEnrollments:s};n=await d.register(h,u),o.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${t?"as super user":""}`)}catch(e){throw this.parseError(e)}return n}static identityFromEnrollment(t,r){const{certificate:i,key:a,rootCertificate:s}=t,n=c.Logging.for(te,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${i} in msp ${r}`);const o=k.fabricIdFromCertificate(i),l=k.encode(o);n.debug(`Identity ${o} and encodedId ${l}`);const d=new Date;return new e.Identity({id:l,credentials:{id:l,certificate:i,privateKey:a.toBytes(),rootCertificate:s,createdOn:d,updatedOn:d},mspId:r,createdOn:d,updatedOn:d})}async enroll(e,t){let r;const i=this.log.for(this.enroll);try{const a=await this.CA();i.debug("Enrolling "+e);const s=await a.enroll({enrollmentID:e,enrollmentSecret:t});r=te.identityFromEnrollment(s,this.caConfig.caName),i.info(`Successfully enrolled ${e} under ${this.caConfig.caName} as ${r.id}`)}catch(e){throw this.parseError(e)}return r}async registerAndEnroll(e,t=!1,r="",i,a,s){const n=await this.register(e,t,r,i,a,s),{userName:o}=e;return this.enroll(o,n)}async revoke(e){const t=await this.CA(),r=await this.User(),a=await this.read(e);if(!a)throw new i.NotFoundError("Could not find enrollment with id "+e);let s;try{s=await t.revoke({enrollmentID:a.id,reason:"User Deletation"},r)}catch(t){throw new i.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!s.success)throw new i.InternalError(`Could not revoke enrollment with id ${e}: ${s.errors.join("\n")}`);return s}}class re extends r.Model{constructor(){super(...arguments),this.affiliation=""}build(){const e=this.hasErrors();if(e)throw new i.ValidationError(e.toString());const t={enrollmentID:this.enrollmentID,enrollmentSecret:this.enrollmentSecret,role:this.role,affiliation:this.affiliation};return void 0!==this.maxEnrollments&&(t.maxEnrollments=this.maxEnrollments),this.attrs&&(t.attrs=this.attrs),t}setAffiliation(e){return this.affiliation=e,this}addAttr(e){return this.attrs=this.attrs||[],this.attrs.push(e),this}setAttrs(e){return this.attrs=e,this}setEnrollmentID(e){return this.enrollmentID=e,this}setEnrollmentSecret(e){return this.enrollmentSecret=e,this}setMaxEnrollments(e){return this.maxEnrollments=e,this}setRole(e){return this.role=e,this}}function ie(e){if(e)return"string"==typeof e?e:e.getMSPID()}async function ae(e,t,r,i){const{stub:a}=e,s=(await a.getCreator()).mspid;Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:s})}async function se(e,t,r,i){const{stub:a}=e;i[r]=a.getTxID()}async function ne(e,t,a){let s=t;if("string"!=typeof s)try{const i=r.Model.ownerOf(e)||a.get("stub").getCreator().toString();t&&"function"==typeof t&&(s=await t(e,i,a))}catch(e){throw new i.InternalError("Failed to resolve collection mirror name: "+e)}if(!s||"string"!=typeof s)throw new i.InternalError("No collection found model "+e.constructor.name);return s}async function oe(e,t,i,a){const s=await ne(a,t.resolver,e),n=e;n.put("mirror",!0),n.put("mirrorCollection",s);try{const t=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:s,ignoreValidation:!0,ignoreHandlers:!0})),i=await t.create(a,e);e.logger.info(`Mirror for ${r.Model.tableName(this.class)} created with ${r.Model.pk(a)}: ${i[r.Model.pk(a)]}`)}finally{n.put("mirror",void 0),n.put("mirrorCollection",void 0)}}async function ce(e,t,i,a){const s=await ne(a,t.resolver,e),n=e;n.put("mirror",!0),n.put("mirrorCollection",s);try{const t=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:s,ignoreValidation:!0,ignoreHandlers:!0,applyUpdateValidation:!1,mergeForUpdate:!1}));await t.update(a,e),e.logger.info(`Mirror for ${r.Model.tableName(this.class)} updated: ${a[r.Model.pk(a)]}`)}finally{n.put("mirror",void 0),n.put("mirrorCollection",void 0)}}async function le(e,t,i,a){const s=await ne(a,t.resolver,e),n=e;n.put("mirror",!0),n.put("segregated",s);try{const t=a[r.Model.pk(a)],i=this.override(Object.assign({},this._overrides,{segregated:s,mirror:!0,ignoreValidation:!0,ignoreHandlers:!0}));try{await i.delete(t,e)}catch{}e.logger.info(`Mirror for ${r.Model.tableName(this.class)} deleted: ${t+""}`)}finally{n.put("mirror",void 0),n.put("segregated",void 0)}}async function de(e,r,i,a){const s=ie(e.get("identity"));if(s&&(s===r.mspId||r.condition&&r.condition(s)))throw new t.AuthorizationError(`Organization ${s} is not authorized to modify mirrored data`)}async function ue(e,t,r,i){const a=ie(e.get("identity"));if(!a)return;const s=await ne(i,t.resolver,e),n=e;(a===t.mspId||t.condition&&t.condition(a))&&(e.logger.info(`Mirror read: MSP ${a} matches, routing reads to mirror collection ${s}`),n.put("fullySegregated",!0),n.readFrom(s))}s.__decorate([r.required(),s.__metadata("design:type",String)],re.prototype,"affiliation",void 0),s.__decorate([r.minlength(1),s.__metadata("design:type",Array)],re.prototype,"attrs",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],re.prototype,"enrollmentID",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],re.prototype,"enrollmentSecret",void 0),s.__decorate([r.min(0),s.__metadata("design:type",Number)],re.prototype,"maxEnrollments",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],re.prototype,"role",void 0),e.ERC20Events=void 0,(P=e.ERC20Events||(e.ERC20Events={})).TRANSFER="Transfer",P.APPROVAL="Approval",e.FabricBaseModel=class extends r.Model{constructor(e){super(e)}},s.__decorate([n.description("Stores the original timestamp of creation"),t.column(),t.createdAt(),s.__metadata("design:type",Date)],e.FabricBaseModel.prototype,"createdAt",void 0),s.__decorate([n.description("Stores the timestamp of the last update"),t.column(),t.updatedAt(),s.__metadata("design:type",Date)],e.FabricBaseModel.prototype,"updatedAt",void 0),s.__decorate([n.description("Stores the version of the model"),t.column(),i.version(),s.__metadata("design:type",Number)],e.FabricBaseModel.prototype,"version",void 0),e.FabricBaseModel=s.__decorate([n.uses(M),s.__metadata("design:paramtypes",[Object])],e.FabricBaseModel),e.FabricIdentifiedBaseModel=class extends e.FabricBaseModel{constructor(e){super(e)}},s.__decorate([n.description("Stores the creator"),t.column(),t.createdBy(),s.__metadata("design:type",String)],e.FabricIdentifiedBaseModel.prototype,"createdBy",void 0),s.__decorate([n.description("Stores the user that last updated the model"),t.column(),t.updatedBy(),s.__metadata("design:type",String)],e.FabricIdentifiedBaseModel.prototype,"updatedBy",void 0),e.FabricIdentifiedBaseModel=s.__decorate([n.uses(M),s.__metadata("design:paramtypes",[Object])],e.FabricIdentifiedBaseModel),r.Model.prototype.isShared=function(){return r.Model.isShared(this.constructor)},r.Model.prototype.isPrivate=function(){return r.Model.isPrivate(this.constructor)},r.Model.prototype.segregate=function(){return r.Model.segregate(this)},r.Model.segregate=(t=>{if(!r.Model.isTransient(t))return{model:t};const a=n.Metadata.getAttributes(t.constructor)||[],s=n.Metadata.get(t.constructor,i.DBKeys.TRANSIENT),o=n.Metadata.get(t.constructor,e.FabricModelKeys.PRIVATE),c=n.Metadata.get(t.constructor,e.FabricModelKeys.SHARED),l={model:{},public:{},transient:{},privates:{},shared:{}},d=Object.keys(s||{}),u=Object.keys(o||{}),h=Object.keys(c||{});for(const e of a){const r=t[e],i=d.includes(e),a=!i,s=u.includes(e),n=h.includes(e);(i||s||n)&&(l.transient=l.transient||{},l.transient[e]=r),s&&(l.privates=l.privates||{},l.privates[e]=r),n&&(l.shared=l.shared||{},l.shared[e]=r),a&&(l.public=l.public||{},l.public[e]=r)}return l.model=r.Model.build(l.public,t.constructor.name),l}).bind(r.Model),r.Model.isPrivate=(t=>!!n.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.PRIVATE)).bind(r.Model),r.Model.isShared=(t=>!!n.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.SHARED)).bind(r.Model),r.Model.mirrored=(t=>n.Metadata.get("function"!=typeof t?t.constructor:t,n.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR))).bind(r.Model),r.Model.ownerOf=(t=>{const r=n.Metadata.get(t.constructor,n.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.OWNED_BY));if(r)return t[r]}).bind(r.Model),r.Model.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,n.Metadata.get(t,n.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR)))).bind(r.Model),r.Model.collectionsFor=(t=>{const r=[e.FabricModelKeys.PRIVATE],i=[e.FabricModelKeys.SHARED],a=n.Metadata.key(...r),s=n.Metadata.key(...i),o="function"==typeof t?t:t.constructor,c=n.Metadata.get(o,a),l=n.Metadata.get(o,s);return{privateCols:c?.collections||[],sharedCols:l?.collections||[]}}).bind(r.Model);const he=(e,t)=>{const a=t||("function"!=typeof e?r.Model.ownerOf(e):void 0);if(!a)throw new i.InternalError(`Model ${e.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${c.toPascalCase(a)}PrivateCollection`};function ge(t,a,s){a.length>0&&s.readFrom(a),!s.isFullySegregated&&a.length&&((t=>{const a=n.Metadata.getAttributes(t)||[],s=r.Model.pk(t),o=n.Metadata.get(t,i.DBKeys.TRANSIENT)||{},c=n.Metadata.get(t,n.Metadata.key(e.FabricModelKeys.PRIVATE))||{},l=n.Metadata.get(t,n.Metadata.key(e.FabricModelKeys.SHARED))||{};return a.some(e=>e!==s&&!(e in o)&&!(e in c)&&!(e in l))})(t.constructor)||s.markFullySegregated())}async function pe(e,t,i,a){const s=Array.isArray(t)?t:[t],n=r.Model.ownerOf(a)||ie(e.get("identity"));if(!n)return;const o=[];for(const t of s){const r=t.collections,i="string"==typeof r?r:r(a,n,e);i&&!o.includes(i)&&o.push(i)}ge(a,o,e);const c=r.Model.sequenceName(a,"pk");e.setSequenceSegregation(c,e.isFullySegregated,o)}async function fe(e,a,s,n){const o=Array.isArray(a)?a:[a],c=Array.isArray(s)?s:[s];if(c.length!==o.length)throw new i.InternalError("Segregated data keys and metadata length mismatch");const l=r.Model.ownerOf(n)||ie(e.get("identity"));if(!l)throw new i.ValidationError("There's no assigned organization for model "+n.constructor.name);const d=o[0].collections,u="string"==typeof d?d:d(n,l,e);c.forEach((r,i)=>{const a="string"==typeof o[i].collections?o[i].collections:o[i].collections(n,l,e);if(a!==u)throw new t.UnsupportedError(`Segregated data collection mismatch: ${a} vs ${u}`)});const h=c.map(e=>e+"");e.writeTo(u,h)}async function ye(e,t,a,s){const n=Array.isArray(t)?t:[t];if((Array.isArray(a)?a:[a]).length!==n.length)throw new i.InternalError("Segregated data keys and metadata length mismatch");const o=r.Model.ownerOf(s)||ie(e.get("identity"));if(!o)throw new i.ValidationError("There's no assigned organization for model "+s.constructor.name);const c=n[0].collections,l="string"==typeof c?c:await c(s,o,e);e.readFrom(l)}async function me(e,a,s,n,o){const c=Array.isArray(a)?a:[a],l=Array.isArray(s)?s:[s];if(l.length!==c.length)throw new i.InternalError("Segregated data keys and metadata length mismatch");const d=r.Model.ownerOf(n)||ie(e.get("identity"));if(!d)throw new i.ValidationError("There's no assigned organization for model "+n.constructor.name);const u=c[0].collections,h="string"==typeof u?u:u(n,d,e);l.forEach((r,i)=>{const a="string"==typeof c[i].collections?c[i].collections:c[i].collections(n,d,e);if(a!==h)throw new t.UnsupportedError(`Segregated data collection mismatch: ${a} vs ${h}`)});const g=l.map(e=>e+"");e.writeTo(h,g)}async function we(e,t,a,s){const n=Array.isArray(t)?t:[t];if((Array.isArray(a)?a:[a]).length!==n.length)throw new i.InternalError("Segregated data keys and metadata length mismatch");const o=r.Model.ownerOf(s)||ie(e.get("identity"));if(!o)throw new i.ValidationError("There's no assigned organization for model "+s.constructor.name);const c=n[0].collections,l="string"==typeof c?c:c(s,o,e);e.readFrom(l)}function be(e,t,r){return(r,a)=>{const s=[];if(!a){const i=n.Metadata.getAttributes(r);return i?.forEach(i=>{be(e,t)(r.prototype,i)}),r}{const r="string"==typeof e?e:e.toString(),a=r+":data",o={collections:e},c={priority:35,group:r+":extract"};s.push(n.prop(),i.transient(),(r,a)=>{const s=n.Metadata.key(t,a),o=r.constructor,c=n.Metadata.get(o,s)||{},l=new Set(c.collections||[]);l.add(e),c.collections=[...l],n.Metadata.set(o,s,c);const d=n.Metadata.get(o,t)||{},u=new Set(d.collections||[]);u.add(e),d.collections=[...u],n.Metadata.set(o,t,d);const h={...n.Metadata.get(o,i.DBKeys.TRANSIENT)||{},[a]:{}};n.Metadata.set(o,i.DBKeys.TRANSIENT,h)},i.on(i.DBOperations.ALL,pe,o,c),i.onCreate(fe,{collections:e},{priority:95,group:a}),i.onRead(ye,{collections:e},{priority:95,group:a}),i.onUpdate(me,{collections:e},{priority:95,group:a}),i.onDelete(we,{collections:e},{priority:95,group:a}))}return n.apply(...s)(r,a)}}function Ee(e){return null===e||"object"!=typeof e?e:Array.isArray(e)?e.map(Ee):e.constructor!==Object?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Ee(e[r]),t),{})}class Ce extends r.JSONSerializer{constructor(){super()}preSerialize(e){const t=Object.assign({},e);let i;try{i=n.Metadata.modelName(e.constructor)}catch(e){i=void 0}t[r.ModelKeys.ANCHOR]=i||e.constructor.name;const a=function e(t){const r=this;return"object"!=typeof t?t:Array.isArray(t)?t.map(t=>e.call(r,t)):this.preSerialize.call(this,t)}.bind(this);return r.Model.relations(e).forEach(e=>{t[e]=a(t[e])}),t}deserialize(e){const t=JSON.parse(e),i=t[r.ModelKeys.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return r.Model.build(t,i)}serialize(e){return require("json-stringify-deterministic")(Ee(this.preSerialize(e)))}}function Ae(e){const t=e.split("_");return 2>t.length||t.length>3?{table:void 0,event:e,owner:void 0}:{table:t[0],event:t[1],owner:t[2]}}class ve extends r.JSONSerializer{constructor(){super()}deserialize(e,t){return JSON.parse(e)}serialize(e,t=!0){return require("json-stringify-deterministic")(Ee(this.preSerialize(e,t)))}preSerialize(e,t=!0){const i=Object.assign({},e);let a;try{a=n.Metadata.modelName(e.constructor)}catch(e){a=void 0}function s(e){return"object"!=typeof e?e:Array.isArray(e)?e.map(s):this.preSerialize(e)}return t&&(i[r.ModelKeys.ANCHOR]=a||e.constructor.name),r.Model.relations(e).forEach(e=>{i[e]=s.call(this,i[e])}),i}}class Se extends t.ClientBasedService{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new i.InternalError("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(e,t){const r=t.logger.for(this.getUser),{caName:a,caCert:s,caKey:n,url:o,hsm:c}=e;r.info(`Creating CA user for ${a} at ${o}`),r.verbose("Retrieving CA certificate from "+s);const l=await x.getFirstDirFileNameContent(s);let d;if(c)r.debug(`Using HSM configuration for CA ${a} with library ${c.library}`);else{if(!n)throw new i.InternalError(`Missing caKey configuration for CA ${a}. Provide a key directory or configure HSM support.`);r.debug("Retrieving CA key from "+n),d=await x.getFirstDirFileNameContent(n)}return r.debug("Loading Admin user for ca "+a),this._user=await x.getCAUser("admin",d,l,a,{hsm:c}),this._user}async initialize(...e){const{log:r,ctx:a}=(await this.logCtx(e,t.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize),[s]=e;if(!s)throw new i.InternalError("Missing Fabric CA configuration");const{url:n,tls:c,caName:l}=s;r.info(`Initializing CA Client for CA ${s.caName} at ${s.url}`);const{trustedRoots:d,verify:u}=c,h=d[0];r.debug(`Retrieving CA certificate from ${h}. cwd: ${process.cwd()}`);const g=await x.getFileContent(h);r.debug("CA Certificate: "+g.toString());const p=new o(n,{trustedRoots:Buffer.from(g),verify:u},l),f=await this.getUser(s,a);return r.debug("CA user loaded: "+f.getName()),{config:s,client:p}}async getCertificates(e,r=!0,...a){e instanceof t.Context?(a=[e],r=!0,e=void 0):"boolean"==typeof e?(r=e,e=void 0):"boolean"!=typeof r&&(a=[r,...a],r=!0);const{log:s}=(await this.logCtx(a,i.OperationKeys.READ,!0)).for(this.getCertificates);s.debug(`Retrieving certificates${e?" for "+e.id:""} for CA ${this.config.caName}`);const n=(await this.certificates.getCertificates(e||{},this.user)).result;return s.verbose(`Found ${n.certs.length} certificates`),s.debug(n.certs),r?n.certs.map(e=>e.PEM):n}async getIdentities(e){const t=e.logger.for(this.getIdentities);t.verbose("Retrieving Identities under CA "+this.config.caName);const r=(await this.identities.getAll(this.user)).result;return t.verbose(`Found ${r.identities.length} Identities`),t.debug(r.identities),r.identities}async getAffiliations(e){const t=e.logger.for(this.getAffiliations);t.verbose("Retrieving Affiliations under CA "+this.config.caName);const r=(await this.affiliations.getAll(this.user)).result;return t.verbose(`Found ${r.a.length} Affiliations`),t.debug(JSON.stringify(r)),r}parseError(e){const r=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(e.message);if(!r)return new U(e);const[,a,s]=r;switch(a){case"74":case"71":return new i.ConflictError(s);case"20":return new t.AuthorizationError(s);default:return new U(s)}}async read(e,...t){const{log:r}=(await this.logCtx(t,i.OperationKeys.READ,!0)).for(this.read);let a;r.verbose("Retrieving identity with enrollment ID "+e);try{a=await this.identities.getOne(e,this.user)}catch(t){throw new i.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new i.NotFoundError(`Couldn't find enrollment with id ${e}: ${a.errors.join("\n")}`);return a.result}async register(e,t=!1,r="",i,a,s,...n){const{log:o}=(await this.logCtx(n,"register",!0)).for(this.register);let c;try{const{userName:n,password:l}=e,d={enrollmentID:n,enrollmentSecret:l,affiliation:r,userRole:i,attrs:a,maxEnrollments:s};c=await this.client.register(d,this.user),o.info(`Registration for ${n} created with user type ${i??"Undefined Role"} ${t?"as super user":""}`)}catch(e){throw this.parseError(e)}return c}static identityFromEnrollment(t,r,i){const a=i.logger.for(this.identityFromEnrollment),{certificate:s,key:n,rootCertificate:o}=t;a.verbose(`Generating Identity from certificate ${s} in msp ${r}`);const c=k.fabricIdFromCertificate(s),l=k.encode(c);return a.debug(`Identity ${c} and encodedId ${l}`),new e.Identity({id:l,credentials:{id:l,certificate:s,privateKey:n.toBytes(),rootCertificate:o},mspId:r})}async enroll(e,t,...r){const{log:i,ctx:a}=(await this.logCtx(r,"enroll",!0)).for(this.enroll);let s;try{i.debug("Enrolling "+e);const r=await this.client.enroll({enrollmentID:e,enrollmentSecret:t});s=Se.identityFromEnrollment(r,this.config.caName,a),i.info(`Successfully enrolled ${e} under ${this.config.caName} as ${s.id}`)}catch(e){throw this.parseError(e)}return s}async registerAndEnroll(e,t=!1,r="",i,a,s,...n){const{ctx:o}=(await this.logCtx(n,"register-enroll",!0)).for(this.registerAndEnroll),c=await this.register(e,t,r,i,a,s,o),{userName:l}=e;return this.enroll(l,c,o)}async updateIdentity(e,t,r,...i){const{log:a,ctx:s}=(await this.logCtx(i,"reenroll",!0)).for(this.updateIdentity);try{a.info("Renewing identity for "+e);const n=this.client.newIdentityService(),o=await n.getOne(e,this.user);await n.update(e,r,this.user);const c=d.User.createUser(e,"",this.user.getMspid(),t.certificate,t.privateKey);c.setCryptoSuite(this.user.getCryptoSuite());const l=(o.result.attrs||[]).map(({name:e})=>({name:e,optional:!1})),u=await this.client.reenroll(c,l),h=Se.identityFromEnrollment(u,this.config.caName,s);a.debug("Revoking previous certificates for "+e);const{aki:g,serial:p}=N(t.certificate);return await this.revoke(e,{aki:g,serial:p},i),a.debug("Renew identity successful for "+e),h}catch(e){throw this.parseError(e)}}async revoke(e,t,...r){const{log:a}=(await this.logCtx(r,"revoke",!0)).for(this.revoke);a.verbose("Revoking identity with enrollment ID "+e);const s=await this.read(e);if(!s)throw new i.NotFoundError("Could not find enrollment with id "+e);let n;try{const e={reason:t.serial||t.aki?"Revoke User Certificate":"User Deletion",...t,enrollmentID:s.id};n=await this.client.revoke(e,this.user)}catch(t){throw new i.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!n.success)throw new i.InternalError(`Could not revoke enrollment with id ${e}: ${n.errors.join("\n")}`);return n}}var Oe;e.CA_ROLE=void 0,(Oe=e.CA_ROLE||(e.CA_ROLE={})).ADMIN="admin",Oe.USER="user",Oe.CLIENT="client";const _e=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60,legacy:!1,allowManualEndorsingOrgs:!1,allowGatewayOverride:!1,rebuildWithTransient:!0,encryptTransient:!1}),Ie=new c.MiniLogger("fabric-fs");async function Me(e,t){return e instanceof Uint8Array||e.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?e:await t(e)}async function xe(e,r){return{mspId:e,credentials:await Me(r,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await Ne(e);return await r.readFile(i)})}}async function Ne(e){const{promises:r}=await t.normalizeImport(import("fs")),{join:i}=await t.normalizeImport(import("path"));return i(e,(await r.readdir(e))[0])}async function Te(e){const r=await Me(e,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await Ne(e);return await r.readFile(i)}),i=await Fe(r),a=i[Object.getOwnPropertySymbols(i)[0]];return l.signers.newPrivateKeySigner(a)}async function Fe(e){let r;if(c.isBrowser())r=globalThis.crypto.subtle;else{const e=await t.normalizeImport(import("crypto"));r=e.subtle||e.webcrypto.subtle}if(!r)throw Error("Could not load SubtleCrypto module");const a=e.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),s=(e=>{const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t})(Buffer.from(a,"base64").toString("binary"));try{return await r.importKey("pkcs8",s,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}catch(e){throw new i.InternalError(e)}}function De(e){if(!e)return"\0";const t=Array.from(e);for(let e=t.length-1;e>=0;e-=1){const r=t[e].codePointAt(0);if(void 0!==r&&1114111>r)return t[e]=String.fromCodePoint(r+1),t.slice(0,e+1).join("")}return e+"\0"}class Re extends t.Statement{constructor(e,t){super(e,t)}squash(e){const r=super.squash(e);if(!r)return r;const{method:a,params:s,args:n}=r,{direction:o,limit:c}=s;switch(a){case t.PreparedStatementKeys.FIND:break;case t.PreparedStatementKeys.PAGE:n.push(o,c);break;case t.PreparedStatementKeys.FIND_BY:break;case t.PreparedStatementKeys.LIST_BY:n.push(o);break;case t.PreparedStatementKeys.PAGE_BY:n.push(o,c);break;case t.PreparedStatementKeys.FIND_ONE_BY:break;default:throw new i.InternalError("Unsupported method "+a)}return r}async executePrepared(...e){const r=t.Repository.forModel(this.fromSelector,this.adapter.alias),{method:i,args:a}=this.prepared;return r.statement(i,...a,...e)}async prepare(e){if(e=e||await this.adapter.context(t.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&e.get("forcePrepareSimpleQueries")){const t=this.squash(e);if(t)return this.prepared=t,this}const r=[],i={},a={class:this.fromSelector,args:r,params:i},s=[t.QueryClause.FIND_BY];if(this.whereCondition){const t=this.prepareCondition(this.whereCondition,e);s.push(t.method),t.args&&t.args.length&&r.push(...t.args)}return this.selectSelector&&s.push(t.QueryClause.SELECT,this.selectSelector.join(` ${t.QueryClause.AND.toLowerCase()} `)),this.orderBySelectors?.length&&(s.push(t.QueryClause.ORDER_BY,this.orderBySelectors[0][0]),r.push(this.orderBySelectors[0][1])),a.method=c.toCamelCase(s.join(" ")),a.params=i,this.prepared=a,this}processRecord(e,r,i,s){if(e[a.CouchDBKeys.ID]){const[,...r]=e[a.CouchDBKeys.ID].split(a.CouchDBKeys.SEPARATOR),n=r.join("_");return this.adapter.revert(e,this.fromSelector,t.Sequence.parseValue(i,n),void 0,s)}return e}async raw(e,...t){const{ctx:a}=this.logCtx(t,this.raw),s=e?.aggregateInfo;if(e?.aggregate&&s)return this.executeAggregate(s,a);const o=await this.adapter.raw(e,!0,this.fromSelector,a),c=r.Model.pk(this.fromSelector),l=n.Metadata.get(this.fromSelector,n.Metadata.key(i.DBKeys.ID,c))?.type;return this.selectSelector?o:o.map(e=>this.processRecord(e,c,l,a))}build(){const e=this.log.for(this.build),i=this.buildAggregateQuery();if(i)return i;const s={};s[a.CouchDBKeys.TABLE]={},s[a.CouchDBKeys.TABLE]=r.Model.tableName(this.fromSelector);const n={selector:s};if(this.selectSelector&&(n.fields=this.selectSelector),this.whereCondition){const r=this.parseCondition(t.Condition.and(this.whereCondition,t.Condition.attribute(a.CouchDBKeys.TABLE).eq(n.selector[a.CouchDBKeys.TABLE]))).selector,i=Object.keys(r);if(1===i.length&&-1!==Object.values(a.CouchDBGroupOperator).indexOf(i[0]))switch(i[0]){case a.CouchDBGroupOperator.AND:r[a.CouchDBGroupOperator.AND]=[...Object.values(r[a.CouchDBGroupOperator.AND]).reduce((e,t)=>{const r=Object.keys(t);if(1!==r.length)throw Error("Too many keys in query selector. should be one");const i=r[0];return i===a.CouchDBGroupOperator.AND?e.push(...t[i]):e.push(t),e},[])],n.selector=r;break;case a.CouchDBGroupOperator.OR:{const e={};e[a.CouchDBGroupOperator.AND]=[r,...Object.entries(n.selector).map(([e,t])=>{const r={};return r[e]=t,r})],n.selector=e;break}default:throw Error("This should be impossible")}else Object.entries(r).forEach(([t,r])=>{n.selector[t]&&e.warn(`A ${t} query param is about to be overridden: ${n.selector[t]} by ${r}`),n.selector[t]=r})}if(this.orderBySelectors?.length){n.sort=n.sort||[],n.selector=n.selector||{};for(const[e,t]of this.orderBySelectors){const r=e,i={};i[r]=t,n.sort.push(i),n.selector[r]||(n.selector[r]={},n.selector[r][a.CouchDBOperator.BIGGER]=null)}}return this.limitSelector?n.limit=this.limitSelector:(e.warn("No limit selector defined. Using default couchdb limit of "+a.CouchDBQueryLimit),n.limit=a.CouchDBQueryLimit),this.offsetSelector&&(n.skip=this.offsetSelector),n}parseCondition(e){const{attr1:r,operator:i,comparison:s}=e;if(i===t.Operator.STARTS_WITH){if("string"!=typeof r)throw new t.QueryError("STARTS_WITH requires an attribute name");if("string"!=typeof s)throw new t.QueryError("STARTS_WITH requires a string comparison");const e={start:n=s,end:De(n)},i={};return i[r]={},i[r][a.CouchDBOperator.BIGGER_EQ]=e.start,i[r][a.CouchDBOperator.SMALLER]=e.end,{selector:i}}var n,o;if(i===t.Operator.ENDS_WITH){if("string"!=typeof r)throw new t.QueryError("ENDS_WITH requires an attribute name");if("string"!=typeof s)throw new t.QueryError("ENDS_WITH requires a string comparison");const e={};return e[r]={[a.CouchDBOperator.REGEXP]:(o=s,o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"$")},{selector:e}}if(i===t.Operator.BETWEEN){const e=r;if(!Array.isArray(s)||2!==s.length)throw new t.QueryError("BETWEEN operator requires [min, max] comparison");const[i,n]=s,o={};return o[e]={},o[e][a.translateOperators(t.Operator.BIGGER_EQ)]=i,o[e][a.translateOperators(t.Operator.SMALLER_EQ)]=n,{selector:o}}let c={};if(-1===[t.GroupOperator.AND,t.GroupOperator.OR,t.Operator.NOT].indexOf(i))c[r]={},c[r][a.translateOperators(i)]=s;else if(i===t.Operator.NOT)c=this.parseCondition(r).selector,c[a.translateOperators(t.Operator.NOT)]={},c[a.translateOperators(t.Operator.NOT)][r.attr1]=s;else{const e=this.parseCondition(r).selector,t=this.parseCondition(s).selector;c=((e,t,r)=>{const i={selector:{}};return i.selector[e]=[t,r],i})(a.translateOperators(i),e,t).selector}return{selector:c}}buildAggregateQuery(){if(!this.fromSelector)return;if(this.avgSelector){const e=this.avgSelector+"",r=this.createAggregateDescriptor("sum",e),i=this.createAggregateDescriptor("count",e);if(!r||!i)throw new t.QueryError("Avg operation requires sum and count views for attribute "+e);return this.createAggregateQuery({kind:"avg",attribute:e,sumDescriptor:r.descriptor,countDescriptor:i.descriptor})}if(void 0!==this.countDistinctSelector){const e=null==this.countDistinctSelector?void 0:this.countDistinctSelector+"",t=this.createAggregateDescriptor("distinct",e);if(t)return t.countDistinct=!0,this.createAggregateQuery(t)}const e=!!(void 0!==this.countSelector||void 0!==this.countDistinctSelector||this.minSelector||this.maxSelector||this.sumSelector||this.distinctSelector),i=[["count",this.countSelector??void 0],["max",this.maxSelector],["min",this.minSelector],["sum",this.sumSelector],["distinct",this.distinctSelector]];for(const[e,t]of i){const r=t?t+"":void 0,i=this.createAggregateDescriptor(e,r);if(i)return this.createAggregateQuery(i)}if(e)throw new t.QueryError(`No CouchDB view metadata found for table ${r.Model.tableName(this.fromSelector)} aggregator`)}createAggregateDescriptor(e,t){if(!this.fromSelector)return;const i=a.findViewMetadata(this.fromSelector,e,t);if(!i.length)return;const s=i[0],n=r.Model.tableName(this.fromSelector),o=a.generateViewName(n,s.attribute,e,s),c=s.ddoc||a.generateDesignDocName(n,o),l={reduce:void 0!==s.reduce||!s.returnDocs};return"distinct"!==e&&"groupBy"!==e||(l.group=!0),{kind:e,meta:s,descriptor:{ddoc:c,view:o,options:l}}}createAggregateQuery(e){return{selector:{},aggregate:!0,aggregateInfo:e}}getFabricAdapter(){return this.adapter}async executeAggregate(e,t){if(!this.isViewAggregate(e))return this.handleAverage(e,t);const r=this.getFabricAdapter(),i=e,a=await r.view(i.descriptor.ddoc,i.descriptor.view,i.descriptor.options,t);return this.processViewResponse(e,a)}async handleAverage(e,r){if("avg"!==e.kind)throw new t.QueryError("Average descriptor is not valid");const i=this.getFabricAdapter(),[a,s]=[e.sumDescriptor,e.countDescriptor],[n,o]=await Promise.all([i.view(a.ddoc,a.view,a.options,r),i.view(s.ddoc,s.view,s.options,r)]),c=n.rows?.[0]?.value??0,l=o.rows?.[0]?.value??0;return l?c/l:0}processViewResponse(e,r){if("avg"===e.kind)throw new t.QueryError("Average results should be handled before processing rows");const i=r.rows||[],a=e,s=a.meta;return a.countDistinct?i.length||0:"distinct"===a.kind||"groupBy"===a.kind?i.map(e=>e.key??e.value):s.returnDocs?i.map(e=>e.value??e.doc??e):i.length?i[0].value??i[0].key??null:"count"===a.kind?0:null}isViewAggregate(e){return"avg"!==e.kind}}class $e extends t.Paginator{constructor(e,t,r,i){super(e,t,r,i)}prepare(e){throw new t.UnsupportedError("Raw query access must be implemented by a subclass. only prepared statements are natively available")}page(e=1,...t){return super.page(e,...t)}}var Be;class Pe extends t.Adapter{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new v}static{this.log=c.Logging.for(Pe)}constructor(e,t){super(Object.assign({},_e,e),M,t),this.serializer=Pe.serializer}Statement(e){return new Re(this,e)}Paginator(e,t,r){return new $e(this,e,t,r)}async flags(e,t,r,...i){const a=Object.assign({},this.config,r);return Object.assign(await super.flags(e,t,a,...i))}async context(e,i,a,...s){this.log.for(this.context).silly(`creating new context for ${e} operation on ${a?Array.isArray(a)?a.map(e=>r.Model.tableName(e)):r.Model.tableName(a):"no"} table ${i&&Object.keys(i)?Object.keys(i).length:"no"} with flag overrides`);let n=s.pop();void 0===n||n instanceof t.Context||(s.push(n),n=void 0),i=n?Object.assign({},n.toOverrides(),i):i;const o=await this.flags("string"==typeof e?e:e.name,a,i,...[...s,n].filter(Boolean));if(n){if(!(n instanceof this.Context)){const e=(new this.Context).accumulate({...n.cache,...o,parentContext:n});return n.accumulate({childContexts:[...n.getOrUndefined("childContexts")||[],e]}),e}const t=n.getOrUndefined("operation"),r=n.getOrUndefined("affectedTables");if(!t||t!==e||a&&a!==r){const e=(new this.Context).accumulate({...n.cache,...o,parentContext:n});return n.accumulate({childContexts:[...n.getOrUndefined("childContexts")||[],e]}),e}return n.accumulate(o)}return(new this.Context).accumulate({...o})}decode(e){return Pe.decoder.decode(e)}repository(){return b}createPrefix(e,t,i,...s){const{ctxArgs:n}=this.logCtx(s,this.createPrefix),o=r.Model.tableName(e),c={};return c[a.CouchDBKeys.TABLE]=o,Object.assign(c,i),[e,t,c,...n]}createAllPrefix(e,t,s,...n){const o=r.Model.tableName(e);if(t.length!==s.length)throw new i.InternalError("Ids and models must have the same length");const{ctxArgs:c}=this.logCtx(n,this.createAllPrefix),l=t.map((e,t)=>{const r={};return r[a.CouchDBKeys.TABLE]=o,Object.assign(r,s[t]),r});return[e,t,l,...c]}updateAllPrefix(e,t,s,...n){const o=r.Model.tableName(e);if(t.length!==s.length)throw new i.InternalError("Ids and models must have the same length");const{ctxArgs:c}=this.logCtx(n,this.updateAllPrefix),l=t.map(()=>{const e={};return e[a.CouchDBKeys.TABLE]=o,e});return[e,t,l,...c]}async createAll(e,t,a,...s){if(t.length!==a.length)throw new i.InternalError("Ids and models must have the same length");const n=[...s],o=n.shift(),{log:c,ctx:l}=this.logCtx(n,this.createAll),d=r.Model.tableName(e);c.info(`adding ${t.length} entries to ${d} table`),c.verbose("pks: "+t);const u=o&&Object.keys(o).length>0,h=u?{[d]:o}:{},g=await this.submitTransaction(l,i.BulkCrudOperationKeys.CREATE_ALL,[JSON.stringify(a.map(t=>this.serializer.serialize(t,e.name)))],h,this.getEndorsingOrganizations(l),e.name);if(this.shouldRefreshAfterWrite(l,u,t[0]))return this.readAll(e,t,l);try{return JSON.parse(this.decode(g)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}async readAll(e,t,...a){const{log:s,ctx:n}=this.logCtx(a,this.readAll),o=r.Model.tableName(e);s.info(`reading ${t.length} entries to ${o} table`),s.verbose("pks: "+t);const c=await this.evaluateTransaction(n,i.BulkCrudOperationKeys.READ_ALL,[JSON.stringify(t)],void 0,void 0,e.name);try{return JSON.parse(this.decode(c)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}async updateAll(e,t,a,...s){if(t.length!==a.length)throw new i.InternalError("Ids and models must have the same length");const n=[...s];let o=n.shift();const{log:c,ctx:l}=this.logCtx(n,this.updateAll),d=r.Model.tableName(e);c.info(`updating ${t.length} entries to ${d} table`),c.verbose("pks: "+t),o=o&&(Array.isArray(o)?o:Object.keys(o)).length?{[d]:o}:{};const u=await this.submitTransaction(l,i.BulkCrudOperationKeys.UPDATE_ALL,[JSON.stringify(a.map(t=>this.serializer.serialize(t,e.name)))],o,this.getEndorsingOrganizations(l),e.name),h=o&&Object.keys(o).length>0;if(this.shouldRefreshAfterWrite(l,h,t[0]))return this.readAll(e,t,l);try{return JSON.parse(this.decode(u)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}async deleteAll(e,t,...a){const{log:s,ctx:n}=this.logCtx(a,this.deleteAll),o=r.Model.tableName(e);s.info(`deleting ${t.length} entries to ${o} table`),s.verbose("pks: "+t);const c=await this.submitTransaction(n,i.BulkCrudOperationKeys.DELETE_ALL,[JSON.stringify(t)],void 0,this.getEndorsingOrganizations(n),e.name);try{return JSON.parse(this.decode(c)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}prepare(e,...a){const{log:s,ctx:n}=this.logCtx(a,this.prepare),o=r.Model.segregate(e);e[t.PersistenceKeys.METADATA]&&(s.silly("Passing along persistence metadata for "+e[t.PersistenceKeys.METADATA]),Object.defineProperty(o.model,t.PersistenceKeys.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[t.PersistenceKeys.METADATA]}));const c=r.Model.mirroredAt(e);if(c){const e=c.mspId;if(!e)throw new i.InternalError("No mirror MSP could be found");const t=this.getEndorsingOrganizations(n)||[],r=[...new Set([...t,e])];n.accumulate({endorsingOrgs:r,endorsingOrganizations:r,legacy:!0})}return{record:o.model,model:o.model,id:e[r.Model.pk(e.constructor)],transient:o.transient,privates:o.privates,shared:o.shared}}revert(e,t,r,i,...a){const{log:s,ctx:n}=this.logCtx(a,this.revert);return i&&this.shouldRebuildWithTransient(n,n.getOrUndefined("operation"))&&(s.verbose("re-adding transient properties: "+Object.keys(i).join(", ")),Object.entries(i).filter(([,e])=>void 0!==e).forEach(([t,r])=>{t in e&&void 0!==e[t]&&s.warn(`overwriting existing ${t}. if this is not a default value, this may pose a problem`),e[t]=r})),new t(e)}shouldRebuildWithTransient(e,t){if(!e)return!1;if(e.getOrUndefined("rebuildWithTransient"))return!0;if("function"==typeof e.getFromChildren?e.getFromChildren("rebuildWithTransient"):void 0)return!0;const r=this.resolveOperation(e,t);if(!r)return!1;const i=r.toString().toLowerCase();return i.includes("read")||i.includes("find")||i.includes("query")||i.includes("statement")||i.includes("page")}resolveOperation(e,t){return t||("function"==typeof e.getFromChildren?e.getFromChildren("operation"):void 0)}shouldRefreshAfterWrite(e,t,r){return!!t&&null!=r&&!e.getOrUndefined("mirror")}getEndorsingOrganizations(e){const t=e.getOrUndefined("endorsingOrgs")||e.getOrUndefined("endorsingOrgs");return t&&t.length?t:e.getFromChildren("endorsingOrgs")||e.getFromChildren("endorsingOrgs")}async create(e,t,a,s={},...n){const o=[...n],{log:c,ctx:l}=this.logCtx(o,this.create),d=r.Model.tableName(e);c.verbose(`adding entry to ${d} table`),c.debug("pk: "+t);const u=s&&Object.keys(s).length>0,h=u?{[d]:s}:{},g=await this.submitTransaction(l,i.OperationKeys.CREATE,[this.serializer.serialize(a,e.name)],h,this.getEndorsingOrganizations(l),e.name),p=this.serializer.deserialize(this.decode(g));return this.shouldRefreshAfterWrite(l,u,t)?this.read(e,t,l):p}async healthcheck(e,...t){const{log:i,ctx:a}=this.logCtx(t,this.healthcheck),s=r.Model.tableName(e);i.verbose(`reading entry from ${s} table`);const n=await this.evaluateTransaction(a,"healthcheck",[],void 0,void 0,e.name);return JSON.parse(this.decode(n))}async read(e,t,...a){const{log:s,ctx:n}=this.logCtx(a,this.read),o=r.Model.tableName(e);s.verbose(`reading entry from ${o} table`),s.debug("pk: "+t);const c=await this.evaluateTransaction(n,i.OperationKeys.READ,[t.toString()],void 0,void 0,e.name);return this.serializer.deserialize(this.decode(c))}updatePrefix(e,t,i,...s){const n=r.Model.tableName(e),{ctxArgs:o}=this.logCtx(s,this.updatePrefix),c={};return c[a.CouchDBKeys.TABLE]=n,Object.assign(c,i),[e,t,c,...o]}async update(e,t,a,s={},...n){const o=[...n],{log:c,ctx:l}=this.logCtx(o,this.update);c.info("CLIENT UPDATE class : "+typeof e);const d=r.Model.tableName(e);c.verbose(`updating entry to ${d} table`),c.debug("pk: "+t);const u=s&&Object.keys(s).length>0,h=u?{[d]:s}:{},g=await this.submitTransaction(l,i.OperationKeys.UPDATE,[this.serializer.serialize(a,e.name||e)],h,this.getEndorsingOrganizations(l),e.name),p=this.serializer.deserialize(this.decode(g));return this.shouldRefreshAfterWrite(l,u,t)?this.read(e,t,l):p}async delete(e,t,...a){const{log:s,ctx:n}=this.logCtx(a,this.delete),o=r.Model.tableName(e);s.verbose(`deleting entry from ${o} table`),s.debug("pk: "+t);const c=await this.submitTransaction(n,i.OperationKeys.DELETE,[t.toString()],void 0,this.getEndorsingOrganizations(n),e.name);return this.serializer.deserialize(this.decode(c))}async raw(e,t=!0,a,...s){const{log:n,ctx:o}=this.logCtx(s,this.raw),c=a.name;let l,d;n.info("Performing raw statement on table "+r.Model.tableName(a));try{l=await this.evaluateTransaction(o,"raw",[JSON.stringify(e),t],void 0,void 0,c)}catch(e){throw this.parseError(e)}try{d=JSON.parse(this.decode(l))}catch(e){throw new i.SerializationError("Failed to process result: "+e)}if(Array.isArray(d)){if(!d.length)return d;const e=d[0];return r.Model.isModel(e)?d.map(e=>r.Model.build(e)):d}return u=d,r.Model.isModel(u)?r.Model.build(u):u;var u}async view(e,t,r,...a){const{log:s,ctx:n}=this.logCtx(a,this.view);let o,c;s.info(`Querying view ${e}/${t}`);try{o=await this.evaluateTransaction(n,"view",[e,t,JSON.stringify(r)],void 0,void 0,void 0)}catch(e){throw this.parseError(e)}try{c=JSON.parse(this.decode(o))}catch(e){throw new i.SerializationError("Failed to process view result: "+e)}return c}getClient(){return this._client||(this._client=Pe.getClient(this.config)),this._client}async Gateway(e){return Pe.getGateway(e,this.config,this.client)}getContractName(e){if(e)return e+"Contract"}async Contract(e,t){return Pe.getContract(await this.Gateway(e),this.config,t)}async transaction(e,t,r=!0,i,a={},s,n){const o=this.log.for(this.transaction),c=await this.Gateway(e);try{const c=await this.Contract(e,this.getContractName(n));o.verbose(`${r?"Submit":"Evaluate"}ting transaction ${this.getContractName(n)||this.config.contractName}.${t}`),o.debug("args: "+(i?.map(e=>e.toString()).join("\n")||"none"));const l=r?c.submit:c.evaluate;s=s?.length?s:void 0;const d={arguments:i||[],transientData:Object.entries(a).reduce((e,[t,r])=>(e[t]=JSON.stringify(r),e),{}),endorsingOrganizations:e.getOrUndefined("allowManualEndorsingOrgs")&&s||void 0};return await l.call(c,t,d)}catch(e){throw this.parseError(e)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}shouldUseLegacyGateway(e){return!!e.getOrUndefined("legacy")&&!!e.getOrUndefined("allowGatewayOverride")}prepareLegacyArgs(e){return(e||[]).map(e=>"string"==typeof e?e:JSON.stringify(e))}buildLegacyTransient(e){if(!e)return;const t=Object.entries(e);if(!t.length)return;const r={};for(const[e,i]of t)r[e]=Buffer.from(JSON.stringify(i));return r}buildLegacyPeerConfigs(){return[{peerEndpoint:this.config.peerEndpoint,tlsCert:this.config.tlsCert,peerHostAlias:this.config.peerHostAlias}]}async submitLegacyWithExplicitEndorsers(e,t,r,i,a,s){const n=this.log.for(this.submitLegacyWithExplicitEndorsers),o=await this.Gateway(e);try{const c=Pe.getContract(o,this.config,this.getContractName(s));n.verbose(`Legacy submitting ${this.getContractName(s)||this.config.contractName}.${t}`),n.debug("Explicit peers: "+a.map(e=>e.peerEndpoint));const l=new Set;this.config.mspId&&l.add(this.config.mspId),(this.getEndorsingOrganizations(e)||[]).forEach(e=>l.add(e));const d={arguments:r,transientData:i,endorsingOrganizations:l.size>0?Array.from(l):void 0},u=c.newProposal(t,d),h=await u.endorse(),g=await h.submit(),p=await g.getStatus();if(!p.successful)throw Error(`Legacy endorsement failed for ${h.getTransactionId()}: ${p.code}`);return h.getResult()}catch(e){throw this.parseError(e)}finally{o.close()}}parseError(e){return Pe.parseError(e)}async submitTransaction(e,t,r,i,a,s){if(this.shouldUseLegacyGateway(e)){const a=this.prepareLegacyArgs(r),n=this.buildLegacyTransient(i),o=this.buildLegacyPeerConfigs();return this.submitLegacyWithExplicitEndorsers(e,t,a,n,o,s)}return this.transaction(e,t,!0,r,i,a,s)}async evaluateTransaction(e,t,r,i,a,s){return this.transaction(e,t,!1,r,i,a,s)}async close(){this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static getContract(e,t,r){const i=this.log.for(this.getContract),a=this.getNetwork(e,t.channel);let s;try{i.debug(`Retrieving chaincode ${t.chaincodeName} contract ${r||t.contractName} from network ${t.channel}`),r=r||t.contractName,s=a.getContract(t.chaincodeName,r)}catch(e){throw this.parseError(e)}return s}static getNetwork(e,t){const r=c.Logging.for(this.getNetwork);let i;try{r.debug("Connecting to channel "+t),i=e.getNetwork(t)}catch(e){throw this.parseError(e)}return i}static async getGateway(e,t,r){return await this.getConnection(r||await this.getClient(t),t,e)}static getClient(e){const t=this.log.for(this.getClient);t.debug("generating TLS credentials for msp "+e.mspId);let r=e.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(f.readFileSync(r,"utf8"))}catch(e){throw new i.InternalError(`Failed to read the tls certificate from ${r}: ${e}`)}const a=w.credentials.createSsl(r);return t.debug("generating Gateway Client for url "+e.peerEndpoint),new p.Client(e.peerEndpoint,a,{"grpc.max_receive_message_length":1024*(e.sizeLimit||15)*1024,"grpc.max_send_message_length":1024*(e.sizeLimit||15)*1024})}static async getConnection(e,r,i){const a=c.Logging.for(this.getConnection);a.debug(`Retrieving Peer Identity for ${r.mspId} under ${r.certCertOrDirectoryPath}`);const s=await xe(r.mspId,r.certCertOrDirectoryPath);try{a.debug("preparing transaction signer for "+k.fabricIdFromCertificate(s.credentials.toString()))}catch(e){a.error("Failed to extract Fabric ID from certificate",e)}let n;if(r.hsm)throw new t.UnsupportedError("HSM NOT IMPLEMENTED");n=await Te(r.keyCertOrDirectoryPath);const o={client:e,identity:s,signer:n,evaluateOptions:()=>({deadline:Date.now()+1e3*i.get("evaluateTimeout")}),endorseOptions:()=>({deadline:Date.now()+1e3*i.get("endorseTimeout")}),submitOptions:()=>({deadline:Date.now()+1e3*i.get("submitTimeout")}),commitStatusOptions:()=>({deadline:Date.now()+1e3*i.get("commitTimeout")})};a.debug("Connecting to "+r.mspId);const d=l.connect(o);return r.hsm&&(d.close=new Proxy(d.close,{apply(e,t,r){Reflect.apply(e,t,r)}})),d}Dispatch(){return new Pe._baseDispatch}static parseError(e){let r="string"==typeof e?e:e.message;return e instanceof l.GatewayError&&e.details.length&&10===e.code&&(r=""+e.details[0].message),r.includes("MVCC_READ_CONFLICT")?new W(e):r.includes("DEADLINE_EXCEEDED")?new Z(e):r.includes("ENDORSEMENT_POLICY_FAILURE")?new Q(e):r.includes("PHANTOM_READ_CONFLICT")?new J(e):e instanceof Error&&e.code&&9===e.code?new Y(e):r.includes(i.ValidationError.name)?new i.ValidationError(e):r.includes(i.NotFoundError.name)?new i.NotFoundError(e):r.includes(i.ConflictError.name)?new i.ConflictError(e):r.includes(i.BadRequestError.name)?new i.BadRequestError(e):r.includes(t.QueryError.name)?new t.QueryError(e):r.includes(t.PagingError.name)?new t.PagingError(e):r.includes(t.UnsupportedError.name)?new t.UnsupportedError(e):r.includes(t.MigrationError.name)?new t.MigrationError(e):r.includes(t.ObserverError.name)?new t.ObserverError(e):r.includes(t.AuthorizationError.name)?new t.AuthorizationError(e):r.includes(t.ForbiddenError.name)?new t.ForbiddenError(e):r.includes(t.ConnectionError.name)?new t.ConnectionError(e):r.includes(i.SerializationError.name)?new i.SerializationError(e):new i.InternalError(e)}}s.__decorate([c.debug(),c.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,Object,Object,t.Context]),s.__metadata("design:returntype",Promise)],Pe.prototype,"create",null),s.__decorate([c.debug(),c.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,t.Context]),s.__metadata("design:returntype",Promise)],Pe.prototype,"healthcheck",null),s.__decorate([c.debug(),c.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,t.Context]),s.__metadata("design:returntype",Promise)],Pe.prototype,"read",null),s.__decorate([c.debug(),c.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,Object,Object,t.Context]),s.__metadata("design:returntype",Promise)],Pe.prototype,"update",null),s.__decorate([c.debug(),c.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,t.Context]),s.__metadata("design:returntype",Promise)],Pe.prototype,"delete",null),s.__decorate([c.debug(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,"function"==typeof(Be="undefined"!=typeof D&&D)?Be:Object,Object,t.Context]),s.__metadata("design:returntype",Promise)],Pe.prototype,"raw",null),s.__decorate([c.debug(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[String,String,Object,t.Context]),s.__metadata("design:returntype",Promise)],Pe.prototype,"view",null),Pe.decoration(),t.Adapter.setCurrent(M);class Ke extends t.Dispatch{constructor(e){super(),this.client=e,this.decoder=new TextDecoder("utf8")}async close(){this.listeningStack&&this.listeningStack.close()}parsePayload(e){const t=this.decoder.decode(e);return JSON.parse(t)}observe(e){if(!(e instanceof Pe))throw new t.UnsupportedError("Only FabricClientAdapter can be observed by dispatch");return super.observe(e),()=>this.unObserve(e)}async updateObservers(e,a,s,...n){const{log:o,ctxArgs:c}=t.Adapter.logCtx(this.updateObservers,a,!1,...n);if(this.adapter)try{await this.adapter.refresh(e,a,s,...c)}catch(e){throw new i.InternalError("Failed to refresh dispatch: "+e)}else o.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof e?e:r.Model.tableName(e)}:${a}`)}async handleEvents(e){if(!this.listeningStack)throw new i.InternalError('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new i.InternalError("No adapter found. should be impossible");const t=e||await this.adapter.context(i.OperationKeys.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||r.Model),a=this.log.for(this.handleEvents);a.info(`Listening for incoming events on chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}"...`);try{for await(const e of this.listeningStack){const{table:i,event:s,owner:n}=Ae(e.eventName);if(n&&n!==this.adapter.config?.mspId)continue;const o=this.parsePayload(e.payload);try{const e=(i?r.Model.get(i):r.Model.get(this.models[0].name))??(i||this.models[0]?.name);await this.updateObservers(e,s,o.id,t)}catch(e){a.error(`Failed update observables for table ${i} event ${s} id: ${o.id}: ${e}`)}}}catch(e){a.error(`Failed to read event for chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}": ${e}`),await this.close()}}async initialize(){if(!this.adapter)throw new i.InternalError("No adapter or config observed for dispatch");const e=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},r.Model),{ctx:t}=this.logCtx([e],this.initialize),a=(await Pe.getGateway(t,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new i.InternalError("No adapter observed for dispatch");this.listeningStack=await a.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(t)}}Pe&&(Pe._baseDispatch=Ke);const ke="##VERSION##",ze="##PACKAGE##";n.Metadata.registerLibrary(ze,ke),e.AllowanceError=j,e.BalanceError=L,e.BaseEncoder=K,e.ClientSerializer=v,e.CoreUtils=x,e.CryptoUtils=k,e.DefaultFabricClientFlags=_e,e.DeterministicSerializer=Ce,e.EndorsementError=Y,e.EndorsementPolicyError=Q,e.FabricClientAdapter=Pe,e.FabricClientDispatch=Ke,e.FabricClientRepository=b,e.FabricERC20ClientRepository=S,e.FabricEnrollmentService=te,e.FabricFlavour=M,e.FabricIdentityService=Se,e.ImplicitPrivateCollection=he,e.MissingContextError=H,e.MissingPKCSS11Lib=V,e.ModelCollection=(e,t)=>{const a=t||("function"!=typeof e?r.Model.ownerOf(e):void 0),s="function"==typeof e?e:e.constructor;if(!a)throw new i.InternalError(`Model ${s.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${c.toPascalCase(s.name)}${a?c.toPascalCase(a):""}`},e.MvccReadConflictError=W,e.NamespaceCollection=e=>(t,a)=>{const s=a||("function"!=typeof t?r.Model.ownerOf(t):void 0),n="function"==typeof t?t:t.constructor;if(!s)throw new i.InternalError(`Model ${n.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${e}${s?c.toPascalCase(s):""}`},e.NotInitializedError=q,e.OverflowError=z,e.Owner=function(){return function(e,r,a){const s=a.value;return a.value=async function(...e){const a=e[0],n=a.clientIdentity.getID(),o=await this.tokenRepository.select(),c=await o.execute(a);if(0==c.length)throw new i.NotFoundError("No tokens avaialble");if(c.length>1)throw new i.NotFoundError("To many token available : "+c.length);if(c[0].owner!=n)throw new t.AuthorizationError(`User not authorized to run ${r} on the token`);return await s.apply(this,e)},a}},e.PACKAGE_NAME=ze,e.PhantomReadConflictError=J,e.RegistrationError=U,e.RegistrationRequestBuilder=re,e.SEGREGATED_COLLECTION_EXTRACTION_PRIORITY=35,e.SimpleDeterministicSerializer=ve,e.TransactionBufferSizeError=ee,e.TransactionLimitsError=X,e.TransactionTimeoutError=Z,e.UnauthorizedPrivateDataAccess=G,e.VERSION=ke,e.add=(e,t)=>{const r=e+t;if(e!==r-t||t!==r-e)throw new z(`Addition overflow: ${e} + ${t}`);return r},e.applySegregationFlags=ge,e.contentOfLoadFile=Me,e.createMirrorHandler=oe,e.deleteMirrorHandler=le,e.evalMirrorMetadata=ne,e.extractMspId=ie,e.extractPrivateKey=Fe,e.extractSegregatedCollections=pe,e.generateFabricEventName=(e,t,r)=>{const i=[e,t];return r&&i.push(r),i.join("_")},e.generateModelDesignDocs=(e,t)=>{const r=a.generateViews([e]),i=t||{};return r.forEach(e=>{i[e._id]=e}),r},e.generateModelIndexes=e=>a.generateIndexes([e]),e.getAkiAndSerialFromCert=N,e.getCAUser=async(e,t,r,i)=>{Ie.debug(`Creating a CA ${i} user ${e} with certificate ${r}`);const a=new d.User(e),s=d.User.newCryptoSuite();a.setCryptoSuite(s);const n=s.createKeyFromRaw(t);return await a.setEnrollment(n,r,i),a},e.getFirstDirFileName=Ne,e.getFirstDirFileNameContent=async e=>{const{promises:r}=await t.normalizeImport(import("fs")),{join:i}=await t.normalizeImport(import("path")),a=await r.readdir(e);return(await r.readFile(i(e,a[0]))).toString()},e.getIdentity=xe,e.getSigner=Te,e.mirror=(t,r,a)=>{const s="string"!=typeof r&&!!r,o=s?void 0:r,c=s?r:a;return n.Decoration.for(e.FabricModelKeys.MIRROR).define({decorator:(t,r,a)=>{const s={condition:a,mspId:r,resolver:t};return n.apply(n.metadata(n.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR),s),i.onRead(ue,s,{priority:30}),i.onCreate(de,s,{priority:20}),i.onUpdate(de,s,{priority:20}),i.onDelete(de,s,{priority:20}),i.afterCreate(oe,s,{priority:95}),i.afterUpdate(ce,s,{priority:95}),i.afterDelete(le,s,{priority:95}))},args:[t,o,c]}).apply()},e.mirrorWriteGuard=de,e.ownedBy=()=>n.Decoration.for(e.FabricModelKeys.OWNED_BY).define({decorator:()=>(t,a)=>n.apply(r.required(),i.generated(),i.readonly(),i.onCreate(ae),n.propMetadata(n.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.OWNED_BY),a))(t,a),args:[]}).apply(),e.ownedByOnCreate=ae,e.parseEventName=Ae,e.privateData=(t=he)=>n.Decoration.for(e.FabricModelKeys.PRIVATE).define({decorator:t=>be(t,e.FabricModelKeys.PRIVATE),args:[t]}).apply(),e.readFile=async e=>"string"!=typeof e?e:await(async e=>{const{promises:r}=await t.normalizeImport(import("fs"));return await r.readFile(e)})(e),e.readMirrorHandler=ue,e.readModelFile=_,e.readModelFolders=async(...e)=>{const t=require("fs"),r=[];for(const i of e){const e=t.readdirSync(i,{withFileTypes:!0,recursive:!0}).filter(e=>e.isFile()&&e.name.endsWith("js"));for(const t of e)r.push(..._(t))}return r},e.safeParseInt=e=>{if(!/^\d+$/.test(e))throw new i.ValidationError(r.stringFormat("Failed to parse: {0}","string contains digits"));const t=parseInt(e);if(isNaN(t))throw new i.ValidationError(r.stringFormat("Failed to parse: {0}","string is not a parsable integer"));return t},e.segregatedDataOnCreate=fe,e.segregatedDataOnDelete=we,e.segregatedDataOnRead=ye,e.segregatedDataOnUpdate=me,e.sharedData=t=>n.Decoration.for(e.FabricModelKeys.SHARED).define({decorator:t=>be(t,e.FabricModelKeys.SHARED),args:[t]}).apply(),e.sortKeysOnlyRecursive=Ee,e.sub=(e,t)=>{const r=e-t;if(e!==r+t||t!==e-r)throw new z(`Subtraction overflow: ${e} - ${t}`);return r},e.transactionId=()=>n.Decoration.for(e.FabricModelKeys.TRANSACTION_ID).define({decorator:()=>(t,a)=>n.apply(r.required(),i.readonly(),i.onCreate(se),i.onUpdate(se),n.propMetadata(n.Metadata.key(e.FabricModelKeys.FABRIC,a,e.FabricModelKeys.TRANSACTION_ID),a))(t,a),args:[]}).apply(),e.transactionIdOnCreate=se,e.updateMirrorHandler=ce,e.writeDesignDocs=(e,t=process.cwd(),r)=>{if(!e.length)return;const i=require("fs"),a=require("path");e.forEach(e=>{const s=e._id.replace(/^_design\//,""),n=a.resolve(a.join(t,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}design_docs/${s}.json`));O(n);const o={...e};delete o._rev,i.writeFileSync(n,JSON.stringify(o,void 0,2))})},e.writeIndexes=(e,t=process.cwd(),r)=>{const i=require("fs"),a=require("path");e.forEach(e=>{const s=a.resolve(a.join(t,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}indexes/${e.name}.json`));O(s),i.writeFileSync(s,JSON.stringify(e,void 0,2))})}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/core"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/db-decorators"),require("@decaf-ts/for-couchdb"),require("tslib"),require("@decaf-ts/decoration"),require("fabric-ca-client"),require("@decaf-ts/logging"),require("@hyperledger/fabric-gateway"),require("fabric-common"),require("crypto"),require("@peculiar/x509"),require("@peculiar/webcrypto"),require("@grpc/grpc-js"),require("fs")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/core","@decaf-ts/decorator-validation","@decaf-ts/db-decorators","@decaf-ts/for-couchdb","tslib","@decaf-ts/decoration","fabric-ca-client","@decaf-ts/logging","@hyperledger/fabric-gateway","fabric-common","crypto","@peculiar/x509","@peculiar/webcrypto","@grpc/grpc-js","fs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-fabric"]={},e.decafTsCore,e.decafTsDecoratorValidation,e.decafTsDbDecorators,e.decafTsForCouchdb,e.tslib,e.decafTsDecoration,e.fabricCaClient,e.decafTsLogging,e.hyperledgerFabricGateway,e.fabricCommon,e.crypto,e.peculiarX509,e.peculiarWebcrypto,e.grpcGrpcJs,e.fs);
|
|
2
2
|
//# sourceMappingURL=for-fabric.cjs.map
|