Skip to content

Commit 599c5b0

Browse files
authored
fix(module-runner): keep stack trace interception working when Object.prototype is frozen (#23073)
1 parent 3ac77d9 commit 599c5b0

2 files changed

Lines changed: 38 additions & 1 deletion

File tree

‎packages/vite/src/module-runner/sourcemap/interceptor.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -330,7 +330,9 @@ function CallSiteToString(this: CallSite) {
330330
}
331331

332332
function cloneCallSite(frame: CallSite) {
333-
const object = {} as CallSite
333+
// null prototype so assigning `constructor` below doesn't throw
334+
// when user code has frozen `Object.prototype`
335+
const object = Object.create(null) as CallSite
334336
Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach((name) => {
335337
const key = name as keyof CallSite
336338
// @ts-expect-error difficult to type

‎packages/vite/src/node/ssr/runtime/__tests__/server-source-maps.spec.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,41 @@ describe('module runner initialization', async () => {
9292
)
9393
})
9494

95+
it('stack traces work when Object.prototype is frozen', async ({
96+
runner,
97+
server,
98+
}) => {
99+
const methodError = await getError(async () => {
100+
const mod = await runner.import('/fixtures/throws-error-method.ts')
101+
mod.throwError()
102+
})
103+
104+
// simulate `Object.freeze(Object.prototype)` in user code without
105+
// permanently freezing it for the other tests in this worker: assigning
106+
// an inherited `constructor` throws exactly like it does when frozen
107+
const original = Object.getOwnPropertyDescriptor(
108+
Object.prototype,
109+
'constructor',
110+
)!
111+
Object.defineProperty(Object.prototype, 'constructor', {
112+
configurable: true,
113+
get: () => original.value,
114+
set: () => {
115+
throw new TypeError(
116+
`Cannot assign to read only property 'constructor' of object '#<Object>'`,
117+
)
118+
},
119+
})
120+
try {
121+
// reading `.stack` for the first time invokes `prepareStackTrace`
122+
expect(serializeStack(server, methodError)).toBe(
123+
' at Module.throwError (<root>/fixtures/throws-error-method.ts:6:9)',
124+
)
125+
} finally {
126+
Object.defineProperty(Object.prototype, 'constructor', original)
127+
}
128+
})
129+
95130
it('deep stacktrace', async ({ runner, server }) => {
96131
const methodError = await getError(async () => {
97132
const mod = await runner.import('/fixtures/has-error-deep.ts')

0 commit comments

Comments
 (0)