@rangojs/router 0.0.0-experimental.c873df95 → 0.0.0-experimental.c8906ead
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 +188 -35
- package/dist/bin/rango.js +130 -47
- package/dist/vite/index.js +1884 -537
- package/dist/vite/index.js.bak +5448 -0
- package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
- package/package.json +7 -5
- package/skills/breadcrumbs/SKILL.md +3 -1
- package/skills/cache-guide/SKILL.md +32 -0
- package/skills/caching/SKILL.md +8 -0
- package/skills/handler-use/SKILL.md +362 -0
- package/skills/hooks/SKILL.md +33 -20
- package/skills/i18n/SKILL.md +276 -0
- package/skills/intercept/SKILL.md +20 -0
- package/skills/layout/SKILL.md +22 -0
- package/skills/links/SKILL.md +93 -17
- package/skills/loader/SKILL.md +123 -46
- package/skills/middleware/SKILL.md +36 -3
- package/skills/migrate-nextjs/SKILL.md +562 -0
- package/skills/migrate-react-router/SKILL.md +769 -0
- package/skills/parallel/SKILL.md +133 -0
- package/skills/prerender/SKILL.md +110 -68
- package/skills/rango/SKILL.md +26 -22
- package/skills/response-routes/SKILL.md +8 -0
- package/skills/route/SKILL.md +75 -0
- package/skills/router-setup/SKILL.md +87 -2
- package/skills/server-actions/SKILL.md +739 -0
- package/skills/streams-and-websockets/SKILL.md +283 -0
- package/skills/typesafety/SKILL.md +19 -1
- package/src/__internal.ts +1 -1
- package/src/browser/app-shell.ts +52 -0
- package/src/browser/app-version.ts +14 -0
- package/src/browser/event-controller.ts +44 -4
- package/src/browser/navigation-bridge.ts +95 -7
- package/src/browser/navigation-client.ts +128 -53
- package/src/browser/navigation-store.ts +68 -9
- package/src/browser/partial-update.ts +83 -13
- package/src/browser/prefetch/cache.ts +129 -21
- package/src/browser/prefetch/fetch.ts +156 -18
- package/src/browser/prefetch/queue.ts +92 -29
- package/src/browser/prefetch/resource-ready.ts +77 -0
- package/src/browser/rango-state.ts +53 -13
- package/src/browser/react/Link.tsx +72 -8
- package/src/browser/react/NavigationProvider.tsx +82 -21
- package/src/browser/react/context.ts +7 -2
- package/src/browser/react/filter-segment-order.ts +51 -7
- package/src/browser/react/use-handle.ts +9 -58
- package/src/browser/react/use-navigation.ts +22 -2
- package/src/browser/react/use-params.ts +17 -4
- package/src/browser/react/use-router.ts +29 -9
- package/src/browser/react/use-segments.ts +11 -8
- package/src/browser/rsc-router.tsx +60 -9
- package/src/browser/scroll-restoration.ts +10 -8
- package/src/browser/segment-reconciler.ts +36 -14
- package/src/browser/server-action-bridge.ts +8 -6
- package/src/browser/types.ts +46 -5
- package/src/build/generate-manifest.ts +6 -6
- package/src/build/generate-route-types.ts +3 -0
- package/src/build/route-trie.ts +52 -25
- package/src/build/route-types/include-resolution.ts +8 -1
- package/src/build/route-types/router-processing.ts +211 -72
- package/src/build/route-types/scan-filter.ts +8 -1
- package/src/cache/cache-scope.ts +46 -5
- package/src/cache/cf/cf-cache-store.ts +5 -7
- package/src/cache/taint.ts +55 -0
- package/src/client.tsx +84 -230
- package/src/context-var.ts +72 -2
- package/src/handle.ts +40 -0
- package/src/index.rsc.ts +6 -1
- package/src/index.ts +49 -6
- package/src/outlet-context.ts +1 -1
- package/src/prerender/store.ts +5 -4
- package/src/prerender.ts +138 -77
- package/src/response-utils.ts +28 -0
- package/src/reverse.ts +28 -2
- package/src/route-definition/dsl-helpers.ts +210 -35
- package/src/route-definition/helpers-types.ts +73 -20
- package/src/route-definition/index.ts +3 -0
- package/src/route-definition/redirect.ts +9 -1
- package/src/route-definition/resolve-handler-use.ts +155 -0
- package/src/route-types.ts +18 -0
- package/src/router/content-negotiation.ts +100 -1
- package/src/router/handler-context.ts +102 -25
- package/src/router/intercept-resolution.ts +9 -4
- package/src/router/lazy-includes.ts +6 -6
- package/src/router/loader-resolution.ts +159 -21
- package/src/router/manifest.ts +22 -13
- package/src/router/match-api.ts +128 -192
- package/src/router/match-handlers.ts +1 -0
- package/src/router/match-middleware/background-revalidation.ts +12 -1
- package/src/router/match-middleware/cache-lookup.ts +40 -13
- package/src/router/match-middleware/cache-store.ts +21 -4
- package/src/router/match-middleware/segment-resolution.ts +53 -0
- package/src/router/match-result.ts +121 -18
- package/src/router/middleware-types.ts +20 -33
- package/src/router/middleware.ts +56 -12
- package/src/router/navigation-snapshot.ts +182 -0
- package/src/router/pattern-matching.ts +101 -17
- package/src/router/prerender-match.ts +110 -10
- package/src/router/preview-match.ts +30 -102
- package/src/router/request-classification.ts +310 -0
- package/src/router/revalidation.ts +15 -1
- package/src/router/route-snapshot.ts +245 -0
- package/src/router/router-context.ts +1 -0
- package/src/router/router-interfaces.ts +36 -4
- package/src/router/router-options.ts +37 -11
- package/src/router/segment-resolution/fresh.ts +88 -9
- package/src/router/segment-resolution/helpers.ts +29 -24
- package/src/router/segment-resolution/revalidation.ts +219 -108
- package/src/router/trie-matching.ts +18 -13
- package/src/router/types.ts +1 -0
- package/src/router/url-params.ts +49 -0
- package/src/router.ts +55 -7
- package/src/rsc/handler.ts +478 -374
- package/src/rsc/helpers.ts +69 -41
- package/src/rsc/loader-fetch.ts +23 -3
- package/src/rsc/manifest-init.ts +5 -1
- package/src/rsc/progressive-enhancement.ts +18 -2
- package/src/rsc/response-route-handler.ts +14 -1
- package/src/rsc/rsc-rendering.ts +20 -1
- package/src/rsc/server-action.ts +12 -0
- package/src/rsc/ssr-setup.ts +2 -2
- package/src/rsc/types.ts +15 -1
- package/src/segment-content-promise.ts +67 -0
- package/src/segment-loader-promise.ts +122 -0
- package/src/segment-system.tsx +11 -61
- package/src/server/context.ts +76 -4
- package/src/server/handle-store.ts +19 -0
- package/src/server/loader-registry.ts +9 -8
- package/src/server/request-context.ts +185 -57
- package/src/ssr/index.tsx +8 -1
- package/src/static-handler.ts +18 -6
- package/src/types/cache-types.ts +4 -4
- package/src/types/handler-context.ts +47 -56
- package/src/types/loader-types.ts +41 -15
- package/src/types/request-scope.ts +126 -0
- package/src/types/route-entry.ts +12 -1
- package/src/types/segments.ts +18 -1
- package/src/urls/include-helper.ts +24 -14
- package/src/urls/path-helper-types.ts +39 -6
- package/src/urls/path-helper.ts +47 -12
- package/src/urls/pattern-types.ts +12 -0
- package/src/urls/response-types.ts +18 -16
- package/src/use-loader.tsx +77 -5
- package/src/vite/debug.ts +184 -0
- package/src/vite/discovery/bundle-postprocess.ts +30 -33
- package/src/vite/discovery/discover-routers.ts +36 -4
- package/src/vite/discovery/gate-state.ts +171 -0
- package/src/vite/discovery/prerender-collection.ts +175 -74
- package/src/vite/discovery/self-gen-tracking.ts +27 -1
- package/src/vite/discovery/state.ts +13 -4
- package/src/vite/index.ts +4 -0
- package/src/vite/plugin-types.ts +60 -5
- package/src/vite/plugins/cjs-to-esm.ts +5 -0
- package/src/vite/plugins/client-ref-dedup.ts +16 -0
- package/src/vite/plugins/client-ref-hashing.ts +16 -4
- package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
- package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
- package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
- package/src/vite/plugins/expose-action-id.ts +52 -28
- package/src/vite/plugins/expose-id-utils.ts +12 -0
- package/src/vite/plugins/expose-ids/handler-transform.ts +30 -0
- package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
- package/src/vite/plugins/expose-internal-ids.ts +563 -316
- package/src/vite/plugins/performance-tracks.ts +96 -0
- package/src/vite/plugins/refresh-cmd.ts +88 -26
- package/src/vite/plugins/use-cache-transform.ts +56 -43
- package/src/vite/plugins/version-injector.ts +37 -11
- package/src/vite/rango.ts +63 -11
- package/src/vite/router-discovery.ts +732 -86
- package/src/vite/utils/banner.ts +1 -1
- package/src/vite/utils/package-resolution.ts +41 -1
- package/src/vite/utils/prerender-utils.ts +38 -5
- package/src/vite/utils/shared-utils.ts +3 -2
package/src/segment-system.tsx
CHANGED
|
@@ -2,11 +2,7 @@ import * as React from "react";
|
|
|
2
2
|
import { createElement, type ReactNode, type ComponentType } from "react";
|
|
3
3
|
import { OutletProvider } from "./client.js";
|
|
4
4
|
import { MountContextProvider } from "./browser/react/mount-context.js";
|
|
5
|
-
import type {
|
|
6
|
-
ResolvedSegment,
|
|
7
|
-
LoaderDataResult,
|
|
8
|
-
RootLayoutProps,
|
|
9
|
-
} from "./types.js";
|
|
5
|
+
import type { ResolvedSegment, RootLayoutProps } from "./types.js";
|
|
10
6
|
import { isLoaderDataResult } from "./types.js";
|
|
11
7
|
import { invariant } from "./errors.js";
|
|
12
8
|
import {
|
|
@@ -14,6 +10,8 @@ import {
|
|
|
14
10
|
LoaderBoundary,
|
|
15
11
|
} from "./route-content-wrapper.js";
|
|
16
12
|
import { RootErrorBoundary } from "./root-error-boundary.js";
|
|
13
|
+
import { getMemoizedContentPromise } from "./segment-content-promise.js";
|
|
14
|
+
import { getMemoizedLoaderPromise } from "./segment-loader-promise.js";
|
|
17
15
|
|
|
18
16
|
// ViewTransition is only available in React experimental.
|
|
19
17
|
// Access via namespace import to avoid compile-time errors on stable React.
|
|
@@ -61,20 +59,6 @@ function restoreParallelLoaderMarkers(
|
|
|
61
59
|
return nextSegments ?? segments;
|
|
62
60
|
}
|
|
63
61
|
|
|
64
|
-
function hasSameReferences(a: unknown[] | undefined, b: unknown[]): boolean {
|
|
65
|
-
if (!a || a.length !== b.length) {
|
|
66
|
-
return false;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
for (let i = 0; i < a.length; i++) {
|
|
70
|
-
if (a[i] !== b[i]) {
|
|
71
|
-
return false;
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
return true;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
62
|
/**
|
|
79
63
|
* Resolve loader data from raw results, unwrapping LoaderDataResult wrappers
|
|
80
64
|
*/
|
|
@@ -278,10 +262,7 @@ export async function renderSegments(
|
|
|
278
262
|
loading !== null && loading !== undefined && loading !== false
|
|
279
263
|
? createElement(RouteContentWrapper, {
|
|
280
264
|
key: `suspense-loading-${id}`,
|
|
281
|
-
content:
|
|
282
|
-
resolvedComponent instanceof Promise
|
|
283
|
-
? resolvedComponent
|
|
284
|
-
: Promise.resolve(resolvedComponent),
|
|
265
|
+
content: getMemoizedContentPromise(resolvedComponent),
|
|
285
266
|
fallback: loading,
|
|
286
267
|
segmentId: id,
|
|
287
268
|
})
|
|
@@ -305,16 +286,7 @@ export async function renderSegments(
|
|
|
305
286
|
|
|
306
287
|
// Prepare loader data if there are loaders
|
|
307
288
|
const loaderIds = loaderEntries.map((loader) => loader.loaderId!);
|
|
308
|
-
const loaderDataPromise =
|
|
309
|
-
loaderEntries.length > 0
|
|
310
|
-
? Promise.all(
|
|
311
|
-
loaderEntries.map((loader) =>
|
|
312
|
-
loader.loaderData instanceof Promise
|
|
313
|
-
? loader.loaderData
|
|
314
|
-
: Promise.resolve(loader.loaderData),
|
|
315
|
-
),
|
|
316
|
-
)
|
|
317
|
-
: Promise.resolve([]);
|
|
289
|
+
const loaderDataPromise = getMemoizedLoaderPromise(loaderEntries);
|
|
318
290
|
|
|
319
291
|
// Use LoaderBoundary when loading is defined to maintain consistent tree structure
|
|
320
292
|
// This ensures cached segments (which may not have loader segments) have the same
|
|
@@ -396,34 +368,12 @@ export async function renderSegments(
|
|
|
396
368
|
continue;
|
|
397
369
|
}
|
|
398
370
|
|
|
399
|
-
|
|
400
|
-
const
|
|
401
|
-
p.
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
hasSameReferences(p.parallelLoaderSources, parallelLoaderSources);
|
|
406
|
-
|
|
407
|
-
const parallelLoaderDataPromise = shouldReuseParallelPromise
|
|
408
|
-
? p.loaderDataPromise
|
|
409
|
-
: forceAwait || isAction
|
|
410
|
-
? await Promise.all(
|
|
411
|
-
ownedLoaders.map((l) =>
|
|
412
|
-
l.loaderData instanceof Promise
|
|
413
|
-
? l.loaderData
|
|
414
|
-
: Promise.resolve(l.loaderData),
|
|
415
|
-
),
|
|
416
|
-
)
|
|
417
|
-
: Promise.all(
|
|
418
|
-
ownedLoaders.map((l) =>
|
|
419
|
-
l.loaderData instanceof Promise
|
|
420
|
-
? l.loaderData
|
|
421
|
-
: Promise.resolve(l.loaderData),
|
|
422
|
-
),
|
|
423
|
-
);
|
|
424
|
-
|
|
425
|
-
p.loaderDataPromise = parallelLoaderDataPromise;
|
|
426
|
-
p.parallelLoaderSources = parallelLoaderSources;
|
|
371
|
+
p.loaderIds = ownedLoaders.map((l) => l.loaderId!);
|
|
372
|
+
const aggregated = getMemoizedLoaderPromise(ownedLoaders);
|
|
373
|
+
p.loaderDataPromise =
|
|
374
|
+
(forceAwait || isAction) && aggregated instanceof Promise
|
|
375
|
+
? await aggregated
|
|
376
|
+
: aggregated;
|
|
427
377
|
}
|
|
428
378
|
}
|
|
429
379
|
|
package/src/server/context.ts
CHANGED
|
@@ -191,8 +191,12 @@ export type EntryData =
|
|
|
191
191
|
/** Original PrerenderHandlerDefinition (for build-time getParams access) */
|
|
192
192
|
prerenderDef?: {
|
|
193
193
|
getParams?: (ctx: any) => Promise<any[]> | any[];
|
|
194
|
-
options?: {
|
|
194
|
+
options?: { concurrency?: number };
|
|
195
195
|
};
|
|
196
|
+
/** Set when route is wrapped with Passthrough() — has a separate live handler */
|
|
197
|
+
isPassthrough?: true;
|
|
198
|
+
/** Live handler for runtime fallback (only set on Passthrough routes) */
|
|
199
|
+
liveHandler?: Handler<any, any, any>;
|
|
196
200
|
/** Set when handler is a Static definition (build-time only) */
|
|
197
201
|
isStaticPrerender?: true;
|
|
198
202
|
/** Static handler $$id for build-time store lookup */
|
|
@@ -273,6 +277,25 @@ interface HelperContext {
|
|
|
273
277
|
string,
|
|
274
278
|
import("../cache/profile-registry.js").CacheProfile
|
|
275
279
|
>;
|
|
280
|
+
/** True when resolving handlers inside a cache() DSL boundary.
|
|
281
|
+
* Read by ctx.get() to guard non-cacheable variable reads. */
|
|
282
|
+
insideCacheScope?: boolean;
|
|
283
|
+
/**
|
|
284
|
+
* Include scope string applied to direct-descendant shortCodes.
|
|
285
|
+
*
|
|
286
|
+
* Each `include(...)` call allocates a sibling-positional token like `I0`,
|
|
287
|
+
* `I1` from its parent's include counter and stores the composed scope
|
|
288
|
+
* (`${parentScope}I${idx}`) in its lazyContext. When the include's handler
|
|
289
|
+
* evaluates lazily, the store's `includeScope` is set from that context so
|
|
290
|
+
* every direct-descendant shortCode is generated as
|
|
291
|
+
* `${parent.shortCode}${includeScope}${prefix}${index}` — preventing
|
|
292
|
+
* collisions with siblings declared outside the include.
|
|
293
|
+
*
|
|
294
|
+
* The scope is NOT propagated through `store.run(...)`, so layouts /
|
|
295
|
+
* parallels / caches inside the include absorb the scope into their own
|
|
296
|
+
* shortCodes and their children start fresh.
|
|
297
|
+
*/
|
|
298
|
+
includeScope?: string;
|
|
276
299
|
}
|
|
277
300
|
// Use a global symbol key so the AsyncLocalStorage instance survives HMR
|
|
278
301
|
// module re-evaluation. Without this, Vite's RSC module runner may create
|
|
@@ -375,6 +398,8 @@ export const getContext = (): {
|
|
|
375
398
|
const mountPrefix =
|
|
376
399
|
store.mountIndex !== undefined ? `M${store.mountIndex}` : "";
|
|
377
400
|
|
|
401
|
+
const includeScope = store.includeScope ?? "";
|
|
402
|
+
|
|
378
403
|
if (!parent) {
|
|
379
404
|
// Root entry: prefix with mount index and use mount-scoped counter
|
|
380
405
|
const counterKey = mountPrefix
|
|
@@ -385,12 +410,16 @@ export const getContext = (): {
|
|
|
385
410
|
store.counters[counterKey] = index + 1;
|
|
386
411
|
return `${mountPrefix}${prefix}${index}`;
|
|
387
412
|
} else {
|
|
388
|
-
// Child entry: use parent-scoped counter
|
|
389
|
-
|
|
413
|
+
// Child entry: use parent-scoped counter with includeScope appended.
|
|
414
|
+
// When we're evaluating a lazy include's direct children, includeScope
|
|
415
|
+
// is a per-include token like "I0" / "I1I0" that partitions the
|
|
416
|
+
// parent's counter namespace so routes inside one include cannot
|
|
417
|
+
// collide with siblings declared outside it.
|
|
418
|
+
const counterKey = `${parent.shortCode}${includeScope}_${type}`;
|
|
390
419
|
store.counters[counterKey] ??= 0;
|
|
391
420
|
const index = store.counters[counterKey];
|
|
392
421
|
store.counters[counterKey] = index + 1;
|
|
393
|
-
return `${parent.shortCode}${prefix}${index}`;
|
|
422
|
+
return `${parent.shortCode}${includeScope}${prefix}${index}`;
|
|
394
423
|
}
|
|
395
424
|
},
|
|
396
425
|
runWithStore: <T>(
|
|
@@ -417,6 +446,7 @@ export const getContext = (): {
|
|
|
417
446
|
rootScoped: store.rootScoped,
|
|
418
447
|
trackedIncludes: store.trackedIncludes,
|
|
419
448
|
cacheProfiles: store.cacheProfiles,
|
|
449
|
+
includeScope: store.includeScope,
|
|
420
450
|
},
|
|
421
451
|
callback,
|
|
422
452
|
);
|
|
@@ -666,3 +696,45 @@ export function track(label: string, depth?: number): () => void {
|
|
|
666
696
|
});
|
|
667
697
|
};
|
|
668
698
|
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Separate ALS for tracking loader execution scope.
|
|
702
|
+
* Uses a dedicated ALS (not RSCRouterContext) to avoid issues with
|
|
703
|
+
* nested RSCRouterContext.run() calls in Vite's module runner.
|
|
704
|
+
*/
|
|
705
|
+
const LOADER_SCOPE_KEY = Symbol.for("rangojs-router:loader-scope");
|
|
706
|
+
const loaderScopeALS: AsyncLocalStorage<{ active: true }> = ((
|
|
707
|
+
globalThis as any
|
|
708
|
+
)[LOADER_SCOPE_KEY] ??= new AsyncLocalStorage<{ active: true }>());
|
|
709
|
+
|
|
710
|
+
/**
|
|
711
|
+
* Check if the current execution is inside a cache() DSL boundary.
|
|
712
|
+
* Returns false inside loader execution — loaders are always fresh
|
|
713
|
+
* (never cached), so non-cacheable reads are safe.
|
|
714
|
+
*/
|
|
715
|
+
export function isInsideCacheScope(): boolean {
|
|
716
|
+
if (RSCRouterContext.getStore()?.insideCacheScope !== true) return false;
|
|
717
|
+
// Loaders are always fresh — even inside a cache() boundary, the loader
|
|
718
|
+
// function re-executes on every request. Skip the guard when running
|
|
719
|
+
// inside a loader.
|
|
720
|
+
if (loaderScopeALS.getStore()?.active) return false;
|
|
721
|
+
return true;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/**
|
|
725
|
+
* Check if the current execution is inside a DSL loader scope
|
|
726
|
+
* (wrapped by runInsideLoaderScope). Used by rendered() barrier
|
|
727
|
+
* to distinguish DSL loaders from handler-invoked loaders.
|
|
728
|
+
*/
|
|
729
|
+
export function isInsideLoaderScope(): boolean {
|
|
730
|
+
return loaderScopeALS.getStore()?.active === true;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Run `fn` inside a loader scope. While active, cache-scope guards
|
|
735
|
+
* are bypassed because loaders are always fresh (never cached) and
|
|
736
|
+
* their side effects (setCookie, header, etc.) are safe.
|
|
737
|
+
*/
|
|
738
|
+
export function runInsideLoaderScope<T>(fn: () => T): T {
|
|
739
|
+
return loaderScopeALS.run({ active: true }, fn);
|
|
740
|
+
}
|
|
@@ -13,6 +13,25 @@
|
|
|
13
13
|
*/
|
|
14
14
|
export type HandleData = Record<string, Record<string, unknown[]>>;
|
|
15
15
|
|
|
16
|
+
/**
|
|
17
|
+
* Build a HandleData snapshot from a HandleStore using segment ordering.
|
|
18
|
+
* Reads data directly from the store for each segment in order.
|
|
19
|
+
*/
|
|
20
|
+
export function buildHandleSnapshot(
|
|
21
|
+
handleStore: HandleStore,
|
|
22
|
+
segmentOrder: string[],
|
|
23
|
+
): HandleData {
|
|
24
|
+
const data: HandleData = {};
|
|
25
|
+
for (const segmentId of segmentOrder) {
|
|
26
|
+
const segData = handleStore.getDataForSegment(segmentId);
|
|
27
|
+
for (const handleName in segData) {
|
|
28
|
+
if (!data[handleName]) data[handleName] = {};
|
|
29
|
+
data[handleName][segmentId] = segData[handleName];
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return data;
|
|
33
|
+
}
|
|
34
|
+
|
|
16
35
|
function createLateHandlePushError(
|
|
17
36
|
handleName: string,
|
|
18
37
|
segmentId: string,
|
|
@@ -44,20 +44,21 @@ export function setLoaderImports(
|
|
|
44
44
|
export async function getLoaderLazy(
|
|
45
45
|
id: string,
|
|
46
46
|
): Promise<LoaderRegistryEntry | undefined> {
|
|
47
|
-
//
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
return existing;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
// Check the fetchable loader registry (populated by createLoader)
|
|
47
|
+
// Always check fetchableLoaderRegistry first — it's the source of truth.
|
|
48
|
+
// createLoader() updates it during module re-evaluation (HMR), so checking
|
|
49
|
+
// here ensures we pick up the fresh function after a loader file change.
|
|
54
50
|
const fetchable = getFetchableLoader(id);
|
|
55
51
|
if (fetchable) {
|
|
56
|
-
// Cache in main registry for future requests
|
|
57
52
|
loaderRegistry.set(id, fetchable);
|
|
58
53
|
return fetchable;
|
|
59
54
|
}
|
|
60
55
|
|
|
56
|
+
// Fall back to local cache (populated by previous lazy imports in production)
|
|
57
|
+
const existing = loaderRegistry.get(id);
|
|
58
|
+
if (existing) {
|
|
59
|
+
return existing;
|
|
60
|
+
}
|
|
61
|
+
|
|
61
62
|
// Try to lazy load from the import map (production mode)
|
|
62
63
|
if (lazyLoaderImports && lazyLoaderImports.size > 0) {
|
|
63
64
|
const lazyImport = lazyLoaderImports.get(id);
|
|
@@ -20,16 +20,29 @@ import type {
|
|
|
20
20
|
DefaultRouteName,
|
|
21
21
|
} from "../types/global-namespace.js";
|
|
22
22
|
import type { Handle } from "../handle.js";
|
|
23
|
-
import {
|
|
24
|
-
|
|
23
|
+
import {
|
|
24
|
+
type ContextVar,
|
|
25
|
+
contextGet,
|
|
26
|
+
contextSet,
|
|
27
|
+
isNonCacheable,
|
|
28
|
+
} from "../context-var.js";
|
|
29
|
+
import {
|
|
30
|
+
createHandleStore,
|
|
31
|
+
buildHandleSnapshot,
|
|
32
|
+
type HandleStore,
|
|
33
|
+
type HandleData,
|
|
34
|
+
} from "./handle-store.js";
|
|
25
35
|
import { isHandle } from "../handle.js";
|
|
26
36
|
import { track, type MetricsStore } from "./context.js";
|
|
27
37
|
import { getFetchableLoader } from "./fetchable-loader-store.js";
|
|
28
38
|
import type { SegmentCacheStore } from "../cache/types.js";
|
|
29
39
|
import type { Theme, ResolvedThemeConfig } from "../theme/types.js";
|
|
40
|
+
import type { ExecutionContext, RequestScope } from "../types/request-scope.js";
|
|
41
|
+
import { fireAndForgetWaitUntil } from "../types/request-scope.js";
|
|
30
42
|
import { THEME_COOKIE } from "../theme/constants.js";
|
|
31
43
|
import type { LocationStateEntry } from "../browser/react/location-state-shared.js";
|
|
32
44
|
import { NOCACHE_SYMBOL, assertNotInsideCacheExec } from "../cache/taint.js";
|
|
45
|
+
import { isInsideCacheScope } from "./context.js";
|
|
33
46
|
import {
|
|
34
47
|
createReverseFunction,
|
|
35
48
|
stripInternalParams,
|
|
@@ -47,24 +60,9 @@ import { isAutoGeneratedRouteName } from "../route-name.js";
|
|
|
47
60
|
export interface RequestContext<
|
|
48
61
|
TEnv = DefaultEnv,
|
|
49
62
|
TParams = Record<string, string>,
|
|
50
|
-
> {
|
|
51
|
-
/**
|
|
52
|
-
|
|
53
|
-
/** Original HTTP request */
|
|
54
|
-
request: Request;
|
|
55
|
-
/** Parsed URL (with internal `_rsc*` params stripped) */
|
|
56
|
-
url: URL;
|
|
57
|
-
/**
|
|
58
|
-
* The original request URL with all parameters intact, including
|
|
59
|
-
* internal `_rsc*` transport params.
|
|
60
|
-
*/
|
|
61
|
-
originalUrl: URL;
|
|
62
|
-
/** URL pathname */
|
|
63
|
-
pathname: string;
|
|
64
|
-
/** URL search params (with internal `_rsc*` params stripped, same as `url.searchParams`) */
|
|
65
|
-
searchParams: URLSearchParams;
|
|
66
|
-
/** Variables set by middleware (same as ctx.var) */
|
|
67
|
-
var: Record<string, any>;
|
|
63
|
+
> extends RequestScope<TEnv> {
|
|
64
|
+
/** @internal Shared variable backing store for ctx.get()/ctx.set(). */
|
|
65
|
+
_variables: Record<string, any>;
|
|
68
66
|
/** Get a variable set by middleware */
|
|
69
67
|
get: {
|
|
70
68
|
<T>(contextVar: ContextVar<T>): T | undefined;
|
|
@@ -72,8 +70,12 @@ export interface RequestContext<
|
|
|
72
70
|
};
|
|
73
71
|
/** Set a variable (shared with middleware and handlers) */
|
|
74
72
|
set: {
|
|
75
|
-
<T>(
|
|
76
|
-
|
|
73
|
+
<T>(
|
|
74
|
+
contextVar: ContextVar<T>,
|
|
75
|
+
value: T,
|
|
76
|
+
options?: { cache?: boolean },
|
|
77
|
+
): void;
|
|
78
|
+
<K extends string>(key: K, value: any, options?: { cache?: boolean }): void;
|
|
77
79
|
};
|
|
78
80
|
/**
|
|
79
81
|
* Route params (populated after route matching)
|
|
@@ -144,20 +146,6 @@ export interface RequestContext<
|
|
|
144
146
|
import("../cache/profile-registry.js").CacheProfile
|
|
145
147
|
>;
|
|
146
148
|
|
|
147
|
-
/**
|
|
148
|
-
* Schedule work to run after the response is sent.
|
|
149
|
-
* On Cloudflare Workers, uses ctx.waitUntil().
|
|
150
|
-
* On Node.js, runs as fire-and-forget.
|
|
151
|
-
*
|
|
152
|
-
* @example
|
|
153
|
-
* ```typescript
|
|
154
|
-
* ctx.waitUntil(async () => {
|
|
155
|
-
* await cacheStore.set(key, data, ttl);
|
|
156
|
-
* });
|
|
157
|
-
* ```
|
|
158
|
-
*/
|
|
159
|
-
waitUntil(fn: () => Promise<void>): void;
|
|
160
|
-
|
|
161
149
|
/**
|
|
162
150
|
* Register a callback to run when the response is created.
|
|
163
151
|
* Callbacks are sync and receive the response. They can:
|
|
@@ -261,6 +249,54 @@ export interface RequestContext<
|
|
|
261
249
|
/** @internal Previous route key (from the navigation source), used for revalidation */
|
|
262
250
|
_prevRouteKey?: string;
|
|
263
251
|
|
|
252
|
+
/**
|
|
253
|
+
* @internal Render barrier for experimental `rendered()` API.
|
|
254
|
+
* Resolves when all non-loader segments have settled and handle data
|
|
255
|
+
* is available. Used by DSL loaders that call `ctx.rendered()`.
|
|
256
|
+
*/
|
|
257
|
+
_renderBarrier: Promise<void>;
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* @internal Resolve the render barrier. Accepts resolved segments, filters
|
|
261
|
+
* out loaders, and captures non-loader segment IDs as the handle ordering.
|
|
262
|
+
* Called after segment resolution (fresh) or handle replay (cache/prerender).
|
|
263
|
+
*/
|
|
264
|
+
_resolveRenderBarrier: (
|
|
265
|
+
segments: Array<{ type: string; id: string }>,
|
|
266
|
+
) => void;
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* @internal Segment order at barrier resolution time, used by loader
|
|
270
|
+
* ctx.use(handle) to collect handle data in correct order.
|
|
271
|
+
*/
|
|
272
|
+
_renderBarrierSegmentOrder?: string[];
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* @internal Set to true when the matched entry tree contains any `loading()`
|
|
276
|
+
* entries (streaming). Used by rendered() to fail fast.
|
|
277
|
+
*/
|
|
278
|
+
_treeHasStreaming?: boolean;
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* @internal Loader IDs that have called rendered() and are waiting for the
|
|
282
|
+
* barrier. Used to detect deadlocks when a handler tries to await the same
|
|
283
|
+
* loader via ctx.use(Loader).
|
|
284
|
+
*/
|
|
285
|
+
_renderBarrierWaiters?: Set<string>;
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* @internal Loader IDs that handlers have started awaiting via ctx.use().
|
|
289
|
+
* Used for bidirectional deadlock detection: if a loader later calls
|
|
290
|
+
* rendered() and a handler already awaits it, we can detect the deadlock.
|
|
291
|
+
*/
|
|
292
|
+
_handlerLoaderDeps?: Set<string>;
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* @internal Cached HandleData snapshot built at barrier resolution time.
|
|
296
|
+
* Avoids rebuilding the snapshot on every loader ctx.use(handle) call.
|
|
297
|
+
*/
|
|
298
|
+
_renderBarrierHandleSnapshot?: HandleData;
|
|
299
|
+
|
|
264
300
|
/** @internal Per-request error dedup set for onError reporting */
|
|
265
301
|
_reportedErrors: WeakSet<object>;
|
|
266
302
|
|
|
@@ -277,6 +313,15 @@ export interface RequestContext<
|
|
|
277
313
|
|
|
278
314
|
/** @internal Request-scoped performance metrics store */
|
|
279
315
|
_metricsStore?: MetricsStore;
|
|
316
|
+
|
|
317
|
+
/** @internal Router basename for this request (used by redirect()) */
|
|
318
|
+
_basename?: string;
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* @internal RouteSnapshot from classifyRequest, reused by match/matchPartial
|
|
322
|
+
* to avoid a second resolveRoute call. Cleared on HMR invalidation.
|
|
323
|
+
*/
|
|
324
|
+
_classifiedRoute?: import("../router/route-snapshot.js").RouteSnapshot;
|
|
280
325
|
}
|
|
281
326
|
|
|
282
327
|
/**
|
|
@@ -303,10 +348,20 @@ export type PublicRequestContext<
|
|
|
303
348
|
| "_routeName"
|
|
304
349
|
| "_prevRouteKey"
|
|
305
350
|
| "_reportedErrors"
|
|
351
|
+
| "_renderBarrier"
|
|
352
|
+
| "_resolveRenderBarrier"
|
|
353
|
+
| "_renderBarrierSegmentOrder"
|
|
354
|
+
| "_treeHasStreaming"
|
|
355
|
+
| "_renderBarrierWaiters"
|
|
356
|
+
| "_handlerLoaderDeps"
|
|
357
|
+
| "_renderBarrierHandleSnapshot"
|
|
306
358
|
| "_reportBackgroundError"
|
|
307
359
|
| "_debugPerformance"
|
|
308
360
|
| "_metricsStore"
|
|
361
|
+
| "_basename"
|
|
309
362
|
| "_setStatus"
|
|
363
|
+
| "_variables"
|
|
364
|
+
| "_classifiedRoute"
|
|
310
365
|
| "res"
|
|
311
366
|
>;
|
|
312
367
|
|
|
@@ -416,13 +471,7 @@ export function requireRequestContext<
|
|
|
416
471
|
return getRequestContext<TEnv>();
|
|
417
472
|
}
|
|
418
473
|
|
|
419
|
-
|
|
420
|
-
* Cloudflare Workers ExecutionContext (subset we need)
|
|
421
|
-
*/
|
|
422
|
-
export interface ExecutionContext {
|
|
423
|
-
waitUntil(promise: Promise<any>): void;
|
|
424
|
-
passThroughOnException(): void;
|
|
425
|
-
}
|
|
474
|
+
export type { ExecutionContext };
|
|
426
475
|
|
|
427
476
|
/**
|
|
428
477
|
* Options for creating a request context
|
|
@@ -506,6 +555,18 @@ export function createRequestContext<TEnv>(
|
|
|
506
555
|
responseCookieCache = null;
|
|
507
556
|
};
|
|
508
557
|
|
|
558
|
+
// Guard: throw if a response-level side effect is called inside a cache() scope.
|
|
559
|
+
// Uses ALS to detect the scope (set during segment resolution).
|
|
560
|
+
function assertNotInsideCacheScopeALS(methodName: string): void {
|
|
561
|
+
if (isInsideCacheScope()) {
|
|
562
|
+
throw new Error(
|
|
563
|
+
`ctx.${methodName}() cannot be called inside a cache() boundary. ` +
|
|
564
|
+
`On cache hit the handler is skipped, so this side effect would be lost. ` +
|
|
565
|
+
`Move ctx.${methodName}() to a middleware or layout outside the cache() scope.`,
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
|
|
509
570
|
// Effective cookie read: response stub Set-Cookie wins, then original header.
|
|
510
571
|
// The stub IS the source of truth for same-request mutations.
|
|
511
572
|
const effectiveCookie = (name: string): string | undefined => {
|
|
@@ -569,12 +630,20 @@ export function createRequestContext<TEnv>(
|
|
|
569
630
|
originalUrl: new URL(request.url),
|
|
570
631
|
pathname: url.pathname,
|
|
571
632
|
searchParams: cleanUrl.searchParams,
|
|
572
|
-
|
|
573
|
-
get: ((keyOrVar: any) =>
|
|
574
|
-
|
|
575
|
-
|
|
633
|
+
_variables: variables,
|
|
634
|
+
get: ((keyOrVar: any) => {
|
|
635
|
+
if (isNonCacheable(variables, keyOrVar) && isInsideCacheScope()) {
|
|
636
|
+
throw new Error(
|
|
637
|
+
`ctx.get() for a non-cacheable variable cannot be called inside a cache() boundary. ` +
|
|
638
|
+
`The variable was created with { cache: false } or set with { cache: false }, ` +
|
|
639
|
+
`and its value would be stale on cache hit. Move the read outside the cached scope.`,
|
|
640
|
+
);
|
|
641
|
+
}
|
|
642
|
+
return contextGet(variables, keyOrVar);
|
|
643
|
+
}) as RequestContext<TEnv>["get"],
|
|
644
|
+
set: ((keyOrVar: any, value: any, options?: any) => {
|
|
576
645
|
assertNotInsideCacheExec(ctx, "set");
|
|
577
|
-
contextSet(variables, keyOrVar, value);
|
|
646
|
+
contextSet(variables, keyOrVar, value, options);
|
|
578
647
|
}) as RequestContext<TEnv>["set"],
|
|
579
648
|
params: {} as Record<string, string>,
|
|
580
649
|
|
|
@@ -612,6 +681,7 @@ export function createRequestContext<TEnv>(
|
|
|
612
681
|
|
|
613
682
|
setCookie(name: string, value: string, options?: CookieOptions): void {
|
|
614
683
|
assertNotInsideCacheExec(ctx, "setCookie");
|
|
684
|
+
assertNotInsideCacheScopeALS("setCookie");
|
|
615
685
|
stubResponse.headers.append(
|
|
616
686
|
"Set-Cookie",
|
|
617
687
|
serializeCookieValue(name, value, options),
|
|
@@ -624,6 +694,7 @@ export function createRequestContext<TEnv>(
|
|
|
624
694
|
options?: Pick<CookieOptions, "domain" | "path">,
|
|
625
695
|
): void {
|
|
626
696
|
assertNotInsideCacheExec(ctx, "deleteCookie");
|
|
697
|
+
assertNotInsideCacheScopeALS("deleteCookie");
|
|
627
698
|
stubResponse.headers.append(
|
|
628
699
|
"Set-Cookie",
|
|
629
700
|
serializeCookieValue(name, "", { ...options, maxAge: 0 }),
|
|
@@ -633,11 +704,13 @@ export function createRequestContext<TEnv>(
|
|
|
633
704
|
|
|
634
705
|
header(name: string, value: string): void {
|
|
635
706
|
assertNotInsideCacheExec(ctx, "header");
|
|
707
|
+
assertNotInsideCacheScopeALS("header");
|
|
636
708
|
stubResponse.headers.set(name, value);
|
|
637
709
|
},
|
|
638
710
|
|
|
639
711
|
setStatus(status: number): void {
|
|
640
712
|
assertNotInsideCacheExec(ctx, "setStatus");
|
|
713
|
+
assertNotInsideCacheScopeALS("setStatus");
|
|
641
714
|
stubResponse = new Response(null, {
|
|
642
715
|
status,
|
|
643
716
|
headers: stubResponse.headers,
|
|
@@ -662,20 +735,19 @@ export function createRequestContext<TEnv>(
|
|
|
662
735
|
|
|
663
736
|
waitUntil(fn: () => Promise<void>): void {
|
|
664
737
|
if (executionContext?.waitUntil) {
|
|
665
|
-
// Cloudflare Workers: use native waitUntil
|
|
666
738
|
executionContext.waitUntil(fn());
|
|
667
739
|
} else {
|
|
668
|
-
|
|
669
|
-
fn().catch((err) =>
|
|
670
|
-
console.error("[waitUntil] Background task failed:", err),
|
|
671
|
-
);
|
|
740
|
+
fireAndForgetWaitUntil(fn);
|
|
672
741
|
}
|
|
673
742
|
},
|
|
674
743
|
|
|
744
|
+
executionContext,
|
|
745
|
+
|
|
675
746
|
_onResponseCallbacks: [],
|
|
676
747
|
|
|
677
748
|
onResponse(callback: (response: Response) => Response): void {
|
|
678
749
|
assertNotInsideCacheExec(ctx, "onResponse");
|
|
750
|
+
assertNotInsideCacheScopeALS("onResponse");
|
|
679
751
|
this._onResponseCallbacks.push(callback);
|
|
680
752
|
},
|
|
681
753
|
|
|
@@ -703,9 +775,58 @@ export function createRequestContext<TEnv>(
|
|
|
703
775
|
_reportedErrors: new WeakSet<object>(),
|
|
704
776
|
_metricsStore: undefined,
|
|
705
777
|
|
|
778
|
+
// Render barrier: deferred promise resolved after non-loader segments settle.
|
|
779
|
+
_renderBarrier: null as any, // set below
|
|
780
|
+
_resolveRenderBarrier: null as any, // set below
|
|
781
|
+
_renderBarrierSegmentOrder: undefined,
|
|
782
|
+
|
|
706
783
|
reverse: createReverseFunction(getGlobalRouteMap(), undefined, {}),
|
|
707
784
|
};
|
|
708
785
|
|
|
786
|
+
// Lazy render barrier: only allocate the Promise when a loader actually
|
|
787
|
+
// calls rendered(). Requests that don't use rendered() pay zero cost.
|
|
788
|
+
let barrierResolved = false;
|
|
789
|
+
let resolveBarrier: (() => void) | undefined;
|
|
790
|
+
ctx._renderBarrier = null as any; // lazy — created on first access
|
|
791
|
+
ctx._resolveRenderBarrier = (
|
|
792
|
+
segments: Array<{ type: string; id: string }>,
|
|
793
|
+
) => {
|
|
794
|
+
if (barrierResolved) return;
|
|
795
|
+
barrierResolved = true;
|
|
796
|
+
const segOrder = segments
|
|
797
|
+
.filter((s) => s.type !== "loader")
|
|
798
|
+
.map((s) => s.id);
|
|
799
|
+
ctx._renderBarrierSegmentOrder = segOrder;
|
|
800
|
+
// Build and cache handle snapshot so loader ctx.use(handle) calls
|
|
801
|
+
// don't rebuild it on every invocation.
|
|
802
|
+
ctx._renderBarrierHandleSnapshot = buildHandleSnapshot(
|
|
803
|
+
handleStore,
|
|
804
|
+
segOrder,
|
|
805
|
+
);
|
|
806
|
+
ctx._renderBarrierWaiters = undefined;
|
|
807
|
+
ctx._handlerLoaderDeps = undefined;
|
|
808
|
+
if (resolveBarrier) resolveBarrier();
|
|
809
|
+
};
|
|
810
|
+
Object.defineProperty(ctx, "_renderBarrier", {
|
|
811
|
+
get() {
|
|
812
|
+
// Barrier already resolved (cache/prerender hit) or first lazy access.
|
|
813
|
+
// Either way, replace the getter with a concrete value to avoid
|
|
814
|
+
// repeated Promise.resolve() allocations on subsequent reads.
|
|
815
|
+
const p = barrierResolved
|
|
816
|
+
? Promise.resolve()
|
|
817
|
+
: new Promise<void>((resolve) => {
|
|
818
|
+
resolveBarrier = resolve;
|
|
819
|
+
});
|
|
820
|
+
Object.defineProperty(ctx, "_renderBarrier", {
|
|
821
|
+
value: p,
|
|
822
|
+
writable: false,
|
|
823
|
+
configurable: false,
|
|
824
|
+
});
|
|
825
|
+
return p;
|
|
826
|
+
},
|
|
827
|
+
configurable: true,
|
|
828
|
+
});
|
|
829
|
+
|
|
709
830
|
// Now create use() with access to ctx
|
|
710
831
|
ctx.use = createUseFunction({
|
|
711
832
|
handleStore,
|
|
@@ -887,15 +1008,17 @@ export function createUseFunction<TEnv>(
|
|
|
887
1008
|
search: (ctx as any).search ?? {},
|
|
888
1009
|
pathname: ctx.pathname,
|
|
889
1010
|
url: ctx.url,
|
|
1011
|
+
originalUrl: ctx.originalUrl,
|
|
890
1012
|
env: ctx.env as any,
|
|
891
|
-
|
|
1013
|
+
waitUntil: ctx.waitUntil.bind(ctx),
|
|
1014
|
+
executionContext: ctx.executionContext,
|
|
892
1015
|
get: ctx.get as any,
|
|
893
|
-
use: <TDep, TDepParams = any>(
|
|
1016
|
+
use: (<TDep, TDepParams = any>(
|
|
894
1017
|
dep: LoaderDefinition<TDep, TDepParams>,
|
|
895
1018
|
): Promise<TDep> => {
|
|
896
1019
|
// Recursive call - will start dep loader if not already started
|
|
897
1020
|
return ctx.use(dep);
|
|
898
|
-
},
|
|
1021
|
+
}) as LoaderContext["use"],
|
|
899
1022
|
method: "GET",
|
|
900
1023
|
body: undefined,
|
|
901
1024
|
reverse: createReverseFunction(
|
|
@@ -904,9 +1027,14 @@ export function createUseFunction<TEnv>(
|
|
|
904
1027
|
ctx.params as Record<string, string>,
|
|
905
1028
|
ctx._routeName ? isRouteRootScoped(ctx._routeName) : undefined,
|
|
906
1029
|
),
|
|
1030
|
+
rendered: () => {
|
|
1031
|
+
throw new Error(
|
|
1032
|
+
`ctx.rendered() is only available in DSL loaders (registered via loader() in urls()). ` +
|
|
1033
|
+
`It cannot be used from request-context loaders or server actions.`,
|
|
1034
|
+
);
|
|
1035
|
+
},
|
|
907
1036
|
};
|
|
908
1037
|
|
|
909
|
-
// Start loader execution with tracking
|
|
910
1038
|
const doneLoader = track(`loader:${loader.$$id}`, 2);
|
|
911
1039
|
const promise = Promise.resolve(loaderFn(loaderCtx)).finally(() => {
|
|
912
1040
|
doneLoader();
|