New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@better-typed/react-hyper-fetch

Package Overview
Dependencies
Maintainers
2
Versions
55
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@better-typed/react-hyper-fetch - npm Package Compare versions

Comparing version 0.9.0 to 0.9.5

__tests__/features/helpers/use-tracked-state/use-tacked-state.actions.spec.ts

114

__tests__/features/helpers/use-command-events/use-command-events.utils.spec.ts

@@ -1,101 +0,31 @@

import { isEmpty, isEqual } from "utils";
import { startServer, resetInterceptors, stopServer } from "../../../server";
import { createCommand, renderUseCommandEvents } from "../../../utils";
describe("useCommand [ Utils ]", () => {
describe("when isEmpty gets triggered", () => {
it("should return true for empty array or object", async () => {
expect(isEmpty([])).toBe(true);
expect(isEmpty({})).toBe(true);
});
describe("useCommandEvents [ Utils ]", () => {
let command = createCommand();
it("should return false", async () => {
expect(isEmpty(null)).toBe(false);
expect(isEmpty(new Date())).toBe(false);
expect(isEmpty(NaN)).toBe(false);
expect(isEmpty("")).toBe(false);
expect(isEmpty(false)).toBe(false);
expect(isEmpty(undefined)).toBe(false);
expect(isEmpty(0)).toBe(false);
expect(isEmpty(true)).toBe(false);
expect(isEmpty(123)).toBe(false);
expect(isEmpty("123")).toBe(false);
expect(isEmpty([1, 2, 3])).toBe(false);
expect(isEmpty({ something: 1 })).toBe(false);
});
beforeAll(() => {
startServer();
});
describe("when isEqual gets triggered", () => {
it("should return false for non equal values", async () => {
expect(isEqual(true, false)).toBe(false);
expect(isEqual(null, {})).toBe(false);
expect(isEqual(new Date(), {})).toBe(false);
expect(isEqual(new Date(), null)).toBe(false);
expect(isEqual(NaN, {})).toBe(false);
expect(isEqual(NaN, null)).toBe(false);
expect(isEqual("1", 1)).toBe(false);
expect(isEqual(0, -1)).toBe(false);
expect(isEqual("2", "3")).toBe(false);
expect(isEqual([], [1])).toBe(false);
expect(isEqual([1], [2])).toBe(false);
expect(isEqual(["1"], [1])).toBe(false);
expect(isEqual([null], [NaN])).toBe(false);
expect(isEqual([null], [new Date()])).toBe(false);
expect(isEqual([null], [{}])).toBe(false);
expect(isEqual([new Date()], [{}])).toBe(false);
expect(isEqual([NaN], [{}])).toBe(false);
expect(isEqual([{ someKey: 1 }], [{ someKey: 2 }])).toBe(false);
expect(isEqual([{ someKey: "1" }], [{ someKey: 1 }])).toBe(false);
expect(isEqual([{ someKey: null }], [{ someKey: {} }])).toBe(false);
expect(isEqual([{ someKey: null }], [{ someKey: NaN }])).toBe(false);
expect(isEqual([{ someKey: null }], [{ someKey: new Date() }])).toBe(false);
expect(isEqual([{ someKey: {} }], [{ someKey: new Date() }])).toBe(false);
expect(isEqual([{ someKey: {} }], [{ someKey: NaN }])).toBe(false);
expect(isEqual({ someKey: 1 }, { otherKey: 1 })).toBe(false);
expect(isEqual({ someKey: 1 }, { someKey: 1, otherKey: 1 })).toBe(false);
expect(isEqual({ someKey: 1 }, { someKey: 2 })).toBe(false);
expect(isEqual({ someKey: "1" }, { someKey: 1 })).toBe(false);
expect(isEqual({ someKey: null }, { someKey: {} })).toBe(false);
expect(isEqual({ someKey: null }, { someKey: NaN })).toBe(false);
expect(isEqual({ someKey: null }, { someKey: new Date() })).toBe(false);
expect(isEqual({ someKey: {} }, { someKey: new Date() })).toBe(false);
expect(isEqual({ someKey: {} }, { someKey: NaN })).toBe(false);
expect(isEqual({ someKey: 1 }, { otherKey: 1 })).toBe(false);
expect(isEqual({ someKey: 1 }, { someKey: 1, otherKey: 1 })).toBe(false);
});
afterEach(() => {
resetInterceptors();
});
it("should return true for equal arguments", async () => {
const date = new Date();
afterAll(() => {
stopServer();
});
expect(isEqual(true, true)).toBe(true);
expect(isEqual(false, false)).toBe(true);
expect(isEqual(undefined, undefined)).toBe(true);
expect(isEqual(null, null)).toBe(true);
expect(isEqual(date, date)).toBe(true);
expect(isEqual(date, date)).toBe(true);
expect(isEqual(NaN, NaN)).toBe(true);
expect(isEqual("1", "1")).toBe(true);
expect(isEqual(0, 0)).toBe(true);
expect(isEqual(1, 1)).toBe(true);
expect(isEqual("2", "2")).toBe(true);
expect(isEqual([], [])).toBe(true);
expect(isEqual([1], [1])).toBe(true);
expect(isEqual(["1"], ["1"])).toBe(true);
expect(isEqual([NaN], [NaN])).toBe(true);
expect(isEqual([date], [date])).toBe(true);
expect(isEqual([null], [null])).toBe(true);
expect(isEqual([{}], [{}])).toBe(true);
expect(isEqual([{ someKey: 1 }], [{ someKey: 1 }])).toBe(true);
expect(isEqual([{ someKey: "1" }], [{ someKey: "1" }])).toBe(true);
expect(isEqual([{ someKey: null }], [{ someKey: null }])).toBe(true);
expect(isEqual([{ someKey: NaN }], [{ someKey: NaN }])).toBe(true);
expect(isEqual([{ someKey: date }], [{ someKey: date }])).toBe(true);
expect(isEqual([{ someKey: {} }], [{ someKey: {} }])).toBe(true);
expect(isEqual({ someKey: 1, otherKey: 1 }, { someKey: 1, otherKey: 1 })).toBe(true);
expect(isEqual({ someKey: "1" }, { someKey: "1" })).toBe(true);
expect(isEqual({ someKey: {} }, { someKey: {} })).toBe(true);
expect(isEqual({ someKey: NaN }, { someKey: NaN })).toBe(true);
expect(isEqual({ someKey: null }, { someKey: null })).toBe(true);
expect(isEqual({ someKey: date }, { someKey: date })).toBe(true);
expect(isEqual({}, {})).toBe(true);
beforeEach(() => {
jest.resetModules();
command = createCommand();
});
describe("When handling lifecycle events", () => {
it("should not throw when removing non existing event", async () => {
const response = renderUseCommandEvents(command);
expect(response.result.current[1].removeLifecycleListener).not.toThrow();
});
});
});

@@ -1,7 +0,23 @@

import { startServer, resetInterceptors, stopServer, createRequestInterceptor } from "../../server";
import { act } from "react-dom/test-utils";
import { CacheValueType } from "@better-typed/hyper-fetch";
import { startServer, resetInterceptors, stopServer } from "../../server";
import { builder, createCommand } from "../../utils";
import { renderUseCache } from "../../utils/use-cache.utils";
import { testInitialState, testSuccessState } from "../../shared";
describe("useCache [ Base ]", () => {
let command = createCommand();
const cacheData: CacheValueType = {
data: [{ test: 1 }, null, 200],
details: {
retries: 0,
timestamp: +new Date(),
isFailed: false,
isCanceled: false,
isOffline: false,
},
cacheTime: command.cacheTime,
clearKey: command.builder.cache.clearKey,
};

@@ -29,3 +45,2 @@ beforeAll(() => {

it("should initialize with non-loading state", async () => {
createRequestInterceptor(command);
const { result } = renderUseCache(command);

@@ -40,3 +55,5 @@

it("should return empty state", async () => {
// Todo
const response = renderUseCache(command);
testInitialState(response, false);
});

@@ -48,6 +65,59 @@ });

it("should return state", async () => {
// Todo
builder.cache.set(command, cacheData.data, cacheData.details);
const response = renderUseCache(command);
await testSuccessState(cacheData.data[0], response);
expect(+response.result.current.timestamp).toBe(cacheData.details.timestamp);
expect(response.result.current.retries).toBe(0);
});
it("should allow to revalidate by Command", async () => {
const spy = jest.spyOn(builder.cache, "revalidate");
const { result } = renderUseCache(command);
act(() => {
result.current.revalidate(command);
});
expect(spy).toBeCalledTimes(1);
expect(spy).toBeCalledWith(command.cacheKey);
});
it("should allow to revalidate by RegExp", async () => {
const spy = jest.spyOn(builder.cache, "revalidate");
const { result } = renderUseCache(command);
act(() => {
result.current.revalidate(new RegExp(command.cacheKey));
});
expect(spy).toBeCalledTimes(1);
expect(spy).toBeCalledWith(new RegExp(command.cacheKey));
});
it("should allow to revalidate by cacheKey", async () => {
const spy = jest.spyOn(builder.cache, "revalidate");
const { result } = renderUseCache(command);
act(() => {
result.current.revalidate(command.cacheKey);
});
expect(spy).toBeCalledTimes(1);
expect(spy).toBeCalledWith(command.cacheKey);
});
it("should allow to revalidate by default key", async () => {
const spy = jest.spyOn(builder.cache, "revalidate");
const { result } = renderUseCache(command);
act(() => {
result.current.revalidate();
});
expect(spy).toBeCalledTimes(1);
expect(spy).toBeCalledWith(command.cacheKey);
});
});
});
});
import { act } from "@testing-library/react";
import { ClientResponseType } from "@better-typed/hyper-fetch";
import { createCommand, renderUseFetch, createCacheData, builder } from "../../utils";
import { createCommand, renderUseFetch, createCacheData, builder, sleep } from "../../utils";
import { startServer, resetInterceptors, stopServer, createRequestInterceptor } from "../../server";

@@ -57,3 +58,6 @@ import { testSuccessState, testErrorState, testInitialState, testCacheState, testBuilderIsolation } from "../../shared";

it("should allow to use initial data", async () => {
// Todo
const initialData: ClientResponseType<unknown, unknown> = [{ test: [1, 2, 3] }, null, 200];
const view = renderUseFetch(command, { disabled: true, initialData });
await testSuccessState(initialData[0], view);
});

@@ -64,3 +68,3 @@ it("should prefer cache data over initial data", async () => {

it("should make only one request", async () => {
const spy = jest.spyOn(builder.fetchDispatcher, "add");
const spy = jest.spyOn(builder, "client");
await testBuilderIsolation(builder);

@@ -71,2 +75,3 @@ const mock = createRequestInterceptor(command);

await testSuccessState(mock, view);
await sleep(50);
expect(spy).toBeCalledTimes(1);

@@ -73,0 +78,0 @@ });

@@ -0,1 +1,2 @@

import { waitFor } from "@testing-library/react";
import { act } from "react-dom/test-utils";

@@ -32,3 +33,2 @@ import { startServer, resetInterceptors, stopServer, createRequestInterceptor } from "../../server";

await waitForRender();
await testSuccessState(mock, response);

@@ -43,9 +43,6 @@

await waitForRender();
expect(spy).toBeCalledTimes(0);
});
it("should finish request when coming back online", async () => {
act(() => {
builder.appManager.setOnline(false);
});
builder.appManager.setOnline(false);

@@ -55,3 +52,2 @@ const mock = createRequestInterceptor(command);

await waitForRender();
act(() => {

@@ -62,2 +58,17 @@ builder.appManager.setOnline(true);

});
it("should refetch when coming back online", async () => {
const spy = jest.fn();
const mock = createRequestInterceptor(command);
const response = renderUseFetch(command, { refreshOnReconnect: true });
await testSuccessState(mock, response);
act(() => {
response.result.current.onRequestStart(spy);
builder.appManager.setOnline(false);
builder.appManager.setOnline(true);
});
await waitFor(() => {
expect(spy).toBeCalledTimes(1);
});
});
});

@@ -64,0 +75,0 @@ describe("when command offline attribute is set to true", () => {

@@ -26,2 +26,5 @@ import { startServer, resetInterceptors, stopServer } from "../../server";

});
it("should not override previous results by initialData", async () => {
// TODO
});
it("should cache pages on change", async () => {

@@ -28,0 +31,0 @@ // TODO

@@ -11,4 +11,4 @@ import { act } from "@testing-library/react";

refreshOnReconnect: true,
refreshOnTabBlur: true,
refreshOnTabFocus: true,
refreshOnBlur: true,
refreshOnFocus: true,
};

@@ -54,3 +54,3 @@

createRequestInterceptor(command);
const { result } = renderUseFetch(command, { ...hookOptions, refreshOnTabBlur: false });
const { result } = renderUseFetch(command, { ...hookOptions, refreshOnBlur: false });

@@ -69,3 +69,3 @@ act(() => {

createRequestInterceptor(command);
const { result } = renderUseFetch(command, { ...hookOptions, refreshOnTabBlur: false, refreshBlurred: false });
const { result } = renderUseFetch(command, { ...hookOptions, refreshOnBlur: false, refreshBlurred: false });

@@ -72,0 +72,0 @@ act(() => {

@@ -21,9 +21,17 @@ import { startServer, resetInterceptors, stopServer } from "../../server";

describe("when command retry attribute is set to false", () => {
it("should not retry request on failure", async () => {});
it("should not retry request on failure", async () => {
// Todo
});
});
describe("when command retry attribute is set to true", () => {
it("should retry request once", async () => {});
it("should retry request twice", async () => {});
it("should trigger retries with the config interval", async () => {});
it("should retry request once", async () => {
// Todo
});
it("should retry request twice", async () => {
// Todo
});
it("should trigger retries with the config interval", async () => {
// Todo
});
});
});

@@ -33,3 +33,3 @@ import { act, waitFor } from "@testing-library/react";

retries: 0,
timestamp: new Date(),
timestamp: +new Date(),
isFailed: false,

@@ -48,3 +48,3 @@ isCanceled: false,

retries: 0,
timestamp: new Date(),
timestamp: +new Date(),
isFailed: false,

@@ -51,0 +51,0 @@ isCanceled: false,

@@ -29,3 +29,3 @@ import { act, waitFor } from "@testing-library/react";

createRequestInterceptor(command, { delay: 0 });
const response = renderUseFetch(command, { refreshOnTabFocus: true });
const response = renderUseFetch(command, { refreshOnFocus: true });

@@ -46,3 +46,3 @@ await waitForRender();

createRequestInterceptor(command, { delay: 0 });
const response = renderUseFetch(command, { refreshOnTabBlur: true });
const response = renderUseFetch(command, { refreshOnBlur: true });

@@ -49,0 +49,0 @@ await waitForRender();

@@ -0,1 +1,2 @@

import { CommandInstance, ExtractClientReturnType } from "@better-typed/hyper-fetch";
import { act, waitFor } from "@testing-library/react";

@@ -6,3 +7,4 @@ import { startServer, resetInterceptors, stopServer, createRequestInterceptor } from "../../server";

describe("useSubmit [ Debounce ]", () => {
const options = { debounce: true, debounceTime: 100 };
const options = { debounce: true, debounceTime: 50 };
const maxDelay = 20;

@@ -49,6 +51,6 @@ let command = createCommand({ method: "POST" });

expect(startTime - submitTime).toBeGreaterThanOrEqual(100);
expect(startTime - submitTime).toBeLessThan(120);
expect(startTime - submitTime).toBeGreaterThanOrEqual(options.debounceTime);
expect(startTime - submitTime).toBeLessThan(options.debounceTime + maxDelay);
});
it("should debounce multiple request triggers by 100ms", async () => {
it("should debounce multiple request triggers by debounceTime", async () => {
const spy = jest.fn();

@@ -67,7 +69,7 @@ let submitTime = null;

response.result.current.submit();
await waitForRender(20);
await waitForRender(10);
response.result.current.submit();
await waitForRender(20);
await waitForRender(10);
response.result.current.submit();
await waitForRender(20);
await waitForRender(10);
response.result.current.submit();

@@ -80,6 +82,67 @@ });

expect(startTime - submitTime).toBeGreaterThanOrEqual(160);
expect(startTime - submitTime).toBeLessThan(180);
expect(startTime - submitTime).toBeGreaterThanOrEqual(options.debounceTime + 30);
expect(startTime - submitTime).toBeLessThan(options.debounceTime + maxDelay + 30);
expect(spy).toBeCalledTimes(1);
});
it("should resolve debounced methods", async () => {
createRequestInterceptor(command);
const response = renderUseSubmit(command, options);
let value: ExtractClientReturnType<CommandInstance>[] = [];
await act(async () => {
const promiseOne = await response.result.current.submit();
await waitForRender(1);
const promiseTwo = await response.result.current.submit();
await waitForRender(1);
const promiseThree = await response.result.current.submit();
await waitForRender(1);
const promiseFour = await response.result.current.submit();
value = [promiseOne, promiseTwo, promiseThree, promiseFour];
});
expect(value).toHaveLength(4);
const isResponse = (res: ExtractClientReturnType<CommandInstance>) => {
return !!res[0] && !res[1] && res[2] === 200;
};
expect(value).toSatisfyAny(isResponse);
expect(value).toHaveLength(4);
});
it("should change debounce time", async () => {
const newDebounceTime = 200;
const spy = jest.fn();
let submitTime = null;
let startTime = null;
createRequestInterceptor(command);
const response = renderUseSubmit(command, options);
await act(async () => {
await response.rerender({ debounceTime: newDebounceTime });
});
await waitForRender(1);
await act(async () => {
response.result.current.onSubmitRequestStart(() => {
spy();
startTime = +new Date();
});
submitTime = +new Date();
response.result.current.submit();
await waitForRender(10);
response.result.current.submit();
await waitForRender(10);
response.result.current.submit();
await waitForRender(10);
response.result.current.submit();
});
await waitFor(() => {
expect(startTime).not.toBeNull();
});
expect(startTime - submitTime).toBeGreaterThanOrEqual(newDebounceTime + 30);
expect(startTime - submitTime).toBeLessThan(newDebounceTime + maxDelay + 30);
expect(spy).toBeCalledTimes(1);
});
});

@@ -104,7 +167,7 @@ });

response.result.current.submit();
await waitForRender(20);
await waitForRender(10);
response.result.current.submit();
await waitForRender(20);
await waitForRender(10);
response.result.current.submit();
await waitForRender(20);
await waitForRender(10);
response.result.current.submit();

@@ -117,3 +180,3 @@ });

expect(startTime - submitTime).toBeLessThan(100);
expect(startTime - submitTime).toBeLessThan(options.debounceTime + 30);
expect(spy).toBeCalledTimes(4);

@@ -120,0 +183,0 @@ });

@@ -48,2 +48,49 @@ import { act } from "@testing-library/react";

});
it("should allow to revalidate by Command", async () => {
const spy = jest.spyOn(builder.cache, "revalidate");
const { result } = renderUseSubmit(commandSubmit);
act(() => {
result.current.revalidate(commandSubmit);
});
expect(spy).toBeCalledTimes(1);
expect(spy).toBeCalledWith(commandSubmit.cacheKey);
});
it("should allow to revalidate by RegExp", async () => {
const spy = jest.spyOn(builder.cache, "revalidate");
const { result } = renderUseSubmit(commandSubmit);
act(() => {
result.current.revalidate(new RegExp(commandSubmit.cacheKey));
});
expect(spy).toBeCalledTimes(1);
expect(spy).toBeCalledWith(new RegExp(commandSubmit.cacheKey));
});
it("should allow to revalidate by cacheKey", async () => {
const spy = jest.spyOn(builder.cache, "revalidate");
const { result } = renderUseSubmit(commandSubmit);
act(() => {
result.current.revalidate(commandSubmit.cacheKey);
});
expect(spy).toBeCalledTimes(1);
expect(spy).toBeCalledWith(commandSubmit.cacheKey);
});
it("should not allow to revalidate without key", async () => {
const spy = jest.spyOn(builder.cache, "revalidate");
const { result } = renderUseSubmit(commandSubmit);
act(() => {
result.current.revalidate(undefined as string);
});
expect(spy).toBeCalledTimes(0);
});
});

@@ -93,3 +93,3 @@ import { act } from "@testing-library/react";

const commandWithParams = createCommand({ endpoint: "/users/:userId" });
createRequestInterceptor(commandWithParams.setParams({ userId: 1 }));
createRequestInterceptor(commandWithParams.setParams({ userId: 1 } as any));
const response = renderUseSubmit(commandWithParams);

@@ -101,3 +101,3 @@

});
response.result.current.submit({ params: { userId: 1 } });
response.result.current.submit({ params: { userId: 1 } } as any);
});

@@ -132,3 +132,8 @@

});
it("should throw when hook is disabled", async () => {
const response = renderUseSubmit(command, { disabled: true });
expect(response.result.current.submit).toThrow();
});
});
});

@@ -8,3 +8,3 @@ import { waitFor, RenderHookResult } from "@testing-library/react";

export const testInitialState = <H extends RenderHookResult<any, any>>(render: H) => {
export const testInitialState = <H extends RenderHookResult<any, any>>(render: H, expectedLoading = true) => {
const response = getCurrentState(render);

@@ -17,3 +17,3 @@ expect(response.data).toBe(null);

} else {
expect(response.loading).toBe(true);
expect(response.loading).toBe(expectedLoading);
}

@@ -34,2 +34,4 @@ };

expect(response.status).toBe(200);
expect(response.retries).toBeNumber();
expect(response.timestamp).toBeDate();
if (typeof response.submitting === "boolean") {

@@ -57,2 +59,4 @@ expect(response.submitting).toBe(false);

expect(response.error).toBeDefined();
expect(response.retries).toBeNumber();
expect(response.timestamp).toBeDate();
expect((status >= 400 && status < 600) || status === 0).toBeTruthy();

@@ -59,0 +63,0 @@ if (typeof response.submitting === "boolean") {

@@ -19,3 +19,3 @@ import {

retries: 0,
timestamp: new Date(),
timestamp: +new Date(),
isFailed: false,

@@ -33,4 +33,5 @@ isCanceled: false,

cacheTime: 1000,
clearKey: command.builder.cache.clearKey,
});
return [dataValue, detailsValue] as const;
};

@@ -11,1 +11,3 @@ export * from "./builder.utils";

export * from "./use-queue.utils";
export * from "./use-command-events.utils";
export * from "./use-tracked-state.utils";

@@ -1,3 +0,3 @@

import { CommandInstance, getCommandDispatcher } from "@better-typed/hyper-fetch";
import { renderHook } from "@testing-library/react";
import { CommandInstance, getCommandDispatcher, getProgressData } from "@better-typed/hyper-fetch";

@@ -25,1 +25,43 @@ import { useQueue, UseQueueOptionsType } from "use-queue";

};
export const emitDownloadProgress = <T extends CommandInstance>(
requestId: string,
command: T,
options?: {
total: number;
loaded: number;
},
) => {
const values = options || { total: 50, loaded: 25 };
const startTimestamp = new Date(+new Date() - 20000);
const progressTimestamp = new Date();
const progress = getProgressData(startTimestamp, progressTimestamp, values);
command.builder.commandManager.events.emitDownloadProgress(command.queueKey, requestId, progress, {
requestId,
command,
});
return [startTimestamp, progressTimestamp];
};
export const emitUploadProgress = <T extends CommandInstance>(
requestId: string,
command: T,
options?: {
total: number;
loaded: number;
},
) => {
const values = options || { total: 50, loaded: 25 };
const startTimestamp = new Date(+new Date() - 20000);
const progressTimestamp = new Date();
const progress = getProgressData(startTimestamp, progressTimestamp, values);
command.builder.commandManager.events.emitUploadProgress(command.queueKey, requestId, progress, {
requestId,
command,
});
return [startTimestamp, progressTimestamp];
};

@@ -7,3 +7,6 @@ import { CommandInstance } from "@better-typed/hyper-fetch";

export const renderUseSubmit = <T extends CommandInstance>(command: T, options?: UseSubmitOptionsType<T>) => {
return renderHook(() => useSubmit(command, { dependencyTracking: false, ...options }));
return renderHook((rerenderOptions: UseSubmitOptionsType<CommandInstance> & { command?: CommandInstance }) => {
const { command: cmd, ...rest } = rerenderOptions || {};
return useSubmit(cmd || command, { dependencyTracking: false, ...options, ...rest });
});
};
import { CommandInstance } from "@better-typed/hyper-fetch";
import { UseCommandEventsReturnType, UseCommandEventsOptionsType } from "./..";
import { UseCommandEventsReturnType, UseCommandEventsPropsType } from "./..";
/**

@@ -9,2 +9,2 @@ * This is helper hook that handles main Hyper-Fetch event/data flow

*/
export declare const useCommandEvents: <T extends CommandInstance>({ command, dispatcher, logger, actions, setCacheData, }: UseCommandEventsOptionsType<T>) => UseCommandEventsReturnType<T>;
export declare const useCommandEvents: <T extends CommandInstance>({ command, dispatcher, logger, actions, setCacheData, }: UseCommandEventsPropsType<T>) => UseCommandEventsReturnType<T>;

@@ -9,3 +9,3 @@ import { Dispatcher, ExtractError, CacheValueType, ExtractResponse, LoggerType, FetchProgressType, ExtractClientReturnType, CommandEventDetails, CommandInstance, CommandResponseDetails } from "@better-typed/hyper-fetch";

}>;
export declare type UseCommandEventsOptionsType<T extends CommandInstance> = {
export declare type UseCommandEventsPropsType<T extends CommandInstance> = {
command: T;

@@ -74,9 +74,9 @@ dispatcher: Dispatcher;

};
export declare type OnSuccessCallbackType<Command extends CommandInstance> = (params: CallbackParameters<Command, ExtractResponse<Command>>) => void;
export declare type OnErrorCallbackType<Command extends CommandInstance> = (params: CallbackParameters<Command, ExtractError<Command>>) => void;
export declare type OnFinishedCallbackType<Command extends CommandInstance> = (params: CallbackParameters<Command, ExtractClientReturnType<Command>>) => void;
export declare type OnSuccessCallbackType<Command extends CommandInstance> = (params: CallbackParameters<Command, ExtractResponse<Command>>) => void | Promise<void>;
export declare type OnErrorCallbackType<Command extends CommandInstance> = (params: CallbackParameters<Command, ExtractError<Command>>) => void | Promise<void>;
export declare type OnFinishedCallbackType<Command extends CommandInstance> = (params: CallbackParameters<Command, ExtractClientReturnType<Command>>) => void | Promise<void>;
export declare type OnStartCallbackType<Command extends CommandInstance> = (params: {
details: CommandEventDetails<Command>;
command: Command;
}) => void;
export declare type OnProgressCallbackType = <Command extends CommandInstance>(progress: FetchProgressType, details: CommandEventDetails<Command>) => void;
}) => void | Promise<void>;
export declare type OnProgressCallbackType = <Command extends CommandInstance>(progress: FetchProgressType, details: CommandEventDetails<Command>) => void | Promise<void>;

@@ -11,2 +11,2 @@ import { CommandInstance } from "@better-typed/hyper-fetch";

*/
export declare const UseTrackedState: <T extends CommandInstance>({ command, dispatcher, initialData, deepCompare, dependencyTracking, defaultCacheEmitting, }: UseTrackedStateProps<T>) => UseTrackedStateReturn<T>;
export declare const useTrackedState: <T extends CommandInstance>({ command, dispatcher, initialData, deepCompare, dependencyTracking, defaultCacheEmitting, }: UseTrackedStateProps<T>) => UseTrackedStateReturn<T>;
import { CacheValueType, NullableType, CommandInstance, ClientResponseType, ExtractResponse, ExtractError, ExtractClientReturnType, Dispatcher } from "@better-typed/hyper-fetch";
import { UseTrackedStateType } from "./..";
export declare const getDetailsState: (state?: UseTrackedStateType<CommandInstance>, details?: Partial<CacheValueType<unknown, unknown>["details"]>) => CacheValueType<unknown, unknown>["details"];
export declare const isStaleCacheData: (cacheTime: NullableType<number>, cacheTimestamp: NullableType<Date | number>) => boolean;
export declare const isStaleCacheData: (cacheTime: number, cacheTimestamp: NullableType<Date | number>) => boolean;
export declare const getValidCacheData: <T extends CommandInstance>(command: T, initialData: ExtractClientReturnType<T>, cacheData: CacheValueType<ExtractResponse<T>, ExtractError<T>>) => CacheValueType<ExtractResponse<T>, ExtractError<T>>;
export declare const getTimestamp: (timestamp?: NullableType<number | Date>) => Date;
export declare const responseToCacheValue: <T>(response: ClientResponseType<ExtractResponse<T>, ExtractError<T>>) => NullableType<CacheValueType>;
export declare const getInitialState: <T extends CommandInstance>(initialData: ClientResponseType<ExtractResponse<T>, ExtractError<T>>, dispatcher: Dispatcher, command: T) => UseTrackedStateType<T>;

@@ -1,2 +0,2 @@

var ie=Object.defineProperty,Be=Object.defineProperties,je=Object.getOwnPropertyDescriptor,Ne=Object.getOwnPropertyDescriptors,We=Object.getOwnPropertyNames,De=Object.getOwnPropertySymbols;var Ue=Object.prototype.hasOwnProperty,$e=Object.prototype.propertyIsEnumerable;var Oe=(e,t,r)=>t in e?ie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,k=(e,t)=>{for(var r in t||(t={}))Ue.call(t,r)&&Oe(e,r,t[r]);if(De)for(var r of De(t))$e.call(t,r)&&Oe(e,r,t[r]);return e},P=(e,t)=>Be(e,Ne(t));var Ge=(e,t)=>{for(var r in t)ie(e,r,{get:t[r],enumerable:!0})},Je=(e,t,r,g)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of We(t))!Ue.call(e,i)&&i!==r&&ie(e,i,{get:()=>t[i],enumerable:!(g=je(t,i))||g.enumerable});return e};var ze=e=>Je(ie({},"__esModule",{value:!0}),e);var re=(e,t,r)=>new Promise((g,i)=>{var C=a=>{try{u(r.next(a))}catch(y){i(y)}},d=a=>{try{u(r.throw(a))}catch(y){i(y)}},u=a=>a.done?g(a.value):Promise.resolve(a.value).then(C,d);u((r=r.apply(e,t)).next())});var et={};Ge(et,{UseTrackedState:()=>G,getDetailsState:()=>N,getInitialState:()=>de,getTimestamp:()=>Fe,getValidCacheData:()=>qe,initialState:()=>j,isEmpty:()=>he,isEqual:()=>se,isStaleCacheData:()=>me,responseToCacheValue:()=>He,useAppManager:()=>Ve,useCache:()=>_e,useCacheDefaultOptions:()=>ee,useCommandEvents:()=>$,useDebounce:()=>_,useFetch:()=>Xe,useFetchDefaultOptions:()=>v,useQueue:()=>Ze,useQueueDefaultOptions:()=>Te,useSubmit:()=>Ye,useSubmitDefaultOptions:()=>W});module.exports=ze(et);var Ie=require("react"),V=require("@better-typed/react-lifecycle-hooks"),ae=require("@better-typed/hyper-fetch");var L=require("react"),ke=require("@better-typed/hyper-fetch"),pe=require("@better-typed/react-lifecycle-hooks"),$=({command:e,dispatcher:t,logger:r,actions:g,setCacheData:i})=>{let{cache:C,commandManager:d}=e.builder,u=(0,pe.useIsMounted)(),a=(0,L.useRef)(null),y=(0,L.useRef)(null),T=(0,L.useRef)(null),h=(0,L.useRef)(null),R=(0,L.useRef)(null),s=(0,L.useRef)(null),O=(0,L.useRef)(null),x=(0,L.useRef)(null),b=(0,L.useRef)(null),f=(0,L.useRef)(new Map),q=(0,L.useRef)(null),M=n=>{let c=f.current.get(n);c==null||c.unmount(),f.current.delete(n)},A=()=>{let n=f.current;Array.from(n.values()).forEach(l=>{l.unmount()}),n.clear()},o=(n,c,l)=>{var H,X,Y,D,Q;if(!u)return r.debug("Callback cancelled, component is unmounted");let{isOffline:F,isFailed:I,isCanceled:te}=l;e.offline&&F&&I?(r.debug("Performing offline error callback",{data:c,details:l}),(H=h.current)==null||H.call(h,{response:c[1],command:n,details:l})):te?(r.debug("Performing abort callback",{data:c,details:l}),(X=T.current)==null||X.call(T,{response:c[1],command:n,details:l})):I?(r.debug("Performing error callback",{data:c,details:l}),(D=y.current)==null||D.call(y,{response:c[1],command:n,details:l})):(r.debug("Performing success callback",{data:c,details:l}),(Y=a.current)==null||Y.call(a,{response:c[0],command:n,details:l})),(Q=R.current)==null||Q.call(R,{response:c,command:n,details:l})},p=n=>({isLoading:c})=>{let l=!c&&!t.hasRunningRequests(n);(c||l)&&g.setLoading(c,!1)},m=(n,c)=>{var l;(l=x==null?void 0:x.current)==null||l.call(x,n,c)},U=(n,c)=>{var l;(l=b==null?void 0:b.current)==null||l.call(b,n,c)},E=n=>c=>{var l;(l=s==null?void 0:s.current)==null||l.call(s,{command:n,details:c})},S=n=>c=>{var l;(l=O==null?void 0:O.current)==null||l.call(O,{command:n,details:c})},K=n=>(c,l)=>{o(n,c,l)},w=({requestId:n})=>{M(n)},ce=n=>()=>{let c=[null,(0,ke.getErrorMessage)("abort"),0],l={retries:0,timestamp:+new Date,isFailed:!1,isCanceled:!0,isOffline:!1};o(n,c,l)},B=()=>{var n;(n=q.current)==null||n.unmount(),q.current=null},ye=n=>{let c=d.events.onLoading(n.queueKey,p(n.queueKey)),l=C.events.onData(n.cacheKey,i),F=d.events.onAbort(n.abortKey,ce(n)),I=()=>{c(),l(),F()};return B(),q.current={unmount:I},I},ge=(n,c)=>{if(!c){let{queueKey:D,cacheKey:Q}=n,ne=d.events.onRequestStart(D,E(n)),Z=d.events.onResponseStart(D,S(n)),Ce=d.events.onUploadProgress(D,U),Ee=d.events.onDownloadProgress(D,m),Qe=d.events.onResponse(Q,K(n)),Se=()=>{Ee(),Ce(),ne(),Z(),Qe()};return f.current.set(D,{unmount:Se}),Se}let l=d.events.onRemoveById(c,w),F=d.events.onRequestStartById(c,E(n)),I=d.events.onResponseStartById(c,S(n)),te=d.events.onResponseById(c,K(n)),H=d.events.onUploadProgressById(c,U),X=d.events.onDownloadProgressById(c,m),Y=()=>{l(),X(),H(),F(),I(),te()};return f.current.set(c,{unmount:Y}),Y},be=()=>{let{abortKey:n}=e;t.getAllRunningRequest().forEach(l=>{l.command.abortKey===n&&t.delete(l.command.queueKey,l.requestId,n)})};return(0,pe.useWillUnmount)(()=>{A(),B()}),[{abort:be,onSuccess:n=>{a.current=n},onError:n=>{y.current=n},onAbort:n=>{T.current=n},onOfflineError:n=>{h.current=n},onFinished:n=>{R.current=n},onRequestStart:n=>{s.current=n},onResponseStart:n=>{O.current=n},onDownloadProgress:n=>{x.current=n},onUploadProgress:n=>{b.current=n}},{addDataListener:ye,clearDataListener:B,addLifecycleListeners:ge,removeLifecycleListener:M,clearLifecycleListeners:A}]};var ve=require("react"),le=require("@better-typed/react-lifecycle-hooks"),_=(e=600)=>{let t=(0,ve.useRef)({time:e,timer:null});(0,le.useDidUpdate)(()=>{t.current.time=e},[e]);let r=()=>{t.current.timer!==null&&clearTimeout(t.current.timer),t.current.timer=null},g=(i,C)=>{r(),t.current.timer=setTimeout(()=>{i()},C||t.current.time)};return(0,le.useWillUnmount)(r),{debounce:g,resetDebounce:r,active:!!t.current.timer}};var j={data:null,error:null,loading:!1,status:null,retries:0,timestamp:null};var Re=require("react"),oe=require("@better-typed/react-lifecycle-hooks");var he=e=>{let t=Object.prototype.toString.call(e);return Array.isArray(e)?!e.length:typeof e=="object"&&e!==null&&t==="[object Object]"?!Object.keys(e).length:!1},se=(e,t)=>{let r=Object.prototype.toString.call(e),g=Object.prototype.toString.call(t),i=typeof e,C=typeof t,d=a=>i===a&&C===a,u=a=>r===a&&g===a;return r!==g?!1:e===null&&t===null||d("number")&&Number.isNaN(e)&&Number.isNaN(t)||he(e)&&he(t)?!0:Array.isArray(e)&&Array.isArray(t)?e.length!==t.length?!1:!e.some((a,y)=>!se(a,t[y])):d("object")&&u("[object Object]")?Object.keys(e).length!==Object.keys(t).length?!1:!Object.entries(e).some(([a,y])=>!se(y,t[a])):e instanceof Date&&t instanceof Date?+e==+t:e===t};var N=(e,t)=>k({retries:(e==null?void 0:e.retries)||0,timestamp:+new Date,isFailed:!1,isCanceled:!1,isOffline:!1},t),me=(e,t)=>t?e?+new Date>+t+e:!1:!0,qe=(e,t,r)=>!me(e.cacheTime,r==null?void 0:r.details.timestamp)&&r?r:t?{data:t,details:N(),cacheTime:1e3,clearKey:e.builder.cache.clearKey}:null,Fe=e=>e?new Date(e):null,He=e=>e?{data:e,details:N(),cacheTime:1e3,clearKey:""}:null,de=(e,t,r)=>{var y,T,h;let{builder:g,cacheKey:i}=r,{cache:C}=g,d=C.get(i),u=qe(r,e,d),a=t.hasRunningRequests(r.queueKey);return P(k({},j),{data:((y=u==null?void 0:u.data)==null?void 0:y[0])||j.data,error:((T=u==null?void 0:u.data)==null?void 0:T[1])||j.error,status:((h=u==null?void 0:u.data)==null?void 0:h[2])||j.status,retries:(u==null?void 0:u.details.retries)||j.retries,timestamp:Fe((u==null?void 0:u.details.timestamp)||j.timestamp),loading:a!=null?a:j.loading})};var G=({command:e,dispatcher:t,initialData:r,deepCompare:g,dependencyTracking:i,defaultCacheEmitting:C=!0})=>{let{builder:d,cacheKey:u,queueKey:a,cacheTime:y}=e,{cache:T,commandManager:h}=d,R=(0,oe.useForceUpdate)(),s=(0,Re.useRef)(de(r,t,e)),O=(0,Re.useRef)([]),x=()=>{var p;let o=T.get(u);return me(y,(o==null?void 0:o.details.timestamp)||((p=s.current)==null?void 0:p.timestamp))},b=o=>{O.current.some(m=>o.includes(m))&&R()},f=o=>{O.current.includes(o)||O.current.push(o)};(0,oe.useDidUpdate)(()=>{s.current.loading=t.hasRunningRequests(a);let o=de(r,t,e),p=(r==null?void 0:r[0])===s.current.data,m=!!(s.current.data||s.current.error)&&!p,U=!m&&s.current.data,E=m&&!s.current.data;(U||E)&&(s.current=o)},[u,a],!0),(0,oe.useDidUpdate)(()=>{(()=>{i||Object.keys(s.current).forEach(p=>f(p))})()},[i],!0);let q=(o,p)=>typeof g=="function"?g(o,p):g?se(o,p):!1,M=o=>re(void 0,null,function*(){let p={data:o.data[0],error:o.data[1],status:o.data[2],retries:o.details.retries,timestamp:new Date(o.details.timestamp),loading:s.current.loading},m=Object.keys(p).filter(U=>{let E=U,S=s.current[E],K=p[E];return!q(S,K)});s.current=k(k({},s.current),p),b(m)}),A={setData:(o,p=C)=>{if(p){let m=s.current;T.set(e,[o,m.error,m.status],N(s.current))}else s.current.data=o,b(["data"])},setError:(o,p=C)=>{if(p){let m=s.current;T.set(e,[m.data,o,m.status],N(s.current,{isFailed:!!o}))}else s.current.error=o,b(["error"])},setLoading:(o,p=!0)=>{p?h.events.emitLoading(a,"",{queueKey:a,requestId:"",isLoading:o,isRetry:!1,isOffline:!1}):(s.current.loading=o,b(["loading"]))},setStatus:(o,p=C)=>{if(p){let m=s.current;T.set(e,[m.data,m.error,o],N(s.current))}else s.current.status=o,b(["status"])},setRetries:(o,p=C)=>{if(p){let m=s.current;T.set(e,[m.data,m.error,m.status],N(s.current,{retries:o}))}else s.current.retries=o,b(["retries"])},setTimestamp:(o,p=C)=>{if(p){let m=s.current;T.set(e,[m.data,m.error,m.status],N(s.current,{timestamp:+o}))}else s.current.timestamp=o,b(["timestamp"])}};return[s.current,A,{setRenderKey:f,setCacheData:M,getStaleStatus:x}]};var Xe=(e,{dependencies:t=v.dependencies,disabled:r=v.disabled,dependencyTracking:g=v.dependencyTracking,revalidateOnMount:i=v.revalidateOnMount,initialData:C=v.initialData,refresh:d=v.refresh,refreshTime:u=v.refreshTime,refreshBlurred:a=v.refreshBlurred,refreshOnTabBlur:y=v.refreshOnTabBlur,refreshOnTabFocus:T=v.refreshOnTabFocus,refreshOnReconnect:h=v.refreshOnReconnect,debounce:R=v.debounce,debounceTime:s=v.debounceTime,deepCompare:O=v.deepCompare}=v)=>{let x=JSON.stringify(e.dump()),b=_(s),f=_(u),{cacheKey:q,queueKey:M,builder:A}=e,{cache:o,fetchDispatcher:p,appManager:m,loggerManager:U}=A,E=(0,Ie.useRef)(U.init("useFetch")).current,[S,K,{setRenderKey:w,setCacheData:ce,getStaleStatus:B}]=G({logger:E,command:e,dispatcher:p,initialData:C,deepCompare:O,dependencyTracking:g}),[ye,ge]=$({logger:E,actions:K,command:e,dispatcher:p,setCacheData:ce}),{addDataListener:be,addLifecycleListeners:n,clearDataListener:c,clearLifecycleListeners:l}=ge,F=()=>{r?E.debug("Cannot add to fetch queue",{disabled:r}):(E.debug("Fetching data"),p.add(e))};function I(){!d||(E.debug(`Starting refresh counter, request will be send in ${u}ms`),f.debounce(()=>{let D=!m.isFocused,Q=p.hasRunningRequests(e.queueKey),ne=p.getIsActiveQueue(e.queueKey),Z=Q||ne;(D&&a&&!Z||!D&&!Z)&&(F(),E.debug("Performing refresh request")),I()}))}let te=D=>{D&&D instanceof ae.Command?o.revalidate((0,ae.getCommandKey)(D)):D&&!(D instanceof ae.Command)?o.revalidate(D):(F(),I())},H=()=>{let D=B(),Q=p.getIsActiveQueue(M);(i||D&&!Q)&&F()},X=()=>{R?(E.debug("Debouncing request",{queueKey:M,command:e}),b.debounce(()=>F())):F()};return(0,V.useDidUpdate)(()=>{be(e),n(e);let D=m.events.onFocus(()=>{T&&(F(),I())}),Q=m.events.onBlur(()=>{y&&(F(),I())}),ne=m.events.onOnline(()=>{h&&(F(),I())}),Z=o.events.onRevalidate(q,F);return()=>{c(),l(),D(),Q(),ne(),Z()}},[x],!0),(0,V.useDidMount)(H),(0,V.useDidUpdate)(X,[x,...t]),(0,V.useDidUpdate)(I,[x,...t,r,d,u],!0),P(k(k({get data(){return w("data"),S.data},get error(){return w("error"),S.error},get loading(){return w("loading"),S.loading},get status(){return w("status"),S.status},get retries(){return w("retries"),S.retries},get timestamp(){return w("timestamp"),S.timestamp}},K),ye),{isDebouncing:b.active,revalidate:te})};var we=require("@better-typed/hyper-fetch"),v={dependencies:[],disabled:!1,dependencyTracking:!0,revalidateOnMount:!0,initialData:null,refresh:!1,refreshTime:we.DateInterval.hour,refreshBlurred:!0,refreshOnTabBlur:!1,refreshOnTabFocus:!1,refreshOnReconnect:!1,debounce:!1,debounceTime:400,deepCompare:!0};var Me=require("react"),J=require("@better-typed/hyper-fetch"),Pe=require("@better-typed/react-lifecycle-hooks");var Ye=(e,{disabled:t=W.disabled,dependencyTracking:r=W.dependencyTracking,initialData:g=W.initialData,debounce:i=W.debounce,debounceTime:C=W.debounceTime,deepCompare:d=W.deepCompare}=W)=>{let{builder:u}=e,{cache:a,submitDispatcher:y,loggerManager:T}=u,h=(0,Me.useRef)(T.init("useSubmit")).current,R=_(C),[s,O,{setRenderKey:x,setCacheData:b}]=G({logger:h,command:e,dispatcher:y,initialData:g,deepCompare:d,dependencyTracking:r}),[f,q]=$({logger:h,actions:O,command:e,dispatcher:y,setCacheData:b}),{addDataListener:M,addLifecycleListeners:A}=q,o=(...U)=>{let E=U[0],S=e.clone(E);if(t)return h.warning("Cannot submit request",{disabled:t,options:E}),[null,null,0];let K=()=>(M(S),(0,J.commandSendRequest)(S,"submit",w=>{A(S,w)}));return new Promise(w=>{(()=>re(void 0,null,function*(){if(h.debug("Submitting request",{disabled:t,options:E}),i)R.debounce(()=>re(void 0,null,function*(){let B=yield K();w(B)}));else{let B=yield K();w(B)}}))()})},p=U=>{!U||(U&&U instanceof J.Command?a.revalidate((0,J.getCommandKey)(U)):U instanceof J.Command||a.revalidate(U))},m={onSubmitSuccess:f.onSuccess,onSubmitError:f.onError,onSubmitFinished:f.onFinished,onSubmitRequestStart:f.onRequestStart,onSubmitResponseStart:f.onResponseStart,onSubmitDownloadProgress:f.onDownloadProgress,onSubmitUploadProgress:f.onUploadProgress,onSubmitOfflineError:f.onOfflineError,onSubmitAbort:f.onAbort};return(0,Pe.useDidMount)(()=>{M(e)}),P(k(k({submit:o,get data(){return x("data"),s.data},get error(){return x("error"),s.error},get submitting(){return x("loading"),s.loading},get status(){return x("status"),s.status},get retries(){return x("retries"),s.retries},get timestamp(){return x("timestamp"),s.timestamp},abort:f.abort},O),m),{isDebouncing:R.active,revalidate:p})};var W={disabled:!1,dependencyTracking:!0,cacheOnMount:!0,initialData:null,debounce:!1,debounceTime:400,suspense:!1,shouldThrow:!1,invalidate:[],deepCompare:!0};var ue=require("react"),Le=require("@better-typed/hyper-fetch"),fe=require("@better-typed/react-lifecycle-hooks");var Ze=(e,t=Te)=>{let{queueType:r=Te.queueType}=t,{abortKey:g,queueKey:i,builder:C}=e,{commandManager:d}=C,[u]=(0,Le.getCommandDispatcher)(e,r),a=(0,ue.useRef)(null),[y,T]=(0,ue.useState)(!1),[h,R]=(0,ue.useState)([]),s=f=>f.map(q=>P(k({},q),{stopRequest:()=>u[0].stopRequest(i,q.requestId),startRequest:()=>u[0].startRequest(i,q.requestId),deleteRequest:()=>u[0].delete(i,q.requestId,g)})),O=()=>{let f=u.getQueue(i);T(f.stopped),R(s(f.requests))},x=f=>{T(f.stopped),R(s(f.requests))},b=()=>{var p;let f=u.events.onQueueChange(i,x),q=u.events.onQueueStatus(i,x),M=d.events.onDownloadProgress(i,(m,{requestId:U})=>{R(E=>E.map(S=>S.requestId===U?P(k({},S),{downloading:m}):S))}),A=d.events.onUploadProgress(i,(m,{requestId:U})=>{R(E=>E.map(S=>S.requestId===U?P(k({},S),{uploading:m}):S))}),o=()=>{q(),f(),M(),A()};return(p=a.current)==null||p.call(a),a.current=o,o};return(0,fe.useDidMount)(O),(0,fe.useDidUpdate)(b,[y,h,R,T],!0),{stopped:y,requests:h,stop:()=>u[0].stop(i),pause:()=>u[0].pause(i),start:()=>u[0].start(i)}};var Te={queueType:"auto"};var Ae=require("react"),z=require("@better-typed/hyper-fetch");var _e=(e,{dependencyTracking:t=ee.dependencyTracking,initialData:r=ee.initialData,deepCompare:g=ee.deepCompare}=ee)=>{let{cacheKey:i,builder:C}=e,{cache:d,loggerManager:u}=C,a=(0,Ae.useRef)(u.init("useCache")).current,[y]=(0,z.getCommandDispatcher)(e),[T,h,{setRenderKey:R,setCacheData:s}]=G({logger:a,command:e,dispatcher:y,initialData:r,deepCompare:g,dependencyTracking:t}),[O]=$({logger:a,actions:h,command:e,dispatcher:y,setCacheData:s}),x=b=>{b&&b instanceof z.Command?d.revalidate(`/${(0,z.getCommandKey)(b,!0)}/`):b&&!(b instanceof z.Command)?d.revalidate(b):d.revalidate(i)};return P(k({get data(){return R("data"),T.data},get error(){return R("error"),T.error},get loading(){return R("loading"),T.loading},get status(){return R("status"),T.status},get retries(){return R("retries"),T.retries},get timestamp(){return R("timestamp"),T.timestamp},onCacheError:O.onError,onCacheSuccess:O.onSuccess,onCacheChange:O.onFinished},h),{revalidate:x})};var ee={dependencyTracking:!0,initialData:null,deepCompare:!0};var xe=require("react"),Ke=require("@better-typed/react-lifecycle-hooks"),Ve=e=>{let[t,r]=(0,xe.useState)(e.appManager.isOnline),[g,i]=(0,xe.useState)(e.appManager.isFocused),C=()=>{let a=e.appManager.events.onOnline(()=>r(!0)),y=e.appManager.events.onOffline(()=>r(!1)),T=e.appManager.events.onFocus(()=>i(!0)),h=e.appManager.events.onBlur(()=>i(!1));return()=>{a(),y(),T(),h()}},d=a=>{e.appManager.setOnline(a)},u=a=>{e.appManager.setFocused(a)};return(0,Ke.useDidMount)(C),{isOnline:t,isFocused:g,setOnline:d,setFocused:u}};
var me=Object.defineProperty,Qe=Object.defineProperties,Be=Object.getOwnPropertyDescriptor,je=Object.getOwnPropertyDescriptors,Ne=Object.getOwnPropertyNames,Se=Object.getOwnPropertySymbols;var Oe=Object.prototype.hasOwnProperty,We=Object.prototype.propertyIsEnumerable;var De=(e,t,r)=>t in e?me(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,O=(e,t)=>{for(var r in t||(t={}))Oe.call(t,r)&&De(e,r,t[r]);if(Se)for(var r of Se(t))We.call(t,r)&&De(e,r,t[r]);return e},B=(e,t)=>Qe(e,je(t));var Ge=(e,t)=>{for(var r in t)me(e,r,{get:t[r],enumerable:!0})},Je=(e,t,r,b)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ne(t))!Oe.call(e,i)&&i!==r&&me(e,i,{get:()=>t[i],enumerable:!(b=Be(t,i))||b.enumerable});return e};var $e=e=>Je(me({},"__esModule",{value:!0}),e);var ae=(e,t,r)=>new Promise((b,i)=>{var R=a=>{try{o(r.next(a))}catch(y){i(y)}},m=a=>{try{o(r.throw(a))}catch(y){i(y)}},o=a=>a.done?b(a.value):Promise.resolve(a.value).then(R,m);o((r=r.apply(e,t)).next())});var _e={};Ge(_e,{getDetailsState:()=>G,getInitialState:()=>Te,getTimestamp:()=>Ie,getValidCacheData:()=>Fe,initialState:()=>W,isEmpty:()=>be,isEqual:()=>ue,isStaleCacheData:()=>de,useAppManager:()=>Ze,useCache:()=>Ye,useCacheDefaultOptions:()=>ne,useCommandEvents:()=>H,useDebounce:()=>ee,useFetch:()=>ze,useFetchDefaultOptions:()=>v,useQueue:()=>Xe,useQueueDefaultOptions:()=>fe,useSubmit:()=>He,useSubmitDefaultOptions:()=>N,useTrackedState:()=>X});module.exports=$e(_e);var we=require("react"),te=require("@better-typed/react-lifecycle-hooks"),ie=require("@better-typed/hyper-fetch");var P=require("react"),Ue=require("@better-typed/hyper-fetch"),ke=require("@better-typed/react-lifecycle-hooks"),H=({command:e,dispatcher:t,logger:r,actions:b,setCacheData:i})=>{let{cache:R,commandManager:m}=e.builder,o=(0,P.useRef)(null),a=(0,P.useRef)(null),y=(0,P.useRef)(null),T=(0,P.useRef)(null),h=(0,P.useRef)(null),x=(0,P.useRef)(null),u=(0,P.useRef)(null),E=(0,P.useRef)(null),U=(0,P.useRef)(null),f=(0,P.useRef)(new Map),w=(0,P.useRef)(null),g=n=>{let c=f.current.get(n);c==null||c.unmount(),f.current.delete(n)},S=()=>{let n=f.current;Array.from(n.values()).forEach(p=>{p.unmount()}),n.clear()},I=(n,c,p)=>{var Z,_,$,j,D;let{isOffline:J,isFailed:k,isCanceled:Q}=p;e.offline&&J&&k?(r.debug("Performing offline error callback",{data:c,details:p}),(Z=T.current)==null||Z.call(T,{response:c[1],command:n,details:p})):Q?(r.debug("Performing abort callback",{data:c,details:p}),(_=y.current)==null||_.call(y,{response:c[1],command:n,details:p})):k?(r.debug("Performing error callback",{data:c,details:p}),(j=a.current)==null||j.call(a,{response:c[1],command:n,details:p})):(r.debug("Performing success callback",{data:c,details:p}),($=o.current)==null||$.call(o,{response:c[0],command:n,details:p})),(D=h.current)==null||D.call(h,{response:c,command:n,details:p})},s=n=>({isLoading:c})=>{let p=!c&&!t.hasRunningRequests(n);(c||p)&&b.setLoading(c,!1)},l=(n,c)=>{var p;(p=E.current)==null||p.call(E,n,c)},d=(n,c)=>{var p;(p=U.current)==null||p.call(U,n,c)},F=n=>c=>{var p;(p=x.current)==null||p.call(x,{command:n,details:c})},C=n=>c=>{var p;(p=u.current)==null||p.call(u,{command:n,details:c})},q=n=>(c,p)=>{I(n,c,p)},L=({requestId:n})=>{g(n)},M=n=>()=>{let c=[null,(0,Ue.getErrorMessage)("abort"),0],p={retries:0,timestamp:+new Date,isFailed:!1,isCanceled:!0,isOffline:!1};I(n,c,p)},K=()=>{var n;(n=w.current)==null||n.unmount(),w.current=null},le=n=>{let c=m.events.onLoading(n.queueKey,s(n.queueKey)),p=R.events.onData(n.cacheKey,i),J=m.events.onAbort(n.abortKey,M(n)),k=()=>{c(),p(),J()};return K(),w.current={unmount:k},k},A=(n,c)=>{if(!c){let{queueKey:j,cacheKey:D}=n,z=m.events.onRequestStart(j,F(n)),oe=m.events.onResponseStart(j,C(n)),V=m.events.onUploadProgress(j,d),ge=m.events.onDownloadProgress(j,l),Ee=m.events.onResponse(D,q(n)),xe=()=>{ge(),V(),z(),oe(),Ee()};return f.current.set(j,{unmount:xe}),xe}let p=m.events.onRemoveById(c,L),J=m.events.onRequestStartById(c,F(n)),k=m.events.onResponseStartById(c,C(n)),Q=m.events.onResponseById(c,q(n)),Z=m.events.onUploadProgressById(c,d),_=m.events.onDownloadProgressById(c,l),$=()=>{p(),_(),Z(),J(),k(),Q()};return f.current.set(c,{unmount:$}),$},se=()=>{let{abortKey:n}=e;t.getAllRunningRequest().forEach(p=>{p.command.abortKey===n&&t.delete(p.command.queueKey,p.requestId,n)})};return(0,ke.useWillUnmount)(()=>{S(),K()}),[{abort:se,onSuccess:n=>{o.current=n},onError:n=>{a.current=n},onAbort:n=>{y.current=n},onOfflineError:n=>{T.current=n},onFinished:n=>{h.current=n},onRequestStart:n=>{x.current=n},onResponseStart:n=>{u.current=n},onDownloadProgress:n=>{E.current=n},onUploadProgress:n=>{U.current=n}},{addDataListener:le,clearDataListener:K,addLifecycleListeners:A,removeLifecycleListener:g,clearLifecycleListeners:S}]};var ve=require("react"),qe=require("@better-typed/react-lifecycle-hooks"),ee=(e=600)=>{let t=(0,ve.useRef)(null),r=()=>{t.current!==null&&clearTimeout(t.current),t.current=null},b=(i,R)=>{r(),t.current=setTimeout(()=>{i()},R||e)};return(0,qe.useWillUnmount)(r),{debounce:b,resetDebounce:r,active:!!t.current}};var W={data:null,error:null,loading:!1,status:null,retries:0,timestamp:null};var Ce=require("react"),ce=require("@better-typed/react-lifecycle-hooks");var be=e=>{let t=Object.prototype.toString.call(e);return Array.isArray(e)?!e.length:typeof e=="object"&&e!==null&&t==="[object Object]"?!Object.keys(e).length:!1},ue=(e,t)=>{let r=Object.prototype.toString.call(e),b=Object.prototype.toString.call(t),i=typeof e,R=typeof t,m=a=>i===a&&R===a,o=a=>r===a&&b===a;return r!==b?!1:e===null&&t===null||m("number")&&Number.isNaN(e)&&Number.isNaN(t)||be(e)&&be(t)?!0:Array.isArray(e)&&Array.isArray(t)?e.length!==t.length?!1:!e.some((a,y)=>!ue(a,t[y])):m("object")&&o("[object Object]")?Object.keys(e).length!==Object.keys(t).length?!1:!Object.entries(e).some(([a,y])=>!ue(y,t[a])):e instanceof Date&&t instanceof Date?+e==+t:e===t};var G=(e,t)=>O({retries:(e==null?void 0:e.retries)||0,timestamp:+new Date,isFailed:!1,isCanceled:!1,isOffline:!1},t),de=(e,t)=>t?+new Date>+t+e:!0,Fe=(e,t,r)=>!de(e.cacheTime,r==null?void 0:r.details.timestamp)&&r?r:t?{data:t,details:G(),cacheTime:1e3,clearKey:e.builder.cache.clearKey}:null,Ie=e=>e?new Date(e):null,Te=(e,t,r)=>{var y,T,h;let{builder:b,cacheKey:i}=r,{cache:R}=b,m=R.get(i),o=Fe(r,e,m),a=t.hasRunningRequests(r.queueKey);return B(O({},W),{data:((y=o==null?void 0:o.data)==null?void 0:y[0])||W.data,error:((T=o==null?void 0:o.data)==null?void 0:T[1])||W.error,status:((h=o==null?void 0:o.data)==null?void 0:h[2])||W.status,retries:(o==null?void 0:o.details.retries)||W.retries,timestamp:Ie((o==null?void 0:o.details.timestamp)||W.timestamp),loading:a})};var X=({command:e,dispatcher:t,initialData:r,deepCompare:b,dependencyTracking:i,defaultCacheEmitting:R=!0})=>{let{builder:m,cacheKey:o,queueKey:a,cacheTime:y}=e,{cache:T,commandManager:h}=m,x=(0,ce.useForceUpdate)(),u=(0,Ce.useRef)(Te(r,t,e)),E=(0,Ce.useRef)([]),U=()=>{let s=T.get(o);return de(y,(s==null?void 0:s.details.timestamp)||u.current.timestamp)},f=s=>{E.current.some(d=>s.includes(d))&&x()},w=s=>{E.current.includes(s)||E.current.push(s)};(0,ce.useDidUpdate)(()=>{u.current.loading=t.hasRunningRequests(a);let s=Te(r,t,e),l=(r==null?void 0:r[0])===u.current.data,d=!!(u.current.data||u.current.error)&&!l,F=!d&&u.current.data,C=d&&!u.current.data;(F||C)&&(u.current=s)},[o,a],!0),(0,ce.useDidUpdate)(()=>{(()=>{i||Object.keys(u.current).forEach(l=>w(l))})()},[i],!0);let g=(s,l)=>typeof b=="function"?b(s,l):b?ue(s,l):!1,S=s=>ae(void 0,null,function*(){let l={data:s.data[0],error:s.data[1],status:s.data[2],retries:s.details.retries,timestamp:new Date(s.details.timestamp),loading:u.current.loading},d=Object.keys(l).filter(F=>{let C=F,q=u.current[C],L=l[C];return!g(q,L)});u.current=O(O({},u.current),l),f(d)}),I={setData:(s,l=R)=>{if(l){let d=u.current;T.set(e,[s,d.error,d.status],G(u.current))}else u.current.data=s,f(["data"])},setError:(s,l=R)=>{if(l){let d=u.current;T.set(e,[d.data,s,d.status],G(u.current,{isFailed:!!s}))}else u.current.error=s,f(["error"])},setLoading:(s,l=!0)=>{l?h.events.emitLoading(a,"",{queueKey:a,requestId:"",isLoading:s,isRetry:!1,isOffline:!1}):(u.current.loading=s,f(["loading"]))},setStatus:(s,l=R)=>{if(l){let d=u.current;T.set(e,[d.data,d.error,s],G(u.current))}else u.current.status=s,f(["status"])},setRetries:(s,l=R)=>{if(l){let d=u.current;T.set(e,[d.data,d.error,d.status],G(u.current,{retries:s}))}else u.current.retries=s,f(["retries"])},setTimestamp:(s,l=R)=>{if(l){let d=u.current;T.set(e,[d.data,d.error,d.status],G(u.current,{timestamp:+s}))}else u.current.timestamp=s,f(["timestamp"])}};return[u.current,I,{setRenderKey:w,setCacheData:S,getStaleStatus:U}]};var ze=(e,{dependencies:t=v.dependencies,disabled:r=v.disabled,dependencyTracking:b=v.dependencyTracking,revalidateOnMount:i=v.revalidateOnMount,initialData:R=v.initialData,refresh:m=v.refresh,refreshTime:o=v.refreshTime,refreshBlurred:a=v.refreshBlurred,refreshOnBlur:y=v.refreshOnBlur,refreshOnFocus:T=v.refreshOnFocus,refreshOnReconnect:h=v.refreshOnReconnect,debounce:x=v.debounce,debounceTime:u=v.debounceTime,deepCompare:E=v.deepCompare}=v)=>{let U=JSON.stringify(e.dump()),f=ee(u),w=ee(o),{cacheKey:g,queueKey:S,builder:I}=e,{cache:s,fetchDispatcher:l,appManager:d,loggerManager:F}=I,C=(0,we.useRef)(F.init("useFetch")).current,[q,L,{setRenderKey:M,setCacheData:K,getStaleStatus:le}]=X({logger:C,command:e,dispatcher:l,initialData:R,deepCompare:E,dependencyTracking:b}),[A,se]=H({logger:C,actions:L,command:e,dispatcher:l,setCacheData:K}),{addDataListener:n,addLifecycleListeners:c,clearDataListener:p,clearLifecycleListeners:J}=se,k=()=>{r?C.debug("Cannot add to fetch queue",{disabled:r}):(C.debug("Fetching data"),l.add(e))};function Q(){!m||(C.debug(`Starting refresh counter, request will be send in ${o}ms`),w.debounce(()=>{let D=!d.isFocused,z=l.hasRunningRequests(e.queueKey),oe=l.getIsActiveQueue(e.queueKey),V=z||oe;(D&&a&&!V||!D&&!V)&&(k(),C.debug("Performing refresh request")),Q()}))}let Z=D=>{D&&D instanceof ie.Command?s.revalidate((0,ie.getCommandKey)(D)):D&&!(D instanceof ie.Command)?s.revalidate(D):(k(),Q())},_=()=>{let D=le(),z=l.getIsActiveQueue(S);(i||D&&!z)&&k()},$=()=>{x?(C.debug("Debouncing request",{queueKey:S,command:e}),f.debounce(()=>k())):k()};return(0,te.useDidUpdate)(()=>{n(e),c(e);let D=d.events.onFocus(()=>{T&&(k(),Q())}),z=d.events.onBlur(()=>{y&&(k(),Q())}),oe=d.events.onOnline(()=>{h&&(k(),Q())}),V=s.events.onRevalidate(g,k);return()=>{p(),J(),D(),z(),oe(),V()}},[U],!0),(0,te.useDidMount)(_),(0,te.useDidUpdate)($,[U,...t]),(0,te.useDidUpdate)(Q,[U,...t,r,m,o],!0),B(O(O({get data(){return M("data"),q.data},get error(){return M("error"),q.error},get loading(){return M("loading"),q.loading},get status(){return M("status"),q.status},get retries(){return M("retries"),q.retries},get timestamp(){return M("timestamp"),q.timestamp}},L),A),{isDebouncing:f.active,revalidate:Z})};var Pe=require("@better-typed/hyper-fetch"),v={dependencies:[],disabled:!1,dependencyTracking:!0,revalidateOnMount:!0,initialData:null,refresh:!1,refreshTime:Pe.DateInterval.hour,refreshBlurred:!0,refreshOnBlur:!1,refreshOnFocus:!1,refreshOnReconnect:!1,debounce:!1,debounceTime:400,deepCompare:!0};var Re=require("react"),Y=require("@better-typed/hyper-fetch"),Me=require("@better-typed/react-lifecycle-hooks");var He=(e,{disabled:t=N.disabled,dependencyTracking:r=N.dependencyTracking,initialData:b=N.initialData,debounce:i=N.debounce,debounceTime:R=N.debounceTime,deepCompare:m=N.deepCompare}=N)=>{let{builder:o}=e,{cache:a,submitDispatcher:y,loggerManager:T}=o,h=(0,Re.useRef)(T.init("useSubmit")).current,x=ee(R),u=(0,Re.useRef)(()=>null),[E,U,{setRenderKey:f,setCacheData:w}]=X({logger:h,command:e,dispatcher:y,initialData:b,deepCompare:m,dependencyTracking:r}),[g,S]=H({logger:h,actions:U,command:e,dispatcher:y,setCacheData:w}),{addDataListener:I,addLifecycleListeners:s}=S,l=(...C)=>{let q=C[0],L=e.clone(q);if(t)throw h.warning("Cannot submit request",{disabled:t,options:q}),new Error("Cannot submit request. Option 'disabled' is enabled");let M=()=>(I(L),(0,Y.commandSendRequest)(L,"submit",K=>{s(L,K)}));return new Promise(K=>{(()=>ae(void 0,null,function*(){if(h.debug("Submitting request",{disabled:t,options:q}),i)u.current=A=>{u.current(A),K(A)},x.debounce(()=>ae(void 0,null,function*(){let A=u.current;u.current=()=>null;let se=yield M();A(se)}));else{let A=yield M();K(A)}}))()})},d=C=>{!C||(C&&C instanceof Y.Command?a.revalidate((0,Y.getCommandKey)(C)):C instanceof Y.Command||a.revalidate(C))},F={onSubmitSuccess:g.onSuccess,onSubmitError:g.onError,onSubmitFinished:g.onFinished,onSubmitRequestStart:g.onRequestStart,onSubmitResponseStart:g.onResponseStart,onSubmitDownloadProgress:g.onDownloadProgress,onSubmitUploadProgress:g.onUploadProgress,onSubmitOfflineError:g.onOfflineError,onSubmitAbort:g.onAbort};return(0,Me.useDidMount)(()=>{I(e)}),B(O(O({submit:l,get data(){return f("data"),E.data},get error(){return f("error"),E.error},get submitting(){return f("loading"),E.loading},get status(){return f("status"),E.status},get retries(){return f("retries"),E.retries},get timestamp(){return f("timestamp"),E.timestamp},abort:g.abort},U),F),{isDebouncing:x.active,revalidate:d})};var N={disabled:!1,dependencyTracking:!0,cacheOnMount:!0,initialData:null,debounce:!1,debounceTime:400,suspense:!1,shouldThrow:!1,invalidate:[],deepCompare:!0};var pe=require("react"),Le=require("@better-typed/hyper-fetch"),ye=require("@better-typed/react-lifecycle-hooks");var Xe=(e,t=fe)=>{let{queueType:r=fe.queueType}=t,{abortKey:b,queueKey:i,builder:R}=e,{commandManager:m}=R,[o]=(0,Le.getCommandDispatcher)(e,r),a=(0,pe.useRef)(null),[y,T]=(0,pe.useState)(!1),[h,x]=(0,pe.useState)([]),u=g=>g.map(S=>B(O({},S),{stopRequest:()=>o.stopRequest(i,S.requestId),startRequest:()=>o.startRequest(i,S.requestId),deleteRequest:()=>o.delete(i,S.requestId,b)})),E=(g,S)=>{x(I=>I.map(s=>s.requestId===g?O(O({},s),S):s))},U=()=>{let g=o.getQueue(i);T(g.stopped),x(u(g.requests))},f=g=>{T(g.stopped),x(u(g.requests))},w=()=>{var d;let g=o.events.onQueueChange(i,f),S=o.events.onQueueStatus(i,f),I=m.events.onDownloadProgress(i,(F,{requestId:C})=>{E(C,{downloading:F})}),s=m.events.onUploadProgress(i,(F,{requestId:C})=>{E(C,{uploading:F})}),l=()=>{S(),g(),I(),s()};return(d=a.current)==null||d.call(a),a.current=l,l};return(0,ye.useDidMount)(U),(0,ye.useDidUpdate)(w,[y,h,x,T],!0),{stopped:y,requests:h,stop:()=>o.stop(i),pause:()=>o.pause(i),start:()=>o.start(i)}};var fe={queueType:"auto"};var Ke=require("react"),re=require("@better-typed/hyper-fetch");var Ye=(e,{dependencyTracking:t=ne.dependencyTracking,initialData:r=ne.initialData,deepCompare:b=ne.deepCompare}=ne)=>{let{cacheKey:i,builder:R}=e,{cache:m,loggerManager:o}=R,a=(0,Ke.useRef)(o.init("useCache")).current,[y]=(0,re.getCommandDispatcher)(e),[T,h,{setRenderKey:x,setCacheData:u}]=X({logger:a,command:e,dispatcher:y,initialData:r,deepCompare:b,dependencyTracking:t}),[E]=H({logger:a,actions:h,command:e,dispatcher:y,setCacheData:u}),U=f=>{f instanceof re.Command?m.revalidate((0,re.getCommandKey)(f,!0)):f?m.revalidate(f):m.revalidate(i)};return B(O({get data(){return x("data"),T.data},get error(){return x("error"),T.error},get loading(){return x("loading"),T.loading},get status(){return x("status"),T.status},get retries(){return x("retries"),T.retries},get timestamp(){return x("timestamp"),T.timestamp},onCacheError:E.onError,onCacheSuccess:E.onSuccess,onCacheChange:E.onFinished},h),{revalidate:U})};var ne={dependencyTracking:!0,initialData:null,deepCompare:!0};var he=require("react"),Ae=require("@better-typed/react-lifecycle-hooks"),Ze=e=>{let[t,r]=(0,he.useState)(e.appManager.isOnline),[b,i]=(0,he.useState)(e.appManager.isFocused),R=()=>{let a=e.appManager.events.onOnline(()=>r(!0)),y=e.appManager.events.onOffline(()=>r(!1)),T=e.appManager.events.onFocus(()=>i(!0)),h=e.appManager.events.onBlur(()=>i(!1));return()=>{a(),y(),T(),h()}},m=a=>{e.appManager.setOnline(a)},o=a=>{e.appManager.setFocused(a)};return(0,Ae.useDidMount)(R),{isOnline:t,isFocused:b,setOnline:m,setFocused:o}};
//# sourceMappingURL=index.cjs.js.map

@@ -1,2 +0,2 @@

var Se=Object.defineProperty,De=Object.defineProperties;var Oe=Object.getOwnPropertyDescriptors;var de=Object.getOwnPropertySymbols;var Ue=Object.prototype.hasOwnProperty,ke=Object.prototype.propertyIsEnumerable;var Te=(e,t,r)=>t in e?Se(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,k=(e,t)=>{for(var r in t||(t={}))Ue.call(t,r)&&Te(e,r,t[r]);if(de)for(var r of de(t))ke.call(t,r)&&Te(e,r,t[r]);return e},P=(e,t)=>De(e,Oe(t));var _=(e,t,r)=>new Promise((b,d)=>{var C=a=>{try{u(r.next(a))}catch(y){d(y)}},m=a=>{try{u(r.throw(a))}catch(y){d(y)}},u=a=>a.done?b(a.value):Promise.resolve(a.value).then(C,m);u((r=r.apply(e,t)).next())});import{useRef as Ke}from"react";import{useDidUpdate as ie,useDidMount as Qe}from"@better-typed/react-lifecycle-hooks";import{Command as be,getCommandKey as Be}from"@better-typed/hyper-fetch";import{useRef as L}from"react";import{getErrorMessage as ve}from"@better-typed/hyper-fetch";import{useIsMounted as qe,useWillUnmount as Fe}from"@better-typed/react-lifecycle-hooks";var H=({command:e,dispatcher:t,logger:r,actions:b,setCacheData:d})=>{let{cache:C,commandManager:m}=e.builder,u=qe(),a=L(null),y=L(null),T=L(null),h=L(null),R=L(null),s=L(null),O=L(null),x=L(null),g=L(null),f=L(new Map),v=L(null),M=n=>{let c=f.current.get(n);c==null||c.unmount(),f.current.delete(n)},A=()=>{let n=f.current;Array.from(n.values()).forEach(p=>{p.unmount()}),n.clear()},o=(n,c,p)=>{var $,G,J,D,Q;if(!u)return r.debug("Callback cancelled, component is unmounted");let{isOffline:F,isFailed:I,isCanceled:Y}=p;e.offline&&F&&I?(r.debug("Performing offline error callback",{data:c,details:p}),($=h.current)==null||$.call(h,{response:c[1],command:n,details:p})):Y?(r.debug("Performing abort callback",{data:c,details:p}),(G=T.current)==null||G.call(T,{response:c[1],command:n,details:p})):I?(r.debug("Performing error callback",{data:c,details:p}),(D=y.current)==null||D.call(y,{response:c[1],command:n,details:p})):(r.debug("Performing success callback",{data:c,details:p}),(J=a.current)==null||J.call(a,{response:c[0],command:n,details:p})),(Q=R.current)==null||Q.call(R,{response:c,command:n,details:p})},i=n=>({isLoading:c})=>{let p=!c&&!t.hasRunningRequests(n);(c||p)&&b.setLoading(c,!1)},l=(n,c)=>{var p;(p=x==null?void 0:x.current)==null||p.call(x,n,c)},U=(n,c)=>{var p;(p=g==null?void 0:g.current)==null||p.call(g,n,c)},E=n=>c=>{var p;(p=s==null?void 0:s.current)==null||p.call(s,{command:n,details:c})},S=n=>c=>{var p;(p=O==null?void 0:O.current)==null||p.call(O,{command:n,details:c})},K=n=>(c,p)=>{o(n,c,p)},w=({requestId:n})=>{M(n)},te=n=>()=>{let c=[null,ve("abort"),0],p={retries:0,timestamp:+new Date,isFailed:!1,isCanceled:!0,isOffline:!1};o(n,c,p)},B=()=>{var n;(n=v.current)==null||n.unmount(),v.current=null},re=n=>{let c=m.events.onLoading(n.queueKey,i(n.queueKey)),p=C.events.onData(n.cacheKey,d),F=m.events.onAbort(n.abortKey,te(n)),I=()=>{c(),p(),F()};return B(),v.current={unmount:I},I},se=(n,c)=>{if(!c){let{queueKey:D,cacheKey:Q}=n,Z=m.events.onRequestStart(D,E(n)),z=m.events.onResponseStart(D,S(n)),ae=m.events.onUploadProgress(D,U),le=m.events.onDownloadProgress(D,l),Ee=m.events.onResponse(Q,K(n)),me=()=>{le(),ae(),Z(),z(),Ee()};return f.current.set(D,{unmount:me}),me}let p=m.events.onRemoveById(c,w),F=m.events.onRequestStartById(c,E(n)),I=m.events.onResponseStartById(c,S(n)),Y=m.events.onResponseById(c,K(n)),$=m.events.onUploadProgressById(c,U),G=m.events.onDownloadProgressById(c,l),J=()=>{p(),G(),$(),F(),I(),Y()};return f.current.set(c,{unmount:J}),J},oe=()=>{let{abortKey:n}=e;t.getAllRunningRequest().forEach(p=>{p.command.abortKey===n&&t.delete(p.command.queueKey,p.requestId,n)})};return Fe(()=>{A(),B()}),[{abort:oe,onSuccess:n=>{a.current=n},onError:n=>{y.current=n},onAbort:n=>{T.current=n},onOfflineError:n=>{h.current=n},onFinished:n=>{R.current=n},onRequestStart:n=>{s.current=n},onResponseStart:n=>{O.current=n},onDownloadProgress:n=>{x.current=n},onUploadProgress:n=>{g.current=n}},{addDataListener:re,clearDataListener:B,addLifecycleListeners:se,removeLifecycleListener:M,clearLifecycleListeners:A}]};import{useRef as Ie}from"react";import{useWillUnmount as we,useDidUpdate as Me}from"@better-typed/react-lifecycle-hooks";var V=(e=600)=>{let t=Ie({time:e,timer:null});Me(()=>{t.current.time=e},[e]);let r=()=>{t.current.timer!==null&&clearTimeout(t.current.timer),t.current.timer=null},b=(d,C)=>{r(),t.current.timer=setTimeout(()=>{d()},C||t.current.time)};return we(r),{debounce:b,resetDebounce:r,active:!!t.current.timer}};var j={data:null,error:null,loading:!1,status:null,retries:0,timestamp:null};import{useRef as ye}from"react";import{useDidUpdate as ge,useForceUpdate as Ae}from"@better-typed/react-lifecycle-hooks";var fe=e=>{let t=Object.prototype.toString.call(e);return Array.isArray(e)?!e.length:typeof e=="object"&&e!==null&&t==="[object Object]"?!Object.keys(e).length:!1},ne=(e,t)=>{let r=Object.prototype.toString.call(e),b=Object.prototype.toString.call(t),d=typeof e,C=typeof t,m=a=>d===a&&C===a,u=a=>r===a&&b===a;return r!==b?!1:e===null&&t===null||m("number")&&Number.isNaN(e)&&Number.isNaN(t)||fe(e)&&fe(t)?!0:Array.isArray(e)&&Array.isArray(t)?e.length!==t.length?!1:!e.some((a,y)=>!ne(a,t[y])):m("object")&&u("[object Object]")?Object.keys(e).length!==Object.keys(t).length?!1:!Object.entries(e).some(([a,y])=>!ne(y,t[a])):e instanceof Date&&t instanceof Date?+e==+t:e===t};var N=(e,t)=>k({retries:(e==null?void 0:e.retries)||0,timestamp:+new Date,isFailed:!1,isCanceled:!1,isOffline:!1},t),ue=(e,t)=>t?e?+new Date>+t+e:!1:!0,Pe=(e,t,r)=>!ue(e.cacheTime,r==null?void 0:r.details.timestamp)&&r?r:t?{data:t,details:N(),cacheTime:1e3,clearKey:e.builder.cache.clearKey}:null,Le=e=>e?new Date(e):null,Ut=e=>e?{data:e,details:N(),cacheTime:1e3,clearKey:""}:null,ce=(e,t,r)=>{var y,T,h;let{builder:b,cacheKey:d}=r,{cache:C}=b,m=C.get(d),u=Pe(r,e,m),a=t.hasRunningRequests(r.queueKey);return P(k({},j),{data:((y=u==null?void 0:u.data)==null?void 0:y[0])||j.data,error:((T=u==null?void 0:u.data)==null?void 0:T[1])||j.error,status:((h=u==null?void 0:u.data)==null?void 0:h[2])||j.status,retries:(u==null?void 0:u.details.retries)||j.retries,timestamp:Le((u==null?void 0:u.details.timestamp)||j.timestamp),loading:a!=null?a:j.loading})};var X=({command:e,dispatcher:t,initialData:r,deepCompare:b,dependencyTracking:d,defaultCacheEmitting:C=!0})=>{let{builder:m,cacheKey:u,queueKey:a,cacheTime:y}=e,{cache:T,commandManager:h}=m,R=Ae(),s=ye(ce(r,t,e)),O=ye([]),x=()=>{var i;let o=T.get(u);return ue(y,(o==null?void 0:o.details.timestamp)||((i=s.current)==null?void 0:i.timestamp))},g=o=>{O.current.some(l=>o.includes(l))&&R()},f=o=>{O.current.includes(o)||O.current.push(o)};ge(()=>{s.current.loading=t.hasRunningRequests(a);let o=ce(r,t,e),i=(r==null?void 0:r[0])===s.current.data,l=!!(s.current.data||s.current.error)&&!i,U=!l&&s.current.data,E=l&&!s.current.data;(U||E)&&(s.current=o)},[u,a],!0),ge(()=>{(()=>{d||Object.keys(s.current).forEach(i=>f(i))})()},[d],!0);let v=(o,i)=>typeof b=="function"?b(o,i):b?ne(o,i):!1,M=o=>_(void 0,null,function*(){let i={data:o.data[0],error:o.data[1],status:o.data[2],retries:o.details.retries,timestamp:new Date(o.details.timestamp),loading:s.current.loading},l=Object.keys(i).filter(U=>{let E=U,S=s.current[E],K=i[E];return!v(S,K)});s.current=k(k({},s.current),i),g(l)}),A={setData:(o,i=C)=>{if(i){let l=s.current;T.set(e,[o,l.error,l.status],N(s.current))}else s.current.data=o,g(["data"])},setError:(o,i=C)=>{if(i){let l=s.current;T.set(e,[l.data,o,l.status],N(s.current,{isFailed:!!o}))}else s.current.error=o,g(["error"])},setLoading:(o,i=!0)=>{i?h.events.emitLoading(a,"",{queueKey:a,requestId:"",isLoading:o,isRetry:!1,isOffline:!1}):(s.current.loading=o,g(["loading"]))},setStatus:(o,i=C)=>{if(i){let l=s.current;T.set(e,[l.data,l.error,o],N(s.current))}else s.current.status=o,g(["status"])},setRetries:(o,i=C)=>{if(i){let l=s.current;T.set(e,[l.data,l.error,l.status],N(s.current,{retries:o}))}else s.current.retries=o,g(["retries"])},setTimestamp:(o,i=C)=>{if(i){let l=s.current;T.set(e,[l.data,l.error,l.status],N(s.current,{timestamp:+o}))}else s.current.timestamp=o,g(["timestamp"])}};return[s.current,A,{setRenderKey:f,setCacheData:M,getStaleStatus:x}]};var Zt=(e,{dependencies:t=q.dependencies,disabled:r=q.disabled,dependencyTracking:b=q.dependencyTracking,revalidateOnMount:d=q.revalidateOnMount,initialData:C=q.initialData,refresh:m=q.refresh,refreshTime:u=q.refreshTime,refreshBlurred:a=q.refreshBlurred,refreshOnTabBlur:y=q.refreshOnTabBlur,refreshOnTabFocus:T=q.refreshOnTabFocus,refreshOnReconnect:h=q.refreshOnReconnect,debounce:R=q.debounce,debounceTime:s=q.debounceTime,deepCompare:O=q.deepCompare}=q)=>{let x=JSON.stringify(e.dump()),g=V(s),f=V(u),{cacheKey:v,queueKey:M,builder:A}=e,{cache:o,fetchDispatcher:i,appManager:l,loggerManager:U}=A,E=Ke(U.init("useFetch")).current,[S,K,{setRenderKey:w,setCacheData:te,getStaleStatus:B}]=X({logger:E,command:e,dispatcher:i,initialData:C,deepCompare:O,dependencyTracking:b}),[re,se]=H({logger:E,actions:K,command:e,dispatcher:i,setCacheData:te}),{addDataListener:oe,addLifecycleListeners:n,clearDataListener:c,clearLifecycleListeners:p}=se,F=()=>{r?E.debug("Cannot add to fetch queue",{disabled:r}):(E.debug("Fetching data"),i.add(e))};function I(){!m||(E.debug(`Starting refresh counter, request will be send in ${u}ms`),f.debounce(()=>{let D=!l.isFocused,Q=i.hasRunningRequests(e.queueKey),Z=i.getIsActiveQueue(e.queueKey),z=Q||Z;(D&&a&&!z||!D&&!z)&&(F(),E.debug("Performing refresh request")),I()}))}let Y=D=>{D&&D instanceof be?o.revalidate(Be(D)):D&&!(D instanceof be)?o.revalidate(D):(F(),I())},$=()=>{let D=B(),Q=i.getIsActiveQueue(M);(d||D&&!Q)&&F()},G=()=>{R?(E.debug("Debouncing request",{queueKey:M,command:e}),g.debounce(()=>F())):F()};return ie(()=>{oe(e),n(e);let D=l.events.onFocus(()=>{T&&(F(),I())}),Q=l.events.onBlur(()=>{y&&(F(),I())}),Z=l.events.onOnline(()=>{h&&(F(),I())}),z=o.events.onRevalidate(v,F);return()=>{c(),p(),D(),Q(),Z(),z()}},[x],!0),Qe($),ie(G,[x,...t]),ie(I,[x,...t,r,m,u],!0),P(k(k({get data(){return w("data"),S.data},get error(){return w("error"),S.error},get loading(){return w("loading"),S.loading},get status(){return w("status"),S.status},get retries(){return w("retries"),S.retries},get timestamp(){return w("timestamp"),S.timestamp}},K),re),{isDebouncing:g.active,revalidate:Y})};import{DateInterval as je}from"@better-typed/hyper-fetch";var q={dependencies:[],disabled:!1,dependencyTracking:!0,revalidateOnMount:!0,initialData:null,refresh:!1,refreshTime:je.hour,refreshBlurred:!0,refreshOnTabBlur:!1,refreshOnTabFocus:!1,refreshOnReconnect:!1,debounce:!1,debounceTime:400,deepCompare:!0};import{useRef as Ne}from"react";import{Command as Ce,getCommandKey as We,commandSendRequest as $e}from"@better-typed/hyper-fetch";import{useDidMount as Ge}from"@better-typed/react-lifecycle-hooks";var gn=(e,{disabled:t=W.disabled,dependencyTracking:r=W.dependencyTracking,initialData:b=W.initialData,debounce:d=W.debounce,debounceTime:C=W.debounceTime,deepCompare:m=W.deepCompare}=W)=>{let{builder:u}=e,{cache:a,submitDispatcher:y,loggerManager:T}=u,h=Ne(T.init("useSubmit")).current,R=V(C),[s,O,{setRenderKey:x,setCacheData:g}]=X({logger:h,command:e,dispatcher:y,initialData:b,deepCompare:m,dependencyTracking:r}),[f,v]=H({logger:h,actions:O,command:e,dispatcher:y,setCacheData:g}),{addDataListener:M,addLifecycleListeners:A}=v,o=(...U)=>{let E=U[0],S=e.clone(E);if(t)return h.warning("Cannot submit request",{disabled:t,options:E}),[null,null,0];let K=()=>(M(S),$e(S,"submit",w=>{A(S,w)}));return new Promise(w=>{(()=>_(void 0,null,function*(){if(h.debug("Submitting request",{disabled:t,options:E}),d)R.debounce(()=>_(void 0,null,function*(){let B=yield K();w(B)}));else{let B=yield K();w(B)}}))()})},i=U=>{!U||(U&&U instanceof Ce?a.revalidate(We(U)):U instanceof Ce||a.revalidate(U))},l={onSubmitSuccess:f.onSuccess,onSubmitError:f.onError,onSubmitFinished:f.onFinished,onSubmitRequestStart:f.onRequestStart,onSubmitResponseStart:f.onResponseStart,onSubmitDownloadProgress:f.onDownloadProgress,onSubmitUploadProgress:f.onUploadProgress,onSubmitOfflineError:f.onOfflineError,onSubmitAbort:f.onAbort};return Ge(()=>{M(e)}),P(k(k({submit:o,get data(){return x("data"),s.data},get error(){return x("error"),s.error},get submitting(){return x("loading"),s.loading},get status(){return x("status"),s.status},get retries(){return x("retries"),s.retries},get timestamp(){return x("timestamp"),s.timestamp},abort:f.abort},O),l),{isDebouncing:R.active,revalidate:i})};var W={disabled:!1,dependencyTracking:!0,cacheOnMount:!0,initialData:null,debounce:!1,debounceTime:400,suspense:!1,shouldThrow:!1,invalidate:[],deepCompare:!0};import{useState as he,useRef as Je}from"react";import{getCommandDispatcher as ze}from"@better-typed/hyper-fetch";import{useDidMount as He,useDidUpdate as Xe}from"@better-typed/react-lifecycle-hooks";var wn=(e,t=pe)=>{let{queueType:r=pe.queueType}=t,{abortKey:b,queueKey:d,builder:C}=e,{commandManager:m}=C,[u]=ze(e,r),a=Je(null),[y,T]=he(!1),[h,R]=he([]),s=f=>f.map(v=>P(k({},v),{stopRequest:()=>u[0].stopRequest(d,v.requestId),startRequest:()=>u[0].startRequest(d,v.requestId),deleteRequest:()=>u[0].delete(d,v.requestId,b)})),O=()=>{let f=u.getQueue(d);T(f.stopped),R(s(f.requests))},x=f=>{T(f.stopped),R(s(f.requests))},g=()=>{var i;let f=u.events.onQueueChange(d,x),v=u.events.onQueueStatus(d,x),M=m.events.onDownloadProgress(d,(l,{requestId:U})=>{R(E=>E.map(S=>S.requestId===U?P(k({},S),{downloading:l}):S))}),A=m.events.onUploadProgress(d,(l,{requestId:U})=>{R(E=>E.map(S=>S.requestId===U?P(k({},S),{uploading:l}):S))}),o=()=>{v(),f(),M(),A()};return(i=a.current)==null||i.call(a),a.current=o,o};return He(O),Xe(g,[y,h,R,T],!0),{stopped:y,requests:h,stop:()=>u[0].stop(d),pause:()=>u[0].pause(d),start:()=>u[0].start(d)}};var pe={queueType:"auto"};import{useRef as Ye}from"react";import{getCommandDispatcher as Ze,Command as Re,getCommandKey as _e}from"@better-typed/hyper-fetch";var zn=(e,{dependencyTracking:t=ee.dependencyTracking,initialData:r=ee.initialData,deepCompare:b=ee.deepCompare}=ee)=>{let{cacheKey:d,builder:C}=e,{cache:m,loggerManager:u}=C,a=Ye(u.init("useCache")).current,[y]=Ze(e),[T,h,{setRenderKey:R,setCacheData:s}]=X({logger:a,command:e,dispatcher:y,initialData:r,deepCompare:b,dependencyTracking:t}),[O]=H({logger:a,actions:h,command:e,dispatcher:y,setCacheData:s}),x=g=>{g&&g instanceof Re?m.revalidate(`/${_e(g,!0)}/`):g&&!(g instanceof Re)?m.revalidate(g):m.revalidate(d)};return P(k({get data(){return R("data"),T.data},get error(){return R("error"),T.error},get loading(){return R("loading"),T.loading},get status(){return R("status"),T.status},get retries(){return R("retries"),T.retries},get timestamp(){return R("timestamp"),T.timestamp},onCacheError:O.onError,onCacheSuccess:O.onSuccess,onCacheChange:O.onFinished},h),{revalidate:x})};var ee={dependencyTracking:!0,initialData:null,deepCompare:!0};import{useState as xe}from"react";import{useDidMount as Ve}from"@better-typed/react-lifecycle-hooks";var nr=e=>{let[t,r]=xe(e.appManager.isOnline),[b,d]=xe(e.appManager.isFocused),C=()=>{let a=e.appManager.events.onOnline(()=>r(!0)),y=e.appManager.events.onOffline(()=>r(!1)),T=e.appManager.events.onFocus(()=>d(!0)),h=e.appManager.events.onBlur(()=>d(!1));return()=>{a(),y(),T(),h()}},m=a=>{e.appManager.setOnline(a)},u=a=>{e.appManager.setFocused(a)};return Ve(C),{isOnline:t,isFocused:b,setOnline:m,setFocused:u}};export{X as UseTrackedState,N as getDetailsState,ce as getInitialState,Le as getTimestamp,Pe as getValidCacheData,j as initialState,fe as isEmpty,ne as isEqual,ue as isStaleCacheData,Ut as responseToCacheValue,nr as useAppManager,zn as useCache,ee as useCacheDefaultOptions,H as useCommandEvents,V as useDebounce,Zt as useFetch,q as useFetchDefaultOptions,wn as useQueue,pe as useQueueDefaultOptions,gn as useSubmit,W as useSubmitDefaultOptions};
var xe=Object.defineProperty,Se=Object.defineProperties;var De=Object.getOwnPropertyDescriptors;var de=Object.getOwnPropertySymbols;var Oe=Object.prototype.hasOwnProperty,Ue=Object.prototype.propertyIsEnumerable;var Te=(e,t,r)=>t in e?xe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,O=(e,t)=>{for(var r in t||(t={}))Oe.call(t,r)&&Te(e,r,t[r]);if(de)for(var r of de(t))Ue.call(t,r)&&Te(e,r,t[r]);return e},B=(e,t)=>Se(e,De(t));var te=(e,t,r)=>new Promise((C,d)=>{var R=a=>{try{o(r.next(a))}catch(y){d(y)}},l=a=>{try{o(r.throw(a))}catch(y){d(y)}},o=a=>a.done?C(a.value):Promise.resolve(a.value).then(R,l);o((r=r.apply(e,t)).next())});import{useRef as Me}from"react";import{useDidUpdate as ie,useDidMount as Le}from"@better-typed/react-lifecycle-hooks";import{Command as be,getCommandKey as Ke}from"@better-typed/hyper-fetch";import{useRef as M}from"react";import{getErrorMessage as ke}from"@better-typed/hyper-fetch";import{useWillUnmount as ve}from"@better-typed/react-lifecycle-hooks";var Z=({command:e,dispatcher:t,logger:r,actions:C,setCacheData:d})=>{let{cache:R,commandManager:l}=e.builder,o=M(null),a=M(null),y=M(null),T=M(null),h=M(null),x=M(null),u=M(null),E=M(null),U=M(null),f=M(new Map),w=M(null),g=n=>{let c=f.current.get(n);c==null||c.unmount(),f.current.delete(n)},S=()=>{let n=f.current;Array.from(n.values()).forEach(i=>{i.unmount()}),n.clear()},I=(n,c,i)=>{var H,X,G,j,D;let{isOffline:W,isFailed:k,isCanceled:Q}=i;e.offline&&W&&k?(r.debug("Performing offline error callback",{data:c,details:i}),(H=T.current)==null||H.call(T,{response:c[1],command:n,details:i})):Q?(r.debug("Performing abort callback",{data:c,details:i}),(X=y.current)==null||X.call(y,{response:c[1],command:n,details:i})):k?(r.debug("Performing error callback",{data:c,details:i}),(j=a.current)==null||j.call(a,{response:c[1],command:n,details:i})):(r.debug("Performing success callback",{data:c,details:i}),(G=o.current)==null||G.call(o,{response:c[0],command:n,details:i})),(D=h.current)==null||D.call(h,{response:c,command:n,details:i})},s=n=>({isLoading:c})=>{let i=!c&&!t.hasRunningRequests(n);(c||i)&&C.setLoading(c,!1)},p=(n,c)=>{var i;(i=E.current)==null||i.call(E,n,c)},m=(n,c)=>{var i;(i=U.current)==null||i.call(U,n,c)},F=n=>c=>{var i;(i=x.current)==null||i.call(x,{command:n,details:c})},b=n=>c=>{var i;(i=u.current)==null||i.call(u,{command:n,details:c})},q=n=>(c,i)=>{I(n,c,i)},L=({requestId:n})=>{g(n)},P=n=>()=>{let c=[null,ke("abort"),0],i={retries:0,timestamp:+new Date,isFailed:!1,isCanceled:!0,isOffline:!1};I(n,c,i)},K=()=>{var n;(n=w.current)==null||n.unmount(),w.current=null},se=n=>{let c=l.events.onLoading(n.queueKey,s(n.queueKey)),i=R.events.onData(n.cacheKey,d),W=l.events.onAbort(n.abortKey,P(n)),k=()=>{c(),i(),W()};return K(),w.current={unmount:k},k},A=(n,c)=>{if(!c){let{queueKey:j,cacheKey:D}=n,J=l.events.onRequestStart(j,F(n)),ee=l.events.onResponseStart(j,b(n)),Y=l.events.onUploadProgress(j,m),ae=l.events.onDownloadProgress(j,p),le=l.events.onResponse(D,q(n)),me=()=>{ae(),Y(),J(),ee(),le()};return f.current.set(j,{unmount:me}),me}let i=l.events.onRemoveById(c,L),W=l.events.onRequestStartById(c,F(n)),k=l.events.onResponseStartById(c,b(n)),Q=l.events.onResponseById(c,q(n)),H=l.events.onUploadProgressById(c,m),X=l.events.onDownloadProgressById(c,p),G=()=>{i(),X(),H(),W(),k(),Q()};return f.current.set(c,{unmount:G}),G},V=()=>{let{abortKey:n}=e;t.getAllRunningRequest().forEach(i=>{i.command.abortKey===n&&t.delete(i.command.queueKey,i.requestId,n)})};return ve(()=>{S(),K()}),[{abort:V,onSuccess:n=>{o.current=n},onError:n=>{a.current=n},onAbort:n=>{y.current=n},onOfflineError:n=>{T.current=n},onFinished:n=>{h.current=n},onRequestStart:n=>{x.current=n},onResponseStart:n=>{u.current=n},onDownloadProgress:n=>{E.current=n},onUploadProgress:n=>{U.current=n}},{addDataListener:se,clearDataListener:K,addLifecycleListeners:A,removeLifecycleListener:g,clearLifecycleListeners:S}]};import{useRef as qe}from"react";import{useWillUnmount as Fe}from"@better-typed/react-lifecycle-hooks";var ne=(e=600)=>{let t=qe(null),r=()=>{t.current!==null&&clearTimeout(t.current),t.current=null},C=(d,R)=>{r(),t.current=setTimeout(()=>{d()},R||e)};return Fe(r),{debounce:C,resetDebounce:r,active:!!t.current}};var $={data:null,error:null,loading:!1,status:null,retries:0,timestamp:null};import{useRef as ye}from"react";import{useDidUpdate as ge,useForceUpdate as Pe}from"@better-typed/react-lifecycle-hooks";var fe=e=>{let t=Object.prototype.toString.call(e);return Array.isArray(e)?!e.length:typeof e=="object"&&e!==null&&t==="[object Object]"?!Object.keys(e).length:!1},oe=(e,t)=>{let r=Object.prototype.toString.call(e),C=Object.prototype.toString.call(t),d=typeof e,R=typeof t,l=a=>d===a&&R===a,o=a=>r===a&&C===a;return r!==C?!1:e===null&&t===null||l("number")&&Number.isNaN(e)&&Number.isNaN(t)||fe(e)&&fe(t)?!0:Array.isArray(e)&&Array.isArray(t)?e.length!==t.length?!1:!e.some((a,y)=>!oe(a,t[y])):l("object")&&o("[object Object]")?Object.keys(e).length!==Object.keys(t).length?!1:!Object.entries(e).some(([a,y])=>!oe(y,t[a])):e instanceof Date&&t instanceof Date?+e==+t:e===t};var z=(e,t)=>O({retries:(e==null?void 0:e.retries)||0,timestamp:+new Date,isFailed:!1,isCanceled:!1,isOffline:!1},t),ue=(e,t)=>t?+new Date>+t+e:!0,Ie=(e,t,r)=>!ue(e.cacheTime,r==null?void 0:r.details.timestamp)&&r?r:t?{data:t,details:z(),cacheTime:1e3,clearKey:e.builder.cache.clearKey}:null,we=e=>e?new Date(e):null,ce=(e,t,r)=>{var y,T,h;let{builder:C,cacheKey:d}=r,{cache:R}=C,l=R.get(d),o=Ie(r,e,l),a=t.hasRunningRequests(r.queueKey);return B(O({},$),{data:((y=o==null?void 0:o.data)==null?void 0:y[0])||$.data,error:((T=o==null?void 0:o.data)==null?void 0:T[1])||$.error,status:((h=o==null?void 0:o.data)==null?void 0:h[2])||$.status,retries:(o==null?void 0:o.details.retries)||$.retries,timestamp:we((o==null?void 0:o.details.timestamp)||$.timestamp),loading:a})};var _=({command:e,dispatcher:t,initialData:r,deepCompare:C,dependencyTracking:d,defaultCacheEmitting:R=!0})=>{let{builder:l,cacheKey:o,queueKey:a,cacheTime:y}=e,{cache:T,commandManager:h}=l,x=Pe(),u=ye(ce(r,t,e)),E=ye([]),U=()=>{let s=T.get(o);return ue(y,(s==null?void 0:s.details.timestamp)||u.current.timestamp)},f=s=>{E.current.some(m=>s.includes(m))&&x()},w=s=>{E.current.includes(s)||E.current.push(s)};ge(()=>{u.current.loading=t.hasRunningRequests(a);let s=ce(r,t,e),p=(r==null?void 0:r[0])===u.current.data,m=!!(u.current.data||u.current.error)&&!p,F=!m&&u.current.data,b=m&&!u.current.data;(F||b)&&(u.current=s)},[o,a],!0),ge(()=>{(()=>{d||Object.keys(u.current).forEach(p=>w(p))})()},[d],!0);let g=(s,p)=>typeof C=="function"?C(s,p):C?oe(s,p):!1,S=s=>te(void 0,null,function*(){let p={data:s.data[0],error:s.data[1],status:s.data[2],retries:s.details.retries,timestamp:new Date(s.details.timestamp),loading:u.current.loading},m=Object.keys(p).filter(F=>{let b=F,q=u.current[b],L=p[b];return!g(q,L)});u.current=O(O({},u.current),p),f(m)}),I={setData:(s,p=R)=>{if(p){let m=u.current;T.set(e,[s,m.error,m.status],z(u.current))}else u.current.data=s,f(["data"])},setError:(s,p=R)=>{if(p){let m=u.current;T.set(e,[m.data,s,m.status],z(u.current,{isFailed:!!s}))}else u.current.error=s,f(["error"])},setLoading:(s,p=!0)=>{p?h.events.emitLoading(a,"",{queueKey:a,requestId:"",isLoading:s,isRetry:!1,isOffline:!1}):(u.current.loading=s,f(["loading"]))},setStatus:(s,p=R)=>{if(p){let m=u.current;T.set(e,[m.data,m.error,s],z(u.current))}else u.current.status=s,f(["status"])},setRetries:(s,p=R)=>{if(p){let m=u.current;T.set(e,[m.data,m.error,m.status],z(u.current,{retries:s}))}else u.current.retries=s,f(["retries"])},setTimestamp:(s,p=R)=>{if(p){let m=u.current;T.set(e,[m.data,m.error,m.status],z(u.current,{timestamp:+s}))}else u.current.timestamp=s,f(["timestamp"])}};return[u.current,I,{setRenderKey:w,setCacheData:S,getStaleStatus:U}]};var zt=(e,{dependencies:t=v.dependencies,disabled:r=v.disabled,dependencyTracking:C=v.dependencyTracking,revalidateOnMount:d=v.revalidateOnMount,initialData:R=v.initialData,refresh:l=v.refresh,refreshTime:o=v.refreshTime,refreshBlurred:a=v.refreshBlurred,refreshOnBlur:y=v.refreshOnBlur,refreshOnFocus:T=v.refreshOnFocus,refreshOnReconnect:h=v.refreshOnReconnect,debounce:x=v.debounce,debounceTime:u=v.debounceTime,deepCompare:E=v.deepCompare}=v)=>{let U=JSON.stringify(e.dump()),f=ne(u),w=ne(o),{cacheKey:g,queueKey:S,builder:I}=e,{cache:s,fetchDispatcher:p,appManager:m,loggerManager:F}=I,b=Me(F.init("useFetch")).current,[q,L,{setRenderKey:P,setCacheData:K,getStaleStatus:se}]=_({logger:b,command:e,dispatcher:p,initialData:R,deepCompare:E,dependencyTracking:C}),[A,V]=Z({logger:b,actions:L,command:e,dispatcher:p,setCacheData:K}),{addDataListener:n,addLifecycleListeners:c,clearDataListener:i,clearLifecycleListeners:W}=V,k=()=>{r?b.debug("Cannot add to fetch queue",{disabled:r}):(b.debug("Fetching data"),p.add(e))};function Q(){!l||(b.debug(`Starting refresh counter, request will be send in ${o}ms`),w.debounce(()=>{let D=!m.isFocused,J=p.hasRunningRequests(e.queueKey),ee=p.getIsActiveQueue(e.queueKey),Y=J||ee;(D&&a&&!Y||!D&&!Y)&&(k(),b.debug("Performing refresh request")),Q()}))}let H=D=>{D&&D instanceof be?s.revalidate(Ke(D)):D&&!(D instanceof be)?s.revalidate(D):(k(),Q())},X=()=>{let D=se(),J=p.getIsActiveQueue(S);(d||D&&!J)&&k()},G=()=>{x?(b.debug("Debouncing request",{queueKey:S,command:e}),f.debounce(()=>k())):k()};return ie(()=>{n(e),c(e);let D=m.events.onFocus(()=>{T&&(k(),Q())}),J=m.events.onBlur(()=>{y&&(k(),Q())}),ee=m.events.onOnline(()=>{h&&(k(),Q())}),Y=s.events.onRevalidate(g,k);return()=>{i(),W(),D(),J(),ee(),Y()}},[U],!0),Le(X),ie(G,[U,...t]),ie(Q,[U,...t,r,l,o],!0),B(O(O({get data(){return P("data"),q.data},get error(){return P("error"),q.error},get loading(){return P("loading"),q.loading},get status(){return P("status"),q.status},get retries(){return P("retries"),q.retries},get timestamp(){return P("timestamp"),q.timestamp}},L),A),{isDebouncing:f.active,revalidate:H})};import{DateInterval as Ae}from"@better-typed/hyper-fetch";var v={dependencies:[],disabled:!1,dependencyTracking:!0,revalidateOnMount:!0,initialData:null,refresh:!1,refreshTime:Ae.hour,refreshBlurred:!0,refreshOnBlur:!1,refreshOnFocus:!1,refreshOnReconnect:!1,debounce:!1,debounceTime:400,deepCompare:!0};import{useRef as Ce}from"react";import{Command as Re,getCommandKey as Qe,commandSendRequest as Be}from"@better-typed/hyper-fetch";import{useDidMount as je}from"@better-typed/react-lifecycle-hooks";var yn=(e,{disabled:t=N.disabled,dependencyTracking:r=N.dependencyTracking,initialData:C=N.initialData,debounce:d=N.debounce,debounceTime:R=N.debounceTime,deepCompare:l=N.deepCompare}=N)=>{let{builder:o}=e,{cache:a,submitDispatcher:y,loggerManager:T}=o,h=Ce(T.init("useSubmit")).current,x=ne(R),u=Ce(()=>null),[E,U,{setRenderKey:f,setCacheData:w}]=_({logger:h,command:e,dispatcher:y,initialData:C,deepCompare:l,dependencyTracking:r}),[g,S]=Z({logger:h,actions:U,command:e,dispatcher:y,setCacheData:w}),{addDataListener:I,addLifecycleListeners:s}=S,p=(...b)=>{let q=b[0],L=e.clone(q);if(t)throw h.warning("Cannot submit request",{disabled:t,options:q}),new Error("Cannot submit request. Option 'disabled' is enabled");let P=()=>(I(L),Be(L,"submit",K=>{s(L,K)}));return new Promise(K=>{(()=>te(void 0,null,function*(){if(h.debug("Submitting request",{disabled:t,options:q}),d)u.current=A=>{u.current(A),K(A)},x.debounce(()=>te(void 0,null,function*(){let A=u.current;u.current=()=>null;let V=yield P();A(V)}));else{let A=yield P();K(A)}}))()})},m=b=>{!b||(b&&b instanceof Re?a.revalidate(Qe(b)):b instanceof Re||a.revalidate(b))},F={onSubmitSuccess:g.onSuccess,onSubmitError:g.onError,onSubmitFinished:g.onFinished,onSubmitRequestStart:g.onRequestStart,onSubmitResponseStart:g.onResponseStart,onSubmitDownloadProgress:g.onDownloadProgress,onSubmitUploadProgress:g.onUploadProgress,onSubmitOfflineError:g.onOfflineError,onSubmitAbort:g.onAbort};return je(()=>{I(e)}),B(O(O({submit:p,get data(){return f("data"),E.data},get error(){return f("error"),E.error},get submitting(){return f("loading"),E.loading},get status(){return f("status"),E.status},get retries(){return f("retries"),E.retries},get timestamp(){return f("timestamp"),E.timestamp},abort:g.abort},U),F),{isDebouncing:x.active,revalidate:m})};var N={disabled:!1,dependencyTracking:!0,cacheOnMount:!0,initialData:null,debounce:!1,debounceTime:400,suspense:!1,shouldThrow:!1,invalidate:[],deepCompare:!0};import{useState as he,useRef as Ne}from"react";import{getCommandDispatcher as We}from"@better-typed/hyper-fetch";import{useDidMount as Ge,useDidUpdate as Je}from"@better-typed/react-lifecycle-hooks";var In=(e,t=pe)=>{let{queueType:r=pe.queueType}=t,{abortKey:C,queueKey:d,builder:R}=e,{commandManager:l}=R,[o]=We(e,r),a=Ne(null),[y,T]=he(!1),[h,x]=he([]),u=g=>g.map(S=>B(O({},S),{stopRequest:()=>o.stopRequest(d,S.requestId),startRequest:()=>o.startRequest(d,S.requestId),deleteRequest:()=>o.delete(d,S.requestId,C)})),E=(g,S)=>{x(I=>I.map(s=>s.requestId===g?O(O({},s),S):s))},U=()=>{let g=o.getQueue(d);T(g.stopped),x(u(g.requests))},f=g=>{T(g.stopped),x(u(g.requests))},w=()=>{var m;let g=o.events.onQueueChange(d,f),S=o.events.onQueueStatus(d,f),I=l.events.onDownloadProgress(d,(F,{requestId:b})=>{E(b,{downloading:F})}),s=l.events.onUploadProgress(d,(F,{requestId:b})=>{E(b,{uploading:F})}),p=()=>{S(),g(),I(),s()};return(m=a.current)==null||m.call(a),a.current=p,p};return Ge(U),Je(w,[y,h,x,T],!0),{stopped:y,requests:h,stop:()=>o.stop(d),pause:()=>o.pause(d),start:()=>o.start(d)}};var pe={queueType:"auto"};import{useRef as $e}from"react";import{getCommandDispatcher as ze,Command as He,getCommandKey as Xe}from"@better-typed/hyper-fetch";var $n=(e,{dependencyTracking:t=re.dependencyTracking,initialData:r=re.initialData,deepCompare:C=re.deepCompare}=re)=>{let{cacheKey:d,builder:R}=e,{cache:l,loggerManager:o}=R,a=$e(o.init("useCache")).current,[y]=ze(e),[T,h,{setRenderKey:x,setCacheData:u}]=_({logger:a,command:e,dispatcher:y,initialData:r,deepCompare:C,dependencyTracking:t}),[E]=Z({logger:a,actions:h,command:e,dispatcher:y,setCacheData:u}),U=f=>{f instanceof He?l.revalidate(Xe(f,!0)):f?l.revalidate(f):l.revalidate(d)};return B(O({get data(){return x("data"),T.data},get error(){return x("error"),T.error},get loading(){return x("loading"),T.loading},get status(){return x("status"),T.status},get retries(){return x("retries"),T.retries},get timestamp(){return x("timestamp"),T.timestamp},onCacheError:E.onError,onCacheSuccess:E.onSuccess,onCacheChange:E.onFinished},h),{revalidate:U})};var re={dependencyTracking:!0,initialData:null,deepCompare:!0};import{useState as Ee}from"react";import{useDidMount as Ye}from"@better-typed/react-lifecycle-hooks";var tr=e=>{let[t,r]=Ee(e.appManager.isOnline),[C,d]=Ee(e.appManager.isFocused),R=()=>{let a=e.appManager.events.onOnline(()=>r(!0)),y=e.appManager.events.onOffline(()=>r(!1)),T=e.appManager.events.onFocus(()=>d(!0)),h=e.appManager.events.onBlur(()=>d(!1));return()=>{a(),y(),T(),h()}},l=a=>{e.appManager.setOnline(a)},o=a=>{e.appManager.setFocused(a)};return Ye(R),{isOnline:t,isFocused:C,setOnline:l,setFocused:o}};export{z as getDetailsState,ce as getInitialState,we as getTimestamp,Ie as getValidCacheData,$ as initialState,fe as isEmpty,oe as isEqual,ue as isStaleCacheData,tr as useAppManager,$n as useCache,re as useCacheDefaultOptions,Z as useCommandEvents,ne as useDebounce,zt as useFetch,v as useFetchDefaultOptions,In as useQueue,pe as useQueueDefaultOptions,yn as useSubmit,N as useSubmitDefaultOptions,_ as useTrackedState};
//# sourceMappingURL=index.esm.js.map

@@ -34,3 +34,3 @@ import { CommandInstance, ExtractResponse, ExtractError, CacheValueType } from "@better-typed/hyper-fetch";

*/
revalidate: (invalidateKey?: string | CommandInstance) => void;
revalidate: (invalidateKey?: string | RegExp | CommandInstance) => void;
};

@@ -9,2 +9,2 @@ import { CommandInstance } from "@better-typed/hyper-fetch";

*/
export declare const useFetch: <T extends CommandInstance>(command: T, { dependencies, disabled, dependencyTracking, revalidateOnMount, initialData, refresh, refreshTime, refreshBlurred, refreshOnTabBlur, refreshOnTabFocus, refreshOnReconnect, debounce, debounceTime, deepCompare, }?: UseFetchOptionsType<T>) => UseFetchReturnType<T>;
export declare const useFetch: <T extends CommandInstance>(command: T, { dependencies, disabled, dependencyTracking, revalidateOnMount, initialData, refresh, refreshTime, refreshBlurred, refreshOnBlur, refreshOnFocus, refreshOnReconnect, debounce, debounceTime, deepCompare, }?: UseFetchOptionsType<T>) => UseFetchReturnType<T>;

@@ -40,7 +40,7 @@ import { CommandInstance, ExtractResponse, ExtractError, CacheValueType } from "@better-typed/hyper-fetch";

*/
refreshOnTabBlur?: boolean;
refreshOnBlur?: boolean;
/**
* Enable/disable data refresh if user enters current tab.
*/
refreshOnTabFocus?: boolean;
refreshOnFocus?: boolean;
/**

@@ -71,3 +71,3 @@ * Enable/disable data refresh if network is restored.

*/
revalidate: (invalidateKey?: string | CommandInstance) => void;
revalidate: (invalidateKey?: string | RegExp | CommandInstance) => void;
};

@@ -1,2 +0,2 @@

import { CacheValueType, ExtractError, ExtractResponse, CommandInstance } from "@better-typed/hyper-fetch";
import { CacheValueType, ExtractError, ExtractResponse, CommandInstance, ExtractClientReturnType } from "@better-typed/hyper-fetch";
import { isEqual } from "../utils";

@@ -74,3 +74,3 @@ import { OnErrorCallbackType, OnFinishedCallbackType, OnProgressCallbackType, OnStartCallbackType, OnSuccessCallbackType, UseTrackedStateType, UseTrackedStateActions } from "../helpers";

*/
submit: (...parameters: Parameters<T["send"]>) => void;
submit: (...parameters: Parameters<T["send"]>) => Promise<ExtractClientReturnType<T>>;
/**

@@ -77,0 +77,0 @@ * Request loading state

{
"name": "@better-typed/react-hyper-fetch",
"version": "0.9.0",
"version": "0.9.5",
"private": false,

@@ -17,3 +17,3 @@ "description": "React hooks and utils for the hyper-fetch",

"test": "jest --watchAll --maxWorkers=3",
"test-pipeline": "jest --watchAll=false --maxWorkers=1",
"test-pipeline": "jest --watchAll=false --maxWorkers=1 --no-cache",
"start": "yarn build && npx run-when-changed --watch 'src/**/*.ts' --exec 'yarn build'",

@@ -24,4 +24,3 @@ "build": "yarn clean && node ../../scripts/build.js",

"format": "prettier --write .",
"precommit": "yarn lint-staged",
"semantic-release": "semantic-release --ci"
"precommit": "yarn lint-staged"
},

@@ -28,0 +27,0 @@ "peerDependencies": {

@@ -13,3 +13,3 @@ import { useRef } from "react";

} from "@better-typed/hyper-fetch";
import { useIsMounted, useWillUnmount } from "@better-typed/react-lifecycle-hooks";
import { useWillUnmount } from "@better-typed/react-lifecycle-hooks";

@@ -24,3 +24,3 @@ import {

UseCommandEventsReturnType,
UseCommandEventsOptionsType,
UseCommandEventsPropsType,
UseCommandEventsLifecycleMap,

@@ -41,7 +41,5 @@ } from "helpers";

setCacheData,
}: UseCommandEventsOptionsType<T>): UseCommandEventsReturnType<T> => {
}: UseCommandEventsPropsType<T>): UseCommandEventsReturnType<T> => {
const { cache, commandManager } = command.builder;
const isMounted = useIsMounted();
// ******************

@@ -92,4 +90,2 @@ // Callbacks

) => {
if (!isMounted) return logger.debug("Callback cancelled, component is unmounted");
const { isOffline, isFailed, isCanceled } = details;

@@ -127,7 +123,7 @@

const handleDownloadProgress = (progress: FetchProgressType, details: CommandEventDetails<T>) => {
onDownloadProgressCallback?.current?.(progress, details);
onDownloadProgressCallback.current?.(progress, details);
};
const handleUploadProgress = (progress: FetchProgressType, details: CommandEventDetails<T>) => {
onUploadProgressCallback?.current?.(progress, details);
onUploadProgressCallback.current?.(progress, details);
};

@@ -137,3 +133,3 @@

return (details: CommandEventDetails<T>) => {
onRequestStartCallback?.current?.({ command: cmd, details });
onRequestStartCallback.current?.({ command: cmd, details });
};

@@ -143,3 +139,3 @@ };

return (details: CommandEventDetails<T>) => {
onResponseStartCallback?.current?.({ command: cmd, details });
onResponseStartCallback.current?.({ command: cmd, details });
};

@@ -146,0 +142,0 @@ };

@@ -21,3 +21,3 @@ import {

// Props
export type UseCommandEventsOptionsType<T extends CommandInstance> = {
export type UseCommandEventsPropsType<T extends CommandInstance> = {
command: T;

@@ -95,16 +95,16 @@ dispatcher: Dispatcher;

params: CallbackParameters<Command, ExtractResponse<Command>>,
) => void;
) => void | Promise<void>;
export type OnErrorCallbackType<Command extends CommandInstance> = (
params: CallbackParameters<Command, ExtractError<Command>>,
) => void;
) => void | Promise<void>;
export type OnFinishedCallbackType<Command extends CommandInstance> = (
params: CallbackParameters<Command, ExtractClientReturnType<Command>>,
) => void;
) => void | Promise<void>;
export type OnStartCallbackType<Command extends CommandInstance> = (params: {
details: CommandEventDetails<Command>;
command: Command;
}) => void;
}) => void | Promise<void>;
export type OnProgressCallbackType = <Command extends CommandInstance>(
progress: FetchProgressType,
details: CommandEventDetails<Command>,
) => void;
) => void | Promise<void>;
import { useRef } from "react";
import { useWillUnmount, useDidUpdate } from "@better-typed/react-lifecycle-hooks";
import { useWillUnmount } from "@better-typed/react-lifecycle-hooks";
type Debounce = {
time: number;
timer: ReturnType<typeof setTimeout> | null;
};
type Debounce = ReturnType<typeof setTimeout> | null;

@@ -23,14 +20,7 @@ type DebounceFunction = (callback: () => void | Promise<void>, time?: number) => void;

export const useDebounce = (delay = 600): UseDebounceReturnType => {
const debounce = useRef<Debounce>({
time: delay,
timer: null,
});
const debounce = useRef<Debounce>(null);
useDidUpdate(() => {
debounce.current.time = delay;
}, [delay]);
const resetDebounce = () => {
if (debounce.current.timer !== null) clearTimeout(debounce.current.timer);
debounce.current.timer = null;
if (debounce.current !== null) clearTimeout(debounce.current);
debounce.current = null;
};

@@ -40,5 +30,5 @@

resetDebounce();
debounce.current.timer = setTimeout(() => {
debounce.current = setTimeout(() => {
callback();
}, time || debounce.current.time);
}, time || delay);
};

@@ -48,3 +38,3 @@

return { debounce: setDebounce, resetDebounce, active: !!debounce.current.timer };
return { debounce: setDebounce, resetDebounce, active: !!debounce.current };
};

@@ -22,3 +22,3 @@ import { useRef } from "react";

*/
export const UseTrackedState = <T extends CommandInstance>({
export const useTrackedState = <T extends CommandInstance>({
command,

@@ -46,3 +46,3 @@ dispatcher,

return isStaleCacheData(cacheTime, cacheData?.details.timestamp || state.current?.timestamp);
return isStaleCacheData(cacheTime, cacheData?.details.timestamp || state.current.timestamp);
};

@@ -49,0 +49,0 @@

@@ -28,5 +28,4 @@ import {

export const isStaleCacheData = (cacheTime: NullableType<number>, cacheTimestamp: NullableType<Date | number>) => {
export const isStaleCacheData = (cacheTime: number, cacheTimestamp: NullableType<Date | number>) => {
if (!cacheTimestamp) return true;
if (!cacheTime) return false;
return +new Date() > +cacheTimestamp + cacheTime;

@@ -62,14 +61,2 @@ };

export const responseToCacheValue = <T>(
response: ClientResponseType<ExtractResponse<T>, ExtractError<T>> | null,
): NullableType<CacheValueType> => {
if (!response) return null;
return {
data: response,
details: getDetailsState(),
cacheTime: 1000,
clearKey: "",
};
};
export const getInitialState = <T extends CommandInstance>(

@@ -95,4 +82,4 @@ initialData: ClientResponseType<ExtractResponse<T>, ExtractError<T>> | null,

timestamp: getTimestamp(cacheState?.details.timestamp || initialState.timestamp),
loading: initialLoading ?? initialState.loading,
loading: initialLoading,
};
};
import { useRef } from "react";
import { getCommandDispatcher, CommandInstance, Command, getCommandKey } from "@better-typed/hyper-fetch";
import { useCommandEvents, UseTrackedState } from "helpers";
import { useCommandEvents, useTrackedState } from "helpers";
import { UseCacheOptionsType, useCacheDefaultOptions, UseCacheReturnType } from "use-cache";

@@ -25,3 +25,3 @@

*/
const [state, actions, { setRenderKey, setCacheData }] = UseTrackedState<T>({
const [state, actions, { setRenderKey, setCacheData }] = useTrackedState<T>({
logger,

@@ -47,5 +47,5 @@ command,

const revalidate = (invalidateKey?: string | CommandInstance | RegExp) => {
if (invalidateKey && invalidateKey instanceof Command) {
cache.revalidate(`/${getCommandKey(invalidateKey, true)}/`);
} else if (invalidateKey && !(invalidateKey instanceof Command)) {
if (invalidateKey instanceof Command) {
cache.revalidate(getCommandKey(invalidateKey, true));
} else if (invalidateKey) {
cache.revalidate(invalidateKey);

@@ -52,0 +52,0 @@ } else {

@@ -44,3 +44,3 @@ import { CommandInstance, ExtractResponse, ExtractError, CacheValueType } from "@better-typed/hyper-fetch";

*/
revalidate: (invalidateKey?: string | CommandInstance) => void;
revalidate: (invalidateKey?: string | RegExp | CommandInstance) => void;
};

@@ -18,4 +18,4 @@ import { DateInterval, CommandInstance, RequiredKeys } from "@better-typed/hyper-fetch";

refreshBlurred: true,
refreshOnTabBlur: false,
refreshOnTabFocus: false,
refreshOnBlur: false,
refreshOnFocus: false,
refreshOnReconnect: false,

@@ -22,0 +22,0 @@ debounce: false,

@@ -5,3 +5,3 @@ import { useRef } from "react";

import { useDebounce, useCommandEvents, UseTrackedState } from "helpers";
import { useDebounce, useCommandEvents, useTrackedState } from "helpers";
import { UseFetchOptionsType, useFetchDefaultOptions, UseFetchReturnType } from "use-fetch";

@@ -26,4 +26,4 @@

refreshBlurred = useFetchDefaultOptions.refreshBlurred,
refreshOnTabBlur = useFetchDefaultOptions.refreshOnTabBlur,
refreshOnTabFocus = useFetchDefaultOptions.refreshOnTabFocus,
refreshOnBlur = useFetchDefaultOptions.refreshOnBlur,
refreshOnFocus = useFetchDefaultOptions.refreshOnFocus,
refreshOnReconnect = useFetchDefaultOptions.refreshOnReconnect,

@@ -47,3 +47,3 @@ debounce = useFetchDefaultOptions.debounce,

*/
const [state, actions, { setRenderKey, setCacheData, getStaleStatus }] = UseTrackedState<T>({
const [state, actions, { setRenderKey, setCacheData, getStaleStatus }] = useTrackedState<T>({
logger,

@@ -155,3 +155,3 @@ command,

const focusUnmount = appManager.events.onFocus(() => {
if (refreshOnTabFocus) {
if (refreshOnFocus) {
handleFetch();

@@ -162,3 +162,3 @@ handleRefresh();

const blurUnmount = appManager.events.onBlur(() => {
if (refreshOnTabBlur) {
if (refreshOnBlur) {
handleFetch();

@@ -165,0 +165,0 @@ handleRefresh();

@@ -42,7 +42,7 @@ import { CommandInstance, ExtractResponse, ExtractError, CacheValueType } from "@better-typed/hyper-fetch";

*/
refreshOnTabBlur?: boolean;
refreshOnBlur?: boolean;
/**
* Enable/disable data refresh if user enters current tab.
*/
refreshOnTabFocus?: boolean;
refreshOnFocus?: boolean;
/**

@@ -76,3 +76,3 @@ * Enable/disable data refresh if network is restored.

*/
revalidate: (invalidateKey?: string | CommandInstance) => void;
revalidate: (invalidateKey?: string | RegExp | CommandInstance) => void;
};

@@ -35,8 +35,12 @@ import { useState, useRef } from "react";

...req,
stopRequest: () => dispatcher[0].stopRequest(queueKey, req.requestId),
startRequest: () => dispatcher[0].startRequest(queueKey, req.requestId),
deleteRequest: () => dispatcher[0].delete(queueKey, req.requestId, abortKey),
stopRequest: () => dispatcher.stopRequest(queueKey, req.requestId),
startRequest: () => dispatcher.startRequest(queueKey, req.requestId),
deleteRequest: () => dispatcher.delete(queueKey, req.requestId, abortKey),
}));
};
const mergeRequestData = (requestId: string, data: Partial<QueueRequest<Command>>) => {
setRequests((prev) => prev.map((el) => (el.requestId === requestId ? { ...el, ...data } : el)));
};
// ******************

@@ -67,7 +71,7 @@ // State

const unmountDownload = commandManager.events.onDownloadProgress(queueKey, (progress, { requestId }) => {
setRequests((prev) => prev.map((el) => (el.requestId === requestId ? { ...el, downloading: progress } : el)));
mergeRequestData(requestId, { downloading: progress });
});
const unmountUpload = commandManager.events.onUploadProgress(queueKey, (progress, { requestId }) => {
setRequests((prev) => prev.map((el) => (el.requestId === requestId ? { ...el, uploading: progress } : el)));
mergeRequestData(requestId, { uploading: progress });
});

@@ -98,6 +102,6 @@

requests,
stop: () => dispatcher[0].stop(queueKey),
pause: () => dispatcher[0].pause(queueKey),
start: () => dispatcher[0].start(queueKey),
stop: () => dispatcher.stop(queueKey),
pause: () => dispatcher.pause(queueKey),
start: () => dispatcher.start(queueKey),
};
};

@@ -8,6 +8,9 @@ import { useRef } from "react";

CommandInstance,
ClientResponseType,
ExtractResponse,
ExtractError,
} from "@better-typed/hyper-fetch";
import { useDidMount } from "@better-typed/react-lifecycle-hooks";
import { useDebounce, UseTrackedState, useCommandEvents } from "helpers";
import { useDebounce, useTrackedState, useCommandEvents } from "helpers";
import { UseSubmitOptionsType, useSubmitDefaultOptions, UseSubmitReturnType } from "use-submit";

@@ -41,2 +44,3 @@

const requestDebounce = useDebounce(debounceTime);
const debounceResolve = useRef<(value: ClientResponseType<ExtractResponse<T>, ExtractError<T>>) => void>(() => null);

@@ -46,3 +50,3 @@ /**

*/
const [state, actions, { setRenderKey, setCacheData }] = UseTrackedState<T>({
const [state, actions, { setRenderKey, setCacheData }] = useTrackedState<T>({
logger,

@@ -79,3 +83,3 @@ command,

logger.warning(`Cannot submit request`, { disabled, options });
return [null, null, 0];
throw new Error("Cannot submit request. Option 'disabled' is enabled");
}

@@ -90,10 +94,19 @@

return new Promise<ExtractClientReturnType<T> | [null, null, null]>((resolve) => {
return new Promise<ExtractClientReturnType<T>>((resolve) => {
const performSubmit = async () => {
logger.debug(`Submitting request`, { disabled, options });
if (debounce) {
// We need to keep the resolve of debounced requests to prevent memory leaks
debounceResolve.current = (value: ClientResponseType<ExtractResponse<T>, ExtractError<T>>) => {
debounceResolve.current(value);
resolve(value);
};
// Start debouncing
requestDebounce.debounce(async () => {
// Cleanup debounce resolve
const callback = debounceResolve.current;
debounceResolve.current = () => null;
const value = await triggerRequest();
resolve(value);
callback(value);
});

@@ -100,0 +113,0 @@ } else {

@@ -1,2 +0,8 @@

import { CacheValueType, ExtractError, ExtractResponse, CommandInstance } from "@better-typed/hyper-fetch";
import {
CacheValueType,
ExtractError,
ExtractResponse,
CommandInstance,
ExtractClientReturnType,
} from "@better-typed/hyper-fetch";

@@ -86,3 +92,3 @@ import { isEqual } from "utils";

*/
submit: (...parameters: Parameters<T["send"]>) => void;
submit: (...parameters: Parameters<T["send"]>) => Promise<ExtractClientReturnType<T>>;
/**

@@ -89,0 +95,0 @@ * Request loading state

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc