@5minds/processcube_app_sdk 8.2.0-develop-97e5a9-mlkoajac → 8.2.1-alpha.1
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.
package/build/server/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var R=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var pe=Object.getOwnPropertyNames;var fe=Object.prototype.hasOwnProperty;var ye=(e,t)=>{for(var s in t)R(e,s,{get:t[s],enumerable:!0})},Ie=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of pe(t))!fe.call(e,o)&&o!==s&&R(e,o,{get:()=>t[o],enumerable:!(n=ue(t,o))||n.enumerable});return e};var me=e=>Ie(R({},"__esModule",{value:!0}),e);var Ve={};ye(Ve,{cancelReservedUserTask:()=>Be,finishManualTask:()=>K,finishTask:()=>$e,finishUntypedTask:()=>X,finishUserTask:()=>$,finishUserTaskAndGetNext:()=>Re,getActiveProcessInstances:()=>he,getAssignedUserTasksByIdentity:()=>De,getEngineClient:()=>_e,getFlowNodeInstances:()=>He,getFlowNodeInstancesByProcessInstanceId:()=>B,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds:()=>D,getIdentity:()=>i,getProcessInstance:()=>je,getProcessInstanceById:()=>M,getReservedUserTasksByIdentity:()=>Oe,getTriggeredFlowNodeInstances:()=>Ye,getUserTasks:()=>ae,getWaitingUserTaskByFlowNodeInstanceId:()=>ie,getWaitingUserTasks:()=>Ue,getWaitingUserTasksByCorrelationId:()=>ve,getWaitingUserTasksByFlowNodeId:()=>Ae,getWaitingUserTasksByProcessInstanceId:()=>Fe,navigateToUrl:()=>We,reserveUserTask:()=>Me,retryProcess:()=>Ge,retryProcessInstance:()=>L,startProcess:()=>qe,terminateProcess:()=>Xe,terminateProcessInstance:()=>W,waitForProcessEnd:()=>Ne,waitForUserTask:()=>be,withApplicationSdk:()=>Le});module.exports=me(Ve);var Rt=require("only-server"),Ut=require("../common/index.cjs");var H=require("chokidar"),Y=require("esbuild"),V=require("jwt-decode"),Q=require("node:child_process"),S=require("node:fs"),u=require("node:path"),N=require("openid-client"),Z=require("@5minds/processcube_engine_sdk");var j=require("@5minds/processcube_engine_client"),U=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",r=new j.EngineClient(U);var ke={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},Te=.85,h=["external_task.ts","external_task.js"],A=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,p=new Z.Logger("processcube_app_sdk:external_task_adapter"),k={},F={},x,J=6,ge=3e5,we=3e4;async function z(e){if(e&&!(0,S.existsSync)(e))throw new Error(`Invalid customExternalTasksDirPath. The given path '${e}' does not exist`);N.custom.setHttpOptionsDefaults({timeout:1e5});let t=await te();x=await se(t),await Ce(t);let s=xe(e);(0,H.watch)(s).on("add",async n=>{if(h.includes((0,u.basename)(n)))return v(n,s)}).on("change",async n=>{if(h.includes((0,u.basename)(n)))return Ee(n,s)}).on("unlink",async n=>{h.includes((0,u.basename)(n))&&ee(n)}).on("error",n=>p.error(`Watcher error: ${n}`))}async function v(e,t){let s=(0,u.dirname)(e);if((await S.promises.readdir(s)).filter(l=>h.includes(l)).length>1){p.error(`Multiple external task files found in directory ${s}. Stopping all external task workers for this directory.`),k[s]&&ee(e);return}let a=await ne(e),c=(0,u.relative)(t,s),d=re(c),f=(0,u.join)(__dirname,"lib/ExternalTaskWorkerProcess.cjs"),y=(0,Q.fork)(f,{env:{...process.env,PROCESSCUBE_ENGINE_URL:U}});k[s]=y,y.once("disconnect",()=>{delete k[s]}),y.on("error",l=>{p.error(`External Task Worker process error for ${d}`,{error:l,topic:d,workerDirectory:s})}),y.on("exit",(l,E)=>{if(p.info(`External Task Worker process exited for ${d}`,{code:l,signal:E,topic:d,workerDirectory:s}),delete k[s],l===3||l===4)if(Se(s)){let C=F[s]?.count??1,P=Math.min(1e3*Math.pow(2,C-1),we);p.info(`Scheduling restart for ${d} in ${P}ms (attempt ${C}/${J})`,{delay:P,restartCount:C,exitCode:l,topic:d,workerDirectory:s}),setTimeout(()=>{v(e,t).catch(b=>{p.error(`Failed to restart External Task Worker process for ${d}`,{error:b,topic:d,workerDirectory:s})})},P)}else p.error(`External Task Worker process for ${d} reached maximum restart attempts`,{exitCode:l,topic:d,workerDirectory:s})}),y.send({action:"create",payload:{topic:d,identity:x,moduleString:a,workerPath:e}})}async function Ee(e,t){let s=(0,u.dirname)(e),n=k[s];if(!n)return v(e,t);let o=await ne(e),a=(0,u.relative)(t,s),c=re(a);n.send({action:"restart",payload:{topic:c,identity:x,moduleString:o,workerPath:e}})}function ee(e){let t=(0,u.dirname)(e),s=k[t];s&&s.kill()}async function te(){if(!A)return null;if(!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID||!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET){let n=new Error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing. For help, please refer to our documentation on environment variables at: https://processcube.io/docs/app-sdk/samples/nextjs/external-task-adapter-with-nextjs#authority");throw p.error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing",{err:n}),n}let e=await N.Issuer.discover(process.env.PROCESSCUBE_AUTHORITY_URL);return await new e.Client({client_id:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID,client_secret:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET}).grant({grant_type:"client_credentials",scope:"engine_etw"})}function se(e){if(!A||e===null)return ke;let t=e.access_token,s=(0,V.jwtDecode)(t);return{token:e.access_token,userId:s.sub}}async function Ce(e){let t=5;if(!A||e===null)return;let n=await Pe(e)*Te*1e3,o=async()=>{try{let a=await te();x=se(a);for(let c of Object.values(k))c.send({action:"updateIdentity",payload:{identity:x}});t=5,setTimeout(o,n)}catch(a){if(t===0){p.error("Could not refresh identity for external task worker processes. Stopping all external task workers.",{error:a});for(let d of Object.values(k))d.kill();return}p.error("Could not refresh identity for external task worker processes.",{error:a,retryCount:t}),t--;let c=2*1e3;setTimeout(o,c)}};setTimeout(o,n)}async function ne(e){let t=await(0,Y.build)({entryPoints:[e],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(t.errors.length>0)throw p.error(`Could not transpile file at '${e}'`,{errors:t.errors}),new Error(`Could not transpile file at '${e}'`);return t.warnings.length>0&&p.warn(`Transpiled file at '${e}' with warnings`,{warnings:t.warnings}),t.outputFiles[0].text}async function Pe(e){let t=e.expires_in;if(!t&&e.expires_at&&(t=Math.floor(e.expires_at-Date.now()/1e3)),t===void 0)throw new Error("Could not determine the time until the access token for external task workers expires");return t}function re(e){return e.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function xe(e){let t,s=[e,(0,u.join)(process.cwd(),"app"),(0,u.join)(process.cwd(),"src","app")];for(let n of s)if(n&&(0,S.existsSync)(n)){t=n;break}if(!t)throw new Error("Could not find external tasks directory");return t}function Se(e){let t=Date.now(),s=F[e];return!s||t-s.timestamp>ge?(F[e]={count:1,timestamp:t},!0):s.count>=J?!1:(s.count++,!0)}function _e(){return r}var O=require("next-auth/jwt"),oe=require("next/dist/compiled/@edge-runtime/cookies/index.js"),T=require("next/headers");async function i(){let e=await(0,O.getToken)({req:{cookies:await(0,T.cookies)(),headers:await(0,T.headers)()}});if(e?.expiresAt&&Date.now()>=e.expiresAt*1e3){let s=await fetch(`${process.env.NEXTAUTH_URL}/api/auth/session`,{method:"GET",headers:{"Content-Type":"application/json",cookie:(await(0,T.cookies)()).toString()}}),n=new oe.ResponseCookies(s.headers);if(n.getAll().length){let o=!1;try{for(let a of n.getAll())(await(0,T.cookies)()).set(a.name,a.value,{...a})}catch{o=!0}if(e=await(0,O.getToken)({req:{cookies:o?n:await(0,T.cookies)(),headers:await(0,T.headers)()}}),e?.error)throw e.error}}if(!e?.accessToken||!e?.sub)throw new Error("AccessToken or Sub could not be determined!");return{token:e?.accessToken,userId:e?.sub}}var g=require("@5minds/processcube_engine_client");async function _(){try{return i()}catch{return}}async function M(e){let t=await _();return(await r.processInstances.query({processInstanceId:e},{identity:t,includeXml:!0})).processInstances[0]}async function B(e,t={sortSettings:{sortBy:g.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await r.flowNodeInstances.query({processInstanceId:e},{...t,identity:t.identity??await _()})).flowNodeInstances}async function D(e){let t=await _();return(await r.flowNodeInstances.query({triggeredByFlowNodeInstance:e},{identity:t})).flowNodeInstances}async function L(e,t,s){let n=await _();await r.processInstances.retryProcessInstance(e,{flowNodeInstanceId:t,newStartToken:s,identity:n})}async function W(e){let t=await _();await r.processInstances.terminateProcessInstance(e,t)}async function he(e={options:{identity:!0}}){switch(e.options.identity){case!0:e.options.identity=await i();break;case!1:e.options.identity=void 0;break;case void 0:e.options.identity=await i();break}return await r.processInstances.query({...e?.query,state:g.DataModels.ProcessInstances.ProcessInstanceState.running},e?.options)}async function Ne(e={},t=!0){let{processInstanceId:s}=e,n=typeof t=="boolean"?t==!0?await i():void 0:t;return new Promise(async(o,a)=>{let c=[],d=async f=>{if(s!==void 0&&f.processInstanceId!==s)return;let l=await r.processInstances.query({processInstanceId:f.processInstanceId},{identity:n});for(let E of c)r.notification.removeSubscription(E,n);return l.totalCount===0?a(new Error(`Process with instance ID "${f.processInstanceId}" does not exist.`)):o(l.processInstances[0])};if(c.push(await r.notification.onProcessEnded(d,{identity:n})),c.push(await r.notification.onProcessError(d,{identity:n})),c.push(await r.notification.onProcessTerminated(d,{identity:n})),s){let f=await r.processInstances.query({processInstanceId:s,state:[g.DataModels.ProcessInstances.ProcessInstanceState.finished,g.DataModels.ProcessInstances.ProcessInstanceState.terminated,g.DataModels.ProcessInstances.ProcessInstanceState.error]},{identity:n});if(f.totalCount>0){for(let y of c)r.notification.removeSubscription(y,n);o(f.processInstances[0])}}})}var m=require("@5minds/processcube_engine_client"),I=require("../common/index.cjs");async function be(e={},t=!0){let{correlationId:s,processInstanceId:n,flowNodeId:o}=e,a=typeof t=="boolean"?t==!0?await i():void 0:t;return new Promise(async(c,d)=>{let f=await r.userTasks.onUserTaskWaiting(async l=>{let E=s!==void 0&&l.correlationId!==s,C=l.flowNodeInstanceId===void 0,P=n!==void 0&&l.processInstanceId!==n,b=o!==void 0&&l.flowNodeId!==o;if(E||C||P||b)return;let G=await ie(l.flowNodeInstanceId,{identity:a});return r.notification.removeSubscription(f,a),G===null?d(new Error(`UserTask with instance ID "${l.flowNodeInstanceId}" does not exist.`)):c(G)},{identity:a}),y=await ae({correlationId:s,processInstanceId:n,flowNodeId:o,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:a});y.userTasks.length>0&&(r.notification.removeSubscription(f,a),c(y.userTasks[0]))})}async function Re(e,t={},s={},n=!0){let o=typeof n=="boolean"?n==!0?await i():void 0:n;await r.userTasks.finishUserTask(e,s,o);let a={state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended,...t},c=await r.userTasks.query(a,{identity:o});return(0,I.mapUserTask)(c.userTasks[0])}async function ae(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await i();break;case!1:t.identity=void 0;break;case void 0:t.identity=await i();break}let s=await r.userTasks.query(e,t);return(0,I.mapUserTaskList)(s)}async function Ue(e={identity:!0}){switch(e?.identity){case!0:e.identity=await i();break;case!1:e.identity=void 0;break;case void 0:e.identity=await i();break}let t=await r.userTasks.query({state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return(0,I.mapUserTaskList)(t)}async function Fe(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await i();break;case!1:t.identity=void 0;break;case void 0:t.identity=await i();break}let s=await r.userTasks.query({processInstanceId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function Ae(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await i();break;case!1:t.identity=void 0;break;case void 0:t.identity=await i();break}let s=await r.userTasks.query({flowNodeId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function ie(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await i();break;case!1:t.identity=void 0;break;case void 0:t.identity=await i();break}let s=await r.userTasks.query({flowNodeInstanceId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{...t,limit:1});return s.userTasks.length===0?null:(0,I.mapUserTask)(s.userTasks[0])}async function ve(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await i();break;case!1:t.identity=void 0;break;case void 0:t.identity=await i();break}let s=await r.userTasks.query({correlationId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function Oe(e,t){let s=e||await i(),n=await r.userTasks.query({state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:s,...t}),o=n.userTasks.filter(a=>a.actualOwnerId===s.userId);return n.userTasks=o,(0,I.mapUserTaskList)(n)}async function Me(e,t,s){await r.userTasks.reserveUserTaskInstance(e,t,s||e.userId)}async function Be(e,t){await r.userTasks.cancelUserTaskInstanceReservation(e,t)}async function De(e,t){let s=e||await i(),n=await r.userTasks.query({state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:s,...t}),o=n.userTasks.filter(a=>a.assignedUserIds?.includes(s.userId));return n.userTasks=o,(0,I.mapUserTaskList)(n)}var w=require("next/dist/shared/lib/constants");var ce=!1,q=!1;function Le(e={}){let{applicationSdk:t,...s}=e;return async(n,o)=>{q=q||n===w.PHASE_PRODUCTION_BUILD;let a=n===w.PHASE_DEVELOPMENT_SERVER||n===w.PHASE_PRODUCTION_SERVER;return t?.useExternalTasks&&a&&!ce&&!q&&(ce=!0,await z(t?.customExternalTasksDirPath)),{...s,experimental:{...s.experimental,serverComponentsExternalPackages:[...s.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}var de=require("next/navigation");function We(e){(0,de.redirect)(e)}async function qe(...e){return await r.processModels.startProcessInstance(...e)}async function K(...e){await r.manualTasks.finishManualTask(...e)}async function $(...e){await r.userTasks.finishUserTask(...e)}async function X(...e){await r.untypedTasks.finishTask(...e)}var le=require("@5minds/processcube_engine_client");async function Ke(){try{return i()}catch{return}}var $e=async(e,t)=>{let s=await Ke();t==="bpmn:UserTask"?await $(e,{},s):t==="bpmn:ManualTask"?await K(e,s):t==="bpmn:Task"?await X(e,s):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${t}`)},Xe=async e=>{await W(e)},Ge=async(e,t,s)=>{await L(e,t,s)},je=async e=>M(e),He=async e=>B(e,{sortSettings:{sortBy:le.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),Ye=async e=>D(e);0&&(module.exports={cancelReservedUserTask,finishManualTask,finishTask,finishUntypedTask,finishUserTask,finishUserTaskAndGetNext,getActiveProcessInstances,getAssignedUserTasksByIdentity,getEngineClient,getFlowNodeInstances,getFlowNodeInstancesByProcessInstanceId,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,getIdentity,getProcessInstance,getProcessInstanceById,getReservedUserTasksByIdentity,getTriggeredFlowNodeInstances,getUserTasks,getWaitingUserTaskByFlowNodeInstanceId,getWaitingUserTasks,getWaitingUserTasksByCorrelationId,getWaitingUserTasksByFlowNodeId,getWaitingUserTasksByProcessInstanceId,navigateToUrl,reserveUserTask,retryProcess,retryProcessInstance,startProcess,terminateProcess,terminateProcessInstance,waitForProcessEnd,waitForUserTask,withApplicationSdk});
|
|
1
|
+
var U=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var ke=Object.prototype.hasOwnProperty;var ge=(e,t)=>{for(var s in t)U(e,s,{get:t[s],enumerable:!0})},we=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Te(t))!ke.call(e,o)&&o!==s&&U(e,o,{get:()=>t[o],enumerable:!(n=me(t,o))||n.enumerable});return e};var Ee=e=>we(U({},"__esModule",{value:!0}),e);var tt={};ge(tt,{cancelReservedUserTask:()=>Ke,finishManualTask:()=>G,finishTask:()=>Ve,finishUntypedTask:()=>j,finishUserTask:()=>H,finishUserTaskAndGetNext:()=>ve,getActiveProcessInstances:()=>Ae,getAssignedUserTasksByIdentity:()=>Xe,getEngineClient:()=>Fe,getFlowNodeInstances:()=>ze,getFlowNodeInstancesByProcessInstanceId:()=>W,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds:()=>q,getIdentity:()=>a,getProcessInstance:()=>Je,getProcessInstanceById:()=>L,getReservedUserTasksByIdentity:()=>qe,getTriggeredFlowNodeInstances:()=>et,getUserTasks:()=>ue,getWaitingUserTaskByFlowNodeInstanceId:()=>pe,getWaitingUserTasks:()=>Be,getWaitingUserTasksByCorrelationId:()=>We,getWaitingUserTasksByFlowNodeId:()=>Le,getWaitingUserTasksByProcessInstanceId:()=>De,navigateToUrl:()=>He,reserveUserTask:()=>$e,retryProcess:()=>Ze,retryProcessInstance:()=>$,startProcess:()=>je,terminateProcess:()=>Qe,terminateProcessInstance:()=>K,waitForProcessEnd:()=>Me,waitForUserTask:()=>Oe,withApplicationSdk:()=>Ge});module.exports=Ee(tt);var vt=require("only-server"),Bt=require("../common/index.cjs");var Z=require("chokidar"),J=require("esbuild"),z=require("jwt-decode"),ee=require("node:child_process"),x=require("node:fs"),p=require("node:path"),b=require("openid-client"),te=require("@5minds/processcube_engine_sdk");var V=require("@5minds/processcube_engine_client"),F=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",r=new V.EngineClient(F);var Ce={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},_e=.85,R=["external_task.ts","external_task.js"],h=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,u=new te.Logger("processcube_app_sdk:external_task_adapter"),k={},M={},w,O=!1,se=6,Pe=3e5,Se=3e4,A=10,xe=3e4,Q=10,he=6e4;async function ne(e){if(e&&!(0,x.existsSync)(e))throw new Error(`Invalid customExternalTasksDirPath. The given path '${e}' does not exist`);b.custom.setHttpOptionsDefaults({timeout:1e5});let t=await ie();w=B(t),await ae(t);let s=be(e);(0,Z.watch)(s).on("add",async n=>{if(R.includes((0,p.basename)(n)))return v(n,s)}).on("change",async n=>{if(R.includes((0,p.basename)(n)))return Ne(n,s)}).on("unlink",async n=>{R.includes((0,p.basename)(n))&&re(n)}).on("error",n=>u.error(`Watcher error: ${n}`))}async function v(e,t){let s=(0,p.dirname)(e);if((await x.promises.readdir(s)).filter(l=>R.includes(l)).length>1){u.error(`Multiple external task files found in directory ${s}. Stopping all external task workers for this directory.`),k[s]&&re(e);return}let i=await ce(e),c=(0,p.relative)(t,s),d=de(c),f=(0,p.join)(__dirname,"lib/ExternalTaskWorkerProcess.cjs"),y=(0,ee.fork)(f,{env:{...process.env,PROCESSCUBE_ENGINE_URL:F}});k[s]=y,y.once("disconnect",()=>{delete k[s]}),y.on("error",l=>{u.error(`External Task Worker process error for ${d}`,{error:l,topic:d,workerDirectory:s})}),y.on("exit",(l,_)=>{if(u.info(`External Task Worker process exited for ${d}`,{code:l,signal:_,topic:d,workerDirectory:s}),delete k[s],l===3||l===4)if(Ue(s)){let P=M[s]?.count??1,S=Math.min(1e3*Math.pow(2,P-1),Se);u.info(`Scheduling restart for ${d} in ${S}ms (attempt ${P}/${se})`,{delay:S,restartCount:P,exitCode:l,topic:d,workerDirectory:s}),setTimeout(async()=>{try{if(h&&!O){u.info("Token refresh cycle is not active, restarting it before worker restart");let g=await ie();w=B(g),await ae(g)}await v(e,t)}catch(g){u.error(`Failed to restart External Task Worker process for ${d}`,{error:g,topic:d,workerDirectory:s})}},S)}else u.error(`External Task Worker process for ${d} reached maximum restart attempts`,{exitCode:l,topic:d,workerDirectory:s})}),y.send({action:"create",payload:{topic:d,identity:w,moduleString:i,workerPath:e}})}async function Ne(e,t){let s=(0,p.dirname)(e),n=k[s];if(!n)return v(e,t);let o=await ce(e),i=(0,p.relative)(t,s),c=de(i);n.send({action:"restart",payload:{topic:c,identity:w,moduleString:o,workerPath:e}})}function re(e){let t=(0,p.dirname)(e),s=k[t];s&&s.kill()}async function oe(){if(!h)return null;if(!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID||!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET){let n=new Error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing. For help, please refer to our documentation on environment variables at: https://processcube.io/docs/app-sdk/samples/nextjs/external-task-adapter-with-nextjs#authority");throw u.error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing",{err:n}),n}let e=await b.Issuer.discover(process.env.PROCESSCUBE_AUTHORITY_URL);return await new e.Client({client_id:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID,client_secret:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET}).grant({grant_type:"client_credentials",scope:"engine_etw"})}async function ie(){if(!h)return null;for(let e=1;e<=A;e++)try{return await oe()}catch(t){let s=Math.min(1e3*Math.pow(2,e-1),xe);if(u.error(`Failed to fetch initial token set (attempt ${e}/${A}), retrying in ${s}ms`,{error:t,attempt:e,delay:s}),e===A)throw t;await new Promise(n=>setTimeout(n,s))}return null}function B(e){if(!h||e===null)return Ce;let t=e.access_token,s=(0,z.jwtDecode)(t);return{token:e.access_token,userId:s.sub}}async function ae(e){if(!h||e===null||O)return;O=!0;let t=0,n=await Re(e)*_e*1e3,o=async()=>{try{let i=await oe();w=B(i);for(let[c,d]of Object.entries(k))try{d.send({action:"updateIdentity",payload:{identity:w}})}catch(f){u.warn(`Failed to send identity update to worker process ${c}`,{sendError:f})}t=0,setTimeout(o,n)}catch(i){t++;let c=Math.min(1e3*Math.pow(2,t-1),he);t<=Q?u.error(`Could not refresh identity (attempt ${t}/${Q}), retrying in ${c}ms`,{error:i,attempt:t,delay:c}):u.error(`Could not refresh identity (attempt ${t}), continuing to retry every ${c}ms`,{error:i,attempt:t,delay:c}),setTimeout(o,c)}};setTimeout(o,n)}async function ce(e){let t=await(0,J.build)({entryPoints:[e],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(t.errors.length>0)throw u.error(`Could not transpile file at '${e}'`,{errors:t.errors}),new Error(`Could not transpile file at '${e}'`);return t.warnings.length>0&&u.warn(`Transpiled file at '${e}' with warnings`,{warnings:t.warnings}),t.outputFiles[0].text}async function Re(e){let t=e.expires_in;if(!t&&e.expires_at&&(t=Math.floor(e.expires_at-Date.now()/1e3)),t===void 0)throw new Error("Could not determine the time until the access token for external task workers expires");return t}function de(e){return e.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function be(e){let t,s=[e,(0,p.join)(process.cwd(),"app"),(0,p.join)(process.cwd(),"src","app")];for(let n of s)if(n&&(0,x.existsSync)(n)){t=n;break}if(!t)throw new Error("Could not find external tasks directory");return t}function Ue(e){let t=Date.now(),s=M[e];return!s||t-s.timestamp>Pe?(M[e]={count:1,timestamp:t},!0):s.count>=se?!1:(s.count++,!0)}function Fe(){return r}var D=require("next-auth/jwt"),le=require("next/dist/compiled/@edge-runtime/cookies/index.js"),T=require("next/headers");async function a(){let e=await(0,D.getToken)({req:{cookies:await(0,T.cookies)(),headers:await(0,T.headers)()}});if(e?.expiresAt&&Date.now()>=e.expiresAt*1e3){let s=await fetch(`${process.env.NEXTAUTH_URL}/api/auth/session`,{method:"GET",headers:{"Content-Type":"application/json",cookie:(await(0,T.cookies)()).toString()}}),n=new le.ResponseCookies(s.headers);if(n.getAll().length){let o=!1;try{for(let i of n.getAll())(await(0,T.cookies)()).set(i.name,i.value,{...i})}catch{o=!0}if(e=await(0,D.getToken)({req:{cookies:o?n:await(0,T.cookies)(),headers:await(0,T.headers)()}}),e?.error)throw e.error}}if(!e?.accessToken||!e?.sub)throw new Error("AccessToken or Sub could not be determined!");return{token:e?.accessToken,userId:e?.sub}}var E=require("@5minds/processcube_engine_client");async function N(){try{return a()}catch{return}}async function L(e){let t=await N();return(await r.processInstances.query({processInstanceId:e},{identity:t,includeXml:!0})).processInstances[0]}async function W(e,t={sortSettings:{sortBy:E.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await r.flowNodeInstances.query({processInstanceId:e},{...t,identity:t.identity??await N()})).flowNodeInstances}async function q(e){let t=await N();return(await r.flowNodeInstances.query({triggeredByFlowNodeInstance:e},{identity:t})).flowNodeInstances}async function $(e,t,s){let n=await N();await r.processInstances.retryProcessInstance(e,{flowNodeInstanceId:t,newStartToken:s,identity:n})}async function K(e){let t=await N();await r.processInstances.terminateProcessInstance(e,t)}async function Ae(e={options:{identity:!0}}){switch(e.options.identity){case!0:e.options.identity=await a();break;case!1:e.options.identity=void 0;break;case void 0:e.options.identity=await a();break}return await r.processInstances.query({...e?.query,state:E.DataModels.ProcessInstances.ProcessInstanceState.running},e?.options)}async function Me(e={},t=!0){let{processInstanceId:s}=e,n=typeof t=="boolean"?t==!0?await a():void 0:t;return new Promise(async(o,i)=>{let c=[],d=async f=>{if(s!==void 0&&f.processInstanceId!==s)return;let l=await r.processInstances.query({processInstanceId:f.processInstanceId},{identity:n});for(let _ of c)r.notification.removeSubscription(_,n);return l.totalCount===0?i(new Error(`Process with instance ID "${f.processInstanceId}" does not exist.`)):o(l.processInstances[0])};if(c.push(await r.notification.onProcessEnded(d,{identity:n})),c.push(await r.notification.onProcessError(d,{identity:n})),c.push(await r.notification.onProcessTerminated(d,{identity:n})),s){let f=await r.processInstances.query({processInstanceId:s,state:[E.DataModels.ProcessInstances.ProcessInstanceState.finished,E.DataModels.ProcessInstances.ProcessInstanceState.terminated,E.DataModels.ProcessInstances.ProcessInstanceState.error]},{identity:n});if(f.totalCount>0){for(let y of c)r.notification.removeSubscription(y,n);o(f.processInstances[0])}}})}var m=require("@5minds/processcube_engine_client"),I=require("../common/index.cjs");async function Oe(e={},t=!0){let{correlationId:s,processInstanceId:n,flowNodeId:o}=e,i=typeof t=="boolean"?t==!0?await a():void 0:t;return new Promise(async(c,d)=>{let f=await r.userTasks.onUserTaskWaiting(async l=>{let _=s!==void 0&&l.correlationId!==s,P=l.flowNodeInstanceId===void 0,S=n!==void 0&&l.processInstanceId!==n,g=o!==void 0&&l.flowNodeId!==o;if(_||P||S||g)return;let Y=await pe(l.flowNodeInstanceId,{identity:i});return r.notification.removeSubscription(f,i),Y===null?d(new Error(`UserTask with instance ID "${l.flowNodeInstanceId}" does not exist.`)):c(Y)},{identity:i}),y=await ue({correlationId:s,processInstanceId:n,flowNodeId:o,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});y.userTasks.length>0&&(r.notification.removeSubscription(f,i),c(y.userTasks[0]))})}async function ve(e,t={},s={},n=!0){let o=typeof n=="boolean"?n==!0?await a():void 0:n;await r.userTasks.finishUserTask(e,s,o);let i={state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended,...t},c=await r.userTasks.query(i,{identity:o});return(0,I.mapUserTask)(c.userTasks[0])}async function ue(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query(e,t);return(0,I.mapUserTaskList)(s)}async function Be(e={identity:!0}){switch(e?.identity){case!0:e.identity=await a();break;case!1:e.identity=void 0;break;case void 0:e.identity=await a();break}let t=await r.userTasks.query({state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return(0,I.mapUserTaskList)(t)}async function De(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query({processInstanceId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function Le(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query({flowNodeId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function pe(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query({flowNodeInstanceId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{...t,limit:1});return s.userTasks.length===0?null:(0,I.mapUserTask)(s.userTasks[0])}async function We(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query({correlationId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function qe(e,t){let s=e||await a(),n=await r.userTasks.query({state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:s,...t}),o=n.userTasks.filter(i=>i.actualOwnerId===s.userId);return n.userTasks=o,(0,I.mapUserTaskList)(n)}async function $e(e,t,s){await r.userTasks.reserveUserTaskInstance(e,t,s||e.userId)}async function Ke(e,t){await r.userTasks.cancelUserTaskInstanceReservation(e,t)}async function Xe(e,t){let s=e||await a(),n=await r.userTasks.query({state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:s,...t}),o=n.userTasks.filter(i=>i.assignedUserIds?.includes(s.userId));return n.userTasks=o,(0,I.mapUserTaskList)(n)}var C=require("next/dist/shared/lib/constants");var fe=!1,X=!1;function Ge(e={}){let{applicationSdk:t,...s}=e;return async(n,o)=>{X=X||n===C.PHASE_PRODUCTION_BUILD;let i=n===C.PHASE_DEVELOPMENT_SERVER||n===C.PHASE_PRODUCTION_SERVER;return t?.useExternalTasks&&i&&!fe&&!X&&(fe=!0,await ne(t?.customExternalTasksDirPath)),{...s,experimental:{...s.experimental,serverComponentsExternalPackages:[...s.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}var ye=require("next/navigation");function He(e){(0,ye.redirect)(e)}async function je(...e){return await r.processModels.startProcessInstance(...e)}async function G(...e){await r.manualTasks.finishManualTask(...e)}async function H(...e){await r.userTasks.finishUserTask(...e)}async function j(...e){await r.untypedTasks.finishTask(...e)}var Ie=require("@5minds/processcube_engine_client");async function Ye(){try{return a()}catch{return}}var Ve=async(e,t)=>{let s=await Ye();t==="bpmn:UserTask"?await H(e,{},s):t==="bpmn:ManualTask"?await G(e,s):t==="bpmn:Task"?await j(e,s):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${t}`)},Qe=async e=>{await K(e)},Ze=async(e,t,s)=>{await $(e,t,s)},Je=async e=>L(e),ze=async e=>W(e,{sortSettings:{sortBy:Ie.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),et=async e=>q(e);0&&(module.exports={cancelReservedUserTask,finishManualTask,finishTask,finishUntypedTask,finishUserTask,finishUserTaskAndGetNext,getActiveProcessInstances,getAssignedUserTasksByIdentity,getEngineClient,getFlowNodeInstances,getFlowNodeInstancesByProcessInstanceId,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,getIdentity,getProcessInstance,getProcessInstanceById,getReservedUserTasksByIdentity,getTriggeredFlowNodeInstances,getUserTasks,getWaitingUserTaskByFlowNodeInstanceId,getWaitingUserTasks,getWaitingUserTasksByCorrelationId,getWaitingUserTasksByFlowNodeId,getWaitingUserTasksByProcessInstanceId,navigateToUrl,reserveUserTask,retryProcess,retryProcessInstance,startProcess,terminateProcess,terminateProcessInstance,waitForProcessEnd,waitForUserTask,withApplicationSdk});
|
package/build/server/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"only-server";import"../common/index.mjs";import{stat as be}from"fs";import{stat as Se,readdir as Ce}from"fs/promises";import{EventEmitter as Ne}from"events";import*as p from"path";import{stat as Zt,lstat as dt,readdir as Jt,realpath as te}from"node:fs/promises";import{Readable as ee}from"node:stream";import{resolve as lt,relative as se,join as ne,sep as re}from"node:path";var E={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},Y={root:".",fileFilter:s=>!0,directoryFilter:s=>!0,type:E.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(Y);var pt="READDIRP_RECURSIVE_ERROR",ie=new Set(["ENOENT","EPERM","EACCES","ELOOP",pt]),ft=[E.DIR_TYPE,E.EVERYTHING_TYPE,E.FILE_DIR_TYPE,E.FILE_TYPE],oe=new Set([E.DIR_TYPE,E.EVERYTHING_TYPE,E.FILE_DIR_TYPE]),ae=new Set([E.EVERYTHING_TYPE,E.FILE_DIR_TYPE,E.FILE_TYPE]),ce=s=>ie.has(s.code),de=process.platform==="win32",ut=s=>!0,ht=s=>{if(s===void 0)return ut;if(typeof s=="function")return s;if(typeof s=="string"){let t=s.trim();return e=>e.basename===t}if(Array.isArray(s)){let t=s.map(e=>e.trim());return e=>t.some(n=>e.basename===n)}return ut},z=class extends ee{constructor(t={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:t.highWaterMark});let e={...Y,...t},{root:n,type:r}=e;this._fileFilter=ht(e.fileFilter),this._directoryFilter=ht(e.directoryFilter);let i=e.lstat?dt:Zt;de?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=e.depth??Y.depth,this._wantsDir=r?oe.has(r):!1,this._wantsFile=r?ae.has(r):!1,this._wantsEverything=r===E.EVERYTHING_TYPE,this._root=lt(n),this._isDirent=!e.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(t){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&t>0;){let e=this.parent,n=e&&e.files;if(n&&n.length>0){let{path:r,depth:i}=e,a=n.splice(0,t).map(c=>this._formatEntry(c,r)),o=await Promise.all(a);for(let c of o){if(!c)continue;if(this.destroyed)return;let l=await this._getEntryType(c);l==="directory"&&this._directoryFilter(c)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(c.fullPath,i+1)),this._wantsDir&&(this.push(c),t--)):(l==="file"||this._includeAsFile(c))&&this._fileFilter(c)&&this._wantsFile&&(this.push(c),t--)}}else{let r=this.parents.pop();if(!r){this.push(null);break}if(this.parent=await r,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(t,e){let n;try{n=await Jt(t,this._rdOptions)}catch(r){this._onError(r)}return{files:n,depth:e,path:t}}async _formatEntry(t,e){let n,r=this._isDirent?t.name:t;try{let i=lt(ne(e,r));n={path:se(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?t:await this._stat(i)}catch(i){this._onError(i);return}return n}_onError(t){ce(t)&&!this.destroyed?this.emit("warn",t):this.destroy(t)}async _getEntryType(t){if(!t&&this._statsProp in t)return"";let e=t[this._statsProp];if(e.isFile())return"file";if(e.isDirectory())return"directory";if(e&&e.isSymbolicLink()){let n=t.fullPath;try{let r=await te(n),i=await dt(r);if(i.isFile())return"file";if(i.isDirectory()){let a=r.length;if(n.startsWith(r)&&n.substr(a,1)===re){let o=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return o.code=pt,this._onError(o)}return"directory"}}catch(r){return this._onError(r),""}}}_includeAsFile(t){let e=t&&t[this._statsProp];return e&&this._wantsEverything&&!e.isDirectory()}};function mt(s,t={}){let e=t.entryType||t.type;if(e==="both"&&(e=E.FILE_DIR_TYPE),e&&(t.type=e),s){if(typeof s!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(e&&!ft.includes(e))throw new Error(`readdirp: Invalid type passed. Use one of ${ft.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return t.root=s,new z(t)}import{watchFile as le,unwatchFile as yt,watch as fe}from"fs";import{open as ue,stat as _t,lstat as he,realpath as K}from"fs/promises";import*as y from"path";import{type as pe}from"os";var me="data",$="end",gt="close",O=()=>{};var M=process.platform,V=M==="win32",ye=M==="darwin",we=M==="linux",_e=M==="freebsd",Et=pe()==="OS400",_={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},T=_,ge="watch",Ee={lstat:he,stat:_t},R="listeners",A="errHandlers",S="rawEmitters",Ie=[R,A,S],Te=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Pe=s=>Te.has(y.extname(s).slice(1).toLowerCase()),G=(s,t)=>{s instanceof Set?s.forEach(t):t(s)},C=(s,t,e)=>{let n=s[t];n instanceof Set||(s[t]=n=new Set([n])),n.add(e)},ke=s=>t=>{let e=s[t];e instanceof Set?e.clear():delete s[t]},N=(s,t,e)=>{let n=s[t];n instanceof Set?n.delete(e):n===e&&delete s[t]},It=s=>s instanceof Set?s.size===0:!s,U=new Map;function wt(s,t,e,n,r){let i=(a,o)=>{e(s),r(a,o,{watchedPath:s}),o&&s!==o&&W(y.resolve(s,o),R,y.join(s,o))};try{return fe(s,{persistent:t.persistent},i)}catch(a){n(a);return}}var W=(s,t,e,n,r)=>{let i=U.get(s);i&&G(i[t],a=>{a(e,n,r)})},xe=(s,t,e,n)=>{let{listener:r,errHandler:i,rawEmitter:a}=n,o=U.get(t),c;if(!e.persistent)return c=wt(s,e,r,i,a),c?c.close.bind(c):void 0;if(o)C(o,R,r),C(o,A,i),C(o,S,a);else{if(c=wt(s,e,W.bind(null,t,R),i,W.bind(null,t,S)),!c)return;c.on(T.ERROR,async l=>{let d=W.bind(null,t,A);if(o&&(o.watcherUnusable=!0),V&&l.code==="EPERM")try{await(await ue(s,"r")).close(),d(l)}catch{}else d(l)}),o={listeners:r,errHandlers:i,rawEmitters:a,watcher:c},U.set(t,o)}return()=>{N(o,R,r),N(o,A,i),N(o,S,a),It(o.listeners)&&(o.watcher.close(),U.delete(t),Ie.forEach(ke(o)),o.watcher=void 0,Object.freeze(o))}},q=new Map,Re=(s,t,e,n)=>{let{listener:r,rawEmitter:i}=n,a=q.get(t),o=a&&a.options;return o&&(o.persistent<e.persistent||o.interval>e.interval)&&(yt(t),a=void 0),a?(C(a,R,r),C(a,S,i)):(a={listeners:r,rawEmitters:i,options:e,watcher:le(t,e,(c,l)=>{G(a.rawEmitters,f=>{f(T.CHANGE,t,{curr:c,prev:l})});let d=c.mtimeMs;(c.size!==l.size||d>l.mtimeMs||d===0)&&G(a.listeners,f=>f(s,c))})},q.set(t,a)),()=>{N(a,R,r),N(a,S,i),It(a.listeners)&&(q.delete(t),yt(t),a.options=a.watcher=void 0,Object.freeze(a))}},L=class{constructor(t){this.fsw=t,this._boundHandleError=e=>t._handleError(e)}_watchWithNodeFs(t,e){let n=this.fsw.options,r=y.dirname(t),i=y.basename(t);this.fsw._getWatchedDir(r).add(i);let o=y.resolve(t),c={persistent:n.persistent};e||(e=O);let l;if(n.usePolling){let d=n.interval!==n.binaryInterval;c.interval=d&&Pe(i)?n.binaryInterval:n.interval,l=Re(t,o,c,{listener:e,rawEmitter:this.fsw._emitRaw})}else l=xe(t,o,c,{listener:e,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(t,e,n){if(this.fsw.closed)return;let r=y.dirname(t),i=y.basename(t),a=this.fsw._getWatchedDir(r),o=e;if(a.has(i))return;let c=async(d,f)=>{if(this.fsw._throttle(ge,t,5)){if(!f||f.mtimeMs===0)try{let u=await _t(t);if(this.fsw.closed)return;let m=u.atimeMs,g=u.mtimeMs;if((!m||m<=g||g!==o.mtimeMs)&&this.fsw._emit(T.CHANGE,t,u),(ye||we||_e)&&o.ino!==u.ino){this.fsw._closeFile(d),o=u;let k=this._watchWithNodeFs(t,c);k&&this.fsw._addPathCloser(d,k)}else o=u}catch{this.fsw._remove(r,i)}else if(a.has(i)){let u=f.atimeMs,m=f.mtimeMs;(!u||u<=m||m!==o.mtimeMs)&&this.fsw._emit(T.CHANGE,t,f),o=f}}},l=this._watchWithNodeFs(t,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(T.ADD,t,0))return;this.fsw._emit(T.ADD,t,e)}return l}async _handleSymlink(t,e,n,r){if(this.fsw.closed)return;let i=t.fullPath,a=this.fsw._getWatchedDir(e);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let o;try{o=await K(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==o&&(this.fsw._symlinkPaths.set(i,o),this.fsw._emit(T.CHANGE,n,t.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,o),this.fsw._emit(T.ADD,n,t.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(t,e,n,r,i,a,o){if(t=y.join(t,""),o=this.fsw._throttle("readdir",t,1e3),!o)return;let c=this.fsw._getWatchedDir(n.path),l=new Set,d=this.fsw._readdirp(t,{fileFilter:f=>n.filterPath(f),directoryFilter:f=>n.filterDir(f)});if(d)return d.on(me,async f=>{if(this.fsw.closed){d=void 0;return}let u=f.path,m=y.join(t,u);if(l.add(u),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,t,m,u))){if(this.fsw.closed){d=void 0;return}(u===r||!r&&!c.has(u))&&(this.fsw._incrReadyCount(),m=y.join(i,y.relative(i,m)),this._addToNodeFs(m,e,n,a+1))}}).on(T.ERROR,this._boundHandleError),new Promise((f,u)=>{if(!d)return u();d.once($,()=>{if(this.fsw.closed){d=void 0;return}let m=o?o.clear():!1;f(void 0),c.getChildren().filter(g=>g!==t&&!l.has(g)).forEach(g=>{this.fsw._remove(t,g)}),d=void 0,m&&this._handleRead(t,!1,n,r,i,a,o)})})}async _handleDir(t,e,n,r,i,a,o){let c=this.fsw._getWatchedDir(y.dirname(t)),l=c.has(y.basename(t));!(n&&this.fsw.options.ignoreInitial)&&!i&&!l&&this.fsw._emit(T.ADD_DIR,t,e),c.add(y.basename(t)),this.fsw._getWatchedDir(t);let d,f,u=this.fsw.options.depth;if((u==null||r<=u)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(t,n,a,i,t,r,d),this.fsw.closed))return;f=this._watchWithNodeFs(t,(m,g)=>{g&&g.mtimeMs===0||this._handleRead(m,!1,a,i,t,r,d)})}return f}async _addToNodeFs(t,e,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(t);n&&(o.filterPath=c=>n.filterPath(c),o.filterDir=c=>n.filterDir(c));try{let c=await Ee[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,c))return a(),!1;let l=this.fsw.options.followSymlinks,d;if(c.isDirectory()){let f=y.resolve(t),u=l?await K(t):t;if(this.fsw.closed||(d=await this._handleDir(o.watchPath,c,e,r,i,o,u),this.fsw.closed))return;f!==u&&u!==void 0&&this.fsw._symlinkPaths.set(f,u)}else if(c.isSymbolicLink()){let f=l?await K(t):t;if(this.fsw.closed)return;let u=y.dirname(o.watchPath);if(this.fsw._getWatchedDir(u).add(o.watchPath),this.fsw._emit(T.ADD,o.watchPath,c),d=await this._handleDir(u,c,e,r,t,o,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(y.resolve(t),f)}else d=this._handleFile(o.watchPath,c,e);return a(),d&&this.fsw._addPathCloser(t,d),!1}catch(c){if(this.fsw._handleError(c))return a(),t}}};var X="/",De="//",bt=".",Fe="..",ve="string",Ae=/\\/g,Tt=/\/\//,Ue=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,We=/^\.[/\\]/;function B(s){return Array.isArray(s)?s:[s]}var Q=s=>typeof s=="object"&&s!==null&&!(s instanceof RegExp);function Le(s){return typeof s=="function"?s:typeof s=="string"?t=>s===t:s instanceof RegExp?t=>s.test(t):typeof s=="object"&&s!==null?t=>{if(s.path===t)return!0;if(s.recursive){let e=p.relative(s.path,t);return e?!e.startsWith("..")&&!p.isAbsolute(e):!1}return!1}:()=>!1}function Oe(s){if(typeof s!="string")throw new Error("string expected");s=p.normalize(s),s=s.replace(/\\/g,"/");let t=!1;s.startsWith("//")&&(t=!0);let e=/\/\//;for(;s.match(e);)s=s.replace(e,"/");return t&&(s="/"+s),s}function Pt(s,t,e){let n=Oe(t);for(let r=0;r<s.length;r++){let i=s[r];if(i(n,e))return!0}return!1}function Me(s,t){if(s==null)throw new TypeError("anymatch: specify first argument");let n=B(s).map(r=>Le(r));return t==null?(r,i)=>Pt(n,r,i):Pt(n,t)}var kt=s=>{let t=B(s).flat();if(!t.every(e=>typeof e===ve))throw new TypeError(`Non-string provided as watch path: ${t}`);return t.map(St)},xt=s=>{let t=s.replace(Ae,X),e=!1;for(t.startsWith(De)&&(e=!0);t.match(Tt);)t=t.replace(Tt,X);return e&&(t=X+t),t},St=s=>xt(p.normalize(xt(s))),Rt=(s="")=>t=>typeof t=="string"?St(p.isAbsolute(t)?t:p.join(s,t)):t,Be=(s,t)=>p.isAbsolute(s)?s:p.join(t,s),He=Object.freeze(new Set),Z=class{constructor(t,e){this.path=t,this._removeWatcher=e,this.items=new Set}add(t){let{items:e}=this;e&&t!==bt&&t!==Fe&&e.add(t)}async remove(t){let{items:e}=this;if(!e||(e.delete(t),e.size>0))return;let n=this.path;try{await Ce(n)}catch{this._removeWatcher&&this._removeWatcher(p.dirname(n),p.basename(n))}}has(t){let{items:e}=this;if(e)return e.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=O,this.items=He,Object.freeze(this)}},je="stat",Ye="lstat",J=class{constructor(t,e,n){this.fsw=n;let r=t;this.path=t=t.replace(We,""),this.watchPath=r,this.fullWatchPath=p.resolve(r),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=e,this.statMethod=e?je:Ye}entryPath(t){return p.join(this.watchPath,p.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:e}=t;if(e&&e.isSymbolicLink())return this.filterDir(t);let n=this.entryPath(t);return this.fsw._isntIgnored(n,e)&&this.fsw._hasReadPermissions(e)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}},tt=class extends Ne{constructor(t={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let e=t.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...t,ignored:t.ignored?B(t.ignored):B([]),awaitWriteFinish:e===!0?n:typeof e=="object"?{...n,...e}:!1};Et&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let c=i.toLowerCase();c==="false"||c==="0"?r.usePolling=!1:c==="true"||c==="1"?r.usePolling=!0:r.usePolling=!!c}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=O,this._readyEmitted=!0,process.nextTick(()=>this.emit(_.READY)))},this._emitRaw=(...c)=>this.emit(_.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new L(this),Object.freeze(r)}_addIgnoredPath(t){if(Q(t)){for(let e of this._ignoredPaths)if(Q(e)&&e.path===t.path&&e.recursive===t.recursive)return}this._ignoredPaths.add(t)}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),typeof t=="string")for(let e of this._ignoredPaths)Q(e)&&e.path===t&&this._ignoredPaths.delete(e)}add(t,e,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=kt(t);return r&&(i=i.map(a=>Be(a,r))),i.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async a=>{let o=await this._nodeFsHandler._addToNodeFs(a,!n,void 0,0,e);return o&&this._emitReady(),o})).then(a=>{this.closed||a.forEach(o=>{o&&this.add(p.dirname(o),p.basename(e||o))})}),this}unwatch(t){if(this.closed)return this;let e=kt(t),{cwd:n}=this.options;return e.forEach(r=>{!p.isAbsolute(r)&&!this._closers.has(r)&&(n&&(r=p.join(n,r)),r=p.resolve(r)),this._closePath(r),this._addIgnoredPath(r),this._watched.has(r)&&this._addIgnoredPath({path:r,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let t=[];return this._closers.forEach(e=>e.forEach(n=>{let r=n();r instanceof Promise&&t.push(r)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((e,n)=>{let i=(this.options.cwd?p.relative(this.options.cwd,n):n)||bt;t[i]=e.getChildren().sort()}),t}emitWithAll(t,e){this.emit(t,...e),t!==_.ERROR&&this.emit(_.ALL,t,...e)}async _emit(t,e,n){if(this.closed)return;let r=this.options;V&&(e=p.normalize(e)),r.cwd&&(e=p.relative(r.cwd,e));let i=[e];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(e)))return o.lastChange=new Date,this;if(r.atomic){if(t===_.UNLINK)return this._pendingUnlinks.set(e,[t,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((c,l)=>{this.emit(...c),this.emit(_.ALL,...c),this._pendingUnlinks.delete(l)})},typeof r.atomic=="number"?r.atomic:100),this;t===_.ADD&&this._pendingUnlinks.has(e)&&(t=_.CHANGE,this._pendingUnlinks.delete(e))}if(a&&(t===_.ADD||t===_.CHANGE)&&this._readyEmitted){let c=(l,d)=>{l?(t=_.ERROR,i[0]=l,this.emitWithAll(t,i)):d&&(i.length>1?i[1]=d:i.push(d),this.emitWithAll(t,i))};return this._awaitWriteFinish(e,a.stabilityThreshold,t,c),this}if(t===_.CHANGE&&!this._throttle(_.CHANGE,e,50))return this;if(r.alwaysStat&&n===void 0&&(t===_.ADD||t===_.ADD_DIR||t===_.CHANGE)){let c=r.cwd?p.join(r.cwd,e):e,l;try{l=await Se(c)}catch{}if(!l||this.closed)return;i.push(l)}return this.emitWithAll(t,i),this}_handleError(t){let e=t&&t.code;return t&&e!=="ENOENT"&&e!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||e!=="EPERM"&&e!=="EACCES")&&this.emit(_.ERROR,t),t||this.closed}_throttle(t,e,n){this._throttled.has(t)||this._throttled.set(t,new Map);let r=this._throttled.get(t);if(!r)throw new Error("invalid throttle");let i=r.get(e);if(i)return i.count++,!1;let a,o=()=>{let l=r.get(e),d=l?l.count:0;return r.delete(e),clearTimeout(a),l&&clearTimeout(l.timeoutObject),d};a=setTimeout(o,n);let c={timeoutObject:a,clear:o,count:0};return r.set(e,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,e,n,r){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let a=i.pollInterval,o,c=t;this.options.cwd&&!p.isAbsolute(t)&&(c=p.join(this.options.cwd,t));let l=new Date,d=this._pendingWrites;function f(u){be(c,(m,g)=>{if(m||!d.has(t)){m&&m.code!=="ENOENT"&&r(m);return}let k=Number(new Date);u&&g.size!==u.size&&(d.get(t).lastChange=k);let Qt=d.get(t);k-Qt.lastChange>=e?(d.delete(t),r(void 0,g)):o=setTimeout(f,a,g)})}d.has(t)||(d.set(t,{lastChange:l,cancelWait:()=>(d.delete(t),clearTimeout(o),n)}),o=setTimeout(f,a))}_isIgnored(t,e){if(this.options.atomic&&Ue.test(t))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=(this.options.ignored||[]).map(Rt(n)),o=[...[...this._ignoredPaths].map(Rt(n)),...i];this._userIgnored=Me(o,void 0)}return this._userIgnored(t,e)}_isntIgnored(t,e){return!this._isIgnored(t,e)}_getWatchHelpers(t){return new J(t,this.options.followSymlinks,this)}_getWatchedDir(t){let e=p.resolve(t);return this._watched.has(e)||this._watched.set(e,new Z(e,this._boundRemove)),this._watched.get(e)}_hasReadPermissions(t){return this.options.ignorePermissionErrors?!0:!!(Number(t.mode)&256)}_remove(t,e,n){let r=p.join(t,e),i=p.resolve(r);if(n=n??(this._watched.has(r)||this._watched.has(i)),!this._throttle("remove",r,100))return;!n&&this._watched.size===1&&this.add(t,e,!0),this._getWatchedDir(r).getChildren().forEach(u=>this._remove(r,u));let c=this._getWatchedDir(t),l=c.has(e);c.remove(e),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let d=r;if(this.options.cwd&&(d=p.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(d)&&this._pendingWrites.get(d).cancelWait()===_.ADD)return;this._watched.delete(r),this._watched.delete(i);let f=n?_.UNLINK_DIR:_.UNLINK;l&&!this._isIgnored(r)&&this._emit(f,r),this._closePath(r)}_closePath(t){this._closeFile(t);let e=p.dirname(t);this._getWatchedDir(e).remove(p.basename(t))}_closeFile(t){let e=this._closers.get(t);e&&(e.forEach(n=>n()),this._closers.delete(t))}_addPathCloser(t,e){if(!e)return;let n=this._closers.get(t);n||(n=[],this._closers.set(t,n)),n.push(e)}_readdirp(t,e){if(this.closed)return;let n={type:_.ALL,alwaysStat:!0,lstat:!0,...e,depth:0},r=mt(t,n);return this._streams.add(r),r.once(gt,()=>{r=void 0}),r.once($,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};function Ct(s,t={}){let e=new tt(t);return e.add(s),e}import{build as Ke}from"esbuild";import{jwtDecode as qe}from"jwt-decode";import{fork as Ge}from"node:child_process";import{existsSync as Nt,promises as $e}from"node:fs";import{basename as st,dirname as it,join as nt,relative as Dt}from"node:path";import{Issuer as Ve,custom as Xe}from"openid-client";import{Logger as Qe}from"@5minds/processcube_engine_sdk";import{EngineClient as ze}from"@5minds/processcube_engine_client";var et=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",h=new ze(et);var Ze={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},Je=.85,H=["external_task.ts","external_task.js"],ot=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,I=new Qe("processcube_app_sdk:external_task_adapter"),x={},rt={},D,Ft=6,ts=3e5,es=3e4;async function vt(s){if(s&&!Nt(s))throw new Error(`Invalid customExternalTasksDirPath. The given path '${s}' does not exist`);Xe.setHttpOptionsDefaults({timeout:1e5});let t=await Ut();D=await Wt(t),await ns(t);let e=is(s);Ct(e).on("add",async n=>{if(H.includes(st(n)))return at(n,e)}).on("change",async n=>{if(H.includes(st(n)))return ss(n,e)}).on("unlink",async n=>{H.includes(st(n))&&At(n)}).on("error",n=>I.error(`Watcher error: ${n}`))}async function at(s,t){let e=it(s);if((await $e.readdir(e)).filter(d=>H.includes(d)).length>1){I.error(`Multiple external task files found in directory ${e}. Stopping all external task workers for this directory.`),x[e]&&At(s);return}let i=await Lt(s),a=Dt(t,e),o=Ot(a),c=nt(__dirname,"lib/ExternalTaskWorkerProcess.cjs"),l=Ge(c,{env:{...process.env,PROCESSCUBE_ENGINE_URL:et}});x[e]=l,l.once("disconnect",()=>{delete x[e]}),l.on("error",d=>{I.error(`External Task Worker process error for ${o}`,{error:d,topic:o,workerDirectory:e})}),l.on("exit",(d,f)=>{if(I.info(`External Task Worker process exited for ${o}`,{code:d,signal:f,topic:o,workerDirectory:e}),delete x[e],d===3||d===4)if(os(e)){let u=rt[e]?.count??1,m=Math.min(1e3*Math.pow(2,u-1),es);I.info(`Scheduling restart for ${o} in ${m}ms (attempt ${u}/${Ft})`,{delay:m,restartCount:u,exitCode:d,topic:o,workerDirectory:e}),setTimeout(()=>{at(s,t).catch(g=>{I.error(`Failed to restart External Task Worker process for ${o}`,{error:g,topic:o,workerDirectory:e})})},m)}else I.error(`External Task Worker process for ${o} reached maximum restart attempts`,{exitCode:d,topic:o,workerDirectory:e})}),l.send({action:"create",payload:{topic:o,identity:D,moduleString:i,workerPath:s}})}async function ss(s,t){let e=it(s),n=x[e];if(!n)return at(s,t);let r=await Lt(s),i=Dt(t,e),a=Ot(i);n.send({action:"restart",payload:{topic:a,identity:D,moduleString:r,workerPath:s}})}function At(s){let t=it(s),e=x[t];e&&e.kill()}async function Ut(){if(!ot)return null;if(!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID||!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET){let n=new Error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing. For help, please refer to our documentation on environment variables at: https://processcube.io/docs/app-sdk/samples/nextjs/external-task-adapter-with-nextjs#authority");throw I.error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing",{err:n}),n}let s=await Ve.discover(process.env.PROCESSCUBE_AUTHORITY_URL);return await new s.Client({client_id:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID,client_secret:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET}).grant({grant_type:"client_credentials",scope:"engine_etw"})}function Wt(s){if(!ot||s===null)return Ze;let t=s.access_token,e=qe(t);return{token:s.access_token,userId:e.sub}}async function ns(s){let t=5;if(!ot||s===null)return;let n=await rs(s)*Je*1e3,r=async()=>{try{let i=await Ut();D=Wt(i);for(let a of Object.values(x))a.send({action:"updateIdentity",payload:{identity:D}});t=5,setTimeout(r,n)}catch(i){if(t===0){I.error("Could not refresh identity for external task worker processes. Stopping all external task workers.",{error:i});for(let o of Object.values(x))o.kill();return}I.error("Could not refresh identity for external task worker processes.",{error:i,retryCount:t}),t--;let a=2*1e3;setTimeout(r,a)}};setTimeout(r,n)}async function Lt(s){let t=await Ke({entryPoints:[s],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(t.errors.length>0)throw I.error(`Could not transpile file at '${s}'`,{errors:t.errors}),new Error(`Could not transpile file at '${s}'`);return t.warnings.length>0&&I.warn(`Transpiled file at '${s}' with warnings`,{warnings:t.warnings}),t.outputFiles[0].text}async function rs(s){let t=s.expires_in;if(!t&&s.expires_at&&(t=Math.floor(s.expires_at-Date.now()/1e3)),t===void 0)throw new Error("Could not determine the time until the access token for external task workers expires");return t}function Ot(s){return s.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function is(s){let t,e=[s,nt(process.cwd(),"app"),nt(process.cwd(),"src","app")];for(let n of e)if(n&&Nt(n)){t=n;break}if(!t)throw new Error("Could not find external tasks directory");return t}function os(s){let t=Date.now(),e=rt[s];return!e||t-e.timestamp>ts?(rt[s]={count:1,timestamp:t},!0):e.count>=Ft?!1:(e.count++,!0)}function Gs(){return h}import{getToken as Mt}from"next-auth/jwt";import{ResponseCookies as as}from"next/dist/compiled/@edge-runtime/cookies/index.js";import{cookies as j,headers as Bt}from"next/headers";async function w(){let s=await Mt({req:{cookies:await j(),headers:await Bt()}});if(s?.expiresAt&&Date.now()>=s.expiresAt*1e3){let e=await fetch(`${process.env.NEXTAUTH_URL}/api/auth/session`,{method:"GET",headers:{"Content-Type":"application/json",cookie:(await j()).toString()}}),n=new as(e.headers);if(n.getAll().length){let r=!1;try{for(let i of n.getAll())(await j()).set(i.name,i.value,{...i})}catch{r=!0}if(s=await Mt({req:{cookies:r?n:await j(),headers:await Bt()}}),s?.error)throw s.error}}if(!s?.accessToken||!s?.sub)throw new Error("AccessToken or Sub could not be determined!");return{token:s?.accessToken,userId:s?.sub}}import{DataModels as F}from"@5minds/processcube_engine_client";async function v(){try{return w()}catch{return}}async function Ht(s){let t=await v();return(await h.processInstances.query({processInstanceId:s},{identity:t,includeXml:!0})).processInstances[0]}async function jt(s,t={sortSettings:{sortBy:F.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await h.flowNodeInstances.query({processInstanceId:s},{...t,identity:t.identity??await v()})).flowNodeInstances}async function Yt(s){let t=await v();return(await h.flowNodeInstances.query({triggeredByFlowNodeInstance:s},{identity:t})).flowNodeInstances}async function zt(s,t,e){let n=await v();await h.processInstances.retryProcessInstance(s,{flowNodeInstanceId:t,newStartToken:e,identity:n})}async function Kt(s){let t=await v();await h.processInstances.terminateProcessInstance(s,t)}async function sn(s={options:{identity:!0}}){switch(s.options.identity){case!0:s.options.identity=await w();break;case!1:s.options.identity=void 0;break;case void 0:s.options.identity=await w();break}return await h.processInstances.query({...s?.query,state:F.ProcessInstances.ProcessInstanceState.running},s?.options)}async function nn(s={},t=!0){let{processInstanceId:e}=s,n=typeof t=="boolean"?t==!0?await w():void 0:t;return new Promise(async(r,i)=>{let a=[],o=async c=>{if(e!==void 0&&c.processInstanceId!==e)return;let d=await h.processInstances.query({processInstanceId:c.processInstanceId},{identity:n});for(let f of a)h.notification.removeSubscription(f,n);return d.totalCount===0?i(new Error(`Process with instance ID "${c.processInstanceId}" does not exist.`)):r(d.processInstances[0])};if(a.push(await h.notification.onProcessEnded(o,{identity:n})),a.push(await h.notification.onProcessError(o,{identity:n})),a.push(await h.notification.onProcessTerminated(o,{identity:n})),e){let c=await h.processInstances.query({processInstanceId:e,state:[F.ProcessInstances.ProcessInstanceState.finished,F.ProcessInstances.ProcessInstanceState.terminated,F.ProcessInstances.ProcessInstanceState.error]},{identity:n});if(c.totalCount>0){for(let l of a)h.notification.removeSubscription(l,n);r(c.processInstances[0])}}})}import{DataModels as P}from"@5minds/processcube_engine_client";import{mapUserTask as qt,mapUserTaskList as b}from"../common/index.mjs";async function un(s={},t=!0){let{correlationId:e,processInstanceId:n,flowNodeId:r}=s,i=typeof t=="boolean"?t==!0?await w():void 0:t;return new Promise(async(a,o)=>{let c=await h.userTasks.onUserTaskWaiting(async d=>{let f=e!==void 0&&d.correlationId!==e,u=d.flowNodeInstanceId===void 0,m=n!==void 0&&d.processInstanceId!==n,g=r!==void 0&&d.flowNodeId!==r;if(f||u||m||g)return;let k=await ds(d.flowNodeInstanceId,{identity:i});return h.notification.removeSubscription(c,i),k===null?o(new Error(`UserTask with instance ID "${d.flowNodeInstanceId}" does not exist.`)):a(k)},{identity:i}),l=await cs({correlationId:e,processInstanceId:n,flowNodeId:r,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});l.userTasks.length>0&&(h.notification.removeSubscription(c,i),a(l.userTasks[0]))})}async function hn(s,t={},e={},n=!0){let r=typeof n=="boolean"?n==!0?await w():void 0:n;await h.userTasks.finishUserTask(s,e,r);let i={state:P.FlowNodeInstances.FlowNodeInstanceState.suspended,...t},a=await h.userTasks.query(i,{identity:r});return qt(a.userTasks[0])}async function cs(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query(s,t);return b(e)}async function pn(s={identity:!0}){switch(s?.identity){case!0:s.identity=await w();break;case!1:s.identity=void 0;break;case void 0:s.identity=await w();break}let t=await h.userTasks.query({state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},s);return b(t)}async function mn(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query({processInstanceId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return b(e)}async function yn(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query({flowNodeId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return b(e)}async function ds(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query({flowNodeInstanceId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{...t,limit:1});return e.userTasks.length===0?null:qt(e.userTasks[0])}async function wn(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query({correlationId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return b(e)}async function _n(s,t){let e=s||await w(),n=await h.userTasks.query({state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:e,...t}),r=n.userTasks.filter(i=>i.actualOwnerId===e.userId);return n.userTasks=r,b(n)}async function gn(s,t,e){await h.userTasks.reserveUserTaskInstance(s,t,e||s.userId)}async function En(s,t){await h.userTasks.cancelUserTaskInstanceReservation(s,t)}async function In(s,t){let e=s||await w(),n=await h.userTasks.query({state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:e,...t}),r=n.userTasks.filter(i=>i.assignedUserIds?.includes(e.userId));return n.userTasks=r,b(n)}import{PHASE_DEVELOPMENT_SERVER as ls,PHASE_PRODUCTION_BUILD as fs,PHASE_PRODUCTION_SERVER as us}from"next/dist/shared/lib/constants";var Gt=!1,ct=!1;function xn(s={}){let{applicationSdk:t,...e}=s;return async(n,r)=>{ct=ct||n===fs;let i=n===ls||n===us;return t?.useExternalTasks&&i&&!Gt&&!ct&&(Gt=!0,await vt(t?.customExternalTasksDirPath)),{...e,experimental:{...e.experimental,serverComponentsExternalPackages:[...e.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}import{redirect as hs}from"next/navigation";function Cn(s){hs(s)}async function Fn(...s){return await h.processModels.startProcessInstance(...s)}async function $t(...s){await h.manualTasks.finishManualTask(...s)}async function Vt(...s){await h.userTasks.finishUserTask(...s)}async function Xt(...s){await h.untypedTasks.finishTask(...s)}import{DataModels as ps}from"@5minds/processcube_engine_client";async function ms(){try{return w()}catch{return}}var zn=async(s,t)=>{let e=await ms();t==="bpmn:UserTask"?await Vt(s,{},e):t==="bpmn:ManualTask"?await $t(s,e):t==="bpmn:Task"?await Xt(s,e):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${t}`)},Kn=async s=>{await Kt(s)},qn=async(s,t,e)=>{await zt(s,t,e)},Gn=async s=>Ht(s),$n=async s=>jt(s,{sortSettings:{sortBy:ps.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),Vn=async s=>Yt(s);export{En as cancelReservedUserTask,$t as finishManualTask,zn as finishTask,Xt as finishUntypedTask,Vt as finishUserTask,hn as finishUserTaskAndGetNext,sn as getActiveProcessInstances,In as getAssignedUserTasksByIdentity,Gs as getEngineClient,$n as getFlowNodeInstances,jt as getFlowNodeInstancesByProcessInstanceId,Yt as getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,w as getIdentity,Gn as getProcessInstance,Ht as getProcessInstanceById,_n as getReservedUserTasksByIdentity,Vn as getTriggeredFlowNodeInstances,cs as getUserTasks,ds as getWaitingUserTaskByFlowNodeInstanceId,pn as getWaitingUserTasks,wn as getWaitingUserTasksByCorrelationId,yn as getWaitingUserTasksByFlowNodeId,mn as getWaitingUserTasksByProcessInstanceId,Cn as navigateToUrl,gn as reserveUserTask,qn as retryProcess,zt as retryProcessInstance,Fn as startProcess,Kn as terminateProcess,Kt as terminateProcessInstance,nn as waitForProcessEnd,un as waitForUserTask,xn as withApplicationSdk};
|
|
1
|
+
import"only-server";import"../common/index.mjs";import{stat as Fe}from"fs";import{stat as Ae,readdir as ve}from"fs/promises";import{EventEmitter as Le}from"events";import*as p from"path";import{stat as ne,lstat as ut,readdir as re,realpath as ie}from"node:fs/promises";import{Readable as oe}from"node:stream";import{resolve as ht,relative as ae,join as ce,sep as de}from"node:path";var I={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},z={root:".",fileFilter:s=>!0,directoryFilter:s=>!0,type:I.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(z);var wt="READDIRP_RECURSIVE_ERROR",le=new Set(["ENOENT","EPERM","EACCES","ELOOP",wt]),pt=[I.DIR_TYPE,I.EVERYTHING_TYPE,I.FILE_DIR_TYPE,I.FILE_TYPE],fe=new Set([I.DIR_TYPE,I.EVERYTHING_TYPE,I.FILE_DIR_TYPE]),ue=new Set([I.EVERYTHING_TYPE,I.FILE_DIR_TYPE,I.FILE_TYPE]),he=s=>le.has(s.code),pe=process.platform==="win32",mt=s=>!0,yt=s=>{if(s===void 0)return mt;if(typeof s=="function")return s;if(typeof s=="string"){let t=s.trim();return e=>e.basename===t}if(Array.isArray(s)){let t=s.map(e=>e.trim());return e=>t.some(n=>e.basename===n)}return mt},K=class extends oe{constructor(t={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:t.highWaterMark});let e={...z,...t},{root:n,type:r}=e;this._fileFilter=yt(e.fileFilter),this._directoryFilter=yt(e.directoryFilter);let i=e.lstat?ut:ne;pe?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=e.depth??z.depth,this._wantsDir=r?fe.has(r):!1,this._wantsFile=r?ue.has(r):!1,this._wantsEverything=r===I.EVERYTHING_TYPE,this._root=ht(n),this._isDirent=!e.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(t){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&t>0;){let e=this.parent,n=e&&e.files;if(n&&n.length>0){let{path:r,depth:i}=e,a=n.splice(0,t).map(c=>this._formatEntry(c,r)),o=await Promise.all(a);for(let c of o){if(!c)continue;if(this.destroyed)return;let l=await this._getEntryType(c);l==="directory"&&this._directoryFilter(c)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(c.fullPath,i+1)),this._wantsDir&&(this.push(c),t--)):(l==="file"||this._includeAsFile(c))&&this._fileFilter(c)&&this._wantsFile&&(this.push(c),t--)}}else{let r=this.parents.pop();if(!r){this.push(null);break}if(this.parent=await r,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(t,e){let n;try{n=await re(t,this._rdOptions)}catch(r){this._onError(r)}return{files:n,depth:e,path:t}}async _formatEntry(t,e){let n,r=this._isDirent?t.name:t;try{let i=ht(ce(e,r));n={path:ae(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?t:await this._stat(i)}catch(i){this._onError(i);return}return n}_onError(t){he(t)&&!this.destroyed?this.emit("warn",t):this.destroy(t)}async _getEntryType(t){if(!t&&this._statsProp in t)return"";let e=t[this._statsProp];if(e.isFile())return"file";if(e.isDirectory())return"directory";if(e&&e.isSymbolicLink()){let n=t.fullPath;try{let r=await ie(n),i=await ut(r);if(i.isFile())return"file";if(i.isDirectory()){let a=r.length;if(n.startsWith(r)&&n.substr(a,1)===de){let o=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return o.code=wt,this._onError(o)}return"directory"}}catch(r){return this._onError(r),""}}}_includeAsFile(t){let e=t&&t[this._statsProp];return e&&this._wantsEverything&&!e.isDirectory()}};function _t(s,t={}){let e=t.entryType||t.type;if(e==="both"&&(e=I.FILE_DIR_TYPE),e&&(t.type=e),s){if(typeof s!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(e&&!pt.includes(e))throw new Error(`readdirp: Invalid type passed. Use one of ${pt.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return t.root=s,new K(t)}import{watchFile as me,unwatchFile as gt,watch as ye}from"fs";import{open as we,stat as It,lstat as _e,realpath as $}from"fs/promises";import*as y from"path";import{type as ge}from"os";var Ee="data",X="end",Tt="close",M=()=>{};var B=process.platform,V=B==="win32",Ie=B==="darwin",Te=B==="linux",Pe=B==="freebsd",Pt=ge()==="OS400",_={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},T=_,ke="watch",Re={lstat:_e,stat:It},R="listeners",L="errHandlers",S="rawEmitters",xe=[R,L,S],be=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Se=s=>be.has(y.extname(s).slice(1).toLowerCase()),G=(s,t)=>{s instanceof Set?s.forEach(t):t(s)},N=(s,t,e)=>{let n=s[t];n instanceof Set||(s[t]=n=new Set([n])),n.add(e)},Ce=s=>t=>{let e=s[t];e instanceof Set?e.clear():delete s[t]},D=(s,t,e)=>{let n=s[t];n instanceof Set?n.delete(e):n===e&&delete s[t]},kt=s=>s instanceof Set?s.size===0:!s,O=new Map;function Et(s,t,e,n,r){let i=(a,o)=>{e(s),r(a,o,{watchedPath:s}),o&&s!==o&&U(y.resolve(s,o),R,y.join(s,o))};try{return ye(s,{persistent:t.persistent},i)}catch(a){n(a);return}}var U=(s,t,e,n,r)=>{let i=O.get(s);i&&G(i[t],a=>{a(e,n,r)})},Ne=(s,t,e,n)=>{let{listener:r,errHandler:i,rawEmitter:a}=n,o=O.get(t),c;if(!e.persistent)return c=Et(s,e,r,i,a),c?c.close.bind(c):void 0;if(o)N(o,R,r),N(o,L,i),N(o,S,a);else{if(c=Et(s,e,U.bind(null,t,R),i,U.bind(null,t,S)),!c)return;c.on(T.ERROR,async l=>{let d=U.bind(null,t,L);if(o&&(o.watcherUnusable=!0),V&&l.code==="EPERM")try{await(await we(s,"r")).close(),d(l)}catch{}else d(l)}),o={listeners:r,errHandlers:i,rawEmitters:a,watcher:c},O.set(t,o)}return()=>{D(o,R,r),D(o,L,i),D(o,S,a),kt(o.listeners)&&(o.watcher.close(),O.delete(t),xe.forEach(Ce(o)),o.watcher=void 0,Object.freeze(o))}},q=new Map,De=(s,t,e,n)=>{let{listener:r,rawEmitter:i}=n,a=q.get(t),o=a&&a.options;return o&&(o.persistent<e.persistent||o.interval>e.interval)&&(gt(t),a=void 0),a?(N(a,R,r),N(a,S,i)):(a={listeners:r,rawEmitters:i,options:e,watcher:me(t,e,(c,l)=>{G(a.rawEmitters,f=>{f(T.CHANGE,t,{curr:c,prev:l})});let d=c.mtimeMs;(c.size!==l.size||d>l.mtimeMs||d===0)&&G(a.listeners,f=>f(s,c))})},q.set(t,a)),()=>{D(a,R,r),D(a,S,i),kt(a.listeners)&&(q.delete(t),gt(t),a.options=a.watcher=void 0,Object.freeze(a))}},W=class{constructor(t){this.fsw=t,this._boundHandleError=e=>t._handleError(e)}_watchWithNodeFs(t,e){let n=this.fsw.options,r=y.dirname(t),i=y.basename(t);this.fsw._getWatchedDir(r).add(i);let o=y.resolve(t),c={persistent:n.persistent};e||(e=M);let l;if(n.usePolling){let d=n.interval!==n.binaryInterval;c.interval=d&&Se(i)?n.binaryInterval:n.interval,l=De(t,o,c,{listener:e,rawEmitter:this.fsw._emitRaw})}else l=Ne(t,o,c,{listener:e,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(t,e,n){if(this.fsw.closed)return;let r=y.dirname(t),i=y.basename(t),a=this.fsw._getWatchedDir(r),o=e;if(a.has(i))return;let c=async(d,f)=>{if(this.fsw._throttle(ke,t,5)){if(!f||f.mtimeMs===0)try{let u=await It(t);if(this.fsw.closed)return;let m=u.atimeMs,g=u.mtimeMs;if((!m||m<=g||g!==o.mtimeMs)&&this.fsw._emit(T.CHANGE,t,u),(Ie||Te||Pe)&&o.ino!==u.ino){this.fsw._closeFile(d),o=u;let k=this._watchWithNodeFs(t,c);k&&this.fsw._addPathCloser(d,k)}else o=u}catch{this.fsw._remove(r,i)}else if(a.has(i)){let u=f.atimeMs,m=f.mtimeMs;(!u||u<=m||m!==o.mtimeMs)&&this.fsw._emit(T.CHANGE,t,f),o=f}}},l=this._watchWithNodeFs(t,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(T.ADD,t,0))return;this.fsw._emit(T.ADD,t,e)}return l}async _handleSymlink(t,e,n,r){if(this.fsw.closed)return;let i=t.fullPath,a=this.fsw._getWatchedDir(e);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let o;try{o=await $(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==o&&(this.fsw._symlinkPaths.set(i,o),this.fsw._emit(T.CHANGE,n,t.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,o),this.fsw._emit(T.ADD,n,t.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(t,e,n,r,i,a,o){if(t=y.join(t,""),o=this.fsw._throttle("readdir",t,1e3),!o)return;let c=this.fsw._getWatchedDir(n.path),l=new Set,d=this.fsw._readdirp(t,{fileFilter:f=>n.filterPath(f),directoryFilter:f=>n.filterDir(f)});if(d)return d.on(Ee,async f=>{if(this.fsw.closed){d=void 0;return}let u=f.path,m=y.join(t,u);if(l.add(u),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,t,m,u))){if(this.fsw.closed){d=void 0;return}(u===r||!r&&!c.has(u))&&(this.fsw._incrReadyCount(),m=y.join(i,y.relative(i,m)),this._addToNodeFs(m,e,n,a+1))}}).on(T.ERROR,this._boundHandleError),new Promise((f,u)=>{if(!d)return u();d.once(X,()=>{if(this.fsw.closed){d=void 0;return}let m=o?o.clear():!1;f(void 0),c.getChildren().filter(g=>g!==t&&!l.has(g)).forEach(g=>{this.fsw._remove(t,g)}),d=void 0,m&&this._handleRead(t,!1,n,r,i,a,o)})})}async _handleDir(t,e,n,r,i,a,o){let c=this.fsw._getWatchedDir(y.dirname(t)),l=c.has(y.basename(t));!(n&&this.fsw.options.ignoreInitial)&&!i&&!l&&this.fsw._emit(T.ADD_DIR,t,e),c.add(y.basename(t)),this.fsw._getWatchedDir(t);let d,f,u=this.fsw.options.depth;if((u==null||r<=u)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(t,n,a,i,t,r,d),this.fsw.closed))return;f=this._watchWithNodeFs(t,(m,g)=>{g&&g.mtimeMs===0||this._handleRead(m,!1,a,i,t,r,d)})}return f}async _addToNodeFs(t,e,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(t);n&&(o.filterPath=c=>n.filterPath(c),o.filterDir=c=>n.filterDir(c));try{let c=await Re[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,c))return a(),!1;let l=this.fsw.options.followSymlinks,d;if(c.isDirectory()){let f=y.resolve(t),u=l?await $(t):t;if(this.fsw.closed||(d=await this._handleDir(o.watchPath,c,e,r,i,o,u),this.fsw.closed))return;f!==u&&u!==void 0&&this.fsw._symlinkPaths.set(f,u)}else if(c.isSymbolicLink()){let f=l?await $(t):t;if(this.fsw.closed)return;let u=y.dirname(o.watchPath);if(this.fsw._getWatchedDir(u).add(o.watchPath),this.fsw._emit(T.ADD,o.watchPath,c),d=await this._handleDir(u,c,e,r,t,o,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(y.resolve(t),f)}else d=this._handleFile(o.watchPath,c,e);return a(),d&&this.fsw._addPathCloser(t,d),!1}catch(c){if(this.fsw._handleError(c))return a(),t}}};var Q="/",Oe="//",Nt=".",Ue="..",We="string",Me=/\\/g,Rt=/\/\//,Be=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,He=/^\.[/\\]/;function H(s){return Array.isArray(s)?s:[s]}var Z=s=>typeof s=="object"&&s!==null&&!(s instanceof RegExp);function je(s){return typeof s=="function"?s:typeof s=="string"?t=>s===t:s instanceof RegExp?t=>s.test(t):typeof s=="object"&&s!==null?t=>{if(s.path===t)return!0;if(s.recursive){let e=p.relative(s.path,t);return e?!e.startsWith("..")&&!p.isAbsolute(e):!1}return!1}:()=>!1}function Ye(s){if(typeof s!="string")throw new Error("string expected");s=p.normalize(s),s=s.replace(/\\/g,"/");let t=!1;s.startsWith("//")&&(t=!0);let e=/\/\//;for(;s.match(e);)s=s.replace(e,"/");return t&&(s="/"+s),s}function xt(s,t,e){let n=Ye(t);for(let r=0;r<s.length;r++){let i=s[r];if(i(n,e))return!0}return!1}function ze(s,t){if(s==null)throw new TypeError("anymatch: specify first argument");let n=H(s).map(r=>je(r));return t==null?(r,i)=>xt(n,r,i):xt(n,t)}var bt=s=>{let t=H(s).flat();if(!t.every(e=>typeof e===We))throw new TypeError(`Non-string provided as watch path: ${t}`);return t.map(Dt)},St=s=>{let t=s.replace(Me,Q),e=!1;for(t.startsWith(Oe)&&(e=!0);t.match(Rt);)t=t.replace(Rt,Q);return e&&(t=Q+t),t},Dt=s=>St(p.normalize(St(s))),Ct=(s="")=>t=>typeof t=="string"?Dt(p.isAbsolute(t)?t:p.join(s,t)):t,Ke=(s,t)=>p.isAbsolute(s)?s:p.join(t,s),$e=Object.freeze(new Set),J=class{constructor(t,e){this.path=t,this._removeWatcher=e,this.items=new Set}add(t){let{items:e}=this;e&&t!==Nt&&t!==Ue&&e.add(t)}async remove(t){let{items:e}=this;if(!e||(e.delete(t),e.size>0))return;let n=this.path;try{await ve(n)}catch{this._removeWatcher&&this._removeWatcher(p.dirname(n),p.basename(n))}}has(t){let{items:e}=this;if(e)return e.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=M,this.items=$e,Object.freeze(this)}},qe="stat",Ge="lstat",tt=class{constructor(t,e,n){this.fsw=n;let r=t;this.path=t=t.replace(He,""),this.watchPath=r,this.fullWatchPath=p.resolve(r),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=e,this.statMethod=e?qe:Ge}entryPath(t){return p.join(this.watchPath,p.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:e}=t;if(e&&e.isSymbolicLink())return this.filterDir(t);let n=this.entryPath(t);return this.fsw._isntIgnored(n,e)&&this.fsw._hasReadPermissions(e)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}},et=class extends Le{constructor(t={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let e=t.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...t,ignored:t.ignored?H(t.ignored):H([]),awaitWriteFinish:e===!0?n:typeof e=="object"?{...n,...e}:!1};Pt&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let c=i.toLowerCase();c==="false"||c==="0"?r.usePolling=!1:c==="true"||c==="1"?r.usePolling=!0:r.usePolling=!!c}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=M,this._readyEmitted=!0,process.nextTick(()=>this.emit(_.READY)))},this._emitRaw=(...c)=>this.emit(_.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new W(this),Object.freeze(r)}_addIgnoredPath(t){if(Z(t)){for(let e of this._ignoredPaths)if(Z(e)&&e.path===t.path&&e.recursive===t.recursive)return}this._ignoredPaths.add(t)}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),typeof t=="string")for(let e of this._ignoredPaths)Z(e)&&e.path===t&&this._ignoredPaths.delete(e)}add(t,e,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=bt(t);return r&&(i=i.map(a=>Ke(a,r))),i.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async a=>{let o=await this._nodeFsHandler._addToNodeFs(a,!n,void 0,0,e);return o&&this._emitReady(),o})).then(a=>{this.closed||a.forEach(o=>{o&&this.add(p.dirname(o),p.basename(e||o))})}),this}unwatch(t){if(this.closed)return this;let e=bt(t),{cwd:n}=this.options;return e.forEach(r=>{!p.isAbsolute(r)&&!this._closers.has(r)&&(n&&(r=p.join(n,r)),r=p.resolve(r)),this._closePath(r),this._addIgnoredPath(r),this._watched.has(r)&&this._addIgnoredPath({path:r,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let t=[];return this._closers.forEach(e=>e.forEach(n=>{let r=n();r instanceof Promise&&t.push(r)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((e,n)=>{let i=(this.options.cwd?p.relative(this.options.cwd,n):n)||Nt;t[i]=e.getChildren().sort()}),t}emitWithAll(t,e){this.emit(t,...e),t!==_.ERROR&&this.emit(_.ALL,t,...e)}async _emit(t,e,n){if(this.closed)return;let r=this.options;V&&(e=p.normalize(e)),r.cwd&&(e=p.relative(r.cwd,e));let i=[e];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(e)))return o.lastChange=new Date,this;if(r.atomic){if(t===_.UNLINK)return this._pendingUnlinks.set(e,[t,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((c,l)=>{this.emit(...c),this.emit(_.ALL,...c),this._pendingUnlinks.delete(l)})},typeof r.atomic=="number"?r.atomic:100),this;t===_.ADD&&this._pendingUnlinks.has(e)&&(t=_.CHANGE,this._pendingUnlinks.delete(e))}if(a&&(t===_.ADD||t===_.CHANGE)&&this._readyEmitted){let c=(l,d)=>{l?(t=_.ERROR,i[0]=l,this.emitWithAll(t,i)):d&&(i.length>1?i[1]=d:i.push(d),this.emitWithAll(t,i))};return this._awaitWriteFinish(e,a.stabilityThreshold,t,c),this}if(t===_.CHANGE&&!this._throttle(_.CHANGE,e,50))return this;if(r.alwaysStat&&n===void 0&&(t===_.ADD||t===_.ADD_DIR||t===_.CHANGE)){let c=r.cwd?p.join(r.cwd,e):e,l;try{l=await Ae(c)}catch{}if(!l||this.closed)return;i.push(l)}return this.emitWithAll(t,i),this}_handleError(t){let e=t&&t.code;return t&&e!=="ENOENT"&&e!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||e!=="EPERM"&&e!=="EACCES")&&this.emit(_.ERROR,t),t||this.closed}_throttle(t,e,n){this._throttled.has(t)||this._throttled.set(t,new Map);let r=this._throttled.get(t);if(!r)throw new Error("invalid throttle");let i=r.get(e);if(i)return i.count++,!1;let a,o=()=>{let l=r.get(e),d=l?l.count:0;return r.delete(e),clearTimeout(a),l&&clearTimeout(l.timeoutObject),d};a=setTimeout(o,n);let c={timeoutObject:a,clear:o,count:0};return r.set(e,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,e,n,r){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let a=i.pollInterval,o,c=t;this.options.cwd&&!p.isAbsolute(t)&&(c=p.join(this.options.cwd,t));let l=new Date,d=this._pendingWrites;function f(u){Fe(c,(m,g)=>{if(m||!d.has(t)){m&&m.code!=="ENOENT"&&r(m);return}let k=Number(new Date);u&&g.size!==u.size&&(d.get(t).lastChange=k);let se=d.get(t);k-se.lastChange>=e?(d.delete(t),r(void 0,g)):o=setTimeout(f,a,g)})}d.has(t)||(d.set(t,{lastChange:l,cancelWait:()=>(d.delete(t),clearTimeout(o),n)}),o=setTimeout(f,a))}_isIgnored(t,e){if(this.options.atomic&&Be.test(t))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=(this.options.ignored||[]).map(Ct(n)),o=[...[...this._ignoredPaths].map(Ct(n)),...i];this._userIgnored=ze(o,void 0)}return this._userIgnored(t,e)}_isntIgnored(t,e){return!this._isIgnored(t,e)}_getWatchHelpers(t){return new tt(t,this.options.followSymlinks,this)}_getWatchedDir(t){let e=p.resolve(t);return this._watched.has(e)||this._watched.set(e,new J(e,this._boundRemove)),this._watched.get(e)}_hasReadPermissions(t){return this.options.ignorePermissionErrors?!0:!!(Number(t.mode)&256)}_remove(t,e,n){let r=p.join(t,e),i=p.resolve(r);if(n=n??(this._watched.has(r)||this._watched.has(i)),!this._throttle("remove",r,100))return;!n&&this._watched.size===1&&this.add(t,e,!0),this._getWatchedDir(r).getChildren().forEach(u=>this._remove(r,u));let c=this._getWatchedDir(t),l=c.has(e);c.remove(e),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let d=r;if(this.options.cwd&&(d=p.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(d)&&this._pendingWrites.get(d).cancelWait()===_.ADD)return;this._watched.delete(r),this._watched.delete(i);let f=n?_.UNLINK_DIR:_.UNLINK;l&&!this._isIgnored(r)&&this._emit(f,r),this._closePath(r)}_closePath(t){this._closeFile(t);let e=p.dirname(t);this._getWatchedDir(e).remove(p.basename(t))}_closeFile(t){let e=this._closers.get(t);e&&(e.forEach(n=>n()),this._closers.delete(t))}_addPathCloser(t,e){if(!e)return;let n=this._closers.get(t);n||(n=[],this._closers.set(t,n)),n.push(e)}_readdirp(t,e){if(this.closed)return;let n={type:_.ALL,alwaysStat:!0,lstat:!0,...e,depth:0},r=_t(t,n);return this._streams.add(r),r.once(Tt,()=>{r=void 0}),r.once(X,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};function Ft(s,t={}){let e=new et(t);return e.add(s),e}import{build as Ve}from"esbuild";import{jwtDecode as Qe}from"jwt-decode";import{fork as Ze}from"node:child_process";import{existsSync as vt,promises as Je}from"node:fs";import{basename as nt,dirname as ct,join as it,relative as Lt}from"node:path";import{Issuer as ts,custom as es}from"openid-client";import{Logger as ss}from"@5minds/processcube_engine_sdk";import{EngineClient as Xe}from"@5minds/processcube_engine_client";var st=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",h=new Xe(st);var ns={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},rs=.85,j=["external_task.ts","external_task.js"],F=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,E=new ss("processcube_app_sdk:external_task_adapter"),x={},ot={},C,at=!1,Ot=6,is=3e5,os=3e4,rt=10,as=3e4,At=10,cs=6e4;async function Ut(s){if(s&&!vt(s))throw new Error(`Invalid customExternalTasksDirPath. The given path '${s}' does not exist`);es.setHttpOptionsDefaults({timeout:1e5});let t=await Bt();C=lt(t),await Ht(t);let e=fs(s);Ft(e).on("add",async n=>{if(j.includes(nt(n)))return dt(n,e)}).on("change",async n=>{if(j.includes(nt(n)))return ds(n,e)}).on("unlink",async n=>{j.includes(nt(n))&&Wt(n)}).on("error",n=>E.error(`Watcher error: ${n}`))}async function dt(s,t){let e=ct(s);if((await Je.readdir(e)).filter(d=>j.includes(d)).length>1){E.error(`Multiple external task files found in directory ${e}. Stopping all external task workers for this directory.`),x[e]&&Wt(s);return}let i=await jt(s),a=Lt(t,e),o=Yt(a),c=it(__dirname,"lib/ExternalTaskWorkerProcess.cjs"),l=Ze(c,{env:{...process.env,PROCESSCUBE_ENGINE_URL:st}});x[e]=l,l.once("disconnect",()=>{delete x[e]}),l.on("error",d=>{E.error(`External Task Worker process error for ${o}`,{error:d,topic:o,workerDirectory:e})}),l.on("exit",(d,f)=>{if(E.info(`External Task Worker process exited for ${o}`,{code:d,signal:f,topic:o,workerDirectory:e}),delete x[e],d===3||d===4)if(us(e)){let u=ot[e]?.count??1,m=Math.min(1e3*Math.pow(2,u-1),os);E.info(`Scheduling restart for ${o} in ${m}ms (attempt ${u}/${Ot})`,{delay:m,restartCount:u,exitCode:d,topic:o,workerDirectory:e}),setTimeout(async()=>{try{if(F&&!at){E.info("Token refresh cycle is not active, restarting it before worker restart");let g=await Bt();C=lt(g),await Ht(g)}await dt(s,t)}catch(g){E.error(`Failed to restart External Task Worker process for ${o}`,{error:g,topic:o,workerDirectory:e})}},m)}else E.error(`External Task Worker process for ${o} reached maximum restart attempts`,{exitCode:d,topic:o,workerDirectory:e})}),l.send({action:"create",payload:{topic:o,identity:C,moduleString:i,workerPath:s}})}async function ds(s,t){let e=ct(s),n=x[e];if(!n)return dt(s,t);let r=await jt(s),i=Lt(t,e),a=Yt(i);n.send({action:"restart",payload:{topic:a,identity:C,moduleString:r,workerPath:s}})}function Wt(s){let t=ct(s),e=x[t];e&&e.kill()}async function Mt(){if(!F)return null;if(!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID||!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET){let n=new Error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing. For help, please refer to our documentation on environment variables at: https://processcube.io/docs/app-sdk/samples/nextjs/external-task-adapter-with-nextjs#authority");throw E.error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing",{err:n}),n}let s=await ts.discover(process.env.PROCESSCUBE_AUTHORITY_URL);return await new s.Client({client_id:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID,client_secret:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET}).grant({grant_type:"client_credentials",scope:"engine_etw"})}async function Bt(){if(!F)return null;for(let s=1;s<=rt;s++)try{return await Mt()}catch(t){let e=Math.min(1e3*Math.pow(2,s-1),as);if(E.error(`Failed to fetch initial token set (attempt ${s}/${rt}), retrying in ${e}ms`,{error:t,attempt:s,delay:e}),s===rt)throw t;await new Promise(n=>setTimeout(n,e))}return null}function lt(s){if(!F||s===null)return ns;let t=s.access_token,e=Qe(t);return{token:s.access_token,userId:e.sub}}async function Ht(s){if(!F||s===null||at)return;at=!0;let t=0,n=await ls(s)*rs*1e3,r=async()=>{try{let i=await Mt();C=lt(i);for(let[a,o]of Object.entries(x))try{o.send({action:"updateIdentity",payload:{identity:C}})}catch(c){E.warn(`Failed to send identity update to worker process ${a}`,{sendError:c})}t=0,setTimeout(r,n)}catch(i){t++;let a=Math.min(1e3*Math.pow(2,t-1),cs);t<=At?E.error(`Could not refresh identity (attempt ${t}/${At}), retrying in ${a}ms`,{error:i,attempt:t,delay:a}):E.error(`Could not refresh identity (attempt ${t}), continuing to retry every ${a}ms`,{error:i,attempt:t,delay:a}),setTimeout(r,a)}};setTimeout(r,n)}async function jt(s){let t=await Ve({entryPoints:[s],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(t.errors.length>0)throw E.error(`Could not transpile file at '${s}'`,{errors:t.errors}),new Error(`Could not transpile file at '${s}'`);return t.warnings.length>0&&E.warn(`Transpiled file at '${s}' with warnings`,{warnings:t.warnings}),t.outputFiles[0].text}async function ls(s){let t=s.expires_in;if(!t&&s.expires_at&&(t=Math.floor(s.expires_at-Date.now()/1e3)),t===void 0)throw new Error("Could not determine the time until the access token for external task workers expires");return t}function Yt(s){return s.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function fs(s){let t,e=[s,it(process.cwd(),"app"),it(process.cwd(),"src","app")];for(let n of e)if(n&&vt(n)){t=n;break}if(!t)throw new Error("Could not find external tasks directory");return t}function us(s){let t=Date.now(),e=ot[s];return!e||t-e.timestamp>is?(ot[s]={count:1,timestamp:t},!0):e.count>=Ot?!1:(e.count++,!0)}function Js(){return h}import{getToken as zt}from"next-auth/jwt";import{ResponseCookies as hs}from"next/dist/compiled/@edge-runtime/cookies/index.js";import{cookies as Y,headers as Kt}from"next/headers";async function w(){let s=await zt({req:{cookies:await Y(),headers:await Kt()}});if(s?.expiresAt&&Date.now()>=s.expiresAt*1e3){let e=await fetch(`${process.env.NEXTAUTH_URL}/api/auth/session`,{method:"GET",headers:{"Content-Type":"application/json",cookie:(await Y()).toString()}}),n=new hs(e.headers);if(n.getAll().length){let r=!1;try{for(let i of n.getAll())(await Y()).set(i.name,i.value,{...i})}catch{r=!0}if(s=await zt({req:{cookies:r?n:await Y(),headers:await Kt()}}),s?.error)throw s.error}}if(!s?.accessToken||!s?.sub)throw new Error("AccessToken or Sub could not be determined!");return{token:s?.accessToken,userId:s?.sub}}import{DataModels as A}from"@5minds/processcube_engine_client";async function v(){try{return w()}catch{return}}async function $t(s){let t=await v();return(await h.processInstances.query({processInstanceId:s},{identity:t,includeXml:!0})).processInstances[0]}async function qt(s,t={sortSettings:{sortBy:A.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await h.flowNodeInstances.query({processInstanceId:s},{...t,identity:t.identity??await v()})).flowNodeInstances}async function Gt(s){let t=await v();return(await h.flowNodeInstances.query({triggeredByFlowNodeInstance:s},{identity:t})).flowNodeInstances}async function Xt(s,t,e){let n=await v();await h.processInstances.retryProcessInstance(s,{flowNodeInstanceId:t,newStartToken:e,identity:n})}async function Vt(s){let t=await v();await h.processInstances.terminateProcessInstance(s,t)}async function dn(s={options:{identity:!0}}){switch(s.options.identity){case!0:s.options.identity=await w();break;case!1:s.options.identity=void 0;break;case void 0:s.options.identity=await w();break}return await h.processInstances.query({...s?.query,state:A.ProcessInstances.ProcessInstanceState.running},s?.options)}async function ln(s={},t=!0){let{processInstanceId:e}=s,n=typeof t=="boolean"?t==!0?await w():void 0:t;return new Promise(async(r,i)=>{let a=[],o=async c=>{if(e!==void 0&&c.processInstanceId!==e)return;let d=await h.processInstances.query({processInstanceId:c.processInstanceId},{identity:n});for(let f of a)h.notification.removeSubscription(f,n);return d.totalCount===0?i(new Error(`Process with instance ID "${c.processInstanceId}" does not exist.`)):r(d.processInstances[0])};if(a.push(await h.notification.onProcessEnded(o,{identity:n})),a.push(await h.notification.onProcessError(o,{identity:n})),a.push(await h.notification.onProcessTerminated(o,{identity:n})),e){let c=await h.processInstances.query({processInstanceId:e,state:[A.ProcessInstances.ProcessInstanceState.finished,A.ProcessInstances.ProcessInstanceState.terminated,A.ProcessInstances.ProcessInstanceState.error]},{identity:n});if(c.totalCount>0){for(let l of a)h.notification.removeSubscription(l,n);r(c.processInstances[0])}}})}import{DataModels as P}from"@5minds/processcube_engine_client";import{mapUserTask as Qt,mapUserTaskList as b}from"../common/index.mjs";async function _n(s={},t=!0){let{correlationId:e,processInstanceId:n,flowNodeId:r}=s,i=typeof t=="boolean"?t==!0?await w():void 0:t;return new Promise(async(a,o)=>{let c=await h.userTasks.onUserTaskWaiting(async d=>{let f=e!==void 0&&d.correlationId!==e,u=d.flowNodeInstanceId===void 0,m=n!==void 0&&d.processInstanceId!==n,g=r!==void 0&&d.flowNodeId!==r;if(f||u||m||g)return;let k=await ms(d.flowNodeInstanceId,{identity:i});return h.notification.removeSubscription(c,i),k===null?o(new Error(`UserTask with instance ID "${d.flowNodeInstanceId}" does not exist.`)):a(k)},{identity:i}),l=await ps({correlationId:e,processInstanceId:n,flowNodeId:r,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});l.userTasks.length>0&&(h.notification.removeSubscription(c,i),a(l.userTasks[0]))})}async function gn(s,t={},e={},n=!0){let r=typeof n=="boolean"?n==!0?await w():void 0:n;await h.userTasks.finishUserTask(s,e,r);let i={state:P.FlowNodeInstances.FlowNodeInstanceState.suspended,...t},a=await h.userTasks.query(i,{identity:r});return Qt(a.userTasks[0])}async function ps(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query(s,t);return b(e)}async function En(s={identity:!0}){switch(s?.identity){case!0:s.identity=await w();break;case!1:s.identity=void 0;break;case void 0:s.identity=await w();break}let t=await h.userTasks.query({state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},s);return b(t)}async function In(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query({processInstanceId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return b(e)}async function Tn(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query({flowNodeId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return b(e)}async function ms(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query({flowNodeInstanceId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{...t,limit:1});return e.userTasks.length===0?null:Qt(e.userTasks[0])}async function Pn(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query({correlationId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return b(e)}async function kn(s,t){let e=s||await w(),n=await h.userTasks.query({state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:e,...t}),r=n.userTasks.filter(i=>i.actualOwnerId===e.userId);return n.userTasks=r,b(n)}async function Rn(s,t,e){await h.userTasks.reserveUserTaskInstance(s,t,e||s.userId)}async function xn(s,t){await h.userTasks.cancelUserTaskInstanceReservation(s,t)}async function bn(s,t){let e=s||await w(),n=await h.userTasks.query({state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:e,...t}),r=n.userTasks.filter(i=>i.assignedUserIds?.includes(e.userId));return n.userTasks=r,b(n)}import{PHASE_DEVELOPMENT_SERVER as ys,PHASE_PRODUCTION_BUILD as ws,PHASE_PRODUCTION_SERVER as _s}from"next/dist/shared/lib/constants";var Zt=!1,ft=!1;function Dn(s={}){let{applicationSdk:t,...e}=s;return async(n,r)=>{ft=ft||n===ws;let i=n===ys||n===_s;return t?.useExternalTasks&&i&&!Zt&&!ft&&(Zt=!0,await Ut(t?.customExternalTasksDirPath)),{...e,experimental:{...e.experimental,serverComponentsExternalPackages:[...e.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}import{redirect as gs}from"next/navigation";function Ln(s){gs(s)}async function Wn(...s){return await h.processModels.startProcessInstance(...s)}async function Jt(...s){await h.manualTasks.finishManualTask(...s)}async function te(...s){await h.userTasks.finishUserTask(...s)}async function ee(...s){await h.untypedTasks.finishTask(...s)}import{DataModels as Es}from"@5minds/processcube_engine_client";async function Is(){try{return w()}catch{return}}var Vn=async(s,t)=>{let e=await Is();t==="bpmn:UserTask"?await te(s,{},e):t==="bpmn:ManualTask"?await Jt(s,e):t==="bpmn:Task"?await ee(s,e):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${t}`)},Qn=async s=>{await Vt(s)},Zn=async(s,t,e)=>{await Xt(s,t,e)},Jn=async s=>$t(s),tr=async s=>qt(s,{sortSettings:{sortBy:Es.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),er=async s=>Gt(s);export{xn as cancelReservedUserTask,Jt as finishManualTask,Vn as finishTask,ee as finishUntypedTask,te as finishUserTask,gn as finishUserTaskAndGetNext,dn as getActiveProcessInstances,bn as getAssignedUserTasksByIdentity,Js as getEngineClient,tr as getFlowNodeInstances,qt as getFlowNodeInstancesByProcessInstanceId,Gt as getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,w as getIdentity,Jn as getProcessInstance,$t as getProcessInstanceById,kn as getReservedUserTasksByIdentity,er as getTriggeredFlowNodeInstances,ps as getUserTasks,ms as getWaitingUserTaskByFlowNodeInstanceId,En as getWaitingUserTasks,Pn as getWaitingUserTasksByCorrelationId,Tn as getWaitingUserTasksByFlowNodeId,In as getWaitingUserTasksByProcessInstanceId,Ln as navigateToUrl,Rn as reserveUserTask,Zn as retryProcess,Xt as retryProcessInstance,Wn as startProcess,Qn as terminateProcess,Vt as terminateProcessInstance,ln as waitForProcessEnd,_n as waitForUserTask,Dn as withApplicationSdk};
|
|
2
2
|
/*! Bundled license information:
|
|
3
3
|
|
|
4
4
|
chokidar/esm/index.js:
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
1
|
+
var o=require("node:process"),T=require("@5minds/processcube_engine_client"),y=require("@5minds/processcube_engine_sdk"),s=new y.Logger("processcube_app_sdk:external_task_worker_process"),g=process.env.PROCESSCUBE_ENGINE_URL??null,r=null,f,l=0,E=!1,_=6,I=parseInt(process.env.PROCESSCUBE_APP_SDK_ETW_RETRY??"",10)||_,$=3e4,m,h,S;function W(e){if(!(e instanceof Error))return!1;let n=e.code;return["ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENOTFOUND","EAI_AGAIN"].includes(n)||e.message?.includes("socket hang up")||e.message?.includes("fetch failed")}process.on("message",e=>{(async()=>{try{switch(e.action){case"create":await p(e.payload);break;case"restart":await O(e.payload);break;case"updateIdentity":U(e.payload);break}}catch(n){s.error("Error handling IPC message",{action:e.action,error:n,pid:o.pid})}})()});process.once("SIGTERM",()=>{u("External Task Worker Process received SIGTERM signal")});process.once("SIGINT",()=>{u("External Task Worker Process received SIGINT signal")});process.once("SIGHUP",()=>{u("External Task Worker Process received SIGHUP signal")});process.once("disconnect",()=>{u("External Task Worker Process received disconnect signal")});process.on("unhandledRejection",e=>{s.error("Unhandled Promise Rejection in External Task Worker Process",{reason:e,pid:o.pid})});process.on("uncaughtException",e=>{s.error("Uncaught Exception in External Task Worker Process",{error:e,pid:o.pid}),process.exit(4)});async function p({topic:e,identity:n,moduleString:t,workerPath:a,workerId:c}){f=e,m=n,h=t,S=a;let d=await M(t,a);d===null&&process.exit(1),"default"in d||(s.error(`Failed starting external task worker ${r?.workerId??""} for topic ${e}. Please export a default handler function. For more information see https://processcube.io/docs/app-sdk/samples/nextjs/external-task-adapter-with-nextjs#external-tasks-entwickeln`,{workerId:r?.workerId,topic:e,pid:o.pid}),process.exit(2));let N={identity:n,...d?.config,workerId:c},P=d.default;x(g,"EngineURL"),r=new T.ExternalTaskWorker(g,e,P,N),r.onWorkerError((k,i,R)=>{x(r,"externalTaskWorker"),s.error(`External task worker ${r.workerId} for topic ${e} ran into an error`,{errorType:k,error:i instanceof Error?{message:i.message,name:i.name,stack:i.stack,...i.code&&{code:i.code}}:i,externalTaskId:R?.id,workerId:r.workerId,topic:e,pid:o.pid}),r.stop(),r.dispose(),r=null,w(i,e)});try{r.start()}catch(k){s.error(`Failed to start external task worker for topic ${e}`,{error:k,pid:o.pid}),r.stop(),r.dispose(),r=null,w(k,e);return}E||(l=0),E=!1,s.info(`Started external task worker ${r.workerId} for topic ${e}`,{workerId:r.workerId,topic:e,pid:o.pid})}function w(e,n){if(W(e)&&l<I){l++,E=!0;let t=Math.min(1e3*Math.pow(2,l-1),$);s.info(`Connection error for topic ${n}, retrying in ${t}ms (attempt ${l}/${I})`,{topic:n,pid:o.pid,delay:t,attempt:l}),setTimeout(()=>{p({topic:n,identity:m,moduleString:h,workerPath:S})},t);return}process.exit(3)}async function O({topic:e,identity:n,moduleString:t,workerPath:a}){let c=r?.workerId;s.info(`Restarting external task worker ${c??""} for topic ${e}`,{reason:`Code changes in External Task for ${e}`,workerId:c,topic:e,pid:o.pid}),C("External Task Worker restarting"),await p({topic:e,identity:n,moduleString:t,workerPath:a,workerId:c})}function U({identity:e}){r&&(r.identity=e)}function u(e){C(e),process.exit()}function C(e){s.info(`Stopping external task worker ${r?.workerId??""} for topic ${f}`,{reason:e,workerId:r?.workerId,topic:f,pid:o.pid}),r?.stop(),r?.dispose()}function M(e,n){try{var t=module.constructor,a=new t;return a._compile(e,n),a.exports}catch(c){return s.error("Could not start external task worker due to error while requiring module from string",{err:c,pid:o.pid}),null}}function x(e,n,t){if(e==null){let a=t==null?"":`
|
|
2
2
|
|
|
3
3
|
Context:
|
|
4
4
|
|
|
5
|
-
${JSON.stringify(
|
|
5
|
+
${JSON.stringify(t,null,2)}`;throw new Error(`Unexpected value: \`${n}\` should not be null here.${a}`)}}
|