@5minds/processcube_app_sdk 8.1.1 → 8.2.0-develop-97e5a9-mlkoajac

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.
@@ -1 +1 @@
1
- var h=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var pe=Object.prototype.hasOwnProperty;var fe=(e,t)=>{for(var s in t)h(e,s,{get:t[s],enumerable:!0})},ye=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ue(t))!pe.call(e,o)&&o!==s&&h(e,o,{get:()=>t[o],enumerable:!(n=le(t,o))||n.enumerable});return e};var Ie=e=>ye(h({},"__esModule",{value:!0}),e);var Ye={};fe(Ye,{cancelReservedUserTask:()=>Be,finishManualTask:()=>D,finishTask:()=>Ke,finishUntypedTask:()=>q,finishUserTask:()=>L,finishUserTaskAndGetNext:()=>be,getActiveProcessInstances:()=>_e,getAssignedUserTasksByIdentity:()=>Me,getEngineClient:()=>Se,getFlowNodeInstances:()=>je,getFlowNodeInstancesByProcessInstanceId:()=>A,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds:()=>O,getIdentity:()=>i,getProcessInstance:()=>Ge,getProcessInstanceById:()=>v,getReservedUserTasksByIdentity:()=>Ae,getTriggeredFlowNodeInstances:()=>He,getUserTasks:()=>ne,getWaitingUserTaskByFlowNodeInstanceId:()=>re,getWaitingUserTasks:()=>Re,getWaitingUserTasksByCorrelationId:()=>ve,getWaitingUserTasksByFlowNodeId:()=>Fe,getWaitingUserTasksByProcessInstanceId:()=>Ue,navigateToUrl:()=>De,reserveUserTask:()=>Oe,retryProcess:()=>Xe,retryProcessInstance:()=>B,startProcess:()=>Le,terminateProcess:()=>$e,terminateProcessInstance:()=>M,waitForProcessEnd:()=>Ne,waitForUserTask:()=>he,withApplicationSdk:()=>We});module.exports=Ie(Ye);var bt=require("only-server"),Rt=require("../common/index.cjs");var G=require("chokidar"),j=require("esbuild"),H=require("jwt-decode"),Y=require("node:child_process"),P=require("node:fs"),u=require("node:path"),_=require("openid-client"),V=require("@5minds/processcube_engine_sdk");var $=require("@5minds/processcube_engine_client"),b=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",r=new $.EngineClient(b);var ke={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},me=.85,S=["external_task.ts","external_task.js"],R=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,p=new V.Logger("processcube_app_sdk:external_task_adapter"),m={},X={},C,Te=3,ge=6e4;async function Q(e){if(e&&!(0,P.existsSync)(e))throw new Error(`Invalid customExternalTasksDirPath. The given path '${e}' does not exist`);_.custom.setHttpOptionsDefaults({timeout:1e5});let t=await J();C=await z(t),await Ee(t);let s=Pe(e);(0,G.watch)(s).on("add",async n=>{if(S.includes((0,u.basename)(n)))return U(n,s)}).on("change",async n=>{if(S.includes((0,u.basename)(n)))return we(n,s)}).on("unlink",async n=>{S.includes((0,u.basename)(n))&&Z(n)}).on("error",n=>p.error(`Watcher error: ${n}`))}async function U(e,t){let s=(0,u.dirname)(e);if((await P.promises.readdir(s)).filter(l=>S.includes(l)).length>1){p.error(`Multiple external task files found in directory ${s}. Stopping all external task workers for this directory.`),m[s]&&Z(e);return}let a=await ee(e),c=(0,u.relative)(t,s),d=te(c),f=(0,u.join)(__dirname,"lib/ExternalTaskWorkerProcess.cjs"),y=(0,Y.fork)(f,{env:{...process.env,PROCESSCUBE_ENGINE_URL:b}});m[s]=y,y.once("disconnect",()=>{delete m[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)=>{p.info(`External Task Worker process exited for ${d}`,{code:l,signal:E,topic:d,workerDirectory:s}),delete m[s],(l===3||l===4)&&(xe(s)?(p.info(`Restarting External Task Worker process for ${d} after error`,{exitCode:l,topic:d,workerDirectory:s}),setTimeout(()=>{U(e,t).catch(N=>{p.error(`Failed to restart External Task Worker process for ${d}`,{error:N,topic:d,workerDirectory:s})})},1e3)):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:C,moduleString:a,workerPath:e}})}async function we(e,t){let s=(0,u.dirname)(e),n=m[s];if(!n)return U(e,t);let o=await ee(e),a=(0,u.relative)(t,s),c=te(a);n.send({action:"restart",payload:{topic:c,identity:C,moduleString:o,workerPath:e}})}function Z(e){let t=(0,u.dirname)(e),s=m[t];s&&s.kill()}async function J(){if(!R)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 _.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 z(e){if(!R||e===null)return ke;let t=e.access_token,s=(0,H.jwtDecode)(t);return{token:e.access_token,userId:s.sub}}async function Ee(e){let t=5;if(!R||e===null)return;let n=await Ce(e)*me*1e3,o=async()=>{try{let a=await J();C=z(a);for(let c of Object.values(m))c.send({action:"updateIdentity",payload:{identity:C}});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(m))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 ee(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 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 Ce(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 te(e){return e.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function Pe(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,P.existsSync)(n)){t=n;break}if(!t)throw new Error("Could not find external tasks directory");return t}function xe(e){let t=Date.now(),s=X[e];return!s||t-s.timestamp>ge?(X[e]={count:1,timestamp:t},!0):s.count>=Te?!1:(s.count++,!0)}function Se(){return r}var F=require("next-auth/jwt"),se=require("next/dist/compiled/@edge-runtime/cookies/index.js"),T=require("next/headers");async function i(){let e=await(0,F.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 se.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,F.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 x(){try{return i()}catch{return}}async function v(e){let t=await x();return(await r.processInstances.query({processInstanceId:e},{identity:t,includeXml:!0})).processInstances[0]}async function A(e,t={sortSettings:{sortBy:g.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await r.flowNodeInstances.query({processInstanceId:e},{...t,identity:t.identity??await x()})).flowNodeInstances}async function O(e){let t=await x();return(await r.flowNodeInstances.query({triggeredByFlowNodeInstance:e},{identity:t})).flowNodeInstances}async function B(e,t,s){let n=await x();await r.processInstances.retryProcessInstance(e,{flowNodeInstanceId:t,newStartToken:s,identity:n})}async function M(e){let t=await x();await r.processInstances.terminateProcessInstance(e,t)}async function _e(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 k=require("@5minds/processcube_engine_client"),I=require("../common/index.cjs");async function he(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,N=l.flowNodeInstanceId===void 0,ce=n!==void 0&&l.processInstanceId!==n,de=o!==void 0&&l.flowNodeId!==o;if(E||N||ce||de)return;let K=await re(l.flowNodeInstanceId,{identity:a});return r.notification.removeSubscription(f,a),K===null?d(new Error(`UserTask with instance ID "${l.flowNodeInstanceId}" does not exist.`)):c(K)},{identity:a}),y=await ne({correlationId:s,processInstanceId:n,flowNodeId:o,state:k.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:a});y.userTasks.length>0&&(r.notification.removeSubscription(f,a),c(y.userTasks[0]))})}async function be(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:k.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended,...t},c=await r.userTasks.query(a,{identity:o});return(0,I.mapUserTask)(c.userTasks[0])}async function ne(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 Re(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:k.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return(0,I.mapUserTaskList)(t)}async function Ue(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:k.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}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({flowNodeId:e,state:k.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function re(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:k.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:k.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function Ae(e,t){let s=e||await i(),n=await r.userTasks.query({state:k.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 Oe(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 Me(e,t){let s=e||await i(),n=await r.userTasks.query({state:k.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 oe=!1,W=!1;function We(e={}){let{applicationSdk:t,...s}=e;return async(n,o)=>{W=W||n===w.PHASE_PRODUCTION_BUILD;let a=n===w.PHASE_DEVELOPMENT_SERVER||n===w.PHASE_PRODUCTION_SERVER;return t?.useExternalTasks&&a&&!oe&&!W&&(oe=!0,await Q(t?.customExternalTasksDirPath)),{...s,experimental:{...s.experimental,serverComponentsExternalPackages:[...s.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}var ae=require("next/navigation");function De(e){(0,ae.redirect)(e)}async function Le(...e){return await r.processModels.startProcessInstance(...e)}async function D(...e){await r.manualTasks.finishManualTask(...e)}async function L(...e){await r.userTasks.finishUserTask(...e)}async function q(...e){await r.untypedTasks.finishTask(...e)}var ie=require("@5minds/processcube_engine_client");async function qe(){try{return i()}catch{return}}var Ke=async(e,t)=>{let s=await qe();t==="bpmn:UserTask"?await L(e,{},s):t==="bpmn:ManualTask"?await D(e,s):t==="bpmn:Task"?await q(e,s):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${t}`)},$e=async e=>{await M(e)},Xe=async(e,t,s)=>{await B(e,t,s)},Ge=async e=>v(e),je=async e=>A(e,{sortSettings:{sortBy:ie.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),He=async e=>O(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 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,4 +1,4 @@
1
- import"only-server";import"../common/index.mjs";import{stat as Rt}from"fs";import{stat as bt,readdir as Ct}from"fs/promises";import{EventEmitter as St}from"events";import*as p from"path";import{stat as Qe,lstat as ce,readdir as Ze,realpath as Je}from"node:fs/promises";import{Readable as et}from"node:stream";import{resolve as de,relative as tt,join as st,sep as nt}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 he="READDIRP_RECURSIVE_ERROR",rt=new Set(["ENOENT","EPERM","EACCES","ELOOP",he]),le=[E.DIR_TYPE,E.EVERYTHING_TYPE,E.FILE_DIR_TYPE,E.FILE_TYPE],it=new Set([E.DIR_TYPE,E.EVERYTHING_TYPE,E.FILE_DIR_TYPE]),ot=new Set([E.EVERYTHING_TYPE,E.FILE_DIR_TYPE,E.FILE_TYPE]),at=s=>rt.has(s.code),ct=process.platform==="win32",fe=s=>!0,ue=s=>{if(s===void 0)return fe;if(typeof s=="function")return s;if(typeof s=="string"){let e=s.trim();return t=>t.basename===e}if(Array.isArray(s)){let e=s.map(t=>t.trim());return t=>e.some(n=>t.basename===n)}return fe},z=class extends et{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...Y,...e},{root:n,type:r}=t;this._fileFilter=ue(t.fileFilter),this._directoryFilter=ue(t.directoryFilter);let i=t.lstat?ce:Qe;ct?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=t.depth??Y.depth,this._wantsDir=r?it.has(r):!1,this._wantsFile=r?ot.has(r):!1,this._wantsEverything=r===E.EVERYTHING_TYPE,this._root=de(n),this._isDirent=!t.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(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).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),e--)):(l==="file"||this._includeAsFile(c))&&this._fileFilter(c)&&this._wantsFile&&(this.push(c),e--)}}else{let r=this.parents.pop();if(!r){this.push(null);break}if(this.parent=await r,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await Ze(e,this._rdOptions)}catch(r){this._onError(r)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,r=this._isDirent?e.name:e;try{let i=de(st(t,r));n={path:tt(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(i){this._onError(i);return}return n}_onError(e){at(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return"";let t=e[this._statsProp];if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let n=e.fullPath;try{let r=await Je(n),i=await ce(r);if(i.isFile())return"file";if(i.isDirectory()){let a=r.length;if(n.startsWith(r)&&n.substr(a,1)===nt){let o=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return o.code=he,this._onError(o)}return"directory"}}catch(r){return this._onError(r),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function pe(s,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=E.FILE_DIR_TYPE),t&&(e.type=t),s){if(typeof s!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!le.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${le.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=s,new z(e)}import{watchFile as dt,unwatchFile as me,watch as lt}from"fs";import{open as ft,stat as we,lstat as ut,realpath as K}from"fs/promises";import*as m from"path";import{type as ht}from"os";var pt="data",$="end",_e="close",O=()=>{};var M=process.platform,V=M==="win32",mt=M==="darwin",yt=M==="linux",wt=M==="freebsd",ge=ht()==="OS400",w={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},T=w,_t="watch",gt={lstat:ut,stat:we},R="listeners",A="errHandlers",C="rawEmitters",Et=[R,A,C],It=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"]),Tt=s=>It.has(m.extname(s).slice(1).toLowerCase()),G=(s,e)=>{s instanceof Set?s.forEach(e):e(s)},S=(s,e,t)=>{let n=s[e];n instanceof Set||(s[e]=n=new Set([n])),n.add(t)},Pt=s=>e=>{let t=s[e];t instanceof Set?t.clear():delete s[e]},N=(s,e,t)=>{let n=s[e];n instanceof Set?n.delete(t):n===t&&delete s[e]},Ee=s=>s instanceof Set?s.size===0:!s,W=new Map;function ye(s,e,t,n,r){let i=(a,o)=>{t(s),r(a,o,{watchedPath:s}),o&&s!==o&&U(m.resolve(s,o),R,m.join(s,o))};try{return lt(s,{persistent:e.persistent},i)}catch(a){n(a);return}}var U=(s,e,t,n,r)=>{let i=W.get(s);i&&G(i[e],a=>{a(t,n,r)})},kt=(s,e,t,n)=>{let{listener:r,errHandler:i,rawEmitter:a}=n,o=W.get(e),c;if(!t.persistent)return c=ye(s,t,r,i,a),c?c.close.bind(c):void 0;if(o)S(o,R,r),S(o,A,i),S(o,C,a);else{if(c=ye(s,t,U.bind(null,e,R),i,U.bind(null,e,C)),!c)return;c.on(T.ERROR,async l=>{let d=U.bind(null,e,A);if(o&&(o.watcherUnusable=!0),V&&l.code==="EPERM")try{await(await ft(s,"r")).close(),d(l)}catch{}else d(l)}),o={listeners:r,errHandlers:i,rawEmitters:a,watcher:c},W.set(e,o)}return()=>{N(o,R,r),N(o,A,i),N(o,C,a),Ee(o.listeners)&&(o.watcher.close(),W.delete(e),Et.forEach(Pt(o)),o.watcher=void 0,Object.freeze(o))}},q=new Map,xt=(s,e,t,n)=>{let{listener:r,rawEmitter:i}=n,a=q.get(e),o=a&&a.options;return o&&(o.persistent<t.persistent||o.interval>t.interval)&&(me(e),a=void 0),a?(S(a,R,r),S(a,C,i)):(a={listeners:r,rawEmitters:i,options:t,watcher:dt(e,t,(c,l)=>{G(a.rawEmitters,f=>{f(T.CHANGE,e,{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(e,a)),()=>{N(a,R,r),N(a,C,i),Ee(a.listeners)&&(q.delete(e),me(e),a.options=a.watcher=void 0,Object.freeze(a))}},L=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=m.dirname(e),i=m.basename(e);this.fsw._getWatchedDir(r).add(i);let o=m.resolve(e),c={persistent:n.persistent};t||(t=O);let l;if(n.usePolling){let d=n.interval!==n.binaryInterval;c.interval=d&&Tt(i)?n.binaryInterval:n.interval,l=xt(e,o,c,{listener:t,rawEmitter:this.fsw._emitRaw})}else l=kt(e,o,c,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(e,t,n){if(this.fsw.closed)return;let r=m.dirname(e),i=m.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let c=async(d,f)=>{if(this.fsw._throttle(_t,e,5)){if(!f||f.mtimeMs===0)try{let h=await we(e);if(this.fsw.closed)return;let _=h.atimeMs,g=h.mtimeMs;if((!_||_<=g||g!==o.mtimeMs)&&this.fsw._emit(T.CHANGE,e,h),(mt||yt||wt)&&o.ino!==h.ino){this.fsw._closeFile(d),o=h;let k=this._watchWithNodeFs(e,c);k&&this.fsw._addPathCloser(d,k)}else o=h}catch{this.fsw._remove(r,i)}else if(a.has(i)){let h=f.atimeMs,_=f.mtimeMs;(!h||h<=_||_!==o.mtimeMs)&&this.fsw._emit(T.CHANGE,e,f),o=f}}},l=this._watchWithNodeFs(e,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(T.ADD,e,0))return;this.fsw._emit(T.ADD,e,t)}return l}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);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,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,o),this.fsw._emit(T.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,r,i,a,o){if(e=m.join(e,""),o=this.fsw._throttle("readdir",e,1e3),!o)return;let c=this.fsw._getWatchedDir(n.path),l=new Set,d=this.fsw._readdirp(e,{fileFilter:f=>n.filterPath(f),directoryFilter:f=>n.filterDir(f)});if(d)return d.on(pt,async f=>{if(this.fsw.closed){d=void 0;return}let h=f.path,_=m.join(e,h);if(l.add(h),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,e,_,h))){if(this.fsw.closed){d=void 0;return}(h===r||!r&&!c.has(h))&&(this.fsw._incrReadyCount(),_=m.join(i,m.relative(i,_)),this._addToNodeFs(_,t,n,a+1))}}).on(T.ERROR,this._boundHandleError),new Promise((f,h)=>{if(!d)return h();d.once($,()=>{if(this.fsw.closed){d=void 0;return}let _=o?o.clear():!1;f(void 0),c.getChildren().filter(g=>g!==e&&!l.has(g)).forEach(g=>{this.fsw._remove(e,g)}),d=void 0,_&&this._handleRead(e,!1,n,r,i,a,o)})})}async _handleDir(e,t,n,r,i,a,o){let c=this.fsw._getWatchedDir(m.dirname(e)),l=c.has(m.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!l&&this.fsw._emit(T.ADD_DIR,e,t),c.add(m.basename(e)),this.fsw._getWatchedDir(e);let d,f,h=this.fsw.options.depth;if((h==null||r<=h)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(e,n,a,i,e,r,d),this.fsw.closed))return;f=this._watchWithNodeFs(e,(_,g)=>{g&&g.mtimeMs===0||this._handleRead(_,!1,a,i,e,r,d)})}return f}async _addToNodeFs(e,t,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);n&&(o.filterPath=c=>n.filterPath(c),o.filterDir=c=>n.filterDir(c));try{let c=await gt[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=m.resolve(e),h=l?await K(e):e;if(this.fsw.closed||(d=await this._handleDir(o.watchPath,c,t,r,i,o,h),this.fsw.closed))return;f!==h&&h!==void 0&&this.fsw._symlinkPaths.set(f,h)}else if(c.isSymbolicLink()){let f=l?await K(e):e;if(this.fsw.closed)return;let h=m.dirname(o.watchPath);if(this.fsw._getWatchedDir(h).add(o.watchPath),this.fsw._emit(T.ADD,o.watchPath,c),d=await this._handleDir(h,c,t,r,e,o,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(m.resolve(e),f)}else d=this._handleFile(o.watchPath,c,t);return a(),d&&this.fsw._addPathCloser(e,d),!1}catch(c){if(this.fsw._handleError(c))return a(),e}}};var X="/",Nt="//",Re=".",Dt="..",Ft="string",vt=/\\/g,Ie=/\/\//,At=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Wt=/^\.[/\\]/;function B(s){return Array.isArray(s)?s:[s]}var Q=s=>typeof s=="object"&&s!==null&&!(s instanceof RegExp);function Ut(s){return typeof s=="function"?s:typeof s=="string"?e=>s===e:s instanceof RegExp?e=>s.test(e):typeof s=="object"&&s!==null?e=>{if(s.path===e)return!0;if(s.recursive){let t=p.relative(s.path,e);return t?!t.startsWith("..")&&!p.isAbsolute(t):!1}return!1}:()=>!1}function Lt(s){if(typeof s!="string")throw new Error("string expected");s=p.normalize(s),s=s.replace(/\\/g,"/");let e=!1;s.startsWith("//")&&(e=!0);let t=/\/\//;for(;s.match(t);)s=s.replace(t,"/");return e&&(s="/"+s),s}function Te(s,e,t){let n=Lt(e);for(let r=0;r<s.length;r++){let i=s[r];if(i(n,t))return!0}return!1}function Ot(s,e){if(s==null)throw new TypeError("anymatch: specify first argument");let n=B(s).map(r=>Ut(r));return e==null?(r,i)=>Te(n,r,i):Te(n,e)}var Pe=s=>{let e=B(s).flat();if(!e.every(t=>typeof t===Ft))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(be)},ke=s=>{let e=s.replace(vt,X),t=!1;for(e.startsWith(Nt)&&(t=!0);e.match(Ie);)e=e.replace(Ie,X);return t&&(e=X+e),e},be=s=>ke(p.normalize(ke(s))),xe=(s="")=>e=>typeof e=="string"?be(p.isAbsolute(e)?e:p.join(s,e)):e,Mt=(s,e)=>p.isAbsolute(s)?s:p.join(e,s),Bt=Object.freeze(new Set),Z=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Re&&e!==Dt&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await Ct(n)}catch{this._removeWatcher&&this._removeWatcher(p.dirname(n),p.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=O,this.items=Bt,Object.freeze(this)}},Ht="stat",jt="lstat",J=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(Wt,""),this.watchPath=r,this.fullWatchPath=p.resolve(r),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=t,this.statMethod=t?Ht:jt}entryPath(e){return p.join(this.watchPath,p.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},ee=class extends St{constructor(e={}){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 t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?B(e.ignored):B([]),awaitWriteFinish:t===!0?n:typeof t=="object"?{...n,...t}:!1};ge&&(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(w.READY)))},this._emitRaw=(...c)=>this.emit(w.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new L(this),Object.freeze(r)}_addIgnoredPath(e){if(Q(e)){for(let t of this._ignoredPaths)if(Q(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let t of this._ignoredPaths)Q(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=Pe(e);return r&&(i=i.map(a=>Mt(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,t);return o&&this._emitReady(),o})).then(a=>{this.closed||a.forEach(o=>{o&&this.add(p.dirname(o),p.basename(t||o))})}),this}unwatch(e){if(this.closed)return this;let t=Pe(e),{cwd:n}=this.options;return t.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 e=[];return this._closers.forEach(t=>t.forEach(n=>{let r=n();r instanceof Promise&&e.push(r)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let i=(this.options.cwd?p.relative(this.options.cwd,n):n)||Re;e[i]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==w.ERROR&&this.emit(w.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;V&&(t=p.normalize(t)),r.cwd&&(t=p.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===w.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((c,l)=>{this.emit(...c),this.emit(w.ALL,...c),this._pendingUnlinks.delete(l)})},typeof r.atomic=="number"?r.atomic:100),this;e===w.ADD&&this._pendingUnlinks.has(t)&&(e=w.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===w.ADD||e===w.CHANGE)&&this._readyEmitted){let c=(l,d)=>{l?(e=w.ERROR,i[0]=l,this.emitWithAll(e,i)):d&&(i.length>1?i[1]=d:i.push(d),this.emitWithAll(e,i))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,c),this}if(e===w.CHANGE&&!this._throttle(w.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===w.ADD||e===w.ADD_DIR||e===w.CHANGE)){let c=r.cwd?p.join(r.cwd,t):t,l;try{l=await bt(c)}catch{}if(!l||this.closed)return;i.push(l)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(w.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw new Error("invalid throttle");let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let l=r.get(t),d=l?l.count:0;return r.delete(t),clearTimeout(a),l&&clearTimeout(l.timeoutObject),d};a=setTimeout(o,n);let c={timeoutObject:a,clear:o,count:0};return r.set(t,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let a=i.pollInterval,o,c=e;this.options.cwd&&!p.isAbsolute(e)&&(c=p.join(this.options.cwd,e));let l=new Date,d=this._pendingWrites;function f(h){Rt(c,(_,g)=>{if(_||!d.has(e)){_&&_.code!=="ENOENT"&&r(_);return}let k=Number(new Date);h&&g.size!==h.size&&(d.get(e).lastChange=k);let Xe=d.get(e);k-Xe.lastChange>=t?(d.delete(e),r(void 0,g)):o=setTimeout(f,a,g)})}d.has(e)||(d.set(e,{lastChange:l,cancelWait:()=>(d.delete(e),clearTimeout(o),n)}),o=setTimeout(f,a))}_isIgnored(e,t){if(this.options.atomic&&At.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=(this.options.ignored||[]).map(xe(n)),o=[...[...this._ignoredPaths].map(xe(n)),...i];this._userIgnored=Ot(o,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new J(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=p.resolve(e);return this._watched.has(t)||this._watched.set(t,new Z(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=p.join(e,t),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(e,t,!0),this._getWatchedDir(r).getChildren().forEach(h=>this._remove(r,h));let c=this._getWatchedDir(e),l=c.has(t);c.remove(t),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()===w.ADD)return;this._watched.delete(r),this._watched.delete(i);let f=n?w.UNLINK_DIR:w.UNLINK;l&&!this._isIgnored(r)&&this._emit(f,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=p.dirname(e);this._getWatchedDir(t).remove(p.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(n=>n()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n={type:w.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},r=pe(e,n);return this._streams.add(r),r.once(_e,()=>{r=void 0}),r.once($,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};function Ce(s,e={}){let t=new ee(e);return t.add(s),t}import{build as zt}from"esbuild";import{jwtDecode as Kt}from"jwt-decode";import{fork as qt}from"node:child_process";import{existsSync as Ne,promises as Gt}from"node:fs";import{basename as se,dirname as re,join as ne,relative as De}from"node:path";import{Issuer as $t,custom as Vt}from"openid-client";import{Logger as Xt}from"@5minds/processcube_engine_sdk";import{EngineClient as Yt}from"@5minds/processcube_engine_client";var te=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",u=new Yt(te);var Qt={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},Zt=.85,H=["external_task.ts","external_task.js"],ie=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,I=new Xt("processcube_app_sdk:external_task_adapter"),x={},Se={},D,Jt=3,es=6e4;async function Fe(s){if(s&&!Ne(s))throw new Error(`Invalid customExternalTasksDirPath. The given path '${s}' does not exist`);Vt.setHttpOptionsDefaults({timeout:1e5});let e=await Ae();D=await We(e),await ss(e);let t=rs(s);Ce(t).on("add",async n=>{if(H.includes(se(n)))return oe(n,t)}).on("change",async n=>{if(H.includes(se(n)))return ts(n,t)}).on("unlink",async n=>{H.includes(se(n))&&ve(n)}).on("error",n=>I.error(`Watcher error: ${n}`))}async function oe(s,e){let t=re(s);if((await Gt.readdir(t)).filter(d=>H.includes(d)).length>1){I.error(`Multiple external task files found in directory ${t}. Stopping all external task workers for this directory.`),x[t]&&ve(s);return}let i=await Ue(s),a=De(e,t),o=Le(a),c=ne(__dirname,"lib/ExternalTaskWorkerProcess.cjs"),l=qt(c,{env:{...process.env,PROCESSCUBE_ENGINE_URL:te}});x[t]=l,l.once("disconnect",()=>{delete x[t]}),l.on("error",d=>{I.error(`External Task Worker process error for ${o}`,{error:d,topic:o,workerDirectory:t})}),l.on("exit",(d,f)=>{I.info(`External Task Worker process exited for ${o}`,{code:d,signal:f,topic:o,workerDirectory:t}),delete x[t],(d===3||d===4)&&(is(t)?(I.info(`Restarting External Task Worker process for ${o} after error`,{exitCode:d,topic:o,workerDirectory:t}),setTimeout(()=>{oe(s,e).catch(h=>{I.error(`Failed to restart External Task Worker process for ${o}`,{error:h,topic:o,workerDirectory:t})})},1e3)):I.error(`External Task Worker process for ${o} reached maximum restart attempts`,{exitCode:d,topic:o,workerDirectory:t}))}),l.send({action:"create",payload:{topic:o,identity:D,moduleString:i,workerPath:s}})}async function ts(s,e){let t=re(s),n=x[t];if(!n)return oe(s,e);let r=await Ue(s),i=De(e,t),a=Le(i);n.send({action:"restart",payload:{topic:a,identity:D,moduleString:r,workerPath:s}})}function ve(s){let e=re(s),t=x[e];t&&t.kill()}async function Ae(){if(!ie)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 $t.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 We(s){if(!ie||s===null)return Qt;let e=s.access_token,t=Kt(e);return{token:s.access_token,userId:t.sub}}async function ss(s){let e=5;if(!ie||s===null)return;let n=await ns(s)*Zt*1e3,r=async()=>{try{let i=await Ae();D=We(i);for(let a of Object.values(x))a.send({action:"updateIdentity",payload:{identity:D}});e=5,setTimeout(r,n)}catch(i){if(e===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:e}),e--;let a=2*1e3;setTimeout(r,a)}};setTimeout(r,n)}async function Ue(s){let e=await zt({entryPoints:[s],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(e.errors.length>0)throw I.error(`Could not transpile file at '${s}'`,{errors:e.errors}),new Error(`Could not transpile file at '${s}'`);return e.warnings.length>0&&I.warn(`Transpiled file at '${s}' with warnings`,{warnings:e.warnings}),e.outputFiles[0].text}async function ns(s){let e=s.expires_in;if(!e&&s.expires_at&&(e=Math.floor(s.expires_at-Date.now()/1e3)),e===void 0)throw new Error("Could not determine the time until the access token for external task workers expires");return e}function Le(s){return s.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function rs(s){let e,t=[s,ne(process.cwd(),"app"),ne(process.cwd(),"src","app")];for(let n of t)if(n&&Ne(n)){e=n;break}if(!e)throw new Error("Could not find external tasks directory");return e}function is(s){let e=Date.now(),t=Se[s];return!t||e-t.timestamp>es?(Se[s]={count:1,timestamp:e},!0):t.count>=Jt?!1:(t.count++,!0)}function qs(){return u}import{getToken as Oe}from"next-auth/jwt";import{ResponseCookies as os}from"next/dist/compiled/@edge-runtime/cookies/index.js";import{cookies as j,headers as Me}from"next/headers";async function y(){let s=await Oe({req:{cookies:await j(),headers:await Me()}});if(s?.expiresAt&&Date.now()>=s.expiresAt*1e3){let t=await fetch(`${process.env.NEXTAUTH_URL}/api/auth/session`,{method:"GET",headers:{"Content-Type":"application/json",cookie:(await j()).toString()}}),n=new os(t.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 Oe({req:{cookies:r?n:await j(),headers:await Me()}}),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 y()}catch{return}}async function Be(s){let e=await v();return(await u.processInstances.query({processInstanceId:s},{identity:e,includeXml:!0})).processInstances[0]}async function He(s,e={sortSettings:{sortBy:F.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await u.flowNodeInstances.query({processInstanceId:s},{...e,identity:e.identity??await v()})).flowNodeInstances}async function je(s){let e=await v();return(await u.flowNodeInstances.query({triggeredByFlowNodeInstance:s},{identity:e})).flowNodeInstances}async function Ye(s,e,t){let n=await v();await u.processInstances.retryProcessInstance(s,{flowNodeInstanceId:e,newStartToken:t,identity:n})}async function ze(s){let e=await v();await u.processInstances.terminateProcessInstance(s,e)}async function tn(s={options:{identity:!0}}){switch(s.options.identity){case!0:s.options.identity=await y();break;case!1:s.options.identity=void 0;break;case void 0:s.options.identity=await y();break}return await u.processInstances.query({...s?.query,state:F.ProcessInstances.ProcessInstanceState.running},s?.options)}async function sn(s={},e=!0){let{processInstanceId:t}=s,n=typeof e=="boolean"?e==!0?await y():void 0:e;return new Promise(async(r,i)=>{let a=[],o=async c=>{if(t!==void 0&&c.processInstanceId!==t)return;let d=await u.processInstances.query({processInstanceId:c.processInstanceId},{identity:n});for(let f of a)u.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 u.notification.onProcessEnded(o,{identity:n})),a.push(await u.notification.onProcessError(o,{identity:n})),a.push(await u.notification.onProcessTerminated(o,{identity:n})),t){let c=await u.processInstances.query({processInstanceId:t,state:[F.ProcessInstances.ProcessInstanceState.finished,F.ProcessInstances.ProcessInstanceState.terminated,F.ProcessInstances.ProcessInstanceState.error]},{identity:n});if(c.totalCount>0){for(let l of a)u.notification.removeSubscription(l,n);r(c.processInstances[0])}}})}import{DataModels as P}from"@5minds/processcube_engine_client";import{mapUserTask as Ke,mapUserTaskList as b}from"../common/index.mjs";async function fn(s={},e=!0){let{correlationId:t,processInstanceId:n,flowNodeId:r}=s,i=typeof e=="boolean"?e==!0?await y():void 0:e;return new Promise(async(a,o)=>{let c=await u.userTasks.onUserTaskWaiting(async d=>{let f=t!==void 0&&d.correlationId!==t,h=d.flowNodeInstanceId===void 0,_=n!==void 0&&d.processInstanceId!==n,g=r!==void 0&&d.flowNodeId!==r;if(f||h||_||g)return;let k=await cs(d.flowNodeInstanceId,{identity:i});return u.notification.removeSubscription(c,i),k===null?o(new Error(`UserTask with instance ID "${d.flowNodeInstanceId}" does not exist.`)):a(k)},{identity:i}),l=await as({correlationId:t,processInstanceId:n,flowNodeId:r,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});l.userTasks.length>0&&(u.notification.removeSubscription(c,i),a(l.userTasks[0]))})}async function un(s,e={},t={},n=!0){let r=typeof n=="boolean"?n==!0?await y():void 0:n;await u.userTasks.finishUserTask(s,t,r);let i={state:P.FlowNodeInstances.FlowNodeInstanceState.suspended,...e},a=await u.userTasks.query(i,{identity:r});return Ke(a.userTasks[0])}async function as(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await y();break;case!1:e.identity=void 0;break;case void 0:e.identity=await y();break}let t=await u.userTasks.query(s,e);return b(t)}async function hn(s={identity:!0}){switch(s?.identity){case!0:s.identity=await y();break;case!1:s.identity=void 0;break;case void 0:s.identity=await y();break}let e=await u.userTasks.query({state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},s);return b(e)}async function pn(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await y();break;case!1:e.identity=void 0;break;case void 0:e.identity=await y();break}let t=await u.userTasks.query({processInstanceId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return b(t)}async function mn(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await y();break;case!1:e.identity=void 0;break;case void 0:e.identity=await y();break}let t=await u.userTasks.query({flowNodeId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return b(t)}async function cs(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await y();break;case!1:e.identity=void 0;break;case void 0:e.identity=await y();break}let t=await u.userTasks.query({flowNodeInstanceId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{...e,limit:1});return t.userTasks.length===0?null:Ke(t.userTasks[0])}async function yn(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await y();break;case!1:e.identity=void 0;break;case void 0:e.identity=await y();break}let t=await u.userTasks.query({correlationId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return b(t)}async function wn(s,e){let t=s||await y(),n=await u.userTasks.query({state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:t,...e}),r=n.userTasks.filter(i=>i.actualOwnerId===t.userId);return n.userTasks=r,b(n)}async function _n(s,e,t){await u.userTasks.reserveUserTaskInstance(s,e,t||s.userId)}async function gn(s,e){await u.userTasks.cancelUserTaskInstanceReservation(s,e)}async function En(s,e){let t=s||await y(),n=await u.userTasks.query({state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:t,...e}),r=n.userTasks.filter(i=>i.assignedUserIds?.includes(t.userId));return n.userTasks=r,b(n)}import{PHASE_DEVELOPMENT_SERVER as ds,PHASE_PRODUCTION_BUILD as ls,PHASE_PRODUCTION_SERVER as fs}from"next/dist/shared/lib/constants";var qe=!1,ae=!1;function kn(s={}){let{applicationSdk:e,...t}=s;return async(n,r)=>{ae=ae||n===ls;let i=n===ds||n===fs;return e?.useExternalTasks&&i&&!qe&&!ae&&(qe=!0,await Fe(e?.customExternalTasksDirPath)),{...t,experimental:{...t.experimental,serverComponentsExternalPackages:[...t.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}import{redirect as us}from"next/navigation";function Cn(s){us(s)}async function Dn(...s){return await u.processModels.startProcessInstance(...s)}async function Ge(...s){await u.manualTasks.finishManualTask(...s)}async function $e(...s){await u.userTasks.finishUserTask(...s)}async function Ve(...s){await u.untypedTasks.finishTask(...s)}import{DataModels as hs}from"@5minds/processcube_engine_client";async function ps(){try{return y()}catch{return}}var Yn=async(s,e)=>{let t=await ps();e==="bpmn:UserTask"?await $e(s,{},t):e==="bpmn:ManualTask"?await Ge(s,t):e==="bpmn:Task"?await Ve(s,t):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${e}`)},zn=async s=>{await ze(s)},Kn=async(s,e,t)=>{await Ye(s,e,t)},qn=async s=>Be(s),Gn=async s=>He(s,{sortSettings:{sortBy:hs.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),$n=async s=>je(s);export{gn as cancelReservedUserTask,Ge as finishManualTask,Yn as finishTask,Ve as finishUntypedTask,$e as finishUserTask,un as finishUserTaskAndGetNext,tn as getActiveProcessInstances,En as getAssignedUserTasksByIdentity,qs as getEngineClient,Gn as getFlowNodeInstances,He as getFlowNodeInstancesByProcessInstanceId,je as getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,y as getIdentity,qn as getProcessInstance,Be as getProcessInstanceById,wn as getReservedUserTasksByIdentity,$n as getTriggeredFlowNodeInstances,as as getUserTasks,cs as getWaitingUserTaskByFlowNodeInstanceId,hn as getWaitingUserTasks,yn as getWaitingUserTasksByCorrelationId,mn as getWaitingUserTasksByFlowNodeId,pn as getWaitingUserTasksByProcessInstanceId,Cn as navigateToUrl,_n as reserveUserTask,Kn as retryProcess,Ye as retryProcessInstance,Dn as startProcess,zn as terminateProcess,ze as terminateProcessInstance,sn as waitForProcessEnd,fn as waitForUserTask,kn as withApplicationSdk};
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};
2
2
  /*! Bundled license information:
3
3
 
4
4
  chokidar/esm/index.js:
@@ -1,5 +1,5 @@
1
- var n=require("node:process"),w=require("@5minds/processcube_engine_client"),f=require("@5minds/processcube_engine_sdk"),t=new f.Logger("processcube_app_sdk:external_task_worker_process"),u=process.env.PROCESSCUBE_ENGINE_URL??null,e=null,d;process.on("message",r=>{(async()=>{try{switch(r.action){case"create":await x(r.payload);break;case"restart":await m(r.payload);break;case"updateIdentity":h(r.payload);break}}catch(o){t.error("Error handling IPC message",{action:r.action,error:o,pid:n.pid})}})()});process.once("SIGTERM",()=>{k("External Task Worker Process received SIGTERM signal")});process.once("SIGINT",()=>{k("External Task Worker Process received SIGINT signal")});process.once("SIGHUP",()=>{k("External Task Worker Process received SIGHUP signal")});process.once("disconnect",()=>{k("External Task Worker Process received disconnect signal")});process.on("unhandledRejection",r=>{t.error("Unhandled Promise Rejection in External Task Worker Process",{reason:r,pid:n.pid})});process.on("uncaughtException",r=>{t.error("Uncaught Exception in External Task Worker Process",{error:r,pid:n.pid}),process.exit(4)});async function x({topic:r,identity:o,moduleString:a,workerPath:s,workerId:i}){d=r;let l=await P(a,s);l===null&&process.exit(1),"default"in l||(t.error(`Failed starting external task worker ${e?.workerId??""} for topic ${r}. 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:e?.workerId,topic:r,pid:n.pid}),process.exit(2));let I={identity:o,...l?.config,workerId:i},y=l.default;p(u,"EngineURL"),e=new w.ExternalTaskWorker(u,r,y,I),e.onWorkerError((E,c,T)=>{p(e,"externalTaskWorker"),t.error(`External task worker ${e.workerId} for topic ${r} ran into an error`,{errorType:E,error:c instanceof Error?{message:c.message,name:c.name,stack:c.stack,...c.code&&{code:c.code}}:c,externalTaskId:T?.id,workerId:e.workerId,topic:r,pid:n.pid}),e.stop(),e.dispose(),process.exit(3)}),e.start(),t.info(`Started external task worker ${e.workerId} for topic ${r}`,{workerId:e.workerId,topic:r,pid:n.pid})}async function m({topic:r,identity:o,moduleString:a,workerPath:s}){let i=e?.workerId;t.info(`Restarting external task worker ${i??""} for topic ${r}`,{reason:`Code changes in External Task for ${r}`,workerId:i,topic:r,pid:n.pid}),g("External Task Worker restarting"),await x({topic:r,identity:o,moduleString:a,workerPath:s,workerId:i})}function h({identity:r}){e&&(e.identity=r)}function k(r){g(r),process.exit()}function g(r){t.info(`Stopping external task worker ${e?.workerId??""} for topic ${d}`,{reason:r,workerId:e?.workerId,topic:d,pid:n.pid}),e?.stop(),e?.dispose()}function P(r,o){try{var a=module.constructor,s=new a;return s._compile(r,o),s.exports}catch(i){return t.error("Could not start external task worker due to error while requiring module from string",{err:i,pid:n.pid}),null}}function p(r,o,a){if(r==null){let s=a==null?"":`
1
+ var t=require("node:process"),y=require("@5minds/processcube_engine_client"),m=require("@5minds/processcube_engine_sdk"),o=new m.Logger("processcube_app_sdk:external_task_worker_process"),f=process.env.PROCESSCUBE_ENGINE_URL??null,r=null,E,l=0,_=6,I=parseInt(process.env.PROCESSCUBE_APP_SDK_ETW_RETRY??"",10)||_,R=3e4,g,w,x;function $(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 W(e.payload);break;case"updateIdentity":U(e.payload);break}}catch(n){o.error("Error handling IPC message",{action:e.action,error:n,pid:t.pid})}})()});process.once("SIGTERM",()=>{k("External Task Worker Process received SIGTERM signal")});process.once("SIGINT",()=>{k("External Task Worker Process received SIGINT signal")});process.once("SIGHUP",()=>{k("External Task Worker Process received SIGHUP signal")});process.once("disconnect",()=>{k("External Task Worker Process received disconnect signal")});process.on("unhandledRejection",e=>{o.error("Unhandled Promise Rejection in External Task Worker Process",{reason:e,pid:t.pid})});process.on("uncaughtException",e=>{o.error("Uncaught Exception in External Task Worker Process",{error:e,pid:t.pid}),process.exit(4)});async function p({topic:e,identity:n,moduleString:s,workerPath:a,workerId:c}){E=e,g=n,w=s,x=a;let d=await O(s,a);d===null&&process.exit(1),"default"in d||(o.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:t.pid}),process.exit(2));let h={identity:n,...d?.config,workerId:c},C=d.default;T(f,"EngineURL"),r=new y.ExternalTaskWorker(f,e,C,h),r.onWorkerError((N,i,P)=>{if(T(r,"externalTaskWorker"),o.error(`External task worker ${r.workerId} for topic ${e} ran into an error`,{errorType:N,error:i instanceof Error?{message:i.message,name:i.name,stack:i.stack,...i.code&&{code:i.code}}:i,externalTaskId:P?.id,workerId:r.workerId,topic:e,pid:t.pid}),r.stop(),r.dispose(),r=null,$(i)&&l<I){l++;let u=Math.min(1e3*Math.pow(2,l-1),R);o.info(`Connection error for topic ${e}, retrying in ${u}ms (attempt ${l}/${I})`,{topic:e,pid:t.pid,delay:u,attempt:l}),setTimeout(()=>{p({topic:e,identity:g,moduleString:w,workerPath:x})},u);return}process.exit(3)}),r.start(),l=0,o.info(`Started external task worker ${r.workerId} for topic ${e}`,{workerId:r.workerId,topic:e,pid:t.pid})}async function W({topic:e,identity:n,moduleString:s,workerPath:a}){let c=r?.workerId;o.info(`Restarting external task worker ${c??""} for topic ${e}`,{reason:`Code changes in External Task for ${e}`,workerId:c,topic:e,pid:t.pid}),S("External Task Worker restarting"),await p({topic:e,identity:n,moduleString:s,workerPath:a,workerId:c})}function U({identity:e}){r&&(r.identity=e)}function k(e){S(e),process.exit()}function S(e){o.info(`Stopping external task worker ${r?.workerId??""} for topic ${E}`,{reason:e,workerId:r?.workerId,topic:E,pid:t.pid}),r?.stop(),r?.dispose()}function O(e,n){try{var s=module.constructor,a=new s;return a._compile(e,n),a.exports}catch(c){return o.error("Could not start external task worker due to error while requiring module from string",{err:c,pid:t.pid}),null}}function T(e,n,s){if(e==null){let a=s==null?"":`
2
2
 
3
3
  Context:
4
4
 
5
- ${JSON.stringify(a,null,2)}`;throw new Error(`Unexpected value: \`${o}\` should not be null here.${s}`)}}
5
+ ${JSON.stringify(s,null,2)}`;throw new Error(`Unexpected value: \`${n}\` should not be null here.${a}`)}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@5minds/processcube_app_sdk",
3
- "version": "8.1.1",
3
+ "version": "8.2.0-develop-97e5a9-mlkoajac",
4
4
  "description": "The SDK for ProcessCube Apps",
5
5
  "type": "module",
6
6
  "main": "build/common/index.cjs",
@@ -98,7 +98,7 @@
98
98
  "react": "^19.1.0"
99
99
  },
100
100
  "dependencies": {
101
- "@5minds/processcube_engine_client": "6.2.1-develop-5ee5c8-mlf0gcna",
101
+ "@5minds/processcube_engine_client": "6.2.1-develop-ca239b-mlju3ron",
102
102
  "@5minds/processcube_engine_sdk": "7.1.2",
103
103
  "@headlessui/react": "^2.2.1",
104
104
  "@heroicons/react": "^2.2.0",