@nocobase/plugin-async-task-manager 1.7.0-beta.32 → 1.7.0-beta.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/client/index.js +1 -1
  2. package/dist/externalVersion.js +4 -4
  3. package/dist/locale/en-US.json +2 -1
  4. package/dist/locale/zh-CN.json +1 -1
  5. package/dist/node_modules/p-queue/dist/index.d.ts +101 -0
  6. package/dist/node_modules/p-queue/dist/index.js +1 -0
  7. package/dist/node_modules/p-queue/dist/lower-bound.d.ts +1 -0
  8. package/dist/node_modules/p-queue/dist/lower-bound.js +21 -0
  9. package/dist/node_modules/p-queue/dist/options.d.ts +64 -0
  10. package/dist/node_modules/p-queue/dist/options.js +2 -0
  11. package/dist/node_modules/p-queue/dist/priority-queue.d.ts +12 -0
  12. package/dist/node_modules/p-queue/dist/priority-queue.js +32 -0
  13. package/dist/node_modules/p-queue/dist/queue.d.ts +7 -0
  14. package/dist/node_modules/p-queue/dist/queue.js +2 -0
  15. package/dist/node_modules/p-queue/license +9 -0
  16. package/dist/node_modules/p-queue/node_modules/eventemitter3/index.d.ts +134 -0
  17. package/dist/node_modules/p-queue/node_modules/eventemitter3/index.js +336 -0
  18. package/dist/node_modules/p-queue/node_modules/eventemitter3/package.json +56 -0
  19. package/dist/node_modules/p-queue/node_modules/eventemitter3/umd/eventemitter3.js +340 -0
  20. package/dist/node_modules/p-queue/node_modules/eventemitter3/umd/eventemitter3.min.js +1 -0
  21. package/dist/node_modules/p-queue/package.json +1 -0
  22. package/dist/node_modules/uuid/package.json +1 -1
  23. package/dist/server/base-task-manager.d.ts +14 -0
  24. package/dist/server/base-task-manager.js +64 -0
  25. package/dist/server/interfaces/async-task-manager.d.ts +11 -0
  26. package/dist/server/interfaces/task.d.ts +9 -0
  27. package/dist/server/task-type.d.ts +1 -0
  28. package/dist/server/task-type.js +7 -4
  29. package/package.json +5 -2
@@ -7,4 +7,4 @@
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
9
 
10
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("dayjs"),require("@nocobase/client"),require("antd")):"function"==typeof define&&define.amd?define("@nocobase/plugin-async-task-manager",["react","dayjs","@nocobase/client","antd"],t):"object"==typeof exports?exports["@nocobase/plugin-async-task-manager"]=t(require("react"),require("dayjs"),require("@nocobase/client"),require("antd")):e["@nocobase/plugin-async-task-manager"]=t(e.react,e.dayjs,e["@nocobase/client"],e.antd)}(self,function(e,t,n,r){var o={379:function(e,t,n){e.exports=function(e){"use strict";var t={name:"zh-cn",weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"周日_周一_周二_周三_周四_周五_周六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),ordinal:function(e,t){return"W"===t?e+"周":e+"日"},weekStart:1,yearStart:4,formats:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY/MM/DD",LL:"YYYY年M月D日",LLL:"YYYY年M月D日Ah点mm分",LLLL:"YYYY年M月D日ddddAh点mm分",l:"YYYY/M/D",ll:"YYYY年M月D日",lll:"YYYY年M月D日 HH:mm",llll:"YYYY年M月D日dddd HH:mm"},relativeTime:{future:"%s内",past:"%s前",s:"几秒",m:"1 分钟",mm:"%d 分钟",h:"1 小时",hh:"%d 小时",d:"1 天",dd:"%d 天",M:"1 个月",MM:"%d 个月",y:"1 年",yy:"%d 年"},meridiem:function(e,t){var n=100*e+t;return n<600?"凌晨":n<900?"早上":n<1100?"上午":n<1300?"中午":n<1800?"下午":"晚上"}};return(e&&"object"==typeof e&&"default"in e?e:{default:e}).default.locale(t,null,!0),t}(n(760))},809:function(e){e.exports=function(e,t,n){e=e||{};var r=t.prototype,o={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function a(e,t,n,o){return r.fromToBase(e,t,n,o)}n.en.relativeTime=o,r.fromToBase=function(t,r,a,i,l){for(var s,c,u,f=a.$locale().relativeTime||o,p=e.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],d=p.length,y=0;y<d;y+=1){var m=p[y];m.d&&(s=i?n(t).diff(a,m.d,!0):a.diff(t,m.d,!0));var v=(e.rounding||Math.round)(Math.abs(s));if(u=s>0,v<=m.r||!m.r){v<=1&&y>0&&(m=p[y-1]);var h=f[m.l];l&&(v=l(""+v)),c="string"==typeof h?h.replace("%d",v):h(v,r,m.l,u);break}}if(r)return c;var b=u?f.future:f.past;return"function"==typeof b?b(c):b.replace("%s",c)},r.to=function(e,t){return a(e,t,this,!0)},r.from=function(e,t){return a(e,t,this)};var i=function(e){return e.$u?n.utc():n()};r.toNow=function(e){return this.to(i(this),e)},r.fromNow=function(e){return this.from(i(this),e)}}},772:function(e){"use strict";e.exports=n},721:function(e){"use strict";e.exports=r},760:function(e){"use strict";e.exports=t},156:function(t){"use strict";t.exports=e}},a={};function i(e){var t=a[e];if(void 0!==t)return t.exports;var n=a[e]={exports:{}};return o[e].call(n.exports,n,n.exports,i),n.exports}i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,{a:t}),t},i.d=function(e,t){for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var l={};return!function(){"use strict";i.r(l),i.d(l,{PluginAsyncExportClient:function(){return C},default:function(){return M}});var e=i(772),t=i(156),n=i.n(t),r=i(721),o=i(760),a=i.n(o);i(379);var s=i(809),c=i.n(s),u=JSON.parse('{"u2":"@nocobase/plugin-async-task-manager"}');function f(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function p(e,t,n,r,o,a,i){try{var l=e[a](i),s=l.value}catch(e){n(e);return}l.done?t(s):Promise.resolve(s).then(r,o)}function d(e){return function(){var t=this,n=arguments;return new Promise(function(r,o){var a=e.apply(t,n);function i(e){p(a,r,o,i,l,"next",e)}function l(e){p(a,r,o,i,l,"throw",e)}i(void 0)})}}function y(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,o=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=o){var a=[],i=!0,l=!1;try{for(o=o.call(e);!(i=(n=o.next()).done)&&(a.push(n.value),!t||a.length!==t);i=!0);}catch(e){l=!0,r=e}finally{try{i||null==o.return||o.return()}finally{if(l)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return f(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return f(e,t)}}(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function m(e,t){var n,r,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function l(a){return function(l){var s=[a,l];if(n)throw TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(o=(o=i.trys).length>0&&o[o.length-1])&&(6===s[0]||2===s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}}var v=(0,e.createStyles)(function(e){return{button:{color:e.token.colorTextHeaderMenu+" !important"}}});a().extend(c());var h=function(e,t){if("success"!==e.type||!(null==(a=e.payload)||null==(o=a.message)?void 0:o.messageId))return null;var o,a,i=e.payload.message,l=i.messageId,s=i.messageValues;return n().createElement("div",{style:{marginLeft:8}},n().createElement(r.Tag,{color:"success"},t(l,s)))},b=function(){var t=(0,e.useRequest)({url:"asyncTasks:list"}),n=t.data,r=t.refreshAsync;return{loading:t.loading,tasks:(null==n?void 0:n.data)||[],refresh:r}},g=function(t){var o,i=t.popoverVisible,l=t.setPopoverVisible,s=t.tasks,c=t.refresh,f=t.loading,p=t.hasProcessingTasks,y=(0,e.useApp)(),b=(0,e.useAPIClient)(),g=(0,e.useCurrentAppInfo)(),k=(o=(0,e.useApp)(),function(e){return o.i18n.t(e,{ns:[u.u2,"client"]})}),w=v().styles,E=(0,e.usePlugin)("async-task-manager"),x=(0,e.useCollectionManager)(),_=(0,e.useCompile)(),O=function(e){l(!1)},T=[{title:k("Created at"),dataIndex:"createdAt",key:"createdAt",width:180,render:function(e){return n().createElement(r.Tooltip,{title:a()(e).format("YYYY-MM-DD HH:mm:ss")},a()(e).fromNow())}},{title:k("Task"),dataIndex:"title",key:"title",render:function(e,t){var n=t.title;if(!n)return"-";var r=x.getCollection(n.collection),o={export:k("Export"),import:k("Import"),"export-attachments":k("Export attachments")}[n.actionType]||n.actionType;return(({"export-attachments":k("Export {collection} attachments"),export:k("Export {collection} data"),import:k("Import {collection} data")})[n.actionType]||"".concat(o)).replace("{collection}",_((null==r?void 0:r.title)||n.collection))}},{title:k("Status"),dataIndex:"status",key:"status",width:160,render:function(t,o){var a,i={pending:{color:"default",text:k("Waiting"),icon:"ClockCircleOutlined"},running:{color:"processing",text:k("Processing"),icon:"LoadingOutlined"},success:{color:"success",text:k("Completed"),icon:"CheckCircleOutlined"},failed:{color:"error",text:k("Failed"),icon:"CloseCircleOutlined"},cancelled:{color:"warning",text:k("Cancelled"),icon:"StopOutlined"}},l=i[t.type]||{},s=l.color;return l.text,n().createElement("div",{style:{display:"flex",alignItems:"center",gap:8}},n().createElement("div",{style:{flex:1}},function(){var e,a,i={width:100,margin:0};switch(t.indicator){case"spinner":return n().createElement(r.Progress,{type:"line",size:"small",strokeWidth:4,percent:100,status:"active",showInfo:!1,style:i});case"progress":return n().createElement(r.Progress,{type:"line",size:"small",strokeWidth:4,percent:Number(((null==(e=o.progress)?void 0:e.current)/(null==(a=o.progress)?void 0:a.total)*100).toFixed(2)),status:"active",style:i,format:function(e){return"".concat(e.toFixed(1),"%")}});case"success":return n().createElement(r.Progress,{type:"line",size:"small",strokeWidth:4,percent:100,status:"success",style:i,format:function(){return""}});case"error":return n().createElement(r.Progress,{type:"line",size:"small",strokeWidth:4,percent:100,status:"exception",style:i,format:function(){return""}});default:return null}}()),n().createElement(r.Tag,{color:s,icon:(null==(a=i[t.type])?void 0:a.icon)?n().createElement(e.Icon,{type:i[t.type].icon}):null,style:{margin:0,padding:"0 4px",height:22,width:22}}),h(t,k))}},{title:k("Actions"),key:"actions",width:180,render:function(t,o){var a=[];return("running"===o.status.type||"pending"===o.status.type)&&o.cancelable&&a.push(n().createElement(r.Popconfirm,{key:"cancel",title:k("Confirm cancel"),description:k("Confirm cancel description"),onConfirm:d(function(){return m(this,function(e){switch(e.label){case 0:return[4,b.request({url:"asyncTasks:cancel",params:{filterByTk:o.taskId}})];case 1:return e.sent(),c(),[2]}})}),okText:k("Confirm"),cancelText:k("Cancel"),disabled:!1},n().createElement(r.Button,{type:"link",size:"small",icon:n().createElement(e.Icon,{type:"StopOutlined"}),disabled:!1},k("Cancel")))),"success"===o.status.type&&("file"===o.status.resultType?a.push(n().createElement(r.Button,{key:"download",type:"link",size:"small",icon:n().createElement(e.Icon,{type:"DownloadOutlined"}),onClick:function(){var e,t,n,r=y.apiClient.auth.token,a=x.getCollection(o.title.collection),i=_(null==a?void 0:a.title),l=(null==o||null==(e=o.title)?void 0:e.actionType)==="export-attachments"?"-attachments.zip":".xlsx",s="".concat(i).concat(l),c=(null==o||null==(t=o.title)?void 0:t.actionType)!=="create migration"?encodeURIComponent(s):null,u=y.getApiUrl("asyncTasks:fetchFile/".concat(o.taskId,"?token=").concat(r,"&__appName=").concat(encodeURIComponent((null==g||null==(n=g.data)?void 0:n.name)||y.name)).concat(c?"&filename=".concat(c):""));window.open(u)}},k("Download"))):o.status.payload&&a.push(n().createElement(r.Button,{key:"view",type:"link",size:"small",icon:n().createElement(e.Icon,{type:"EyeOutlined"}),onClick:function(){O(o);var e=o.status.payload,t=E.taskResultRendererManager.get(o.title.actionType);r.Modal.info({title:k("Task result"),content:t?n().createElement(t,{payload:e,task:o}):n().createElement("div",null,k("No renderer available for this task type, payload: ".concat(e)))})}},k("View result")))),"failed"===o.status.type&&a.push(n().createElement(r.Button,{key:"error",type:"link",size:"small",icon:n().createElement(e.Icon,{type:"ExclamationCircleOutlined"}),onClick:function(){var e;l(!1),r.Modal.info({title:k("Error Details"),content:null==(e=o.status.errors)?void 0:e.map(function(e,t){return n().createElement("div",{key:t,style:{marginBottom:16}},n().createElement("div",{style:{color:"#ff4d4f",marginBottom:8}},e.message),e.code&&n().createElement("div",{style:{color:"#999",fontSize:12}},k("Error code"),": ",e.code))}),closable:!0,width:400})}},k("Error details"))),n().createElement(r.Space,{size:"middle"},a)}}],P=n().createElement("div",{style:{maxHeight:"70vh",overflow:"auto",width:s.length>0?800:200}},s.length>0?n().createElement(r.Table,{loading:f,columns:T,dataSource:s,size:"small",pagination:!1,rowKey:"taskId"}):n().createElement("div",{style:{padding:"24px 0",display:"flex",justifyContent:"center"}},n().createElement(r.Empty,{description:k("No tasks"),image:r.Empty.PRESENTED_IMAGE_SIMPLE})));return n().createElement(n().Fragment,null,n().createElement(r.Popover,{content:P,trigger:"hover",placement:"bottom",open:i,onOpenChange:l},n().createElement(r.Button,{className:["sync-task-button",w.button].join(" "),icon:n().createElement(e.Icon,{type:"SyncOutlined",spin:p}),onClick:function(){return l(!i)}})))},k=function(){var r=b(),o=r.tasks,a=r.refresh,i=function(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},a=Object.keys(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}(r,["tasks","refresh"]),l=(0,e.useApp)(),s=y((0,t.useState)(!1),2),c=s[0],u=s[1],f=y((0,t.useState)(!1),2),p=f[0],v=f[1];(0,t.useEffect)(function(){v(o.some(function(e){return"success"!==e.status.type&&"failed"!==e.status.type}))},[o]);var h=(0,t.useCallback)(d(function(){return m(this,function(e){return u(!0),[2]})}),[]),k=(0,t.useCallback)(function(){a(),console.log("handleTaskProgress")},[]),w=(0,t.useCallback)(function(){a(),console.log("handleTaskStatus")},[]),E=(0,t.useCallback)(function(){a(),console.log("handleTaskCancelled")},[]);return(0,t.useEffect)(function(){return l.eventBus.addEventListener("ws:message:async-tasks:created",h),l.eventBus.addEventListener("ws:message:async-tasks:progress",k),l.eventBus.addEventListener("ws:message:async-tasks:status",w),l.eventBus.addEventListener("ws:message:async-tasks:cancelled",E),function(){l.eventBus.removeEventListener("ws:message:async-tasks:created",h),l.eventBus.removeEventListener("ws:message:async-tasks:progress",k),l.eventBus.removeEventListener("ws:message:async-tasks:status",w),l.eventBus.removeEventListener("ws:message:async-tasks:cancelled",E)}},[l,E,h,k,w]),(null==o?void 0:o.length)>0&&n().createElement(g,function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){var r;r=n[t],t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r})}return e}({tasks:o,refresh:a,popoverVisible:c,setPopoverVisible:u,hasProcessingTasks:p},i))},w=function(t){return n().createElement(e.PinnedPluginListProvider,{items:{asyncTasks:{order:300,component:"AsyncTasks",pin:!0,snippet:"*"}}},n().createElement(e.SchemaComponentOptions,{components:{AsyncTasks:k}},t.children))},E=function(){var e;function t(){var e,n;if(!(this instanceof t))throw TypeError("Cannot call a class as a function");e="renderers",n=new Map,e in this?Object.defineProperty(this,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):this[e]=n}return e=[{key:"register",value:function(e,t){this.renderers.set(e,t)}},{key:"get",value:function(e){return this.renderers.get(e)}}],function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(t.prototype,e),t}();function x(e,t,n,r,o,a,i){try{var l=e[a](i),s=l.value}catch(e){n(e);return}l.done?t(s):Promise.resolve(s).then(r,o)}function _(e,t,n){return(_=S()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&T(o,n.prototype),o}).apply(null,arguments)}function O(e){return(O=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function T(e,t){return(T=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function P(e){var t="function"==typeof Map?new Map:void 0;return(P=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return _(e,arguments,O(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),T(n,e)})(e)}function S(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(S=function(){return!!e})()}var C=function(e){var t;if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function n(){var e,t,r,o,a,i;if(!(this instanceof n))throw TypeError("Cannot call a class as a function");return t=n,r=arguments,t=O(t),o=e=function(e,t){var n;if(t&&("object"==((n=t)&&"undefined"!=typeof Symbol&&n.constructor===Symbol?"symbol":typeof n)||"function"==typeof t))return t;if(void 0===e)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(this,S()?Reflect.construct(t,r||[],O(this).constructor):t.apply(this,r)),a="taskResultRendererManager",i=new E,a in o?Object.defineProperty(o,a,{value:i,enumerable:!0,configurable:!0,writable:!0}):o[a]=i,e}return n.prototype=Object.create(e&&e.prototype,{constructor:{value:n,writable:!0,configurable:!0}}),e&&T(n,e),t=[{key:"load",value:function(){var e,t=this;return(e=function(){return function(e,t){var n,r,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function l(a){return function(l){var s=[a,l];if(n)throw TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(o=(o=i.trys).length>0&&o[o.length-1])&&(6===s[0]||2===s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}}(this,function(e){return t.app.use(w),[2]})},function(){var t=this,n=arguments;return new Promise(function(r,o){var a=e.apply(t,n);function i(e){x(a,r,o,i,l,"next",e)}function l(e){x(a,r,o,i,l,"throw",e)}i(void 0)})})()}}],function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(n.prototype,t),n}(P(e.Plugin)),M=C}(),l});
10
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("dayjs"),require("@nocobase/client"),require("antd")):"function"==typeof define&&define.amd?define("@nocobase/plugin-async-task-manager",["react","dayjs","@nocobase/client","antd"],t):"object"==typeof exports?exports["@nocobase/plugin-async-task-manager"]=t(require("react"),require("dayjs"),require("@nocobase/client"),require("antd")):e["@nocobase/plugin-async-task-manager"]=t(e.react,e.dayjs,e["@nocobase/client"],e.antd)}(self,function(e,t,n,r){var o={379:function(e,t,n){e.exports=function(e){"use strict";var t={name:"zh-cn",weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"周日_周一_周二_周三_周四_周五_周六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),ordinal:function(e,t){return"W"===t?e+"周":e+"日"},weekStart:1,yearStart:4,formats:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY/MM/DD",LL:"YYYY年M月D日",LLL:"YYYY年M月D日Ah点mm分",LLLL:"YYYY年M月D日ddddAh点mm分",l:"YYYY/M/D",ll:"YYYY年M月D日",lll:"YYYY年M月D日 HH:mm",llll:"YYYY年M月D日dddd HH:mm"},relativeTime:{future:"%s内",past:"%s前",s:"几秒",m:"1 分钟",mm:"%d 分钟",h:"1 小时",hh:"%d 小时",d:"1 天",dd:"%d 天",M:"1 个月",MM:"%d 个月",y:"1 年",yy:"%d 年"},meridiem:function(e,t){var n=100*e+t;return n<600?"凌晨":n<900?"早上":n<1100?"上午":n<1300?"中午":n<1800?"下午":"晚上"}};return(e&&"object"==typeof e&&"default"in e?e:{default:e}).default.locale(t,null,!0),t}(n(760))},809:function(e){e.exports=function(e,t,n){e=e||{};var r=t.prototype,o={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function a(e,t,n,o){return r.fromToBase(e,t,n,o)}n.en.relativeTime=o,r.fromToBase=function(t,r,a,i,l){for(var s,c,u,f=a.$locale().relativeTime||o,p=e.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],d=p.length,y=0;y<d;y+=1){var m=p[y];m.d&&(s=i?n(t).diff(a,m.d,!0):a.diff(t,m.d,!0));var v=(e.rounding||Math.round)(Math.abs(s));if(u=s>0,v<=m.r||!m.r){v<=1&&y>0&&(m=p[y-1]);var h=f[m.l];l&&(v=l(""+v)),c="string"==typeof h?h.replace("%d",v):h(v,r,m.l,u);break}}if(r)return c;var b=u?f.future:f.past;return"function"==typeof b?b(c):b.replace("%s",c)},r.to=function(e,t){return a(e,t,this,!0)},r.from=function(e,t){return a(e,t,this)};var i=function(e){return e.$u?n.utc():n()};r.toNow=function(e){return this.to(i(this),e)},r.fromNow=function(e){return this.from(i(this),e)}}},772:function(e){"use strict";e.exports=n},721:function(e){"use strict";e.exports=r},760:function(e){"use strict";e.exports=t},156:function(t){"use strict";t.exports=e}},a={};function i(e){var t=a[e];if(void 0!==t)return t.exports;var n=a[e]={exports:{}};return o[e].call(n.exports,n,n.exports,i),n.exports}i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,{a:t}),t},i.d=function(e,t){for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var l={};return!function(){"use strict";i.r(l),i.d(l,{PluginAsyncExportClient:function(){return C},default:function(){return M}});var e=i(772),t=i(156),n=i.n(t),r=i(721),o=i(760),a=i.n(o);i(379);var s=i(809),c=i.n(s),u=JSON.parse('{"u2":"@nocobase/plugin-async-task-manager"}');function f(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function p(e,t,n,r,o,a,i){try{var l=e[a](i),s=l.value}catch(e){n(e);return}l.done?t(s):Promise.resolve(s).then(r,o)}function d(e){return function(){var t=this,n=arguments;return new Promise(function(r,o){var a=e.apply(t,n);function i(e){p(a,r,o,i,l,"next",e)}function l(e){p(a,r,o,i,l,"throw",e)}i(void 0)})}}function y(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,o=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=o){var a=[],i=!0,l=!1;try{for(o=o.call(e);!(i=(n=o.next()).done)&&(a.push(n.value),!t||a.length!==t);i=!0);}catch(e){l=!0,r=e}finally{try{i||null==o.return||o.return()}finally{if(l)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return f(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return f(e,t)}}(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function m(e,t){var n,r,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function l(a){return function(l){var s=[a,l];if(n)throw TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(o=(o=i.trys).length>0&&o[o.length-1])&&(6===s[0]||2===s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}}var v=(0,e.createStyles)(function(e){return{button:{color:e.token.colorTextHeaderMenu+" !important"}}});a().extend(c());var h=function(e,t){if("success"!==e.type||!(null==(a=e.payload)||null==(o=a.message)?void 0:o.messageId))return null;var o,a,i=e.payload.message,l=i.messageId,s=i.messageValues;return n().createElement("div",{style:{marginLeft:8}},n().createElement(r.Tag,{color:"success"},t(l,s)))},b=function(){var t=(0,e.useRequest)({url:"asyncTasks:list"}),n=t.data,r=t.refreshAsync;return{loading:t.loading,tasks:(null==n?void 0:n.data)||[],refresh:r}},g=function(t){var o,i=t.popoverVisible,l=t.setPopoverVisible,s=t.tasks,c=t.refresh,f=t.loading,p=t.hasProcessingTasks,y=(0,e.useApp)(),b=(0,e.useAPIClient)(),g=(0,e.useCurrentAppInfo)(),k=(o=(0,e.useApp)(),function(e){return o.i18n.t(e,{ns:[u.u2,"client"]})}),w=v().styles,E=(0,e.usePlugin)("async-task-manager"),x=(0,e.useCollectionManager)(),_=(0,e.useCompile)(),O=function(e){l(!1)},T=[{title:k("Created at"),dataIndex:"createdAt",key:"createdAt",width:180,render:function(e){return n().createElement(r.Tooltip,{title:a()(e).format("YYYY-MM-DD HH:mm:ss")},a()(e).fromNow())}},{title:k("Task"),dataIndex:"title",key:"title",render:function(e,t){var n=t.title;if(!n)return"-";var r=x.getCollection(n.collection),o={export:k("Export"),import:k("Import"),"export-attachments":k("Export attachments")}[n.actionType]||n.actionType;return(({"export-attachments":k("Export {collection} attachments"),export:k("Export {collection} data"),import:k("Import {collection} data")})[n.actionType]||"".concat(o)).replace("{collection}",_((null==r?void 0:r.title)||n.collection))}},{title:k("Status"),dataIndex:"status",key:"status",width:160,render:function(t,o){var a,i={pending:{color:"default",text:k("Waiting"),icon:"ClockCircleOutlined"},running:{color:"processing",text:k("Processing"),icon:"LoadingOutlined"},success:{color:"success",text:k("Completed"),icon:"CheckCircleOutlined"},failed:{color:"error",text:k("Failed"),icon:"CloseCircleOutlined"},cancelled:{color:"warning",text:k("Cancelled"),icon:"StopOutlined"}},l=i[t.type]||{},s=l.color,c=l.text;return n().createElement("div",{style:{display:"flex",alignItems:"center",gap:8}},n().createElement("div",{style:{flex:1}},function(){var e,a,i={width:100,margin:0};switch(t.indicator){case"spinner":return n().createElement(r.Alert,{showIcon:!1,message:c,banner:!0});case"progress":return n().createElement(r.Progress,{type:"line",size:"small",strokeWidth:4,percent:Number(((null==(e=o.progress)?void 0:e.current)/(null==(a=o.progress)?void 0:a.total)*100).toFixed(2)),status:"active",style:i,format:function(e){return"".concat(e.toFixed(1),"%")}});case"success":return n().createElement(r.Progress,{type:"line",size:"small",strokeWidth:4,percent:100,status:"success",style:i,format:function(){return""}});case"error":return n().createElement(r.Progress,{type:"line",size:"small",strokeWidth:4,percent:100,status:"exception",style:i,format:function(){return""}});default:return null}}()),n().createElement(r.Tag,{color:s,icon:(null==(a=i[t.type])?void 0:a.icon)?n().createElement(e.Icon,{type:i[t.type].icon}):null,style:{margin:0,padding:"0 4px",height:22,width:22}}),h(t,k))}},{title:k("Actions"),key:"actions",width:180,render:function(t,o){var a=[];return("running"===o.status.type||"pending"===o.status.type)&&o.cancelable&&a.push(n().createElement(r.Popconfirm,{key:"cancel",title:k("Confirm cancel"),description:k("Confirm cancel description"),onConfirm:d(function(){return m(this,function(e){switch(e.label){case 0:return[4,b.request({url:"asyncTasks:cancel",params:{filterByTk:o.taskId}})];case 1:return e.sent(),c(),[2]}})}),okText:k("Confirm"),cancelText:k("Cancel"),disabled:!1},n().createElement(r.Button,{type:"link",size:"small",icon:n().createElement(e.Icon,{type:"StopOutlined"}),disabled:!1},k("Cancel")))),"success"===o.status.type&&("file"===o.status.resultType?a.push(n().createElement(r.Button,{key:"download",type:"link",size:"small",icon:n().createElement(e.Icon,{type:"DownloadOutlined"}),onClick:function(){var e,t,n,r=y.apiClient.auth.token,a=x.getCollection(o.title.collection),i=_(null==a?void 0:a.title),l=(null==o||null==(e=o.title)?void 0:e.actionType)==="export-attachments"?"-attachments.zip":".xlsx",s="".concat(i).concat(l),c=(null==o||null==(t=o.title)?void 0:t.actionType)!=="create migration"?encodeURIComponent(s):null,u=y.getApiUrl("asyncTasks:fetchFile/".concat(o.taskId,"?token=").concat(r,"&__appName=").concat(encodeURIComponent((null==g||null==(n=g.data)?void 0:n.name)||y.name)).concat(c?"&filename=".concat(c):""));window.open(u)}},k("Download"))):o.status.payload&&a.push(n().createElement(r.Button,{key:"view",type:"link",size:"small",icon:n().createElement(e.Icon,{type:"EyeOutlined"}),onClick:function(){O(o);var e=o.status.payload,t=E.taskResultRendererManager.get(o.title.actionType);r.Modal.info({title:k("Task result"),content:t?n().createElement(t,{payload:e,task:o}):n().createElement("div",null,k("No renderer available for this task type, payload: ".concat(e)))})}},k("View result")))),"failed"===o.status.type&&a.push(n().createElement(r.Button,{key:"error",type:"link",size:"small",icon:n().createElement(e.Icon,{type:"ExclamationCircleOutlined"}),onClick:function(){var e;l(!1),r.Modal.info({title:k("Error Details"),content:null==(e=o.status.errors)?void 0:e.map(function(e,t){return n().createElement("div",{key:t,style:{marginBottom:16}},n().createElement("div",{style:{color:"#ff4d4f",marginBottom:8}},e.message),e.code&&n().createElement("div",{style:{color:"#999",fontSize:12}},k("Error code"),": ",e.code))}),closable:!0,width:400})}},k("Error details"))),n().createElement(r.Space,{size:"middle"},a)}}],S=n().createElement("div",{style:{maxHeight:"70vh",overflow:"auto",width:s.length>0?800:200}},s.length>0?n().createElement(r.Table,{loading:f,columns:T,dataSource:s,size:"small",pagination:!1,rowKey:"taskId"}):n().createElement("div",{style:{padding:"24px 0",display:"flex",justifyContent:"center"}},n().createElement(r.Empty,{description:k("No tasks"),image:r.Empty.PRESENTED_IMAGE_SIMPLE})));return n().createElement(n().Fragment,null,n().createElement(r.Popover,{content:S,trigger:"hover",placement:"bottom",open:i,onOpenChange:l},n().createElement(r.Button,{className:["sync-task-button",w.button].join(" "),icon:n().createElement(e.Icon,{type:"SyncOutlined",spin:p}),onClick:function(){return l(!i)}})))},k=function(){var r=b(),o=r.tasks,a=r.refresh,i=function(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},a=Object.keys(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}(r,["tasks","refresh"]),l=(0,e.useApp)(),s=y((0,t.useState)(!1),2),c=s[0],u=s[1],f=y((0,t.useState)(!1),2),p=f[0],v=f[1];(0,t.useEffect)(function(){v(o.some(function(e){return"success"!==e.status.type&&"failed"!==e.status.type}))},[o]);var h=(0,t.useCallback)(d(function(){return m(this,function(e){return u(!0),[2]})}),[]),k=(0,t.useCallback)(function(){a(),console.log("handleTaskProgress")},[]),w=(0,t.useCallback)(function(){a(),console.log("handleTaskStatus")},[]),E=(0,t.useCallback)(function(){a(),console.log("handleTaskCancelled")},[]);return(0,t.useEffect)(function(){return l.eventBus.addEventListener("ws:message:async-tasks:created",h),l.eventBus.addEventListener("ws:message:async-tasks:progress",k),l.eventBus.addEventListener("ws:message:async-tasks:status",w),l.eventBus.addEventListener("ws:message:async-tasks:cancelled",E),function(){l.eventBus.removeEventListener("ws:message:async-tasks:created",h),l.eventBus.removeEventListener("ws:message:async-tasks:progress",k),l.eventBus.removeEventListener("ws:message:async-tasks:status",w),l.eventBus.removeEventListener("ws:message:async-tasks:cancelled",E)}},[l,E,h,k,w]),(null==o?void 0:o.length)>0&&n().createElement(g,function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){var r;r=n[t],t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r})}return e}({tasks:o,refresh:a,popoverVisible:c,setPopoverVisible:u,hasProcessingTasks:p},i))},w=function(t){return n().createElement(e.PinnedPluginListProvider,{items:{asyncTasks:{order:300,component:"AsyncTasks",pin:!0,snippet:"*"}}},n().createElement(e.SchemaComponentOptions,{components:{AsyncTasks:k}},t.children))},E=function(){var e;function t(){var e,n;if(!(this instanceof t))throw TypeError("Cannot call a class as a function");e="renderers",n=new Map,e in this?Object.defineProperty(this,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):this[e]=n}return e=[{key:"register",value:function(e,t){this.renderers.set(e,t)}},{key:"get",value:function(e){return this.renderers.get(e)}}],function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(t.prototype,e),t}();function x(e,t,n,r,o,a,i){try{var l=e[a](i),s=l.value}catch(e){n(e);return}l.done?t(s):Promise.resolve(s).then(r,o)}function _(e,t,n){return(_=P()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&T(o,n.prototype),o}).apply(null,arguments)}function O(e){return(O=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function T(e,t){return(T=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function S(e){var t="function"==typeof Map?new Map:void 0;return(S=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return _(e,arguments,O(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),T(n,e)})(e)}function P(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(P=function(){return!!e})()}var C=function(e){var t;if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function n(){var e,t,r,o,a,i;if(!(this instanceof n))throw TypeError("Cannot call a class as a function");return t=n,r=arguments,t=O(t),o=e=function(e,t){var n;if(t&&("object"==((n=t)&&"undefined"!=typeof Symbol&&n.constructor===Symbol?"symbol":typeof n)||"function"==typeof t))return t;if(void 0===e)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(this,P()?Reflect.construct(t,r||[],O(this).constructor):t.apply(this,r)),a="taskResultRendererManager",i=new E,a in o?Object.defineProperty(o,a,{value:i,enumerable:!0,configurable:!0,writable:!0}):o[a]=i,e}return n.prototype=Object.create(e&&e.prototype,{constructor:{value:n,writable:!0,configurable:!0}}),e&&T(n,e),t=[{key:"load",value:function(){var e,t=this;return(e=function(){return function(e,t){var n,r,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function l(a){return function(l){var s=[a,l];if(n)throw TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(o=(o=i.trys).length>0&&o[o.length-1])&&(6===s[0]||2===s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}}(this,function(e){return t.app.use(w),[2]})},function(){var t=this,n=arguments;return new Promise(function(r,o){var a=e.apply(t,n);function i(e){x(a,r,o,i,l,"next",e)}function l(e){x(a,r,o,i,l,"throw",e)}i(void 0)})})()}}],function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(n.prototype,t),n}(S(e.Plugin)),M=C}(),l});
@@ -8,12 +8,12 @@
8
8
  */
9
9
 
10
10
  module.exports = {
11
- "@nocobase/client": "1.7.0-beta.32",
11
+ "@nocobase/client": "1.7.0-beta.34",
12
12
  "react": "18.2.0",
13
- "@nocobase/logger": "1.7.0-beta.32",
14
- "@nocobase/server": "1.7.0-beta.32",
13
+ "@nocobase/logger": "1.7.0-beta.34",
14
+ "@nocobase/server": "1.7.0-beta.34",
15
15
  "lodash": "4.17.21",
16
- "@nocobase/plugin-error-handler": "1.7.0-beta.32",
16
+ "@nocobase/plugin-error-handler": "1.7.0-beta.34",
17
17
  "antd": "5.24.2",
18
18
  "dayjs": "1.11.13"
19
19
  };
@@ -1,5 +1,6 @@
1
1
  {
2
2
  "Export {collection} attachments": "{collection} attachments export",
3
3
  "Export {collection} data": "{collection} data export",
4
- "Import {collection} data": "{collection} data import"
4
+ "Import {collection} data": "{collection} data import",
5
+ "Waiting": "Being in a queue..."
5
6
  }
@@ -7,7 +7,7 @@
7
7
  "Actions": "操作",
8
8
  "Created at": "创建时间",
9
9
  "Type": "类型",
10
- "Waiting": "等待中",
10
+ "Waiting": "正在排队等待...",
11
11
  "Processing": "进行中",
12
12
  "Completed": "已完成",
13
13
  "Failed": "执行失败",
@@ -0,0 +1,101 @@
1
+ import EventEmitter = require('eventemitter3');
2
+ import { Queue, RunFunction } from './queue';
3
+ import PriorityQueue from './priority-queue';
4
+ import { QueueAddOptions, DefaultAddOptions, Options } from './options';
5
+ declare type Task<TaskResultType> = (() => PromiseLike<TaskResultType>) | (() => TaskResultType);
6
+ /**
7
+ Promise queue with concurrency control.
8
+ */
9
+ export default class PQueue<QueueType extends Queue<RunFunction, EnqueueOptionsType> = PriorityQueue, EnqueueOptionsType extends QueueAddOptions = DefaultAddOptions> extends EventEmitter<'active' | 'idle' | 'add' | 'next'> {
10
+ private readonly _carryoverConcurrencyCount;
11
+ private readonly _isIntervalIgnored;
12
+ private _intervalCount;
13
+ private readonly _intervalCap;
14
+ private readonly _interval;
15
+ private _intervalEnd;
16
+ private _intervalId?;
17
+ private _timeoutId?;
18
+ private _queue;
19
+ private readonly _queueClass;
20
+ private _pendingCount;
21
+ private _concurrency;
22
+ private _isPaused;
23
+ private _resolveEmpty;
24
+ private _resolveIdle;
25
+ private _timeout?;
26
+ private readonly _throwOnTimeout;
27
+ constructor(options?: Options<QueueType, EnqueueOptionsType>);
28
+ private get _doesIntervalAllowAnother();
29
+ private get _doesConcurrentAllowAnother();
30
+ private _next;
31
+ private _resolvePromises;
32
+ private _onResumeInterval;
33
+ private _isIntervalPaused;
34
+ private _tryToStartAnother;
35
+ private _initializeIntervalIfNeeded;
36
+ private _onInterval;
37
+ /**
38
+ Executes all queued functions until it reaches the limit.
39
+ */
40
+ private _processQueue;
41
+ get concurrency(): number;
42
+ set concurrency(newConcurrency: number);
43
+ /**
44
+ Adds a sync or async task to the queue. Always returns a promise.
45
+ */
46
+ add<TaskResultType>(fn: Task<TaskResultType>, options?: Partial<EnqueueOptionsType>): Promise<TaskResultType>;
47
+ /**
48
+ Same as `.add()`, but accepts an array of sync or async functions.
49
+
50
+ @returns A promise that resolves when all functions are resolved.
51
+ */
52
+ addAll<TaskResultsType>(functions: ReadonlyArray<Task<TaskResultsType>>, options?: EnqueueOptionsType): Promise<TaskResultsType[]>;
53
+ /**
54
+ Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)
55
+ */
56
+ start(): this;
57
+ /**
58
+ Put queue execution on hold.
59
+ */
60
+ pause(): void;
61
+ /**
62
+ Clear the queue.
63
+ */
64
+ clear(): void;
65
+ /**
66
+ Can be called multiple times. Useful if you for example add additional items at a later time.
67
+
68
+ @returns A promise that settles when the queue becomes empty.
69
+ */
70
+ onEmpty(): Promise<void>;
71
+ /**
72
+ The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.
73
+
74
+ @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.
75
+ */
76
+ onIdle(): Promise<void>;
77
+ /**
78
+ Size of the queue.
79
+ */
80
+ get size(): number;
81
+ /**
82
+ Size of the queue, filtered by the given options.
83
+
84
+ For example, this can be used to find the number of items remaining in the queue with a specific priority level.
85
+ */
86
+ sizeBy(options: Readonly<Partial<EnqueueOptionsType>>): number;
87
+ /**
88
+ Number of pending promises.
89
+ */
90
+ get pending(): number;
91
+ /**
92
+ Whether the queue is currently paused.
93
+ */
94
+ get isPaused(): boolean;
95
+ get timeout(): number | undefined;
96
+ /**
97
+ Set the timeout for future operations.
98
+ */
99
+ set timeout(milliseconds: number | undefined);
100
+ }
101
+ export { Queue, QueueAddOptions, DefaultAddOptions, Options };
@@ -0,0 +1 @@
1
+ (function(){"use strict";var e={330:function(e){e.exports=(e,t)=>{t=t||(()=>{});return e.then((e=>new Promise((e=>{e(t())})).then((()=>e))),(e=>new Promise((e=>{e(t())})).then((()=>{throw e}))))}},291:function(e,t){Object.defineProperty(t,"__esModule",{value:true});function lowerBound(e,t,n){let r=0;let i=e.length;while(i>0){const s=i/2|0;let o=r+s;if(n(e[o],t)<=0){r=++o;i-=s+1}else{i=s}}return r}t["default"]=lowerBound},492:function(e,t,n){Object.defineProperty(t,"__esModule",{value:true});const r=n(291);class PriorityQueue{constructor(){this._queue=[]}enqueue(e,t){t=Object.assign({priority:0},t);const n={priority:t.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority){this._queue.push(n);return}const i=r.default(this._queue,n,((e,t)=>t.priority-e.priority));this._queue.splice(i,0,n)}dequeue(){const e=this._queue.shift();return e===null||e===void 0?void 0:e.run}filter(e){return this._queue.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this._queue.length}}t["default"]=PriorityQueue},924:function(e){var t=Object.prototype.hasOwnProperty,n="~";function Events(){}if(Object.create){Events.prototype=Object.create(null);if(!(new Events).__proto__)n=false}function EE(e,t,n){this.fn=e;this.context=t;this.once=n||false}function addListener(e,t,r,i,s){if(typeof r!=="function"){throw new TypeError("The listener must be a function")}var o=new EE(r,i||e,s),u=n?n+t:t;if(!e._events[u])e._events[u]=o,e._eventsCount++;else if(!e._events[u].fn)e._events[u].push(o);else e._events[u]=[e._events[u],o];return e}function clearEvent(e,t){if(--e._eventsCount===0)e._events=new Events;else delete e._events[t]}function EventEmitter(){this._events=new Events;this._eventsCount=0}EventEmitter.prototype.eventNames=function eventNames(){var e=[],r,i;if(this._eventsCount===0)return e;for(i in r=this._events){if(t.call(r,i))e.push(n?i.slice(1):i)}if(Object.getOwnPropertySymbols){return e.concat(Object.getOwnPropertySymbols(r))}return e};EventEmitter.prototype.listeners=function listeners(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,s=r.length,o=new Array(s);i<s;i++){o[i]=r[i].fn}return o};EventEmitter.prototype.listenerCount=function listenerCount(e){var t=n?n+e:e,r=this._events[t];if(!r)return 0;if(r.fn)return 1;return r.length};EventEmitter.prototype.emit=function emit(e,t,r,i,s,o){var u=n?n+e:e;if(!this._events[u])return false;var a=this._events[u],l=arguments.length,c,h;if(a.fn){if(a.once)this.removeListener(e,a.fn,undefined,true);switch(l){case 1:return a.fn.call(a.context),true;case 2:return a.fn.call(a.context,t),true;case 3:return a.fn.call(a.context,t,r),true;case 4:return a.fn.call(a.context,t,r,i),true;case 5:return a.fn.call(a.context,t,r,i,s),true;case 6:return a.fn.call(a.context,t,r,i,s,o),true}for(h=1,c=new Array(l-1);h<l;h++){c[h-1]=arguments[h]}a.fn.apply(a.context,c)}else{var _=a.length,f;for(h=0;h<_;h++){if(a[h].once)this.removeListener(e,a[h].fn,undefined,true);switch(l){case 1:a[h].fn.call(a[h].context);break;case 2:a[h].fn.call(a[h].context,t);break;case 3:a[h].fn.call(a[h].context,t,r);break;case 4:a[h].fn.call(a[h].context,t,r,i);break;default:if(!c)for(f=1,c=new Array(l-1);f<l;f++){c[f-1]=arguments[f]}a[h].fn.apply(a[h].context,c)}}}return true};EventEmitter.prototype.on=function on(e,t,n){return addListener(this,e,t,n,false)};EventEmitter.prototype.once=function once(e,t,n){return addListener(this,e,t,n,true)};EventEmitter.prototype.removeListener=function removeListener(e,t,r,i){var s=n?n+e:e;if(!this._events[s])return this;if(!t){clearEvent(this,s);return this}var o=this._events[s];if(o.fn){if(o.fn===t&&(!i||o.once)&&(!r||o.context===r)){clearEvent(this,s)}}else{for(var u=0,a=[],l=o.length;u<l;u++){if(o[u].fn!==t||i&&!o[u].once||r&&o[u].context!==r){a.push(o[u])}}if(a.length)this._events[s]=a.length===1?a[0]:a;else clearEvent(this,s)}return this};EventEmitter.prototype.removeAllListeners=function removeAllListeners(e){var t;if(e){t=n?n+e:e;if(this._events[t])clearEvent(this,t)}else{this._events=new Events;this._eventsCount=0}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prefixed=n;EventEmitter.EventEmitter=EventEmitter;if(true){e.exports=EventEmitter}},424:function(e,t,n){const r=n(330);class TimeoutError extends Error{constructor(e){super(e);this.name="TimeoutError"}}const pTimeout=(e,t,n)=>new Promise(((i,s)=>{if(typeof t!=="number"||t<0){throw new TypeError("Expected `milliseconds` to be a positive number")}if(t===Infinity){i(e);return}const o=setTimeout((()=>{if(typeof n==="function"){try{i(n())}catch(e){s(e)}return}const r=typeof n==="string"?n:`Promise timed out after ${t} milliseconds`;const o=n instanceof Error?n:new TimeoutError(r);if(typeof e.cancel==="function"){e.cancel()}s(o)}),t);r(e.then(i,s),(()=>{clearTimeout(o)}))}));e.exports=pTimeout;e.exports["default"]=pTimeout;e.exports.TimeoutError=TimeoutError}};var t={};function __nccwpck_require__(n){var r=t[n];if(r!==undefined){return r.exports}var i=t[n]={exports:{}};var s=true;try{e[n](i,i.exports,__nccwpck_require__);s=false}finally{if(s)delete t[n]}return i.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var n={};!function(){var e=n;Object.defineProperty(e,"__esModule",{value:true});const t=__nccwpck_require__(924);const r=__nccwpck_require__(424);const i=__nccwpck_require__(492);const empty=()=>{};const s=new r.TimeoutError;class PQueue extends t{constructor(e){var t,n,r,s;super();this._intervalCount=0;this._intervalEnd=0;this._pendingCount=0;this._resolveEmpty=empty;this._resolveIdle=empty;e=Object.assign({carryoverConcurrencyCount:false,intervalCap:Infinity,interval:0,concurrency:Infinity,autoStart:true,queueClass:i.default},e);if(!(typeof e.intervalCap==="number"&&e.intervalCap>=1)){throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`)}if(e.interval===undefined||!(Number.isFinite(e.interval)&&e.interval>=0)){throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(r=e.interval)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`)}this._carryoverConcurrencyCount=e.carryoverConcurrencyCount;this._isIntervalIgnored=e.intervalCap===Infinity||e.interval===0;this._intervalCap=e.intervalCap;this._interval=e.interval;this._queue=new e.queueClass;this._queueClass=e.queueClass;this.concurrency=e.concurrency;this._timeout=e.timeout;this._throwOnTimeout=e.throwOnTimeout===true;this._isPaused=e.autoStart===false}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--;this._tryToStartAnother();this.emit("next")}_resolvePromises(){this._resolveEmpty();this._resolveEmpty=empty;if(this._pendingCount===0){this._resolveIdle();this._resolveIdle=empty;this.emit("idle")}}_onResumeInterval(){this._onInterval();this._initializeIntervalIfNeeded();this._timeoutId=undefined}_isIntervalPaused(){const e=Date.now();if(this._intervalId===undefined){const t=this._intervalEnd-e;if(t<0){this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}else{if(this._timeoutId===undefined){this._timeoutId=setTimeout((()=>{this._onResumeInterval()}),t)}return true}}return false}_tryToStartAnother(){if(this._queue.size===0){if(this._intervalId){clearInterval(this._intervalId)}this._intervalId=undefined;this._resolvePromises();return false}if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const t=this._queue.dequeue();if(!t){return false}this.emit("active");t();if(e){this._initializeIntervalIfNeeded()}return true}}return false}_initializeIntervalIfNeeded(){if(this._isIntervalIgnored||this._intervalId!==undefined){return}this._intervalId=setInterval((()=>{this._onInterval()}),this._interval);this._intervalEnd=Date.now()+this._interval}_onInterval(){if(this._intervalCount===0&&this._pendingCount===0&&this._intervalId){clearInterval(this._intervalId);this._intervalId=undefined}this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;this._processQueue()}_processQueue(){while(this._tryToStartAnother()){}}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e==="number"&&e>=1)){throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`)}this._concurrency=e;this._processQueue()}async add(e,t={}){return new Promise(((n,i)=>{const run=async()=>{this._pendingCount++;this._intervalCount++;try{const o=this._timeout===undefined&&t.timeout===undefined?e():r.default(Promise.resolve(e()),t.timeout===undefined?this._timeout:t.timeout,(()=>{if(t.throwOnTimeout===undefined?this._throwOnTimeout:t.throwOnTimeout){i(s)}return undefined}));n(await o)}catch(e){i(e)}this._next()};this._queue.enqueue(run,t);this._tryToStartAnother();this.emit("add")}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){if(!this._isPaused){return this}this._isPaused=false;this._processQueue();return this}pause(){this._isPaused=true}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size===0){return}return new Promise((e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t();e()}}))}async onIdle(){if(this._pendingCount===0&&this._queue.size===0){return}return new Promise((e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t();e()}}))}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}e["default"]=PQueue}();module.exports=n})();
@@ -0,0 +1 @@
1
+ export default function lowerBound<T>(array: readonly T[], value: T, comparator: (a: T, b: T) => number): number;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ // Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound
4
+ // Used to compute insertion index to keep queue sorted after insertion
5
+ function lowerBound(array, value, comparator) {
6
+ let first = 0;
7
+ let count = array.length;
8
+ while (count > 0) {
9
+ const step = (count / 2) | 0;
10
+ let it = first + step;
11
+ if (comparator(array[it], value) <= 0) {
12
+ first = ++it;
13
+ count -= step + 1;
14
+ }
15
+ else {
16
+ count = step;
17
+ }
18
+ }
19
+ return first;
20
+ }
21
+ exports.default = lowerBound;
@@ -0,0 +1,64 @@
1
+ import { Queue, RunFunction } from './queue';
2
+ export interface QueueAddOptions {
3
+ readonly [key: string]: unknown;
4
+ }
5
+ export interface Options<QueueType extends Queue<RunFunction, QueueOptions>, QueueOptions extends QueueAddOptions> {
6
+ /**
7
+ Concurrency limit.
8
+
9
+ Minimum: `1`.
10
+
11
+ @default Infinity
12
+ */
13
+ readonly concurrency?: number;
14
+ /**
15
+ Whether queue tasks within concurrency limit, are auto-executed as soon as they're added.
16
+
17
+ @default true
18
+ */
19
+ readonly autoStart?: boolean;
20
+ /**
21
+ Class with a `enqueue` and `dequeue` method, and a `size` getter. See the [Custom QueueClass](https://github.com/sindresorhus/p-queue#custom-queueclass) section.
22
+ */
23
+ readonly queueClass?: new () => QueueType;
24
+ /**
25
+ The max number of runs in the given interval of time.
26
+
27
+ Minimum: `1`.
28
+
29
+ @default Infinity
30
+ */
31
+ readonly intervalCap?: number;
32
+ /**
33
+ The length of time in milliseconds before the interval count resets. Must be finite.
34
+
35
+ Minimum: `0`.
36
+
37
+ @default 0
38
+ */
39
+ readonly interval?: number;
40
+ /**
41
+ Whether the task must finish in the given interval or will be carried over into the next interval count.
42
+
43
+ @default false
44
+ */
45
+ readonly carryoverConcurrencyCount?: boolean;
46
+ /**
47
+ Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.
48
+ */
49
+ timeout?: number;
50
+ /**
51
+ Whether or not a timeout is considered an exception.
52
+
53
+ @default false
54
+ */
55
+ throwOnTimeout?: boolean;
56
+ }
57
+ export interface DefaultAddOptions extends QueueAddOptions {
58
+ /**
59
+ Priority of operation. Operations with greater priority will be scheduled first.
60
+
61
+ @default 0
62
+ */
63
+ readonly priority?: number;
64
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,12 @@
1
+ import { Queue, RunFunction } from './queue';
2
+ import { QueueAddOptions } from './options';
3
+ export interface PriorityQueueOptions extends QueueAddOptions {
4
+ priority?: number;
5
+ }
6
+ export default class PriorityQueue implements Queue<RunFunction, PriorityQueueOptions> {
7
+ private readonly _queue;
8
+ enqueue(run: RunFunction, options?: Partial<PriorityQueueOptions>): void;
9
+ dequeue(): RunFunction | undefined;
10
+ filter(options: Readonly<Partial<PriorityQueueOptions>>): RunFunction[];
11
+ get size(): number;
12
+ }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const lower_bound_1 = require("./lower-bound");
4
+ class PriorityQueue {
5
+ constructor() {
6
+ this._queue = [];
7
+ }
8
+ enqueue(run, options) {
9
+ options = Object.assign({ priority: 0 }, options);
10
+ const element = {
11
+ priority: options.priority,
12
+ run
13
+ };
14
+ if (this.size && this._queue[this.size - 1].priority >= options.priority) {
15
+ this._queue.push(element);
16
+ return;
17
+ }
18
+ const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority);
19
+ this._queue.splice(index, 0, element);
20
+ }
21
+ dequeue() {
22
+ const item = this._queue.shift();
23
+ return item === null || item === void 0 ? void 0 : item.run;
24
+ }
25
+ filter(options) {
26
+ return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run);
27
+ }
28
+ get size() {
29
+ return this._queue.length;
30
+ }
31
+ }
32
+ exports.default = PriorityQueue;
@@ -0,0 +1,7 @@
1
+ export declare type RunFunction = () => Promise<unknown>;
2
+ export interface Queue<Element, Options> {
3
+ size: number;
4
+ filter: (options: Partial<Options>) => Element[];
5
+ dequeue: () => Element | undefined;
6
+ enqueue: (run: Element, options?: Partial<Options>) => void;
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Minimal `EventEmitter` interface that is molded against the Node.js
3
+ * `EventEmitter` interface.
4
+ */
5
+ declare class EventEmitter<
6
+ EventTypes extends EventEmitter.ValidEventTypes = string | symbol,
7
+ Context extends any = any
8
+ > {
9
+ static prefixed: string | boolean;
10
+
11
+ /**
12
+ * Return an array listing the events for which the emitter has registered
13
+ * listeners.
14
+ */
15
+ eventNames(): Array<EventEmitter.EventNames<EventTypes>>;
16
+
17
+ /**
18
+ * Return the listeners registered for a given event.
19
+ */
20
+ listeners<T extends EventEmitter.EventNames<EventTypes>>(
21
+ event: T
22
+ ): Array<EventEmitter.EventListener<EventTypes, T>>;
23
+
24
+ /**
25
+ * Return the number of listeners listening to a given event.
26
+ */
27
+ listenerCount(event: EventEmitter.EventNames<EventTypes>): number;
28
+
29
+ /**
30
+ * Calls each of the listeners registered for a given event.
31
+ */
32
+ emit<T extends EventEmitter.EventNames<EventTypes>>(
33
+ event: T,
34
+ ...args: EventEmitter.EventArgs<EventTypes, T>
35
+ ): boolean;
36
+
37
+ /**
38
+ * Add a listener for a given event.
39
+ */
40
+ on<T extends EventEmitter.EventNames<EventTypes>>(
41
+ event: T,
42
+ fn: EventEmitter.EventListener<EventTypes, T>,
43
+ context?: Context
44
+ ): this;
45
+ addListener<T extends EventEmitter.EventNames<EventTypes>>(
46
+ event: T,
47
+ fn: EventEmitter.EventListener<EventTypes, T>,
48
+ context?: Context
49
+ ): this;
50
+
51
+ /**
52
+ * Add a one-time listener for a given event.
53
+ */
54
+ once<T extends EventEmitter.EventNames<EventTypes>>(
55
+ event: T,
56
+ fn: EventEmitter.EventListener<EventTypes, T>,
57
+ context?: Context
58
+ ): this;
59
+
60
+ /**
61
+ * Remove the listeners of a given event.
62
+ */
63
+ removeListener<T extends EventEmitter.EventNames<EventTypes>>(
64
+ event: T,
65
+ fn?: EventEmitter.EventListener<EventTypes, T>,
66
+ context?: Context,
67
+ once?: boolean
68
+ ): this;
69
+ off<T extends EventEmitter.EventNames<EventTypes>>(
70
+ event: T,
71
+ fn?: EventEmitter.EventListener<EventTypes, T>,
72
+ context?: Context,
73
+ once?: boolean
74
+ ): this;
75
+
76
+ /**
77
+ * Remove all listeners, or those of the specified event.
78
+ */
79
+ removeAllListeners(event?: EventEmitter.EventNames<EventTypes>): this;
80
+ }
81
+
82
+ declare namespace EventEmitter {
83
+ export interface ListenerFn<Args extends any[] = any[]> {
84
+ (...args: Args): void;
85
+ }
86
+
87
+ export interface EventEmitterStatic {
88
+ new <
89
+ EventTypes extends ValidEventTypes = string | symbol,
90
+ Context = any
91
+ >(): EventEmitter<EventTypes, Context>;
92
+ }
93
+
94
+ /**
95
+ * `object` should be in either of the following forms:
96
+ * ```
97
+ * interface EventTypes {
98
+ * 'event-with-parameters': any[]
99
+ * 'event-with-example-handler': (...args: any[]) => void
100
+ * }
101
+ * ```
102
+ */
103
+ export type ValidEventTypes = string | symbol | object;
104
+
105
+ export type EventNames<T extends ValidEventTypes> = T extends string | symbol
106
+ ? T
107
+ : keyof T;
108
+
109
+ export type ArgumentMap<T extends object> = {
110
+ [K in keyof T]: T[K] extends (...args: any[]) => void
111
+ ? Parameters<T[K]>
112
+ : T[K] extends any[]
113
+ ? T[K]
114
+ : any[];
115
+ };
116
+
117
+ export type EventListener<
118
+ T extends ValidEventTypes,
119
+ K extends EventNames<T>
120
+ > = T extends string | symbol
121
+ ? (...args: any[]) => void
122
+ : (
123
+ ...args: ArgumentMap<Exclude<T, string | symbol>>[Extract<K, keyof T>]
124
+ ) => void;
125
+
126
+ export type EventArgs<
127
+ T extends ValidEventTypes,
128
+ K extends EventNames<T>
129
+ > = Parameters<EventListener<T, K>>;
130
+
131
+ export const EventEmitter: EventEmitterStatic;
132
+ }
133
+
134
+ export = EventEmitter;