@intrig/next 1.0.10 → 1.0.11

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intrig/next",
3
- "version": "1.0.10",
3
+ "version": "1.0.11",
4
4
  "private": false,
5
5
  "description": "Placeholder module for autogenerated intrig next.js boilerplate",
6
6
  "dependencies": {
@@ -12,8 +12,7 @@
12
12
  "date-fns": "^4.1.0",
13
13
  "loglevel": "1.8.1",
14
14
  "pino": "^9.6.0",
15
- "pino-pretty": "^13.0.0",
16
- "qs": "^6.13.0"
15
+ "pino-pretty": "^13.0.0"
17
16
  },
18
17
  "peerDependencies": {
19
18
  "react": "18.3.1",
@@ -13,10 +13,10 @@ import { useIntrigContext } from '@intrig/next/intrig-context';
13
13
  * 2. A function to execute the provided asynchronous operation.
14
14
  * 3. A function to reset the network state back to the initial state.
15
15
  */
16
- export function useAsNetworkState<T, F extends ((...args: any) => Promise<T>)>(fn: F, key = 'default'): [NetworkState<T>, (...params: Parameters<F>) => void, () => void] {
17
- const id = useId();
16
+ export function useAsNetworkState<T, F extends ((...args: any) => Promise<T>)>(fn: F, key: string = 'default'): [NetworkState<T>, (...params: Parameters<F>) => void, () => void] {
17
+ let id = useId();
18
18
 
19
- const context = useIntrigContext();
19
+ let context = useIntrigContext();
20
20
 
21
21
  const networkState = useMemo(() => {
22
22
  return context.state?.[`promiseState:${id}:${key}}`] ?? init()
@@ -82,7 +82,7 @@ export function useAsPromise<P, B, T, E>(
82
82
  const resolveRef = useRef<(value: T) => void>();
83
83
  const rejectRef = useRef<(reason?: any) => void>();
84
84
 
85
- const [state, dispatch, clear] = hook(options as any); // Casting to `any` to match all overloads
85
+ let [state, dispatch, clear] = hook(options as any); // Casting to `any` to match all overloads
86
86
 
87
87
  useEffect(() => {
88
88
  if (isSuccess(state)) {
@@ -99,7 +99,7 @@ export function useAsPromise<P, B, T, E>(
99
99
  resolveRef.current = resolve;
100
100
  rejectRef.current = reject;
101
101
 
102
- const dispatchState = (dispatch as any)(...args);
102
+ let dispatchState = (dispatch as any)(...args);
103
103
  if (isValidationError(dispatchState)) {
104
104
  reject(dispatchState.error);
105
105
  }
@@ -2,7 +2,7 @@ import { useIntrigContext } from '@intrig/next/intrig-context';
2
2
  import { useCallback, useMemo } from 'react';
3
3
  import { error, init, isInit, isSuccess, NetworkState, success } from '@intrig/next/network-state';
4
4
 
5
- export interface LocalReducerOptions<T> {
5
+ export interface LocalReducerOptions<T, E> {
6
6
  initState?: T;
7
7
  key?: string;
8
8
  }
@@ -11,8 +11,8 @@ function isPromise<T>(item: any): item is Promise<T> {
11
11
  return !!item && typeof item.then === 'function' && typeof item.catch === 'function';
12
12
  }
13
13
 
14
- export function useLocalReducer<T, E, F extends (event: E, curState?: T) => T | Promise<T>>(fn: F, options: LocalReducerOptions<T>) {
15
- const context = useIntrigContext();
14
+ export function useLocalReducer<T, E, F extends (event: E, curState?: T) => T | Promise<T>>(fn: F, options: LocalReducerOptions<T, E>) {
15
+ let context = useIntrigContext();
16
16
 
17
17
  const key = useMemo(() => {
18
18
  return options.key ?? 'default';
@@ -32,7 +32,7 @@ export function useLocalReducer<T, E, F extends (event: E, curState?: T) => T |
32
32
  const execute = useCallback((event: E) => {
33
33
  try {
34
34
  if (isSuccess(networkState)) {
35
- const data = fn(event, networkState.data);
35
+ let data = fn(event, networkState.data);
36
36
  if (isPromise(data)) {
37
37
  dispatch(init());
38
38
  data.then(data => dispatch(success(data)));
@@ -40,7 +40,7 @@ export function useLocalReducer<T, E, F extends (event: E, curState?: T) => T |
40
40
  dispatch(success(data));
41
41
  }
42
42
  } else if (isInit(networkState)) {
43
- const data1 = fn(event, options.initState);
43
+ let data1 = fn(event, options.initState);
44
44
  if (isPromise(data1)) {
45
45
  dispatch(init());
46
46
  data1.then(data => dispatch(success(data)));
@@ -73,7 +73,7 @@ export function useResolvedCachedValue<P, B, T, E>(hook: BinaryFunctionHook<P, B
73
73
  export function useResolvedCachedValue<P, B, T, E>(hook: IntrigHook<P, B, T, E>, options: IntrigHookOptions<P, B>): T | undefined {
74
74
  const [cachedValue, setCachedValue] = useState<T | undefined>();
75
75
 
76
- const [state] = hook(options as any); // Ensure compatibility with different hook types
76
+ let [state] = hook(options as any); // Ensure compatibility with different hook types
77
77
 
78
78
  useEffect(() => {
79
79
  if (isSuccess(state)) {
@@ -68,7 +68,7 @@ export function useResolvedValue<P, B, T, E>(hook: BinaryFunctionHook<P, B, T, E
68
68
  export function useResolvedValue<P, B, T, E>(hook: IntrigHook<P, B, T, E>, options: IntrigHookOptions<P, B>): T | undefined {
69
69
  const [value, setValue] = useState<T | undefined>();
70
70
 
71
- const [state] = hook(options as any); // Ensure compatibility with different hook types
71
+ let [state] = hook(options as any); // Ensure compatibility with different hook types
72
72
 
73
73
  useEffect(() => {
74
74
  if (isSuccess(state)) {
package/src/extra.ts CHANGED
@@ -15,7 +15,7 @@ import {
15
15
  UnitHook,
16
16
  UnitHookOptions
17
17
  } from '@intrig/next/network-state';
18
- import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
18
+ import { useCallback, useEffect, useId, useMemo, useReducer, useRef, useState } from 'react';
19
19
  import { useIntrigContext } from '@intrig/next/intrig-context';
20
20
 
21
21
  /**
@@ -42,7 +42,7 @@ export function useAsPromise<P, B, T, E>(
42
42
  const resolveRef = useRef<(value: T) => void>();
43
43
  const rejectRef = useRef<(reason?: any) => void>();
44
44
 
45
- const [state, dispatch, clear] = hook(options as any); // Casting to `any` to match all overloads
45
+ let [state, dispatch, clear] = hook(options as any); // Casting to `any` to match all overloads
46
46
 
47
47
  useEffect(() => {
48
48
  if (isSuccess(state)) {
@@ -59,7 +59,7 @@ export function useAsPromise<P, B, T, E>(
59
59
  resolveRef.current = resolve;
60
60
  rejectRef.current = reject;
61
61
 
62
- const dispatchState = (dispatch as any)(...args);
62
+ let dispatchState = (dispatch as any)(...args);
63
63
  if (isValidationError(dispatchState)) {
64
64
  reject(dispatchState.error);
65
65
  }
@@ -77,10 +77,10 @@ export function useAsPromise<P, B, T, E>(
77
77
  * @param key An optional identifier for the network state. Defaults to 'default'.
78
78
  * @return A tuple containing the current network state, a function to execute the promise, and a function to clear the state.
79
79
  */
80
- export function useAsNetworkState<T, F extends ((...args: any) => Promise<T>)>(fn: F, key = 'default'): [NetworkState<T>, (...params: Parameters<F>) => void, () => void] {
81
- const id = useId();
80
+ export function useAsNetworkState<T, F extends ((...args: any) => Promise<T>)>(fn: F, key: string = 'default'): [NetworkState<T>, (...params: Parameters<F>) => void, () => void] {
81
+ let id = useId();
82
82
 
83
- const context = useIntrigContext();
83
+ let context = useIntrigContext();
84
84
 
85
85
  const networkState = useMemo(() => {
86
86
  return context.state?.[`promiseState:${id}:${key}}`] ?? init()
@@ -139,7 +139,7 @@ export function useResolvedValue<P, B, T, E>(hook: BinaryFunctionHook<P, B, T, E
139
139
  export function useResolvedValue<P, B, T, E>(hook: IntrigHook<P, B, T, E>, options: IntrigHookOptions<P, B>): T | undefined {
140
140
  const [value, setValue] = useState<T | undefined>();
141
141
 
142
- const [state] = hook(options as any); // Ensure compatibility with different hook types
142
+ let [state] = hook(options as any); // Ensure compatibility with different hook types
143
143
 
144
144
  useEffect(() => {
145
145
  if (isSuccess(state)) {
@@ -177,14 +177,14 @@ export function useResolvedCachedValue<P, B, T, E>(hook: BinaryFunctionHook<P, B
177
177
  export function useResolvedCachedValue<P, B, T, E>(hook: IntrigHook<P, B, T, E>, options: IntrigHookOptions<P, B>): T | undefined {
178
178
  const [cachedValue, setCachedValue] = useState<T | undefined>();
179
179
 
180
- const [state] = hook(options as any); // Ensure compatibility with different hook types
180
+ let [state] = hook(options as any); // Ensure compatibility with different hook types
181
181
 
182
182
  useEffect(() => {
183
183
  if (isSuccess(state)) {
184
184
  setCachedValue(state.data);
185
185
  }
186
186
  // Do not clear cached value if state is unsuccessful
187
- }, [state]);
187
+ }, [state]);
188
188
 
189
189
  return cachedValue;
190
190
  }
@@ -43,15 +43,13 @@ export interface ContextType {
43
43
  *
44
44
  * @type {ContextType}
45
45
  */
46
- const Context = createContext<ContextType>({
46
+ let Context = createContext<ContextType>({
47
47
  state: {},
48
48
  filteredState: {},
49
- dispatch() {
50
- //noop
51
- },
49
+ dispatch() {},
52
50
  configs: {},
53
51
  async execute() {
54
- //noop
52
+
55
53
  }
56
54
  });
57
55
 
@@ -5,9 +5,9 @@ import { DefaultConfigs, IntrigProvider } from './intrig-provider';
5
5
 
6
6
  export default async function IntrigLayout({children, configs}: { children: React.ReactNode, configs?: DefaultConfigs}) {
7
7
 
8
- const headersData = await headers();
9
- const hydratedResponsesStr = headersData.get('INTRIG_HYDRATED');
10
- const hydratedResponses = hydratedResponsesStr ? JSON.parse(hydratedResponsesStr) : {}
8
+ let headersData = await headers();
9
+ let hydratedResponsesStr = headersData.get('INTRIG_HYDRATED');
10
+ let hydratedResponses = hydratedResponsesStr ? JSON.parse(hydratedResponsesStr) : {}
11
11
  headersData.delete('INTRIG_HYDRATED');
12
12
 
13
13
  return <>
@@ -0,0 +1,9 @@
1
+ import { extractPathVariables } from './intrig-middleware';
2
+
3
+ describe('intrig-middleware', () => {
4
+ it('should extract params', () => {
5
+ let variables = extractPathVariables('/api/v1/database/{dbId}/table/{tableId}', '/api/v1/database/dap/table/users');
6
+
7
+ console.log(variables);
8
+ })
9
+ })
@@ -1,8 +1,8 @@
1
1
  "use server"
2
2
 
3
3
  import axios from 'axios';
4
- //@ts-expect-error: 'intrig-hook' is a dynamic module and may not be statically analyzable
5
- const insightHook = await import('intrig-hook');
4
+ //@ts-ignore
5
+ let insightHook = await import('intrig-hook');
6
6
  import {headers as requestHeaders} from 'next/headers'
7
7
 
8
8
  export async function getAxiosInstance(key: string) {
@@ -23,9 +23,9 @@ export async function getAxiosInstance(key: string) {
23
23
  }
24
24
 
25
25
  export async function addResponseToHydrate(key: string, responseData: any) {
26
- const _headers = await requestHeaders();
27
- const intrigHydrated = _headers.get('INTRIG_HYDRATED');
28
- const ob = intrigHydrated ? JSON.parse(intrigHydrated) : {};
26
+ let _headers = await requestHeaders();
27
+ let intrigHydrated = _headers.get('INTRIG_HYDRATED');
28
+ let ob = intrigHydrated ? JSON.parse(intrigHydrated) : {};
29
29
  ob[key] = responseData;
30
30
  _headers.set('INTRIG_HYDRATED', JSON.stringify(ob));
31
31
  }
@@ -88,11 +88,11 @@ export function IntrigProvider({
88
88
  async function execute<T, E = unknown>(request: RequestType, dispatch: (state: NetworkState<T, E>) => void, schema: ZodSchema<T> | undefined, errorSchema: ZodSchema<E> | undefined) {
89
89
  try {
90
90
  dispatch(pending());
91
- const response = await axiosInstance.request(request);
91
+ let response = await axiosInstance.request(request);
92
92
 
93
93
  if (response.status >= 200 && response.status < 300) {
94
94
  if (schema) {
95
- const data = schema.safeParse(response.data);
95
+ let data = schema.safeParse(response.data);
96
96
  if (!data.success) {
97
97
  dispatch(
98
98
  error(data.error.issues, response.status, request)
@@ -104,7 +104,7 @@ export function IntrigProvider({
104
104
  dispatch(success(response.data));
105
105
  }
106
106
  } else {
107
- const { data } = errorSchema?.safeParse(response.data ?? {}) ?? {};
107
+ let { data, error: validationError } = errorSchema?.safeParse(response.data ?? {}) ?? {};
108
108
  //todo: handle error validation error.
109
109
  dispatch(
110
110
  error(data ?? response.data ?? response.statusText, response.status)
@@ -112,7 +112,7 @@ export function IntrigProvider({
112
112
  }
113
113
  } catch (e: any) {
114
114
  if (isAxiosError(e)) {
115
- const { data } = errorSchema?.safeParse(e.response?.data ?? {}) ?? {};
115
+ let { data, error: validationError } = errorSchema?.safeParse(e.response?.data ?? {}) ?? {};
116
116
  dispatch(error(data ?? e.response?.data, e.response?.status, request));
117
117
  } else {
118
118
  dispatch(error(e));
@@ -132,17 +132,17 @@ export function IntrigProvider({
132
132
  return <Context.Provider value={contextValue}>{children}</Context.Provider>;
133
133
  }
134
134
 
135
- export interface StubType {
135
+ export interface StubType<P, B, T> {
136
136
  <P, B, T>(hook: IntrigHook<P, B, T>, fn: (params: P, body: B, dispatch: (state: NetworkState<T>) => void) => Promise<void>): void
137
137
  }
138
138
 
139
139
  export type WithStubSupport<T> = T & {
140
- stubs?: (stub: StubType) => void;
140
+ stubs?: (stub: StubType<any, any, any>) => void;
141
141
  }
142
142
 
143
143
  export interface IntrigProviderStubProps {
144
144
  configs?: DefaultConfigs;
145
- stubs?: (stub: StubType) => void;
145
+ stubs?: (stub: StubType<any, any, any>) => void;
146
146
  children: React.ReactNode;
147
147
  }
148
148
 
@@ -150,7 +150,7 @@ export function IntrigProviderStub({ children, configs = {}, stubs = () => {} }:
150
150
  const [state, dispatch] = useReducer(requestReducer, {} as GlobalState);
151
151
 
152
152
  const collectedStubs = useMemo(() => {
153
- const fns: Record<string, (params: any, body: any, dispatch: (state: NetworkState<any>) => void) => Promise<void>> = {};
153
+ let fns: Record<string, (params: any, body: any, dispatch: (state: NetworkState<any>) => void) => Promise<void>> = {};
154
154
  function stub<P, B, T>(hook: IntrigHook<P, B, T>, fn: (params: P, body: B, dispatch: (state: NetworkState<T>) => void) => Promise<void>) {
155
155
  fns[hook.key] = fn;
156
156
  }
@@ -161,9 +161,9 @@ export function IntrigProviderStub({ children, configs = {}, stubs = () => {} }:
161
161
  const contextValue = useMemo(() => {
162
162
 
163
163
  async function execute<T>(request: RequestType, dispatch: (state: NetworkState<T>) => void, schema: ZodSchema<T> | undefined) {
164
- const stub = collectedStubs[request.key];
164
+ let stub = collectedStubs[request.key];
165
165
 
166
- if (stub) {
166
+ if (!!stub) {
167
167
  try {
168
168
  await stub(request.params, request.data, dispatch);
169
169
  } catch (e) {
@@ -334,10 +334,10 @@ export function useNetworkState<T, E = unknown>({
334
334
  logger.info(`Executing request ${key} ${operation} ${source}`);
335
335
  logger.debug(`⇨`, request)
336
336
 
337
- const abortController = new AbortController();
337
+ let abortController = new AbortController();
338
338
  setAbortController(abortController);
339
339
 
340
- const requestConfig: RequestType = {
340
+ let requestConfig: RequestType = {
341
341
  ...request,
342
342
  onUploadProgress(event: AxiosProgressEvent) {
343
343
  dispatch(
@@ -410,7 +410,7 @@ export function useCentralError() {
410
410
  return Object.entries(ctx.filteredState)
411
411
  .filter(([, state]) => isError(state))
412
412
  .map(([k, state]) => {
413
- const [source, operation, key] = k.split(':');
413
+ let [source, operation, key] = k.split(':');
414
414
  return {
415
415
  ...(state as ErrorState<unknown>),
416
416
  source,
@@ -431,12 +431,12 @@ export function useCentralPendingState() {
431
431
  const ctx = useContext(Context);
432
432
 
433
433
  const result: NetworkState = useMemo(() => {
434
- const pendingStates = Object.values(ctx.filteredState).filter(isPending);
434
+ let pendingStates = Object.values(ctx.filteredState).filter(isPending);
435
435
  if (!pendingStates.length) {
436
436
  return init();
437
437
  }
438
438
 
439
- const progress = pendingStates
439
+ let progress = pendingStates
440
440
  .filter((a) => a.progress)
441
441
  .reduce(
442
442
  (progress, current) => {
@@ -447,7 +447,7 @@ export function useCentralPendingState() {
447
447
  },
448
448
  { total: 0, loaded: 0 } satisfies Progress
449
449
  );
450
- return pending(progress.total ? progress : undefined);
450
+ return pending(!!progress.total ? progress : undefined);
451
451
  }, [ctx.filteredState]);
452
452
 
453
453
  return result;
package/src/logger.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import log from 'loglevel';
2
2
 
3
3
  // Set the default logging level (can be overridden via environment variables)
4
- log.setLevel(process.env.LOG_LEVEL as log.LogLevelDesc || 'error');
4
+ log.setLevel(process.env.LOG_LEVEL as log.LogLevelDesc || 'info');
5
5
 
6
6
  const logWrapper = {
7
7
  info: (msg: string, meta?: object) => meta ? log.info(msg, meta) : log.info(msg),
@@ -16,7 +16,7 @@ export function encode<T>(request: T, mediaType: string, schema: ZodSchema) {
16
16
  return request;
17
17
  }
18
18
 
19
- encoders['application/json'] = async (request) => {
19
+ encoders['application/json'] = async (request, mediaType, schema) => {
20
20
  return request;
21
21
  }
22
22
 
@@ -29,7 +29,7 @@ function appendFormData(
29
29
  formData.append(parentKey, data);
30
30
  } else if (data !== null && typeof data === 'object') {
31
31
  if (Array.isArray(data)) {
32
- data.forEach((item: any) => {
32
+ data.forEach((item: any, index: number) => {
33
33
  const key = `${parentKey}`;
34
34
  appendFormData(formData, item, key);
35
35
  });
@@ -45,22 +45,22 @@ function appendFormData(
45
45
  }
46
46
 
47
47
 
48
- encoders['multipart/form-data'] = async (request) => {
49
- const _request = request as Record<string, any>;
50
- const formData = new FormData();
48
+ encoders['multipart/form-data'] = async (request, mediaType, schema) => {
49
+ let _request = request as Record<string, any>;
50
+ let formData = new FormData();
51
51
  Object.keys(_request).forEach((key: string) => {
52
52
  appendFormData(formData, _request[key], key);
53
53
  });
54
54
  return formData;
55
55
  }
56
56
 
57
- encoders['application/octet-stream'] = async (request) => {
57
+ encoders['application/octet-stream'] = async (request, mediaType, schema) => {
58
58
  return request;
59
59
  }
60
60
 
61
- encoders['application/x-www-form-urlencoded'] = async (request) => {
62
- const formData = new FormData();
63
- for (const key in request) {
61
+ encoders['application/x-www-form-urlencoded'] = async (request, mediaType, schema) => {
62
+ let formData = new FormData();
63
+ for (let key in request) {
64
64
  const value = request[key];
65
65
  formData.append(key, value instanceof Blob || typeof value === 'string' ? value : String(value));
66
66
  }
@@ -93,8 +93,8 @@ transformers['application/json'] = async (request, mediaType, schema) => {
93
93
  };
94
94
 
95
95
  transformers['multipart/form-data'] = async (request, mediaType, schema) => {
96
- const formData = await request.formData();
97
- const content: Record<string, any> = {};
96
+ let formData = await request.formData();
97
+ let content: Record<string, any> = {};
98
98
  formData.forEach((value, key) => {
99
99
  if (content[key]) {
100
100
  if (!(content[key] instanceof Array)) {
@@ -125,15 +125,15 @@ transformers['application/x-www-form-urlencoded'] = async (
125
125
  mediaType,
126
126
  schema
127
127
  ) => {
128
- const formData = await request.formData();
129
- const content: Record<string, any> = {};
128
+ let formData = await request.formData();
129
+ let content: Record<string, any> = {};
130
130
  formData.forEach((value, key) => (content[key] = value));
131
131
  return schema.parse(content);
132
132
  };
133
133
 
134
134
  transformers['application/xml'] = async (request, mediaType, schema) => {
135
- const xmlParser = new XMLParser();
136
- const content = await xmlParser.parse(await request.text());
135
+ let xmlParser = new XMLParser();
136
+ let content = await xmlParser.parse(await request.text());
137
137
  return schema.parse(await content);
138
138
  };
139
139
 
@@ -168,7 +168,7 @@ responseTransformers['application/json'] = async (data, mediaType, schema) => {
168
168
  };
169
169
 
170
170
  responseTransformers['application/xml'] = async (data, mediaType, schema) => {
171
- const parsed = new XMLParser().parse(data);
171
+ let parsed = new XMLParser().parse(data);
172
172
  return schema.parse(parsed);
173
173
  }
174
174