@5minds/processcube_app_sdk 8.0.2-develop-e160d2-mioj0fki → 8.0.2-develop-397e95-miso77om
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/server/index.cjs +1 -1
- package/build/server/index.mjs +1 -1
- package/package.json +1 -1
package/build/server/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var N=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var ue=Object.prototype.hasOwnProperty;var pe=(e,t)=>{for(var s in t)N(e,s,{get:t[s],enumerable:!0})},fe=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of le(t))!ue.call(e,o)&&o!==s&&N(e,o,{get:()=>t[o],enumerable:!(n=de(t,o))||n.enumerable});return e};var ye=e=>fe(N({},"__esModule",{value:!0}),e);var Ge={};pe(Ge,{cancelReservedUserTask:()=>Fe,finishManualTask:()=>D,finishTask:()=>Le,finishUntypedTask:()=>M,finishUserTask:()=>L,finishUserTaskAndGetNext:()=>Se,getActiveProcessInstances:()=>Ce,getAssignedUserTasksByIdentity:()=>ve,getEngineClient:()=>Ee,getFlowNodeInstances:()=>Ke,getFlowNodeInstancesByProcessInstanceId:()=>F,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds:()=>v,getIdentity:()=>i,getProcessInstance:()=>qe,getProcessInstanceById:()=>U,getReservedUserTasksByIdentity:()=>Re,getTriggeredFlowNodeInstances:()=>Xe,getUserTasks:()=>te,getWaitingUserTaskByFlowNodeInstanceId:()=>se,getWaitingUserTasks:()=>_e,getWaitingUserTasksByCorrelationId:()=>be,getWaitingUserTasksByFlowNodeId:()=>he,getWaitingUserTasksByProcessInstanceId:()=>Ne,navigateToUrl:()=>Be,reserveUserTask:()=>Ue,retryProcess:()=>We,retryProcessInstance:()=>O,startProcess:()=>Ae,terminateProcess:()=>Me,terminateProcessInstance:()=>B,waitForProcessEnd:()=>Pe,waitForUserTask:()=>xe,withApplicationSdk:()=>Oe});module.exports=ye(Ge);var St=require("only-server"),_t=require("../common/index.cjs");var K=require("chokidar"),X=require("esbuild"),G=require("jwt-decode"),$=require("node:child_process"),P=require("node:fs"),l=require("node:path"),_=require("openid-client"),j=require("@5minds/processcube_engine_sdk");var q=require("@5minds/processcube_engine_client"),h=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",r=new q.EngineClient(h);var Ie={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},ke=.85,S=["external_task.ts","external_task.js"],b=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,k=new j.Logger("processcube_app_sdk:external_task_adapter"),m={},C;async function H(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 Q();C=await Z(t),await Te(t);let s=we(e);(0,K.watch)(s).on("add",async n=>{if(S.includes((0,l.basename)(n)))return Y(n,s)}).on("change",async n=>{if(S.includes((0,l.basename)(n)))return me(n,s)}).on("unlink",async n=>{S.includes((0,l.basename)(n))&&V(n)}).on("error",n=>k.error(`Watcher error: ${n}`))}async function Y(e,t){let s=(0,l.dirname)(e);if((await P.promises.readdir(s)).filter(d=>S.includes(d)).length>1){k.error(`Multiple external task files found in directory ${s}. Stopping all external task workers for this directory.`),m[s]&&V(e);return}let a=await J(e),c=(0,l.relative)(t,s),u=z(c),p=(0,l.join)(__dirname,"lib/ExternalTaskWorkerProcess.cjs"),f=(0,$.fork)(p,{env:{...process.env,PROCESSCUBE_ENGINE_URL:h}});m[s]=f,f.once("disconnect",()=>{delete m[s]}),f.on("error",d=>{k.error(`External Task Worker process error for ${u}`,{error:d,topic:u,workerDirectory:s})}),f.on("exit",(d,E)=>{k.info(`External Task Worker process exited for ${u}`,{code:d,signal:E,topic:u,workerDirectory:s}),delete m[s]}),f.send({action:"create",payload:{topic:u,identity:C,moduleString:a,workerPath:e}})}async function me(e,t){let s=(0,l.dirname)(e),n=m[s];if(!n)return Y(e,t);let o=await J(e),a=(0,l.relative)(t,s),c=z(a);n.send({action:"restart",payload:{topic:c,identity:C,moduleString:o,workerPath:e}})}function V(e){let t=(0,l.dirname)(e),s=m[t];s&&s.kill()}async function Q(){if(!b)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 k.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(!b||e===null)return Ie;let t=e.access_token,s=(0,G.jwtDecode)(t);return{token:e.access_token,userId:s.sub}}async function Te(e){let t=5;if(!b||e===null)return;let n=await ge(e)*ke*1e3,o=async()=>{try{let a=await Q();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){k.error("Could not refresh identity for external task worker processes. Stopping all external task workers.",{error:a});for(let u of Object.values(m))u.kill();return}k.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 J(e){let t=await(0,X.build)({entryPoints:[e],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(t.errors.length>0)throw k.error(`Could not transpile file at '${e}'`,{errors:t.errors}),new Error(`Could not transpile file at '${e}'`);return t.warnings.length>0&&k.warn(`Transpiled file at '${e}' with warnings`,{warnings:t.warnings}),t.outputFiles[0].text}async function ge(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 z(e){return e.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function we(e){let t,s=[e,(0,l.join)(process.cwd(),"app"),(0,l.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 Ee(){return r}var R=require("next-auth/jwt"),ee=require("next/dist/compiled/@edge-runtime/cookies/index.js"),T=require("next/headers");async function i(){let e=await(0,R.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 ee.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,R.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 U(e){let t=await x();return(await r.processInstances.query({processInstanceId:e},{identity:t,includeXml:!0})).processInstances[0]}async function F(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 v(e){let t=await x();return(await r.flowNodeInstances.query({triggeredByFlowNodeInstance:e},{identity:t})).flowNodeInstances}async function O(e,t,s){let n=await x();await r.processInstances.retryProcessInstance(e,{flowNodeInstanceId:t,newStartToken:s,identity:n})}async function B(e){let t=await x();await r.processInstances.terminateProcessInstance(e,t)}async function Ce(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 Pe(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=[],u=async p=>{if(s!==void 0&&p.processInstanceId!==s)return;let d=await r.processInstances.query({processInstanceId:p.processInstanceId},{identity:n});for(let E of c)r.notification.removeSubscription(E,n);return d.totalCount===0?a(new Error(`Process with instance ID "${p.processInstanceId}" does not exist.`)):o(d.processInstances[0])};if(c.push(await r.notification.onProcessEnded(u,{identity:n})),c.push(await r.notification.onProcessError(u,{identity:n})),c.push(await r.notification.onProcessTerminated(u,{identity:n})),s){let p=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(p.totalCount>0){for(let f of c)r.notification.removeSubscription(f,n);o(p.processInstances[0])}}})}var I=require("@5minds/processcube_engine_client"),y=require("../common/index.cjs");async function xe(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,u)=>{let p=await r.userTasks.onUserTaskWaiting(async d=>{let E=s!==void 0&&d.correlationId!==s,ae=d.flowNodeInstanceId===void 0,ie=n!==void 0&&d.processInstanceId!==n,ce=o!==void 0&&d.flowNodeId!==o;if(E||ae||ie||ce)return;let W=await se(d.flowNodeInstanceId,{identity:a});return r.notification.removeSubscription(p,a),W===null?u(new Error(`UserTask with instance ID "${d.flowNodeInstanceId}" does not exist.`)):c(W)},{identity:a}),f=await te({correlationId:s,processInstanceId:n,flowNodeId:o,state:I.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:a});f.userTasks.length>0&&(r.notification.removeSubscription(p,a),c(f.userTasks[0]))})}async function Se(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:I.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended,...t},c=await r.userTasks.query(a,{identity:o});return(0,y.mapUserTask)(c.userTasks[0])}async function te(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,y.mapUserTaskList)(s)}async function _e(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:I.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return(0,y.mapUserTaskList)(t)}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({processInstanceId:e,state:I.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,y.mapUserTaskList)(s)}async function he(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:I.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,y.mapUserTaskList)(s)}async function se(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:I.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{...t,limit:1});return s.userTasks.length===0?null:(0,y.mapUserTask)(s.userTasks[0])}async function be(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:I.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,y.mapUserTaskList)(s)}async function Re(e,t){let s=e||await i(),n=await r.userTasks.query({state:I.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:s,...t}),o=n.userTasks.filter(a=>a.actualOwnerId===s.userId);return n.userTasks=o,(0,y.mapUserTaskList)(n)}async function Ue(e,t,s){await r.userTasks.reserveUserTaskInstance(e,t,s||e.userId)}async function Fe(e,t){await r.userTasks.cancelUserTaskInstanceReservation(e,t)}async function ve(e,t){let s=e||await i(),n=await r.userTasks.query({state:I.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:s,...t}),o=n.userTasks.filter(a=>a.assignedUserIds?.includes(s.userId));return n.userTasks=o,(0,y.mapUserTaskList)(n)}var w=require("next/dist/shared/lib/constants");var ne=!1,A=!1;function Oe(e={}){let{applicationSdk:t,...s}=e;return async(n,o)=>{A=A||n===w.PHASE_PRODUCTION_BUILD;let a=n===w.PHASE_DEVELOPMENT_SERVER||n===w.PHASE_PRODUCTION_SERVER;return t?.useExternalTasks&&a&&!ne&&!A&&(ne=!0,await H(t?.customExternalTasksDirPath)),{...s,experimental:{...s.experimental,serverComponentsExternalPackages:[...s.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}var re=require("next/navigation");function Be(e){(0,re.redirect)(e)}async function Ae(...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 M(...e){await r.untypedTasks.finishTask(...e)}var oe=require("@5minds/processcube_engine_client");async function De(){try{return i()}catch{return}}var Le=async(e,t)=>{let s=await De();t==="bpmn:UserTask"?await L(e,{},s):t==="bpmn:ManualTask"?await D(e,s):t==="bpmn:Task"?await M(e,s):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${t}`)},Me=async e=>{await B(e)},We=async(e,t,s)=>{await O(e,t,s)},qe=async e=>U(e),Ke=async e=>F(e,{sortSettings:{sortBy:oe.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),Xe=async e=>v(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 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});
|
package/build/server/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"only-server";import"../common/index.mjs";import{stat as xt}from"fs";import{stat as bt,readdir as Rt}from"fs/promises";import{EventEmitter as Ct}from"events";import*as p from"path";import{stat as Xe,lstat as ae,readdir as Qe,realpath as Ze}from"node:fs/promises";import{Readable as Je}from"node:stream";import{resolve as ce,relative as et,join as tt,sep as st}from"node:path";var I={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},Y={root:".",fileFilter:s=>!0,directoryFilter:s=>!0,type:I.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(Y);var ue="READDIRP_RECURSIVE_ERROR",nt=new Set(["ENOENT","EPERM","EACCES","ELOOP",ue]),de=[I.DIR_TYPE,I.EVERYTHING_TYPE,I.FILE_DIR_TYPE,I.FILE_TYPE],rt=new Set([I.DIR_TYPE,I.EVERYTHING_TYPE,I.FILE_DIR_TYPE]),it=new Set([I.EVERYTHING_TYPE,I.FILE_DIR_TYPE,I.FILE_TYPE]),ot=s=>nt.has(s.code),at=process.platform==="win32",le=s=>!0,fe=s=>{if(s===void 0)return le;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 le},z=class extends Je{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...Y,...e},{root:n,type:r}=t;this._fileFilter=fe(t.fileFilter),this._directoryFilter=fe(t.directoryFilter);let i=t.lstat?ae:Xe;at?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=t.depth??Y.depth,this._wantsDir=r?rt.has(r):!1,this._wantsFile=r?it.has(r):!1,this._wantsEverything=r===I.EVERYTHING_TYPE,this._root=ce(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 Qe(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=ce(tt(t,r));n={path:et(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){ot(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 Ze(n),i=await ae(r);if(i.isFile())return"file";if(i.isDirectory()){let a=r.length;if(n.startsWith(r)&&n.substr(a,1)===st){let o=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return o.code=ue,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 he(s,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=I.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&&!de.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${de.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=s,new z(e)}import{watchFile as ct,unwatchFile as pe,watch as dt}from"fs";import{open as lt,stat as ye,lstat as ft,realpath as K}from"fs/promises";import*as m from"path";import{type as ut}from"os";var ht="data",$="end",we="close",O=()=>{};var M=process.platform,V=M==="win32",pt=M==="darwin",mt=M==="linux",yt=M==="freebsd",_e=ut()==="OS400",w={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},E=w,wt="watch",_t={lstat:ft,stat:ye},b="listeners",A="errHandlers",C="rawEmitters",gt=[b,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"]),Et=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]},ge=s=>s instanceof Set?s.size===0:!s,U=new Map;function me(s,e,t,n,r){let i=(a,o)=>{t(s),r(a,o,{watchedPath:s}),o&&s!==o&&L(m.resolve(s,o),b,m.join(s,o))};try{return dt(s,{persistent:e.persistent},i)}catch(a){n(a);return}}var L=(s,e,t,n,r)=>{let i=U.get(s);i&&G(i[e],a=>{a(t,n,r)})},Tt=(s,e,t,n)=>{let{listener:r,errHandler:i,rawEmitter:a}=n,o=U.get(e),c;if(!t.persistent)return c=me(s,t,r,i,a),c?c.close.bind(c):void 0;if(o)S(o,b,r),S(o,A,i),S(o,C,a);else{if(c=me(s,t,L.bind(null,e,b),i,L.bind(null,e,C)),!c)return;c.on(E.ERROR,async l=>{let d=L.bind(null,e,A);if(o&&(o.watcherUnusable=!0),V&&l.code==="EPERM")try{await(await lt(s,"r")).close(),d(l)}catch{}else d(l)}),o={listeners:r,errHandlers:i,rawEmitters:a,watcher:c},U.set(e,o)}return()=>{N(o,b,r),N(o,A,i),N(o,C,a),ge(o.listeners)&&(o.watcher.close(),U.delete(e),gt.forEach(Pt(o)),o.watcher=void 0,Object.freeze(o))}},q=new Map,kt=(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)&&(pe(e),a=void 0),a?(S(a,b,r),S(a,C,i)):(a={listeners:r,rawEmitters:i,options:t,watcher:ct(e,t,(c,l)=>{G(a.rawEmitters,f=>{f(E.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,b,r),N(a,C,i),ge(a.listeners)&&(q.delete(e),pe(e),a.options=a.watcher=void 0,Object.freeze(a))}},W=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&&Et(i)?n.binaryInterval:n.interval,l=kt(e,o,c,{listener:t,rawEmitter:this.fsw._emitRaw})}else l=Tt(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(wt,e,5)){if(!f||f.mtimeMs===0)try{let h=await ye(e);if(this.fsw.closed)return;let _=h.atimeMs,g=h.mtimeMs;if((!_||_<=g||g!==o.mtimeMs)&&this.fsw._emit(E.CHANGE,e,h),(pt||mt||yt)&&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(E.CHANGE,e,f),o=f}}},l=this._watchWithNodeFs(e,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(E.ADD,e,0))return;this.fsw._emit(E.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(E.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,o),this.fsw._emit(E.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(ht,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(E.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(E.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 _t[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(E.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="/",St="//",xe=".",Nt="..",Dt="string",Ft=/\\/g,Ie=/\/\//,vt=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,At=/^\.[/\\]/;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 Ee(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 Wt(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)=>Ee(n,r,i):Ee(n,e)}var Pe=s=>{let e=B(s).flat();if(!e.every(t=>typeof t===Dt))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(be)},Te=s=>{let e=s.replace(Ft,X),t=!1;for(e.startsWith(St)&&(t=!0);e.match(Ie);)e=e.replace(Ie,X);return t&&(e=X+e),e},be=s=>Te(p.normalize(Te(s))),ke=(s="")=>e=>typeof e=="string"?be(p.isAbsolute(e)?e:p.join(s,e)):e,Ot=(s,e)=>p.isAbsolute(s)?s:p.join(e,s),Mt=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!==xe&&e!==Nt&&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 Rt(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=Mt,Object.freeze(this)}},Bt="stat",Ht="lstat",J=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(At,""),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?Bt:Ht}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 Ct{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};_e&&(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 W(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=>Ot(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)||xe;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){xt(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 Ve=d.get(e);k-Ve.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&&vt.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=(this.options.ignored||[]).map(ke(n)),o=[...[...this._ignoredPaths].map(ke(n)),...i];this._userIgnored=Wt(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=he(e,n);return this._streams.add(r),r.once(we,()=>{r=void 0}),r.once($,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};function Re(s,e={}){let t=new ee(e);return t.add(s),t}import{build as Yt}from"esbuild";import{jwtDecode as zt}from"jwt-decode";import{fork as Kt}from"node:child_process";import{existsSync as Ce,promises as qt}from"node:fs";import{basename as se,dirname as re,join as ne,relative as Se}from"node:path";import{Issuer as Gt,custom as $t}from"openid-client";import{Logger as Vt}from"@5minds/processcube_engine_sdk";import{EngineClient as jt}from"@5minds/processcube_engine_client";var te=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",u=new jt(te);var Xt={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},Qt=.85,H=["external_task.ts","external_task.js"],ie=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,P=new Vt("processcube_app_sdk:external_task_adapter"),x={},D;async function Ne(s){if(s&&!Ce(s))throw new Error(`Invalid customExternalTasksDirPath. The given path '${s}' does not exist`);$t.setHttpOptionsDefaults({timeout:1e5});let e=await ve();D=await Ae(e),await Jt(e);let t=ts(s);Re(t).on("add",async n=>{if(H.includes(se(n)))return De(n,t)}).on("change",async n=>{if(H.includes(se(n)))return Zt(n,t)}).on("unlink",async n=>{H.includes(se(n))&&Fe(n)}).on("error",n=>P.error(`Watcher error: ${n}`))}async function De(s,e){let t=re(s);if((await qt.readdir(t)).filter(d=>H.includes(d)).length>1){P.error(`Multiple external task files found in directory ${t}. Stopping all external task workers for this directory.`),x[t]&&Fe(s);return}let i=await Ue(s),a=Se(e,t),o=Le(a),c=ne(__dirname,"lib/ExternalTaskWorkerProcess.cjs"),l=Kt(c,{env:{...process.env,PROCESSCUBE_ENGINE_URL:te}});x[t]=l,l.once("disconnect",()=>{delete x[t]}),l.on("error",d=>{P.error(`External Task Worker process error for ${o}`,{error:d,topic:o,workerDirectory:t})}),l.on("exit",(d,f)=>{P.info(`External Task Worker process exited for ${o}`,{code:d,signal:f,topic:o,workerDirectory:t}),delete x[t]}),l.send({action:"create",payload:{topic:o,identity:D,moduleString:i,workerPath:s}})}async function Zt(s,e){let t=re(s),n=x[t];if(!n)return De(s,e);let r=await Ue(s),i=Se(e,t),a=Le(i);n.send({action:"restart",payload:{topic:a,identity:D,moduleString:r,workerPath:s}})}function Fe(s){let e=re(s),t=x[e];t&&t.kill()}async function ve(){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 P.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 Gt.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 Ae(s){if(!ie||s===null)return Xt;let e=s.access_token,t=zt(e);return{token:s.access_token,userId:t.sub}}async function Jt(s){let e=5;if(!ie||s===null)return;let n=await es(s)*Qt*1e3,r=async()=>{try{let i=await ve();D=Ae(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){P.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}P.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 Yt({entryPoints:[s],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(e.errors.length>0)throw P.error(`Could not transpile file at '${s}'`,{errors:e.errors}),new Error(`Could not transpile file at '${s}'`);return e.warnings.length>0&&P.warn(`Transpiled file at '${s}' with warnings`,{warnings:e.warnings}),e.outputFiles[0].text}async function es(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 ts(s){let e,t=[s,ne(process.cwd(),"app"),ne(process.cwd(),"src","app")];for(let n of t)if(n&&Ce(n)){e=n;break}if(!e)throw new Error("Could not find external tasks directory");return e}function js(){return u}import{getToken as We}from"next-auth/jwt";import{ResponseCookies as ss}from"next/dist/compiled/@edge-runtime/cookies/index.js";import{cookies as j,headers as Oe}from"next/headers";async function y(){let s=await We({req:{cookies:await j(),headers:await Oe()}});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 ss(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 We({req:{cookies:r?n:await j(),headers:await Oe()}}),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 Me(s){let e=await v();return(await u.processInstances.query({processInstanceId:s},{identity:e,includeXml:!0})).processInstances[0]}async function Be(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 He(s){let e=await v();return(await u.flowNodeInstances.query({triggeredByFlowNodeInstance:s},{identity:e})).flowNodeInstances}async function je(s,e,t){let n=await v();await u.processInstances.retryProcessInstance(s,{flowNodeInstanceId:e,newStartToken:t,identity:n})}async function Ye(s){let e=await v();await u.processInstances.terminateProcessInstance(s,e)}async function Qs(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 Zs(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 T}from"@5minds/processcube_engine_client";import{mapUserTask as ze,mapUserTaskList as R}from"../common/index.mjs";async function an(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 rs(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 ns({correlationId:t,processInstanceId:n,flowNodeId:r,state:T.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});l.userTasks.length>0&&(u.notification.removeSubscription(c,i),a(l.userTasks[0]))})}async function cn(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:T.FlowNodeInstances.FlowNodeInstanceState.suspended,...e},a=await u.userTasks.query(i,{identity:r});return ze(a.userTasks[0])}async function ns(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 R(t)}async function dn(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:T.FlowNodeInstances.FlowNodeInstanceState.suspended},s);return R(e)}async function ln(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:T.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return R(t)}async function fn(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:T.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return R(t)}async function rs(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:T.FlowNodeInstances.FlowNodeInstanceState.suspended},{...e,limit:1});return t.userTasks.length===0?null:ze(t.userTasks[0])}async function un(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:T.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return R(t)}async function hn(s,e){let t=s||await y(),n=await u.userTasks.query({state:T.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:t,...e}),r=n.userTasks.filter(i=>i.actualOwnerId===t.userId);return n.userTasks=r,R(n)}async function pn(s,e,t){await u.userTasks.reserveUserTaskInstance(s,e,t||s.userId)}async function mn(s,e){await u.userTasks.cancelUserTaskInstanceReservation(s,e)}async function yn(s,e){let t=s||await y(),n=await u.userTasks.query({state:T.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:t,...e}),r=n.userTasks.filter(i=>i.assignedUserIds?.includes(t.userId));return n.userTasks=r,R(n)}import{PHASE_DEVELOPMENT_SERVER as is,PHASE_PRODUCTION_BUILD as os,PHASE_PRODUCTION_SERVER as as}from"next/dist/shared/lib/constants";var Ke=!1,oe=!1;function In(s={}){let{applicationSdk:e,...t}=s;return async(n,r)=>{oe=oe||n===os;let i=n===is||n===as;return e?.useExternalTasks&&i&&!Ke&&!oe&&(Ke=!0,await Ne(e?.customExternalTasksDirPath)),{...t,experimental:{...t.experimental,serverComponentsExternalPackages:[...t.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}import{redirect as cs}from"next/navigation";function kn(s){cs(s)}async function Rn(...s){return await u.processModels.startProcessInstance(...s)}async function qe(...s){await u.manualTasks.finishManualTask(...s)}async function Ge(...s){await u.userTasks.finishUserTask(...s)}async function $e(...s){await u.untypedTasks.finishTask(...s)}import{DataModels as ds}from"@5minds/processcube_engine_client";async function ls(){try{return y()}catch{return}}var Mn=async(s,e)=>{let t=await ls();e==="bpmn:UserTask"?await Ge(s,{},t):e==="bpmn:ManualTask"?await qe(s,t):e==="bpmn:Task"?await $e(s,t):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${e}`)},Bn=async s=>{await Ye(s)},Hn=async(s,e,t)=>{await je(s,e,t)},jn=async s=>Me(s),Yn=async s=>Be(s,{sortSettings:{sortBy:ds.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),zn=async s=>He(s);export{mn as cancelReservedUserTask,qe as finishManualTask,Mn as finishTask,$e as finishUntypedTask,Ge as finishUserTask,cn as finishUserTaskAndGetNext,Qs as getActiveProcessInstances,yn as getAssignedUserTasksByIdentity,js as getEngineClient,Yn as getFlowNodeInstances,Be as getFlowNodeInstancesByProcessInstanceId,He as getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,y as getIdentity,jn as getProcessInstance,Me as getProcessInstanceById,hn as getReservedUserTasksByIdentity,zn as getTriggeredFlowNodeInstances,ns as getUserTasks,rs as getWaitingUserTaskByFlowNodeInstanceId,dn as getWaitingUserTasks,un as getWaitingUserTasksByCorrelationId,fn as getWaitingUserTasksByFlowNodeId,ln as getWaitingUserTasksByProcessInstanceId,kn as navigateToUrl,pn as reserveUserTask,Hn as retryProcess,je as retryProcessInstance,Rn as startProcess,Bn as terminateProcess,Ye as terminateProcessInstance,Zs as waitForProcessEnd,an as waitForUserTask,In as withApplicationSdk};
|
|
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};
|
|
2
2
|
/*! Bundled license information:
|
|
3
3
|
|
|
4
4
|
chokidar/esm/index.js:
|
package/package.json
CHANGED