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