@flight-framework/router 0.3.1 → 0.3.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.
@@ -1,492 +0,0 @@
1
- var __getOwnPropNames = Object.getOwnPropertyNames;
2
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
- }) : x)(function(x) {
5
- if (typeof require !== "undefined") return require.apply(this, arguments);
6
- throw Error('Dynamic require of "' + x + '" is not supported');
7
- });
8
- var __commonJS = (cb, mod) => function __require2() {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
- };
11
-
12
- // src/context.ts
13
- var isBrowser = typeof window !== "undefined";
14
- var currentContext = {
15
- path: "/",
16
- searchParams: new URLSearchParams(),
17
- navigate: () => {
18
- },
19
- back: () => {
20
- },
21
- forward: () => {
22
- }
23
- };
24
- var subscribers = /* @__PURE__ */ new Set();
25
- function subscribe(callback) {
26
- subscribers.add(callback);
27
- return () => subscribers.delete(callback);
28
- }
29
- function getRouterContext() {
30
- return currentContext;
31
- }
32
- function updateContext(updates) {
33
- currentContext = { ...currentContext, ...updates };
34
- subscribers.forEach((cb) => cb(currentContext));
35
- }
36
- function navigateTo(to, options = {}) {
37
- if (!isBrowser) return;
38
- const { replace = false, scroll = true, state } = options;
39
- if (replace) {
40
- window.history.replaceState(state ?? null, "", to);
41
- } else {
42
- window.history.pushState(state ?? null, "", to);
43
- }
44
- const url = new URL(to, window.location.origin);
45
- updateContext({
46
- path: url.pathname,
47
- searchParams: url.searchParams
48
- });
49
- if (scroll) {
50
- window.scrollTo({ top: 0, left: 0, behavior: "instant" });
51
- }
52
- }
53
- function initRouter(options = {}) {
54
- const { initialPath, basePath = "" } = options;
55
- let path;
56
- let searchParams;
57
- if (isBrowser) {
58
- path = window.location.pathname;
59
- searchParams = new URLSearchParams(window.location.search);
60
- } else {
61
- path = initialPath || "/";
62
- searchParams = new URLSearchParams();
63
- }
64
- if (basePath && path.startsWith(basePath)) {
65
- path = path.slice(basePath.length) || "/";
66
- }
67
- currentContext = {
68
- path,
69
- searchParams,
70
- navigate: navigateTo,
71
- back: () => isBrowser && window.history.back(),
72
- forward: () => isBrowser && window.history.forward()
73
- };
74
- if (isBrowser) {
75
- window.addEventListener("popstate", () => {
76
- updateContext({
77
- path: window.location.pathname,
78
- searchParams: new URLSearchParams(window.location.search)
79
- });
80
- });
81
- const originalPushState = history.pushState.bind(history);
82
- const originalReplaceState = history.replaceState.bind(history);
83
- history.pushState = function(state, unused, url) {
84
- originalPushState(state, unused, url);
85
- if (url) {
86
- const newUrl = new URL(url.toString(), window.location.origin);
87
- updateContext({
88
- path: newUrl.pathname,
89
- searchParams: newUrl.searchParams
90
- });
91
- }
92
- };
93
- history.replaceState = function(state, unused, url) {
94
- originalReplaceState(state, unused, url);
95
- if (url) {
96
- const newUrl = new URL(url.toString(), window.location.origin);
97
- updateContext({
98
- path: newUrl.pathname,
99
- searchParams: newUrl.searchParams
100
- });
101
- }
102
- };
103
- }
104
- }
105
- var initialized = false;
106
- if (isBrowser && !initialized) {
107
- initialized = true;
108
- initRouter();
109
- }
110
- var RouterContext = null;
111
- var RouterProvider = null;
112
- var useRouter = getRouterContext;
113
- if (typeof globalThis !== "undefined") {
114
- try {
115
- const React = globalThis.React;
116
- if (React?.createContext) {
117
- const { createContext, useState, useEffect, useContext } = React;
118
- const ReactRouterContext = createContext(currentContext);
119
- RouterContext = ReactRouterContext;
120
- RouterProvider = function FlightRouterProvider({
121
- children,
122
- initialPath,
123
- basePath = ""
124
- }) {
125
- const [routerState, setRouterState] = useState(() => {
126
- const path = isBrowser ? window.location.pathname : initialPath || "/";
127
- const searchParams = isBrowser ? new URLSearchParams(window.location.search) : new URLSearchParams();
128
- return {
129
- path: basePath && path.startsWith(basePath) ? path.slice(basePath.length) || "/" : path,
130
- searchParams,
131
- navigate: navigateTo,
132
- back: () => isBrowser && window.history.back(),
133
- forward: () => isBrowser && window.history.forward()
134
- };
135
- });
136
- useEffect(() => {
137
- if (!isBrowser) return;
138
- const handlePopState = () => {
139
- let path = window.location.pathname;
140
- if (basePath && path.startsWith(basePath)) {
141
- path = path.slice(basePath.length) || "/";
142
- }
143
- setRouterState((prev) => ({
144
- ...prev,
145
- path,
146
- searchParams: new URLSearchParams(window.location.search)
147
- }));
148
- };
149
- window.addEventListener("popstate", handlePopState);
150
- return () => window.removeEventListener("popstate", handlePopState);
151
- }, [basePath]);
152
- useEffect(() => {
153
- return subscribe((ctx) => {
154
- setRouterState((prev) => ({
155
- ...prev,
156
- path: ctx.path,
157
- searchParams: ctx.searchParams
158
- }));
159
- });
160
- }, []);
161
- return React.createElement(
162
- ReactRouterContext.Provider,
163
- { value: routerState },
164
- children
165
- );
166
- };
167
- useRouter = function useFlightRouter() {
168
- return useContext(ReactRouterContext);
169
- };
170
- }
171
- } catch {
172
- }
173
- }
174
-
175
- // src/prefetch.ts
176
- var isBrowser2 = typeof window !== "undefined";
177
- var supportsIntersectionObserver = isBrowser2 && "IntersectionObserver" in window;
178
- var prefetchedUrls = /* @__PURE__ */ new Set();
179
- var prefetchingUrls = /* @__PURE__ */ new Set();
180
- var viewportObservers = /* @__PURE__ */ new Map();
181
- function prefetch(href, options = {}) {
182
- if (!isBrowser2) return;
183
- const {
184
- priority = "auto",
185
- includeModules = true,
186
- includeData = false
187
- } = options;
188
- const url = normalizeUrl(href);
189
- if (prefetchedUrls.has(url) || prefetchingUrls.has(url)) {
190
- return;
191
- }
192
- prefetchingUrls.add(url);
193
- createPrefetchLink(url, "document", priority);
194
- if (includeModules) {
195
- prefetchModules(url, priority);
196
- }
197
- if (includeData) {
198
- prefetchData(url, priority);
199
- }
200
- prefetchedUrls.add(url);
201
- prefetchingUrls.delete(url);
202
- }
203
- function prefetchAll(hrefs, options = {}) {
204
- for (const href of hrefs) {
205
- prefetch(href, options);
206
- }
207
- }
208
- function isPrefetched(href) {
209
- return prefetchedUrls.has(normalizeUrl(href));
210
- }
211
- function clearPrefetchCache() {
212
- prefetchedUrls.clear();
213
- prefetchingUrls.clear();
214
- }
215
- function createPrefetchLink(href, as, priority) {
216
- if (!isBrowser2) return null;
217
- const existing = document.querySelector(
218
- `link[rel="prefetch"][href="${href}"], link[rel="modulepreload"][href="${href}"]`
219
- );
220
- if (existing) return existing;
221
- const link = document.createElement("link");
222
- if (as === "script") {
223
- link.rel = "modulepreload";
224
- } else {
225
- link.rel = "prefetch";
226
- link.as = as;
227
- }
228
- link.href = href;
229
- if (priority !== "auto" && "fetchPriority" in link) {
230
- link.fetchPriority = priority;
231
- }
232
- if (priority === "low" && "requestIdleCallback" in window) {
233
- window.requestIdleCallback(() => {
234
- document.head.appendChild(link);
235
- });
236
- } else {
237
- document.head.appendChild(link);
238
- }
239
- return link;
240
- }
241
- function prefetchModules(href, priority) {
242
- const manifest = window.__FLIGHT_MANIFEST__;
243
- if (!manifest?.routes) return;
244
- const routeModules = manifest.routes[href];
245
- if (!routeModules) return;
246
- for (const module of routeModules) {
247
- createPrefetchLink(module, "script", priority);
248
- }
249
- }
250
- function prefetchData(href, priority) {
251
- const dataUrl = `/_flight/data${href === "/" ? "/index" : href}.json`;
252
- createPrefetchLink(dataUrl, "fetch", priority);
253
- }
254
- var sharedObserver = null;
255
- var observerCallbacks = /* @__PURE__ */ new Map();
256
- function getViewportObserver() {
257
- if (!supportsIntersectionObserver) return null;
258
- if (!sharedObserver) {
259
- sharedObserver = new IntersectionObserver(
260
- (entries) => {
261
- for (const entry of entries) {
262
- if (entry.isIntersecting) {
263
- const callback = observerCallbacks.get(entry.target);
264
- if (callback) {
265
- callback();
266
- sharedObserver?.unobserve(entry.target);
267
- observerCallbacks.delete(entry.target);
268
- }
269
- }
270
- }
271
- },
272
- {
273
- // Start prefetching when link is 25% visible or within 100px of viewport
274
- rootMargin: "100px",
275
- threshold: 0.25
276
- }
277
- );
278
- }
279
- return sharedObserver;
280
- }
281
- function observeForPrefetch(element, href) {
282
- if (!supportsIntersectionObserver) {
283
- return () => {
284
- };
285
- }
286
- const observer = getViewportObserver();
287
- if (!observer) return () => {
288
- };
289
- const callback = () => {
290
- prefetch(href, { priority: "low" });
291
- };
292
- observerCallbacks.set(element, callback);
293
- observer.observe(element);
294
- const cleanup = () => {
295
- observer.unobserve(element);
296
- observerCallbacks.delete(element);
297
- viewportObservers.delete(element);
298
- };
299
- viewportObservers.set(element, cleanup);
300
- return cleanup;
301
- }
302
- function setupIntentPrefetch(element, href) {
303
- if (!isBrowser2) return () => {
304
- };
305
- let prefetchTriggered = false;
306
- const handleIntent = () => {
307
- if (!prefetchTriggered) {
308
- prefetchTriggered = true;
309
- prefetch(href, { priority: "auto" });
310
- }
311
- };
312
- element.addEventListener("mouseenter", handleIntent, { passive: true });
313
- element.addEventListener("focus", handleIntent, { passive: true });
314
- element.addEventListener("touchstart", handleIntent, { passive: true });
315
- return () => {
316
- element.removeEventListener("mouseenter", handleIntent);
317
- element.removeEventListener("focus", handleIntent);
318
- element.removeEventListener("touchstart", handleIntent);
319
- };
320
- }
321
- function normalizeUrl(href) {
322
- if (isBrowser2 && !href.startsWith("http")) {
323
- try {
324
- const url = new URL(href, window.location.origin);
325
- return url.pathname + url.search;
326
- } catch {
327
- return href;
328
- }
329
- }
330
- return href;
331
- }
332
-
333
- // src/prefetch-links.ts
334
- var isBrowser3 = typeof window !== "undefined";
335
- var PrefetchPageLinks = null;
336
- if (typeof globalThis !== "undefined") {
337
- try {
338
- const React = globalThis.React;
339
- if (React?.createElement && "useEffect" in React) {
340
- const { useEffect, useState } = React;
341
- PrefetchPageLinks = function FlightPrefetchPageLinks({
342
- page,
343
- options = {}
344
- }) {
345
- const [shouldRender, setShouldRender] = useState(false);
346
- useEffect(() => {
347
- if (!isBrowser3) return;
348
- if (isPrefetched(page)) {
349
- return;
350
- }
351
- prefetch(page, {
352
- priority: "low",
353
- includeModules: true,
354
- ...options
355
- });
356
- setShouldRender(false);
357
- }, [page, options]);
358
- return null;
359
- };
360
- }
361
- } catch {
362
- }
363
- }
364
- function prefetchPages(pages, options = {}) {
365
- if (!isBrowser3) return;
366
- for (const page of pages) {
367
- if (!isPrefetched(page)) {
368
- prefetch(page, {
369
- priority: "low",
370
- ...options
371
- });
372
- }
373
- }
374
- }
375
- function prefetchWhenIdle(page, options = {}) {
376
- if (!isBrowser3) return;
377
- const doPrefetch = () => {
378
- if (!isPrefetched(page)) {
379
- prefetch(page, {
380
- priority: "low",
381
- ...options
382
- });
383
- }
384
- };
385
- if ("requestIdleCallback" in window) {
386
- window.requestIdleCallback(doPrefetch, { timeout: 3e3 });
387
- } else {
388
- setTimeout(doPrefetch, 100);
389
- }
390
- }
391
-
392
- // src/navigate.ts
393
- var isBrowser4 = typeof window !== "undefined";
394
- function navigate(to, options = {}) {
395
- const { navigate: routerNavigate } = getRouterContext();
396
- routerNavigate(to, options);
397
- }
398
- function patternToRegex(pattern) {
399
- const paramNames = [];
400
- let regexStr = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\\\[\.\.\.(\w+)\\\]/g, (_, name) => {
401
- paramNames.push(name);
402
- return "(.+)";
403
- }).replace(/\\\[(\w+)\\\]/g, (_, name) => {
404
- paramNames.push(name);
405
- return "([^/]+)";
406
- }).replace(/:(\w+)/g, (_, name) => {
407
- paramNames.push(name);
408
- return "([^/]+)";
409
- });
410
- regexStr = `^${regexStr}$`;
411
- return {
412
- regex: new RegExp(regexStr),
413
- paramNames
414
- };
415
- }
416
- function matchRoute(pathname, pattern) {
417
- const { regex, paramNames } = patternToRegex(pattern);
418
- const match = pathname.match(regex);
419
- if (!match) {
420
- return { matched: false, params: {} };
421
- }
422
- const params = {};
423
- paramNames.forEach((name, index) => {
424
- params[name] = match[index + 1] || "";
425
- });
426
- return { matched: true, params };
427
- }
428
- function parseParams(pathname, pattern) {
429
- const { params } = matchRoute(pathname, pattern);
430
- return params;
431
- }
432
- function findRoute(pathname, routes) {
433
- for (const route of routes) {
434
- const { matched, params } = matchRoute(pathname, route.path);
435
- if (matched) {
436
- return {
437
- route,
438
- params,
439
- pathname
440
- };
441
- }
442
- }
443
- return null;
444
- }
445
- function generatePath(pattern, params = {}) {
446
- let path = pattern;
447
- path = path.replace(/\[(\w+)\]/g, (_, name) => {
448
- return params[name] || "";
449
- });
450
- path = path.replace(/:(\w+)/g, (_, name) => {
451
- return params[name] || "";
452
- });
453
- return path;
454
- }
455
- function isActive(pattern) {
456
- const { path } = getRouterContext();
457
- const { matched } = matchRoute(path, pattern);
458
- return matched;
459
- }
460
- function redirect(url) {
461
- if (isBrowser4) {
462
- window.location.href = url;
463
- }
464
- throw new Error(`Redirect to: ${url}`);
465
- }
466
-
467
- export {
468
- __require,
469
- __commonJS,
470
- subscribe,
471
- getRouterContext,
472
- initRouter,
473
- RouterContext,
474
- RouterProvider,
475
- useRouter,
476
- prefetch,
477
- prefetchAll,
478
- isPrefetched,
479
- clearPrefetchCache,
480
- observeForPrefetch,
481
- setupIntentPrefetch,
482
- PrefetchPageLinks,
483
- prefetchPages,
484
- prefetchWhenIdle,
485
- navigate,
486
- matchRoute,
487
- parseParams,
488
- findRoute,
489
- generatePath,
490
- isActive,
491
- redirect
492
- };