@spoosh/plugin-debounce 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,50 @@
1
+ # @spoosh/plugin-debounce
2
+
3
+ Request debouncing plugin for Spoosh - waits for inactivity before fetching.
4
+
5
+ **[Documentation](https://spoosh.dev/docs/plugins/debounce)** · **Requirements:** TypeScript >= 5.0 · **Peer Dependencies:** `@spoosh/core`
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @spoosh/plugin-debounce
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```typescript
16
+ import { debouncePlugin } from "@spoosh/plugin-debounce";
17
+
18
+ const plugins = [debouncePlugin()];
19
+
20
+ // Wait 300ms after typing stops before fetching
21
+ const { data } = useRead(
22
+ (api) => api.search.$get({ query: { q: searchTerm } }),
23
+ { debounce: 300 }
24
+ );
25
+
26
+ // Conditional debounce - only debounce when search query changes
27
+ const { data } = useRead(
28
+ (api) => api.search.$get({ query: { q: searchTerm, page } }),
29
+ { debounce: ({ prevQuery }) => (prevQuery?.q !== searchTerm ? 300 : 0) }
30
+ );
31
+ ```
32
+
33
+ ## Options
34
+
35
+ ### Per-Request Options
36
+
37
+ | Option | Type | Description |
38
+ | ---------- | ------------------------------- | -------------------------------------------------------------------- |
39
+ | `debounce` | `number \| (context) => number` | Milliseconds to wait, or function receiving previous request context |
40
+
41
+ ### Debounce Function Context
42
+
43
+ When using a function, you receive:
44
+
45
+ | Property | Type | Description |
46
+ | -------------- | --------- | ------------------------- |
47
+ | `prevQuery` | `object` | Previous query parameters |
48
+ | `prevBody` | `unknown` | Previous request body |
49
+ | `prevParams` | `object` | Previous path parameters |
50
+ | `prevFormData` | `object` | Previous form data |
@@ -0,0 +1,67 @@
1
+ import { SpooshPlugin } from '@spoosh/core';
2
+
3
+ type PrevQueryField<TQuery> = [TQuery] extends [never] ? object : {
4
+ prevQuery?: TQuery;
5
+ };
6
+ type PrevBodyField<TBody> = [TBody] extends [never] ? object : {
7
+ prevBody?: TBody;
8
+ };
9
+ type PrevParamsField<TParams> = [TParams] extends [never] ? object : {
10
+ prevParams?: TParams;
11
+ };
12
+ type PrevFormDataField<TFormData> = [TFormData] extends [never] ? object : {
13
+ prevFormData?: TFormData;
14
+ };
15
+ type DebounceContext<TQuery = never, TBody = never, TParams = never, TFormData = never> = PrevQueryField<TQuery> & PrevBodyField<TBody> & PrevParamsField<TParams> & PrevFormDataField<TFormData>;
16
+ type DebounceFn<TQuery = never, TBody = never, TParams = never, TFormData = never> = (context: DebounceContext<TQuery, TBody, TParams, TFormData>) => number;
17
+ type DebounceValue<TQuery = never, TBody = never, TParams = never, TFormData = never> = number | DebounceFn<TQuery, TBody, TParams, TFormData>;
18
+ type RequestAwareDebounceFn = DebounceValue<never, never, never, never>;
19
+ interface DebounceReadOptions {
20
+ /**
21
+ * Debounce requests by X milliseconds. Waits for inactivity before fetching.
22
+ * Can be a number or a function that returns a number based on previous request.
23
+ */
24
+ debounce?: RequestAwareDebounceFn;
25
+ }
26
+ type DebounceInfiniteReadOptions = DebounceReadOptions;
27
+ type DebounceWriteOptions = object;
28
+ type DebounceReadResult = object;
29
+ type DebounceWriteResult = object;
30
+ declare module "@spoosh/core" {
31
+ interface PluginResolvers<TContext> {
32
+ debounce: DebounceValue<TContext["input"]["query"], TContext["input"]["body"], TContext["input"]["params"], TContext["input"]["formData"]> | undefined;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Enables debouncing for read operations.
38
+ *
39
+ * Delays requests until input stops changing, useful for search inputs
40
+ * to avoid excessive API calls while typing.
41
+ *
42
+ * @see {@link https://spoosh.dev/docs/plugins/debounce | Debounce Plugin Documentation}
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * const plugins = [debouncePlugin()];
47
+ *
48
+ * // Debounce search by 300ms
49
+ * useRead((api) => api.search.$get({ query: { q: searchTerm } }), {
50
+ * debounce: 300,
51
+ * });
52
+ *
53
+ * // Dynamic debounce based on previous query
54
+ * useRead((api) => api.search.$get({ query: { q: searchTerm } }), {
55
+ * debounce: ({ prevQuery }) => prevQuery?.q ? 300 : 0,
56
+ * });
57
+ * ```
58
+ */
59
+ declare function debouncePlugin(): SpooshPlugin<{
60
+ readOptions: DebounceReadOptions;
61
+ writeOptions: DebounceWriteOptions;
62
+ infiniteReadOptions: DebounceInfiniteReadOptions;
63
+ readResult: DebounceReadResult;
64
+ writeResult: DebounceWriteResult;
65
+ }>;
66
+
67
+ export { type DebounceContext, type DebounceFn, type DebounceInfiniteReadOptions, type DebounceReadOptions, type DebounceReadResult, type DebounceValue, type DebounceWriteOptions, type DebounceWriteResult, type RequestAwareDebounceFn, debouncePlugin };
@@ -0,0 +1,67 @@
1
+ import { SpooshPlugin } from '@spoosh/core';
2
+
3
+ type PrevQueryField<TQuery> = [TQuery] extends [never] ? object : {
4
+ prevQuery?: TQuery;
5
+ };
6
+ type PrevBodyField<TBody> = [TBody] extends [never] ? object : {
7
+ prevBody?: TBody;
8
+ };
9
+ type PrevParamsField<TParams> = [TParams] extends [never] ? object : {
10
+ prevParams?: TParams;
11
+ };
12
+ type PrevFormDataField<TFormData> = [TFormData] extends [never] ? object : {
13
+ prevFormData?: TFormData;
14
+ };
15
+ type DebounceContext<TQuery = never, TBody = never, TParams = never, TFormData = never> = PrevQueryField<TQuery> & PrevBodyField<TBody> & PrevParamsField<TParams> & PrevFormDataField<TFormData>;
16
+ type DebounceFn<TQuery = never, TBody = never, TParams = never, TFormData = never> = (context: DebounceContext<TQuery, TBody, TParams, TFormData>) => number;
17
+ type DebounceValue<TQuery = never, TBody = never, TParams = never, TFormData = never> = number | DebounceFn<TQuery, TBody, TParams, TFormData>;
18
+ type RequestAwareDebounceFn = DebounceValue<never, never, never, never>;
19
+ interface DebounceReadOptions {
20
+ /**
21
+ * Debounce requests by X milliseconds. Waits for inactivity before fetching.
22
+ * Can be a number or a function that returns a number based on previous request.
23
+ */
24
+ debounce?: RequestAwareDebounceFn;
25
+ }
26
+ type DebounceInfiniteReadOptions = DebounceReadOptions;
27
+ type DebounceWriteOptions = object;
28
+ type DebounceReadResult = object;
29
+ type DebounceWriteResult = object;
30
+ declare module "@spoosh/core" {
31
+ interface PluginResolvers<TContext> {
32
+ debounce: DebounceValue<TContext["input"]["query"], TContext["input"]["body"], TContext["input"]["params"], TContext["input"]["formData"]> | undefined;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Enables debouncing for read operations.
38
+ *
39
+ * Delays requests until input stops changing, useful for search inputs
40
+ * to avoid excessive API calls while typing.
41
+ *
42
+ * @see {@link https://spoosh.dev/docs/plugins/debounce | Debounce Plugin Documentation}
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * const plugins = [debouncePlugin()];
47
+ *
48
+ * // Debounce search by 300ms
49
+ * useRead((api) => api.search.$get({ query: { q: searchTerm } }), {
50
+ * debounce: 300,
51
+ * });
52
+ *
53
+ * // Dynamic debounce based on previous query
54
+ * useRead((api) => api.search.$get({ query: { q: searchTerm } }), {
55
+ * debounce: ({ prevQuery }) => prevQuery?.q ? 300 : 0,
56
+ * });
57
+ * ```
58
+ */
59
+ declare function debouncePlugin(): SpooshPlugin<{
60
+ readOptions: DebounceReadOptions;
61
+ writeOptions: DebounceWriteOptions;
62
+ infiniteReadOptions: DebounceInfiniteReadOptions;
63
+ readResult: DebounceReadResult;
64
+ writeResult: DebounceWriteResult;
65
+ }>;
66
+
67
+ export { type DebounceContext, type DebounceFn, type DebounceInfiniteReadOptions, type DebounceReadOptions, type DebounceReadResult, type DebounceValue, type DebounceWriteOptions, type DebounceWriteResult, type RequestAwareDebounceFn, debouncePlugin };
package/dist/index.js ADDED
@@ -0,0 +1,105 @@
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
+ debouncePlugin: () => debouncePlugin
24
+ });
25
+ module.exports = __toCommonJS(src_exports);
26
+
27
+ // src/plugin.ts
28
+ function resolveDebounceMs(debounce, context) {
29
+ if (debounce === void 0) return 0;
30
+ if (typeof debounce === "number") return debounce;
31
+ return debounce(context);
32
+ }
33
+ function debouncePlugin() {
34
+ const timers = /* @__PURE__ */ new Map();
35
+ const latestQueryKeys = /* @__PURE__ */ new Map();
36
+ const prevRequests = /* @__PURE__ */ new Map();
37
+ return {
38
+ name: "spoosh:debounce",
39
+ operations: ["read", "infiniteRead"],
40
+ middleware: async (context, next) => {
41
+ const pluginOptions = context.pluginOptions;
42
+ const debounceOption = pluginOptions?.debounce;
43
+ if (debounceOption === void 0 || context.forceRefetch) {
44
+ return next();
45
+ }
46
+ const { queryKey, requestOptions, path, method } = context;
47
+ const stableKey = `${path.join("/")}:${method}`;
48
+ const opts = requestOptions;
49
+ const currentRequest = {
50
+ query: opts?.query,
51
+ params: opts?.params,
52
+ body: opts?.body,
53
+ formData: opts?.formData
54
+ };
55
+ const prevRequest = prevRequests.get(stableKey);
56
+ const prevContext = {};
57
+ if (prevRequest?.query !== void 0) {
58
+ prevContext.prevQuery = prevRequest.query;
59
+ }
60
+ if (prevRequest?.params !== void 0) {
61
+ prevContext.prevParams = prevRequest.params;
62
+ }
63
+ if (prevRequest?.body !== void 0) {
64
+ prevContext.prevBody = prevRequest.body;
65
+ }
66
+ if (prevRequest?.formData !== void 0) {
67
+ prevContext.prevFormData = prevRequest.formData;
68
+ }
69
+ const debounceMs = resolveDebounceMs(debounceOption, prevContext);
70
+ prevRequests.set(stableKey, currentRequest);
71
+ if (!debounceMs || debounceMs <= 0) {
72
+ return next();
73
+ }
74
+ const existingQueryKey = latestQueryKeys.get(stableKey);
75
+ if (existingQueryKey === queryKey) {
76
+ const cached2 = context.stateManager.getCache(queryKey);
77
+ if (cached2?.state?.data !== void 0) {
78
+ return { data: cached2.state.data, status: 200 };
79
+ }
80
+ return { data: void 0, status: 0 };
81
+ }
82
+ const existingTimer = timers.get(stableKey);
83
+ if (existingTimer) {
84
+ clearTimeout(existingTimer);
85
+ }
86
+ latestQueryKeys.set(stableKey, queryKey);
87
+ const cached = context.stateManager.getCache(queryKey);
88
+ const timer = setTimeout(() => {
89
+ timers.delete(stableKey);
90
+ const latestKey = latestQueryKeys.get(stableKey);
91
+ if (latestKey) {
92
+ context.eventEmitter.emit("refetch", {
93
+ queryKey: latestKey,
94
+ reason: "invalidate"
95
+ });
96
+ }
97
+ }, debounceMs);
98
+ timers.set(stableKey, timer);
99
+ if (cached?.state?.data !== void 0) {
100
+ return { data: cached.state.data, status: 200 };
101
+ }
102
+ return { data: void 0, status: 0 };
103
+ }
104
+ };
105
+ }
package/dist/index.mjs ADDED
@@ -0,0 +1,82 @@
1
+ // src/plugin.ts
2
+ function resolveDebounceMs(debounce, context) {
3
+ if (debounce === void 0) return 0;
4
+ if (typeof debounce === "number") return debounce;
5
+ return debounce(context);
6
+ }
7
+ function debouncePlugin() {
8
+ const timers = /* @__PURE__ */ new Map();
9
+ const latestQueryKeys = /* @__PURE__ */ new Map();
10
+ const prevRequests = /* @__PURE__ */ new Map();
11
+ return {
12
+ name: "spoosh:debounce",
13
+ operations: ["read", "infiniteRead"],
14
+ middleware: async (context, next) => {
15
+ const pluginOptions = context.pluginOptions;
16
+ const debounceOption = pluginOptions?.debounce;
17
+ if (debounceOption === void 0 || context.forceRefetch) {
18
+ return next();
19
+ }
20
+ const { queryKey, requestOptions, path, method } = context;
21
+ const stableKey = `${path.join("/")}:${method}`;
22
+ const opts = requestOptions;
23
+ const currentRequest = {
24
+ query: opts?.query,
25
+ params: opts?.params,
26
+ body: opts?.body,
27
+ formData: opts?.formData
28
+ };
29
+ const prevRequest = prevRequests.get(stableKey);
30
+ const prevContext = {};
31
+ if (prevRequest?.query !== void 0) {
32
+ prevContext.prevQuery = prevRequest.query;
33
+ }
34
+ if (prevRequest?.params !== void 0) {
35
+ prevContext.prevParams = prevRequest.params;
36
+ }
37
+ if (prevRequest?.body !== void 0) {
38
+ prevContext.prevBody = prevRequest.body;
39
+ }
40
+ if (prevRequest?.formData !== void 0) {
41
+ prevContext.prevFormData = prevRequest.formData;
42
+ }
43
+ const debounceMs = resolveDebounceMs(debounceOption, prevContext);
44
+ prevRequests.set(stableKey, currentRequest);
45
+ if (!debounceMs || debounceMs <= 0) {
46
+ return next();
47
+ }
48
+ const existingQueryKey = latestQueryKeys.get(stableKey);
49
+ if (existingQueryKey === queryKey) {
50
+ const cached2 = context.stateManager.getCache(queryKey);
51
+ if (cached2?.state?.data !== void 0) {
52
+ return { data: cached2.state.data, status: 200 };
53
+ }
54
+ return { data: void 0, status: 0 };
55
+ }
56
+ const existingTimer = timers.get(stableKey);
57
+ if (existingTimer) {
58
+ clearTimeout(existingTimer);
59
+ }
60
+ latestQueryKeys.set(stableKey, queryKey);
61
+ const cached = context.stateManager.getCache(queryKey);
62
+ const timer = setTimeout(() => {
63
+ timers.delete(stableKey);
64
+ const latestKey = latestQueryKeys.get(stableKey);
65
+ if (latestKey) {
66
+ context.eventEmitter.emit("refetch", {
67
+ queryKey: latestKey,
68
+ reason: "invalidate"
69
+ });
70
+ }
71
+ }, debounceMs);
72
+ timers.set(stableKey, timer);
73
+ if (cached?.state?.data !== void 0) {
74
+ return { data: cached.state.data, status: 200 };
75
+ }
76
+ return { data: void 0, status: 0 };
77
+ }
78
+ };
79
+ }
80
+ export {
81
+ debouncePlugin
82
+ };
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@spoosh/plugin-debounce",
3
+ "version": "0.1.0-beta.0",
4
+ "description": "Request debouncing plugin for Spoosh - waits for inactivity before fetching",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/nxnom/spoosh.git",
9
+ "directory": "packages/plugin-debounce"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/nxnom/spoosh/issues"
13
+ },
14
+ "homepage": "https://spoosh.dev/docs/plugins/debounce",
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "keywords": [
19
+ "spoosh",
20
+ "plugin",
21
+ "debounce",
22
+ "api-client",
23
+ "search"
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
+ }