@tonyclaw/llm-inspector 1.7.8 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/public/assets/index-BLVa7n9b.css +1 -0
  3. package/.output/public/assets/index-DH3FOgcK.js +97 -0
  4. package/.output/public/assets/main-Beo3LJDa.js +17 -0
  5. package/.output/server/_libs/dequal.mjs +27 -0
  6. package/.output/server/_libs/lucide-react.mjs +98 -91
  7. package/.output/server/_libs/swr.mjs +938 -0
  8. package/.output/server/_libs/use-sync-external-store.mjs +64 -1
  9. package/.output/server/_libs/zod.mjs +1 -0
  10. package/.output/server/_ssr/{index-hNquJMfH.mjs → index-HkueJ4Un.mjs} +218 -71
  11. package/.output/server/_ssr/index.mjs +2 -2
  12. package/.output/server/_ssr/{router-MmnX-LYh.mjs → router-DTswxb7l.mjs} +264 -52
  13. package/.output/server/_tanstack-start-manifest_v-DhUuivt-.mjs +4 -0
  14. package/.output/server/index.mjs +26 -26
  15. package/package.json +2 -1
  16. package/src/components/ProxyViewer.tsx +2 -0
  17. package/src/components/providers/ProviderCard.tsx +38 -33
  18. package/src/components/providers/ProviderLogo.tsx +6 -1
  19. package/src/components/providers/ProvidersPanel.tsx +144 -43
  20. package/src/components/providers/SettingsDialog.tsx +5 -3
  21. package/src/components/proxy-viewer/ConversationGroup.tsx +3 -3
  22. package/src/components/proxy-viewer/LogEntry.tsx +6 -3
  23. package/src/components/proxy-viewer/LogEntryHeader.tsx +3 -2
  24. package/src/lib/useProviders.ts +30 -0
  25. package/src/proxy/formats/anthropic/stream.ts +3 -2
  26. package/src/proxy/formats/openai/stream.ts +3 -2
  27. package/src/proxy/handler.ts +5 -0
  28. package/src/proxy/providers.ts +98 -0
  29. package/src/routes/__root.tsx +4 -1
  30. package/src/routes/api/providers.export.ts +26 -0
  31. package/src/routes/api/providers.import.ts +47 -0
  32. package/.output/public/assets/index-B3RwBPLW.css +0 -1
  33. package/.output/public/assets/index-C8o6bEv6.js +0 -97
  34. package/.output/public/assets/main-Bxc5pKCu.js +0 -17
  35. package/.output/server/_tanstack-start-manifest_v-CYKtU_9S.mjs +0 -4
@@ -0,0 +1,938 @@
1
+ import { r as reactExports, a as React } from "./react.mjs";
2
+ import { s as shimExports } from "./use-sync-external-store.mjs";
3
+ import { d as dequal } from "./dequal.mjs";
4
+ const FOCUS_EVENT = 0;
5
+ const RECONNECT_EVENT = 1;
6
+ const MUTATE_EVENT = 2;
7
+ const ERROR_REVALIDATE_EVENT = 3;
8
+ const SWRGlobalState = /* @__PURE__ */ new WeakMap();
9
+ const noop = () => {
10
+ };
11
+ const UNDEFINED = (
12
+ /*#__NOINLINE__*/
13
+ noop()
14
+ );
15
+ const OBJECT = Object;
16
+ const isUndefined = (v) => v === UNDEFINED;
17
+ const isFunction = (v) => typeof v == "function";
18
+ const mergeObjects = (a, b) => ({
19
+ ...a,
20
+ ...b
21
+ });
22
+ const isPromiseLike = (x) => isFunction(x.then);
23
+ const EMPTY_CACHE = {};
24
+ const INITIAL_CACHE = {};
25
+ const STR_UNDEFINED = "undefined";
26
+ const isWindowDefined = typeof window != STR_UNDEFINED;
27
+ const isDocumentDefined = typeof document != STR_UNDEFINED;
28
+ const isLegacyDeno = isWindowDefined && "Deno" in window;
29
+ const hasRequestAnimationFrame = () => isWindowDefined && typeof window["requestAnimationFrame"] != STR_UNDEFINED;
30
+ const createCacheHelper = (cache2, key) => {
31
+ const state = SWRGlobalState.get(cache2);
32
+ return [
33
+ // Getter
34
+ () => !isUndefined(key) && cache2.get(key) || EMPTY_CACHE,
35
+ // Setter
36
+ (info) => {
37
+ if (!isUndefined(key)) {
38
+ const prev = cache2.get(key);
39
+ if (!(key in INITIAL_CACHE)) {
40
+ INITIAL_CACHE[key] = prev;
41
+ }
42
+ state[5](key, mergeObjects(prev, info), prev || EMPTY_CACHE);
43
+ }
44
+ },
45
+ // Subscriber
46
+ state[6],
47
+ // Get server cache snapshot
48
+ () => {
49
+ if (!isUndefined(key)) {
50
+ if (key in INITIAL_CACHE) return INITIAL_CACHE[key];
51
+ }
52
+ return !isUndefined(key) && cache2.get(key) || EMPTY_CACHE;
53
+ }
54
+ ];
55
+ };
56
+ let online = true;
57
+ const isOnline = () => online;
58
+ const [onWindowEvent, offWindowEvent] = isWindowDefined && window.addEventListener ? [
59
+ window.addEventListener.bind(window),
60
+ window.removeEventListener.bind(window)
61
+ ] : [
62
+ noop,
63
+ noop
64
+ ];
65
+ const isVisible = () => {
66
+ const visibilityState = isDocumentDefined && document.visibilityState;
67
+ return isUndefined(visibilityState) || visibilityState !== "hidden";
68
+ };
69
+ const initFocus = (callback) => {
70
+ if (isDocumentDefined) {
71
+ document.addEventListener("visibilitychange", callback);
72
+ }
73
+ onWindowEvent("focus", callback);
74
+ return () => {
75
+ if (isDocumentDefined) {
76
+ document.removeEventListener("visibilitychange", callback);
77
+ }
78
+ offWindowEvent("focus", callback);
79
+ };
80
+ };
81
+ const initReconnect = (callback) => {
82
+ const onOnline = () => {
83
+ online = true;
84
+ callback();
85
+ };
86
+ const onOffline = () => {
87
+ online = false;
88
+ };
89
+ onWindowEvent("online", onOnline);
90
+ onWindowEvent("offline", onOffline);
91
+ return () => {
92
+ offWindowEvent("online", onOnline);
93
+ offWindowEvent("offline", onOffline);
94
+ };
95
+ };
96
+ const preset = {
97
+ isOnline,
98
+ isVisible
99
+ };
100
+ const defaultConfigOptions = {
101
+ initFocus,
102
+ initReconnect
103
+ };
104
+ const IS_REACT_LEGACY = !React.useId;
105
+ const IS_SERVER = !isWindowDefined || isLegacyDeno;
106
+ const rAF = (f) => hasRequestAnimationFrame() ? window["requestAnimationFrame"](f) : setTimeout(f, 1);
107
+ const useIsomorphicLayoutEffect = IS_SERVER ? reactExports.useEffect : reactExports.useLayoutEffect;
108
+ const navigatorConnection = typeof navigator !== "undefined" && navigator.connection;
109
+ const slowConnection = !IS_SERVER && navigatorConnection && ([
110
+ "slow-2g",
111
+ "2g"
112
+ ].includes(navigatorConnection.effectiveType) || navigatorConnection.saveData);
113
+ const table = /* @__PURE__ */ new WeakMap();
114
+ const getTypeName = (value) => OBJECT.prototype.toString.call(value);
115
+ const isObjectTypeName = (typeName, type) => typeName === `[object ${type}]`;
116
+ let counter = 0;
117
+ const stableHash = (arg) => {
118
+ const type = typeof arg;
119
+ const typeName = getTypeName(arg);
120
+ const isDate = isObjectTypeName(typeName, "Date");
121
+ const isRegex = isObjectTypeName(typeName, "RegExp");
122
+ const isPlainObject = isObjectTypeName(typeName, "Object");
123
+ let result;
124
+ let index;
125
+ if (OBJECT(arg) === arg && !isDate && !isRegex) {
126
+ result = table.get(arg);
127
+ if (result) return result;
128
+ result = ++counter + "~";
129
+ table.set(arg, result);
130
+ if (Array.isArray(arg)) {
131
+ result = "@";
132
+ for (index = 0; index < arg.length; index++) {
133
+ result += stableHash(arg[index]) + ",";
134
+ }
135
+ table.set(arg, result);
136
+ }
137
+ if (isPlainObject) {
138
+ result = "#";
139
+ const keys = OBJECT.keys(arg).sort();
140
+ while (!isUndefined(index = keys.pop())) {
141
+ if (!isUndefined(arg[index])) {
142
+ result += index + ":" + stableHash(arg[index]) + ",";
143
+ }
144
+ }
145
+ table.set(arg, result);
146
+ }
147
+ } else {
148
+ result = isDate ? arg.toJSON() : type == "symbol" ? arg.toString() : type == "string" ? JSON.stringify(arg) : "" + arg;
149
+ }
150
+ return result;
151
+ };
152
+ const serialize = (key) => {
153
+ if (isFunction(key)) {
154
+ try {
155
+ key = key();
156
+ } catch (err) {
157
+ key = "";
158
+ }
159
+ }
160
+ const args = key;
161
+ key = typeof key == "string" ? key : (Array.isArray(key) ? key.length : key) ? stableHash(key) : "";
162
+ return [
163
+ key,
164
+ args
165
+ ];
166
+ };
167
+ let __timestamp = 0;
168
+ const getTimestamp = () => ++__timestamp;
169
+ async function internalMutate(...args) {
170
+ const [cache2, _key, _data, _opts] = args;
171
+ const options = mergeObjects({
172
+ populateCache: true,
173
+ throwOnError: true
174
+ }, typeof _opts === "boolean" ? {
175
+ revalidate: _opts
176
+ } : _opts || {});
177
+ let populateCache = options.populateCache;
178
+ const rollbackOnErrorOption = options.rollbackOnError;
179
+ let optimisticData = options.optimisticData;
180
+ const rollbackOnError = (error) => {
181
+ return typeof rollbackOnErrorOption === "function" ? rollbackOnErrorOption(error) : rollbackOnErrorOption !== false;
182
+ };
183
+ const throwOnError = options.throwOnError;
184
+ if (isFunction(_key)) {
185
+ const keyFilter = _key;
186
+ const matchedKeys = [];
187
+ const it = cache2.keys();
188
+ for (const key of it) {
189
+ if (
190
+ // Skip the special useSWRInfinite and useSWRSubscription keys.
191
+ !/^\$(inf|sub)\$/.test(key) && keyFilter(cache2.get(key)._k)
192
+ ) {
193
+ matchedKeys.push(key);
194
+ }
195
+ }
196
+ return Promise.all(matchedKeys.map(mutateByKey));
197
+ }
198
+ return mutateByKey(_key);
199
+ async function mutateByKey(_k) {
200
+ const [key] = serialize(_k);
201
+ if (!key) return;
202
+ const [get, set] = createCacheHelper(cache2, key);
203
+ const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = SWRGlobalState.get(cache2);
204
+ const startRevalidate = () => {
205
+ const revalidators = EVENT_REVALIDATORS[key];
206
+ const revalidate = isFunction(options.revalidate) ? options.revalidate(get().data, _k) : options.revalidate !== false;
207
+ if (revalidate) {
208
+ delete FETCH[key];
209
+ delete PRELOAD[key];
210
+ if (revalidators && revalidators[0]) {
211
+ return revalidators[0](MUTATE_EVENT).then(() => get().data);
212
+ }
213
+ }
214
+ return get().data;
215
+ };
216
+ if (args.length < 3) {
217
+ return startRevalidate();
218
+ }
219
+ let data = _data;
220
+ let error;
221
+ let isError = false;
222
+ const beforeMutationTs = getTimestamp();
223
+ MUTATION[key] = [
224
+ beforeMutationTs,
225
+ 0
226
+ ];
227
+ const hasOptimisticData = !isUndefined(optimisticData);
228
+ const state = get();
229
+ const displayedData = state.data;
230
+ const currentData = state._c;
231
+ const committedData = isUndefined(currentData) ? displayedData : currentData;
232
+ if (hasOptimisticData) {
233
+ optimisticData = isFunction(optimisticData) ? optimisticData(committedData, displayedData) : optimisticData;
234
+ set({
235
+ data: optimisticData,
236
+ _c: committedData
237
+ });
238
+ }
239
+ if (isFunction(data)) {
240
+ try {
241
+ data = data(committedData);
242
+ } catch (err) {
243
+ error = err;
244
+ isError = true;
245
+ }
246
+ }
247
+ if (data && isPromiseLike(data)) {
248
+ data = await data.catch((err) => {
249
+ error = err;
250
+ isError = true;
251
+ });
252
+ if (beforeMutationTs !== MUTATION[key][0]) {
253
+ if (isError) throw error;
254
+ return data;
255
+ } else if (isError && hasOptimisticData && rollbackOnError(error)) {
256
+ populateCache = true;
257
+ set({
258
+ data: committedData,
259
+ _c: UNDEFINED
260
+ });
261
+ }
262
+ }
263
+ if (populateCache) {
264
+ if (!isError) {
265
+ if (isFunction(populateCache)) {
266
+ const populateCachedData = populateCache(data, committedData);
267
+ set({
268
+ data: populateCachedData,
269
+ error: UNDEFINED,
270
+ _c: UNDEFINED
271
+ });
272
+ } else {
273
+ set({
274
+ data,
275
+ error: UNDEFINED,
276
+ _c: UNDEFINED
277
+ });
278
+ }
279
+ }
280
+ }
281
+ MUTATION[key][1] = getTimestamp();
282
+ Promise.resolve(startRevalidate()).then(() => {
283
+ set({
284
+ _c: UNDEFINED
285
+ });
286
+ });
287
+ if (isError) {
288
+ if (throwOnError) throw error;
289
+ return;
290
+ }
291
+ return data;
292
+ }
293
+ }
294
+ const revalidateAllKeys = (revalidators, type) => {
295
+ for (const key in revalidators) {
296
+ if (revalidators[key][0]) revalidators[key][0](type);
297
+ }
298
+ };
299
+ const initCache = (provider, options) => {
300
+ if (!SWRGlobalState.has(provider)) {
301
+ const opts = mergeObjects(defaultConfigOptions, options);
302
+ const EVENT_REVALIDATORS = /* @__PURE__ */ Object.create(null);
303
+ const mutate2 = internalMutate.bind(UNDEFINED, provider);
304
+ let unmount = noop;
305
+ const subscriptions = /* @__PURE__ */ Object.create(null);
306
+ const subscribe = (key, callback) => {
307
+ const subs = subscriptions[key] || [];
308
+ subscriptions[key] = subs;
309
+ subs.push(callback);
310
+ return () => subs.splice(subs.indexOf(callback), 1);
311
+ };
312
+ const setter = (key, value, prev) => {
313
+ provider.set(key, value);
314
+ const subs = subscriptions[key];
315
+ if (subs) {
316
+ for (const fn of subs) {
317
+ fn(value, prev);
318
+ }
319
+ }
320
+ };
321
+ const initProvider = () => {
322
+ if (!SWRGlobalState.has(provider)) {
323
+ SWRGlobalState.set(provider, [
324
+ EVENT_REVALIDATORS,
325
+ /* @__PURE__ */ Object.create(null),
326
+ /* @__PURE__ */ Object.create(null),
327
+ /* @__PURE__ */ Object.create(null),
328
+ mutate2,
329
+ setter,
330
+ subscribe
331
+ ]);
332
+ if (!IS_SERVER) {
333
+ const releaseFocus = opts.initFocus(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, FOCUS_EVENT)));
334
+ const releaseReconnect = opts.initReconnect(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, RECONNECT_EVENT)));
335
+ unmount = () => {
336
+ releaseFocus && releaseFocus();
337
+ releaseReconnect && releaseReconnect();
338
+ SWRGlobalState.delete(provider);
339
+ };
340
+ }
341
+ }
342
+ };
343
+ initProvider();
344
+ return [
345
+ provider,
346
+ mutate2,
347
+ initProvider,
348
+ unmount
349
+ ];
350
+ }
351
+ return [
352
+ provider,
353
+ SWRGlobalState.get(provider)[4]
354
+ ];
355
+ };
356
+ const onErrorRetry = (_, __, config, revalidate, opts) => {
357
+ const maxRetryCount = config.errorRetryCount;
358
+ const currentRetryCount = opts.retryCount;
359
+ const timeout = ~~((Math.random() + 0.5) * (1 << (currentRetryCount < 8 ? currentRetryCount : 8))) * config.errorRetryInterval;
360
+ if (!isUndefined(maxRetryCount) && currentRetryCount > maxRetryCount) {
361
+ return;
362
+ }
363
+ setTimeout(revalidate, timeout, opts);
364
+ };
365
+ const compare = dequal;
366
+ const [cache, mutate] = initCache(/* @__PURE__ */ new Map());
367
+ const defaultConfig = mergeObjects(
368
+ {
369
+ // events
370
+ onLoadingSlow: noop,
371
+ onSuccess: noop,
372
+ onError: noop,
373
+ onErrorRetry,
374
+ onDiscarded: noop,
375
+ // switches
376
+ revalidateOnFocus: true,
377
+ revalidateOnReconnect: true,
378
+ revalidateIfStale: true,
379
+ shouldRetryOnError: true,
380
+ // timeouts
381
+ errorRetryInterval: slowConnection ? 1e4 : 5e3,
382
+ focusThrottleInterval: 5 * 1e3,
383
+ dedupingInterval: 2 * 1e3,
384
+ loadingTimeout: slowConnection ? 5e3 : 3e3,
385
+ // providers
386
+ compare,
387
+ isPaused: () => false,
388
+ cache,
389
+ mutate,
390
+ fallback: {}
391
+ },
392
+ // use web preset by default
393
+ preset
394
+ );
395
+ const mergeConfigs = (a, b) => {
396
+ const v = mergeObjects(a, b);
397
+ if (b) {
398
+ const { use: u1, fallback: f1 } = a;
399
+ const { use: u2, fallback: f2 } = b;
400
+ if (u1 && u2) {
401
+ v.use = u1.concat(u2);
402
+ }
403
+ if (f1 && f2) {
404
+ v.fallback = mergeObjects(f1, f2);
405
+ }
406
+ }
407
+ return v;
408
+ };
409
+ const SWRConfigContext = reactExports.createContext({});
410
+ const SWRConfig$1 = (props) => {
411
+ const { value } = props;
412
+ const parentConfig = reactExports.useContext(SWRConfigContext);
413
+ const isFunctionalConfig = isFunction(value);
414
+ const config = reactExports.useMemo(() => isFunctionalConfig ? value(parentConfig) : value, [
415
+ isFunctionalConfig,
416
+ parentConfig,
417
+ value
418
+ ]);
419
+ const extendedConfig = reactExports.useMemo(() => isFunctionalConfig ? config : mergeConfigs(parentConfig, config), [
420
+ isFunctionalConfig,
421
+ parentConfig,
422
+ config
423
+ ]);
424
+ const provider = config && config.provider;
425
+ const cacheContextRef = reactExports.useRef(UNDEFINED);
426
+ if (provider && !cacheContextRef.current) {
427
+ cacheContextRef.current = initCache(provider(extendedConfig.cache || cache), config);
428
+ }
429
+ const cacheContext = cacheContextRef.current;
430
+ if (cacheContext) {
431
+ extendedConfig.cache = cacheContext[0];
432
+ extendedConfig.mutate = cacheContext[1];
433
+ }
434
+ useIsomorphicLayoutEffect(() => {
435
+ if (cacheContext) {
436
+ cacheContext[2] && cacheContext[2]();
437
+ return cacheContext[3];
438
+ }
439
+ }, []);
440
+ return reactExports.createElement(SWRConfigContext.Provider, mergeObjects(props, {
441
+ value: extendedConfig
442
+ }));
443
+ };
444
+ const INFINITE_PREFIX = "$inf$";
445
+ const enableDevtools = isWindowDefined && window.__SWR_DEVTOOLS_USE__;
446
+ const use$1 = enableDevtools ? window.__SWR_DEVTOOLS_USE__ : [];
447
+ const setupDevTools = () => {
448
+ if (enableDevtools) {
449
+ window.__SWR_DEVTOOLS_REACT__ = React;
450
+ }
451
+ };
452
+ const normalize = (args) => {
453
+ return isFunction(args[1]) ? [
454
+ args[0],
455
+ args[1],
456
+ args[2] || {}
457
+ ] : [
458
+ args[0],
459
+ null,
460
+ (args[1] === null ? args[2] : args[1]) || {}
461
+ ];
462
+ };
463
+ const useSWRConfig = () => {
464
+ const parentConfig = reactExports.useContext(SWRConfigContext);
465
+ const mergedConfig = reactExports.useMemo(() => mergeObjects(defaultConfig, parentConfig), [
466
+ parentConfig
467
+ ]);
468
+ return mergedConfig;
469
+ };
470
+ const middleware = (useSWRNext) => (key_, fetcher_, config) => {
471
+ const fetcher = fetcher_ && ((...args) => {
472
+ const [key] = serialize(key_);
473
+ const [, , , PRELOAD] = SWRGlobalState.get(cache);
474
+ if (key.startsWith(INFINITE_PREFIX)) {
475
+ return fetcher_(...args);
476
+ }
477
+ const req = PRELOAD[key];
478
+ if (isUndefined(req)) return fetcher_(...args);
479
+ delete PRELOAD[key];
480
+ return req;
481
+ });
482
+ return useSWRNext(key_, fetcher, config);
483
+ };
484
+ const BUILT_IN_MIDDLEWARE = use$1.concat(middleware);
485
+ const withArgs = (hook) => {
486
+ return function useSWRArgs(...args) {
487
+ const fallbackConfig = useSWRConfig();
488
+ const [key, fn, _config] = normalize(args);
489
+ const config = mergeConfigs(fallbackConfig, _config);
490
+ let next = hook;
491
+ const { use: use2 } = config;
492
+ const middleware2 = (use2 || []).concat(BUILT_IN_MIDDLEWARE);
493
+ for (let i = middleware2.length; i--; ) {
494
+ next = middleware2[i](next);
495
+ }
496
+ return next(key, fn || config.fetcher || null, config);
497
+ };
498
+ };
499
+ const subscribeCallback = (key, callbacks, callback) => {
500
+ const keyedRevalidators = callbacks[key] || (callbacks[key] = []);
501
+ keyedRevalidators.push(callback);
502
+ return () => {
503
+ const index = keyedRevalidators.indexOf(callback);
504
+ if (index >= 0) {
505
+ keyedRevalidators[index] = keyedRevalidators[keyedRevalidators.length - 1];
506
+ keyedRevalidators.pop();
507
+ }
508
+ };
509
+ };
510
+ setupDevTools();
511
+ const use = React.use || // This extra generic is to avoid TypeScript mixing up the generic and JSX sytax
512
+ // and emitting an error.
513
+ // We assume that this is only for the `use(thenable)` case, not `use(context)`.
514
+ // https://github.com/facebook/react/blob/aed00dacfb79d17c53218404c52b1c7aa59c4a89/packages/react-server/src/ReactFizzThenable.js#L45
515
+ ((thenable) => {
516
+ switch (thenable.status) {
517
+ case "pending":
518
+ throw thenable;
519
+ case "fulfilled":
520
+ return thenable.value;
521
+ case "rejected":
522
+ throw thenable.reason;
523
+ default:
524
+ thenable.status = "pending";
525
+ thenable.then((v) => {
526
+ thenable.status = "fulfilled";
527
+ thenable.value = v;
528
+ }, (e) => {
529
+ thenable.status = "rejected";
530
+ thenable.reason = e;
531
+ });
532
+ throw thenable;
533
+ }
534
+ });
535
+ const WITH_DEDUPE = {
536
+ dedupe: true
537
+ };
538
+ const resolvedUndef = Promise.resolve(UNDEFINED);
539
+ const sub = () => noop;
540
+ const useSWRHandler = (_key, fetcher, config) => {
541
+ const { cache: cache2, compare: compare2, suspense, fallbackData, revalidateOnMount, revalidateIfStale, refreshInterval, refreshWhenHidden, refreshWhenOffline, keepPreviousData, strictServerPrefetchWarning } = config;
542
+ const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = SWRGlobalState.get(cache2);
543
+ const [key, fnArg] = serialize(_key);
544
+ const initialMountedRef = reactExports.useRef(false);
545
+ const unmountedRef = reactExports.useRef(false);
546
+ const keyRef = reactExports.useRef(key);
547
+ const fetcherRef = reactExports.useRef(fetcher);
548
+ const configRef = reactExports.useRef(config);
549
+ const getConfig = () => configRef.current;
550
+ const isActive = () => getConfig().isVisible() && getConfig().isOnline();
551
+ const [getCache, setCache, subscribeCache, getInitialCache] = createCacheHelper(cache2, key);
552
+ const stateDependencies = reactExports.useRef({}).current;
553
+ const fallback = isUndefined(fallbackData) ? isUndefined(config.fallback) ? UNDEFINED : config.fallback[key] : fallbackData;
554
+ const isEqual = (prev, current) => {
555
+ for (const _ in stateDependencies) {
556
+ const t = _;
557
+ if (t === "data") {
558
+ if (!compare2(prev[t], current[t])) {
559
+ if (!isUndefined(prev[t])) {
560
+ return false;
561
+ }
562
+ if (!compare2(returnedData, current[t])) {
563
+ return false;
564
+ }
565
+ }
566
+ } else {
567
+ if (current[t] !== prev[t]) {
568
+ return false;
569
+ }
570
+ }
571
+ }
572
+ return true;
573
+ };
574
+ const isInitialMount = !initialMountedRef.current;
575
+ const getSnapshot = reactExports.useMemo(() => {
576
+ const cachedData2 = getCache();
577
+ const initialData = getInitialCache();
578
+ const getSelectedCache = (state) => {
579
+ const snapshot = mergeObjects(state);
580
+ delete snapshot._k;
581
+ const shouldStartRequest = (() => {
582
+ if (!key) return false;
583
+ if (!fetcher) return false;
584
+ if (getConfig().isPaused()) return false;
585
+ if (isInitialMount && !isUndefined(revalidateOnMount)) return revalidateOnMount;
586
+ const data2 = !isUndefined(fallback) ? fallback : snapshot.data;
587
+ if (suspense) return isUndefined(data2) || revalidateIfStale;
588
+ return isUndefined(data2) || revalidateIfStale;
589
+ })();
590
+ if (!shouldStartRequest) {
591
+ return snapshot;
592
+ }
593
+ return {
594
+ isValidating: true,
595
+ isLoading: true,
596
+ ...snapshot
597
+ };
598
+ };
599
+ const clientSnapshot = getSelectedCache(cachedData2);
600
+ const serverSnapshot = cachedData2 === initialData ? clientSnapshot : getSelectedCache(initialData);
601
+ let memorizedSnapshot = clientSnapshot;
602
+ return [
603
+ () => {
604
+ const newSnapshot = getSelectedCache(getCache());
605
+ const compareResult = isEqual(newSnapshot, memorizedSnapshot);
606
+ if (compareResult) {
607
+ memorizedSnapshot.data = newSnapshot.data;
608
+ memorizedSnapshot.isLoading = newSnapshot.isLoading;
609
+ memorizedSnapshot.isValidating = newSnapshot.isValidating;
610
+ memorizedSnapshot.error = newSnapshot.error;
611
+ return memorizedSnapshot;
612
+ } else {
613
+ memorizedSnapshot = newSnapshot;
614
+ return newSnapshot;
615
+ }
616
+ },
617
+ () => serverSnapshot
618
+ ];
619
+ }, [
620
+ cache2,
621
+ key
622
+ ]);
623
+ const cached = shimExports.useSyncExternalStore(reactExports.useCallback(
624
+ (callback) => subscribeCache(key, (current, prev) => {
625
+ if (!isEqual(prev, current)) callback();
626
+ }),
627
+ // eslint-disable-next-line react-hooks/exhaustive-deps
628
+ [
629
+ cache2,
630
+ key
631
+ ]
632
+ ), getSnapshot[0], getSnapshot[1]);
633
+ const hasRevalidator = EVENT_REVALIDATORS[key] && EVENT_REVALIDATORS[key].length > 0;
634
+ const cachedData = cached.data;
635
+ const data = isUndefined(cachedData) ? fallback && isPromiseLike(fallback) ? use(fallback) : fallback : cachedData;
636
+ const error = cached.error;
637
+ const laggyDataRef = reactExports.useRef(data);
638
+ const returnedData = keepPreviousData ? isUndefined(cachedData) ? isUndefined(laggyDataRef.current) ? data : laggyDataRef.current : cachedData : data;
639
+ const hasKeyButNoData = key && isUndefined(data);
640
+ const hydrationRef = reactExports.useRef(null);
641
+ !IS_SERVER && // getServerSnapshot is only called during hydration
642
+ // eslint-disable-next-line react-hooks/rules-of-hooks
643
+ shimExports.useSyncExternalStore(sub, () => {
644
+ hydrationRef.current = false;
645
+ return hydrationRef;
646
+ }, () => {
647
+ hydrationRef.current = true;
648
+ return hydrationRef;
649
+ });
650
+ const isHydration = hydrationRef.current;
651
+ if (strictServerPrefetchWarning && isHydration && !suspense && hasKeyButNoData) {
652
+ console.warn(`Missing pre-initiated data for serialized key "${key}" during server-side rendering. Data fetching should be initiated on the server and provided to SWR via fallback data. You can set "strictServerPrefetchWarning: false" to disable this warning.`);
653
+ }
654
+ const shouldDoInitialRevalidation = (() => {
655
+ if (!key || !fetcher) return false;
656
+ if (getConfig().isPaused()) return false;
657
+ if (hasRevalidator && !isUndefined(error)) return false;
658
+ if (isInitialMount && !isUndefined(revalidateOnMount)) return revalidateOnMount;
659
+ if (suspense) return isUndefined(data) ? false : revalidateIfStale;
660
+ return isUndefined(data) || revalidateIfStale;
661
+ })();
662
+ const defaultValidatingState = isInitialMount && shouldDoInitialRevalidation;
663
+ const isValidating = isUndefined(cached.isValidating) ? defaultValidatingState : cached.isValidating;
664
+ const isLoading = isUndefined(cached.isLoading) ? defaultValidatingState : cached.isLoading;
665
+ const revalidate = reactExports.useCallback(
666
+ async (revalidateOpts) => {
667
+ const currentFetcher = fetcherRef.current;
668
+ if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) {
669
+ return false;
670
+ }
671
+ let newData;
672
+ let startAt;
673
+ let loading = true;
674
+ const opts = revalidateOpts || {};
675
+ const shouldStartNewRequest = !FETCH[key] || !opts.dedupe;
676
+ const callbackSafeguard = () => {
677
+ if (IS_REACT_LEGACY) {
678
+ return !unmountedRef.current && key === keyRef.current && initialMountedRef.current;
679
+ }
680
+ return key === keyRef.current;
681
+ };
682
+ const finalState = {
683
+ isValidating: false,
684
+ isLoading: false
685
+ };
686
+ const finishRequestAndUpdateState = () => {
687
+ setCache(finalState);
688
+ };
689
+ const cleanupState = () => {
690
+ const requestInfo = FETCH[key];
691
+ if (requestInfo && requestInfo[1] === startAt) {
692
+ delete FETCH[key];
693
+ }
694
+ };
695
+ const initialState = {
696
+ isValidating: true
697
+ };
698
+ if (isUndefined(getCache().data)) {
699
+ initialState.isLoading = true;
700
+ }
701
+ try {
702
+ if (shouldStartNewRequest) {
703
+ setCache(initialState);
704
+ if (config.loadingTimeout && isUndefined(getCache().data)) {
705
+ setTimeout(() => {
706
+ if (loading && callbackSafeguard()) {
707
+ getConfig().onLoadingSlow(key, config);
708
+ }
709
+ }, config.loadingTimeout);
710
+ }
711
+ FETCH[key] = [
712
+ currentFetcher(fnArg),
713
+ getTimestamp()
714
+ ];
715
+ }
716
+ ;
717
+ [newData, startAt] = FETCH[key];
718
+ newData = await newData;
719
+ if (shouldStartNewRequest) {
720
+ setTimeout(cleanupState, config.dedupingInterval);
721
+ }
722
+ if (!FETCH[key] || FETCH[key][1] !== startAt) {
723
+ if (shouldStartNewRequest) {
724
+ if (callbackSafeguard()) {
725
+ getConfig().onDiscarded(key);
726
+ }
727
+ }
728
+ return false;
729
+ }
730
+ finalState.error = UNDEFINED;
731
+ const mutationInfo = MUTATION[key];
732
+ if (!isUndefined(mutationInfo) && // case 1
733
+ (startAt <= mutationInfo[0] || // case 2
734
+ startAt <= mutationInfo[1] || // case 3
735
+ mutationInfo[1] === 0)) {
736
+ finishRequestAndUpdateState();
737
+ if (shouldStartNewRequest) {
738
+ if (callbackSafeguard()) {
739
+ getConfig().onDiscarded(key);
740
+ }
741
+ }
742
+ return false;
743
+ }
744
+ const cacheData = getCache().data;
745
+ finalState.data = compare2(cacheData, newData) ? cacheData : newData;
746
+ if (shouldStartNewRequest) {
747
+ if (callbackSafeguard()) {
748
+ getConfig().onSuccess(newData, key, config);
749
+ }
750
+ }
751
+ } catch (err) {
752
+ cleanupState();
753
+ const currentConfig = getConfig();
754
+ const { shouldRetryOnError } = currentConfig;
755
+ if (!currentConfig.isPaused()) {
756
+ finalState.error = err;
757
+ if (shouldStartNewRequest && callbackSafeguard()) {
758
+ currentConfig.onError(err, key, currentConfig);
759
+ if (shouldRetryOnError === true || isFunction(shouldRetryOnError) && shouldRetryOnError(err)) {
760
+ if (!getConfig().revalidateOnFocus || !getConfig().revalidateOnReconnect || isActive()) {
761
+ currentConfig.onErrorRetry(err, key, currentConfig, (_opts) => {
762
+ const revalidators = EVENT_REVALIDATORS[key];
763
+ if (revalidators && revalidators[0]) {
764
+ revalidators[0](ERROR_REVALIDATE_EVENT, _opts);
765
+ }
766
+ }, {
767
+ retryCount: (opts.retryCount || 0) + 1,
768
+ dedupe: true
769
+ });
770
+ }
771
+ }
772
+ }
773
+ }
774
+ }
775
+ loading = false;
776
+ finishRequestAndUpdateState();
777
+ return true;
778
+ },
779
+ // `setState` is immutable, and `eventsCallback`, `fnArg`, and
780
+ // `keyValidating` are depending on `key`, so we can exclude them from
781
+ // the deps array.
782
+ //
783
+ // FIXME:
784
+ // `fn` and `config` might be changed during the lifecycle,
785
+ // but they might be changed every render like this.
786
+ // `useSWR('key', () => fetch('/api/'), { suspense: true })`
787
+ // So we omit the values from the deps array
788
+ // even though it might cause unexpected behaviors.
789
+ // eslint-disable-next-line react-hooks/exhaustive-deps
790
+ [
791
+ key,
792
+ cache2
793
+ ]
794
+ );
795
+ const boundMutate = reactExports.useCallback(
796
+ // Use callback to make sure `keyRef.current` returns latest result every time
797
+ (...args) => {
798
+ return internalMutate(cache2, keyRef.current, ...args);
799
+ },
800
+ // eslint-disable-next-line react-hooks/exhaustive-deps
801
+ []
802
+ );
803
+ useIsomorphicLayoutEffect(() => {
804
+ fetcherRef.current = fetcher;
805
+ configRef.current = config;
806
+ if (!isUndefined(cachedData)) {
807
+ laggyDataRef.current = cachedData;
808
+ }
809
+ });
810
+ useIsomorphicLayoutEffect(() => {
811
+ if (!key) return;
812
+ const softRevalidate = revalidate.bind(UNDEFINED, WITH_DEDUPE);
813
+ let nextFocusRevalidatedAt = 0;
814
+ if (getConfig().revalidateOnFocus) {
815
+ const initNow = Date.now();
816
+ nextFocusRevalidatedAt = initNow + getConfig().focusThrottleInterval;
817
+ }
818
+ const onRevalidate = (type, opts = {}) => {
819
+ if (type == FOCUS_EVENT) {
820
+ const now = Date.now();
821
+ if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) {
822
+ nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval;
823
+ softRevalidate();
824
+ }
825
+ } else if (type == RECONNECT_EVENT) {
826
+ if (getConfig().revalidateOnReconnect && isActive()) {
827
+ softRevalidate();
828
+ }
829
+ } else if (type == MUTATE_EVENT) {
830
+ return revalidate();
831
+ } else if (type == ERROR_REVALIDATE_EVENT) {
832
+ return revalidate(opts);
833
+ }
834
+ return;
835
+ };
836
+ const unsubEvents = subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate);
837
+ unmountedRef.current = false;
838
+ keyRef.current = key;
839
+ initialMountedRef.current = true;
840
+ setCache({
841
+ _k: fnArg
842
+ });
843
+ if (shouldDoInitialRevalidation) {
844
+ if (!FETCH[key]) {
845
+ if (isUndefined(data) || IS_SERVER) {
846
+ softRevalidate();
847
+ } else {
848
+ rAF(softRevalidate);
849
+ }
850
+ }
851
+ }
852
+ return () => {
853
+ unmountedRef.current = true;
854
+ unsubEvents();
855
+ };
856
+ }, [
857
+ key
858
+ ]);
859
+ useIsomorphicLayoutEffect(() => {
860
+ let timer;
861
+ function next() {
862
+ const interval = isFunction(refreshInterval) ? refreshInterval(getCache().data) : refreshInterval;
863
+ if (interval && timer !== -1) {
864
+ timer = setTimeout(execute, interval);
865
+ }
866
+ }
867
+ function execute() {
868
+ if (!getCache().error && (refreshWhenHidden || getConfig().isVisible()) && (refreshWhenOffline || getConfig().isOnline())) {
869
+ revalidate(WITH_DEDUPE).then(next);
870
+ } else {
871
+ next();
872
+ }
873
+ }
874
+ next();
875
+ return () => {
876
+ if (timer) {
877
+ clearTimeout(timer);
878
+ timer = -1;
879
+ }
880
+ };
881
+ }, [
882
+ refreshInterval,
883
+ refreshWhenHidden,
884
+ refreshWhenOffline,
885
+ key
886
+ ]);
887
+ reactExports.useDebugValue(returnedData);
888
+ if (suspense) {
889
+ if (!IS_REACT_LEGACY && IS_SERVER && hasKeyButNoData) {
890
+ throw new Error("Fallback data is required when using Suspense in SSR.");
891
+ }
892
+ if (hasKeyButNoData) {
893
+ fetcherRef.current = fetcher;
894
+ configRef.current = config;
895
+ unmountedRef.current = false;
896
+ }
897
+ const req = PRELOAD[key];
898
+ const mutateReq = !isUndefined(req) && hasKeyButNoData ? boundMutate(req) : resolvedUndef;
899
+ use(mutateReq);
900
+ if (!isUndefined(error) && hasKeyButNoData) {
901
+ throw error;
902
+ }
903
+ const revalidation = hasKeyButNoData ? revalidate(WITH_DEDUPE) : resolvedUndef;
904
+ if (!isUndefined(returnedData) && hasKeyButNoData) {
905
+ revalidation.status = "fulfilled";
906
+ revalidation.value = true;
907
+ }
908
+ use(revalidation);
909
+ }
910
+ const swrResponse = {
911
+ mutate: boundMutate,
912
+ get data() {
913
+ stateDependencies.data = true;
914
+ return returnedData;
915
+ },
916
+ get error() {
917
+ stateDependencies.error = true;
918
+ return error;
919
+ },
920
+ get isValidating() {
921
+ stateDependencies.isValidating = true;
922
+ return isValidating;
923
+ },
924
+ get isLoading() {
925
+ stateDependencies.isLoading = true;
926
+ return isLoading;
927
+ }
928
+ };
929
+ return swrResponse;
930
+ };
931
+ const SWRConfig = OBJECT.defineProperty(SWRConfig$1, "defaultValue", {
932
+ value: defaultConfig
933
+ });
934
+ const useSWR = withArgs(useSWRHandler);
935
+ export {
936
+ SWRConfig as S,
937
+ useSWR as u
938
+ };