antfu / trace-record

Get the stack trace of the creation of objects.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

trace-record

npm version npm downloads bundle JSDocs License

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

About

Get the stack trace of the creation of objects.

License:MIT License


Languages

Language:TypeScript 91.7%Language:JavaScript 8.3%