Skip to content

Commit

Permalink
fix(cordis): mock Function.prototype.toString, fix #14
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Aug 11, 2024
1 parent f53d475 commit f58c078
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
17 changes: 16 additions & 1 deletion packages/core/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,27 @@ function createShadowMethod(ctx: Context, value: any, outer: any, shadow: {}) {
if (thisArg === outer) thisArg = shadow
// contravariant
args = args.map((arg) => {
if (typeof arg !== 'function') return arg
if (typeof arg !== 'function' || arg[symbols.original]) return arg
return new Proxy(arg, {
get: (target, prop, receiver) => {
if (prop === symbols.original) return target
const value = Reflect.get(target, prop, receiver)
// https://github.com/cordiverse/cordis/issues/14
if (prop === 'toString' && value === Function.prototype.toString) {
return function (...args: any[]) {
return Reflect.apply(value, this === receiver ? target : this, args)
}
}
return value
},
apply: (target: Function, thisArg, args) => {
// covariant
return Reflect.apply(target, getTraceable(ctx, thisArg), args.map(arg => getTraceable(ctx, arg)))
},
construct: (target: Function, args, newTarget) => {
// covariant
return Reflect.construct(target, args.map(arg => getTraceable(ctx, arg)), newTarget)
},
})
})
// covariant
Expand Down
23 changes: 23 additions & 0 deletions packages/core/tests/associate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,4 +171,27 @@ describe('Association', () => {

await checkError(root)
})

// https://github.com/cordiverse/cordis/issues/14
it('inspect', () => {
class Foo extends Service {
constructor(ctx: Context) {
super(ctx, 'foo', true)
}

bar(arg: any) {
expect(arg.toString()).to.include('class X')
this.baz(arg)
}

baz(arg: any) {
expect(arg.toString()).to.include('class X')
}
}

const root = new Context()
root.plugin(Foo)
class X {}
root.foo.bar(X)
})
})

0 comments on commit f58c078

Please sign in to comment.