|
|
import type { IncomingMessage } from 'http' |
|
|
import type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies' |
|
|
import type { ResponseCookies } from '../web/spec-extension/cookies' |
|
|
import type { BaseNextRequest } from '../base-http' |
|
|
import type { NextRequest } from '../web/spec-extension/request' |
|
|
|
|
|
import { |
|
|
COOKIE_NAME_PRERENDER_BYPASS, |
|
|
checkIsOnDemandRevalidate, |
|
|
} from '../api-utils' |
|
|
import type { __ApiPreviewProps } from '../api-utils' |
|
|
|
|
|
export class DraftModeProvider { |
|
|
|
|
|
|
|
|
|
|
|
private _isEnabled: boolean |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
private readonly _previewModeId: string | undefined |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
private readonly _mutableCookies: ResponseCookies |
|
|
|
|
|
constructor( |
|
|
previewProps: __ApiPreviewProps | undefined, |
|
|
req: IncomingMessage | BaseNextRequest<unknown> | NextRequest, |
|
|
cookies: ReadonlyRequestCookies, |
|
|
mutableCookies: ResponseCookies |
|
|
) { |
|
|
|
|
|
|
|
|
const isOnDemandRevalidate = |
|
|
previewProps && |
|
|
checkIsOnDemandRevalidate(req, previewProps).isOnDemandRevalidate |
|
|
|
|
|
const cookieValue = cookies.get(COOKIE_NAME_PRERENDER_BYPASS)?.value |
|
|
|
|
|
this._isEnabled = Boolean( |
|
|
!isOnDemandRevalidate && |
|
|
cookieValue && |
|
|
previewProps && |
|
|
(cookieValue === previewProps.previewModeId || |
|
|
|
|
|
(process.env.NODE_ENV !== 'production' && |
|
|
previewProps.previewModeId === 'development-id')) |
|
|
) |
|
|
|
|
|
this._previewModeId = previewProps?.previewModeId |
|
|
this._mutableCookies = mutableCookies |
|
|
} |
|
|
|
|
|
get isEnabled() { |
|
|
return this._isEnabled |
|
|
} |
|
|
|
|
|
enable() { |
|
|
if (!this._previewModeId) { |
|
|
throw new Error( |
|
|
'Invariant: previewProps missing previewModeId this should never happen' |
|
|
) |
|
|
} |
|
|
|
|
|
this._mutableCookies.set({ |
|
|
name: COOKIE_NAME_PRERENDER_BYPASS, |
|
|
value: this._previewModeId, |
|
|
httpOnly: true, |
|
|
sameSite: process.env.NODE_ENV !== 'development' ? 'none' : 'lax', |
|
|
secure: process.env.NODE_ENV !== 'development', |
|
|
path: '/', |
|
|
}) |
|
|
|
|
|
this._isEnabled = true |
|
|
} |
|
|
|
|
|
disable() { |
|
|
|
|
|
|
|
|
|
|
|
this._mutableCookies.set({ |
|
|
name: COOKIE_NAME_PRERENDER_BYPASS, |
|
|
value: '', |
|
|
httpOnly: true, |
|
|
sameSite: process.env.NODE_ENV !== 'development' ? 'none' : 'lax', |
|
|
secure: process.env.NODE_ENV !== 'development', |
|
|
path: '/', |
|
|
expires: new Date(0), |
|
|
}) |
|
|
|
|
|
this._isEnabled = false |
|
|
} |
|
|
} |
|
|
|