{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport type Fn<T extends unknown[], R> = (...args: T) => R;\n\nexport const createContext = <T>() => {\n  const storage = new AsyncLocalStorage<{ context: T }>();\n  return {\n    contextualize<R>(context: T, callback: Fn<[], R>): R {\n      return storage.run({ context }, callback);\n    },\n    getContext() {\n      const store = storage.getStore();\n      if (!store) {\n        throw new Error('Context not initialized');\n      }\n      return store.context;\n    }\n  };\n};\n\ntype Constructor = new (...args: any) => any;\n\nexport interface Contextualized {\n  contextualize<R>(callback: Fn<[], R>): Promise<R>;\n}\n\nexport function Contextable(BaseClass: Constructor = class { }) {\n  const context = createContext();\n  return class Contextual extends BaseClass {\n    static getContext<C extends Constructor>(this: C) {\n      return context.getContext() as InstanceType<C>;\n    }\n    constructor(...args: unknown[]) {\n      super(...args);\n    }\n\n    contextualize<R>(callback: Fn<[], R>): R {\n      return context.contextualize(this, callback);\n    }\n  };\n}\n\nexport function contextualize<T extends Contextualized, K extends keyof T>(...args: unknown[]) {\n  const [, , descriptor] = args as [T, K, TypedPropertyDescriptor<T[K]>];\n  const property = descriptor?.value;\n  if (typeof property === 'function') {\n    descriptor.value = function(this: Contextualized, ...args: unknown[]) {\n      return this.contextualize(() => property.apply(this, args));\n    } as T[K];\n  }\n}\n\n"],"names":["Contextable","contextualize","createContext","storage","AsyncLocalStorage","context","callback","run","getContext","store","getStore","Error","BaseClass","Contextual","args","descriptor","property","value","apply"],"mappings":";;;;;;;;;;;QA0BgBA;eAAAA;;QAgBAC;eAAAA;;QAtCHC;eAAAA;;;iCAJqB;AAI3B,MAAMA,gBAAgB;IAC3B,MAAMC,UAAU,IAAIC,kCAAiB;IACrC,OAAO;QACLH,eAAiBI,OAAU,EAAEC,QAAmB;YAC9C,OAAOH,QAAQI,GAAG,CAAC;gBAAEF;YAAQ,GAAGC;QAClC;QACAE;YACE,MAAMC,QAAQN,QAAQO,QAAQ;YAC9B,IAAI,CAACD,OAAO;gBACV,MAAM,IAAIE,MAAM;YAClB;YACA,OAAOF,MAAMJ,OAAO;QACtB;IACF;AACF;AAQO,SAASL,YAAYY,YAAyB;AAAQ,CAAC;IAC5D,MAAMP,UAAUH;IAChB,OAAO,MAAMW,mBAAmBD;QAC9B,OAAOJ,aAA2C;YAChD,OAAOH,QAAQG,UAAU;QAC3B;QACA,YAAY,GAAGM,IAAe,CAAE;YAC9B,KAAK,IAAIA;QACX;QAEAb,cAAiBK,QAAmB,EAAK;YACvC,OAAOD,QAAQJ,aAAa,CAAC,IAAI,EAAEK;QACrC;IACF;AACF;AAEO,SAASL,cAA2D,GAAGa,IAAe;IAC3F,MAAM,KAAKC,WAAW,GAAGD;IACzB,MAAME,WAAWD,YAAYE;IAC7B,IAAI,OAAOD,aAAa,YAAY;QAClCD,WAAWE,KAAK,GAAG,SAA+B,GAAGH,IAAe;YAClE,OAAO,IAAI,CAACb,aAAa,CAAC,IAAMe,SAASE,KAAK,CAAC,IAAI,EAAEJ;QACvD;IACF;AACF"}