@decaf-ts/for-fabric 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/dist/for-fabric.cjs +1 -1
  2. package/dist/for-fabric.cjs.map +1 -1
  3. package/dist/for-fabric.js +1 -1
  4. package/dist/for-fabric.js.map +1 -1
  5. package/lib/client/FabricClientAdapter.cjs +94 -81
  6. package/lib/client/FabricClientAdapter.d.ts +24 -33
  7. package/lib/client/FabricClientAdapter.js.map +1 -1
  8. package/lib/client/FabricClientDispatch.cjs +14 -5
  9. package/lib/client/FabricClientDispatch.d.ts +7 -5
  10. package/lib/client/FabricClientDispatch.js.map +1 -1
  11. package/lib/client/FabricClientRepository.cjs +4 -137
  12. package/lib/client/FabricClientRepository.d.ts +6 -78
  13. package/lib/client/FabricClientRepository.js.map +1 -1
  14. package/lib/client/erc20/FabricERC20ClientRepository.cjs +17 -17
  15. package/lib/client/erc20/FabricERC20ClientRepository.d.ts +5 -5
  16. package/lib/client/erc20/FabricERC20ClientRepository.js.map +1 -1
  17. package/lib/client/logging.cjs +1 -1
  18. package/lib/client/logging.js.map +1 -1
  19. package/lib/client/services/FabricEnrollmentService.cjs +3 -3
  20. package/lib/client/services/FabricEnrollmentService.d.ts +2 -2
  21. package/lib/client/services/FabricEnrollmentService.js.map +1 -1
  22. package/lib/contract/Product.cjs +2 -2
  23. package/lib/contract/Product.d.ts +1 -1
  24. package/lib/contracts/ContractAdapter.cjs +204 -115
  25. package/lib/contracts/ContractAdapter.d.ts +26 -34
  26. package/lib/contracts/ContractAdapter.js.map +1 -1
  27. package/lib/contracts/ContractContext.cjs +1 -9
  28. package/lib/contracts/ContractContext.d.ts +0 -6
  29. package/lib/contracts/ContractContext.js.map +1 -1
  30. package/lib/contracts/ContractPrivateDataAdapter.cjs +429 -288
  31. package/lib/contracts/ContractPrivateDataAdapter.d.ts +0 -76
  32. package/lib/contracts/ContractPrivateDataAdapter.js.map +1 -1
  33. package/lib/contracts/FabricConstruction.cjs +3 -3
  34. package/lib/contracts/FabricConstruction.d.ts +9 -8
  35. package/lib/contracts/FabricConstruction.js.map +1 -1
  36. package/lib/contracts/FabricContractRepository.cjs +7 -202
  37. package/lib/contracts/FabricContractRepository.d.ts +5 -68
  38. package/lib/contracts/FabricContractRepository.js.map +1 -1
  39. package/lib/contracts/FabricContractRepositoryObservableHandler.cjs +4 -1
  40. package/lib/contracts/FabricContractRepositoryObservableHandler.d.ts +4 -4
  41. package/lib/contracts/FabricContractRepositoryObservableHandler.js.map +1 -1
  42. package/lib/contracts/FabricContractSequence.cjs +39 -60
  43. package/lib/contracts/FabricContractSequence.d.ts +29 -41
  44. package/lib/contracts/FabricContractSequence.js.map +1 -1
  45. package/lib/contracts/FabricContractStatement.cjs +6 -6
  46. package/lib/contracts/FabricContractStatement.d.ts +4 -6
  47. package/lib/contracts/FabricContractStatement.js.map +1 -1
  48. package/lib/contracts/crud/crud-contract.cjs +74 -44
  49. package/lib/contracts/crud/crud-contract.d.ts +7 -11
  50. package/lib/contracts/crud/crud-contract.js.map +1 -1
  51. package/lib/contracts/crud/serialized-crud-contract.cjs +12 -21
  52. package/lib/contracts/crud/serialized-crud-contract.d.ts +3 -11
  53. package/lib/contracts/crud/serialized-crud-contract.js.map +1 -1
  54. package/lib/contracts/erc20/erc20contract.cjs +73 -67
  55. package/lib/contracts/erc20/erc20contract.d.ts +13 -12
  56. package/lib/contracts/erc20/erc20contract.js.map +1 -1
  57. package/lib/contracts/logging.cjs +9 -13
  58. package/lib/contracts/logging.d.ts +1 -2
  59. package/lib/contracts/logging.js.map +1 -1
  60. package/lib/contracts/private-data.cjs +202 -118
  61. package/lib/contracts/private-data.d.ts +0 -16
  62. package/lib/contracts/private-data.js.map +1 -1
  63. package/lib/contracts/types.d.ts +1 -1
  64. package/lib/esm/client/FabricClientAdapter.d.ts +24 -33
  65. package/lib/esm/client/FabricClientAdapter.js +90 -78
  66. package/lib/esm/client/FabricClientAdapter.js.map +1 -1
  67. package/lib/esm/client/FabricClientDispatch.d.ts +7 -5
  68. package/lib/esm/client/FabricClientDispatch.js +17 -8
  69. package/lib/esm/client/FabricClientDispatch.js.map +1 -1
  70. package/lib/esm/client/FabricClientRepository.d.ts +6 -78
  71. package/lib/esm/client/FabricClientRepository.js +4 -137
  72. package/lib/esm/client/FabricClientRepository.js.map +1 -1
  73. package/lib/esm/client/erc20/FabricERC20ClientRepository.d.ts +5 -5
  74. package/lib/esm/client/erc20/FabricERC20ClientRepository.js +17 -17
  75. package/lib/esm/client/erc20/FabricERC20ClientRepository.js.map +1 -1
  76. package/lib/esm/client/logging.js +1 -1
  77. package/lib/esm/client/logging.js.map +1 -1
  78. package/lib/esm/client/services/FabricEnrollmentService.d.ts +2 -2
  79. package/lib/esm/client/services/FabricEnrollmentService.js +3 -3
  80. package/lib/esm/client/services/FabricEnrollmentService.js.map +1 -1
  81. package/lib/esm/contract/Product.d.ts +1 -1
  82. package/lib/esm/contract/Product.js +2 -2
  83. package/lib/esm/contracts/ContractAdapter.d.ts +26 -34
  84. package/lib/esm/contracts/ContractAdapter.js +205 -116
  85. package/lib/esm/contracts/ContractAdapter.js.map +1 -1
  86. package/lib/esm/contracts/ContractContext.d.ts +0 -6
  87. package/lib/esm/contracts/ContractContext.js +1 -9
  88. package/lib/esm/contracts/ContractContext.js.map +1 -1
  89. package/lib/esm/contracts/ContractPrivateDataAdapter.d.ts +0 -76
  90. package/lib/esm/contracts/ContractPrivateDataAdapter.js +430 -285
  91. package/lib/esm/contracts/ContractPrivateDataAdapter.js.map +1 -1
  92. package/lib/esm/contracts/FabricConstruction.d.ts +9 -8
  93. package/lib/esm/contracts/FabricConstruction.js +3 -3
  94. package/lib/esm/contracts/FabricConstruction.js.map +1 -1
  95. package/lib/esm/contracts/FabricContractRepository.d.ts +5 -68
  96. package/lib/esm/contracts/FabricContractRepository.js +7 -202
  97. package/lib/esm/contracts/FabricContractRepository.js.map +1 -1
  98. package/lib/esm/contracts/FabricContractRepositoryObservableHandler.d.ts +4 -4
  99. package/lib/esm/contracts/FabricContractRepositoryObservableHandler.js +5 -2
  100. package/lib/esm/contracts/FabricContractRepositoryObservableHandler.js.map +1 -1
  101. package/lib/esm/contracts/FabricContractSequence.d.ts +29 -41
  102. package/lib/esm/contracts/FabricContractSequence.js +40 -61
  103. package/lib/esm/contracts/FabricContractSequence.js.map +1 -1
  104. package/lib/esm/contracts/FabricContractStatement.d.ts +4 -6
  105. package/lib/esm/contracts/FabricContractStatement.js +7 -7
  106. package/lib/esm/contracts/FabricContractStatement.js.map +1 -1
  107. package/lib/esm/contracts/crud/crud-contract.d.ts +7 -11
  108. package/lib/esm/contracts/crud/crud-contract.js +75 -45
  109. package/lib/esm/contracts/crud/crud-contract.js.map +1 -1
  110. package/lib/esm/contracts/crud/serialized-crud-contract.d.ts +3 -11
  111. package/lib/esm/contracts/crud/serialized-crud-contract.js +12 -21
  112. package/lib/esm/contracts/crud/serialized-crud-contract.js.map +1 -1
  113. package/lib/esm/contracts/erc20/erc20contract.d.ts +13 -12
  114. package/lib/esm/contracts/erc20/erc20contract.js +73 -67
  115. package/lib/esm/contracts/erc20/erc20contract.js.map +1 -1
  116. package/lib/esm/contracts/logging.d.ts +1 -2
  117. package/lib/esm/contracts/logging.js +9 -13
  118. package/lib/esm/contracts/logging.js.map +1 -1
  119. package/lib/esm/contracts/private-data.d.ts +0 -16
  120. package/lib/esm/contracts/private-data.js +203 -111
  121. package/lib/esm/contracts/private-data.js.map +1 -1
  122. package/lib/esm/contracts/types.d.ts +1 -1
  123. package/lib/esm/shared/decorators.d.ts +14 -4
  124. package/lib/esm/shared/decorators.js +142 -42
  125. package/lib/esm/shared/decorators.js.map +1 -1
  126. package/lib/esm/shared/errors.js +2 -2
  127. package/lib/esm/shared/errors.js.map +1 -1
  128. package/lib/esm/shared/events.d.ts +1 -5
  129. package/lib/esm/shared/events.js.map +1 -1
  130. package/lib/esm/shared/model/Sequence.d.ts +14 -0
  131. package/lib/esm/shared/model/Sequence.js +33 -0
  132. package/lib/esm/shared/model/Sequence.js.map +1 -0
  133. package/lib/esm/shared/model/index.d.ts +2 -0
  134. package/lib/esm/shared/model/index.js +2 -0
  135. package/lib/esm/shared/model/index.js.map +1 -1
  136. package/lib/esm/version.d.ts +1 -1
  137. package/lib/esm/version.js +1 -1
  138. package/lib/shared/decorators.cjs +148 -41
  139. package/lib/shared/decorators.d.ts +14 -4
  140. package/lib/shared/decorators.js.map +1 -1
  141. package/lib/shared/errors.cjs +2 -2
  142. package/lib/shared/errors.js.map +1 -1
  143. package/lib/shared/events.d.ts +1 -5
  144. package/lib/shared/events.js.map +1 -1
  145. package/lib/shared/model/Sequence.cjs +36 -0
  146. package/lib/shared/model/Sequence.d.ts +14 -0
  147. package/lib/shared/model/Sequence.js.map +1 -0
  148. package/lib/shared/model/index.cjs +2 -0
  149. package/lib/shared/model/index.d.ts +2 -0
  150. package/lib/shared/model/index.js.map +1 -1
  151. package/lib/version.cjs +1 -1
  152. package/lib/version.d.ts +1 -1
  153. package/package.json +2 -3
  154. package/lib/client/services/LoggedService.cjs +0 -47
  155. package/lib/client/services/LoggedService.d.ts +0 -42
  156. package/lib/client/services/LoggedService.js.map +0 -1
  157. package/lib/esm/client/services/LoggedService.d.ts +0 -42
  158. package/lib/esm/client/services/LoggedService.js +0 -43
  159. package/lib/esm/client/services/LoggedService.js.map +0 -1
@@ -2,11 +2,11 @@ import { CouchDBAdapter, MangoQuery } from "@decaf-ts/for-couchdb";
2
2
  import { Model } from "@decaf-ts/decorator-validation";
3
3
  import { FabricContractFlags } from "./types";
4
4
  import { FabricContractContext } from "./ContractContext";
5
- import { Context, OperationKeys } from "@decaf-ts/db-decorators";
5
+ import { BaseError, Context, OperationKeys, PrimaryKeyType } from "@decaf-ts/db-decorators";
6
6
  import { Context as Ctx } from "fabric-contract-api";
7
7
  import { Logger } from "@decaf-ts/logging";
8
- import { ContractLogger } from "./logging";
9
- import { RelationsMetadata, Repository, Sequence, SequenceOptions, Adapter } from "@decaf-ts/core";
8
+ import { RelationsMetadata, Sequence, SequenceOptions, Adapter, PreparedModel, Repository } from "@decaf-ts/core";
9
+ import type { ContextualArgs, MaybeContextualArg } from "@decaf-ts/core";
10
10
  import { FabricContractRepository } from "./FabricContractRepository";
11
11
  import { ChaincodeStub, Iterators, StateQueryResponse } from "fabric-shim-api";
12
12
  import { FabricStatement } from "./FabricContractStatement";
@@ -67,7 +67,7 @@ export declare function createdByOnFabricCreateUpdate<M extends Model, R extends
67
67
  * S-->>R: next value
68
68
  * R->>M: define non-writable primary key
69
69
  */
70
- export declare function pkFabricOnCreate<M extends Model, R extends FabricContractRepository<M>, V extends SequenceOptions, F extends FabricContractFlags>(this: R, context: Context<F>, data: V, key: keyof M, model: M): Promise<void>;
70
+ export declare function pkFabricOnCreate<M extends Model, R extends FabricContractRepository<M>>(this: R, context: FabricContractContext, data: SequenceOptions, key: keyof M, model: M): Promise<void>;
71
71
  /**
72
72
  * @description Adapter for Hyperledger Fabric chaincode state database operations
73
73
  * @summary Provides a CouchDB-like interface for interacting with the Fabric state database from within a chaincode contract
@@ -105,20 +105,13 @@ export declare function pkFabricOnCreate<M extends Model, R extends FabricContra
105
105
  * Stub-->>FabricContractAdapter: Success
106
106
  * FabricContractAdapter-->>Contract: model
107
107
  */
108
- export declare class FabricContractAdapter extends CouchDBAdapter<any, void, FabricContractFlags, FabricContractContext> {
108
+ export declare class FabricContractAdapter extends CouchDBAdapter<any, void, FabricContractContext> {
109
109
  protected getClient(): void;
110
110
  /**
111
111
  * @description Text decoder for converting binary data to strings
112
112
  */
113
113
  private static textDecoder;
114
114
  protected static readonly serializer: SimpleDeterministicSerializer<Model<false>>;
115
- /**
116
- * @description Creates a logger for a specific chaincode context
117
- * @summary Returns a ContractLogger instance configured for the current context
118
- * @param {Ctx} ctx - The Fabric chaincode context
119
- * @return {ContractLogger} The logger instance
120
- */
121
- logFor(ctx: Ctx): ContractLogger;
122
115
  /**
123
116
  * @description Context constructor for this adapter
124
117
  * @summary Overrides the base Context constructor with FabricContractContext
@@ -130,7 +123,7 @@ export declare class FabricContractAdapter extends CouchDBAdapter<any, void, Fab
130
123
  * @template M - Type extending Model
131
124
  * @return {Constructor<Repository<M, MangoQuery, FabricContractAdapter, FabricContractFlags, FabricContractContext>>} The repository constructor
132
125
  */
133
- repository<M extends Model>(): Constructor<Repository<M, MangoQuery, Adapter<any, any, MangoQuery, FabricContractFlags, FabricContractContext>, FabricContractFlags, FabricContractContext>>;
126
+ repository<R extends Repository<any, Adapter<any, void, MangoQuery, FabricContractContext>>>(): Constructor<R>;
134
127
  /**
135
128
  * @description Creates a new FabricContractAdapter instance
136
129
  * @summary Initializes an adapter for interacting with the Fabric state database
@@ -149,7 +142,7 @@ export declare class FabricContractAdapter extends CouchDBAdapter<any, void, Fab
149
142
  * @param {...any[]} args - Additional arguments, including the chaincode stub and logger
150
143
  * @return {Promise<Record<string, any>>} Promise resolving to the created record
151
144
  */
152
- create(tableName: string, id: string | number, model: Record<string, any>, ...args: any[]): Promise<Record<string, any>>;
145
+ create<M extends Model>(clazz: Constructor<M>, id: PrimaryKeyType, model: Record<string, any>, ...args: ContextualArgs<FabricContractContext>): Promise<Record<string, any>>;
153
146
  /**
154
147
  * @description Reads a record from the state database
155
148
  * @summary Retrieves and deserializes a record from the Fabric state database
@@ -158,7 +151,7 @@ export declare class FabricContractAdapter extends CouchDBAdapter<any, void, Fab
158
151
  * @param {...any[]} args - Additional arguments, including the chaincode stub and logger
159
152
  * @return {Promise<Record<string, any>>} Promise resolving to the retrieved record
160
153
  */
161
- read(tableName: string, id: string | number, ...args: any[]): Promise<Record<string, any>>;
154
+ read<M extends Model>(clazz: Constructor<M>, id: PrimaryKeyType, ...args: ContextualArgs<FabricContractContext>): Promise<Record<string, any>>;
162
155
  /**
163
156
  * @description Updates a record in the state database
164
157
  * @summary Serializes a model and updates it in the Fabric state database
@@ -169,7 +162,7 @@ export declare class FabricContractAdapter extends CouchDBAdapter<any, void, Fab
169
162
  * @param {...any[]} args - Additional arguments, including the chaincode stub and logger
170
163
  * @return {Promise<Record<string, any>>} Promise resolving to the updated record
171
164
  */
172
- update(tableName: string, id: string | number, model: Record<string, any>, ...args: any[]): Promise<Record<string, any>>;
165
+ update<M extends Model>(clazz: Constructor<M>, id: PrimaryKeyType, model: Record<string, any>, ...args: ContextualArgs<FabricContractContext>): Promise<Record<string, any>>;
173
166
  /**
174
167
  * @description Deletes a record from the state database
175
168
  * @summary Retrieves a record and then removes it from the Fabric state database
@@ -178,10 +171,11 @@ export declare class FabricContractAdapter extends CouchDBAdapter<any, void, Fab
178
171
  * @param {...any[]} args - Additional arguments, including the chaincode stub and logger
179
172
  * @return {Promise<Record<string, any>>} Promise resolving to the deleted record
180
173
  */
181
- delete(tableName: string, id: string | number, ...args: any[]): Promise<Record<string, any>>;
182
- protected deleteState(stub: ChaincodeStub, tableName: string, id: string, ...args: any[]): Promise<void>;
183
- protected putState(stub: ChaincodeStub, id: string, model: Record<string, any>, ...args: any[]): Promise<Record<string, any>>;
184
- protected readState(stub: ChaincodeStub, tableName: string, id: string, ...args: any[]): Promise<any[]>;
174
+ delete<M extends Model>(clazz: Constructor<M>, id: PrimaryKeyType, ...args: ContextualArgs<FabricContractContext>): Promise<Record<string, any>>;
175
+ protected deleteState(id: string, ctx: FabricContractContext): Promise<void>;
176
+ forPrivate(collection: string): FabricContractAdapter;
177
+ protected putState(id: string, model: Record<string, any>, ctx: FabricContractContext): Promise<Record<string, any>>;
178
+ protected readState(id: string, ctx: FabricContractContext): Promise<any>;
185
179
  protected queryResult(stub: ChaincodeStub, rawInput: any, ...args: any[]): Promise<Iterators.StateQueryIterator>;
186
180
  protected queryResultPaginated(stub: ChaincodeStub, rawInput: any, limit?: number, skip?: number, ...args: any[]): Promise<StateQueryResponse<Iterators.StateQueryIterator>>;
187
181
  protected mergeModels(results: Record<string, any>[]): Record<string, any>;
@@ -265,27 +259,25 @@ export declare class FabricContractAdapter extends CouchDBAdapter<any, void, Fab
265
259
  * FabricContractAdapter->>FabricContractAdapter: resultIterator(log, iterator)
266
260
  * FabricContractAdapter-->>Caller: results
267
261
  */
268
- raw<R>(rawInput: MangoQuery, docsOnly: boolean, ...args: any[]): Promise<R>;
269
- Statement<M extends Model>(ctx?: FabricContractContext): FabricStatement<M, any>;
262
+ raw<R>(rawInput: MangoQuery, ...args: ContextualArgs<FabricContractContext>): Promise<R>;
263
+ Statement<M extends Model>(): FabricStatement<M, any>;
270
264
  Sequence(options: SequenceOptions): Promise<Sequence>;
271
- createAll(tableName: string, id: (string | number)[], model: Record<string, any>[], ...args: any[]): Promise<Record<string, any>[]>;
272
- updateAll(tableName: string, id: string[] | number[], model: Record<string, any>[], ...args: any[]): Promise<Record<string, any>[]>;
265
+ createAll<M extends Model>(tableName: Constructor<M>, id: PrimaryKeyType[], model: Record<string, any>[], ...args: ContextualArgs<FabricContractContext>): Promise<Record<string, any>[]>;
266
+ updateAll<M extends Model>(tableName: Constructor<M>, id: PrimaryKeyType[], model: Record<string, any>[], ...args: ContextualArgs<FabricContractContext>): Promise<Record<string, any>[]>;
273
267
  /**
274
268
  *
275
269
  * @param model
276
270
  * @param {string} pk
277
271
  * @param args
278
272
  */
279
- prepare<M extends Model>(model: M, pk: keyof M, ...args: any[]): {
280
- record: Record<string, any>;
281
- id: string;
282
- transient?: Record<string, any>;
283
- };
284
- revert<M extends Model>(obj: Record<string, any>, clazz: string | Constructor<M>, pk: keyof M, id: string | number, transient?: Record<string, any>): M;
285
- createPrefix(tableName: string, id: string | number, model: Record<string, any>, ...args: any[]): (string | number | FabricContractContext | Record<string, any>)[];
286
- updatePrefix(tableName: string, id: string | number, model: Record<string, any>, ...args: any[]): (string | number | Record<string, any>)[];
287
- protected createAllPrefix(tableName: string, ids: string[] | number[], models: Record<string, any>[], ...args: any[]): (string | string[] | number[] | Record<string, any>[])[];
288
- protected updateAllPrefix(tableName: string, ids: string[] | number[], models: Record<string, any>[], ...args: any[]): any[];
273
+ prepare<M extends Model>(model: M, ...args: ContextualArgs<FabricContractContext>): PreparedModel;
274
+ revert<M extends Model>(obj: Record<string, any>, clazz: Constructor<M>, id: PrimaryKeyType, transient?: Record<string, any>, ...args: ContextualArgs<FabricContractContext>): M;
275
+ createPrefix<M extends Model>(tableName: Constructor<M>, id: PrimaryKeyType, model: Record<string, any>, ...args: MaybeContextualArg<FabricContractContext>): [Constructor<M>, PrimaryKeyType, Record<string, any>, ...any[], FabricContractContext];
276
+ updatePrefix<M extends Model>(tableName: Constructor<M>, id: PrimaryKeyType, model: Record<string, any>, ...args: MaybeContextualArg<FabricContractContext>): any[];
277
+ protected createAllPrefix<M extends Model>(tableName: Constructor<M>, ids: PrimaryKeyType[], models: Record<string, any>[], ...args: [...any, FabricContractContext]): (string | string[] | number[] | Record<string, any>[])[];
278
+ protected updateAllPrefix<M extends Model>(tableName: Constructor<M>, ids: PrimaryKeyType[], models: Record<string, any>[], ...args: [...any, FabricContractContext]): any[];
279
+ parseError<E extends BaseError>(err: Error | string, reason?: string): E;
280
+ static parseError<E extends BaseError>(err: Error | string, reason?: string): E;
289
281
  /**
290
282
  * @description Static method for decoration overrides
291
283
  * @summary Overrides/extends decaf decoration with Fabric-specific functionality
@@ -3,12 +3,10 @@ import { list, Model, required, type } from "@decaf-ts/decorator-validation";
3
3
  import { FabricContractContext } from "./ContractContext.js";
4
4
  import { afterAny, DBKeys, InternalError, NotFoundError, onCreate, onCreateUpdate, onDelete, onUpdate, readonly, SerializationError, } from "@decaf-ts/db-decorators";
5
5
  import { Object as FabricObject, Property as FabricProperty, } from "fabric-contract-api";
6
- import { Logging } from "@decaf-ts/logging";
7
- import { PersistenceKeys, Repository, sequenceNameForModel, UnsupportedError, Adapter, oneToManyOnUpdate, relation, } from "@decaf-ts/core";
6
+ import { PersistenceKeys, UnsupportedError, Adapter, oneToManyOnUpdate, relation, } from "@decaf-ts/core";
8
7
  import { FabricContractRepository } from "./FabricContractRepository.js";
9
8
  import { FabricStatement } from "./FabricContractStatement.js";
10
9
  import { FabricContractSequence } from "./FabricContractSequence.js";
11
- import { MissingContextError } from "./../shared/errors.js";
12
10
  import { FabricFlavour } from "./../shared/constants.js";
13
11
  import { SimpleDeterministicSerializer } from "./../shared/SimpleDeterministicSerializer.js";
14
12
  import { oneToManyOnCreate, oneToManyOnDelete, oneToOneOnCreate, oneToOneOnDelete, oneToOneOnUpdate, populate as pop, } from "./FabricConstruction.js";
@@ -41,7 +39,7 @@ import { apply, Decoration, prop, propMetadata, Metadata, } from "@decaf-ts/deco
41
39
  */
42
40
  export async function createdByOnFabricCreateUpdate(context, data, key, model) {
43
41
  try {
44
- const user = context.get("clientIdentity");
42
+ const user = context.get("identity");
45
43
  model[key] = user.getID();
46
44
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
47
45
  }
@@ -90,7 +88,7 @@ export async function pkFabricOnCreate(context, data, key, model) {
90
88
  });
91
89
  };
92
90
  if (!data.name)
93
- data.name = sequenceNameForModel(model, "pk");
91
+ data.name = Model.sequenceName(model, "pk");
94
92
  let sequence;
95
93
  try {
96
94
  sequence = (await this.adapter.Sequence(data));
@@ -147,15 +145,6 @@ export class FabricContractAdapter extends CouchDBAdapter {
147
145
  */
148
146
  static { this.textDecoder = new TextDecoder("utf8"); }
149
147
  static { this.serializer = new SimpleDeterministicSerializer(); }
150
- /**
151
- * @description Creates a logger for a specific chaincode context
152
- * @summary Returns a ContractLogger instance configured for the current context
153
- * @param {Ctx} ctx - The Fabric chaincode context
154
- * @return {ContractLogger} The logger instance
155
- */
156
- logFor(ctx) {
157
- return Logging.for(FabricContractAdapter, {}, ctx);
158
- }
159
148
  /**
160
149
  * @description Gets the repository constructor for this adapter
161
150
  * @summary Returns the FabricContractRepository constructor for creating repositories
@@ -192,12 +181,14 @@ export class FabricContractAdapter extends CouchDBAdapter {
192
181
  * @param {...any[]} args - Additional arguments, including the chaincode stub and logger
193
182
  * @return {Promise<Record<string, any>>} Promise resolving to the created record
194
183
  */
195
- async create(tableName, id, model, ...args) {
196
- const { stub, logger } = args.pop();
197
- const log = logger.for(this.create);
184
+ async create(clazz, id, model, ...args) {
185
+ const { ctx, log } = this.logCtx(args, this.create);
186
+ const { stub } = ctx;
187
+ const tableName = Model.tableName(clazz);
198
188
  try {
199
189
  log.info(`adding entry to ${tableName} table with pk ${id}`);
200
- model = await this.putState(stub, id.toString(), model);
190
+ const composedKey = stub.createCompositeKey(tableName, [String(id)]);
191
+ model = await this.putState(composedKey, model, ctx);
201
192
  }
202
193
  catch (e) {
203
194
  throw this.parseError(e);
@@ -212,12 +203,14 @@ export class FabricContractAdapter extends CouchDBAdapter {
212
203
  * @param {...any[]} args - Additional arguments, including the chaincode stub and logger
213
204
  * @return {Promise<Record<string, any>>} Promise resolving to the retrieved record
214
205
  */
215
- async read(tableName, id, ...args) {
216
- const { stub, logger } = args.pop();
217
- const log = logger.for(this.read);
206
+ async read(clazz, id, ...args) {
207
+ const { ctx, log } = this.logCtx(args, this.read);
208
+ const { stub } = ctx;
209
+ const tableName = Model.tableName(clazz);
218
210
  let model;
219
211
  try {
220
- const results = await this.readState(stub, tableName, id.toString());
212
+ const composedKey = stub.createCompositeKey(tableName, [String(id)]);
213
+ const results = await this.readState(composedKey, ctx);
221
214
  if (results.length < 1) {
222
215
  log.debug(`No record found for id ${id} in ${tableName} table`);
223
216
  throw new NotFoundError(`No record found for id ${id} in ${tableName} table`);
@@ -245,12 +238,14 @@ export class FabricContractAdapter extends CouchDBAdapter {
245
238
  * @param {...any[]} args - Additional arguments, including the chaincode stub and logger
246
239
  * @return {Promise<Record<string, any>>} Promise resolving to the updated record
247
240
  */
248
- async update(tableName, id, model, ...args) {
249
- const { stub, logger } = args.pop();
250
- const log = logger.for(this.update);
241
+ async update(clazz, id, model, ...args) {
242
+ const { ctx, log } = this.logCtx(args, this.update);
243
+ const { stub } = ctx;
244
+ const tableName = Model.tableName(clazz);
251
245
  try {
252
- log.info(`updating entry to ${tableName} table with pk ${id}`);
253
- model = await this.putState(stub, id.toString(), model);
246
+ log.verbose(`updating entry to ${tableName} table with pk ${id}`);
247
+ const composedKey = stub.createCompositeKey(tableName, [String(id)]);
248
+ model = await this.putState(composedKey, model, ctx);
254
249
  }
255
250
  catch (e) {
256
251
  throw this.parseError(e);
@@ -265,32 +260,120 @@ export class FabricContractAdapter extends CouchDBAdapter {
265
260
  * @param {...any[]} args - Additional arguments, including the chaincode stub and logger
266
261
  * @return {Promise<Record<string, any>>} Promise resolving to the deleted record
267
262
  */
268
- async delete(tableName, id, ...args) {
269
- const ctx = args.pop();
270
- const { stub, logger } = ctx;
271
- const log = logger.for(this.delete);
272
- args.push(ctx);
263
+ async delete(clazz, id, ...args) {
264
+ const { ctx, log, ctxArgs } = this.logCtx(args, this.delete);
265
+ const { stub } = ctx;
266
+ const tableName = Model.tableName(clazz);
273
267
  let model;
274
268
  try {
275
- model = await this.read(tableName, id, ...args);
269
+ const composedKey = stub.createCompositeKey(tableName, [String(id)]);
270
+ model = await this.read(clazz, id, ...ctxArgs);
276
271
  log.verbose(`deleting entry with pk ${id} from ${tableName} table`);
277
- this.deleteState(stub, tableName, id.toString());
272
+ await this.deleteState(composedKey, ctx);
278
273
  }
279
274
  catch (e) {
280
275
  throw this.parseError(e);
281
276
  }
282
277
  return model;
283
278
  }
284
- async deleteState(stub, tableName, id,
285
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
286
- ...args) {
287
- const composedKey = stub.createCompositeKey(tableName, [String(id)]);
288
- await stub.deleteState(composedKey);
279
+ async deleteState(id, ctx) {
280
+ const { stub, logger } = ctx;
281
+ const log = logger.for(this.deleteState);
282
+ await stub.deleteState(id);
283
+ log.trace(`Deleted state for id ${id}`);
284
+ }
285
+ forPrivate(collection) {
286
+ const toOverride = [
287
+ this.putState,
288
+ this.readState,
289
+ this.deleteState,
290
+ this.queryResult,
291
+ this.queryResultPaginated,
292
+ ].map((fn) => fn.name);
293
+ return new Proxy(this, {
294
+ get(target, prop, receiver) {
295
+ if (!toOverride.includes(prop))
296
+ return Reflect.get(target, prop, receiver);
297
+ return new Proxy(target[prop], {
298
+ async apply(fn, thisArg, argsList) {
299
+ switch (prop) {
300
+ case "putState": {
301
+ const [stub, id, model] = argsList;
302
+ await stub.putPrivateData(collection, id.toString(), model);
303
+ return model;
304
+ }
305
+ case "deleteState": {
306
+ const [stub, id] = argsList;
307
+ return stub.deletePrivateData(collection, id);
308
+ }
309
+ case "readState": {
310
+ const [stub, id] = argsList;
311
+ return stub.getPrivateData(collection, id);
312
+ }
313
+ case "queryResult": {
314
+ const [stub, rawInput] = argsList;
315
+ return stub.getPrivateDataQueryResult(collection, rawInput);
316
+ }
317
+ case "queryResultPaginated": {
318
+ const [stub, rawInput, limit, skip] = argsList;
319
+ const iterator = await stub.getPrivateDataQueryResult(collection, rawInput);
320
+ const results = [];
321
+ let count = 0;
322
+ let reachedBookmark = skip ? false : true;
323
+ let lastKey = null;
324
+ while (true) {
325
+ const res = await iterator.next();
326
+ if (res.value && res.value.value.toString()) {
327
+ const recordKey = res.value.key;
328
+ const recordValue = res.value.value.toString("utf8");
329
+ // If we have a skip, skip until we reach it
330
+ if (!reachedBookmark) {
331
+ if (recordKey === skip?.toString()) {
332
+ reachedBookmark = true;
333
+ }
334
+ continue;
335
+ }
336
+ results.push({
337
+ Key: recordKey,
338
+ Record: JSON.parse(recordValue),
339
+ });
340
+ lastKey = recordKey;
341
+ count++;
342
+ if (count >= limit) {
343
+ await iterator.close();
344
+ return {
345
+ iterator: results,
346
+ metadata: {
347
+ fetchedRecordsCount: results.length,
348
+ bookmark: lastKey,
349
+ },
350
+ };
351
+ }
352
+ }
353
+ if (res.done) {
354
+ await iterator.close();
355
+ return {
356
+ iterator: results,
357
+ metadata: {
358
+ fetchedRecordsCount: results.length,
359
+ bookmark: "",
360
+ },
361
+ };
362
+ }
363
+ }
364
+ }
365
+ default:
366
+ throw new InternalError(`Unsupported method override ${String(prop)}`);
367
+ }
368
+ },
369
+ });
370
+ },
371
+ });
289
372
  }
290
- async putState(stub, id, model,
291
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
292
- ...args) {
373
+ async putState(id, model, ctx) {
293
374
  let data;
375
+ const { stub, logger } = ctx;
376
+ const log = logger.for(this.putState);
294
377
  try {
295
378
  data = Buffer.from(FabricContractAdapter.serializer.serialize(model));
296
379
  }
@@ -298,26 +381,24 @@ export class FabricContractAdapter extends CouchDBAdapter {
298
381
  throw new SerializationError(`Failed to serialize record with id ${id}: ${e}`);
299
382
  }
300
383
  await stub.putState(id.toString(), data);
384
+ log.silly(`state stored under id ${id}`);
301
385
  return model;
302
386
  }
303
- async readState(stub, tableName, id,
304
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
305
- ...args) {
306
- const composedKey = stub.createCompositeKey(tableName, [String(id)]);
307
- const results = [];
308
- let res = await stub.getState(composedKey);
309
- if (res.toString() === "")
387
+ async readState(id, ctx) {
388
+ let result;
389
+ const { stub, logger } = ctx;
390
+ const log = logger.for(this.readState);
391
+ const res = (await stub.getState(id)).toString();
392
+ if (!res)
310
393
  throw new NotFoundError(`Record with id ${id} not found`);
394
+ log.silly(`Read state for id ${id}`);
311
395
  try {
312
- res = FabricContractAdapter.serializer.deserialize(res.toString()
313
- // model.constructor.name
314
- );
396
+ result = FabricContractAdapter.serializer.deserialize(res.toString());
315
397
  }
316
398
  catch (e) {
317
399
  throw new SerializationError(`Failed to parse record: ${e}`);
318
400
  }
319
- results.push(res);
320
- return results;
401
+ return result;
321
402
  }
322
403
  async queryResult(stub, rawInput,
323
404
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -361,10 +442,32 @@ export class FabricContractAdapter extends CouchDBAdapter {
361
442
  * @return {FabricContractFlags} The merged flags
362
443
  */
363
444
  async flags(operation, model, flags, ctx, ...args) {
364
- return Object.assign(await super.flags(operation, model, flags, ...args), {
445
+ const ensureLogger = (logger) => {
446
+ const base = logger ?? this.log.for(this.flags);
447
+ if (typeof base.clear !== "function")
448
+ base.clear = () => base;
449
+ if (typeof base.for !== "function")
450
+ base.for = () => base;
451
+ return base;
452
+ };
453
+ const fabricCtx = ctx instanceof FabricContractContext
454
+ ? ctx.accumulate({
455
+ logger: ensureLogger(ctx.logger),
456
+ })
457
+ : new FabricContractContext().accumulate({
458
+ stub: ctx.stub,
459
+ identity: ctx.clientIdentity,
460
+ logger: ensureLogger(),
461
+ });
462
+ const baseFlags = Object.assign({}, flags, {
463
+ logger: fabricCtx.logger,
464
+ });
465
+ return Object.assign(await super.flags(operation, model, baseFlags, ...args), {
365
466
  stub: ctx.stub,
366
- identity: ctx.clientIdentity ?? ctx.identity,
367
- logger: ctx.logger ?? this.logFor(ctx),
467
+ identity: (ctx.clientIdentity ??
468
+ fabricCtx.identity),
469
+ logger: fabricCtx.logger,
470
+ correlationId: ctx.stub.getTxID(),
368
471
  });
369
472
  }
370
473
  /**
@@ -466,9 +569,10 @@ export class FabricContractAdapter extends CouchDBAdapter {
466
569
  * FabricContractAdapter->>FabricContractAdapter: resultIterator(log, iterator)
467
570
  * FabricContractAdapter-->>Caller: results
468
571
  */
469
- async raw(rawInput, docsOnly, ...args) {
470
- const { stub, logger } = args.pop();
471
- const log = logger.for(this.raw);
572
+ async raw(rawInput, ...args) {
573
+ const { ctx, log, ctxArgs } = this.logCtx(args, this.raw);
574
+ const docsOnly = typeof ctxArgs[0] === "boolean" ? ctxArgs.shift() : false;
575
+ const { stub } = ctx;
472
576
  const { skip, limit } = rawInput;
473
577
  let iterator;
474
578
  if (limit || skip) {
@@ -487,11 +591,8 @@ export class FabricContractAdapter extends CouchDBAdapter {
487
591
  log.debug(`returning {0} results`, `${Array.isArray(results) ? results.length : 1}`);
488
592
  return results;
489
593
  }
490
- Statement(ctx) {
491
- if (!ctx) {
492
- throw new MissingContextError("Context is required");
493
- }
494
- return new FabricStatement(this, ctx);
594
+ Statement() {
595
+ return new FabricStatement(this);
495
596
  }
496
597
  async Sequence(options) {
497
598
  return new FabricContractSequence(options, this);
@@ -499,24 +600,18 @@ export class FabricContractAdapter extends CouchDBAdapter {
499
600
  async createAll(tableName, id, model, ...args) {
500
601
  if (id.length !== model.length)
501
602
  throw new InternalError("Ids and models must have the same length");
502
- const { logger } = args[args.length - 1];
503
- const log = logger.for(this.createAll);
504
- log.info(`Creating ${id.length} entries ${tableName} table`);
505
- log.debug(`pks: ${id}`);
506
- return Promise.all(id.map(async (i, index) => {
507
- return this.create(tableName, i, model[index], ...args);
508
- }));
603
+ const { log, ctxArgs } = this.logCtx(args, this.createAll);
604
+ const tableLabel = Model.tableName(tableName);
605
+ log.debug(`Creating ${id.length} entries ${tableLabel} table`);
606
+ return Promise.all(id.map((i, count) => this.create(tableName, i, model[count], ...ctxArgs)));
509
607
  }
510
608
  async updateAll(tableName, id, model, ...args) {
511
609
  if (id.length !== model.length)
512
610
  throw new InternalError("Ids and models must have the same length");
513
- const { logger } = args[args.length - 1];
514
- const log = logger.for(this.createAll);
515
- log.info(`Updating ${id.length} entries ${tableName} table`);
516
- log.debug(`pks: ${id}`);
517
- return Promise.all(id.map(async (i, index) => {
518
- return this.update(tableName, i, model[index], ...args);
519
- }));
611
+ const { log, ctxArgs } = this.logCtx(args, this.updateAll);
612
+ const tableLabel = Model.tableName(tableName);
613
+ log.debug(`Updating ${id.length} entries ${tableLabel} table`);
614
+ return Promise.all(id.map((i, count) => this.update(tableName, i, model[count], ...ctxArgs)));
520
615
  }
521
616
  /**
522
617
  *
@@ -524,79 +619,62 @@ export class FabricContractAdapter extends CouchDBAdapter {
524
619
  * @param {string} pk
525
620
  * @param args
526
621
  */
527
- prepare(model, pk, ...args) {
528
- const { stub, logger } = args.pop();
529
- const tableName = args.shift();
530
- const log = logger.for(this.prepare);
622
+ prepare(model, ...args) {
623
+ const { log } = this.logCtx(args, this.prepare);
624
+ const tableName = Model.tableName(model.constructor);
625
+ const pk = Model.pk(model.constructor);
531
626
  const split = Model.segregate(model);
532
627
  const result = Object.entries(split.model).reduce((accum, [key, val]) => {
533
628
  if (typeof val === "undefined")
534
629
  return accum;
535
- const mappedProp = Repository.column(model, key);
630
+ const mappedProp = Model.columnName(model, key);
536
631
  if (this.isReserved(mappedProp))
537
632
  throw new InternalError(`Property name ${mappedProp} is reserved`);
538
633
  accum[mappedProp] = val;
539
634
  return accum;
540
635
  }, {});
541
- if (model[PersistenceKeys.METADATA]) {
542
- log.silly(`Passing along persistence metadata for ${model[PersistenceKeys.METADATA]}`);
543
- Object.defineProperty(result, PersistenceKeys.METADATA, {
544
- enumerable: false,
545
- writable: false,
546
- configurable: true,
547
- value: model[PersistenceKeys.METADATA],
548
- });
549
- }
550
- log.info(`Preparing record for ${tableName} table with pk ${model[pk]}`);
636
+ log.silly(`Preparing record for ${tableName} table with pk ${model[pk]}`);
551
637
  return {
552
638
  record: result,
553
- id: stub.createCompositeKey(tableName, [String(model[pk])]),
639
+ id: model[pk],
554
640
  transient: split.transient,
555
641
  };
556
642
  }
557
- revert(obj, clazz, pk, id, transient) {
558
- const log = this.log.for(this.revert);
643
+ revert(obj, clazz, id, transient, ...args) {
644
+ const { log } = this.logCtx(args, this.revert);
559
645
  const ob = {};
646
+ const pk = Model.pk(clazz);
560
647
  ob[pk] = id;
561
648
  const m = (typeof clazz === "string" ? Model.build(ob, clazz) : new clazz(ob));
562
649
  log.silly(`Rebuilding model ${m.constructor.name} id ${id}`);
563
- const metadata = obj[PersistenceKeys.METADATA];
564
650
  const result = Object.keys(m).reduce((accum, key) => {
565
- accum[key] = obj[Repository.column(accum, key)];
651
+ accum[key] =
652
+ obj[Model.columnName(accum, key)];
566
653
  return accum;
567
654
  }, m);
568
655
  if (transient) {
569
- log.verbose(`re-adding transient properties: ${Object.keys(transient).join(", ")}`);
656
+ log.debug(`re-adding transient properties: ${Object.keys(transient).join(", ")}`);
570
657
  Object.entries(transient).forEach(([key, val]) => {
571
658
  if (key in result && result[key] !== undefined)
572
659
  throw new InternalError(`Transient property ${key} already exists on model ${m.constructor.name}. should be impossible`);
573
660
  result[key] = val;
574
661
  });
575
662
  }
576
- if (metadata) {
577
- log.silly(`Passing along ${this.flavour} persistence metadata for ${m.constructor.name} id ${id}: ${metadata}`);
578
- Object.defineProperty(result, PersistenceKeys.METADATA, {
579
- enumerable: false,
580
- configurable: false,
581
- writable: false,
582
- value: metadata,
583
- });
584
- }
585
663
  return result;
586
664
  }
587
665
  createPrefix(tableName, id, model, ...args) {
588
- const ctx = args.pop();
666
+ const { ctxArgs } = this.logCtx(args, this.createPrefix);
589
667
  const record = {};
590
- record[CouchDBKeys.TABLE] = tableName;
668
+ record[CouchDBKeys.TABLE] = Model.tableName(tableName);
591
669
  Object.assign(record, model);
592
- return [tableName, id, record, ctx];
670
+ return [tableName, id, record, ...ctxArgs];
593
671
  }
594
672
  updatePrefix(tableName, id, model, ...args) {
595
- const ctx = args.pop();
673
+ const { ctxArgs } = this.logCtx(args, this.updatePrefix);
596
674
  const record = {};
597
- record[CouchDBKeys.TABLE] = tableName;
675
+ record[CouchDBKeys.TABLE] = Model.tableName(tableName);
598
676
  Object.assign(record, model);
599
- return [tableName, id, record, ctx];
677
+ return [tableName, id, record, ...ctxArgs];
600
678
  }
601
679
  createAllPrefix(tableName, ids, models, ...args) {
602
680
  if (ids.length !== models.length)
@@ -605,7 +683,6 @@ export class FabricContractAdapter extends CouchDBAdapter {
605
683
  const records = ids.map((id, count) => {
606
684
  const record = {};
607
685
  record[CouchDBKeys.TABLE] = tableName;
608
- // record[CouchDBKeys.ID] = this.generateId(tableName, id);
609
686
  Object.assign(record, models[count]);
610
687
  return record;
611
688
  });
@@ -623,6 +700,18 @@ export class FabricContractAdapter extends CouchDBAdapter {
623
700
  });
624
701
  return [tableName, ids, records, ctx];
625
702
  }
703
+ parseError(err, reason) {
704
+ return FabricContractAdapter.parseError(reason || err);
705
+ }
706
+ static parseError(err, reason) {
707
+ // if (
708
+ // MISSING_PRIVATE_DATA_REGEX.test(
709
+ // typeof err === "string" ? err : err.message
710
+ // )
711
+ // )
712
+ // return new UnauthorizedPrivateDataAccess(err) as E;
713
+ return super.parseError(err, reason);
714
+ }
626
715
  /**
627
716
  * @description Static method for decoration overrides
628
717
  * @summary Overrides/extends decaf decoration with Fabric-specific functionality