enlace 0.0.0-alpha.4 → 0.0.1-beta.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.
@@ -0,0 +1,443 @@
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 __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
21
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
22
+
23
+ // src/next/createEnlaceHook.ts
24
+ var createEnlaceHook_exports = {};
25
+ __export(createEnlaceHook_exports, {
26
+ createEnlaceHook: () => createEnlaceHook
27
+ });
28
+ module.exports = __toCommonJS(createEnlaceHook_exports);
29
+
30
+ // src/next/index.ts
31
+ var next_exports = {};
32
+ __export(next_exports, {
33
+ createEnlace: () => createEnlace
34
+ });
35
+ var import_enlace_core2 = require("enlace-core");
36
+
37
+ // src/next/fetch.ts
38
+ var import_enlace_core = require("enlace-core");
39
+
40
+ // src/utils/generateTags.ts
41
+ function generateTags(path) {
42
+ return path.map((_, i) => path.slice(0, i + 1).join("/"));
43
+ }
44
+
45
+ // src/next/fetch.ts
46
+ async function executeNextFetch(baseUrl, path, method, combinedOptions, requestOptions) {
47
+ const {
48
+ autoGenerateTags = true,
49
+ autoRevalidateTags = true,
50
+ revalidator,
51
+ headers: defaultHeaders,
52
+ ...restOptions
53
+ } = combinedOptions;
54
+ const url = (0, import_enlace_core.buildUrl)(baseUrl, path, requestOptions?.query);
55
+ let headers = (0, import_enlace_core.mergeHeaders)(defaultHeaders, requestOptions?.headers);
56
+ const isGet = method === "GET";
57
+ const autoTags = generateTags(path);
58
+ const fetchOptions = {
59
+ ...restOptions,
60
+ method
61
+ };
62
+ if (requestOptions?.cache) {
63
+ fetchOptions.cache = requestOptions.cache;
64
+ }
65
+ if (isGet) {
66
+ const tags = requestOptions?.tags ?? (autoGenerateTags ? autoTags : void 0);
67
+ const nextFetchOptions = {};
68
+ if (tags) {
69
+ nextFetchOptions.tags = tags;
70
+ }
71
+ if (requestOptions?.revalidate !== void 0) {
72
+ nextFetchOptions.revalidate = requestOptions.revalidate;
73
+ }
74
+ fetchOptions.next = nextFetchOptions;
75
+ }
76
+ if (headers) {
77
+ fetchOptions.headers = headers;
78
+ }
79
+ if (requestOptions?.body !== void 0) {
80
+ if ((0, import_enlace_core.isJsonBody)(requestOptions.body)) {
81
+ fetchOptions.body = JSON.stringify(requestOptions.body);
82
+ headers = (0, import_enlace_core.mergeHeaders)(headers, { "Content-Type": "application/json" });
83
+ if (headers) {
84
+ fetchOptions.headers = headers;
85
+ }
86
+ } else {
87
+ fetchOptions.body = requestOptions.body;
88
+ }
89
+ }
90
+ const response = await fetch(url, fetchOptions);
91
+ const contentType = response.headers.get("content-type");
92
+ const isJson = contentType?.includes("application/json");
93
+ if (response.ok) {
94
+ if (!isGet && !requestOptions?.skipRevalidator) {
95
+ const revalidateTags = requestOptions?.revalidateTags ?? (autoRevalidateTags ? autoTags : []);
96
+ const revalidatePaths = requestOptions?.revalidatePaths ?? [];
97
+ if (revalidateTags.length || revalidatePaths.length) {
98
+ revalidator?.(revalidateTags, revalidatePaths);
99
+ }
100
+ }
101
+ return {
102
+ ok: true,
103
+ status: response.status,
104
+ data: isJson ? await response.json() : response
105
+ };
106
+ }
107
+ return {
108
+ ok: false,
109
+ status: response.status,
110
+ error: isJson ? await response.json() : response
111
+ };
112
+ }
113
+
114
+ // src/next/index.ts
115
+ __reExport(next_exports, require("enlace-core"));
116
+ function createEnlace(baseUrl, defaultOptions = {}, nextOptions = {}) {
117
+ const combinedOptions = { ...defaultOptions, ...nextOptions };
118
+ return (0, import_enlace_core2.createProxyHandler)(baseUrl, combinedOptions, [], executeNextFetch);
119
+ }
120
+
121
+ // src/react/useQueryMode.ts
122
+ var import_react = require("react");
123
+
124
+ // src/react/reducer.ts
125
+ var initialState = {
126
+ loading: false,
127
+ fetching: false,
128
+ ok: void 0,
129
+ data: void 0,
130
+ error: void 0
131
+ };
132
+ function hookReducer(state, action) {
133
+ switch (action.type) {
134
+ case "RESET":
135
+ return action.state;
136
+ case "FETCH_START":
137
+ return {
138
+ ...state,
139
+ loading: state.data === void 0,
140
+ fetching: true
141
+ };
142
+ case "FETCH_SUCCESS":
143
+ return {
144
+ loading: false,
145
+ fetching: false,
146
+ ok: true,
147
+ data: action.data,
148
+ error: void 0
149
+ };
150
+ case "FETCH_ERROR":
151
+ return {
152
+ loading: false,
153
+ fetching: false,
154
+ ok: false,
155
+ data: void 0,
156
+ error: action.error
157
+ };
158
+ case "SYNC_CACHE":
159
+ return action.state;
160
+ default:
161
+ return state;
162
+ }
163
+ }
164
+
165
+ // src/utils/sortObjectKeys.ts
166
+ function sortObjectKeys(obj) {
167
+ if (obj === null || typeof obj !== "object") return obj;
168
+ if (Array.isArray(obj)) return obj.map(sortObjectKeys);
169
+ return Object.keys(obj).sort().reduce(
170
+ (sorted, key) => {
171
+ sorted[key] = sortObjectKeys(obj[key]);
172
+ return sorted;
173
+ },
174
+ {}
175
+ );
176
+ }
177
+
178
+ // src/react/cache.ts
179
+ var cache = /* @__PURE__ */ new Map();
180
+ function createQueryKey(tracked) {
181
+ return JSON.stringify(
182
+ sortObjectKeys({
183
+ path: tracked.path,
184
+ method: tracked.method,
185
+ options: tracked.options
186
+ })
187
+ );
188
+ }
189
+ function getCache(key) {
190
+ return cache.get(key);
191
+ }
192
+ function setCache(key, entry) {
193
+ const existing = cache.get(key);
194
+ if (existing) {
195
+ if ("ok" in entry) {
196
+ delete existing.promise;
197
+ }
198
+ Object.assign(existing, entry);
199
+ existing.subscribers.forEach((cb) => cb());
200
+ } else {
201
+ cache.set(key, {
202
+ data: void 0,
203
+ error: void 0,
204
+ ok: void 0,
205
+ timestamp: 0,
206
+ tags: [],
207
+ subscribers: /* @__PURE__ */ new Set(),
208
+ ...entry
209
+ });
210
+ }
211
+ }
212
+ function subscribeCache(key, callback) {
213
+ let entry = cache.get(key);
214
+ if (!entry) {
215
+ cache.set(key, {
216
+ data: void 0,
217
+ error: void 0,
218
+ ok: void 0,
219
+ timestamp: 0,
220
+ tags: [],
221
+ subscribers: /* @__PURE__ */ new Set()
222
+ });
223
+ entry = cache.get(key);
224
+ }
225
+ entry.subscribers.add(callback);
226
+ return () => {
227
+ entry.subscribers.delete(callback);
228
+ };
229
+ }
230
+ function isStale(key, staleTime) {
231
+ const entry = cache.get(key);
232
+ if (!entry) return true;
233
+ return Date.now() - entry.timestamp > staleTime;
234
+ }
235
+ function clearCacheByTags(tags) {
236
+ cache.forEach((entry) => {
237
+ const hasMatch = entry.tags.some((tag) => tags.includes(tag));
238
+ if (hasMatch) {
239
+ entry.data = void 0;
240
+ entry.error = void 0;
241
+ entry.ok = void 0;
242
+ entry.timestamp = 0;
243
+ delete entry.promise;
244
+ }
245
+ });
246
+ }
247
+
248
+ // src/react/revalidator.ts
249
+ var listeners = /* @__PURE__ */ new Set();
250
+ function invalidateTags(tags) {
251
+ clearCacheByTags(tags);
252
+ listeners.forEach((listener) => listener(tags));
253
+ }
254
+ function onRevalidate(callback) {
255
+ listeners.add(callback);
256
+ return () => listeners.delete(callback);
257
+ }
258
+
259
+ // src/react/useQueryMode.ts
260
+ function useQueryMode(api, trackedCall, options) {
261
+ const { autoGenerateTags, staleTime } = options;
262
+ const queryKey = createQueryKey(trackedCall);
263
+ const requestOptions = trackedCall.options;
264
+ const queryTags = requestOptions?.tags ?? (autoGenerateTags ? generateTags(trackedCall.path) : []);
265
+ const getCacheState = (includeNeedsFetch = false) => {
266
+ const cached = getCache(queryKey);
267
+ const hasCachedData = cached?.data !== void 0;
268
+ const isFetching = !!cached?.promise;
269
+ const needsFetch = includeNeedsFetch && (!hasCachedData || isStale(queryKey, staleTime));
270
+ return {
271
+ loading: !hasCachedData && (isFetching || needsFetch),
272
+ fetching: isFetching || needsFetch,
273
+ ok: cached?.ok,
274
+ data: cached?.data,
275
+ error: cached?.error
276
+ };
277
+ };
278
+ const [state, dispatch] = (0, import_react.useReducer)(hookReducer, null, () => getCacheState(true));
279
+ const mountedRef = (0, import_react.useRef)(true);
280
+ const fetchRef = (0, import_react.useRef)(null);
281
+ (0, import_react.useEffect)(() => {
282
+ mountedRef.current = true;
283
+ dispatch({ type: "RESET", state: getCacheState(true) });
284
+ const unsubscribe = subscribeCache(queryKey, () => {
285
+ if (mountedRef.current) {
286
+ dispatch({ type: "SYNC_CACHE", state: getCacheState() });
287
+ }
288
+ });
289
+ const doFetch = () => {
290
+ const cached2 = getCache(queryKey);
291
+ if (cached2?.promise) {
292
+ return;
293
+ }
294
+ dispatch({ type: "FETCH_START" });
295
+ let current = api;
296
+ for (const segment of trackedCall.path) {
297
+ current = current[segment];
298
+ }
299
+ const method = current[trackedCall.method];
300
+ const fetchPromise = method(trackedCall.options).then((res) => {
301
+ if (mountedRef.current) {
302
+ setCache(queryKey, {
303
+ data: res.ok ? res.data : void 0,
304
+ error: res.ok ? void 0 : res.error,
305
+ ok: res.ok,
306
+ timestamp: Date.now(),
307
+ tags: queryTags
308
+ });
309
+ }
310
+ });
311
+ setCache(queryKey, {
312
+ promise: fetchPromise,
313
+ tags: queryTags
314
+ });
315
+ };
316
+ fetchRef.current = doFetch;
317
+ const cached = getCache(queryKey);
318
+ if (cached?.data !== void 0 && !isStale(queryKey, staleTime)) {
319
+ dispatch({ type: "SYNC_CACHE", state: getCacheState() });
320
+ } else {
321
+ doFetch();
322
+ }
323
+ return () => {
324
+ mountedRef.current = false;
325
+ fetchRef.current = null;
326
+ unsubscribe();
327
+ };
328
+ }, [queryKey]);
329
+ (0, import_react.useEffect)(() => {
330
+ if (queryTags.length === 0) return;
331
+ return onRevalidate((invalidatedTags) => {
332
+ const hasMatch = invalidatedTags.some((tag) => queryTags.includes(tag));
333
+ if (hasMatch && mountedRef.current && fetchRef.current) {
334
+ fetchRef.current();
335
+ }
336
+ });
337
+ }, [JSON.stringify(queryTags)]);
338
+ return state;
339
+ }
340
+
341
+ // src/react/useSelectorMode.ts
342
+ var import_react2 = require("react");
343
+ function useSelectorMode(method, path, autoRevalidateTags) {
344
+ const [state, dispatch] = (0, import_react2.useReducer)(hookReducer, initialState);
345
+ const methodRef = (0, import_react2.useRef)(method);
346
+ const triggerRef = (0, import_react2.useRef)(null);
347
+ const pathRef = (0, import_react2.useRef)(path);
348
+ const autoRevalidateRef = (0, import_react2.useRef)(autoRevalidateTags);
349
+ methodRef.current = method;
350
+ pathRef.current = path;
351
+ autoRevalidateRef.current = autoRevalidateTags;
352
+ if (!triggerRef.current) {
353
+ triggerRef.current = (async (...args) => {
354
+ dispatch({ type: "FETCH_START" });
355
+ const res = await methodRef.current(...args);
356
+ if (res.ok) {
357
+ dispatch({ type: "FETCH_SUCCESS", data: res.data });
358
+ const options = args[0];
359
+ const tagsToInvalidate = options?.revalidateTags ?? (autoRevalidateRef.current ? generateTags(pathRef.current) : []);
360
+ if (tagsToInvalidate.length > 0) {
361
+ invalidateTags(tagsToInvalidate);
362
+ }
363
+ } else {
364
+ dispatch({ type: "FETCH_ERROR", error: res.error });
365
+ }
366
+ return res;
367
+ });
368
+ }
369
+ return {
370
+ trigger: triggerRef.current,
371
+ ...state
372
+ };
373
+ }
374
+
375
+ // src/react/types.ts
376
+ var HTTP_METHODS = ["get", "post", "put", "patch", "delete"];
377
+
378
+ // src/react/trackingProxy.ts
379
+ function createTrackingProxy(onTrack) {
380
+ const createProxy = (path = []) => {
381
+ return new Proxy(() => {
382
+ }, {
383
+ get(_, prop) {
384
+ if (HTTP_METHODS.includes(prop)) {
385
+ const methodFn = (options) => {
386
+ onTrack({
387
+ trackedCall: { path, method: prop, options },
388
+ selectorPath: null,
389
+ selectorMethod: null
390
+ });
391
+ return Promise.resolve({ ok: true, data: void 0 });
392
+ };
393
+ onTrack({
394
+ trackedCall: null,
395
+ selectorPath: path,
396
+ selectorMethod: prop
397
+ });
398
+ return methodFn;
399
+ }
400
+ return createProxy([...path, prop]);
401
+ }
402
+ });
403
+ };
404
+ return createProxy();
405
+ }
406
+
407
+ // src/next/createEnlaceHook.ts
408
+ function createEnlaceHook(baseUrl, defaultOptions = {}, hookOptions = {}) {
409
+ const {
410
+ autoGenerateTags = true,
411
+ autoRevalidateTags = true,
412
+ staleTime = 0,
413
+ ...nextOptions
414
+ } = hookOptions;
415
+ const api = createEnlace(baseUrl, defaultOptions, {
416
+ autoGenerateTags,
417
+ autoRevalidateTags,
418
+ ...nextOptions
419
+ });
420
+ function useEnlaceHook(selectorOrQuery) {
421
+ let trackedCall = null;
422
+ let selectorPath = null;
423
+ const trackingProxy = createTrackingProxy((result2) => {
424
+ trackedCall = result2.trackedCall;
425
+ selectorPath = result2.selectorPath;
426
+ });
427
+ const result = selectorOrQuery(trackingProxy);
428
+ if (typeof result === "function") {
429
+ const actualResult = selectorOrQuery(api);
430
+ return useSelectorMode(
431
+ actualResult,
432
+ selectorPath ?? [],
433
+ autoRevalidateTags
434
+ );
435
+ }
436
+ return useQueryMode(
437
+ api,
438
+ trackedCall,
439
+ { autoGenerateTags, staleTime }
440
+ );
441
+ }
442
+ return useEnlaceHook;
443
+ }