Unverified Commit b425b40a authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Replace custom Thenable type with native Promises (#58337)

Next.js's implementation includes a custom Thenable type based on a
similar one used in React's codebase. It was used to implement a
userspace equivalent of the React.use API before that API became stable,
by throwing a promise-like object and tracking the status on an expando
field. However, it didn't cover all the same cases and behaviors that
React.use does, which led to some subtle bugs like the one fixed by
@ztanner in https://github.com/vercel/next.js/pull/55690.

Now that React.use is stable, and we use that for suspending instead of
throwing a promise, we no longer need our custom Thenable type. I've
removed the type and associated functions, and updated our types to use
Promise instead.

Even in cases where a function does return a thenable-object rather than
a native promise, like React Flight's createFromFetch, we should use
TypeScript's built-in PromiseLike utility. Currently, though, we always
await these objects anyway (in fetch-server-response.ts), which turns
them into promises. So Promise is almost always sufficient.
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 00f5b5e7
...@@ -27,7 +27,6 @@ import { RedirectBoundary } from './redirect-boundary' ...@@ -27,7 +27,6 @@ import { RedirectBoundary } from './redirect-boundary'
import { NotFoundBoundary } from './not-found-boundary' import { NotFoundBoundary } from './not-found-boundary'
import { getSegmentValue } from './router-reducer/reducers/get-segment-value' import { getSegmentValue } from './router-reducer/reducers/get-segment-value'
import { createRouterCacheKey } from './router-reducer/create-router-cache-key' import { createRouterCacheKey } from './router-reducer/create-router-cache-key'
import { createRecordFromThenable } from './router-reducer/create-record-from-thenable'
/** /**
* Add refetch marker to router state at the point of the current layout segment. * Add refetch marker to router state at the point of the current layout segment.
...@@ -379,13 +378,11 @@ function InnerLayoutRouter({ ...@@ -379,13 +378,11 @@ function InnerLayoutRouter({
childNode = { childNode = {
status: CacheStates.DATA_FETCH, status: CacheStates.DATA_FETCH,
data: createRecordFromThenable( data: fetchServerResponse(
fetchServerResponse( new URL(url, location.origin),
new URL(url, location.origin), refetchTree,
refetchTree, context.nextUrl,
context.nextUrl, buildId
buildId
)
), ),
subTreeData: null, subTreeData: null,
head: head:
......
import type { ThenableRecord } from './router-reducer/router-reducer-types'
/* /*
This is a simple promise queue that allows you to limit the number of concurrent promises This is a simple promise queue that allows you to limit the number of concurrent promises
that are running at any given time. It's used to limit the number of concurrent that are running at any given time. It's used to limit the number of concurrent
...@@ -10,7 +8,7 @@ export class PromiseQueue { ...@@ -10,7 +8,7 @@ export class PromiseQueue {
#maxConcurrency: number #maxConcurrency: number
#runningCount: number #runningCount: number
#queue: Array<{ #queue: Array<{
promiseFn: ThenableRecord<any> | Promise<any> promiseFn: Promise<any>
task: () => void task: () => void
}> }>
...@@ -50,7 +48,7 @@ export class PromiseQueue { ...@@ -50,7 +48,7 @@ export class PromiseQueue {
return taskPromise return taskPromise
} }
bump(promiseFn: ThenableRecord<any> | Promise<any>) { bump(promiseFn: Promise<any>) {
const index = this.#queue.findIndex((item) => item.promiseFn === promiseFn) const index = this.#queue.findIndex((item) => item.promiseFn === promiseFn)
if (index > -1) { if (index > -1) {
......
import { createRecordFromThenable } from './create-record-from-thenable'
describe('createRecordFromThenable', () => {
it('successful promise', async () => {
const thenable = Promise.resolve('success')
const record = createRecordFromThenable(thenable)
expect(record.status).toBe('pending')
await thenable
expect(record.status).toBe('fulfilled')
// typeguard
if (record.status !== 'fulfilled') {
throw new Error('Invalid Type')
}
expect(record.value).toBe('success')
})
it('rejecting promise', async () => {
const thenable = Promise.reject('error')
const record = createRecordFromThenable(thenable)
expect(record.status).toBe('pending')
await thenable.catch(() => {})
expect(record.status).toBe('rejected')
// typeguard
if (record.status !== 'rejected') {
throw new Error('Invalid Type')
}
expect(record.reason).toBe('error')
})
})
import type { ThenableRecord } from './router-reducer-types'
/**
* Create data fetching record for Promise.
*/
export function createRecordFromThenable<T>(
promise: PromiseLike<T>
): ThenableRecord<T> {
const thenable = promise as any
thenable.status = 'pending'
thenable.then(
(value: any) => {
if (thenable.status === 'pending') {
thenable.status = 'fulfilled'
thenable.value = value
}
},
(err: any) => {
if (thenable.status === 'pending') {
thenable.status = 'rejected'
thenable.reason = err
}
}
)
return thenable
}
...@@ -3,19 +3,16 @@ import type { FetchServerResponseResult } from './fetch-server-response' ...@@ -3,19 +3,16 @@ import type { FetchServerResponseResult } from './fetch-server-response'
import { fillCacheWithDataProperty } from './fill-cache-with-data-property' import { fillCacheWithDataProperty } from './fill-cache-with-data-property'
import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime' import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime'
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime' import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime'
import { createRecordFromThenable } from './create-record-from-thenable'
import type { ThenableRecord } from './router-reducer-types'
describe('fillCacheWithDataProperty', () => { describe('fillCacheWithDataProperty', () => {
it('should add data property', () => { it('should add data property', () => {
const fetchServerResponseMock: jest.Mock< const fetchServerResponseMock: jest.Mock<
ThenableRecord<FetchServerResponseResult> Promise<FetchServerResponseResult>
> = jest.fn(() => > = jest.fn(() =>
createRecordFromThenable( Promise.resolve([
Promise.resolve([ /* TODO-APP: replace with actual FlightData */ '',
/* TODO-APP: replace with actual FlightData */ '', undefined,
undefined, ])
])
)
) )
const pathname = '/dashboard/settings' const pathname = '/dashboard/settings'
const segments = pathname.split('/') const segments = pathname.split('/')
...@@ -97,9 +94,7 @@ describe('fillCacheWithDataProperty', () => { ...@@ -97,9 +94,7 @@ describe('fillCacheWithDataProperty', () => {
</React.Fragment>, </React.Fragment>,
}, },
"dashboard" => { "dashboard" => {
"data": Promise { "data": Promise {},
"status": "pending",
},
"parallelRoutes": Map {}, "parallelRoutes": Map {},
"status": "DATAFETCH", "status": "DATAFETCH",
"subTreeData": null, "subTreeData": null,
......
import type { FetchServerResponseResult } from './fetch-server-response' import type { FetchServerResponseResult } from './fetch-server-response'
import type { ThenableRecord } from './router-reducer-types'
import type { FlightSegmentPath } from '../../../server/app-render/types' import type { FlightSegmentPath } from '../../../server/app-render/types'
import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime' import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime'
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime' import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime'
...@@ -12,7 +11,7 @@ export function fillCacheWithDataProperty( ...@@ -12,7 +11,7 @@ export function fillCacheWithDataProperty(
newCache: CacheNode, newCache: CacheNode,
existingCache: CacheNode, existingCache: CacheNode,
flightSegmentPath: FlightSegmentPath, flightSegmentPath: FlightSegmentPath,
fetchResponse: () => ThenableRecord<FetchServerResponseResult>, fetchResponse: () => Promise<FetchServerResponseResult>,
bailOnParallelRoutes: boolean = false bailOnParallelRoutes: boolean = false
): { bailOptimistic: boolean } | undefined { ): { bailOptimistic: boolean } | undefined {
const isLastEntry = flightSegmentPath.length <= 2 const isLastEntry = flightSegmentPath.length <= 2
......
import { fetchServerResponse } from '../fetch-server-response' import { fetchServerResponse } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable'
import { createHrefFromUrl } from '../create-href-from-url' import { createHrefFromUrl } from '../create-href-from-url'
import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree' import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'
import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout' import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
...@@ -30,13 +29,11 @@ function fastRefreshReducerImpl( ...@@ -30,13 +29,11 @@ function fastRefreshReducerImpl(
if (!cache.data) { if (!cache.data) {
// TODO-APP: verify that `href` is not an external url. // TODO-APP: verify that `href` is not an external url.
// Fetch data from the root of the tree. // Fetch data from the root of the tree.
cache.data = createRecordFromThenable( cache.data = fetchServerResponse(
fetchServerResponse( new URL(href, origin),
new URL(href, origin), [state.tree[0], state.tree[1], state.tree[2], 'refetch'],
[state.tree[0], state.tree[1], state.tree[2], 'refetch'], state.nextUrl,
state.nextUrl, state.buildId
state.buildId
)
) )
} }
......
...@@ -274,37 +274,7 @@ describe('navigateReducer', () => { ...@@ -274,37 +274,7 @@ describe('navigateReducer', () => {
"nextUrl": "/linking/about", "nextUrl": "/linking/about",
"prefetchCache": Map { "prefetchCache": Map {
"/linking/about" => { "/linking/about" => {
"data": Promise { "data": Promise {},
"status": "fulfilled",
"value": [
[
[
"children",
"linking",
"children",
"about",
[
"about",
{
"children": [
"__PAGE__",
{},
],
},
],
<h1>
About Page!
</h1>,
<React.Fragment>
<title>
About page!
</title>
</React.Fragment>,
],
],
undefined,
],
},
"kind": "temporary", "kind": "temporary",
"lastUsedTime": 1690329600000, "lastUsedTime": 1690329600000,
"prefetchTime": 1690329600000, "prefetchTime": 1690329600000,
...@@ -973,37 +943,7 @@ describe('navigateReducer', () => { ...@@ -973,37 +943,7 @@ describe('navigateReducer', () => {
</React.Fragment>, </React.Fragment>,
}, },
"about" => { "about" => {
"data": Promise { "data": Promise {},
"status": "fulfilled",
"value": [
[
[
"children",
"linking",
"children",
"about",
[
"about",
{
"children": [
"__PAGE__",
{},
],
},
],
<h1>
About Page!
</h1>,
<React.Fragment>
<title>
About page!
</title>
</React.Fragment>,
],
],
undefined,
],
},
"parallelRoutes": Map {}, "parallelRoutes": Map {},
"status": "DATAFETCH", "status": "DATAFETCH",
"subTreeData": null, "subTreeData": null,
...@@ -1422,37 +1362,7 @@ describe('navigateReducer', () => { ...@@ -1422,37 +1362,7 @@ describe('navigateReducer', () => {
"nextUrl": "/linking/about", "nextUrl": "/linking/about",
"prefetchCache": Map { "prefetchCache": Map {
"/linking/about" => { "/linking/about" => {
"data": Promise { "data": Promise {},
"status": "fulfilled",
"value": [
[
[
"children",
"linking",
"children",
"about",
[
"about",
{
"children": [
"__PAGE__",
{},
],
},
],
<h1>
About Page!
</h1>,
<React.Fragment>
<title>
About page!
</title>
</React.Fragment>,
],
],
undefined,
],
},
"kind": "auto", "kind": "auto",
"lastUsedTime": null, "lastUsedTime": null,
"prefetchTime": 1690329600000, "prefetchTime": 1690329600000,
...@@ -2063,37 +1973,7 @@ describe('navigateReducer', () => { ...@@ -2063,37 +1973,7 @@ describe('navigateReducer', () => {
"nextUrl": "/linking/about", "nextUrl": "/linking/about",
"prefetchCache": Map { "prefetchCache": Map {
"/linking/about" => { "/linking/about" => {
"data": Promise { "data": Promise {},
"status": "fulfilled",
"value": [
[
[
"children",
"linking",
"children",
"about",
[
"about",
{
"children": [
"__PAGE__",
{},
],
},
],
<h1>
About Page!
</h1>,
<React.Fragment>
<title>
About page!
</title>
</React.Fragment>,
],
],
undefined,
],
},
"kind": "temporary", "kind": "temporary",
"lastUsedTime": 1690329600000, "lastUsedTime": 1690329600000,
"prefetchTime": 1690329600000, "prefetchTime": 1690329600000,
......
...@@ -6,7 +6,6 @@ import type { ...@@ -6,7 +6,6 @@ import type {
} from '../../../../server/app-render/types' } from '../../../../server/app-render/types'
import { fetchServerResponse } from '../fetch-server-response' import { fetchServerResponse } from '../fetch-server-response'
import type { FetchServerResponseResult } from '../fetch-server-response' import type { FetchServerResponseResult } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable'
import { createHrefFromUrl } from '../create-href-from-url' import { createHrefFromUrl } from '../create-href-from-url'
import { invalidateCacheBelowFlightSegmentPath } from '../invalidate-cache-below-flight-segmentpath' import { invalidateCacheBelowFlightSegmentPath } from '../invalidate-cache-below-flight-segmentpath'
import { fillCacheWithDataProperty } from '../fill-cache-with-data-property' import { fillCacheWithDataProperty } from '../fill-cache-with-data-property'
...@@ -19,7 +18,6 @@ import type { ...@@ -19,7 +18,6 @@ import type {
NavigateAction, NavigateAction,
ReadonlyReducerState, ReadonlyReducerState,
ReducerState, ReducerState,
ThenableRecord,
} from '../router-reducer-types' } from '../router-reducer-types'
import { PrefetchKind } from '../router-reducer-types' import { PrefetchKind } from '../router-reducer-types'
import { handleMutable } from '../handle-mutable' import { handleMutable } from '../handle-mutable'
...@@ -77,7 +75,7 @@ function addRefetchToLeafSegments( ...@@ -77,7 +75,7 @@ function addRefetchToLeafSegments(
currentCache: CacheNode, currentCache: CacheNode,
flightSegmentPath: FlightSegmentPath, flightSegmentPath: FlightSegmentPath,
treePatch: FlightRouterState, treePatch: FlightRouterState,
data: () => ThenableRecord<FetchServerResponseResult> data: () => Promise<FetchServerResponseResult>
) { ) {
let appliedPatch = false let appliedPatch = false
...@@ -158,12 +156,15 @@ export function navigateReducer( ...@@ -158,12 +156,15 @@ export function navigateReducer(
temporaryCacheNode.subTreeData = state.cache.subTreeData temporaryCacheNode.subTreeData = state.cache.subTreeData
temporaryCacheNode.parallelRoutes = new Map(state.cache.parallelRoutes) temporaryCacheNode.parallelRoutes = new Map(state.cache.parallelRoutes)
let data: ThenableRecord<FetchServerResponseResult> | null = null let data: Promise<FetchServerResponseResult> | null = null
const fetchResponse = () => { const fetchResponse = () => {
if (!data) { if (!data) {
data = createRecordFromThenable( data = fetchServerResponse(
fetchServerResponse(url, optimisticTree, state.nextUrl, state.buildId) url,
optimisticTree,
state.nextUrl,
state.buildId
) )
} }
return data return data
...@@ -198,7 +199,7 @@ export function navigateReducer( ...@@ -198,7 +199,7 @@ export function navigateReducer(
mutable.canonicalUrl = href mutable.canonicalUrl = href
state.prefetchCache.set(createHrefFromUrl(url, false), { state.prefetchCache.set(createHrefFromUrl(url, false), {
data: data ? createRecordFromThenable(Promise.resolve(data)) : null, data: data ? data : null,
// this will make sure that the entry will be discarded after 30s // this will make sure that the entry will be discarded after 30s
kind: PrefetchKind.TEMPORARY, kind: PrefetchKind.TEMPORARY,
prefetchTime: Date.now(), prefetchTime: Date.now(),
...@@ -212,20 +213,18 @@ export function navigateReducer( ...@@ -212,20 +213,18 @@ export function navigateReducer(
// If we don't have a prefetch value, we need to create one // If we don't have a prefetch value, we need to create one
if (!prefetchValues) { if (!prefetchValues) {
const data = createRecordFromThenable( const data = fetchServerResponse(
fetchServerResponse( url,
url, state.tree,
state.tree, state.nextUrl,
state.nextUrl, state.buildId,
state.buildId, // in dev, there's never gonna be a prefetch entry so we want to prefetch here
// 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
// in order to simulate the behavior of the prefetch cache process.env.NODE_ENV === 'development' ? PrefetchKind.AUTO : undefined
process.env.NODE_ENV === 'development' ? PrefetchKind.AUTO : undefined
)
) )
const newPrefetchValue = { const newPrefetchValue = {
data: createRecordFromThenable(Promise.resolve(data)), data,
// this will make sure that the entry will be discarded after 30s // this will make sure that the entry will be discarded after 30s
kind: kind:
process.env.NODE_ENV === 'development' process.env.NODE_ENV === 'development'
...@@ -320,13 +319,11 @@ export function navigateReducer( ...@@ -320,13 +319,11 @@ export function navigateReducer(
treePatch, treePatch,
// eslint-disable-next-line no-loop-func // eslint-disable-next-line no-loop-func
() => () =>
createRecordFromThenable( fetchServerResponse(
fetchServerResponse( url,
url, currentTree,
currentTree, state.nextUrl,
state.nextUrl, state.buildId
state.buildId
)
) )
) )
} }
......
...@@ -9,7 +9,6 @@ import { ACTION_PREFETCH, PrefetchKind } from '../router-reducer-types' ...@@ -9,7 +9,6 @@ import { ACTION_PREFETCH, PrefetchKind } from '../router-reducer-types'
import type { PrefetchAction } from '../router-reducer-types' import type { PrefetchAction } from '../router-reducer-types'
import { prefetchReducer } from './prefetch-reducer' import { prefetchReducer } from './prefetch-reducer'
import { fetchServerResponse } from '../fetch-server-response' import { fetchServerResponse } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable'
jest.mock('../fetch-server-response', () => { jest.mock('../fetch-server-response', () => {
const flightData: FlightData = [ const flightData: FlightData = [
...@@ -142,7 +141,6 @@ describe('prefetchReducer', () => { ...@@ -142,7 +141,6 @@ describe('prefetchReducer', () => {
) )
const prom = Promise.resolve(serverResponse) const prom = Promise.resolve(serverResponse)
const record = createRecordFromThenable(prom)
await prom await prom
const expectedState: ReturnType<typeof prefetchReducer> = { const expectedState: ReturnType<typeof prefetchReducer> = {
...@@ -151,7 +149,7 @@ describe('prefetchReducer', () => { ...@@ -151,7 +149,7 @@ describe('prefetchReducer', () => {
[ [
'/linking/about', '/linking/about',
{ {
data: record, data: prom,
kind: PrefetchKind.AUTO, kind: PrefetchKind.AUTO,
lastUsedTime: null, lastUsedTime: null,
prefetchTime: expect.any(Number), prefetchTime: expect.any(Number),
...@@ -298,7 +296,6 @@ describe('prefetchReducer', () => { ...@@ -298,7 +296,6 @@ describe('prefetchReducer', () => {
) )
const prom = Promise.resolve(serverResponse) const prom = Promise.resolve(serverResponse)
const record = createRecordFromThenable(prom)
await prom await prom
const expectedState: ReturnType<typeof prefetchReducer> = { const expectedState: ReturnType<typeof prefetchReducer> = {
...@@ -307,7 +304,7 @@ describe('prefetchReducer', () => { ...@@ -307,7 +304,7 @@ describe('prefetchReducer', () => {
[ [
'/linking/about', '/linking/about',
{ {
data: record, data: prom,
prefetchTime: expect.any(Number), prefetchTime: expect.any(Number),
kind: PrefetchKind.AUTO, kind: PrefetchKind.AUTO,
lastUsedTime: null, lastUsedTime: null,
......
...@@ -6,7 +6,6 @@ import type { ...@@ -6,7 +6,6 @@ import type {
ReadonlyReducerState, ReadonlyReducerState,
} from '../router-reducer-types' } from '../router-reducer-types'
import { PrefetchKind } from '../router-reducer-types' import { PrefetchKind } from '../router-reducer-types'
import { createRecordFromThenable } from '../create-record-from-thenable'
import { prunePrefetchCache } from './prune-prefetch-cache' import { prunePrefetchCache } from './prune-prefetch-cache'
import { NEXT_RSC_UNION_QUERY } from '../../app-router-headers' import { NEXT_RSC_UNION_QUERY } from '../../app-router-headers'
import { PromiseQueue } from '../../promise-queue' import { PromiseQueue } from '../../promise-queue'
...@@ -57,16 +56,14 @@ export function prefetchReducer( ...@@ -57,16 +56,14 @@ export function prefetchReducer(
} }
// fetchServerResponse is intentionally not awaited so that it can be unwrapped in the navigate-reducer // fetchServerResponse is intentionally not awaited so that it can be unwrapped in the navigate-reducer
const serverResponse = createRecordFromThenable( const serverResponse = prefetchQueue.enqueue(() =>
prefetchQueue.enqueue(() => fetchServerResponse(
fetchServerResponse( url,
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.
// 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.tree, state.nextUrl,
state.nextUrl, state.buildId,
state.buildId, action.kind
action.kind
)
) )
) )
......
import { fetchServerResponse } from '../fetch-server-response' import { fetchServerResponse } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable'
import { createHrefFromUrl } from '../create-href-from-url' import { createHrefFromUrl } from '../create-href-from-url'
import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree' import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'
import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout' import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
...@@ -32,13 +31,11 @@ export function refreshReducer( ...@@ -32,13 +31,11 @@ export function refreshReducer(
if (!cache.data) { if (!cache.data) {
// TODO-APP: verify that `href` is not an external url. // TODO-APP: verify that `href` is not an external url.
// Fetch data from the root of the tree. // Fetch data from the root of the tree.
cache.data = createRecordFromThenable( cache.data = fetchServerResponse(
fetchServerResponse( new URL(href, origin),
new URL(href, origin), [currentTree[0], currentTree[1], currentTree[2], 'refetch'],
[currentTree[0], currentTree[1], currentTree[2], 'refetch'], state.nextUrl,
state.nextUrl, state.buildId
state.buildId
)
) )
} }
......
...@@ -10,7 +10,6 @@ import { ...@@ -10,7 +10,6 @@ import {
NEXT_URL, NEXT_URL,
RSC_CONTENT_TYPE_HEADER, RSC_CONTENT_TYPE_HEADER,
} from '../../app-router-headers' } from '../../app-router-headers'
import { createRecordFromThenable } from '../create-record-from-thenable'
// // eslint-disable-next-line import/no-extraneous-dependencies // // eslint-disable-next-line import/no-extraneous-dependencies
// import { createFromFetch } from 'react-server-dom-webpack/client' // import { createFromFetch } from 'react-server-dom-webpack/client'
// // eslint-disable-next-line import/no-extraneous-dependencies // // eslint-disable-next-line import/no-extraneous-dependencies
...@@ -158,9 +157,7 @@ export function serverActionReducer( ...@@ -158,9 +157,7 @@ export function serverActionReducer(
return handleMutable(state, mutable) return handleMutable(state, mutable)
} }
mutable.inFlightServerAction = createRecordFromThenable( mutable.inFlightServerAction = fetchServerAction(state, action)
fetchServerAction(state, action)
)
// suspends until the server action is resolved. // suspends until the server action is resolved.
......
...@@ -655,37 +655,7 @@ describe('serverPatchReducer', () => { ...@@ -655,37 +655,7 @@ describe('serverPatchReducer', () => {
"nextUrl": "/linking/somewhere-else", "nextUrl": "/linking/somewhere-else",
"prefetchCache": Map { "prefetchCache": Map {
"/linking/about" => { "/linking/about" => {
"data": Promise { "data": Promise {},
"status": "fulfilled",
"value": [
[
[
"children",
"linking",
"children",
"about",
[
"about",
{
"children": [
"",
{},
],
},
],
<h1>
About Page!
</h1>,
<React.Fragment>
<title>
About page!
</title>
</React.Fragment>,
],
],
undefined,
],
},
"kind": "temporary", "kind": "temporary",
"lastUsedTime": 1690329600000, "lastUsedTime": 1690329600000,
"prefetchTime": 1690329600000, "prefetchTime": 1690329600000,
......
...@@ -41,7 +41,7 @@ export interface Mutable { ...@@ -41,7 +41,7 @@ export interface Mutable {
} }
export interface ServerActionMutable extends Mutable { export interface ServerActionMutable extends Mutable {
inFlightServerAction?: ThenableRecord<any> | null inFlightServerAction?: Promise<any> | null
actionResultResolved?: boolean actionResultResolved?: boolean
} }
...@@ -212,7 +212,7 @@ export type FocusAndScrollRef = { ...@@ -212,7 +212,7 @@ export type FocusAndScrollRef = {
export type PrefetchCacheEntry = { export type PrefetchCacheEntry = {
treeAtTimeOfPrefetch: FlightRouterState treeAtTimeOfPrefetch: FlightRouterState
data: ThenableRecord<FetchServerResponseResult> | null data: Promise<FetchServerResponseResult> | null
kind: PrefetchKind kind: PrefetchKind
prefetchTime: number prefetchTime: number
lastUsedTime: number | null lastUsedTime: number | null
...@@ -274,33 +274,11 @@ export type ReducerActions = Readonly< ...@@ -274,33 +274,11 @@ export type ReducerActions = Readonly<
| ServerActionAction | ServerActionAction
> >
export interface PendingThenable<T> extends ThenableImpl<T> {
status: 'pending'
}
export interface FulfilledThenable<T> extends ThenableImpl<T> {
status: 'fulfilled'
value: T
}
export interface RejectedThenable<T> extends ThenableImpl<T> {
status: 'rejected'
reason: unknown
}
interface ThenableImpl<T> {
then<TResult1 = T, TResult2 = never>(
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null
): Promise<TResult1 | TResult2>
}
export type ThenableRecord<T> =
| PendingThenable<T>
| RejectedThenable<T>
| FulfilledThenable<T>
export function isThenable(value: any): value is Promise<AppRouterState> { export function isThenable(value: any): value is Promise<AppRouterState> {
// TODO: We don't gain anything from this abstraction. It's unsound, and only
// makes sense in the specific places where we use it. So it's better to keep
// the type coercion inline, instead of leaking this to other places in
// the codebase.
return ( return (
value && value &&
(typeof value === 'object' || typeof value === 'function') && (typeof value === 'object' || typeof value === 'function') &&
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
import type { import type {
FocusAndScrollRef, FocusAndScrollRef,
PrefetchKind, PrefetchKind,
ThenableRecord,
} from '../../client/components/router-reducer/router-reducer-types' } from '../../client/components/router-reducer/router-reducer-types'
import type { FetchServerResponseResult } from '../../client/components/router-reducer/fetch-server-response' import type { FetchServerResponseResult } from '../../client/components/router-reducer/fetch-server-response'
import type { import type {
...@@ -30,7 +29,7 @@ export type CacheNode = ...@@ -30,7 +29,7 @@ export type CacheNode =
/** /**
* In-flight request for this node. * In-flight request for this node.
*/ */
data: ThenableRecord<FetchServerResponseResult> | null data: Promise<FetchServerResponseResult> | null
head?: React.ReactNode head?: React.ReactNode
/** /**
* React Component for this node. * React Component for this node.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment