@spoosh/plugin-invalidation 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,115 @@
1
+ # @spoosh/plugin-invalidation
2
+
3
+ Cache invalidation plugin for Spoosh - auto-invalidates related queries after mutations.
4
+
5
+ **[Documentation](https://spoosh.dev/docs/plugins/invalidation)** · **Requirements:** TypeScript >= 5.0 · **Peer Dependencies:** `@spoosh/core`
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @spoosh/plugin-invalidation
11
+ ```
12
+
13
+ ## How It Works
14
+
15
+ Tags are automatically generated from the API path hierarchy:
16
+
17
+ ```typescript
18
+ // Query tags are generated from the path:
19
+ useRead((api) => api.users.$get());
20
+ // → tags: ["users"]
21
+
22
+ useRead((api) => api.users[123].$get());
23
+ // → tags: ["users", "users/123"]
24
+
25
+ useRead((api) => api.users[123].posts.$get());
26
+ // → tags: ["users", "users/123", "users/123/posts"]
27
+ ```
28
+
29
+ When a mutation succeeds, related queries are automatically invalidated:
30
+
31
+ ```typescript
32
+ // Creating a post at users/123/posts invalidates:
33
+ const { trigger } = useWrite((api) => api.users[123].posts.$post);
34
+ await trigger({ body: { title: "New Post" } });
35
+
36
+ // ✓ Invalidates: "users", "users/123", "users/123/posts"
37
+ // All queries matching these tags will refetch automatically
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ ```typescript
43
+ import { invalidationPlugin } from "@spoosh/plugin-invalidation";
44
+
45
+ const plugins = [invalidationPlugin()];
46
+
47
+ // Auto-invalidates all related queries after mutation (default)
48
+ const { trigger } = useWrite((api) => api.posts.$post);
49
+ await trigger({ body: { title: "New Post" } });
50
+ ```
51
+
52
+ ## Default Configuration
53
+
54
+ ```typescript
55
+ // Default: invalidate all related tags (full hierarchy)
56
+ invalidationPlugin(); // same as { autoInvalidate: "all" }
57
+
58
+ // Only invalidate the exact endpoint by default
59
+ invalidationPlugin({ autoInvalidate: "self" });
60
+
61
+ // Disable auto-invalidation by default (manual only)
62
+ invalidationPlugin({ autoInvalidate: "none" });
63
+ ```
64
+
65
+ ## Per-Request Override
66
+
67
+ ```typescript
68
+ // Override to invalidate all related tags
69
+ await trigger({
70
+ body: { title: "New Post" },
71
+ autoInvalidate: "all",
72
+ });
73
+
74
+ // Override to only invalidate the exact endpoint
75
+ await trigger({
76
+ body: { title: "New Post" },
77
+ autoInvalidate: "self",
78
+ });
79
+
80
+ // Disable auto-invalidation and specify custom targets
81
+ await trigger({
82
+ body: { title: "New Post" },
83
+ autoInvalidate: "none",
84
+ invalidate: (api) => [api.posts.$get, api.stats.$get, "dashboard-data"],
85
+ });
86
+
87
+ // Add specific tags (works alongside autoInvalidate)
88
+ await trigger({
89
+ body: { title: "New Post" },
90
+ invalidate: ["posts", "user-posts"],
91
+ });
92
+ ```
93
+
94
+ ## Options
95
+
96
+ ### Plugin Config
97
+
98
+ | Option | Type | Default | Description |
99
+ | ---------------- | --------------------------- | ------- | ---------------------------------- |
100
+ | `autoInvalidate` | `"all" \| "self" \| "none"` | `"all"` | Default auto-invalidation behavior |
101
+
102
+ ### Per-Request Options
103
+
104
+ | Option | Type | Description |
105
+ | ---------------- | ------------------------------ | ---------------------------------------- |
106
+ | `autoInvalidate` | `"all" \| "self" \| "none"` | Override auto-invalidation behavior |
107
+ | `invalidate` | `string[] \| ((api) => [...])` | Specific tags or endpoints to invalidate |
108
+
109
+ ### Auto-Invalidate Modes
110
+
111
+ | Mode | Description | Example |
112
+ | -------- | --------------------------------------- | ----------------------------------------------------------- |
113
+ | `"all"` | Invalidate all tags from path hierarchy | `users/123/posts` → `users`, `users/123`, `users/123/posts` |
114
+ | `"self"` | Only invalidate the exact endpoint tag | `users/123/posts` → `users/123/posts` |
115
+ | `"none"` | Disable auto-invalidation (manual only) | No automatic invalidation |
@@ -0,0 +1,62 @@
1
+ import { QuerySchemaHelper, SpooshResponse, SpooshPlugin } from '@spoosh/core';
2
+
3
+ type AutoInvalidate = "all" | "self" | "none";
4
+ type InvalidateCallbackFn<TSchema> = (api: QuerySchemaHelper<TSchema>) => (((...args: never[]) => Promise<SpooshResponse<unknown, unknown>>) | string)[];
5
+ type InvalidateOption<TSchema> = string[] | InvalidateCallbackFn<TSchema>;
6
+ interface InvalidationPluginConfig {
7
+ /** Default auto-invalidation behavior. Defaults to `"all"`. */
8
+ autoInvalidate?: AutoInvalidate;
9
+ }
10
+ interface InvalidationWriteOptions<TSchema = unknown> {
11
+ /** Auto-invalidation behavior. Overrides plugin default. */
12
+ autoInvalidate?: AutoInvalidate;
13
+ /** Specific tags or endpoints to invalidate after mutation. */
14
+ invalidate?: InvalidateOption<TSchema>;
15
+ }
16
+ type InvalidationReadOptions = object;
17
+ type InvalidationInfiniteReadOptions = object;
18
+ type InvalidationReadResult = object;
19
+ type InvalidationWriteResult = object;
20
+ interface InvalidationPluginExports {
21
+ /** Set the default autoInvalidate behavior for this mutation */
22
+ setAutoInvalidateDefault: (value: AutoInvalidate) => void;
23
+ }
24
+ declare module "@spoosh/core" {
25
+ interface PluginExportsRegistry {
26
+ "spoosh:invalidation": InvalidationPluginExports;
27
+ }
28
+ interface PluginResolvers<TContext> {
29
+ invalidate: InvalidateOption<TContext["schema"]> | undefined;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Enables automatic cache invalidation after mutations.
35
+ *
36
+ * Marks related cache entries as stale and triggers refetches
37
+ * based on tags or explicit invalidation targets.
38
+ *
39
+ * @param config - Plugin configuration
40
+ *
41
+ * @see {@link https://spoosh.dev/docs/plugins/invalidation | Invalidation Plugin Documentation}
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * const plugins = [invalidationPlugin({ autoInvalidate: "all" })];
46
+ *
47
+ * // Per-mutation override
48
+ * trigger({
49
+ * autoInvalidate: "self", // Only invalidate the same endpoint
50
+ * invalidate: ["posts"], // Or explicit tags
51
+ * });
52
+ * ```
53
+ */
54
+ declare function invalidationPlugin(config?: InvalidationPluginConfig): SpooshPlugin<{
55
+ readOptions: InvalidationReadOptions;
56
+ writeOptions: InvalidationWriteOptions;
57
+ infiniteReadOptions: InvalidationInfiniteReadOptions;
58
+ readResult: InvalidationReadResult;
59
+ writeResult: InvalidationWriteResult;
60
+ }>;
61
+
62
+ export { type AutoInvalidate, type InvalidateOption, type InvalidationInfiniteReadOptions, type InvalidationPluginConfig, type InvalidationPluginExports, type InvalidationReadOptions, type InvalidationReadResult, type InvalidationWriteOptions, type InvalidationWriteResult, invalidationPlugin };
@@ -0,0 +1,62 @@
1
+ import { QuerySchemaHelper, SpooshResponse, SpooshPlugin } from '@spoosh/core';
2
+
3
+ type AutoInvalidate = "all" | "self" | "none";
4
+ type InvalidateCallbackFn<TSchema> = (api: QuerySchemaHelper<TSchema>) => (((...args: never[]) => Promise<SpooshResponse<unknown, unknown>>) | string)[];
5
+ type InvalidateOption<TSchema> = string[] | InvalidateCallbackFn<TSchema>;
6
+ interface InvalidationPluginConfig {
7
+ /** Default auto-invalidation behavior. Defaults to `"all"`. */
8
+ autoInvalidate?: AutoInvalidate;
9
+ }
10
+ interface InvalidationWriteOptions<TSchema = unknown> {
11
+ /** Auto-invalidation behavior. Overrides plugin default. */
12
+ autoInvalidate?: AutoInvalidate;
13
+ /** Specific tags or endpoints to invalidate after mutation. */
14
+ invalidate?: InvalidateOption<TSchema>;
15
+ }
16
+ type InvalidationReadOptions = object;
17
+ type InvalidationInfiniteReadOptions = object;
18
+ type InvalidationReadResult = object;
19
+ type InvalidationWriteResult = object;
20
+ interface InvalidationPluginExports {
21
+ /** Set the default autoInvalidate behavior for this mutation */
22
+ setAutoInvalidateDefault: (value: AutoInvalidate) => void;
23
+ }
24
+ declare module "@spoosh/core" {
25
+ interface PluginExportsRegistry {
26
+ "spoosh:invalidation": InvalidationPluginExports;
27
+ }
28
+ interface PluginResolvers<TContext> {
29
+ invalidate: InvalidateOption<TContext["schema"]> | undefined;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Enables automatic cache invalidation after mutations.
35
+ *
36
+ * Marks related cache entries as stale and triggers refetches
37
+ * based on tags or explicit invalidation targets.
38
+ *
39
+ * @param config - Plugin configuration
40
+ *
41
+ * @see {@link https://spoosh.dev/docs/plugins/invalidation | Invalidation Plugin Documentation}
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * const plugins = [invalidationPlugin({ autoInvalidate: "all" })];
46
+ *
47
+ * // Per-mutation override
48
+ * trigger({
49
+ * autoInvalidate: "self", // Only invalidate the same endpoint
50
+ * invalidate: ["posts"], // Or explicit tags
51
+ * });
52
+ * ```
53
+ */
54
+ declare function invalidationPlugin(config?: InvalidationPluginConfig): SpooshPlugin<{
55
+ readOptions: InvalidationReadOptions;
56
+ writeOptions: InvalidationWriteOptions;
57
+ infiniteReadOptions: InvalidationInfiniteReadOptions;
58
+ readResult: InvalidationReadResult;
59
+ writeResult: InvalidationWriteResult;
60
+ }>;
61
+
62
+ export { type AutoInvalidate, type InvalidateOption, type InvalidationInfiniteReadOptions, type InvalidationPluginConfig, type InvalidationPluginExports, type InvalidationReadOptions, type InvalidationReadResult, type InvalidationWriteOptions, type InvalidationWriteResult, invalidationPlugin };
package/dist/index.js ADDED
@@ -0,0 +1,86 @@
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
+ invalidationPlugin: () => invalidationPlugin
24
+ });
25
+ module.exports = __toCommonJS(src_exports);
26
+
27
+ // src/plugin.ts
28
+ var import_core = require("@spoosh/core");
29
+ var INVALIDATION_DEFAULT_KEY = "invalidation:autoInvalidateDefault";
30
+ function resolveInvalidateTags(context, defaultAutoInvalidate) {
31
+ const pluginOptions = context.pluginOptions;
32
+ const tags = [];
33
+ if (pluginOptions?.invalidate) {
34
+ if (Array.isArray(pluginOptions.invalidate)) {
35
+ tags.push(...pluginOptions.invalidate);
36
+ } else {
37
+ const proxy = (0, import_core.createSelectorProxy)();
38
+ const invalidationTargets = pluginOptions.invalidate(proxy);
39
+ for (const target of invalidationTargets) {
40
+ if (typeof target === "string") {
41
+ tags.push(target);
42
+ } else {
43
+ const path = (0, import_core.extractPathFromSelector)(target);
44
+ const derivedTags = (0, import_core.generateTags)(path);
45
+ const exactTag = derivedTags[derivedTags.length - 1];
46
+ if (exactTag) {
47
+ tags.push(exactTag);
48
+ }
49
+ }
50
+ }
51
+ }
52
+ }
53
+ const overrideDefault = context.metadata.get(INVALIDATION_DEFAULT_KEY);
54
+ const effectiveDefault = overrideDefault ?? defaultAutoInvalidate;
55
+ const autoInvalidate = pluginOptions?.autoInvalidate ?? effectiveDefault;
56
+ if (autoInvalidate === "all") {
57
+ tags.push(...context.tags);
58
+ } else if (autoInvalidate === "self") {
59
+ const selfTag = context.path.join("/");
60
+ tags.push(selfTag);
61
+ }
62
+ return [...new Set(tags)];
63
+ }
64
+ function invalidationPlugin(config = {}) {
65
+ const { autoInvalidate: defaultAutoInvalidate = "all" } = config;
66
+ return {
67
+ name: "spoosh:invalidation",
68
+ operations: ["write"],
69
+ exports(context) {
70
+ return {
71
+ setAutoInvalidateDefault(value) {
72
+ context.metadata.set(INVALIDATION_DEFAULT_KEY, value);
73
+ }
74
+ };
75
+ },
76
+ onResponse(context, response) {
77
+ if (!response.error) {
78
+ const tags = resolveInvalidateTags(context, defaultAutoInvalidate);
79
+ if (tags.length > 0) {
80
+ context.stateManager.markStale(tags);
81
+ context.eventEmitter.emit("invalidate", tags);
82
+ }
83
+ }
84
+ }
85
+ };
86
+ }
package/dist/index.mjs ADDED
@@ -0,0 +1,67 @@
1
+ // src/plugin.ts
2
+ import {
3
+ createSelectorProxy,
4
+ extractPathFromSelector,
5
+ generateTags
6
+ } from "@spoosh/core";
7
+ var INVALIDATION_DEFAULT_KEY = "invalidation:autoInvalidateDefault";
8
+ function resolveInvalidateTags(context, defaultAutoInvalidate) {
9
+ const pluginOptions = context.pluginOptions;
10
+ const tags = [];
11
+ if (pluginOptions?.invalidate) {
12
+ if (Array.isArray(pluginOptions.invalidate)) {
13
+ tags.push(...pluginOptions.invalidate);
14
+ } else {
15
+ const proxy = createSelectorProxy();
16
+ const invalidationTargets = pluginOptions.invalidate(proxy);
17
+ for (const target of invalidationTargets) {
18
+ if (typeof target === "string") {
19
+ tags.push(target);
20
+ } else {
21
+ const path = extractPathFromSelector(target);
22
+ const derivedTags = generateTags(path);
23
+ const exactTag = derivedTags[derivedTags.length - 1];
24
+ if (exactTag) {
25
+ tags.push(exactTag);
26
+ }
27
+ }
28
+ }
29
+ }
30
+ }
31
+ const overrideDefault = context.metadata.get(INVALIDATION_DEFAULT_KEY);
32
+ const effectiveDefault = overrideDefault ?? defaultAutoInvalidate;
33
+ const autoInvalidate = pluginOptions?.autoInvalidate ?? effectiveDefault;
34
+ if (autoInvalidate === "all") {
35
+ tags.push(...context.tags);
36
+ } else if (autoInvalidate === "self") {
37
+ const selfTag = context.path.join("/");
38
+ tags.push(selfTag);
39
+ }
40
+ return [...new Set(tags)];
41
+ }
42
+ function invalidationPlugin(config = {}) {
43
+ const { autoInvalidate: defaultAutoInvalidate = "all" } = config;
44
+ return {
45
+ name: "spoosh:invalidation",
46
+ operations: ["write"],
47
+ exports(context) {
48
+ return {
49
+ setAutoInvalidateDefault(value) {
50
+ context.metadata.set(INVALIDATION_DEFAULT_KEY, value);
51
+ }
52
+ };
53
+ },
54
+ onResponse(context, response) {
55
+ if (!response.error) {
56
+ const tags = resolveInvalidateTags(context, defaultAutoInvalidate);
57
+ if (tags.length > 0) {
58
+ context.stateManager.markStale(tags);
59
+ context.eventEmitter.emit("invalidate", tags);
60
+ }
61
+ }
62
+ }
63
+ };
64
+ }
65
+ export {
66
+ invalidationPlugin
67
+ };
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@spoosh/plugin-invalidation",
3
+ "version": "0.1.0-beta.0",
4
+ "description": "Cache invalidation plugin for Spoosh - auto-invalidates after mutations",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/nxnom/spoosh.git",
9
+ "directory": "packages/plugin-invalidation"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/nxnom/spoosh/issues"
13
+ },
14
+ "homepage": "https://spoosh.dev/docs/plugins/invalidation",
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "keywords": [
19
+ "spoosh",
20
+ "plugin",
21
+ "invalidation",
22
+ "cache",
23
+ "api-client"
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
+ },
38
+ "devDependencies": {
39
+ "@spoosh/core": "0.1.0-beta.0",
40
+ "@spoosh/test-utils": "0.1.0-beta.0"
41
+ },
42
+ "scripts": {
43
+ "dev": "tsup --watch",
44
+ "build": "tsup",
45
+ "typecheck": "tsc --noEmit",
46
+ "lint": "eslint src --max-warnings 0",
47
+ "format": "prettier --write 'src/**/*.ts'"
48
+ }
49
+ }