enlace 0.0.0-alpha.4 → 0.0.1-beta.10

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.
@@ -0,0 +1,173 @@
1
+ import { EnlaceCallbackPayload, EnlaceErrorCallbackPayload, EnlaceResponse, WildcardClient, EnlaceClient, EnlaceOptions, EnlaceCallbacks } from 'enlace-core';
2
+
3
+ /** Per-request options for React hooks */
4
+ type ReactRequestOptionsBase = {
5
+ /**
6
+ * Cache tags for caching (GET requests only)
7
+ * This will auto generate tags from the URL path if not provided and autoGenerateTags is enabled.
8
+ * But can be manually specified to override auto-generation.
9
+ * */
10
+ tags?: string[];
11
+ /** Tags to invalidate after mutation (triggers refetch in matching queries) */
12
+ revalidateTags?: string[];
13
+ /**
14
+ * Path parameters for dynamic URL segments.
15
+ * Used to replace :paramName placeholders in the URL path.
16
+ * @example
17
+ * // With path api.products[':id'].delete
18
+ * trigger({ pathParams: { id: '123' } }) // → DELETE /products/123
19
+ */
20
+ pathParams?: Record<string, string | number>;
21
+ };
22
+ /** Options for query mode hooks */
23
+ type UseEnlaceQueryOptions = {
24
+ /**
25
+ * Whether the query should execute.
26
+ * Set to false to skip fetching (useful when ID is "new" or undefined).
27
+ * @default true
28
+ */
29
+ enabled?: boolean;
30
+ };
31
+ type ApiClient<TSchema, TDefaultError = unknown, TOptions = ReactRequestOptionsBase> = unknown extends TSchema ? WildcardClient<TOptions> : EnlaceClient<TSchema, TDefaultError, TOptions>;
32
+ type QueryFn<TSchema, TData, TError, TDefaultError = unknown, TOptions = ReactRequestOptionsBase> = (api: ApiClient<TSchema, TDefaultError, TOptions>) => Promise<EnlaceResponse<TData, TError>>;
33
+ type SelectorFn<TSchema, TMethod, TDefaultError = unknown, TOptions = ReactRequestOptionsBase> = (api: ApiClient<TSchema, TDefaultError, TOptions>) => TMethod;
34
+ type HookState = {
35
+ loading: boolean;
36
+ fetching: boolean;
37
+ data: unknown;
38
+ error: unknown;
39
+ };
40
+ type TrackedCall = {
41
+ path: string[];
42
+ method: string;
43
+ options: unknown;
44
+ };
45
+ declare const HTTP_METHODS: readonly ["get", "post", "put", "patch", "delete"];
46
+ type ExtractData<T> = T extends (...args: any[]) => Promise<EnlaceResponse<infer D, unknown>> ? D : never;
47
+ type ExtractError<T> = T extends (...args: any[]) => Promise<EnlaceResponse<unknown, infer E>> ? E : never;
48
+ /** Discriminated union for hook response state - enables type narrowing via error check */
49
+ type HookResponseState<TData, TError> = {
50
+ data: TData;
51
+ error?: undefined;
52
+ } | {
53
+ data?: undefined;
54
+ error: TError;
55
+ };
56
+ /** Result when hook is called with query function (auto-fetch mode) */
57
+ type UseEnlaceQueryResult<TData, TError> = {
58
+ loading: boolean;
59
+ fetching: boolean;
60
+ } & HookResponseState<TData, TError>;
61
+ /** Result when hook is called with method selector (trigger mode) */
62
+ type UseEnlaceSelectorResult<TMethod> = {
63
+ trigger: TMethod;
64
+ loading: boolean;
65
+ fetching: boolean;
66
+ } & HookResponseState<ExtractData<TMethod>, ExtractError<TMethod>>;
67
+ /** Options for createEnlaceHookReact factory */
68
+ type EnlaceHookOptions = {
69
+ /**
70
+ * Auto-generate cache tags from URL path for GET requests.
71
+ * e.g., `/posts/1` generates tags `['posts', 'posts/1']`
72
+ * @default true
73
+ */
74
+ autoGenerateTags?: boolean;
75
+ /** Auto-revalidate generated tags after successful mutations. @default true */
76
+ autoRevalidateTags?: boolean;
77
+ /** Time in ms before cached data is considered stale. @default 0 (always stale) */
78
+ staleTime?: number;
79
+ /** Callback called on successful API responses */
80
+ onSuccess?: (payload: EnlaceCallbackPayload<unknown>) => void;
81
+ /** Callback called on error responses (HTTP errors or network failures) */
82
+ onError?: (payload: EnlaceErrorCallbackPayload<unknown>) => void;
83
+ };
84
+ /** Hook type returned by createEnlaceHookReact */
85
+ type EnlaceHook<TSchema, TDefaultError = unknown> = {
86
+ <TMethod extends (...args: any[]) => Promise<EnlaceResponse<unknown, unknown>>>(selector: SelectorFn<TSchema, TMethod, TDefaultError>): UseEnlaceSelectorResult<TMethod>;
87
+ <TData, TError>(queryFn: QueryFn<TSchema, TData, TError, TDefaultError>, options?: UseEnlaceQueryOptions): UseEnlaceQueryResult<TData, TError>;
88
+ };
89
+
90
+ /**
91
+ * Creates a React hook for making API calls.
92
+ * Called at module level to create a reusable hook.
93
+ *
94
+ * @example
95
+ * const useAPI = createEnlaceHookReact<ApiSchema>('https://api.com');
96
+ *
97
+ * // Query mode - auto-fetch (auto-tracks changes, no deps array needed)
98
+ * const { loading, data, error } = useAPI((api) => api.posts.get({ query: { userId } }));
99
+ *
100
+ * // Selector mode - typed trigger for lazy calls
101
+ * const { trigger, loading, data, error } = useAPI((api) => api.posts.delete);
102
+ * onClick={() => trigger({ body: { id: 1 } })}
103
+ */
104
+ declare function createEnlaceHookReact<TSchema = unknown, TDefaultError = unknown>(baseUrl: string, defaultOptions?: EnlaceOptions, hookOptions?: EnlaceHookOptions): EnlaceHook<TSchema, TDefaultError>;
105
+
106
+ /**
107
+ * Handler function called after successful mutations to trigger server-side revalidation.
108
+ * @param tags - Cache tags to revalidate
109
+ * @param paths - URL paths to revalidate
110
+ */
111
+ type RevalidateHandler = (tags: string[], paths: string[]) => void | Promise<void>;
112
+ /** Next.js-specific options (third argument for createEnlaceNext) */
113
+ type NextOptions = Pick<EnlaceHookOptions, "autoGenerateTags" | "autoRevalidateTags"> & EnlaceCallbacks & {
114
+ /**
115
+ * Handler called after successful mutations to trigger server-side revalidation.
116
+ * Receives auto-generated or manually specified tags and paths.
117
+ * @example
118
+ * ```ts
119
+ * createEnlaceNext("http://localhost:3000/api/", {}, {
120
+ * revalidator: (tags, paths) => revalidateServerAction(tags, paths)
121
+ * });
122
+ * ```
123
+ */
124
+ revalidator?: RevalidateHandler;
125
+ };
126
+ /** Next.js hook options (third argument for createEnlaceHookNext) - extends React's EnlaceHookOptions */
127
+ type NextHookOptions = EnlaceHookOptions & Pick<NextOptions, "revalidator">;
128
+ /** Per-request options for Next.js fetch - extends React's base options */
129
+ type NextRequestOptionsBase = ReactRequestOptionsBase & {
130
+ /** Time in seconds to revalidate, or false to disable */
131
+ revalidate?: number | false;
132
+ /**
133
+ * URL paths to revalidate after mutation
134
+ * This doesn't do anything on the client by itself - it's passed to the revalidator handler.
135
+ * You must implement the revalidation logic in the revalidator.
136
+ */
137
+ revalidatePaths?: string[];
138
+ /**
139
+ * Skip server-side revalidation for this request.
140
+ * Useful when autoRevalidateTags is enabled but you want to opt-out for specific mutations.
141
+ * You can still pass empty [] to revalidateTags to skip triggering revalidation.
142
+ * But this flag can be used if you want to revalidate client-side and skip server-side entirely.
143
+ * Eg. you don't fetch any data on server component and you might want to skip the overhead of revalidation.
144
+ */
145
+ skipRevalidator?: boolean;
146
+ };
147
+ type NextQueryFn<TSchema, TData, TError, TDefaultError = unknown> = QueryFn<TSchema, TData, TError, TDefaultError, NextRequestOptionsBase>;
148
+ type NextSelectorFn<TSchema, TMethod, TDefaultError = unknown> = SelectorFn<TSchema, TMethod, TDefaultError, NextRequestOptionsBase>;
149
+ /** Hook type returned by createEnlaceHookNext */
150
+ type NextEnlaceHook<TSchema, TDefaultError = unknown> = {
151
+ <TMethod extends (...args: any[]) => Promise<EnlaceResponse<unknown, unknown>>>(selector: NextSelectorFn<TSchema, TMethod, TDefaultError>): UseEnlaceSelectorResult<TMethod>;
152
+ <TData, TError>(queryFn: NextQueryFn<TSchema, TData, TError, TDefaultError>, options?: UseEnlaceQueryOptions): UseEnlaceQueryResult<TData, TError>;
153
+ };
154
+
155
+ /**
156
+ * Creates a React hook for making API calls in Next.js Client Components.
157
+ * Uses Next.js-specific features like revalidator for server-side cache invalidation.
158
+ *
159
+ * @example
160
+ * const useAPI = createEnlaceHookNext<ApiSchema>('https://api.com', {}, {
161
+ * revalidator: (tags) => revalidateTagsAction(tags),
162
+ * staleTime: 5000,
163
+ * });
164
+ *
165
+ * // Query mode - auto-fetch
166
+ * const { loading, data, error } = useAPI((api) => api.posts.get());
167
+ *
168
+ * // Selector mode - trigger for mutations
169
+ * const { trigger } = useAPI((api) => api.posts.delete);
170
+ */
171
+ declare function createEnlaceHookNext<TSchema = unknown, TDefaultError = unknown>(baseUrl: string, defaultOptions?: EnlaceOptions, hookOptions?: NextHookOptions): NextEnlaceHook<TSchema, TDefaultError>;
172
+
173
+ export { type ApiClient, type EnlaceHook, type EnlaceHookOptions, HTTP_METHODS, type HookState, type NextEnlaceHook, type NextHookOptions, type QueryFn, type ReactRequestOptionsBase, type SelectorFn, type TrackedCall, type UseEnlaceQueryOptions, type UseEnlaceQueryResult, type UseEnlaceSelectorResult, createEnlaceHookNext, createEnlaceHookReact };
@@ -0,0 +1,173 @@
1
+ import { EnlaceCallbackPayload, EnlaceErrorCallbackPayload, EnlaceResponse, WildcardClient, EnlaceClient, EnlaceOptions, EnlaceCallbacks } from 'enlace-core';
2
+
3
+ /** Per-request options for React hooks */
4
+ type ReactRequestOptionsBase = {
5
+ /**
6
+ * Cache tags for caching (GET requests only)
7
+ * This will auto generate tags from the URL path if not provided and autoGenerateTags is enabled.
8
+ * But can be manually specified to override auto-generation.
9
+ * */
10
+ tags?: string[];
11
+ /** Tags to invalidate after mutation (triggers refetch in matching queries) */
12
+ revalidateTags?: string[];
13
+ /**
14
+ * Path parameters for dynamic URL segments.
15
+ * Used to replace :paramName placeholders in the URL path.
16
+ * @example
17
+ * // With path api.products[':id'].delete
18
+ * trigger({ pathParams: { id: '123' } }) // → DELETE /products/123
19
+ */
20
+ pathParams?: Record<string, string | number>;
21
+ };
22
+ /** Options for query mode hooks */
23
+ type UseEnlaceQueryOptions = {
24
+ /**
25
+ * Whether the query should execute.
26
+ * Set to false to skip fetching (useful when ID is "new" or undefined).
27
+ * @default true
28
+ */
29
+ enabled?: boolean;
30
+ };
31
+ type ApiClient<TSchema, TDefaultError = unknown, TOptions = ReactRequestOptionsBase> = unknown extends TSchema ? WildcardClient<TOptions> : EnlaceClient<TSchema, TDefaultError, TOptions>;
32
+ type QueryFn<TSchema, TData, TError, TDefaultError = unknown, TOptions = ReactRequestOptionsBase> = (api: ApiClient<TSchema, TDefaultError, TOptions>) => Promise<EnlaceResponse<TData, TError>>;
33
+ type SelectorFn<TSchema, TMethod, TDefaultError = unknown, TOptions = ReactRequestOptionsBase> = (api: ApiClient<TSchema, TDefaultError, TOptions>) => TMethod;
34
+ type HookState = {
35
+ loading: boolean;
36
+ fetching: boolean;
37
+ data: unknown;
38
+ error: unknown;
39
+ };
40
+ type TrackedCall = {
41
+ path: string[];
42
+ method: string;
43
+ options: unknown;
44
+ };
45
+ declare const HTTP_METHODS: readonly ["get", "post", "put", "patch", "delete"];
46
+ type ExtractData<T> = T extends (...args: any[]) => Promise<EnlaceResponse<infer D, unknown>> ? D : never;
47
+ type ExtractError<T> = T extends (...args: any[]) => Promise<EnlaceResponse<unknown, infer E>> ? E : never;
48
+ /** Discriminated union for hook response state - enables type narrowing via error check */
49
+ type HookResponseState<TData, TError> = {
50
+ data: TData;
51
+ error?: undefined;
52
+ } | {
53
+ data?: undefined;
54
+ error: TError;
55
+ };
56
+ /** Result when hook is called with query function (auto-fetch mode) */
57
+ type UseEnlaceQueryResult<TData, TError> = {
58
+ loading: boolean;
59
+ fetching: boolean;
60
+ } & HookResponseState<TData, TError>;
61
+ /** Result when hook is called with method selector (trigger mode) */
62
+ type UseEnlaceSelectorResult<TMethod> = {
63
+ trigger: TMethod;
64
+ loading: boolean;
65
+ fetching: boolean;
66
+ } & HookResponseState<ExtractData<TMethod>, ExtractError<TMethod>>;
67
+ /** Options for createEnlaceHookReact factory */
68
+ type EnlaceHookOptions = {
69
+ /**
70
+ * Auto-generate cache tags from URL path for GET requests.
71
+ * e.g., `/posts/1` generates tags `['posts', 'posts/1']`
72
+ * @default true
73
+ */
74
+ autoGenerateTags?: boolean;
75
+ /** Auto-revalidate generated tags after successful mutations. @default true */
76
+ autoRevalidateTags?: boolean;
77
+ /** Time in ms before cached data is considered stale. @default 0 (always stale) */
78
+ staleTime?: number;
79
+ /** Callback called on successful API responses */
80
+ onSuccess?: (payload: EnlaceCallbackPayload<unknown>) => void;
81
+ /** Callback called on error responses (HTTP errors or network failures) */
82
+ onError?: (payload: EnlaceErrorCallbackPayload<unknown>) => void;
83
+ };
84
+ /** Hook type returned by createEnlaceHookReact */
85
+ type EnlaceHook<TSchema, TDefaultError = unknown> = {
86
+ <TMethod extends (...args: any[]) => Promise<EnlaceResponse<unknown, unknown>>>(selector: SelectorFn<TSchema, TMethod, TDefaultError>): UseEnlaceSelectorResult<TMethod>;
87
+ <TData, TError>(queryFn: QueryFn<TSchema, TData, TError, TDefaultError>, options?: UseEnlaceQueryOptions): UseEnlaceQueryResult<TData, TError>;
88
+ };
89
+
90
+ /**
91
+ * Creates a React hook for making API calls.
92
+ * Called at module level to create a reusable hook.
93
+ *
94
+ * @example
95
+ * const useAPI = createEnlaceHookReact<ApiSchema>('https://api.com');
96
+ *
97
+ * // Query mode - auto-fetch (auto-tracks changes, no deps array needed)
98
+ * const { loading, data, error } = useAPI((api) => api.posts.get({ query: { userId } }));
99
+ *
100
+ * // Selector mode - typed trigger for lazy calls
101
+ * const { trigger, loading, data, error } = useAPI((api) => api.posts.delete);
102
+ * onClick={() => trigger({ body: { id: 1 } })}
103
+ */
104
+ declare function createEnlaceHookReact<TSchema = unknown, TDefaultError = unknown>(baseUrl: string, defaultOptions?: EnlaceOptions, hookOptions?: EnlaceHookOptions): EnlaceHook<TSchema, TDefaultError>;
105
+
106
+ /**
107
+ * Handler function called after successful mutations to trigger server-side revalidation.
108
+ * @param tags - Cache tags to revalidate
109
+ * @param paths - URL paths to revalidate
110
+ */
111
+ type RevalidateHandler = (tags: string[], paths: string[]) => void | Promise<void>;
112
+ /** Next.js-specific options (third argument for createEnlaceNext) */
113
+ type NextOptions = Pick<EnlaceHookOptions, "autoGenerateTags" | "autoRevalidateTags"> & EnlaceCallbacks & {
114
+ /**
115
+ * Handler called after successful mutations to trigger server-side revalidation.
116
+ * Receives auto-generated or manually specified tags and paths.
117
+ * @example
118
+ * ```ts
119
+ * createEnlaceNext("http://localhost:3000/api/", {}, {
120
+ * revalidator: (tags, paths) => revalidateServerAction(tags, paths)
121
+ * });
122
+ * ```
123
+ */
124
+ revalidator?: RevalidateHandler;
125
+ };
126
+ /** Next.js hook options (third argument for createEnlaceHookNext) - extends React's EnlaceHookOptions */
127
+ type NextHookOptions = EnlaceHookOptions & Pick<NextOptions, "revalidator">;
128
+ /** Per-request options for Next.js fetch - extends React's base options */
129
+ type NextRequestOptionsBase = ReactRequestOptionsBase & {
130
+ /** Time in seconds to revalidate, or false to disable */
131
+ revalidate?: number | false;
132
+ /**
133
+ * URL paths to revalidate after mutation
134
+ * This doesn't do anything on the client by itself - it's passed to the revalidator handler.
135
+ * You must implement the revalidation logic in the revalidator.
136
+ */
137
+ revalidatePaths?: string[];
138
+ /**
139
+ * Skip server-side revalidation for this request.
140
+ * Useful when autoRevalidateTags is enabled but you want to opt-out for specific mutations.
141
+ * You can still pass empty [] to revalidateTags to skip triggering revalidation.
142
+ * But this flag can be used if you want to revalidate client-side and skip server-side entirely.
143
+ * Eg. you don't fetch any data on server component and you might want to skip the overhead of revalidation.
144
+ */
145
+ skipRevalidator?: boolean;
146
+ };
147
+ type NextQueryFn<TSchema, TData, TError, TDefaultError = unknown> = QueryFn<TSchema, TData, TError, TDefaultError, NextRequestOptionsBase>;
148
+ type NextSelectorFn<TSchema, TMethod, TDefaultError = unknown> = SelectorFn<TSchema, TMethod, TDefaultError, NextRequestOptionsBase>;
149
+ /** Hook type returned by createEnlaceHookNext */
150
+ type NextEnlaceHook<TSchema, TDefaultError = unknown> = {
151
+ <TMethod extends (...args: any[]) => Promise<EnlaceResponse<unknown, unknown>>>(selector: NextSelectorFn<TSchema, TMethod, TDefaultError>): UseEnlaceSelectorResult<TMethod>;
152
+ <TData, TError>(queryFn: NextQueryFn<TSchema, TData, TError, TDefaultError>, options?: UseEnlaceQueryOptions): UseEnlaceQueryResult<TData, TError>;
153
+ };
154
+
155
+ /**
156
+ * Creates a React hook for making API calls in Next.js Client Components.
157
+ * Uses Next.js-specific features like revalidator for server-side cache invalidation.
158
+ *
159
+ * @example
160
+ * const useAPI = createEnlaceHookNext<ApiSchema>('https://api.com', {}, {
161
+ * revalidator: (tags) => revalidateTagsAction(tags),
162
+ * staleTime: 5000,
163
+ * });
164
+ *
165
+ * // Query mode - auto-fetch
166
+ * const { loading, data, error } = useAPI((api) => api.posts.get());
167
+ *
168
+ * // Selector mode - trigger for mutations
169
+ * const { trigger } = useAPI((api) => api.posts.delete);
170
+ */
171
+ declare function createEnlaceHookNext<TSchema = unknown, TDefaultError = unknown>(baseUrl: string, defaultOptions?: EnlaceOptions, hookOptions?: NextHookOptions): NextEnlaceHook<TSchema, TDefaultError>;
172
+
173
+ export { type ApiClient, type EnlaceHook, type EnlaceHookOptions, HTTP_METHODS, type HookState, type NextEnlaceHook, type NextHookOptions, type QueryFn, type ReactRequestOptionsBase, type SelectorFn, type TrackedCall, type UseEnlaceQueryOptions, type UseEnlaceQueryResult, type UseEnlaceSelectorResult, createEnlaceHookNext, createEnlaceHookReact };