@demokit-ai/swr 0.2.0 → 0.4.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,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Kasava, Inc.
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/dist/index.cjs CHANGED
@@ -1,18 +1,62 @@
1
- 'use strict';
2
-
3
- var react = require('react');
4
- var swr = require('swr');
5
- var core = require('@demokit-ai/core');
6
- var jsxRuntime = require('react/jsx-runtime');
7
- var useSWRMutation = require('swr/mutation');
8
-
9
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
10
29
 
11
- var useSWRMutation__default = /*#__PURE__*/_interopDefault(useSWRMutation);
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ DemoSWRProvider: () => DemoSWRProvider,
34
+ createDemoFetcher: () => createDemoFetcher,
35
+ createDemoMiddleware: () => createDemoMiddleware,
36
+ createRemoteSource: () => createRemoteSource,
37
+ defaultFetcher: () => defaultFetcher,
38
+ findMatchingFixture: () => findMatchingFixture,
39
+ matchQueryKey: () => import_core.matchQueryKey,
40
+ normalizeFixtureMap: () => normalizeFixtureMap,
41
+ normalizeKey: () => normalizeKey,
42
+ parsePatternString: () => parsePatternString,
43
+ useDemoSWR: () => useDemoSWR,
44
+ useDemoSWRMutation: () => useDemoSWRMutation,
45
+ useIsDemoSWRMode: () => useIsDemoSWRMode
46
+ });
47
+ module.exports = __toCommonJS(index_exports);
12
48
 
13
49
  // src/provider.tsx
14
- var DemoSWRContext = react.createContext(void 0);
50
+ var import_react2 = require("react");
51
+ var import_swr = require("swr");
52
+
53
+ // src/context.ts
54
+ var import_react = require("react");
55
+ var DemoSWRContext = (0, import_react.createContext)(void 0);
15
56
  DemoSWRContext.displayName = "DemoSWRContext";
57
+
58
+ // src/matcher.ts
59
+ var import_core = require("@demokit-ai/core");
16
60
  function normalizeKey(key) {
17
61
  if (typeof key === "string") {
18
62
  return [key];
@@ -48,7 +92,7 @@ function normalizeFixtureMap(fixtures) {
48
92
  }
49
93
  function findMatchingFixture(fixtures, key) {
50
94
  const normalizedKey = normalizeKey(key);
51
- const result = core.findMatchingQueryKeyPattern(fixtures, normalizedKey);
95
+ const result = (0, import_core.findMatchingQueryKeyPattern)(fixtures, normalizedKey);
52
96
  if (result) {
53
97
  const [, handler, matchResult] = result;
54
98
  return [handler, { params: matchResult.params, normalizedKey }];
@@ -137,6 +181,9 @@ function createDemoMiddleware(options) {
137
181
  };
138
182
  return middleware;
139
183
  }
184
+
185
+ // src/provider.tsx
186
+ var import_jsx_runtime = require("react/jsx-runtime");
140
187
  function DemoSWRProvider({
141
188
  children,
142
189
  fixtures = /* @__PURE__ */ new Map(),
@@ -146,12 +193,12 @@ function DemoSWRProvider({
146
193
  fallback = {},
147
194
  swrConfig = {}
148
195
  }) {
149
- const fixturesRef = react.useRef(normalizeFixtureMap(fixtures));
150
- const mutationFixturesRef = react.useRef(
196
+ const fixturesRef = (0, import_react2.useRef)(normalizeFixtureMap(fixtures));
197
+ const mutationFixturesRef = (0, import_react2.useRef)(
151
198
  mutations instanceof Map ? mutations : new Map(Object.entries(mutations))
152
199
  );
153
200
  const isDemoMode = enabled;
154
- const demoMiddleware = react.useMemo(
201
+ const demoMiddleware = (0, import_react2.useMemo)(
155
202
  () => createDemoMiddleware({
156
203
  fixtures: fixturesRef.current,
157
204
  isEnabled: () => isDemoMode,
@@ -159,7 +206,7 @@ function DemoSWRProvider({
159
206
  }),
160
207
  [isDemoMode, delay]
161
208
  );
162
- const demoFetcher = react.useMemo(
209
+ const demoFetcher = (0, import_react2.useMemo)(
163
210
  () => createDemoFetcher({
164
211
  fixtures: fixturesRef.current,
165
212
  isEnabled: () => isDemoMode,
@@ -168,7 +215,7 @@ function DemoSWRProvider({
168
215
  }),
169
216
  [isDemoMode, delay]
170
217
  );
171
- const combinedFallback = react.useMemo(() => {
218
+ const combinedFallback = (0, import_react2.useMemo)(() => {
172
219
  if (!isDemoMode) return swrConfig.fallback || {};
173
220
  const staticFixtures = {};
174
221
  for (const [pattern, handler] of fixturesRef.current) {
@@ -183,7 +230,7 @@ function DemoSWRProvider({
183
230
  ...swrConfig.fallback || {}
184
231
  };
185
232
  }, [isDemoMode, fallback, swrConfig.fallback]);
186
- const config = react.useMemo(
233
+ const config = (0, import_react2.useMemo)(
187
234
  () => ({
188
235
  ...swrConfig,
189
236
  use: [...swrConfig.use || [], demoMiddleware],
@@ -197,9 +244,9 @@ function DemoSWRProvider({
197
244
  }),
198
245
  [swrConfig, demoMiddleware, combinedFallback, isDemoMode]
199
246
  );
200
- const getFetcher = react.useCallback(() => demoFetcher, [demoFetcher]);
201
- const getMiddleware = react.useCallback(() => demoMiddleware, [demoMiddleware]);
202
- const contextValue = react.useMemo(
247
+ const getFetcher = (0, import_react2.useCallback)(() => demoFetcher, [demoFetcher]);
248
+ const getMiddleware = (0, import_react2.useCallback)(() => demoMiddleware, [demoMiddleware]);
249
+ const contextValue = (0, import_react2.useMemo)(
203
250
  () => ({
204
251
  isDemoMode,
205
252
  setFixture: (pattern, handler) => {
@@ -219,10 +266,25 @@ function DemoSWRProvider({
219
266
  }),
220
267
  [isDemoMode, getFetcher, getMiddleware]
221
268
  );
222
- return /* @__PURE__ */ jsxRuntime.jsx(DemoSWRContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxRuntime.jsx(swr.SWRConfig, { value: config, children }) });
269
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DemoSWRContext.Provider, { value: contextValue, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_swr.SWRConfig, { value: config, children }) });
270
+ }
271
+
272
+ // src/config.ts
273
+ function createRemoteSource(config) {
274
+ return {
275
+ timeout: 1e4,
276
+ retry: true,
277
+ maxRetries: 3,
278
+ ...config
279
+ };
223
280
  }
281
+
282
+ // src/hooks.ts
283
+ var import_react3 = require("react");
284
+ var import_mutation = __toESM(require("swr/mutation"), 1);
285
+ var import_swr2 = require("swr");
224
286
  function useDemoSWR() {
225
- const context = react.useContext(DemoSWRContext);
287
+ const context = (0, import_react3.useContext)(DemoSWRContext);
226
288
  if (context === void 0) {
227
289
  throw new Error(
228
290
  "useDemoSWR must be used within a DemoSWRProvider. Make sure to wrap your app with <DemoSWRProvider>."
@@ -235,14 +297,14 @@ function useIsDemoSWRMode() {
235
297
  }
236
298
  function useDemoSWRMutation(key, options) {
237
299
  const { fetcher, demoFixture, demoDelay = 0, ...mutationOptions } = options;
238
- const { mutate } = swr.useSWRConfig();
300
+ const { mutate } = (0, import_swr2.useSWRConfig)();
239
301
  let isDemoMode = false;
240
302
  try {
241
303
  const demoState = useDemoSWR();
242
304
  isDemoMode = demoState.isDemoMode;
243
305
  } catch {
244
306
  }
245
- const demoAwareFetcher = react.useCallback(
307
+ const demoAwareFetcher = (0, import_react3.useCallback)(
246
308
  async (mutationKey, { arg }) => {
247
309
  if (!isDemoMode) {
248
310
  return fetcher(mutationKey, { arg });
@@ -271,23 +333,22 @@ function useDemoSWRMutation(key, options) {
271
333
  },
272
334
  [isDemoMode, fetcher, demoFixture, demoDelay, key, mutate]
273
335
  );
274
- return useSWRMutation__default.default(key, demoAwareFetcher, mutationOptions);
336
+ return (0, import_mutation.default)(key, demoAwareFetcher, mutationOptions);
275
337
  }
276
-
277
- Object.defineProperty(exports, "matchQueryKey", {
278
- enumerable: true,
279
- get: function () { return core.matchQueryKey; }
338
+ // Annotate the CommonJS export names for ESM import in node:
339
+ 0 && (module.exports = {
340
+ DemoSWRProvider,
341
+ createDemoFetcher,
342
+ createDemoMiddleware,
343
+ createRemoteSource,
344
+ defaultFetcher,
345
+ findMatchingFixture,
346
+ matchQueryKey,
347
+ normalizeFixtureMap,
348
+ normalizeKey,
349
+ parsePatternString,
350
+ useDemoSWR,
351
+ useDemoSWRMutation,
352
+ useIsDemoSWRMode
280
353
  });
281
- exports.DemoSWRProvider = DemoSWRProvider;
282
- exports.createDemoFetcher = createDemoFetcher;
283
- exports.createDemoMiddleware = createDemoMiddleware;
284
- exports.defaultFetcher = defaultFetcher;
285
- exports.findMatchingFixture = findMatchingFixture;
286
- exports.normalizeFixtureMap = normalizeFixtureMap;
287
- exports.normalizeKey = normalizeKey;
288
- exports.parsePatternString = parsePatternString;
289
- exports.useDemoSWR = useDemoSWR;
290
- exports.useDemoSWRMutation = useDemoSWRMutation;
291
- exports.useIsDemoSWRMode = useIsDemoSWRMode;
292
- //# sourceMappingURL=index.cjs.map
293
354
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/context.ts","../src/matcher.ts","../src/fetcher.ts","../src/middleware.ts","../src/provider.tsx","../src/hooks.ts"],"names":["createContext","findMatchingQueryKeyPattern","useRef","useMemo","useCallback","jsx","SWRConfig","useContext","useSWRConfig","useSWRMutation"],"mappings":";;;;;;;;;;;;;AASO,IAAM,cAAA,GAAiBA,oBAAwC,MAAS,CAAA;AAE/E,cAAA,CAAe,WAAA,GAAc,gBAAA;ACCtB,SAAS,aAAa,GAA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A,MAC/D;AAGA,MAAA,IAAI,gBAAgB,MAAA,EAAW;AAC7B,QAAA,MAAM,OAAA,GAAkD;AAAA,UACtD,GAAA,EAAK,WAAA;AAAA,UACL,GAAA;AAAA,UACA,WAAA,EAAa,MAAA;AAAA;AAAA,UACb;AAAA,SACF;AAEA,QAAA,IAAI,OAAO,gBAAgB,UAAA,EAAY;AACrC,UAAA,MAAM,SAAA,GAAY,WAAA;AAGlB,UAAA,OAAO,UAAU,OAAO,CAAA;AAAA,QAC1B;AACA,QAAA,OAAO,WAAA;AAAA,MACT;AAGA,MAAA,OAAA,CAAQ,IAAA;AAAA,QACN,gDAAgD,GAAG,CAAA,gCAAA;AAAA,OACrD;AACA,MAAA,OAAO,OAAA,CAAQ,WAAA,EAAa,EAAE,GAAA,EAAK,CAAA;AAAA,IACrC,CAAA;AAAA,IACA,CAAC,UAAA,EAAY,OAAA,EAAS,WAAA,EAAa,SAAA,EAAW,KAAK,MAAM;AAAA,GAC3D;AAEA,EAAA,OAAOK,+BAAA,CAAe,GAAA,EAAK,gBAAA,EAAkB,eAAe,CAAA;AAC9D","file":"index.cjs","sourcesContent":["'use client'\n\nimport { createContext } from 'react'\nimport type { DemoSWRState } from './types'\n\n/**\n * Context for DemoSWR state\n * @internal\n */\nexport const DemoSWRContext = createContext<DemoSWRState | undefined>(undefined)\n\nDemoSWRContext.displayName = 'DemoSWRContext'\n","import { matchQueryKey, findMatchingQueryKeyPattern } from '@demokit-ai/core'\nimport type { QueryKey } from '@demokit-ai/core'\nimport type { SWRFixtureHandler, SWRFixtureMap, SWRFixtureMapObject } from './types'\n\n/**\n * Normalize an SWR key to a QueryKey for matching\n *\n * SWR keys can be:\n * - Strings: '/api/users' -> ['/api/users']\n * - Arrays: ['/api/users', id] -> ['/api/users', id]\n * - Functions that return keys (not handled here)\n */\nexport function normalizeKey(key: string | unknown[]): QueryKey {\n if (typeof key === 'string') {\n return [key]\n }\n\n return key.map((element) => {\n if (element === null || element === undefined) {\n return element\n }\n if (typeof element === 'object') {\n return element as Record<string, unknown>\n }\n return element as string | number | boolean\n })\n}\n\n/**\n * Parse a JSON string pattern into a QueryKey\n * Handles both array notation and simple string patterns\n *\n * @example\n * parsePatternString('[\"/api/users\"]') // ['/api/users']\n * parsePatternString('[\"/api/users\", \":id\"]') // ['/api/users', ':id']\n * parsePatternString('/api/users') // ['/api/users']\n */\nexport function parsePatternString(pattern: string): QueryKey {\n // Try to parse as JSON array\n if (pattern.startsWith('[')) {\n try {\n return JSON.parse(pattern) as QueryKey\n } catch {\n // Fall through to simple string\n }\n }\n\n // Simple string becomes single-element array\n return [pattern]\n}\n\n/**\n * Convert object-based fixture map to Map-based fixture map\n */\nexport function normalizeFixtureMap(fixtures: SWRFixtureMapObject | SWRFixtureMap): SWRFixtureMap {\n if (fixtures instanceof Map) {\n return fixtures\n }\n\n const map = new Map<QueryKey, SWRFixtureHandler>()\n for (const [pattern, handler] of Object.entries(fixtures)) {\n map.set(parsePatternString(pattern), handler)\n }\n return map\n}\n\n/**\n * Find a matching fixture for an SWR key\n *\n * @param fixtures - Map of key patterns to handlers\n * @param key - The SWR key to match\n * @returns Tuple of [handler, match result] or null if no match\n */\nexport function findMatchingFixture(\n fixtures: SWRFixtureMap,\n key: string | unknown[]\n): [SWRFixtureHandler, { params: Record<string, unknown>; normalizedKey: QueryKey }] | null {\n const normalizedKey = normalizeKey(key)\n const result = findMatchingQueryKeyPattern(fixtures, normalizedKey)\n\n if (result) {\n const [, handler, matchResult] = result\n return [handler, { params: matchResult.params, normalizedKey }]\n }\n\n return null\n}\n\n/**\n * Re-export the matchQueryKey function for direct use\n */\nexport { matchQueryKey }","import type { QueryKey } from '@demokit-ai/core'\nimport type { SWRFixtureMap, SWRFixtureContext } from './types'\nimport { findMatchingFixture, normalizeKey } from './matcher'\n\n/**\n * Options for creating a demo-aware fetcher\n */\nexport interface CreateDemoFetcherOptions {\n /**\n * Map of key patterns to fixture handlers\n */\n fixtures: SWRFixtureMap\n\n /**\n * Function to check if demo mode is enabled\n */\n isEnabled: () => boolean\n\n /**\n * Delay in ms before returning fixture data\n * @default 0\n */\n delay?: number\n\n /**\n * Fallback fetcher to use when demo mode is disabled\n * or no fixture matches\n */\n fallbackFetcher?: <T>(key: string | unknown[]) => Promise<T>\n}\n\n/**\n * Create a demo-aware fetcher function for SWR\n *\n * This fetcher intercepts requests when demo mode is enabled\n * and returns fixture data instead of making real API calls.\n *\n * @example\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'User' })],\n * ])\n *\n * const fetcher = createDemoFetcher({\n * fixtures,\n * isEnabled: () => isDemoMode,\n * delay: 100,\n * })\n *\n * // Use with SWR\n * const { data } = useSWR('/api/users', fetcher)\n */\nexport function createDemoFetcher(options: CreateDemoFetcherOptions) {\n const { fixtures, isEnabled, delay = 0, fallbackFetcher } = options\n\n return async function demoFetcher<TData = unknown>(key: string | unknown[]): Promise<TData> {\n // If demo mode is not enabled, use fallback\n if (!isEnabled()) {\n if (fallbackFetcher) {\n return fallbackFetcher<TData>(key)\n }\n throw new Error(\n `[DemoKit SWR] No fallback fetcher provided and demo mode is disabled. ` +\n `Key: ${JSON.stringify(key)}`\n )\n }\n\n // Find matching fixture\n const match = findMatchingFixture(fixtures, key)\n\n if (!match) {\n // No fixture found, try fallback\n if (fallbackFetcher) {\n return fallbackFetcher<TData>(key)\n }\n throw new Error(`[DemoKit SWR] No fixture found for key: ${JSON.stringify(key)}`)\n }\n\n const [handler, { params, normalizedKey }] = match\n\n // Apply delay if configured\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n\n // Build context\n const context: SWRFixtureContext = {\n key,\n normalizedKey,\n params,\n match: { matched: true, params },\n }\n\n // Execute handler\n if (typeof handler === 'function') {\n return handler(context) as TData\n }\n\n // Return static value\n return handler as TData\n }\n}\n\n/**\n * Default fetcher that uses fetch API\n * Used as fallback when demo mode is disabled\n */\nexport async function defaultFetcher<TData = unknown>(key: string | unknown[]): Promise<TData> {\n const url = typeof key === 'string' ? key : String(key[0])\n const response = await fetch(url)\n\n if (!response.ok) {\n const error = new Error('An error occurred while fetching the data.')\n throw error\n }\n\n return response.json()\n}\n","import type { Middleware } from 'swr'\nimport type { SWRFixtureMap, SWRFixtureContext } from './types'\nimport { findMatchingFixture } from './matcher'\n\n/**\n * Options for creating the demo middleware\n */\nexport interface CreateDemoMiddlewareOptions {\n /**\n * Map of key patterns to fixture handlers\n */\n fixtures: SWRFixtureMap\n\n /**\n * Function to check if demo mode is enabled\n */\n isEnabled: () => boolean\n\n /**\n * Delay in ms before returning fixture data\n * @default 0\n */\n delay?: number\n}\n\n/**\n * Create a demo-aware SWR middleware\n *\n * This middleware intercepts SWR requests when demo mode is enabled\n * and returns fixture data instead of using the original fetcher.\n *\n * @example\n * import { SWRConfig } from 'swr'\n * import { createDemoMiddleware } from '@demokit-ai/swr'\n *\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'User' })],\n * ])\n *\n * const demoMiddleware = createDemoMiddleware({\n * fixtures,\n * isEnabled: () => isDemoMode,\n * delay: 100,\n * })\n *\n * function App() {\n * return (\n * <SWRConfig value={{ use: [demoMiddleware] }}>\n * <YourApp />\n * </SWRConfig>\n * )\n * }\n */\nexport function createDemoMiddleware(options: CreateDemoMiddlewareOptions): Middleware {\n const { fixtures, isEnabled, delay = 0 } = options\n\n // Use the simpler middleware pattern that SWR expects\n const middleware: Middleware = (useSWRNext) => (key, fetcher, config) => {\n // Create an extended fetcher that checks for demo mode\n const extendedFetcher =\n fetcher === null\n ? null\n : async (...args: Parameters<typeof fetcher>) => {\n // Resolve the key if it's a function\n const resolvedKey = typeof key === 'function' ? key() : key\n\n // If no key, let SWR handle it\n if (resolvedKey === null || resolvedKey === undefined) {\n return fetcher(...args)\n }\n\n // If demo mode is not enabled, use original fetcher\n if (!isEnabled()) {\n return fetcher(...args)\n }\n\n // Normalize key for matching\n const keyToMatch =\n typeof resolvedKey === 'string' ? resolvedKey : (resolvedKey as unknown[])\n\n // Find matching fixture\n const match = findMatchingFixture(fixtures, keyToMatch)\n\n if (!match) {\n // No fixture found, use original fetcher\n return fetcher(...args)\n }\n\n const [handler, { params, normalizedKey }] = match\n\n // Apply delay if configured\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n\n // Build context\n const context: SWRFixtureContext = {\n key: resolvedKey,\n normalizedKey,\n params,\n match: { matched: true, params },\n }\n\n // Execute handler\n if (typeof handler === 'function') {\n return handler(context)\n }\n\n // Return static value\n return handler\n }\n\n return useSWRNext(key, extendedFetcher, config)\n }\n\n return middleware\n}\n","'use client'\n\nimport { useMemo, useRef, useCallback } from 'react'\nimport { SWRConfig } from 'swr'\nimport type { QueryKey } from '@demokit-ai/core'\nimport { DemoSWRContext } from './context'\nimport { createDemoFetcher, defaultFetcher } from './fetcher'\nimport { createDemoMiddleware } from './middleware'\nimport { normalizeFixtureMap } from './matcher'\nimport type {\n DemoSWRProviderProps,\n SWRFixtureHandler,\n SWRFixtureMap,\n SWRMutationFixtureHandler,\n SWRMutationFixtureMap,\n DemoSWRState,\n} from './types'\n\n/**\n * Provider component for DemoKit SWR integration\n *\n * Wraps SWRConfig and intercepts fetches when demo mode is enabled.\n * Uses SWR's middleware pattern for maximum flexibility.\n *\n * @example\n * // With object-based fixtures\n * <DemoSWRProvider\n * enabled={true}\n * fixtures={{\n * '/api/users': [{ id: '1', name: 'Demo User' }],\n * '[\"/api/users\", \":id\"]': ({ params }) => ({ id: params.id, name: 'Demo User' }),\n * '[\"/api/projects\", { status: \":status\" }]': ({ params }) => [\n * { id: '1', name: 'Project', status: params.status },\n * ],\n * }}\n * delay={100}\n * >\n * <App />\n * </DemoSWRProvider>\n *\n * @example\n * // With Map-based fixtures\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'Demo User' })],\n * ])\n *\n * <DemoSWRProvider enabled={true} fixtures={fixtures}>\n * <App />\n * </DemoSWRProvider>\n *\n * @example\n * // With cache seeding via fallback\n * <DemoSWRProvider\n * enabled={true}\n * fixtures={fixtures}\n * fallback={{\n * '/api/users': [{ id: '1', name: 'Pre-loaded User' }],\n * }}\n * >\n * <App />\n * </DemoSWRProvider>\n */\nexport function DemoSWRProvider({\n children,\n fixtures = new Map(),\n mutations = new Map(),\n enabled = false,\n delay = 0,\n fallback = {},\n swrConfig = {},\n}: DemoSWRProviderProps) {\n // Normalize fixtures\n const fixturesRef = useRef<SWRFixtureMap>(normalizeFixtureMap(fixtures))\n const mutationFixturesRef = useRef<SWRMutationFixtureMap>(\n mutations instanceof Map ? mutations : new Map(Object.entries(mutations))\n )\n\n const isDemoMode = enabled\n\n // Create demo middleware\n const demoMiddleware = useMemo(\n () =>\n createDemoMiddleware({\n fixtures: fixturesRef.current,\n isEnabled: () => isDemoMode,\n delay,\n }),\n [isDemoMode, delay]\n )\n\n // Create demo fetcher (for direct use)\n const demoFetcher = useMemo(\n () =>\n createDemoFetcher({\n fixtures: fixturesRef.current,\n isEnabled: () => isDemoMode,\n delay,\n fallbackFetcher: defaultFetcher,\n }),\n [isDemoMode, delay]\n )\n\n // Build fallback data from static fixtures + provided fallback\n const combinedFallback = useMemo(() => {\n if (!isDemoMode) return swrConfig.fallback || {}\n\n const staticFixtures: Record<string, unknown> = {}\n\n // Add static fixture values to fallback\n for (const [pattern, handler] of fixturesRef.current) {\n if (typeof handler !== 'function') {\n // Use the pattern as key for static fixtures\n const key = pattern.length === 1 ? String(pattern[0]) : JSON.stringify(pattern)\n staticFixtures[key] = handler\n }\n }\n\n return {\n ...staticFixtures,\n ...fallback,\n ...(swrConfig.fallback || {}),\n }\n }, [isDemoMode, fallback, swrConfig.fallback])\n\n // Build SWR config\n const config = useMemo(\n () => ({\n ...swrConfig,\n use: [...(swrConfig.use || []), demoMiddleware],\n fallback: combinedFallback,\n // In demo mode, don't retry and keep data fresh longer\n ...(isDemoMode\n ? {\n revalidateOnFocus: false,\n revalidateOnReconnect: false,\n shouldRetryOnError: false,\n }\n : {}),\n }),\n [swrConfig, demoMiddleware, combinedFallback, isDemoMode]\n )\n\n // Context value with manipulation methods\n const getFetcher = useCallback(() => demoFetcher, [demoFetcher])\n const getMiddleware = useCallback(() => demoMiddleware, [demoMiddleware])\n\n const contextValue = useMemo<DemoSWRState>(\n () => ({\n isDemoMode,\n\n setFixture: (pattern: QueryKey, handler: SWRFixtureHandler) => {\n fixturesRef.current.set(pattern, handler)\n },\n\n removeFixture: (pattern: QueryKey) => {\n fixturesRef.current.delete(pattern)\n },\n\n setMutationFixture: (name: string, handler: SWRMutationFixtureHandler) => {\n mutationFixturesRef.current.set(name, handler)\n },\n\n removeMutationFixture: (name: string) => {\n mutationFixturesRef.current.delete(name)\n },\n\n getFetcher,\n getMiddleware,\n }),\n [isDemoMode, getFetcher, getMiddleware]\n )\n\n return (\n <DemoSWRContext.Provider value={contextValue}>\n <SWRConfig value={config}>{children}</SWRConfig>\n </DemoSWRContext.Provider>\n )\n}\n","'use client'\n\nimport { useContext, useCallback } from 'react'\nimport useSWRMutation, { type SWRMutationConfiguration, type SWRMutationResponse } from 'swr/mutation'\nimport { useSWRConfig } from 'swr'\nimport { DemoSWRContext } from './context'\nimport type { DemoSWRState, SWRMutationFixtureContext, SWRMutationFixtureHandler } from './types'\n\n/**\n * Hook to access DemoSWR state and controls\n *\n * @returns DemoSWR context value\n * @throws Error if used outside of DemoSWRProvider\n *\n * @example\n * function MyComponent() {\n * const { isDemoMode, setFixture } = useDemoSWR()\n *\n * // Dynamically add a fixture\n * const handleAddFixture = () => {\n * setFixture(['/api/users', 'custom'], { id: 'custom', name: 'Custom User' })\n * }\n *\n * return (\n * <button onClick={handleAddFixture}>Add Custom Fixture</button>\n * )\n * }\n */\nexport function useDemoSWR(): DemoSWRState {\n const context = useContext(DemoSWRContext)\n\n if (context === undefined) {\n throw new Error(\n 'useDemoSWR must be used within a DemoSWRProvider. ' +\n 'Make sure to wrap your app with <DemoSWRProvider>.'\n )\n }\n\n return context\n}\n\n/**\n * Hook to check if demo mode is enabled\n * Shorthand for useDemoSWR().isDemoMode\n *\n * @example\n * function MyComponent() {\n * const isDemoMode = useIsDemoSWRMode()\n *\n * return isDemoMode ? <DemoBadge /> : null\n * }\n */\nexport function useIsDemoSWRMode(): boolean {\n return useDemoSWR().isDemoMode\n}\n\n/**\n * Options for useDemoSWRMutation hook\n */\nexport interface UseDemoSWRMutationOptions<TData, TError, TArg>\n extends Omit<SWRMutationConfiguration<TData, TError, string, TArg>, 'fetcher'> {\n /**\n * The real mutation function to use when demo mode is disabled\n */\n fetcher: (key: string, options: { arg: TArg }) => Promise<TData>\n\n /**\n * Demo fixture handler for this mutation\n */\n demoFixture?: SWRMutationFixtureHandler<TData, TArg>\n\n /**\n * Delay in ms before returning demo data\n * @default 0\n */\n demoDelay?: number\n}\n\n/**\n * A mutation hook that automatically uses demo fixtures when demo mode is enabled\n *\n * Works with useSWRMutation from swr/mutation.\n *\n * @example\n * const { trigger: createUser, isMutating } = useDemoSWRMutation('/api/users', {\n * fetcher: async (key, { arg }) => api.createUser(arg),\n * demoFixture: ({ arg, mutate }) => {\n * // Create demo user\n * const newUser = { id: crypto.randomUUID(), ...arg }\n *\n * // Update the users cache\n * mutate('/api/users', (current: User[] = []) => [...current, newUser])\n *\n * return newUser\n * },\n * onSuccess: (data) => {\n * console.log('Created user:', data)\n * },\n * })\n *\n * // Use like normal useSWRMutation\n * createUser({ name: 'New User', email: 'user@example.com' })\n */\nexport function useDemoSWRMutation<TData = unknown, TError = unknown, TArg = unknown>(\n key: string,\n options: UseDemoSWRMutationOptions<TData, TError, TArg>\n): SWRMutationResponse<TData, TError, string, TArg> {\n const { fetcher, demoFixture, demoDelay = 0, ...mutationOptions } = options\n\n const { mutate } = useSWRConfig()\n\n // Try to get demo state - may not be in DemoSWRProvider context\n let isDemoMode = false\n try {\n const demoState = useDemoSWR()\n isDemoMode = demoState.isDemoMode\n } catch {\n // Not in DemoSWRProvider context, use real mutation\n }\n\n // Create the demo-aware mutation function\n const demoAwareFetcher = useCallback(\n async (mutationKey: string, { arg }: { arg: TArg }): Promise<TData> => {\n // If not in demo mode, use real mutation\n if (!isDemoMode) {\n return fetcher(mutationKey, { arg })\n }\n\n // Apply delay if configured\n if (demoDelay > 0) {\n await new Promise((resolve) => setTimeout(resolve, demoDelay))\n }\n\n // If a demo fixture is provided, use it\n if (demoFixture !== undefined) {\n const context: SWRMutationFixtureContext<TData, TArg> = {\n key: mutationKey,\n arg,\n currentData: undefined, // SWR mutation doesn't have direct access to current data\n mutate: mutate as SWRMutationFixtureContext<TData, TArg>['mutate'],\n }\n\n if (typeof demoFixture === 'function') {\n const fixtureFn = demoFixture as (\n context: SWRMutationFixtureContext<TData, TArg>\n ) => TData | Promise<TData>\n return fixtureFn(context)\n }\n return demoFixture as TData\n }\n\n // No fixture found, fall back to real mutation\n console.warn(\n `[DemoKit SWR] No mutation fixture found for \"${key}\". Using real mutation function.`\n )\n return fetcher(mutationKey, { arg })\n },\n [isDemoMode, fetcher, demoFixture, demoDelay, key, mutate]\n )\n\n return useSWRMutation(key, demoAwareFetcher, mutationOptions)\n}\n"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/provider.tsx","../src/context.ts","../src/matcher.ts","../src/fetcher.ts","../src/middleware.ts","../src/config.ts","../src/hooks.ts"],"sourcesContent":["/**\n * @demokit-ai/swr\n *\n * SWR adapter for DemoKit.\n * Mock fetches and mutations when demo mode is enabled using SWR's middleware pattern.\n *\n * @example\n * import { DemoSWRProvider } from '@demokit-ai/swr'\n *\n * // Define fixtures\n * const fixtures = {\n * '/api/users': [\n * { id: '1', name: 'Demo User' },\n * { id: '2', name: 'Another User' },\n * ],\n * '[\"/api/users\", \":id\"]': ({ params }) => ({\n * id: params.id,\n * name: `User ${params.id}`,\n * }),\n * '[\"/api/projects\", { status: \":status\" }]': ({ params }) => [\n * { id: '1', name: 'Project', status: params.status },\n * ],\n * }\n *\n * // Wrap your app\n * <DemoSWRProvider fixtures={fixtures} enabled={true}>\n * <App />\n * </DemoSWRProvider>\n *\n * @packageDocumentation\n */\n\n// Provider\nexport { DemoSWRProvider } from './provider'\n\n// Config helpers\nexport { createRemoteSource } from './config'\n\n// Hooks\nexport { useDemoSWR, useIsDemoSWRMode, useDemoSWRMutation } from './hooks'\nexport type { UseDemoSWRMutationOptions } from './hooks'\n\n// Fetcher utilities\nexport { createDemoFetcher, defaultFetcher } from './fetcher'\nexport type { CreateDemoFetcherOptions } from './fetcher'\n\n// Middleware\nexport { createDemoMiddleware } from './middleware'\nexport type { CreateDemoMiddlewareOptions } from './middleware'\n\n// Matcher utilities\nexport {\n findMatchingFixture,\n normalizeKey,\n normalizeFixtureMap,\n parsePatternString,\n matchQueryKey,\n} from './matcher'\n\n// Types\nexport type {\n SWRFixtureContext,\n SWRFixtureHandler,\n SWRFixtureMap,\n SWRFixtureMapObject,\n SWRMutationFixtureContext,\n SWRMutationFixtureHandler,\n SWRMutationFixtureMap,\n SWRMutationFixtureMapObject,\n DemoSWRProviderConfig,\n DemoSWRProviderProps,\n DemoSWRState,\n RemoteSourceConfig,\n} from './types'\n","'use client'\n\nimport { useMemo, useRef, useCallback } from 'react'\nimport { SWRConfig } from 'swr'\nimport type { QueryKey } from '@demokit-ai/core'\nimport { DemoSWRContext } from './context'\nimport { createDemoFetcher, defaultFetcher } from './fetcher'\nimport { createDemoMiddleware } from './middleware'\nimport { normalizeFixtureMap } from './matcher'\nimport type {\n DemoSWRProviderProps,\n SWRFixtureHandler,\n SWRFixtureMap,\n SWRMutationFixtureHandler,\n SWRMutationFixtureMap,\n DemoSWRState,\n} from './types'\n\n/**\n * Provider component for DemoKit SWR integration\n *\n * Wraps SWRConfig and intercepts fetches when demo mode is enabled.\n * Uses SWR's middleware pattern for maximum flexibility.\n *\n * @example\n * // With object-based fixtures\n * <DemoSWRProvider\n * enabled={true}\n * fixtures={{\n * '/api/users': [{ id: '1', name: 'Demo User' }],\n * '[\"/api/users\", \":id\"]': ({ params }) => ({ id: params.id, name: 'Demo User' }),\n * '[\"/api/projects\", { status: \":status\" }]': ({ params }) => [\n * { id: '1', name: 'Project', status: params.status },\n * ],\n * }}\n * delay={100}\n * >\n * <App />\n * </DemoSWRProvider>\n *\n * @example\n * // With Map-based fixtures\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'Demo User' })],\n * ])\n *\n * <DemoSWRProvider enabled={true} fixtures={fixtures}>\n * <App />\n * </DemoSWRProvider>\n *\n * @example\n * // With cache seeding via fallback\n * <DemoSWRProvider\n * enabled={true}\n * fixtures={fixtures}\n * fallback={{\n * '/api/users': [{ id: '1', name: 'Pre-loaded User' }],\n * }}\n * >\n * <App />\n * </DemoSWRProvider>\n */\nexport function DemoSWRProvider({\n children,\n fixtures = new Map(),\n mutations = new Map(),\n enabled = false,\n delay = 0,\n fallback = {},\n swrConfig = {},\n}: DemoSWRProviderProps) {\n // Normalize fixtures\n const fixturesRef = useRef<SWRFixtureMap>(normalizeFixtureMap(fixtures))\n const mutationFixturesRef = useRef<SWRMutationFixtureMap>(\n mutations instanceof Map ? mutations : new Map(Object.entries(mutations))\n )\n\n const isDemoMode = enabled\n\n // Create demo middleware\n const demoMiddleware = useMemo(\n () =>\n createDemoMiddleware({\n fixtures: fixturesRef.current,\n isEnabled: () => isDemoMode,\n delay,\n }),\n [isDemoMode, delay]\n )\n\n // Create demo fetcher (for direct use)\n const demoFetcher = useMemo(\n () =>\n createDemoFetcher({\n fixtures: fixturesRef.current,\n isEnabled: () => isDemoMode,\n delay,\n fallbackFetcher: defaultFetcher,\n }),\n [isDemoMode, delay]\n )\n\n // Build fallback data from static fixtures + provided fallback\n const combinedFallback = useMemo(() => {\n if (!isDemoMode) return swrConfig.fallback || {}\n\n const staticFixtures: Record<string, unknown> = {}\n\n // Add static fixture values to fallback\n for (const [pattern, handler] of fixturesRef.current) {\n if (typeof handler !== 'function') {\n // Use the pattern as key for static fixtures\n const key = pattern.length === 1 ? String(pattern[0]) : JSON.stringify(pattern)\n staticFixtures[key] = handler\n }\n }\n\n return {\n ...staticFixtures,\n ...fallback,\n ...(swrConfig.fallback || {}),\n }\n }, [isDemoMode, fallback, swrConfig.fallback])\n\n // Build SWR config\n const config = useMemo(\n () => ({\n ...swrConfig,\n use: [...(swrConfig.use || []), demoMiddleware],\n fallback: combinedFallback,\n // In demo mode, don't retry and keep data fresh longer\n ...(isDemoMode\n ? {\n revalidateOnFocus: false,\n revalidateOnReconnect: false,\n shouldRetryOnError: false,\n }\n : {}),\n }),\n [swrConfig, demoMiddleware, combinedFallback, isDemoMode]\n )\n\n // Context value with manipulation methods\n const getFetcher = useCallback(() => demoFetcher, [demoFetcher])\n const getMiddleware = useCallback(() => demoMiddleware, [demoMiddleware])\n\n const contextValue = useMemo<DemoSWRState>(\n () => ({\n isDemoMode,\n\n setFixture: (pattern: QueryKey, handler: SWRFixtureHandler) => {\n fixturesRef.current.set(pattern, handler)\n },\n\n removeFixture: (pattern: QueryKey) => {\n fixturesRef.current.delete(pattern)\n },\n\n setMutationFixture: (name: string, handler: SWRMutationFixtureHandler) => {\n mutationFixturesRef.current.set(name, handler)\n },\n\n removeMutationFixture: (name: string) => {\n mutationFixturesRef.current.delete(name)\n },\n\n getFetcher,\n getMiddleware,\n }),\n [isDemoMode, getFetcher, getMiddleware]\n )\n\n return (\n <DemoSWRContext.Provider value={contextValue}>\n <SWRConfig value={config}>{children}</SWRConfig>\n </DemoSWRContext.Provider>\n )\n}\n","'use client'\n\nimport { createContext } from 'react'\nimport type { DemoSWRState } from './types'\n\n/**\n * Context for DemoSWR state\n * @internal\n */\nexport const DemoSWRContext = createContext<DemoSWRState | undefined>(undefined)\n\nDemoSWRContext.displayName = 'DemoSWRContext'\n","import { matchQueryKey, findMatchingQueryKeyPattern } from '@demokit-ai/core'\nimport type { QueryKey } from '@demokit-ai/core'\nimport type { SWRFixtureHandler, SWRFixtureMap, SWRFixtureMapObject } from './types'\n\n/**\n * Normalize an SWR key to a QueryKey for matching\n *\n * SWR keys can be:\n * - Strings: '/api/users' -> ['/api/users']\n * - Arrays: ['/api/users', id] -> ['/api/users', id]\n * - Functions that return keys (not handled here)\n */\nexport function normalizeKey(key: string | unknown[]): QueryKey {\n if (typeof key === 'string') {\n return [key]\n }\n\n return key.map((element) => {\n if (element === null || element === undefined) {\n return element\n }\n if (typeof element === 'object') {\n return element as Record<string, unknown>\n }\n return element as string | number | boolean\n })\n}\n\n/**\n * Parse a JSON string pattern into a QueryKey\n * Handles both array notation and simple string patterns\n *\n * @example\n * parsePatternString('[\"/api/users\"]') // ['/api/users']\n * parsePatternString('[\"/api/users\", \":id\"]') // ['/api/users', ':id']\n * parsePatternString('/api/users') // ['/api/users']\n */\nexport function parsePatternString(pattern: string): QueryKey {\n // Try to parse as JSON array\n if (pattern.startsWith('[')) {\n try {\n return JSON.parse(pattern) as QueryKey\n } catch {\n // Fall through to simple string\n }\n }\n\n // Simple string becomes single-element array\n return [pattern]\n}\n\n/**\n * Convert object-based fixture map to Map-based fixture map\n */\nexport function normalizeFixtureMap(fixtures: SWRFixtureMapObject | SWRFixtureMap): SWRFixtureMap {\n if (fixtures instanceof Map) {\n return fixtures\n }\n\n const map = new Map<QueryKey, SWRFixtureHandler>()\n for (const [pattern, handler] of Object.entries(fixtures)) {\n map.set(parsePatternString(pattern), handler)\n }\n return map\n}\n\n/**\n * Find a matching fixture for an SWR key\n *\n * @param fixtures - Map of key patterns to handlers\n * @param key - The SWR key to match\n * @returns Tuple of [handler, match result] or null if no match\n */\nexport function findMatchingFixture(\n fixtures: SWRFixtureMap,\n key: string | unknown[]\n): [SWRFixtureHandler, { params: Record<string, unknown>; normalizedKey: QueryKey }] | null {\n const normalizedKey = normalizeKey(key)\n const result = findMatchingQueryKeyPattern(fixtures, normalizedKey)\n\n if (result) {\n const [, handler, matchResult] = result\n return [handler, { params: matchResult.params, normalizedKey }]\n }\n\n return null\n}\n\n/**\n * Re-export the matchQueryKey function for direct use\n */\nexport { matchQueryKey }","import type { QueryKey } from '@demokit-ai/core'\nimport type { SWRFixtureMap, SWRFixtureContext } from './types'\nimport { findMatchingFixture, normalizeKey } from './matcher'\n\n/**\n * Options for creating a demo-aware fetcher\n */\nexport interface CreateDemoFetcherOptions {\n /**\n * Map of key patterns to fixture handlers\n */\n fixtures: SWRFixtureMap\n\n /**\n * Function to check if demo mode is enabled\n */\n isEnabled: () => boolean\n\n /**\n * Delay in ms before returning fixture data\n * @default 0\n */\n delay?: number\n\n /**\n * Fallback fetcher to use when demo mode is disabled\n * or no fixture matches\n */\n fallbackFetcher?: <T>(key: string | unknown[]) => Promise<T>\n}\n\n/**\n * Create a demo-aware fetcher function for SWR\n *\n * This fetcher intercepts requests when demo mode is enabled\n * and returns fixture data instead of making real API calls.\n *\n * @example\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'User' })],\n * ])\n *\n * const fetcher = createDemoFetcher({\n * fixtures,\n * isEnabled: () => isDemoMode,\n * delay: 100,\n * })\n *\n * // Use with SWR\n * const { data } = useSWR('/api/users', fetcher)\n */\nexport function createDemoFetcher(options: CreateDemoFetcherOptions) {\n const { fixtures, isEnabled, delay = 0, fallbackFetcher } = options\n\n return async function demoFetcher<TData = unknown>(key: string | unknown[]): Promise<TData> {\n // If demo mode is not enabled, use fallback\n if (!isEnabled()) {\n if (fallbackFetcher) {\n return fallbackFetcher<TData>(key)\n }\n throw new Error(\n `[DemoKit SWR] No fallback fetcher provided and demo mode is disabled. ` +\n `Key: ${JSON.stringify(key)}`\n )\n }\n\n // Find matching fixture\n const match = findMatchingFixture(fixtures, key)\n\n if (!match) {\n // No fixture found, try fallback\n if (fallbackFetcher) {\n return fallbackFetcher<TData>(key)\n }\n throw new Error(`[DemoKit SWR] No fixture found for key: ${JSON.stringify(key)}`)\n }\n\n const [handler, { params, normalizedKey }] = match\n\n // Apply delay if configured\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n\n // Build context\n const context: SWRFixtureContext = {\n key,\n normalizedKey,\n params,\n match: { matched: true, params },\n }\n\n // Execute handler\n if (typeof handler === 'function') {\n return handler(context) as TData\n }\n\n // Return static value\n return handler as TData\n }\n}\n\n/**\n * Default fetcher that uses fetch API\n * Used as fallback when demo mode is disabled\n */\nexport async function defaultFetcher<TData = unknown>(key: string | unknown[]): Promise<TData> {\n const url = typeof key === 'string' ? key : String(key[0])\n const response = await fetch(url)\n\n if (!response.ok) {\n const error = new Error('An error occurred while fetching the data.')\n throw error\n }\n\n return response.json()\n}\n","import type { Middleware } from 'swr'\nimport type { SWRFixtureMap, SWRFixtureContext } from './types'\nimport { findMatchingFixture } from './matcher'\n\n/**\n * Options for creating the demo middleware\n */\nexport interface CreateDemoMiddlewareOptions {\n /**\n * Map of key patterns to fixture handlers\n */\n fixtures: SWRFixtureMap\n\n /**\n * Function to check if demo mode is enabled\n */\n isEnabled: () => boolean\n\n /**\n * Delay in ms before returning fixture data\n * @default 0\n */\n delay?: number\n}\n\n/**\n * Create a demo-aware SWR middleware\n *\n * This middleware intercepts SWR requests when demo mode is enabled\n * and returns fixture data instead of using the original fetcher.\n *\n * @example\n * import { SWRConfig } from 'swr'\n * import { createDemoMiddleware } from '@demokit-ai/swr'\n *\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'User' })],\n * ])\n *\n * const demoMiddleware = createDemoMiddleware({\n * fixtures,\n * isEnabled: () => isDemoMode,\n * delay: 100,\n * })\n *\n * function App() {\n * return (\n * <SWRConfig value={{ use: [demoMiddleware] }}>\n * <YourApp />\n * </SWRConfig>\n * )\n * }\n */\nexport function createDemoMiddleware(options: CreateDemoMiddlewareOptions): Middleware {\n const { fixtures, isEnabled, delay = 0 } = options\n\n // Use the simpler middleware pattern that SWR expects\n const middleware: Middleware = (useSWRNext) => (key, fetcher, config) => {\n // Create an extended fetcher that checks for demo mode\n const extendedFetcher =\n fetcher === null\n ? null\n : async (...args: Parameters<typeof fetcher>) => {\n // Resolve the key if it's a function\n const resolvedKey = typeof key === 'function' ? key() : key\n\n // If no key, let SWR handle it\n if (resolvedKey === null || resolvedKey === undefined) {\n return fetcher(...args)\n }\n\n // If demo mode is not enabled, use original fetcher\n if (!isEnabled()) {\n return fetcher(...args)\n }\n\n // Normalize key for matching\n const keyToMatch =\n typeof resolvedKey === 'string' ? resolvedKey : (resolvedKey as unknown[])\n\n // Find matching fixture\n const match = findMatchingFixture(fixtures, keyToMatch)\n\n if (!match) {\n // No fixture found, use original fetcher\n return fetcher(...args)\n }\n\n const [handler, { params, normalizedKey }] = match\n\n // Apply delay if configured\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n\n // Build context\n const context: SWRFixtureContext = {\n key: resolvedKey,\n normalizedKey,\n params,\n match: { matched: true, params },\n }\n\n // Execute handler\n if (typeof handler === 'function') {\n return handler(context)\n }\n\n // Return static value\n return handler\n }\n\n return useSWRNext(key, extendedFetcher, config)\n }\n\n return middleware\n}\n","import type { RemoteSourceConfig } from './types'\n\n/**\n * Create a remote source configuration for fetching fixtures from DemoKit Cloud\n *\n * The SDK appends `/fixtures` to your apiUrl, so provide the versioned base URL.\n *\n * @example\n * ```typescript\n * // lib/demokit-config.ts\n * import { createRemoteSource } from '@demokit-ai/swr'\n *\n * // .env:\n * // VITE_DEMOKIT_API_URL=https://demokit-cloud.kasava.dev/api\n * // VITE_DEMOKIT_API_KEY=dk_live_xxxx\n *\n * export const demokitSource = createRemoteSource({\n * apiUrl: import.meta.env.VITE_DEMOKIT_API_URL,\n * apiKey: import.meta.env.VITE_DEMOKIT_API_KEY,\n * })\n *\n * // Then in your app:\n * import { demokitSource } from './lib/demokit-config'\n *\n * <DemoSWRProvider source={demokitSource}>\n * <SWRConfig>\n * <App />\n * </SWRConfig>\n * </DemoSWRProvider>\n * ```\n */\nexport function createRemoteSource(config: RemoteSourceConfig): RemoteSourceConfig {\n return {\n timeout: 10000,\n retry: true,\n maxRetries: 3,\n ...config,\n }\n}\n","'use client'\n\nimport { useContext, useCallback } from 'react'\nimport useSWRMutation, { type SWRMutationConfiguration, type SWRMutationResponse } from 'swr/mutation'\nimport { useSWRConfig } from 'swr'\nimport { DemoSWRContext } from './context'\nimport type { DemoSWRState, SWRMutationFixtureContext, SWRMutationFixtureHandler } from './types'\n\n/**\n * Hook to access DemoSWR state and controls\n *\n * @returns DemoSWR context value\n * @throws Error if used outside of DemoSWRProvider\n *\n * @example\n * function MyComponent() {\n * const { isDemoMode, setFixture } = useDemoSWR()\n *\n * // Dynamically add a fixture\n * const handleAddFixture = () => {\n * setFixture(['/api/users', 'custom'], { id: 'custom', name: 'Custom User' })\n * }\n *\n * return (\n * <button onClick={handleAddFixture}>Add Custom Fixture</button>\n * )\n * }\n */\nexport function useDemoSWR(): DemoSWRState {\n const context = useContext(DemoSWRContext)\n\n if (context === undefined) {\n throw new Error(\n 'useDemoSWR must be used within a DemoSWRProvider. ' +\n 'Make sure to wrap your app with <DemoSWRProvider>.'\n )\n }\n\n return context\n}\n\n/**\n * Hook to check if demo mode is enabled\n * Shorthand for useDemoSWR().isDemoMode\n *\n * @example\n * function MyComponent() {\n * const isDemoMode = useIsDemoSWRMode()\n *\n * return isDemoMode ? <DemoBadge /> : null\n * }\n */\nexport function useIsDemoSWRMode(): boolean {\n return useDemoSWR().isDemoMode\n}\n\n/**\n * Options for useDemoSWRMutation hook\n */\nexport interface UseDemoSWRMutationOptions<TData, TError, TArg>\n extends Omit<SWRMutationConfiguration<TData, TError, string, TArg>, 'fetcher'> {\n /**\n * The real mutation function to use when demo mode is disabled\n */\n fetcher: (key: string, options: { arg: TArg }) => Promise<TData>\n\n /**\n * Demo fixture handler for this mutation\n */\n demoFixture?: SWRMutationFixtureHandler<TData, TArg>\n\n /**\n * Delay in ms before returning demo data\n * @default 0\n */\n demoDelay?: number\n}\n\n/**\n * A mutation hook that automatically uses demo fixtures when demo mode is enabled\n *\n * Works with useSWRMutation from swr/mutation.\n *\n * @example\n * const { trigger: createUser, isMutating } = useDemoSWRMutation('/api/users', {\n * fetcher: async (key, { arg }) => api.createUser(arg),\n * demoFixture: ({ arg, mutate }) => {\n * // Create demo user\n * const newUser = { id: crypto.randomUUID(), ...arg }\n *\n * // Update the users cache\n * mutate('/api/users', (current: User[] = []) => [...current, newUser])\n *\n * return newUser\n * },\n * onSuccess: (data) => {\n * console.log('Created user:', data)\n * },\n * })\n *\n * // Use like normal useSWRMutation\n * createUser({ name: 'New User', email: 'user@example.com' })\n */\nexport function useDemoSWRMutation<TData = unknown, TError = unknown, TArg = unknown>(\n key: string,\n options: UseDemoSWRMutationOptions<TData, TError, TArg>\n): SWRMutationResponse<TData, TError, string, TArg> {\n const { fetcher, demoFixture, demoDelay = 0, ...mutationOptions } = options\n\n const { mutate } = useSWRConfig()\n\n // Try to get demo state - may not be in DemoSWRProvider context\n let isDemoMode = false\n try {\n const demoState = useDemoSWR()\n isDemoMode = demoState.isDemoMode\n } catch {\n // Not in DemoSWRProvider context, use real mutation\n }\n\n // Create the demo-aware mutation function\n const demoAwareFetcher = useCallback(\n async (mutationKey: string, { arg }: { arg: TArg }): Promise<TData> => {\n // If not in demo mode, use real mutation\n if (!isDemoMode) {\n return fetcher(mutationKey, { arg })\n }\n\n // Apply delay if configured\n if (demoDelay > 0) {\n await new Promise((resolve) => setTimeout(resolve, demoDelay))\n }\n\n // If a demo fixture is provided, use it\n if (demoFixture !== undefined) {\n const context: SWRMutationFixtureContext<TData, TArg> = {\n key: mutationKey,\n arg,\n currentData: undefined, // SWR mutation doesn't have direct access to current data\n mutate: mutate as SWRMutationFixtureContext<TData, TArg>['mutate'],\n }\n\n if (typeof demoFixture === 'function') {\n const fixtureFn = demoFixture as (\n context: SWRMutationFixtureContext<TData, TArg>\n ) => TData | Promise<TData>\n return fixtureFn(context)\n }\n return demoFixture as TData\n }\n\n // No fixture found, fall back to real mutation\n console.warn(\n `[DemoKit SWR] No mutation fixture found for \"${key}\". Using real mutation function.`\n )\n return fetcher(mutationKey, { arg })\n },\n [isDemoMode, fetcher, demoFixture, demoDelay, key, mutate]\n )\n\n return useSWRMutation(key, demoAwareFetcher, mutationOptions)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,IAAAA,gBAA6C;AAC7C,iBAA0B;;;ACD1B,mBAA8B;AAOvB,IAAM,qBAAiB,4BAAwC,MAAS;AAE/E,eAAe,cAAc;;;ACX7B,kBAA2D;AAYpD,SAAS,aAAa,KAAmC;AAC9D,MAAI,OAAO,QAAQ,UAAU;AAC3B,WAAO,CAAC,GAAG;AAAA,EACb;AAEA,SAAO,IAAI,IAAI,CAAC,YAAY;AAC1B,QAAI,YAAY,QAAQ,YAAY,QAAW;AAC7C,aAAO;AAAA,IACT;AACA,QAAI,OAAO,YAAY,UAAU;AAC/B,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT,CAAC;AACH;AAWO,SAAS,mBAAmB,SAA2B;AAE5D,MAAI,QAAQ,WAAW,GAAG,GAAG;AAC3B,QAAI;AACF,aAAO,KAAK,MAAM,OAAO;AAAA,IAC3B,QAAQ;AAAA,IAER;AAAA,EACF;AAGA,SAAO,CAAC,OAAO;AACjB;AAKO,SAAS,oBAAoB,UAA8D;AAChG,MAAI,oBAAoB,KAAK;AAC3B,WAAO;AAAA,EACT;AAEA,QAAM,MAAM,oBAAI,IAAiC;AACjD,aAAW,CAAC,SAAS,OAAO,KAAK,OAAO,QAAQ,QAAQ,GAAG;AACzD,QAAI,IAAI,mBAAmB,OAAO,GAAG,OAAO;AAAA,EAC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B;AAiDO,SAAS,mBACd,KACA,SACkD;AAClD,QAAM,EAAE,SAAS,aAAa,YAAY,GAAG,GAAG,gBAAgB,IAAI;AAEpE,QAAM,EAAE,OAAO,QAAI,0BAAa;AAGhC,MAAI,aAAa;AACjB,MAAI;AACF,UAAM,YAAY,WAAW;AAC7B,iBAAa,UAAU;AAAA,EACzB,QAAQ;AAAA,EAER;AAGA,QAAM,uBAAmB;AAAA,IACvB,OAAO,aAAqB,EAAE,IAAI,MAAqC;AAErE,UAAI,CAAC,YAAY;AACf,eAAO,QAAQ,aAAa,EAAE,IAAI,CAAC;AAAA,MACrC;AAGA,UAAI,YAAY,GAAG;AACjB,cAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,SAAS,CAAC;AAAA,MAC/D;AAGA,UAAI,gBAAgB,QAAW;AAC7B,cAAM,UAAkD;AAAA,UACtD,KAAK;AAAA,UACL;AAAA,UACA,aAAa;AAAA;AAAA,UACb;AAAA,QACF;AAEA,YAAI,OAAO,gBAAgB,YAAY;AACrC,gBAAM,YAAY;AAGlB,iBAAO,UAAU,OAAO;AAAA,QAC1B;AACA,eAAO;AAAA,MACT;AAGA,cAAQ;AAAA,QACN,gDAAgD,GAAG;AAAA,MACrD;AACA,aAAO,QAAQ,aAAa,EAAE,IAAI,CAAC;AAAA,IACrC;AAAA,IACA,CAAC,YAAY,SAAS,aAAa,WAAW,KAAK,MAAM;AAAA,EAC3D;AAEA,aAAO,gBAAAC,SAAe,KAAK,kBAAkB,eAAe;AAC9D;","names":["import_react","import_react","import_swr","useSWRMutation"]}
package/dist/index.d.cts CHANGED
@@ -149,6 +149,38 @@ interface DemoSWRState {
149
149
  */
150
150
  getMiddleware: () => Middleware;
151
151
  }
152
+ /**
153
+ * Configuration for remote fixture source (DemoKit Cloud)
154
+ */
155
+ interface RemoteSourceConfig {
156
+ /**
157
+ * DemoKit Cloud API URL (versioned base URL)
158
+ * The SDK will append `/fixtures` to this URL.
159
+ * @example 'https://demokit-cloud.kasava.dev/api'
160
+ * @default 'https://api.demokit.cloud/api'
161
+ */
162
+ apiUrl: string;
163
+ /**
164
+ * DemoKit Cloud API key
165
+ * Format: dk_live_xxx
166
+ */
167
+ apiKey: string;
168
+ /**
169
+ * Request timeout in milliseconds
170
+ * @default 10000
171
+ */
172
+ timeout?: number;
173
+ /**
174
+ * Whether to retry failed requests
175
+ * @default true
176
+ */
177
+ retry?: boolean;
178
+ /**
179
+ * Maximum number of retries
180
+ * @default 3
181
+ */
182
+ maxRetries?: number;
183
+ }
152
184
 
153
185
  /**
154
186
  * Provider component for DemoKit SWR integration
@@ -197,6 +229,37 @@ interface DemoSWRState {
197
229
  */
198
230
  declare function DemoSWRProvider({ children, fixtures, mutations, enabled, delay, fallback, swrConfig, }: DemoSWRProviderProps): react_jsx_runtime.JSX.Element;
199
231
 
232
+ /**
233
+ * Create a remote source configuration for fetching fixtures from DemoKit Cloud
234
+ *
235
+ * The SDK appends `/fixtures` to your apiUrl, so provide the versioned base URL.
236
+ *
237
+ * @example
238
+ * ```typescript
239
+ * // lib/demokit-config.ts
240
+ * import { createRemoteSource } from '@demokit-ai/swr'
241
+ *
242
+ * // .env:
243
+ * // VITE_DEMOKIT_API_URL=https://demokit-cloud.kasava.dev/api
244
+ * // VITE_DEMOKIT_API_KEY=dk_live_xxxx
245
+ *
246
+ * export const demokitSource = createRemoteSource({
247
+ * apiUrl: import.meta.env.VITE_DEMOKIT_API_URL,
248
+ * apiKey: import.meta.env.VITE_DEMOKIT_API_KEY,
249
+ * })
250
+ *
251
+ * // Then in your app:
252
+ * import { demokitSource } from './lib/demokit-config'
253
+ *
254
+ * <DemoSWRProvider source={demokitSource}>
255
+ * <SWRConfig>
256
+ * <App />
257
+ * </SWRConfig>
258
+ * </DemoSWRProvider>
259
+ * ```
260
+ */
261
+ declare function createRemoteSource(config: RemoteSourceConfig): RemoteSourceConfig;
262
+
200
263
  /**
201
264
  * Hook to access DemoSWR state and controls
202
265
  *
@@ -412,4 +475,4 @@ declare function findMatchingFixture(fixtures: SWRFixtureMap, key: string | unkn
412
475
  normalizedKey: QueryKey;
413
476
  }] | null;
414
477
 
415
- export { type CreateDemoFetcherOptions, type CreateDemoMiddlewareOptions, DemoSWRProvider, type DemoSWRProviderConfig, type DemoSWRProviderProps, type DemoSWRState, type SWRFixtureContext, type SWRFixtureHandler, type SWRFixtureMap, type SWRFixtureMapObject, type SWRMutationFixtureContext, type SWRMutationFixtureHandler, type SWRMutationFixtureMap, type SWRMutationFixtureMapObject, type UseDemoSWRMutationOptions, createDemoFetcher, createDemoMiddleware, defaultFetcher, findMatchingFixture, normalizeFixtureMap, normalizeKey, parsePatternString, useDemoSWR, useDemoSWRMutation, useIsDemoSWRMode };
478
+ export { type CreateDemoFetcherOptions, type CreateDemoMiddlewareOptions, DemoSWRProvider, type DemoSWRProviderConfig, type DemoSWRProviderProps, type DemoSWRState, type RemoteSourceConfig, type SWRFixtureContext, type SWRFixtureHandler, type SWRFixtureMap, type SWRFixtureMapObject, type SWRMutationFixtureContext, type SWRMutationFixtureHandler, type SWRMutationFixtureMap, type SWRMutationFixtureMapObject, type UseDemoSWRMutationOptions, createDemoFetcher, createDemoMiddleware, createRemoteSource, defaultFetcher, findMatchingFixture, normalizeFixtureMap, normalizeKey, parsePatternString, useDemoSWR, useDemoSWRMutation, useIsDemoSWRMode };
package/dist/index.d.ts CHANGED
@@ -149,6 +149,38 @@ interface DemoSWRState {
149
149
  */
150
150
  getMiddleware: () => Middleware;
151
151
  }
152
+ /**
153
+ * Configuration for remote fixture source (DemoKit Cloud)
154
+ */
155
+ interface RemoteSourceConfig {
156
+ /**
157
+ * DemoKit Cloud API URL (versioned base URL)
158
+ * The SDK will append `/fixtures` to this URL.
159
+ * @example 'https://demokit-cloud.kasava.dev/api'
160
+ * @default 'https://api.demokit.cloud/api'
161
+ */
162
+ apiUrl: string;
163
+ /**
164
+ * DemoKit Cloud API key
165
+ * Format: dk_live_xxx
166
+ */
167
+ apiKey: string;
168
+ /**
169
+ * Request timeout in milliseconds
170
+ * @default 10000
171
+ */
172
+ timeout?: number;
173
+ /**
174
+ * Whether to retry failed requests
175
+ * @default true
176
+ */
177
+ retry?: boolean;
178
+ /**
179
+ * Maximum number of retries
180
+ * @default 3
181
+ */
182
+ maxRetries?: number;
183
+ }
152
184
 
153
185
  /**
154
186
  * Provider component for DemoKit SWR integration
@@ -197,6 +229,37 @@ interface DemoSWRState {
197
229
  */
198
230
  declare function DemoSWRProvider({ children, fixtures, mutations, enabled, delay, fallback, swrConfig, }: DemoSWRProviderProps): react_jsx_runtime.JSX.Element;
199
231
 
232
+ /**
233
+ * Create a remote source configuration for fetching fixtures from DemoKit Cloud
234
+ *
235
+ * The SDK appends `/fixtures` to your apiUrl, so provide the versioned base URL.
236
+ *
237
+ * @example
238
+ * ```typescript
239
+ * // lib/demokit-config.ts
240
+ * import { createRemoteSource } from '@demokit-ai/swr'
241
+ *
242
+ * // .env:
243
+ * // VITE_DEMOKIT_API_URL=https://demokit-cloud.kasava.dev/api
244
+ * // VITE_DEMOKIT_API_KEY=dk_live_xxxx
245
+ *
246
+ * export const demokitSource = createRemoteSource({
247
+ * apiUrl: import.meta.env.VITE_DEMOKIT_API_URL,
248
+ * apiKey: import.meta.env.VITE_DEMOKIT_API_KEY,
249
+ * })
250
+ *
251
+ * // Then in your app:
252
+ * import { demokitSource } from './lib/demokit-config'
253
+ *
254
+ * <DemoSWRProvider source={demokitSource}>
255
+ * <SWRConfig>
256
+ * <App />
257
+ * </SWRConfig>
258
+ * </DemoSWRProvider>
259
+ * ```
260
+ */
261
+ declare function createRemoteSource(config: RemoteSourceConfig): RemoteSourceConfig;
262
+
200
263
  /**
201
264
  * Hook to access DemoSWR state and controls
202
265
  *
@@ -412,4 +475,4 @@ declare function findMatchingFixture(fixtures: SWRFixtureMap, key: string | unkn
412
475
  normalizedKey: QueryKey;
413
476
  }] | null;
414
477
 
415
- export { type CreateDemoFetcherOptions, type CreateDemoMiddlewareOptions, DemoSWRProvider, type DemoSWRProviderConfig, type DemoSWRProviderProps, type DemoSWRState, type SWRFixtureContext, type SWRFixtureHandler, type SWRFixtureMap, type SWRFixtureMapObject, type SWRMutationFixtureContext, type SWRMutationFixtureHandler, type SWRMutationFixtureMap, type SWRMutationFixtureMapObject, type UseDemoSWRMutationOptions, createDemoFetcher, createDemoMiddleware, defaultFetcher, findMatchingFixture, normalizeFixtureMap, normalizeKey, parsePatternString, useDemoSWR, useDemoSWRMutation, useIsDemoSWRMode };
478
+ export { type CreateDemoFetcherOptions, type CreateDemoMiddlewareOptions, DemoSWRProvider, type DemoSWRProviderConfig, type DemoSWRProviderProps, type DemoSWRState, type RemoteSourceConfig, type SWRFixtureContext, type SWRFixtureHandler, type SWRFixtureMap, type SWRFixtureMapObject, type SWRMutationFixtureContext, type SWRMutationFixtureHandler, type SWRMutationFixtureMap, type SWRMutationFixtureMapObject, type UseDemoSWRMutationOptions, createDemoFetcher, createDemoMiddleware, createRemoteSource, defaultFetcher, findMatchingFixture, normalizeFixtureMap, normalizeKey, parsePatternString, useDemoSWR, useDemoSWRMutation, useIsDemoSWRMode };
package/dist/index.js CHANGED
@@ -1,13 +1,14 @@
1
- import { createContext, useRef, useMemo, useCallback, useContext } from 'react';
2
- import { SWRConfig, useSWRConfig } from 'swr';
3
- import { findMatchingQueryKeyPattern } from '@demokit-ai/core';
4
- export { matchQueryKey } from '@demokit-ai/core';
5
- import { jsx } from 'react/jsx-runtime';
6
- import useSWRMutation from 'swr/mutation';
7
-
8
1
  // src/provider.tsx
2
+ import { useMemo, useRef, useCallback } from "react";
3
+ import { SWRConfig } from "swr";
4
+
5
+ // src/context.ts
6
+ import { createContext } from "react";
9
7
  var DemoSWRContext = createContext(void 0);
10
8
  DemoSWRContext.displayName = "DemoSWRContext";
9
+
10
+ // src/matcher.ts
11
+ import { matchQueryKey, findMatchingQueryKeyPattern } from "@demokit-ai/core";
11
12
  function normalizeKey(key) {
12
13
  if (typeof key === "string") {
13
14
  return [key];
@@ -132,6 +133,9 @@ function createDemoMiddleware(options) {
132
133
  };
133
134
  return middleware;
134
135
  }
136
+
137
+ // src/provider.tsx
138
+ import { jsx } from "react/jsx-runtime";
135
139
  function DemoSWRProvider({
136
140
  children,
137
141
  fixtures = /* @__PURE__ */ new Map(),
@@ -216,6 +220,21 @@ function DemoSWRProvider({
216
220
  );
217
221
  return /* @__PURE__ */ jsx(DemoSWRContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsx(SWRConfig, { value: config, children }) });
218
222
  }
223
+
224
+ // src/config.ts
225
+ function createRemoteSource(config) {
226
+ return {
227
+ timeout: 1e4,
228
+ retry: true,
229
+ maxRetries: 3,
230
+ ...config
231
+ };
232
+ }
233
+
234
+ // src/hooks.ts
235
+ import { useContext, useCallback as useCallback2 } from "react";
236
+ import useSWRMutation from "swr/mutation";
237
+ import { useSWRConfig } from "swr";
219
238
  function useDemoSWR() {
220
239
  const context = useContext(DemoSWRContext);
221
240
  if (context === void 0) {
@@ -237,7 +256,7 @@ function useDemoSWRMutation(key, options) {
237
256
  isDemoMode = demoState.isDemoMode;
238
257
  } catch {
239
258
  }
240
- const demoAwareFetcher = useCallback(
259
+ const demoAwareFetcher = useCallback2(
241
260
  async (mutationKey, { arg }) => {
242
261
  if (!isDemoMode) {
243
262
  return fetcher(mutationKey, { arg });
@@ -268,7 +287,19 @@ function useDemoSWRMutation(key, options) {
268
287
  );
269
288
  return useSWRMutation(key, demoAwareFetcher, mutationOptions);
270
289
  }
271
-
272
- export { DemoSWRProvider, createDemoFetcher, createDemoMiddleware, defaultFetcher, findMatchingFixture, normalizeFixtureMap, normalizeKey, parsePatternString, useDemoSWR, useDemoSWRMutation, useIsDemoSWRMode };
273
- //# sourceMappingURL=index.js.map
290
+ export {
291
+ DemoSWRProvider,
292
+ createDemoFetcher,
293
+ createDemoMiddleware,
294
+ createRemoteSource,
295
+ defaultFetcher,
296
+ findMatchingFixture,
297
+ matchQueryKey,
298
+ normalizeFixtureMap,
299
+ normalizeKey,
300
+ parsePatternString,
301
+ useDemoSWR,
302
+ useDemoSWRMutation,
303
+ useIsDemoSWRMode
304
+ };
274
305
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/context.ts","../src/matcher.ts","../src/fetcher.ts","../src/middleware.ts","../src/provider.tsx","../src/hooks.ts"],"names":["useCallback"],"mappings":";;;;;;;;AASO,IAAM,cAAA,GAAiB,cAAwC,MAAS,CAAA;AAE/E,cAAA,CAAe,WAAA,GAAc,gBAAA;ACCtB,SAAS,aAAa,GAAA,EAAmC;AAC9D,EAAA,IAAI,OAAO,QAAQ,QAAA,EAAU;AAC3B,IAAA,OAAO,CAAC,GAAG,CAAA;AAAA,EACb;AAEA,EAAA,OAAO,GAAA,CAAI,GAAA,CAAI,CAAC,OAAA,KAAY;AAC1B,IAAA,IAAI,OAAA,KAAY,IAAA,IAAQ,OAAA,KAAY,MAAA,EAAW;AAC7C,MAAA,OAAO,OAAA;AAAA,IACT;AACA,IAAA,IAAI,OAAO,YAAY,QAAA,EAAU;AAC/B,MAAA,OAAO,OAAA;AAAA,IACT;AACA,IAAA,OAAO,OAAA;AAAA,EACT,CAAC,CAAA;AACH;AAWO,SAAS,mBAAmB,OAAA,EAA2B;AAE5D,EAAA,IAAI,OAAA,CAAQ,UAAA,CAAW,GAAG,CAAA,EAAG;AAC3B,IAAA,IAAI;AACF,MAAA,OAAO,IAAA,CAAK,MAAM,OAAO,CAAA;AAAA,IAC3B,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF;AAGA,EAAA,OAAO,CAAC,OAAO,CAAA;AACjB;AAKO,SAAS,oBAAoB,QAAA,EAA8D;AAChG,EAAA,IAAI,oBAAoB,GAAA,EAAK;AAC3B,IAAA,OAAO,QAAA;AAAA,EACT;AAEA,EAAA,MAAM,GAAA,uBAAU,GAAA,EAAiC;AACjD,EAAA,KAAA,MAAW,CAAC,OAAA,EAAS,OAAO,KAAK,MAAA,CAAO,OAAA,CAAQ,QAAQ,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GAAmBA,WAAAA;AAAA,IACvB,OAAO,WAAA,EAAqB,EAAE,GAAA,EAAI,KAAqC;AAErE,MAAA,IAAI,CAAC,UAAA,EAAY;AACf,QAAA,OAAO,OAAA,CAAQ,WAAA,EAAa,EAAE,GAAA,EAAK,CAAA;AAAA,MACrC;AAGA,MAAA,IAAI,YAAY,CAAA,EAAG;AACjB,QAAA,MAAM,IAAI,OAAA,CAAQ,CAAC,YAAY,UAAA,CAAW,OAAA,EAAS,SAAS,CAAC,CAAA;AAAA,MAC/D;AAGA,MAAA,IAAI,gBAAgB,MAAA,EAAW;AAC7B,QAAA,MAAM,OAAA,GAAkD;AAAA,UACtD,GAAA,EAAK,WAAA;AAAA,UACL,GAAA;AAAA,UACA,WAAA,EAAa,MAAA;AAAA;AAAA,UACb;AAAA,SACF;AAEA,QAAA,IAAI,OAAO,gBAAgB,UAAA,EAAY;AACrC,UAAA,MAAM,SAAA,GAAY,WAAA;AAGlB,UAAA,OAAO,UAAU,OAAO,CAAA;AAAA,QAC1B;AACA,QAAA,OAAO,WAAA;AAAA,MACT;AAGA,MAAA,OAAA,CAAQ,IAAA;AAAA,QACN,gDAAgD,GAAG,CAAA,gCAAA;AAAA,OACrD;AACA,MAAA,OAAO,OAAA,CAAQ,WAAA,EAAa,EAAE,GAAA,EAAK,CAAA;AAAA,IACrC,CAAA;AAAA,IACA,CAAC,UAAA,EAAY,OAAA,EAAS,WAAA,EAAa,SAAA,EAAW,KAAK,MAAM;AAAA,GAC3D;AAEA,EAAA,OAAO,cAAA,CAAe,GAAA,EAAK,gBAAA,EAAkB,eAAe,CAAA;AAC9D","file":"index.js","sourcesContent":["'use client'\n\nimport { createContext } from 'react'\nimport type { DemoSWRState } from './types'\n\n/**\n * Context for DemoSWR state\n * @internal\n */\nexport const DemoSWRContext = createContext<DemoSWRState | undefined>(undefined)\n\nDemoSWRContext.displayName = 'DemoSWRContext'\n","import { matchQueryKey, findMatchingQueryKeyPattern } from '@demokit-ai/core'\nimport type { QueryKey } from '@demokit-ai/core'\nimport type { SWRFixtureHandler, SWRFixtureMap, SWRFixtureMapObject } from './types'\n\n/**\n * Normalize an SWR key to a QueryKey for matching\n *\n * SWR keys can be:\n * - Strings: '/api/users' -> ['/api/users']\n * - Arrays: ['/api/users', id] -> ['/api/users', id]\n * - Functions that return keys (not handled here)\n */\nexport function normalizeKey(key: string | unknown[]): QueryKey {\n if (typeof key === 'string') {\n return [key]\n }\n\n return key.map((element) => {\n if (element === null || element === undefined) {\n return element\n }\n if (typeof element === 'object') {\n return element as Record<string, unknown>\n }\n return element as string | number | boolean\n })\n}\n\n/**\n * Parse a JSON string pattern into a QueryKey\n * Handles both array notation and simple string patterns\n *\n * @example\n * parsePatternString('[\"/api/users\"]') // ['/api/users']\n * parsePatternString('[\"/api/users\", \":id\"]') // ['/api/users', ':id']\n * parsePatternString('/api/users') // ['/api/users']\n */\nexport function parsePatternString(pattern: string): QueryKey {\n // Try to parse as JSON array\n if (pattern.startsWith('[')) {\n try {\n return JSON.parse(pattern) as QueryKey\n } catch {\n // Fall through to simple string\n }\n }\n\n // Simple string becomes single-element array\n return [pattern]\n}\n\n/**\n * Convert object-based fixture map to Map-based fixture map\n */\nexport function normalizeFixtureMap(fixtures: SWRFixtureMapObject | SWRFixtureMap): SWRFixtureMap {\n if (fixtures instanceof Map) {\n return fixtures\n }\n\n const map = new Map<QueryKey, SWRFixtureHandler>()\n for (const [pattern, handler] of Object.entries(fixtures)) {\n map.set(parsePatternString(pattern), handler)\n }\n return map\n}\n\n/**\n * Find a matching fixture for an SWR key\n *\n * @param fixtures - Map of key patterns to handlers\n * @param key - The SWR key to match\n * @returns Tuple of [handler, match result] or null if no match\n */\nexport function findMatchingFixture(\n fixtures: SWRFixtureMap,\n key: string | unknown[]\n): [SWRFixtureHandler, { params: Record<string, unknown>; normalizedKey: QueryKey }] | null {\n const normalizedKey = normalizeKey(key)\n const result = findMatchingQueryKeyPattern(fixtures, normalizedKey)\n\n if (result) {\n const [, handler, matchResult] = result\n return [handler, { params: matchResult.params, normalizedKey }]\n }\n\n return null\n}\n\n/**\n * Re-export the matchQueryKey function for direct use\n */\nexport { matchQueryKey }","import type { QueryKey } from '@demokit-ai/core'\nimport type { SWRFixtureMap, SWRFixtureContext } from './types'\nimport { findMatchingFixture, normalizeKey } from './matcher'\n\n/**\n * Options for creating a demo-aware fetcher\n */\nexport interface CreateDemoFetcherOptions {\n /**\n * Map of key patterns to fixture handlers\n */\n fixtures: SWRFixtureMap\n\n /**\n * Function to check if demo mode is enabled\n */\n isEnabled: () => boolean\n\n /**\n * Delay in ms before returning fixture data\n * @default 0\n */\n delay?: number\n\n /**\n * Fallback fetcher to use when demo mode is disabled\n * or no fixture matches\n */\n fallbackFetcher?: <T>(key: string | unknown[]) => Promise<T>\n}\n\n/**\n * Create a demo-aware fetcher function for SWR\n *\n * This fetcher intercepts requests when demo mode is enabled\n * and returns fixture data instead of making real API calls.\n *\n * @example\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'User' })],\n * ])\n *\n * const fetcher = createDemoFetcher({\n * fixtures,\n * isEnabled: () => isDemoMode,\n * delay: 100,\n * })\n *\n * // Use with SWR\n * const { data } = useSWR('/api/users', fetcher)\n */\nexport function createDemoFetcher(options: CreateDemoFetcherOptions) {\n const { fixtures, isEnabled, delay = 0, fallbackFetcher } = options\n\n return async function demoFetcher<TData = unknown>(key: string | unknown[]): Promise<TData> {\n // If demo mode is not enabled, use fallback\n if (!isEnabled()) {\n if (fallbackFetcher) {\n return fallbackFetcher<TData>(key)\n }\n throw new Error(\n `[DemoKit SWR] No fallback fetcher provided and demo mode is disabled. ` +\n `Key: ${JSON.stringify(key)}`\n )\n }\n\n // Find matching fixture\n const match = findMatchingFixture(fixtures, key)\n\n if (!match) {\n // No fixture found, try fallback\n if (fallbackFetcher) {\n return fallbackFetcher<TData>(key)\n }\n throw new Error(`[DemoKit SWR] No fixture found for key: ${JSON.stringify(key)}`)\n }\n\n const [handler, { params, normalizedKey }] = match\n\n // Apply delay if configured\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n\n // Build context\n const context: SWRFixtureContext = {\n key,\n normalizedKey,\n params,\n match: { matched: true, params },\n }\n\n // Execute handler\n if (typeof handler === 'function') {\n return handler(context) as TData\n }\n\n // Return static value\n return handler as TData\n }\n}\n\n/**\n * Default fetcher that uses fetch API\n * Used as fallback when demo mode is disabled\n */\nexport async function defaultFetcher<TData = unknown>(key: string | unknown[]): Promise<TData> {\n const url = typeof key === 'string' ? key : String(key[0])\n const response = await fetch(url)\n\n if (!response.ok) {\n const error = new Error('An error occurred while fetching the data.')\n throw error\n }\n\n return response.json()\n}\n","import type { Middleware } from 'swr'\nimport type { SWRFixtureMap, SWRFixtureContext } from './types'\nimport { findMatchingFixture } from './matcher'\n\n/**\n * Options for creating the demo middleware\n */\nexport interface CreateDemoMiddlewareOptions {\n /**\n * Map of key patterns to fixture handlers\n */\n fixtures: SWRFixtureMap\n\n /**\n * Function to check if demo mode is enabled\n */\n isEnabled: () => boolean\n\n /**\n * Delay in ms before returning fixture data\n * @default 0\n */\n delay?: number\n}\n\n/**\n * Create a demo-aware SWR middleware\n *\n * This middleware intercepts SWR requests when demo mode is enabled\n * and returns fixture data instead of using the original fetcher.\n *\n * @example\n * import { SWRConfig } from 'swr'\n * import { createDemoMiddleware } from '@demokit-ai/swr'\n *\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'User' })],\n * ])\n *\n * const demoMiddleware = createDemoMiddleware({\n * fixtures,\n * isEnabled: () => isDemoMode,\n * delay: 100,\n * })\n *\n * function App() {\n * return (\n * <SWRConfig value={{ use: [demoMiddleware] }}>\n * <YourApp />\n * </SWRConfig>\n * )\n * }\n */\nexport function createDemoMiddleware(options: CreateDemoMiddlewareOptions): Middleware {\n const { fixtures, isEnabled, delay = 0 } = options\n\n // Use the simpler middleware pattern that SWR expects\n const middleware: Middleware = (useSWRNext) => (key, fetcher, config) => {\n // Create an extended fetcher that checks for demo mode\n const extendedFetcher =\n fetcher === null\n ? null\n : async (...args: Parameters<typeof fetcher>) => {\n // Resolve the key if it's a function\n const resolvedKey = typeof key === 'function' ? key() : key\n\n // If no key, let SWR handle it\n if (resolvedKey === null || resolvedKey === undefined) {\n return fetcher(...args)\n }\n\n // If demo mode is not enabled, use original fetcher\n if (!isEnabled()) {\n return fetcher(...args)\n }\n\n // Normalize key for matching\n const keyToMatch =\n typeof resolvedKey === 'string' ? resolvedKey : (resolvedKey as unknown[])\n\n // Find matching fixture\n const match = findMatchingFixture(fixtures, keyToMatch)\n\n if (!match) {\n // No fixture found, use original fetcher\n return fetcher(...args)\n }\n\n const [handler, { params, normalizedKey }] = match\n\n // Apply delay if configured\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n\n // Build context\n const context: SWRFixtureContext = {\n key: resolvedKey,\n normalizedKey,\n params,\n match: { matched: true, params },\n }\n\n // Execute handler\n if (typeof handler === 'function') {\n return handler(context)\n }\n\n // Return static value\n return handler\n }\n\n return useSWRNext(key, extendedFetcher, config)\n }\n\n return middleware\n}\n","'use client'\n\nimport { useMemo, useRef, useCallback } from 'react'\nimport { SWRConfig } from 'swr'\nimport type { QueryKey } from '@demokit-ai/core'\nimport { DemoSWRContext } from './context'\nimport { createDemoFetcher, defaultFetcher } from './fetcher'\nimport { createDemoMiddleware } from './middleware'\nimport { normalizeFixtureMap } from './matcher'\nimport type {\n DemoSWRProviderProps,\n SWRFixtureHandler,\n SWRFixtureMap,\n SWRMutationFixtureHandler,\n SWRMutationFixtureMap,\n DemoSWRState,\n} from './types'\n\n/**\n * Provider component for DemoKit SWR integration\n *\n * Wraps SWRConfig and intercepts fetches when demo mode is enabled.\n * Uses SWR's middleware pattern for maximum flexibility.\n *\n * @example\n * // With object-based fixtures\n * <DemoSWRProvider\n * enabled={true}\n * fixtures={{\n * '/api/users': [{ id: '1', name: 'Demo User' }],\n * '[\"/api/users\", \":id\"]': ({ params }) => ({ id: params.id, name: 'Demo User' }),\n * '[\"/api/projects\", { status: \":status\" }]': ({ params }) => [\n * { id: '1', name: 'Project', status: params.status },\n * ],\n * }}\n * delay={100}\n * >\n * <App />\n * </DemoSWRProvider>\n *\n * @example\n * // With Map-based fixtures\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'Demo User' })],\n * ])\n *\n * <DemoSWRProvider enabled={true} fixtures={fixtures}>\n * <App />\n * </DemoSWRProvider>\n *\n * @example\n * // With cache seeding via fallback\n * <DemoSWRProvider\n * enabled={true}\n * fixtures={fixtures}\n * fallback={{\n * '/api/users': [{ id: '1', name: 'Pre-loaded User' }],\n * }}\n * >\n * <App />\n * </DemoSWRProvider>\n */\nexport function DemoSWRProvider({\n children,\n fixtures = new Map(),\n mutations = new Map(),\n enabled = false,\n delay = 0,\n fallback = {},\n swrConfig = {},\n}: DemoSWRProviderProps) {\n // Normalize fixtures\n const fixturesRef = useRef<SWRFixtureMap>(normalizeFixtureMap(fixtures))\n const mutationFixturesRef = useRef<SWRMutationFixtureMap>(\n mutations instanceof Map ? mutations : new Map(Object.entries(mutations))\n )\n\n const isDemoMode = enabled\n\n // Create demo middleware\n const demoMiddleware = useMemo(\n () =>\n createDemoMiddleware({\n fixtures: fixturesRef.current,\n isEnabled: () => isDemoMode,\n delay,\n }),\n [isDemoMode, delay]\n )\n\n // Create demo fetcher (for direct use)\n const demoFetcher = useMemo(\n () =>\n createDemoFetcher({\n fixtures: fixturesRef.current,\n isEnabled: () => isDemoMode,\n delay,\n fallbackFetcher: defaultFetcher,\n }),\n [isDemoMode, delay]\n )\n\n // Build fallback data from static fixtures + provided fallback\n const combinedFallback = useMemo(() => {\n if (!isDemoMode) return swrConfig.fallback || {}\n\n const staticFixtures: Record<string, unknown> = {}\n\n // Add static fixture values to fallback\n for (const [pattern, handler] of fixturesRef.current) {\n if (typeof handler !== 'function') {\n // Use the pattern as key for static fixtures\n const key = pattern.length === 1 ? String(pattern[0]) : JSON.stringify(pattern)\n staticFixtures[key] = handler\n }\n }\n\n return {\n ...staticFixtures,\n ...fallback,\n ...(swrConfig.fallback || {}),\n }\n }, [isDemoMode, fallback, swrConfig.fallback])\n\n // Build SWR config\n const config = useMemo(\n () => ({\n ...swrConfig,\n use: [...(swrConfig.use || []), demoMiddleware],\n fallback: combinedFallback,\n // In demo mode, don't retry and keep data fresh longer\n ...(isDemoMode\n ? {\n revalidateOnFocus: false,\n revalidateOnReconnect: false,\n shouldRetryOnError: false,\n }\n : {}),\n }),\n [swrConfig, demoMiddleware, combinedFallback, isDemoMode]\n )\n\n // Context value with manipulation methods\n const getFetcher = useCallback(() => demoFetcher, [demoFetcher])\n const getMiddleware = useCallback(() => demoMiddleware, [demoMiddleware])\n\n const contextValue = useMemo<DemoSWRState>(\n () => ({\n isDemoMode,\n\n setFixture: (pattern: QueryKey, handler: SWRFixtureHandler) => {\n fixturesRef.current.set(pattern, handler)\n },\n\n removeFixture: (pattern: QueryKey) => {\n fixturesRef.current.delete(pattern)\n },\n\n setMutationFixture: (name: string, handler: SWRMutationFixtureHandler) => {\n mutationFixturesRef.current.set(name, handler)\n },\n\n removeMutationFixture: (name: string) => {\n mutationFixturesRef.current.delete(name)\n },\n\n getFetcher,\n getMiddleware,\n }),\n [isDemoMode, getFetcher, getMiddleware]\n )\n\n return (\n <DemoSWRContext.Provider value={contextValue}>\n <SWRConfig value={config}>{children}</SWRConfig>\n </DemoSWRContext.Provider>\n )\n}\n","'use client'\n\nimport { useContext, useCallback } from 'react'\nimport useSWRMutation, { type SWRMutationConfiguration, type SWRMutationResponse } from 'swr/mutation'\nimport { useSWRConfig } from 'swr'\nimport { DemoSWRContext } from './context'\nimport type { DemoSWRState, SWRMutationFixtureContext, SWRMutationFixtureHandler } from './types'\n\n/**\n * Hook to access DemoSWR state and controls\n *\n * @returns DemoSWR context value\n * @throws Error if used outside of DemoSWRProvider\n *\n * @example\n * function MyComponent() {\n * const { isDemoMode, setFixture } = useDemoSWR()\n *\n * // Dynamically add a fixture\n * const handleAddFixture = () => {\n * setFixture(['/api/users', 'custom'], { id: 'custom', name: 'Custom User' })\n * }\n *\n * return (\n * <button onClick={handleAddFixture}>Add Custom Fixture</button>\n * )\n * }\n */\nexport function useDemoSWR(): DemoSWRState {\n const context = useContext(DemoSWRContext)\n\n if (context === undefined) {\n throw new Error(\n 'useDemoSWR must be used within a DemoSWRProvider. ' +\n 'Make sure to wrap your app with <DemoSWRProvider>.'\n )\n }\n\n return context\n}\n\n/**\n * Hook to check if demo mode is enabled\n * Shorthand for useDemoSWR().isDemoMode\n *\n * @example\n * function MyComponent() {\n * const isDemoMode = useIsDemoSWRMode()\n *\n * return isDemoMode ? <DemoBadge /> : null\n * }\n */\nexport function useIsDemoSWRMode(): boolean {\n return useDemoSWR().isDemoMode\n}\n\n/**\n * Options for useDemoSWRMutation hook\n */\nexport interface UseDemoSWRMutationOptions<TData, TError, TArg>\n extends Omit<SWRMutationConfiguration<TData, TError, string, TArg>, 'fetcher'> {\n /**\n * The real mutation function to use when demo mode is disabled\n */\n fetcher: (key: string, options: { arg: TArg }) => Promise<TData>\n\n /**\n * Demo fixture handler for this mutation\n */\n demoFixture?: SWRMutationFixtureHandler<TData, TArg>\n\n /**\n * Delay in ms before returning demo data\n * @default 0\n */\n demoDelay?: number\n}\n\n/**\n * A mutation hook that automatically uses demo fixtures when demo mode is enabled\n *\n * Works with useSWRMutation from swr/mutation.\n *\n * @example\n * const { trigger: createUser, isMutating } = useDemoSWRMutation('/api/users', {\n * fetcher: async (key, { arg }) => api.createUser(arg),\n * demoFixture: ({ arg, mutate }) => {\n * // Create demo user\n * const newUser = { id: crypto.randomUUID(), ...arg }\n *\n * // Update the users cache\n * mutate('/api/users', (current: User[] = []) => [...current, newUser])\n *\n * return newUser\n * },\n * onSuccess: (data) => {\n * console.log('Created user:', data)\n * },\n * })\n *\n * // Use like normal useSWRMutation\n * createUser({ name: 'New User', email: 'user@example.com' })\n */\nexport function useDemoSWRMutation<TData = unknown, TError = unknown, TArg = unknown>(\n key: string,\n options: UseDemoSWRMutationOptions<TData, TError, TArg>\n): SWRMutationResponse<TData, TError, string, TArg> {\n const { fetcher, demoFixture, demoDelay = 0, ...mutationOptions } = options\n\n const { mutate } = useSWRConfig()\n\n // Try to get demo state - may not be in DemoSWRProvider context\n let isDemoMode = false\n try {\n const demoState = useDemoSWR()\n isDemoMode = demoState.isDemoMode\n } catch {\n // Not in DemoSWRProvider context, use real mutation\n }\n\n // Create the demo-aware mutation function\n const demoAwareFetcher = useCallback(\n async (mutationKey: string, { arg }: { arg: TArg }): Promise<TData> => {\n // If not in demo mode, use real mutation\n if (!isDemoMode) {\n return fetcher(mutationKey, { arg })\n }\n\n // Apply delay if configured\n if (demoDelay > 0) {\n await new Promise((resolve) => setTimeout(resolve, demoDelay))\n }\n\n // If a demo fixture is provided, use it\n if (demoFixture !== undefined) {\n const context: SWRMutationFixtureContext<TData, TArg> = {\n key: mutationKey,\n arg,\n currentData: undefined, // SWR mutation doesn't have direct access to current data\n mutate: mutate as SWRMutationFixtureContext<TData, TArg>['mutate'],\n }\n\n if (typeof demoFixture === 'function') {\n const fixtureFn = demoFixture as (\n context: SWRMutationFixtureContext<TData, TArg>\n ) => TData | Promise<TData>\n return fixtureFn(context)\n }\n return demoFixture as TData\n }\n\n // No fixture found, fall back to real mutation\n console.warn(\n `[DemoKit SWR] No mutation fixture found for \"${key}\". Using real mutation function.`\n )\n return fetcher(mutationKey, { arg })\n },\n [isDemoMode, fetcher, demoFixture, demoDelay, key, mutate]\n )\n\n return useSWRMutation(key, demoAwareFetcher, mutationOptions)\n}\n"]}
1
+ {"version":3,"sources":["../src/provider.tsx","../src/context.ts","../src/matcher.ts","../src/fetcher.ts","../src/middleware.ts","../src/config.ts","../src/hooks.ts"],"sourcesContent":["'use client'\n\nimport { useMemo, useRef, useCallback } from 'react'\nimport { SWRConfig } from 'swr'\nimport type { QueryKey } from '@demokit-ai/core'\nimport { DemoSWRContext } from './context'\nimport { createDemoFetcher, defaultFetcher } from './fetcher'\nimport { createDemoMiddleware } from './middleware'\nimport { normalizeFixtureMap } from './matcher'\nimport type {\n DemoSWRProviderProps,\n SWRFixtureHandler,\n SWRFixtureMap,\n SWRMutationFixtureHandler,\n SWRMutationFixtureMap,\n DemoSWRState,\n} from './types'\n\n/**\n * Provider component for DemoKit SWR integration\n *\n * Wraps SWRConfig and intercepts fetches when demo mode is enabled.\n * Uses SWR's middleware pattern for maximum flexibility.\n *\n * @example\n * // With object-based fixtures\n * <DemoSWRProvider\n * enabled={true}\n * fixtures={{\n * '/api/users': [{ id: '1', name: 'Demo User' }],\n * '[\"/api/users\", \":id\"]': ({ params }) => ({ id: params.id, name: 'Demo User' }),\n * '[\"/api/projects\", { status: \":status\" }]': ({ params }) => [\n * { id: '1', name: 'Project', status: params.status },\n * ],\n * }}\n * delay={100}\n * >\n * <App />\n * </DemoSWRProvider>\n *\n * @example\n * // With Map-based fixtures\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'Demo User' })],\n * ])\n *\n * <DemoSWRProvider enabled={true} fixtures={fixtures}>\n * <App />\n * </DemoSWRProvider>\n *\n * @example\n * // With cache seeding via fallback\n * <DemoSWRProvider\n * enabled={true}\n * fixtures={fixtures}\n * fallback={{\n * '/api/users': [{ id: '1', name: 'Pre-loaded User' }],\n * }}\n * >\n * <App />\n * </DemoSWRProvider>\n */\nexport function DemoSWRProvider({\n children,\n fixtures = new Map(),\n mutations = new Map(),\n enabled = false,\n delay = 0,\n fallback = {},\n swrConfig = {},\n}: DemoSWRProviderProps) {\n // Normalize fixtures\n const fixturesRef = useRef<SWRFixtureMap>(normalizeFixtureMap(fixtures))\n const mutationFixturesRef = useRef<SWRMutationFixtureMap>(\n mutations instanceof Map ? mutations : new Map(Object.entries(mutations))\n )\n\n const isDemoMode = enabled\n\n // Create demo middleware\n const demoMiddleware = useMemo(\n () =>\n createDemoMiddleware({\n fixtures: fixturesRef.current,\n isEnabled: () => isDemoMode,\n delay,\n }),\n [isDemoMode, delay]\n )\n\n // Create demo fetcher (for direct use)\n const demoFetcher = useMemo(\n () =>\n createDemoFetcher({\n fixtures: fixturesRef.current,\n isEnabled: () => isDemoMode,\n delay,\n fallbackFetcher: defaultFetcher,\n }),\n [isDemoMode, delay]\n )\n\n // Build fallback data from static fixtures + provided fallback\n const combinedFallback = useMemo(() => {\n if (!isDemoMode) return swrConfig.fallback || {}\n\n const staticFixtures: Record<string, unknown> = {}\n\n // Add static fixture values to fallback\n for (const [pattern, handler] of fixturesRef.current) {\n if (typeof handler !== 'function') {\n // Use the pattern as key for static fixtures\n const key = pattern.length === 1 ? String(pattern[0]) : JSON.stringify(pattern)\n staticFixtures[key] = handler\n }\n }\n\n return {\n ...staticFixtures,\n ...fallback,\n ...(swrConfig.fallback || {}),\n }\n }, [isDemoMode, fallback, swrConfig.fallback])\n\n // Build SWR config\n const config = useMemo(\n () => ({\n ...swrConfig,\n use: [...(swrConfig.use || []), demoMiddleware],\n fallback: combinedFallback,\n // In demo mode, don't retry and keep data fresh longer\n ...(isDemoMode\n ? {\n revalidateOnFocus: false,\n revalidateOnReconnect: false,\n shouldRetryOnError: false,\n }\n : {}),\n }),\n [swrConfig, demoMiddleware, combinedFallback, isDemoMode]\n )\n\n // Context value with manipulation methods\n const getFetcher = useCallback(() => demoFetcher, [demoFetcher])\n const getMiddleware = useCallback(() => demoMiddleware, [demoMiddleware])\n\n const contextValue = useMemo<DemoSWRState>(\n () => ({\n isDemoMode,\n\n setFixture: (pattern: QueryKey, handler: SWRFixtureHandler) => {\n fixturesRef.current.set(pattern, handler)\n },\n\n removeFixture: (pattern: QueryKey) => {\n fixturesRef.current.delete(pattern)\n },\n\n setMutationFixture: (name: string, handler: SWRMutationFixtureHandler) => {\n mutationFixturesRef.current.set(name, handler)\n },\n\n removeMutationFixture: (name: string) => {\n mutationFixturesRef.current.delete(name)\n },\n\n getFetcher,\n getMiddleware,\n }),\n [isDemoMode, getFetcher, getMiddleware]\n )\n\n return (\n <DemoSWRContext.Provider value={contextValue}>\n <SWRConfig value={config}>{children}</SWRConfig>\n </DemoSWRContext.Provider>\n )\n}\n","'use client'\n\nimport { createContext } from 'react'\nimport type { DemoSWRState } from './types'\n\n/**\n * Context for DemoSWR state\n * @internal\n */\nexport const DemoSWRContext = createContext<DemoSWRState | undefined>(undefined)\n\nDemoSWRContext.displayName = 'DemoSWRContext'\n","import { matchQueryKey, findMatchingQueryKeyPattern } from '@demokit-ai/core'\nimport type { QueryKey } from '@demokit-ai/core'\nimport type { SWRFixtureHandler, SWRFixtureMap, SWRFixtureMapObject } from './types'\n\n/**\n * Normalize an SWR key to a QueryKey for matching\n *\n * SWR keys can be:\n * - Strings: '/api/users' -> ['/api/users']\n * - Arrays: ['/api/users', id] -> ['/api/users', id]\n * - Functions that return keys (not handled here)\n */\nexport function normalizeKey(key: string | unknown[]): QueryKey {\n if (typeof key === 'string') {\n return [key]\n }\n\n return key.map((element) => {\n if (element === null || element === undefined) {\n return element\n }\n if (typeof element === 'object') {\n return element as Record<string, unknown>\n }\n return element as string | number | boolean\n })\n}\n\n/**\n * Parse a JSON string pattern into a QueryKey\n * Handles both array notation and simple string patterns\n *\n * @example\n * parsePatternString('[\"/api/users\"]') // ['/api/users']\n * parsePatternString('[\"/api/users\", \":id\"]') // ['/api/users', ':id']\n * parsePatternString('/api/users') // ['/api/users']\n */\nexport function parsePatternString(pattern: string): QueryKey {\n // Try to parse as JSON array\n if (pattern.startsWith('[')) {\n try {\n return JSON.parse(pattern) as QueryKey\n } catch {\n // Fall through to simple string\n }\n }\n\n // Simple string becomes single-element array\n return [pattern]\n}\n\n/**\n * Convert object-based fixture map to Map-based fixture map\n */\nexport function normalizeFixtureMap(fixtures: SWRFixtureMapObject | SWRFixtureMap): SWRFixtureMap {\n if (fixtures instanceof Map) {\n return fixtures\n }\n\n const map = new Map<QueryKey, SWRFixtureHandler>()\n for (const [pattern, handler] of Object.entries(fixtures)) {\n map.set(parsePatternString(pattern), handler)\n }\n return map\n}\n\n/**\n * Find a matching fixture for an SWR key\n *\n * @param fixtures - Map of key patterns to handlers\n * @param key - The SWR key to match\n * @returns Tuple of [handler, match result] or null if no match\n */\nexport function findMatchingFixture(\n fixtures: SWRFixtureMap,\n key: string | unknown[]\n): [SWRFixtureHandler, { params: Record<string, unknown>; normalizedKey: QueryKey }] | null {\n const normalizedKey = normalizeKey(key)\n const result = findMatchingQueryKeyPattern(fixtures, normalizedKey)\n\n if (result) {\n const [, handler, matchResult] = result\n return [handler, { params: matchResult.params, normalizedKey }]\n }\n\n return null\n}\n\n/**\n * Re-export the matchQueryKey function for direct use\n */\nexport { matchQueryKey }","import type { QueryKey } from '@demokit-ai/core'\nimport type { SWRFixtureMap, SWRFixtureContext } from './types'\nimport { findMatchingFixture, normalizeKey } from './matcher'\n\n/**\n * Options for creating a demo-aware fetcher\n */\nexport interface CreateDemoFetcherOptions {\n /**\n * Map of key patterns to fixture handlers\n */\n fixtures: SWRFixtureMap\n\n /**\n * Function to check if demo mode is enabled\n */\n isEnabled: () => boolean\n\n /**\n * Delay in ms before returning fixture data\n * @default 0\n */\n delay?: number\n\n /**\n * Fallback fetcher to use when demo mode is disabled\n * or no fixture matches\n */\n fallbackFetcher?: <T>(key: string | unknown[]) => Promise<T>\n}\n\n/**\n * Create a demo-aware fetcher function for SWR\n *\n * This fetcher intercepts requests when demo mode is enabled\n * and returns fixture data instead of making real API calls.\n *\n * @example\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'User' })],\n * ])\n *\n * const fetcher = createDemoFetcher({\n * fixtures,\n * isEnabled: () => isDemoMode,\n * delay: 100,\n * })\n *\n * // Use with SWR\n * const { data } = useSWR('/api/users', fetcher)\n */\nexport function createDemoFetcher(options: CreateDemoFetcherOptions) {\n const { fixtures, isEnabled, delay = 0, fallbackFetcher } = options\n\n return async function demoFetcher<TData = unknown>(key: string | unknown[]): Promise<TData> {\n // If demo mode is not enabled, use fallback\n if (!isEnabled()) {\n if (fallbackFetcher) {\n return fallbackFetcher<TData>(key)\n }\n throw new Error(\n `[DemoKit SWR] No fallback fetcher provided and demo mode is disabled. ` +\n `Key: ${JSON.stringify(key)}`\n )\n }\n\n // Find matching fixture\n const match = findMatchingFixture(fixtures, key)\n\n if (!match) {\n // No fixture found, try fallback\n if (fallbackFetcher) {\n return fallbackFetcher<TData>(key)\n }\n throw new Error(`[DemoKit SWR] No fixture found for key: ${JSON.stringify(key)}`)\n }\n\n const [handler, { params, normalizedKey }] = match\n\n // Apply delay if configured\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n\n // Build context\n const context: SWRFixtureContext = {\n key,\n normalizedKey,\n params,\n match: { matched: true, params },\n }\n\n // Execute handler\n if (typeof handler === 'function') {\n return handler(context) as TData\n }\n\n // Return static value\n return handler as TData\n }\n}\n\n/**\n * Default fetcher that uses fetch API\n * Used as fallback when demo mode is disabled\n */\nexport async function defaultFetcher<TData = unknown>(key: string | unknown[]): Promise<TData> {\n const url = typeof key === 'string' ? key : String(key[0])\n const response = await fetch(url)\n\n if (!response.ok) {\n const error = new Error('An error occurred while fetching the data.')\n throw error\n }\n\n return response.json()\n}\n","import type { Middleware } from 'swr'\nimport type { SWRFixtureMap, SWRFixtureContext } from './types'\nimport { findMatchingFixture } from './matcher'\n\n/**\n * Options for creating the demo middleware\n */\nexport interface CreateDemoMiddlewareOptions {\n /**\n * Map of key patterns to fixture handlers\n */\n fixtures: SWRFixtureMap\n\n /**\n * Function to check if demo mode is enabled\n */\n isEnabled: () => boolean\n\n /**\n * Delay in ms before returning fixture data\n * @default 0\n */\n delay?: number\n}\n\n/**\n * Create a demo-aware SWR middleware\n *\n * This middleware intercepts SWR requests when demo mode is enabled\n * and returns fixture data instead of using the original fetcher.\n *\n * @example\n * import { SWRConfig } from 'swr'\n * import { createDemoMiddleware } from '@demokit-ai/swr'\n *\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'User' })],\n * ])\n *\n * const demoMiddleware = createDemoMiddleware({\n * fixtures,\n * isEnabled: () => isDemoMode,\n * delay: 100,\n * })\n *\n * function App() {\n * return (\n * <SWRConfig value={{ use: [demoMiddleware] }}>\n * <YourApp />\n * </SWRConfig>\n * )\n * }\n */\nexport function createDemoMiddleware(options: CreateDemoMiddlewareOptions): Middleware {\n const { fixtures, isEnabled, delay = 0 } = options\n\n // Use the simpler middleware pattern that SWR expects\n const middleware: Middleware = (useSWRNext) => (key, fetcher, config) => {\n // Create an extended fetcher that checks for demo mode\n const extendedFetcher =\n fetcher === null\n ? null\n : async (...args: Parameters<typeof fetcher>) => {\n // Resolve the key if it's a function\n const resolvedKey = typeof key === 'function' ? key() : key\n\n // If no key, let SWR handle it\n if (resolvedKey === null || resolvedKey === undefined) {\n return fetcher(...args)\n }\n\n // If demo mode is not enabled, use original fetcher\n if (!isEnabled()) {\n return fetcher(...args)\n }\n\n // Normalize key for matching\n const keyToMatch =\n typeof resolvedKey === 'string' ? resolvedKey : (resolvedKey as unknown[])\n\n // Find matching fixture\n const match = findMatchingFixture(fixtures, keyToMatch)\n\n if (!match) {\n // No fixture found, use original fetcher\n return fetcher(...args)\n }\n\n const [handler, { params, normalizedKey }] = match\n\n // Apply delay if configured\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n\n // Build context\n const context: SWRFixtureContext = {\n key: resolvedKey,\n normalizedKey,\n params,\n match: { matched: true, params },\n }\n\n // Execute handler\n if (typeof handler === 'function') {\n return handler(context)\n }\n\n // Return static value\n return handler\n }\n\n return useSWRNext(key, extendedFetcher, config)\n }\n\n return middleware\n}\n","import type { RemoteSourceConfig } from './types'\n\n/**\n * Create a remote source configuration for fetching fixtures from DemoKit Cloud\n *\n * The SDK appends `/fixtures` to your apiUrl, so provide the versioned base URL.\n *\n * @example\n * ```typescript\n * // lib/demokit-config.ts\n * import { createRemoteSource } from '@demokit-ai/swr'\n *\n * // .env:\n * // VITE_DEMOKIT_API_URL=https://demokit-cloud.kasava.dev/api\n * // VITE_DEMOKIT_API_KEY=dk_live_xxxx\n *\n * export const demokitSource = createRemoteSource({\n * apiUrl: import.meta.env.VITE_DEMOKIT_API_URL,\n * apiKey: import.meta.env.VITE_DEMOKIT_API_KEY,\n * })\n *\n * // Then in your app:\n * import { demokitSource } from './lib/demokit-config'\n *\n * <DemoSWRProvider source={demokitSource}>\n * <SWRConfig>\n * <App />\n * </SWRConfig>\n * </DemoSWRProvider>\n * ```\n */\nexport function createRemoteSource(config: RemoteSourceConfig): RemoteSourceConfig {\n return {\n timeout: 10000,\n retry: true,\n maxRetries: 3,\n ...config,\n }\n}\n","'use client'\n\nimport { useContext, useCallback } from 'react'\nimport useSWRMutation, { type SWRMutationConfiguration, type SWRMutationResponse } from 'swr/mutation'\nimport { useSWRConfig } from 'swr'\nimport { DemoSWRContext } from './context'\nimport type { DemoSWRState, SWRMutationFixtureContext, SWRMutationFixtureHandler } from './types'\n\n/**\n * Hook to access DemoSWR state and controls\n *\n * @returns DemoSWR context value\n * @throws Error if used outside of DemoSWRProvider\n *\n * @example\n * function MyComponent() {\n * const { isDemoMode, setFixture } = useDemoSWR()\n *\n * // Dynamically add a fixture\n * const handleAddFixture = () => {\n * setFixture(['/api/users', 'custom'], { id: 'custom', name: 'Custom User' })\n * }\n *\n * return (\n * <button onClick={handleAddFixture}>Add Custom Fixture</button>\n * )\n * }\n */\nexport function useDemoSWR(): DemoSWRState {\n const context = useContext(DemoSWRContext)\n\n if (context === undefined) {\n throw new Error(\n 'useDemoSWR must be used within a DemoSWRProvider. ' +\n 'Make sure to wrap your app with <DemoSWRProvider>.'\n )\n }\n\n return context\n}\n\n/**\n * Hook to check if demo mode is enabled\n * Shorthand for useDemoSWR().isDemoMode\n *\n * @example\n * function MyComponent() {\n * const isDemoMode = useIsDemoSWRMode()\n *\n * return isDemoMode ? <DemoBadge /> : null\n * }\n */\nexport function useIsDemoSWRMode(): boolean {\n return useDemoSWR().isDemoMode\n}\n\n/**\n * Options for useDemoSWRMutation hook\n */\nexport interface UseDemoSWRMutationOptions<TData, TError, TArg>\n extends Omit<SWRMutationConfiguration<TData, TError, string, TArg>, 'fetcher'> {\n /**\n * The real mutation function to use when demo mode is disabled\n */\n fetcher: (key: string, options: { arg: TArg }) => Promise<TData>\n\n /**\n * Demo fixture handler for this mutation\n */\n demoFixture?: SWRMutationFixtureHandler<TData, TArg>\n\n /**\n * Delay in ms before returning demo data\n * @default 0\n */\n demoDelay?: number\n}\n\n/**\n * A mutation hook that automatically uses demo fixtures when demo mode is enabled\n *\n * Works with useSWRMutation from swr/mutation.\n *\n * @example\n * const { trigger: createUser, isMutating } = useDemoSWRMutation('/api/users', {\n * fetcher: async (key, { arg }) => api.createUser(arg),\n * demoFixture: ({ arg, mutate }) => {\n * // Create demo user\n * const newUser = { id: crypto.randomUUID(), ...arg }\n *\n * // Update the users cache\n * mutate('/api/users', (current: User[] = []) => [...current, newUser])\n *\n * return newUser\n * },\n * onSuccess: (data) => {\n * console.log('Created user:', data)\n * },\n * })\n *\n * // Use like normal useSWRMutation\n * createUser({ name: 'New User', email: 'user@example.com' })\n */\nexport function useDemoSWRMutation<TData = unknown, TError = unknown, TArg = unknown>(\n key: string,\n options: UseDemoSWRMutationOptions<TData, TError, TArg>\n): SWRMutationResponse<TData, TError, string, TArg> {\n const { fetcher, demoFixture, demoDelay = 0, ...mutationOptions } = options\n\n const { mutate } = useSWRConfig()\n\n // Try to get demo state - may not be in DemoSWRProvider context\n let isDemoMode = false\n try {\n const demoState = useDemoSWR()\n isDemoMode = demoState.isDemoMode\n } catch {\n // Not in DemoSWRProvider context, use real mutation\n }\n\n // Create the demo-aware mutation function\n const demoAwareFetcher = useCallback(\n async (mutationKey: string, { arg }: { arg: TArg }): Promise<TData> => {\n // If not in demo mode, use real mutation\n if (!isDemoMode) {\n return fetcher(mutationKey, { arg })\n }\n\n // Apply delay if configured\n if (demoDelay > 0) {\n await new Promise((resolve) => setTimeout(resolve, demoDelay))\n }\n\n // If a demo fixture is provided, use it\n if (demoFixture !== undefined) {\n const context: SWRMutationFixtureContext<TData, TArg> = {\n key: mutationKey,\n arg,\n currentData: undefined, // SWR mutation doesn't have direct access to current data\n mutate: mutate as SWRMutationFixtureContext<TData, TArg>['mutate'],\n }\n\n if (typeof demoFixture === 'function') {\n const fixtureFn = demoFixture as (\n context: SWRMutationFixtureContext<TData, TArg>\n ) => TData | Promise<TData>\n return fixtureFn(context)\n }\n return demoFixture as TData\n }\n\n // No fixture found, fall back to real mutation\n console.warn(\n `[DemoKit SWR] No mutation fixture found for \"${key}\". Using real mutation function.`\n )\n return fetcher(mutationKey, { arg })\n },\n [isDemoMode, fetcher, demoFixture, demoDelay, key, mutate]\n )\n\n return useSWRMutation(key, demoAwareFetcher, mutationOptions)\n}\n"],"mappings":";AAEA,SAAS,SAAS,QAAQ,mBAAmB;AAC7C,SAAS,iBAAiB;;;ACD1B,SAAS,qBAAqB;AAOvB,IAAM,iBAAiB,cAAwC,MAAS;AAE/E,eAAe,cAAc;;;ACX7B,SAAS,eAAe,mCAAmC;AAYpD,SAAS,aAAa,KAAmC;AAC9D,MAAI,OAAO,QAAQ,UAAU;AAC3B,WAAO,CAAC,GAAG;AAAA,EACb;AAEA,SAAO,IAAI,IAAI,CAAC,YAAY;AAC1B,QAAI,YAAY,QAAQ,YAAY,QAAW;AAC7C,aAAO;AAAA,IACT;AACA,QAAI,OAAO,YAAY,UAAU;AAC/B,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT,CAAC;AACH;AAWO,SAAS,mBAAmB,SAA2B;AAE5D,MAAI,QAAQ,WAAW,GAAG,GAAG;AAC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A,SAAO,eAAe,KAAK,kBAAkB,eAAe;AAC9D;","names":["useCallback","useCallback"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@demokit-ai/swr",
3
- "version": "0.2.0",
4
- "description": "SWR adapter for DemoKit - mock fetchers and middleware for demo mode",
3
+ "version": "0.4.0",
4
+ "description": "SWR integration for DemoKit",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
7
7
  "module": "./dist/index.js",
@@ -21,44 +21,30 @@
21
21
  "files": [
22
22
  "dist"
23
23
  ],
24
- "scripts": {
25
- "build": "tsup",
26
- "dev": "tsup --watch",
27
- "test": "vitest",
28
- "typecheck": "tsc --noEmit"
29
- },
30
24
  "dependencies": {
31
- "@demokit-ai/core": "*",
32
- "@demokit-ai/react": "*"
25
+ "@demokit-ai/core": "0.4.0",
26
+ "@demokit-ai/react": "0.4.0"
33
27
  },
34
28
  "devDependencies": {
29
+ "@types/node": "^22.0.0",
35
30
  "@types/react": "^19.0.0",
36
- "@types/react-dom": "^19.0.0",
37
- "react": "^19.0.0",
38
- "react-dom": "^19.0.0",
39
31
  "swr": "^2.2.5",
40
32
  "tsup": "^8.3.5",
41
- "typescript": "^5.7.2",
42
- "vitest": "^2.1.8"
33
+ "typescript": "^5.7.2"
43
34
  },
44
35
  "peerDependencies": {
45
36
  "react": ">=17.0.0",
46
- "react-dom": ">=17.0.0",
47
37
  "swr": ">=2.0.0"
48
38
  },
49
- "keywords": [
50
- "demo",
51
- "mock",
52
- "swr",
53
- "fixtures",
54
- "testing",
55
- "middleware"
56
- ],
57
- "license": "MIT",
58
- "repository": {
59
- "type": "git",
60
- "url": "https://github.com/your-org/demokit",
61
- "directory": "packages/swr"
39
+ "engines": {
40
+ "node": ">=18"
62
41
  },
63
- "sideEffects": false
42
+ "license": "Apache-2.0",
43
+ "sideEffects": false,
44
+ "scripts": {
45
+ "build": "tsup",
46
+ "dev": "tsup --watch --no-dts",
47
+ "typecheck": "tsc --noEmit",
48
+ "clean": "rm -rf dist"
49
+ }
64
50
  }
package/README.md DELETED
@@ -1,233 +0,0 @@
1
- # @demokit-ai/swr
2
-
3
- ![Tests](https://img.shields.io/badge/tests-30%20passing-brightgreen)
4
- ![Coverage](https://img.shields.io/badge/coverage-6%25-red)
5
-
6
- SWR adapter for DemoKit - mock fetchers and middleware for demo mode.
7
-
8
- ## Installation
9
-
10
- ```bash
11
- npm install @demokit-ai/swr @demokit-ai/core @demokit-ai/react swr
12
- ```
13
-
14
- ## Features
15
-
16
- - **Demo Fetcher** - Intercept SWR fetches and return fixtures
17
- - **Middleware Support** - SWR middleware for demo mode
18
- - **Key Matching** - Pattern-based key matching for fixtures
19
- - **Provider Pattern** - Centralized fixture management
20
- - **Mutation Mocking** - Mock mutate operations in demo mode
21
- - Full TypeScript support
22
-
23
- ## Usage
24
-
25
- ### Basic Fetcher Wrapping
26
-
27
- ```tsx
28
- import useSWR from 'swr'
29
- import { createDemoFetcher } from '@demokit-ai/swr'
30
-
31
- const fetcher = createDemoFetcher({
32
- fetcher: (url) => fetch(url).then((r) => r.json()),
33
- isEnabled: () => localStorage.getItem('demoMode') === 'true',
34
- fixtures: {
35
- '/api/users': [
36
- { id: '1', name: 'Demo User' },
37
- { id: '2', name: 'Another User' },
38
- ],
39
- '/api/users/:id': (key) => ({
40
- id: key.params.id,
41
- name: 'Demo User',
42
- email: 'demo@example.com',
43
- }),
44
- },
45
- })
46
-
47
- function UserList() {
48
- const { data } = useSWR('/api/users', fetcher)
49
- return <ul>{data?.map((u) => <li key={u.id}>{u.name}</li>)}</ul>
50
- }
51
- ```
52
-
53
- ### SWR Middleware
54
-
55
- ```tsx
56
- import { SWRConfig } from 'swr'
57
- import { createDemoMiddleware } from '@demokit-ai/swr'
58
-
59
- const demoMiddleware = createDemoMiddleware({
60
- fixtures: {
61
- '/api/users': [{ id: '1', name: 'Demo User' }],
62
- '/api/products': [{ id: '1', name: 'Demo Product', price: 99.99 }],
63
- },
64
- isEnabled: () => localStorage.getItem('demoMode') === 'true',
65
- delay: 100,
66
- })
67
-
68
- function App() {
69
- return (
70
- <SWRConfig value={{ use: [demoMiddleware] }}>
71
- <YourApp />
72
- </SWRConfig>
73
- )
74
- }
75
- ```
76
-
77
- ### Provider Pattern
78
-
79
- ```tsx
80
- import { DemoSWRProvider, useDemoSWR } from '@demokit-ai/swr'
81
-
82
- const fixtures = {
83
- '/api/users': [{ id: '1', name: 'Demo User' }],
84
- '/api/products': [{ id: '1', name: 'Demo Product' }],
85
- }
86
-
87
- function App() {
88
- return (
89
- <DemoSWRProvider fixtures={fixtures} enabled>
90
- <YourApp />
91
- <DemoControls />
92
- </DemoSWRProvider>
93
- )
94
- }
95
-
96
- function DemoControls() {
97
- const { enabled, toggle, setFixture } = useDemoSWR()
98
-
99
- return (
100
- <div>
101
- <button onClick={toggle}>Demo: {enabled ? 'ON' : 'OFF'}</button>
102
- <button
103
- onClick={() =>
104
- setFixture('/api/custom', () => ({ custom: true }))
105
- }
106
- >
107
- Add Custom Fixture
108
- </button>
109
- </div>
110
- )
111
- }
112
- ```
113
-
114
- ### Dynamic Fixtures
115
-
116
- ```tsx
117
- import { createDemoFetcher } from '@demokit-ai/swr'
118
-
119
- const fetcher = createDemoFetcher({
120
- fetcher: (url) => fetch(url).then((r) => r.json()),
121
- isEnabled: () => true,
122
- fixtures: {
123
- // Static fixture
124
- '/api/config': { version: '1.0', features: ['demo'] },
125
-
126
- // Dynamic fixture based on key
127
- '/api/users/:id': ({ params }) => ({
128
- id: params.id,
129
- name: `User ${params.id}`,
130
- }),
131
-
132
- // Dynamic fixture with query params
133
- '/api/search': ({ searchParams }) => {
134
- const query = searchParams.get('q') || ''
135
- return [
136
- { id: '1', title: `Result for: ${query}` },
137
- ]
138
- },
139
- },
140
- })
141
- ```
142
-
143
- ### Mutation Mocking
144
-
145
- ```tsx
146
- import useSWRMutation from 'swr/mutation'
147
- import { createDemoMutator } from '@demokit-ai/swr'
148
-
149
- const mutator = createDemoMutator({
150
- mutator: async (url, { arg }) => {
151
- const res = await fetch(url, {
152
- method: 'POST',
153
- body: JSON.stringify(arg),
154
- })
155
- return res.json()
156
- },
157
- isEnabled: () => true,
158
- fixtures: {
159
- '/api/users': (key, { arg }) => ({
160
- id: 'new-id',
161
- ...arg,
162
- created: true,
163
- }),
164
- },
165
- })
166
-
167
- function CreateUser() {
168
- const { trigger, isMutating } = useSWRMutation('/api/users', mutator)
169
-
170
- return (
171
- <button
172
- onClick={() => trigger({ name: 'New User' })}
173
- disabled={isMutating}
174
- >
175
- Create User
176
- </button>
177
- )
178
- }
179
- ```
180
-
181
- ## API Reference
182
-
183
- ### `createDemoFetcher(options)`
184
-
185
- Create a demo-aware SWR fetcher.
186
-
187
- Options:
188
- - `fetcher` - The real fetcher function
189
- - `isEnabled` - Function to check if demo mode is enabled
190
- - `fixtures` - Fixture definitions by key pattern
191
- - `delay` - Simulated delay in milliseconds
192
-
193
- ### `createDemoMiddleware(options)`
194
-
195
- Create SWR middleware for demo mode.
196
-
197
- Options:
198
- - `fixtures` - Fixture definitions by key pattern
199
- - `isEnabled` - Function to check if demo mode is enabled
200
- - `delay` - Simulated delay in milliseconds
201
- - `onIntercept` - Callback when a request is intercepted
202
-
203
- ### `DemoSWRProvider`
204
-
205
- Props:
206
- - `fixtures` - Fixture definitions
207
- - `enabled` - Whether demo mode is enabled
208
- - `delay` - Simulated delay in milliseconds
209
- - `children` - React children
210
-
211
- ### `useDemoSWR()`
212
-
213
- Returns:
214
- - `enabled` - Whether demo mode is enabled
215
- - `toggle()` - Toggle demo mode
216
- - `fixtures` - Current fixtures
217
- - `setFixture(key, fixture)` - Set a fixture
218
- - `removeFixture(key)` - Remove a fixture
219
- - `clearFixtures()` - Clear all fixtures
220
-
221
- ### `createDemoMutator(options)`
222
-
223
- Create a demo-aware SWR mutator.
224
-
225
- Options:
226
- - `mutator` - The real mutator function
227
- - `isEnabled` - Function to check if demo mode is enabled
228
- - `fixtures` - Mutation fixtures by key pattern
229
- - `delay` - Simulated delay in milliseconds
230
-
231
- ## License
232
-
233
- MIT