@fozy-labs/rx-toolkit 0.5.3 → 0.6.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 (302) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +22 -13
  3. package/dist/common/devtools/reduxDevtools.js +17 -2
  4. package/dist/common/react/index.d.ts +1 -0
  5. package/dist/common/react/index.js +1 -0
  6. package/dist/common/react/useIsomorphicLayoutEffect.d.ts +17 -0
  7. package/dist/common/react/useIsomorphicLayoutEffect.js +17 -0
  8. package/dist/index.d.ts +1 -2
  9. package/dist/index.js +1 -2
  10. package/dist/query/api/createApi.d.ts +4 -0
  11. package/dist/query/api/createApi.js +9 -0
  12. package/dist/query/api/index.d.ts +1 -0
  13. package/dist/query/api/index.js +1 -0
  14. package/dist/query/constants.d.ts +12 -0
  15. package/dist/query/constants.js +15 -0
  16. package/dist/query/core/api/Api.d.ts +20 -0
  17. package/dist/query/core/api/Api.js +129 -0
  18. package/dist/query/core/api/constants.d.ts +2 -0
  19. package/dist/query/core/api/constants.js +3 -0
  20. package/dist/query/core/api/index.d.ts +4 -0
  21. package/dist/query/core/api/index.js +4 -0
  22. package/dist/query/core/api/mergeHooks.d.ts +2 -0
  23. package/dist/query/core/api/mergeHooks.js +26 -0
  24. package/dist/query/core/api/normalizeLinks.d.ts +2 -0
  25. package/dist/query/core/api/normalizeLinks.js +11 -0
  26. package/dist/query/core/cache/CacheEntry.d.ts +21 -0
  27. package/dist/query/core/cache/CacheEntry.js +54 -0
  28. package/dist/query/core/cache/CacheMap.d.ts +19 -0
  29. package/dist/query/core/cache/CacheMap.js +32 -0
  30. package/dist/query/core/cache/QueryCacheEntry.d.ts +21 -0
  31. package/dist/query/core/cache/QueryCacheEntry.js +136 -0
  32. package/dist/query/core/cache/index.d.ts +3 -0
  33. package/dist/query/core/cache/index.js +3 -0
  34. package/dist/query/core/command/Command.d.ts +67 -0
  35. package/dist/query/core/command/Command.js +253 -0
  36. package/dist/query/core/command/CommandAgent.d.ts +17 -0
  37. package/dist/query/core/command/CommandAgent.js +67 -0
  38. package/dist/query/core/command/LinkManager.d.ts +24 -0
  39. package/dist/query/core/command/LinkManager.js +71 -0
  40. package/dist/query/core/command/index.d.ts +2 -0
  41. package/dist/query/core/command/index.js +2 -0
  42. package/dist/query/core/errors/CacheEntryRemovedError.d.ts +7 -0
  43. package/dist/query/core/errors/CacheEntryRemovedError.js +9 -0
  44. package/dist/query/core/errors/MachineStateError.d.ts +8 -0
  45. package/dist/query/core/errors/MachineStateError.js +10 -0
  46. package/dist/query/core/errors/MachineTransitionError.d.ts +7 -0
  47. package/dist/query/core/errors/MachineTransitionError.js +9 -0
  48. package/dist/query/core/errors/index.d.ts +3 -0
  49. package/dist/query/core/errors/index.js +3 -0
  50. package/dist/query/core/index.d.ts +8 -0
  51. package/dist/query/core/index.js +8 -0
  52. package/dist/query/core/machine/Machine.d.ts +21 -0
  53. package/dist/query/core/machine/Machine.js +42 -0
  54. package/dist/query/core/machine/MachineBase.d.ts +31 -0
  55. package/dist/query/core/machine/MachineBase.js +176 -0
  56. package/dist/query/core/machine/MachineError.d.ts +10 -0
  57. package/dist/query/core/machine/MachineError.js +19 -0
  58. package/dist/query/core/machine/MachinePending.d.ts +13 -0
  59. package/dist/query/core/machine/MachinePending.js +32 -0
  60. package/dist/query/core/machine/MachineRefreshError.d.ts +12 -0
  61. package/dist/query/core/machine/MachineRefreshError.js +23 -0
  62. package/dist/query/core/machine/MachineRefreshing.d.ts +15 -0
  63. package/dist/query/core/machine/MachineRefreshing.js +43 -0
  64. package/dist/query/core/machine/MachineSuccess.d.ts +12 -0
  65. package/dist/query/core/machine/MachineSuccess.js +23 -0
  66. package/dist/query/core/machine/MachineWithData.d.ts +25 -0
  67. package/dist/query/core/machine/MachineWithData.js +73 -0
  68. package/dist/query/core/machine/index.d.ts +9 -0
  69. package/dist/query/core/machine/index.js +9 -0
  70. package/dist/query/core/machine/machine-helpers.d.ts +9 -0
  71. package/dist/query/core/machine/machine-helpers.js +80 -0
  72. package/dist/query/core/patcher/Patcher.d.ts +30 -0
  73. package/dist/query/core/patcher/Patcher.js +122 -0
  74. package/dist/query/core/patcher/index.d.ts +1 -0
  75. package/dist/query/core/patcher/index.js +1 -0
  76. package/dist/query/core/resource/Resource.d.ts +105 -0
  77. package/dist/query/core/resource/Resource.js +340 -0
  78. package/dist/query/core/resource/ResourceAgent.d.ts +37 -0
  79. package/dist/query/core/resource/ResourceAgent.js +179 -0
  80. package/dist/query/core/resource/index.d.ts +2 -0
  81. package/dist/query/core/resource/index.js +2 -0
  82. package/dist/query/core/snapshoter/Snapshoter.d.ts +22 -0
  83. package/dist/query/core/snapshoter/Snapshoter.js +78 -0
  84. package/dist/query/core/snapshoter/index.d.ts +2 -0
  85. package/dist/query/core/snapshoter/index.js +1 -0
  86. package/dist/query/core/syncer/Syncer.d.ts +32 -0
  87. package/dist/query/core/syncer/Syncer.js +85 -0
  88. package/dist/query/core/syncer/index.d.ts +2 -0
  89. package/dist/query/core/syncer/index.js +1 -0
  90. package/dist/query/index.d.ts +5 -10
  91. package/dist/query/index.js +5 -13
  92. package/dist/query/lib/broadcastSyncDriver.d.ts +5 -0
  93. package/dist/query/lib/broadcastSyncDriver.js +46 -0
  94. package/dist/query/lib/index.d.ts +3 -0
  95. package/dist/query/lib/index.js +3 -0
  96. package/dist/{query-v2 → query}/lib/stableStringify.js +5 -3
  97. package/dist/query/lib/toKeyed.d.ts +11 -0
  98. package/dist/query/lib/toKeyed.js +18 -0
  99. package/dist/query/react/ReactHooksPlugin.d.ts +31 -0
  100. package/dist/query/react/ReactHooksPlugin.js +21 -0
  101. package/dist/query/react/index.d.ts +3 -0
  102. package/dist/query/react/index.js +3 -0
  103. package/dist/query/react/useCommand.d.ts +2 -0
  104. package/dist/query/react/useCommand.js +14 -0
  105. package/dist/query/react/useResource.d.ts +2 -0
  106. package/dist/query/react/useResource.js +16 -0
  107. package/dist/query/types/api.d.ts +39 -0
  108. package/dist/query/types/cache.d.ts +51 -0
  109. package/dist/query/types/command.d.ts +52 -0
  110. package/dist/query/types/common.d.ts +65 -0
  111. package/dist/query/types/index.d.ts +8 -4
  112. package/dist/query/types/index.js +8 -5
  113. package/dist/query/types/plugin-hkt.d.ts +64 -0
  114. package/dist/query/types/resource.d.ts +49 -0
  115. package/dist/query/types/snapshot.d.ts +27 -0
  116. package/dist/query/types/snapshot.js +2 -0
  117. package/dist/query/types/state.d.ts +24 -0
  118. package/dist/signals/base/ComputeCache.js +1 -1
  119. package/dist/signals/base/Devtools.js +2 -6
  120. package/dist/signals/signals/Computed.d.ts +1 -0
  121. package/dist/signals/signals/Computed.js +5 -1
  122. package/dist/signals/signals/Effect.d.ts +0 -4
  123. package/dist/signals/signals/Effect.js +0 -6
  124. package/dist/signals/signals/LocalState.d.ts +1 -10
  125. package/dist/signals/signals/LocalState.js +0 -12
  126. package/dist/signals/signals/Signal.d.ts +2 -8
  127. package/dist/signals/signals/Signal.js +1 -10
  128. package/dist/signals/signals/State.d.ts +2 -1
  129. package/dist/signals/signals/State.js +9 -0
  130. package/dist/signals/types/SignalOptions.d.ts +0 -2
  131. package/dist/signals/types/normalizeSignalOptions.js +0 -3
  132. package/dist/signals/types/signals.types.d.ts +3 -1
  133. package/docs/CHANGELOG.md +61 -31
  134. package/docs/migrations/0.6.0.md +224 -0
  135. package/docs/query/README.md +52 -562
  136. package/docs/query/api/README.md +59 -0
  137. package/docs/query/api/_CacheEntry.md +39 -0
  138. package/docs/query/api/_CacheMap.md +30 -0
  139. package/docs/query/api/_QueryCacheEntry.md +81 -0
  140. package/docs/query/api/command-agent.md +60 -0
  141. package/docs/query/api/command.md +76 -0
  142. package/docs/query/api/resource-agent.md +68 -0
  143. package/docs/query/api/resource.md +77 -0
  144. package/docs/query/concepts/agent.md +70 -0
  145. package/docs/query/concepts/architecture.md +139 -0
  146. package/docs/query/concepts/cache.md +81 -0
  147. package/docs/query/concepts/dataflows.md +473 -0
  148. package/docs/query/concepts/keyed.md +42 -0
  149. package/docs/query/concepts/machine.md +106 -0
  150. package/docs/query/concepts/patching.md +85 -0
  151. package/docs/query/usage/broadcast.md +188 -0
  152. package/docs/query/usage/command.md +203 -0
  153. package/docs/query/usage/lifecycle.md +114 -0
  154. package/docs/query/usage/links.md +125 -0
  155. package/docs/query/usage/plugins.md +96 -0
  156. package/docs/query/usage/resource.md +206 -0
  157. package/docs/query/usage/snapshot.md +80 -0
  158. package/docs/usage/react/README.md +45 -91
  159. package/package.json +6 -9
  160. package/dist/query/SKIP_TOKEN.d.ts +0 -1
  161. package/dist/query/SKIP_TOKEN.js +0 -1
  162. package/dist/query/api/createCommand.d.ts +0 -21
  163. package/dist/query/api/createCommand.js +0 -20
  164. package/dist/query/api/createOperation.d.ts +0 -5
  165. package/dist/query/api/createOperation.js +0 -6
  166. package/dist/query/api/createResource.d.ts +0 -3
  167. package/dist/query/api/createResource.js +0 -2
  168. package/dist/query/api/createResourceDuplicator.d.ts +0 -4
  169. package/dist/query/api/createResourceDuplicator.js +0 -2
  170. package/dist/query/api/resetAllQueriesCache.d.ts +0 -1
  171. package/dist/query/api/resetAllQueriesCache.js +0 -4
  172. package/dist/query/core/Command/Command.d.ts +0 -35
  173. package/dist/query/core/Command/Command.js +0 -210
  174. package/dist/query/core/Command/CommandAgent.d.ts +0 -19
  175. package/dist/query/core/Command/CommandAgent.js +0 -54
  176. package/dist/query/core/Command/index.d.ts +0 -2
  177. package/dist/query/core/Command/index.js +0 -2
  178. package/dist/query/core/Operation/Operation.d.ts +0 -8
  179. package/dist/query/core/Operation/Operation.js +0 -4
  180. package/dist/query/core/Operation/OperationAgent.d.ts +0 -4
  181. package/dist/query/core/Operation/OperationAgent.js +0 -4
  182. package/dist/query/core/QueriesCache.d.ts +0 -9
  183. package/dist/query/core/QueriesCache.js +0 -28
  184. package/dist/query/core/QueriesLifetimeHooks.d.ts +0 -22
  185. package/dist/query/core/QueriesLifetimeHooks.js +0 -86
  186. package/dist/query/core/ResetAllQueriesSignal.d.ts +0 -6
  187. package/dist/query/core/ResetAllQueriesSignal.js +0 -11
  188. package/dist/query/core/Resource/Resource.d.ts +0 -51
  189. package/dist/query/core/Resource/Resource.js +0 -232
  190. package/dist/query/core/Resource/ResourceAgent.d.ts +0 -35
  191. package/dist/query/core/Resource/ResourceAgent.js +0 -110
  192. package/dist/query/core/Resource/ResourceDuplicator.d.ts +0 -73
  193. package/dist/query/core/Resource/ResourceDuplicator.js +0 -227
  194. package/dist/query/core/Resource/ResourceDuplicatorAgent.d.ts +0 -35
  195. package/dist/query/core/Resource/ResourceDuplicatorAgent.js +0 -110
  196. package/dist/query/core/Resource/ResourceRef.d.ts +0 -16
  197. package/dist/query/core/Resource/ResourceRef.js +0 -136
  198. package/dist/query/lib/IndirectMap.d.ts +0 -19
  199. package/dist/query/lib/IndirectMap.js +0 -88
  200. package/dist/query/lib/ReactiveCache.d.ts +0 -62
  201. package/dist/query/lib/ReactiveCache.js +0 -80
  202. package/dist/query/react/useCommandAgent.d.ts +0 -24
  203. package/dist/query/react/useCommandAgent.js +0 -39
  204. package/dist/query/react/useOperationAgent.d.ts +0 -6
  205. package/dist/query/react/useOperationAgent.js +0 -6
  206. package/dist/query/react/useResourceAgent.d.ts +0 -6
  207. package/dist/query/react/useResourceAgent.js +0 -31
  208. package/dist/query/react/useResourceRef.d.ts +0 -5
  209. package/dist/query/react/useResourceRef.js +0 -13
  210. package/dist/query/types/Command.types.d.ts +0 -154
  211. package/dist/query/types/Command.types.js +0 -1
  212. package/dist/query/types/Operation.types.d.ts +0 -13
  213. package/dist/query/types/Operation.types.js +0 -1
  214. package/dist/query/types/Resource.types.d.ts +0 -129
  215. package/dist/query/types/Resource.types.js +0 -1
  216. package/dist/query/types/shared.types.d.ts +0 -26
  217. package/dist/query/types/shared.types.js +0 -1
  218. package/dist/query-v2/api/createApi.d.ts +0 -10
  219. package/dist/query-v2/api/createApi.js +0 -83
  220. package/dist/query-v2/core/common/CacheEntry.d.ts +0 -29
  221. package/dist/query-v2/core/common/CacheEntry.js +0 -71
  222. package/dist/query-v2/core/common/CacheMap.d.ts +0 -38
  223. package/dist/query-v2/core/common/CacheMap.js +0 -127
  224. package/dist/query-v2/core/common/LifecycleHooks.d.ts +0 -22
  225. package/dist/query-v2/core/common/LifecycleHooks.js +0 -104
  226. package/dist/query-v2/core/common/index.d.ts +0 -3
  227. package/dist/query-v2/core/common/index.js +0 -3
  228. package/dist/query-v2/core/index.d.ts +0 -3
  229. package/dist/query-v2/core/index.js +0 -3
  230. package/dist/query-v2/core/machines/Machine.d.ts +0 -14
  231. package/dist/query-v2/core/machines/Machine.js +0 -33
  232. package/dist/query-v2/core/machines/MachineError.d.ts +0 -11
  233. package/dist/query-v2/core/machines/MachineError.js +0 -26
  234. package/dist/query-v2/core/machines/MachineIdle.d.ts +0 -8
  235. package/dist/query-v2/core/machines/MachineIdle.js +0 -19
  236. package/dist/query-v2/core/machines/MachinePending.d.ts +0 -12
  237. package/dist/query-v2/core/machines/MachinePending.js +0 -29
  238. package/dist/query-v2/core/machines/MachineRefreshing.d.ts +0 -14
  239. package/dist/query-v2/core/machines/MachineRefreshing.js +0 -46
  240. package/dist/query-v2/core/machines/MachineSuccess.d.ts +0 -16
  241. package/dist/query-v2/core/machines/MachineSuccess.js +0 -42
  242. package/dist/query-v2/core/machines/MachineWithData.d.ts +0 -18
  243. package/dist/query-v2/core/machines/MachineWithData.js +0 -40
  244. package/dist/query-v2/core/machines/Patcher.d.ts +0 -20
  245. package/dist/query-v2/core/machines/Patcher.js +0 -104
  246. package/dist/query-v2/core/machines/index.d.ts +0 -8
  247. package/dist/query-v2/core/machines/index.js +0 -8
  248. package/dist/query-v2/core/resource/ResourceV2.d.ts +0 -120
  249. package/dist/query-v2/core/resource/ResourceV2.js +0 -464
  250. package/dist/query-v2/core/resource/ResourceV2Agent.d.ts +0 -26
  251. package/dist/query-v2/core/resource/ResourceV2Agent.js +0 -132
  252. package/dist/query-v2/core/resource/index.d.ts +0 -2
  253. package/dist/query-v2/core/resource/index.js +0 -2
  254. package/dist/query-v2/index.d.ts +0 -11
  255. package/dist/query-v2/index.js +0 -17
  256. package/dist/query-v2/lib/NO_VALUE.d.ts +0 -2
  257. package/dist/query-v2/lib/NO_VALUE.js +0 -1
  258. package/dist/query-v2/lib/SKIP_TOKEN.d.ts +0 -2
  259. package/dist/query-v2/lib/SKIP_TOKEN.js +0 -1
  260. package/dist/query-v2/lib/index.d.ts +0 -4
  261. package/dist/query-v2/lib/index.js +0 -3
  262. package/dist/query-v2/plugins/ReactHooksPlugin.d.ts +0 -25
  263. package/dist/query-v2/plugins/ReactHooksPlugin.js +0 -19
  264. package/dist/query-v2/plugins/types.d.ts +0 -1
  265. package/dist/query-v2/react/__tests__/helpers.d.ts +0 -12
  266. package/dist/query-v2/react/__tests__/helpers.js +0 -33
  267. package/dist/query-v2/react/index.d.ts +0 -2
  268. package/dist/query-v2/react/index.js +0 -2
  269. package/dist/query-v2/react/useResourceV2Agent.d.ts +0 -12
  270. package/dist/query-v2/react/useResourceV2Agent.js +0 -36
  271. package/dist/query-v2/react/useResourceV2Ref.d.ts +0 -12
  272. package/dist/query-v2/react/useResourceV2Ref.js +0 -57
  273. package/dist/query-v2/snapshot/Snapshot.d.ts +0 -13
  274. package/dist/query-v2/snapshot/Snapshot.js +0 -76
  275. package/dist/query-v2/types/agent.types.d.ts +0 -54
  276. package/dist/query-v2/types/api.types.d.ts +0 -22
  277. package/dist/query-v2/types/cache.types.d.ts +0 -37
  278. package/dist/query-v2/types/index.d.ts +0 -9
  279. package/dist/query-v2/types/index.js +0 -9
  280. package/dist/query-v2/types/lifecycle.types.d.ts +0 -25
  281. package/dist/query-v2/types/machine.types.d.ts +0 -67
  282. package/dist/query-v2/types/plugin.types.d.ts +0 -38
  283. package/dist/query-v2/types/resource.types.d.ts +0 -35
  284. package/dist/query-v2/types/resource.types.js +0 -1
  285. package/dist/query-v2/types/shared.types.d.ts +0 -20
  286. package/dist/query-v2/types/shared.types.js +0 -1
  287. package/dist/query-v2/types/snapshot.types.d.ts +0 -21
  288. package/dist/query-v2/types/snapshot.types.js +0 -1
  289. package/docs/contributing/query-v2/README.md +0 -379
  290. package/docs/migrations/query-v2.md +0 -171
  291. package/docs/query-v2/README.md +0 -280
  292. package/docs/query-v2/api-reference.md +0 -235
  293. package/docs/query-v2/optimistic-updates.md +0 -148
  294. package/docs/query-v2/ssr.md +0 -130
  295. /package/dist/{query-v2 → query}/lib/stableStringify.d.ts +0 -0
  296. /package/dist/{query-v2/plugins/types.js → query/types/api.js} +0 -0
  297. /package/dist/{query-v2/types/agent.types.js → query/types/cache.js} +0 -0
  298. /package/dist/{query-v2/types/api.types.js → query/types/command.js} +0 -0
  299. /package/dist/{query-v2/types/cache.types.js → query/types/common.js} +0 -0
  300. /package/dist/{query-v2/types/lifecycle.types.js → query/types/plugin-hkt.js} +0 -0
  301. /package/dist/{query-v2/types/machine.types.js → query/types/resource.js} +0 -0
  302. /package/dist/{query-v2/types/plugin.types.js → query/types/state.js} +0 -0
@@ -1,136 +0,0 @@
1
- import { applyPatches, enablePatches, produceWithPatches } from "immer";
2
- enablePatches();
3
- export class ResourceRef {
4
- _resource;
5
- _args;
6
- _cacheItem = null;
7
- constructor(_resource, _args) {
8
- this._resource = _resource;
9
- this._args = _args;
10
- }
11
- get has() {
12
- if (this._cacheItem)
13
- return true;
14
- this._cacheItem = this._resource.getQueryCache(this._args) ?? null;
15
- return !!this._cacheItem;
16
- }
17
- lock() {
18
- this._cacheItem = this._resource.incrementLock(this._args, { cache: this._cacheItem ?? undefined });
19
- let isLocked = true;
20
- return {
21
- unlock: () => {
22
- if (!isLocked)
23
- return;
24
- isLocked = false;
25
- this._resource.decrementLock(this._args, { cache: this._cacheItem });
26
- },
27
- };
28
- }
29
- unlockOne() {
30
- this._cacheItem = this._resource.decrementLock(this._args, { cache: this._cacheItem });
31
- }
32
- patch(patchFn) {
33
- let isSkipped = true;
34
- const reapplyFn = (data, savedData, transactions) => {
35
- if (!transactions || transactions.length === 0) {
36
- return { data, transactions, savedData };
37
- }
38
- // Все валидные committed - пропускаем и убираем из очереди
39
- // Все aborted - применяем и убираем из очереди
40
- // Все pending - применяем и оставляем в очереди
41
- // Все commited (которые после pending) - применяем, но оставляем в очереди
42
- // Все aborted (которые после pending) - откатываем, но оставляем в очереди
43
- // Если после aborted нет pending - пропускаем и убираем из очереди
44
- // Те после применения всех транзакций, очередь должна начинаться с первой pending транзакции (если есть), включая все, что после неё.
45
- let newSavedData = savedData ?? data;
46
- let currentData = savedData ?? data;
47
- const remainingTransactions = [];
48
- let foundPending = false;
49
- const lastPendingIndex = transactions.findLastIndex((t) => t.status === "pending");
50
- transactions.forEach((transaction, index) => {
51
- if (transaction.status === "pending") {
52
- foundPending = true;
53
- // Применяем pending транзакцию и оставляем в очереди
54
- currentData = applyPatches(currentData, transaction.patches);
55
- remainingTransactions.push(transaction);
56
- }
57
- else if (foundPending) {
58
- // После pending транзакции
59
- if (transaction.status === "committed") {
60
- // Применяем и оставляем в очереди
61
- currentData = applyPatches(currentData, transaction.patches);
62
- remainingTransactions.push(transaction);
63
- }
64
- else if (transaction.status === "aborted") {
65
- // Проверяем, есть ли pending после текущей aborted
66
- const hasPendingAfter = index < lastPendingIndex;
67
- if (hasPendingAfter) {
68
- currentData = applyPatches(currentData, transaction.inversePatches);
69
- remainingTransactions.push(transaction);
70
- }
71
- // Если pending нет - пропускаем и убираем из очереди
72
- }
73
- }
74
- else {
75
- // До первой pending транзакции
76
- if (transaction.status === "committed") {
77
- // Применяем и убираем из очереди
78
- const patches = transaction.patches;
79
- currentData = applyPatches(currentData, patches);
80
- newSavedData = currentData;
81
- }
82
- }
83
- });
84
- const hasTransactions = remainingTransactions.length > 0;
85
- return {
86
- data: currentData,
87
- transactions: hasTransactions ? remainingTransactions : null,
88
- savedData: hasTransactions ? newSavedData : null,
89
- };
90
- };
91
- const reapplyTransactions = () => {
92
- this._resource.update(this._args, reapplyFn, { cache: this._cacheItem ?? undefined });
93
- };
94
- const transaction = {
95
- patches: [],
96
- inversePatches: [],
97
- status: "pending",
98
- abort() {
99
- if (this.status !== "pending")
100
- return;
101
- this.status = "aborted";
102
- reapplyTransactions();
103
- },
104
- commit() {
105
- if (this.status !== "pending")
106
- return;
107
- this.status = "committed";
108
- reapplyTransactions();
109
- },
110
- };
111
- const updateFn = (data, savedData, transactions) => {
112
- isSkipped = false;
113
- const [newData, patches, inversePatches] = produceWithPatches(data, (draft) => patchFn(draft));
114
- transaction.patches = patches;
115
- transaction.inversePatches = inversePatches;
116
- const newTransactions = [...(transactions ?? [])];
117
- newTransactions.push(transaction);
118
- return {
119
- data: newData,
120
- transactions: newTransactions,
121
- savedData: savedData ?? data,
122
- };
123
- };
124
- this._cacheItem = this._resource.update(this._args, updateFn, { cache: this._cacheItem ?? undefined });
125
- if (isSkipped) {
126
- return null;
127
- }
128
- return transaction;
129
- }
130
- create(data) {
131
- this._cacheItem = this._resource.createWithData(this._args, data, { cache: this._cacheItem ?? undefined });
132
- }
133
- invalidate() {
134
- this._cacheItem = this._resource.initiate(this._args, { cache: this._cacheItem ?? undefined });
135
- }
136
- }
@@ -1,19 +0,0 @@
1
- type CompareFn<T> = (a: T, b: T) => boolean;
2
- export declare class IndirectMap<KEY, VALUE> {
3
- private _compareObjectsFn;
4
- private _compareCache;
5
- private _map;
6
- constructor(_compareObjectsFn?: CompareFn<KEY>);
7
- private _getCachedKey;
8
- get(key: KEY): VALUE | undefined;
9
- set(key: KEY, value: VALUE): void;
10
- /**
11
- * Удаляет элемент из кеша, не зависимо от того,
12
- * ссылается ли на него другой объект или нет
13
- * @param key
14
- */
15
- delete(key: KEY): void;
16
- has(key: KEY): boolean;
17
- values(): MapIterator<VALUE>;
18
- }
19
- export {};
@@ -1,88 +0,0 @@
1
- import { shallowEqual } from "../../common/utils";
2
- export class IndirectMap {
3
- _compareObjectsFn;
4
- _compareCache = new WeakMap();
5
- _map = new Map();
6
- constructor(_compareObjectsFn = shallowEqual) {
7
- this._compareObjectsFn = _compareObjectsFn;
8
- }
9
- _getCachedKey(key) {
10
- const cachedKey = this._compareCache.get(key);
11
- if (cachedKey) {
12
- return cachedKey;
13
- }
14
- for (const cachedKey of this._map.keys()) {
15
- if (this._compareObjectsFn(key, cachedKey)) {
16
- this._compareCache.set(key, cachedKey);
17
- return cachedKey;
18
- }
19
- }
20
- return undefined;
21
- }
22
- get(key) {
23
- const item = this._map.get(key);
24
- if (!item) {
25
- const isObject = typeof key === "object" && key !== null;
26
- if (!isObject) {
27
- return undefined;
28
- }
29
- const cachedKey = this._getCachedKey(key);
30
- if (!cachedKey) {
31
- return undefined;
32
- }
33
- return this._map.get(cachedKey);
34
- }
35
- return item;
36
- }
37
- set(key, value) {
38
- const has = this._map.has(key);
39
- if (has) {
40
- this._map.set(key, value);
41
- }
42
- else {
43
- const isObject = typeof key === "object" && key !== null;
44
- if (!isObject) {
45
- this._map.set(key, value);
46
- return;
47
- }
48
- const cachedKey = this._getCachedKey(key);
49
- if (cachedKey) {
50
- this._map.set(cachedKey, value);
51
- }
52
- else {
53
- this._map.set(key, value);
54
- this._compareCache.set(key, key);
55
- }
56
- }
57
- }
58
- /**
59
- * Удаляет элемент из кеша, не зависимо от того,
60
- * ссылается ли на него другой объект или нет
61
- * @param key
62
- */
63
- delete(key) {
64
- const isObject = typeof key === "object" && key !== null;
65
- if (isObject) {
66
- const cachedKey = this._getCachedKey(key);
67
- if (cachedKey) {
68
- this._map.delete(cachedKey);
69
- this._compareCache.delete(key);
70
- }
71
- }
72
- this._map.delete(key);
73
- }
74
- has(key) {
75
- const has = this._map.has(key);
76
- if (!has && typeof key === "object" && key !== null) {
77
- const cachedKey = this._getCachedKey(key);
78
- if (!cachedKey) {
79
- return false;
80
- }
81
- return this._map.has(cachedKey);
82
- }
83
- return has;
84
- }
85
- values() {
86
- return this._map.values();
87
- }
88
- }
@@ -1,62 +0,0 @@
1
- import { Observable, Subject } from "rxjs";
2
- import { ReadableSignalLike } from "../../signals/types";
3
- type Options<VALUE> = {
4
- /**
5
- * Начальное состояние кэша
6
- */
7
- initialState: VALUE;
8
- /**
9
- * Время жизни кэша в миллисекундах (пока нет подписок на кеш)
10
- * Если указано `false`, кэш не будет очищаться автоматически.
11
- * Если указано `0` или меньше, кэш будет очищаться сразу после отписки от него.
12
- * @default 60_000 (1 минута)
13
- */
14
- cacheLifeTime?: number | false;
15
- };
16
- /**
17
- * Класс `ReactiveCache` представляет собой реактивный кэш,
18
- * который позволяет управлять состоянием и временем жизни кэшированных данных.
19
- *
20
- * @template VALUE Тип значения, хранимого в кэше.
21
- */
22
- export declare class ReactiveCache<VALUE> {
23
- /**
24
- * Внутренний `BehaviorSubject`, хранящий текущее состояние кэша.
25
- * @private
26
- */
27
- private _state$;
28
- /**
29
- * Реактивное значене (Observable)
30
- */
31
- value$: ReadableSignalLike<VALUE>;
32
- /**
33
- * Значение без сайд-эффектов (для использования в DevTools)
34
- */
35
- spy$: Observable<VALUE>;
36
- /**
37
- * Subject, уведомляющий об очистке кэша.
38
- */
39
- onClean$: Subject<VALUE>;
40
- closed: boolean;
41
- /**
42
- * Создает новый экземпляр `ReactiveCacheItem`.
43
- *
44
- * @param options Параметры для настройки элемента кэша.
45
- * @param options.initialState Начальное состояние кэша.
46
- * @param options.cacheLifeTime Время жизни кэша в миллисекундах (по умолчанию 60_000).
47
- */
48
- constructor(options: Options<VALUE>);
49
- private _getOnRefCountZero;
50
- get value(): VALUE;
51
- /**
52
- * Устанавливает новое значение в кэш и обновляет поток состояния.
53
- *
54
- * @param value Новое значение для кэша.
55
- */
56
- next(value: VALUE): void;
57
- /**
58
- * Завершает работу кэша, закрывая все потоки и уведомляя об очистке.
59
- */
60
- complete(): void;
61
- }
62
- export {};
@@ -1,80 +0,0 @@
1
- import { BehaviorSubject, finalize, ReplaySubject, share, Subject, takeUntil, timer } from "rxjs";
2
- import { signalize } from "../../signals";
3
- /**
4
- * Класс `ReactiveCache` представляет собой реактивный кэш,
5
- * который позволяет управлять состоянием и временем жизни кэшированных данных.
6
- *
7
- * @template VALUE Тип значения, хранимого в кэше.
8
- */
9
- export class ReactiveCache {
10
- /**
11
- * Внутренний `BehaviorSubject`, хранящий текущее состояние кэша.
12
- * @private
13
- */
14
- _state$;
15
- /**
16
- * Реактивное значене (Observable)
17
- */
18
- value$;
19
- /**
20
- * Значение без сайд-эффектов (для использования в DevTools)
21
- */
22
- spy$;
23
- /**
24
- * Subject, уведомляющий об очистке кэша.
25
- */
26
- onClean$ = new Subject();
27
- closed = false;
28
- /**
29
- * Создает новый экземпляр `ReactiveCacheItem`.
30
- *
31
- * @param options Параметры для настройки элемента кэша.
32
- * @param options.initialState Начальное состояние кэша.
33
- * @param options.cacheLifeTime Время жизни кэша в миллисекундах (по умолчанию 60_000).
34
- */
35
- constructor(options) {
36
- const cacheLifeTime = options.cacheLifeTime ?? 60_000;
37
- this._state$ = new BehaviorSubject(options.initialState);
38
- this.spy$ = this._state$.pipe(takeUntil(this.onClean$));
39
- this.value$ = signalize(this._state$.pipe(finalize(() => {
40
- this.complete();
41
- }), share({
42
- connector: () => new ReplaySubject(1),
43
- resetOnRefCountZero: this._getOnRefCountZero(cacheLifeTime),
44
- resetOnComplete: true,
45
- })));
46
- }
47
- _getOnRefCountZero(cacheLifeTime) {
48
- if (cacheLifeTime === false) {
49
- return false;
50
- }
51
- if (cacheLifeTime <= 0) {
52
- return true;
53
- }
54
- return () => {
55
- return timer(cacheLifeTime);
56
- };
57
- }
58
- get value() {
59
- return this._state$.getValue();
60
- }
61
- /**
62
- * Устанавливает новое значение в кэш и обновляет поток состояния.
63
- *
64
- * @param value Новое значение для кэша.
65
- */
66
- next(value) {
67
- this._state$.next(value);
68
- }
69
- /**
70
- * Завершает работу кэша, закрывая все потоки и уведомляя об очистке.
71
- */
72
- complete() {
73
- if (this.closed)
74
- return;
75
- this.closed = true;
76
- this._state$.complete();
77
- this.onClean$.next(this._state$.getValue());
78
- this.onClean$.complete();
79
- }
80
- }
@@ -1,24 +0,0 @@
1
- import type { CommandAgentInstance, CommandDefinition, CommandQueryState, Prettify } from "../../query/types";
2
- type WithAgent<D extends CommandDefinition> = {
3
- createAgent: () => CommandAgentInstance<D>;
4
- };
5
- type TriggerFn<D extends CommandDefinition> = (args: D["Args"]) => Promise<D["Data"]>;
6
- type Result<D extends CommandDefinition> = [TriggerFn<D>, Prettify<CommandQueryState<D>>];
7
- /**
8
- * React hook для работы с командой (Command).
9
- *
10
- * Возвращает кортеж `[trigger, state]`:
11
- * - `trigger(args)` — инициирует выполнение команды и возвращает Promise с результатом.
12
- * - `state` — реактивное состояние выполнения команды.
13
- *
14
- * @example
15
- * ```tsx
16
- * const [updateUser, state] = useCommandAgent(api.updateUser);
17
- *
18
- * const handleSubmit = async () => {
19
- * const result = await updateUser({ id: 1, name: 'New Name' });
20
- * };
21
- * ```
22
- */
23
- export declare function useCommandAgent<D extends CommandDefinition>(op: WithAgent<D>): Result<D>;
24
- export {};
@@ -1,39 +0,0 @@
1
- import { useConstant, useEventHandler } from "../../common/react";
2
- import { useSignal } from "../../signals/react";
3
- /**
4
- * React hook для работы с командой (Command).
5
- *
6
- * Возвращает кортеж `[trigger, state]`:
7
- * - `trigger(args)` — инициирует выполнение команды и возвращает Promise с результатом.
8
- * - `state` — реактивное состояние выполнения команды.
9
- *
10
- * @example
11
- * ```tsx
12
- * const [updateUser, state] = useCommandAgent(api.updateUser);
13
- *
14
- * const handleSubmit = async () => {
15
- * const result = await updateUser({ id: 1, name: 'New Name' });
16
- * };
17
- * ```
18
- */
19
- export function useCommandAgent(op) {
20
- const agent = useConstant(() => op.createAgent());
21
- const state = useSignal(agent.state$);
22
- const trigger = useEventHandler((args) => {
23
- agent.initiate(args);
24
- return new Promise((resolve, reject) => {
25
- const sub = agent.state$.obs.subscribe((s) => {
26
- if (s.isDone && !s.isLoading) {
27
- sub.unsubscribe();
28
- if (s.isSuccess) {
29
- resolve(s.data);
30
- }
31
- else {
32
- reject(s.error);
33
- }
34
- }
35
- });
36
- });
37
- });
38
- return [trigger, state];
39
- }
@@ -1,6 +0,0 @@
1
- import { useCommandAgent } from "./useCommandAgent";
2
- /**
3
- * @deprecated Use `useCommandAgent` instead. Will be removed in v0.6.0.
4
- * @see useCommandAgent
5
- */
6
- export declare const useOperationAgent: typeof useCommandAgent;
@@ -1,6 +0,0 @@
1
- import { useCommandAgent } from "./useCommandAgent";
2
- /**
3
- * @deprecated Use `useCommandAgent` instead. Will be removed in v0.6.0.
4
- * @see useCommandAgent
5
- */
6
- export const useOperationAgent = useCommandAgent;
@@ -1,6 +0,0 @@
1
- import { DuplicatorDefinition, ResourceDuplicator } from "../../query/core/Resource/ResourceDuplicator";
2
- import { SKIP } from "../../query/SKIP_TOKEN";
3
- import { Prettify, ResourceDefinition, ResourceInstance, ResourceQueryState } from "../../query/types";
4
- type Result<D extends ResourceDefinition> = Prettify<ResourceQueryState<D>>;
5
- export declare function useResourceAgent<D extends ResourceDefinition>(res: ResourceInstance<D> | ResourceDuplicator<DuplicatorDefinition<D>>, ...argss: D["Args"] extends void ? [] | [typeof SKIP] : [D["Args"] | typeof SKIP]): Result<D>;
6
- export {};
@@ -1,31 +0,0 @@
1
- import React from "react";
2
- import { useConstant } from "../../common/react";
3
- import { SKIP } from "../../query/SKIP_TOKEN";
4
- import { useSignal } from "../../signals/react";
5
- export function useResourceAgent(res, ...argss) {
6
- const args = (argss[0] === SKIP ? SKIP : argss[0]);
7
- const prevArgsRef = React.useRef(SKIP);
8
- const agent = useConstant(() => {
9
- const agent = res.createAgent();
10
- if (args !== SKIP) {
11
- agent.initiate(args);
12
- }
13
- return agent;
14
- });
15
- if (!compare(args, prevArgsRef.current, agent)) {
16
- prevArgsRef.current = args;
17
- if (args !== SKIP) {
18
- agent.initiate(args);
19
- }
20
- }
21
- return useSignal(agent.state$);
22
- }
23
- function compare(args, prevArgs, agent) {
24
- if (args === SKIP && prevArgs === SKIP) {
25
- return true;
26
- }
27
- if (args === SKIP || prevArgs === SKIP) {
28
- return false;
29
- }
30
- return agent.compareArgs(args, prevArgs);
31
- }
@@ -1,5 +0,0 @@
1
- import { SKIP } from "../../query/SKIP_TOKEN";
2
- import type { Prettify, ResourceDefinition, ResourceInstance, ResourceRefInstance } from "../../query/types";
3
- type Result<D extends ResourceDefinition> = Prettify<ResourceRefInstance<D>>;
4
- export declare function useResourceRef<D extends ResourceDefinition>(res: ResourceInstance<D>, ...argss: D["Args"] extends void ? [] | [typeof SKIP] : [D["Args"] | typeof SKIP]): Result<D>;
5
- export {};
@@ -1,13 +0,0 @@
1
- import React from "react";
2
- import { shallowEqual } from "../../common/utils/shallowEqual";
3
- import { SKIP } from "../../query/SKIP_TOKEN";
4
- export function useResourceRef(res, ...argss) {
5
- const args = (argss[0] === SKIP ? SKIP : argss[0]);
6
- const stableArgsRef = React.useRef(args);
7
- if (!shallowEqual(stableArgsRef.current, args)) {
8
- stableArgsRef.current = args;
9
- }
10
- return React.useMemo(() => {
11
- return res.createRef(stableArgsRef.current);
12
- }, [stableArgsRef.current]);
13
- }