@decaf-ts/for-fabric 0.0.6 → 0.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/for-fabric.cjs +1 -1
- package/dist/for-fabric.cjs.map +1 -1
- package/dist/for-fabric.js +1 -1
- package/dist/for-fabric.js.map +1 -1
- package/lib/client/fabric-fs.d.ts +1 -1
- package/lib/client/services/FabricEnrollmentService.d.ts +1 -1
- package/lib/contracts/ContractAdapter.d.ts +1 -1
- package/lib/contracts/ContractPrivateDataAdapter.d.ts +1 -1
- package/lib/esm/client/fabric-fs.d.ts +1 -1
- package/lib/esm/client/services/FabricEnrollmentService.d.ts +1 -1
- package/lib/esm/contracts/ContractAdapter.d.ts +1 -1
- package/lib/esm/contracts/ContractPrivateDataAdapter.d.ts +1 -1
- package/lib/esm/index.d.ts +0 -2
- package/lib/esm/index.js +2 -2
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.js +1 -1
- package/lib/index.cjs +2 -2
- package/lib/index.d.ts +0 -2
- package/lib/index.js.map +1 -1
- package/lib/version.cjs +1 -1
- package/lib/version.d.ts +1 -1
- package/package.json +5 -1
package/dist/for-fabric.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e,t;e=this,t=function(e,t,r,a,i,n,s,o,c,l,d,p,u,h,g,y,f){"use strict";function m(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function w(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var b=w(i),_=m(p),v=w(u);const A=s.Logging.for("fabric-fs");async function C(e,t){return e instanceof Uint8Array||e.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?e:await t(e)}async function E(e,t){return{mspId:e,credentials:await C(t,async e=>{const{promises:t}=await c.normalizeImport(import("fs")),r=await S(e);return await t.readFile(r)})}}async function S(e){const{promises:t}=await c.normalizeImport(import("fs")),{join:r}=await c.normalizeImport(import("path"));return r(e,(await t.readdir(e))[0])}async function O(e){const t=await C(e,async e=>{const{promises:t}=await c.normalizeImport(import("fs")),r=await S(e);return await t.readFile(r)}),r=await T(t),a=r[Object.getOwnPropertySymbols(r)[0]];return o.signers.newPrivateKeySigner(a)}async function T(e){let t;if(s.isBrowser())t=globalThis.crypto.subtle;else{const e=await c.normalizeImport(import("crypto"));t=e.subtle||e.webcrypto.subtle}if(!t)throw Error("Could not load SubtleCrypto module");const r=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,a=e.length;a>t;t++)r[t]=e.charCodeAt(t);return t})(Buffer.from(r,"base64").toString("binary"));try{return await t.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}catch(e){throw new d.InternalError(e)}}class I extends t.Repository{constructor(e,t){super(e,t)}async createPrefix(e,...t){const r=await d.Context.args(d.OperationKeys.CREATE,this.class,t,this.adapter,this._overrides||{});return[e=new this.class(e),...r.args]}async createAllPrefix(e,...t){return[e,...(await d.Context.args(d.OperationKeys.CREATE,this.class,t,this.adapter,this._overrides||{})).args]}async readPrefix(e,...t){return[e,...(await d.Context.args(d.OperationKeys.READ,this.class,t,this.adapter,this._overrides||{})).args]}async readAllPrefix(e,...t){return[e,...(await d.Context.args(d.OperationKeys.READ,this.class,t,this.adapter,this._overrides||{})).args]}async updatePrefix(e,...t){return[e,...(await d.Context.args(d.OperationKeys.UPDATE,this.class,t,this.adapter,this._overrides||{})).args]}async updateAllPrefix(e,...t){return[e,...(await d.Context.args(d.OperationKeys.UPDATE,this.class,t,this.adapter,this._overrides||{})).args]}async deletePrefix(e,...t){const r=await d.Context.args(d.OperationKeys.DELETE,this.class,t,this.adapter,this._overrides||{});return await this.read(e,...r.args),[e,...r.args]}async deleteAllPrefix(e,...t){const r=await d.Context.args(d.OperationKeys.DELETE,this.class,t,this.adapter,this._overrides||{});return await this.readAll(e,...r.args),[e,...r.args]}}var F;e.FabricModelKeys=void 0,(F=e.FabricModelKeys||(e.FabricModelKeys={})).PRIVATE="private",F.FABRIC="fabric.",F.OWNEDBY="owned-by",e.IdentityType=void 0,(e.IdentityType||(e.IdentityType={})).X509="X.509";const N="hlf-fabric";class R extends n.JSONSerializer{constructor(){super()}preSerialize(e,t){const r=Object.assign({},e);let a;try{a=n.getMetadata(e)}catch(e){a=t}if(!a)throw new d.SerializationError("Could not find metadata for "+e.constructor.name);return r[n.ModelKeys.ANCHOR]=a,r}deserialize(e){const t=JSON.parse(e),r=t[n.ModelKeys.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return n.Model.build(t,r)}serialize(e,t){return JSON.stringify(this.preSerialize(e,t))}}class k extends a.CouchDBAdapter{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new R}static{this.log=s.Logging.for(k)}get log(){return k.log}constructor(e,t){super(e,N,t),this.serializer=k.serializer}decode(e){return k.decoder.decode(e)}repository(){return I}async createAll(e,t,r,a){const i=this.log.for(this.createAll);if(t.length!==r.length)throw new d.InternalError(`Ids and models must have the same length: ${t.length} != ${r.length}`);i.info(`adding ${t.length} entries to ${e} table`),i.verbose("pks: "+t);const n=await this.submitTransaction(d.BulkCrudOperationKeys.CREATE_ALL,[t,r.map(t=>this.serializer.serialize(t,e))],a);try{return JSON.parse(this.decode(n)).map(e=>JSON.parse(e))}catch(e){throw new d.SerializationError(e)}}async readAll(e,t){const r=this.log.for(this.readAll);r.info(`reading ${t.length} entries to ${e} table`),r.verbose("pks: "+t);const a=await this.submitTransaction(d.BulkCrudOperationKeys.READ_ALL,[t]);try{return JSON.parse(this.decode(a)).map(e=>JSON.parse(e))}catch(e){throw new d.SerializationError(e)}}async updateAll(e,t,r,a){const i=this.log.for(this.updateAll);if(t.length!==r.length)throw new d.InternalError(`Ids and models must have the same length: ${t.length} != ${r.length}`);i.info(`updating ${t.length} entries to ${e} table`),i.verbose("pks: "+t);const n=await this.submitTransaction(d.BulkCrudOperationKeys.UPDATE_ALL,[t,r.map(t=>this.serializer.serialize(t,e))],a);try{return JSON.parse(this.decode(n)).map(e=>JSON.parse(e))}catch(e){throw new d.SerializationError(e)}}async deleteAll(e,t){const r=this.log.for(this.deleteAll);r.info(`deleting ${t.length} entries to ${e} table`),r.verbose("pks: "+t);const a=await this.submitTransaction(d.BulkCrudOperationKeys.DELETE_ALL,[t]);try{return JSON.parse(this.decode(a)).map(e=>JSON.parse(e))}catch(e){throw new d.SerializationError(e)}}prepare(e,r){const a=this.log.for(this.prepare),i=d.modelToTransient(e);return e[t.PersistenceKeys.METADATA]&&(a.silly("Passing along persistence metadata for "+e[t.PersistenceKeys.METADATA]),Object.defineProperty(i.model,t.PersistenceKeys.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[t.PersistenceKeys.METADATA]})),{record:i.model,id:e[r],transient:i.transient}}revert(e,r,a,i,s){const o=this.log.for(this.revert),c={};c[a]=i;const l="string"==typeof r?n.Model.build(c,r):new r(c);o.silly(`Rebuilding model ${l.constructor.name} id ${i}`);const p=e[t.PersistenceKeys.METADATA],u=Object.keys(l).reduce((t,r)=>(t[r]=e[r],t),l);return s&&(o.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([e,t])=>{if(e in u&&void 0!==u[e])throw new d.InternalError(`Transient property ${e} already exists on model ${l.constructor.name}. should be impossible`);u[e]=t})),p&&(o.silly(`Passing along ${this.flavour} persistence metadata for ${l.constructor.name} id ${i}: ${p}`),Object.defineProperty(u,t.PersistenceKeys.METADATA,{enumerable:!1,configurable:!1,writable:!1,value:p})),u}index(e){throw Error()}async create(e,t,r,a){const i=this.log.for(this.create);i.verbose(`adding entry to ${e} table`),i.debug("pk: "+t);const n=await this.submitTransaction(d.OperationKeys.CREATE,[this.serializer.serialize(r,e)],a);return this.serializer.deserialize(this.decode(n))}async read(e,t){const r=this.log.for(this.read);r.verbose(`reading entry from ${e} table`),r.debug("pk: "+t);const a=await this.evaluateTransaction(d.OperationKeys.READ,[t.toString()]);return this.serializer.deserialize(this.decode(a))}async update(e,t,r,a){const i=this.log.for(this.update);i.verbose(`updating entry to ${e} table`),i.debug("pk: "+t);const n=await this.submitTransaction(d.OperationKeys.UPDATE,[this.serializer.serialize(r,e)],a);return this.serializer.deserialize(this.decode(n))}async delete(e,t){const r=this.log.for(this.delete);r.verbose(`deleting entry from ${e} table`),r.debug("pk: "+t);const a=await this.submitTransaction(d.OperationKeys.DELETE,[e,t]);return this.serializer.deserialize(this.decode(a))}async raw(e,t){const r=this.log.for(this.raw);let a,i,s;r.info("Performing raw query on table"),r.debug("processing raw input for query: "+JSON.stringify(e));try{a=JSON.stringify(e)}catch(e){throw new d.SerializationError("Failed to process raw input for query: "+e)}try{i=await this.evaluateTransaction("query",[a])}catch(e){throw this.parseError(e)}try{s=JSON.parse(this.decode(i))}catch(e){throw new d.SerializationError("Failed to process result: "+e)}if(Array.isArray(s)){if(!s.length)return s;const e=s[0];return n.Model.isModel(e)?s.map(e=>n.Model.build(e)):s}return o=s,n.Model.isModel(o)?n.Model.build(o):o;var o}getClient(){return this._client||(this._client=k.getClient(this.config)),this._client}async Gateway(){return k.getGateway(this.config,this.client)}async Contract(){return k.getContract(await this.Gateway(),this.config)}async transaction(e,t=!0,r,a,i){const n=this.log.for(this.transaction),s=await this.Gateway();try{const s=await this.Contract();n.verbose(`${t?"Submit":"Evaluate"}ting transaction ${this.config.contractName}.${e}`),n.debug("args: "+(r?.map(e=>e.toString()).join("\n")||"none"));const o=t?s.submit:s.evaluate;i=i?.length?i:void 0;const c={arguments:r||[],transientData:a};return await o.call(s,e,c)}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`),s.close()}}parseError(e,t){return k.parseError(e,t)}async submitTransaction(e,t,r,a){return this.transaction(e,!0,t,r,a)}async evaluateTransaction(e,t,r,a){return this.transaction(e,!1,t,r,a)}async close(){this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static getContract(e,t){const r=this.log.for(this.getContract),a=this.getNetwork(e,t.channel);let i;try{r.debug(`Retrieving chaincode ${t.chaincodeName} contract ${t.contractName} from network ${t.channel}`),i=a.getContract(t.chaincodeName,t.contractName)}catch(e){throw this.parseError(e)}return i}static getNetwork(e,t){const r=this.log.for(this.getNetwork);let a;try{r.debug("Connecting to channel "+t),a=e.getNetwork(t)}catch(e){throw this.parseError(e)}return a}static async getGateway(e,t){return await this.getConnection(t||await this.getClient(e),e)}static getClient(e){const t=this.log.for(this.getClient);t.debug("generating TLS credentials for msp "+e.mspId);const r=b.credentials.createSsl("string"==typeof e.tlsCert?Buffer.from(e.tlsCert):e.tlsCert);return t.debug("generating Gateway Client for url "+e.peerEndpoint),new i.Client(e.peerEndpoint,r)}static async getConnection(e,t){const r=this.log.for(this.getConnection);r.debug(`Retrieving Peer Identity for ${t.mspId} under ${t.certCertOrDirectoryPath}`);const a=await E(t.mspId,t.certCertOrDirectoryPath);r.debug("Retrieving signer key from "+t.keyCertOrDirectoryPath);const i={client:e,identity:a,signer:await O(t.keyCertOrDirectoryPath),evaluateOptions:()=>({deadline:Date.now()+5e3}),endorseOptions:()=>({deadline:Date.now()+15e3}),submitOptions:()=>({deadline:Date.now()+5e3}),commitStatusOptions:()=>({deadline:Date.now()+6e4})};return r.debug("Connecting to "+t.mspId),o.connect(i)}Dispatch(){return new k._baseDispatch}static parseError(e,t){return super.parseError(e,t)}}function x(e,t,r){const a=[e,t];return r&&a.push(r),a.join("_")}function D(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]}}r.__decorate([s.debug(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Promise)],k.prototype,"index",null),r.__decorate([s.debug(),t.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object,Object,Object]),r.__metadata("design:returntype",Promise)],k.prototype,"create",null),r.__decorate([s.debug(),t.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object]),r.__metadata("design:returntype",Promise)],k.prototype,"read",null),r.__decorate([s.debug(),t.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object,Object,Object]),r.__metadata("design:returntype",Promise)],k.prototype,"update",null),r.__decorate([s.debug(),t.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object]),r.__metadata("design:returntype",Promise)],k.prototype,"delete",null),r.__decorate([s.debug(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Boolean]),r.__metadata("design:returntype",Promise)],k.prototype,"raw",null),k.decoration(),t.Adapter.setCurrent(N);class P 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 k))throw new t.UnsupportedError("Only FabricClientAdapter can be observed by dispatch");this.adapter=e,this.models=t.Adapter.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`))}async updateObservers(e,t,r){if(this.adapter)try{await this.adapter.refresh(e,t,r.id?r.id:void 0,r)}catch(e){throw new d.InternalError("Failed to refresh dispatch: "+e)}else this.log.verbose(`No adapter observed for dispatch; skipping observer update for ${e}:${t}`)}async handleEvents(){if(!this.listeningStack)throw new d.InternalError('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new d.InternalError("No adapter found. should be impossible");const e=this.log.for(this.handleEvents);e.info(`Listening for incoming events on chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}"...`);try{for await(const r of this.listeningStack){const{table:a,event:i,owner:s}=D(r.eventName);if(s&&s!==this.adapter.config?.mspId)continue;const o=this.parsePayload(r.payload);try{await this.updateObservers(a||t.Repository.table(n.Model.get(this.models[0].name)),i,o)}catch(t){e.error(`Failed update observables for table ${a} event ${i} id: ${o.id}: ${t}`)}}}catch(t){e.error(`Failed to read event for chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}": ${t}`),await this.close()}}async initialize(){if(!this.adapter)throw new d.InternalError("No adapter or config observed for dispatch");const e=(await k.getGateway(this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new d.InternalError("No adapter observed for dispatch");this.listeningStack=await e.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents()}}k&&(k._baseDispatch=P);let $=class extends t.BaseModel{constructor(e){super(e),this.id=void 0,this.certificate=void 0,this.rootCertificate=void 0,this.privateKey=void 0}};r.__decorate([t.pk(),r.__metadata("design:type",String)],$.prototype,"id",void 0),r.__decorate([n.required(),r.__metadata("design:type",String)],$.prototype,"certificate",void 0),r.__decorate([n.required(),r.__metadata("design:type",String)],$.prototype,"rootCertificate",void 0),r.__decorate([n.required(),r.__metadata("design:type",String)],$.prototype,"privateKey",void 0),$=r.__decorate([n.model(),r.__metadata("design:paramtypes",[Object])],$),e.Identity=class extends t.BaseModel{constructor(t){super(t),this.id=void 0,this.credentials=void 0,this.mspId=void 0,this.type=e.IdentityType.X509}},r.__decorate([t.pk(),r.__metadata("design:type",String)],e.Identity.prototype,"id",void 0),r.__decorate([t.oneToOne($,{update:t.Cascade.CASCADE,delete:t.Cascade.CASCADE}),r.__metadata("design:type",$)],e.Identity.prototype,"credentials",void 0),r.__decorate([n.required(),r.__metadata("design:type",String)],e.Identity.prototype,"mspId",void 0),r.__decorate([n.required(),r.__metadata("design:type",String)],e.Identity.prototype,"type",void 0),e.Identity=r.__decorate([n.model(),r.__metadata("design:paramtypes",[Object])],e.Identity);class z{static{this.logger=s.Logging.for(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:t}=await c.normalizeImport(import("fs"));return await t.readFile(e)})(e)}static async getCAUser(e,t,r,a){this.logger.debug(n.stringFormat("Creating CA {0} user {1} with certificate {2}",a,e,r));const i=new l.User(e),s=l.User.newCryptoSuite();i.setCryptoSuite(s);const o=s.createKeyFromRaw(t);return await i.setEnrollment(o,r,a),i}static async getIdentity(e,t){return{mspId:e,credentials:await this.contentOfLoadFile(t,async e=>{const{promises:t}=await c.normalizeImport(import("fs")),r=await this.getFirstDirFileName(e);return await t.readFile(r)})}}static async getFirstDirFileName(e){const{promises:t}=await c.normalizeImport(import("fs")),{join:r}=await c.normalizeImport(import("path"));return r(e,(await t.readdir(e))[0])}static async getFirstDirFileNameContent(e){const{promises:t}=await c.normalizeImport(import("fs")),{join:r}=await c.normalizeImport(import("path")),a=await t.readdir(e);return(await t.readFile(r(e,a[0]))).toString()}static async getFileContent(e){const{promises:t}=await c.normalizeImport(import("fs"));return(await t.readFile(e)).toString()}static async getSigner(e){const t=await this.contentOfLoadFile(e,async e=>{const{promises:t}=await c.normalizeImport(import("fs")),r=await this.getFirstDirFileName(e);return await t.readFile(r)}),r=await this.extractPrivateKey(t),a=r[Object.getOwnPropertySymbols(r)[0]];return o.signers.newPrivateKeySigner(a)}static async extractPrivateKey(e){let t;if(globalThis.window&&globalThis.window.Crypto)t=globalThis.Crypto.subtle;else{const e=await c.normalizeImport(import("crypto"));t=e.subtle||e.webcrypto.subtle}if(!t)throw Error("Could not load SubtleCrypto module");const r=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,a=e.length;a>t;t++)r[t]=e.charCodeAt(t);return t})(Buffer.from(r,"base64").toString("binary"));return await t.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}}const K=new h.Crypto;var B,M;v.cryptoProvider.set(K),(e=>{e.BASE2="01",e.BASE8="01234567",e.BASE11="0123456789a",e.BASE16="0123456789abcdef",e.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",e.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",e.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",e.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",e.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",e.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~"})(B||(B={})),(e=>{e.HASH="SHA-256",e[e.ITERATIONS=1e3]="ITERATIONS",e[e.KEYLENGTH=48]="KEYLENGTH",e[e.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",e[e.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",e.ALGORYTHM="AES-GCM",e.KEY_ALGORYTHM="PBKDF2"})(M||(M={}));class j{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),a=r.charCodeAt(0);if(255!==this.baseMap[a])throw Error(r+" is ambiguous");this.baseMap[a]=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,a=0;const i=e.length;for(;a!==i&&0===e[a];)a++,t++;const n=(i-a)*this.iFactor+1>>>0,s=new Uint8Array(n);for(;a!==i;){let t=e[a],i=0;for(let e=n-1;(0!==t||r>i)&&-1!==e;e--,i++)t+=256*s[e]>>>0,s[e]=t%this.base>>>0,t=t/this.base>>>0;if(0!==t)throw Error("Non-zero carry");r=i,a++}let o=n-r;for(;o!==n&&0===s[o];)o++;let c=this.leader.repeat(t);for(;n>o;++o)c+=this.alphabet.charAt(s[o]);return c}decodeUnsafe(e){if(0===e.length)return new Uint8Array(0);let t=0,r=0,a=0;for(;e[t]===this.leader;)r++,t++;const i=(e.length-t)*this.factor+1>>>0,n=new Uint8Array(i);for(;e[t];){let r=this.baseMap[e.charCodeAt(t)];if(255===r)return;let s=0;for(let e=i-1;(0!==r||a>s)&&-1!==e;e--,s++)r+=this.base*n[e]>>>0,n[e]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");a=s,t++}let s=i-a;for(;s!==i&&0===n[s];)s++;const o=new Uint8Array(r+(i-s));let c=r;for(;s!==i;)o[c++]=n[s++];return o}decode(e){const t=this.decodeUnsafe(e);if(t)return t;throw Error("Non-base"+this.base+" character")}}class L{static{this.b58encoder=new j(B.BASE58)}static{this.logger=s.Logging.for(L.name)}constructor(){}static fabricIdFromCertificate(e){this.logger.debug(n.stringFormat("Parsing certificate: {0}",e));const t=new v.X509Certificate(e),{subject:r,issuer:a}=t;return this.logger.debug(n.stringFormat("Certificate parsed with subject {0} and issuer {1}",r,a)),`x509::/${r.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,a=e.length;a>t;t++)r[t]=e.charCodeAt(t);return t}static async extractKey(e,t,r){const a=K.subtle,i=t.toString("utf8").replace(RegExp(`-----BEGIN (${e.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${e.toUpperCase()} KEY|CERTIFICATE)-----`),""),n=Buffer.from(i,"base64").toString("binary"),s=this.stringToArrayBuffer(n);return await a.importKey("pkcs8",s,{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),a=await K.subtle.sign({name:"ECDSA",hash:"SHA-256"},r,t);return Array.from(new Uint8Array(a)).map(e=>e.toString(16).padStart(2,"0")).join("")}static async verify(e,t,r){const a=new v.X509Certificate(e),i=await a.publicKey.export();return t="string"==typeof t?Buffer.from(t,"hex"):t,r="string"==typeof r?Buffer.from(r):r,K.subtle.verify({name:"ECDSA",hash:"SHA-256"},i,t,r)}static async encrypt(e,t){const r=new v.X509Certificate(e),a=await r.publicKey.export();t="string"==typeof t?Buffer.from(t):t;const i=await this.getSubtleCrypto().encrypt({name:"ECDSA"},a,t);return Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join("")}static getSubtleCrypto(){return s.isBrowser()?globalThis.window.crypto.subtle:K.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(e){const t=new TextEncoder;if(void 0===e){const r=K.randomUUID();e=t.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",e,M.KEY_ALGORYTHM,!1,["deriveBits"]),iv:e}}static async getDerivationKey(e,t){const r=(new TextEncoder).encode(e),a=await this.getSubtleCrypto().digest("SHA-256",r),i={name:M.KEY_ALGORYTHM,hash:M.HASH,salt:a,iterations:M.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(i,t,8*M.KEYLENGTH);return this.getKey(n)}static async getKey(e){const t=e.slice(0,32),r=e.slice(32);return{key:await this.getSubtleCrypto().importKey("raw",t,{name:M.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(e,t){const r=(new TextEncoder).encode(e);return await this.getSubtleCrypto().encrypt({name:M.ALGORYTHM,iv:t.iv},t.key,r)}static async decryptPin(e,t){const r=new TextDecoder,a=await this.getSubtleCrypto().decrypt({name:M.ALGORYTHM,iv:t.iv},t.key,e);return r.decode(a)}}function q(){return function(e,r,a){const i=a.value;return a.value=async function(...e){const a=e[0],n=a.clientIdentity.getID(),s=await this.tokenRepository.selectWithContext(void 0,a),o=await s.execute();if(0==o.length)throw new d.NotFoundError("No tokens avaialble");if(o.length>1)throw new d.NotFoundError("To many token available : "+o.length);if(o[0].owner!=n)throw new t.AuthorizationError(`User not authorized to run ${r} on the token`);return await i.apply(this,e)},a}}async function U(e,t,r,a){const{stub:i}=e,n=(await i.getCreator()).mspid;Object.defineProperty(a,r,{enumerable:!0,writable:!1,configurable:!0,value:n})}function J(t){return n.Model.key(e.FabricModelKeys.FABRIC+t)}function H(t){if(!t)throw Error("Collection name is required");const r=J(e.FabricModelKeys.PRIVATE);return(a,i)=>{const s=i||void 0,o=Reflect.getMetadata(r,a[n.ModelKeys.ANCHOR]||a,s),c=o?.collections||[];n.propMetadata(J(e.FabricModelKeys.PRIVATE),{...!i&&{collections:c?[...new Set([...c,t])]:[t]},isPrivate:!i})(i?a.constructor:a[n.ModelKeys.ANCHOR]||a),i&&(n.propMetadata(J(e.FabricModelKeys.PRIVATE),{collections:c?[...new Set([...c,t])]:[t]})(a,i),d.transient()(a,i))}}const G=/private\s+data\s+matching\s+public\s+hash\s+version\s+is\s+not\s+available/i;function V(t){let r=Reflect.getMetadata(J(e.FabricModelKeys.PRIVATE),t);return r=r||Reflect.getMetadata(J(e.FabricModelKeys.PRIVATE),t.constructor),r}function Y(e){const t=V(e);return!(!t||void 0===t.isPrivate)&&t.isPrivate}function W(t){if(!(e=>!!V(e))(t))return{model:t};const r=d.getAllPropertyDecoratorsRecursive(t,void 0,J(e.FabricModelKeys.PRIVATE)),a=Y(t),i=V(t);let s={model:t,private:void 0};if(s=a?Object.keys(t).reduce((e,r)=>{const a=i.collections;e.private=e.private||{};for(const i of a)try{e.private[i]=e.private[i]||{},e.private[i][r]=t[r]}catch(e){throw new d.SerializationError(`Failed to serialize private property ${r}: ${e}`)}return e},{model:{}}):Object.entries(r).reduce((e,[r,a])=>{const i=a.find(e=>""===e.key);if(i){const a=i.props.collections;e.private=e.private||{};for(const i of a)try{e.private[i]=e.private[i]||{},e.private[i][r]=t[r]}catch(e){throw new d.SerializationError(`Failed to serialize private property ${r}: ${e}`)}}else e.model=e.model||{},e.model[r]=t[r];return e},{}),s.model=s.model||{},s.model=n.Model.build(s.model,t.constructor.name),s.private){const e=Object.keys(s.private);for(const r of e)s.private[r]=n.Model.build(s.private[r],t.constructor.name)}return s}class X extends d.InternalError{constructor(e){super(e,X.name)}}class Q extends d.InternalError{constructor(e){super(e,Q.name)}}class Z extends d.InternalError{constructor(e){super(e,Z.name)}}class ee extends t.AuthorizationError{constructor(e){super(e,ee.name)}}class te extends d.InternalError{constructor(e){super(e,te.name,500)}}class re extends d.BaseError{constructor(e="private data matching public hash version is not available ..."){super(re.name,e,403)}}class ae extends d.BaseError{constructor(e){super(ae.name,e,409)}}class ie{constructor(){}get log(){return this._log||(this._log=s.Logging.for(this.constructor.name)),this._log}static get log(){return ie._log||(ie._log=s.Logging.get()),ie._log}}var ne,se;e.HFCAIdentityType=void 0,(ne=e.HFCAIdentityType||(e.HFCAIdentityType={})).PEER="peer",ne.ORDERER="orderer",ne.CLIENT="client",ne.USER="user",ne.ADMIN="admin",e.HFCAIdentityAttributes=void 0,(se=e.HFCAIdentityAttributes||(e.HFCAIdentityAttributes={})).HFREGISTRARROLES="hf.Registrar.Roles",se.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",se.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",se.HFINTERMEDIATECA="hf.IntermediateCA",se.HFREVOKER="hf.Revoker",se.HFAFFILIATIONMGR="hf.AffiliationMgr",se.HFGENCRL="hf.GenCRL";class oe extends ie{constructor(e){super(),this.caConfig=e}async User(){if(this.user)return this.user;const{caName:e,caCert:t,caKey:r,url:a}=this.caConfig,i=this.log.for(this.User);i.debug(`Creating CA user for ${e} at ${a}`),i.debug("Retrieving CA certificate from "+t);const n=await z.getFirstDirFileNameContent(t);i.debug("Retrieving CA key from "+r);const s=await z.getFirstDirFileNameContent(r);return i.debug("Loading Admin user for ca "+e),this.user=await z.getCAUser("admin",s,n,e),this.user}async CA(){if(this.ca)return this.ca;const e=this.log.for(this.CA),{url:t,tls:r,caName:a}=this.caConfig;let{trustedRoots:i,verify:n}=r;n=!1;const s=i[0];e.debug(`Retrieving CA certificate from ${s}. cwd: ${process.cwd()}`);const o=await z.getFileContent(s);return e.debug(`Creating CA Client for CA ${a} under ${t}`),this.ca=new _.default(t,{trustedRoots:Buffer.from(o),verify:n},a),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(),a=await this.User(),i=this.log.for(this.getCertificates);i.debug(`Retrieving certificates${e?" for "+e.id:""} for CA ${this.caConfig.caName}`);const n=(await r.getCertificates(e||{},a)).result;return i.debug(`Found ${n.certs.length} certificates: ${JSON.stringify(n)}`),t?n.certs.map(e=>e.PEM):n}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 ee(e);const[,a,i]=r;switch(a){case"74":case"71":return new d.ConflictError(i);case"20":return new t.AuthorizationError(i);default:return new ee(i)}}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 d.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new d.NotFoundError(`Couldn't find enrollment with id ${e}: ${a.errors.join("\n")}`);return a.result}async register(e,t=!1,r="",a,i,n){let s;const o=this.log.for(this.register);try{const{userName:c,password:l}=e,d=await this.CA(),p=await this.User(),u={enrollmentID:c,enrollmentSecret:l,affiliation:r,userRole:a,attrs:i,maxEnrollments:n};s=await d.register(u,p),o.info(`Registration for ${c} created with user type ${a??"Undefined Role"} ${t?"as super user":""}`)}catch(e){throw this.parseError(e)}return s}static identityFromEnrollment(t,r){const{certificate:a,key:i,rootCertificate:n}=t,s=this.log.for(this.identityFromEnrollment);s.debug(`Generating Identity from certificate ${a} in msp ${r}`);const o=L.fabricIdFromCertificate(a),c=L.encode(o);s.debug(`Identity ${o} and encodedId ${c}`);const l=new Date;return new e.Identity({id:c,credentials:{id:c,certificate:a,privateKey:i.toBytes(),rootCertificate:n,createdOn:l,updatedOn:l},mspId:r,createdOn:l,updatedOn:l})}async enroll(e,t){let r;const a=this.log.for(this.enroll);try{const i=await this.CA();a.debug("Enrolling "+e);const n=await i.enroll({enrollmentID:e,enrollmentSecret:t});r=oe.identityFromEnrollment(n,this.caConfig.caName),a.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="",a,i,n){const s=await this.register(e,t,r,a,i,n),{userName:o}=e;return this.enroll(o,s)}async revoke(e){const t=await this.CA(),r=await this.User(),a=await this.read(e);if(!a)throw new d.NotFoundError("Could not find enrollment with id "+e);let i;try{i=await t.revoke({enrollmentID:a.id,reason:"User Deletation"},r)}catch(t){throw new d.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!i.success)throw new d.InternalError(`Could not revoke enrollment with id ${e}: ${i.errors.join("\n")}`);return i}}let ce=class extends t.BaseModel{constructor(e){super(e)}};r.__decorate([t.pk({type:"String"}),r.__metadata("design:type",String)],ce.prototype,"name",void 0),r.__decorate([t.column(),n.required(),r.__metadata("design:type",String)],ce.prototype,"owner",void 0),r.__decorate([t.column(),n.required(),r.__metadata("design:type",String)],ce.prototype,"symbol",void 0),r.__decorate([t.column(),n.required(),r.__metadata("design:type",Number)],ce.prototype,"decimals",void 0),ce=r.__decorate([t.table("erc20_tokens"),n.model(),r.__metadata("design:paramtypes",[Object])],ce);let le=class extends t.BaseModel{constructor(e){super(e)}};r.__decorate([t.pk({type:"String"}),r.__metadata("design:type",String)],le.prototype,"id",void 0),r.__decorate([t.column(),n.required(),r.__metadata("design:type",String)],le.prototype,"token",void 0),r.__decorate([t.column(),n.required(),r.__metadata("design:type",Number)],le.prototype,"balance",void 0),r.__decorate([t.column(),r.__metadata("design:type",String)],le.prototype,"captive",void 0),le=r.__decorate([t.table("erc20_wallets"),n.model(),r.__metadata("design:paramtypes",[Object])],le);let de=class extends t.BaseModel{constructor(e){super(e)}};r.__decorate([t.pk({type:"String"}),t.column(),n.required(),r.__metadata("design:type",String)],de.prototype,"owner",void 0),r.__decorate([t.column(),n.required(),r.__metadata("design:type",String)],de.prototype,"spender",void 0),r.__decorate([t.column(),n.required(),r.__metadata("design:type",Number)],de.prototype,"value",void 0),de=r.__decorate([t.table("erc20_allowances"),n.model(),r.__metadata("design:paramtypes",[Object])],de);class pe extends I{static{this.serializer=new R}static{this.decoder=new TextDecoder("utf8")}async updateObservers(e,r,a,...i){if(!this.observerHandler)throw new d.InternalError("ObserverHandler not initialized. Did you register any observables?");let n;this.log.for(this.updateObservers).verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),n=void 0===a?void 0:Array.isArray(a)?a.map(e=>t.Sequence.parseValue(this.pkProps.type,e)):t.Sequence.parseValue(this.pkProps.type,a),await this.observerHandler.updateObservers(this.log,e,r,n,...i)}decode(e){return pe.decoder.decode(e)}get adapter(){return super.adapter}constructor(e){super(e,le),this.serializer=pe.serializer}async tokenName(){const e=await this.adapter.submitTransaction("TokenName");return this.decode(e)}async symbol(){const e=await this.adapter.submitTransaction("Symbol");return this.decode(e)}async decimals(){const e=await this.adapter.submitTransaction("Decimals");return Number(this.decode(e))}async totalSupply(){const e=await this.adapter.submitTransaction("TotalSupply");return Number(this.decode(e))}async balanceOf(e){const t=await this.adapter.submitTransaction("BalanceOf",[e]);return Number(this.decode(t))}async transfer(e,t){const r=await this.adapter.submitTransaction("Transfer",[e,t.toString()]);return"true"===this.decode(r)}async transferFrom(e,t,r){const a=await this.adapter.submitTransaction("TransferFrom",[e,t,r.toString()]);return"true"===this.decode(a)}async approve(e,t){const r=await this.adapter.submitTransaction("Approve",[e,t.toString()]);return"true"===this.decode(r)}async allowance(e,t){const r=await this.adapter.submitTransaction("Allowance",[e,t]);return Number(this.decode(r))}async initialize(e){const t=await this.adapter.submitTransaction("Initialize",[pe.serializer.serialize(e)]);return"true"===this.decode(t)}async checkInitialized(){await this.adapter.submitTransaction("CheckInitialized")}async mint(e){await this.adapter.submitTransaction("Mint",[e.toString()])}async burn(e){await this.adapter.submitTransaction("Burn",[e.toString()])}async burnFrom(e,t){await this.adapter.submitTransaction("BurnFrom",[e,t.toString()])}async clientAccountBalance(){const e=await this.adapter.submitTransaction("ClientAccountBalance");return Number(this.decode(e))}async clientAccountID(){const e=await this.adapter.submitTransaction("ClientAccountID");return this.decode(e)}}class ue extends d.Context{constructor(){super()}get stub(){return this.get("stub")}get timestamp(){return this.stub.getDateTimestamp()}get identity(){try{return this.get("clientIdentity")}catch(e){return this.get("identity")}}get logger(){return this.get("logger")}}class he extends t.ObserverHandler{constructor(e=[d.OperationKeys.CREATE,d.OperationKeys.UPDATE,d.OperationKeys.DELETE,d.BulkCrudOperationKeys.CREATE_ALL,d.BulkCrudOperationKeys.UPDATE_ALL,d.BulkCrudOperationKeys.DELETE_ALL]){super(),this.supportedEvents=e}async updateObservers(e,t,r,a,i,n,s){const{stub:o}=i;if(-1!==this.supportedEvents.indexOf(r)){e.debug(`Emitting ${r} event`);const i=x(t,r,n);o.setEvent(i,Buffer.from(JSON.stringify({id:a})))}else o.setEvent(r,Buffer.from(JSON.stringify(s)))}}let ge=class extends t.BaseModel{constructor(e){super(e)}};r.__decorate([t.pk(),r.__metadata("design:type",String)],ge.prototype,"id",void 0),r.__decorate([n.required(),t.index(),r.__metadata("design:type",Object)],ge.prototype,"current",void 0),ge=r.__decorate([t.table(a.CouchDBKeys.SEQUENCE),n.model(),r.__metadata("design:paramtypes",[Object])],ge);class ye extends t.Sequence{constructor(e,r,a){super(e);for(const e of a||[])H(e)(ge);this.repo=t.Repository.forModel(ge,r.alias)}async current(e){if(!e)throw new te("Context is required");const{name:t,startWith:r}=this.options;try{const r=await this.repo.read(t,e);return this.parse(r.current)}catch(e){if(e instanceof d.NotFoundError){if(void 0===r)throw new d.InternalError("Starting value is not defined for a non existing sequence");try{return this.parse(r)}catch(e){throw new d.InternalError(`Failed to parse initial value for sequence ${r}: ${e}`)}}throw new d.InternalError(`Failed to retrieve current value for sequence ${t}: ${e}`)}}parse(e){return t.Sequence.parseValue(this.options.type,e)}async increment(e,t,r){if(!r)throw new te("Context is required");const{type:a,incrementBy:i,name:n}=this.options;let s;const o=t||i;if(o%i!==0)throw new d.InternalError("Value to increment does not consider the incrementBy setting: "+i);switch(a){case"Number":s=this.parse(e)+o;break;case"BigInt":s=this.parse(e)+BigInt(o);break;default:throw new d.InternalError("Should never happen")}let c;try{c=await this.repo.update(new ge({id:n,current:s}),r)}catch(e){if(!(e instanceof d.NotFoundError))throw e;c=await this.repo.create(new ge({id:n,current:s}),r)}return c.current}async next(e){if(!e)throw new te("Context is required");const t=await this.current(e);return this.increment(t,void 0,e)}async range(e,t){if(!t)throw new te("Context is required");const r=await this.current(t),a=this.parse(this.options.incrementBy),i=await this.increment(r,this.parse(e)*a,t),n=[];for(let t=1;e>=t;t++)n.push(r+a*this.parse(t));if(n[n.length-1]!==i)throw new d.InternalError("Miscalculation of range");return n}}class fe extends t.Repository{constructor(e,t,r){super(e,t),this.trackedEvents=r}logFor(e){return s.Logging.for(fe,{},e)}async create(e,...t){const r=t[t.length-1],a=this.logFor(r).for(this.create);a.info("Preparing model: "+JSON.stringify(e));let i,{record:n,id:s,transient:o}=this.adapter.prepare(e,this.pk,this.tableName,...t);return a.info("Creating model: "+JSON.stringify(e)),n=await this.adapter.create(this.tableName,s,n,...t),t.length&&(i=t[t.length-1]),a.info("Reverting model: "+JSON.stringify(e)),this.adapter.revert(n,this.class,this.pk,s,i&&i.get("rebuildWithTransient")?o:void 0)}async read(e,...t){const r=await this.adapter.read(this.tableName,e,new this.class,...t);return this.adapter.revert(r,this.class,this.pk,e)}async delete(e,...t){const r=await this.adapter.delete(this.tableName,e,new this.class,...t);return this.adapter.revert(r,this.class,this.pk,e)}async update(e,...t){const r=t[t.length-1],a=this.logFor(r).for(this.update);a.info("Preparing model: "+JSON.stringify(e));let i,{record:n,id:s,transient:o}=this.adapter.prepare(e,this.pk,this.tableName,...t);return a.info("Updating model: "+JSON.stringify(e)),n=await this.adapter.update(this.tableName,s,n,...t),t.length&&(i=t[t.length-1]),a.info("Reverting model: "+JSON.stringify(e)),this.adapter.revert(n,this.class,this.pk,s,i&&i.get("rebuildWithTransient")?o:void 0)}ObserverHandler(){return new he}async createAll(e,...t){if(!e.length)return e;const r=e.map(e=>this.adapter.prepare(e,this.pk,this.tableName,...t)),a=r.map(e=>e.id);let i=r.map(e=>e.record);const n=r.map(e=>e.transient).filter(e=>!!e);let s;return t.length&&(s=t[t.length-1]),i=await this.adapter.createAll(this.tableName,a,i,...t),i.map((e,t)=>this.adapter.revert(e,this.class,this.pk,a[t],s&&s.get("rebuildWithTransient")?n:void 0))}async updateAll(e,...t){if(!e.length)return e;const r=e.map(e=>this.adapter.prepare(e,this.pk,this.tableName,...t)),a=r.map(e=>e.transient).filter(e=>!!e);let i;return t.length&&(i=t[t.length-1]),(await this.adapter.updateAll(this.tableName,r.map(e=>e.id),r.map(e=>e.record),...t)).map((e,t)=>this.adapter.revert(e,this.class,this.pk,r[t].id,i&&i.get("rebuildWithTransient")?a:void 0))}async raw(e,t,...r){const a=r.pop(),i=await d.Context.args("QUERY",this.class,[a],this.adapter,{});return this.adapter.raw(e,t,new this.class,...i.args)}async updateObservers(e,t,r,a,...i){if(!this.trackedEvents||-1!==this.trackedEvents.indexOf(t))return await super.updateObservers(e,t,r,a,...i)}async selectWithContext(e,t){let r;return t instanceof ue?r.context=t:r=await d.Context.args(d.OperationKeys.CREATE,this.class,[t],this.adapter,this._overrides||{}),e?this.adapter.Statement(r.context).select(e).from(this.class):this.adapter.Statement(r.context).select().from(this.class)}async createAllPrefix(e,...r){const a=r[r.length-1],i=await d.Context.args(d.OperationKeys.CREATE,this.class,r,this.adapter,this._overrides||{});if(!e.length)return[e,...i.args];const n=t.Repository.getSequenceOptions(e[0]);let s=[];n.type?(n.name||(n.name=ye.pk(e[0])),s=await(await this.adapter.Sequence(n)).range(e.length,a)):s=e.map((e,t)=>{if(void 0===e[this.pk])throw new d.InternalError("Primary key is not defined for model in position "+t);return e[this.pk]}),e=await Promise.all(e.map(async(e,t)=>(e=new this.class(e),n.type&&(e[this.pk]=s[t]),await d.enforceDBDecorators(this,i.context,e,d.OperationKeys.CREATE,d.OperationKeys.ON),e)));const o=i.context.get("ignoredValidationProperties")||[],c=(await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...o))))).reduce((e,t,r)=>(t&&(e="string"==typeof e?e+`\n - ${r}: ${t.toString()}`:` - ${r}: ${t.toString()}`),e),void 0);if(c)throw new d.ValidationError(c);return[e,...i.args]}async createPrefix(e,...t){const r=await super.createPrefix(e,...t),a=r[0][this.pk];try{if(await this.read(a+"",...t))throw new d.ConflictError(`Conflict detected while creating model with id: ${a} already exists`)}catch(e){if(404!==e.code)throw e;this.logFor(t[t.length-1]).info(`Record entry with pk ${a} does not exist, creating it now...`)}return r}}class me extends a.CouchDBStatement{constructor(e,t){super(e),this.ctx=t}async raw(e){const t=await this.adapter.raw(e,!0,this.ctx),r=d.findPrimaryKey(new this.fromSelector),a=r.id,i=r.props.type;return this.selectSelector?t:t.map(e=>this.processRecord(e,a,i))}build(){const e={};e[a.CouchDBKeys.TABLE]={},e[a.CouchDBKeys.TABLE]=t.Repository.table(this.fromSelector);const r={selector:e};if(this.selectSelector&&(r.fields=this.selectSelector),this.whereCondition){const e=this.parseCondition(t.Condition.and(this.whereCondition,t.Condition.attribute(a.CouchDBKeys.TABLE).eq(r.selector[a.CouchDBKeys.TABLE]))).selector,i=Object.keys(e);if(1===i.length&&-1!==Object.values(a.CouchDBGroupOperator).indexOf(i[0]))switch(i[0]){case a.CouchDBGroupOperator.AND:e[a.CouchDBGroupOperator.AND]=[...Object.values(e[a.CouchDBGroupOperator.AND]).reduce((e,t)=>{const r=Object.keys(t);if(1!==r.length)throw Error("Too many keys in query selector. should be one");const i=r[0];return i===a.CouchDBGroupOperator.AND?e.push(...t[i]):e.push(t),e},[])],r.selector=e;break;case a.CouchDBGroupOperator.OR:{const t={};t[a.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,i={};i[e]=t,r.sort.push(i),r.selector[e]||(r.selector[e]={},r.selector[e][a.CouchDBOperator.BIGGER]=null)}return this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),r}}class we extends n.JSONSerializer{constructor(){super()}deserialize(e,t){return JSON.parse(e)}serialize(e){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(e)))}preSerialize(e){return Object.assign({},e)}}async function be(e,r,a,i){const s=i[a];if(!s)return;if("object"!=typeof s){const r=t.repositoryFromTypeMetadata(i,a,this.adapter.alias),n=await r.read(s,e);return await t.cacheModelForPopulate(e,i,a,s,n),void(i[a]=s)}r.class="string"==typeof r.class?r.class:r.class().name;const o=n.Model.get(r.class);if(!o)throw new d.InternalError("Could not find model "+r.class);const c=t.Repository.forModel(o,this.adapter.alias),l=await c.create(s,e),p=d.findPrimaryKey(l).id;await t.cacheModelForPopulate(e,i,a,l[p],l),i[a]=l[p]}async function _e(e,r,a,i){const n=i[a];if(!n)return;if(r.cascade.update!==t.Cascade.CASCADE)return;if("object"!=typeof n){const r=t.repositoryFromTypeMetadata(i,a,this.adapter.alias),s=await r.read(n,e);return await t.cacheModelForPopulate(e,i,a,n,s),void(i[a]=n)}const s=await t.createOrUpdate(i[a],e,this.adapter.alias),o=d.findPrimaryKey(s).id;await t.cacheModelForPopulate(e,i,a,s[o],s),i[a]=s[o]}async function ve(e,r,a,i){const s=i[a];if(!s)return;if(r.cascade.update!==t.Cascade.CASCADE)return;const o=t.repositoryFromTypeMetadata(i,a,this.adapter.alias);let c;c=s instanceof n.Model?await o.delete(i[a][o.pk],e):await o.delete(i[a],e),await t.cacheModelForPopulate(e,i,a,c[o.pk],c)}async function Ae(e,r,a,i){const n=i[a];if(!n||!n.length)return;const s=typeof n[0];if(!n.every(e=>typeof e===s))throw new d.InternalError(`Invalid operation. All elements of property ${a} must match the same type.`);const o=new Set([...n]);if("object"!==s){const r=t.repositoryFromTypeMetadata(i,a,this.adapter.alias);for(const n of o){const s=await r.read(n,e);await t.cacheModelForPopulate(e,i,a,n,s)}return void(i[a]=[...o])}const c=d.findPrimaryKey(n[0]).id,l=new Set;for(const r of n){const n=await t.createOrUpdate(r,e,this.adapter.alias);await t.cacheModelForPopulate(e,i,a,n[c],n),l.add(n[c])}i[a]=[...l]}async function Ce(e,r,a,i){if(r.cascade.delete!==t.Cascade.CASCADE)return;const n=i[a];if(!n||!n.length)return;const s=typeof n[0];if(!n.every(e=>typeof e===s))throw new d.InternalError(`Invalid operation. All elements of property ${a} must match the same type.`);const o="object"===s,c=o?t.Repository.forModel(n[0],this.adapter.alias):t.repositoryFromTypeMetadata(i,a,this.adapter.alias),l=new Set([...o?n.map(e=>e[c.pk]):n]);for(const r of l.values()){const n=await c.delete(r,e);await t.cacheModelForPopulate(e,i,a,r,n)}i[a]=[...l]}async function Ee(e,r,a,i){if(!r.populate)return;const n=i[a],s=Array.isArray(n);if(void 0===n||s&&0===n.length)return;const o=await(async(r,a,i,n,s)=>{let o,c;const l=[];for(const p of n){o=t.getPopulateKey(a.constructor.name,i,p);try{c=await r.get(o)}catch(r){const n=t.repositoryFromTypeMetadata(a,i,s);if(!n)throw new d.InternalError("Could not find repo");c=await n.read(p,e)}l.push(c)}return l})(e,i,a,s?n:[n],this.adapter.alias);i[a]=s?o:o[0]}async function Se(e,r,a,i){try{const t=e.get("clientIdentity");i[a]=t.getID()}catch(e){throw new t.UnsupportedError("No User found in context. Please provide a user in the context")}}async function Oe(e,r,a,i){if(!r.type||i[a])return;let n;r.name||(r.name=t.sequenceNameForModel(i,"pk"));try{n=await this.adapter.Sequence(r)}catch(e){throw new d.InternalError(`Failed to instantiate Sequence ${r.name}: ${e}`)}const s=await n.next(e);Object.defineProperty(i,a,{enumerable:!0,writable:!1,configurable:!0,value:s})}class Te extends a.CouchDBAdapter{getClient(){throw new t.UnsupportedError("Client is not supported in Fabric contracts")}static{this.textDecoder=new TextDecoder("utf8")}static{this.serializer=new we}logFor(e){return s.Logging.for(Te,{},e)}repository(){return fe}constructor(e,t){super(e,N,t),this.Context=ue}for(e,...t){return super.for(e,...t)}async create(e,t,r,...a){const{stub:i,logger:n}=a.pop(),s=n.for(this.create);try{s.info(`adding entry to ${e} table with pk ${t}`),r=await this.putState(i,t.toString(),r)}catch(e){throw this.parseError(e)}return r}async read(e,t,...r){const{stub:a,logger:i}=r.pop(),n=i.for(this.read);let s;try{const r=await this.readState(a,e,t.toString());if(1>r.length)throw n.debug(`No record found for id ${t} in ${e} table`),new d.NotFoundError(`No record found for id ${t} in ${e} table`);2>r.length?(n.debug(`No record found for id ${t} in ${e} table`),s=r.pop()):s=this.mergeModels(r)}catch(e){throw this.parseError(e)}return s}async update(e,t,r,...a){const{stub:i,logger:n}=a.pop(),s=n.for(this.update);try{s.info(`updating entry to ${e} table with pk ${t}`),r=await this.putState(i,t.toString(),r)}catch(e){throw this.parseError(e)}return r}async delete(e,t,...r){const a=r.pop(),{stub:i,logger:n}=a,s=n.for(this.delete);let o;r.push(a);try{o=await this.read(e,t,...r),s.verbose(`deleting entry with pk ${t} from ${e} table`),this.deleteState(i,e,t.toString())}catch(e){throw this.parseError(e)}return o}async deleteState(e,t,r,...a){const i=e.createCompositeKey(t,[r+""]);await e.deleteState(i)}async putState(e,t,r,...a){let i;try{i=Buffer.from(Te.serializer.serialize(r))}catch(e){throw new d.SerializationError(`Failed to serialize record with id ${t}: ${e}`)}return await e.putState(t.toString(),i),r}async readState(e,t,r,...a){const i=e.createCompositeKey(t,[r+""]),n=[];let s=await e.getState(i);if(""===s.toString())throw new d.NotFoundError(`Record with id ${r} not found`);try{s=Te.serializer.deserialize(s.toString())}catch(e){throw new d.SerializationError("Failed to parse record: "+e)}return n.push(s),n}async queryResult(e,t,...r){return await e.getQueryResult(JSON.stringify(t))}async queryResultPaginated(e,t,r=250,a,...i){return await e.getQueryResultWithPagination(JSON.stringify(t),r,a?.toString())}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 Te.textDecoder.decode(e)}async flags(e,t,r,a,...i){return Object.assign(await super.flags(e,t,r,...i),{stub:a.stub,identity:a.clientIdentity,logger:this.logFor(a)})}index(e){return Promise.resolve(void 0)}async resultIterator(e,t,r=!1){const a=[];let i=await t.next();for(;!i.done;){if(i.value&&i.value.value.toString()){let t={};if(e.debug(i.value.value.toString("utf8")),r){t.TxId=i.value.txId,t.Timestamp=i.value.timestamp;try{t.Value=JSON.parse(i.value.value.toString("utf8"))}catch(r){e.error(r),t.Value=i.value.value.toString("utf8")}}else try{t=JSON.parse(i.value.value.toString("utf8"))}catch(r){e.error(r),t=i.value.value.toString("utf8")}a.push(t)}i=await t.next()}return e.debug(`Closing iterator after ${a.length} results`),t.close(),a}async raw(e,t,...r){const{stub:a,logger:i}=r.pop(),n=i.for(this.raw),{skip:s,limit:o}=e;let c;o||s?(delete e.limit,delete e.skip,n.debug(`Retrieving paginated iterator: limit: ${o}/ skip: ${s}`),c=(await this.queryResultPaginated(a,e,o||250,s?.toString())).iterator):(n.debug("Retrieving iterator"),c=await this.queryResult(a,e)),n.debug("Iterator acquired");const l=await this.resultIterator(n,c);return n.debug("returning {0} results",""+(Array.isArray(l)?l.length:1)),l}Statement(e){if(!e)throw new te("Context is required");return new me(this,e)}async Sequence(e){return new ye(e,this)}async createAll(e,t,r,...a){if(t.length!==r.length)throw new d.InternalError("Ids and models must have the same length");const{logger:i}=a[a.length-1],n=i.for(this.createAll);return n.info(`Creating ${t.length} entries ${e} table`),n.debug("pks: "+t),Promise.all(t.map(async(t,i)=>this.create(e,t,r[i],...a)))}async updateAll(e,t,r,...a){if(t.length!==r.length)throw new d.InternalError("Ids and models must have the same length");const{logger:i}=a[a.length-1],n=i.for(this.createAll);return n.info(`Updating ${t.length} entries ${e} table`),n.debug("pks: "+t),Promise.all(t.map(async(t,i)=>this.update(e,t,r[i],...a)))}prepare(e,r,...a){const{stub:i,logger:n}=a.pop(),s=a.shift(),o=n.for(this.prepare),c=d.modelToTransient(e),l=Object.entries(c.model).reduce((r,[a,i])=>{if(void 0===i)return r;const n=t.Repository.column(e,a);if(this.isReserved(n))throw new d.InternalError(`Property name ${n} is reserved`);return r[n]=i,r},{});return e[t.PersistenceKeys.METADATA]&&(o.silly("Passing along persistence metadata for "+e[t.PersistenceKeys.METADATA]),Object.defineProperty(l,t.PersistenceKeys.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[t.PersistenceKeys.METADATA]})),o.info(`Preparing record for ${s} table with pk ${e[r]}`),{record:l,id:i.createCompositeKey(s,[e[r]+""]),transient:c.transient}}revert(e,r,a,i,s){const o=this.log.for(this.revert),c={};c[a]=i;const l="string"==typeof r?n.Model.build(c,r):new r(c);o.silly(`Rebuilding model ${l.constructor.name} id ${i}`);const p=e[t.PersistenceKeys.METADATA],u=Object.keys(l).reduce((r,a)=>(r[a]=e[t.Repository.column(r,a)],r),l);return s&&(o.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([e,t])=>{if(e in u&&void 0!==u[e])throw new d.InternalError(`Transient property ${e} already exists on model ${l.constructor.name}. should be impossible`);u[e]=t})),p&&(o.silly(`Passing along ${this.flavour} persistence metadata for ${l.constructor.name} id ${i}: ${p}`),Object.defineProperty(u,t.PersistenceKeys.METADATA,{enumerable:!1,configurable:!1,writable:!1,value:p})),u}createPrefix(e,t,r,...i){const n=i.pop(),s={};return s[a.CouchDBKeys.TABLE]=e,Object.assign(s,r),[e,t,s,n]}updatePrefix(e,t,r,...i){const n=i.pop(),s={};return s[a.CouchDBKeys.TABLE]=e,Object.assign(s,r),[e,t,s,n]}createAllPrefix(e,t,r,...i){if(t.length!==r.length)throw new d.InternalError("Ids and models must have the same length");const n=i.pop(),s=t.map((t,i)=>{const n={};return n[a.CouchDBKeys.TABLE]=e,Object.assign(n,r[i]),n});return[e,t,s,n]}updateAllPrefix(e,t,r,...i){if(t.length!==r.length)throw new d.InternalError("Ids and models must have the same length");const n=i.pop(),s=t.map((t,i)=>{const n={};return n[a.CouchDBKeys.TABLE]=e,Object.assign(n,r[i]),n});return[e,t,s,n]}static decoration(){super.decoration();const e=t.Repository.key(t.PersistenceKeys.CREATED_BY),r=t.Repository.key(t.PersistenceKeys.UPDATED_BY);n.Decoration.flavouredAs(N).for(e).define(d.onCreate(Se),n.propMetadata(e,{})).apply(),n.Decoration.flavouredAs(N).for(r).define(d.onCreateUpdate(Se),n.propMetadata(r,{})).apply();const a=t.Repository.key(d.DBKeys.ID);n.Decoration.flavouredAs(N).for(a).define(t.index([t.OrderDirection.ASC,t.OrderDirection.DSC]),n.required(),d.readonly(),n.propMetadata(a,t.NumericSequence),d.onCreate(Oe,t.NumericSequence)).apply();const i=t.Adapter.key(t.PersistenceKeys.COLUMN);n.Decoration.flavouredAs(N).for(i).extend(y.Property()).apply();const s=t.Adapter.key(t.PersistenceKeys.TABLE);n.Decoration.flavouredAs(N).for(s).extend(e=>y.Object()(e)).apply();const o=t.Repository.key(t.PersistenceKeys.ONE_TO_ONE);n.Decoration.flavouredAs(N).for(o).define({decorator:(e,r,a,i,s)=>{const c={class:e.name?e.name:e,cascade:r,populate:a};return i&&(c.joinTable=i),s&&(c.name=s),g.apply(n.prop(t.PersistenceKeys.RELATIONS),n.type([e.name?e.name:e,String.name,Number.name,BigInt.name]),d.onCreate(be,c),d.onUpdate(_e,c),d.onDelete(ve,c),d.afterAny(Ee,c),n.propMetadata(o,c))}}).apply();const c=t.Repository.key(t.PersistenceKeys.ONE_TO_MANY);n.Decoration.for(c).define({decorator:(e,r,a,i,s)=>{const o={class:e.name?e.name:e,cascade:r,populate:a};return i&&(o.joinTable=i),s&&(o.name=s),g.apply(n.prop(t.PersistenceKeys.RELATIONS),n.list([e,String,Number]),d.onCreate(Ae,o),d.onUpdate(t.oneToManyOnUpdate,o),d.onDelete(Ce,o),d.afterAny(Ee,o),n.propMetadata(c,o))}}).apply()}}Te.decoration(),t.Adapter.setCurrent(N);class Ie extends n.JSONSerializer{constructor(){super()}deserialize(e){return super.deserialize(e)}serialize(e){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(e)))}}class Fe extends Te{constructor(e,t,r){super(e,t),this.collections=r,this.collections=r||[]}async Sequence(e){return new ye(e,this,this.collections)}async read(e,t,r,...a){const{stub:i,logger:n}=a.pop(),s=n.for(this.read);let o;try{const a=await this.readState(i,e,t.toString(),r);if(1>a.length)throw s.debug(`No record found for id ${t} in ${e} table`),new d.NotFoundError(`No record found for id ${t} in ${e} table`);2>a.length?(s.debug(`No record found for id ${t} in ${e} table`),o=a.pop()):o=this.mergeModels(a)}catch(e){throw this.parseError(e)}return o}async delete(e,t,r,...a){const i=a.pop(),{stub:n,logger:s}=i,o=s.for(this.delete);let c;a.push(i);try{c=await this.read(e,t,r,...a),o.verbose(`deleting entry with pk ${t} from ${e} table`),this.deleteState(n,e,t.toString(),r)}catch(e){throw this.parseError(e)}return c}prepare(e,r,...a){const{stub:i,logger:n}=a.pop(),s=a.shift(),o=n.for(this.prepare),c=((e,r)=>{const a=d.modelToTransient(r),i=W(r),n=r=>Object.entries(r).reduce((a,[i,n])=>{if(void 0===n)return a;const s=t.Repository.column(r,i);if(e.isReserved(s))throw new d.InternalError(`Property name ${s} is reserved`);return a[s]=n,a},{});if(i.private){const e=Object.keys(i.private);for(const t of e)i.private[t]=n(i.private[t])}return{model:a.model,transient:a.transient,privateData:i.private,result:n(a.model)}})(this,e);return o.info(`Preparing record for ${s} table with pk ${e[r]}`),{record:c.privateData,id:i.createCompositeKey(s,[e[r]+""]),transient:c.transient}}createPrefix(e,t,r,...i){const n=i.pop(),s=Object.keys(r);for(const t of s)r[t][a.CouchDBKeys.TABLE]=e;return[e,t,r,n]}updatePrefix(e,t,r,...i){const n=i.pop(),s=Object.keys(r);for(const t of s)r[t][a.CouchDBKeys.TABLE]=e;return[e,t,r,n]}async putState(e,t,r,...a){const i=Object.keys(r);let n,s={};for(const a of i){s=r[a];try{n=Buffer.from(Te.serializer.serialize(r[a]))}catch(e){throw new d.SerializationError(`Failed to serialize record with id ${t}: ${e}`)}await e.putPrivateData(a,t.toString(),n)}return s}async readState(e,t,r,a,...i){const n=e.createCompositeKey(t,[r+""]),s=W(a),o=Object.keys(s.private),c=[];for(const t of o)try{let a=await e.getPrivateData(t,n);if(""===a.toString())throw new d.NotFoundError(`Entry with id ${r} doesn't exist...`);try{a=Te.serializer.deserialize(a.toString())}catch(e){throw new d.SerializationError("Failed to parse private data: "+e)}c.push(a)}catch(e){if(G.test(e.message))throw new re(e);throw e}return c}async deleteState(e,t,r,a,...i){const n=e.createCompositeKey(t,[r+""]),s=W(a),o=Object.keys(s.private);for(const t of o)await e.deletePrivateData(t,n)}async queryResult(e,t,r){const a=W(r).private,i=Object.keys(a)[0]||"";return(await e.getPrivateDataQueryResult(i,JSON.stringify(t))).iterator}async queryResultPaginated(e,t,r=250,a=void 0,i){const n=W(i).private,s=Object.keys(n)[0]||"",o=await e.getPrivateDataQueryResult(s,JSON.stringify(t)),c=[];let l=0,d=!a,p=null;for(;;){const e=await o.next();if(e.value&&e.value.value.toString()){const t=e.value.key,i=e.value.value.toString("utf8");if(!d){t===a?.toString()&&(d=!0);continue}if(c.push({Key:t,Record:JSON.parse(i)}),p=t,l++,l>=r)return await o.close(),{iterator:c,metadata:{fetchedRecordsCount:c.length,bookmark:p}}}if(e.done)return await o.close(),{iterator:c,metadata:{fetchedRecordsCount:c.length,bookmark:""}}}}async raw(e,t,...r){const{stub:a,logger:i}=r.pop(),n=i.for(this.raw),{skip:s,limit:o}=e,c=r.shift();let l;o||s?(delete e.limit,delete e.skip,n.debug(`Retrieving paginated iterator: limit: ${o}/ skip: ${s}`),l=(await this.queryResultPaginated(a,e,o||250,s?.toString(),c)).iterator):(n.debug("Retrieving iterator"),l=await this.queryResult(a,e,c)),n.debug("Iterator acquired");const d=await this.resultIterator(n,l);return n.debug("returning {0} results",""+(Array.isArray(d)?d.length:1)),d}}class Ne extends y.Contract{static{this.serializer=new Ie}constructor(e,r){super(e),this.clazz=r,this.initialized=!1,Ne.adapter=this.getAdapter(r),this.repo=t.Repository.forModel(r,Ne.adapter.alias)}getAdapter(e){const t=new e;if(Y(t)){const e=W(t),r=Object.keys(e.private);return new Fe(void 0,"fabric-private-data-adapter",r)}return new Te(void 0,"fabric-public-data-adapter")}logFor(e){return s.Logging.for(Ne.name,{},e)}async create(e,t,...r){const a=this.logFor(e).for(this.create);"string"==typeof t&&(t=this.deserialize(t)),a.info("Creating model: "+JSON.stringify(t));const i=this.getTransientData(e);return a.info("Merging transient data..."),t=this.repo.merge(t,i),this.repo.create(t,e,...r)}async read(e,t,...r){return this.logFor(e).for(this.read).info(`reading entry with pk ${t} `),this.repo.read(t,e,...r)}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,t,...r){const a=this.logFor(e).for(this.update);"string"==typeof t&&(t=this.deserialize(t)),a.info("Updating model: "+JSON.stringify(t));const i=this.getTransientData(e);return a.info("Merging transient data..."),t=this.repo.merge(t,i),this.repo.update(t,e,...r)}async delete(e,t,...r){return this.logFor(e).for(this.delete).info(`deleting entry with pk ${t} `),this.repo.delete(t+"",e,...r)}async deleteAll(e,t,...r){return"string"==typeof t&&(t=JSON.parse(t)),this.repo.deleteAll(t,e,...r)}async readAll(e,t,...r){return"string"==typeof t&&(t=JSON.parse(t)),this.repo.readAll(t,e,...r)}async updateAll(e,t,...r){const a=this.logFor(e).for(this.updateAll);return"string"==typeof t&&(t=JSON.parse(t).map(e=>this.deserialize(e)).map(e=>new this.clazz(e))),a.info(`updating ${t.length} entries to the table`),this.repo.updateAll(t,e,...r)}async raw(e,t,r,...a){return"string"==typeof t&&(t=JSON.parse(t)),this.repo.raw(t,r,e,...a)}serialize(e){return Ne.serializer.serialize(e)}deserialize(e){return Ne.serializer.deserialize(e)}async init(e){const t=this.logFor(e).for(this.init);t.info("Running contract initialization..."),this.initialized=!0,t.info("Contract initialization completed.")}async healthcheck(e){return this.logFor(e).for(this.healthcheck).info(`Running Healthcheck: ${this.initialized}...`),{healthcheck:this.initialized}}async createAll(e,t,...r){const a=this.logFor(e).for(this.createAll);return"string"==typeof t&&(t=JSON.parse(t).map(e=>this.deserialize(e)).map(e=>new this.clazz(e))),a.info(`adding ${t.length} entries to the table`),this.repo.createAll(t,e,...r)}}class Re extends Ne{constructor(e,t){super(e,t)}logFor(e){return s.Logging.for(Re,{},e)}async create(e,t){const r=this.logFor(e).for(this.create);r.info("Creating model: "+t);const a=this.deserialize(t);return r.info("Model deserialized: "+JSON.stringify(a)),this.serialize(await super.create(e,a))}async read(e,t){return this.logFor(e).for(this.read).info("Reading id: "+t),this.serialize(await super.read(e,t))}async update(e,t){return this.logFor(e).for(this.update).info("Updating model: "+t),this.serialize(await super.update(e,t))}async delete(e,t){return this.logFor(e).for(this.delete).info("Deleting id: "+t),this.serialize(await super.delete(e,t))}async deleteAll(e,t){const r=JSON.parse(t);return this.logFor(e).for(this.deleteAll).info(`deleting ${r.length} entries from the table`),JSON.stringify((await super.deleteAll(e,r)).map(e=>this.serialize(e)))}async readAll(e,t){const r=JSON.parse(t);return this.logFor(e).for(this.readAll).info(`reading ${r.length} entries from the table`),JSON.stringify((await super.readAll(e,r)).map(e=>this.serialize(e)))}async updateAll(e,t){const r=this.logFor(e).for(this.updateAll),a=JSON.parse(t).map(e=>this.deserialize(e)).map(e=>new this.clazz(e));return r.info(`Updating ${a.length} entries to the table`),JSON.stringify((await super.updateAll(e,a)).map(e=>this.serialize(e)))}async raw(e,t,r){const a=JSON.parse(t);return super.raw(e,a,r)}async init(e){await super.init(e)}async healthcheck(e){return JSON.stringify(await super.healthcheck(e))}async createAll(e,t){const r=this.logFor(e).for(this.createAll),a=JSON.parse(t).map(e=>this.deserialize(e)).map(e=>new this.clazz(e));return r.info(`Adding ${a.length} entries to the table`),JSON.stringify((await super.createAll(e,a)).map(e=>this.serialize(e)))}}function ke(e,t){const r=e+t;if(e!==r-t||t!==r-e)throw new X(`Addition overflow: ${e} + ${t}`);return r}function xe(e,t){const r=e-t;if(e!==r+t||t!==e-r)throw new X(`Subtraction overflow: ${e} - ${t}`);return r}var De;r.__decorate([y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,String]),r.__metadata("design:returntype",Promise)],Re.prototype,"create",null),r.__decorate([y.Transaction(!1),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,String]),r.__metadata("design:returntype",Promise)],Re.prototype,"read",null),r.__decorate([y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,String]),r.__metadata("design:returntype",Promise)],Re.prototype,"update",null),r.__decorate([y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,String]),r.__metadata("design:returntype",Promise)],Re.prototype,"delete",null),r.__decorate([y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,String]),r.__metadata("design:returntype",Promise)],Re.prototype,"deleteAll",null),r.__decorate([y.Transaction(!1),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,String]),r.__metadata("design:returntype",Promise)],Re.prototype,"readAll",null),r.__decorate([y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,String]),r.__metadata("design:returntype",Promise)],Re.prototype,"updateAll",null),r.__decorate([y.Transaction(!1),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,String,Boolean]),r.__metadata("design:returntype",Promise)],Re.prototype,"raw",null),r.__decorate([y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context]),r.__metadata("design:returntype",Promise)],Re.prototype,"init",null),r.__decorate([y.Transaction(!1),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context]),r.__metadata("design:returntype",Promise)],Re.prototype,"healthcheck",null),r.__decorate([y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,String]),r.__metadata("design:returntype",Promise)],Re.prototype,"createAll",null),(e=>{e.TRANSFER="Transfer",e.APPROVAL="Approval"})(De||(De={}));class Pe extends Ne{constructor(e){super(e,le),Pe.adapter=Pe.adapter||new Te,this.walletRepository=fe.forModel(le,Pe.adapter.alias),this.tokenRepository=fe.forModel(ce,Pe.adapter.alias),this.allowanceRepository=fe.forModel(de,Pe.adapter.alias)}async TokenName(e){await this.CheckInitialized(e);const t=await this.tokenRepository.selectWithContext(void 0,e);return(await t.execute())[0].name}async Symbol(e){await this.CheckInitialized(e);const t=await this.tokenRepository.selectWithContext(void 0,e);return(await t.execute())[0].symbol}async Decimals(e){await this.CheckInitialized(e);const t=await this.tokenRepository.selectWithContext(void 0,e);return(await t.execute())[0].decimals}async TotalSupply(e){await this.CheckInitialized(e);const t=await this.walletRepository.selectWithContext(void 0,e),r=await t.execute();if(0==r.length)throw new d.NotFoundError(`The token ${this.getName()} does not exist`);let a=0;return r.forEach(e=>{a+=e.balance}),a}async BalanceOf(e,t){return await this.CheckInitialized(e),(await this.walletRepository.read(t,e)).balance}async Transfer(e,t,r){await this.CheckInitialized(e);const a=e.clientIdentity.getID();if(!await this._transfer(e,a,t,r))throw new d.InternalError("Failed to transfer");return!0}async TransferFrom(e,t,r,a){await this.CheckInitialized(e);const i=e.clientIdentity.getID(),n=await this._getAllowance(e,t,i);if(!n||0>n.value)throw new Z(`spender ${i} has no allowance from ${t}`);const s=n.value;if(a>s)throw new Q("The spender does not have enough allowance to spend.");const o=xe(s,a),c=Object.assign({},n,{value:o});if(await this.allowanceRepository.update(c,e),!await this._transfer(e,t,r,a))throw new d.InternalError("Failed to transfer");return!0}async _transfer(e,r,a,i){const n=this.logFor(e).for(this._transfer);if(r===a)throw new t.AuthorizationError("cannot transfer to and from same client account");if(0>i)throw new Q("transfer amount cannot be negative");const s=await this.walletRepository.read(r,e),o=s.balance;if(i>o)throw new Q(`client account ${r} has insufficient funds.`);let c,l=!1;try{c=await this.walletRepository.read(a,e)}catch(t){if(!(t instanceof d.BaseError))throw new d.InternalError(t);if(404!==t.code)throw new d.InternalError(t.message);c=new le({id:a,balance:0,token:await this.TokenName(e)}),l=!0}const p=c.balance,u=xe(o,i),h=ke(p,i),g=Object.assign({},s,{balance:u});await this.walletRepository.update(g,e);const y=Object.assign({},c,{balance:h});l?await this.walletRepository.create(y,e):await this.walletRepository.update(y,e);const f={from:r,to:a,value:i};return this.repo.ObserverHandler().updateObservers(n,"",De.TRANSFER,"",e,"",f),!0}async Approve(e,t,r){await this.CheckInitialized(e);const a=this.logFor(e).for(this.Approve),i=e.clientIdentity.getID();let n=await this._getAllowance(e,i,t);if((await this.walletRepository.read(i,e)).balance<r)throw new Q(`client account ${i} has insufficient funds.`);n?(n.value=r,await this.allowanceRepository.update(n,e)):(n=new de({owner:i,spender:t,value:r}),await this.allowanceRepository.create(n,e));const s={owner:i,spender:t,value:r};return this.repo.ObserverHandler().updateObservers(a,"",De.APPROVAL,"",e,"",s),!0}async Allowance(e,t,r){await this.CheckInitialized(e);const a=await this._getAllowance(e,t,r);if(!a)throw new Z(`spender ${r} has no allowance from ${t}`);return a.value}async _getAllowance(e,r,a){const i=t.Condition.and(t.Condition.attribute("owner").eq(r),t.Condition.attribute("spender").eq(a)),n=await this.allowanceRepository.selectWithContext(void 0,e),s=await n.where(i).execute();return s?.[0]}async Initialize(e,r){const a=await this.tokenRepository.selectWithContext(void 0,e);if((await a.execute()).length>0)throw new t.AuthorizationError("contract options are already set, client is not authorized to change them");return r.owner=e.clientIdentity.getID(),await this.tokenRepository.create(r,e),!0}async CheckInitialized(e){const t=await this.tokenRepository.selectWithContext(void 0,e);if(0==(await t.execute()).length)throw new ae("contract options need to be set before calling any function, call Initialize() to initialize contract")}async Mint(e,t){await this.CheckInitialized(e);const r=this.logFor(e).for(this.Mint),a=e.clientIdentity.getID();if(0>=t)throw new d.ValidationError("mint amount must be a positive integer");let i;try{i=await this.walletRepository.read(a,e);const r=ke(i.balance,t),n=Object.assign({},i,{balance:r});await this.walletRepository.update(n,e)}catch(r){if(!(r instanceof d.BaseError))throw new d.InternalError(r);if(404!==r.code)throw new d.InternalError(r.message);{const r=new le({id:a,balance:t,token:await this.TokenName(e)});await this.walletRepository.create(r,e)}}const n={from:"0x0",to:a,value:t};this.repo.ObserverHandler().updateObservers(r,"",De.TRANSFER,"",e,"",n)}async Burn(e,t){await this.CheckInitialized(e);const r=this.logFor(e).for(this.Burn),a=e.clientIdentity.getID(),i=await this.walletRepository.read(a,e),n=i.balance;if(t>n)throw new Q("Minter has insufficient funds.");const s=xe(n,t),o=Object.assign({},i,{balance:s});await this.walletRepository.update(o,e),r.info(t+" tokens were burned");const c={from:a,to:"0x0",value:t};this.repo.ObserverHandler().updateObservers(r,"",De.TRANSFER,"",e,"",c)}async BurnFrom(e,t,r){await this.CheckInitialized(e);const a=this.logFor(e).for(this.BurnFrom),i=await this.walletRepository.read(t,e),n=i.balance;if(r>n)throw new Q(t+" has insufficient funds.");const s=xe(n,r),o=Object.assign({},i,{balance:s});await this.walletRepository.update(o,e),a.info(`${r} tokens were berned from ${t}`);const c={from:t,to:"0x0",value:r};this.repo.ObserverHandler().updateObservers(a,"",De.TRANSFER,"",e,"",c)}async ClientAccountBalance(e){await this.CheckInitialized(e);const t=e.clientIdentity.getID(),r=await this.walletRepository.read(t,e);if(!r)throw new Q(`The account ${t} does not exist`);return r.balance}async ClientAccountID(e){return await this.CheckInitialized(e),e.clientIdentity.getID()}}r.__decorate([y.Transaction(!1),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context]),r.__metadata("design:returntype",Promise)],Pe.prototype,"TokenName",null),r.__decorate([y.Transaction(!1),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context]),r.__metadata("design:returntype",Promise)],Pe.prototype,"Symbol",null),r.__decorate([y.Transaction(!1),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context]),r.__metadata("design:returntype",Promise)],Pe.prototype,"Decimals",null),r.__decorate([y.Transaction(!1),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context]),r.__metadata("design:returntype",Promise)],Pe.prototype,"TotalSupply",null),r.__decorate([y.Transaction(!1),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,String]),r.__metadata("design:returntype",Promise)],Pe.prototype,"BalanceOf",null),r.__decorate([y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,String,Number]),r.__metadata("design:returntype",Promise)],Pe.prototype,"Transfer",null),r.__decorate([y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,String,String,Number]),r.__metadata("design:returntype",Promise)],Pe.prototype,"TransferFrom",null),r.__decorate([y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,String,Number]),r.__metadata("design:returntype",Promise)],Pe.prototype,"Approve",null),r.__decorate([y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,String,String]),r.__metadata("design:returntype",Promise)],Pe.prototype,"Allowance",null),r.__decorate([y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,ce]),r.__metadata("design:returntype",Promise)],Pe.prototype,"Initialize",null),r.__decorate([y.Transaction(!1),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context]),r.__metadata("design:returntype",Promise)],Pe.prototype,"CheckInitialized",null),r.__decorate([q(),y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,Number]),r.__metadata("design:returntype",Promise)],Pe.prototype,"Mint",null),r.__decorate([q(),y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,Number]),r.__metadata("design:returntype",Promise)],Pe.prototype,"Burn",null),r.__decorate([q(),y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context,String,Number]),r.__metadata("design:returntype",Promise)],Pe.prototype,"BurnFrom",null),r.__decorate([y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context]),r.__metadata("design:returntype",Promise)],Pe.prototype,"ClientAccountBalance",null),r.__decorate([y.Transaction(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[y.Context]),r.__metadata("design:returntype",Promise)],Pe.prototype,"ClientAccountID",null);const $e=[Pe];class ze extends s.MiniLogger{constructor(e,t,r){super(e,t),this.logger=r?r.logger:new s.MiniLogger(e,t)}log(e,t,r){if(s.NumericLogLevels[this.config("level")]<s.NumericLogLevels[e])return;let a;switch(e){case s.LogLevel.info:a=this.logger.info;break;case s.LogLevel.verbose:a=this.logger.verbose;break;case s.LogLevel.debug:a=this.logger.debug;break;case s.LogLevel.error:a=this.logger.error;break;case s.LogLevel.silly:a=this.logger.silly;break;default:throw Error("Invalid log level")}a.call(this.logger,this.createLog(e,t,r))}}s.Logging.setFactory((e,t,r)=>new ze(e,t||{},r));const Ke="##VERSION##",Be="##PACKAGE##";f.Metadata.registerLibrary(Be,Ke),e.ContractLogger=ze,e.CoreUtils=z,e.FabricClientAdapter=k,e.FabricClientDispatch=P,e.FabricContractAdapter=Te,e.FabricContractContext=ue,e.FabricContractRepository=fe,e.FabricContractRepositoryObservableHandler=he,e.FabricContractSequence=ye,e.FabricCrudContract=Ne,e.FabricERC20ClientRepository=pe,e.FabricEnrollmentService=oe,e.FabricFlavour=N,e.FabricStatement=me,e.OwnedBy=()=>{const t=J(e.FabricModelKeys.OWNEDBY);return n.Decoration.for(t).define({decorator:()=>(t,r)=>g.apply(n.required(),d.readonly(),d.onCreate(U),n.propMetadata(J(e.FabricModelKeys.OWNEDBY),r))(t,r),args:[]}).apply()},e.Owner=q,e.PACKAGE_NAME=Be,e.SerializedCrudContract=Re,e.VERSION=Ke,e.contentOfLoadFile=C,e.contracts=$e,e.createdByOnFabricCreateUpdate=Se,e.extractPrivateKey=T,e.generateFabricEventName=x,e.getCAUser=async(e,t,r,a)=>{A.debug(`Creating a CA ${a} user ${e} with certificate ${r}`);const i=new l.User(e),n=l.User.newCryptoSuite();i.setCryptoSuite(n);const s=n.createKeyFromRaw(t);return await i.setEnrollment(s,r,a),i},e.getFabricModelKey=J,e.getFirstDirFileName=S,e.getFirstDirFileNameContent=async e=>{const{promises:t}=await c.normalizeImport(import("fs")),{join:r}=await c.normalizeImport(import("path")),a=await t.readdir(e);return(await t.readFile(r(e,a[0]))).toString()},e.getIdentity=E,e.getSigner=O,e.ownedByOnCreate=U,e.parseEventName=D,e.pkFabricOnCreate=Oe,e.privateData=H,e.readFile=async e=>"string"!=typeof e?e:await(async e=>{const{promises:t}=await c.normalizeImport(import("fs"));return await t.readFile(e)})(e)},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/core"),require("tslib"),require("@decaf-ts/for-couchdb"),require("@grpc/grpc-js"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/logging"),require("@hyperledger/fabric-gateway"),require("@decaf-ts/utils"),require("fabric-common"),require("@decaf-ts/db-decorators"),require("fabric-ca-client"),require("@peculiar/x509"),require("@peculiar/webcrypto"),require("@decaf-ts/reflection"),require("fabric-contract-api"),require("@decaf-ts/decoration")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/core","tslib","@decaf-ts/for-couchdb","@grpc/grpc-js","@decaf-ts/decorator-validation","@decaf-ts/logging","@hyperledger/fabric-gateway","@decaf-ts/utils","fabric-common","@decaf-ts/db-decorators","fabric-ca-client","@peculiar/x509","@peculiar/webcrypto","@decaf-ts/reflection","fabric-contract-api","@decaf-ts/decoration"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-fabric"]={},e.decafTsCore,e.tslib,e.decafTsForCouchdb,e.grpcGrpcJs,e.decafTsDecoratorValidation,e.decafTsLogging,e.hyperledgerFabricGateway,e.decafTsUtils,e.fabricCommon,e.decafTsDbDecorators,e.fabricCaClient,e.peculiarX509,e.peculiarWebcrypto,e.decafTsReflection,e.fabricContractApi,e.decafTsDecoration);
|
|
1
|
+
var e,t;e=this,t=function(e,t,r,a,i,n,o,s,c,l){"use strict";class d extends a.Context{constructor(){super()}get stub(){return this.get("stub")}get timestamp(){return this.stub.getDateTimestamp()}get identity(){try{return this.get("clientIdentity")}catch(e){return this.get("identity")}}get logger(){return this.get("logger")}}class p extends o.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,i,n,o){const{stub:s}=i;if(-1!==this.supportedEvents.indexOf(r)){e.debug(`Emitting ${r} event`);const i=((e,t,r)=>{const a=[e,t];return r&&a.push(r),a.join("_")})(t,r,n);s.setEvent(i,Buffer.from(JSON.stringify({id:a})))}else s.setEvent(r,Buffer.from(JSON.stringify(o)))}}var u,h;(e=>{e.PRIVATE="private",e.FABRIC="fabric.",e.OWNEDBY="owned-by"})(u||(u={})),(e=>{e.X509="X.509"})(h||(h={}));const y="hlf-fabric";function g(){return function(e,t,r){const i=r.value;return r.value=async function(...e){const r=e[0],n=r.clientIdentity.getID(),s=await this.tokenRepository.selectWithContext(void 0,r),c=await s.execute();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!=n)throw new o.AuthorizationError(`User not authorized to run ${t} on the token`);return await i.apply(this,e)},r}}function f(e){return r.Model.key(u.FABRIC+e)}function m(e){if(!e)throw Error("Collection name is required");const t=f(u.PRIVATE);return(i,n)=>{const o=n||void 0,s=Reflect.getMetadata(t,i[r.ModelKeys.ANCHOR]||i,o),c=s?.collections||[];r.propMetadata(f(u.PRIVATE),{...!n&&{collections:c?[...new Set([...c,e])]:[e]},isPrivate:!n})(n?i.constructor:i[r.ModelKeys.ANCHOR]||i),n&&(r.propMetadata(f(u.PRIVATE),{collections:c?[...new Set([...c,e])]:[e]})(i,n),a.transient()(i,n))}}const w=/private\s+data\s+matching\s+public\s+hash\s+version\s+is\s+not\s+available/i;function _(e){let t=Reflect.getMetadata(f(u.PRIVATE),e);return t=t||Reflect.getMetadata(f(u.PRIVATE),e.constructor),t}function b(e){const t=_(e);return!(!t||void 0===t.isPrivate)&&t.isPrivate}function v(e){if(!(e=>!!_(e))(e))return{model:e};const t=a.getAllPropertyDecoratorsRecursive(e,void 0,f(u.PRIVATE)),i=b(e),n=_(e);let o={model:e,private:void 0};if(o=i?Object.keys(e).reduce((t,r)=>{const i=n.collections;t.private=t.private||{};for(const n of i)try{t.private[n]=t.private[n]||{},t.private[n][r]=e[r]}catch(e){throw new a.SerializationError(`Failed to serialize private property ${r}: ${e}`)}return t},{model:{}}):Object.entries(t).reduce((t,[r,i])=>{const n=i.find(e=>""===e.key);if(n){const i=n.props.collections;t.private=t.private||{};for(const n of i)try{t.private[n]=t.private[n]||{},t.private[n][r]=e[r]}catch(e){throw new a.SerializationError(`Failed to serialize private property ${r}: ${e}`)}}else t.model=t.model||{},t.model[r]=e[r];return t},{}),o.model=o.model||{},o.model=r.Model.build(o.model,e.constructor.name),o.private){const t=Object.keys(o.private);for(const a of t)o.private[a]=r.Model.build(o.private[a],e.constructor.name)}return o}class S extends a.InternalError{constructor(e){super(e,S.name)}}class C extends a.InternalError{constructor(e){super(e,C.name)}}class A extends a.InternalError{constructor(e){super(e,A.name)}}class E extends a.InternalError{constructor(e){super(e,E.name,500)}}class O extends a.BaseError{constructor(e="private data matching public hash version is not available ..."){super(O.name,e,403)}}class k extends a.BaseError{constructor(e){super(k.name,e,409)}}let T=class extends o.BaseModel{constructor(e){super(e)}};c.__decorate([o.pk(),c.__metadata("design:type",String)],T.prototype,"id",void 0),c.__decorate([r.required(),o.index(),c.__metadata("design:type",Object)],T.prototype,"current",void 0),T=c.__decorate([o.table(t.CouchDBKeys.SEQUENCE),r.model(),c.__metadata("design:paramtypes",[Object])],T);class x extends o.Sequence{constructor(e,t,r){super(e);for(const e of r||[])m(e)(T);this.repo=o.Repository.forModel(T,t.alias)}async current(e){if(!e)throw new E("Context is required");const{name:t,startWith:r}=this.options;try{const r=await this.repo.read(t,e);return this.parse(r.current)}catch(e){if(e instanceof a.NotFoundError){if(void 0===r)throw new a.InternalError("Starting value is not defined for a non existing sequence");try{return this.parse(r)}catch(e){throw new a.InternalError(`Failed to parse initial value for sequence ${r}: ${e}`)}}throw new a.InternalError(`Failed to retrieve current value for sequence ${t}: ${e}`)}}parse(e){return o.Sequence.parseValue(this.options.type,e)}async increment(e,t,r){if(!r)throw new E("Context is required");const{type:i,incrementBy:n,name:o}=this.options;let s;const c=t||n;if(c%n!==0)throw new a.InternalError("Value to increment does not consider the incrementBy setting: "+n);switch(i){case"Number":s=this.parse(e)+c;break;case"BigInt":s=this.parse(e)+BigInt(c);break;default:throw new a.InternalError("Should never happen")}let l;try{l=await this.repo.update(new T({id:o,current:s}),r)}catch(e){if(!(e instanceof a.NotFoundError))throw e;l=await this.repo.create(new T({id:o,current:s}),r)}return l.current}async next(e){if(!e)throw new E("Context is required");const t=await this.current(e);return this.increment(t,void 0,e)}async range(e,t){if(!t)throw new E("Context is required");const r=await this.current(t),i=this.parse(this.options.incrementBy),n=await this.increment(r,this.parse(e)*i,t),o=[];for(let t=1;e>=t;t++)o.push(r+i*this.parse(t));if(o[o.length-1]!==n)throw new a.InternalError("Miscalculation of range");return o}}class R extends o.Repository{constructor(e,t,r){super(e,t),this.trackedEvents=r}logFor(e){return n.Logging.for(R,{},e)}async create(e,...t){const r=t[t.length-1],a=this.logFor(r).for(this.create);a.info("Preparing model: "+JSON.stringify(e));let i,{record:n,id:o,transient:s}=this.adapter.prepare(e,this.pk,this.tableName,...t);return a.info("Creating model: "+JSON.stringify(e)),n=await this.adapter.create(this.tableName,o,n,...t),t.length&&(i=t[t.length-1]),a.info("Reverting model: "+JSON.stringify(e)),this.adapter.revert(n,this.class,this.pk,o,i&&i.get("rebuildWithTransient")?s:void 0)}async read(e,...t){const r=await this.adapter.read(this.tableName,e,new this.class,...t);return this.adapter.revert(r,this.class,this.pk,e)}async delete(e,...t){const r=await this.adapter.delete(this.tableName,e,new this.class,...t);return this.adapter.revert(r,this.class,this.pk,e)}async update(e,...t){const r=t[t.length-1],a=this.logFor(r).for(this.update);a.info("Preparing model: "+JSON.stringify(e));let i,{record:n,id:o,transient:s}=this.adapter.prepare(e,this.pk,this.tableName,...t);return a.info("Updating model: "+JSON.stringify(e)),n=await this.adapter.update(this.tableName,o,n,...t),t.length&&(i=t[t.length-1]),a.info("Reverting model: "+JSON.stringify(e)),this.adapter.revert(n,this.class,this.pk,o,i&&i.get("rebuildWithTransient")?s:void 0)}ObserverHandler(){return new p}async createAll(e,...t){if(!e.length)return e;const r=e.map(e=>this.adapter.prepare(e,this.pk,this.tableName,...t)),a=r.map(e=>e.id);let i=r.map(e=>e.record);const n=r.map(e=>e.transient).filter(e=>!!e);let o;return t.length&&(o=t[t.length-1]),i=await this.adapter.createAll(this.tableName,a,i,...t),i.map((e,t)=>this.adapter.revert(e,this.class,this.pk,a[t],o&&o.get("rebuildWithTransient")?n:void 0))}async updateAll(e,...t){if(!e.length)return e;const r=e.map(e=>this.adapter.prepare(e,this.pk,this.tableName,...t)),a=r.map(e=>e.transient).filter(e=>!!e);let i;return t.length&&(i=t[t.length-1]),(await this.adapter.updateAll(this.tableName,r.map(e=>e.id),r.map(e=>e.record),...t)).map((e,t)=>this.adapter.revert(e,this.class,this.pk,r[t].id,i&&i.get("rebuildWithTransient")?a:void 0))}async raw(e,t,...r){const i=r.pop(),n=await a.Context.args("QUERY",this.class,[i],this.adapter,{});return this.adapter.raw(e,t,new this.class,...n.args)}async updateObservers(e,t,r,a,...i){if(!this.trackedEvents||-1!==this.trackedEvents.indexOf(t))return await super.updateObservers(e,t,r,a,...i)}async selectWithContext(e,t){let r;return t instanceof d?r.context=t:r=await a.Context.args(a.OperationKeys.CREATE,this.class,[t],this.adapter,this._overrides||{}),e?this.adapter.Statement(r.context).select(e).from(this.class):this.adapter.Statement(r.context).select().from(this.class)}async createAllPrefix(e,...t){const r=t[t.length-1],i=await a.Context.args(a.OperationKeys.CREATE,this.class,t,this.adapter,this._overrides||{});if(!e.length)return[e,...i.args];const n=o.Repository.getSequenceOptions(e[0]);let s=[];n.type?(n.name||(n.name=x.pk(e[0])),s=await(await this.adapter.Sequence(n)).range(e.length,r)):s=e.map((e,t)=>{if(void 0===e[this.pk])throw new a.InternalError("Primary key is not defined for model in position "+t);return e[this.pk]}),e=await Promise.all(e.map(async(e,t)=>(e=new this.class(e),n.type&&(e[this.pk]=s[t]),await a.enforceDBDecorators(this,i.context,e,a.OperationKeys.CREATE,a.OperationKeys.ON),e)));const c=i.context.get("ignoredValidationProperties")||[],l=(await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...c))))).reduce((e,t,r)=>(t&&(e="string"==typeof e?e+`\n - ${r}: ${t.toString()}`:` - ${r}: ${t.toString()}`),e),void 0);if(l)throw new a.ValidationError(l);return[e,...i.args]}async createPrefix(e,...t){const r=await super.createPrefix(e,...t),i=r[0][this.pk];try{if(await this.read(i+"",...t))throw new a.ConflictError(`Conflict detected while creating model with id: ${i} already exists`)}catch(e){if(404!==e.code)throw e;this.logFor(t[t.length-1]).info(`Record entry with pk ${i} does not exist, creating it now...`)}return r}}class F extends t.CouchDBStatement{constructor(e,t){super(e),this.ctx=t}async raw(e){const t=await this.adapter.raw(e,!0,this.ctx),r=a.findPrimaryKey(new this.fromSelector),i=r.id,n=r.props.type;return this.selectSelector?t:t.map(e=>this.processRecord(e,i,n))}build(){const e={};e[t.CouchDBKeys.TABLE]={},e[t.CouchDBKeys.TABLE]=o.Repository.table(this.fromSelector);const r={selector:e};if(this.selectSelector&&(r.fields=this.selectSelector),this.whereCondition){const e=this.parseCondition(o.Condition.and(this.whereCondition,o.Condition.attribute(t.CouchDBKeys.TABLE).eq(r.selector[t.CouchDBKeys.TABLE]))).selector,a=Object.keys(e);if(1===a.length&&-1!==Object.values(t.CouchDBGroupOperator).indexOf(a[0]))switch(a[0]){case t.CouchDBGroupOperator.AND:e[t.CouchDBGroupOperator.AND]=[...Object.values(e[t.CouchDBGroupOperator.AND]).reduce((e,r)=>{const a=Object.keys(r);if(1!==a.length)throw Error("Too many keys in query selector. should be one");const i=a[0];return i===t.CouchDBGroupOperator.AND?e.push(...r[i]):e.push(r),e},[])],r.selector=e;break;case t.CouchDBGroupOperator.OR:{const a={};a[t.CouchDBGroupOperator.AND]=[e,...Object.entries(r.selector).map(([e,t])=>{const r={};return r[e]=t,r})],r.selector=a;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,a]=this.orderBySelector,i={};i[e]=a,r.sort.push(i),r.selector[e]||(r.selector[e]={},r.selector[e][t.CouchDBOperator.BIGGER]=null)}return this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),r}}class P extends r.JSONSerializer{constructor(){super()}deserialize(e,t){return JSON.parse(e)}serialize(e){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(e)))}preSerialize(e){return Object.assign({},e)}}async function N(e,t,i,n){const s=n[i];if(!s)return;if("object"!=typeof s){const t=o.repositoryFromTypeMetadata(n,i,this.adapter.alias),r=await t.read(s,e);return await o.cacheModelForPopulate(e,n,i,s,r),void(n[i]=s)}t.class="string"==typeof t.class?t.class:t.class().name;const c=r.Model.get(t.class);if(!c)throw new a.InternalError("Could not find model "+t.class);const l=o.Repository.forModel(c,this.adapter.alias),d=await l.create(s,e),p=a.findPrimaryKey(d).id;await o.cacheModelForPopulate(e,n,i,d[p],d),n[i]=d[p]}async function I(e,t,r,i){const n=i[r];if(!n)return;if(t.cascade.update!==o.Cascade.CASCADE)return;if("object"!=typeof n){const t=o.repositoryFromTypeMetadata(i,r,this.adapter.alias),a=await t.read(n,e);return await o.cacheModelForPopulate(e,i,r,n,a),void(i[r]=n)}const s=await o.createOrUpdate(i[r],e,this.adapter.alias),c=a.findPrimaryKey(s).id;await o.cacheModelForPopulate(e,i,r,s[c],s),i[r]=s[c]}async function z(e,t,a,i){const n=i[a];if(!n)return;if(t.cascade.update!==o.Cascade.CASCADE)return;const s=o.repositoryFromTypeMetadata(i,a,this.adapter.alias);let c;c=n instanceof r.Model?await s.delete(i[a][s.pk],e):await s.delete(i[a],e),await o.cacheModelForPopulate(e,i,a,c[s.pk],c)}async function D(e,t,r,i){const n=i[r];if(!n||!n.length)return;const s=typeof n[0];if(!n.every(e=>typeof e===s))throw new a.InternalError(`Invalid operation. All elements of property ${r} must match the same type.`);const c=new Set([...n]);if("object"!==s){const t=o.repositoryFromTypeMetadata(i,r,this.adapter.alias);for(const a of c){const n=await t.read(a,e);await o.cacheModelForPopulate(e,i,r,a,n)}return void(i[r]=[...c])}const l=a.findPrimaryKey(n[0]).id,d=new Set;for(const t of n){const a=await o.createOrUpdate(t,e,this.adapter.alias);await o.cacheModelForPopulate(e,i,r,a[l],a),d.add(a[l])}i[r]=[...d]}async function $(e,t,r,i){if(t.cascade.delete!==o.Cascade.CASCADE)return;const n=i[r];if(!n||!n.length)return;const s=typeof n[0];if(!n.every(e=>typeof e===s))throw new a.InternalError(`Invalid operation. All elements of property ${r} must match the same type.`);const c="object"===s,l=c?o.Repository.forModel(n[0],this.adapter.alias):o.repositoryFromTypeMetadata(i,r,this.adapter.alias),d=new Set([...c?n.map(e=>e[l.pk]):n]);for(const t of d.values()){const a=await l.delete(t,e);await o.cacheModelForPopulate(e,i,r,t,a)}i[r]=[...d]}async function B(e,t,r,i){if(!t.populate)return;const n=i[r],s=Array.isArray(n);if(void 0===n||s&&0===n.length)return;const c=await(async(t,r,i,n,s)=>{let c,l;const d=[];for(const p of n){c=o.getPopulateKey(r.constructor.name,i,p);try{l=await t.get(c)}catch(t){const n=o.repositoryFromTypeMetadata(r,i,s);if(!n)throw new a.InternalError("Could not find repo");l=await n.read(p,e)}d.push(l)}return d})(e,i,r,s?n:[n],this.adapter.alias);i[r]=s?c:c[0]}async function M(e,t,r,a){try{const t=e.get("clientIdentity");a[r]=t.getID()}catch(e){throw new o.UnsupportedError("No User found in context. Please provide a user in the context")}}async function q(e,t,r,i){if(!t.type||i[r])return;let n;t.name||(t.name=o.sequenceNameForModel(i,"pk"));try{n=await this.adapter.Sequence(t)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${t.name}: ${e}`)}const s=await n.next(e);Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:s})}class j extends t.CouchDBAdapter{getClient(){throw new o.UnsupportedError("Client is not supported in Fabric contracts")}static{this.textDecoder=new TextDecoder("utf8")}static{this.serializer=new P}logFor(e){return n.Logging.for(j,{},e)}repository(){return R}constructor(e,t){super(e,y,t),this.Context=d}for(e,...t){return super.for(e,...t)}async create(e,t,r,...a){const{stub:i,logger:n}=a.pop(),o=n.for(this.create);try{o.info(`adding entry to ${e} table with pk ${t}`),r=await this.putState(i,t.toString(),r)}catch(e){throw this.parseError(e)}return r}async read(e,t,...r){const{stub:i,logger:n}=r.pop(),o=n.for(this.read);let s;try{const r=await this.readState(i,e,t.toString());if(1>r.length)throw o.debug(`No record found for id ${t} in ${e} table`),new a.NotFoundError(`No record found for id ${t} in ${e} table`);2>r.length?(o.debug(`No record found for id ${t} in ${e} table`),s=r.pop()):s=this.mergeModels(r)}catch(e){throw this.parseError(e)}return s}async update(e,t,r,...a){const{stub:i,logger:n}=a.pop(),o=n.for(this.update);try{o.info(`updating entry to ${e} table with pk ${t}`),r=await this.putState(i,t.toString(),r)}catch(e){throw this.parseError(e)}return r}async delete(e,t,...r){const a=r.pop(),{stub:i,logger:n}=a,o=n.for(this.delete);let s;r.push(a);try{s=await this.read(e,t,...r),o.verbose(`deleting entry with pk ${t} from ${e} table`),this.deleteState(i,e,t.toString())}catch(e){throw this.parseError(e)}return s}async deleteState(e,t,r,...a){const i=e.createCompositeKey(t,[r+""]);await e.deleteState(i)}async putState(e,t,r,...i){let n;try{n=Buffer.from(j.serializer.serialize(r))}catch(e){throw new a.SerializationError(`Failed to serialize record with id ${t}: ${e}`)}return await e.putState(t.toString(),n),r}async readState(e,t,r,...i){const n=e.createCompositeKey(t,[r+""]),o=[];let s=await e.getState(n);if(""===s.toString())throw new a.NotFoundError(`Record with id ${r} not found`);try{s=j.serializer.deserialize(s.toString())}catch(e){throw new a.SerializationError("Failed to parse record: "+e)}return o.push(s),o}async queryResult(e,t,...r){return await e.getQueryResult(JSON.stringify(t))}async queryResultPaginated(e,t,r=250,a,...i){return await e.getQueryResultWithPagination(JSON.stringify(t),r,a?.toString())}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 j.textDecoder.decode(e)}async flags(e,t,r,a,...i){return Object.assign(await super.flags(e,t,r,...i),{stub:a.stub,identity:a.clientIdentity,logger:this.logFor(a)})}index(e){return Promise.resolve(void 0)}async resultIterator(e,t,r=!1){const a=[];let i=await t.next();for(;!i.done;){if(i.value&&i.value.value.toString()){let t={};if(e.debug(i.value.value.toString("utf8")),r){t.TxId=i.value.txId,t.Timestamp=i.value.timestamp;try{t.Value=JSON.parse(i.value.value.toString("utf8"))}catch(r){e.error(r),t.Value=i.value.value.toString("utf8")}}else try{t=JSON.parse(i.value.value.toString("utf8"))}catch(r){e.error(r),t=i.value.value.toString("utf8")}a.push(t)}i=await t.next()}return e.debug(`Closing iterator after ${a.length} results`),t.close(),a}async raw(e,t,...r){const{stub:a,logger:i}=r.pop(),n=i.for(this.raw),{skip:o,limit:s}=e;let c;s||o?(delete e.limit,delete e.skip,n.debug(`Retrieving paginated iterator: limit: ${s}/ skip: ${o}`),c=(await this.queryResultPaginated(a,e,s||250,o?.toString())).iterator):(n.debug("Retrieving iterator"),c=await this.queryResult(a,e)),n.debug("Iterator acquired");const l=await this.resultIterator(n,c);return n.debug("returning {0} results",""+(Array.isArray(l)?l.length:1)),l}Statement(e){if(!e)throw new E("Context is required");return new F(this,e)}async Sequence(e){return new x(e,this)}async createAll(e,t,r,...i){if(t.length!==r.length)throw new a.InternalError("Ids and models must have the same length");const{logger:n}=i[i.length-1],o=n.for(this.createAll);return o.info(`Creating ${t.length} entries ${e} table`),o.debug("pks: "+t),Promise.all(t.map(async(t,a)=>this.create(e,t,r[a],...i)))}async updateAll(e,t,r,...i){if(t.length!==r.length)throw new a.InternalError("Ids and models must have the same length");const{logger:n}=i[i.length-1],o=n.for(this.createAll);return o.info(`Updating ${t.length} entries ${e} table`),o.debug("pks: "+t),Promise.all(t.map(async(t,a)=>this.update(e,t,r[a],...i)))}prepare(e,t,...r){const{stub:i,logger:n}=r.pop(),s=r.shift(),c=n.for(this.prepare),l=a.modelToTransient(e),d=Object.entries(l.model).reduce((t,[r,i])=>{if(void 0===i)return t;const n=o.Repository.column(e,r);if(this.isReserved(n))throw new a.InternalError(`Property name ${n} is reserved`);return t[n]=i,t},{});return e[o.PersistenceKeys.METADATA]&&(c.silly("Passing along persistence metadata for "+e[o.PersistenceKeys.METADATA]),Object.defineProperty(d,o.PersistenceKeys.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[o.PersistenceKeys.METADATA]})),c.info(`Preparing record for ${s} table with pk ${e[t]}`),{record:d,id:i.createCompositeKey(s,[e[t]+""]),transient:l.transient}}revert(e,t,i,n,s){const c=this.log.for(this.revert),l={};l[i]=n;const d="string"==typeof t?r.Model.build(l,t):new t(l);c.silly(`Rebuilding model ${d.constructor.name} id ${n}`);const p=e[o.PersistenceKeys.METADATA],u=Object.keys(d).reduce((t,r)=>(t[r]=e[o.Repository.column(t,r)],t),d);return s&&(c.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([e,t])=>{if(e in u&&void 0!==u[e])throw new a.InternalError(`Transient property ${e} already exists on model ${d.constructor.name}. should be impossible`);u[e]=t})),p&&(c.silly(`Passing along ${this.flavour} persistence metadata for ${d.constructor.name} id ${n}: ${p}`),Object.defineProperty(u,o.PersistenceKeys.METADATA,{enumerable:!1,configurable:!1,writable:!1,value:p})),u}createPrefix(e,r,a,...i){const n=i.pop(),o={};return o[t.CouchDBKeys.TABLE]=e,Object.assign(o,a),[e,r,o,n]}updatePrefix(e,r,a,...i){const n=i.pop(),o={};return o[t.CouchDBKeys.TABLE]=e,Object.assign(o,a),[e,r,o,n]}createAllPrefix(e,r,i,...n){if(r.length!==i.length)throw new a.InternalError("Ids and models must have the same length");const o=n.pop(),s=r.map((r,a)=>{const n={};return n[t.CouchDBKeys.TABLE]=e,Object.assign(n,i[a]),n});return[e,r,s,o]}updateAllPrefix(e,r,i,...n){if(r.length!==i.length)throw new a.InternalError("Ids and models must have the same length");const o=n.pop(),s=r.map((r,a)=>{const n={};return n[t.CouchDBKeys.TABLE]=e,Object.assign(n,i[a]),n});return[e,r,s,o]}static decoration(){super.decoration();const e=o.Repository.key(o.PersistenceKeys.CREATED_BY),t=o.Repository.key(o.PersistenceKeys.UPDATED_BY);r.Decoration.flavouredAs(y).for(e).define(a.onCreate(M),r.propMetadata(e,{})).apply(),r.Decoration.flavouredAs(y).for(t).define(a.onCreateUpdate(M),r.propMetadata(t,{})).apply();const n=o.Repository.key(a.DBKeys.ID);r.Decoration.flavouredAs(y).for(n).define(o.index([o.OrderDirection.ASC,o.OrderDirection.DSC]),r.required(),a.readonly(),r.propMetadata(n,o.NumericSequence),a.onCreate(q,o.NumericSequence)).apply();const c=o.Adapter.key(o.PersistenceKeys.COLUMN);r.Decoration.flavouredAs(y).for(c).extend(i.Property()).apply();const l=o.Adapter.key(o.PersistenceKeys.TABLE);r.Decoration.flavouredAs(y).for(l).extend(e=>i.Object()(e)).apply();const d=o.Repository.key(o.PersistenceKeys.ONE_TO_ONE);r.Decoration.flavouredAs(y).for(d).define({decorator:(e,t,i,n,c)=>{const l={class:e.name?e.name:e,cascade:t,populate:i};return n&&(l.joinTable=n),c&&(l.name=c),s.apply(r.prop(o.PersistenceKeys.RELATIONS),r.type([e.name?e.name:e,String.name,Number.name,BigInt.name]),a.onCreate(N,l),a.onUpdate(I,l),a.onDelete(z,l),a.afterAny(B,l),r.propMetadata(d,l))}}).apply();const p=o.Repository.key(o.PersistenceKeys.ONE_TO_MANY);r.Decoration.for(p).define({decorator:(e,t,i,n,c)=>{const l={class:e.name?e.name:e,cascade:t,populate:i};return n&&(l.joinTable=n),c&&(l.name=c),s.apply(r.prop(o.PersistenceKeys.RELATIONS),r.list([e,String,Number]),a.onCreate(D,l),a.onUpdate(o.oneToManyOnUpdate,l),a.onDelete($,l),a.afterAny(B,l),r.propMetadata(p,l))}}).apply()}}j.decoration(),o.Adapter.setCurrent(y);class K extends r.JSONSerializer{constructor(){super()}deserialize(e){return super.deserialize(e)}serialize(e){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(e)))}}class L extends j{constructor(e,t,r){super(e,t),this.collections=r,this.collections=r||[]}async Sequence(e){return new x(e,this,this.collections)}async read(e,t,r,...i){const{stub:n,logger:o}=i.pop(),s=o.for(this.read);let c;try{const i=await this.readState(n,e,t.toString(),r);if(1>i.length)throw s.debug(`No record found for id ${t} in ${e} table`),new a.NotFoundError(`No record found for id ${t} in ${e} table`);2>i.length?(s.debug(`No record found for id ${t} in ${e} table`),c=i.pop()):c=this.mergeModels(i)}catch(e){throw this.parseError(e)}return c}async delete(e,t,r,...a){const i=a.pop(),{stub:n,logger:o}=i,s=o.for(this.delete);let c;a.push(i);try{c=await this.read(e,t,r,...a),s.verbose(`deleting entry with pk ${t} from ${e} table`),this.deleteState(n,e,t.toString(),r)}catch(e){throw this.parseError(e)}return c}prepare(e,t,...r){const{stub:i,logger:n}=r.pop(),s=r.shift(),c=n.for(this.prepare),l=((e,t)=>{const r=a.modelToTransient(t),i=v(t),n=t=>Object.entries(t).reduce((r,[i,n])=>{if(void 0===n)return r;const s=o.Repository.column(t,i);if(e.isReserved(s))throw new a.InternalError(`Property name ${s} is reserved`);return r[s]=n,r},{});if(i.private){const e=Object.keys(i.private);for(const t of e)i.private[t]=n(i.private[t])}return{model:r.model,transient:r.transient,privateData:i.private,result:n(r.model)}})(this,e);return c.info(`Preparing record for ${s} table with pk ${e[t]}`),{record:l.privateData,id:i.createCompositeKey(s,[e[t]+""]),transient:l.transient}}createPrefix(e,r,a,...i){const n=i.pop(),o=Object.keys(a);for(const r of o)a[r][t.CouchDBKeys.TABLE]=e;return[e,r,a,n]}updatePrefix(e,r,a,...i){const n=i.pop(),o=Object.keys(a);for(const r of o)a[r][t.CouchDBKeys.TABLE]=e;return[e,r,a,n]}async putState(e,t,r,...i){const n=Object.keys(r);let o,s={};for(const i of n){s=r[i];try{o=Buffer.from(j.serializer.serialize(r[i]))}catch(e){throw new a.SerializationError(`Failed to serialize record with id ${t}: ${e}`)}await e.putPrivateData(i,t.toString(),o)}return s}async readState(e,t,r,i,...n){const o=e.createCompositeKey(t,[r+""]),s=v(i),c=Object.keys(s.private),l=[];for(const t of c)try{let i=await e.getPrivateData(t,o);if(""===i.toString())throw new a.NotFoundError(`Entry with id ${r} doesn't exist...`);try{i=j.serializer.deserialize(i.toString())}catch(e){throw new a.SerializationError("Failed to parse private data: "+e)}l.push(i)}catch(e){if(w.test(e.message))throw new O(e);throw e}return l}async deleteState(e,t,r,a,...i){const n=e.createCompositeKey(t,[r+""]),o=v(a),s=Object.keys(o.private);for(const t of s)await e.deletePrivateData(t,n)}async queryResult(e,t,r){const a=v(r).private,i=Object.keys(a)[0]||"";return(await e.getPrivateDataQueryResult(i,JSON.stringify(t))).iterator}async queryResultPaginated(e,t,r=250,a=void 0,i){const n=v(i).private,o=Object.keys(n)[0]||"",s=await e.getPrivateDataQueryResult(o,JSON.stringify(t)),c=[];let l=0,d=!a,p=null;for(;;){const e=await s.next();if(e.value&&e.value.value.toString()){const t=e.value.key,i=e.value.value.toString("utf8");if(!d){t===a?.toString()&&(d=!0);continue}if(c.push({Key:t,Record:JSON.parse(i)}),p=t,l++,l>=r)return await s.close(),{iterator:c,metadata:{fetchedRecordsCount:c.length,bookmark:p}}}if(e.done)return await s.close(),{iterator:c,metadata:{fetchedRecordsCount:c.length,bookmark:""}}}}async raw(e,t,...r){const{stub:a,logger:i}=r.pop(),n=i.for(this.raw),{skip:o,limit:s}=e,c=r.shift();let l;s||o?(delete e.limit,delete e.skip,n.debug(`Retrieving paginated iterator: limit: ${s}/ skip: ${o}`),l=(await this.queryResultPaginated(a,e,s||250,o?.toString(),c)).iterator):(n.debug("Retrieving iterator"),l=await this.queryResult(a,e,c)),n.debug("Iterator acquired");const d=await this.resultIterator(n,l);return n.debug("returning {0} results",""+(Array.isArray(d)?d.length:1)),d}}class J extends i.Contract{static{this.serializer=new K}constructor(e,t){super(e),this.clazz=t,this.initialized=!1,J.adapter=this.getAdapter(t),this.repo=o.Repository.forModel(t,J.adapter.alias)}getAdapter(e){const t=new e;if(b(t)){const e=v(t),r=Object.keys(e.private);return new L(void 0,"fabric-private-data-adapter",r)}return new j(void 0,"fabric-public-data-adapter")}logFor(e){return n.Logging.for(J.name,{},e)}async create(e,t,...r){const a=this.logFor(e).for(this.create);"string"==typeof t&&(t=this.deserialize(t)),a.info("Creating model: "+JSON.stringify(t));const i=this.getTransientData(e);return a.info("Merging transient data..."),t=this.repo.merge(t,i),this.repo.create(t,e,...r)}async read(e,t,...r){return this.logFor(e).for(this.read).info(`reading entry with pk ${t} `),this.repo.read(t,e,...r)}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,t,...r){const a=this.logFor(e).for(this.update);"string"==typeof t&&(t=this.deserialize(t)),a.info("Updating model: "+JSON.stringify(t));const i=this.getTransientData(e);return a.info("Merging transient data..."),t=this.repo.merge(t,i),this.repo.update(t,e,...r)}async delete(e,t,...r){return this.logFor(e).for(this.delete).info(`deleting entry with pk ${t} `),this.repo.delete(t+"",e,...r)}async deleteAll(e,t,...r){return"string"==typeof t&&(t=JSON.parse(t)),this.repo.deleteAll(t,e,...r)}async readAll(e,t,...r){return"string"==typeof t&&(t=JSON.parse(t)),this.repo.readAll(t,e,...r)}async updateAll(e,t,...r){const a=this.logFor(e).for(this.updateAll);return"string"==typeof t&&(t=JSON.parse(t).map(e=>this.deserialize(e)).map(e=>new this.clazz(e))),a.info(`updating ${t.length} entries to the table`),this.repo.updateAll(t,e,...r)}async raw(e,t,r,...a){return"string"==typeof t&&(t=JSON.parse(t)),this.repo.raw(t,r,e,...a)}serialize(e){return J.serializer.serialize(e)}deserialize(e){return J.serializer.deserialize(e)}async init(e){const t=this.logFor(e).for(this.init);t.info("Running contract initialization..."),this.initialized=!0,t.info("Contract initialization completed.")}async healthcheck(e){return this.logFor(e).for(this.healthcheck).info(`Running Healthcheck: ${this.initialized}...`),{healthcheck:this.initialized}}async createAll(e,t,...r){const a=this.logFor(e).for(this.createAll);return"string"==typeof t&&(t=JSON.parse(t).map(e=>this.deserialize(e)).map(e=>new this.clazz(e))),a.info(`adding ${t.length} entries to the table`),this.repo.createAll(t,e,...r)}}class U extends J{constructor(e,t){super(e,t)}logFor(e){return n.Logging.for(U,{},e)}async create(e,t){const r=this.logFor(e).for(this.create);r.info("Creating model: "+t);const a=this.deserialize(t);return r.info("Model deserialized: "+JSON.stringify(a)),this.serialize(await super.create(e,a))}async read(e,t){return this.logFor(e).for(this.read).info("Reading id: "+t),this.serialize(await super.read(e,t))}async update(e,t){return this.logFor(e).for(this.update).info("Updating model: "+t),this.serialize(await super.update(e,t))}async delete(e,t){return this.logFor(e).for(this.delete).info("Deleting id: "+t),this.serialize(await super.delete(e,t))}async deleteAll(e,t){const r=JSON.parse(t);return this.logFor(e).for(this.deleteAll).info(`deleting ${r.length} entries from the table`),JSON.stringify((await super.deleteAll(e,r)).map(e=>this.serialize(e)))}async readAll(e,t){const r=JSON.parse(t);return this.logFor(e).for(this.readAll).info(`reading ${r.length} entries from the table`),JSON.stringify((await super.readAll(e,r)).map(e=>this.serialize(e)))}async updateAll(e,t){const r=this.logFor(e).for(this.updateAll),a=JSON.parse(t).map(e=>this.deserialize(e)).map(e=>new this.clazz(e));return r.info(`Updating ${a.length} entries to the table`),JSON.stringify((await super.updateAll(e,a)).map(e=>this.serialize(e)))}async raw(e,t,r){const a=JSON.parse(t);return super.raw(e,a,r)}async init(e){await super.init(e)}async healthcheck(e){return JSON.stringify(await super.healthcheck(e))}async createAll(e,t){const r=this.logFor(e).for(this.createAll),a=JSON.parse(t).map(e=>this.deserialize(e)).map(e=>new this.clazz(e));return r.info(`Adding ${a.length} entries to the table`),JSON.stringify((await super.createAll(e,a)).map(e=>this.serialize(e)))}}function V(e,t){const r=e+t;if(e!==r-t||t!==r-e)throw new S(`Addition overflow: ${e} + ${t}`);return r}function W(e,t){const r=e-t;if(e!==r+t||t!==e-r)throw new S(`Subtraction overflow: ${e} - ${t}`);return r}c.__decorate([i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,String]),c.__metadata("design:returntype",Promise)],U.prototype,"create",null),c.__decorate([i.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,String]),c.__metadata("design:returntype",Promise)],U.prototype,"read",null),c.__decorate([i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,String]),c.__metadata("design:returntype",Promise)],U.prototype,"update",null),c.__decorate([i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,String]),c.__metadata("design:returntype",Promise)],U.prototype,"delete",null),c.__decorate([i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,String]),c.__metadata("design:returntype",Promise)],U.prototype,"deleteAll",null),c.__decorate([i.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,String]),c.__metadata("design:returntype",Promise)],U.prototype,"readAll",null),c.__decorate([i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,String]),c.__metadata("design:returntype",Promise)],U.prototype,"updateAll",null),c.__decorate([i.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,String,Boolean]),c.__metadata("design:returntype",Promise)],U.prototype,"raw",null),c.__decorate([i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context]),c.__metadata("design:returntype",Promise)],U.prototype,"init",null),c.__decorate([i.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context]),c.__metadata("design:returntype",Promise)],U.prototype,"healthcheck",null),c.__decorate([i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,String]),c.__metadata("design:returntype",Promise)],U.prototype,"createAll",null);let G=class extends o.BaseModel{constructor(e){super(e)}};c.__decorate([o.pk({type:"String"}),c.__metadata("design:type",String)],G.prototype,"name",void 0),c.__decorate([o.column(),r.required(),c.__metadata("design:type",String)],G.prototype,"owner",void 0),c.__decorate([o.column(),r.required(),c.__metadata("design:type",String)],G.prototype,"symbol",void 0),c.__decorate([o.column(),r.required(),c.__metadata("design:type",Number)],G.prototype,"decimals",void 0),G=c.__decorate([o.table("erc20_tokens"),r.model(),c.__metadata("design:paramtypes",[Object])],G);let H=class extends o.BaseModel{constructor(e){super(e)}};c.__decorate([o.pk({type:"String"}),c.__metadata("design:type",String)],H.prototype,"id",void 0),c.__decorate([o.column(),r.required(),c.__metadata("design:type",String)],H.prototype,"token",void 0),c.__decorate([o.column(),r.required(),c.__metadata("design:type",Number)],H.prototype,"balance",void 0),c.__decorate([o.column(),c.__metadata("design:type",String)],H.prototype,"captive",void 0),H=c.__decorate([o.table("erc20_wallets"),r.model(),c.__metadata("design:paramtypes",[Object])],H);let Q=class extends o.BaseModel{constructor(e){super(e)}};var Y;c.__decorate([o.pk({type:"String"}),o.column(),r.required(),c.__metadata("design:type",String)],Q.prototype,"owner",void 0),c.__decorate([o.column(),r.required(),c.__metadata("design:type",String)],Q.prototype,"spender",void 0),c.__decorate([o.column(),r.required(),c.__metadata("design:type",Number)],Q.prototype,"value",void 0),Q=c.__decorate([o.table("erc20_allowances"),r.model(),c.__metadata("design:paramtypes",[Object])],Q),(e=>{e.TRANSFER="Transfer",e.APPROVAL="Approval"})(Y||(Y={}));class X extends J{constructor(e){super(e,H),X.adapter=X.adapter||new j,this.walletRepository=R.forModel(H,X.adapter.alias),this.tokenRepository=R.forModel(G,X.adapter.alias),this.allowanceRepository=R.forModel(Q,X.adapter.alias)}async TokenName(e){await this.CheckInitialized(e);const t=await this.tokenRepository.selectWithContext(void 0,e);return(await t.execute())[0].name}async Symbol(e){await this.CheckInitialized(e);const t=await this.tokenRepository.selectWithContext(void 0,e);return(await t.execute())[0].symbol}async Decimals(e){await this.CheckInitialized(e);const t=await this.tokenRepository.selectWithContext(void 0,e);return(await t.execute())[0].decimals}async TotalSupply(e){await this.CheckInitialized(e);const t=await this.walletRepository.selectWithContext(void 0,e),r=await t.execute();if(0==r.length)throw new a.NotFoundError(`The token ${this.getName()} does not exist`);let i=0;return r.forEach(e=>{i+=e.balance}),i}async BalanceOf(e,t){return await this.CheckInitialized(e),(await this.walletRepository.read(t,e)).balance}async Transfer(e,t,r){await this.CheckInitialized(e);const i=e.clientIdentity.getID();if(!await this._transfer(e,i,t,r))throw new a.InternalError("Failed to transfer");return!0}async TransferFrom(e,t,r,i){await this.CheckInitialized(e);const n=e.clientIdentity.getID(),o=await this._getAllowance(e,t,n);if(!o||0>o.value)throw new A(`spender ${n} has no allowance from ${t}`);const s=o.value;if(i>s)throw new C("The spender does not have enough allowance to spend.");const c=W(s,i),l=Object.assign({},o,{value:c});if(await this.allowanceRepository.update(l,e),!await this._transfer(e,t,r,i))throw new a.InternalError("Failed to transfer");return!0}async _transfer(e,t,r,i){const n=this.logFor(e).for(this._transfer);if(t===r)throw new o.AuthorizationError("cannot transfer to and from same client account");if(0>i)throw new C("transfer amount cannot be negative");const s=await this.walletRepository.read(t,e),c=s.balance;if(i>c)throw new C(`client account ${t} has insufficient funds.`);let l,d=!1;try{l=await this.walletRepository.read(r,e)}catch(t){if(!(t instanceof a.BaseError))throw new a.InternalError(t);if(404!==t.code)throw new a.InternalError(t.message);l=new H({id:r,balance:0,token:await this.TokenName(e)}),d=!0}const p=l.balance,u=W(c,i),h=V(p,i),y=Object.assign({},s,{balance:u});await this.walletRepository.update(y,e);const g=Object.assign({},l,{balance:h});d?await this.walletRepository.create(g,e):await this.walletRepository.update(g,e);const f={from:t,to:r,value:i};return this.repo.ObserverHandler().updateObservers(n,"",Y.TRANSFER,"",e,"",f),!0}async Approve(e,t,r){await this.CheckInitialized(e);const a=this.logFor(e).for(this.Approve),i=e.clientIdentity.getID();let n=await this._getAllowance(e,i,t);if((await this.walletRepository.read(i,e)).balance<r)throw new C(`client account ${i} has insufficient funds.`);n?(n.value=r,await this.allowanceRepository.update(n,e)):(n=new Q({owner:i,spender:t,value:r}),await this.allowanceRepository.create(n,e));const o={owner:i,spender:t,value:r};return this.repo.ObserverHandler().updateObservers(a,"",Y.APPROVAL,"",e,"",o),!0}async Allowance(e,t,r){await this.CheckInitialized(e);const a=await this._getAllowance(e,t,r);if(!a)throw new A(`spender ${r} has no allowance from ${t}`);return a.value}async _getAllowance(e,t,r){const a=o.Condition.and(o.Condition.attribute("owner").eq(t),o.Condition.attribute("spender").eq(r)),i=await this.allowanceRepository.selectWithContext(void 0,e),n=await i.where(a).execute();return n?.[0]}async Initialize(e,t){const r=await this.tokenRepository.selectWithContext(void 0,e);if((await r.execute()).length>0)throw new o.AuthorizationError("contract options are already set, client is not authorized to change them");return t.owner=e.clientIdentity.getID(),await this.tokenRepository.create(t,e),!0}async CheckInitialized(e){const t=await this.tokenRepository.selectWithContext(void 0,e);if(0==(await t.execute()).length)throw new k("contract options need to be set before calling any function, call Initialize() to initialize contract")}async Mint(e,t){await this.CheckInitialized(e);const r=this.logFor(e).for(this.Mint),i=e.clientIdentity.getID();if(0>=t)throw new a.ValidationError("mint amount must be a positive integer");let n;try{n=await this.walletRepository.read(i,e);const r=V(n.balance,t),a=Object.assign({},n,{balance:r});await this.walletRepository.update(a,e)}catch(r){if(!(r instanceof a.BaseError))throw new a.InternalError(r);if(404!==r.code)throw new a.InternalError(r.message);{const r=new H({id:i,balance:t,token:await this.TokenName(e)});await this.walletRepository.create(r,e)}}const o={from:"0x0",to:i,value:t};this.repo.ObserverHandler().updateObservers(r,"",Y.TRANSFER,"",e,"",o)}async Burn(e,t){await this.CheckInitialized(e);const r=this.logFor(e).for(this.Burn),a=e.clientIdentity.getID(),i=await this.walletRepository.read(a,e),n=i.balance;if(t>n)throw new C("Minter has insufficient funds.");const o=W(n,t),s=Object.assign({},i,{balance:o});await this.walletRepository.update(s,e),r.info(t+" tokens were burned");const c={from:a,to:"0x0",value:t};this.repo.ObserverHandler().updateObservers(r,"",Y.TRANSFER,"",e,"",c)}async BurnFrom(e,t,r){await this.CheckInitialized(e);const a=this.logFor(e).for(this.BurnFrom),i=await this.walletRepository.read(t,e),n=i.balance;if(r>n)throw new C(t+" has insufficient funds.");const o=W(n,r),s=Object.assign({},i,{balance:o});await this.walletRepository.update(s,e),a.info(`${r} tokens were berned from ${t}`);const c={from:t,to:"0x0",value:r};this.repo.ObserverHandler().updateObservers(a,"",Y.TRANSFER,"",e,"",c)}async ClientAccountBalance(e){await this.CheckInitialized(e);const t=e.clientIdentity.getID(),r=await this.walletRepository.read(t,e);if(!r)throw new C(`The account ${t} does not exist`);return r.balance}async ClientAccountID(e){return await this.CheckInitialized(e),e.clientIdentity.getID()}}c.__decorate([i.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context]),c.__metadata("design:returntype",Promise)],X.prototype,"TokenName",null),c.__decorate([i.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context]),c.__metadata("design:returntype",Promise)],X.prototype,"Symbol",null),c.__decorate([i.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context]),c.__metadata("design:returntype",Promise)],X.prototype,"Decimals",null),c.__decorate([i.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context]),c.__metadata("design:returntype",Promise)],X.prototype,"TotalSupply",null),c.__decorate([i.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,String]),c.__metadata("design:returntype",Promise)],X.prototype,"BalanceOf",null),c.__decorate([i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,String,Number]),c.__metadata("design:returntype",Promise)],X.prototype,"Transfer",null),c.__decorate([i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,String,String,Number]),c.__metadata("design:returntype",Promise)],X.prototype,"TransferFrom",null),c.__decorate([i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,String,Number]),c.__metadata("design:returntype",Promise)],X.prototype,"Approve",null),c.__decorate([i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,String,String]),c.__metadata("design:returntype",Promise)],X.prototype,"Allowance",null),c.__decorate([i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,G]),c.__metadata("design:returntype",Promise)],X.prototype,"Initialize",null),c.__decorate([i.Transaction(!1),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context]),c.__metadata("design:returntype",Promise)],X.prototype,"CheckInitialized",null),c.__decorate([g(),i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,Number]),c.__metadata("design:returntype",Promise)],X.prototype,"Mint",null),c.__decorate([g(),i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,Number]),c.__metadata("design:returntype",Promise)],X.prototype,"Burn",null),c.__decorate([g(),i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context,String,Number]),c.__metadata("design:returntype",Promise)],X.prototype,"BurnFrom",null),c.__decorate([i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context]),c.__metadata("design:returntype",Promise)],X.prototype,"ClientAccountBalance",null),c.__decorate([i.Transaction(),c.__metadata("design:type",Function),c.__metadata("design:paramtypes",[i.Context]),c.__metadata("design:returntype",Promise)],X.prototype,"ClientAccountID",null);const Z=[X];class ee extends n.MiniLogger{constructor(e,t,r){super(e,t),this.logger=r?r.logger:new n.MiniLogger(e,t)}log(e,t,r){if(n.NumericLogLevels[this.config("level")]<n.NumericLogLevels[e])return;let a;switch(e){case n.LogLevel.info:a=this.logger.info;break;case n.LogLevel.verbose:a=this.logger.verbose;break;case n.LogLevel.debug:a=this.logger.debug;break;case n.LogLevel.error:a=this.logger.error;break;case n.LogLevel.silly:a=this.logger.silly;break;default:throw Error("Invalid log level")}a.call(this.logger,this.createLog(e,t,r))}}n.Logging.setFactory((e,t,r)=>new ee(e,t||{},r));const te="##VERSION##",re="##PACKAGE##";l.Metadata.registerLibrary(re,te),e.ContractLogger=ee,e.FabricContractAdapter=j,e.FabricContractContext=d,e.FabricContractRepository=R,e.FabricContractRepositoryObservableHandler=p,e.FabricContractSequence=x,e.FabricCrudContract=J,e.FabricStatement=F,e.PACKAGE_NAME=re,e.SerializedCrudContract=U,e.VERSION=te,e.contracts=Z,e.createdByOnFabricCreateUpdate=M,e.pkFabricOnCreate=q},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/for-couchdb"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/db-decorators"),require("fabric-contract-api"),require("@decaf-ts/logging"),require("@decaf-ts/core"),require("@decaf-ts/reflection"),require("tslib"),require("@decaf-ts/decoration")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/for-couchdb","@decaf-ts/decorator-validation","@decaf-ts/db-decorators","fabric-contract-api","@decaf-ts/logging","@decaf-ts/core","@decaf-ts/reflection","tslib","@decaf-ts/decoration"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-fabric"]={},e.decafTsForCouchdb,e.decafTsDecoratorValidation,e.decafTsDbDecorators,e.fabricContractApi,e.decafTsLogging,e.decafTsCore,e.decafTsReflection,e.tslib,e.decafTsDecoration);
|
|
2
2
|
//# sourceMappingURL=for-fabric.cjs.map
|