@5minds/processcube_app_sdk 8.4.0 → 8.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/server/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var F=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var ke=Object.getOwnPropertyNames;var ge=Object.prototype.hasOwnProperty;var we=(e,t)=>{for(var s in t)F(e,s,{get:t[s],enumerable:!0})},Ee=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ke(t))!ge.call(e,o)&&o!==s&&F(e,o,{get:()=>t[o],enumerable:!(n=Te(t,o))||n.enumerable});return e};var Ce=e=>Ee(F({},"__esModule",{value:!0}),e);var nt={};we(nt,{cancelReservedUserTask:()=>Ge,finishManualTask:()=>H,finishTask:()=>Ze,finishUntypedTask:()=>Y,finishUserTask:()=>j,finishUserTaskAndGetNext:()=>De,getActiveProcessInstances:()=>Oe,getAssignedUserTasksByIdentity:()=>He,getEngineClient:()=>Me,getFlowNodeInstances:()=>tt,getFlowNodeInstancesByProcessInstanceId:()=>q,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds:()=>$,getIdentity:()=>a,getProcessInstance:()=>et,getProcessInstanceById:()=>W,getReservedUserTasksByIdentity:()=>Ke,getTriggeredFlowNodeInstances:()=>st,getUserTasks:()=>pe,getWaitingUserTaskByFlowNodeInstanceId:()=>fe,getWaitingUserTasks:()=>Le,getWaitingUserTasksByCorrelationId:()=>$e,getWaitingUserTasksByFlowNodeId:()=>qe,getWaitingUserTasksByProcessInstanceId:()=>We,navigateToUrl:()=>Ye,reserveUserTask:()=>Xe,retryProcess:()=>ze,retryProcessInstance:()=>K,startProcess:()=>Ve,terminateProcess:()=>Je,terminateProcessInstance:()=>X,waitForProcessEnd:()=>ve,waitForUserTask:()=>Be,withApplicationSdk:()=>je});module.exports=Ce(nt);var Dt=require("only-server"),Lt=require("../common/index.cjs");var Z=require("chokidar"),J=require("esbuild"),z=require("jwt-decode"),ee=require("node:child_process"),h=require("node:fs"),l=require("node:path"),te=require("node:url"),b=require("openid-client"),se=require("@5minds/processcube_engine_sdk");var V=require("@5minds/processcube_engine_client"),A=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",r=new V.EngineClient(A);var Ae={},_e={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},Pe=.85,R=["external_task.ts","external_task.js"],x=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,p=new se.Logger("processcube_app_sdk:external_task_adapter"),w={},O={},E,v=!1,ne=6,Se=3e5,he=3e4,M=10,xe=3e4,Q=10,Ne=6e4;async function re(e){if(e&&!(0,h.existsSync)(e))throw new Error(`Invalid customExternalTasksDirPath. The given path '${e}' does not exist`);b.custom.setHttpOptionsDefaults({timeout:1e5});let t=await ae();E=D(t),await ce(t);let s=Ue(e);(0,Z.watch)(s).on("add",async n=>{if(R.includes((0,l.basename)(n)))return B(n,s)}).on("change",async n=>{if(R.includes((0,l.basename)(n)))return Re(n,s)}).on("unlink",async n=>{R.includes((0,l.basename)(n))&&oe(n)}).on("error",n=>p.error(`Watcher error: ${n}`))}async function B(e,t){let s=(0,l.dirname)(e);if((await h.promises.readdir(s)).filter(y=>R.includes(y)).length>1){p.error(`Multiple external task files found in directory ${s}. Stopping all external task workers for this directory.`),w[s]&&oe(e);return}let i=await de(e),c=(0,l.relative)(t,s),d=le(c),f=typeof __dirname<"u"?__dirname:(0,l.dirname)((0,te.fileURLToPath)(Ae.url)),k=(0,l.join)(f,"lib/ExternalTaskWorkerProcess.cjs"),u=(0,ee.fork)(k,{stdio:["pipe","inherit","inherit","ipc"],env:{...process.env,PROCESSCUBE_ENGINE_URL:A}});w[s]=u,u.once("disconnect",()=>{delete w[s]}),u.on("error",y=>{p.error(`External Task Worker process error for ${d}`,{error:y,topic:d,workerDirectory:s})}),u.on("exit",(y,U)=>{if(p.info(`External Task Worker process exited for ${d}`,{code:y,signal:U,topic:d,workerDirectory:s}),delete w[s],y===3||y===4)if(Fe(s)){let P=O[s]?.count??1,S=Math.min(1e3*Math.pow(2,P-1),he);p.info(`Scheduling restart for ${d} in ${S}ms (attempt ${P}/${ne})`,{delay:S,restartCount:P,exitCode:y,topic:d,workerDirectory:s}),setTimeout(async()=>{try{if(x&&!v){p.info("Token refresh cycle is not active, restarting it before worker restart");let g=await ae();E=D(g),await ce(g)}await B(e,t)}catch(g){p.error(`Failed to restart External Task Worker process for ${d}`,{error:g,topic:d,workerDirectory:s})}},S)}else p.error(`External Task Worker process for ${d} reached maximum restart attempts`,{exitCode:y,topic:d,workerDirectory:s})}),u.send({action:"create",payload:{topic:d,identity:E,moduleString:i,workerPath:e}})}async function Re(e,t){let s=(0,l.dirname)(e),n=w[s];if(!n)return B(e,t);let o=await de(e),i=(0,l.relative)(t,s),c=le(i);n.send({action:"restart",payload:{topic:c,identity:E,moduleString:o,workerPath:e}})}function oe(e){let t=(0,l.dirname)(e),s=w[t];s&&s.kill()}async function ie(){if(!x)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 b.Issuer.discover(process.env.PROCESSCUBE_AUTHORITY_URL);return await new e.Client({client_id:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID,client_secret:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET}).grant({grant_type:"client_credentials",scope:"engine_etw"})}async function ae(){if(!x)return null;for(let e=1;e<=M;e++)try{return await ie()}catch(t){let s=Math.min(1e3*Math.pow(2,e-1),xe);if(p.error(`Failed to fetch initial token set (attempt ${e}/${M}), retrying in ${s}ms`,{error:t,attempt:e,delay:s}),e===M)throw t;await new Promise(n=>setTimeout(n,s))}return null}function D(e){if(!x||e===null)return _e;let t=e.access_token,s=(0,z.jwtDecode)(t);return{token:e.access_token,userId:s.sub}}async function ce(e){if(!x||e===null||v)return;v=!0;let t=0,n=await be(e)*Pe*1e3,o=async()=>{try{let i=await ie();E=D(i);for(let[c,d]of Object.entries(w))try{d.send({action:"updateIdentity",payload:{identity:E}})}catch(f){p.warn(`Failed to send identity update to worker process ${c}`,{sendError:f})}t=0,setTimeout(o,n)}catch(i){t++;let c=Math.min(1e3*Math.pow(2,t-1),Ne);t<=Q?p.error(`Could not refresh identity (attempt ${t}/${Q}), retrying in ${c}ms`,{error:i,attempt:t,delay:c}):p.error(`Could not refresh identity (attempt ${t}), continuing to retry every ${c}ms`,{error:i,attempt:t,delay:c}),setTimeout(o,c)}};setTimeout(o,n)}async function de(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 be(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 le(e){return e.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function Ue(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,h.existsSync)(n)){t=n;break}if(!t)throw new Error("Could not find external tasks directory");return t}function Fe(e){let t=Date.now(),s=O[e];return!s||t-s.timestamp>Se?(O[e]={count:1,timestamp:t},!0):s.count>=ne?!1:(s.count++,!0)}function Me(){return r}var L=require("next-auth/jwt"),ue=require("next/dist/compiled/@edge-runtime/cookies/index.js"),T=require("next/headers");async function a(){let e=await(0,L.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 ue.ResponseCookies(s.headers);if(n.getAll().length){let o=!1;try{for(let i of n.getAll())(await(0,T.cookies)()).set(i.name,i.value,{...i})}catch{o=!0}if(e=await(0,L.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 C=require("@5minds/processcube_engine_client");async function N(){try{return a()}catch{return}}async function W(e){let t=await N();return(await r.processInstances.query({processInstanceId:e},{identity:t,includeXml:!0})).processInstances[0]}async function q(e,t={sortSettings:{sortBy:C.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await r.flowNodeInstances.query({processInstanceId:e},{...t,identity:t.identity??await N()})).flowNodeInstances}async function $(e){let t=await N();return(await r.flowNodeInstances.query({triggeredByFlowNodeInstance:e},{identity:t})).flowNodeInstances}async function K(e,t,s){let n=await N();await r.processInstances.retryProcessInstance(e,{flowNodeInstanceId:t,newStartToken:s,identity:n})}async function X(e){let t=await N();await r.processInstances.terminateProcessInstance(e,t)}async function Oe(e={options:{identity:!0}}){switch(e.options.identity){case!0:e.options.identity=await a();break;case!1:e.options.identity=void 0;break;case void 0:e.options.identity=await a();break}return await r.processInstances.query({...e?.query,state:C.DataModels.ProcessInstances.ProcessInstanceState.running},e?.options)}async function ve(e={},t=!0){let{processInstanceId:s}=e,n=typeof t=="boolean"?t==!0?await a():void 0:t;return new Promise(async(o,i)=>{let c=[],d=async f=>{if(s!==void 0&&f.processInstanceId!==s)return;let u=await r.processInstances.query({processInstanceId:f.processInstanceId},{identity:n});for(let y of c)r.notification.removeSubscription(y,n);return u.totalCount===0?i(new Error(`Process with instance ID "${f.processInstanceId}" does not exist.`)):o(u.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:[C.DataModels.ProcessInstances.ProcessInstanceState.finished,C.DataModels.ProcessInstances.ProcessInstanceState.terminated,C.DataModels.ProcessInstances.ProcessInstanceState.error]},{identity:n});if(f.totalCount>0){for(let k of c)r.notification.removeSubscription(k,n);o(f.processInstances[0])}}})}var m=require("@5minds/processcube_engine_client"),I=require("../common/index.cjs");async function Be(e={},t=!0){let{correlationId:s,processInstanceId:n,flowNodeId:o}=e,i=typeof t=="boolean"?t==!0?await a():void 0:t;return new Promise(async(c,d)=>{let f=await r.userTasks.onUserTaskWaiting(async u=>{let y=s!==void 0&&u.correlationId!==s,U=u.flowNodeInstanceId===void 0,P=n!==void 0&&u.processInstanceId!==n,S=o!==void 0&&u.flowNodeId!==o;if(y||U||P||S)return;let g=await fe(u.flowNodeInstanceId,{identity:i});return r.notification.removeSubscription(f,i),g===null?d(new Error(`UserTask with instance ID "${u.flowNodeInstanceId}" does not exist.`)):c(g)},{identity:i}),k=await pe({correlationId:s,processInstanceId:n,flowNodeId:o,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});k.userTasks.length>0&&(r.notification.removeSubscription(f,i),c(k.userTasks[0]))})}async function De(e,t={},s={},n=!0){let o=typeof n=="boolean"?n==!0?await a():void 0:n;await r.userTasks.finishUserTask(e,s,o);let i={state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended,...t},c=await r.userTasks.query(i,{identity:o});return(0,I.mapUserTask)(c.userTasks[0])}async function pe(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query(e,t);return(0,I.mapUserTaskList)(s)}async function Le(e={identity:!0}){switch(e?.identity){case!0:e.identity=await a();break;case!1:e.identity=void 0;break;case void 0:e.identity=await a();break}let t=await r.userTasks.query({state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return(0,I.mapUserTaskList)(t)}async function We(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query({processInstanceId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function qe(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query({flowNodeId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function fe(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query({flowNodeInstanceId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{...t,limit:1});return s.userTasks.length===0?null:(0,I.mapUserTask)(s.userTasks[0])}async function $e(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query({correlationId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function Ke(e,t){let s=e||await a(),n=await r.userTasks.query({state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:s,...t}),o=n.userTasks.filter(i=>i.actualOwnerId===s.userId);return n.userTasks=o,(0,I.mapUserTaskList)(n)}async function Xe(e,t,s){await r.userTasks.reserveUserTaskInstance(e,t,s||e.userId)}async function Ge(e,t){await r.userTasks.cancelUserTaskInstanceReservation(e,t)}async function He(e,t){let s=e||await a(),n=await r.userTasks.query({state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:s,...t}),o=n.userTasks.filter(i=>i.assignedUserIds?.includes(s.userId));return n.userTasks=o,(0,I.mapUserTaskList)(n)}var _=require("next/dist/shared/lib/constants");var ye=!1,G=!1;function je(e={}){let{applicationSdk:t,...s}=e;return async(n,o)=>{G=G||n===_.PHASE_PRODUCTION_BUILD;let i=n===_.PHASE_DEVELOPMENT_SERVER||n===_.PHASE_PRODUCTION_SERVER;return t?.useExternalTasks&&i&&!ye&&!G&&(ye=!0,await re(t?.customExternalTasksDirPath)),{...s,experimental:{...s.experimental,serverComponentsExternalPackages:[...s.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}var Ie=require("next/navigation");function Ye(e){(0,Ie.redirect)(e)}async function Ve(...e){return await r.processModels.startProcessInstance(...e)}async function H(...e){await r.manualTasks.finishManualTask(...e)}async function j(...e){await r.userTasks.finishUserTask(...e)}async function Y(...e){await r.untypedTasks.finishTask(...e)}var me=require("@5minds/processcube_engine_client");async function Qe(){try{return a()}catch{return}}var Ze=async(e,t)=>{let s=await Qe();t==="bpmn:UserTask"?await j(e,{},s):t==="bpmn:ManualTask"?await H(e,s):t==="bpmn:Task"?await Y(e,s):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${t}`)},Je=async e=>{await X(e)},ze=async(e,t,s)=>{await K(e,t,s)},et=async e=>W(e),tt=async e=>q(e,{sortSettings:{sortBy:me.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),st=async e=>$(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 v=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Re=Object.prototype.hasOwnProperty;var xe=(e,t)=>{for(var s in t)v(e,s,{get:t[s],enumerable:!0})},Ne=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Pe(t))!Re.call(e,o)&&o!==s&&v(e,o,{get:()=>t[o],enumerable:!(n=Ce(t,o))||n.enumerable});return e};var Ue=e=>Ne(v({},"__esModule",{value:!0}),e);var mt={};xe(mt,{AuthorityClient:()=>M,cancelReservedUserTask:()=>rt,finishManualTask:()=>J,finishTask:()=>ut,finishUntypedTask:()=>Z,finishUserTask:()=>Q,finishUserTaskAndGetNext:()=>Qe,getActiveProcessInstances:()=>Ye,getAssignedUserTasksByIdentity:()=>ot,getEngineClient:()=>je,getFlowNodeInstances:()=>yt,getFlowNodeInstancesByProcessInstanceId:()=>H,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds:()=>G,getIdentity:()=>d,getProcessInstance:()=>ft,getProcessInstanceById:()=>X,getReservedUserTasksByIdentity:()=>st,getServerAccessToken:()=>U,getServerIdentity:()=>Fe,getTriggeredFlowNodeInstances:()=>It,getUserTasks:()=>we,getWaitingUserTaskByFlowNodeInstanceId:()=>Ee,getWaitingUserTasks:()=>Ze,getWaitingUserTasksByCorrelationId:()=>tt,getWaitingUserTasksByFlowNodeId:()=>et,getWaitingUserTasksByProcessInstanceId:()=>ze,navigateToUrl:()=>at,reserveUserTask:()=>nt,retryProcess:()=>pt,retryProcessInstance:()=>j,startProcess:()=>ct,terminateProcess:()=>lt,terminateProcessInstance:()=>Y,waitForProcessEnd:()=>Ve,waitForUserTask:()=>Je,withApplicationSdk:()=>it});module.exports=Ue(mt);var ts=require("only-server"),ss=require("../common/index.cjs");var se=require("@5minds/processcube_engine_sdk");var z=require("jwt-decode"),ee=require("@5minds/processcube_engine_sdk"),F=new ee.Logger("processcube_app_sdk:server_identity"),be=.85,Ae="upe_admin engine_read engine_write",P=null;function Oe(e){let t=e?.authorityUrl??process.env.PROCESSCUBE_AUTHORITY_URL,s=e?.clientId??process.env.PROCESSCUBE_SERVER_CLIENT_ID,n=e?.clientSecret??process.env.PROCESSCUBE_SERVER_CLIENT_SECRET,o=e?.scopes??process.env.PROCESSCUBE_SERVER_SCOPES??Ae;if(!t)throw new Error("PROCESSCUBE_AUTHORITY_URL is not configured. Set the environment variable or pass authorityUrl.");if(!s)throw new Error("PROCESSCUBE_SERVER_CLIENT_ID is not configured. Set the environment variable or pass clientId.");if(!n)throw new Error("PROCESSCUBE_SERVER_CLIENT_SECRET is not configured. Set the environment variable or pass clientSecret.");return{authorityUrl:t,clientId:s,clientSecret:n,scopes:o}}function ve(){return P?Date.now()<P.expiresAt:!1}async function U(e){if(!e?.skipCache&&ve())return P.accessToken;let{authorityUrl:t,clientId:s,clientSecret:n,scopes:o}=Oe(e);F.info("Fetching new server access token");let i=await fetch(`${t}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},redirect:"follow",body:new URLSearchParams({grant_type:"client_credentials",client_id:s,client_secret:n,scope:o}).toString(),cache:"no-store"});if(!i.ok){let u=await i.text().catch(()=>""),m=`Failed to fetch server access token: ${i.status} ${i.statusText}${u?` \u2014 ${u}`:""}`;throw F.error(m),new Error(m)}let a=await i.json();if(!a.access_token)throw new Error("Authority response did not contain an access_token");let c=a.expires_in;return c&&c>0?P={accessToken:a.access_token,expiresAt:Date.now()+c*be*1e3}:P=null,F.info("Server access token fetched successfully"),a.access_token}async function Fe(e){let t=await U(e),s=(0,z.jwtDecode)(t);if(!s.sub)throw new Error('Server access token does not contain a "sub" claim');return{token:t,userId:s.sub}}var te=new se.Logger("processcube_app_sdk:authority_client"),M=class{authorityUrl;tokenOptions;constructor(t){let s=t?.authorityUrl??process.env.PROCESSCUBE_AUTHORITY_URL;if(!s)throw new Error("PROCESSCUBE_AUTHORITY_URL is not configured. Set the environment variable or pass authorityUrl.");this.authorityUrl=s.replace(/\/+$/,""),this.tokenOptions=t??{}}async request(t,s,n){let o=await U(this.tokenOptions),i=`${this.authorityUrl}${s}`;te.info(`Authority request: ${t} ${s}`);let a={Cookie:`access_token=${o}`,"Content-Type":"application/json"},c=await fetch(i,{method:t,headers:a,redirect:"follow",body:n!==void 0?JSON.stringify(n):void 0}),u;try{u=await c.json()}catch{u=void 0}return c.ok||te.error(`Authority request failed: ${t} ${s} \u2192 ${c.status} ${c.statusText}`),{ok:c.ok,status:c.status,data:u}}userAdminPath(t,s){return`/acr/username_password/admin/user/${encodeURIComponent(t)}/${s}`}async updateClaim(t,s,n){return this.request("PATCH",this.userAdminPath(t,"update/claim"),{claimName:s,claimValue:n})}async addScope(t,s){return this.request("PATCH",this.userAdminPath(t,"add/scope"),{scopeName:s})}async addGroup(t,s){return this.request("PATCH",this.userAdminPath(t,"add/group"),{groupName:s})}async deleteUser(t,s){return this.request("DELETE",this.userAdminPath(t,"delete"),{fullDelete:s?.fullDelete??!1})}};var oe=require("chokidar"),ie=require("esbuild"),ae=require("jwt-decode"),ce=require("node:child_process"),R=require("node:fs"),l=require("node:path"),de=require("node:url"),A=require("openid-client"),ue=require("@5minds/processcube_engine_sdk");var ne=require("@5minds/processcube_engine_client"),B=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",r=new ne.EngineClient(B);var Ge={},Me={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},Be=.85,b=["external_task.ts","external_task.js"],x=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,f=new ue.Logger("processcube_app_sdk:external_task_adapter"),w={},L={},E,W=!1,le=6,De=3e5,Le=3e4,D=10,We=3e4,re=10,$e=6e4;async function pe(e){if(e&&!(0,R.existsSync)(e))throw new Error(`Invalid customExternalTasksDirPath. The given path '${e}' does not exist`);A.custom.setHttpOptionsDefaults({timeout:1e5});let t=await Ie();E=q(t),await me(t);let s=Xe(e);(0,oe.watch)(s).on("add",async n=>{if(b.includes((0,l.basename)(n)))return $(n,s)}).on("change",async n=>{if(b.includes((0,l.basename)(n)))return qe(n,s)}).on("unlink",async n=>{b.includes((0,l.basename)(n))&&fe(n)}).on("error",n=>f.error(`Watcher error: ${n}`))}async function $(e,t){let s=(0,l.dirname)(e);if((await R.promises.readdir(s)).filter(y=>b.includes(y)).length>1){f.error(`Multiple external task files found in directory ${s}. Stopping all external task workers for this directory.`),w[s]&&fe(e);return}let i=await Te(e),a=(0,l.relative)(t,s),c=ke(a),u=typeof __dirname<"u"?__dirname:(0,l.dirname)((0,de.fileURLToPath)(Ge.url)),m=(0,l.join)(u,"lib/ExternalTaskWorkerProcess.cjs"),p=(0,ce.fork)(m,{stdio:["pipe","inherit","inherit","ipc"],env:{...process.env,PROCESSCUBE_ENGINE_URL:B}});w[s]=p,p.once("disconnect",()=>{delete w[s]}),p.on("error",y=>{f.error(`External Task Worker process error for ${c}`,{error:y,topic:c,workerDirectory:s})}),p.on("exit",(y,O)=>{if(f.info(`External Task Worker process exited for ${c}`,{code:y,signal:O,topic:c,workerDirectory:s}),delete w[s],y===3||y===4)if(He(s)){let _=L[s]?.count??1,C=Math.min(1e3*Math.pow(2,_-1),Le);f.info(`Scheduling restart for ${c} in ${C}ms (attempt ${_}/${le})`,{delay:C,restartCount:_,exitCode:y,topic:c,workerDirectory:s}),setTimeout(async()=>{try{if(x&&!W){f.info("Token refresh cycle is not active, restarting it before worker restart");let g=await Ie();E=q(g),await me(g)}await $(e,t)}catch(g){f.error(`Failed to restart External Task Worker process for ${c}`,{error:g,topic:c,workerDirectory:s})}},C)}else f.error(`External Task Worker process for ${c} reached maximum restart attempts`,{exitCode:y,topic:c,workerDirectory:s})}),p.send({action:"create",payload:{topic:c,identity:E,moduleString:i,workerPath:e}})}async function qe(e,t){let s=(0,l.dirname)(e),n=w[s];if(!n)return $(e,t);let o=await Te(e),i=(0,l.relative)(t,s),a=ke(i);n.send({action:"restart",payload:{topic:a,identity:E,moduleString:o,workerPath:e}})}function fe(e){let t=(0,l.dirname)(e),s=w[t];s&&s.kill()}async function ye(){if(!x)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 f.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 A.Issuer.discover(process.env.PROCESSCUBE_AUTHORITY_URL);return await new e.Client({client_id:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID,client_secret:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET}).grant({grant_type:"client_credentials",scope:"engine_etw"})}async function Ie(){if(!x)return null;for(let e=1;e<=D;e++)try{return await ye()}catch(t){let s=Math.min(1e3*Math.pow(2,e-1),We);if(f.error(`Failed to fetch initial token set (attempt ${e}/${D}), retrying in ${s}ms`,{error:t,attempt:e,delay:s}),e===D)throw t;await new Promise(n=>setTimeout(n,s))}return null}function q(e){if(!x||e===null)return Me;let t=e.access_token,s=(0,ae.jwtDecode)(t);return{token:e.access_token,userId:s.sub}}async function me(e){if(!x||e===null||W)return;W=!0;let t=0,n=await Ke(e)*Be*1e3,o=async()=>{try{let i=await ye();E=q(i);for(let[a,c]of Object.entries(w))try{c.send({action:"updateIdentity",payload:{identity:E}})}catch(u){f.warn(`Failed to send identity update to worker process ${a}`,{sendError:u})}t=0,setTimeout(o,n)}catch(i){t++;let a=Math.min(1e3*Math.pow(2,t-1),$e);t<=re?f.error(`Could not refresh identity (attempt ${t}/${re}), retrying in ${a}ms`,{error:i,attempt:t,delay:a}):f.error(`Could not refresh identity (attempt ${t}), continuing to retry every ${a}ms`,{error:i,attempt:t,delay:a}),setTimeout(o,a)}};setTimeout(o,n)}async function Te(e){let t=await(0,ie.build)({entryPoints:[e],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(t.errors.length>0)throw f.error(`Could not transpile file at '${e}'`,{errors:t.errors}),new Error(`Could not transpile file at '${e}'`);return t.warnings.length>0&&f.warn(`Transpiled file at '${e}' with warnings`,{warnings:t.warnings}),t.outputFiles[0].text}async function Ke(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 ke(e){return e.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function Xe(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,R.existsSync)(n)){t=n;break}if(!t)throw new Error("Could not find external tasks directory");return t}function He(e){let t=Date.now(),s=L[e];return!s||t-s.timestamp>De?(L[e]={count:1,timestamp:t},!0):s.count>=le?!1:(s.count++,!0)}function je(){return r}var K=require("next-auth/jwt"),ge=require("next/dist/compiled/@edge-runtime/cookies/index.js"),k=require("next/headers");async function d(){let e=await(0,K.getToken)({req:{cookies:await(0,k.cookies)(),headers:await(0,k.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,k.cookies)()).toString()}}),n=new ge.ResponseCookies(s.headers);if(n.getAll().length){let o=!1;try{for(let i of n.getAll())(await(0,k.cookies)()).set(i.name,i.value,{...i})}catch{o=!0}if(e=await(0,K.getToken)({req:{cookies:o?n:await(0,k.cookies)(),headers:await(0,k.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 h=require("@5minds/processcube_engine_client");async function N(){try{return d()}catch{return}}async function X(e){let t=await N();return(await r.processInstances.query({processInstanceId:e},{identity:t,includeXml:!0})).processInstances[0]}async function H(e,t={sortSettings:{sortBy:h.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await r.flowNodeInstances.query({processInstanceId:e},{...t,identity:t.identity??await N()})).flowNodeInstances}async function G(e){let t=await N();return(await r.flowNodeInstances.query({triggeredByFlowNodeInstance:e},{identity:t})).flowNodeInstances}async function j(e,t,s){let n=await N();await r.processInstances.retryProcessInstance(e,{flowNodeInstanceId:t,newStartToken:s,identity:n})}async function Y(e){let t=await N();await r.processInstances.terminateProcessInstance(e,t)}async function Ye(e={options:{identity:!0}}){switch(e.options.identity){case!0:e.options.identity=await d();break;case!1:e.options.identity=void 0;break;case void 0:e.options.identity=await d();break}return await r.processInstances.query({...e?.query,state:h.DataModels.ProcessInstances.ProcessInstanceState.running},e?.options)}async function Ve(e={},t=!0){let{processInstanceId:s}=e,n=typeof t=="boolean"?t==!0?await d():void 0:t;return new Promise(async(o,i)=>{let a=[],c=async u=>{if(s!==void 0&&u.processInstanceId!==s)return;let p=await r.processInstances.query({processInstanceId:u.processInstanceId},{identity:n});for(let y of a)r.notification.removeSubscription(y,n);return p.totalCount===0?i(new Error(`Process with instance ID "${u.processInstanceId}" does not exist.`)):o(p.processInstances[0])};if(a.push(await r.notification.onProcessEnded(c,{identity:n})),a.push(await r.notification.onProcessError(c,{identity:n})),a.push(await r.notification.onProcessTerminated(c,{identity:n})),s){let u=await r.processInstances.query({processInstanceId:s,state:[h.DataModels.ProcessInstances.ProcessInstanceState.finished,h.DataModels.ProcessInstances.ProcessInstanceState.terminated,h.DataModels.ProcessInstances.ProcessInstanceState.error]},{identity:n});if(u.totalCount>0){for(let m of a)r.notification.removeSubscription(m,n);o(u.processInstances[0])}}})}var T=require("@5minds/processcube_engine_client"),I=require("../common/index.cjs");async function Je(e={},t=!0){let{correlationId:s,processInstanceId:n,flowNodeId:o}=e,i=typeof t=="boolean"?t==!0?await d():void 0:t;return new Promise(async(a,c)=>{let u=await r.userTasks.onUserTaskWaiting(async p=>{let y=s!==void 0&&p.correlationId!==s,O=p.flowNodeInstanceId===void 0,_=n!==void 0&&p.processInstanceId!==n,C=o!==void 0&&p.flowNodeId!==o;if(y||O||_||C)return;let g=await Ee(p.flowNodeInstanceId,{identity:i});return r.notification.removeSubscription(u,i),g===null?c(new Error(`UserTask with instance ID "${p.flowNodeInstanceId}" does not exist.`)):a(g)},{identity:i}),m=await we({correlationId:s,processInstanceId:n,flowNodeId:o,state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});m.userTasks.length>0&&(r.notification.removeSubscription(u,i),a(m.userTasks[0]))})}async function Qe(e,t={},s={},n=!0){let o=typeof n=="boolean"?n==!0?await d():void 0:n;await r.userTasks.finishUserTask(e,s,o);let i={state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended,...t},a=await r.userTasks.query(i,{identity:o});return(0,I.mapUserTask)(a.userTasks[0])}async function we(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await d();break;case!1:t.identity=void 0;break;case void 0:t.identity=await d();break}let s=await r.userTasks.query(e,t);return(0,I.mapUserTaskList)(s)}async function Ze(e={identity:!0}){switch(e?.identity){case!0:e.identity=await d();break;case!1:e.identity=void 0;break;case void 0:e.identity=await d();break}let t=await r.userTasks.query({state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return(0,I.mapUserTaskList)(t)}async function ze(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await d();break;case!1:t.identity=void 0;break;case void 0:t.identity=await d();break}let s=await r.userTasks.query({processInstanceId:e,state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function et(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await d();break;case!1:t.identity=void 0;break;case void 0:t.identity=await d();break}let s=await r.userTasks.query({flowNodeId:e,state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function Ee(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await d();break;case!1:t.identity=void 0;break;case void 0:t.identity=await d();break}let s=await r.userTasks.query({flowNodeInstanceId:e,state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{...t,limit:1});return s.userTasks.length===0?null:(0,I.mapUserTask)(s.userTasks[0])}async function tt(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await d();break;case!1:t.identity=void 0;break;case void 0:t.identity=await d();break}let s=await r.userTasks.query({correlationId:e,state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function st(e,t){let s=e||await d(),n=await r.userTasks.query({state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:s,...t}),o=n.userTasks.filter(i=>i.actualOwnerId===s.userId);return n.userTasks=o,(0,I.mapUserTaskList)(n)}async function nt(e,t,s){await r.userTasks.reserveUserTaskInstance(e,t,s||e.userId)}async function rt(e,t){await r.userTasks.cancelUserTaskInstanceReservation(e,t)}async function ot(e,t){let s=e||await d(),n=await r.userTasks.query({state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:s,...t}),o=n.userTasks.filter(i=>i.assignedUserIds?.includes(s.userId));return n.userTasks=o,(0,I.mapUserTaskList)(n)}var S=require("next/dist/shared/lib/constants");var he=!1,V=!1;function it(e={}){let{applicationSdk:t,...s}=e;return async(n,o)=>{V=V||n===S.PHASE_PRODUCTION_BUILD;let i=n===S.PHASE_DEVELOPMENT_SERVER||n===S.PHASE_PRODUCTION_SERVER;return t?.useExternalTasks&&i&&!he&&!V&&(he=!0,await pe(t?.customExternalTasksDirPath)),{...s,experimental:{...s.experimental,serverComponentsExternalPackages:[...s.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}var Se=require("next/navigation");function at(e){(0,Se.redirect)(e)}async function ct(...e){return await r.processModels.startProcessInstance(...e)}async function J(...e){await r.manualTasks.finishManualTask(...e)}async function Q(...e){await r.userTasks.finishUserTask(...e)}async function Z(...e){await r.untypedTasks.finishTask(...e)}var _e=require("@5minds/processcube_engine_client");async function dt(){try{return d()}catch{return}}var ut=async(e,t)=>{let s=await dt();t==="bpmn:UserTask"?await Q(e,{},s):t==="bpmn:ManualTask"?await J(e,s):t==="bpmn:Task"?await Z(e,s):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${t}`)},lt=async e=>{await Y(e)},pt=async(e,t,s)=>{await j(e,t,s)},ft=async e=>X(e),yt=async e=>H(e,{sortSettings:{sortBy:_e.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),It=async e=>G(e);0&&(module.exports={AuthorityClient,cancelReservedUserTask,finishManualTask,finishTask,finishUntypedTask,finishUserTask,finishUserTaskAndGetNext,getActiveProcessInstances,getAssignedUserTasksByIdentity,getEngineClient,getFlowNodeInstances,getFlowNodeInstancesByProcessInstanceId,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,getIdentity,getProcessInstance,getProcessInstanceById,getReservedUserTasksByIdentity,getServerAccessToken,getServerIdentity,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 Fe}from"node:fs";import{stat as Ae,readdir as ve}from"node:fs/promises";import{EventEmitter as Le}from"node:events";import*as p from"node:path";import{stat as ne,lstat as ut,readdir as re,realpath as ie}from"node:fs/promises";import{Readable as oe}from"node:stream";import{resolve as ht,relative as ae,join as ce,sep as de}from"node:path";var T={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},K={root:".",fileFilter:s=>!0,directoryFilter:s=>!0,type:T.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(K);var wt="READDIRP_RECURSIVE_ERROR",le=new Set(["ENOENT","EPERM","EACCES","ELOOP",wt]),pt=[T.DIR_TYPE,T.EVERYTHING_TYPE,T.FILE_DIR_TYPE,T.FILE_TYPE],fe=new Set([T.DIR_TYPE,T.EVERYTHING_TYPE,T.FILE_DIR_TYPE]),ue=new Set([T.EVERYTHING_TYPE,T.FILE_DIR_TYPE,T.FILE_TYPE]),he=s=>le.has(s.code),pe=process.platform==="win32",mt=s=>!0,yt=s=>{if(s===void 0)return mt;if(typeof s=="function")return s;if(typeof s=="string"){let t=s.trim();return e=>e.basename===t}if(Array.isArray(s)){let t=s.map(e=>e.trim());return e=>t.some(n=>e.basename===n)}return mt},$=class extends oe{constructor(t={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:t.highWaterMark});let e={...K,...t},{root:n,type:r}=e;this._fileFilter=yt(e.fileFilter),this._directoryFilter=yt(e.directoryFilter);let i=e.lstat?ut:ne;pe?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=e.depth??K.depth,this._wantsDir=r?fe.has(r):!1,this._wantsFile=r?ue.has(r):!1,this._wantsEverything=r===T.EVERYTHING_TYPE,this._root=ht(n),this._isDirent=!e.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(t){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&t>0;){let e=this.parent,n=e&&e.files;if(n&&n.length>0){let{path:r,depth:i}=e,a=n.splice(0,t).map(c=>this._formatEntry(c,r)),o=await Promise.all(a);for(let c of o){if(!c)continue;if(this.destroyed)return;let f=await this._getEntryType(c);f==="directory"&&this._directoryFilter(c)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(c.fullPath,i+1)),this._wantsDir&&(this.push(c),t--)):(f==="file"||this._includeAsFile(c))&&this._fileFilter(c)&&this._wantsFile&&(this.push(c),t--)}}else{let r=this.parents.pop();if(!r){this.push(null);break}if(this.parent=await r,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(t,e){let n;try{n=await re(t,this._rdOptions)}catch(r){this._onError(r)}return{files:n,depth:e,path:t}}async _formatEntry(t,e){let n,r=this._isDirent?t.name:t;try{let i=ht(ce(e,r));n={path:ae(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?t:await this._stat(i)}catch(i){this._onError(i);return}return n}_onError(t){he(t)&&!this.destroyed?this.emit("warn",t):this.destroy(t)}async _getEntryType(t){if(!t&&this._statsProp in t)return"";let e=t[this._statsProp];if(e.isFile())return"file";if(e.isDirectory())return"directory";if(e&&e.isSymbolicLink()){let n=t.fullPath;try{let r=await ie(n),i=await ut(r);if(i.isFile())return"file";if(i.isDirectory()){let a=r.length;if(n.startsWith(r)&&n.substr(a,1)===de){let o=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return o.code=wt,this._onError(o)}return"directory"}}catch(r){return this._onError(r),""}}}_includeAsFile(t){let e=t&&t[this._statsProp];return e&&this._wantsEverything&&!e.isDirectory()}};function _t(s,t={}){let e=t.entryType||t.type;if(e==="both"&&(e=T.FILE_DIR_TYPE),e&&(t.type=e),s){if(typeof s!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(e&&!pt.includes(e))throw new Error(`readdirp: Invalid type passed. Use one of ${pt.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return t.root=s,new $(t)}import{watchFile as me,unwatchFile as gt,watch as ye}from"node:fs";import{open as we,stat as It,lstat as _e,realpath as q}from"node:fs/promises";import*as y from"node:path";import{type as ge}from"node:os";var Ee="data",V="end",Tt="close",M=()=>{};var B=process.platform,Q=B==="win32",Ie=B==="darwin",Te=B==="linux",Pe=B==="freebsd",Pt=ge()==="OS400",_={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},P=_,ke="watch",Re={lstat:_e,stat:It},R="listeners",L="errHandlers",S="rawEmitters",xe=[R,L,S],be=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Se=s=>be.has(y.extname(s).slice(1).toLowerCase()),X=(s,t)=>{s instanceof Set?s.forEach(t):t(s)},N=(s,t,e)=>{let n=s[t];n instanceof Set||(s[t]=n=new Set([n])),n.add(e)},Ce=s=>t=>{let e=s[t];e instanceof Set?e.clear():delete s[t]},D=(s,t,e)=>{let n=s[t];n instanceof Set?n.delete(e):n===e&&delete s[t]},kt=s=>s instanceof Set?s.size===0:!s,U=new Map;function Et(s,t,e,n,r){let i=(a,o)=>{e(s),r(a,o,{watchedPath:s}),o&&s!==o&&O(y.resolve(s,o),R,y.join(s,o))};try{return ye(s,{persistent:t.persistent},i)}catch(a){n(a);return}}var O=(s,t,e,n,r)=>{let i=U.get(s);i&&X(i[t],a=>{a(e,n,r)})},Ne=(s,t,e,n)=>{let{listener:r,errHandler:i,rawEmitter:a}=n,o=U.get(t),c;if(!e.persistent)return c=Et(s,e,r,i,a),c?c.close.bind(c):void 0;if(o)N(o,R,r),N(o,L,i),N(o,S,a);else{if(c=Et(s,e,O.bind(null,t,R),i,O.bind(null,t,S)),!c)return;c.on(P.ERROR,async f=>{let d=O.bind(null,t,L);if(o&&(o.watcherUnusable=!0),Q&&f.code==="EPERM")try{await(await we(s,"r")).close(),d(f)}catch{}else d(f)}),o={listeners:r,errHandlers:i,rawEmitters:a,watcher:c},U.set(t,o)}return()=>{D(o,R,r),D(o,L,i),D(o,S,a),kt(o.listeners)&&(o.watcher.close(),U.delete(t),xe.forEach(Ce(o)),o.watcher=void 0,Object.freeze(o))}},G=new Map,De=(s,t,e,n)=>{let{listener:r,rawEmitter:i}=n,a=G.get(t),o=a&&a.options;return o&&(o.persistent<e.persistent||o.interval>e.interval)&&(gt(t),a=void 0),a?(N(a,R,r),N(a,S,i)):(a={listeners:r,rawEmitters:i,options:e,watcher:me(t,e,(c,f)=>{X(a.rawEmitters,l=>{l(P.CHANGE,t,{curr:c,prev:f})});let d=c.mtimeMs;(c.size!==f.size||d>f.mtimeMs||d===0)&&X(a.listeners,l=>l(s,c))})},G.set(t,a)),()=>{D(a,R,r),D(a,S,i),kt(a.listeners)&&(G.delete(t),gt(t),a.options=a.watcher=void 0,Object.freeze(a))}},W=class{constructor(t){this.fsw=t,this._boundHandleError=e=>t._handleError(e)}_watchWithNodeFs(t,e){let n=this.fsw.options,r=y.dirname(t),i=y.basename(t);this.fsw._getWatchedDir(r).add(i);let o=y.resolve(t),c={persistent:n.persistent};e||(e=M);let f;if(n.usePolling){let d=n.interval!==n.binaryInterval;c.interval=d&&Se(i)?n.binaryInterval:n.interval,f=De(t,o,c,{listener:e,rawEmitter:this.fsw._emitRaw})}else f=Ne(t,o,c,{listener:e,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return f}_handleFile(t,e,n){if(this.fsw.closed)return;let r=y.dirname(t),i=y.basename(t),a=this.fsw._getWatchedDir(r),o=e;if(a.has(i))return;let c=async(d,l)=>{if(this.fsw._throttle(ke,t,5)){if(!l||l.mtimeMs===0)try{let h=await It(t);if(this.fsw.closed)return;let m=h.atimeMs,g=h.mtimeMs;if((!m||m<=g||g!==o.mtimeMs)&&this.fsw._emit(P.CHANGE,t,h),(Ie||Te||Pe)&&o.ino!==h.ino){this.fsw._closeFile(d),o=h;let I=this._watchWithNodeFs(t,c);I&&this.fsw._addPathCloser(d,I)}else o=h}catch{this.fsw._remove(r,i)}else if(a.has(i)){let h=l.atimeMs,m=l.mtimeMs;(!h||h<=m||m!==o.mtimeMs)&&this.fsw._emit(P.CHANGE,t,l),o=l}}},f=this._watchWithNodeFs(t,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(P.ADD,t,0))return;this.fsw._emit(P.ADD,t,e)}return f}async _handleSymlink(t,e,n,r){if(this.fsw.closed)return;let i=t.fullPath,a=this.fsw._getWatchedDir(e);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let o;try{o=await q(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(P.CHANGE,n,t.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,o),this.fsw._emit(P.ADD,n,t.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(t,e,n,r,i,a,o){if(t=y.join(t,""),o=this.fsw._throttle("readdir",t,1e3),!o)return;let c=this.fsw._getWatchedDir(n.path),f=new Set,d=this.fsw._readdirp(t,{fileFilter:l=>n.filterPath(l),directoryFilter:l=>n.filterDir(l)});if(d)return d.on(Ee,async l=>{if(this.fsw.closed){d=void 0;return}let h=l.path,m=y.join(t,h);if(f.add(h),!(l.stats.isSymbolicLink()&&await this._handleSymlink(l,t,m,h))){if(this.fsw.closed){d=void 0;return}(h===r||!r&&!c.has(h))&&(this.fsw._incrReadyCount(),m=y.join(i,y.relative(i,m)),this._addToNodeFs(m,e,n,a+1))}}).on(P.ERROR,this._boundHandleError),new Promise((l,h)=>{if(!d)return h();d.once(V,()=>{if(this.fsw.closed){d=void 0;return}let m=o?o.clear():!1;l(void 0),c.getChildren().filter(g=>g!==t&&!f.has(g)).forEach(g=>{this.fsw._remove(t,g)}),d=void 0,m&&this._handleRead(t,!1,n,r,i,a,o)})})}async _handleDir(t,e,n,r,i,a,o){let c=this.fsw._getWatchedDir(y.dirname(t)),f=c.has(y.basename(t));!(n&&this.fsw.options.ignoreInitial)&&!i&&!f&&this.fsw._emit(P.ADD_DIR,t,e),c.add(y.basename(t)),this.fsw._getWatchedDir(t);let d,l,h=this.fsw.options.depth;if((h==null||r<=h)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(t,n,a,i,t,r,d),this.fsw.closed))return;l=this._watchWithNodeFs(t,(m,g)=>{g&&g.mtimeMs===0||this._handleRead(m,!1,a,i,t,r,d)})}return l}async _addToNodeFs(t,e,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(t);n&&(o.filterPath=c=>n.filterPath(c),o.filterDir=c=>n.filterDir(c));try{let c=await Re[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,c))return a(),!1;let f=this.fsw.options.followSymlinks,d;if(c.isDirectory()){let l=y.resolve(t),h=f?await q(t):t;if(this.fsw.closed||(d=await this._handleDir(o.watchPath,c,e,r,i,o,h),this.fsw.closed))return;l!==h&&h!==void 0&&this.fsw._symlinkPaths.set(l,h)}else if(c.isSymbolicLink()){let l=f?await q(t):t;if(this.fsw.closed)return;let h=y.dirname(o.watchPath);if(this.fsw._getWatchedDir(h).add(o.watchPath),this.fsw._emit(P.ADD,o.watchPath,c),d=await this._handleDir(h,c,e,r,t,o,l),this.fsw.closed)return;l!==void 0&&this.fsw._symlinkPaths.set(y.resolve(t),l)}else d=this._handleFile(o.watchPath,c,e);return a(),d&&this.fsw._addPathCloser(t,d),!1}catch(c){if(this.fsw._handleError(c))return a(),t}}};var Z="/",Ue="//",Nt=".",Oe="..",We="string",Me=/\\/g,Rt=/\/\//,Be=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,He=/^\.[/\\]/;function H(s){return Array.isArray(s)?s:[s]}var J=s=>typeof s=="object"&&s!==null&&!(s instanceof RegExp);function je(s){return typeof s=="function"?s:typeof s=="string"?t=>s===t:s instanceof RegExp?t=>s.test(t):typeof s=="object"&&s!==null?t=>{if(s.path===t)return!0;if(s.recursive){let e=p.relative(s.path,t);return e?!e.startsWith("..")&&!p.isAbsolute(e):!1}return!1}:()=>!1}function Ye(s){if(typeof s!="string")throw new Error("string expected");s=p.normalize(s),s=s.replace(/\\/g,"/");let t=!1;s.startsWith("//")&&(t=!0);let e=/\/\//;for(;s.match(e);)s=s.replace(e,"/");return t&&(s="/"+s),s}function xt(s,t,e){let n=Ye(t);for(let r=0;r<s.length;r++){let i=s[r];if(i(n,e))return!0}return!1}function ze(s,t){if(s==null)throw new TypeError("anymatch: specify first argument");let n=H(s).map(r=>je(r));return t==null?(r,i)=>xt(n,r,i):xt(n,t)}var bt=s=>{let t=H(s).flat();if(!t.every(e=>typeof e===We))throw new TypeError(`Non-string provided as watch path: ${t}`);return t.map(Dt)},St=s=>{let t=s.replace(Me,Z),e=!1;for(t.startsWith(Ue)&&(e=!0);t.match(Rt);)t=t.replace(Rt,Z);return e&&(t=Z+t),t},Dt=s=>St(p.normalize(St(s))),Ct=(s="")=>t=>typeof t=="string"?Dt(p.isAbsolute(t)?t:p.join(s,t)):t,Ke=(s,t)=>p.isAbsolute(s)?s:p.join(t,s),$e=Object.freeze(new Set),tt=class{constructor(t,e){this.path=t,this._removeWatcher=e,this.items=new Set}add(t){let{items:e}=this;e&&t!==Nt&&t!==Oe&&e.add(t)}async remove(t){let{items:e}=this;if(!e||(e.delete(t),e.size>0))return;let n=this.path;try{await ve(n)}catch{this._removeWatcher&&this._removeWatcher(p.dirname(n),p.basename(n))}}has(t){let{items:e}=this;if(e)return e.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=M,this.items=$e,Object.freeze(this)}},qe="stat",Ge="lstat",et=class{constructor(t,e,n){this.fsw=n;let r=t;this.path=t=t.replace(He,""),this.watchPath=r,this.fullWatchPath=p.resolve(r),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=e,this.statMethod=e?qe:Ge}entryPath(t){return p.join(this.watchPath,p.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:e}=t;if(e&&e.isSymbolicLink())return this.filterDir(t);let n=this.entryPath(t);return this.fsw._isntIgnored(n,e)&&this.fsw._hasReadPermissions(e)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}},st=class extends Le{constructor(t={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let e=t.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...t,ignored:t.ignored?H(t.ignored):H([]),awaitWriteFinish:e===!0?n:typeof e=="object"?{...n,...e}:!1};Pt&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let c=i.toLowerCase();c==="false"||c==="0"?r.usePolling=!1:c==="true"||c==="1"?r.usePolling=!0:r.usePolling=!!c}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=M,this._readyEmitted=!0,process.nextTick(()=>this.emit(_.READY)))},this._emitRaw=(...c)=>this.emit(_.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new W(this),Object.freeze(r)}_addIgnoredPath(t){if(J(t)){for(let e of this._ignoredPaths)if(J(e)&&e.path===t.path&&e.recursive===t.recursive)return}this._ignoredPaths.add(t)}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),typeof t=="string")for(let e of this._ignoredPaths)J(e)&&e.path===t&&this._ignoredPaths.delete(e)}add(t,e,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=bt(t);return r&&(i=i.map(a=>Ke(a,r))),i.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async a=>{let o=await this._nodeFsHandler._addToNodeFs(a,!n,void 0,0,e);return o&&this._emitReady(),o})).then(a=>{this.closed||a.forEach(o=>{o&&this.add(p.dirname(o),p.basename(e||o))})}),this}unwatch(t){if(this.closed)return this;let e=bt(t),{cwd:n}=this.options;return e.forEach(r=>{!p.isAbsolute(r)&&!this._closers.has(r)&&(n&&(r=p.join(n,r)),r=p.resolve(r)),this._closePath(r),this._addIgnoredPath(r),this._watched.has(r)&&this._addIgnoredPath({path:r,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let t=[];return this._closers.forEach(e=>e.forEach(n=>{let r=n();r instanceof Promise&&t.push(r)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((e,n)=>{let i=(this.options.cwd?p.relative(this.options.cwd,n):n)||Nt;t[i]=e.getChildren().sort()}),t}emitWithAll(t,e){this.emit(t,...e),t!==_.ERROR&&this.emit(_.ALL,t,...e)}async _emit(t,e,n){if(this.closed)return;let r=this.options;Q&&(e=p.normalize(e)),r.cwd&&(e=p.relative(r.cwd,e));let i=[e];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(e)))return o.lastChange=new Date,this;if(r.atomic){if(t===_.UNLINK)return this._pendingUnlinks.set(e,[t,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((c,f)=>{this.emit(...c),this.emit(_.ALL,...c),this._pendingUnlinks.delete(f)})},typeof r.atomic=="number"?r.atomic:100),this;t===_.ADD&&this._pendingUnlinks.has(e)&&(t=_.CHANGE,this._pendingUnlinks.delete(e))}if(a&&(t===_.ADD||t===_.CHANGE)&&this._readyEmitted){let c=(f,d)=>{f?(t=_.ERROR,i[0]=f,this.emitWithAll(t,i)):d&&(i.length>1?i[1]=d:i.push(d),this.emitWithAll(t,i))};return this._awaitWriteFinish(e,a.stabilityThreshold,t,c),this}if(t===_.CHANGE&&!this._throttle(_.CHANGE,e,50))return this;if(r.alwaysStat&&n===void 0&&(t===_.ADD||t===_.ADD_DIR||t===_.CHANGE)){let c=r.cwd?p.join(r.cwd,e):e,f;try{f=await Ae(c)}catch{}if(!f||this.closed)return;i.push(f)}return this.emitWithAll(t,i),this}_handleError(t){let e=t&&t.code;return t&&e!=="ENOENT"&&e!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||e!=="EPERM"&&e!=="EACCES")&&this.emit(_.ERROR,t),t||this.closed}_throttle(t,e,n){this._throttled.has(t)||this._throttled.set(t,new Map);let r=this._throttled.get(t);if(!r)throw new Error("invalid throttle");let i=r.get(e);if(i)return i.count++,!1;let a,o=()=>{let f=r.get(e),d=f?f.count:0;return r.delete(e),clearTimeout(a),f&&clearTimeout(f.timeoutObject),d};a=setTimeout(o,n);let c={timeoutObject:a,clear:o,count:0};return r.set(e,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,e,n,r){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let a=i.pollInterval,o,c=t;this.options.cwd&&!p.isAbsolute(t)&&(c=p.join(this.options.cwd,t));let f=new Date,d=this._pendingWrites;function l(h){Fe(c,(m,g)=>{if(m||!d.has(t)){m&&m.code!=="ENOENT"&&r(m);return}let I=Number(new Date);h&&g.size!==h.size&&(d.get(t).lastChange=I);let se=d.get(t);I-se.lastChange>=e?(d.delete(t),r(void 0,g)):o=setTimeout(l,a,g)})}d.has(t)||(d.set(t,{lastChange:f,cancelWait:()=>(d.delete(t),clearTimeout(o),n)}),o=setTimeout(l,a))}_isIgnored(t,e){if(this.options.atomic&&Be.test(t))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=(this.options.ignored||[]).map(Ct(n)),o=[...[...this._ignoredPaths].map(Ct(n)),...i];this._userIgnored=ze(o,void 0)}return this._userIgnored(t,e)}_isntIgnored(t,e){return!this._isIgnored(t,e)}_getWatchHelpers(t){return new et(t,this.options.followSymlinks,this)}_getWatchedDir(t){let e=p.resolve(t);return this._watched.has(e)||this._watched.set(e,new tt(e,this._boundRemove)),this._watched.get(e)}_hasReadPermissions(t){return this.options.ignorePermissionErrors?!0:!!(Number(t.mode)&256)}_remove(t,e,n){let r=p.join(t,e),i=p.resolve(r);if(n=n??(this._watched.has(r)||this._watched.has(i)),!this._throttle("remove",r,100))return;!n&&this._watched.size===1&&this.add(t,e,!0),this._getWatchedDir(r).getChildren().forEach(h=>this._remove(r,h));let c=this._getWatchedDir(t),f=c.has(e);c.remove(e),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let d=r;if(this.options.cwd&&(d=p.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(d)&&this._pendingWrites.get(d).cancelWait()===_.ADD)return;this._watched.delete(r),this._watched.delete(i);let l=n?_.UNLINK_DIR:_.UNLINK;f&&!this._isIgnored(r)&&this._emit(l,r),this._closePath(r)}_closePath(t){this._closeFile(t);let e=p.dirname(t);this._getWatchedDir(e).remove(p.basename(t))}_closeFile(t){let e=this._closers.get(t);e&&(e.forEach(n=>n()),this._closers.delete(t))}_addPathCloser(t,e){if(!e)return;let n=this._closers.get(t);n||(n=[],this._closers.set(t,n)),n.push(e)}_readdirp(t,e){if(this.closed)return;let n={type:_.ALL,alwaysStat:!0,lstat:!0,...e,depth:0},r=_t(t,n);return this._streams.add(r),r.once(Tt,()=>{r=void 0}),r.once(V,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};function Ft(s,t={}){let e=new st(t);return e.add(s),e}import{build as Ve}from"esbuild";import{jwtDecode as Qe}from"jwt-decode";import{fork as Ze}from"node:child_process";import{existsSync as vt,promises as Je}from"node:fs";import{basename as rt,dirname as Y,join as ot,relative as Lt}from"node:path";import{fileURLToPath as ts}from"node:url";import{Issuer as es,custom as ss}from"openid-client";import{Logger as ns}from"@5minds/processcube_engine_sdk";import{EngineClient as Xe}from"@5minds/processcube_engine_client";var nt=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",u=new Xe(nt);var rs={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},is=.85,j=["external_task.ts","external_task.js"],F=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,E=new ns("processcube_app_sdk:external_task_adapter"),x={},at={},C,ct=!1,Ut=6,os=3e5,as=3e4,it=10,cs=3e4,At=10,ds=6e4;async function Ot(s){if(s&&!vt(s))throw new Error(`Invalid customExternalTasksDirPath. The given path '${s}' does not exist`);ss.setHttpOptionsDefaults({timeout:1e5});let t=await Bt();C=lt(t),await Ht(t);let e=us(s);Ft(e).on("add",async n=>{if(j.includes(rt(n)))return dt(n,e)}).on("change",async n=>{if(j.includes(rt(n)))return ls(n,e)}).on("unlink",async n=>{j.includes(rt(n))&&Wt(n)}).on("error",n=>E.error(`Watcher error: ${n}`))}async function dt(s,t){let e=Y(s);if((await Je.readdir(e)).filter(l=>j.includes(l)).length>1){E.error(`Multiple external task files found in directory ${e}. Stopping all external task workers for this directory.`),x[e]&&Wt(s);return}let i=await jt(s),a=Lt(t,e),o=Yt(a),c=typeof __dirname<"u"?__dirname:Y(ts(import.meta.url)),f=ot(c,"lib/ExternalTaskWorkerProcess.cjs"),d=Ze(f,{stdio:["pipe","inherit","inherit","ipc"],env:{...process.env,PROCESSCUBE_ENGINE_URL:nt}});x[e]=d,d.once("disconnect",()=>{delete x[e]}),d.on("error",l=>{E.error(`External Task Worker process error for ${o}`,{error:l,topic:o,workerDirectory:e})}),d.on("exit",(l,h)=>{if(E.info(`External Task Worker process exited for ${o}`,{code:l,signal:h,topic:o,workerDirectory:e}),delete x[e],l===3||l===4)if(hs(e)){let m=at[e]?.count??1,g=Math.min(1e3*Math.pow(2,m-1),as);E.info(`Scheduling restart for ${o} in ${g}ms (attempt ${m}/${Ut})`,{delay:g,restartCount:m,exitCode:l,topic:o,workerDirectory:e}),setTimeout(async()=>{try{if(F&&!ct){E.info("Token refresh cycle is not active, restarting it before worker restart");let I=await Bt();C=lt(I),await Ht(I)}await dt(s,t)}catch(I){E.error(`Failed to restart External Task Worker process for ${o}`,{error:I,topic:o,workerDirectory:e})}},g)}else E.error(`External Task Worker process for ${o} reached maximum restart attempts`,{exitCode:l,topic:o,workerDirectory:e})}),d.send({action:"create",payload:{topic:o,identity:C,moduleString:i,workerPath:s}})}async function ls(s,t){let e=Y(s),n=x[e];if(!n)return dt(s,t);let r=await jt(s),i=Lt(t,e),a=Yt(i);n.send({action:"restart",payload:{topic:a,identity:C,moduleString:r,workerPath:s}})}function Wt(s){let t=Y(s),e=x[t];e&&e.kill()}async function Mt(){if(!F)return null;if(!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID||!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET){let n=new Error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing. For help, please refer to our documentation on environment variables at: https://processcube.io/docs/app-sdk/samples/nextjs/external-task-adapter-with-nextjs#authority");throw E.error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing",{err:n}),n}let s=await es.discover(process.env.PROCESSCUBE_AUTHORITY_URL);return await new s.Client({client_id:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID,client_secret:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET}).grant({grant_type:"client_credentials",scope:"engine_etw"})}async function Bt(){if(!F)return null;for(let s=1;s<=it;s++)try{return await Mt()}catch(t){let e=Math.min(1e3*Math.pow(2,s-1),cs);if(E.error(`Failed to fetch initial token set (attempt ${s}/${it}), retrying in ${e}ms`,{error:t,attempt:s,delay:e}),s===it)throw t;await new Promise(n=>setTimeout(n,e))}return null}function lt(s){if(!F||s===null)return rs;let t=s.access_token,e=Qe(t);return{token:s.access_token,userId:e.sub}}async function Ht(s){if(!F||s===null||ct)return;ct=!0;let t=0,n=await fs(s)*is*1e3,r=async()=>{try{let i=await Mt();C=lt(i);for(let[a,o]of Object.entries(x))try{o.send({action:"updateIdentity",payload:{identity:C}})}catch(c){E.warn(`Failed to send identity update to worker process ${a}`,{sendError:c})}t=0,setTimeout(r,n)}catch(i){t++;let a=Math.min(1e3*Math.pow(2,t-1),ds);t<=At?E.error(`Could not refresh identity (attempt ${t}/${At}), retrying in ${a}ms`,{error:i,attempt:t,delay:a}):E.error(`Could not refresh identity (attempt ${t}), continuing to retry every ${a}ms`,{error:i,attempt:t,delay:a}),setTimeout(r,a)}};setTimeout(r,n)}async function jt(s){let t=await Ve({entryPoints:[s],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(t.errors.length>0)throw E.error(`Could not transpile file at '${s}'`,{errors:t.errors}),new Error(`Could not transpile file at '${s}'`);return t.warnings.length>0&&E.warn(`Transpiled file at '${s}' with warnings`,{warnings:t.warnings}),t.outputFiles[0].text}async function fs(s){let t=s.expires_in;if(!t&&s.expires_at&&(t=Math.floor(s.expires_at-Date.now()/1e3)),t===void 0)throw new Error("Could not determine the time until the access token for external task workers expires");return t}function Yt(s){return s.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function us(s){let t,e=[s,ot(process.cwd(),"app"),ot(process.cwd(),"src","app")];for(let n of e)if(n&&vt(n)){t=n;break}if(!t)throw new Error("Could not find external tasks directory");return t}function hs(s){let t=Date.now(),e=at[s];return!e||t-e.timestamp>os?(at[s]={count:1,timestamp:t},!0):e.count>=Ut?!1:(e.count++,!0)}function en(){return u}import{getToken as zt}from"next-auth/jwt";import{ResponseCookies as ps}from"next/dist/compiled/@edge-runtime/cookies/index.js";import{cookies as z,headers as Kt}from"next/headers.js";async function w(){let s=await zt({req:{cookies:await z(),headers:await Kt()}});if(s?.expiresAt&&Date.now()>=s.expiresAt*1e3){let e=await fetch(`${process.env.NEXTAUTH_URL}/api/auth/session`,{method:"GET",headers:{"Content-Type":"application/json",cookie:(await z()).toString()}}),n=new ps(e.headers);if(n.getAll().length){let r=!1;try{for(let i of n.getAll())(await z()).set(i.name,i.value,{...i})}catch{r=!0}if(s=await zt({req:{cookies:r?n:await z(),headers:await Kt()}}),s?.error)throw s.error}}if(!s?.accessToken||!s?.sub)throw new Error("AccessToken or Sub could not be determined!");return{token:s?.accessToken,userId:s?.sub}}import{DataModels as A}from"@5minds/processcube_engine_client";async function v(){try{return w()}catch{return}}async function $t(s){let t=await v();return(await u.processInstances.query({processInstanceId:s},{identity:t,includeXml:!0})).processInstances[0]}async function qt(s,t={sortSettings:{sortBy:A.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await u.flowNodeInstances.query({processInstanceId:s},{...t,identity:t.identity??await v()})).flowNodeInstances}async function Gt(s){let t=await v();return(await u.flowNodeInstances.query({triggeredByFlowNodeInstance:s},{identity:t})).flowNodeInstances}async function Xt(s,t,e){let n=await v();await u.processInstances.retryProcessInstance(s,{flowNodeInstanceId:t,newStartToken:e,identity:n})}async function Vt(s){let t=await v();await u.processInstances.terminateProcessInstance(s,t)}async function fn(s={options:{identity:!0}}){switch(s.options.identity){case!0:s.options.identity=await w();break;case!1:s.options.identity=void 0;break;case void 0:s.options.identity=await w();break}return await u.processInstances.query({...s?.query,state:A.ProcessInstances.ProcessInstanceState.running},s?.options)}async function un(s={},t=!0){let{processInstanceId:e}=s,n=typeof t=="boolean"?t==!0?await w():void 0:t;return new Promise(async(r,i)=>{let a=[],o=async c=>{if(e!==void 0&&c.processInstanceId!==e)return;let d=await u.processInstances.query({processInstanceId:c.processInstanceId},{identity:n});for(let l of a)u.notification.removeSubscription(l,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})),e){let c=await u.processInstances.query({processInstanceId:e,state:[A.ProcessInstances.ProcessInstanceState.finished,A.ProcessInstances.ProcessInstanceState.terminated,A.ProcessInstances.ProcessInstanceState.error]},{identity:n});if(c.totalCount>0){for(let f of a)u.notification.removeSubscription(f,n);r(c.processInstances[0])}}})}import{DataModels as k}from"@5minds/processcube_engine_client";import{mapUserTask as Qt,mapUserTaskList as b}from"../common/index.mjs";async function En(s={},t=!0){let{correlationId:e,processInstanceId:n,flowNodeId:r}=s,i=typeof t=="boolean"?t==!0?await w():void 0:t;return new Promise(async(a,o)=>{let c=await u.userTasks.onUserTaskWaiting(async d=>{let l=e!==void 0&&d.correlationId!==e,h=d.flowNodeInstanceId===void 0,m=n!==void 0&&d.processInstanceId!==n,g=r!==void 0&&d.flowNodeId!==r;if(l||h||m||g)return;let I=await ys(d.flowNodeInstanceId,{identity:i});return u.notification.removeSubscription(c,i),I===null?o(new Error(`UserTask with instance ID "${d.flowNodeInstanceId}" does not exist.`)):a(I)},{identity:i}),f=await ms({correlationId:e,processInstanceId:n,flowNodeId:r,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});f.userTasks.length>0&&(u.notification.removeSubscription(c,i),a(f.userTasks[0]))})}async function In(s,t={},e={},n=!0){let r=typeof n=="boolean"?n==!0?await w():void 0:n;await u.userTasks.finishUserTask(s,e,r);let i={state:k.FlowNodeInstances.FlowNodeInstanceState.suspended,...t},a=await u.userTasks.query(i,{identity:r});return Qt(a.userTasks[0])}async function ms(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await u.userTasks.query(s,t);return b(e)}async function Tn(s={identity:!0}){switch(s?.identity){case!0:s.identity=await w();break;case!1:s.identity=void 0;break;case void 0:s.identity=await w();break}let t=await u.userTasks.query({state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},s);return b(t)}async function Pn(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await u.userTasks.query({processInstanceId:s,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return b(e)}async function kn(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await u.userTasks.query({flowNodeId:s,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return b(e)}async function ys(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await u.userTasks.query({flowNodeInstanceId:s,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},{...t,limit:1});return e.userTasks.length===0?null:Qt(e.userTasks[0])}async function Rn(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await u.userTasks.query({correlationId:s,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return b(e)}async function xn(s,t){let e=s||await w(),n=await u.userTasks.query({state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:e,...t}),r=n.userTasks.filter(i=>i.actualOwnerId===e.userId);return n.userTasks=r,b(n)}async function bn(s,t,e){await u.userTasks.reserveUserTaskInstance(s,t,e||s.userId)}async function Sn(s,t){await u.userTasks.cancelUserTaskInstanceReservation(s,t)}async function Cn(s,t){let e=s||await w(),n=await u.userTasks.query({state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:e,...t}),r=n.userTasks.filter(i=>i.assignedUserIds?.includes(e.userId));return n.userTasks=r,b(n)}import{PHASE_DEVELOPMENT_SERVER as ws,PHASE_PRODUCTION_BUILD as _s,PHASE_PRODUCTION_SERVER as gs}from"next/dist/shared/lib/constants.js";var Zt=!1,ft=!1;function An(s={}){let{applicationSdk:t,...e}=s;return async(n,r)=>{ft=ft||n===_s;let i=n===ws||n===gs;return t?.useExternalTasks&&i&&!Zt&&!ft&&(Zt=!0,await Ot(t?.customExternalTasksDirPath)),{...e,experimental:{...e.experimental,serverComponentsExternalPackages:[...e.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}import{redirect as Es}from"next/navigation.js";function On(s){Es(s)}async function Bn(...s){return await u.processModels.startProcessInstance(...s)}async function Jt(...s){await u.manualTasks.finishManualTask(...s)}async function te(...s){await u.userTasks.finishUserTask(...s)}async function ee(...s){await u.untypedTasks.finishTask(...s)}import{DataModels as Is}from"@5minds/processcube_engine_client";async function Ts(){try{return w()}catch{return}}var Zn=async(s,t)=>{let e=await Ts();t==="bpmn:UserTask"?await te(s,{},e):t==="bpmn:ManualTask"?await Jt(s,e):t==="bpmn:Task"?await ee(s,e):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${t}`)},Jn=async s=>{await Vt(s)},tr=async(s,t,e)=>{await Xt(s,t,e)},er=async s=>$t(s),sr=async s=>qt(s,{sortSettings:{sortBy:Is.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),nr=async s=>Gt(s);export{Sn as cancelReservedUserTask,Jt as finishManualTask,Zn as finishTask,ee as finishUntypedTask,te as finishUserTask,In as finishUserTaskAndGetNext,fn as getActiveProcessInstances,Cn as getAssignedUserTasksByIdentity,en as getEngineClient,sr as getFlowNodeInstances,qt as getFlowNodeInstancesByProcessInstanceId,Gt as getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,w as getIdentity,er as getProcessInstance,$t as getProcessInstanceById,xn as getReservedUserTasksByIdentity,nr as getTriggeredFlowNodeInstances,ms as getUserTasks,ys as getWaitingUserTaskByFlowNodeInstanceId,Tn as getWaitingUserTasks,Rn as getWaitingUserTasksByCorrelationId,kn as getWaitingUserTasksByFlowNodeId,Pn as getWaitingUserTasksByProcessInstanceId,On as navigateToUrl,bn as reserveUserTask,tr as retryProcess,Xt as retryProcessInstance,Bn as startProcess,Jn as terminateProcess,Vt as terminateProcessInstance,un as waitForProcessEnd,En as waitForUserTask,An as withApplicationSdk};
|
|
1
|
+
import"only-server";import"../common/index.mjs";import{Logger as pt}from"@5minds/processcube_engine_sdk";import{jwtDecode as ct}from"jwt-decode";import{Logger as dt}from"@5minds/processcube_engine_sdk";var K=new dt("processcube_app_sdk:server_identity"),lt=.85,ft="upe_admin engine_read engine_write",N=null;function ut(s){let e=s?.authorityUrl??process.env.PROCESSCUBE_AUTHORITY_URL,t=s?.clientId??process.env.PROCESSCUBE_SERVER_CLIENT_ID,n=s?.clientSecret??process.env.PROCESSCUBE_SERVER_CLIENT_SECRET,r=s?.scopes??process.env.PROCESSCUBE_SERVER_SCOPES??ft;if(!e)throw new Error("PROCESSCUBE_AUTHORITY_URL is not configured. Set the environment variable or pass authorityUrl.");if(!t)throw new Error("PROCESSCUBE_SERVER_CLIENT_ID is not configured. Set the environment variable or pass clientId.");if(!n)throw new Error("PROCESSCUBE_SERVER_CLIENT_SECRET is not configured. Set the environment variable or pass clientSecret.");return{authorityUrl:e,clientId:t,clientSecret:n,scopes:r}}function ht(){return N?Date.now()<N.expiresAt:!1}async function q(s){if(!s?.skipCache&&ht())return N.accessToken;let{authorityUrl:e,clientId:t,clientSecret:n,scopes:r}=ut(s);K.info("Fetching new server access token");let i=await fetch(`${e}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},redirect:"follow",body:new URLSearchParams({grant_type:"client_credentials",client_id:t,client_secret:n,scope:r}).toString(),cache:"no-store"});if(!i.ok){let c=await i.text().catch(()=>""),l=`Failed to fetch server access token: ${i.status} ${i.statusText}${c?` \u2014 ${c}`:""}`;throw K.error(l),new Error(l)}let a=await i.json();if(!a.access_token)throw new Error("Authority response did not contain an access_token");let o=a.expires_in;return o&&o>0?N={accessToken:a.access_token,expiresAt:Date.now()+o*lt*1e3}:N=null,K.info("Server access token fetched successfully"),a.access_token}async function Ms(s){let e=await q(s),t=ct(e);if(!t.sub)throw new Error('Server access token does not contain a "sub" claim');return{token:e,userId:t.sub}}var me=new pt("processcube_app_sdk:authority_client"),ye=class{authorityUrl;tokenOptions;constructor(e){let t=e?.authorityUrl??process.env.PROCESSCUBE_AUTHORITY_URL;if(!t)throw new Error("PROCESSCUBE_AUTHORITY_URL is not configured. Set the environment variable or pass authorityUrl.");this.authorityUrl=t.replace(/\/+$/,""),this.tokenOptions=e??{}}async request(e,t,n){let r=await q(this.tokenOptions),i=`${this.authorityUrl}${t}`;me.info(`Authority request: ${e} ${t}`);let a={Cookie:`access_token=${r}`,"Content-Type":"application/json"},o=await fetch(i,{method:e,headers:a,redirect:"follow",body:n!==void 0?JSON.stringify(n):void 0}),c;try{c=await o.json()}catch{c=void 0}return o.ok||me.error(`Authority request failed: ${e} ${t} \u2192 ${o.status} ${o.statusText}`),{ok:o.ok,status:o.status,data:c}}userAdminPath(e,t){return`/acr/username_password/admin/user/${encodeURIComponent(e)}/${t}`}async updateClaim(e,t,n){return this.request("PATCH",this.userAdminPath(e,"update/claim"),{claimName:t,claimValue:n})}async addScope(e,t){return this.request("PATCH",this.userAdminPath(e,"add/scope"),{scopeName:t})}async addGroup(e,t){return this.request("PATCH",this.userAdminPath(e,"add/group"),{groupName:t})}async deleteUser(e,t){return this.request("DELETE",this.userAdminPath(e,"delete"),{fullDelete:t?.fullDelete??!1})}};import{stat as Yt}from"node:fs";import{stat as zt,readdir as Kt}from"node:fs/promises";import{EventEmitter as qt}from"node:events";import*as p from"node:path";import{stat as mt,lstat as we,readdir as yt,realpath as wt}from"node:fs/promises";import{Readable as _t}from"node:stream";import{resolve as _e,relative as gt,join as Et,sep as It}from"node:path";var T={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},G={root:".",fileFilter:s=>!0,directoryFilter:s=>!0,type:T.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(G);var Te="READDIRP_RECURSIVE_ERROR",Tt=new Set(["ENOENT","EPERM","EACCES","ELOOP",Te]),ge=[T.DIR_TYPE,T.EVERYTHING_TYPE,T.FILE_DIR_TYPE,T.FILE_TYPE],Pt=new Set([T.DIR_TYPE,T.EVERYTHING_TYPE,T.FILE_DIR_TYPE]),kt=new Set([T.EVERYTHING_TYPE,T.FILE_DIR_TYPE,T.FILE_TYPE]),Rt=s=>Tt.has(s.code),St=process.platform==="win32",Ee=s=>!0,Ie=s=>{if(s===void 0)return Ee;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 Ee},V=class extends _t{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...G,...e},{root:n,type:r}=t;this._fileFilter=Ie(t.fileFilter),this._directoryFilter=Ie(t.directoryFilter);let i=t.lstat?we:mt;St?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=t.depth??G.depth,this._wantsDir=r?Pt.has(r):!1,this._wantsFile=r?kt.has(r):!1,this._wantsEverything=r===T.EVERYTHING_TYPE,this._root=_e(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 yt(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=_e(Et(t,r));n={path:gt(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){Rt(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 wt(n),i=await we(r);if(i.isFile())return"file";if(i.isDirectory()){let a=r.length;if(n.startsWith(r)&&n.substr(a,1)===It){let o=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return o.code=Te,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=T.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&&!ge.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${ge.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=s,new V(e)}import{watchFile as Ct,unwatchFile as ke,watch as xt}from"node:fs";import{open as bt,stat as Se,lstat as Nt,realpath as X}from"node:fs/promises";import*as y from"node:path";import{type as At}from"node:os";var vt="data",Z="end",Ce="close",B=()=>{};var H=process.platform,ee=H==="win32",Dt=H==="darwin",Ft=H==="linux",Ut=H==="freebsd",xe=At()==="OS400",_={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},P=_,Ot="watch",Lt={lstat:Nt,stat:Se},R="listeners",O="errHandlers",x="rawEmitters",Mt=[R,O,x],Wt=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"]),Bt=s=>Wt.has(y.extname(s).slice(1).toLowerCase()),Q=(s,e)=>{s instanceof Set?s.forEach(e):e(s)},A=(s,e,t)=>{let n=s[e];n instanceof Set||(s[e]=n=new Set([n])),n.add(t)},Ht=s=>e=>{let t=s[e];t instanceof Set?t.clear():delete s[e]},v=(s,e,t)=>{let n=s[e];n instanceof Set?n.delete(t):n===t&&delete s[e]},be=s=>s instanceof Set?s.size===0:!s,L=new Map;function Re(s,e,t,n,r){let i=(a,o)=>{t(s),r(a,o,{watchedPath:s}),o&&s!==o&&M(y.resolve(s,o),R,y.join(s,o))};try{return xt(s,{persistent:e.persistent},i)}catch(a){n(a);return}}var M=(s,e,t,n,r)=>{let i=L.get(s);i&&Q(i[e],a=>{a(t,n,r)})},$t=(s,e,t,n)=>{let{listener:r,errHandler:i,rawEmitter:a}=n,o=L.get(e),c;if(!t.persistent)return c=Re(s,t,r,i,a),c?c.close.bind(c):void 0;if(o)A(o,R,r),A(o,O,i),A(o,x,a);else{if(c=Re(s,t,M.bind(null,e,R),i,M.bind(null,e,x)),!c)return;c.on(P.ERROR,async l=>{let d=M.bind(null,e,O);if(o&&(o.watcherUnusable=!0),ee&&l.code==="EPERM")try{await(await bt(s,"r")).close(),d(l)}catch{}else d(l)}),o={listeners:r,errHandlers:i,rawEmitters:a,watcher:c},L.set(e,o)}return()=>{v(o,R,r),v(o,O,i),v(o,x,a),be(o.listeners)&&(o.watcher.close(),L.delete(e),Mt.forEach(Ht(o)),o.watcher=void 0,Object.freeze(o))}},J=new Map,jt=(s,e,t,n)=>{let{listener:r,rawEmitter:i}=n,a=J.get(e),o=a&&a.options;return o&&(o.persistent<t.persistent||o.interval>t.interval)&&(ke(e),a=void 0),a?(A(a,R,r),A(a,x,i)):(a={listeners:r,rawEmitters:i,options:t,watcher:Ct(e,t,(c,l)=>{Q(a.rawEmitters,f=>{f(P.CHANGE,e,{curr:c,prev:l})});let d=c.mtimeMs;(c.size!==l.size||d>l.mtimeMs||d===0)&&Q(a.listeners,f=>f(s,c))})},J.set(e,a)),()=>{v(a,R,r),v(a,x,i),be(a.listeners)&&(J.delete(e),ke(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=y.dirname(e),i=y.basename(e);this.fsw._getWatchedDir(r).add(i);let o=y.resolve(e),c={persistent:n.persistent};t||(t=B);let l;if(n.usePolling){let d=n.interval!==n.binaryInterval;c.interval=d&&Bt(i)?n.binaryInterval:n.interval,l=jt(e,o,c,{listener:t,rawEmitter:this.fsw._emitRaw})}else l=$t(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=y.dirname(e),i=y.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let c=async(d,f)=>{if(this.fsw._throttle(Ot,e,5)){if(!f||f.mtimeMs===0)try{let h=await Se(e);if(this.fsw.closed)return;let m=h.atimeMs,g=h.mtimeMs;if((!m||m<=g||g!==o.mtimeMs)&&this.fsw._emit(P.CHANGE,e,h),(Dt||Ft||Ut)&&o.ino!==h.ino){this.fsw._closeFile(d),o=h;let I=this._watchWithNodeFs(e,c);I&&this.fsw._addPathCloser(d,I)}else o=h}catch{this.fsw._remove(r,i)}else if(a.has(i)){let h=f.atimeMs,m=f.mtimeMs;(!h||h<=m||m!==o.mtimeMs)&&this.fsw._emit(P.CHANGE,e,f),o=f}}},l=this._watchWithNodeFs(e,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(P.ADD,e,0))return;this.fsw._emit(P.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 X(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(P.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,o),this.fsw._emit(P.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=y.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(vt,async f=>{if(this.fsw.closed){d=void 0;return}let h=f.path,m=y.join(e,h);if(l.add(h),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,e,m,h))){if(this.fsw.closed){d=void 0;return}(h===r||!r&&!c.has(h))&&(this.fsw._incrReadyCount(),m=y.join(i,y.relative(i,m)),this._addToNodeFs(m,t,n,a+1))}}).on(P.ERROR,this._boundHandleError),new Promise((f,h)=>{if(!d)return h();d.once(Z,()=>{if(this.fsw.closed){d=void 0;return}let m=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,m&&this._handleRead(e,!1,n,r,i,a,o)})})}async _handleDir(e,t,n,r,i,a,o){let c=this.fsw._getWatchedDir(y.dirname(e)),l=c.has(y.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!l&&this.fsw._emit(P.ADD_DIR,e,t),c.add(y.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,(m,g)=>{g&&g.mtimeMs===0||this._handleRead(m,!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 Lt[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,c))return a(),!1;let l=this.fsw.options.followSymlinks,d;if(c.isDirectory()){let f=y.resolve(e),h=l?await X(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 X(e):e;if(this.fsw.closed)return;let h=y.dirname(o.watchPath);if(this.fsw._getWatchedDir(h).add(o.watchPath),this.fsw._emit(P.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(y.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 te="/",Gt="//",Ue=".",Vt="..",Xt="string",Jt=/\\/g,Ne=/\/\//,Qt=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Zt=/^\.[/\\]/;function $(s){return Array.isArray(s)?s:[s]}var se=s=>typeof s=="object"&&s!==null&&!(s instanceof RegExp);function es(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 ts(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 Ae(s,e,t){let n=ts(e);for(let r=0;r<s.length;r++){let i=s[r];if(i(n,t))return!0}return!1}function ss(s,e){if(s==null)throw new TypeError("anymatch: specify first argument");let n=$(s).map(r=>es(r));return e==null?(r,i)=>Ae(n,r,i):Ae(n,e)}var ve=s=>{let e=$(s).flat();if(!e.every(t=>typeof t===Xt))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Oe)},De=s=>{let e=s.replace(Jt,te),t=!1;for(e.startsWith(Gt)&&(t=!0);e.match(Ne);)e=e.replace(Ne,te);return t&&(e=te+e),e},Oe=s=>De(p.normalize(De(s))),Fe=(s="")=>e=>typeof e=="string"?Oe(p.isAbsolute(e)?e:p.join(s,e)):e,ns=(s,e)=>p.isAbsolute(s)?s:p.join(e,s),rs=Object.freeze(new Set),ne=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Ue&&e!==Vt&&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 Kt(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=B,this.items=rs,Object.freeze(this)}},is="stat",os="lstat",re=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(Zt,""),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?is:os}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)}},ie=class extends qt{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?$(e.ignored):$([]),awaitWriteFinish:t===!0?n:typeof t=="object"?{...n,...t}:!1};xe&&(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=B,this._readyEmitted=!0,process.nextTick(()=>this.emit(_.READY)))},this._emitRaw=(...c)=>this.emit(_.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new W(this),Object.freeze(r)}_addIgnoredPath(e){if(se(e)){for(let t of this._ignoredPaths)if(se(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)se(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=ve(e);return r&&(i=i.map(a=>ns(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=ve(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)||Ue;e[i]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==_.ERROR&&this.emit(_.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;ee&&(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===_.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((c,l)=>{this.emit(...c),this.emit(_.ALL,...c),this._pendingUnlinks.delete(l)})},typeof r.atomic=="number"?r.atomic:100),this;e===_.ADD&&this._pendingUnlinks.has(t)&&(e=_.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===_.ADD||e===_.CHANGE)&&this._readyEmitted){let c=(l,d)=>{l?(e=_.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===_.CHANGE&&!this._throttle(_.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===_.ADD||e===_.ADD_DIR||e===_.CHANGE)){let c=r.cwd?p.join(r.cwd,t):t,l;try{l=await zt(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(_.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){Yt(c,(m,g)=>{if(m||!d.has(e)){m&&m.code!=="ENOENT"&&r(m);return}let I=Number(new Date);h&&g.size!==h.size&&(d.get(e).lastChange=I);let at=d.get(e);I-at.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&&Qt.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=(this.options.ignored||[]).map(Fe(n)),o=[...[...this._ignoredPaths].map(Fe(n)),...i];this._userIgnored=ss(o,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new re(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=p.resolve(e);return this._watched.has(t)||this._watched.set(t,new ne(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()===_.ADD)return;this._watched.delete(r),this._watched.delete(i);let f=n?_.UNLINK_DIR:_.UNLINK;l&&!this._isIgnored(r)&&this._emit(f,r),this._closePath(r)}_closePath(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:_.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},r=Pe(e,n);return this._streams.add(r),r.once(Ce,()=>{r=void 0}),r.once(Z,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};function Le(s,e={}){let t=new ie(e);return t.add(s),t}import{build as cs}from"esbuild";import{jwtDecode as ds}from"jwt-decode";import{fork as ls}from"node:child_process";import{existsSync as We,promises as fs}from"node:fs";import{basename as ae,dirname as Y,join as de,relative as Be}from"node:path";import{fileURLToPath as us}from"node:url";import{Issuer as hs,custom as ps}from"openid-client";import{Logger as ms}from"@5minds/processcube_engine_sdk";import{EngineClient as as}from"@5minds/processcube_engine_client";var oe=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",u=new as(oe);var ys={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},ws=.85,j=["external_task.ts","external_task.js"],D=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,E=new ms("processcube_app_sdk:external_task_adapter"),S={},le={},b,fe=!1,He=6,_s=3e5,gs=3e4,ce=10,Es=3e4,Me=10,Is=6e4;async function $e(s){if(s&&!We(s))throw new Error(`Invalid customExternalTasksDirPath. The given path '${s}' does not exist`);ps.setHttpOptionsDefaults({timeout:1e5});let e=await ze();b=he(e),await Ke(e);let t=ks(s);Le(t).on("add",async n=>{if(j.includes(ae(n)))return ue(n,t)}).on("change",async n=>{if(j.includes(ae(n)))return Ts(n,t)}).on("unlink",async n=>{j.includes(ae(n))&&je(n)}).on("error",n=>E.error(`Watcher error: ${n}`))}async function ue(s,e){let t=Y(s);if((await fs.readdir(t)).filter(f=>j.includes(f)).length>1){E.error(`Multiple external task files found in directory ${t}. Stopping all external task workers for this directory.`),S[t]&&je(s);return}let i=await qe(s),a=Be(e,t),o=Ge(a),c=typeof __dirname<"u"?__dirname:Y(us(import.meta.url)),l=de(c,"lib/ExternalTaskWorkerProcess.cjs"),d=ls(l,{stdio:["pipe","inherit","inherit","ipc"],env:{...process.env,PROCESSCUBE_ENGINE_URL:oe}});S[t]=d,d.once("disconnect",()=>{delete S[t]}),d.on("error",f=>{E.error(`External Task Worker process error for ${o}`,{error:f,topic:o,workerDirectory:t})}),d.on("exit",(f,h)=>{if(E.info(`External Task Worker process exited for ${o}`,{code:f,signal:h,topic:o,workerDirectory:t}),delete S[t],f===3||f===4)if(Rs(t)){let m=le[t]?.count??1,g=Math.min(1e3*Math.pow(2,m-1),gs);E.info(`Scheduling restart for ${o} in ${g}ms (attempt ${m}/${He})`,{delay:g,restartCount:m,exitCode:f,topic:o,workerDirectory:t}),setTimeout(async()=>{try{if(D&&!fe){E.info("Token refresh cycle is not active, restarting it before worker restart");let I=await ze();b=he(I),await Ke(I)}await ue(s,e)}catch(I){E.error(`Failed to restart External Task Worker process for ${o}`,{error:I,topic:o,workerDirectory:t})}},g)}else E.error(`External Task Worker process for ${o} reached maximum restart attempts`,{exitCode:f,topic:o,workerDirectory:t})}),d.send({action:"create",payload:{topic:o,identity:b,moduleString:i,workerPath:s}})}async function Ts(s,e){let t=Y(s),n=S[t];if(!n)return ue(s,e);let r=await qe(s),i=Be(e,t),a=Ge(i);n.send({action:"restart",payload:{topic:a,identity:b,moduleString:r,workerPath:s}})}function je(s){let e=Y(s),t=S[e];t&&t.kill()}async function Ye(){if(!D)return null;if(!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID||!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET){let n=new Error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing. For help, please refer to our documentation on environment variables at: https://processcube.io/docs/app-sdk/samples/nextjs/external-task-adapter-with-nextjs#authority");throw E.error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing",{err:n}),n}let s=await hs.discover(process.env.PROCESSCUBE_AUTHORITY_URL);return await new s.Client({client_id:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID,client_secret:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET}).grant({grant_type:"client_credentials",scope:"engine_etw"})}async function ze(){if(!D)return null;for(let s=1;s<=ce;s++)try{return await Ye()}catch(e){let t=Math.min(1e3*Math.pow(2,s-1),Es);if(E.error(`Failed to fetch initial token set (attempt ${s}/${ce}), retrying in ${t}ms`,{error:e,attempt:s,delay:t}),s===ce)throw e;await new Promise(n=>setTimeout(n,t))}return null}function he(s){if(!D||s===null)return ys;let e=s.access_token,t=ds(e);return{token:s.access_token,userId:t.sub}}async function Ke(s){if(!D||s===null||fe)return;fe=!0;let e=0,n=await Ps(s)*ws*1e3,r=async()=>{try{let i=await Ye();b=he(i);for(let[a,o]of Object.entries(S))try{o.send({action:"updateIdentity",payload:{identity:b}})}catch(c){E.warn(`Failed to send identity update to worker process ${a}`,{sendError:c})}e=0,setTimeout(r,n)}catch(i){e++;let a=Math.min(1e3*Math.pow(2,e-1),Is);e<=Me?E.error(`Could not refresh identity (attempt ${e}/${Me}), retrying in ${a}ms`,{error:i,attempt:e,delay:a}):E.error(`Could not refresh identity (attempt ${e}), continuing to retry every ${a}ms`,{error:i,attempt:e,delay:a}),setTimeout(r,a)}};setTimeout(r,n)}async function qe(s){let e=await cs({entryPoints:[s],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(e.errors.length>0)throw E.error(`Could not transpile file at '${s}'`,{errors:e.errors}),new Error(`Could not transpile file at '${s}'`);return e.warnings.length>0&&E.warn(`Transpiled file at '${s}' with warnings`,{warnings:e.warnings}),e.outputFiles[0].text}async function Ps(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 Ge(s){return s.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function ks(s){let e,t=[s,de(process.cwd(),"app"),de(process.cwd(),"src","app")];for(let n of t)if(n&&We(n)){e=n;break}if(!e)throw new Error("Could not find external tasks directory");return e}function Rs(s){let e=Date.now(),t=le[s];return!t||e-t.timestamp>_s?(le[s]={count:1,timestamp:e},!0):t.count>=He?!1:(t.count++,!0)}function Tn(){return u}import{getToken as Ve}from"next-auth/jwt";import{ResponseCookies as Ss}from"next/dist/compiled/@edge-runtime/cookies/index.js";import{cookies as z,headers as Xe}from"next/headers.js";async function w(){let s=await Ve({req:{cookies:await z(),headers:await Xe()}});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 z()).toString()}}),n=new Ss(t.headers);if(n.getAll().length){let r=!1;try{for(let i of n.getAll())(await z()).set(i.name,i.value,{...i})}catch{r=!0}if(s=await Ve({req:{cookies:r?n:await z(),headers:await Xe()}}),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 U(){try{return w()}catch{return}}async function Je(s){let e=await U();return(await u.processInstances.query({processInstanceId:s},{identity:e,includeXml:!0})).processInstances[0]}async function Qe(s,e={sortSettings:{sortBy:F.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await u.flowNodeInstances.query({processInstanceId:s},{...e,identity:e.identity??await U()})).flowNodeInstances}async function Ze(s){let e=await U();return(await u.flowNodeInstances.query({triggeredByFlowNodeInstance:s},{identity:e})).flowNodeInstances}async function et(s,e,t){let n=await U();await u.processInstances.retryProcessInstance(s,{flowNodeInstanceId:e,newStartToken:t,identity:n})}async function tt(s){let e=await U();await u.processInstances.terminateProcessInstance(s,e)}async function An(s={options:{identity:!0}}){switch(s.options.identity){case!0:s.options.identity=await w();break;case!1:s.options.identity=void 0;break;case void 0:s.options.identity=await w();break}return await u.processInstances.query({...s?.query,state:F.ProcessInstances.ProcessInstanceState.running},s?.options)}async function vn(s={},e=!0){let{processInstanceId:t}=s,n=typeof e=="boolean"?e==!0?await w():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 k}from"@5minds/processcube_engine_client";import{mapUserTask as st,mapUserTaskList as C}from"../common/index.mjs";async function Bn(s={},e=!0){let{correlationId:t,processInstanceId:n,flowNodeId:r}=s,i=typeof e=="boolean"?e==!0?await w():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,m=n!==void 0&&d.processInstanceId!==n,g=r!==void 0&&d.flowNodeId!==r;if(f||h||m||g)return;let I=await xs(d.flowNodeInstanceId,{identity:i});return u.notification.removeSubscription(c,i),I===null?o(new Error(`UserTask with instance ID "${d.flowNodeInstanceId}" does not exist.`)):a(I)},{identity:i}),l=await Cs({correlationId:t,processInstanceId:n,flowNodeId:r,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});l.userTasks.length>0&&(u.notification.removeSubscription(c,i),a(l.userTasks[0]))})}async function Hn(s,e={},t={},n=!0){let r=typeof n=="boolean"?n==!0?await w():void 0:n;await u.userTasks.finishUserTask(s,t,r);let i={state:k.FlowNodeInstances.FlowNodeInstanceState.suspended,...e},a=await u.userTasks.query(i,{identity:r});return st(a.userTasks[0])}async function Cs(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await w();break;case!1:e.identity=void 0;break;case void 0:e.identity=await w();break}let t=await u.userTasks.query(s,e);return C(t)}async function $n(s={identity:!0}){switch(s?.identity){case!0:s.identity=await w();break;case!1:s.identity=void 0;break;case void 0:s.identity=await w();break}let e=await u.userTasks.query({state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},s);return C(e)}async function jn(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await w();break;case!1:e.identity=void 0;break;case void 0:e.identity=await w();break}let t=await u.userTasks.query({processInstanceId:s,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return C(t)}async function Yn(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await w();break;case!1:e.identity=void 0;break;case void 0:e.identity=await w();break}let t=await u.userTasks.query({flowNodeId:s,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return C(t)}async function xs(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await w();break;case!1:e.identity=void 0;break;case void 0:e.identity=await w();break}let t=await u.userTasks.query({flowNodeInstanceId:s,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},{...e,limit:1});return t.userTasks.length===0?null:st(t.userTasks[0])}async function zn(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await w();break;case!1:e.identity=void 0;break;case void 0:e.identity=await w();break}let t=await u.userTasks.query({correlationId:s,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return C(t)}async function Kn(s,e){let t=s||await w(),n=await u.userTasks.query({state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:t,...e}),r=n.userTasks.filter(i=>i.actualOwnerId===t.userId);return n.userTasks=r,C(n)}async function qn(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 Vn(s,e){let t=s||await w(),n=await u.userTasks.query({state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:t,...e}),r=n.userTasks.filter(i=>i.assignedUserIds?.includes(t.userId));return n.userTasks=r,C(n)}import{PHASE_DEVELOPMENT_SERVER as bs,PHASE_PRODUCTION_BUILD as Ns,PHASE_PRODUCTION_SERVER as As}from"next/dist/shared/lib/constants.js";var nt=!1,pe=!1;function Zn(s={}){let{applicationSdk:e,...t}=s;return async(n,r)=>{pe=pe||n===Ns;let i=n===bs||n===As;return e?.useExternalTasks&&i&&!nt&&!pe&&(nt=!0,await $e(e?.customExternalTasksDirPath)),{...t,experimental:{...t.experimental,serverComponentsExternalPackages:[...t.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}import{redirect as vs}from"next/navigation.js";function nr(s){vs(s)}async function or(...s){return await u.processModels.startProcessInstance(...s)}async function rt(...s){await u.manualTasks.finishManualTask(...s)}async function it(...s){await u.userTasks.finishUserTask(...s)}async function ot(...s){await u.untypedTasks.finishTask(...s)}import{DataModels as Ds}from"@5minds/processcube_engine_client";async function Fs(){try{return w()}catch{return}}var _r=async(s,e)=>{let t=await Fs();e==="bpmn:UserTask"?await it(s,{},t):e==="bpmn:ManualTask"?await rt(s,t):e==="bpmn:Task"?await ot(s,t):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${e}`)},gr=async s=>{await tt(s)},Er=async(s,e,t)=>{await et(s,e,t)},Ir=async s=>Je(s),Tr=async s=>Qe(s,{sortSettings:{sortBy:Ds.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),Pr=async s=>Ze(s);export{ye as AuthorityClient,Gn as cancelReservedUserTask,rt as finishManualTask,_r as finishTask,ot as finishUntypedTask,it as finishUserTask,Hn as finishUserTaskAndGetNext,An as getActiveProcessInstances,Vn as getAssignedUserTasksByIdentity,Tn as getEngineClient,Tr as getFlowNodeInstances,Qe as getFlowNodeInstancesByProcessInstanceId,Ze as getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,w as getIdentity,Ir as getProcessInstance,Je as getProcessInstanceById,Kn as getReservedUserTasksByIdentity,q as getServerAccessToken,Ms as getServerIdentity,Pr as getTriggeredFlowNodeInstances,Cs as getUserTasks,xs as getWaitingUserTaskByFlowNodeInstanceId,$n as getWaitingUserTasks,zn as getWaitingUserTasksByCorrelationId,Yn as getWaitingUserTasksByFlowNodeId,jn as getWaitingUserTasksByProcessInstanceId,nr as navigateToUrl,qn as reserveUserTask,Er as retryProcess,et as retryProcessInstance,or as startProcess,gr as terminateProcess,tt as terminateProcessInstance,vn as waitForProcessEnd,Bn as waitForUserTask,Zn as withApplicationSdk};
|
|
2
2
|
/*! Bundled license information:
|
|
3
3
|
|
|
4
4
|
chokidar/esm/index.js:
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { ServerAccessTokenOptions } from './getServerIdentity';
|
|
2
|
+
export interface AuthorityClientOptions extends ServerAccessTokenOptions {
|
|
3
|
+
/**
|
|
4
|
+
* Base URL of the Authority. Defaults to `process.env.PROCESSCUBE_AUTHORITY_URL`.
|
|
5
|
+
*/
|
|
6
|
+
authorityUrl?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface AuthorityResponse<T = unknown> {
|
|
9
|
+
ok: boolean;
|
|
10
|
+
status: number;
|
|
11
|
+
data: T;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Client for the ProcessCube Authority API.
|
|
15
|
+
*
|
|
16
|
+
* **Stufe 1 — Allgemein:** Use {@link request} for arbitrary Authority API calls.
|
|
17
|
+
* The client handles authentication (access token in cookie) automatically.
|
|
18
|
+
*
|
|
19
|
+
* **Stufe 2 — ProcessCube-spezifisch:** Convenience methods for common user admin operations:
|
|
20
|
+
* {@link updateClaim}, {@link addScope}, {@link addGroup}, {@link deleteUser}.
|
|
21
|
+
*/
|
|
22
|
+
export declare class AuthorityClient {
|
|
23
|
+
private readonly authorityUrl;
|
|
24
|
+
private readonly tokenOptions;
|
|
25
|
+
constructor(options?: AuthorityClientOptions);
|
|
26
|
+
/**
|
|
27
|
+
* Sends an authenticated request to the Authority API.
|
|
28
|
+
*
|
|
29
|
+
* The access token is automatically fetched (and cached) via {@link getServerAccessToken}.
|
|
30
|
+
* It is sent as a cookie (`access_token=...`).
|
|
31
|
+
*
|
|
32
|
+
* @param method HTTP method (GET, POST, PATCH, PUT, DELETE)
|
|
33
|
+
* @param path Path relative to the authority URL (e.g. `/acr/username_password/admin/user/...`)
|
|
34
|
+
* @param body Optional request body (will be JSON-serialized)
|
|
35
|
+
* @returns Typed {@link AuthorityResponse} with status, ok flag, and parsed JSON data.
|
|
36
|
+
*/
|
|
37
|
+
request<T = unknown>(method: string, path: string, body?: unknown): Promise<AuthorityResponse<T>>;
|
|
38
|
+
private userAdminPath;
|
|
39
|
+
/**
|
|
40
|
+
* Updates a claim on a user account.
|
|
41
|
+
*
|
|
42
|
+
* @param username The username (typically the email address)
|
|
43
|
+
* @param claimName Name of the claim to set
|
|
44
|
+
* @param claimValue Value of the claim
|
|
45
|
+
*/
|
|
46
|
+
updateClaim(username: string, claimName: string, claimValue: unknown): Promise<AuthorityResponse>;
|
|
47
|
+
/**
|
|
48
|
+
* Adds a scope to a user account.
|
|
49
|
+
*
|
|
50
|
+
* @param username The username (typically the email address)
|
|
51
|
+
* @param scopeName Name of the scope to add
|
|
52
|
+
*/
|
|
53
|
+
addScope(username: string, scopeName: string): Promise<AuthorityResponse>;
|
|
54
|
+
/**
|
|
55
|
+
* Adds a user to a group.
|
|
56
|
+
*
|
|
57
|
+
* @param username The username (typically the email address)
|
|
58
|
+
* @param groupName Name of the group to add the user to
|
|
59
|
+
*/
|
|
60
|
+
addGroup(username: string, groupName: string): Promise<AuthorityResponse>;
|
|
61
|
+
/**
|
|
62
|
+
* Deletes (or soft-deletes) a user account.
|
|
63
|
+
*
|
|
64
|
+
* @param username The username (typically the email address)
|
|
65
|
+
* @param options Delete options. `fullDelete: false` (default) performs a soft delete.
|
|
66
|
+
*/
|
|
67
|
+
deleteUser(username: string, options?: {
|
|
68
|
+
fullDelete?: boolean;
|
|
69
|
+
}): Promise<AuthorityResponse<{
|
|
70
|
+
username?: string;
|
|
71
|
+
}>>;
|
|
72
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { DataModels } from '@5minds/processcube_engine_sdk';
|
|
2
|
+
export interface ServerAccessTokenOptions {
|
|
3
|
+
/**
|
|
4
|
+
* OAuth2 Client ID. Defaults to `process.env.PROCESSCUBE_SERVER_CLIENT_ID`.
|
|
5
|
+
*/
|
|
6
|
+
clientId?: string;
|
|
7
|
+
/**
|
|
8
|
+
* OAuth2 Client Secret. Defaults to `process.env.PROCESSCUBE_SERVER_CLIENT_SECRET`.
|
|
9
|
+
*/
|
|
10
|
+
clientSecret?: string;
|
|
11
|
+
/**
|
|
12
|
+
* Space-separated OAuth2 scopes. Defaults to `process.env.PROCESSCUBE_SERVER_SCOPES`
|
|
13
|
+
* or `'upe_admin engine_read engine_write'`.
|
|
14
|
+
*/
|
|
15
|
+
scopes?: string;
|
|
16
|
+
/**
|
|
17
|
+
* Authority URL. Defaults to `process.env.PROCESSCUBE_AUTHORITY_URL`.
|
|
18
|
+
*/
|
|
19
|
+
authorityUrl?: string;
|
|
20
|
+
/**
|
|
21
|
+
* Skip the token cache and always fetch a fresh token.
|
|
22
|
+
*/
|
|
23
|
+
skipCache?: boolean;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Fetches a server-to-server access token using the OAuth2 Client Credentials flow.
|
|
27
|
+
*
|
|
28
|
+
* Tokens are cached and reused until they expire (with a safety buffer).
|
|
29
|
+
* Throws on authentication errors (e.g. invalid credentials, blocked client).
|
|
30
|
+
*
|
|
31
|
+
* @param options Optional overrides for authority URL, credentials, and scopes.
|
|
32
|
+
* @returns The access token string.
|
|
33
|
+
*/
|
|
34
|
+
export declare function getServerAccessToken(options?: ServerAccessTokenOptions): Promise<string>;
|
|
35
|
+
/**
|
|
36
|
+
* Returns a server-to-server {@link DataModels.Iam.Identity} using the Client Credentials flow.
|
|
37
|
+
*
|
|
38
|
+
* Useful in External Tasks or other server-side code that needs to act as a service account
|
|
39
|
+
* rather than an end user.
|
|
40
|
+
*
|
|
41
|
+
* @param options Optional overrides for authority URL, credentials, and scopes.
|
|
42
|
+
* @returns An Identity with `token` and `userId`.
|
|
43
|
+
*/
|
|
44
|
+
export declare function getServerIdentity(options?: ServerAccessTokenOptions): Promise<DataModels.Iam.Identity>;
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
export * from './AuthorityClient';
|
|
1
2
|
export { ExternalTaskConfig } from './ExternalTaskAdapter';
|
|
2
3
|
export * from './getEngineClient';
|
|
3
4
|
export * from './getIdentity';
|
|
5
|
+
export * from './getServerIdentity';
|
|
4
6
|
export * from './ProcessInstanceFunctions';
|
|
5
7
|
export * from './UserTaskFunctions';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@5minds/processcube_app_sdk",
|
|
3
|
-
"version": "8.
|
|
3
|
+
"version": "8.5.0",
|
|
4
4
|
"description": "The SDK for ProcessCube Apps",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "build/common/index.cjs",
|
|
@@ -10,16 +10,19 @@
|
|
|
10
10
|
"exports": {
|
|
11
11
|
".": {
|
|
12
12
|
"types": "./common.d.ts",
|
|
13
|
+
"import": "./build/common/index.mjs",
|
|
13
14
|
"require": "./build/common/index.cjs",
|
|
14
15
|
"default": "./build/common/index.mjs"
|
|
15
16
|
},
|
|
16
17
|
"./server": {
|
|
17
18
|
"types": "./server.d.ts",
|
|
19
|
+
"import": "./build/server/index.mjs",
|
|
18
20
|
"require": "./build/server/index.cjs",
|
|
19
21
|
"default": "./build/server/index.mjs"
|
|
20
22
|
},
|
|
21
23
|
"./client": {
|
|
22
24
|
"types": "./client.d.ts",
|
|
25
|
+
"import": "./build/client/index.mjs",
|
|
23
26
|
"require": "./build/client/index.cjs",
|
|
24
27
|
"default": "./build/client/index.mjs"
|
|
25
28
|
},
|
|
@@ -27,7 +30,8 @@
|
|
|
27
30
|
"import": "./build/client/components/*.css",
|
|
28
31
|
"require": "./build/client/components/*.css",
|
|
29
32
|
"default": "./build/client/components/*.css"
|
|
30
|
-
}
|
|
33
|
+
},
|
|
34
|
+
"./package.json": "./package.json"
|
|
31
35
|
},
|
|
32
36
|
"scripts": {
|
|
33
37
|
"build": "concurrently -n=build:code,build:types,build:css \"NODE_ENV=development node build.js\" \"npm run build:types\" \"NODE_ENV=development node build-css.cjs\"",
|