vite-plugin-smart-prefetch 0.1.0

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,758 @@
1
+ // src/frameworks/react/usePrefetch.ts
2
+ import { useEffect, useRef } from "react";
3
+ import { useLocation } from "react-router-dom";
4
+
5
+ // src/runtime/prefetch-manager.ts
6
+ var PrefetchManager = class {
7
+ constructor(strategy = "hybrid", debug = false) {
8
+ this.config = null;
9
+ this.prefetched = /* @__PURE__ */ new Set();
10
+ this.observer = null;
11
+ this.currentSegment = null;
12
+ this.fallbackToDefault = true;
13
+ this.strategy = strategy;
14
+ this.debug = debug;
15
+ }
16
+ /**
17
+ * Initialize the prefetch manager
18
+ * Loads configuration and sets up observers
19
+ */
20
+ async init() {
21
+ if (this.debug) {
22
+ console.log("\u{1F680} Smart Prefetch Manager - Initializing...");
23
+ console.log(" Strategy:", this.strategy);
24
+ console.log(" Debug mode: enabled");
25
+ }
26
+ try {
27
+ if (this.debug) {
28
+ console.log("\u{1F4E5} Fetching prefetch-config.json...");
29
+ }
30
+ const response = await fetch("/prefetch-config.json");
31
+ if (!response.ok) {
32
+ if (response.status === 404) {
33
+ if (this.debug) {
34
+ console.warn("\u26A0\uFE0F Prefetch config not found (404)");
35
+ console.log(" This is expected if:");
36
+ console.log(" 1. You haven't built the app yet (run `pnpm build`)");
37
+ console.log(" 2. The plugin failed to generate the config during build");
38
+ console.log(" Prefetch manager will be inactive until config is available");
39
+ }
40
+ return;
41
+ }
42
+ throw new Error(`Failed to load prefetch config: ${response.statusText}`);
43
+ }
44
+ this.config = await response.json();
45
+ if (this.debug && this.config) {
46
+ console.log("\u2705 Config loaded successfully");
47
+ console.log(` Routes with prefetch rules: ${Object.keys(this.config.routes).length} ${typeof this.config.routes}`);
48
+ console.log(` Environment: ${this.config.environment}`);
49
+ console.log(` Config version: ${this.config.version || "N/A"}`);
50
+ console.groupCollapsed("\u{1F4CB} Available prefetch rules:");
51
+ Object.entries(this.config.routes).forEach(([source, data]) => {
52
+ console.log(
53
+ `${source} \u2192 ${data.prefetch.length} target(s)`,
54
+ data.prefetch.map((t) => t.route)
55
+ );
56
+ });
57
+ console.groupEnd();
58
+ }
59
+ if (this.strategy === "visible" || this.strategy === "hybrid") {
60
+ this.initIntersectionObserver();
61
+ if (this.debug) {
62
+ console.log("\u{1F441}\uFE0F IntersectionObserver initialized for visibility-based prefetching");
63
+ }
64
+ }
65
+ if (this.debug) {
66
+ console.log("\u2705 Prefetch Manager fully initialized");
67
+ console.log("\u{1F4A1} Run window.__PREFETCH_DEBUG__() to see current state");
68
+ window.__PREFETCH_DEBUG__ = () => this.logDebugInfo();
69
+ }
70
+ } catch (error) {
71
+ if (this.debug) {
72
+ console.error("\u274C Failed to initialize Prefetch Manager:", error);
73
+ }
74
+ }
75
+ }
76
+ /**
77
+ * Set the user segment for segment-based prefetch rules
78
+ * @param segment - The user's segment (e.g., 'premium', 'free', 'admin')
79
+ * @param fallbackToDefault - Use default rules if segment rules unavailable
80
+ */
81
+ setSegment(segment, fallbackToDefault = true) {
82
+ this.currentSegment = segment;
83
+ this.fallbackToDefault = fallbackToDefault;
84
+ if (this.debug) {
85
+ console.log(`\u{1F504} Segment updated: ${segment || "(none)"}`);
86
+ console.log(` Fallback to default: ${fallbackToDefault}`);
87
+ }
88
+ }
89
+ /**
90
+ * Get the current segment
91
+ */
92
+ getSegment() {
93
+ return this.currentSegment;
94
+ }
95
+ /**
96
+ * Prefetch routes based on current route
97
+ */
98
+ prefetch(currentRoute) {
99
+ const cleanRoute = currentRoute.split("?")[0].split("#")[0];
100
+ if (this.debug) {
101
+ console.log(`\u{1F4CD} Checking prefetch for route: ${currentRoute}`);
102
+ if (currentRoute !== cleanRoute) {
103
+ console.log(` Clean route: ${cleanRoute}`);
104
+ }
105
+ }
106
+ if (!this.config) {
107
+ if (this.debug) {
108
+ console.warn("\u26A0\uFE0F Config not loaded yet - cannot prefetch");
109
+ console.log(" Make sure the app was built with the plugin enabled");
110
+ }
111
+ return;
112
+ }
113
+ if (!this.shouldPrefetch()) {
114
+ if (this.debug) {
115
+ console.log("\u23ED\uFE0F Skipping prefetch due to network conditions");
116
+ }
117
+ return;
118
+ }
119
+ let routeConfig = this.config.routes[cleanRoute] || this.config.routes[currentRoute];
120
+ const matchedRoute = routeConfig ? this.config.routes[cleanRoute] ? cleanRoute : currentRoute : null;
121
+ if (!routeConfig) {
122
+ if (this.debug) {
123
+ console.warn(`\u26A0\uFE0F No prefetch rules configured for route: ${cleanRoute}`);
124
+ console.groupCollapsed("Available routes in config:");
125
+ Object.keys(this.config.routes).forEach((route) => {
126
+ const targets = this.config.routes[route].prefetch;
127
+ console.log(` ${route} \u2192 ${targets.length} target(s)`, targets.map((t) => t.route));
128
+ });
129
+ console.groupEnd();
130
+ console.log(`\u{1F4A1} Tip: Make sure your manualRules key matches exactly: "${cleanRoute}"`);
131
+ }
132
+ return;
133
+ }
134
+ let prefetchTargets = routeConfig.prefetch;
135
+ let ruleSource = "default";
136
+ if (this.currentSegment && routeConfig.segments?.[this.currentSegment]) {
137
+ prefetchTargets = routeConfig.segments[this.currentSegment];
138
+ ruleSource = `segment (${this.currentSegment})`;
139
+ } else if (this.currentSegment && !routeConfig.segments?.[this.currentSegment] && !this.fallbackToDefault) {
140
+ if (this.debug) {
141
+ console.warn(`\u26A0\uFE0F No prefetch rules for segment "${this.currentSegment}" and fallback disabled`);
142
+ }
143
+ return;
144
+ }
145
+ console.log(`\u2705 Found prefetch rule for: ${matchedRoute}`);
146
+ console.log(` Total targets to prefetch: ${prefetchTargets.length}`);
147
+ console.log(` Using: ${ruleSource} rules`);
148
+ console.log(` Strategy: ${this.strategy}`);
149
+ if (this.debug) {
150
+ console.groupCollapsed(`\u{1F4CA} Prefetch Rules for: ${matchedRoute} (${ruleSource})`);
151
+ prefetchTargets.forEach((target, index) => {
152
+ console.log(` ${index + 1}. ${target.route} (${target.priority} priority, ${(target.probability * 100).toFixed(1)}%)`);
153
+ });
154
+ console.groupEnd();
155
+ }
156
+ prefetchTargets.forEach((target) => {
157
+ this.prefetchTarget(target);
158
+ });
159
+ }
160
+ /**
161
+ * Prefetch a specific target
162
+ */
163
+ prefetchTarget(target) {
164
+ if (this.prefetched.has(target.route)) {
165
+ console.log(` \u23ED\uFE0F Already prefetched: ${target.route}`);
166
+ return;
167
+ }
168
+ console.log(` \u{1F517} Prefetch target: ${target.route}, chunk: ${target.chunk}`);
169
+ try {
170
+ switch (this.strategy) {
171
+ case "auto":
172
+ this.injectPrefetchLink(target);
173
+ break;
174
+ case "hover":
175
+ break;
176
+ case "visible":
177
+ break;
178
+ case "idle":
179
+ this.prefetchOnIdle(target);
180
+ break;
181
+ case "hybrid":
182
+ this.prefetchHybrid(target);
183
+ break;
184
+ default:
185
+ console.warn(`\u26A0\uFE0F Unknown strategy: ${this.strategy}`);
186
+ }
187
+ } catch (error) {
188
+ console.error(`\u274C Error prefetching ${target.route}:`, error);
189
+ }
190
+ }
191
+ /**
192
+ * Hybrid strategy: prioritize based on probability
193
+ * FOR TESTING: Fetch all priorities to verify chunks are correct
194
+ */
195
+ prefetchHybrid(target) {
196
+ if (target.priority === "high" || target.probability >= 0.7) {
197
+ console.log(` \u26A1 High priority (${(target.probability * 100).toFixed(1)}%) - Prefetching immediately`);
198
+ this.injectPrefetchLink(target);
199
+ } else if (target.priority === "medium" || target.probability >= 0.4) {
200
+ console.log(` \u23F1\uFE0F Medium priority (${(target.probability * 100).toFixed(1)}%) - Fetching immediately (TESTING MODE)`);
201
+ this.injectPrefetchLink(target);
202
+ } else {
203
+ console.log(` \u{1F514} Low priority (${(target.probability * 100).toFixed(1)}%) - Fetching immediately (TESTING MODE)`);
204
+ this.injectPrefetchLink(target);
205
+ }
206
+ }
207
+ /**
208
+ * Prefetch during idle time
209
+ */
210
+ prefetchOnIdle(target) {
211
+ if ("requestIdleCallback" in window) {
212
+ requestIdleCallback(() => {
213
+ this.injectPrefetchLink(target);
214
+ });
215
+ } else {
216
+ setTimeout(() => {
217
+ this.injectPrefetchLink(target);
218
+ }, 1e3);
219
+ }
220
+ }
221
+ /**
222
+ * Resolve chunk path for the current environment
223
+ * In production: chunks are built with hashes (e.g., chunks/Privacy-D5qJZu-O.js or js/index-CJMMxcQV.js)
224
+ * In dev mode: need to resolve to the actual module or use a proxy
225
+ */
226
+ resolveChunkPath(chunkPath, route) {
227
+ const isDev = window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1";
228
+ if (!isDev) {
229
+ return `/${chunkPath}`;
230
+ }
231
+ let componentName = null;
232
+ const match1 = chunkPath.match(/\/([A-Z][a-zA-Z]*)-[a-zA-Z0-9_-]+\.js$/);
233
+ if (match1) {
234
+ componentName = match1[1];
235
+ }
236
+ const match2 = chunkPath.match(/\/(index)-[a-zA-Z0-9_-]+\.js$/);
237
+ if (match2) {
238
+ componentName = match2[1];
239
+ }
240
+ if (componentName) {
241
+ const sourceFile = componentName === "index" ? "/src/main.tsx" : `/src/pages/${componentName}.tsx`;
242
+ if (this.debug) {
243
+ console.log(` \u{1F4CD} Dev mode: Resolved ${chunkPath} \u2192 ${sourceFile}`);
244
+ }
245
+ return sourceFile;
246
+ }
247
+ if (this.debug) {
248
+ console.log(` \u26A0\uFE0F Dev mode: Could not extract component name from ${chunkPath}, using as-is`);
249
+ }
250
+ return `/${chunkPath}`;
251
+ }
252
+ /**
253
+ * Inject prefetch link into DOM
254
+ */
255
+ injectPrefetchLink(target) {
256
+ if (this.prefetched.has(target.route)) {
257
+ if (this.debug) {
258
+ console.log(` \u23ED\uFE0F Already prefetched: ${target.route}`);
259
+ }
260
+ return;
261
+ }
262
+ const chunkPath = this.resolveChunkPath(target.chunk, target.route);
263
+ const link = document.createElement("link");
264
+ link.rel = "modulepreload";
265
+ link.href = chunkPath;
266
+ link.setAttribute("data-prefetch-route", target.route);
267
+ link.setAttribute("data-prefetch-priority", target.priority);
268
+ link.setAttribute("data-prefetch-probability", target.probability.toString());
269
+ console.groupCollapsed(`\u{1F517} PREFETCH: ${target.route}`);
270
+ console.log(` \u{1F4C4} Page/Route: ${target.route}`);
271
+ console.log(` \u{1F4E6} Main Chunk: ${target.chunk}`);
272
+ console.log(` \u{1F310} Resolved URL: ${window.location.origin}${chunkPath}`);
273
+ console.log(` \u2B50 Priority: ${target.priority}`);
274
+ console.log(` \u{1F4CA} Probability: ${(target.probability * 100).toFixed(1)}%`);
275
+ let totalChunksForThisRoute = 1;
276
+ const injectedLinks = [];
277
+ try {
278
+ document.head.appendChild(link);
279
+ injectedLinks.push(target.chunk);
280
+ console.log(` \u2705 Main chunk link injected: ${target.chunk}`);
281
+ } catch (e) {
282
+ console.error(` \u274C Failed to inject main chunk link:`, e);
283
+ console.groupEnd();
284
+ return;
285
+ }
286
+ if (target.imports && target.imports.length > 0) {
287
+ console.log(` \u{1F4DA} Dependencies (${target.imports.length}):`);
288
+ target.imports.forEach((importChunk, index) => {
289
+ const importId = `import:${importChunk}`;
290
+ if (this.prefetched.has(importId)) {
291
+ console.log(` ${index + 1}. ${importChunk} (already prefetched)`);
292
+ return;
293
+ }
294
+ try {
295
+ const importLink = document.createElement("link");
296
+ importLink.rel = "modulepreload";
297
+ importLink.href = `/${importChunk}`;
298
+ importLink.setAttribute("data-prefetch-import", "true");
299
+ importLink.setAttribute("data-prefetch-parent", target.route);
300
+ document.head.appendChild(importLink);
301
+ this.prefetched.add(importId);
302
+ totalChunksForThisRoute++;
303
+ injectedLinks.push(importChunk);
304
+ console.log(` ${index + 1}. ${importChunk} \u2705`);
305
+ } catch (e) {
306
+ console.error(` ${index + 1}. ${importChunk} \u274C Error:`, e);
307
+ }
308
+ });
309
+ }
310
+ this.prefetched.add(target.route);
311
+ console.log(` \u2705 Total chunks injected: ${totalChunksForThisRoute}`);
312
+ console.log(` \u{1F4C8} Overall prefetched count: ${this.prefetched.size}`);
313
+ if (this.debug) {
314
+ console.log(` DOM Status: ${injectedLinks.length} link tag(s) added to document.head`);
315
+ console.log(` Injected URLs:`, injectedLinks.map((c) => `/${c}`));
316
+ setTimeout(() => {
317
+ const addedLink = document.querySelector(`link[data-prefetch-route="${target.route}"]`);
318
+ if (addedLink) {
319
+ console.log(` \u2714\uFE0F DOM Verification: Link exists`);
320
+ console.log(` href:`, addedLink.href);
321
+ console.log(` as:`, addedLink.getAttribute("as"));
322
+ console.log(` rel:`, addedLink.rel);
323
+ if (addedLink.relList?.contains("modulepreload")) {
324
+ console.log(` \u{1F504} Link has modulepreload rel (will fetch)`);
325
+ }
326
+ } else {
327
+ console.error(` \u274C ERROR: Link tag not found in DOM after 100ms`);
328
+ }
329
+ console.log(` \u{1F4CB} Verifying all injected links in head:`);
330
+ document.querySelectorAll("link[data-prefetch-route], link[data-prefetch-import]").forEach((el, idx) => {
331
+ const isMain = el.hasAttribute("data-prefetch-route");
332
+ const parent = isMain ? el.getAttribute("data-prefetch-route") : el.getAttribute("data-prefetch-parent");
333
+ console.log(` ${idx + 1}. ${el.href} (parent: ${parent})`);
334
+ });
335
+ }, 50);
336
+ }
337
+ console.groupEnd();
338
+ }
339
+ /**
340
+ * Check if prefetching should be performed based on network conditions
341
+ */
342
+ shouldPrefetch() {
343
+ const nav = navigator;
344
+ const connection = nav.connection || nav.mozConnection || nav.webkitConnection;
345
+ if (!connection) {
346
+ return true;
347
+ }
348
+ if (connection.saveData) {
349
+ if (this.debug) console.log(" \u26A0\uFE0F Data Saver enabled");
350
+ return false;
351
+ }
352
+ const slowConnections = ["slow-2g", "2g"];
353
+ if (slowConnections.includes(connection.effectiveType)) {
354
+ if (this.debug) console.log(` \u26A0\uFE0F Slow connection: ${connection.effectiveType}`);
355
+ return false;
356
+ }
357
+ if (connection.type === "cellular" && connection.effectiveType !== "4g") {
358
+ if (this.debug) console.log(" \u26A0\uFE0F Metered connection");
359
+ return false;
360
+ }
361
+ return true;
362
+ }
363
+ /**
364
+ * Initialize IntersectionObserver for 'visible' strategy
365
+ */
366
+ initIntersectionObserver() {
367
+ this.observer = new IntersectionObserver(
368
+ (entries) => {
369
+ entries.forEach((entry) => {
370
+ if (entry.isIntersecting) {
371
+ const route = entry.target.getAttribute("data-prefetch-route");
372
+ if (route && this.config) {
373
+ Object.values(this.config.routes).forEach((routeConfig) => {
374
+ const target = routeConfig.prefetch.find((t) => t.route === route);
375
+ if (target) {
376
+ this.injectPrefetchLink(target);
377
+ }
378
+ });
379
+ }
380
+ }
381
+ });
382
+ },
383
+ {
384
+ rootMargin: "50px"
385
+ // Start prefetch 50px before element is visible
386
+ }
387
+ );
388
+ }
389
+ /**
390
+ * Observe an element for visibility-based prefetching
391
+ */
392
+ observeLink(element, route) {
393
+ if (this.observer) {
394
+ element.setAttribute("data-prefetch-route", route);
395
+ this.observer.observe(element);
396
+ }
397
+ }
398
+ /**
399
+ * Manually trigger prefetch for a specific route
400
+ * Useful for hover events
401
+ */
402
+ prefetchRoute(route) {
403
+ if (!this.config) return;
404
+ Object.values(this.config.routes).forEach((routeConfig) => {
405
+ const target = routeConfig.prefetch.find((t) => t.route === route);
406
+ if (target) {
407
+ this.injectPrefetchLink(target);
408
+ }
409
+ });
410
+ }
411
+ /**
412
+ * Get prefetch statistics
413
+ */
414
+ getStats() {
415
+ return {
416
+ totalPrefetched: this.prefetched.size,
417
+ prefetchedRoutes: Array.from(this.prefetched),
418
+ configLoaded: this.config !== null,
419
+ strategy: this.strategy
420
+ };
421
+ }
422
+ /**
423
+ * Check if a route has been prefetched
424
+ */
425
+ isPrefetched(route) {
426
+ return this.prefetched.has(route);
427
+ }
428
+ /**
429
+ * Clear all prefetch state
430
+ */
431
+ clear() {
432
+ this.prefetched.clear();
433
+ if (this.observer) {
434
+ this.observer.disconnect();
435
+ }
436
+ }
437
+ /**
438
+ * Get all prefetch link elements currently in the DOM
439
+ */
440
+ getActivePrefetchLinks() {
441
+ return Array.from(document.querySelectorAll('link[rel="modulepreload"][data-prefetch-route]'));
442
+ }
443
+ /**
444
+ * Log current state for debugging
445
+ */
446
+ logDebugInfo() {
447
+ console.group("\u{1F41B} Smart Prefetch Debug Info");
448
+ console.log("Strategy:", this.strategy);
449
+ console.log("Config loaded:", this.config !== null);
450
+ console.log("Total prefetch entries:", this.prefetched.size);
451
+ console.log("Prefetched items:", Array.from(this.prefetched));
452
+ const links = this.getActivePrefetchLinks();
453
+ console.log("\n\u{1F517} Active Link Tags in DOM:", links.length);
454
+ if (links.length > 0) {
455
+ console.table(links.map((link) => ({
456
+ route: link.getAttribute("data-prefetch-route"),
457
+ chunk: link.href.replace(window.location.origin + "/", ""),
458
+ priority: link.getAttribute("data-prefetch-priority"),
459
+ probability: link.getAttribute("data-prefetch-probability")
460
+ })));
461
+ }
462
+ if (this.config) {
463
+ console.log("\n\u{1F4CA} Configuration Summary:");
464
+ console.log("Available routes in config:", Object.keys(this.config.routes).length);
465
+ console.log("Config environment:", this.config.environment);
466
+ console.group("\u{1F4CB} All configured routes with prefetch targets:");
467
+ Object.entries(this.config.routes).forEach(([route, data]) => {
468
+ console.group(`${route}`);
469
+ data.prefetch.forEach((t, idx) => {
470
+ console.log(` ${idx + 1}. ${t.route} (${t.priority}, ${(t.probability * 100).toFixed(1)}%) \u2192 ${t.chunk}`);
471
+ });
472
+ console.groupEnd();
473
+ });
474
+ console.groupEnd();
475
+ console.log("\n\u{1F4A1} Current location:", window.location.pathname);
476
+ console.log("\u{1F4A1} Clean route:", window.location.pathname.split("?")[0].split("#")[0]);
477
+ }
478
+ console.groupEnd();
479
+ }
480
+ /**
481
+ * Log all prefetched pages and chunks (summary view)
482
+ */
483
+ logPrefetchSummary() {
484
+ const links = this.getActivePrefetchLinks();
485
+ const routeLinks = links.filter((l) => !l.getAttribute("data-prefetch-import"));
486
+ const dependencyLinks = links.filter((l) => l.getAttribute("data-prefetch-import"));
487
+ console.group("\u{1F4CA} PREFETCH SUMMARY");
488
+ console.log(`Total pages prefetched: ${routeLinks.length}`);
489
+ console.log(`Total dependency chunks: ${dependencyLinks.length}`);
490
+ console.log(`Total overall entries: ${this.prefetched.size}`);
491
+ if (routeLinks.length > 0) {
492
+ console.group("\u{1F4C4} Pages/Routes Prefetched:");
493
+ const pageTable = routeLinks.map((link) => ({
494
+ route: link.getAttribute("data-prefetch-route"),
495
+ chunk: link.href.replace(window.location.origin + "/", ""),
496
+ priority: link.getAttribute("data-prefetch-priority"),
497
+ probability: `${link.getAttribute("data-prefetch-probability")}`
498
+ }));
499
+ console.table(pageTable);
500
+ console.groupEnd();
501
+ }
502
+ if (dependencyLinks.length > 0) {
503
+ console.group("\u{1F4E6} Dependency Chunks Prefetched:");
504
+ const depsTable = dependencyLinks.map((link) => ({
505
+ parentRoute: link.getAttribute("data-prefetch-parent"),
506
+ chunk: link.href.replace(window.location.origin + "/", "")
507
+ }));
508
+ console.table(depsTable);
509
+ console.groupEnd();
510
+ }
511
+ console.groupEnd();
512
+ }
513
+ };
514
+
515
+ // src/frameworks/react/usePrefetch.ts
516
+ var managerInstance = null;
517
+ function usePrefetch() {
518
+ const location = useLocation();
519
+ const initialized = useRef(false);
520
+ useEffect(() => {
521
+ if (!initialized.current) {
522
+ const config = window.__SMART_PREFETCH__ || {};
523
+ const strategy = config.strategy || "hybrid";
524
+ const debug = config.debug || false;
525
+ managerInstance = new PrefetchManager(strategy, debug);
526
+ managerInstance.init();
527
+ window.__FARMART_PREFETCH_MANAGER__ = managerInstance;
528
+ initialized.current = true;
529
+ if (debug) {
530
+ console.log("\u2705 usePrefetch initialized");
531
+ console.log("\u2705 Prefetch manager exposed as window.__FARMART_PREFETCH_MANAGER__");
532
+ }
533
+ }
534
+ }, []);
535
+ useEffect(() => {
536
+ if (managerInstance) {
537
+ managerInstance.prefetch(location.pathname);
538
+ }
539
+ }, [location.pathname]);
540
+ return managerInstance;
541
+ }
542
+ function getPrefetchManager() {
543
+ return managerInstance;
544
+ }
545
+
546
+ // src/frameworks/react/PrefetchLink.tsx
547
+ import React, { useRef as useRef2, useEffect as useEffect2 } from "react";
548
+ import { Link } from "react-router-dom";
549
+ import { jsx } from "react/jsx-runtime";
550
+ var PrefetchLink = React.forwardRef(
551
+ ({ prefetch, to, children, onMouseEnter, ...props }, forwardedRef) => {
552
+ const linkRef = useRef2(null);
553
+ const manager = getPrefetchManager();
554
+ const route = typeof to === "string" ? to : to.pathname || "";
555
+ useEffect2(() => {
556
+ if (prefetch === "visible" && linkRef.current && manager) {
557
+ manager.observeLink(linkRef.current, route);
558
+ }
559
+ }, [prefetch, route, manager]);
560
+ const handleMouseEnter = (e) => {
561
+ if (prefetch === "hover" && manager) {
562
+ manager.prefetchRoute(route);
563
+ }
564
+ if (onMouseEnter) {
565
+ onMouseEnter(e);
566
+ }
567
+ };
568
+ return /* @__PURE__ */ jsx(
569
+ Link,
570
+ {
571
+ ref: (node) => {
572
+ if (node) {
573
+ linkRef.current = node;
574
+ if (typeof forwardedRef === "function") {
575
+ forwardedRef(node);
576
+ } else if (forwardedRef) {
577
+ forwardedRef.current = node;
578
+ }
579
+ }
580
+ },
581
+ to,
582
+ onMouseEnter: handleMouseEnter,
583
+ ...props,
584
+ children
585
+ }
586
+ );
587
+ }
588
+ );
589
+ PrefetchLink.displayName = "PrefetchLink";
590
+
591
+ // src/frameworks/react/PrefetchDebugPanel.tsx
592
+ import { useEffect as useEffect3, useState } from "react";
593
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
594
+ function PrefetchDebugPanel({
595
+ manager,
596
+ position = "bottom-right",
597
+ defaultOpen = false
598
+ }) {
599
+ const [isOpen, setIsOpen] = useState(defaultOpen);
600
+ const [stats, setStats] = useState(null);
601
+ const [links, setLinks] = useState([]);
602
+ useEffect3(() => {
603
+ if (!manager) return;
604
+ const updateStats = () => {
605
+ setStats(manager.getStats());
606
+ const linkElements = manager.getActivePrefetchLinks();
607
+ setLinks(
608
+ linkElements.map((link) => ({
609
+ route: link.getAttribute("data-prefetch-route") || "",
610
+ href: link.href,
611
+ priority: link.getAttribute("data-prefetch-priority") || "",
612
+ probability: link.getAttribute("data-prefetch-probability") || ""
613
+ }))
614
+ );
615
+ };
616
+ updateStats();
617
+ const interval = setInterval(updateStats, 1e3);
618
+ return () => clearInterval(interval);
619
+ }, [manager]);
620
+ if (!manager) {
621
+ return null;
622
+ }
623
+ const positionStyles = {
624
+ "top-left": { top: 10, left: 10 },
625
+ "top-right": { top: 10, right: 10 },
626
+ "bottom-left": { bottom: 10, left: 10 },
627
+ "bottom-right": { bottom: 10, right: 10 }
628
+ };
629
+ const containerStyle = {
630
+ position: "fixed",
631
+ ...positionStyles[position],
632
+ zIndex: 99999,
633
+ fontFamily: "system-ui, -apple-system, sans-serif",
634
+ fontSize: "12px"
635
+ };
636
+ const buttonStyle = {
637
+ background: "#4CAF50",
638
+ color: "white",
639
+ border: "none",
640
+ borderRadius: "50%",
641
+ width: "48px",
642
+ height: "48px",
643
+ cursor: "pointer",
644
+ boxShadow: "0 4px 8px rgba(0,0,0,0.2)",
645
+ display: "flex",
646
+ alignItems: "center",
647
+ justifyContent: "center",
648
+ fontSize: "20px"
649
+ };
650
+ const panelStyle = {
651
+ background: "white",
652
+ border: "1px solid #ddd",
653
+ borderRadius: "8px",
654
+ boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
655
+ padding: "12px",
656
+ minWidth: "320px",
657
+ maxWidth: "400px",
658
+ maxHeight: "500px",
659
+ overflow: "auto",
660
+ marginBottom: "8px"
661
+ };
662
+ const headerStyle = {
663
+ fontWeight: "bold",
664
+ marginBottom: "8px",
665
+ color: "#333",
666
+ borderBottom: "2px solid #4CAF50",
667
+ paddingBottom: "4px"
668
+ };
669
+ const statStyle = {
670
+ display: "flex",
671
+ justifyContent: "space-between",
672
+ padding: "4px 0",
673
+ borderBottom: "1px solid #eee"
674
+ };
675
+ const linkStyle = {
676
+ background: "#f5f5f5",
677
+ padding: "8px",
678
+ borderRadius: "4px",
679
+ marginBottom: "8px",
680
+ fontSize: "11px"
681
+ };
682
+ return /* @__PURE__ */ jsxs("div", { style: containerStyle, children: [
683
+ isOpen && stats && /* @__PURE__ */ jsxs("div", { style: panelStyle, children: [
684
+ /* @__PURE__ */ jsx2("div", { style: headerStyle, children: "\u{1F680} Smart Prefetch Debug" }),
685
+ /* @__PURE__ */ jsxs("div", { style: { marginBottom: "12px" }, children: [
686
+ /* @__PURE__ */ jsxs("div", { style: statStyle, children: [
687
+ /* @__PURE__ */ jsx2("span", { children: "Strategy:" }),
688
+ /* @__PURE__ */ jsx2("strong", { children: stats.strategy })
689
+ ] }),
690
+ /* @__PURE__ */ jsxs("div", { style: statStyle, children: [
691
+ /* @__PURE__ */ jsx2("span", { children: "Config Loaded:" }),
692
+ /* @__PURE__ */ jsx2("strong", { children: stats.configLoaded ? "\u2705" : "\u274C" })
693
+ ] }),
694
+ /* @__PURE__ */ jsxs("div", { style: statStyle, children: [
695
+ /* @__PURE__ */ jsx2("span", { children: "Total Prefetched:" }),
696
+ /* @__PURE__ */ jsx2("strong", { children: stats.totalPrefetched })
697
+ ] }),
698
+ /* @__PURE__ */ jsxs("div", { style: statStyle, children: [
699
+ /* @__PURE__ */ jsx2("span", { children: "Link Tags in DOM:" }),
700
+ /* @__PURE__ */ jsx2("strong", { children: links.length })
701
+ ] })
702
+ ] }),
703
+ stats.prefetchedRoutes.length > 0 && /* @__PURE__ */ jsxs("div", { children: [
704
+ /* @__PURE__ */ jsx2("div", { style: { ...headerStyle, fontSize: "11px" }, children: "Prefetched Routes:" }),
705
+ /* @__PURE__ */ jsx2("div", { style: { fontSize: "11px", color: "#666", marginBottom: "8px" }, children: stats.prefetchedRoutes.join(", ") })
706
+ ] }),
707
+ links.length > 0 && /* @__PURE__ */ jsxs("div", { children: [
708
+ /* @__PURE__ */ jsx2("div", { style: { ...headerStyle, fontSize: "11px" }, children: "Active Link Tags:" }),
709
+ links.map((link, i) => /* @__PURE__ */ jsxs("div", { style: linkStyle, children: [
710
+ /* @__PURE__ */ jsx2("div", { children: /* @__PURE__ */ jsx2("strong", { children: link.route }) }),
711
+ /* @__PURE__ */ jsxs("div", { style: { color: "#666", marginTop: "4px" }, children: [
712
+ "Priority: ",
713
+ link.priority,
714
+ " | Prob: ",
715
+ (parseFloat(link.probability) * 100).toFixed(1),
716
+ "%"
717
+ ] }),
718
+ /* @__PURE__ */ jsx2("div", { style: { color: "#999", marginTop: "2px", wordBreak: "break-all" }, children: link.href.split("/").pop() })
719
+ ] }, i))
720
+ ] }),
721
+ /* @__PURE__ */ jsx2(
722
+ "button",
723
+ {
724
+ onClick: () => {
725
+ manager.logDebugInfo();
726
+ },
727
+ style: {
728
+ width: "100%",
729
+ padding: "8px",
730
+ background: "#2196F3",
731
+ color: "white",
732
+ border: "none",
733
+ borderRadius: "4px",
734
+ cursor: "pointer",
735
+ marginTop: "8px"
736
+ },
737
+ children: "Log Debug Info to Console"
738
+ }
739
+ )
740
+ ] }),
741
+ /* @__PURE__ */ jsx2(
742
+ "button",
743
+ {
744
+ style: buttonStyle,
745
+ onClick: () => setIsOpen(!isOpen),
746
+ title: "Smart Prefetch Debug Panel",
747
+ children: "\u{1F517}"
748
+ }
749
+ )
750
+ ] });
751
+ }
752
+ export {
753
+ PrefetchDebugPanel,
754
+ PrefetchLink,
755
+ getPrefetchManager,
756
+ usePrefetch
757
+ };
758
+ //# sourceMappingURL=index.js.map