trace-record
v0.2.0
Published
Get the stack trace of the creation of objects
Downloads
9
Readme
trace-record
Get the stack trace of the creation of objects.
Usages
// foo.ts
import { record } from 'trace-record'
export const obj = record({ some: 'obj' })
// bar.ts
import { getTrace } from 'trace-record'
import { obj } from './foo'
console.log(getTrace(obj)) // [{ file: 'foo.ts', line: 3, column: 0 }, ...]
APIs
record<T>(obj: T): T
record()
is a bypass function that returns the object passed in. But also records the current stack trace and binds it to the object with an internal WeakMap. To retrieve the stack trace, use getTrace()
and pass the object instance to it.
import { record } from 'trace-record'
const obj = record({ some: 'obj' })
const arr = record([1, 2, 3])
const fn = record(() => {})
Since it uses WeakMap under the hood, it requires the object to be a reference type (object-like). Primitive types like string
, number
, boolean
, null
, undefined
will not work.
getTrace(obj: any): StackFrame[] | undefined
getTrace()
retrieves the stack trace of the object created by record()
. It returns an array of StackFrame
array. Returns undefined
if the object is not recorded. Stacktrace parsing is powered by error-stack-parser-es
getTraceRaw(obj: any): string | undefined
Same as getTrace()
but returns a raw, unparsed, stacktrace string provided by the the JavaScript engine. The format may vary between engines and runtimes.
Noop Exports
To make it easier to bail out the tracing in production, you can alias the package to the noop export in your build tool.
defineConfig({
alias: {
'trace-record': 'trace-record/noop'
}
})
Transpiler
I have a plan to rewrite a transpiler to automatically insert the record()
for specific types of objects. For now, you might need to manually add record()
to the objects you want to trace.
Sponsors
License
MIT License © 2023-PRESENT Anthony Fu