@decaf-ts/for-fabric 0.1.58 → 0.1.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/for-fabric.cjs +1 -1
  2. package/dist/for-fabric.cjs.map +1 -1
  3. package/dist/for-fabric.js +1 -1
  4. package/dist/for-fabric.js.map +1 -1
  5. package/lib/cli-module.cjs +7 -6
  6. package/lib/cli-module.js.map +1 -1
  7. package/lib/client/FabricClientAdapter.cjs +1 -1
  8. package/lib/client/FabricClientAdapter.js.map +1 -1
  9. package/lib/client/FabricClientRepository.cjs +1 -0
  10. package/lib/client/FabricClientRepository.d.ts +1 -0
  11. package/lib/client/FabricClientRepository.js.map +1 -1
  12. package/lib/client/constants.cjs +3 -2
  13. package/lib/client/constants.js.map +1 -1
  14. package/lib/contracts/ContractAdapter.cjs +13 -13
  15. package/lib/contracts/ContractAdapter.d.ts +1 -1
  16. package/lib/contracts/ContractAdapter.js.map +1 -1
  17. package/lib/contracts/FabricContractPaginator.cjs +6 -8
  18. package/lib/contracts/FabricContractPaginator.js.map +1 -1
  19. package/lib/esm/cli-module.js +7 -6
  20. package/lib/esm/cli-module.js.map +1 -1
  21. package/lib/esm/client/FabricClientAdapter.js +1 -1
  22. package/lib/esm/client/FabricClientAdapter.js.map +1 -1
  23. package/lib/esm/client/FabricClientRepository.d.ts +1 -0
  24. package/lib/esm/client/FabricClientRepository.js +1 -0
  25. package/lib/esm/client/FabricClientRepository.js.map +1 -1
  26. package/lib/esm/client/constants.js +3 -2
  27. package/lib/esm/client/constants.js.map +1 -1
  28. package/lib/esm/contracts/ContractAdapter.d.ts +1 -1
  29. package/lib/esm/contracts/ContractAdapter.js +13 -13
  30. package/lib/esm/contracts/ContractAdapter.js.map +1 -1
  31. package/lib/esm/contracts/FabricContractPaginator.js +6 -8
  32. package/lib/esm/contracts/FabricContractPaginator.js.map +1 -1
  33. package/lib/esm/index.d.ts +2 -1
  34. package/lib/esm/index.js +3 -3
  35. package/lib/esm/index.js.map +1 -1
  36. package/lib/esm/version.d.ts +1 -1
  37. package/lib/esm/version.js +1 -1
  38. package/lib/index.cjs +3 -3
  39. package/lib/index.d.ts +2 -1
  40. package/lib/index.js.map +1 -1
  41. package/lib/version.cjs +1 -1
  42. package/lib/version.d.ts +1 -1
  43. package/package.json +2 -2
@@ -1,2 +1,2 @@
1
- var e,t;e=this,t=function(e,t,r,a,n,i,o,s,c){"use strict";var l,d;(e=>{e.PRIVATE="private",e.SHARED="shared",e.FABRIC="fabric.",e.OWNEDBY="owned-by",e.TRANSACTION_ID="transaction-id"})(l||(l={})),(e=>{e.X509="X.509"})(d||(d={}));const u="hlf-fabric";t.Model.prototype.isShared=function(){return t.Model.isShared(this.constructor)},t.Model.prototype.isPrivate=function(){return t.Model.isPrivate(this.constructor)},t.Model.prototype.segregate=function(){return t.Model.segregate(this)},t.Model.segregate=(e=>{if(!t.Model.isTransient(e))return{model:e};const n=r.Metadata.validatableProperties(e.constructor),i=r.Metadata.get(e.constructor,a.DBKeys.TRANSIENT),o=r.Metadata.get(e.constructor,l.PRIVATE),s=r.Metadata.get(e.constructor,l.PRIVATE),c={model:{},transient:{},private:{},shared:{}},d=Object.keys(i),u=Object.keys(o),p=Object.keys(s);for(const t of n){const r=d.includes(t),a=u.includes(t),n=p.includes(t);r?(c.transient=c.transient||{},c.transient[t]=e[t],a&&(c.private=c.private||{},c.private[t]=e[t]),n&&(c.shared=c.shared||{},c.shared[t]=e[t])):(c.model=c.model||{},c.model[t]=e[t])}return c.model=t.Model.build(c.model,e.constructor.name),c}).bind(t.Model),t.Model.tableName=e=>{const a=e instanceof t.Model?e.constructor:e;return r.Metadata.get(a,n.PersistenceKeys.TABLE)||(e instanceof t.Model?e.constructor.name:e.name)},t.Model.isPrivate=(e=>!!r.Metadata.get("function"!=typeof e?e.constructor:e,l.PRIVATE)).bind(t.Model),r.Metadata.isShared=(e=>!!r.Metadata.get("function"!=typeof e?e.constructor:e,l.SHARED)).bind(r.Metadata);class p extends n.Context{constructor(){super()}get stub(){return this.get("stub")}get timestamp(){return this.stub.getDateTimestamp()}get identity(){return this.get("identity")}toString(){return"fabric ctx"+(this.stub?" with stub":"without stub")}}class g extends n.ObserverHandler{constructor(e=[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL]){super(),this.supportedEvents=e}async updateObservers(e,t,r,...a){const{log:i,ctx:o}=n.Adapter.logCtx(this.updateObservers,t,!1,...a),{stub:s}=o,[c,l]=a,d="string"==typeof e?e:e.name;if(-1!==this.supportedEvents.indexOf(t)){i.debug(`Emitting ${t} event`);const e=((e,t,r)=>{const a=[e,t];return r&&a.push(r),a.join("_")})(d,t,c);s.setEvent(e,Buffer.from(JSON.stringify({id:r})))}else s.setEvent(t,Buffer.from(JSON.stringify(l)))}}class h extends n.Repository{constructor(e,t,r){super(e,t),this.trackedEvents=r,this._overrides=Object.assign({},super._overrides,{ignoreValidation:!1,ignoreHandlers:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1})}async paginateBy(e,r,a={offset:1,limit:10},...i){let{offset:o,bookmark:s,limit:c}=a;if(!o&&!s)throw new n.QueryError("PaginateBy needs a page or a bookmark");const{log:l,ctxArgs:d}=(await this.logCtx(i,n.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);let u;if(l.verbose(`paginating ${t.Model.tableName(this.class)} with page size ${c}`),s)u=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(this.attr(t.Model.pk(this.class)).gt(s)).orderBy([e,r]).paginate(c,...d),o=1;else{if(!o)throw new n.QueryError("PaginateBy needs a page or a bookmark");u=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([e,r]).paginate(c,...d)}const p=await u.page(o,s,...d);return u.serialize(p)}async statement(e,...t){const{log:r,ctx:i,ctxArgs:o}=(await this.logCtx(t,n.PersistenceKeys.STATEMENT,!0)).for(this.statement);if(!n.Repository.statements(this,e))throw new n.QueryError("Invalid prepared statement requested "+e);let s;i.logger&&i.logger.info(`Repo statement: ${e} + ${t}`),r.verbose(`Executing prepared statement ${e} with args ${o}`);try{s=await this[e](...o)}catch(t){if(t instanceof a.BaseError)throw t;throw new a.InternalError(`Failed to execute prepared statement ${e} with args ${o}: ${t}`)}return s}ObserverHandler(){return new g}async updateObservers(e,t,r,...a){if(!this.trackedEvents||-1!==this.trackedEvents.indexOf(t))return await super.updateObservers(e,t,r,...a)}}class y extends i.CouchDBStatement{constructor(e){super(e)}async executionPrefix(e,...t){const r=t.filter(Boolean);if(t.length!==r.length)throw new a.InternalError(`Received an undefined in the paginator for ${e}: ${t}`);return super.executionPrefix(e,...t)}async raw(e,...n){const{ctx:i}=this.logCtx(n,this.raw),o=await this.adapter.raw(e,!0,i),s=t.Model.pk(this.fromSelector),c=r.Metadata.get(this.fromSelector,r.Metadata.key(a.DBKeys.ID,s))?.type;return this.selectSelector?o:o.map(e=>this.processRecord(e,s,c,i))}build(){const e={};e[i.CouchDBKeys.TABLE]={},e[i.CouchDBKeys.TABLE]=t.Model.tableName(this.fromSelector);const r={selector:e};if(this.selectSelector&&(r.fields=this.selectSelector),this.whereCondition){const e=this.parseCondition(n.Condition.and(this.whereCondition,n.Condition.attribute(i.CouchDBKeys.TABLE).eq(r.selector[i.CouchDBKeys.TABLE]))).selector,t=Object.keys(e);if(1===t.length&&-1!==Object.values(i.CouchDBGroupOperator).indexOf(t[0]))switch(t[0]){case i.CouchDBGroupOperator.AND:e[i.CouchDBGroupOperator.AND]=[...Object.values(e[i.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 a=r[0];return a===i.CouchDBGroupOperator.AND?e.push(...t[a]):e.push(t),e},[])],r.selector=e;break;case i.CouchDBGroupOperator.OR:{const t={};t[i.CouchDBGroupOperator.AND]=[e,...Object.entries(r.selector).map(([e,t])=>{const r={};return r[e]=t,r})],r.selector=t;break}default:throw Error("This should be impossible")}else Object.entries(e).forEach(([e,t])=>{r.selector[e],r.selector[e]=t})}if(this.orderBySelector){r.sort=r.sort||[],r.selector=r.selector||{};const[e,t]=this.orderBySelector,a={};a[e]=t,r.sort.push(a),r.selector[e]||(r.selector[e]={},r.selector[e][i.CouchDBOperator.BIGGER]=null)}return this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),r}}class m extends n.Sequence{constructor(e,t){super(e,t)}async current(...e){const{ctx:t,log:r}=(await this.logCtx(e,a.OperationKeys.READ,!0)).for(this.current),{name:n,startWith:i}=this.options;try{const e=await this.repo.read(n,t);return this.parse(e.current)}catch(e){if(e instanceof a.NotFoundError){let e;try{r.debug(`Trying to resolve current sequence ${n} value from context`),e=t.get(n),r.debug(`Retrieved cached current value for sequence ${n}: ${e}`)}catch(t){r.info(`No cached value for sequence ${n} in context`),e=i}try{return this.parse(e)}catch(e){throw new a.InternalError(`Failed to parse initial value for sequence ${i}: ${e}`)}}throw new a.InternalError(`Failed to retrieve current value for sequence ${n}: ${e}`)}}async increment(e,t){const r=t.logger.for(this.increment),{type:i,incrementBy:o,name:s}=this.options;if(!s)throw new a.InternalError("Sequence name is required");return r.info("Obtaining sequence lock for sequence "+s),m.lock.execute(async()=>{const c=e||o;if(c%o!==0)throw new a.InternalError("Value to increment does not consider the incrementBy setting: "+o);const l="function"==typeof i&&i?.name?i.name:i,d=await this.current(t);async function u(e){return e instanceof Promise&&(e=await e),r.for(u).info(`Storing new ${s} seq value in cache: ${e.current}`),t.cache.put(s,e.current),e}const p=async e=>{try{return await u(this.repo.update(new n.SequenceModel({id:s,current:e}),t))}catch(i){if(i instanceof a.NotFoundError)return r.debug(`Sequence create ${s} current=${d} next=${e}`),u(this.repo.create(new n.SequenceModel({id:s,current:e}),t));throw i}};if("uuid"===l)for(;;){const e=n.UUID.instance.generate(d);try{const t=await p(e);return r.debug(`Sequence uuid increment ${s} current=${d} next=${e}`),t.current}catch(e){if(e instanceof a.ConflictError)continue;throw e}}const g=(e=>{switch(l){case Number.name:return this.parse(e)+c;case BigInt.name:return this.parse(e)+BigInt(c);case String.name:return this.parse(e);case"serial":return n.Serial.instance.generate(e);default:throw new a.InternalError("Should never happen")}})(d),h=await p(g);return r.debug(`Sequence.increment ${s} current=${d} next=${g}`),h.current},s)}}class f extends t.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,a=!0){const n=Object.assign({},e);let i;try{i=r.Metadata.modelName(e.constructor)}catch(e){i=void 0}function o(e){return"object"!=typeof e?e:Array.isArray(e)?e.map(o):this.preSerialize(e)}return a&&(n[t.ModelKeys.ANCHOR]=i||e.constructor.name),t.Model.relations(e).forEach(e=>{n[e]=o.call(this,n[e])}),n}}class _ extends i.CouchDBPaginator{constructor(e,t,r,a){super(e,t,r,a)}prepare(e){const t=Object.assign({},e);return t.limit&&(this.limit=t.limit),t.limit=this.size,t}async page(e=1,i,...o){const{ctxArgs:s,ctx:c,log:l}=this.adapter.logCtx([i,...o],this.page);if(this.isPreparedStatement())return await this.pagePrepared(e,...s);const d=Object.assign({},this.statement);if(this._recordCount&&this._totalPages)e=this.validatePage(e),d.skip=(e-1)*this.size;else{this._totalPages=this._recordCount=0;const t=await this.adapter.raw({...d,limit:Number.MAX_VALUE},!0,...s)||[];if(this._recordCount=t.length,this._recordCount>0){const t=d?.limit||this.size;return this._totalPages=Math.ceil(this._recordCount/t),await this.page(e,...s)}}if(1!==e){if(!this._bookmark)throw new n.PagingError("No bookmark. Did you start in the first page?");d.bookmark=this._bookmark}const u=await this.adapter.raw(d,!0,...s),{docs:p,bookmark:g,warning:h}=u;if(h&&l.warn(h),!this.clazz)throw new n.PagingError("No statement target defined");const y=t.Model.pk(this.clazz),m=r.Metadata.get(this.clazz,r.Metadata.key(a.DBKeys.ID,y))?.type,f=d.fields&&d.fields.length?u:u.map(e=>this.adapter.revert(e,this.clazz,n.Sequence.parseValue(m,e[y]),void 0,c));return this._bookmark=g,this._currentPage=e,f}}class w extends a.InternalError{constructor(e){super(e,w.name)}}class b extends a.InternalError{constructor(e){super(e,b.name)}}class x extends a.InternalError{constructor(e){super(e,x.name)}}class C extends a.InternalError{constructor(e){super(e,C.name,500)}}class S extends a.BaseError{constructor(e){super(S.name,e,409)}}async function v(e,t,r,a){try{const t=e.get("identity");a[r]=t.getID()}catch(e){throw new n.UnsupportedError("No User found in context. Please provide a user in the context")}}class E extends i.CouchDBAdapter{getClient(){throw new n.UnsupportedError("Client is not supported in Fabric contracts")}static{this.textDecoder=new TextDecoder("utf8")}static{this.serializer=new f}get Context(){return p}repository(){return h}Paginator(e,t,r){return new _(this,e,t,r)}async Sequence(e){return new m(e,this)}constructor(e,t){super(e,u,t)}for(e,...t){return super.for(e,...t)}async create(e,r,a,...n){const{ctx:i,log:o}=this.logCtx(n,this.create);o.info("in ADAPTER create with args "+n);const s=t.Model.tableName(e);try{o.info(`adding entry to ${s} table with pk ${r}`);const e=i.stub.createCompositeKey(s,[r+""]);a=await this.putState(e,a,i)}catch(e){throw this.parseError(e)}return a}async read(e,r,...a){const{ctx:n,log:i}=this.logCtx(a,this.read);i.info("in ADAPTER read with args "+a);const o=t.Model.tableName(e);let s;try{const e=n.stub.createCompositeKey(o,[r+""]);s=await this.readState(e,n)}catch(e){throw this.parseError(e)}return s}async update(e,r,a,...n){const{ctx:i,log:o}=this.logCtx(n,this.update),s=t.Model.tableName(e);try{o.verbose(`updating entry to ${s} table with pk ${r}`);const e=i.stub.createCompositeKey(s,[r+""]);a=await this.putState(e,a,i)}catch(e){throw this.parseError(e)}return a}async delete(e,r,...a){const{ctx:n,log:i,ctxArgs:o}=this.logCtx(a,this.delete),s=t.Model.tableName(e);let c;try{const t=n.stub.createCompositeKey(s,[r+""]);c=await this.read(e,r,...o),i.verbose(`deleting entry with pk ${r} from ${s} table`),await this.deleteState(t,n)}catch(e){throw this.parseError(e)}return c}async deleteState(e,t){const{ctx:r}=this.logCtx([t],this.deleteState);await r.stub.deleteState(e)}forPrivate(e){const t=[this.putState,this.readState,this.deleteState,this.queryResult,this.queryResultPaginated].map(e=>e.name);return new Proxy(this,{get:(r,n,i)=>t.includes(n)?new Proxy(r[n],{async apply(t,r,i){switch(n){case"putState":{const[t,r,a]=i;return await t.putPrivateData(e,r.toString(),a),a}case"deleteState":{const[t,r]=i;return t.deletePrivateData(e,r)}case"readState":{const[t,r]=i;return t.getPrivateData(e,r)}case"queryResult":{const[t,r]=i;return t.getPrivateDataQueryResult(e,r)}case"queryResultPaginated":{const[t,r,a,n]=i,o=await t.getPrivateDataQueryResult(e,r),s=[];let c=0,l=!n,d=null;for(;;){const e=await o.next();if(e.value&&e.value.value.toString()){const t=e.value.key,r=e.value.value.toString("utf8");if(!l){t===n?.toString()&&(l=!0);continue}if(s.push({Key:t,Record:JSON.parse(r)}),d=t,c++,c>=a)return await o.close(),{iterator:s,metadata:{fetchedRecordsCount:s.length,bookmark:d}}}if(e.done)return await o.close(),{iterator:s,metadata:{fetchedRecordsCount:s.length,bookmark:""}}}}default:throw new a.InternalError("Unsupported method override "+n)}}}):Reflect.get(r,n,i)})}async putState(e,t,r){let n;const{log:i}=this.logCtx([r],this.putState);try{n=Buffer.from(E.serializer.serialize(t,!1))}catch(t){throw new a.SerializationError(`Failed to serialize record with id ${e}: ${t}`)}const o=r.get("segregated");return o?await r.stub.putPrivateData(o,e.toString(),n):await r.stub.putState(e.toString(),n),i.silly(`state stored${o?` in ${o} collection`:""} under id ${e}`),t}async readState(e,t){let r;const{log:n}=this.logCtx([t],this.readState);let i;const o=t.get("segregated");if(i=o?(await t.stub.getPrivateData(o,e.toString())).toString():(await t.stub.getState(e.toString())).toString(),!i)throw new a.NotFoundError(`Record with id ${e}${o?` in ${o} collection`:""} not found`);n.silly(`state retrieved from${o?` ${o} collection`:""} under id ${e}`);try{r=E.serializer.deserialize(i.toString())}catch(e){throw new a.SerializationError("Failed to parse record: "+e)}return r}async queryResult(e,t,...r){const{ctx:a}=this.logCtx(r,this.queryResult);let n;const i=a.get("segregated");return n=i?await a.stub.getPrivateDataQueryResult(i,JSON.stringify(t)):await e.getQueryResult(JSON.stringify(t)),n}async queryResultPaginated(e,t,r=250,a,...n){const{ctx:i}=this.logCtx(n,this.readState);let o;const s=i.get("segregated");return s?(t.selector={...t.selector,_id:a?{$gt:a.toString()}:{$gte:""}},o={iterator:await e.getPrivateDataQueryResult(s,JSON.stringify(t)),metadata:{fetchedRecordsCount:r,bookmark:""}}):o=await e.getQueryResultWithPagination(JSON.stringify(t),r,a?.toString()),o}mergeModels(e){const t=e=>Object.entries(e).reduce((e,[t,r])=>(void 0!==r&&(e[t]=r),e),{});let r=e.pop();for(const a of e)r=Object.assign({},t(r),t(a));return r}decode(e){return E.textDecoder.decode(e)}async flags(e,t,r){let a=Object.assign({segregated:!1},r);return r instanceof p||(r.stub?Object.assign(a,{stub:r.stub,identity:r.clientIdentity,cert:r.clientIdentity.getIDBytes().toString(),roles:r.clientIdentity.getAttributeValue("roles"),logger:s.Logging.for(e,{logLevel:!1,timestamp:!1,correlationId:r.stub.getTxID()},r),correlationId:r.stub.getTxID()}):a=Object.assign(a,r||{})),await super.flags(e,t,a)}index(e){return Promise.resolve(void 0)}async resultIterator(e,t,r=!1){const a=[];let n=await t.next();for(;!n.done;){if(n.value&&n.value.value.toString()){let t={};if(e.debug(n.value.value.toString("utf8")),r){t.TxId=n.value.txId,t.Timestamp=n.value.timestamp;try{t.Value=JSON.parse(n.value.value.toString("utf8"))}catch(r){e.error(r),t.Value=n.value.value.toString("utf8")}}else try{t=JSON.parse(n.value.value.toString("utf8"))}catch(r){e.error(r),t=n.value.value.toString("utf8")}a.push(t)}n=await t.next()}return e.debug(`Closing iterator after ${a.length} results`),t.close(),a}async raw(e,t=!0,...r){const{log:a,ctx:n}=this.logCtx(r,this.raw),{skip:i,limit:o}=e;let s;o||i?(delete e.limit,delete e.skip,a.debug(`Retrieving paginated iterator: limit: ${o}/ skip: ${i}`),s=(await this.queryResultPaginated(n.stub,e,o||Number.MAX_VALUE,i?.toString(),n)).iterator):(a.debug("Retrieving iterator"),s=await this.queryResult(n.stub,e,n)),a.debug("Iterator acquired");const c=await this.resultIterator(a,s);return a.debug(`returning ${Array.isArray(c)?c.length:1} results`),c}Statement(){return new y(this)}async createAll(e,r,n,...i){if(r.length!==n.length)throw new a.InternalError("Ids and models must have the same length");const{log:o,ctxArgs:s}=this.logCtx(i,this.createAll),c=t.Model.tableName(e);return o.debug(`Creating ${r.length} entries ${c} table`),Promise.all(r.map((t,r)=>this.create(e,t,n[r],...s)))}async updateAll(e,r,n,...i){if(r.length!==n.length)throw new a.InternalError("Ids and models must have the same length");const{log:o,ctxArgs:s}=this.logCtx(i,this.updateAll),c=t.Model.tableName(e);return o.debug(`Updating ${r.length} entries ${c} table`),Promise.all(r.map((t,r)=>this.update(e,t,n[r],...s)))}prepare(e,...r){const{log:n}=this.logCtx(r,this.prepare),i=t.Model.tableName(e.constructor),o=t.Model.pk(e.constructor),s=t.Model.segregate(e),c=Object.entries(s.model).reduce((r,[n,i])=>{if(void 0===i)return r;const o=t.Model.columnName(e,n);if(this.isReserved(o))throw new a.InternalError(`Property name ${o} is reserved`);return r[o]=i,r},{});return n.silly(`Preparing record for ${i} table with pk ${e[o]}`),{record:c,id:e[o],transient:s.transient}}revert(e,r,n,i,...o){const{log:s}=this.logCtx(o,this.revert),c={};c[t.Model.pk(r)]=n;const l="string"==typeof r?t.Model.build(c,r):new r(c);s.silly(`Rebuilding model ${l.constructor.name} id ${n}`);const d=Object.keys(l).reduce((r,a)=>(r[a]=e[t.Model.columnName(r,a)],r),l);return i&&(s.debug("re-adding transient properties: "+Object.keys(i).join(", ")),Object.entries(i).forEach(([e,t])=>{if(e in d&&void 0!==d[e])throw new a.InternalError(`Transient property ${e} already exists on model ${l.constructor.name}. should be impossible`);d[e]=t})),d}createPrefix(e,r,a,...n){const{ctxArgs:o}=this.logCtx(n,this.createPrefix),s={};return s[i.CouchDBKeys.TABLE]=t.Model.tableName(e),Object.assign(s,a),[e,r,s,...o]}updatePrefix(e,r,a,...n){const{ctxArgs:o}=this.logCtx(n,this.updatePrefix),s={};return s[i.CouchDBKeys.TABLE]=t.Model.tableName(e),Object.assign(s,a),[e,r,s,...o]}createAllPrefix(e,r,n,...o){if(r.length!==n.length)throw new a.InternalError("Ids and models must have the same length");const s=o.pop(),c=r.map((r,a)=>{const o={};return o[i.CouchDBKeys.TABLE]=t.Model.tableName(e),Object.assign(o,n[a]),o});return[e,r,c,s]}updateAllPrefix(e,r,n,...o){if(r.length!==n.length)throw new a.InternalError("Ids and models must have the same length");const s=o.pop(),c=r.map((r,a)=>{const o={};return o[i.CouchDBKeys.TABLE]=t.Model.tableName(e),Object.assign(o,n[a]),o});return[e,r,c,s]}parseError(e,t){return E.parseError(t||e)}logCtx(e,t,r=!1,n){return r?super.logCtx.call(this,e,t,r,n).then(e=>{if(!(e.ctx instanceof p))throw new a.InternalError("Invalid context binding");if(!e.ctx.stub)throw new a.InternalError("Missing Stub");if(!e.ctx.identity)throw new a.InternalError("Missing Identity");return Object.assign(e,{stub:e.ctx.stub,identity:e.ctx.identity})}):super.logCtx(e,t,r,n)}static parseError(e){const t="string"==typeof e?e:e.message;return t.includes(a.NotFoundError.name)?new a.NotFoundError(e):t.includes(a.ConflictError.name)?new a.ConflictError(e):t.includes(a.BadRequestError.name)?new a.BadRequestError(e):t.includes(n.QueryError.name)?new n.QueryError(e):t.includes(n.PagingError.name)?new n.PagingError(e):t.includes(n.UnsupportedError.name)?new n.UnsupportedError(e):t.includes(n.MigrationError.name)?new n.MigrationError(e):t.includes(n.ObserverError.name)?new n.ObserverError(e):t.includes(n.AuthorizationError.name)?new n.AuthorizationError(e):t.includes(n.ForbiddenError.name)?new n.ForbiddenError(e):t.includes(n.ConnectionError.name)?new n.ConnectionError(e):t.includes(a.SerializationError.name)?new a.SerializationError(e):t.includes("no ledger context")?new C("No context found. this can be caused by debugging: "+t):new a.InternalError(e)}static decoration(){super.decoration(),r.Decoration.flavouredAs(u).for(n.PersistenceKeys.CREATED_BY).define(a.onCreate(v),r.propMetadata(n.PersistenceKeys.CREATED_BY,{})).apply(),r.Decoration.flavouredAs(u).for(n.PersistenceKeys.UPDATED_BY).define(a.onCreateUpdate(v),r.propMetadata(n.PersistenceKeys.UPDATED_BY,{})).apply(),r.Decoration.flavouredAs(u).for(n.PersistenceKeys.COLUMN).extend(o.Property()).apply(),r.Decoration.flavouredAs(u).for(t.ValidationKeys.DATE).extend(()=>(e,t)=>{o.Property(t,"string:date")(e,t)}),r.Decoration.flavouredAs(u).for(n.PersistenceKeys.TABLE).extend(e=>{const t=[];let a="function"==typeof e?r.Metadata.constr(e):r.Metadata.constr(e.constructor);for(;a&&a!==Object&&a.prototype;)t.push(a),a=Object.getPrototypeOf(a);for(;t.length>0;){const e=t.pop();o.Object()(e)}return o.Object()(e)}).apply()}}E.decoration(),n.Adapter.setCurrent(u);class A extends t.JSONSerializer{constructor(){super()}preSerialize(e){const a=Object.assign({},e);let n;try{n=r.Metadata.modelName(e.constructor)}catch(e){n=void 0}a[t.ModelKeys.ANCHOR]=n||e.constructor.name;const i=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 t.Model.relations(e).forEach(e=>{a[e]=i(a[e])}),a}deserialize(e){const r=JSON.parse(e),a=r[t.ModelKeys.ANCHOR];if(!a)throw Error("Could not find class reference in serialized model");return t.Model.build(r,a)}serialize(e){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(e)))}}var O;(e=>{e.TRANSFER="Transfer",e.APPROVAL="Approval"})(O||(O={}));let k=class extends t.Model{constructor(e){super(e)}};c.__decorate([r.description("Stores the original timestamp of creation"),n.column(),n.createdAt(),c.__metadata("design:type",Date)],k.prototype,"createdAt",void 0),c.__decorate([r.description("Stores the timestamp of the last update"),n.column(),n.updatedAt(),c.__metadata("design:type",Date)],k.prototype,"updatedAt",void 0),c.__decorate([r.description("Stores the version of the model"),n.column(),a.version(),c.__metadata("design:type",Number)],k.prototype,"version",void 0),k=c.__decorate([r.uses(u),c.__metadata("design:paramtypes",[Object])],k);let P=class extends k{constructor(e){super(e)}};c.__decorate([r.description("Stores the creator"),n.column(),n.createdBy(),c.__metadata("design:type",String)],P.prototype,"createdBy",void 0),c.__decorate([r.description("Stores the user that last updated the model"),n.column(),n.updatedBy(),c.__metadata("design:type",String)],P.prototype,"updatedBy",void 0),P=c.__decorate([r.uses(u),c.__metadata("design:paramtypes",[Object])],P);let T=class extends n.BaseModel{constructor(e){super(e)}};c.__decorate([r.description("Unique identifier of the credentials record"),n.column(),n.pk(),c.__metadata("design:type",String)],T.prototype,"id",void 0),c.__decorate([r.description("PEM-encoded X.509 certificate for the identity"),n.column(),t.required(),c.__metadata("design:type",String)],T.prototype,"certificate",void 0),c.__decorate([r.description("PEM-encoded root or intermediate certificate"),n.column(),t.required(),c.__metadata("design:type",String)],T.prototype,"rootCertificate",void 0),c.__decorate([r.description("PEM-encoded private key"),n.column(),t.required(),c.__metadata("design:type",String)],T.prototype,"privateKey",void 0),T=c.__decorate([t.model(),c.__metadata("design:paramtypes",[Object])],T);let N=class extends n.BaseModel{constructor(e){super(e),this.type=d.X509}};function B(){return function(e,t,r){const i=r.value;return r.value=async function(...e){const r=e[0],o=r.clientIdentity.getID(),s=await this.tokenRepository.select(),c=await s.execute(r);if(0==c.length)throw new a.NotFoundError("No tokens avaialble");if(c.length>1)throw new a.NotFoundError("To many token available : "+c.length);if(c[0].owner!=o)throw new n.AuthorizationError(`User not authorized to run ${t} on the token`);return await i.apply(this,e)},r}}function z(e,t){const r=e+t;if(e!==r-t||t!==r-e)throw new w(`Addition overflow: ${e} + ${t}`);return r}function R(e,t){const r=e-t;if(e!==r+t||t!==e-r)throw new w(`Subtraction overflow: ${e} - ${t}`);return r}c.__decorate([r.description("Unique identifier of the identity"),n.pk(),c.__metadata("design:type",String)],N.prototype,"id",void 0),c.__decorate([n.oneToOne(T,{update:n.Cascade.CASCADE,delete:n.Cascade.CASCADE}),c.__metadata("design:type",T)],N.prototype,"credentials",void 0),c.__decorate([n.column(),t.required(),n.index(),c.__metadata("design:type",String)],N.prototype,"mspId",void 0),c.__decorate([n.column(),t.required(),c.__metadata("design:type",String)],N.prototype,"type",void 0),N=c.__decorate([t.model(),c.__metadata("design:paramtypes",[Object])],N),o.Object()(Date);class I extends o.Contract{static{this.adapter=new E}static{this.serializer=new A}constructor(e,t){super(e),this.clazz=t,this.initialized=!1,this.repo=n.Repository.forModel(t)}async listBy(e,t,r,...a){const{ctxArgs:i,log:o}=(await this.logCtx([...a,e],n.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return o.info(`Running listBy key ${t}, order ${r} and args ${i}`),this.repo.listBy(t,r,...i)}async paginateBy(e,t,r,a={offset:1,limit:10},...i){const{ctxArgs:o,log:s}=(await this.logCtx([...i,e],n.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return s.info(`Running paginateBy key ${t}, order ${r} with size ${a.limit} and args ${o}`),this.repo.paginateBy(t,r,a,...o)}async findOneBy(e,t,r,...a){const{ctxArgs:i,log:o}=(await this.logCtx([...a,e],n.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return o.info(`Running findOneBy key ${t}, value: ${r} with args ${i}`),this.repo.findOneBy(t,r,...i)}async statement(e,t,...r){const{ctxArgs:a,log:i}=(await this.logCtx([...r,e],n.PersistenceKeys.STATEMENT,!0)).for(this.statement);return i.info(`Running statement ${t} with args ${a}`),this.repo.statement(t,...a)}async create(e,r,...n){const{log:i,ctxArgs:o}=(await this.logCtx([...n,e],a.OperationKeys.CREATE,!0)).for(this.create);i.info("CONTRACT CREATE, "+o),"string"==typeof r&&(r=this.deserialize(r)),i.info("Creating model: "+JSON.stringify(r));const s=this.getTransientData(e);return i.info("Merging transient data..."),r=t.Model.merge(r,s,this.clazz),this.repo.create(r,...o)}async read(e,t,...r){const{log:n,ctxArgs:i}=(await this.logCtx([...r,e],a.OperationKeys.READ,!0)).for(this.create);return n.info(`reading entry with pk ${t} `),this.repo.read(t,...i)}getTransientData(e){const t=e.stub.getTransient();let r={};return t.has(this.repo.tableName)&&(r=JSON.parse(t.get(this.repo.tableName)?.toString("utf8"))),r}async update(e,r,...n){const{log:i,ctxArgs:o}=(await this.logCtx([...n,e],a.OperationKeys.UPDATE,!0)).for(this.update);"string"==typeof r&&(r=this.deserialize(r)),i.info("Updating model: "+JSON.stringify(r));const s=this.getTransientData(e);return i.info("Merging transient data..."),r=t.Model.merge(r,s,this.clazz),this.repo.update(r,...o)}async delete(e,t,...r){const{log:n,ctxArgs:i}=(await this.logCtx([...r,e],a.OperationKeys.DELETE,!0)).for(this.delete);return n.info(`deleting entry with pk ${t} `),this.repo.delete(t+"",...i)}async deleteAll(e,t,...r){const{ctxArgs:n}=(await this.logCtx([...r,e],a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);return"string"==typeof t&&(t=JSON.parse(t)),this.repo.deleteAll(t,...n)}async readAll(e,t,...r){const{ctxArgs:n}=(await this.logCtx([...r,e],a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.create);return"string"==typeof t&&(t=JSON.parse(t)),this.repo.readAll(t,...n)}async updateAll(e,t,...r){const{log:n,ctxArgs:i}=(await this.logCtx([...r,e],a.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAll);return"string"==typeof t&&(t=JSON.parse(t).map(e=>this.deserialize(e)).map(e=>new this.clazz(e))),n.info(`updating ${t.length} entries to the table`),this.repo.updateAll(t,...i)}async query(e,t,r,a=n.OrderDirection.ASC,i,o,...s){const{ctxArgs:c}=(await this.logCtx([...s,e],n.PersistenceKeys.QUERY,!0)).for(this.create);return this.repo.query(t,r,a,i,o,...c)}async raw(e,t,r,...a){const{ctxArgs:n}=(await this.logCtx([...a,e],"raw",!0)).for(this.raw);return I.adapter.raw(t,r,...n)}serialize(e){return I.serializer.serialize(e)}deserialize(e){return I.serializer.deserialize(e)}async init(e){const{log:t,ctxArgs:r}=(await this.logCtx([e],n.PersistenceKeys.INITIALIZATION,!0)).for(this.init);t.info(`Running contract ${this.getName()} initialization...`),this.initialized=!0,t.info("Contract initialization completed.")}async healthcheck(e){const{log:t}=(await this.logCtx([e],"healthcheck",!0)).for(this.healthcheck);return t.info(`Running Healthcheck: ${this.initialized}...`),{healthcheck:this.initialized}}async createAll(e,t,...r){const{log:n,ctxArgs:i}=(await this.logCtx([...r,e],a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll);return"string"==typeof t&&(t=JSON.parse(t).map(e=>this.deserialize(e)).map(e=>new this.clazz(e))),n.info(`adding ${t.length} entries to the table`),this.repo.createAll(t,...i)}logCtx(e,t,r=!1){const a=e.pop();if(!a||!a.stub)throw new C("No valid context provided...");const n=I.adapter.logCtx([this.clazz,...e],t,r,a);function i(e){return e.ctxArgs.shift(),e}return n instanceof Promise?n.then(i):i(n)}}class D extends I{constructor(e,t){super(e,t)}async create(e,t){return this.serialize(await super.create(e,t))}async read(e,t){return this.serialize(await super.read(e,t))}async update(e,t){return this.serialize(await super.update(e,t))}async delete(e,t){return this.serialize(await super.delete(e,t))}async deleteAll(e,t){const r=JSON.parse(t);return JSON.stringify((await super.deleteAll(e,r)).map(e=>this.serialize(e)))}async readAll(e,t){const r=JSON.parse(t);return JSON.stringify((await super.readAll(e,r)).map(e=>this.serialize(e)))}async updateAll(e,t){const r=JSON.parse(t).map(e=>this.deserialize(e)).map(e=>new this.clazz(e));return JSON.stringify((await super.updateAll(e,r)).map(e=>this.serialize(e)))}async statement(e,t,r){try{r=JSON.parse(r)}catch(e){throw new a.SerializationError("Invalid args: "+e)}if(!Array.isArray(r))throw new a.SerializationError(`Invalid args: ${JSON.stringify(r)}. must be an array`);return JSON.stringify(await super.statement(e,t,...r))}async listBy(e,t,r){return JSON.stringify(await super.listBy(e,t,r))}async paginateBy(e,t,r,n){try{n=JSON.parse(n)}catch(e){throw new a.SerializationError("Failed to deserialize paginateBy reference: "+e)}return JSON.stringify(await super.paginateBy(e,t,r,n))}async findOneBy(e,t,r){return JSON.stringify(await super.findOneBy(e,t,r))}async query(e,t,r,i,o,s){let c;try{c=n.Condition.from(JSON.parse(t))}catch(e){throw new a.SerializationError("Invalid condition: "+e)}return JSON.stringify(await super.query(e,c,r,i,o,s))}async init(e){await super.init(e)}async healthcheck(e){return JSON.stringify(await super.healthcheck(e))}async createAll(e,t){const r=JSON.parse(t).map(e=>this.deserialize(e)).map(e=>new this.clazz(e)),a=await super.createAll(e,r);return JSON.stringify(a.map(e=>this.serialize(e)))}}c.__decorate([o.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String]),c.__metadata("design:returntype",Promise)],D.prototype,"create",null),c.__decorate([o.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String]),c.__metadata("design:returntype",Promise)],D.prototype,"read",null),c.__decorate([o.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String]),c.__metadata("design:returntype",Promise)],D.prototype,"update",null),c.__decorate([o.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String]),c.__metadata("design:returntype",Promise)],D.prototype,"delete",null),c.__decorate([o.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String]),c.__metadata("design:returntype",Promise)],D.prototype,"deleteAll",null),c.__decorate([o.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String]),c.__metadata("design:returntype",Promise)],D.prototype,"readAll",null),c.__decorate([o.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String]),c.__metadata("design:returntype",Promise)],D.prototype,"updateAll",null),c.__decorate([o.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String,String]),c.__metadata("design:returntype",Promise)],D.prototype,"statement",null),c.__decorate([o.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String,String]),c.__metadata("design:returntype",Promise)],D.prototype,"listBy",null),c.__decorate([o.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String,String,String]),c.__metadata("design:returntype",Promise)],D.prototype,"paginateBy",null),c.__decorate([o.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String,String]),c.__metadata("design:returntype",Promise)],D.prototype,"findOneBy",null),c.__decorate([o.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context]),c.__metadata("design:returntype",Promise)],D.prototype,"init",null),c.__decorate([o.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context]),c.__metadata("design:returntype",Promise)],D.prototype,"healthcheck",null),c.__decorate([o.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String]),c.__metadata("design:returntype",Promise)],D.prototype,"createAll",null);let M=class extends n.BaseModel{constructor(e){super(e)}};c.__decorate([n.pk({type:String}),c.__metadata("design:type",String)],M.prototype,"name",void 0),c.__decorate([n.column(),t.required(),c.__metadata("design:type",String)],M.prototype,"owner",void 0),c.__decorate([n.column(),t.required(),c.__metadata("design:type",String)],M.prototype,"symbol",void 0),c.__decorate([n.column(),t.required(),c.__metadata("design:type",Number)],M.prototype,"decimals",void 0),M=c.__decorate([n.table("erc20_tokens"),t.model(),c.__metadata("design:paramtypes",[Object])],M);let $=class extends n.BaseModel{constructor(e){super(e)}};c.__decorate([n.pk({type:String}),c.__metadata("design:type",String)],$.prototype,"id",void 0),c.__decorate([n.column(),t.required(),c.__metadata("design:type",String)],$.prototype,"token",void 0),c.__decorate([n.column(),t.required(),c.__metadata("design:type",Number)],$.prototype,"balance",void 0),c.__decorate([n.column(),c.__metadata("design:type",String)],$.prototype,"captive",void 0),$=c.__decorate([n.table("erc20_wallets"),t.model(),c.__metadata("design:paramtypes",[Object])],$);let F=class extends n.BaseModel{constructor(e){super(e)}};c.__decorate([n.pk({type:String}),n.column(),t.required(),c.__metadata("design:type",String)],F.prototype,"owner",void 0),c.__decorate([n.column(),t.required(),c.__metadata("design:type",String)],F.prototype,"spender",void 0),c.__decorate([n.column(),t.required(),c.__metadata("design:type",Number)],F.prototype,"value",void 0),F=c.__decorate([n.table("erc20_allowances"),t.model(),c.__metadata("design:paramtypes",[Object])],F);class L extends I{constructor(e){super(e,$),L.adapter=L.adapter||new E,this.walletRepository=h.forModel($,L.adapter.alias),this.tokenRepository=h.forModel(M,L.adapter.alias),this.allowanceRepository=h.forModel(F,L.adapter.alias)}async TokenName(e){const{ctx:t}=await this.logCtx([e],this.TokenName);await this.CheckInitialized(t);const r=this.tokenRepository.select();return(await r.execute(t))[0].name}async Symbol(e){const{ctx:t}=await this.logCtx([e],this.TokenName);await this.CheckInitialized(t);const r=this.tokenRepository.select();return(await r.execute(t))[0].symbol}async Decimals(e){const{ctx:t}=await this.logCtx([e],this.TokenName);await this.CheckInitialized(t);const r=this.tokenRepository.select();return(await r.execute(t))[0].decimals}async TotalSupply(e){const{ctx:t}=await this.logCtx([e],this.TokenName);await this.CheckInitialized(t);const r=this.walletRepository.select(),n=await r.execute(t);if(0==n.length)throw new a.NotFoundError(`The token ${this.getName()} does not exist`);let i=0;return n.forEach(e=>{i+=e.balance}),i}async BalanceOf(e,t){const{ctx:r}=await this.logCtx([e],this.TokenName);return await this.CheckInitialized(r),(await this.walletRepository.read(t,r)).balance}async Transfer(e,t,r){const{ctx:n}=await this.logCtx([e],this.Transfer);await this.CheckInitialized(n);const i=n.identity.getID();if(!await this._transfer(i,t,r,n))throw new a.InternalError("Failed to transfer");return!0}async TransferFrom(e,t,r,n){const{ctx:i}=await this.logCtx([e],this.BurnFrom);await this.CheckInitialized(i);const o=i.identity.getID(),s=await this._getAllowance(t,o,i);if(!s||0>s.value)throw new x(`spender ${o} has no allowance from ${t}`);const c=s.value;if(n>c)throw new b("The spender does not have enough allowance to spend.");const l=R(c,n),d=Object.assign({},s,{value:l});if(await this.allowanceRepository.update(d,i),!await this._transfer(t,r,n,i))throw new a.InternalError("Failed to transfer");return!0}async _transfer(e,t,r,i){const o=i.logger;if(e===t)throw new n.AuthorizationError("cannot transfer to and from same client account");if(0>r)throw new b("transfer amount cannot be negative");const s=await this.walletRepository.read(e,i),c=s.balance;if(r>c)throw new b(`client account ${e} has insufficient funds.`);let l,d=!1;try{l=await this.walletRepository.read(t,i)}catch(e){if(!(e instanceof a.BaseError))throw new a.InternalError(e);if(404!==e.code)throw new a.InternalError(e.message);l=new $({id:t,balance:0,token:await this.TokenName(i)}),d=!0}const u=l.balance,p=R(c,r),g=z(u,r),h=Object.assign({},s,{balance:p});await this.walletRepository.update(h,i);const y=Object.assign({},l,{balance:g});d?await this.walletRepository.create(y,i):await this.walletRepository.update(y,i);const m={from:e,to:t,value:r};return this.repo.refresh(M,O.TRANSFER,"",m,i).catch(e=>o.error("Failed to notify transfer: "+e)),!0}async Approve(e,t,r){const{ctx:a,ctxArgs:n}=await this.logCtx([e],this.Approve);await this.CheckInitialized(a);const i=a.identity.getID();let o=await this._getAllowance(i,t,a);if((await this.walletRepository.read(i,...n)).balance<r)throw new b(`client account ${i} has insufficient funds.`);o?(o.value=r,await this.allowanceRepository.update(o,...n)):(o=new F({owner:i,spender:t,value:r}),await this.allowanceRepository.create(o,...n));const s={owner:i,spender:t,value:r};return this.repo.refresh(M,O.APPROVAL,"",s,a),!0}async Allowance(e,t,r){const{ctx:a}=await this.logCtx([e],this.Allowance);await this.CheckInitialized(a);const n=await this._getAllowance(t,r,a);if(!n)throw new x(`spender ${r} has no allowance from ${t}`);return n.value}async _getAllowance(e,t,r){const a=n.Condition.and(n.Condition.attribute("owner").eq(e),n.Condition.attribute("spender").eq(t)),i=await this.allowanceRepository.select().where(a).execute(r);return i?.[0]}async Initialize(e,t){const{ctx:r}=await this.logCtx([e],this.Initialize);if((await this.tokenRepository.select().execute(r)).length>0)throw new n.AuthorizationError("contract options are already set, client is not authorized to change them");return t.owner=r.identity.getID(),await this.tokenRepository.create(t,r),!0}async CheckInitialized(e){const{ctx:t}=await this.logCtx([e],this.CheckInitialized);if(0==(await this.tokenRepository.select().execute(t)).length)throw new S("contract options need to be set before calling any function, call Initialize() to initialize contract")}async Mint(e,t){const{ctx:r}=await this.logCtx([e],this.Mint);await this.CheckInitialized(r);const n=r.identity.getID();if(0>=t)throw new a.ValidationError("mint amount must be a positive integer");let i;try{i=await this.walletRepository.read(n,r);const e=z(i.balance,t),a=Object.assign({},i,{balance:e});await this.walletRepository.update(a,r)}catch(i){if(!(i instanceof a.BaseError))throw new a.InternalError(i);if(404!==i.code)throw new a.InternalError(i.message);{const a=new $({id:n,balance:t,token:await this.TokenName(e)});await this.walletRepository.create(a,r)}}const o={from:"0x0",to:n,value:t};this.repo.ObserverHandler().updateObservers(M,O.TRANSFER,"",o,r)}async Burn(e,t){const{log:r,ctx:a}=await this.logCtx([e],this.Burn);await this.CheckInitialized(a);const n=a.identity.getID(),i=await this.walletRepository.read(n,a),o=i.balance;if(t>o)throw new b("Minter has insufficient funds.");const s=R(o,t),c=Object.assign({},i,{balance:s});await this.walletRepository.update(c,a),r.info(t+" tokens were burned");const l={from:n,to:"0x0",value:t};this.repo.ObserverHandler().updateObservers(M,O.TRANSFER,"",l,a)}async BurnFrom(e,t,r){const{log:a,ctx:n}=await this.logCtx([e],this.BurnFrom);await this.CheckInitialized(n);const i=await this.walletRepository.read(t,n),o=i.balance;if(r>o)throw new b(t+" has insufficient funds.");const s=R(o,r),c=Object.assign({},i,{balance:s});await this.walletRepository.update(c,n),a.info(`${r} tokens were burned from ${t}`);const l={from:t,to:"0x0",value:r};this.repo.ObserverHandler().updateObservers(M,O.TRANSFER,"",l,n)}async ClientAccountBalance(e){const{ctx:t}=await this.logCtx([e],this.TokenName);await this.CheckInitialized(t);const r=t.identity.getID(),a=await this.walletRepository.read(r,t);if(!a)throw new b(`The account ${r} does not exist`);return a.balance}async ClientAccountID(e){const{ctx:t}=await this.logCtx([e],this.ClientAccountID);return await this.CheckInitialized(t),t.identity.getID()}}c.__decorate([o.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context]),c.__metadata("design:returntype",Promise)],L.prototype,"TokenName",null),c.__decorate([o.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context]),c.__metadata("design:returntype",Promise)],L.prototype,"Symbol",null),c.__decorate([o.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context]),c.__metadata("design:returntype",Promise)],L.prototype,"Decimals",null),c.__decorate([o.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context]),c.__metadata("design:returntype",Promise)],L.prototype,"TotalSupply",null),c.__decorate([o.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String]),c.__metadata("design:returntype",Promise)],L.prototype,"BalanceOf",null),c.__decorate([o.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String,Number]),c.__metadata("design:returntype",Promise)],L.prototype,"Transfer",null),c.__decorate([o.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String,String,Number]),c.__metadata("design:returntype",Promise)],L.prototype,"TransferFrom",null),c.__decorate([o.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String,Number]),c.__metadata("design:returntype",Promise)],L.prototype,"Approve",null),c.__decorate([o.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String,String]),c.__metadata("design:returntype",Promise)],L.prototype,"Allowance",null),c.__decorate([o.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,M]),c.__metadata("design:returntype",Promise)],L.prototype,"Initialize",null),c.__decorate([o.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context]),c.__metadata("design:returntype",Promise)],L.prototype,"CheckInitialized",null),c.__decorate([B(),o.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,Number]),c.__metadata("design:returntype",Promise)],L.prototype,"Mint",null),c.__decorate([B(),o.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,Number]),c.__metadata("design:returntype",Promise)],L.prototype,"Burn",null),c.__decorate([B(),o.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context,String,Number]),c.__metadata("design:returntype",Promise)],L.prototype,"BurnFrom",null),c.__decorate([o.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context]),c.__metadata("design:returntype",Promise)],L.prototype,"ClientAccountBalance",null),c.__decorate([o.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[o.Context]),c.__metadata("design:returntype",Promise)],L.prototype,"ClientAccountID",null);const q=[L];class j extends s.MiniLogger{constructor(e,t,r){super(e,t),r?(this.logger=r.logging.getLogger(e),r.logging.setLevel(t?.level||s.Logging.getConfig().level)):this.logger=new s.MiniLogger(e,t)}log(e,t,r){if(s.NumericLogLevels[this.config("level")]<s.NumericLogLevels[e])return;let n;switch(e){case s.LogLevel.benchmark:n=this.logger.verbose;break;case s.LogLevel.info:n=this.logger.info;break;case s.LogLevel.verbose:n=this.logger.verbose;break;case s.LogLevel.debug:n=this.logger.debug;break;case s.LogLevel.error:n=this.logger.error;break;case s.LogLevel.trace:n=this.logger.trace;break;case s.LogLevel.warn:n=this.logger.warn;break;case s.LogLevel.silly:n=this.logger.silly;break;default:throw new a.InternalError("Invalid log level")}n.call(this.logger,this.createLog(e,t,r))}}s.Logging.setFactory((e,t,r)=>new j(e||j.name,t||{},r));const K="##VERSION##",J="##PACKAGE##";r.Metadata.registerLibrary(J,K),e.ContractLogger=j,e.FabricContractAdapter=E,e.FabricContractContext=p,e.FabricContractPaginator=_,e.FabricContractRepository=h,e.FabricContractRepositoryObservableHandler=g,e.FabricCrudContract=I,e.FabricStatement=y,e.PACKAGE_NAME=J,e.SerializedCrudContract=D,e.VERSION=K,e.contracts=q,e.createdByOnFabricCreateUpdate=v},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/decorator-validation"),require("@decaf-ts/decoration"),require("@decaf-ts/db-decorators"),require("@decaf-ts/core"),require("@decaf-ts/for-couchdb"),require("fabric-contract-api"),require("@decaf-ts/logging"),require("tslib")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/decorator-validation","@decaf-ts/decoration","@decaf-ts/db-decorators","@decaf-ts/core","@decaf-ts/for-couchdb","fabric-contract-api","@decaf-ts/logging","tslib"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-fabric"]={},e.decafTsDecoratorValidation,e.decafTsDecoration,e.decafTsDbDecorators,e.decafTsCore,e.decafTsForCouchdb,e.fabricContractApi,e.decafTsLogging,e.tslib);
1
+ var e,t;e=this,t=function(e,t,r,i,a,s,n,o,c,l,d,u,h,p,g,f,m,y,w){"use strict";function b(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function C(e){if(e&&e.__esModule)return 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 E=b(o),A=b(u),v=C(h),S=C(g),_=b(f),I=b(m),x=b(y);class N 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})}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 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 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)}`);let{record:n,id:o,transient:c}=this.adapter.prepare(e,i);return n=await this.adapter.create(this.class,o,n,c,...s),this.adapter.revert(n,this.class,o,c,i)}async update(e,...t){const{ctxArgs:i,log:a,ctx:s}=this.logCtx(t,this.update);let{record:n,id:o,transient:c}=this.adapter.prepare(e,s);return a.debug(`updating ${this.class.name} in table ${r.Model.tableName(this.class)} with id ${o}`),n=await this.adapter.update(this.class,o,n,c,...i),this.adapter.revert(n,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)}`);const n=e.map(e=>this.adapter.prepare(e,i)),o=n.map(e=>e.id);let c=n.map(e=>e.record);const l=n.map(e=>e.transient);return c=await this.adapter.createAll(this.class,o,c,l,...s),c.map((e,t)=>this.adapter.revert(e,this.class,o[t],i.get("rebuildWithTransient")?n[t].transient:void 0,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)}`);const n=e.map(e=>this.adapter.prepare(e,i));return(await this.adapter.updateAll(this.class,n.map(e=>e.id),n.map(e=>e.record),n.map(e=>e.transient),...s)).map((e,t)=>this.adapter.revert(e,this.class,n[t].id,i.get("rebuildWithTransient")?n[t].transient:void 0,i))}}let T=class extends t.BaseModel{constructor(e){super(e)}};s.__decorate([t.pk({type:String}),s.__metadata("design:type",String)],T.prototype,"name",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],T.prototype,"owner",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],T.prototype,"symbol",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",Number)],T.prototype,"decimals",void 0),T=s.__decorate([t.table("erc20_tokens"),r.model(),s.__metadata("design:paramtypes",[Object])],T);let O=class extends t.BaseModel{constructor(e){super(e)}};s.__decorate([t.pk({type:String}),s.__metadata("design:type",String)],O.prototype,"id",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],O.prototype,"token",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",Number)],O.prototype,"balance",void 0),s.__decorate([t.column(),s.__metadata("design:type",String)],O.prototype,"captive",void 0),O=s.__decorate([t.table("erc20_wallets"),r.model(),s.__metadata("design:paramtypes",[Object])],O);let F=class extends t.BaseModel{constructor(e){super(e)}};s.__decorate([t.pk({type:String}),t.column(),r.required(),s.__metadata("design:type",String)],F.prototype,"owner",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],F.prototype,"spender",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",Number)],F.prototype,"value",void 0),F=s.__decorate([t.table("erc20_allowances"),r.model(),s.__metadata("design:paramtypes",[Object])],F);class M 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 R extends N{static{this.serializer=new M}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 R.decoder.decode(e)}constructor(e){super(e,O),this.serializer=R.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",[R.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 B(e,t,r){return[...e.map(e=>e===a.CouchDBKeys.TABLE?"table":e),...r||[],...t?[t]:[],"index"].join(n.Metadata.splitter)}function P(e,t,r,i){const a=B(t,r,i);let s=[...t,...i||[]];r&&(s=s.reduce((e,t)=>{const i={};return i[t]=r,e.push(i),e},[]));const n={index:{fields:s},name:a,ddoc:a,type:"json"};e[a]=n}function K(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 $;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,($=e.FabricModelKeys||(e.FabricModelKeys={})).PRIVATE="private",$.SHARED="shared",$.FABRIC="fabric.",$.OWNEDBY="owned-by",$.TRANSACTION_ID="transaction-id",e.IdentityType=void 0,(e.IdentityType||(e.IdentityType={})).X509="X.509";const k="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 z{static{this.logger=new c.MiniLogger(z.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?(z.cryptoSuite||(z.cryptoSuite=d.User.newCryptoSuite(e)),z.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 A.default.createHash("sha256").update(Buffer.concat([r,i,a])).digest()}static async getIdentity(e,r){const i=await this.contentOfLoadFile(r,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await this.getFirstDirFileName(e);return await r.readFile(i)});return{mspId:e,credentials: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"])}}const j=new p.Crypto;var L,U,H,q,Y;v.cryptoProvider.set(j),e.BASE_ALPHABET=void 0,(L=e.BASE_ALPHABET||(e.BASE_ALPHABET={})).BASE2="01",L.BASE8="01234567",L.BASE11="0123456789a",L.BASE16="0123456789abcdef",L.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",L.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",L.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",L.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",L.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",L.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",L.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~",e.CRYPTO=void 0,(U=e.CRYPTO||(e.CRYPTO={})).HASH="SHA-256",U[U.ITERATIONS=1e3]="ITERATIONS",U[U.KEYLENGTH=48]="KEYLENGTH",U[U.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",U[U.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",U.ALGORYTHM="AES-GCM",U.KEY_ALGORYTHM="PBKDF2";class G{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 V{static{this.b58encoder=new G(e.BASE_ALPHABET.BASE58)}static{this.logger=new c.MiniLogger(V.name)}constructor(){}static fabricIdFromCertificate(e){this.logger.debug(r.stringFormat("Parsing certificate: {0}",e));const t=new v.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=j.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 j.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 v.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,j.subtle.verify({name:"ECDSA",hash:"SHA-256"},a,t,r)}static async encrypt(e,t){const r=new v.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:j.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=j.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 J extends i.InternalError{constructor(e){super(e,J.name)}}class Q extends i.InternalError{constructor(e){super(e,Q.name)}}class X extends i.InternalError{constructor(e){super(e,X.name)}}class W extends t.AuthorizationError{constructor(e){super(e,W.name)}}class Z extends i.InternalError{constructor(e){super(e,Z.name,500)}}class ee extends i.BaseError{constructor(e="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(ee.name,e,403)}}class te extends i.BaseError{constructor(e){super(te.name,e,409)}}class re extends i.InternalError{constructor(e){super(e,re.name,500)}}class ie extends i.InternalError{constructor(e){super(e,ie.name,500)}}class ae extends i.InternalError{constructor(e){super(e,ae.name,500)}}class se extends i.InternalError{constructor(e){super(e,se.name,500)}}class ne extends i.InternalError{constructor(e){super(e,ne.name,500)}}e.HFCAIdentityType=void 0,(H=e.HFCAIdentityType||(e.HFCAIdentityType={})).PEER="peer",H.ORDERER="orderer",H.CLIENT="client",H.USER="user",H.ADMIN="admin",e.HFCAIdentityAttributes=void 0,(q=e.HFCAIdentityAttributes||(e.HFCAIdentityAttributes={})).HFREGISTRARROLES="hf.Registrar.Roles",q.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",q.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",q.HFINTERMEDIATECA="hf.IntermediateCA",q.HFREVOKER="hf.Revoker",q.HFAFFILIATIONMGR="hf.AffiliationMgr",q.HFGENCRL="hf.GenCRL";class oe extends c.LoggedClass{constructor(e){z.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 z.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 z.getFirstDirFileNameContent(r)}return n.debug("Loading Admin user for ca "+e),this.user=await z.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 o=await z.getFileContent(n);return e.debug(`Creating CA Client for CA ${i} under ${t}`),this.ca=new E.default(t,{trustedRoots:Buffer.from(o),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 W(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 W(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(oe,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${i} in msp ${r}`);const o=V.fabricIdFromCertificate(i),l=V.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=oe.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 ce 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}}async function le(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 de(e,t,r,i){const{stub:a}=e;i[r]=a.getTxID()}function ue(t){return n.Metadata.key(e.FabricModelKeys.FABRIC+t)}s.__decorate([r.required(),s.__metadata("design:type",String)],ce.prototype,"affiliation",void 0),s.__decorate([r.minlength(1),s.__metadata("design:type",Array)],ce.prototype,"attrs",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],ce.prototype,"enrollmentID",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],ce.prototype,"enrollmentSecret",void 0),s.__decorate([r.min(0),s.__metadata("design:type",Number)],ce.prototype,"maxEnrollments",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],ce.prototype,"role",void 0),e.ERC20Events=void 0,(Y=e.ERC20Events||(e.ERC20Events={})).TRANSFER="Transfer",Y.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(k),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(k),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.validatableProperties(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.PRIVATE),l={model:{},transient:{},private:{},shared:{}},d=Object.keys(s),u=Object.keys(o),h=Object.keys(c);for(const e of a){const r=d.includes(e),i=u.includes(e),a=h.includes(e);r?(l.transient=l.transient||{},l.transient[e]=t[e],i&&(l.private=l.private||{},l.private[e]=t[e]),a&&(l.shared=l.shared||{},l.shared[e]=t[e])):(l.model=l.model||{},l.model[e]=t[e])}return l.model=r.Model.build(l.model,t.constructor.name),l}).bind(r.Model),r.Model.tableName=e=>{const i=e instanceof r.Model?e.constructor:e;return n.Metadata.get(i,t.PersistenceKeys.TABLE)||(e instanceof r.Model?e.constructor.name:e.name)},r.Model.isPrivate=(t=>!!n.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.PRIVATE)).bind(r.Model),n.Metadata.isShared=(t=>!!n.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.SHARED)).bind(n.Metadata);const he=e=>`__${e.constructor.name}PrivateCollection`;async function pe(e,r,a,s){if(a.length!==r.length)throw new i.InternalError("Segregated data keys and metadata length mismatch");const n=r[0].collections,o="string"==typeof n?n:n(s),c=a.reduce((e,i,a)=>{const n="string"==typeof r[a].collections?r[a].collections:r[a].collections(s);if(n!==o)throw new t.UnsupportedError(`Segregated data collection mismatch: ${n} vs ${o}`);return e[i]=s[i],e},{}),l=new this.class(c),d=await this.override({segregated:o}).create(l,e);Object.assign(s,d)}async function ge(e,r,a,s){if(a.length!==r.length)throw new i.InternalError("Segregated data keys and metadata length mismatch");const n=r[0].collections,o="string"==typeof n?n:n(s),c=a.reduce((e,i,a)=>{const n="string"==typeof r[a].collections?r[a].collections:r[a].collections(s);if(n!==o)throw new t.UnsupportedError(`Segregated data collection mismatch: ${n} vs ${o}`);return e[i]=s[i],e},{}),l=new this.class(c),d=await this.override({segregated:o}).create(l,e);Object.assign(s,d)}async function fe(e,t,r,i,a){}async function me(e,t,r,i){}function ye(e,t){return(r,a)=>{const s=[];return a?(s.push(i.transient(),(r,i)=>{if(!i){const i=n.Metadata.properties(r)||[];for(const a of i)ye(e,t)(r,a);return r}const a=n.Metadata.key(t,i),s=r.constructor,o=n.Metadata.get(s,a)||{},c=new Set(o.collections||[]);c.add(e),o.collections=[...c],n.Metadata.set(s,a,o)},i.onCreate(pe,{collections:e},{priority:95,group:"string"==typeof e?e:e.toString()}),i.onRead(ge,{collections:e},{priority:95,group:"string"==typeof e?e:e.toString()}),i.onUpdate(fe,{collections:e},{priority:95,group:"string"==typeof e?e:e.toString()}),i.onDelete(me,{collections:e},{priority:95,group:"string"==typeof e?e:e.toString()})),n.apply(...s)(r,a)):(n.Metadata.properties(r)?.forEach(i=>ye(e,t)(r,i)),n.metadata(t,!0)(r))}}class we 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 be(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 Ce 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 Ee 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 z.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 z.getFirstDirFileNameContent(n)}return r.debug("Loading Admin user for ca "+a),this._user=await z.getCAUser("admin",d,l,a,{hsm:c}),this._user}async initialize(...e){const{log:t,ctx:r}=await this.logCtx(e,this.initialize,!0),[a]=e;if(!a)throw new i.InternalError("Missing Fabric CA configuration");const{url:s,tls:n,caName:o}=a;t.info(`Initializing CA Client for CA ${a.caName} at ${a.url}`);const{trustedRoots:c,verify:l}=n,d=c[0];t.debug(`Retrieving CA certificate from ${d}. cwd: ${process.cwd()}`);const u=await z.getFileContent(d);t.debug("CA Certificate: "+u.toString());const h=new E.default(s,{trustedRoots:Buffer.from(u),verify:l},o),p=await this.getUser(a,r);return t.debug("CA user loaded: "+p.getName()),{config:a,client:h}}async getCertificates(e,r=!0,...i){e instanceof t.Context?(i=[e],r=!0,e=void 0):"boolean"==typeof e?(r=e,e=void 0):"boolean"!=typeof r&&(i=[r,...i],r=!0);const{log:a}=await this.logCtx(i,this.getCertificates,!0);a.debug(`Retrieving certificates${e?" for "+e.id:""} for CA ${this.config.caName}`);const s=(await this.certificates.getCertificates(e||{},this.user)).result;return a.verbose(`Found ${s.certs.length} certificates`),a.debug(s.certs),r?s.certs.map(e=>e.PEM):s}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 W(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 W(s)}}async read(e,...t){const{log:r}=await this.logCtx(t,this.read,!0);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,this.register,!0);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=V.fabricIdFromCertificate(s),l=V.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,this.enroll,!0);let s;try{i.debug("Enrolling "+e);const r=await this.client.enroll({enrollmentID:e,enrollmentSecret:t});s=Ee.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,this.registerAndEnroll,!0),c=await this.register(e,t,r,i,a,s,o),{userName:l}=e;return this.enroll(l,c,o)}async revoke(e,...t){const{log:r}=await this.logCtx(t,this.revoke,!0);r.verbose("Revoking identity with enrollment ID "+e);const a=await this.read(e);if(!a)throw new i.NotFoundError("Could not find enrollment with id "+e);let s;try{s=await this.client.revoke({enrollmentID:a.id,reason:"User Deletion"},this.user)}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}}const Ae=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60},t.DefaultAdapterFlags),ve=new c.MiniLogger("fabric-fs");async function Se(e,t){return e instanceof Uint8Array||e.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?e:await t(e)}async function _e(e,r){const i=await Se(r,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await Ie(e);return await r.readFile(i)});return{mspId:e,credentials:i}}async function Ie(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 xe(e){const r=await Se(e,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await Ie(e);return await r.readFile(i)}),i=await Ne(r),a=i[Object.getOwnPropertySymbols(i)[0]];return l.signers.newPrivateKeySigner(a)}async function Ne(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)}}class Te{static#e=null;static#t=!1;constructor(e){if(Te.#e||(Te.#e=new _.default.PKCS11,Te.#e.load(this.findHSMPKCS11Lib(e))),!Te.#t){try{Te.#e.C_Initialize()}catch(e){if(e.code!==_.default.CKR_CRYPTOKI_ALREADY_INITIALIZED)throw e}Te.#t=!0}}findHSMPKCS11Lib(e){const t=["/usr/lib/softhsm/libsofthsm2.so","/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so","/usr/local/lib/softhsm/libsofthsm2.so","/usr/lib/libacsp-pkcs11.so","/opt/homebrew/lib/softhsm/libsofthsm2.so"];e&&t.push(e);for(const e of t)if(I.default.existsSync(e))return e;throw new re("Unable to find PKCS11 library")}dispose(){Te.#e.C_Finalize()}sanitizeOptions(e){const t=Object.assign({userType:_.default.CKU_USER},e);return this.assertNotEmpty(t.label,"label"),this.assertNotEmpty(t.pin,"pin"),this.assertNotEmpty(t.identifier,"identifier"),t}assertNotEmpty(e,t){if(!e||0===e.toString().trim().length)throw Error(t+" property must be provided")}findSlotForLabel(e){const t=Te.#e.C_GetSlotList(!0);if(0===t.length)throw Error("No pkcs11 slots can be found");const r=t.find(t=>Te.#e.C_GetTokenInfo(t).label.trim()===e);if(!r)throw Error(`label ${e} cannot be found in the pkcs11 slot list`);return r}login(e,t,r){try{Te.#e.C_Login(e,t,r)}catch(e){if(e.code!==_.default.CKR_USER_ALREADY_LOGGED_IN)throw e}}findObjectInHSM(e,t,r){const i=[{type:_.default.CKA_ID,value:r},{type:_.default.CKA_CLASS,value:t},{type:_.default.CKA_KEY_TYPE,value:_.default.CKK_EC}];Te.#e.C_FindObjectsInit(e,i);const a=Te.#e.C_FindObjects(e,1)[0];if(!a)throw Te.#e.C_FindObjectsFinal(e),Error("Unable to find object in HSM with ID "+r.toString());return Te.#e.C_FindObjectsFinal(e),a}newSigner(e){const t=this.sanitizeOptions(e),r=Te.#e,i=this.findSlotForLabel(t.label),a=r.C_OpenSession(i,_.default.CKF_SERIAL_SESSION);let s;try{this.login(a,t.userType,t.pin),s=this.findObjectInHSM(a,_.default.CKO_PRIVATE_KEY,t.identifier)}catch(e){throw Te.#e.C_CloseSession(a),e}return{signer:async e=>{Te.#e.C_SignInit(a,{mechanism:_.default.CKM_ECDSA},s);const t=await Te.#e.C_SignAsync(a,Buffer.from(e),Buffer.alloc(2*w.p256.Point.Fn.BYTES));return w.p256.Signature.fromBytes(t,"compact").normalizeS().toBytes("der")},close:()=>{Te.#e.C_CloseSession(a)}}}assertDefined(e){if(void 0===e)throw Error("required value was undefined");return e}getUncompressedPointOnCurve(e){const t=e.export({format:"jwk"}),r=Buffer.from(this.assertDefined(t.x),"base64url"),i=Buffer.from(this.assertDefined(t.y),"base64url"),a=Buffer.from("04","hex");return Buffer.concat([a,r,i])}getSKIFromCertificatePath(e){const t=e.endsWith(".pem")?e:x.default.join(e,"cert.pem"),r=I.default.readFileSync(t);return this.getSKIFromCertificate(r)}getSKIFromCertificate(e){const t=new A.default.X509Certificate(e),r=this.getUncompressedPointOnCurve(t.publicKey);return A.default.createHash("sha256").update(r).digest()}}class Oe 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_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.orderBySelector&&(s.push(t.QueryClause.ORDER_BY,this.orderBySelector[0]),r.push(this.orderBySelector[1])),a.method=c.toCamelCase(s.join(" ")),a.params=i,this.prepared=a,this}build(){throw new t.UnsupportedError("This method is only called is prepared statements are not used. If so, a dedicated implementation for the native queries used is required")}parseCondition(e,...r){throw new t.UnsupportedError("This method is only called is prepared statements are not used. Is so, a dedicated implementation for the native queries used is required")}}class Fe 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 Me;class Re extends t.Adapter{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new M}static{this.log=c.Logging.for(Re)}constructor(e,t){super(e,k,t),this.serializer=Re.serializer}Statement(e){return new Oe(this,e)}Paginator(e,t,r){return new Fe(this,e,t,r)}flags(e,t,r,...i){return super.flags(e,t,r,...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({},i,n.toOverrides()):i;const o=await this.flags("string"==typeof e?e:e.name,a,i,...s,n);if(n){if(!(n instanceof this.Context))return(new this.Context).accumulate({...n.cache,...o,parentContext:n});const t=n.get("operation"),r=n.get("affectedTables");return t!==e||a!==r?(new this.Context).accumulate({...n.cache,...o,parentContext:n}):n.accumulate(o)}return(new this.Context).accumulate({...Ae,...o})}decode(e){return Re.decoder.decode(e)}repository(){return N}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=await this.submitTransaction(l,i.BulkCrudOperationKeys.CREATE_ALL,[JSON.stringify(a.map(t=>this.serializer.serialize(t,e.name)))],o,void 0,e.name);try{return JSON.parse(this.decode(u)).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],o=n.shift(),{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);const u=await this.submitTransaction(l,i.BulkCrudOperationKeys.UPDATE_ALL,[JSON.stringify(a.map(t=>this.serializer.serialize(t,e.name)))],o,void 0,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,void 0,e.name);try{return JSON.parse(this.decode(c)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}prepare(e,...i){const{log:a}=this.logCtx(i,this.prepare),s=r.Model.segregate(e);return e[t.PersistenceKeys.METADATA]&&(a.silly("Passing along persistence metadata for "+e[t.PersistenceKeys.METADATA]),Object.defineProperty(s.model,t.PersistenceKeys.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[t.PersistenceKeys.METADATA]})),{record:s.model,model:s.model,id:e[r.Model.pk(e.constructor)],transient:s.transient,private:s.private,shared:s.shared}}revert(e,t,r,a,...s){const{log:n}=this.logCtx(s,this.revert);return a&&(n.verbose("re-adding transient properties: "+Object.keys(a).join(", ")),Object.entries(a).forEach(([r,a])=>{if(r in e)throw new i.InternalError(`Transient property ${r} already exists on model ${"string"==typeof t?t:t.name}. should be impossible`);e[r]=a})),new t(e)}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=await this.submitTransaction(l,i.OperationKeys.CREATE,[this.serializer.serialize(a,e.name)],s,void 0,e.name);return this.serializer.deserialize(this.decode(u))}async read(e,t,...a){const{log:s,ctx:n}=this.logCtx(a,this.readAll),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.updateAll);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=await this.submitTransaction(l,i.OperationKeys.UPDATE,[this.serializer.serialize(a,e.name||e)],s,void 0,e.name);return this.serializer.deserialize(this.decode(u))}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,void 0,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}getClient(){return this._client||(this._client=Re.getClient(this.config)),this._client}async Gateway(e){return Re.getGateway(e,this.config,this.client)}getContractName(e){if(e)return e+"Contract"}async Contract(e,t){return Re.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:a};return await l.call(c,t,d)}catch(e){if(10===e.code)throw Error(""+e.details[0].message);throw this.parseError(e)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}parseError(e){return Re.parseError(e)}async submitTransaction(e,t,r,i,a,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(I.default.readFileSync(r,"utf8"))}catch(e){throw new i.InternalError(`Failed to read the tls certificate from ${r}: ${e}`)}const a=S.credentials.createSsl(r);return t.debug("generating Gateway Client for url "+e.peerEndpoint),new g.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,t,r){const i=c.Logging.for(this.getConnection);i.debug(`Retrieving Peer Identity for ${t.mspId} under ${t.certCertOrDirectoryPath}`);const a=await _e(t.mspId,t.certCertOrDirectoryPath);i.debug("Retrieving signer key from "+t.keyCertOrDirectoryPath);let s,n=()=>{};if(t.hsm){const e=new Te(t.hsm.library),r=e.getSKIFromCertificatePath(t.certCertOrDirectoryPath),i=e.newSigner({label:t.hsm.tokenLabel,pin:t.hsm.pin+"",identifier:r});s=i.signer,n=i.close}else s=await xe(t.keyCertOrDirectoryPath);const o={client:e,identity:a,signer:s,evaluateOptions:()=>({deadline:Date.now()+1e3*r.get("evaluateTimeout")}),endorseOptions:()=>({deadline:Date.now()+1e3*r.get("endorseTimeout")}),submitOptions:()=>({deadline:Date.now()+1e3*r.get("submitTimeout")}),commitStatusOptions:()=>({deadline:Date.now()+1e3*r.get("commitTimeout")})};i.debug("Connecting to "+t.mspId);const d=l.connect(o);return t.hsm&&(d.close=new Proxy(d.close,{apply(e,t,r){Reflect.apply(e,t,r),n()}})),d}Dispatch(){return new Re._baseDispatch}static parseError(e){const r="string"==typeof e?e:e.message;return r.includes("MVCC_READ_CONFLICT")?new ae(e):r.includes("ENDORSEMENT_POLICY_FAILURE")?new ne(e):r.includes("PHANTOM_READ_CONFLICT")?new se(e):e instanceof Error&&e.code&&9===e.code?new ie(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)],Re.prototype,"create",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)],Re.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)],Re.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)],Re.prototype,"delete",null),s.__decorate([c.debug(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,"function"==typeof(Me="undefined"!=typeof D&&D)?Me:Object,Object,t.Context]),s.__metadata("design:returntype",Promise)],Re.prototype,"raw",null),Re.decoration(),t.Adapter.setCurrent(k);class De 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 Re))throw new t.UnsupportedError("Only FabricClientAdapter can be observed by dispatch");super.observe(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}=be(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 Re.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)}}Re&&(Re._baseDispatch=De);const Be="##VERSION##",Pe="##PACKAGE##";n.Metadata.registerLibrary(Pe,Be),e.AllowanceError=X,e.BalanceError=Q,e.BaseEncoder=G,e.ClientSerializer=M,e.CoreUtils=z,e.CryptoUtils=V,e.DefaultFabricClientFlags=Ae,e.DeterministicSerializer=we,e.EndorsementError=ie,e.EndorsementPolicyError=ne,e.FabricClientAdapter=Re,e.FabricClientDispatch=De,e.FabricClientRepository=N,e.FabricERC20ClientRepository=R,e.FabricEnrollmentService=oe,e.FabricFlavour=k,e.FabricIdentityService=Ee,e.ImplicitPrivateCollection=he,e.MissingContextError=Z,e.MissingPKCSS11Lib=re,e.MvccReadConflictError=ae,e.NotInitializedError=te,e.OverflowError=J,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=Pe,e.PhantomReadConflictError=se,e.RegistrationError=W,e.RegistrationRequestBuilder=ce,e.SimpleDeterministicSerializer=Ce,e.UnauthorizedPrivateDataAccess=ee,e.VERSION=Be,e.add=(e,t)=>{const r=e+t;if(e!==r-t||t!==r-e)throw new J(`Addition overflow: ${e} + ${t}`);return r},e.contentOfLoadFile=Se,e.extractPrivateKey=Ne,e.generateFabricEventName=(e,t,r)=>{const i=[e,t];return r&&i.push(r),i.join("_")},e.generateModelIndexes=(e,t)=>{const i=B([a.CouchDBKeys.TABLE]),s=t||{};s[i]={index:{fields:[a.CouchDBKeys.TABLE]},name:i,ddoc:i,type:"json"};const n={},o=r.Model.indexes(e);for(const e of Object.keys(o))for(const[,t]of Object.entries(o[e])){const r=t.directions,i=t.compositions,s=[e,a.CouchDBKeys.TABLE];P(n,s),i&&i.length&&P(n,s,void 0,i),r&&r.length&&r.forEach(e=>{P(n,s,e),i&&i.length&&P(n,s,e,i)})}return Object.entries(n).forEach(([e,t])=>{s[e]=t}),Object.values(n)},e.getCAUser=async(e,t,r,i)=>{ve.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.getFabricModelKey=ue,e.getFirstDirFileName=Ie,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=_e,e.getSigner=xe,e.ownedBy=()=>{const t=ue(e.FabricModelKeys.OWNEDBY);return n.Decoration.for(t).define({decorator:()=>(t,a)=>n.apply(r.required(),i.readonly(),i.onCreate(le),n.propMetadata(ue(e.FabricModelKeys.OWNEDBY),a))(t,a),args:[]}).apply()},e.ownedByOnCreate=le,e.parseEventName=be,e.privateData=(t=he)=>n.Decoration.for(e.FabricModelKeys.PRIVATE).define({decorator:t=>ye(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.readModelFile=K,e.readModelFolders=async(...e)=>{const t=require("fs");require("path");const 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(...K(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=pe,e.segregatedDataOnDelete=me,e.segregatedDataOnRead=ge,e.segregatedDataOnUpdate=fe,e.sharedData=t=>n.Decoration.for(e.FabricModelKeys.SHARED).define({decorator:t=>ye(t,e.FabricModelKeys.SHARED),args:[t]}).apply(),e.sub=(e,t)=>{const r=e-t;if(e!==r+t||t!==e-r)throw new J(`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(de),i.onUpdate(de),n.propMetadata(n.Metadata.key(e.FabricModelKeys.FABRIC,a,e.FabricModelKeys.TRANSACTION_ID),a))(t,a),args:[]}).apply(),e.transactionIdOnCreate=de,e.writeIndexes=(e,t=process.cwd())=>{const r=require("fs"),i=require("path");function a(e){const t=i.dirname(e);if(r.existsSync(t))return!0;a(t),r.mkdirSync(t)}e.forEach(e=>{const s=i.resolve(i.join(t,`./META-INF/statedb/couchdb/indexes/${e.name}.json`));a(s),r.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("pkcs11js"),require("fs"),require("path"),require("@noble/curves/nist")):"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","pkcs11js","fs","path","@noble/curves/nist"],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.pkcs11js,e.fs,e.path,e.nist);
2
2
  //# sourceMappingURL=for-fabric.cjs.map