@intrig/next 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # @intrig/next
2
+
3
+ @intrig/next is a placeholder project for code generation, specifically tailored for Next.js projects. This package is part of the Intrig toolset, designed to streamline the development process by providing autogenerated code and utilities for Next.js applications.
4
+
5
+ ## Features
6
+
7
+ - **Code Generation for Next.js Projects**: Generate boilerplate code to kickstart Next.js development quickly and efficiently.
8
+ - **Easy Integration**: Works seamlessly with Next.js to create scalable and maintainable applications.
9
+
10
+ ## Getting Started
11
+
12
+ To start using @intrig/next, simply install the package in your Next.js project:
13
+
14
+ ```bash
15
+ npm install @intrig/next
16
+ ```
17
+
18
+ This package will allow you to leverage autogenerated code for a variety of purposes within your Next.js app, saving development time and reducing boilerplate.
19
+
20
+ ## Documentation
21
+
22
+ For detailed instructions on how to use @intrig/next, please refer to the main documentation available in the [Intrig GitHub Repository](https://github.com/intrigsoft/intrig).
23
+
24
+ ## Contributing
25
+
26
+ We welcome contributions! Feel free to check out the [contribution guide](https://github.com/intrigsoft/intrig/blob/main/CONTRIBUTING.md) in the main repository.
27
+
28
+ ## License
29
+
30
+ @intrig/next is licensed under the MIT License. See the [LICENSE](https://github.com/intrigsoft/intrig/blob/main/LICENSE) file for more information.
31
+
32
+ ## Links
33
+
34
+ - [Main GitHub Repository](https://github.com/intrigsoft/intrig)
35
+
36
+ ## Support
37
+
38
+ For questions, suggestions, or assistance, please open an issue on the [GitHub repository](https://github.com/intrigsoft/intrig/issues).
39
+
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@intrig/next",
3
+ "version": "0.0.2",
4
+ "private": false,
5
+ "description": "Placeholder module for autogenerated intrig next.js boilerplate",
6
+ "dependencies": {
7
+ "module-alias": "^2.2.2",
8
+ "axios": "^1.7.7",
9
+ "immer": "^10.1.1",
10
+ "zod": "^3.23.8",
11
+ "fast-xml-parser": "^4.5.0",
12
+ "date-fns": "^4.1.0",
13
+ "loglevel": "1.8.1"
14
+ },
15
+ "peerDependencies": {
16
+ "react": "18.3.1",
17
+ "react-dom": "18.3.1",
18
+ "next": ">=13.0.0"
19
+ },
20
+ "devDependencies": {
21
+ "@types/glob": "^8.1.0"
22
+ },
23
+ "_moduleAliases": {
24
+ "@intrig/next-client": "./src/lib"
25
+ },
26
+ "type": "module",
27
+ "exports": {
28
+ "./*": "./src/*"
29
+ },
30
+ "module": "./src/index.js",
31
+ "main": "./src/index.js",
32
+ "types": "./src/index.d.ts"
33
+ }
@@ -0,0 +1,11 @@
1
+ import { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
2
+ type Interceptor = {
3
+ request?: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig | Promise<InternalAxiosRequestConfig>;
4
+ requestError?: (error: any) => any | Promise<any>;
5
+ response?: (response: AxiosResponse) => AxiosResponse | Promise<AxiosResponse>;
6
+ responseError?: (error: any) => any | Promise<any>;
7
+ };
8
+ export declare function getAxiosInstance(key: string): AxiosInstance;
9
+ export declare function addInterceptor(instanceKey: string | 'global', interceptor: Interceptor): void;
10
+ export declare function clearInterceptors(instanceKey: string | 'global'): void;
11
+ export {};
@@ -0,0 +1,60 @@
1
+ import axios from 'axios';
2
+ const axiosInstances = {};
3
+ const globalInterceptors = [];
4
+ const ejectedInterceptors = {};
5
+ export function getAxiosInstance(key) {
6
+ if (!axiosInstances[key]) {
7
+ const instance = axios.create();
8
+ applyGlobalInterceptors(instance, key);
9
+ axiosInstances[key] = instance;
10
+ }
11
+ return axiosInstances[key];
12
+ }
13
+ export function addInterceptor(instanceKey, interceptor) {
14
+ if (instanceKey === 'global') {
15
+ globalInterceptors.push(interceptor);
16
+ Object.keys(axiosInstances).forEach((key) => applyInterceptor(axiosInstances[key], interceptor, key));
17
+ }
18
+ else {
19
+ const instance = getAxiosInstance(instanceKey);
20
+ applyInterceptor(instance, interceptor, instanceKey);
21
+ }
22
+ }
23
+ export function clearInterceptors(instanceKey) {
24
+ if (instanceKey === 'global') {
25
+ globalInterceptors.length = 0;
26
+ Object.keys(axiosInstances).forEach((key) => ejectInterceptors(key));
27
+ }
28
+ else {
29
+ ejectInterceptors(instanceKey);
30
+ }
31
+ }
32
+ function applyInterceptor(instance, interceptor, key) {
33
+ const ejected = ejectedInterceptors[key] || [];
34
+ if (interceptor.request) {
35
+ const requestId = instance.interceptors.request.use(interceptor.request, interceptor.requestError);
36
+ ejected.push({ requestId });
37
+ }
38
+ if (interceptor.response) {
39
+ const responseId = instance.interceptors.response.use(interceptor.response, interceptor.responseError);
40
+ ejected.push({ responseId });
41
+ }
42
+ ejectedInterceptors[key] = ejected;
43
+ }
44
+ function applyGlobalInterceptors(instance, key) {
45
+ globalInterceptors.forEach((interceptor) => applyInterceptor(instance, interceptor, key));
46
+ }
47
+ function ejectInterceptors(key) {
48
+ const instance = axiosInstances[key];
49
+ const ejected = ejectedInterceptors[key] || [];
50
+ ejected.forEach(({ requestId, responseId }) => {
51
+ if (requestId !== undefined) {
52
+ instance.interceptors.request.eject(requestId);
53
+ }
54
+ if (responseId !== undefined) {
55
+ instance.interceptors.response.eject(responseId);
56
+ }
57
+ });
58
+ ejectedInterceptors[key] = [];
59
+ }
60
+ //# sourceMappingURL=axios.server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"axios.server.js","sourceRoot":"","sources":["../../../../lib/client-next/src/axios.server.ts"],"names":[],"mappings":"AAAA,OAAO,KAIN,MAAM,OAAO,CAAC;AAkBf,MAAM,cAAc,GAAkC,EAAE,CAAC;AACzD,MAAM,kBAAkB,GAAkB,EAAE,CAAC;AAC7C,MAAM,mBAAmB,GAAyC,EAAE,CAAC;AAErE,MAAM,UAAU,gBAAgB,CAAC,GAAW;IAC1C,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE,CAAC;QACzB,MAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC;QAChC,uBAAu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
1
+ import { IntrigHook, NetworkState } from '@intrig/next-client/network-state';
2
+ /**
3
+ * Converts a given hook into a promise-based function.
4
+ *
5
+ * @param {IntrigHook<P, B, T>} hook - The hook function to be converted.
6
+ * @param {string} [key='default'] - An optional key to uniquely identify the hook instance.
7
+ *
8
+ * @return {[(...params: Parameters<ReturnType<IntrigHook<P, B, T>>[1]>) => Promise<T>, () => void]}
9
+ * Returns a tuple containing a function that invokes the hook as a promise and a function to clear the state.
10
+ */
11
+ export declare function useAsPromise<P, B, T>(hook: IntrigHook<P, B, T>, key?: string): [(...params: Parameters<ReturnType<IntrigHook<P, B, T>>[1]>) => Promise<T>, () => void];
12
+ /**
13
+ * A custom hook that manages and returns the network state of a promise-based function,
14
+ * providing a way to execute the function and clear its state.
15
+ *
16
+ * @param fn The promise-based function whose network state is to be managed. It should be a function that returns a promise.
17
+ * @param key An optional identifier for the network state. Defaults to 'default'.
18
+ * @return A tuple containing the current network state, a function to execute the promise, and a function to clear the state.
19
+ */
20
+ export declare function useAsNetworkState<T, F extends ((...args: any) => Promise<T>)>(fn: F, key?: string): [NetworkState<T>, (...params: Parameters<F>) => void, () => void];
package/src/extra.js ADDED
@@ -0,0 +1,76 @@
1
+ import { error, init, isError, isSuccess, isValidationError, pending, success } from '@intrig/next-client/network-state';
2
+ import { useCallback, useEffect, useId, useMemo, useRef } from 'react';
3
+ import { useIntrigContext } from '@intrig/next-client/intrig-context';
4
+ /**
5
+ * Converts a given hook into a promise-based function.
6
+ *
7
+ * @param {IntrigHook<P, B, T>} hook - The hook function to be converted.
8
+ * @param {string} [key='default'] - An optional key to uniquely identify the hook instance.
9
+ *
10
+ * @return {[(...params: Parameters<ReturnType<IntrigHook<P, B, T>>[1]>) => Promise<T>, () => void]}
11
+ * Returns a tuple containing a function that invokes the hook as a promise and a function to clear the state.
12
+ */
13
+ export function useAsPromise(hook, key = 'default') {
14
+ const resolveRef = useRef();
15
+ const rejectRef = useRef();
16
+ let [state, dispatch, clear] = hook(key);
17
+ useEffect(() => {
18
+ if (isSuccess(state)) {
19
+ resolveRef.current?.(state.data);
20
+ clear();
21
+ }
22
+ else if (isError(state)) {
23
+ rejectRef.current?.(state.error);
24
+ clear();
25
+ }
26
+ }, [state]);
27
+ const promiseFn = useCallback((...args) => {
28
+ return new Promise((resolve, reject) => {
29
+ resolveRef.current = resolve;
30
+ rejectRef.current = reject;
31
+ let dispatchState = dispatch(...args);
32
+ if (isValidationError(dispatchState)) {
33
+ reject(dispatchState.error);
34
+ }
35
+ });
36
+ }, [dispatch]);
37
+ return [
38
+ promiseFn,
39
+ clear
40
+ ];
41
+ }
42
+ /**
43
+ * A custom hook that manages and returns the network state of a promise-based function,
44
+ * providing a way to execute the function and clear its state.
45
+ *
46
+ * @param fn The promise-based function whose network state is to be managed. It should be a function that returns a promise.
47
+ * @param key An optional identifier for the network state. Defaults to 'default'.
48
+ * @return A tuple containing the current network state, a function to execute the promise, and a function to clear the state.
49
+ */
50
+ export function useAsNetworkState(fn, key = 'default') {
51
+ let id = useId();
52
+ let context = useIntrigContext();
53
+ const networkState = useMemo(() => {
54
+ return context.state?.[`promiseState:${id}:${key}}`] ?? init();
55
+ }, [context.state?.[`promiseState:${id}:${key}}`]]);
56
+ const dispatch = useCallback((state) => {
57
+ context.dispatch({ key, operation: id, source: 'promiseState', state });
58
+ }, [key, context.dispatch]);
59
+ const execute = useCallback((...args) => {
60
+ dispatch(pending());
61
+ return fn(...args).then((data) => {
62
+ dispatch(success(data));
63
+ }, (e) => {
64
+ dispatch(error(e));
65
+ });
66
+ }, []);
67
+ const clear = useCallback(() => {
68
+ dispatch(init());
69
+ }, []);
70
+ return [
71
+ networkState,
72
+ execute,
73
+ clear
74
+ ];
75
+ }
76
+ //# sourceMappingURL=extra.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extra.js","sourceRoot":"","sources":["../../../../lib/client-next/src/extra.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EACL,IAAI,EACJ,OAAO,EACP,SAAS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EP,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;QAC7B,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAA;IAClB,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO;QACL,YAAY;QACZ,OAAO;QACP,KAAK;KACN,CAAA;AACH,CAAC"}
package/src/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './intrig-provider';
2
+ export * from './axios.server';
3
+ export * from './network-state';
4
+ export * from './extra';
package/src/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * from './intrig-provider';
2
+ export * from './axios.server';
3
+ export * from './network-state';
4
+ export * from './extra';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../lib/client-next/src/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC;AAClC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,SAAS,CAAA"}
@@ -0,0 +1,42 @@
1
+ import { NetworkAction, NetworkState } from '@intrig/next-client/network-state';
2
+ import { AxiosProgressEvent } from 'axios';
3
+ import { ZodSchema } from 'zod';
4
+ import { DefaultConfigs } from '@intrig/next-client/intrig-provider';
5
+ type GlobalState = Record<string, NetworkState>;
6
+ interface RequestType<T = any> {
7
+ method: 'get' | 'post' | 'put' | 'delete';
8
+ url: string;
9
+ headers?: Record<string, string>;
10
+ params?: Record<string, any>;
11
+ data?: any;
12
+ originalData?: T;
13
+ onUploadProgress?: (event: AxiosProgressEvent) => void;
14
+ onDownloadProgress?: (event: AxiosProgressEvent) => void;
15
+ signal?: AbortSignal;
16
+ key: string;
17
+ }
18
+ /**
19
+ * Defines the ContextType interface for managing global state, dispatching actions,
20
+ * and holding a collection of Axios instances.
21
+ *
22
+ * @interface ContextType
23
+ * @property {GlobalState} state - The global state of the application.
24
+ * @property {React.Dispatch<NetworkAction<unknown>>} dispatch - The dispatch function to send network actions.
25
+ * @property {Record<string, AxiosInstance>} axios - A record of Axios instances for making HTTP requests.
26
+ */
27
+ export interface ContextType {
28
+ state: GlobalState;
29
+ filteredState: GlobalState;
30
+ dispatch: React.Dispatch<NetworkAction<unknown>>;
31
+ configs: DefaultConfigs;
32
+ execute: <T>(request: RequestType, dispatch: (state: NetworkState<T>) => void, schema: ZodSchema<T> | undefined) => Promise<void>;
33
+ }
34
+ /**
35
+ * Context object created using `createContext` function. Provides a way to share state, dispatch functions,
36
+ * and axios instance across components without having to pass props down manually at every level.
37
+ *
38
+ * @type {ContextType}
39
+ */
40
+ declare let Context: import("react").Context<ContextType>;
41
+ export declare function useIntrigContext(): ContextType;
42
+ export { Context, GlobalState, RequestType, };
@@ -0,0 +1,20 @@
1
+ import { createContext, useContext } from 'react';
2
+ /**
3
+ * Context object created using `createContext` function. Provides a way to share state, dispatch functions,
4
+ * and axios instance across components without having to pass props down manually at every level.
5
+ *
6
+ * @type {ContextType}
7
+ */
8
+ let Context = createContext({
9
+ state: {},
10
+ filteredState: {},
11
+ dispatch() { },
12
+ configs: {},
13
+ async execute() {
14
+ }
15
+ });
16
+ export function useIntrigContext() {
17
+ return useContext(Context);
18
+ }
19
+ export { Context, };
20
+ //# sourceMappingURL=intrig-context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intrig-context.js","sourceRoot":"","sources":["../../../../lib/client-next/src/intrig-context.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AAmClD;;;;;GAKG;AACH,IAAI,OAAO,GAAG,aAAa,CAAc;IACvC,KAAK,EAAE,EAAE;IACT,aAAa,EAAE,EAAE;IACjB,QAAQ,KAAI,CAAC;IACb,OAAO,EAAE,EAAE;IACX,KAAK,CAAC,OAAO;IAEb,CAAC;CACF,CAAC,CAAC;AAEH,MAAM,UAAU,gBAAgB;IAC9B,OAAO,UAAU,CAAC,OAAO,CAAC,CAAC;AAC7B,CAAC;AAED,OAAO,EACL,OAAO,GAGR,CAAA"}
@@ -0,0 +1 @@
1
+ export declare function getAxiosInstance(key: string): import("axios").AxiosInstance;
@@ -0,0 +1,13 @@
1
+ import axios from 'axios';
2
+ // @ts-ignore
3
+ const insightHook = await import('intrig-hook');
4
+ export function getAxiosInstance(key) {
5
+ let axiosInstance = axios.create({
6
+ baseURL: process.env[`${key.toUpperCase()}_API_URL`],
7
+ });
8
+ if (insightHook) {
9
+ axiosInstance.interceptors.request.use(insightHook.requestInterceptor);
10
+ }
11
+ return axiosInstance;
12
+ }
13
+ //# sourceMappingURL=intrig-middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intrig-middleware.js","sourceRoot":"","sources":["../../../../lib/client-next/src/intrig-middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,aAAa;AACb,MAAM,WAAW,GAAG,MAAM,MAAM,CAAC,aAAa,CAAC,CAAC;AAGhD,MAAM,UAAU,gBAAgB,CAAC,GAAW;IAC1C,IAAI,aAAa,GAAG,KAAK,CAAC,MAAM,CAAC;QAC/B,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,WAAW,EAAE,UAAU,CAAC;KACrD,CAAC,CAAC;IAEH,IAAI,WAAW,EAAE,CAAC;QAChB,aAAa,CAAC,YAAY,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,kBAAkB,CAAC,CAAC;IACzE,CAAC;IAED,OAAO,aAAa,CAAC;AACvB,CAAC"}
@@ -0,0 +1,100 @@
1
+ import { PropsWithChildren } from 'react';
2
+ import { IntrigHook, NetworkState } from './network-state';
3
+ import { CreateAxiosDefaults } from 'axios';
4
+ import { ZodSchema } from 'zod';
5
+ import { RequestType } from './intrig-context';
6
+ export interface DefaultConfigs extends CreateAxiosDefaults {
7
+ debounceDelay?: number;
8
+ }
9
+ export interface IntrigProviderProps {
10
+ configs?: DefaultConfigs;
11
+ children: React.ReactNode;
12
+ }
13
+ /**
14
+ * IntrigProvider is a context provider component that sets up global state management
15
+ * and provides Axios instances for API requests.
16
+ *
17
+ * @param {Object} props - The properties object.
18
+ * @param {React.ReactNode} props.children - The child components to be wrapped by the provider.
19
+ * @param {Object} [props.configs={}] - Configuration object for Axios instances.
20
+ * @param {Object} [props.configs.defaults={}] - Default configuration for Axios.
21
+ * @param {Object} [props.configs.petstore={}] - Configuration specific to the petstore API.
22
+ * @return {JSX.Element} A context provider component that wraps the provided children.
23
+ */
24
+ export declare function IntrigProvider({ children, configs, }: IntrigProviderProps): import("react/jsx-runtime").JSX.Element;
25
+ export interface StubType<P, B, T> {
26
+ <P, B, T>(hook: IntrigHook<P, B, T>, fn: (params: P, body: B, dispatch: (state: NetworkState<T>) => void) => Promise<void>): void;
27
+ }
28
+ export type WithStubSupport<T> = T & {
29
+ stubs?: (stub: StubType<any, any, any>) => void;
30
+ };
31
+ export interface IntrigProviderStubProps {
32
+ configs?: DefaultConfigs;
33
+ stubs?: (stub: StubType<any, any, any>) => void;
34
+ children: React.ReactNode;
35
+ }
36
+ export declare function IntrigProviderStub({ children, configs, stubs }: IntrigProviderStubProps): import("react/jsx-runtime").JSX.Element;
37
+ export interface StatusTrapProps {
38
+ type: 'pending' | 'error' | 'pending + error';
39
+ propagate?: boolean;
40
+ }
41
+ /**
42
+ * StatusTrap component is used to track and manage network request states.
43
+ *
44
+ * @param {Object} props - The properties object.
45
+ * @param {React.ReactNode} props.children - The child elements to be rendered.
46
+ * @param {string} props.type - The type of network state to handle ("error", "pending", "pending + error").
47
+ * @param {boolean} [props.propagate=true] - Whether to propagate the event to the parent context.
48
+ * @return {React.ReactElement} The context provider component with filtered state and custom dispatch.
49
+ */
50
+ export declare function StatusTrap({ children, type, propagate, }: PropsWithChildren<StatusTrapProps>): import("react/jsx-runtime").JSX.Element;
51
+ export interface NetworkStateProps<T> {
52
+ key: string;
53
+ operation: string;
54
+ source: string;
55
+ schema?: ZodSchema<T>;
56
+ debounceDelay?: number;
57
+ }
58
+ /**
59
+ * useNetworkState is a custom hook that manages the network state within the specified context.
60
+ * It handles making network requests, dispatching appropriate states based on the request lifecycle,
61
+ * and allows aborting ongoing requests.
62
+ *
63
+ * @param {Object} params - The parameters required to configure and use the network state.
64
+ * @param {string} params.key - A unique identifier for the network request.
65
+ * @param {string} params.operation - The operation type related to the request.
66
+ * @param {string} params.source - The source or endpoint for the network request.
67
+ * @param {Object} params.schema - The schema used for validating the response data.
68
+ * @param {number} [params.debounceDelay] - The debounce delay for executing the network request.
69
+ *
70
+ * @return {[NetworkState<T>, (request: AxiosRequestConfig) => void, () => void]}
71
+ * Returns a state object representing the current network state,
72
+ * a function to execute the network request, and a function to clear the request.
73
+ */
74
+ export declare function useNetworkState<T>({ key, operation, source, schema, debounceDelay: requestDebounceDelay, }: NetworkStateProps<T>): [
75
+ NetworkState<T>,
76
+ (request: RequestType) => void,
77
+ clear: () => void,
78
+ (state: NetworkState<T>) => void
79
+ ];
80
+ /**
81
+ * Handles central error extraction from the provided context.
82
+ * It filters the state to retain error states and maps them to a structured error object with additional context information.
83
+ * @return {Object[]} An array of objects representing the error states with context information such as source, operation, and key.
84
+ */
85
+ export declare function useCentralErrorHandling(): {
86
+ source: string;
87
+ operation: string;
88
+ key: string;
89
+ state: "error";
90
+ error: any;
91
+ statusCode?: number;
92
+ request?: any;
93
+ }[];
94
+ /**
95
+ * Uses central pending state handling by aggregating pending states from context.
96
+ * It calculates the overall progress of pending states if any, or returns an initial state otherwise.
97
+ *
98
+ * @return {NetworkState} The aggregated network state based on the pending states and their progress.
99
+ */
100
+ export declare function useCentralPendingStateHandling(): NetworkState<unknown>;
@@ -0,0 +1,285 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useCallback, useContext, useMemo, useReducer, useState, } from 'react';
3
+ import { error, init, isError, isPending, pending, success } from './network-state';
4
+ import axios, { isAxiosError, } from 'axios';
5
+ import { Context } from './intrig-context';
6
+ /**
7
+ * Handles state updates for network requests based on the provided action.
8
+ *
9
+ * @param {GlobalState} state - The current state of the application.
10
+ * @param {NetworkAction<unknown>} action - The action containing source, operation, key, and state.
11
+ * @return {GlobalState} - The updated state after applying the action.
12
+ */
13
+ function requestReducer(state, action) {
14
+ return {
15
+ ...state,
16
+ [`${action.source}:${action.operation}:${action.key}`]: action.state,
17
+ };
18
+ }
19
+ /**
20
+ * IntrigProvider is a context provider component that sets up global state management
21
+ * and provides Axios instances for API requests.
22
+ *
23
+ * @param {Object} props - The properties object.
24
+ * @param {React.ReactNode} props.children - The child components to be wrapped by the provider.
25
+ * @param {Object} [props.configs={}] - Configuration object for Axios instances.
26
+ * @param {Object} [props.configs.defaults={}] - Default configuration for Axios.
27
+ * @param {Object} [props.configs.petstore={}] - Configuration specific to the petstore API.
28
+ * @return {JSX.Element} A context provider component that wraps the provided children.
29
+ */
30
+ export function IntrigProvider({ children, configs = {}, }) {
31
+ const [state, dispatch] = useReducer(requestReducer, {});
32
+ const axiosInstance = useMemo(() => {
33
+ return axios.create({
34
+ ...(configs ?? {}),
35
+ });
36
+ }, [configs]);
37
+ const contextValue = useMemo(() => {
38
+ async function execute(request, dispatch, schema) {
39
+ try {
40
+ dispatch(pending());
41
+ let response = await axiosInstance.request(request);
42
+ if (response.status >= 200 && response.status < 300) {
43
+ if (schema) {
44
+ let data = schema.safeParse(response.data);
45
+ if (!data.success) {
46
+ dispatch(error(data.error.issues, response.status, request));
47
+ return;
48
+ }
49
+ dispatch(success(data.data));
50
+ }
51
+ else {
52
+ dispatch(success(response.data));
53
+ }
54
+ }
55
+ else {
56
+ dispatch(error(response.data ?? response.statusText, response.status));
57
+ }
58
+ }
59
+ catch (e) {
60
+ if (isAxiosError(e)) {
61
+ dispatch(error(e.response?.data, e.response?.status, request));
62
+ }
63
+ else {
64
+ dispatch(error(e));
65
+ }
66
+ }
67
+ }
68
+ return {
69
+ state,
70
+ dispatch,
71
+ filteredState: state,
72
+ configs,
73
+ execute,
74
+ };
75
+ }, [state, axiosInstance]);
76
+ return _jsx(Context.Provider, { value: contextValue, children: children });
77
+ }
78
+ export function IntrigProviderStub({ children, configs = {}, stubs = () => { } }) {
79
+ const [state, dispatch] = useReducer(requestReducer, {});
80
+ const collectedStubs = useMemo(() => {
81
+ let fns = {};
82
+ function stub(hook, fn) {
83
+ fns[hook.key] = fn;
84
+ }
85
+ stubs(stub);
86
+ return fns;
87
+ }, [stubs]);
88
+ const contextValue = useMemo(() => {
89
+ async function execute(request, dispatch, schema) {
90
+ let stub = collectedStubs[request.key];
91
+ if (!!stub) {
92
+ try {
93
+ await stub(request.params, request.data, dispatch);
94
+ }
95
+ catch (e) {
96
+ dispatch(error(e));
97
+ }
98
+ }
99
+ else {
100
+ dispatch(init());
101
+ }
102
+ }
103
+ return {
104
+ state,
105
+ dispatch,
106
+ filteredState: state,
107
+ configs,
108
+ execute,
109
+ };
110
+ }, [state, dispatch, configs, collectedStubs]);
111
+ return _jsx(Context.Provider, { value: contextValue, children: children });
112
+ }
113
+ /**
114
+ * StatusTrap component is used to track and manage network request states.
115
+ *
116
+ * @param {Object} props - The properties object.
117
+ * @param {React.ReactNode} props.children - The child elements to be rendered.
118
+ * @param {string} props.type - The type of network state to handle ("error", "pending", "pending + error").
119
+ * @param {boolean} [props.propagate=true] - Whether to propagate the event to the parent context.
120
+ * @return {React.ReactElement} The context provider component with filtered state and custom dispatch.
121
+ */
122
+ export function StatusTrap({ children, type, propagate = true, }) {
123
+ const ctx = useContext(Context);
124
+ const [requests, setRequests] = useState([]);
125
+ const shouldHandleEvent = useCallback((state) => {
126
+ switch (type) {
127
+ case 'error':
128
+ return isError(state);
129
+ case 'pending':
130
+ return isPending(state);
131
+ case 'pending + error':
132
+ return isPending(state) || isError(state);
133
+ default:
134
+ return false;
135
+ }
136
+ }, [type]);
137
+ const dispatch = useCallback((event) => {
138
+ if (!event.handled) {
139
+ if (shouldHandleEvent(event.state)) {
140
+ setRequests((prev) => [...prev, event.key]);
141
+ if (!propagate) {
142
+ ctx.dispatch({
143
+ ...event,
144
+ handled: true,
145
+ });
146
+ return;
147
+ }
148
+ }
149
+ else {
150
+ setRequests((prev) => prev.filter((k) => k !== event.key));
151
+ }
152
+ }
153
+ ctx.dispatch(event);
154
+ }, [ctx, propagate, shouldHandleEvent]);
155
+ const filteredState = useMemo(() => {
156
+ return Object.fromEntries(Object.entries(ctx.state).filter(([key]) => requests.includes(key)));
157
+ }, [ctx.state, requests]);
158
+ return (_jsx(Context.Provider, { value: {
159
+ ...ctx,
160
+ dispatch,
161
+ filteredState,
162
+ }, children: children }));
163
+ }
164
+ /**
165
+ * useNetworkState is a custom hook that manages the network state within the specified context.
166
+ * It handles making network requests, dispatching appropriate states based on the request lifecycle,
167
+ * and allows aborting ongoing requests.
168
+ *
169
+ * @param {Object} params - The parameters required to configure and use the network state.
170
+ * @param {string} params.key - A unique identifier for the network request.
171
+ * @param {string} params.operation - The operation type related to the request.
172
+ * @param {string} params.source - The source or endpoint for the network request.
173
+ * @param {Object} params.schema - The schema used for validating the response data.
174
+ * @param {number} [params.debounceDelay] - The debounce delay for executing the network request.
175
+ *
176
+ * @return {[NetworkState<T>, (request: AxiosRequestConfig) => void, () => void]}
177
+ * Returns a state object representing the current network state,
178
+ * a function to execute the network request, and a function to clear the request.
179
+ */
180
+ export function useNetworkState({ key, operation, source, schema, debounceDelay: requestDebounceDelay, }) {
181
+ const context = useContext(Context);
182
+ const [abortController, setAbortController] = useState();
183
+ const networkState = useMemo(() => {
184
+ return (context.state?.[`${source}:${operation}:${key}`] ??
185
+ init());
186
+ }, [context.state?.[`${source}:${operation}:${key}`]]);
187
+ const dispatch = useCallback((state) => {
188
+ context.dispatch({ key, operation, source, state });
189
+ }, [key, operation, source, context.dispatch]);
190
+ const debounceDelay = useMemo(() => {
191
+ return requestDebounceDelay ?? context.configs?.debounceDelay ?? 0;
192
+ }, [context.configs, requestDebounceDelay]);
193
+ const execute = useCallback(async (request) => {
194
+ let abortController = new AbortController();
195
+ setAbortController(abortController);
196
+ let requestConfig = {
197
+ ...request,
198
+ onUploadProgress(event) {
199
+ dispatch(pending({
200
+ type: 'upload',
201
+ loaded: event.loaded,
202
+ total: event.total,
203
+ }));
204
+ request.onUploadProgress?.(event);
205
+ },
206
+ onDownloadProgress(event) {
207
+ dispatch(pending({
208
+ type: 'download',
209
+ loaded: event.loaded,
210
+ total: event.total,
211
+ }));
212
+ request.onDownloadProgress?.(event);
213
+ },
214
+ signal: abortController.signal,
215
+ };
216
+ await context.execute(requestConfig, dispatch, schema);
217
+ }, [networkState, context.dispatch, axios]);
218
+ const deboundedExecute = useMemo(() => debounce(execute, debounceDelay ?? 0), [execute]);
219
+ const clear = useCallback(() => {
220
+ dispatch(init());
221
+ setAbortController((abortController) => {
222
+ abortController?.abort();
223
+ return undefined;
224
+ });
225
+ }, [dispatch, abortController]);
226
+ return [networkState, deboundedExecute, clear, dispatch];
227
+ }
228
+ function debounce(func, delay) {
229
+ let timeoutId;
230
+ return (...args) => {
231
+ if (timeoutId) {
232
+ clearTimeout(timeoutId);
233
+ }
234
+ timeoutId = setTimeout(() => {
235
+ func(...args);
236
+ }, delay);
237
+ };
238
+ }
239
+ /**
240
+ * Handles central error extraction from the provided context.
241
+ * It filters the state to retain error states and maps them to a structured error object with additional context information.
242
+ * @return {Object[]} An array of objects representing the error states with context information such as source, operation, and key.
243
+ */
244
+ export function useCentralErrorHandling() {
245
+ const ctx = useContext(Context);
246
+ return useMemo(() => {
247
+ return Object.entries(ctx.filteredState)
248
+ .filter(([, state]) => isError(state))
249
+ .map(([k, state]) => {
250
+ let [source, operation, key] = k.split(':');
251
+ return {
252
+ ...state,
253
+ source,
254
+ operation,
255
+ key,
256
+ };
257
+ });
258
+ }, [ctx.filteredState]);
259
+ }
260
+ /**
261
+ * Uses central pending state handling by aggregating pending states from context.
262
+ * It calculates the overall progress of pending states if any, or returns an initial state otherwise.
263
+ *
264
+ * @return {NetworkState} The aggregated network state based on the pending states and their progress.
265
+ */
266
+ export function useCentralPendingStateHandling() {
267
+ const ctx = useContext(Context);
268
+ const result = useMemo(() => {
269
+ let pendingStates = Object.values(ctx.filteredState).filter(isPending);
270
+ if (!pendingStates.length) {
271
+ return init();
272
+ }
273
+ let progress = pendingStates
274
+ .filter((a) => a.progress)
275
+ .reduce((progress, current) => {
276
+ return {
277
+ total: progress.total + (current.progress?.total ?? 0),
278
+ loaded: progress.loaded + (current.progress?.loaded ?? 0),
279
+ };
280
+ }, { total: 0, loaded: 0 });
281
+ return pending(!!progress.total ? progress : undefined);
282
+ }, [ctx.filteredState]);
283
+ return result;
284
+ }
285
+ //# sourceMappingURL=intrig-provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intrig-provider.js","sourceRoot":"","sources":["../../../../lib/client-next/src/intrig-provider.tsx"],"names":[],"mappings":";AAAA,OAAO,EAGL,WAAW,EACX,UAAU,EACV,OAAO,EACP,UAAU,EACV,QAAQ,GACT,MAAM,OAAO,CAAC;AACf,OAAO,EACL,KAAK,EAGL,IAAI,EACJ,OAAO,EACP,SAAS,EAGT,OAAO,EAEP,OAAO,EACR,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,EAKZ,YAAY,GACb,MAAM,OAAO,CAAC;AAGf,OAAO,EAAC,OAAO,EAA2B,MAAM,kBAAkB,CAAC;AAEnE;;;;;;GAMG;AACH,SAAS,cAAc,CACrB,KAAkB,EAClB,MAA8B;IAE9B,OAAO;QACL,GAAG,KAAK;QACR,CAAC,GAAG,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,SAAS,IAAI,MAAM,CAAC,GAAG,EAAE,CAAC,EAAE,MAAM,CAAC,KAAK;KACrE,CAAC;AACJ,CAAC;AAWD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,cAAc,CAAC,EAC7B,QAAQ,EACR,OAAO,GAAG,EAAE,GACQ;IACpB,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,GAAG,UAAU,CAAC,cAAc,EAAE,EAAiB,CAAC,CAAC;IAExE,MAAM,aAAa,GAAU,OAAO,CAAC,GAAG,EA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C,MAAM,EAAE,CAAC;YAC1B,OAAO,IAAI,EAAE,CAAC;QAChB,CAAC;QAED,IAAI,QAAQ,GAAG,aAAa;aACzB,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC;aACzB,MAAM,CACL,CAAC,QAAQ,EAAE,OAAO,EAAE,EAAE;YACpB,OAAO;gBACL,KAAK,EAAE,QAAQ,CAAC,KAAK,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,KAAK,IAAI,CAAC,CAAC;gBACtD,MAAM,EAAE,QAAQ,CAAC,MAAM,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,MAAM,IAAI,CAAC,CAAC;aAC1D,CAAC;QACJ,CAAC,EACD,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAqB,CAC3C,CAAC;QACJ,OAAO,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;IAC1D,CAAC,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC;IAExB,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,3 @@
1
+ import { ZodSchema } from 'zod';
2
+ export declare function transform<T>(request: Request, mediaType: string, schema: ZodSchema): Promise<T>;
3
+ export declare function transformResponse<T>(data: any, mediaType: string, schema: ZodSchema): Promise<T>;
@@ -0,0 +1,60 @@
1
+ import { XMLParser } from 'fast-xml-parser';
2
+ const transformers = {};
3
+ export function transform(request, mediaType, schema) {
4
+ if (transformers[mediaType]) {
5
+ return transformers[mediaType](request, mediaType, schema);
6
+ }
7
+ throw new Error(`Unsupported media type: ` + mediaType);
8
+ }
9
+ transformers['application/json'] = async (request, mediaType, schema) => {
10
+ return schema.parse(await request.json());
11
+ };
12
+ transformers['multipart/form-data'] = async (request, mediaType, schema) => {
13
+ let formData = await request.formData();
14
+ let content = {};
15
+ formData.forEach((value, key) => (content[key] = value));
16
+ return schema.parse(content);
17
+ };
18
+ transformers['application/octet-stream'] = async (request, mediaType, schema) => {
19
+ return schema.parse(new Blob([await request.arrayBuffer()], {
20
+ type: 'application/octet-stream',
21
+ }));
22
+ };
23
+ transformers['application/x-www-form-urlencoded'] = async (request, mediaType, schema) => {
24
+ let formData = await request.formData();
25
+ let content = {};
26
+ formData.forEach((value, key) => (content[key] = value));
27
+ return schema.parse(content);
28
+ };
29
+ transformers['application/xml'] = async (request, mediaType, schema) => {
30
+ let xmlParser = new XMLParser();
31
+ let content = await xmlParser.parse(await request.text());
32
+ return schema.parse(await content);
33
+ };
34
+ transformers['text/plain'] = async (request, mediaType, schema) => {
35
+ return schema.parse(await request.text());
36
+ };
37
+ transformers['text/html'] = async (request, mediaType, schema) => {
38
+ return schema.parse(await request.text());
39
+ };
40
+ transformers['text/css'] = async (request, mediaType, schema) => {
41
+ return schema.parse(await request.text());
42
+ };
43
+ transformers['text/javascript'] = async (request, mediaType, schema) => {
44
+ return schema.parse(await request.text());
45
+ };
46
+ const responseTransformers = {};
47
+ responseTransformers['application/json'] = async (data, mediaType, schema) => {
48
+ return schema.parse(data);
49
+ };
50
+ responseTransformers['application/xml'] = async (data, mediaType, schema) => {
51
+ let parsed = new XMLParser().parse(data);
52
+ return schema.parse(parsed);
53
+ };
54
+ export async function transformResponse(data, mediaType, schema) {
55
+ if (responseTransformers[mediaType]) {
56
+ return await responseTransformers[mediaType](data, mediaType, schema);
57
+ }
58
+ return data;
59
+ }
60
+ //# sourceMappingURL=media-type-utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"media-type-utils.js","sourceRoot":"","sources":["../../../../lib/client-next/src/media-type-utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAU5C,MAAM,YAAY,GAAiB,EAAE,CAAC;AAEtC,MAAM,UAAU,SAAS,CACvB,OAAgB,EAChB,SAAiB,EACjB,MAAiB;IAEjB,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AC,MAAM,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;AAC5C,CAAC,CAAC;AAUF,MAAM,oBAAoB,GAAyB,EAAE,CAAC;AAEtD,oBAAoB,CAAC,kBAAkB,CAAC,GAAG,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,EAAE;IAC3E,OAAO,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAC5B,CAAC,CAAC;AAEF,oBAAoB,CAAC,iBAAiB,CAAC,GAAG,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,EAAE;IAC1E,IAAI,MAAM,GAAG,IAAI,SAAS,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACzC,OAAO,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AAC9B,CAAC,CAAA;AAED,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,IAAS,EACT,SAAiB,EACjB,MAAiB;IAEjB,IAAI,oBAAoB,CAAC,SAAS,CAAC,EAAE,CAAC;QACpC,OAAO,MAAM,oBAAoB,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;IACxE,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC"}
@@ -0,0 +1,223 @@
1
+ /**
2
+ * State of an asynchronous call. Network state follows the state diagram given below.
3
+ *
4
+ *
5
+ * <pre>
6
+ * ┌──────┐
7
+ * ┌─────────────► Init ◄────────────┐
8
+ * │ └▲────┬┘ │
9
+ * │ │ │ │
10
+ * │ Reset Execute │
11
+ * Reset │ │ Reset
12
+ * │ ┌──┴────┴──┐ │
13
+ * │ ┌────► Pending ◄────┐ │
14
+ * │ │ └──┬────┬──┘ │ │
15
+ * │ Execute │ │ Execute │
16
+ * │ │ │ │ │ │
17
+ * │ │ OnSuccess OnError │ │
18
+ * │ ┌────┴──┐ │ │ ┌──┴───┐ │
19
+ * └─┤Success◄────┘ └────►Error ├─┘
20
+ * └───────┘ └──────┘
21
+ *
22
+ * </pre>
23
+ */
24
+ export interface NetworkState<T = unknown> {
25
+ state: 'init' | 'pending' | 'success' | 'error';
26
+ }
27
+ /**
28
+ * Network call is not yet started
29
+ */
30
+ export interface InitState<T> extends NetworkState<T> {
31
+ state: 'init';
32
+ }
33
+ /**
34
+ * Checks whether the state is init state
35
+ * @param state
36
+ */
37
+ export declare function isInit<T>(state: NetworkState<T>): state is InitState<T>;
38
+ /**
39
+ * Initializes a new state.
40
+ *
41
+ * @template T The type of the state.
42
+ * @return {InitState<T>} An object representing the initial state.
43
+ */
44
+ export declare function init<T>(): InitState<T>;
45
+ /**
46
+ * Network call is not yet completed
47
+ */
48
+ export interface PendingState<T> extends NetworkState<T> {
49
+ state: 'pending';
50
+ progress?: Progress;
51
+ }
52
+ /**
53
+ * Interface representing progress information for an upload or download operation.
54
+ *
55
+ * @typedef {object} Progress
56
+ *
57
+ * @property {'upload' | 'download'} type - The type of the operation.
58
+ *
59
+ * @property {number} loaded - The amount of data that has been loaded so far.
60
+ *
61
+ * @property {number} [total] - The total amount of data to be loaded (if known).
62
+ */
63
+ export interface Progress {
64
+ type?: 'upload' | 'download';
65
+ loaded: number;
66
+ total?: number;
67
+ }
68
+ /**
69
+ * Checks whether the state is pending state
70
+ * @param state
71
+ */
72
+ export declare function isPending<T>(state: NetworkState<T>): state is PendingState<T>;
73
+ /**
74
+ * Generates a PendingState object with a state of "pending".
75
+ *
76
+ * @return {PendingState<T>} An object representing the pending state.
77
+ */
78
+ export declare function pending<T>(progress?: Progress | undefined): PendingState<T>;
79
+ /**
80
+ * Network call is completed with success state
81
+ */
82
+ export interface SuccessState<T> extends NetworkState<T> {
83
+ state: 'success';
84
+ data: T;
85
+ }
86
+ /**
87
+ * Checks whether the state is success response
88
+ * @param state
89
+ */
90
+ export declare function isSuccess<T>(state: NetworkState<T>): state is SuccessState<T>;
91
+ /**
92
+ * Creates a success state object with the provided data.
93
+ *
94
+ * @param {T} data - The data to be included in the success state.
95
+ * @return {SuccessState<T>} An object representing a success state containing the provided data.
96
+ */
97
+ export declare function success<T>(data: T): SuccessState<T>;
98
+ /**
99
+ * Network call is completed with error response
100
+ */
101
+ export interface ErrorState<T> extends NetworkState<T> {
102
+ state: 'error';
103
+ error: any;
104
+ statusCode?: number;
105
+ request?: any;
106
+ }
107
+ /**
108
+ * Checks whether the state is error state
109
+ * @param state
110
+ */
111
+ export declare function isError<T>(state: NetworkState<T>): state is ErrorState<T>;
112
+ /**
113
+ * Constructs an ErrorState object representing an error.
114
+ *
115
+ * @param {any} error - The error object or message.
116
+ * @param {string} [statusCode] - An optional status code associated with the error.
117
+ * @return {ErrorState<T>} An object representing the error state.
118
+ */
119
+ export declare function error<T>(error: any, statusCode?: number, request?: any): ErrorState<T>;
120
+ /**
121
+ * Represents an error state with additional contextual information.
122
+ *
123
+ * @typedef {Object} ErrorWithContext
124
+ * @template T
125
+ * @extends ErrorState<T>
126
+ *
127
+ * @property {string} source - The origin of the error.
128
+ * @property {string} operation - The operation being performed when the error occurred.
129
+ * @property {string} key - A unique key identifying the specific error instance.
130
+ */
131
+ export interface ErrorWithContext<T = unknown> extends ErrorState<T> {
132
+ source: string;
133
+ operation: string;
134
+ key: string;
135
+ }
136
+ /**
137
+ * Represents an action in the network context.
138
+ *
139
+ * @template T - The type of data associated with the network action
140
+ *
141
+ * @property {NetworkState<any>} state - The current state of the network action
142
+ * @property {string} key - The unique identifier for the network action
143
+ */
144
+ export interface NetworkAction<T> {
145
+ key: string;
146
+ source: string;
147
+ operation: string;
148
+ state: NetworkState<T>;
149
+ handled?: boolean;
150
+ }
151
+ type HookWithKey = {
152
+ key: string;
153
+ };
154
+ export type DeleteHook<P> = ((key?: string) => [NetworkState<never>, (params: P) => void, () => void]) & HookWithKey;
155
+ export type DeleteHookOp<P> = ((key?: string) => [NetworkState<never>, (params?: P) => void, () => void]) & HookWithKey;
156
+ export type GetHook<P, T> = ((key?: string) => [NetworkState<T>, (params: P) => void, () => void]) & HookWithKey;
157
+ export type GetHookOp<P, T> = ((key?: string) => [NetworkState<T>, (params?: P) => void, () => void]) & HookWithKey;
158
+ export type PostHook<P, T, B> = ((key?: string) => [NetworkState<T>, (body: B, params: P) => void, () => void]) & HookWithKey;
159
+ export type PostHookOp<P, T, B> = ((key?: string) => [NetworkState<T>, (body: B, params?: P) => void, () => void]) & HookWithKey;
160
+ export type PutHook<P, T, B> = ((key?: string) => [NetworkState<T>, (body: B, params: P) => void, () => void]) & HookWithKey;
161
+ export type PutHookOp<P, T, B> = ((key?: string) => [NetworkState<T>, (body: B, params?: P) => void, () => void]) & HookWithKey;
162
+ export type IntrigHook<P = undefined, B = undefined, T = any> = DeleteHook<P> | GetHook<P, T> | PostHook<P, T, B> | PutHook<P, T, B> | PostHookOp<P, T, B> | PutHookOp<P, T, B> | GetHookOp<P, T> | DeleteHookOp<P>;
163
+ /**
164
+ * Represents the dispatch state of a process.
165
+ *
166
+ * @template T The type of the state information.
167
+ * @interface
168
+ *
169
+ * @property {string} state The current state of the dispatch process.
170
+ */
171
+ export interface DispatchState<T> {
172
+ state: string;
173
+ }
174
+ /**
175
+ * Represents a successful dispatch state.
176
+ *
177
+ * @template T - Type of the data associated with the dispatch.
178
+ *
179
+ * @extends DispatchState<T>
180
+ *
181
+ * @property {string} state - The state of the dispatch, always 'success'.
182
+ */
183
+ export interface SuccessfulDispatch<T> extends DispatchState<T> {
184
+ state: 'success';
185
+ }
186
+ /**
187
+ * Indicates a successful dispatch state.
188
+ *
189
+ * @return {DispatchState<T>} An object representing a successful state.
190
+ */
191
+ export declare function successfulDispatch<T>(): DispatchState<T>;
192
+ /**
193
+ * Determines if the provided dispatch state represents a successful dispatch.
194
+ *
195
+ * @param {DispatchState<T>} value - The dispatch state to check.
196
+ * @return {value is SuccessfulDispatch<T>} - True if the dispatch state indicates success, false otherwise.
197
+ */
198
+ export declare function isSuccessfulDispatch<T>(value: DispatchState<T>): value is SuccessfulDispatch<T>;
199
+ /**
200
+ * ValidationError interface represents a specific type of dispatch state
201
+ * where a validation error has occurred.
202
+ *
203
+ * @typeparam T - The type of the data associated with this dispatch state.
204
+ */
205
+ export interface ValidationError<T> extends DispatchState<T> {
206
+ state: 'validation-error';
207
+ error: any;
208
+ }
209
+ /**
210
+ * Generates a ValidationError object.
211
+ *
212
+ * @param error The error details that caused the validation to fail.
213
+ * @return The ValidationError object containing the error state and details.
214
+ */
215
+ export declare function validationError<T>(error: any): ValidationError<T>;
216
+ /**
217
+ * Determines if a provided DispatchState object is a ValidationError.
218
+ *
219
+ * @param {DispatchState<T>} value - The DispatchState object to evaluate.
220
+ * @return {boolean} - Returns true if the provided DispatchState object is a ValidationError, otherwise returns false.
221
+ */
222
+ export declare function isValidationError<T>(value: DispatchState<T>): value is ValidationError<T>;
223
+ export {};
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Checks whether the state is init state
3
+ * @param state
4
+ */
5
+ export function isInit(state) {
6
+ return state.state === 'init';
7
+ }
8
+ /**
9
+ * Initializes a new state.
10
+ *
11
+ * @template T The type of the state.
12
+ * @return {InitState<T>} An object representing the initial state.
13
+ */
14
+ export function init() {
15
+ return {
16
+ state: 'init',
17
+ };
18
+ }
19
+ /**
20
+ * Checks whether the state is pending state
21
+ * @param state
22
+ */
23
+ export function isPending(state) {
24
+ return state.state === 'pending';
25
+ }
26
+ /**
27
+ * Generates a PendingState object with a state of "pending".
28
+ *
29
+ * @return {PendingState<T>} An object representing the pending state.
30
+ */
31
+ export function pending(progress = undefined) {
32
+ return {
33
+ state: 'pending',
34
+ progress,
35
+ };
36
+ }
37
+ /**
38
+ * Checks whether the state is success response
39
+ * @param state
40
+ */
41
+ export function isSuccess(state) {
42
+ return state.state === 'success';
43
+ }
44
+ /**
45
+ * Creates a success state object with the provided data.
46
+ *
47
+ * @param {T} data - The data to be included in the success state.
48
+ * @return {SuccessState<T>} An object representing a success state containing the provided data.
49
+ */
50
+ export function success(data) {
51
+ return {
52
+ state: 'success',
53
+ data,
54
+ };
55
+ }
56
+ /**
57
+ * Checks whether the state is error state
58
+ * @param state
59
+ */
60
+ export function isError(state) {
61
+ return state.state === 'error';
62
+ }
63
+ /**
64
+ * Constructs an ErrorState object representing an error.
65
+ *
66
+ * @param {any} error - The error object or message.
67
+ * @param {string} [statusCode] - An optional status code associated with the error.
68
+ * @return {ErrorState<T>} An object representing the error state.
69
+ */
70
+ export function error(error, statusCode, request) {
71
+ return {
72
+ state: 'error',
73
+ error,
74
+ statusCode,
75
+ request,
76
+ };
77
+ }
78
+ /**
79
+ * Indicates a successful dispatch state.
80
+ *
81
+ * @return {DispatchState<T>} An object representing a successful state.
82
+ */
83
+ export function successfulDispatch() {
84
+ return {
85
+ state: 'success'
86
+ };
87
+ }
88
+ /**
89
+ * Determines if the provided dispatch state represents a successful dispatch.
90
+ *
91
+ * @param {DispatchState<T>} value - The dispatch state to check.
92
+ * @return {value is SuccessfulDispatch<T>} - True if the dispatch state indicates success, false otherwise.
93
+ */
94
+ export function isSuccessfulDispatch(value) {
95
+ return value.state === 'success';
96
+ }
97
+ /**
98
+ * Generates a ValidationError object.
99
+ *
100
+ * @param error The error details that caused the validation to fail.
101
+ * @return The ValidationError object containing the error state and details.
102
+ */
103
+ export function validationError(error) {
104
+ return {
105
+ state: 'validation-error',
106
+ error
107
+ };
108
+ }
109
+ /**
110
+ * Determines if a provided DispatchState object is a ValidationError.
111
+ *
112
+ * @param {DispatchState<T>} value - The DispatchState object to evaluate.
113
+ * @return {boolean} - Returns true if the provided DispatchState object is a ValidationError, otherwise returns false.
114
+ */
115
+ export function isValidationError(value) {
116
+ return value.state === 'validation-error';
117
+ }
118
+ //# sourceMappingURL=network-state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"network-state.js","sourceRoot":"","sources":["../../../../lib/client-next/src/network-state.tsx"],"names":[],"mappings":"AAkCA;;;GAGG;AACH,MAAM,UAAU,MAAM,CAAI,KAAsB;IAC9C,OAAO,KAAK,CAAC,KAAK,KAAK,MAAM,CAAC;AAChC,CAAC;AAED;;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