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,516 @@
1
+ "use client";
2
+ "use strict";
3
+ "use client";
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
+
22
+ // src/hook/index.ts
23
+ var hook_exports = {};
24
+ __export(hook_exports, {
25
+ HTTP_METHODS: () => HTTP_METHODS,
26
+ createEnlaceHookNext: () => createEnlaceHookNext,
27
+ createEnlaceHookReact: () => createEnlaceHookReact
28
+ });
29
+ module.exports = __toCommonJS(hook_exports);
30
+
31
+ // src/react/createEnlaceHookReact.ts
32
+ var import_enlace_core = require("enlace-core");
33
+
34
+ // src/react/useQueryMode.ts
35
+ var import_react = require("react");
36
+
37
+ // src/react/reducer.ts
38
+ var initialState = {
39
+ loading: false,
40
+ fetching: false,
41
+ data: void 0,
42
+ error: void 0
43
+ };
44
+ function hookReducer(state, action) {
45
+ switch (action.type) {
46
+ case "RESET":
47
+ return action.state ?? initialState;
48
+ case "FETCH_START":
49
+ return {
50
+ ...state,
51
+ loading: state.data === void 0,
52
+ fetching: true
53
+ };
54
+ case "FETCH_SUCCESS":
55
+ return {
56
+ loading: false,
57
+ fetching: false,
58
+ data: action.data,
59
+ error: void 0
60
+ };
61
+ case "FETCH_ERROR":
62
+ return {
63
+ loading: false,
64
+ fetching: false,
65
+ data: void 0,
66
+ error: action.error
67
+ };
68
+ case "SYNC_CACHE":
69
+ return action.state;
70
+ default:
71
+ return state;
72
+ }
73
+ }
74
+
75
+ // src/utils/generateTags.ts
76
+ function generateTags(path) {
77
+ return path.map((_, i) => path.slice(0, i + 1).join("/"));
78
+ }
79
+
80
+ // src/utils/sortObjectKeys.ts
81
+ function sortObjectKeys(obj) {
82
+ if (obj === null || typeof obj !== "object") return obj;
83
+ if (Array.isArray(obj)) return obj.map(sortObjectKeys);
84
+ return Object.keys(obj).sort().reduce(
85
+ (sorted, key) => {
86
+ sorted[key] = sortObjectKeys(obj[key]);
87
+ return sorted;
88
+ },
89
+ {}
90
+ );
91
+ }
92
+
93
+ // src/react/cache.ts
94
+ var cache = /* @__PURE__ */ new Map();
95
+ function createQueryKey(tracked) {
96
+ return JSON.stringify(
97
+ sortObjectKeys({
98
+ path: tracked.path,
99
+ method: tracked.method,
100
+ options: tracked.options
101
+ })
102
+ );
103
+ }
104
+ function getCache(key) {
105
+ return cache.get(key);
106
+ }
107
+ function setCache(key, entry) {
108
+ const existing = cache.get(key);
109
+ if (existing) {
110
+ if ("data" in entry || "error" in entry) {
111
+ delete existing.promise;
112
+ }
113
+ Object.assign(existing, entry);
114
+ existing.subscribers.forEach((cb) => cb());
115
+ } else {
116
+ cache.set(key, {
117
+ data: void 0,
118
+ error: void 0,
119
+ timestamp: 0,
120
+ tags: [],
121
+ subscribers: /* @__PURE__ */ new Set(),
122
+ ...entry
123
+ });
124
+ }
125
+ }
126
+ function subscribeCache(key, callback) {
127
+ let entry = cache.get(key);
128
+ if (!entry) {
129
+ cache.set(key, {
130
+ data: void 0,
131
+ error: void 0,
132
+ timestamp: 0,
133
+ tags: [],
134
+ subscribers: /* @__PURE__ */ new Set()
135
+ });
136
+ entry = cache.get(key);
137
+ }
138
+ entry.subscribers.add(callback);
139
+ return () => {
140
+ entry.subscribers.delete(callback);
141
+ };
142
+ }
143
+ function isStale(key, staleTime) {
144
+ const entry = cache.get(key);
145
+ if (!entry) return true;
146
+ return Date.now() - entry.timestamp > staleTime;
147
+ }
148
+ function clearCacheByTags(tags) {
149
+ cache.forEach((entry) => {
150
+ const hasMatch = entry.tags.some((tag) => tags.includes(tag));
151
+ if (hasMatch) {
152
+ entry.data = void 0;
153
+ entry.error = void 0;
154
+ entry.timestamp = 0;
155
+ delete entry.promise;
156
+ }
157
+ });
158
+ }
159
+
160
+ // src/react/revalidator.ts
161
+ var listeners = /* @__PURE__ */ new Set();
162
+ function invalidateTags(tags) {
163
+ clearCacheByTags(tags);
164
+ listeners.forEach((listener) => listener(tags));
165
+ }
166
+ function onRevalidate(callback) {
167
+ listeners.add(callback);
168
+ return () => listeners.delete(callback);
169
+ }
170
+
171
+ // src/react/useQueryMode.ts
172
+ function resolvePath(path, pathParams) {
173
+ if (!pathParams) return path;
174
+ return path.map((segment) => {
175
+ if (segment.startsWith(":")) {
176
+ const paramName = segment.slice(1);
177
+ const value = pathParams[paramName];
178
+ if (value === void 0) {
179
+ throw new Error(`Missing path parameter: ${paramName}`);
180
+ }
181
+ return String(value);
182
+ }
183
+ return segment;
184
+ });
185
+ }
186
+ function useQueryMode(api, trackedCall, options) {
187
+ const { autoGenerateTags, staleTime, enabled } = options;
188
+ const queryKey = createQueryKey(trackedCall);
189
+ const requestOptions = trackedCall.options;
190
+ const resolvedPath = resolvePath(
191
+ trackedCall.path,
192
+ requestOptions?.pathParams
193
+ );
194
+ const queryTags = requestOptions?.tags ?? (autoGenerateTags ? generateTags(resolvedPath) : []);
195
+ const getCacheState = (includeNeedsFetch = false) => {
196
+ const cached = getCache(queryKey);
197
+ const hasCachedData = cached?.data !== void 0;
198
+ const isFetching = !!cached?.promise;
199
+ const needsFetch = includeNeedsFetch && (!hasCachedData || isStale(queryKey, staleTime));
200
+ return {
201
+ loading: !hasCachedData && (isFetching || needsFetch),
202
+ fetching: isFetching || needsFetch,
203
+ data: cached?.data,
204
+ error: cached?.error
205
+ };
206
+ };
207
+ const [state, dispatch] = (0, import_react.useReducer)(
208
+ hookReducer,
209
+ null,
210
+ () => getCacheState(true)
211
+ );
212
+ const mountedRef = (0, import_react.useRef)(true);
213
+ const fetchRef = (0, import_react.useRef)(null);
214
+ (0, import_react.useEffect)(() => {
215
+ mountedRef.current = true;
216
+ if (!enabled) {
217
+ dispatch({ type: "RESET" });
218
+ return () => {
219
+ mountedRef.current = false;
220
+ };
221
+ }
222
+ dispatch({ type: "RESET", state: getCacheState(true) });
223
+ const doFetch = () => {
224
+ const cached2 = getCache(queryKey);
225
+ if (cached2?.promise) {
226
+ return;
227
+ }
228
+ dispatch({ type: "FETCH_START" });
229
+ let current = api;
230
+ for (const segment of resolvedPath) {
231
+ current = current[segment];
232
+ }
233
+ const method = current[trackedCall.method];
234
+ const fetchPromise = method(trackedCall.options).then((res) => {
235
+ if (mountedRef.current) {
236
+ setCache(queryKey, {
237
+ data: res.error ? void 0 : res.data,
238
+ error: res.error,
239
+ timestamp: Date.now(),
240
+ tags: queryTags
241
+ });
242
+ }
243
+ });
244
+ setCache(queryKey, {
245
+ promise: fetchPromise,
246
+ tags: queryTags
247
+ });
248
+ };
249
+ fetchRef.current = doFetch;
250
+ const cached = getCache(queryKey);
251
+ if (cached?.data !== void 0 && !isStale(queryKey, staleTime)) {
252
+ dispatch({ type: "SYNC_CACHE", state: getCacheState() });
253
+ } else {
254
+ doFetch();
255
+ }
256
+ const unsubscribe = subscribeCache(queryKey, () => {
257
+ if (mountedRef.current) {
258
+ dispatch({ type: "SYNC_CACHE", state: getCacheState() });
259
+ }
260
+ });
261
+ return () => {
262
+ mountedRef.current = false;
263
+ fetchRef.current = null;
264
+ unsubscribe();
265
+ };
266
+ }, [queryKey, enabled]);
267
+ (0, import_react.useEffect)(() => {
268
+ if (queryTags.length === 0) return;
269
+ return onRevalidate((invalidatedTags) => {
270
+ const hasMatch = invalidatedTags.some((tag) => queryTags.includes(tag));
271
+ if (hasMatch && mountedRef.current && fetchRef.current) {
272
+ fetchRef.current();
273
+ }
274
+ });
275
+ }, [JSON.stringify(queryTags)]);
276
+ return state;
277
+ }
278
+
279
+ // src/react/types.ts
280
+ var HTTP_METHODS = ["get", "post", "put", "patch", "delete"];
281
+
282
+ // src/react/trackingProxy.ts
283
+ function createTrackingProxy(onTrack) {
284
+ const createProxy = (path = []) => {
285
+ return new Proxy(() => {
286
+ }, {
287
+ get(_, prop) {
288
+ if (HTTP_METHODS.includes(prop)) {
289
+ const methodFn = (options) => {
290
+ onTrack({
291
+ trackedCall: { path, method: prop, options },
292
+ selectorPath: null,
293
+ selectorMethod: null
294
+ });
295
+ return Promise.resolve({ status: 200, data: void 0, error: void 0 });
296
+ };
297
+ onTrack({
298
+ trackedCall: null,
299
+ selectorPath: path,
300
+ selectorMethod: prop
301
+ });
302
+ return methodFn;
303
+ }
304
+ return createProxy([...path, prop]);
305
+ }
306
+ });
307
+ };
308
+ return createProxy();
309
+ }
310
+
311
+ // src/react/useSelectorMode.ts
312
+ var import_react2 = require("react");
313
+ function resolvePath2(path, pathParams) {
314
+ if (!pathParams) return path;
315
+ return path.map((segment) => {
316
+ if (segment.startsWith(":")) {
317
+ const paramName = segment.slice(1);
318
+ const value = pathParams[paramName];
319
+ if (value === void 0) {
320
+ throw new Error(`Missing path parameter: ${paramName}`);
321
+ }
322
+ return String(value);
323
+ }
324
+ return segment;
325
+ });
326
+ }
327
+ function hasPathParams(path) {
328
+ return path.some((segment) => segment.startsWith(":"));
329
+ }
330
+ function useSelectorMode(config) {
331
+ const { method, api, path, methodName, autoRevalidateTags } = config;
332
+ const [state, dispatch] = (0, import_react2.useReducer)(hookReducer, initialState);
333
+ const methodRef = (0, import_react2.useRef)(method);
334
+ const apiRef = (0, import_react2.useRef)(api);
335
+ const triggerRef = (0, import_react2.useRef)(null);
336
+ const pathRef = (0, import_react2.useRef)(path);
337
+ const methodNameRef = (0, import_react2.useRef)(methodName);
338
+ const autoRevalidateRef = (0, import_react2.useRef)(autoRevalidateTags);
339
+ methodRef.current = method;
340
+ apiRef.current = api;
341
+ pathRef.current = path;
342
+ methodNameRef.current = methodName;
343
+ autoRevalidateRef.current = autoRevalidateTags;
344
+ if (!triggerRef.current) {
345
+ triggerRef.current = (async (...args) => {
346
+ dispatch({ type: "FETCH_START" });
347
+ const options = args[0];
348
+ const resolvedPath = resolvePath2(pathRef.current, options?.pathParams);
349
+ let res;
350
+ if (hasPathParams(pathRef.current)) {
351
+ let current = apiRef.current;
352
+ for (const segment of resolvedPath) {
353
+ current = current[segment];
354
+ }
355
+ const resolvedMethod = current[methodNameRef.current];
356
+ res = await resolvedMethod(...args);
357
+ } else {
358
+ res = await methodRef.current(...args);
359
+ }
360
+ if (!res.error) {
361
+ dispatch({ type: "FETCH_SUCCESS", data: res.data });
362
+ const tagsToInvalidate = options?.revalidateTags ?? (autoRevalidateRef.current ? generateTags(resolvedPath) : []);
363
+ if (tagsToInvalidate.length > 0) {
364
+ invalidateTags(tagsToInvalidate);
365
+ }
366
+ } else {
367
+ dispatch({ type: "FETCH_ERROR", error: res.error });
368
+ }
369
+ return res;
370
+ });
371
+ }
372
+ return {
373
+ trigger: triggerRef.current,
374
+ ...state
375
+ };
376
+ }
377
+
378
+ // src/react/createEnlaceHookReact.ts
379
+ function createEnlaceHookReact(baseUrl, defaultOptions = {}, hookOptions = {}) {
380
+ const {
381
+ autoGenerateTags = true,
382
+ autoRevalidateTags = true,
383
+ staleTime = 0,
384
+ onSuccess,
385
+ onError
386
+ } = hookOptions;
387
+ const api = (0, import_enlace_core.createEnlace)(baseUrl, defaultOptions, { onSuccess, onError });
388
+ function useEnlaceHook(selectorOrQuery, queryOptions) {
389
+ let trackingResult = {
390
+ trackedCall: null,
391
+ selectorPath: null,
392
+ selectorMethod: null
393
+ };
394
+ const trackingProxy = createTrackingProxy((result2) => {
395
+ trackingResult = result2;
396
+ });
397
+ const result = selectorOrQuery(
398
+ trackingProxy
399
+ );
400
+ if (typeof result === "function") {
401
+ const actualResult = selectorOrQuery(api);
402
+ return useSelectorMode({
403
+ method: actualResult,
404
+ api,
405
+ path: trackingResult.selectorPath ?? [],
406
+ methodName: trackingResult.selectorMethod ?? "",
407
+ autoRevalidateTags
408
+ });
409
+ }
410
+ return useQueryMode(
411
+ api,
412
+ trackingResult.trackedCall,
413
+ { autoGenerateTags, staleTime, enabled: queryOptions?.enabled ?? true }
414
+ );
415
+ }
416
+ return useEnlaceHook;
417
+ }
418
+
419
+ // src/next/index.ts
420
+ var import_enlace_core3 = require("enlace-core");
421
+
422
+ // src/next/fetch.ts
423
+ var import_enlace_core2 = require("enlace-core");
424
+ async function executeNextFetch(baseUrl, path, method, combinedOptions, requestOptions) {
425
+ const {
426
+ autoGenerateTags = true,
427
+ autoRevalidateTags = true,
428
+ revalidator,
429
+ onSuccess,
430
+ ...coreOptions
431
+ } = combinedOptions;
432
+ const isGet = method === "GET";
433
+ const autoTags = generateTags(path);
434
+ const nextOnSuccess = (payload) => {
435
+ if (!isGet && !requestOptions?.skipRevalidator) {
436
+ const revalidateTags = requestOptions?.revalidateTags ?? (autoRevalidateTags ? autoTags : []);
437
+ const revalidatePaths = requestOptions?.revalidatePaths ?? [];
438
+ if (revalidateTags.length || revalidatePaths.length) {
439
+ revalidator?.(revalidateTags, revalidatePaths);
440
+ }
441
+ }
442
+ onSuccess?.(payload);
443
+ };
444
+ const nextRequestOptions = { ...requestOptions };
445
+ if (isGet) {
446
+ const tags = requestOptions?.tags ?? (autoGenerateTags ? autoTags : void 0);
447
+ const nextFetchOptions = {};
448
+ if (tags) {
449
+ nextFetchOptions.tags = tags;
450
+ }
451
+ if (requestOptions?.revalidate !== void 0) {
452
+ nextFetchOptions.revalidate = requestOptions.revalidate;
453
+ }
454
+ nextRequestOptions.next = nextFetchOptions;
455
+ }
456
+ return (0, import_enlace_core2.executeFetch)(
457
+ baseUrl,
458
+ path,
459
+ method,
460
+ { ...coreOptions, onSuccess: nextOnSuccess },
461
+ nextRequestOptions
462
+ );
463
+ }
464
+
465
+ // src/next/index.ts
466
+ function createEnlaceNext(baseUrl, defaultOptions = {}, nextOptions = {}) {
467
+ const combinedOptions = { ...defaultOptions, ...nextOptions };
468
+ return (0, import_enlace_core3.createProxyHandler)(
469
+ baseUrl,
470
+ combinedOptions,
471
+ [],
472
+ executeNextFetch
473
+ );
474
+ }
475
+
476
+ // src/next/createEnlaceHookNext.ts
477
+ function createEnlaceHookNext(baseUrl, defaultOptions = {}, hookOptions = {}) {
478
+ const {
479
+ autoGenerateTags = true,
480
+ autoRevalidateTags = true,
481
+ staleTime = 0,
482
+ ...nextOptions
483
+ } = hookOptions;
484
+ const api = createEnlaceNext(baseUrl, defaultOptions, {
485
+ autoGenerateTags,
486
+ autoRevalidateTags,
487
+ ...nextOptions
488
+ });
489
+ function useEnlaceHook(selectorOrQuery, queryOptions) {
490
+ let trackedCall = null;
491
+ let selectorPath = null;
492
+ let selectorMethod = null;
493
+ const trackingProxy = createTrackingProxy((result2) => {
494
+ trackedCall = result2.trackedCall;
495
+ selectorPath = result2.selectorPath;
496
+ selectorMethod = result2.selectorMethod;
497
+ });
498
+ const result = selectorOrQuery(trackingProxy);
499
+ if (typeof result === "function") {
500
+ const actualResult = selectorOrQuery(api);
501
+ return useSelectorMode({
502
+ method: actualResult,
503
+ api,
504
+ path: selectorPath ?? [],
505
+ methodName: selectorMethod ?? "",
506
+ autoRevalidateTags
507
+ });
508
+ }
509
+ return useQueryMode(
510
+ api,
511
+ trackedCall,
512
+ { autoGenerateTags, staleTime, enabled: queryOptions?.enabled ?? true }
513
+ );
514
+ }
515
+ return useEnlaceHook;
516
+ }