@alwatr/fetch 1.1.2 → 2.0.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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,24 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ # [2.0.0](https://github.com/AliMD/alwatr/compare/@alwatr/fetch@1.1.3...@alwatr/fetch@2.0.0) (2023-09-19)
7
+
8
+ ### Bug Fixes
9
+
10
+ * **fetch:** remove @alwatr/signal ([03d947b](https://github.com/AliMD/alwatr/commit/03d947be3889d63805eabb7f4be618fed6da0d55)) by @AliMD
11
+
12
+ * fix(fetch)!: remove fetchContext ([eba9cf0](https://github.com/AliMD/alwatr/commit/eba9cf0a443564478b5b985a69d0f54fbd514440)) by @AliMD
13
+
14
+ ### BREAKING CHANGES
15
+
16
+ * fetchContext method removed
17
+
18
+ ## 1.1.3 (2023-09-19)
19
+
20
+ ### Bug Fixes
21
+
22
+ * cleanup extra packages ([dfc0bd2](https://github.com/AliMD/alwatr/commit/dfc0bd2b42d49e1094ae0303d34e653aa289d358)) by @AliMD
23
+
6
24
  ## [1.1.2](https://github.com/AliMD/alwatr/compare/@alwatr/fetch@1.1.1...@alwatr/fetch@1.1.2) (2023-09-12)
7
25
 
8
26
  **Note:** Version bump only for package @alwatr/fetch
@@ -19,51 +37,51 @@ See [Conventional Commits](https://conventionalcommits.org) for commit guideline
19
37
 
20
38
  ### Bug Fixes
21
39
 
22
- * **fetch:** serviceRequest type ([44c1086](https://github.com/AliMD/alwatr/commit/44c10866e1c630bc3cf85b3e9be38b268b5b0c31))
23
- * **fetch:** userAuth in StringifyableFetchOptions ([f554b57](https://github.com/AliMD/alwatr/commit/f554b575584cb1464d48fbe8a8c4006125365853))
40
+ - **fetch:** serviceRequest type ([44c1086](https://github.com/AliMD/alwatr/commit/44c10866e1c630bc3cf85b3e9be38b268b5b0c31))
41
+ - **fetch:** userAuth in StringifyableFetchOptions ([f554b57](https://github.com/AliMD/alwatr/commit/f554b575584cb1464d48fbe8a8c4006125365853))
24
42
 
25
43
  # 0.31.0 (2023-05-08)
26
44
 
27
45
  ### Bug Fixes
28
46
 
29
- * **fetch.ts:** compatible with node ([c3acb53](https://github.com/AliMD/alwatr/commit/c3acb53effd4a79e389bc4de1567b0285c03d71d))
30
- * **fetch:** bodyJson type ([5740467](https://github.com/AliMD/alwatr/commit/57404673e7f031a73d1cf23501e6fa8d89759769))
31
- * **fetch:** check node_mode before use navigator.online ([a688f48](https://github.com/AliMD/alwatr/commit/a688f48e9ce4b103c25ffd50f1b8c96e89c205d1))
32
- * **fetch:** serviceRequest generic type ([074ef38](https://github.com/AliMD/alwatr/commit/074ef3876086f93486753559d8e3db0b60c52a0e))
33
- * **fetch:** suppress fetch_cache_not_found extra error ([c04f609](https://github.com/AliMD/alwatr/commit/c04f60944106dbd8d1bf2fb5ce0e7be644c3abc6))
34
- * new logger api ([9d83a7d](https://github.com/AliMD/alwatr/commit/9d83a7dc5c103bc3bb4282dacfd85fa998915300))
47
+ - **fetch.ts:** compatible with node ([c3acb53](https://github.com/AliMD/alwatr/commit/c3acb53effd4a79e389bc4de1567b0285c03d71d))
48
+ - **fetch:** bodyJson type ([5740467](https://github.com/AliMD/alwatr/commit/57404673e7f031a73d1cf23501e6fa8d89759769))
49
+ - **fetch:** check node_mode before use navigator.online ([a688f48](https://github.com/AliMD/alwatr/commit/a688f48e9ce4b103c25ffd50f1b8c96e89c205d1))
50
+ - **fetch:** serviceRequest generic type ([074ef38](https://github.com/AliMD/alwatr/commit/074ef3876086f93486753559d8e3db0b60c52a0e))
51
+ - **fetch:** suppress fetch_cache_not_found extra error ([c04f609](https://github.com/AliMD/alwatr/commit/c04f60944106dbd8d1bf2fb5ce0e7be644c3abc6))
52
+ - new logger api ([9d83a7d](https://github.com/AliMD/alwatr/commit/9d83a7dc5c103bc3bb4282dacfd85fa998915300))
35
53
 
36
54
  ### Features
37
55
 
38
- * **fetch:** add user auth ([811fbc0](https://github.com/AliMD/alwatr/commit/811fbc018c2b4e3b808704e8623bd5dff2b2f3f7))
39
- * **fetch:** StringifyableFetchOptions type ([e13fdb2](https://github.com/AliMD/alwatr/commit/e13fdb2550cf3a2102c331aa7980234ca6f86e08))
56
+ - **fetch:** add user auth ([811fbc0](https://github.com/AliMD/alwatr/commit/811fbc018c2b4e3b808704e8623bd5dff2b2f3f7))
57
+ - **fetch:** StringifyableFetchOptions type ([e13fdb2](https://github.com/AliMD/alwatr/commit/e13fdb2550cf3a2102c331aa7980234ca6f86e08))
40
58
 
41
59
  # 0.30.0 (2023-03-06)
42
60
 
43
61
  ### Bug Fixes
44
62
 
45
- * **fetch:** fetchContext duplicate setSignalValue ([8aa9b00](https://github.com/AliMD/alwatr/commit/8aa9b003a2d7b7ffc8243ff7092d9560763d7273))
46
- * **fetch:** getClientId in nodejs ([c99e41c](https://github.com/AliMD/alwatr/commit/c99e41c9e9a979ca50cc01aeb5371a3487d9da2e))
63
+ - **fetch:** fetchContext duplicate setSignalValue ([8aa9b00](https://github.com/AliMD/alwatr/commit/8aa9b003a2d7b7ffc8243ff7092d9560763d7273))
64
+ - **fetch:** getClientId in nodejs ([c99e41c](https://github.com/AliMD/alwatr/commit/c99e41c9e9a979ca50cc01aeb5371a3487d9da2e))
47
65
 
48
66
  ### Features
49
67
 
50
- * **fetch:** enhance fetchContext with dispatchOptions and only cache_only request in first time ([1f6b575](https://github.com/AliMD/alwatr/commit/1f6b575437104d64ede8a2c23d141160360d2cd5))
51
- * **fetch:** fetchContext ([d63d17e](https://github.com/AliMD/alwatr/commit/d63d17ecb58221159dc45a473fdd1c992d306d2b))
52
- * **fetch:** fetchContext skip online request when offline ([7c2b649](https://github.com/AliMD/alwatr/commit/7c2b6491f78acb961cdc0583112e3c709a177b79))
53
- * **fetch:** fetchContext work on background ([2e12bfd](https://github.com/AliMD/alwatr/commit/2e12bfde0a0636c30e60906c4812ec66b2d36742))
54
- * **fetch:** handle offline for all requests ([6a8d7b7](https://github.com/AliMD/alwatr/commit/6a8d7b7159732d834be052191935580331e36962))
68
+ - **fetch:** enhance fetchContext with dispatchOptions and only cache_only request in first time ([1f6b575](https://github.com/AliMD/alwatr/commit/1f6b575437104d64ede8a2c23d141160360d2cd5))
69
+ - **fetch:** fetchContext ([d63d17e](https://github.com/AliMD/alwatr/commit/d63d17ecb58221159dc45a473fdd1c992d306d2b))
70
+ - **fetch:** fetchContext skip online request when offline ([7c2b649](https://github.com/AliMD/alwatr/commit/7c2b6491f78acb961cdc0583112e3c709a177b79))
71
+ - **fetch:** fetchContext work on background ([2e12bfd](https://github.com/AliMD/alwatr/commit/2e12bfde0a0636c30e60906c4812ec66b2d36742))
72
+ - **fetch:** handle offline for all requests ([6a8d7b7](https://github.com/AliMD/alwatr/commit/6a8d7b7159732d834be052191935580331e36962))
55
73
 
56
74
  # 0.29.0 (2023-02-10)
57
75
 
58
76
  ### Bug Fixes
59
77
 
60
- * **fetch:** device id to client id ([077e467](https://github.com/AliMD/alwatr/commit/077e4671d804d43c8f61a9d163d8d51d7a69134e))
61
- * **fetch:** headers type ([cd4b14e](https://github.com/AliMD/alwatr/commit/cd4b14e46b5090b6df8cb4f89d22b53966b9151e))
78
+ - **fetch:** device id to client id ([077e467](https://github.com/AliMD/alwatr/commit/077e4671d804d43c8f61a9d163d8d51d7a69134e))
79
+ - **fetch:** headers type ([cd4b14e](https://github.com/AliMD/alwatr/commit/cd4b14e46b5090b6df8cb4f89d22b53966b9151e))
62
80
 
63
81
  ### Features
64
82
 
65
- * **fetch:** add update_cache to CacheStrategy ([e1406b1](https://github.com/AliMD/alwatr/commit/e1406b12e1276de3295c47506c8102ab3f8bfa79))
66
- * **fetch:** clientId on service request ([9575a1d](https://github.com/AliMD/alwatr/commit/9575a1d595a0a4757581a29a66837cbe4be46ed3))
83
+ - **fetch:** add update_cache to CacheStrategy ([e1406b1](https://github.com/AliMD/alwatr/commit/e1406b12e1276de3295c47506c8102ab3f8bfa79))
84
+ - **fetch:** clientId on service request ([9575a1d](https://github.com/AliMD/alwatr/commit/9575a1d595a0a4757581a29a66837cbe4be46ed3))
67
85
 
68
86
  # 0.28.0 (2023-01-20)
69
87
 
@@ -71,36 +89,36 @@ See [Conventional Commits](https://conventionalcommits.org) for commit guideline
71
89
 
72
90
  ### Bug Fixes
73
91
 
74
- * review issue ([e5d192c](https://github.com/AliMD/alwatr/commit/e5d192cbee6917c2de01146cf8bd026895724ab8))
92
+ - review issue ([e5d192c](https://github.com/AliMD/alwatr/commit/e5d192cbee6917c2de01146cf8bd026895724ab8))
75
93
 
76
94
  ### Features
77
95
 
78
- * **type:** add types ([2de3842](https://github.com/AliMD/alwatr/commit/2de384297b70b9818ec8d62ce8d31be4822d95a4))
96
+ - **type:** add types ([2de3842](https://github.com/AliMD/alwatr/commit/2de384297b70b9818ec8d62ce8d31be4822d95a4))
79
97
 
80
98
  # 0.26.0 (2022-12-22)
81
99
 
82
100
  ### Bug Fixes
83
101
 
84
- * all import without .js ([fa739ab](https://github.com/AliMD/alwatr/commit/fa739ab23f67bae1d10bfcc146920b71377a26fc))
85
- * **core/fetch:** tsconfig refrences ([e6b9542](https://github.com/AliMD/alwatr/commit/e6b9542284e67b67600da4dcebd19daedb031c9c))
86
- * **fetch:** always call revalidateCallback ([444edc5](https://github.com/AliMD/alwatr/commit/444edc52b6dd5de5418ae8630e1f2270f0114372))
87
- * **fetch:** enhance handle and report errors in serviceRequest ([dbfc7ff](https://github.com/AliMD/alwatr/commit/dbfc7ff2a036216498dc8e2ff58b74b7eb8d9bc0))
88
- * **fetch:** fetch_cache_not_found is not error ([3d1aa4e](https://github.com/AliMD/alwatr/commit/3d1aa4e572fbf4bc7b0a527a3fdcf4c521af18dd))
89
- * **fetch:** fetch_failed error message ([3e98bd9](https://github.com/AliMD/alwatr/commit/3e98bd926a495c13d476f2f1cfb9e546a059d4d8))
90
- * **fetch:** remove extra _options ([ad24c81](https://github.com/AliMD/alwatr/commit/ad24c8104b944ebda52308e60d41976ac1eeee81))
91
- * **fetch:** revalidateCallback issue ([7207909](https://github.com/AliMD/alwatr/commit/72079098edb438c28256dad03d7802bc2fab0858))
92
- * set correct path ([d01ce6f](https://github.com/AliMD/alwatr/commit/d01ce6ffa749a5e3e0e11e35b4ed61d75d61fec9))
93
- * **storage-engine:** AlwatrDocumentStorage ([ca9a7bf](https://github.com/AliMD/alwatr/commit/ca9a7bf5e17b333538e749ada5d481a06c847101))
94
- * tsconfig ([e96dcd3](https://github.com/AliMD/alwatr/commit/e96dcd30774a9f06f7d051e0504192cbbe019e35))
95
- * tsconfig refrences ([cea0562](https://github.com/AliMD/alwatr/commit/cea05621ecfa499476c5b10a412e60f27ba6a06d))
102
+ - all import without .js ([fa739ab](https://github.com/AliMD/alwatr/commit/fa739ab23f67bae1d10bfcc146920b71377a26fc))
103
+ - **core/fetch:** tsconfig refrences ([e6b9542](https://github.com/AliMD/alwatr/commit/e6b9542284e67b67600da4dcebd19daedb031c9c))
104
+ - **fetch:** always call revalidateCallback ([444edc5](https://github.com/AliMD/alwatr/commit/444edc52b6dd5de5418ae8630e1f2270f0114372))
105
+ - **fetch:** enhance handle and report errors in serviceRequest ([dbfc7ff](https://github.com/AliMD/alwatr/commit/dbfc7ff2a036216498dc8e2ff58b74b7eb8d9bc0))
106
+ - **fetch:** fetch_cache_not_found is not error ([3d1aa4e](https://github.com/AliMD/alwatr/commit/3d1aa4e572fbf4bc7b0a527a3fdcf4c521af18dd))
107
+ - **fetch:** fetch_failed error message ([3e98bd9](https://github.com/AliMD/alwatr/commit/3e98bd926a495c13d476f2f1cfb9e546a059d4d8))
108
+ - **fetch:** remove extra \_options ([ad24c81](https://github.com/AliMD/alwatr/commit/ad24c8104b944ebda52308e60d41976ac1eeee81))
109
+ - **fetch:** revalidateCallback issue ([7207909](https://github.com/AliMD/alwatr/commit/72079098edb438c28256dad03d7802bc2fab0858))
110
+ - set correct path ([d01ce6f](https://github.com/AliMD/alwatr/commit/d01ce6ffa749a5e3e0e11e35b4ed61d75d61fec9))
111
+ - **storage-engine:** AlwatrDocumentStorage ([ca9a7bf](https://github.com/AliMD/alwatr/commit/ca9a7bf5e17b333538e749ada5d481a06c847101))
112
+ - tsconfig ([e96dcd3](https://github.com/AliMD/alwatr/commit/e96dcd30774a9f06f7d051e0504192cbbe019e35))
113
+ - tsconfig refrences ([cea0562](https://github.com/AliMD/alwatr/commit/cea05621ecfa499476c5b10a412e60f27ba6a06d))
96
114
 
97
115
  ### Features
98
116
 
99
- * **fetch:** add AlwatrDocumentStorage type ([44b84f0](https://github.com/AliMD/alwatr/commit/44b84f0754169a707472655811020f6e542a6e5d))
100
- * **fetch:** serviceRequest ([b0b5478](https://github.com/AliMD/alwatr/commit/b0b5478d16b2cb590cfc29d644006e4a459dd6d6))
101
- * **fetch:** serviceRequest ([#513](https://github.com/AliMD/alwatr/issues/513)) ([113ee49](https://github.com/AliMD/alwatr/commit/113ee498c778d9efc00cc4807bfef09e52336a31))
102
- * improve accident debugging ([d697e6c](https://github.com/AliMD/alwatr/commit/d697e6c4c7d0a4172f4dba9caf6fbd478f79de9c))
103
- * improve error debugging ([1fba504](https://github.com/AliMD/alwatr/commit/1fba50400a1e8ececc10bbe8ea11cc8dcea2289c))
117
+ - **fetch:** add AlwatrDocumentStorage type ([44b84f0](https://github.com/AliMD/alwatr/commit/44b84f0754169a707472655811020f6e542a6e5d))
118
+ - **fetch:** serviceRequest ([b0b5478](https://github.com/AliMD/alwatr/commit/b0b5478d16b2cb590cfc29d644006e4a459dd6d6))
119
+ - **fetch:** serviceRequest ([#513](https://github.com/AliMD/alwatr/issues/513)) ([113ee49](https://github.com/AliMD/alwatr/commit/113ee498c778d9efc00cc4807bfef09e52336a31))
120
+ - improve accident debugging ([d697e6c](https://github.com/AliMD/alwatr/commit/d697e6c4c7d0a4172f4dba9caf6fbd478f79de9c))
121
+ - improve error debugging ([1fba504](https://github.com/AliMD/alwatr/commit/1fba50400a1e8ececc10bbe8ea11cc8dcea2289c))
104
122
 
105
123
  # [1.0.0](https://github.com/AliMD/alwatr/compare/v0.32.0...v1.0.0) (2023-06-14)
106
124
 
package/fetch.d.ts CHANGED
@@ -1,8 +1,6 @@
1
- import { type DispatchOptions } from '@alwatr/signal';
2
1
  import type { FetchOptions } from './type.js';
3
2
  import type { AlwatrServiceResponse } from '@alwatr/type';
4
3
  export type * from './type.js';
5
- export declare function fetchContext(contextName: string, fetchOption: FetchOptions, dispatchOptions?: Partial<DispatchOptions>): Promise<void>;
6
4
  /**
7
5
  * Fetch from alwatr services and return standard response.
8
6
  */
package/fetch.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["src/fetch.ts"],"names":[],"mappings":"AACA,OAAO,EAAkB,KAAK,eAAe,EAAC,MAAM,gBAAgB,CAAC;AAGrE,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,WAAW,CAAC;AAC5C,OAAO,KAAK,EAAC,qBAAqB,EAAC,MAAM,cAAc,CAAC;AAExD,mBAAmB,WAAW,CAAC;AAc/B,wBAAsB,YAAY,CAC9B,WAAW,EAAE,MAAM,EACnB,WAAW,EAAE,YAAY,EACzB,eAAe,GAAE,OAAO,CAAC,eAAe,CAAyB,GAClE,OAAO,CAAC,IAAI,CAAC,CAuCf;AAED;;GAEG;AACH,wBAAsB,cAAc,CAClC,CAAC,SAAS,qBAAqB,GAAG,qBAAqB,EACvD,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,CAAC,CAAC,CAwDnC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,KAAK,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,QAAQ,CAAC,CAI9D"}
1
+ {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["src/fetch.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,WAAW,CAAC;AAC5C,OAAO,KAAK,EAAC,qBAAqB,EAAC,MAAM,cAAc,CAAC;AAExD,mBAAmB,WAAW,CAAC;AAc/B;;GAEG;AACH,wBAAsB,cAAc,CAAC,CAAC,SAAS,qBAAqB,GAAG,qBAAqB,EACxF,OAAO,EAAE,YAAY,GACtB,OAAO,CAAC,CAAC,CAAC,CAwDZ;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,KAAK,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,QAAQ,CAAC,CAI9D"}
package/fetch.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import { createLogger, globalAlwatr, NODE_MODE } from '@alwatr/logger';
2
- import { contextProvider } from '@alwatr/signal';
3
2
  import { getClientId, delay } from '@alwatr/util';
4
3
  const logger = createLogger('alwatr/fetch');
5
4
  globalAlwatr.registeredList.push({
@@ -9,43 +8,6 @@ globalAlwatr.registeredList.push({
9
8
  let alwatrCacheStorage;
10
9
  const cacheSupported = 'caches' in globalThis;
11
10
  const duplicateRequestStorage = {};
12
- export async function fetchContext(contextName, fetchOption, dispatchOptions = { debounce: 'Timeout' }) {
13
- logger.logMethodArgs?.('fetchContext', { contextName });
14
- if (cacheSupported && contextProvider.getValue(contextName) == null) {
15
- try {
16
- fetchOption.cacheStrategy = 'cache_only';
17
- const response = await serviceRequest(fetchOption);
18
- contextProvider.setValue(contextName, response, dispatchOptions);
19
- if (navigator.onLine === false) {
20
- logger.logOther?.('fetchContext:', 'offline');
21
- // retry on online
22
- return;
23
- }
24
- }
25
- catch (err) {
26
- if (err.message === 'fetch_cache_not_found') {
27
- logger.logOther?.('fetchContext:', 'fetch_cache_not_found');
28
- }
29
- else {
30
- logger.error('fetchContext', 'fetch_failed', err);
31
- throw err;
32
- }
33
- }
34
- }
35
- try {
36
- fetchOption.cacheStrategy = 'update_cache';
37
- const response = await serviceRequest(fetchOption);
38
- if (response.meta?.lastUpdated === undefined || // skip lastUpdated check
39
- response.meta?.lastUpdated !== contextProvider.getValue(contextName)?.meta?.lastUpdated) {
40
- logger.logOther?.('fetchContext:', 'contextProvider.setValue(new-received-context)', { contextName });
41
- contextProvider.setValue(contextName, response, dispatchOptions);
42
- }
43
- }
44
- catch (err) {
45
- logger.error('fetchContext', 'fetch_failed', err);
46
- throw err;
47
- }
48
- }
49
11
  /**
50
12
  * Fetch from alwatr services and return standard response.
51
13
  */
package/fetch.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.js","sourceRoot":"","sources":["src/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAE,YAAY,EAAE,SAAS,EAAC,MAAM,gBAAgB,CAAC;AACrE,OAAO,EAAC,eAAe,EAAuB,MAAM,gBAAgB,CAAC;AACrE,OAAO,EAAC,WAAW,EAAE,KAAK,EAAC,MAAM,cAAc,CAAC;AAOhD,MAAM,MAAM,GAAG,YAAY,CAAC,cAAc,CAAC,CAAC;AAE5C,YAAY,CAAC,cAAc,CAAC,IAAI,CAAC;IAC/B,IAAI,EAAE,eAAe;IACrB,OAAO,EAAE,gBAAgB;CAC1B,CAAC,CAAC;AAEH,IAAI,kBAAyB,CAAC;AAC9B,MAAM,cAAc,GAAG,QAAQ,IAAI,UAAU,CAAC;AAE9C,MAAM,uBAAuB,GAAsC,EAAE,CAAC;AAEtE,MAAM,CAAC,KAAK,UAAU,YAAY,CAC9B,WAAmB,EACnB,WAAyB,EACzB,kBAA4C,EAAC,QAAQ,EAAE,SAAS,EAAC;IAEnE,MAAM,CAAC,aAAa,EAAE,CAAC,cAAc,EAAE,EAAC,WAAW,EAAC,CAAC,CAAC;IACtD,IAAI,cAAc,IAAI,eAAe,CAAC,QAAQ,CAAC,WAAW,CAAC,IAAI,IAAI,EAAE;QACnE,IAAI;YACF,WAAW,CAAC,aAAa,GAAG,YAAY,CAAC;YACzC,MAAM,QAAQ,GAAG,MAAM,cAAc,CAAC,WAAW,CAAC,CAAC;YACnD,eAAe,CAAC,QAAQ,CAAkB,WAAW,EAAE,QAAQ,EAAE,eAAe,CAAC,CAAC;YAClF,IAA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{getClientId, delay} from '@alwatr/util';\n\nimport type {FetchOptions} from './type.js';\nimport type {AlwatrServiceResponse} from '@alwatr/type';\n\nexport type * from './type.js';\n\nconst logger = createLogger('alwatr/fetch');\n\nglobalAlwatr.registeredList.push({\n name: '@alwatr/fetch',\n version: _ALWATR_VERSION_,\n});\n\nlet alwatrCacheStorage: Cache;\nconst cacheSupported = 'caches' in globalThis;\n\nconst duplicateRequestStorage: Record<string, Promise<Response>> = {};\n\nexport async function fetchContext(\n contextName: string,\n fetchOption: FetchOptions,\n dispatchOptions: Partial<DispatchOptions> = {debounce: 'Timeout'},\n): Promise<void> {\n logger.logMethodArgs?.('fetchContext', {contextName});\n if (cacheSupported && contextProvider.getValue(contextName) == null) {\n try {\n fetchOption.cacheStrategy = 'cache_only';\n const response = await serviceRequest(fetchOption);\n contextProvider.setValue<typeof response>(contextName, response, dispatchOptions);\n if (navigator.onLine === false) {\n logger.logOther?.('fetchContext:', 'offline');\n // retry on online\n return;\n }\n }\n catch (err) {\n if ((err as Error).message === 'fetch_cache_not_found') {\n logger.logOther?.('fetchContext:', 'fetch_cache_not_found');\n }\n else {\n logger.error('fetchContext', 'fetch_failed', err);\n throw err;\n }\n }\n }\n\n try {\n fetchOption.cacheStrategy = 'update_cache';\n const response = await serviceRequest(fetchOption);\n if (\n response.meta?.lastUpdated === undefined || // skip lastUpdated check\n response.meta?.lastUpdated !== contextProvider.getValue<typeof response>(contextName)?.meta?.lastUpdated\n ) {\n logger.logOther?.('fetchContext:', 'contextProvider.setValue(new-received-context)', {contextName});\n contextProvider.setValue<typeof response>(contextName, response, dispatchOptions);\n }\n }\n catch (err) {\n logger.error('fetchContext', 'fetch_failed', err);\n throw err;\n }\n}\n\n/**\n * Fetch from alwatr services and return standard response.\n */\nexport async function serviceRequest<\n T extends AlwatrServiceResponse = AlwatrServiceResponse\n>(options: FetchOptions): Promise<T> {\n logger.logMethodArgs?.('serviceRequest', {url: options.url});\n\n if (!NODE_MODE) {\n options.headers ??= {};\n if (!options.headers['client-id']) {\n options.headers['client-id'] = getClientId();\n }\n }\n\n let response: Response;\n try {\n response = await fetch(options);\n }\n catch (err) {\n const errMessage = (err as Error).message;\n if (errMessage !== 'fetch_cache_not_found') {\n logger.error('serviceRequest', (err as Error).message || 'fetch_failed', err, options);\n }\n throw err;\n }\n\n let responseText: string;\n try {\n responseText = await response.text();\n }\n catch (err) {\n logger.error('serviceRequest', 'invalid_response', err, {\n response,\n });\n throw err;\n }\n\n let responseJson: T;\n try {\n responseJson = JSON.parse(responseText);\n }\n catch (err) {\n logger.error('serviceRequest', 'invalid_json', err, {responseText});\n throw err;\n }\n\n if (responseJson.ok !== true) {\n if (typeof responseJson.errorCode === 'string') {\n logger.accident('serviceRequest', responseJson.errorCode, 'fetch response not ok', {responseJson});\n throw new Error(responseJson.errorCode);\n }\n else {\n logger.error('serviceRequest', 'fetch_nok', 'fetch response not ok', {responseJson});\n throw new Error('fetch_nok');\n }\n }\n\n // TODO: generate fetch signals hook (for easier handle loading and show error toast)\n\n return responseJson;\n}\n\n/**\n * It's a wrapper around the browser's `fetch` function that adds retry pattern, timeout, cacheStrategy,\n * remove duplicates, etc.\n *\n * Example:\n *\n * ```ts\n * const response = await fetch({\n * url: '/api/products',\n * queryParameters: {limit: 10},\n * timeout: 10_000,\n * retry: 3,\n * cacheStrategy: 'stale_while_revalidate',\n * cacheDuplicate: 'auto',\n * });\n * ```\n */\nexport function fetch(options: FetchOptions): Promise<Response> {\n options = _processOptions(options);\n logger.logMethodArgs?.('fetch', {options});\n return _handleCacheStrategy(options as Required<FetchOptions>);\n}\n\n/**\n * Process fetch options and set defaults, etc.\n */\nfunction _processOptions(options: FetchOptions): Required<FetchOptions> {\n options.method ??= 'GET';\n options.window ??= null;\n\n options.timeout ??= 10_000;\n options.retry ??= 3;\n options.retryDelay ??= 1_000;\n options.cacheStrategy ??= 'network_only';\n options.removeDuplicate ??= 'never';\n options.headers ??= {};\n\n if (options.cacheStrategy !== 'network_only' && cacheSupported !== true) {\n logger.incident?.('fetch', 'fetch_cache_strategy_ignore', 'Cache storage not support in this browser', {\n cacheSupported,\n });\n options.cacheStrategy = 'network_only';\n }\n\n if (options.removeDuplicate === 'auto') {\n options.removeDuplicate = cacheSupported ? 'until_load' : 'always';\n }\n\n if (options.url.lastIndexOf('?') === -1 && options.queryParameters != null) {\n const queryParameters = options.queryParameters;\n // prettier-ignore\n const queryArray = Object\n .keys(queryParameters)\n .map((key) => `${key}=${String(queryParameters[key])}`);\n\n if (queryArray.length > 0) {\n options.url += '?' + queryArray.join('&');\n }\n }\n\n if (options.bodyJson != null) {\n options.body = JSON.stringify(options.bodyJson);\n options.headers['Content-Type'] = 'application/json';\n }\n\n if (options.token != null) {\n options.headers.Authorization = `Bearer ${options.token}`;\n }\n\n if (options.userAuth != null) {\n options.headers.Authorization = `Bearer ${options.userAuth.id}/${options.userAuth.token}`;\n }\n\n return options as Required<FetchOptions>;\n}\n\n/**\n * Handle Cache Strategy over `_handleRemoveDuplicate`.\n */\nasync function _handleCacheStrategy(options: Required<FetchOptions>): Promise<Response> {\n if (options.cacheStrategy === 'network_only') {\n return _handleRemoveDuplicate(options);\n }\n // else handle cache strategies!\n logger.logMethod?.('_handleCacheStrategy');\n\n if (alwatrCacheStorage == null && options.cacheStorageName == null) {\n alwatrCacheStorage = await caches.open('alwatr_fetch_cache');\n }\n\n const cacheStorage =\n options.cacheStorageName != null ? await caches.open(options.cacheStorageName) : alwatrCacheStorage;\n\n const request = new Request(options.url, options);\n\n switch (options.cacheStrategy) {\n case 'cache_first': {\n const cachedResponse = await cacheStorage.match(request);\n if (cachedResponse != null) {\n return cachedResponse;\n }\n // else\n const response = await _handleRemoveDuplicate(options);\n if (response.ok) {\n cacheStorage.put(request, response.clone());\n }\n return response;\n }\n\n case 'cache_only': {\n const cachedResponse = await cacheStorage.match(request);\n if (cachedResponse == null) {\n logger.accident(\n '_handleCacheStrategy',\n 'fetch_cache_not_found',\n 'cacheStorage is cache_only but no cache found',\n {url: request.url},\n );\n throw new Error('fetch_cache_not_found');\n }\n // else\n return cachedResponse;\n }\n\n case 'network_first': {\n try {\n const networkResponse = await _handleRemoveDuplicate(options);\n if (networkResponse.ok) {\n cacheStorage.put(request, networkResponse.clone());\n }\n return networkResponse;\n }\n catch (err) {\n const cachedResponse = await cacheStorage.match(request);\n if (cachedResponse != null) {\n return cachedResponse;\n }\n // else\n throw err;\n }\n }\n\n case 'update_cache': {\n const networkResponse = await _handleRemoveDuplicate(options);\n if (networkResponse.ok) {\n cacheStorage.put(request, networkResponse.clone());\n }\n return networkResponse;\n }\n\n case 'stale_while_revalidate': {\n const cachedResponse = await cacheStorage.match(request);\n const fetchedResponsePromise = _handleRemoveDuplicate(options).then((networkResponse) => {\n if (networkResponse.ok) {\n cacheStorage.put(request, networkResponse.clone());\n if (typeof options.revalidateCallback === 'function') {\n setTimeout(options.revalidateCallback, 0, networkResponse.clone());\n }\n }\n return networkResponse;\n });\n\n return cachedResponse ?? fetchedResponsePromise;\n }\n\n default: {\n return _handleRemoveDuplicate(options);\n }\n }\n}\n\n/**\n * Handle Remove Duplicates over `_handleRetryPattern`.\n */\nasync function _handleRemoveDuplicate(options: Required<FetchOptions>): Promise<Response> {\n if (options.removeDuplicate === 'never') return _handleRetryPattern(options);\n\n logger.logMethod?.('_handleRemoveDuplicate');\n\n const cacheKey = options.method + ' ' + options.url;\n\n // We must cache fetch promise without await for handle other parallel requests.\n duplicateRequestStorage[cacheKey] ??= _handleRetryPattern(options);\n\n try {\n // For all requests need to await for clone responses.\n const response = await duplicateRequestStorage[cacheKey];\n\n if (duplicateRequestStorage[cacheKey] != null) {\n if (response.ok !== true || options.removeDuplicate === 'until_load') {\n delete duplicateRequestStorage[cacheKey];\n }\n }\n\n return response.clone();\n }\n catch (err) {\n // clean cache on any error.\n delete duplicateRequestStorage[cacheKey];\n throw err;\n }\n}\n\n/**\n * Handle retry pattern over `_handleTimeout`.\n */\nasync function _handleRetryPattern(options: Required<FetchOptions>): Promise<Response> {\n if (!(options.retry > 1)) return _handleTimeout(options);\n\n logger.logMethod?.('_handleRetryPattern');\n options.retry--;\n\n const externalAbortSignal = options.signal;\n\n try {\n const response = await _handleTimeout(options);\n\n if (response.status < 500) {\n return response;\n }\n // else\n throw new Error('fetch_server_error');\n }\n catch (err) {\n logger.accident('fetch', 'fetch_failed_retry', (err as Error)?.message || 'fetch failed and retry', err);\n\n if (globalThis.navigator?.onLine === false) {\n throw new Error('offline');\n }\n\n await delay(options.retryDelay);\n\n options.signal = externalAbortSignal;\n return _handleRetryPattern(options);\n }\n}\n\n/**\n * It's a wrapper around the browser's `fetch` with timeout.\n */\nfunction _handleTimeout(options: FetchOptions): Promise<Response> {\n if (options.timeout === 0) {\n return globalThis.fetch(options.url, options);\n }\n // else\n logger.logMethod?.('_handleTimeout');\n return new Promise((resolved, reject) => {\n // TODO: AbortController polyfill\n const abortController = new AbortController();\n const externalAbortSignal = options.signal;\n options.signal = abortController.signal;\n\n const timeoutId = setTimeout(() => {\n reject(new Error('fetch_timeout'));\n abortController.abort('fetch_timeout');\n }, options.timeout);\n\n if (externalAbortSignal != null) {\n // Respect external abort signal\n externalAbortSignal.addEventListener('abort', () => abortController.abort(), {once: true});\n }\n\n // abortController.signal.addEventListener('abort', () => {\n // logger.incident('fetch', 'fetch_abort_signal', 'fetch abort signal received', {\n // reason: abortController.signal.reason,\n // });\n // });\n\n globalThis\n .fetch(options.url, options)\n .then((response) => resolved(response))\n .catch((reason) => reject(reason))\n .finally(() => {\n delete options.signal; // try to avoid memory leak in nodejs!\n clearTimeout(timeoutId);\n });\n });\n}\n"]}
1
+ {"version":3,"file":"fetch.js","sourceRoot":"","sources":["src/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAE,YAAY,EAAE,SAAS,EAAC,MAAM,gBAAgB,CAAC;AACrE,OAAO,EAAC,WAAW,EAAE,KAAK,EAAC,MAAM,cAAc,CAAC;AAOhD,MAAM,MAAM,GAAG,YAAY,CAAC,cAAc,CAAC,C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EAAE,OAAO,CAAC;aAC3B,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;aACtC,KAAK,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;aACjC,OAAO,CAAC,GAAG,EAAE;YACZ,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,sCAAsC;YAC7D,YAAY,CAAC,SAAS,CAAC,CAAC;QAC1B,CAAC,CAAC,CAAC;IACT,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {createLogger, globalAlwatr, NODE_MODE} from '@alwatr/logger';\nimport {getClientId, delay} from '@alwatr/util';\n\nimport type {FetchOptions} from './type.js';\nimport type {AlwatrServiceResponse} from '@alwatr/type';\n\nexport type * from './type.js';\n\nconst logger = createLogger('alwatr/fetch');\n\nglobalAlwatr.registeredList.push({\n name: '@alwatr/fetch',\n version: _ALWATR_VERSION_,\n});\n\nlet alwatrCacheStorage: Cache;\nconst cacheSupported = 'caches' in globalThis;\n\nconst duplicateRequestStorage: Record<string, Promise<Response>> = {};\n\n/**\n * Fetch from alwatr services and return standard response.\n */\nexport async function serviceRequest<T extends AlwatrServiceResponse = AlwatrServiceResponse>(\n options: FetchOptions,\n): Promise<T> {\n logger.logMethodArgs?.('serviceRequest', {url: options.url});\n\n if (!NODE_MODE) {\n options.headers ??= {};\n if (!options.headers['client-id']) {\n options.headers['client-id'] = getClientId();\n }\n }\n\n let response: Response;\n try {\n response = await fetch(options);\n }\n catch (err) {\n const errMessage = (err as Error).message;\n if (errMessage !== 'fetch_cache_not_found') {\n logger.error('serviceRequest', (err as Error).message || 'fetch_failed', err, options);\n }\n throw err;\n }\n\n let responseText: string;\n try {\n responseText = await response.text();\n }\n catch (err) {\n logger.error('serviceRequest', 'invalid_response', err, {\n response,\n });\n throw err;\n }\n\n let responseJson: T;\n try {\n responseJson = JSON.parse(responseText);\n }\n catch (err) {\n logger.error('serviceRequest', 'invalid_json', err, {responseText});\n throw err;\n }\n\n if (responseJson.ok !== true) {\n if (typeof responseJson.errorCode === 'string') {\n logger.accident('serviceRequest', responseJson.errorCode, 'fetch response not ok', {responseJson});\n throw new Error(responseJson.errorCode);\n }\n else {\n logger.error('serviceRequest', 'fetch_nok', 'fetch response not ok', {responseJson});\n throw new Error('fetch_nok');\n }\n }\n\n // TODO: generate fetch signals hook (for easier handle loading and show error toast)\n\n return responseJson;\n}\n\n/**\n * It's a wrapper around the browser's `fetch` function that adds retry pattern, timeout, cacheStrategy,\n * remove duplicates, etc.\n *\n * Example:\n *\n * ```ts\n * const response = await fetch({\n * url: '/api/products',\n * queryParameters: {limit: 10},\n * timeout: 10_000,\n * retry: 3,\n * cacheStrategy: 'stale_while_revalidate',\n * cacheDuplicate: 'auto',\n * });\n * ```\n */\nexport function fetch(options: FetchOptions): Promise<Response> {\n options = _processOptions(options);\n logger.logMethodArgs?.('fetch', {options});\n return _handleCacheStrategy(options as Required<FetchOptions>);\n}\n\n/**\n * Process fetch options and set defaults, etc.\n */\nfunction _processOptions(options: FetchOptions): Required<FetchOptions> {\n options.method ??= 'GET';\n options.window ??= null;\n\n options.timeout ??= 10_000;\n options.retry ??= 3;\n options.retryDelay ??= 1_000;\n options.cacheStrategy ??= 'network_only';\n options.removeDuplicate ??= 'never';\n options.headers ??= {};\n\n if (options.cacheStrategy !== 'network_only' && cacheSupported !== true) {\n logger.incident?.('fetch', 'fetch_cache_strategy_ignore', 'Cache storage not support in this browser', {\n cacheSupported,\n });\n options.cacheStrategy = 'network_only';\n }\n\n if (options.removeDuplicate === 'auto') {\n options.removeDuplicate = cacheSupported ? 'until_load' : 'always';\n }\n\n if (options.url.lastIndexOf('?') === -1 && options.queryParameters != null) {\n const queryParameters = options.queryParameters;\n // prettier-ignore\n const queryArray = Object\n .keys(queryParameters)\n .map((key) => `${key}=${String(queryParameters[key])}`);\n\n if (queryArray.length > 0) {\n options.url += '?' + queryArray.join('&');\n }\n }\n\n if (options.bodyJson != null) {\n options.body = JSON.stringify(options.bodyJson);\n options.headers['Content-Type'] = 'application/json';\n }\n\n if (options.token != null) {\n options.headers.Authorization = `Bearer ${options.token}`;\n }\n\n if (options.userAuth != null) {\n options.headers.Authorization = `Bearer ${options.userAuth.id}/${options.userAuth.token}`;\n }\n\n return options as Required<FetchOptions>;\n}\n\n/**\n * Handle Cache Strategy over `_handleRemoveDuplicate`.\n */\nasync function _handleCacheStrategy(options: Required<FetchOptions>): Promise<Response> {\n if (options.cacheStrategy === 'network_only') {\n return _handleRemoveDuplicate(options);\n }\n // else handle cache strategies!\n logger.logMethod?.('_handleCacheStrategy');\n\n if (alwatrCacheStorage == null && options.cacheStorageName == null) {\n alwatrCacheStorage = await caches.open('alwatr_fetch_cache');\n }\n\n const cacheStorage =\n options.cacheStorageName != null ? await caches.open(options.cacheStorageName) : alwatrCacheStorage;\n\n const request = new Request(options.url, options);\n\n switch (options.cacheStrategy) {\n case 'cache_first': {\n const cachedResponse = await cacheStorage.match(request);\n if (cachedResponse != null) {\n return cachedResponse;\n }\n // else\n const response = await _handleRemoveDuplicate(options);\n if (response.ok) {\n cacheStorage.put(request, response.clone());\n }\n return response;\n }\n\n case 'cache_only': {\n const cachedResponse = await cacheStorage.match(request);\n if (cachedResponse == null) {\n logger.accident(\n '_handleCacheStrategy',\n 'fetch_cache_not_found',\n 'cacheStorage is cache_only but no cache found',\n {url: request.url},\n );\n throw new Error('fetch_cache_not_found');\n }\n // else\n return cachedResponse;\n }\n\n case 'network_first': {\n try {\n const networkResponse = await _handleRemoveDuplicate(options);\n if (networkResponse.ok) {\n cacheStorage.put(request, networkResponse.clone());\n }\n return networkResponse;\n }\n catch (err) {\n const cachedResponse = await cacheStorage.match(request);\n if (cachedResponse != null) {\n return cachedResponse;\n }\n // else\n throw err;\n }\n }\n\n case 'update_cache': {\n const networkResponse = await _handleRemoveDuplicate(options);\n if (networkResponse.ok) {\n cacheStorage.put(request, networkResponse.clone());\n }\n return networkResponse;\n }\n\n case 'stale_while_revalidate': {\n const cachedResponse = await cacheStorage.match(request);\n const fetchedResponsePromise = _handleRemoveDuplicate(options).then((networkResponse) => {\n if (networkResponse.ok) {\n cacheStorage.put(request, networkResponse.clone());\n if (typeof options.revalidateCallback === 'function') {\n setTimeout(options.revalidateCallback, 0, networkResponse.clone());\n }\n }\n return networkResponse;\n });\n\n return cachedResponse ?? fetchedResponsePromise;\n }\n\n default: {\n return _handleRemoveDuplicate(options);\n }\n }\n}\n\n/**\n * Handle Remove Duplicates over `_handleRetryPattern`.\n */\nasync function _handleRemoveDuplicate(options: Required<FetchOptions>): Promise<Response> {\n if (options.removeDuplicate === 'never') return _handleRetryPattern(options);\n\n logger.logMethod?.('_handleRemoveDuplicate');\n\n const cacheKey = options.method + ' ' + options.url;\n\n // We must cache fetch promise without await for handle other parallel requests.\n duplicateRequestStorage[cacheKey] ??= _handleRetryPattern(options);\n\n try {\n // For all requests need to await for clone responses.\n const response = await duplicateRequestStorage[cacheKey];\n\n if (duplicateRequestStorage[cacheKey] != null) {\n if (response.ok !== true || options.removeDuplicate === 'until_load') {\n delete duplicateRequestStorage[cacheKey];\n }\n }\n\n return response.clone();\n }\n catch (err) {\n // clean cache on any error.\n delete duplicateRequestStorage[cacheKey];\n throw err;\n }\n}\n\n/**\n * Handle retry pattern over `_handleTimeout`.\n */\nasync function _handleRetryPattern(options: Required<FetchOptions>): Promise<Response> {\n if (!(options.retry > 1)) return _handleTimeout(options);\n\n logger.logMethod?.('_handleRetryPattern');\n options.retry--;\n\n const externalAbortSignal = options.signal;\n\n try {\n const response = await _handleTimeout(options);\n\n if (response.status < 500) {\n return response;\n }\n // else\n throw new Error('fetch_server_error');\n }\n catch (err) {\n logger.accident('fetch', 'fetch_failed_retry', (err as Error)?.message || 'fetch failed and retry', err);\n\n if (globalThis.navigator?.onLine === false) {\n throw new Error('offline');\n }\n\n await delay(options.retryDelay);\n\n options.signal = externalAbortSignal;\n return _handleRetryPattern(options);\n }\n}\n\n/**\n * It's a wrapper around the browser's `fetch` with timeout.\n */\nfunction _handleTimeout(options: FetchOptions): Promise<Response> {\n if (options.timeout === 0) {\n return globalThis.fetch(options.url, options);\n }\n // else\n logger.logMethod?.('_handleTimeout');\n return new Promise((resolved, reject) => {\n // TODO: AbortController polyfill\n const abortController = new AbortController();\n const externalAbortSignal = options.signal;\n options.signal = abortController.signal;\n\n const timeoutId = setTimeout(() => {\n reject(new Error('fetch_timeout'));\n abortController.abort('fetch_timeout');\n }, options.timeout);\n\n if (externalAbortSignal != null) {\n // Respect external abort signal\n externalAbortSignal.addEventListener('abort', () => abortController.abort(), {once: true});\n }\n\n // abortController.signal.addEventListener('abort', () => {\n // logger.incident('fetch', 'fetch_abort_signal', 'fetch abort signal received', {\n // reason: abortController.signal.reason,\n // });\n // });\n\n globalThis\n .fetch(options.url, options)\n .then((response) => resolved(response))\n .catch((reason) => reject(reason))\n .finally(() => {\n delete options.signal; // try to avoid memory leak in nodejs!\n clearTimeout(timeoutId);\n });\n });\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alwatr/fetch",
3
- "version": "1.1.2",
3
+ "version": "2.0.0",
4
4
  "description": "Enhanced fetch API with cache strategy, retry pattern, timeout, helper methods and enhanced types written in tiny TypeScript, ES module.",
5
5
  "keywords": [
6
6
  "fetch",
@@ -34,10 +34,9 @@
34
34
  "url": "https://github.com/AliMD/alwatr/issues"
35
35
  },
36
36
  "dependencies": {
37
- "@alwatr/logger": "^1.1.2",
38
- "@alwatr/signal": "^1.1.2",
39
- "@alwatr/util": "^1.2.0",
37
+ "@alwatr/logger": "^1.1.3",
38
+ "@alwatr/util": "^1.2.1",
40
39
  "tslib": "^2.6.2"
41
40
  },
42
- "gitHead": "16036de8a6d781116e8c463ba41a2cb8cdc34edc"
41
+ "gitHead": "eade159065fc05a23a5ba8bf18bd2600dc2b5be3"
43
42
  }