@spoosh/plugin-optimistic 0.1.0-beta.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Spoosh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,103 @@
1
+ # @spoosh/plugin-optimistic
2
+
3
+ Optimistic updates plugin for Spoosh - instant UI updates with automatic rollback on error.
4
+
5
+ **[Documentation](https://spoosh.dev/docs/plugins/optimistic)** · **Requirements:** TypeScript >= 5.0 · **Peer Dependencies:** `@spoosh/core`, `@spoosh/plugin-invalidation`
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @spoosh/plugin-optimistic @spoosh/plugin-invalidation
11
+ ```
12
+
13
+ Note: This plugin requires `@spoosh/plugin-invalidation` as a peer dependency.
14
+
15
+ > By default, if optimistic updates are used, `autoInvalidate` from `@spoosh/plugin-invalidation` is set to `"none"` to prevent immediate cache invalidation for this request.
16
+ > If you want to keep auto-invalidation, set `autoInvalidate` to `"all"` or `"self"` or target with `invalidate` manually.
17
+
18
+ ## Usage
19
+
20
+ ```typescript
21
+ import { optimisticPlugin } from "@spoosh/plugin-optimistic";
22
+ import { invalidationPlugin } from "@spoosh/plugin-invalidation";
23
+
24
+ const plugins = [invalidationPlugin(), optimisticPlugin()];
25
+
26
+ const { trigger } = useWrite((api) => api.posts[id].$delete);
27
+
28
+ trigger({
29
+ // Optimistic delete - instantly remove item from list
30
+ optimistic: ($, api) =>
31
+ $({
32
+ for: api.posts.$get,
33
+ updater: (posts) => posts.filter((p) => p.id !== id),
34
+ rollbackOnError: true,
35
+ }),
36
+ });
37
+
38
+ // Optimistic update with response data
39
+ trigger({
40
+ optimistic: ($, api) =>
41
+ $({
42
+ for: api.posts.$get,
43
+ timing: "onSuccess",
44
+ updater: (posts, newPost) => [newPost!, ...posts],
45
+ }),
46
+ });
47
+
48
+ // Multiple targets
49
+ trigger({
50
+ optimistic: ($, api) => [
51
+ $({
52
+ for: api.posts.$get,
53
+ updater: (posts) => posts.filter((p) => p.id !== id),
54
+ }),
55
+ $({
56
+ for: api.stats.$get,
57
+ updater: (stats) => ({ ...stats, count: stats.count - 1 }),
58
+ }),
59
+ ],
60
+ });
61
+
62
+ // Filter by request params
63
+ trigger({
64
+ optimistic: ($, api) =>
65
+ $({
66
+ for: api.posts.$get,
67
+ match: (request) => request.query?.page === 1,
68
+ updater: (posts, newPost) => [newPost!, ...posts],
69
+ }),
70
+ });
71
+ ```
72
+
73
+ ## Options
74
+
75
+ ### Per-Request Options
76
+
77
+ | Option | Type | Description |
78
+ | ------------ | -------------------------------- | ------------------------------------- |
79
+ | `optimistic` | `($, api) => config \| config[]` | Callback to define optimistic updates |
80
+
81
+ ### Config Object
82
+
83
+ | Property | Type | Default | Description |
84
+ | ----------------- | ---------------------------- | ------------- | ------------------------------------ |
85
+ | `for` | `api.endpoint.$get` | required | The endpoint to update |
86
+ | `updater` | `(data, response?) => data` | required | Function to update cached data |
87
+ | `match` | `(request) => boolean` | - | Filter which cache entries to update |
88
+ | `timing` | `"immediate" \| "onSuccess"` | `"immediate"` | When to apply the update (see below) |
89
+ | `rollbackOnError` | `boolean` | `true` | Whether to rollback on error |
90
+ | `onError` | `(error) => void` | - | Error callback |
91
+
92
+ ### Result
93
+
94
+ | Property | Type | Description |
95
+ | -------------- | --------- | --------------------------------------------------- |
96
+ | `isOptimistic` | `boolean` | `true` if current data is from an optimistic update |
97
+
98
+ ### Timing Modes
99
+
100
+ | Mode | Description |
101
+ | ------------- | --------------------------------------------------------------------------- |
102
+ | `"immediate"` | Update cache instantly before request completes. Rollback on error. |
103
+ | `"onSuccess"` | Wait for successful response, then update cache with response data applied. |
@@ -0,0 +1,113 @@
1
+ import { SpooshResponse, QuerySchemaHelper, SpooshPlugin } from '@spoosh/core';
2
+
3
+ type ExtractResponseData<T> = T extends SpooshResponse<infer D, unknown, unknown> ? D : unknown;
4
+ type ExtractRequestOptions<T> = T extends SpooshResponse<unknown, unknown, infer R> ? R : never;
5
+ type CleanRequestOptions<T> = unknown extends T ? never : keyof T extends never ? never : T;
6
+ type CacheConfig<TFor extends () => Promise<SpooshResponse<unknown, unknown, unknown>>, TResponse = unknown, TData = ExtractResponseData<Awaited<ReturnType<TFor>>>, TRequest = CleanRequestOptions<ExtractRequestOptions<Awaited<ReturnType<TFor>>>>> = {
7
+ for: TFor;
8
+ match?: [TRequest] extends [never] ? never : (request: TRequest) => boolean;
9
+ timing?: "immediate" | "onSuccess";
10
+ updater: (data: TData, response?: TResponse) => TData;
11
+ rollbackOnError?: boolean;
12
+ onError?: (error: unknown) => void;
13
+ };
14
+ type ResolvedCacheConfig = {
15
+ for: (...args: any[]) => Promise<SpooshResponse<unknown, unknown>>;
16
+ match?: (request: Record<string, unknown>) => boolean;
17
+ timing?: "immediate" | "onSuccess";
18
+ updater: (data: unknown, response?: unknown) => unknown;
19
+ rollbackOnError?: boolean;
20
+ onError?: (error: unknown) => void;
21
+ };
22
+ type OptimisticCallbackFn<TSchema = unknown, TResponse = unknown> = ($: <TFor extends () => Promise<SpooshResponse<unknown, unknown, unknown>>>(config: CacheConfig<TFor, TResponse>) => ResolvedCacheConfig, api: QuerySchemaHelper<TSchema>) => ResolvedCacheConfig | ResolvedCacheConfig[];
23
+ type OptimisticPluginConfig = object;
24
+ interface OptimisticWriteOptions<TSchema = unknown> {
25
+ optimistic?: OptimisticCallbackFn<TSchema>;
26
+ }
27
+ type OptimisticReadOptions = object;
28
+ type OptimisticInfiniteReadOptions = object;
29
+ interface OptimisticReadResult {
30
+ isOptimistic: boolean;
31
+ }
32
+ type OptimisticWriteResult = object;
33
+ declare module "@spoosh/core" {
34
+ interface PluginResolvers<TContext> {
35
+ optimistic: OptimisticCallbackFn<TContext["schema"]> | undefined;
36
+ }
37
+ }
38
+
39
+ declare const OPTIMISTIC_SNAPSHOTS_KEY = "optimistic:snapshots";
40
+ /**
41
+ * Enables optimistic updates for mutations.
42
+ *
43
+ * Immediately updates cached data before the mutation completes,
44
+ * with automatic rollback on error.
45
+ *
46
+ * When using optimistic updates, `autoInvalidate` defaults to `"none"` to prevent
47
+ * unnecessary refetches that would override the optimistic data. You can override
48
+ * this by explicitly setting `autoInvalidate` or using the `invalidate` option.
49
+ *
50
+ * @see {@link https://spoosh.dev/docs/plugins/optimistic | Optimistic Plugin Documentation}
51
+ *
52
+ * @returns Optimistic plugin instance
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * const plugins = [optimisticPlugin()];
57
+ *
58
+ * // In useWrite - autoInvalidate defaults to "none" when optimistic is used
59
+ * trigger({
60
+ * optimistic: ($, api) => $({
61
+ * for: api.posts.$get,
62
+ * updater: (posts) => posts.filter(p => p.id !== deletedId),
63
+ * rollbackOnError: true,
64
+ * }),
65
+ * });
66
+ * ```
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * // Multiple targets
71
+ * trigger({
72
+ * optimistic: ($, api) => [
73
+ * $({ for: api.posts.$get, updater: (posts) => posts.filter(p => p.id !== deletedId) }),
74
+ * $({ for: api.stats.$get, updater: (stats) => ({ ...stats, count: stats.count - 1 }) }),
75
+ * ],
76
+ * });
77
+ * ```
78
+ *
79
+ * @example
80
+ * ```ts
81
+ * // Optimistic update with explicit invalidation
82
+ * trigger({
83
+ * optimistic: ($, api) => $({
84
+ * for: api.posts.$get,
85
+ * updater: (posts) => posts.filter(p => p.id !== deletedId),
86
+ * }),
87
+ * // By default autoInvalidate is "none" when using optimistic updates
88
+ * autoInvalidate: "all", // You can override to enable refetching after mutation
89
+ * });
90
+ * ```
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * // Filtering by request
95
+ * trigger({
96
+ * optimistic: ($, api) => $({
97
+ * for: api.items.$get,
98
+ * timing: "onSuccess",
99
+ * match: (request) => request.query?.page === 1,
100
+ * updater: (items, newItem) => [newItem!, ...items],
101
+ * }),
102
+ * });
103
+ * ```
104
+ */
105
+ declare function optimisticPlugin(): SpooshPlugin<{
106
+ readOptions: OptimisticReadOptions;
107
+ writeOptions: OptimisticWriteOptions;
108
+ infiniteReadOptions: OptimisticInfiniteReadOptions;
109
+ readResult: OptimisticReadResult;
110
+ writeResult: OptimisticWriteResult;
111
+ }>;
112
+
113
+ export { type CacheConfig, OPTIMISTIC_SNAPSHOTS_KEY, type OptimisticCallbackFn, type OptimisticInfiniteReadOptions, type OptimisticPluginConfig, type OptimisticReadOptions, type OptimisticReadResult, type OptimisticWriteOptions, type OptimisticWriteResult, type ResolvedCacheConfig, optimisticPlugin };
@@ -0,0 +1,113 @@
1
+ import { SpooshResponse, QuerySchemaHelper, SpooshPlugin } from '@spoosh/core';
2
+
3
+ type ExtractResponseData<T> = T extends SpooshResponse<infer D, unknown, unknown> ? D : unknown;
4
+ type ExtractRequestOptions<T> = T extends SpooshResponse<unknown, unknown, infer R> ? R : never;
5
+ type CleanRequestOptions<T> = unknown extends T ? never : keyof T extends never ? never : T;
6
+ type CacheConfig<TFor extends () => Promise<SpooshResponse<unknown, unknown, unknown>>, TResponse = unknown, TData = ExtractResponseData<Awaited<ReturnType<TFor>>>, TRequest = CleanRequestOptions<ExtractRequestOptions<Awaited<ReturnType<TFor>>>>> = {
7
+ for: TFor;
8
+ match?: [TRequest] extends [never] ? never : (request: TRequest) => boolean;
9
+ timing?: "immediate" | "onSuccess";
10
+ updater: (data: TData, response?: TResponse) => TData;
11
+ rollbackOnError?: boolean;
12
+ onError?: (error: unknown) => void;
13
+ };
14
+ type ResolvedCacheConfig = {
15
+ for: (...args: any[]) => Promise<SpooshResponse<unknown, unknown>>;
16
+ match?: (request: Record<string, unknown>) => boolean;
17
+ timing?: "immediate" | "onSuccess";
18
+ updater: (data: unknown, response?: unknown) => unknown;
19
+ rollbackOnError?: boolean;
20
+ onError?: (error: unknown) => void;
21
+ };
22
+ type OptimisticCallbackFn<TSchema = unknown, TResponse = unknown> = ($: <TFor extends () => Promise<SpooshResponse<unknown, unknown, unknown>>>(config: CacheConfig<TFor, TResponse>) => ResolvedCacheConfig, api: QuerySchemaHelper<TSchema>) => ResolvedCacheConfig | ResolvedCacheConfig[];
23
+ type OptimisticPluginConfig = object;
24
+ interface OptimisticWriteOptions<TSchema = unknown> {
25
+ optimistic?: OptimisticCallbackFn<TSchema>;
26
+ }
27
+ type OptimisticReadOptions = object;
28
+ type OptimisticInfiniteReadOptions = object;
29
+ interface OptimisticReadResult {
30
+ isOptimistic: boolean;
31
+ }
32
+ type OptimisticWriteResult = object;
33
+ declare module "@spoosh/core" {
34
+ interface PluginResolvers<TContext> {
35
+ optimistic: OptimisticCallbackFn<TContext["schema"]> | undefined;
36
+ }
37
+ }
38
+
39
+ declare const OPTIMISTIC_SNAPSHOTS_KEY = "optimistic:snapshots";
40
+ /**
41
+ * Enables optimistic updates for mutations.
42
+ *
43
+ * Immediately updates cached data before the mutation completes,
44
+ * with automatic rollback on error.
45
+ *
46
+ * When using optimistic updates, `autoInvalidate` defaults to `"none"` to prevent
47
+ * unnecessary refetches that would override the optimistic data. You can override
48
+ * this by explicitly setting `autoInvalidate` or using the `invalidate` option.
49
+ *
50
+ * @see {@link https://spoosh.dev/docs/plugins/optimistic | Optimistic Plugin Documentation}
51
+ *
52
+ * @returns Optimistic plugin instance
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * const plugins = [optimisticPlugin()];
57
+ *
58
+ * // In useWrite - autoInvalidate defaults to "none" when optimistic is used
59
+ * trigger({
60
+ * optimistic: ($, api) => $({
61
+ * for: api.posts.$get,
62
+ * updater: (posts) => posts.filter(p => p.id !== deletedId),
63
+ * rollbackOnError: true,
64
+ * }),
65
+ * });
66
+ * ```
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * // Multiple targets
71
+ * trigger({
72
+ * optimistic: ($, api) => [
73
+ * $({ for: api.posts.$get, updater: (posts) => posts.filter(p => p.id !== deletedId) }),
74
+ * $({ for: api.stats.$get, updater: (stats) => ({ ...stats, count: stats.count - 1 }) }),
75
+ * ],
76
+ * });
77
+ * ```
78
+ *
79
+ * @example
80
+ * ```ts
81
+ * // Optimistic update with explicit invalidation
82
+ * trigger({
83
+ * optimistic: ($, api) => $({
84
+ * for: api.posts.$get,
85
+ * updater: (posts) => posts.filter(p => p.id !== deletedId),
86
+ * }),
87
+ * // By default autoInvalidate is "none" when using optimistic updates
88
+ * autoInvalidate: "all", // You can override to enable refetching after mutation
89
+ * });
90
+ * ```
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * // Filtering by request
95
+ * trigger({
96
+ * optimistic: ($, api) => $({
97
+ * for: api.items.$get,
98
+ * timing: "onSuccess",
99
+ * match: (request) => request.query?.page === 1,
100
+ * updater: (items, newItem) => [newItem!, ...items],
101
+ * }),
102
+ * });
103
+ * ```
104
+ */
105
+ declare function optimisticPlugin(): SpooshPlugin<{
106
+ readOptions: OptimisticReadOptions;
107
+ writeOptions: OptimisticWriteOptions;
108
+ infiniteReadOptions: OptimisticInfiniteReadOptions;
109
+ readResult: OptimisticReadResult;
110
+ writeResult: OptimisticWriteResult;
111
+ }>;
112
+
113
+ export { type CacheConfig, OPTIMISTIC_SNAPSHOTS_KEY, type OptimisticCallbackFn, type OptimisticInfiniteReadOptions, type OptimisticPluginConfig, type OptimisticReadOptions, type OptimisticReadResult, type OptimisticWriteOptions, type OptimisticWriteResult, type ResolvedCacheConfig, optimisticPlugin };
package/dist/index.js ADDED
@@ -0,0 +1,200 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ OPTIMISTIC_SNAPSHOTS_KEY: () => OPTIMISTIC_SNAPSHOTS_KEY,
24
+ optimisticPlugin: () => optimisticPlugin
25
+ });
26
+ module.exports = __toCommonJS(src_exports);
27
+
28
+ // src/plugin.ts
29
+ var import_core = require("@spoosh/core");
30
+ var import_plugin_invalidation = require("@spoosh/plugin-invalidation");
31
+ var OPTIMISTIC_SNAPSHOTS_KEY = "optimistic:snapshots";
32
+ function extractTagsFromFor(forFn) {
33
+ return (0, import_core.generateTags)((0, import_core.extractPathFromSelector)(forFn));
34
+ }
35
+ function getExactMatchPath(tags) {
36
+ return tags.length > 0 ? tags[tags.length - 1] : void 0;
37
+ }
38
+ function findInObject(obj, key) {
39
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
40
+ return void 0;
41
+ }
42
+ const record = obj;
43
+ if (key in record) {
44
+ return record[key];
45
+ }
46
+ for (const value of Object.values(record)) {
47
+ const found = findInObject(value, key);
48
+ if (found !== void 0) return found;
49
+ }
50
+ return void 0;
51
+ }
52
+ function parseRequestFromKey(key) {
53
+ try {
54
+ const parsed = JSON.parse(key);
55
+ return {
56
+ query: findInObject(parsed, "query"),
57
+ params: findInObject(parsed, "params"),
58
+ body: findInObject(parsed, "body")
59
+ };
60
+ } catch {
61
+ return void 0;
62
+ }
63
+ }
64
+ function resolveOptimisticConfigs(context) {
65
+ const pluginOptions = context.pluginOptions;
66
+ if (!pluginOptions?.optimistic) return [];
67
+ const $ = (config) => ({
68
+ for: config.for,
69
+ match: config.match,
70
+ timing: config.timing,
71
+ updater: config.updater,
72
+ rollbackOnError: config.rollbackOnError,
73
+ onError: config.onError
74
+ });
75
+ const apiProxy = (0, import_core.createSelectorProxy)();
76
+ const optimisticConfigs = pluginOptions.optimistic(
77
+ $,
78
+ apiProxy
79
+ );
80
+ return Array.isArray(optimisticConfigs) ? optimisticConfigs : [optimisticConfigs];
81
+ }
82
+ function applyOptimisticUpdate(stateManager, config) {
83
+ const tags = extractTagsFromFor(config.for);
84
+ const targetSelfTag = getExactMatchPath(tags);
85
+ if (!targetSelfTag) return [];
86
+ const snapshots = [];
87
+ const entries = stateManager.getCacheEntriesBySelfTag(targetSelfTag);
88
+ for (const { key, entry } of entries) {
89
+ if (key.includes('"type":"infinite-tracker"')) continue;
90
+ if (!key.includes('"method":"$get"')) continue;
91
+ if (config.match) {
92
+ const request = parseRequestFromKey(key);
93
+ if (!request || !config.match(request)) continue;
94
+ }
95
+ if (entry.state.data === void 0) continue;
96
+ snapshots.push({ key, previousData: entry.state.data });
97
+ stateManager.setCache(key, {
98
+ previousData: entry.state.data,
99
+ state: {
100
+ ...entry.state,
101
+ data: config.updater(entry.state.data, void 0)
102
+ }
103
+ });
104
+ stateManager.setPluginResult(key, { isOptimistic: true });
105
+ }
106
+ return snapshots;
107
+ }
108
+ function confirmOptimistic(stateManager, snapshots) {
109
+ for (const { key } of snapshots) {
110
+ const entry = stateManager.getCache(key);
111
+ if (entry) {
112
+ stateManager.setCache(key, {
113
+ previousData: void 0
114
+ });
115
+ stateManager.setPluginResult(key, { isOptimistic: false });
116
+ }
117
+ }
118
+ }
119
+ function rollbackOptimistic(stateManager, snapshots) {
120
+ for (const { key, previousData } of snapshots) {
121
+ const entry = stateManager.getCache(key);
122
+ if (entry) {
123
+ stateManager.setCache(key, {
124
+ previousData: void 0,
125
+ state: {
126
+ ...entry.state,
127
+ data: previousData
128
+ }
129
+ });
130
+ stateManager.setPluginResult(key, { isOptimistic: false });
131
+ }
132
+ }
133
+ }
134
+ function optimisticPlugin() {
135
+ return {
136
+ name: "spoosh:optimistic",
137
+ operations: ["write"],
138
+ dependencies: ["spoosh:invalidation"],
139
+ middleware: async (context, next) => {
140
+ const { stateManager } = context;
141
+ const configs = resolveOptimisticConfigs(context);
142
+ if (configs.length > 0) {
143
+ context.plugins.get("spoosh:invalidation")?.setAutoInvalidateDefault("none");
144
+ }
145
+ const immediateConfigs = configs.filter((c) => c.timing !== "onSuccess");
146
+ const allSnapshots = [];
147
+ for (const config of immediateConfigs) {
148
+ const snapshots2 = applyOptimisticUpdate(stateManager, config);
149
+ allSnapshots.push(...snapshots2);
150
+ }
151
+ if (allSnapshots.length > 0) {
152
+ context.metadata.set(OPTIMISTIC_SNAPSHOTS_KEY, allSnapshots);
153
+ }
154
+ const response = await next();
155
+ const snapshots = context.metadata.get(
156
+ OPTIMISTIC_SNAPSHOTS_KEY
157
+ ) ?? [];
158
+ if (response.error) {
159
+ const shouldRollback = configs.some(
160
+ (c) => c.rollbackOnError !== false && c.timing !== "onSuccess"
161
+ );
162
+ if (shouldRollback && snapshots.length > 0) {
163
+ rollbackOptimistic(stateManager, snapshots);
164
+ }
165
+ for (const config of configs) {
166
+ if (config.onError) {
167
+ config.onError(response.error);
168
+ }
169
+ }
170
+ } else {
171
+ if (snapshots.length > 0) {
172
+ confirmOptimistic(stateManager, snapshots);
173
+ }
174
+ const onSuccessConfigs = configs.filter(
175
+ (c) => c.timing === "onSuccess"
176
+ );
177
+ for (const config of onSuccessConfigs) {
178
+ const tags = extractTagsFromFor(config.for);
179
+ const targetSelfTag = getExactMatchPath(tags);
180
+ if (!targetSelfTag) continue;
181
+ const entries = stateManager.getCacheEntriesBySelfTag(targetSelfTag);
182
+ for (const { key, entry } of entries) {
183
+ if (!key.includes('"method":"$get"')) continue;
184
+ if (config.match) {
185
+ const request = parseRequestFromKey(key);
186
+ if (!request || !config.match(request)) continue;
187
+ }
188
+ stateManager.setCache(key, {
189
+ state: {
190
+ ...entry.state,
191
+ data: config.updater(entry.state.data, response.data)
192
+ }
193
+ });
194
+ }
195
+ }
196
+ }
197
+ return response;
198
+ }
199
+ };
200
+ }
package/dist/index.mjs ADDED
@@ -0,0 +1,181 @@
1
+ // src/plugin.ts
2
+ import {
3
+ createSelectorProxy,
4
+ extractPathFromSelector,
5
+ generateTags
6
+ } from "@spoosh/core";
7
+ import "@spoosh/plugin-invalidation";
8
+ var OPTIMISTIC_SNAPSHOTS_KEY = "optimistic:snapshots";
9
+ function extractTagsFromFor(forFn) {
10
+ return generateTags(extractPathFromSelector(forFn));
11
+ }
12
+ function getExactMatchPath(tags) {
13
+ return tags.length > 0 ? tags[tags.length - 1] : void 0;
14
+ }
15
+ function findInObject(obj, key) {
16
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
17
+ return void 0;
18
+ }
19
+ const record = obj;
20
+ if (key in record) {
21
+ return record[key];
22
+ }
23
+ for (const value of Object.values(record)) {
24
+ const found = findInObject(value, key);
25
+ if (found !== void 0) return found;
26
+ }
27
+ return void 0;
28
+ }
29
+ function parseRequestFromKey(key) {
30
+ try {
31
+ const parsed = JSON.parse(key);
32
+ return {
33
+ query: findInObject(parsed, "query"),
34
+ params: findInObject(parsed, "params"),
35
+ body: findInObject(parsed, "body")
36
+ };
37
+ } catch {
38
+ return void 0;
39
+ }
40
+ }
41
+ function resolveOptimisticConfigs(context) {
42
+ const pluginOptions = context.pluginOptions;
43
+ if (!pluginOptions?.optimistic) return [];
44
+ const $ = (config) => ({
45
+ for: config.for,
46
+ match: config.match,
47
+ timing: config.timing,
48
+ updater: config.updater,
49
+ rollbackOnError: config.rollbackOnError,
50
+ onError: config.onError
51
+ });
52
+ const apiProxy = createSelectorProxy();
53
+ const optimisticConfigs = pluginOptions.optimistic(
54
+ $,
55
+ apiProxy
56
+ );
57
+ return Array.isArray(optimisticConfigs) ? optimisticConfigs : [optimisticConfigs];
58
+ }
59
+ function applyOptimisticUpdate(stateManager, config) {
60
+ const tags = extractTagsFromFor(config.for);
61
+ const targetSelfTag = getExactMatchPath(tags);
62
+ if (!targetSelfTag) return [];
63
+ const snapshots = [];
64
+ const entries = stateManager.getCacheEntriesBySelfTag(targetSelfTag);
65
+ for (const { key, entry } of entries) {
66
+ if (key.includes('"type":"infinite-tracker"')) continue;
67
+ if (!key.includes('"method":"$get"')) continue;
68
+ if (config.match) {
69
+ const request = parseRequestFromKey(key);
70
+ if (!request || !config.match(request)) continue;
71
+ }
72
+ if (entry.state.data === void 0) continue;
73
+ snapshots.push({ key, previousData: entry.state.data });
74
+ stateManager.setCache(key, {
75
+ previousData: entry.state.data,
76
+ state: {
77
+ ...entry.state,
78
+ data: config.updater(entry.state.data, void 0)
79
+ }
80
+ });
81
+ stateManager.setPluginResult(key, { isOptimistic: true });
82
+ }
83
+ return snapshots;
84
+ }
85
+ function confirmOptimistic(stateManager, snapshots) {
86
+ for (const { key } of snapshots) {
87
+ const entry = stateManager.getCache(key);
88
+ if (entry) {
89
+ stateManager.setCache(key, {
90
+ previousData: void 0
91
+ });
92
+ stateManager.setPluginResult(key, { isOptimistic: false });
93
+ }
94
+ }
95
+ }
96
+ function rollbackOptimistic(stateManager, snapshots) {
97
+ for (const { key, previousData } of snapshots) {
98
+ const entry = stateManager.getCache(key);
99
+ if (entry) {
100
+ stateManager.setCache(key, {
101
+ previousData: void 0,
102
+ state: {
103
+ ...entry.state,
104
+ data: previousData
105
+ }
106
+ });
107
+ stateManager.setPluginResult(key, { isOptimistic: false });
108
+ }
109
+ }
110
+ }
111
+ function optimisticPlugin() {
112
+ return {
113
+ name: "spoosh:optimistic",
114
+ operations: ["write"],
115
+ dependencies: ["spoosh:invalidation"],
116
+ middleware: async (context, next) => {
117
+ const { stateManager } = context;
118
+ const configs = resolveOptimisticConfigs(context);
119
+ if (configs.length > 0) {
120
+ context.plugins.get("spoosh:invalidation")?.setAutoInvalidateDefault("none");
121
+ }
122
+ const immediateConfigs = configs.filter((c) => c.timing !== "onSuccess");
123
+ const allSnapshots = [];
124
+ for (const config of immediateConfigs) {
125
+ const snapshots2 = applyOptimisticUpdate(stateManager, config);
126
+ allSnapshots.push(...snapshots2);
127
+ }
128
+ if (allSnapshots.length > 0) {
129
+ context.metadata.set(OPTIMISTIC_SNAPSHOTS_KEY, allSnapshots);
130
+ }
131
+ const response = await next();
132
+ const snapshots = context.metadata.get(
133
+ OPTIMISTIC_SNAPSHOTS_KEY
134
+ ) ?? [];
135
+ if (response.error) {
136
+ const shouldRollback = configs.some(
137
+ (c) => c.rollbackOnError !== false && c.timing !== "onSuccess"
138
+ );
139
+ if (shouldRollback && snapshots.length > 0) {
140
+ rollbackOptimistic(stateManager, snapshots);
141
+ }
142
+ for (const config of configs) {
143
+ if (config.onError) {
144
+ config.onError(response.error);
145
+ }
146
+ }
147
+ } else {
148
+ if (snapshots.length > 0) {
149
+ confirmOptimistic(stateManager, snapshots);
150
+ }
151
+ const onSuccessConfigs = configs.filter(
152
+ (c) => c.timing === "onSuccess"
153
+ );
154
+ for (const config of onSuccessConfigs) {
155
+ const tags = extractTagsFromFor(config.for);
156
+ const targetSelfTag = getExactMatchPath(tags);
157
+ if (!targetSelfTag) continue;
158
+ const entries = stateManager.getCacheEntriesBySelfTag(targetSelfTag);
159
+ for (const { key, entry } of entries) {
160
+ if (!key.includes('"method":"$get"')) continue;
161
+ if (config.match) {
162
+ const request = parseRequestFromKey(key);
163
+ if (!request || !config.match(request)) continue;
164
+ }
165
+ stateManager.setCache(key, {
166
+ state: {
167
+ ...entry.state,
168
+ data: config.updater(entry.state.data, response.data)
169
+ }
170
+ });
171
+ }
172
+ }
173
+ }
174
+ return response;
175
+ }
176
+ };
177
+ }
178
+ export {
179
+ OPTIMISTIC_SNAPSHOTS_KEY,
180
+ optimisticPlugin
181
+ };
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@spoosh/plugin-optimistic",
3
+ "version": "0.1.0-beta.0",
4
+ "description": "Optimistic updates plugin for Spoosh - instant UI updates with automatic rollback",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/nxnom/spoosh.git",
9
+ "directory": "packages/plugin-optimistic"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/nxnom/spoosh/issues"
13
+ },
14
+ "homepage": "https://spoosh.dev/docs/plugins/optimistic",
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "keywords": [
19
+ "spoosh",
20
+ "plugin",
21
+ "optimistic",
22
+ "api-client",
23
+ "mutations"
24
+ ],
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.mjs",
32
+ "require": "./dist/index.js"
33
+ }
34
+ },
35
+ "peerDependencies": {
36
+ "@spoosh/core": ">=0.1.0",
37
+ "@spoosh/plugin-invalidation": ">=0.1.0"
38
+ },
39
+ "devDependencies": {
40
+ "@spoosh/core": "0.1.0-beta.0",
41
+ "@spoosh/plugin-invalidation": "0.1.0-beta.0",
42
+ "@spoosh/test-utils": "0.1.0-beta.0"
43
+ },
44
+ "scripts": {
45
+ "dev": "tsup --watch",
46
+ "build": "tsup",
47
+ "typecheck": "tsc --noEmit",
48
+ "lint": "eslint src --max-warnings 0",
49
+ "format": "prettier --write 'src/**/*.ts'"
50
+ }
51
+ }