@wishknish/knishio-client-ts 0.7.0

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 (141) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +425 -0
  3. package/dist/index.cjs +9961 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.iife.js +32241 -0
  6. package/dist/index.iife.js.map +1 -0
  7. package/dist/index.js +9853 -0
  8. package/dist/index.js.map +1 -0
  9. package/package.json +113 -0
  10. package/src/AuthToken.ts +214 -0
  11. package/src/KnishIOClient.ts +2020 -0
  12. package/src/constants.ts +398 -0
  13. package/src/core/Atom.ts +646 -0
  14. package/src/core/AtomMeta.ts +278 -0
  15. package/src/core/Meta.ts +428 -0
  16. package/src/core/Molecule.ts +825 -0
  17. package/src/core/PolicyMeta.ts +130 -0
  18. package/src/core/TokenUnit.ts +148 -0
  19. package/src/core/Wallet.ts +467 -0
  20. package/src/exception/AtomIndexException.ts +97 -0
  21. package/src/exception/AtomsMissingException.ts +109 -0
  22. package/src/exception/AuthorizationRejectedException.ts +63 -0
  23. package/src/exception/BalanceInsufficientException.ts +58 -0
  24. package/src/exception/BaseException.ts +275 -0
  25. package/src/exception/BatchIdException.ts +58 -0
  26. package/src/exception/CodeException.ts +119 -0
  27. package/src/exception/DecryptionKeyException.ts +65 -0
  28. package/src/exception/InvalidResponseException.ts +112 -0
  29. package/src/exception/MetaMissingException.ts +58 -0
  30. package/src/exception/MolecularHashMismatchException.ts +115 -0
  31. package/src/exception/MolecularHashMissingException.ts +58 -0
  32. package/src/exception/NegativeAmountException.ts +58 -0
  33. package/src/exception/PolicyInvalidException.ts +58 -0
  34. package/src/exception/SignatureMalformedException.ts +58 -0
  35. package/src/exception/SignatureMismatchException.ts +98 -0
  36. package/src/exception/StackableUnitAmountException.ts +65 -0
  37. package/src/exception/StackableUnitDecimalsException.ts +65 -0
  38. package/src/exception/TransferBalanceException.ts +98 -0
  39. package/src/exception/TransferMalformedException.ts +58 -0
  40. package/src/exception/TransferMismatchedException.ts +58 -0
  41. package/src/exception/TransferRemainderException.ts +58 -0
  42. package/src/exception/TransferToSelfException.ts +58 -0
  43. package/src/exception/TransferUnbalancedException.ts +58 -0
  44. package/src/exception/UnauthenticatedException.ts +147 -0
  45. package/src/exception/WalletCredentialException.ts +108 -0
  46. package/src/exception/WalletShadowException.ts +65 -0
  47. package/src/exception/WrongTokenTypeException.ts +58 -0
  48. package/src/exception/index.ts +272 -0
  49. package/src/index.ts +512 -0
  50. package/src/instance/rules/Callback.ts +257 -0
  51. package/src/instance/rules/Condition.ts +96 -0
  52. package/src/instance/rules/Meta.ts +163 -0
  53. package/src/instance/rules/Rule.ts +29 -0
  54. package/src/instance/rules/exception/RuleArgumentException.ts +65 -0
  55. package/src/libraries/CheckMolecule.ts +581 -0
  56. package/src/libraries/Decimal.ts +94 -0
  57. package/src/libraries/Dot.ts +202 -0
  58. package/src/libraries/GraphQLClient.ts +276 -0
  59. package/src/libraries/Hex.ts +155 -0
  60. package/src/libraries/UrqlClientWrapper.ts +336 -0
  61. package/src/libraries/array.ts +91 -0
  62. package/src/libraries/crypto.ts +816 -0
  63. package/src/libraries/strings.ts +458 -0
  64. package/src/mutation/Mutation.ts +103 -0
  65. package/src/mutation/MutationActiveSession.ts +108 -0
  66. package/src/mutation/MutationClaimShadowWallet.ts +91 -0
  67. package/src/mutation/MutationCreateIdentifier.ts +86 -0
  68. package/src/mutation/MutationCreateMeta.ts +92 -0
  69. package/src/mutation/MutationCreateRule.ts +90 -0
  70. package/src/mutation/MutationCreateToken.ts +92 -0
  71. package/src/mutation/MutationCreateWallet.ts +78 -0
  72. package/src/mutation/MutationDepositBufferToken.ts +72 -0
  73. package/src/mutation/MutationLinkIdentifier.ts +87 -0
  74. package/src/mutation/MutationProposeMolecule.ts +147 -0
  75. package/src/mutation/MutationRequestAuthorization.ts +77 -0
  76. package/src/mutation/MutationRequestAuthorizationGuest.ts +85 -0
  77. package/src/mutation/MutationRequestTokens.ts +98 -0
  78. package/src/mutation/MutationTransferTokens.ts +87 -0
  79. package/src/mutation/MutationWithdrawBufferToken.ts +73 -0
  80. package/src/query/Query.ts +187 -0
  81. package/src/query/QueryActiveSession.ts +89 -0
  82. package/src/query/QueryAtom.ts +275 -0
  83. package/src/query/QueryBalance.ts +102 -0
  84. package/src/query/QueryBatch.ts +145 -0
  85. package/src/query/QueryBatchHistory.ts +86 -0
  86. package/src/query/QueryContinuId.ts +91 -0
  87. package/src/query/QueryMetaType.ts +177 -0
  88. package/src/query/QueryMetaTypeViaAtom.ts +199 -0
  89. package/src/query/QueryPolicy.ts +91 -0
  90. package/src/query/QueryToken.ts +90 -0
  91. package/src/query/QueryUserActivity.ts +153 -0
  92. package/src/query/QueryWalletBundle.ts +92 -0
  93. package/src/query/QueryWalletList.ts +106 -0
  94. package/src/response/EnhancedResponse.ts +345 -0
  95. package/src/response/Response.ts +254 -0
  96. package/src/response/ResponseActiveSession.ts +72 -0
  97. package/src/response/ResponseAtom.ts +132 -0
  98. package/src/response/ResponseAuthorizationGuest.ts +119 -0
  99. package/src/response/ResponseBalance.ts +153 -0
  100. package/src/response/ResponseClaimShadowWallet.ts +56 -0
  101. package/src/response/ResponseContinuId.ts +101 -0
  102. package/src/response/ResponseCreateIdentifier.ts +56 -0
  103. package/src/response/ResponseCreateMeta.ts +58 -0
  104. package/src/response/ResponseCreateRule.ts +56 -0
  105. package/src/response/ResponseCreateToken.ts +58 -0
  106. package/src/response/ResponseCreateWallet.ts +58 -0
  107. package/src/response/ResponseLinkIdentifier.ts +87 -0
  108. package/src/response/ResponseMetaBatch.ts +72 -0
  109. package/src/response/ResponseMetaType.ts +108 -0
  110. package/src/response/ResponseMetaTypeViaAtom.ts +108 -0
  111. package/src/response/ResponsePolicy.ts +90 -0
  112. package/src/response/ResponseProposeMolecule.ts +155 -0
  113. package/src/response/ResponseQueryActiveSession.ts +105 -0
  114. package/src/response/ResponseQueryUserActivity.ts +89 -0
  115. package/src/response/ResponseRequestAuthorization.ts +100 -0
  116. package/src/response/ResponseRequestAuthorizationGuest.ts +133 -0
  117. package/src/response/ResponseRequestTokens.ts +58 -0
  118. package/src/response/ResponseTransferTokens.ts +72 -0
  119. package/src/response/ResponseWalletBundle.ts +95 -0
  120. package/src/response/ResponseWalletList.ts +165 -0
  121. package/src/schemas/index.ts +457 -0
  122. package/src/subscribe/ActiveSessionSubscribe.ts +72 -0
  123. package/src/subscribe/ActiveWalletSubscribe.ts +99 -0
  124. package/src/subscribe/CreateMoleculeSubscribe.ts +106 -0
  125. package/src/subscribe/Subscribe.ts +182 -0
  126. package/src/subscribe/WalletStatusSubscribe.ts +70 -0
  127. package/src/subscribe/index.ts +59 -0
  128. package/src/types/assertions.ts +722 -0
  129. package/src/types/client.ts +567 -0
  130. package/src/types/crypto.ts +541 -0
  131. package/src/types/graphql.ts +630 -0
  132. package/src/types/guards.ts +659 -0
  133. package/src/types/index.ts +614 -0
  134. package/src/types/response.ts +133 -0
  135. package/src/types/template-literals.ts +382 -0
  136. package/src/validation/UNIVERSAL_CONFIGURATION_INTERFACES.ts +580 -0
  137. package/src/validation/ValidationService.ts +607 -0
  138. package/src/validation/schemas.ts +447 -0
  139. package/src/versions/HashAtom.ts +170 -0
  140. package/src/versions/Version4.ts +120 -0
  141. package/src/versions/index.ts +80 -0
@@ -0,0 +1,106 @@
1
+ /*
2
+ (
3
+ (/(
4
+ (//(
5
+ (///(
6
+ (/////(
7
+ (//////( )
8
+ (////////( (/)
9
+ (////////( (///)
10
+ (//////////( (////)
11
+ (//////////( (//////)
12
+ (////////////( (///////)
13
+ (/////////////( (/////////)
14
+ (//////////////( (///////////)
15
+ (///////////////( (/////////////)
16
+ (////////////////( (//////////////)
17
+ ((((((((((((((((((( (((((((((((((((
18
+ ((((((((((((((((((( ((((((((((((((
19
+ ((((((((((((((((((( ((((((((((((((
20
+ (((((((((((((((((((( (((((((((((((
21
+ (((((((((((((((((((( ((((((((((((
22
+ ((((((((((((((((((( ((((((((((((
23
+ ((((((((((((((((((( ((((((((((
24
+ ((((((((((((((((((/ (((((((((
25
+ (((((((((((((((((( ((((((((
26
+ ((((((((((((((((( (((((((
27
+ (((((((((((((((((( (((((
28
+ ################# ##
29
+ ################ #
30
+ ################# ##
31
+ %################ ###
32
+ ###############( ####
33
+ ############### ####
34
+ ############### ######
35
+ %#############( (#######
36
+ %############# #########
37
+ ############( ##########
38
+ ########### #############
39
+ ######### ##############
40
+ %######
41
+
42
+ Powered by Knish.IO: Connecting a Decentralized World
43
+
44
+ Please visit https://github.com/WishKnish/KnishIO-Client-TS for information.
45
+
46
+ License: https://github.com/WishKnish/KnishIO-Client-TS/blob/master/LICENSE
47
+ */
48
+
49
+ import Query from './Query'
50
+ import ResponseWalletList from '../response/ResponseWalletList'
51
+ import type { UrqlClientWrapper } from '../client/GraphQLClient'
52
+ import type KnishIOClient from '../KnishIOClient'
53
+
54
+ /**
55
+ * QueryWalletList class - Query for getting a list of Wallets
56
+ * Matches JavaScript SDK QueryWalletList implementation exactly
57
+ */
58
+ export default class QueryWalletList extends Query {
59
+ /**
60
+ * Create new QueryWalletList instance
61
+ * Matches JavaScript SDK constructor signature exactly
62
+ */
63
+ constructor(graphQLClient: UrqlClientWrapper, knishIOClient: KnishIOClient) {
64
+ super(graphQLClient, knishIOClient)
65
+
66
+ this.$__query = `query( $bundleHash: String, $tokenSlug: String ) {
67
+ Wallet( bundleHash: $bundleHash, tokenSlug: $tokenSlug ) {
68
+ address,
69
+ bundleHash,
70
+ token {
71
+ name,
72
+ amount,
73
+ fungibility,
74
+ supply
75
+ },
76
+ tokenSlug,
77
+ batchId,
78
+ position,
79
+ amount,
80
+ characters,
81
+ pubkey,
82
+ createdAt,
83
+ tokenUnits {
84
+ id,
85
+ name,
86
+ metas
87
+ },
88
+ tradeRates {
89
+ tokenSlug,
90
+ amount
91
+ }
92
+ }
93
+ }`
94
+ }
95
+
96
+ /**
97
+ * Builds a Response object out of a JSON object
98
+ * Matches JavaScript SDK createResponse method exactly
99
+ */
100
+ override createResponse(json: any): ResponseWalletList {
101
+ return new ResponseWalletList({
102
+ query: this,
103
+ json
104
+ })
105
+ }
106
+ }
@@ -0,0 +1,345 @@
1
+ /*
2
+ Enhanced Response Implementation for TypeScript SDK Gold Standard
3
+
4
+ Provides comprehensive response interface with ValidationResult patterns,
5
+ functional programming support, and enhanced error handling.
6
+ */
7
+
8
+ import { z } from 'zod'
9
+ import {
10
+ UniversalResponse,
11
+ EnhancedResponse,
12
+ ValidationResult,
13
+ ResponseError,
14
+ ResponseMetadata,
15
+ ResponseErrorSchema,
16
+ ValidationResultSchema,
17
+ isSuccessResponse,
18
+ isErrorResponse
19
+ } from '@/types/response'
20
+
21
+ /**
22
+ * Enhanced response implementation providing comprehensive interface
23
+ * and functional programming patterns
24
+ */
25
+ export class StandardResponse<T> implements EnhancedResponse<T> {
26
+ private readonly _successful: boolean
27
+ private readonly _payload: T | null
28
+ private readonly _errorMessage: string | null
29
+ private readonly _rawData: any
30
+ private readonly _metadata: ResponseMetadata
31
+
32
+ constructor(
33
+ successful: boolean,
34
+ payload: T | null = null,
35
+ errorMessage: string | null = null,
36
+ rawData: any = null,
37
+ metadata?: Partial<ResponseMetadata>
38
+ ) {
39
+ this._successful = successful
40
+ this._payload = payload
41
+ this._errorMessage = errorMessage
42
+ this._rawData = rawData
43
+ this._metadata = {
44
+ timestamp: new Date().toISOString(),
45
+ operation: 'unknown',
46
+ clientVersion: '1.0.0',
47
+ ...metadata
48
+ }
49
+ }
50
+
51
+ // Core response interface methods
52
+ success(): boolean {
53
+ return this._successful
54
+ }
55
+
56
+ payload(): T | null {
57
+ return this._payload
58
+ }
59
+
60
+ reason(): string | null {
61
+ return this._errorMessage
62
+ }
63
+
64
+ data(): any {
65
+ return this._rawData
66
+ }
67
+
68
+ // Enhanced ValidationResult integration
69
+ toValidationResult(): ValidationResult<T> {
70
+ if (this._successful && this._payload !== null) {
71
+ return {
72
+ success: true,
73
+ data: this._payload,
74
+ warnings: []
75
+ }
76
+ } else {
77
+ return {
78
+ success: false,
79
+ error: {
80
+ message: this._errorMessage || 'Unknown error',
81
+ context: this._rawData,
82
+ timestamp: this._metadata.timestamp,
83
+ operation: this._metadata.operation
84
+ }
85
+ }
86
+ }
87
+ }
88
+
89
+ // Functional programming combinators
90
+ map<U>(mapper: (value: T) => U): EnhancedResponse<U> {
91
+ if (this._successful && this._payload !== null) {
92
+ try {
93
+ const mappedValue = mapper(this._payload)
94
+ return new StandardResponse(true, mappedValue, null, this._rawData, this._metadata)
95
+ } catch (error) {
96
+ return new StandardResponse(false, null, `Mapping failed: ${error instanceof Error ? error.message : String(error)}`, this._rawData, this._metadata)
97
+ }
98
+ } else {
99
+ return new StandardResponse(false, null, this._errorMessage, this._rawData, this._metadata)
100
+ }
101
+ }
102
+
103
+ flatMap<U>(mapper: (value: T) => EnhancedResponse<U>): EnhancedResponse<U> {
104
+ if (this._successful && this._payload !== null) {
105
+ try {
106
+ return mapper(this._payload)
107
+ } catch (error) {
108
+ return new StandardResponse(false, null, `FlatMap failed: ${error instanceof Error ? error.message : String(error)}`, this._rawData, this._metadata)
109
+ }
110
+ } else {
111
+ return new StandardResponse(false, null, this._errorMessage, this._rawData, this._metadata)
112
+ }
113
+ }
114
+
115
+ filter(predicate: (value: T) => boolean): EnhancedResponse<T> {
116
+ if (this._successful && this._payload !== null) {
117
+ try {
118
+ if (predicate(this._payload)) {
119
+ return this
120
+ } else {
121
+ return new StandardResponse(false, null, 'Filter predicate failed', this._rawData, this._metadata)
122
+ }
123
+ } catch (error) {
124
+ return new StandardResponse(false, null, `Filter failed: ${error instanceof Error ? error.message : String(error)}`, this._rawData, this._metadata)
125
+ }
126
+ } else {
127
+ return this
128
+ }
129
+ }
130
+
131
+ // Enhanced error handling with callbacks
132
+ onSuccess(callback: (payload: T) => void): EnhancedResponse<T> {
133
+ if (this._successful && this._payload !== null) {
134
+ try {
135
+ callback(this._payload)
136
+ } catch (error) {
137
+ console.warn('Response.onSuccess callback failed:', error)
138
+ }
139
+ }
140
+ return this
141
+ }
142
+
143
+ onFailure(callback: (error: string) => void): EnhancedResponse<T> {
144
+ if (!this._successful) {
145
+ try {
146
+ callback(this._errorMessage || 'Unknown error')
147
+ } catch (error) {
148
+ console.warn('Response.onFailure callback failed:', error)
149
+ }
150
+ }
151
+ return this
152
+ }
153
+
154
+ // Promise integration for async patterns
155
+ toPromise(): Promise<T> {
156
+ if (this._successful && this._payload !== null) {
157
+ return Promise.resolve(this._payload)
158
+ } else {
159
+ return Promise.reject(new Error(this._errorMessage || 'Unknown error'))
160
+ }
161
+ }
162
+
163
+ // Enhanced debugging with optional labels
164
+ debug(label?: string): EnhancedResponse<T> {
165
+ const debugPrefix = label ? `[${label}]` : '[Response]'
166
+
167
+ if (this._successful) {
168
+ console.debug(`${debugPrefix} Success:`, {
169
+ payload: this._payload,
170
+ metadata: this._metadata
171
+ })
172
+ } else {
173
+ console.debug(`${debugPrefix} Failure:`, {
174
+ error: this._errorMessage,
175
+ rawData: this._rawData,
176
+ metadata: this._metadata
177
+ })
178
+ }
179
+
180
+ return this
181
+ }
182
+
183
+ // Factory methods for enhanced response creation
184
+ static success<T>(payload: T, rawData?: any, metadata?: Partial<ResponseMetadata>): StandardResponse<T> {
185
+ return new StandardResponse(true, payload, null, rawData, metadata)
186
+ }
187
+
188
+ static failure<T>(errorMessage: string | ResponseError, rawData?: any, metadata?: Partial<ResponseMetadata>): StandardResponse<T> {
189
+ const message = typeof errorMessage === 'string' ? errorMessage : errorMessage.message
190
+ return new StandardResponse(false, null, message, rawData, metadata)
191
+ }
192
+
193
+ static fromValidationResult<T>(result: ValidationResult<T>, rawData?: any, metadata?: Partial<ResponseMetadata>): StandardResponse<T> {
194
+ if (result.success && result.data !== undefined) {
195
+ return new StandardResponse(true, result.data, null, rawData, {
196
+ ...metadata,
197
+ warnings: result.warnings
198
+ })
199
+ } else {
200
+ return new StandardResponse(false, null, result.error?.message || 'Validation failed', rawData, {
201
+ ...metadata,
202
+ error: result.error
203
+ })
204
+ }
205
+ }
206
+
207
+ // Enhanced error information extraction
208
+ getErrorDetails(): ResponseError | null {
209
+ if (!this._successful) {
210
+ return {
211
+ message: this._errorMessage || 'Unknown error',
212
+ context: this._metadata.operation,
213
+ timestamp: this._metadata.timestamp,
214
+ operation: this._metadata.operation
215
+ }
216
+ }
217
+ return null
218
+ }
219
+
220
+ // Response metadata access
221
+ getMetadata(): ResponseMetadata {
222
+ return { ...this._metadata }
223
+ }
224
+
225
+ // Enhanced response validation
226
+ validate(): ValidationResult<T> {
227
+ try {
228
+ const validationResult = ValidationResultSchema.parse(this.toValidationResult())
229
+ return {
230
+ success: true,
231
+ data: this._payload as T,
232
+ warnings: ['Response validation successful']
233
+ }
234
+ } catch (error) {
235
+ return {
236
+ success: false,
237
+ error: {
238
+ message: 'Response validation failed',
239
+ details: [error instanceof Error ? error.message : String(error)]
240
+ }
241
+ }
242
+ }
243
+ }
244
+ }
245
+
246
+ // Factory class for creating standardized responses
247
+ export class ResponseFactory {
248
+
249
+ static createSuccessResponse<T>(
250
+ payload: T,
251
+ operation: string,
252
+ rawData?: any,
253
+ duration?: number
254
+ ): StandardResponse<T> {
255
+ return StandardResponse.success(payload, rawData, {
256
+ operation,
257
+ duration,
258
+ timestamp: new Date().toISOString()
259
+ })
260
+ }
261
+
262
+ static createErrorResponse<T>(
263
+ errorMessage: string,
264
+ operation: string,
265
+ rawData?: any,
266
+ duration?: number
267
+ ): StandardResponse<T> {
268
+ return StandardResponse.failure(errorMessage, rawData, {
269
+ operation,
270
+ duration,
271
+ timestamp: new Date().toISOString()
272
+ })
273
+ }
274
+
275
+ static fromLegacyResponse<T>(
276
+ legacyResponse: any,
277
+ operation: string
278
+ ): StandardResponse<T> {
279
+ try {
280
+ const isSuccessful = legacyResponse?.success?.() ?? false
281
+ const payload = legacyResponse?.payload?.() ?? null
282
+ const errorMessage = legacyResponse?.error?.() ?? legacyResponse?.reason?.() ?? null
283
+ const rawData = legacyResponse?.data?.() ?? legacyResponse
284
+
285
+ return isSuccessful
286
+ ? StandardResponse.success(payload, rawData, { operation })
287
+ : StandardResponse.failure(errorMessage || 'Unknown error', rawData, { operation })
288
+ } catch (error) {
289
+ return StandardResponse.failure(
290
+ `Legacy response conversion failed: ${error instanceof Error ? error.message : String(error)}`,
291
+ legacyResponse,
292
+ { operation }
293
+ )
294
+ }
295
+ }
296
+ }
297
+
298
+ // Enhanced response utilities
299
+ export class ResponseUtils {
300
+
301
+ static combineResponses<T>(responses: EnhancedResponse<T>[]): EnhancedResponse<T[]> {
302
+ const successful = responses.every(r => r.success())
303
+
304
+ if (successful) {
305
+ const payloads = responses.map(r => r.payload()).filter((p): p is T => p !== null)
306
+ return StandardResponse.success(payloads, responses, { operation: 'combineResponses' })
307
+ } else {
308
+ const errors = responses.filter(r => !r.success()).map(r => r.reason()).join('; ')
309
+ return StandardResponse.failure(`Combined operation failed: ${errors}`, responses, { operation: 'combineResponses' })
310
+ }
311
+ }
312
+
313
+ static async sequenceResponses<T>(
314
+ operations: (() => Promise<EnhancedResponse<T>>)[]
315
+ ): Promise<EnhancedResponse<T[]>> {
316
+ const results: EnhancedResponse<T>[] = []
317
+
318
+ for (const operation of operations) {
319
+ try {
320
+ const result = await operation()
321
+ results.push(result)
322
+
323
+ if (!result.success()) {
324
+ // Fail fast on first error
325
+ return StandardResponse.failure(
326
+ `Sequence failed at operation ${results.length}: ${result.reason()}`,
327
+ results,
328
+ { operation: 'sequenceResponses' }
329
+ )
330
+ }
331
+ } catch (error) {
332
+ return StandardResponse.failure(
333
+ `Sequence failed with exception: ${error instanceof Error ? error.message : String(error)}`,
334
+ results,
335
+ { operation: 'sequenceResponses' }
336
+ )
337
+ }
338
+ }
339
+
340
+ const payloads = results.map(r => r.payload()).filter((p): p is T => p !== null)
341
+ return StandardResponse.success(payloads, results, { operation: 'sequenceResponses' })
342
+ }
343
+ }
344
+
345
+ export default StandardResponse
@@ -0,0 +1,254 @@
1
+ /*
2
+ (
3
+ (/(
4
+ (//(
5
+ (///(
6
+ (/////(
7
+ (//////( )
8
+ (////////( (/)
9
+ (////////( (///)
10
+ (//////////( (////)
11
+ (//////////( (//////)
12
+ (////////////( (///////)
13
+ (/////////////( (/////////)
14
+ (//////////////( (///////////)
15
+ (///////////////( (/////////////)
16
+ (////////////////( (//////////////)
17
+ ((((((((((((((((((( (((((((((((((((
18
+ ((((((((((((((((((( ((((((((((((((
19
+ ((((((((((((((((((( ((((((((((((((
20
+ (((((((((((((((((((( (((((((((((((
21
+ (((((((((((((((((((( ((((((((((((
22
+ ((((((((((((((((((( ((((((((((((
23
+ ((((((((((((((((((( ((((((((((
24
+ ((((((((((((((((((/ (((((((((
25
+ (((((((((((((((((( ((((((((
26
+ ((((((((((((((((( (((((((
27
+ (((((((((((((((((( (((((
28
+ ################# ##
29
+ ################ #
30
+ ################# ##
31
+ %################ ###
32
+ ###############( ####
33
+ ############### ####
34
+ ############### ######
35
+ %#############( (#######
36
+ %############# #########
37
+ ############( ##########
38
+ ########### #############
39
+ ######### ##############
40
+ %######
41
+
42
+ Powered by Knish.IO: Connecting a Decentralized World
43
+
44
+ Please visit https://github.com/WishKnish/KnishIO-Client-TS for information.
45
+
46
+ License: https://github.com/WishKnish/KnishIO-Client-TS/blob/master/LICENSE
47
+ */
48
+
49
+ import { InvalidResponseException, UnauthenticatedException } from '@/exception'
50
+ import Dot from '@/libraries/Dot'
51
+ import type Query from '@/query/Query'
52
+ import { StandardResponse, ResponseFactory } from './EnhancedResponse'
53
+ import { UniversalResponse, ValidationResult } from '@/types/response'
54
+
55
+ /**
56
+ * Base Response class for processing node responses
57
+ * Enhanced with standardized interface and ValidationResult support
58
+ */
59
+ export default class Response implements UniversalResponse<any> {
60
+ protected dataKey: string | null
61
+ protected errorKey: string = 'exception'
62
+ protected $__payload: any = null
63
+ protected $__query: Query
64
+ protected $__originResponse: any
65
+ protected $__response: any
66
+
67
+ /**
68
+ * Class constructor
69
+ */
70
+ constructor({
71
+ query,
72
+ json,
73
+ dataKey = null
74
+ }: {
75
+ query: Query
76
+ json: any
77
+ dataKey?: string | null
78
+ }) {
79
+ this.dataKey = dataKey
80
+ this.$__query = query
81
+ this.$__originResponse = json
82
+ this.$__response = json
83
+
84
+ if (typeof this.$__response === 'undefined' || this.$__response === null) {
85
+ throw new InvalidResponseException()
86
+ }
87
+
88
+ if (Dot.has(this.$__response, this.errorKey)) {
89
+ const error = Dot.get(this.$__response, this.errorKey)
90
+
91
+ if (String(error).includes('Unauthenticated')) {
92
+ throw new UnauthenticatedException()
93
+ }
94
+
95
+ throw new InvalidResponseException()
96
+ }
97
+
98
+ this.init()
99
+ }
100
+
101
+ /**
102
+ * Initialize response - can be overridden by subclasses
103
+ */
104
+ protected init(): void {
105
+ // Override in subclasses
106
+ }
107
+
108
+ /**
109
+ * Get response data
110
+ */
111
+ data(): any {
112
+ if (!this.dataKey) {
113
+ return this.response()
114
+ }
115
+
116
+ // Check key & return custom data from the response
117
+ if (!Dot.has(this.response(), this.dataKey)) {
118
+ throw new InvalidResponseException()
119
+ }
120
+
121
+ return Dot.get(this.response(), this.dataKey)
122
+ }
123
+
124
+ /**
125
+ * Get raw response
126
+ */
127
+ response(): any {
128
+ return this.$__response
129
+ }
130
+
131
+ /**
132
+ * Get response payload
133
+ */
134
+ payload(): any {
135
+ return this.$__payload
136
+ }
137
+
138
+ /**
139
+ * Check if response was successful
140
+ */
141
+ success(): boolean {
142
+ // Default implementation - can be overridden
143
+ return !this.$__response?.errors?.length
144
+ }
145
+
146
+ /**
147
+ * Get error message if any
148
+ */
149
+ error(): string | null {
150
+ if (this.$__response?.errors?.length) {
151
+ return this.$__response.errors[0].message || 'Unknown error'
152
+ }
153
+ return null
154
+ }
155
+
156
+ /**
157
+ * Enhanced interface methods for standardized response handling
158
+ */
159
+
160
+ /**
161
+ * Get error reason (alias for error() to match standardized interface)
162
+ */
163
+ reason(): string | null {
164
+ return this.error()
165
+ }
166
+
167
+ /**
168
+ * Convert to enhanced response with ValidationResult support
169
+ */
170
+ toEnhanced<T>(): StandardResponse<T> {
171
+ return ResponseFactory.fromLegacyResponse<T>(this, this.constructor.name)
172
+ }
173
+
174
+ /**
175
+ * Convert to ValidationResult for enhanced error handling
176
+ */
177
+ toValidationResult<T>(): ValidationResult<T> {
178
+ if (this.success() && this.payload() !== null) {
179
+ return {
180
+ success: true,
181
+ data: this.payload() as T,
182
+ warnings: []
183
+ }
184
+ } else {
185
+ return {
186
+ success: false,
187
+ error: {
188
+ message: this.reason() || 'Unknown error',
189
+ context: this.constructor.name,
190
+ details: this.$__response?.errors || []
191
+ }
192
+ }
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Enhanced error handling with callbacks (matches enhanced interface)
198
+ */
199
+ onSuccess(callback: (payload: any) => void): Response {
200
+ if (this.success() && this.payload() !== null) {
201
+ try {
202
+ callback(this.payload())
203
+ } catch (error) {
204
+ console.warn('Response.onSuccess callback failed:', error)
205
+ }
206
+ }
207
+ return this
208
+ }
209
+
210
+ onFailure(callback: (error: string) => void): Response {
211
+ if (!this.success()) {
212
+ try {
213
+ callback(this.reason() || 'Unknown error')
214
+ } catch (error) {
215
+ console.warn('Response.onFailure callback failed:', error)
216
+ }
217
+ }
218
+ return this
219
+ }
220
+
221
+ /**
222
+ * Debug logging with enhanced context
223
+ */
224
+ debug(label?: string): Response {
225
+ const debugPrefix = label ? `[${label}]` : `[${this.constructor.name}]`
226
+
227
+ if (this.success()) {
228
+ console.debug(`${debugPrefix} Success:`, {
229
+ payload: this.payload(),
230
+ query: this.$__query?.constructor?.name,
231
+ dataKey: this.dataKey
232
+ })
233
+ } else {
234
+ console.debug(`${debugPrefix} Failure:`, {
235
+ error: this.reason(),
236
+ errors: this.$__response?.errors,
237
+ rawData: this.$__response
238
+ })
239
+ }
240
+
241
+ return this
242
+ }
243
+
244
+ /**
245
+ * Promise conversion for enhanced async patterns
246
+ */
247
+ toPromise<T>(): Promise<T> {
248
+ if (this.success() && this.payload() !== null) {
249
+ return Promise.resolve(this.payload() as T)
250
+ } else {
251
+ return Promise.reject(new Error(this.reason() || 'Unknown error'))
252
+ }
253
+ }
254
+ }