main repo

This commit is contained in:
Basilosaurusrex
2025-11-24 18:09:40 +01:00
parent b636ee5e70
commit f027651f9b
34146 changed files with 4436636 additions and 0 deletions

View File

@@ -0,0 +1,4 @@
import { ReadonlyReducerState, ReducerState, FastRefreshAction } from '../router-reducer-types';
declare function fastRefreshReducerNoop(state: ReadonlyReducerState, _action: FastRefreshAction): ReducerState;
export declare const fastRefreshReducer: typeof fastRefreshReducerNoop;
export {};

View File

@@ -0,0 +1,93 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "fastRefreshReducer", {
enumerable: true,
get: function() {
return fastRefreshReducer;
}
});
const _fetchserverresponse = require("../fetch-server-response");
const _createrecordfromthenable = require("../create-record-from-thenable");
const _readrecordvalue = require("../read-record-value");
const _createhreffromurl = require("../create-href-from-url");
const _applyrouterstatepatchtotree = require("../apply-router-state-patch-to-tree");
const _isnavigatingtonewrootlayout = require("../is-navigating-to-new-root-layout");
const _navigatereducer = require("./navigate-reducer");
const _handlemutable = require("../handle-mutable");
const _applyflightdata = require("../apply-flight-data");
// A version of refresh reducer that keeps the cache around instead of wiping all of it.
function fastRefreshReducerImpl(state, action) {
const { cache, mutable, origin } = action;
const href = state.canonicalUrl;
const isForCurrentTree = JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree);
if (isForCurrentTree) {
return (0, _handlemutable.handleMutable)(state, mutable);
}
if (!cache.data) {
// TODO-APP: verify that `href` is not an external url.
// Fetch data from the root of the tree.
cache.data = (0, _createrecordfromthenable.createRecordFromThenable)((0, _fetchserverresponse.fetchServerResponse)(new URL(href, origin), [
state.tree[0],
state.tree[1],
state.tree[2],
"refetch"
], state.nextUrl, state.buildId));
}
const [flightData, canonicalUrlOverride] = (0, _readrecordvalue.readRecordValue)(cache.data);
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === "string") {
return (0, _navigatereducer.handleExternalUrl)(state, mutable, flightData, state.pushRef.pendingPush);
}
// Remove cache.data as it has been resolved at this point.
cache.data = null;
let currentTree = state.tree;
let currentCache = state.cache;
for (const flightDataPath of flightData){
// FlightDataPath with more than two items means unexpected Flight data was returned
if (flightDataPath.length !== 3) {
// TODO-APP: handle this case better
console.log("REFRESH FAILED");
return state;
}
// Given the path can only have two items the items are only the router state and subTreeData for the root.
const [treePatch] = flightDataPath;
const newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)(// TODO-APP: remove ''
[
""
], currentTree, treePatch);
if (newTree === null) {
throw new Error("SEGMENT MISMATCH");
}
if ((0, _isnavigatingtonewrootlayout.isNavigatingToNewRootLayout)(currentTree, newTree)) {
return (0, _navigatereducer.handleExternalUrl)(state, mutable, href, state.pushRef.pendingPush);
}
const canonicalUrlOverrideHref = canonicalUrlOverride ? (0, _createhreffromurl.createHrefFromUrl)(canonicalUrlOverride) : undefined;
if (canonicalUrlOverride) {
mutable.canonicalUrl = canonicalUrlOverrideHref;
}
const applied = (0, _applyflightdata.applyFlightData)(currentCache, cache, flightDataPath);
if (applied) {
mutable.cache = cache;
currentCache = cache;
}
mutable.previousTree = currentTree;
mutable.patchedTree = newTree;
mutable.canonicalUrl = href;
currentTree = newTree;
}
return (0, _handlemutable.handleMutable)(state, mutable);
}
function fastRefreshReducerNoop(state, _action) {
return state;
}
const fastRefreshReducer = process.env.NODE_ENV === "production" ? fastRefreshReducerNoop : fastRefreshReducerImpl;
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=fast-refresh-reducer.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/fast-refresh-reducer.ts"],"names":["fastRefreshReducer","fastRefreshReducerImpl","state","action","cache","mutable","origin","href","canonicalUrl","isForCurrentTree","JSON","stringify","previousTree","tree","handleMutable","data","createRecordFromThenable","fetchServerResponse","URL","nextUrl","buildId","flightData","canonicalUrlOverride","readRecordValue","handleExternalUrl","pushRef","pendingPush","currentTree","currentCache","flightDataPath","length","console","log","treePatch","newTree","applyRouterStatePatchToTree","Error","isNavigatingToNewRootLayout","canonicalUrlOverrideHref","createHrefFromUrl","undefined","applied","applyFlightData","patchedTree","fastRefreshReducerNoop","_action","process","env","NODE_ENV"],"mappings":";;;;+BAmHaA;;;eAAAA;;;qCAnHuB;0CACK;iCACT;mCACE;6CACU;6CACA;iCAMV;+BACJ;iCACE;AAEhC,wFAAwF;AACxF,SAASC,uBACPC,KAA2B,EAC3BC,MAAyB;IAEzB,MAAM,EAAEC,KAAK,EAAEC,OAAO,EAAEC,MAAM,EAAE,GAAGH;IACnC,MAAMI,OAAOL,MAAMM,YAAY;IAE/B,MAAMC,mBACJC,KAAKC,SAAS,CAACN,QAAQO,YAAY,MAAMF,KAAKC,SAAS,CAACT,MAAMW,IAAI;IAEpE,IAAIJ,kBAAkB;QACpB,OAAOK,IAAAA,4BAAa,EAACZ,OAAOG;IAC9B;IAEA,IAAI,CAACD,MAAMW,IAAI,EAAE;QACf,uDAAuD;QACvD,wCAAwC;QACxCX,MAAMW,IAAI,GAAGC,IAAAA,kDAAwB,EACnCC,IAAAA,wCAAmB,EACjB,IAAIC,IAAIX,MAAMD,SACd;YAACJ,MAAMW,IAAI,CAAC,EAAE;YAAEX,MAAMW,IAAI,CAAC,EAAE;YAAEX,MAAMW,IAAI,CAAC,EAAE;YAAE;SAAU,EACxDX,MAAMiB,OAAO,EACbjB,MAAMkB,OAAO;IAGnB;IACA,MAAM,CAACC,YAAYC,qBAAqB,GAAGC,IAAAA,gCAAe,EAACnB,MAAMW,IAAI;IAErE,4DAA4D;IAC5D,IAAI,OAAOM,eAAe,UAAU;QAClC,OAAOG,IAAAA,kCAAiB,EACtBtB,OACAG,SACAgB,YACAnB,MAAMuB,OAAO,CAACC,WAAW;IAE7B;IAEA,2DAA2D;IAC3DtB,MAAMW,IAAI,GAAG;IAEb,IAAIY,cAAczB,MAAMW,IAAI;IAC5B,IAAIe,eAAe1B,MAAME,KAAK;IAE9B,KAAK,MAAMyB,kBAAkBR,WAAY;QACvC,oFAAoF;QACpF,IAAIQ,eAAeC,MAAM,KAAK,GAAG;YAC/B,oCAAoC;YACpCC,QAAQC,GAAG,CAAC;YACZ,OAAO9B;QACT;QAEA,2GAA2G;QAC3G,MAAM,CAAC+B,UAAU,GAAGJ;QACpB,MAAMK,UAAUC,IAAAA,wDAA2B,EACzC,sBAAsB;QACtB;YAAC;SAAG,EACJR,aACAM;QAGF,IAAIC,YAAY,MAAM;YACpB,MAAM,IAAIE,MAAM;QAClB;QAEA,IAAIC,IAAAA,wDAA2B,EAACV,aAAaO,UAAU;YACrD,OAAOV,IAAAA,kCAAiB,EAACtB,OAAOG,SAASE,MAAML,MAAMuB,OAAO,CAACC,WAAW;QAC1E;QAEA,MAAMY,2BAA2BhB,uBAC7BiB,IAAAA,oCAAiB,EAACjB,wBAClBkB;QAEJ,IAAIlB,sBAAsB;YACxBjB,QAAQG,YAAY,GAAG8B;QACzB;QACA,MAAMG,UAAUC,IAAAA,gCAAe,EAACd,cAAcxB,OAAOyB;QAErD,IAAIY,SAAS;YACXpC,QAAQD,KAAK,GAAGA;YAChBwB,eAAexB;QACjB;QAEAC,QAAQO,YAAY,GAAGe;QACvBtB,QAAQsC,WAAW,GAAGT;QACtB7B,QAAQG,YAAY,GAAGD;QAEvBoB,cAAcO;IAChB;IACA,OAAOpB,IAAAA,4BAAa,EAACZ,OAAOG;AAC9B;AAEA,SAASuC,uBACP1C,KAA2B,EAC3B2C,OAA0B;IAE1B,OAAO3C;AACT;AAEO,MAAMF,qBACX8C,QAAQC,GAAG,CAACC,QAAQ,KAAK,eACrBJ,yBACA3C"}

View File

@@ -0,0 +1,4 @@
/// <reference types="react" />
import type { FlightRouterState } from '../../../../server/app-render/types';
import type { CacheNode } from '../../../../shared/lib/app-router-context.shared-runtime';
export declare function findHeadInCache(cache: CacheNode, parallelRoutes: FlightRouterState[1]): React.ReactNode;

View File

@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "findHeadInCache", {
enumerable: true,
get: function() {
return findHeadInCache;
}
});
const _createroutercachekey = require("../create-router-cache-key");
function findHeadInCache(cache, parallelRoutes) {
const isLastItem = Object.keys(parallelRoutes).length === 0;
if (isLastItem) {
return cache.head;
}
for(const key in parallelRoutes){
const [segment, childParallelRoutes] = parallelRoutes[key];
const childSegmentMap = cache.parallelRoutes.get(key);
if (!childSegmentMap) {
continue;
}
const cacheKey = (0, _createroutercachekey.createRouterCacheKey)(segment);
const cacheNode = childSegmentMap.get(cacheKey);
if (!cacheNode) {
continue;
}
const item = findHeadInCache(cacheNode, childParallelRoutes);
if (item) {
return item;
}
}
return undefined;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=find-head-in-cache.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/find-head-in-cache.ts"],"names":["findHeadInCache","cache","parallelRoutes","isLastItem","Object","keys","length","head","key","segment","childParallelRoutes","childSegmentMap","get","cacheKey","createRouterCacheKey","cacheNode","item","undefined"],"mappings":";;;;+BAIgBA;;;eAAAA;;;sCAFqB;AAE9B,SAASA,gBACdC,KAAgB,EAChBC,cAAoC;IAEpC,MAAMC,aAAaC,OAAOC,IAAI,CAACH,gBAAgBI,MAAM,KAAK;IAC1D,IAAIH,YAAY;QACd,OAAOF,MAAMM,IAAI;IACnB;IACA,IAAK,MAAMC,OAAON,eAAgB;QAChC,MAAM,CAACO,SAASC,oBAAoB,GAAGR,cAAc,CAACM,IAAI;QAC1D,MAAMG,kBAAkBV,MAAMC,cAAc,CAACU,GAAG,CAACJ;QACjD,IAAI,CAACG,iBAAiB;YACpB;QACF;QAEA,MAAME,WAAWC,IAAAA,0CAAoB,EAACL;QAEtC,MAAMM,YAAYJ,gBAAgBC,GAAG,CAACC;QACtC,IAAI,CAACE,WAAW;YACd;QACF;QAEA,MAAMC,OAAOhB,gBAAgBe,WAAWL;QACxC,IAAIM,MAAM;YACR,OAAOA;QACT;IACF;IAEA,OAAOC;AACT"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,2 @@
import { Segment } from '../../../../server/app-render/types';
export declare function getSegmentValue(segment: Segment): string;

View File

@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getSegmentValue", {
enumerable: true,
get: function() {
return getSegmentValue;
}
});
function getSegmentValue(segment) {
return Array.isArray(segment) ? segment[1] : segment;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=get-segment-value.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/get-segment-value.ts"],"names":["getSegmentValue","segment","Array","isArray"],"mappings":";;;;+BAEgBA;;;eAAAA;;;AAAT,SAASA,gBAAgBC,OAAgB;IAC9C,OAAOC,MAAMC,OAAO,CAACF,WAAWA,OAAO,CAAC,EAAE,GAAGA;AAC/C"}

View File

@@ -0,0 +1,3 @@
import { Mutable, NavigateAction, ReadonlyReducerState, ReducerState } from '../router-reducer-types';
export declare function handleExternalUrl(state: ReadonlyReducerState, mutable: Mutable, url: string, pendingPush: boolean): import("../router-reducer-types").AppRouterState;
export declare function navigateReducer(state: ReadonlyReducerState, action: NavigateAction): ReducerState;

View File

@@ -0,0 +1,265 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
handleExternalUrl: null,
navigateReducer: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
handleExternalUrl: function() {
return handleExternalUrl;
},
navigateReducer: function() {
return navigateReducer;
}
});
const _approutercontextsharedruntime = require("../../../../shared/lib/app-router-context.shared-runtime");
const _fetchserverresponse = require("../fetch-server-response");
const _createrecordfromthenable = require("../create-record-from-thenable");
const _readrecordvalue = require("../read-record-value");
const _createhreffromurl = require("../create-href-from-url");
const _invalidatecachebelowflightsegmentpath = require("../invalidate-cache-below-flight-segmentpath");
const _fillcachewithdataproperty = require("../fill-cache-with-data-property");
const _createoptimistictree = require("../create-optimistic-tree");
const _applyrouterstatepatchtotree = require("../apply-router-state-patch-to-tree");
const _shouldhardnavigate = require("../should-hard-navigate");
const _isnavigatingtonewrootlayout = require("../is-navigating-to-new-root-layout");
const _routerreducertypes = require("../router-reducer-types");
const _handlemutable = require("../handle-mutable");
const _applyflightdata = require("../apply-flight-data");
const _getprefetchcacheentrystatus = require("../get-prefetch-cache-entry-status");
const _pruneprefetchcache = require("./prune-prefetch-cache");
const _prefetchreducer = require("./prefetch-reducer");
function handleExternalUrl(state, mutable, url, pendingPush) {
mutable.previousTree = state.tree;
mutable.mpaNavigation = true;
mutable.canonicalUrl = url;
mutable.pendingPush = pendingPush;
mutable.scrollableSegments = undefined;
return (0, _handlemutable.handleMutable)(state, mutable);
}
function generateSegmentsFromPatch(flightRouterPatch) {
const segments = [];
const [segment, parallelRoutes] = flightRouterPatch;
if (Object.keys(parallelRoutes).length === 0) {
return [
[
segment
]
];
}
for (const [parallelRouteKey, parallelRoute] of Object.entries(parallelRoutes)){
for (const childSegment of generateSegmentsFromPatch(parallelRoute)){
// If the segment is empty, it means we are at the root of the tree
if (segment === "") {
segments.push([
parallelRouteKey,
...childSegment
]);
} else {
segments.push([
segment,
parallelRouteKey,
...childSegment
]);
}
}
}
return segments;
}
function addRefetchToLeafSegments(newCache, currentCache, flightSegmentPath, treePatch, data) {
let appliedPatch = false;
newCache.status = _approutercontextsharedruntime.CacheStates.READY;
newCache.subTreeData = currentCache.subTreeData;
newCache.parallelRoutes = new Map(currentCache.parallelRoutes);
const segmentPathsToFill = generateSegmentsFromPatch(treePatch).map((segment)=>[
...flightSegmentPath,
...segment
]);
for (const segmentPaths of segmentPathsToFill){
const res = (0, _fillcachewithdataproperty.fillCacheWithDataProperty)(newCache, currentCache, segmentPaths, data);
if (!(res == null ? void 0 : res.bailOptimistic)) {
appliedPatch = true;
}
}
return appliedPatch;
}
function navigateReducer(state, action) {
const { url, isExternalUrl, navigateType, cache, mutable, forceOptimisticNavigation, shouldScroll } = action;
const { pathname, hash } = url;
const href = (0, _createhreffromurl.createHrefFromUrl)(url);
const pendingPush = navigateType === "push";
// we want to prune the prefetch cache on every navigation to avoid it growing too large
(0, _pruneprefetchcache.prunePrefetchCache)(state.prefetchCache);
const isForCurrentTree = JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree);
if (isForCurrentTree) {
return (0, _handlemutable.handleMutable)(state, mutable);
}
if (isExternalUrl) {
return handleExternalUrl(state, mutable, url.toString(), pendingPush);
}
let prefetchValues = state.prefetchCache.get((0, _createhreffromurl.createHrefFromUrl)(url, false));
if (forceOptimisticNavigation && (prefetchValues == null ? void 0 : prefetchValues.kind) !== _routerreducertypes.PrefetchKind.TEMPORARY) {
const segments = pathname.split("/");
// TODO-APP: figure out something better for index pages
segments.push("__PAGE__");
// Optimistic tree case.
// If the optimistic tree is deeper than the current state leave that deeper part out of the fetch
const optimisticTree = (0, _createoptimistictree.createOptimisticTree)(segments, state.tree, false);
// we need a copy of the cache in case we need to revert to it
const temporaryCacheNode = {
...cache
};
// Copy subTreeData for the root node of the cache.
// Note: didn't do it above because typescript doesn't like it.
temporaryCacheNode.status = _approutercontextsharedruntime.CacheStates.READY;
temporaryCacheNode.subTreeData = state.cache.subTreeData;
temporaryCacheNode.parallelRoutes = new Map(state.cache.parallelRoutes);
let data;
const fetchResponse = ()=>{
if (!data) {
data = (0, _createrecordfromthenable.createRecordFromThenable)((0, _fetchserverresponse.fetchServerResponse)(url, optimisticTree, state.nextUrl, state.buildId));
}
return data;
};
// TODO-APP: segments.slice(1) strips '', we can get rid of '' altogether.
// TODO-APP: re-evaluate if we need to strip the last segment
const optimisticFlightSegmentPath = segments.slice(1).map((segment)=>[
"children",
segment
]).flat();
// Copy existing cache nodes as far as possible and fill in `data` property with the started data fetch.
// The `data` property is used to suspend in layout-router during render if it hasn't resolved yet by the time it renders.
const res = (0, _fillcachewithdataproperty.fillCacheWithDataProperty)(temporaryCacheNode, state.cache, optimisticFlightSegmentPath, fetchResponse, true);
// If optimistic fetch couldn't happen it falls back to the non-optimistic case.
if (!(res == null ? void 0 : res.bailOptimistic)) {
mutable.previousTree = state.tree;
mutable.patchedTree = optimisticTree;
mutable.pendingPush = pendingPush;
mutable.hashFragment = hash;
mutable.shouldScroll = shouldScroll;
mutable.scrollableSegments = [];
mutable.cache = temporaryCacheNode;
mutable.canonicalUrl = href;
state.prefetchCache.set((0, _createhreffromurl.createHrefFromUrl)(url, false), {
data: (0, _createrecordfromthenable.createRecordFromThenable)(Promise.resolve(data)),
// this will make sure that the entry will be discarded after 30s
kind: _routerreducertypes.PrefetchKind.TEMPORARY,
prefetchTime: Date.now(),
treeAtTimeOfPrefetch: state.tree,
lastUsedTime: Date.now()
});
return (0, _handlemutable.handleMutable)(state, mutable);
}
}
// If we don't have a prefetch value, we need to create one
if (!prefetchValues) {
const data = (0, _createrecordfromthenable.createRecordFromThenable)((0, _fetchserverresponse.fetchServerResponse)(url, state.tree, state.nextUrl, state.buildId, // in dev, there's never gonna be a prefetch entry so we want to prefetch here
// in order to simulate the behavior of the prefetch cache
process.env.NODE_ENV === "development" ? _routerreducertypes.PrefetchKind.AUTO : undefined));
const newPrefetchValue = {
data: (0, _createrecordfromthenable.createRecordFromThenable)(Promise.resolve(data)),
// this will make sure that the entry will be discarded after 30s
kind: process.env.NODE_ENV === "development" ? _routerreducertypes.PrefetchKind.AUTO : _routerreducertypes.PrefetchKind.TEMPORARY,
prefetchTime: Date.now(),
treeAtTimeOfPrefetch: state.tree,
lastUsedTime: null
};
state.prefetchCache.set((0, _createhreffromurl.createHrefFromUrl)(url, false), newPrefetchValue);
prefetchValues = newPrefetchValue;
}
const prefetchEntryCacheStatus = (0, _getprefetchcacheentrystatus.getPrefetchEntryCacheStatus)(prefetchValues);
// The one before last item is the router state tree patch
const { treeAtTimeOfPrefetch, data } = prefetchValues;
_prefetchreducer.prefetchQueue.bump(data);
// Unwrap cache data with `use` to suspend here (in the reducer) until the fetch resolves.
const [flightData, canonicalUrlOverride] = (0, _readrecordvalue.readRecordValue)(data);
// we only want to mark this once
if (!prefetchValues.lastUsedTime) {
// important: we should only mark the cache node as dirty after we unsuspend from the call above
prefetchValues.lastUsedTime = Date.now();
}
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === "string") {
return handleExternalUrl(state, mutable, flightData, pendingPush);
}
let currentTree = state.tree;
let currentCache = state.cache;
let scrollableSegments = [];
for (const flightDataPath of flightData){
const flightSegmentPath = flightDataPath.slice(0, -4);
// The one before last item is the router state tree patch
const treePatch = flightDataPath.slice(-3)[0];
// TODO-APP: remove ''
const flightSegmentPathWithLeadingEmpty = [
"",
...flightSegmentPath
];
// Create new tree based on the flightSegmentPath and router state patch
let newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)(// TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty, currentTree, treePatch);
// If the tree patch can't be applied to the current tree then we use the tree at time of prefetch
// TODO-APP: This should instead fill in the missing pieces in `currentTree` with the data from `treeAtTimeOfPrefetch`, then apply the patch.
if (newTree === null) {
newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)(// TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty, treeAtTimeOfPrefetch, treePatch);
}
if (newTree !== null) {
if ((0, _isnavigatingtonewrootlayout.isNavigatingToNewRootLayout)(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, pendingPush);
}
let applied = (0, _applyflightdata.applyFlightData)(currentCache, cache, flightDataPath, prefetchValues.kind === "auto" && prefetchEntryCacheStatus === _getprefetchcacheentrystatus.PrefetchCacheEntryStatus.reusable);
if (!applied && prefetchEntryCacheStatus === _getprefetchcacheentrystatus.PrefetchCacheEntryStatus.stale) {
applied = addRefetchToLeafSegments(cache, currentCache, flightSegmentPath, treePatch, // eslint-disable-next-line no-loop-func
()=>(0, _fetchserverresponse.fetchServerResponse)(url, currentTree, state.nextUrl, state.buildId));
}
const hardNavigate = (0, _shouldhardnavigate.shouldHardNavigate)(// TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty, currentTree);
if (hardNavigate) {
cache.status = _approutercontextsharedruntime.CacheStates.READY;
// Copy subTreeData for the root node of the cache.
cache.subTreeData = currentCache.subTreeData;
(0, _invalidatecachebelowflightsegmentpath.invalidateCacheBelowFlightSegmentPath)(cache, currentCache, flightSegmentPath);
// Ensure the existing cache value is used when the cache was not invalidated.
mutable.cache = cache;
} else if (applied) {
mutable.cache = cache;
}
currentCache = cache;
currentTree = newTree;
for (const subSegment of generateSegmentsFromPatch(treePatch)){
const scrollableSegmentPath = [
...flightSegmentPath,
...subSegment
];
// Filter out the __DEFAULT__ paths as they shouldn't be scrolled to in this case.
if (scrollableSegmentPath[scrollableSegmentPath.length - 1] !== "__DEFAULT__") {
scrollableSegments.push(scrollableSegmentPath);
}
}
}
}
mutable.previousTree = state.tree;
mutable.patchedTree = currentTree;
mutable.canonicalUrl = canonicalUrlOverride ? (0, _createhreffromurl.createHrefFromUrl)(canonicalUrlOverride) : href;
mutable.pendingPush = pendingPush;
mutable.scrollableSegments = scrollableSegments;
mutable.hashFragment = hash;
mutable.shouldScroll = shouldScroll;
return (0, _handlemutable.handleMutable)(state, mutable);
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=navigate-reducer.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,4 @@
import { PrefetchAction, ReducerState, ReadonlyReducerState } from '../router-reducer-types';
import { PromiseQueue } from '../../promise-queue';
export declare const prefetchQueue: PromiseQueue;
export declare function prefetchReducer(state: ReadonlyReducerState, action: PrefetchAction): ReducerState;

View File

@@ -0,0 +1,77 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
prefetchQueue: null,
prefetchReducer: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
prefetchQueue: function() {
return prefetchQueue;
},
prefetchReducer: function() {
return prefetchReducer;
}
});
const _createhreffromurl = require("../create-href-from-url");
const _fetchserverresponse = require("../fetch-server-response");
const _routerreducertypes = require("../router-reducer-types");
const _createrecordfromthenable = require("../create-record-from-thenable");
const _pruneprefetchcache = require("./prune-prefetch-cache");
const _approuterheaders = require("../../app-router-headers");
const _promisequeue = require("../../promise-queue");
const prefetchQueue = new _promisequeue.PromiseQueue(5);
function prefetchReducer(state, action) {
// let's prune the prefetch cache before we do anything else
(0, _pruneprefetchcache.prunePrefetchCache)(state.prefetchCache);
const { url } = action;
url.searchParams.delete(_approuterheaders.NEXT_RSC_UNION_QUERY);
const href = (0, _createhreffromurl.createHrefFromUrl)(url, // Ensures the hash is not part of the cache key as it does not affect fetching the server
false);
const cacheEntry = state.prefetchCache.get(href);
if (cacheEntry) {
/**
* If the cache entry present was marked as temporary, it means that we prefetched it from the navigate reducer,
* where we didn't have the prefetch intent. We want to update it to the new, more accurate, kind here.
*/ if (cacheEntry.kind === _routerreducertypes.PrefetchKind.TEMPORARY) {
state.prefetchCache.set(href, {
...cacheEntry,
kind: action.kind
});
}
/**
* if the prefetch action was a full prefetch and that the current cache entry wasn't one, we want to re-prefetch,
* otherwise we can re-use the current cache entry
**/ if (!(cacheEntry.kind === _routerreducertypes.PrefetchKind.AUTO && action.kind === _routerreducertypes.PrefetchKind.FULL)) {
return state;
}
}
// fetchServerResponse is intentionally not awaited so that it can be unwrapped in the navigate-reducer
const serverResponse = (0, _createrecordfromthenable.createRecordFromThenable)(prefetchQueue.enqueue(()=>(0, _fetchserverresponse.fetchServerResponse)(url, // initialTree is used when history.state.tree is missing because the history state is set in `useEffect` below, it being missing means this is the hydration case.
state.tree, state.nextUrl, state.buildId, action.kind)));
// Create new tree based on the flightSegmentPath and router state patch
state.prefetchCache.set(href, {
// Create new tree based on the flightSegmentPath and router state patch
treeAtTimeOfPrefetch: state.tree,
data: serverResponse,
kind: action.kind,
prefetchTime: Date.now(),
lastUsedTime: null
});
return state;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=prefetch-reducer.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/prefetch-reducer.ts"],"names":["prefetchQueue","prefetchReducer","PromiseQueue","state","action","prunePrefetchCache","prefetchCache","url","searchParams","delete","NEXT_RSC_UNION_QUERY","href","createHrefFromUrl","cacheEntry","get","kind","PrefetchKind","TEMPORARY","set","AUTO","FULL","serverResponse","createRecordFromThenable","enqueue","fetchServerResponse","tree","nextUrl","buildId","treeAtTimeOfPrefetch","data","prefetchTime","Date","now","lastUsedTime"],"mappings":";;;;;;;;;;;;;;;IAaaA,aAAa;eAAbA;;IAEGC,eAAe;eAAfA;;;mCAfkB;qCACE;oCAM7B;0CACkC;oCACN;kCACE;8BACR;AAEtB,MAAMD,gBAAgB,IAAIE,0BAAY,CAAC;AAEvC,SAASD,gBACdE,KAA2B,EAC3BC,MAAsB;IAEtB,4DAA4D;IAC5DC,IAAAA,sCAAkB,EAACF,MAAMG,aAAa;IAEtC,MAAM,EAAEC,GAAG,EAAE,GAAGH;IAChBG,IAAIC,YAAY,CAACC,MAAM,CAACC,sCAAoB;IAE5C,MAAMC,OAAOC,IAAAA,oCAAiB,EAC5BL,KACA,0FAA0F;IAC1F;IAGF,MAAMM,aAAaV,MAAMG,aAAa,CAACQ,GAAG,CAACH;IAC3C,IAAIE,YAAY;QACd;;;KAGC,GACD,IAAIA,WAAWE,IAAI,KAAKC,gCAAY,CAACC,SAAS,EAAE;YAC9Cd,MAAMG,aAAa,CAACY,GAAG,CAACP,MAAM;gBAC5B,GAAGE,UAAU;gBACbE,MAAMX,OAAOW,IAAI;YACnB;QACF;QAEA;;;MAGE,GACF,IACE,CACEF,CAAAA,WAAWE,IAAI,KAAKC,gCAAY,CAACG,IAAI,IACrCf,OAAOW,IAAI,KAAKC,gCAAY,CAACI,IAAI,AAAD,GAElC;YACA,OAAOjB;QACT;IACF;IAEA,uGAAuG;IACvG,MAAMkB,iBAAiBC,IAAAA,kDAAwB,EAC7CtB,cAAcuB,OAAO,CAAC,IACpBC,IAAAA,wCAAmB,EACjBjB,KACA,mKAAmK;QACnKJ,MAAMsB,IAAI,EACVtB,MAAMuB,OAAO,EACbvB,MAAMwB,OAAO,EACbvB,OAAOW,IAAI;IAKjB,wEAAwE;IACxEZ,MAAMG,aAAa,CAACY,GAAG,CAACP,MAAM;QAC5B,wEAAwE;QACxEiB,sBAAsBzB,MAAMsB,IAAI;QAChCI,MAAMR;QACNN,MAAMX,OAAOW,IAAI;QACjBe,cAAcC,KAAKC,GAAG;QACtBC,cAAc;IAChB;IAEA,OAAO9B;AACT"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,2 @@
import type { ReducerState } from '../router-reducer-types';
export declare function prunePrefetchCache(prefetchCache: ReducerState['prefetchCache']): void;

View File

@@ -0,0 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "prunePrefetchCache", {
enumerable: true,
get: function() {
return prunePrefetchCache;
}
});
const _getprefetchcacheentrystatus = require("../get-prefetch-cache-entry-status");
function prunePrefetchCache(prefetchCache) {
for (const [href, prefetchCacheEntry] of prefetchCache){
if ((0, _getprefetchcacheentrystatus.getPrefetchEntryCacheStatus)(prefetchCacheEntry) === _getprefetchcacheentrystatus.PrefetchCacheEntryStatus.expired) {
prefetchCache.delete(href);
}
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=prune-prefetch-cache.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/prune-prefetch-cache.ts"],"names":["prunePrefetchCache","prefetchCache","href","prefetchCacheEntry","getPrefetchEntryCacheStatus","PrefetchCacheEntryStatus","expired","delete"],"mappings":";;;;+BAMgBA;;;eAAAA;;;6CAFT;AAEA,SAASA,mBACdC,aAA4C;IAE5C,KAAK,MAAM,CAACC,MAAMC,mBAAmB,IAAIF,cAAe;QACtD,IACEG,IAAAA,wDAA2B,EAACD,wBAC5BE,qDAAwB,CAACC,OAAO,EAChC;YACAL,cAAcM,MAAM,CAACL;QACvB;IACF;AACF"}

View File

@@ -0,0 +1,2 @@
import { ReadonlyReducerState, ReducerState, RefreshAction } from '../router-reducer-types';
export declare function refreshReducer(state: ReadonlyReducerState, action: RefreshAction): ReducerState;

View File

@@ -0,0 +1,94 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "refreshReducer", {
enumerable: true,
get: function() {
return refreshReducer;
}
});
const _fetchserverresponse = require("../fetch-server-response");
const _createrecordfromthenable = require("../create-record-from-thenable");
const _readrecordvalue = require("../read-record-value");
const _createhreffromurl = require("../create-href-from-url");
const _applyrouterstatepatchtotree = require("../apply-router-state-patch-to-tree");
const _isnavigatingtonewrootlayout = require("../is-navigating-to-new-root-layout");
const _navigatereducer = require("./navigate-reducer");
const _handlemutable = require("../handle-mutable");
const _approutercontextsharedruntime = require("../../../../shared/lib/app-router-context.shared-runtime");
const _filllazyitemstillleafwithhead = require("../fill-lazy-items-till-leaf-with-head");
function refreshReducer(state, action) {
const { cache, mutable, origin } = action;
const href = state.canonicalUrl;
let currentTree = state.tree;
const isForCurrentTree = JSON.stringify(mutable.previousTree) === JSON.stringify(currentTree);
if (isForCurrentTree) {
return (0, _handlemutable.handleMutable)(state, mutable);
}
if (!cache.data) {
// TODO-APP: verify that `href` is not an external url.
// Fetch data from the root of the tree.
cache.data = (0, _createrecordfromthenable.createRecordFromThenable)((0, _fetchserverresponse.fetchServerResponse)(new URL(href, origin), [
currentTree[0],
currentTree[1],
currentTree[2],
"refetch"
], state.nextUrl, state.buildId));
}
const [flightData, canonicalUrlOverride] = (0, _readrecordvalue.readRecordValue)(cache.data);
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === "string") {
return (0, _navigatereducer.handleExternalUrl)(state, mutable, flightData, state.pushRef.pendingPush);
}
// Remove cache.data as it has been resolved at this point.
cache.data = null;
for (const flightDataPath of flightData){
// FlightDataPath with more than two items means unexpected Flight data was returned
if (flightDataPath.length !== 3) {
// TODO-APP: handle this case better
console.log("REFRESH FAILED");
return state;
}
// Given the path can only have two items the items are only the router state and subTreeData for the root.
const [treePatch] = flightDataPath;
const newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)(// TODO-APP: remove ''
[
""
], currentTree, treePatch);
if (newTree === null) {
throw new Error("SEGMENT MISMATCH");
}
if ((0, _isnavigatingtonewrootlayout.isNavigatingToNewRootLayout)(currentTree, newTree)) {
return (0, _navigatereducer.handleExternalUrl)(state, mutable, href, state.pushRef.pendingPush);
}
const canonicalUrlOverrideHref = canonicalUrlOverride ? (0, _createhreffromurl.createHrefFromUrl)(canonicalUrlOverride) : undefined;
if (canonicalUrlOverride) {
mutable.canonicalUrl = canonicalUrlOverrideHref;
}
// The one before last item is the router state tree patch
const [subTreeData, head] = flightDataPath.slice(-2);
// Handles case where prefetch only returns the router tree patch without rendered components.
if (subTreeData !== null) {
cache.status = _approutercontextsharedruntime.CacheStates.READY;
cache.subTreeData = subTreeData;
(0, _filllazyitemstillleafwithhead.fillLazyItemsTillLeafWithHead)(cache, // Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache.
undefined, treePatch, head);
mutable.cache = cache;
mutable.prefetchCache = new Map();
}
mutable.previousTree = currentTree;
mutable.patchedTree = newTree;
mutable.canonicalUrl = href;
currentTree = newTree;
}
return (0, _handlemutable.handleMutable)(state, mutable);
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=refresh-reducer.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/refresh-reducer.ts"],"names":["refreshReducer","state","action","cache","mutable","origin","href","canonicalUrl","currentTree","tree","isForCurrentTree","JSON","stringify","previousTree","handleMutable","data","createRecordFromThenable","fetchServerResponse","URL","nextUrl","buildId","flightData","canonicalUrlOverride","readRecordValue","handleExternalUrl","pushRef","pendingPush","flightDataPath","length","console","log","treePatch","newTree","applyRouterStatePatchToTree","Error","isNavigatingToNewRootLayout","canonicalUrlOverrideHref","createHrefFromUrl","undefined","subTreeData","head","slice","status","CacheStates","READY","fillLazyItemsTillLeafWithHead","prefetchCache","Map","patchedTree"],"mappings":";;;;+BAgBgBA;;;eAAAA;;;qCAhBoB;0CACK;iCACT;mCACE;6CACU;6CACA;iCAMV;+BACJ;+CACF;+CACkB;AAEvC,SAASA,eACdC,KAA2B,EAC3BC,MAAqB;IAErB,MAAM,EAAEC,KAAK,EAAEC,OAAO,EAAEC,MAAM,EAAE,GAAGH;IACnC,MAAMI,OAAOL,MAAMM,YAAY;IAE/B,IAAIC,cAAcP,MAAMQ,IAAI;IAE5B,MAAMC,mBACJC,KAAKC,SAAS,CAACR,QAAQS,YAAY,MAAMF,KAAKC,SAAS,CAACJ;IAE1D,IAAIE,kBAAkB;QACpB,OAAOI,IAAAA,4BAAa,EAACb,OAAOG;IAC9B;IAEA,IAAI,CAACD,MAAMY,IAAI,EAAE;QACf,uDAAuD;QACvD,wCAAwC;QACxCZ,MAAMY,IAAI,GAAGC,IAAAA,kDAAwB,EACnCC,IAAAA,wCAAmB,EACjB,IAAIC,IAAIZ,MAAMD,SACd;YAACG,WAAW,CAAC,EAAE;YAAEA,WAAW,CAAC,EAAE;YAAEA,WAAW,CAAC,EAAE;YAAE;SAAU,EAC3DP,MAAMkB,OAAO,EACblB,MAAMmB,OAAO;IAGnB;IACA,MAAM,CAACC,YAAYC,qBAAqB,GAAGC,IAAAA,gCAAe,EAACpB,MAAMY,IAAI;IAErE,4DAA4D;IAC5D,IAAI,OAAOM,eAAe,UAAU;QAClC,OAAOG,IAAAA,kCAAiB,EACtBvB,OACAG,SACAiB,YACApB,MAAMwB,OAAO,CAACC,WAAW;IAE7B;IAEA,2DAA2D;IAC3DvB,MAAMY,IAAI,GAAG;IAEb,KAAK,MAAMY,kBAAkBN,WAAY;QACvC,oFAAoF;QACpF,IAAIM,eAAeC,MAAM,KAAK,GAAG;YAC/B,oCAAoC;YACpCC,QAAQC,GAAG,CAAC;YACZ,OAAO7B;QACT;QAEA,2GAA2G;QAC3G,MAAM,CAAC8B,UAAU,GAAGJ;QACpB,MAAMK,UAAUC,IAAAA,wDAA2B,EACzC,sBAAsB;QACtB;YAAC;SAAG,EACJzB,aACAuB;QAGF,IAAIC,YAAY,MAAM;YACpB,MAAM,IAAIE,MAAM;QAClB;QAEA,IAAIC,IAAAA,wDAA2B,EAAC3B,aAAawB,UAAU;YACrD,OAAOR,IAAAA,kCAAiB,EAACvB,OAAOG,SAASE,MAAML,MAAMwB,OAAO,CAACC,WAAW;QAC1E;QAEA,MAAMU,2BAA2Bd,uBAC7Be,IAAAA,oCAAiB,EAACf,wBAClBgB;QAEJ,IAAIhB,sBAAsB;YACxBlB,QAAQG,YAAY,GAAG6B;QACzB;QAEA,0DAA0D;QAC1D,MAAM,CAACG,aAAaC,KAAK,GAAGb,eAAec,KAAK,CAAC,CAAC;QAElD,8FAA8F;QAC9F,IAAIF,gBAAgB,MAAM;YACxBpC,MAAMuC,MAAM,GAAGC,0CAAW,CAACC,KAAK;YAChCzC,MAAMoC,WAAW,GAAGA;YACpBM,IAAAA,4DAA6B,EAC3B1C,OACA,4FAA4F;YAC5FmC,WACAP,WACAS;YAEFpC,QAAQD,KAAK,GAAGA;YAChBC,QAAQ0C,aAAa,GAAG,IAAIC;QAC9B;QAEA3C,QAAQS,YAAY,GAAGL;QACvBJ,QAAQ4C,WAAW,GAAGhB;QACtB5B,QAAQG,YAAY,GAAGD;QAEvBE,cAAcwB;IAChB;IAEA,OAAOlB,IAAAA,4BAAa,EAACb,OAAOG;AAC9B"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,2 @@
import { ReadonlyReducerState, ReducerState, RestoreAction } from '../router-reducer-types';
export declare function restoreReducer(state: ReadonlyReducerState, action: RestoreAction): ReducerState;

View File

@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "restoreReducer", {
enumerable: true,
get: function() {
return restoreReducer;
}
});
const _createhreffromurl = require("../create-href-from-url");
function restoreReducer(state, action) {
const { url, tree } = action;
const href = (0, _createhreffromurl.createHrefFromUrl)(url);
return {
buildId: state.buildId,
// Set canonical url
canonicalUrl: href,
pushRef: state.pushRef,
focusAndScrollRef: state.focusAndScrollRef,
cache: state.cache,
prefetchCache: state.prefetchCache,
// Restore provided tree
tree: tree,
nextUrl: url.pathname
};
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=restore-reducer.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/restore-reducer.ts"],"names":["restoreReducer","state","action","url","tree","href","createHrefFromUrl","buildId","canonicalUrl","pushRef","focusAndScrollRef","cache","prefetchCache","nextUrl","pathname"],"mappings":";;;;+BAOgBA;;;eAAAA;;;mCAPkB;AAO3B,SAASA,eACdC,KAA2B,EAC3BC,MAAqB;IAErB,MAAM,EAAEC,GAAG,EAAEC,IAAI,EAAE,GAAGF;IACtB,MAAMG,OAAOC,IAAAA,oCAAiB,EAACH;IAE/B,OAAO;QACLI,SAASN,MAAMM,OAAO;QACtB,oBAAoB;QACpBC,cAAcH;QACdI,SAASR,MAAMQ,OAAO;QACtBC,mBAAmBT,MAAMS,iBAAiB;QAC1CC,OAAOV,MAAMU,KAAK;QAClBC,eAAeX,MAAMW,aAAa;QAClC,wBAAwB;QACxBR,MAAMA;QACNS,SAASV,IAAIW,QAAQ;IACvB;AACF"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,2 @@
import { ReadonlyReducerState, ReducerState, ServerActionAction } from '../router-reducer-types';
export declare function serverActionReducer(state: ReadonlyReducerState, action: ServerActionAction): ReducerState;

View File

@@ -0,0 +1,209 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "serverActionReducer", {
enumerable: true,
get: function() {
return serverActionReducer;
}
});
const _appcallserver = require("../../../app-call-server");
const _approuterheaders = require("../../app-router-headers");
const _createrecordfromthenable = require("../create-record-from-thenable");
const _readrecordvalue = require("../read-record-value");
const _addbasepath = require("../../../add-base-path");
const _createhreffromurl = require("../create-href-from-url");
const _navigatereducer = require("./navigate-reducer");
const _applyrouterstatepatchtotree = require("../apply-router-state-patch-to-tree");
const _isnavigatingtonewrootlayout = require("../is-navigating-to-new-root-layout");
const _approutercontextsharedruntime = require("../../../../shared/lib/app-router-context.shared-runtime");
const _handlemutable = require("../handle-mutable");
const _filllazyitemstillleafwithhead = require("../fill-lazy-items-till-leaf-with-head");
// // eslint-disable-next-line import/no-extraneous-dependencies
// import { createFromFetch } from 'react-server-dom-webpack/client'
// // eslint-disable-next-line import/no-extraneous-dependencies
// import { encodeReply } from 'react-server-dom-webpack/client'
const { createFromFetch, encodeReply } = !!process.env.NEXT_RUNTIME ? require("react-server-dom-webpack/client.edge") : require("react-server-dom-webpack/client");
async function fetchServerAction(state, param) {
let { actionId, actionArgs } = param;
const body = await encodeReply(actionArgs);
const res = await fetch("", {
method: "POST",
headers: {
Accept: _approuterheaders.RSC_CONTENT_TYPE_HEADER,
[_approuterheaders.ACTION]: actionId,
[_approuterheaders.NEXT_ROUTER_STATE_TREE]: encodeURIComponent(JSON.stringify(state.tree)),
...process.env.__NEXT_ACTIONS_DEPLOYMENT_ID && process.env.NEXT_DEPLOYMENT_ID ? {
"x-deployment-id": process.env.NEXT_DEPLOYMENT_ID
} : {},
...state.nextUrl ? {
[_approuterheaders.NEXT_URL]: state.nextUrl
} : {}
},
body
});
const location = res.headers.get("x-action-redirect");
let revalidatedParts;
try {
const revalidatedHeader = JSON.parse(res.headers.get("x-action-revalidated") || "[[],0,0]");
revalidatedParts = {
paths: revalidatedHeader[0] || [],
tag: !!revalidatedHeader[1],
cookie: revalidatedHeader[2]
};
} catch (e) {
revalidatedParts = {
paths: [],
tag: false,
cookie: false
};
}
const redirectLocation = location ? new URL((0, _addbasepath.addBasePath)(location), // Ensure relative redirects in Server Actions work, e.g. redirect('./somewhere-else')
new URL(state.canonicalUrl, window.location.href)) : undefined;
let isFlightResponse = res.headers.get("content-type") === _approuterheaders.RSC_CONTENT_TYPE_HEADER;
if (isFlightResponse) {
const response = await createFromFetch(Promise.resolve(res), {
callServer: _appcallserver.callServer
});
if (location) {
// if it was a redirection, then result is just a regular RSC payload
const [, actionFlightData] = response != null ? response : [];
return {
actionFlightData: actionFlightData,
redirectLocation,
revalidatedParts
};
}
// otherwise it's a tuple of [actionResult, actionFlightData]
const [actionResult, [, actionFlightData]] = response != null ? response : [];
return {
actionResult,
actionFlightData,
redirectLocation,
revalidatedParts
};
}
return {
redirectLocation,
revalidatedParts
};
}
function serverActionReducer(state, action) {
const { mutable, cache, resolve, reject } = action;
const href = state.canonicalUrl;
let currentTree = state.tree;
const isForCurrentTree = JSON.stringify(mutable.previousTree) === JSON.stringify(currentTree);
if (isForCurrentTree) {
return (0, _handlemutable.handleMutable)(state, mutable);
}
if (mutable.inFlightServerAction) {
// unblock if a navigation event comes through
// while we've suspended on an action
if (mutable.globalMutable.pendingNavigatePath && mutable.globalMutable.pendingNavigatePath !== href) {
mutable.inFlightServerAction.then(()=>{
if (mutable.actionResultResolved) return;
// if the server action resolves after a navigation took place,
// reset ServerActionMutable values & trigger a refresh so that any stale data gets updated
mutable.inFlightServerAction = null;
mutable.globalMutable.pendingNavigatePath = undefined;
mutable.globalMutable.refresh();
mutable.actionResultResolved = true;
});
return state;
}
} else {
mutable.inFlightServerAction = (0, _createrecordfromthenable.createRecordFromThenable)(fetchServerAction(state, action));
}
// TODO-APP: Make try/catch wrap only readRecordValue so that other errors bubble up through the reducer instead.
try {
// suspends until the server action is resolved.
const { actionResult, actionFlightData: flightData, redirectLocation } = (0, _readrecordvalue.readRecordValue)(mutable.inFlightServerAction);
// Make sure the redirection is a push instead of a replace.
// Issue: https://github.com/vercel/next.js/issues/53911
if (redirectLocation) {
state.pushRef.pendingPush = true;
mutable.pendingPush = true;
}
mutable.previousTree = state.tree;
if (!flightData) {
if (!mutable.actionResultResolved) {
resolve(actionResult);
mutable.actionResultResolved = true;
}
// If there is a redirect but no flight data we need to do a mpaNavigation.
if (redirectLocation) {
return (0, _navigatereducer.handleExternalUrl)(state, mutable, redirectLocation.href, state.pushRef.pendingPush);
}
return state;
}
if (typeof flightData === "string") {
// Handle case when navigating to page in `pages` from `app`
return (0, _navigatereducer.handleExternalUrl)(state, mutable, flightData, state.pushRef.pendingPush);
}
// Remove cache.data as it has been resolved at this point.
mutable.inFlightServerAction = null;
for (const flightDataPath of flightData){
// FlightDataPath with more than two items means unexpected Flight data was returned
if (flightDataPath.length !== 3) {
// TODO-APP: handle this case better
console.log("SERVER ACTION APPLY FAILED");
return state;
}
// Given the path can only have two items the items are only the router state and subTreeData for the root.
const [treePatch] = flightDataPath;
const newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)(// TODO-APP: remove ''
[
""
], currentTree, treePatch);
if (newTree === null) {
throw new Error("SEGMENT MISMATCH");
}
if ((0, _isnavigatingtonewrootlayout.isNavigatingToNewRootLayout)(currentTree, newTree)) {
return (0, _navigatereducer.handleExternalUrl)(state, mutable, href, state.pushRef.pendingPush);
}
// The one before last item is the router state tree patch
const [subTreeData, head] = flightDataPath.slice(-2);
// Handles case where prefetch only returns the router tree patch without rendered components.
if (subTreeData !== null) {
cache.status = _approutercontextsharedruntime.CacheStates.READY;
cache.subTreeData = subTreeData;
(0, _filllazyitemstillleafwithhead.fillLazyItemsTillLeafWithHead)(cache, // Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache.
undefined, treePatch, head);
mutable.cache = cache;
mutable.prefetchCache = new Map();
}
mutable.previousTree = currentTree;
mutable.patchedTree = newTree;
mutable.canonicalUrl = href;
currentTree = newTree;
}
if (redirectLocation) {
const newHref = (0, _createhreffromurl.createHrefFromUrl)(redirectLocation, false);
mutable.canonicalUrl = newHref;
}
if (!mutable.actionResultResolved) {
resolve(actionResult);
mutable.actionResultResolved = true;
}
return (0, _handlemutable.handleMutable)(state, mutable);
} catch (e) {
if (e.status === "rejected") {
if (!mutable.actionResultResolved) {
reject(e.value);
mutable.actionResultResolved = true;
}
// When the server action is rejected we don't update the state and instead call the reject handler of the promise.
return state;
}
throw e;
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=server-action-reducer.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
import { ServerPatchAction, ReducerState, ReadonlyReducerState } from '../router-reducer-types';
export declare function serverPatchReducer(state: ReadonlyReducerState, action: ServerPatchAction): ReducerState;

View File

@@ -0,0 +1,72 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "serverPatchReducer", {
enumerable: true,
get: function() {
return serverPatchReducer;
}
});
const _createhreffromurl = require("../create-href-from-url");
const _applyrouterstatepatchtotree = require("../apply-router-state-patch-to-tree");
const _isnavigatingtonewrootlayout = require("../is-navigating-to-new-root-layout");
const _navigatereducer = require("./navigate-reducer");
const _applyflightdata = require("../apply-flight-data");
const _handlemutable = require("../handle-mutable");
function serverPatchReducer(state, action) {
const { flightData, previousTree, overrideCanonicalUrl, cache, mutable } = action;
const isForCurrentTree = JSON.stringify(previousTree) === JSON.stringify(state.tree);
// When a fetch is slow to resolve it could be that you navigated away while the request was happening or before the reducer runs.
// In that case opt-out of applying the patch given that the data could be stale.
if (!isForCurrentTree) {
// TODO-APP: Handle tree mismatch
console.log("TREE MISMATCH");
// Keep everything as-is.
return state;
}
if (mutable.previousTree) {
return (0, _handlemutable.handleMutable)(state, mutable);
}
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === "string") {
return (0, _navigatereducer.handleExternalUrl)(state, mutable, flightData, state.pushRef.pendingPush);
}
let currentTree = state.tree;
let currentCache = state.cache;
for (const flightDataPath of flightData){
// Slices off the last segment (which is at -4) as it doesn't exist in the tree yet
const flightSegmentPath = flightDataPath.slice(0, -4);
const [treePatch] = flightDataPath.slice(-3, -2);
const newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)(// TODO-APP: remove ''
[
"",
...flightSegmentPath
], currentTree, treePatch);
if (newTree === null) {
throw new Error("SEGMENT MISMATCH");
}
if ((0, _isnavigatingtonewrootlayout.isNavigatingToNewRootLayout)(currentTree, newTree)) {
return (0, _navigatereducer.handleExternalUrl)(state, mutable, state.canonicalUrl, state.pushRef.pendingPush);
}
const canonicalUrlOverrideHref = overrideCanonicalUrl ? (0, _createhreffromurl.createHrefFromUrl)(overrideCanonicalUrl) : undefined;
if (canonicalUrlOverrideHref) {
mutable.canonicalUrl = canonicalUrlOverrideHref;
}
(0, _applyflightdata.applyFlightData)(currentCache, cache, flightDataPath);
mutable.previousTree = currentTree;
mutable.patchedTree = newTree;
mutable.cache = cache;
currentCache = cache;
currentTree = newTree;
}
return (0, _handlemutable.handleMutable)(state, mutable);
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=server-patch-reducer.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/server-patch-reducer.ts"],"names":["serverPatchReducer","state","action","flightData","previousTree","overrideCanonicalUrl","cache","mutable","isForCurrentTree","JSON","stringify","tree","console","log","handleMutable","handleExternalUrl","pushRef","pendingPush","currentTree","currentCache","flightDataPath","flightSegmentPath","slice","treePatch","newTree","applyRouterStatePatchToTree","Error","isNavigatingToNewRootLayout","canonicalUrl","canonicalUrlOverrideHref","createHrefFromUrl","undefined","applyFlightData","patchedTree"],"mappings":";;;;+BAYgBA;;;eAAAA;;;mCAZkB;6CACU;6CACA;iCAMV;iCACF;+BACF;AAEvB,SAASA,mBACdC,KAA2B,EAC3BC,MAAyB;IAEzB,MAAM,EAAEC,UAAU,EAAEC,YAAY,EAAEC,oBAAoB,EAAEC,KAAK,EAAEC,OAAO,EAAE,GACtEL;IAEF,MAAMM,mBACJC,KAAKC,SAAS,CAACN,kBAAkBK,KAAKC,SAAS,CAACT,MAAMU,IAAI;IAE5D,kIAAkI;IAClI,iFAAiF;IACjF,IAAI,CAACH,kBAAkB;QACrB,iCAAiC;QACjCI,QAAQC,GAAG,CAAC;QACZ,yBAAyB;QACzB,OAAOZ;IACT;IAEA,IAAIM,QAAQH,YAAY,EAAE;QACxB,OAAOU,IAAAA,4BAAa,EAACb,OAAOM;IAC9B;IAEA,4DAA4D;IAC5D,IAAI,OAAOJ,eAAe,UAAU;QAClC,OAAOY,IAAAA,kCAAiB,EACtBd,OACAM,SACAJ,YACAF,MAAMe,OAAO,CAACC,WAAW;IAE7B;IAEA,IAAIC,cAAcjB,MAAMU,IAAI;IAC5B,IAAIQ,eAAelB,MAAMK,KAAK;IAE9B,KAAK,MAAMc,kBAAkBjB,WAAY;QACvC,mFAAmF;QACnF,MAAMkB,oBAAoBD,eAAeE,KAAK,CAAC,GAAG,CAAC;QAEnD,MAAM,CAACC,UAAU,GAAGH,eAAeE,KAAK,CAAC,CAAC,GAAG,CAAC;QAC9C,MAAME,UAAUC,IAAAA,wDAA2B,EACzC,sBAAsB;QACtB;YAAC;eAAOJ;SAAkB,EAC1BH,aACAK;QAGF,IAAIC,YAAY,MAAM;YACpB,MAAM,IAAIE,MAAM;QAClB;QAEA,IAAIC,IAAAA,wDAA2B,EAACT,aAAaM,UAAU;YACrD,OAAOT,IAAAA,kCAAiB,EACtBd,OACAM,SACAN,MAAM2B,YAAY,EAClB3B,MAAMe,OAAO,CAACC,WAAW;QAE7B;QAEA,MAAMY,2BAA2BxB,uBAC7ByB,IAAAA,oCAAiB,EAACzB,wBAClB0B;QAEJ,IAAIF,0BAA0B;YAC5BtB,QAAQqB,YAAY,GAAGC;QACzB;QAEAG,IAAAA,gCAAe,EAACb,cAAcb,OAAOc;QAErCb,QAAQH,YAAY,GAAGc;QACvBX,QAAQ0B,WAAW,GAAGT;QACtBjB,QAAQD,KAAK,GAAGA;QAEhBa,eAAeb;QACfY,cAAcM;IAChB;IAEA,OAAOV,IAAAA,4BAAa,EAACb,OAAOM;AAC9B"}

View File

@@ -0,0 +1 @@
export {};