41 lines
1.4 KiB
TypeScript
41 lines
1.4 KiB
TypeScript
export {}
|
|
|
|
declare global {
|
|
var __performanceMeasurePatched: boolean | undefined
|
|
}
|
|
|
|
function isNegativeTimestampError(error: unknown): boolean {
|
|
if (!(error instanceof Error)) return false
|
|
return error.message.toLowerCase().includes("cannot have a negative time stamp")
|
|
}
|
|
|
|
if (typeof performance !== "undefined" && typeof performance.measure === "function") {
|
|
if (!globalThis.__performanceMeasurePatched) {
|
|
const originalMeasure = performance.measure.bind(performance)
|
|
performance.measure = ((name: string, startOrOptions?: string | PerformanceMeasureOptions, endMark?: string) => {
|
|
try {
|
|
return originalMeasure(name, startOrOptions as string | PerformanceMeasureOptions, endMark)
|
|
} catch (error) {
|
|
if (!isNegativeTimestampError(error)) {
|
|
throw error
|
|
}
|
|
|
|
// Next.js occasionally triggers an invalid interval when profiling slow routes.
|
|
// Clamp the measurement to start at 0 to avoid crashing the page.
|
|
if (typeof startOrOptions === "object" && startOrOptions) {
|
|
const safeOptions: PerformanceMeasureOptions = {
|
|
...startOrOptions,
|
|
start: 0,
|
|
}
|
|
try {
|
|
return originalMeasure(name, safeOptions, endMark)
|
|
} catch {
|
|
return undefined
|
|
}
|
|
}
|
|
return undefined
|
|
}
|
|
}) as typeof performance.measure
|
|
globalThis.__performanceMeasurePatched = true
|
|
}
|
|
}
|