{"version":3,"file":"queuefy.modern.mjs","sources":["../../src/main/ts/index.ts"],"sourcesContent":["import type {\n  ICallable\n} from '@qiwi/substrate'\n\nexport type TInsideOutPromise = {\n  promise: Promise<any>,\n  resolve: ICallable,\n  reject: ICallable\n}\n\nexport type IAsyncFn = (...args: any[]) => Promise<any>\n\nexport type ITask = {\n  args: any[],\n  iop: TInsideOutPromise\n}\nexport type ITaskQueue = Array<ITask>\n\n/**\n * TODO implement lightweight version of 'inside-out-promise'\n * @private\n */\nexport const getPromise = (): TInsideOutPromise => {\n  const iop: any = {}\n\n  iop.promise = new Promise((resolve, reject) => {\n    iop.resolve = resolve\n    iop.reject = reject\n  })\n\n  return iop\n}\n\n/**\n * @private\n * @param target\n */\nexport const isPromiseLike = (target: any): boolean =>\n  !!target\n    && typeof target.then === 'function'\n    && typeof target.catch === 'function'\n\nexport const compose = (cb: ICallable, next: ICallable) => <V>(v: V): void => {\n  cb(v)\n  next()\n}\n\nexport const invoke = (fn: IAsyncFn, task: ITask, next: ICallable): void => {\n  const {iop, args} = task\n  const resolve = compose(iop.resolve, next)\n  const reject = compose(iop.reject, next)\n\n  try {\n    const res = fn(...args)\n\n    if (isPromiseLike(res)) {\n      res.then(resolve, reject)\n    }\n    else {\n      resolve(res)\n    }\n  }\n  catch (e) {\n    reject(e)\n  }\n}\n\nexport const queuefy = <T extends IAsyncFn>(fn: T, limit = 1): T => {\n  const queue: ITaskQueue = []\n  const processQueue = (): void => {\n    if (limit === 0) {\n      return\n    }\n\n    const task = queue.shift()\n    if (!task) {\n      return\n    }\n\n    limit--\n    invoke(fn, task, () => {\n      limit++\n      processQueue()\n    })\n  }\n\n  return ((...args: any[]): any => {\n    const iop = getPromise()\n\n    queue.push({args, iop})\n    processQueue()\n\n    return iop.promise\n  }) as T\n}\n"],"names":["getPromise","iop","promise","Promise","resolve","reject","isPromiseLike","target","then","catch","compose","cb","next","v","invoke","fn","task","args","res","e","queuefy","limit","queue","processQueue","shift","push"],"mappings":"AAsBa,MAAAA,EAAaA,KACxB,MAAMC,EAAW,CAAA,EAOjB,OALAA,EAAIC,QAAU,IAAIC,QAAQ,CAACC,EAASC,KAClCJ,EAAIG,QAAUA,EACdH,EAAII,OAASA,CAAAA,GAGRJ,GAOIK,EAAiBC,KAC1BA,GAC0B,mBAAhBA,EAAOC,MACU,mBAAjBD,EAAOE,MAERC,EAAUA,CAACC,EAAeC,IAAwBC,IAC7DF,EAAGE,GACHD,GACF,EAEaE,EAASA,CAACC,EAAcC,EAAaJ,KAChD,MAAMX,IAACA,EAAGgB,KAAEA,GAAQD,EACdZ,EAAUM,EAAQT,EAAIG,QAASQ,GAC/BP,EAASK,EAAQT,EAAII,OAAQO,GAEnC,IACE,MAAMM,EAAMH,KAAME,GAEdX,EAAcY,GAChBA,EAAIV,KAAKJ,EAASC,GAGlBD,EAAQc,EAEX,CACD,MAAOC,GACLd,EAAOc,EACR,GAGUC,EAAUA,CAAqBL,EAAOM,EAAQ,KACzD,MAAMC,EAAoB,GACpBC,EAAeA,KACnB,GAAc,IAAVF,EACF,OAGF,MAAML,EAAOM,EAAME,QACdR,IAILK,IACAP,EAAOC,EAAIC,EAAM,KACfK,IACAE,MACD,EAGH,MAAQ,IAAIN,KACV,MAAMhB,EAAMD,IAKZ,OAHAsB,EAAMG,KAAK,CAACR,OAAMhB,QAClBsB,IAEOtB,EAAIC,QACb"}