refactor: wrap plain scopes in Context.push()

Centralize null-prototype scope creation in push() so callers pass plain objects; Drop instances and existing null-proto frames are pushed as-is. Remove sanitizeScope in favor of createScope via Object.assign.
This commit is contained in:
Yang Jun
2026-07-19 23:42:09 +08:00
parent 812af67022
commit 90ab891c29
9 changed files with 37 additions and 30 deletions
+16
View File
@@ -1,4 +1,5 @@
import { Context } from './context'
import { Drop } from '../drop/drop'
import { Scope } from './scope'
describe('Context', function () {
@@ -250,6 +251,21 @@ describe('Context', function () {
expect(ctx.getSync(['bar', 'foo'])).toEqual('foo')
expect(ctx.getSync(['bar', 'bar'])).toEqual(undefined)
})
it('should wrap plain objects with null prototype', function () {
const scope = ctx.push({ foo: 'FOO' })
expect(Object.getPrototypeOf(scope)).toBeNull()
})
it('should return pushed scope for in-place mutation', function () {
const scope = ctx.push({})
scope.item = 'ITEM'
expect(ctx.getSync(['item'])).toEqual('ITEM')
})
it('should push Drop instances as-is', function () {
class TestDrop extends Drop {}
const drop = new TestDrop()
const pushed = ctx.push(drop)
expect(pushed).toBe(drop)
})
})
describe('.pop()', function () {
it('should pop scope', async function () {
+8 -2
View File
@@ -94,8 +94,14 @@ export class Context {
}
return scope
}
public push (ctx: object) {
return this.scopes.push(ctx)
public push (ctx: Scope): Scope {
const scope = ctx instanceof Drop
? ctx
: Object.getPrototypeOf(ctx) === null
? ctx
: createScope(ctx)
this.scopes.push(scope)
return scope
}
public pop () {
return this.scopes.pop()
+1 -11
View File
@@ -24,15 +24,5 @@ export function shouldBlockScopeKeyWrite (key: PropertyKey, ownPropertyOnly: boo
}
export function createScope (from?: ScopeObject): ScopeObject {
return from ? sanitizeScope(from) : Object.create(null)
}
export function sanitizeScope (obj: ScopeObject): ScopeObject {
const scope = Object.create(null)
for (const key of Object.keys(obj)) {
if (hasOwnProperty.call(obj, key)) {
scope[key] = obj[key]
}
}
return scope
return Object.assign(Object.create(null), from)
}