@amaster.ai/workflow-client 1.1.72 → 1.1.74

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/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var httpClient=require('@amaster.ai/http-client'),eventsourceParser=require('eventsource-parser');function b(t){if(!t)return {inputs:{},response_mode:"blocking",user:"anonymous"};if(typeof t=="object"&&x(t)){let e=t;return {inputs:e.inputs||{},response_mode:e.response_mode||"blocking",user:e.user||"anonymous",files:e.files,trace_id:e.trace_id,usage:e.usage,usage_detail:e.usage_detail,callback:e.callback}}return {inputs:t,response_mode:"blocking",user:"anonymous"}}function x(t){let e=["inputs","response_mode","user","files","trace_id","usage","usage_detail","callback"],r=["inputs","response_mode","user","files","trace_id"],s=Object.keys(t);return r.some(a=>a in t)?true:s.length>0&&s.every(a=>e.includes(a))}function f(t){return !t||t.includes("/")?{data:null,error:{status:400,message:"Invalid workflowName: use workflow YAML filename without extension (no subpaths)"},status:400}:null}function v(t=httpClient.createHttpClient()){return {async run(e,r){let s=f(e);if(s)return s;let a=b(r),n=await t.request({url:`/api/runworkflow/${e}`,method:"post",headers:{"Content-Type":"application/json"},data:a});if(n.data?.data){let o=n.data.data;return {...n,data:{task_id:n.data.task_id||"",workflow_run_id:n.data.workflow_run_id||"",status:o.status||"unknown",outputs:o.outputs||{},error:o.error||null,elapsed_time:o.elapsed_time||0,total_tokens:o.total_tokens||0,total_steps:o.total_steps||0,created_at:o.created_at||0,finished_at:o.finished_at||0,...o.usage?{usage:o.usage}:{}}}}return {data:null,error:n.error||{status:n.status,message:"Invalid workflow response structure"},status:n.status}},async runAsync(e,r){let s=f(e);if(s)return s;let a=b(r);a.response_mode="async";let n=await t.request({url:`/api/runworkflow/${e}`,method:"post",headers:{"Content-Type":"application/json"},data:a});return n.data?.async_run_id?n:{data:null,error:n.error||{status:n.status,message:"Invalid workflow async run response structure"},status:n.status}},async getAsyncRun(e,r){let s=f(e);if(s)return s;let a=await t.request({url:`/api/runworkflow/${e}/async-runs/${r}`,method:"get"});return a.data?.async_run_id?a:{data:null,error:a.error||{status:a.status,message:"Invalid workflow async run detail response structure"},status:a.status}},async getRun(e,r,s={}){let a=f(e);if(a)return a;let n=await t.request({url:`/api/runworkflow/${e}/runs/${r}`,method:"get",params:{...s.usage!==void 0?{usage:s.usage}:{},...s.usage_detail!==void 0?{usage_detail:s.usage_detail}:{}}});if(n.data?.data){let o=n.data.data;return {...n,data:{task_id:"",workflow_run_id:n.data.workflow_run_id||r,status:o.status||"unknown",outputs:o.outputs||{},error:o.error||null,elapsed_time:o.elapsed_time||0,total_tokens:o.total_tokens||0,total_steps:o.total_steps||0,created_at:o.created_at||0,finished_at:o.finished_at||0,...o.usage?{usage:o.usage}:{}}}}return {data:null,error:n.error||{status:n.status,message:"Invalid workflow run detail response structure"},status:n.status}}}}var d=class extends Error{constructor(e,r,s){super(e),this.name="ChatflowStreamError",this.status=r,this.details=s;}};function W(t,e){let r=t.trim();if(!r||r.includes("/"))throw new d(`Invalid ${e}: use a non-empty value without subpaths`,400);return encodeURIComponent(r)}function w(t){return `/api/runchatflow/${W(t,"chatflowName")}`}function T(t,e){let r=t?.trim().replace(/\/+$/,"");return r?`${r}${e}`:e}function C(t,e){return {...t,inputs:t.inputs??{},response_mode:e}}async function A(t){let e=await t.text();if(!e)return null;try{return JSON.parse(e)}catch{return e}}function E(t,e){if(e&&typeof e=="object"){let r=e;for(let s of ["message","error","detail"])if(typeof r[s]=="string"&&r[s])return r[s]}return typeof e=="string"&&e?e:`Chatflow stream request failed with status ${t}`}function I(t=httpClient.createHttpClient(),e={}){return {async run(r,s){try{return await t.request({url:w(r),method:"post",headers:{"Content-Type":"application/json"},data:C(s,"blocking")})}catch(a){return {data:null,error:{status:400,message:a instanceof Error?a.message:String(a)},status:400}}},async*stream(r,s,a={}){let n=e.fetch??globalThis.fetch?.bind(globalThis);if(typeof n!="function")throw new d("Fetch API not found. Provide ChatflowClientOptions.fetch.",0);let o=new Headers(e.headers);o.set("Accept","text/event-stream"),o.set("Content-Type","application/json");let g=e.getAccessToken?.();g&&o.set("Authorization",`Bearer ${g}`);let i=await n(T(e.baseURL,w(r)),{method:"POST",headers:o,credentials:e.credentials??"include",body:JSON.stringify(C(s,"streaming")),signal:a.signal});if(!i.ok){let l=await A(i);throw i.status===401&&e.onUnauthorized?.(),new d(E(i.status,l),i.status,l)}if(!i.body)throw new d("Chatflow stream response has no body",i.status);let p=i.body.getReader(),k=new TextDecoder,c=[],m=[],R=false,_=eventsourceParser.createParser({onEvent(l){if(!(!l.data||l.data==="[DONE]"))try{let u=JSON.parse(l.data);u&&typeof u=="object"&&typeof u.event=="string"&&c.push(u);}catch(u){m.push(u instanceof Error?u:new Error(String(u)));}}});try{for(;;){let{done:l,value:u}=await p.read();l?(_.feed(k.decode()),R=!0):_.feed(k.decode(u,{stream:!0}));let y=m.shift();if(y)throw new d(`Failed to parse chatflow SSE event: ${y.message}`,i.status);for(;c.length>0;){let h=c.shift();h&&(yield h);}if(l)break}}finally{R||await p.cancel(),p.releaseLock();}},async stop(r,s,a={}){try{return await t.request({url:`${w(r)}/tasks/${W(s,"taskId")}/stop`,method:"post",headers:{"Content-Type":"application/json"},data:a})}catch(n){return {data:null,error:{status:400,message:n instanceof Error?n.message:String(n)},status:400}}}}}exports.ChatflowStreamError=d;exports.createChatflowClient=I;exports.createWorkflowClient=v;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var httpClient=require('@amaster.ai/http-client'),eventsourceParser=require('eventsource-parser');function v(r){if(!r)return {inputs:{},response_mode:"blocking",user:"anonymous"};if(typeof r=="object"&&T(r)){let e=r;return {inputs:e.inputs||{},response_mode:e.response_mode||"blocking",user:e.user||"anonymous",files:e.files,trace_id:e.trace_id,usage:e.usage,usage_detail:e.usage_detail,callback:e.callback}}return {inputs:r,response_mode:"blocking",user:"anonymous"}}function T(r){let e=["inputs","response_mode","user","files","trace_id","usage","usage_detail","callback"],s=["inputs","response_mode","user","files","trace_id"],a=Object.keys(r);return s.some(o=>o in r)?true:a.length>0&&a.every(o=>e.includes(o))}function w(r){return !r||r.includes("/")?{data:null,error:{status:400,message:"Invalid workflowName: use workflow YAML filename without extension (no subpaths)"},status:400}:null}function E(r=httpClient.createHttpClient()){return {async run(e,s){let a=w(e);if(a)return a;let o=v(s),t=await r.request({url:`/api/runworkflow/${e}`,method:"post",headers:{"Content-Type":"application/json"},data:o});if(t.data?.data){let n=t.data.data;return {...t,data:{task_id:t.data.task_id||"",workflow_run_id:t.data.workflow_run_id||"",status:n.status||"unknown",outputs:n.outputs||{},error:n.error||null,elapsed_time:n.elapsed_time||0,total_tokens:n.total_tokens||0,total_steps:n.total_steps||0,created_at:n.created_at||0,finished_at:n.finished_at||0,...n.usage?{usage:n.usage}:{}}}}return {...t,data:null,error:t.error||{status:t.status,message:"Invalid workflow response structure"},status:t.status}},async runAsync(e,s){let a=w(e);if(a)return a;let o=v(s);o.response_mode="async";let t=await r.request({url:`/api/runworkflow/${e}`,method:"post",headers:{"Content-Type":"application/json"},data:o});return t.data?.async_run_id?t:{...t,data:null,error:t.error||{status:t.status,message:"Invalid workflow async run response structure"},status:t.status}},async getAsyncRun(e,s){let a=w(e);if(a)return a;let o=await r.request({url:`/api/runworkflow/${e}/async-runs/${s}`,method:"get"});return o.data?.async_run_id?o:{...o,data:null,error:o.error||{status:o.status,message:"Invalid workflow async run detail response structure"},status:o.status}},async getRun(e,s,a={}){let o=w(e);if(o)return o;let t=await r.request({url:`/api/runworkflow/${e}/runs/${s}`,method:"get",params:{...a.usage!==void 0?{usage:a.usage}:{},...a.usage_detail!==void 0?{usage_detail:a.usage_detail}:{}}});if(t.data?.data){let n=t.data.data;return {...t,data:{task_id:"",workflow_run_id:t.data.workflow_run_id||s,status:n.status||"unknown",outputs:n.outputs||{},error:n.error||null,elapsed_time:n.elapsed_time||0,total_tokens:n.total_tokens||0,total_steps:n.total_steps||0,created_at:n.created_at||0,finished_at:n.finished_at||0,...n.usage?{usage:n.usage}:{}}}}return {...t,data:null,error:t.error||{status:t.status,message:"Invalid workflow run detail response structure"},status:t.status}}}}var d=class extends Error{constructor(e,s,a){super(e),this.name="ChatflowStreamError",this.status=s,this.details=a;}};function S(r,e){let s=r.trim();if(!s||s.includes("/"))throw new d(`Invalid ${e}: use a non-empty value without subpaths`,400);return encodeURIComponent(s)}function m(r){return `/api/runchatflow/${S(r,"chatflowName")}`}function U(r,e){let s=r?.trim().replace(/\/+$/,"");return s?`${s}${e}`:e}function x(r,e){return {...r,inputs:r.inputs??{},response_mode:e}}async function $(r){let e=await r.text();if(!e)return null;try{return JSON.parse(e)}catch{return e}}function D(r,e){if(e&&typeof e=="object"){let s=e;for(let a of ["message","error","detail"])if(typeof s[a]=="string"&&s[a])return s[a]}return typeof e=="string"&&e?e:`Chatflow stream request failed with status ${r}`}function N(r=httpClient.createHttpClient(),e={}){return {async run(s,a){try{return await r.request({url:m(s),method:"post",headers:{"Content-Type":"application/json"},data:x(a,"blocking")})}catch(o){return {data:null,error:{status:400,message:o instanceof Error?o.message:String(o)},status:400}}},async*stream(s,a,o={}){await e.beforeStream?.();let t=e.requestScope,n=t?.capture(),R=e.fetch??globalThis.fetch?.bind(globalThis);if(typeof R!="function")throw new d("Fetch API not found. Provide ChatflowClientOptions.fetch.",0);let f=new Headers(e.headers);f.set("Accept","text/event-stream"),f.set("Content-Type","application/json");let _=e.getAccessToken?.();if(_&&f.set("Authorization",`Bearer ${_}`),t&&n){let u=t.headers(n,Object.fromEntries(f.entries()));for(let[c,g]of Object.entries(u))f.set(c,g);}let y=typeof AbortController>"u"?void 0:new AbortController,p=()=>y?.abort(),O=t&&n?t.onInvalidate(n,p):void 0;o.signal?.addEventListener("abort",p,{once:true}),o.signal?.aborted&&p();try{let u=await R(U(e.baseURL,m(s)),{method:"POST",headers:f,credentials:e.credentials??"include",body:JSON.stringify(x(a,"streaming")),signal:y?.signal??o.signal??n?.signal});if(n&&t.assertCurrent(n),!u.ok){let l=await $(u);throw u.status===401&&e.onUnauthorized?.(),new d(D(u.status,l),u.status,l)}if(!u.body)throw new d("Chatflow stream response has no body",u.status);let c=u.body.getReader(),g=new TextDecoder,k=[],h=[],b=!1,C=eventsourceParser.createParser({onEvent(l){if(!(!l.data||l.data==="[DONE]"))try{let i=JSON.parse(l.data);i&&typeof i=="object"&&typeof i.event=="string"&&k.push(i);}catch(i){h.push(i instanceof Error?i:new Error(String(i)));}}});try{for(;;){let{done:l,value:i}=await c.read();n&&t.assertCurrent(n),l?(C.feed(g.decode()),b=!0):C.feed(g.decode(i,{stream:!0}));let W=h.shift();if(W)throw new d(`Failed to parse chatflow SSE event: ${W.message}`,u.status);for(;k.length>0;){let q=k.shift();q&&(n&&t.assertCurrent(n),yield q);}if(l)break}}finally{b||await c.cancel(),c.releaseLock();}}finally{O?.(),o.signal?.removeEventListener("abort",p);}},async stop(s,a,o={}){try{return await r.request({url:`${m(s)}/tasks/${S(a,"taskId")}/stop`,method:"post",headers:{"Content-Type":"application/json"},data:o})}catch(t){return {data:null,error:{status:400,message:t instanceof Error?t.message:String(t)},status:400}}}}}exports.ChatflowStreamError=d;exports.createChatflowClient=N;exports.createWorkflowClient=E;//# sourceMappingURL=index.cjs.map
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/workflow-client.ts","../src/chatflow-client.ts"],"names":["normalizeRunRequest","inputs","isWorkflowRunRequest","req","value","requestKeys","structuralRequestKeys","keys","key","validateWorkflowName","workflowName","createWorkflowClient","http","createHttpClient","validationError","normalizedRequest","response","innerData","asyncRunId","workflowRunId","options","ChatflowStreamError","message","status","details","validatePathSegment","fieldName","normalized","chatflowPath","chatflowName","resolveRequestURL","baseURL","path","normalizedBaseURL","normalizeRequest","request","responseMode","parseErrorResponse","text","errorMessage","payload","createChatflowClient","error","streamOptions","fetchFn","headers","accessToken","reader","decoder","pendingEvents","parseErrors","completed","parser","createParser","event","parsed","done","parseError","taskId"],"mappings":"+GAgJA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AAA,OAAA,EAAUJ,CAAAA,CAAoBiC,CAAAA,CAAQ,QAAQ,CAAC,CAAA,KAAA,CAAA,CACjF,MAAA,CAAQ,MAAA,CACR,OAAA,CAAS,CAAE,cAAA,CAAgB,kBAAmB,CAAA,CAC9C,KAAMvB,CACR,CAAC,CACH,CAAA,MAASO,CAAAA,CAAO,CAEd,OAAO,CACL,KAAM,IAAA,CACN,KAAA,CAAO,CAAE,MAAA,CAAQ,GAAA,CAAK,OAAA,CAHRA,CAAAA,YAAiB,KAAA,CAAQA,EAAM,OAAA,CAAU,MAAA,CAAOA,CAAK,CAGrC,EAC9B,MAAA,CAAQ,GACV,CACF,CACF,CACF,CACF","file":"index.cjs","sourcesContent":["import { type ClientResult, createHttpClient, type HttpClient } from \"@amaster.ai/http-client\";\n\nexport type WorkflowResponseMode = \"blocking\" | \"streaming\" | \"async\";\n\nexport type WorkflowInputValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | Record<string, unknown>\n | unknown[];\n\nexport type WorkflowFile = {\n name?: string;\n type?: string;\n url?: string;\n [key: string]: unknown;\n};\n\nexport type WorkflowRunRequest = {\n inputs?: Record<string, WorkflowInputValue>;\n response_mode?: WorkflowResponseMode;\n user?: string;\n files?: WorkflowFile[];\n trace_id?: string;\n usage?: boolean;\n usage_detail?: boolean;\n callback?: WorkflowCallbackConfig;\n};\n\nexport type WorkflowCallbackConfig = {\n name?: string;\n include_outputs?: boolean;\n include_usage?: boolean;\n usage_detail?: boolean;\n};\n\nexport type WorkflowUsageSummary = {\n workflow_run_id: string;\n status: string;\n total_tokens: number;\n workflow_run_total_tokens?: number;\n node_usage_total_tokens?: number;\n billable_total_tokens?: number;\n total_steps: number;\n elapsed_time: number;\n created_at: number | null;\n finished_at: number | null;\n is_finished: boolean;\n};\n\nexport type WorkflowNodeUsage = {\n id: string;\n node_execution_id: string | null;\n index: number;\n node_id: string;\n node_type: string;\n title: string;\n status: string;\n error: string | null;\n elapsed_time: number;\n created_at: number | null;\n finished_at: number | null;\n usage: Record<string, unknown>;\n execution_metadata: Record<string, unknown>;\n};\n\nexport type WorkflowRunUsage = {\n summary: WorkflowUsageSummary;\n estimated_price_by_currency?: Record<string, string>;\n nodes?: WorkflowNodeUsage[];\n};\n\nexport type WorkflowRunResponse<TOutput = Record<string, unknown>> = {\n task_id: string;\n workflow_run_id: string;\n status: string;\n outputs: TOutput;\n error: string | null;\n elapsed_time: number;\n total_tokens: number;\n total_steps: number;\n created_at: number;\n finished_at: number;\n usage?: WorkflowRunUsage;\n};\n\nexport type WorkflowAsyncRunStatus =\n | \"pending\"\n | \"queued\"\n | \"running\"\n | \"succeeded\"\n | \"failed\"\n | \"paused\"\n | \"rate_limited\"\n | \"retrying\"\n | string;\n\nexport type WorkflowAsyncRunResponse = {\n async_run_id: string;\n workflow_trigger_log_id: string;\n workflow_run_id: string | null;\n task_id?: string;\n status: WorkflowAsyncRunStatus;\n queue?: string;\n created_at?: number | null;\n};\n\nexport type WorkflowAsyncRunDetailResponse = WorkflowAsyncRunResponse & {\n workflow_id?: string;\n error?: string | null;\n outputs?: Record<string, unknown> | null;\n elapsed_time?: number | null;\n total_tokens?: number | null;\n triggered_at?: number | null;\n finished_at?: number | null;\n};\n\nexport type WorkflowRunDetailOptions = {\n usage?: boolean;\n usage_detail?: boolean;\n};\n\nexport type WorkflowClient = {\n run<TOutput = Record<string, unknown>>(\n workflowName: string,\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n ): Promise<ClientResult<WorkflowRunResponse<TOutput>>>;\n runAsync(\n workflowName: string,\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n ): Promise<ClientResult<WorkflowAsyncRunResponse>>;\n getAsyncRun(\n workflowName: string,\n asyncRunId: string\n ): Promise<ClientResult<WorkflowAsyncRunDetailResponse>>;\n getRun<TOutput = Record<string, unknown>>(\n workflowName: string,\n workflowRunId: string,\n options?: WorkflowRunDetailOptions\n ): Promise<ClientResult<WorkflowRunResponse<TOutput>>>;\n};\n\nfunction normalizeRunRequest(\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n): WorkflowRunRequest {\n if (!inputs) {\n return { inputs: {}, response_mode: \"blocking\", user: \"anonymous\" };\n }\n\n if (typeof inputs === \"object\" && isWorkflowRunRequest(inputs)) {\n const req = inputs as WorkflowRunRequest;\n return {\n inputs: req.inputs || {},\n response_mode: req.response_mode || \"blocking\",\n user: req.user || \"anonymous\",\n files: req.files,\n trace_id: req.trace_id,\n usage: req.usage,\n usage_detail: req.usage_detail,\n callback: req.callback,\n };\n }\n\n return {\n inputs: inputs as Record<string, WorkflowInputValue>,\n response_mode: \"blocking\",\n user: \"anonymous\",\n };\n}\n\nfunction isWorkflowRunRequest(value: Record<string, unknown>): boolean {\n const requestKeys = [\"inputs\", \"response_mode\", \"user\", \"files\", \"trace_id\", \"usage\", \"usage_detail\", \"callback\"];\n const structuralRequestKeys = [\"inputs\", \"response_mode\", \"user\", \"files\", \"trace_id\"];\n const keys = Object.keys(value);\n\n if (structuralRequestKeys.some((key) => key in value)) {\n return true;\n }\n\n return keys.length > 0 && keys.every((key) => requestKeys.includes(key));\n}\n\nfunction validateWorkflowName(workflowName: string): ClientResult<never> | null {\n if (!workflowName || workflowName.includes(\"/\")) {\n return {\n data: null,\n error: {\n status: 400,\n message:\n \"Invalid workflowName: use workflow YAML filename without extension (no subpaths)\",\n },\n status: 400,\n };\n }\n return null;\n}\n\nexport function createWorkflowClient(http: HttpClient = createHttpClient()): WorkflowClient {\n return {\n async run<TOutput = Record<string, unknown>>(\n workflowName: string,\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n ): Promise<ClientResult<WorkflowRunResponse<TOutput>>> {\n const validationError = validateWorkflowName(workflowName);\n if (validationError) {\n return validationError;\n }\n\n const normalizedRequest = normalizeRunRequest(inputs);\n\n const response = await http.request<{\n data: {\n status: string;\n outputs: TOutput;\n error: string | null;\n elapsed_time: number;\n total_tokens: number;\n total_steps: number;\n created_at: number;\n finished_at: number;\n usage?: WorkflowRunUsage;\n };\n task_id: string;\n workflow_run_id: string;\n }>({\n url: `/api/runworkflow/${workflowName}`,\n method: \"post\",\n headers: { \"Content-Type\": \"application/json\" },\n data: normalizedRequest,\n });\n\n if (response.data?.data) {\n const innerData = response.data.data;\n return {\n ...response,\n data: {\n task_id: response.data.task_id || \"\",\n workflow_run_id: response.data.workflow_run_id || \"\",\n status: innerData.status || \"unknown\",\n outputs: innerData.outputs || ({} as TOutput),\n error: innerData.error || null,\n elapsed_time: innerData.elapsed_time || 0,\n total_tokens: innerData.total_tokens || 0,\n total_steps: innerData.total_steps || 0,\n created_at: innerData.created_at || 0,\n finished_at: innerData.finished_at || 0,\n ...(innerData.usage ? { usage: innerData.usage } : {}),\n },\n };\n }\n\n return {\n data: null,\n error: response.error || {\n status: response.status,\n message: \"Invalid workflow response structure\",\n },\n status: response.status,\n };\n },\n async runAsync(\n workflowName: string,\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n ): Promise<ClientResult<WorkflowAsyncRunResponse>> {\n const validationError = validateWorkflowName(workflowName);\n if (validationError) {\n return validationError;\n }\n\n const normalizedRequest = normalizeRunRequest(inputs);\n normalizedRequest.response_mode = \"async\";\n\n const response = await http.request<WorkflowAsyncRunResponse>({\n url: `/api/runworkflow/${workflowName}`,\n method: \"post\",\n headers: { \"Content-Type\": \"application/json\" },\n data: normalizedRequest,\n });\n\n if (response.data?.async_run_id) {\n return response;\n }\n\n return {\n data: null,\n error: response.error || {\n status: response.status,\n message: \"Invalid workflow async run response structure\",\n },\n status: response.status,\n };\n },\n async getAsyncRun(\n workflowName: string,\n asyncRunId: string\n ): Promise<ClientResult<WorkflowAsyncRunDetailResponse>> {\n const validationError = validateWorkflowName(workflowName);\n if (validationError) {\n return validationError;\n }\n\n const response = await http.request<WorkflowAsyncRunDetailResponse>({\n url: `/api/runworkflow/${workflowName}/async-runs/${asyncRunId}`,\n method: \"get\",\n });\n\n if (response.data?.async_run_id) {\n return response;\n }\n\n return {\n data: null,\n error: response.error || {\n status: response.status,\n message: \"Invalid workflow async run detail response structure\",\n },\n status: response.status,\n };\n },\n async getRun<TOutput = Record<string, unknown>>(\n workflowName: string,\n workflowRunId: string,\n options: WorkflowRunDetailOptions = {}\n ): Promise<ClientResult<WorkflowRunResponse<TOutput>>> {\n const validationError = validateWorkflowName(workflowName);\n if (validationError) {\n return validationError;\n }\n\n const response = await http.request<{\n workflow_run_id: string;\n data: {\n status: string;\n outputs: TOutput;\n error: string | null;\n elapsed_time: number;\n total_tokens: number;\n total_steps: number;\n created_at: number;\n finished_at: number;\n usage?: WorkflowRunUsage;\n };\n }>({\n url: `/api/runworkflow/${workflowName}/runs/${workflowRunId}`,\n method: \"get\",\n params: {\n ...(options.usage !== undefined ? { usage: options.usage } : {}),\n ...(options.usage_detail !== undefined ? { usage_detail: options.usage_detail } : {}),\n },\n });\n\n if (response.data?.data) {\n const innerData = response.data.data;\n return {\n ...response,\n data: {\n task_id: \"\",\n workflow_run_id: response.data.workflow_run_id || workflowRunId,\n status: innerData.status || \"unknown\",\n outputs: innerData.outputs || ({} as TOutput),\n error: innerData.error || null,\n elapsed_time: innerData.elapsed_time || 0,\n total_tokens: innerData.total_tokens || 0,\n total_steps: innerData.total_steps || 0,\n created_at: innerData.created_at || 0,\n finished_at: innerData.finished_at || 0,\n ...(innerData.usage ? { usage: innerData.usage } : {}),\n },\n };\n }\n\n return {\n data: null,\n error: response.error || {\n status: response.status,\n message: \"Invalid workflow run detail response structure\",\n },\n status: response.status,\n };\n },\n };\n}\n","import {\n type ClientResult,\n createHttpClient,\n type HttpClient,\n} from \"@amaster.ai/http-client\";\nimport { createParser } from \"eventsource-parser\";\nimport type { WorkflowFile, WorkflowInputValue } from \"./workflow-client\";\n\nexport type ChatflowRunRequest = {\n inputs?: Record<string, WorkflowInputValue>;\n query: string;\n files?: WorkflowFile[];\n conversation_id?: string;\n user?: string;\n retriever_from?: string;\n auto_generate_name?: boolean;\n workflow_id?: string;\n};\n\nexport type ChatflowBlockingResponse = {\n event?: string;\n task_id: string;\n message_id: string;\n conversation_id: string;\n mode?: string;\n answer: string;\n metadata?: Record<string, unknown>;\n created_at?: number;\n};\n\nexport type ChatflowEvent = {\n event: string;\n task_id?: string;\n message_id?: string;\n conversation_id?: string;\n answer?: string;\n created_at?: number;\n [key: string]: unknown;\n};\n\nexport type ChatflowStopRequest = {\n user?: string;\n};\n\nexport type ChatflowStopResponse = {\n result: string;\n};\n\nexport type ChatflowClientOptions = {\n baseURL?: string;\n headers?: Record<string, string>;\n getAccessToken?: () => string | null | undefined;\n fetch?: typeof globalThis.fetch;\n credentials?: RequestCredentials;\n onUnauthorized?: () => void;\n};\n\nexport type ChatflowStreamOptions = {\n signal?: AbortSignal;\n};\n\nexport type ChatflowClient = {\n run(\n chatflowName: string,\n request: ChatflowRunRequest,\n ): Promise<ClientResult<ChatflowBlockingResponse>>;\n stream(\n chatflowName: string,\n request: ChatflowRunRequest,\n options?: ChatflowStreamOptions,\n ): AsyncGenerator<ChatflowEvent, void, void>;\n stop(\n chatflowName: string,\n taskId: string,\n request?: ChatflowStopRequest,\n ): Promise<ClientResult<ChatflowStopResponse>>;\n};\n\nexport class ChatflowStreamError extends Error {\n readonly status: number;\n readonly details?: unknown;\n\n constructor(message: string, status: number, details?: unknown) {\n super(message);\n this.name = \"ChatflowStreamError\";\n this.status = status;\n this.details = details;\n }\n}\n\nfunction validatePathSegment(value: string, fieldName: string): string {\n const normalized = value.trim();\n if (!normalized || normalized.includes(\"/\")) {\n throw new ChatflowStreamError(\n `Invalid ${fieldName}: use a non-empty value without subpaths`,\n 400,\n );\n }\n return encodeURIComponent(normalized);\n}\n\nfunction chatflowPath(chatflowName: string): string {\n return `/api/runchatflow/${validatePathSegment(chatflowName, \"chatflowName\")}`;\n}\n\nfunction resolveRequestURL(baseURL: string | undefined, path: string): string {\n const normalizedBaseURL = baseURL?.trim().replace(/\\/+$/, \"\");\n return normalizedBaseURL ? `${normalizedBaseURL}${path}` : path;\n}\n\nfunction normalizeRequest(\n request: ChatflowRunRequest,\n responseMode: \"blocking\" | \"streaming\",\n): ChatflowRunRequest & { response_mode: \"blocking\" | \"streaming\" } {\n return {\n ...request,\n inputs: request.inputs ?? {},\n response_mode: responseMode,\n };\n}\n\nasync function parseErrorResponse(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) {\n return null;\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction errorMessage(status: number, details: unknown): string {\n if (details && typeof details === \"object\") {\n const payload = details as Record<string, unknown>;\n for (const key of [\"message\", \"error\", \"detail\"]) {\n if (typeof payload[key] === \"string\" && payload[key]) {\n return payload[key];\n }\n }\n }\n if (typeof details === \"string\" && details) {\n return details;\n }\n return `Chatflow stream request failed with status ${status}`;\n}\n\nexport function createChatflowClient(\n http: HttpClient = createHttpClient(),\n options: ChatflowClientOptions = {},\n): ChatflowClient {\n return {\n async run(chatflowName, request) {\n try {\n return await http.request<ChatflowBlockingResponse>({\n url: chatflowPath(chatflowName),\n method: \"post\",\n headers: { \"Content-Type\": \"application/json\" },\n data: normalizeRequest(request, \"blocking\"),\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n data: null,\n error: { status: 400, message },\n status: 400,\n };\n }\n },\n\n async *stream(chatflowName, request, streamOptions = {}) {\n const fetchFn = options.fetch ?? globalThis.fetch?.bind(globalThis);\n if (typeof fetchFn !== \"function\") {\n throw new ChatflowStreamError(\n \"Fetch API not found. Provide ChatflowClientOptions.fetch.\",\n 0,\n );\n }\n\n const headers = new Headers(options.headers);\n headers.set(\"Accept\", \"text/event-stream\");\n headers.set(\"Content-Type\", \"application/json\");\n const accessToken = options.getAccessToken?.();\n if (accessToken) {\n headers.set(\"Authorization\", `Bearer ${accessToken}`);\n }\n\n const response = await fetchFn(\n resolveRequestURL(options.baseURL, chatflowPath(chatflowName)),\n {\n method: \"POST\",\n headers,\n credentials: options.credentials ?? \"include\",\n body: JSON.stringify(normalizeRequest(request, \"streaming\")),\n signal: streamOptions.signal,\n },\n );\n\n if (!response.ok) {\n const details = await parseErrorResponse(response);\n if (response.status === 401) {\n options.onUnauthorized?.();\n }\n throw new ChatflowStreamError(\n errorMessage(response.status, details),\n response.status,\n details,\n );\n }\n if (!response.body) {\n throw new ChatflowStreamError(\"Chatflow stream response has no body\", response.status);\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const pendingEvents: ChatflowEvent[] = [];\n const parseErrors: Error[] = [];\n let completed = false;\n const parser = createParser({\n onEvent(event) {\n if (!event.data || event.data === \"[DONE]\") {\n return;\n }\n try {\n const parsed = JSON.parse(event.data) as unknown;\n if (\n parsed &&\n typeof parsed === \"object\" &&\n typeof (parsed as Record<string, unknown>).event === \"string\"\n ) {\n pendingEvents.push(parsed as ChatflowEvent);\n }\n } catch (error) {\n parseErrors.push(error instanceof Error ? error : new Error(String(error)));\n }\n },\n });\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n parser.feed(decoder.decode());\n completed = true;\n } else {\n parser.feed(decoder.decode(value, { stream: true }));\n }\n\n const parseError = parseErrors.shift();\n if (parseError) {\n throw new ChatflowStreamError(\n `Failed to parse chatflow SSE event: ${parseError.message}`,\n response.status,\n );\n }\n while (pendingEvents.length > 0) {\n const event = pendingEvents.shift();\n if (event) {\n yield event;\n }\n }\n if (done) {\n break;\n }\n }\n } finally {\n if (!completed) {\n await reader.cancel();\n }\n reader.releaseLock();\n }\n },\n\n async stop(chatflowName, taskId, request = {}) {\n try {\n return await http.request<ChatflowStopResponse>({\n url: `${chatflowPath(chatflowName)}/tasks/${validatePathSegment(taskId, \"taskId\")}/stop`,\n method: \"post\",\n headers: { \"Content-Type\": \"application/json\" },\n data: request,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n data: null,\n error: { status: 400, message },\n status: 400,\n };\n }\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/workflow-client.ts","../src/chatflow-client.ts"],"names":["normalizeRunRequest","inputs","isWorkflowRunRequest","req","value","requestKeys","structuralRequestKeys","keys","key","validateWorkflowName","workflowName","createWorkflowClient","http","createHttpClient","validationError","normalizedRequest","response","innerData","asyncRunId","workflowRunId","options","ChatflowStreamError","message","status","details","validatePathSegment","fieldName","normalized","chatflowPath","chatflowName","resolveRequestURL","baseURL","path","normalizedBaseURL","normalizeRequest","request","responseMode","parseErrorResponse","text","errorMessage","payload","createChatflowClient","error","streamOptions","scope","captured","fetchFn","headers","accessToken","scoped","name","controller","abort","removeScope","reader","decoder","pendingEvents","parseErrors","completed","parser","createParser","event","parsed","done","parseError","taskId"],"mappings":"+GAgJA,SAASA,EACPC,CAAAA,CACoB,CACpB,GAAI,CAACA,EACH,OAAO,CAAE,MAAA,CAAQ,GAAI,aAAA,CAAe,UAAA,CAAY,IAAA,CAAM,WAAY,EAGpE,GAAI,OAAOA,CAAAA,EAAW,QAAA,EAAYC,EAAqBD,CAAM,CAAA,CAAG,CAC9D,IAAME,EAAMF,CAAAA,CACZ,OAAO,CACL,MAAA,CAAQE,EAAI,MAAA,EAAU,EAAC,CACvB,aAAA,CAAeA,EAAI,aAAA,EAAiB,UAAA,CACpC,IAAA,CAAMA,CAAAA,CAAI,MAAQ,WAAA,CAClB,KAAA,CAAOA,CAAAA,CAAI,KAAA,CACX,SAAUA,CAAAA,CAAI,QAAA,CACd,KAAA,CAAOA,CAAAA,CAAI,MACX,YAAA,CAAcA,CAAAA,CAAI,YAAA,CAClB,QAAA,CAAUA,EAAI,QAChB,CACF,CAEA,OAAO,CACL,MAAA,CAAQF,CAAAA,CACR,aAAA,CAAe,UAAA,CACf,KAAM,WACR,CACF,CAEA,SAASC,EAAqBE,CAAAA,CAAyC,CACrE,IAAMC,CAAAA,CAAc,CAAC,QAAA,CAAU,eAAA,CAAiB,MAAA,CAAQ,OAAA,CAAS,WAAY,OAAA,CAAS,cAAA,CAAgB,UAAU,CAAA,CAC1GC,EAAwB,CAAC,QAAA,CAAU,eAAA,CAAiB,MAAA,CAAQ,QAA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S,CAAE,cAAA,CAAgB,kBAAmB,CAAA,CAC9C,IAAA,CAAM9B,CACR,CAAC,CACH,CAAA,MAASO,CAAAA,CAAO,CAEd,OAAO,CACL,IAAA,CAAM,IAAA,CACN,KAAA,CAAO,CAAE,OAAQ,GAAA,CAAK,OAAA,CAHRA,CAAAA,YAAiB,KAAA,CAAQA,EAAM,OAAA,CAAU,MAAA,CAAOA,CAAK,CAGrC,EAC9B,MAAA,CAAQ,GACV,CACF,CACF,CACF,CACF","file":"index.cjs","sourcesContent":["import { type ClientResult, createHttpClient, type HttpClient } from \"@amaster.ai/http-client\";\n\nexport type WorkflowResponseMode = \"blocking\" | \"streaming\" | \"async\";\n\nexport type WorkflowInputValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | Record<string, unknown>\n | unknown[];\n\nexport type WorkflowFile = {\n name?: string;\n type?: string;\n url?: string;\n [key: string]: unknown;\n};\n\nexport type WorkflowRunRequest = {\n inputs?: Record<string, WorkflowInputValue>;\n response_mode?: WorkflowResponseMode;\n user?: string;\n files?: WorkflowFile[];\n trace_id?: string;\n usage?: boolean;\n usage_detail?: boolean;\n callback?: WorkflowCallbackConfig;\n};\n\nexport type WorkflowCallbackConfig = {\n name?: string;\n include_outputs?: boolean;\n include_usage?: boolean;\n usage_detail?: boolean;\n};\n\nexport type WorkflowUsageSummary = {\n workflow_run_id: string;\n status: string;\n total_tokens: number;\n workflow_run_total_tokens?: number;\n node_usage_total_tokens?: number;\n billable_total_tokens?: number;\n total_steps: number;\n elapsed_time: number;\n created_at: number | null;\n finished_at: number | null;\n is_finished: boolean;\n};\n\nexport type WorkflowNodeUsage = {\n id: string;\n node_execution_id: string | null;\n index: number;\n node_id: string;\n node_type: string;\n title: string;\n status: string;\n error: string | null;\n elapsed_time: number;\n created_at: number | null;\n finished_at: number | null;\n usage: Record<string, unknown>;\n execution_metadata: Record<string, unknown>;\n};\n\nexport type WorkflowRunUsage = {\n summary: WorkflowUsageSummary;\n estimated_price_by_currency?: Record<string, string>;\n nodes?: WorkflowNodeUsage[];\n};\n\nexport type WorkflowRunResponse<TOutput = Record<string, unknown>> = {\n task_id: string;\n workflow_run_id: string;\n status: string;\n outputs: TOutput;\n error: string | null;\n elapsed_time: number;\n total_tokens: number;\n total_steps: number;\n created_at: number;\n finished_at: number;\n usage?: WorkflowRunUsage;\n};\n\nexport type WorkflowAsyncRunStatus =\n | \"pending\"\n | \"queued\"\n | \"running\"\n | \"succeeded\"\n | \"failed\"\n | \"paused\"\n | \"rate_limited\"\n | \"retrying\"\n | string;\n\nexport type WorkflowAsyncRunResponse = {\n async_run_id: string;\n workflow_trigger_log_id: string;\n workflow_run_id: string | null;\n task_id?: string;\n status: WorkflowAsyncRunStatus;\n queue?: string;\n created_at?: number | null;\n};\n\nexport type WorkflowAsyncRunDetailResponse = WorkflowAsyncRunResponse & {\n workflow_id?: string;\n error?: string | null;\n outputs?: Record<string, unknown> | null;\n elapsed_time?: number | null;\n total_tokens?: number | null;\n triggered_at?: number | null;\n finished_at?: number | null;\n};\n\nexport type WorkflowRunDetailOptions = {\n usage?: boolean;\n usage_detail?: boolean;\n};\n\nexport type WorkflowClient = {\n run<TOutput = Record<string, unknown>>(\n workflowName: string,\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n ): Promise<ClientResult<WorkflowRunResponse<TOutput>>>;\n runAsync(\n workflowName: string,\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n ): Promise<ClientResult<WorkflowAsyncRunResponse>>;\n getAsyncRun(\n workflowName: string,\n asyncRunId: string\n ): Promise<ClientResult<WorkflowAsyncRunDetailResponse>>;\n getRun<TOutput = Record<string, unknown>>(\n workflowName: string,\n workflowRunId: string,\n options?: WorkflowRunDetailOptions\n ): Promise<ClientResult<WorkflowRunResponse<TOutput>>>;\n};\n\nfunction normalizeRunRequest(\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n): WorkflowRunRequest {\n if (!inputs) {\n return { inputs: {}, response_mode: \"blocking\", user: \"anonymous\" };\n }\n\n if (typeof inputs === \"object\" && isWorkflowRunRequest(inputs)) {\n const req = inputs as WorkflowRunRequest;\n return {\n inputs: req.inputs || {},\n response_mode: req.response_mode || \"blocking\",\n user: req.user || \"anonymous\",\n files: req.files,\n trace_id: req.trace_id,\n usage: req.usage,\n usage_detail: req.usage_detail,\n callback: req.callback,\n };\n }\n\n return {\n inputs: inputs as Record<string, WorkflowInputValue>,\n response_mode: \"blocking\",\n user: \"anonymous\",\n };\n}\n\nfunction isWorkflowRunRequest(value: Record<string, unknown>): boolean {\n const requestKeys = [\"inputs\", \"response_mode\", \"user\", \"files\", \"trace_id\", \"usage\", \"usage_detail\", \"callback\"];\n const structuralRequestKeys = [\"inputs\", \"response_mode\", \"user\", \"files\", \"trace_id\"];\n const keys = Object.keys(value);\n\n if (structuralRequestKeys.some((key) => key in value)) {\n return true;\n }\n\n return keys.length > 0 && keys.every((key) => requestKeys.includes(key));\n}\n\nfunction validateWorkflowName(workflowName: string): ClientResult<never> | null {\n if (!workflowName || workflowName.includes(\"/\")) {\n return {\n data: null,\n error: {\n status: 400,\n message:\n \"Invalid workflowName: use workflow YAML filename without extension (no subpaths)\",\n },\n status: 400,\n };\n }\n return null;\n}\n\nexport function createWorkflowClient(http: HttpClient = createHttpClient()): WorkflowClient {\n return {\n async run<TOutput = Record<string, unknown>>(\n workflowName: string,\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n ): Promise<ClientResult<WorkflowRunResponse<TOutput>>> {\n const validationError = validateWorkflowName(workflowName);\n if (validationError) {\n return validationError;\n }\n\n const normalizedRequest = normalizeRunRequest(inputs);\n\n const response = await http.request<{\n data: {\n status: string;\n outputs: TOutput;\n error: string | null;\n elapsed_time: number;\n total_tokens: number;\n total_steps: number;\n created_at: number;\n finished_at: number;\n usage?: WorkflowRunUsage;\n };\n task_id: string;\n workflow_run_id: string;\n }>({\n url: `/api/runworkflow/${workflowName}`,\n method: \"post\",\n headers: { \"Content-Type\": \"application/json\" },\n data: normalizedRequest,\n });\n\n if (response.data?.data) {\n const innerData = response.data.data;\n return {\n ...response,\n data: {\n task_id: response.data.task_id || \"\",\n workflow_run_id: response.data.workflow_run_id || \"\",\n status: innerData.status || \"unknown\",\n outputs: innerData.outputs || ({} as TOutput),\n error: innerData.error || null,\n elapsed_time: innerData.elapsed_time || 0,\n total_tokens: innerData.total_tokens || 0,\n total_steps: innerData.total_steps || 0,\n created_at: innerData.created_at || 0,\n finished_at: innerData.finished_at || 0,\n ...(innerData.usage ? { usage: innerData.usage } : {}),\n },\n };\n }\n\n return {\n ...response,\n data: null,\n error: response.error || {\n status: response.status,\n message: \"Invalid workflow response structure\",\n },\n status: response.status,\n };\n },\n async runAsync(\n workflowName: string,\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n ): Promise<ClientResult<WorkflowAsyncRunResponse>> {\n const validationError = validateWorkflowName(workflowName);\n if (validationError) {\n return validationError;\n }\n\n const normalizedRequest = normalizeRunRequest(inputs);\n normalizedRequest.response_mode = \"async\";\n\n const response = await http.request<WorkflowAsyncRunResponse>({\n url: `/api/runworkflow/${workflowName}`,\n method: \"post\",\n headers: { \"Content-Type\": \"application/json\" },\n data: normalizedRequest,\n });\n\n if (response.data?.async_run_id) {\n return response;\n }\n\n return {\n ...response,\n data: null,\n error: response.error || {\n status: response.status,\n message: \"Invalid workflow async run response structure\",\n },\n status: response.status,\n };\n },\n async getAsyncRun(\n workflowName: string,\n asyncRunId: string\n ): Promise<ClientResult<WorkflowAsyncRunDetailResponse>> {\n const validationError = validateWorkflowName(workflowName);\n if (validationError) {\n return validationError;\n }\n\n const response = await http.request<WorkflowAsyncRunDetailResponse>({\n url: `/api/runworkflow/${workflowName}/async-runs/${asyncRunId}`,\n method: \"get\",\n });\n\n if (response.data?.async_run_id) {\n return response;\n }\n\n return {\n ...response,\n data: null,\n error: response.error || {\n status: response.status,\n message: \"Invalid workflow async run detail response structure\",\n },\n status: response.status,\n };\n },\n async getRun<TOutput = Record<string, unknown>>(\n workflowName: string,\n workflowRunId: string,\n options: WorkflowRunDetailOptions = {}\n ): Promise<ClientResult<WorkflowRunResponse<TOutput>>> {\n const validationError = validateWorkflowName(workflowName);\n if (validationError) {\n return validationError;\n }\n\n const response = await http.request<{\n workflow_run_id: string;\n data: {\n status: string;\n outputs: TOutput;\n error: string | null;\n elapsed_time: number;\n total_tokens: number;\n total_steps: number;\n created_at: number;\n finished_at: number;\n usage?: WorkflowRunUsage;\n };\n }>({\n url: `/api/runworkflow/${workflowName}/runs/${workflowRunId}`,\n method: \"get\",\n params: {\n ...(options.usage !== undefined ? { usage: options.usage } : {}),\n ...(options.usage_detail !== undefined ? { usage_detail: options.usage_detail } : {}),\n },\n });\n\n if (response.data?.data) {\n const innerData = response.data.data;\n return {\n ...response,\n data: {\n task_id: \"\",\n workflow_run_id: response.data.workflow_run_id || workflowRunId,\n status: innerData.status || \"unknown\",\n outputs: innerData.outputs || ({} as TOutput),\n error: innerData.error || null,\n elapsed_time: innerData.elapsed_time || 0,\n total_tokens: innerData.total_tokens || 0,\n total_steps: innerData.total_steps || 0,\n created_at: innerData.created_at || 0,\n finished_at: innerData.finished_at || 0,\n ...(innerData.usage ? { usage: innerData.usage } : {}),\n },\n };\n }\n\n return {\n ...response,\n data: null,\n error: response.error || {\n status: response.status,\n message: \"Invalid workflow run detail response structure\",\n },\n status: response.status,\n };\n },\n };\n}\n","import {\n type ClientResult,\n createHttpClient,\n type HttpClient,\n type RequestScopeController,\n} from \"@amaster.ai/http-client\";\nimport { createParser } from \"eventsource-parser\";\nimport type { WorkflowFile, WorkflowInputValue } from \"./workflow-client\";\n\nexport type ChatflowRunRequest = {\n inputs?: Record<string, WorkflowInputValue>;\n query: string;\n files?: WorkflowFile[];\n conversation_id?: string;\n user?: string;\n retriever_from?: string;\n auto_generate_name?: boolean;\n workflow_id?: string;\n};\n\nexport type ChatflowBlockingResponse = {\n event?: string;\n task_id: string;\n message_id: string;\n conversation_id: string;\n mode?: string;\n answer: string;\n metadata?: Record<string, unknown>;\n created_at?: number;\n};\n\nexport type ChatflowEvent = {\n event: string;\n task_id?: string;\n message_id?: string;\n conversation_id?: string;\n answer?: string;\n created_at?: number;\n [key: string]: unknown;\n};\n\nexport type ChatflowStopRequest = {\n user?: string;\n};\n\nexport type ChatflowStopResponse = {\n result: string;\n};\n\nexport type ChatflowClientOptions = {\n baseURL?: string;\n headers?: Record<string, string>;\n getAccessToken?: () => string | null | undefined;\n fetch?: typeof globalThis.fetch;\n credentials?: RequestCredentials;\n onUnauthorized?: () => void;\n requestScope?: RequestScopeController;\n beforeStream?: () => Promise<void>;\n};\n\nexport type ChatflowStreamOptions = {\n signal?: AbortSignal;\n};\n\nexport type ChatflowClient = {\n run(\n chatflowName: string,\n request: ChatflowRunRequest,\n ): Promise<ClientResult<ChatflowBlockingResponse>>;\n stream(\n chatflowName: string,\n request: ChatflowRunRequest,\n options?: ChatflowStreamOptions,\n ): AsyncGenerator<ChatflowEvent, void, void>;\n stop(\n chatflowName: string,\n taskId: string,\n request?: ChatflowStopRequest,\n ): Promise<ClientResult<ChatflowStopResponse>>;\n};\n\nexport class ChatflowStreamError extends Error {\n readonly status: number;\n readonly details?: unknown;\n\n constructor(message: string, status: number, details?: unknown) {\n super(message);\n this.name = \"ChatflowStreamError\";\n this.status = status;\n this.details = details;\n }\n}\n\nfunction validatePathSegment(value: string, fieldName: string): string {\n const normalized = value.trim();\n if (!normalized || normalized.includes(\"/\")) {\n throw new ChatflowStreamError(\n `Invalid ${fieldName}: use a non-empty value without subpaths`,\n 400,\n );\n }\n return encodeURIComponent(normalized);\n}\n\nfunction chatflowPath(chatflowName: string): string {\n return `/api/runchatflow/${validatePathSegment(chatflowName, \"chatflowName\")}`;\n}\n\nfunction resolveRequestURL(baseURL: string | undefined, path: string): string {\n const normalizedBaseURL = baseURL?.trim().replace(/\\/+$/, \"\");\n return normalizedBaseURL ? `${normalizedBaseURL}${path}` : path;\n}\n\nfunction normalizeRequest(\n request: ChatflowRunRequest,\n responseMode: \"blocking\" | \"streaming\",\n): ChatflowRunRequest & { response_mode: \"blocking\" | \"streaming\" } {\n return {\n ...request,\n inputs: request.inputs ?? {},\n response_mode: responseMode,\n };\n}\n\nasync function parseErrorResponse(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) {\n return null;\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction errorMessage(status: number, details: unknown): string {\n if (details && typeof details === \"object\") {\n const payload = details as Record<string, unknown>;\n for (const key of [\"message\", \"error\", \"detail\"]) {\n if (typeof payload[key] === \"string\" && payload[key]) {\n return payload[key];\n }\n }\n }\n if (typeof details === \"string\" && details) {\n return details;\n }\n return `Chatflow stream request failed with status ${status}`;\n}\n\nexport function createChatflowClient(\n http: HttpClient = createHttpClient(),\n options: ChatflowClientOptions = {},\n): ChatflowClient {\n return {\n async run(chatflowName, request) {\n try {\n return await http.request<ChatflowBlockingResponse>({\n url: chatflowPath(chatflowName),\n method: \"post\",\n headers: { \"Content-Type\": \"application/json\" },\n data: normalizeRequest(request, \"blocking\"),\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n data: null,\n error: { status: 400, message },\n status: 400,\n };\n }\n },\n\n async *stream(chatflowName, request, streamOptions = {}) {\n await options.beforeStream?.();\n const scope = options.requestScope;\n const captured = scope?.capture();\n const fetchFn = options.fetch ?? globalThis.fetch?.bind(globalThis);\n if (typeof fetchFn !== \"function\") {\n throw new ChatflowStreamError(\n \"Fetch API not found. Provide ChatflowClientOptions.fetch.\",\n 0,\n );\n }\n\n const headers = new Headers(options.headers);\n headers.set(\"Accept\", \"text/event-stream\");\n headers.set(\"Content-Type\", \"application/json\");\n const accessToken = options.getAccessToken?.();\n if (accessToken) {\n headers.set(\"Authorization\", `Bearer ${accessToken}`);\n }\n\n if (scope && captured) {\n const scoped = scope.headers(captured, Object.fromEntries(headers.entries()));\n for (const [name, value] of Object.entries(scoped)) headers.set(name, value);\n }\n const controller = typeof AbortController === \"undefined\" ? undefined : new AbortController();\n const abort = () => controller?.abort();\n const removeScope = scope && captured ? scope.onInvalidate(captured, abort) : undefined;\n streamOptions.signal?.addEventListener(\"abort\", abort, { once: true });\n if (streamOptions.signal?.aborted) abort();\n\n try {\n\n const response = await fetchFn(\n resolveRequestURL(options.baseURL, chatflowPath(chatflowName)),\n {\n method: \"POST\",\n headers,\n credentials: options.credentials ?? \"include\",\n body: JSON.stringify(normalizeRequest(request, \"streaming\")),\n signal: controller?.signal ?? streamOptions.signal ?? captured?.signal,\n },\n );\n if (captured) scope!.assertCurrent(captured);\n\n if (!response.ok) {\n const details = await parseErrorResponse(response);\n if (response.status === 401) {\n options.onUnauthorized?.();\n }\n throw new ChatflowStreamError(\n errorMessage(response.status, details),\n response.status,\n details,\n );\n }\n if (!response.body) {\n throw new ChatflowStreamError(\"Chatflow stream response has no body\", response.status);\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const pendingEvents: ChatflowEvent[] = [];\n const parseErrors: Error[] = [];\n let completed = false;\n const parser = createParser({\n onEvent(event) {\n if (!event.data || event.data === \"[DONE]\") {\n return;\n }\n try {\n const parsed = JSON.parse(event.data) as unknown;\n if (\n parsed &&\n typeof parsed === \"object\" &&\n typeof (parsed as Record<string, unknown>).event === \"string\"\n ) {\n pendingEvents.push(parsed as ChatflowEvent);\n }\n } catch (error) {\n parseErrors.push(error instanceof Error ? error : new Error(String(error)));\n }\n },\n });\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (captured) scope!.assertCurrent(captured);\n if (done) {\n parser.feed(decoder.decode());\n completed = true;\n } else {\n parser.feed(decoder.decode(value, { stream: true }));\n }\n\n const parseError = parseErrors.shift();\n if (parseError) {\n throw new ChatflowStreamError(\n `Failed to parse chatflow SSE event: ${parseError.message}`,\n response.status,\n );\n }\n while (pendingEvents.length > 0) {\n const event = pendingEvents.shift();\n if (event) {\n if (captured) scope!.assertCurrent(captured);\n yield event;\n }\n }\n if (done) {\n break;\n }\n }\n } finally {\n if (!completed) {\n await reader.cancel();\n }\n reader.releaseLock();\n }\n } finally {\n removeScope?.();\n streamOptions.signal?.removeEventListener(\"abort\", abort);\n }\n },\n\n async stop(chatflowName, taskId, request = {}) {\n try {\n return await http.request<ChatflowStopResponse>({\n url: `${chatflowPath(chatflowName)}/tasks/${validatePathSegment(taskId, \"taskId\")}/stop`,\n method: \"post\",\n headers: { \"Content-Type\": \"application/json\" },\n data: request,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n data: null,\n error: { status: 400, message },\n status: 400,\n };\n }\n },\n };\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { ClientResult, HttpClient } from '@amaster.ai/http-client';
1
+ import { ClientResult, HttpClient, RequestScopeController } from '@amaster.ai/http-client';
2
2
 
3
3
  type WorkflowResponseMode = "blocking" | "streaming" | "async";
4
4
  type WorkflowInputValue = string | number | boolean | null | undefined | Record<string, unknown> | unknown[];
@@ -143,6 +143,8 @@ type ChatflowClientOptions = {
143
143
  fetch?: typeof globalThis.fetch;
144
144
  credentials?: RequestCredentials;
145
145
  onUnauthorized?: () => void;
146
+ requestScope?: RequestScopeController;
147
+ beforeStream?: () => Promise<void>;
146
148
  };
147
149
  type ChatflowStreamOptions = {
148
150
  signal?: AbortSignal;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ClientResult, HttpClient } from '@amaster.ai/http-client';
1
+ import { ClientResult, HttpClient, RequestScopeController } from '@amaster.ai/http-client';
2
2
 
3
3
  type WorkflowResponseMode = "blocking" | "streaming" | "async";
4
4
  type WorkflowInputValue = string | number | boolean | null | undefined | Record<string, unknown> | unknown[];
@@ -143,6 +143,8 @@ type ChatflowClientOptions = {
143
143
  fetch?: typeof globalThis.fetch;
144
144
  credentials?: RequestCredentials;
145
145
  onUnauthorized?: () => void;
146
+ requestScope?: RequestScopeController;
147
+ beforeStream?: () => Promise<void>;
146
148
  };
147
149
  type ChatflowStreamOptions = {
148
150
  signal?: AbortSignal;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import {createHttpClient}from'@amaster.ai/http-client';import {createParser}from'eventsource-parser';function b(t){if(!t)return {inputs:{},response_mode:"blocking",user:"anonymous"};if(typeof t=="object"&&x(t)){let e=t;return {inputs:e.inputs||{},response_mode:e.response_mode||"blocking",user:e.user||"anonymous",files:e.files,trace_id:e.trace_id,usage:e.usage,usage_detail:e.usage_detail,callback:e.callback}}return {inputs:t,response_mode:"blocking",user:"anonymous"}}function x(t){let e=["inputs","response_mode","user","files","trace_id","usage","usage_detail","callback"],r=["inputs","response_mode","user","files","trace_id"],s=Object.keys(t);return r.some(a=>a in t)?true:s.length>0&&s.every(a=>e.includes(a))}function f(t){return !t||t.includes("/")?{data:null,error:{status:400,message:"Invalid workflowName: use workflow YAML filename without extension (no subpaths)"},status:400}:null}function v(t=createHttpClient()){return {async run(e,r){let s=f(e);if(s)return s;let a=b(r),n=await t.request({url:`/api/runworkflow/${e}`,method:"post",headers:{"Content-Type":"application/json"},data:a});if(n.data?.data){let o=n.data.data;return {...n,data:{task_id:n.data.task_id||"",workflow_run_id:n.data.workflow_run_id||"",status:o.status||"unknown",outputs:o.outputs||{},error:o.error||null,elapsed_time:o.elapsed_time||0,total_tokens:o.total_tokens||0,total_steps:o.total_steps||0,created_at:o.created_at||0,finished_at:o.finished_at||0,...o.usage?{usage:o.usage}:{}}}}return {data:null,error:n.error||{status:n.status,message:"Invalid workflow response structure"},status:n.status}},async runAsync(e,r){let s=f(e);if(s)return s;let a=b(r);a.response_mode="async";let n=await t.request({url:`/api/runworkflow/${e}`,method:"post",headers:{"Content-Type":"application/json"},data:a});return n.data?.async_run_id?n:{data:null,error:n.error||{status:n.status,message:"Invalid workflow async run response structure"},status:n.status}},async getAsyncRun(e,r){let s=f(e);if(s)return s;let a=await t.request({url:`/api/runworkflow/${e}/async-runs/${r}`,method:"get"});return a.data?.async_run_id?a:{data:null,error:a.error||{status:a.status,message:"Invalid workflow async run detail response structure"},status:a.status}},async getRun(e,r,s={}){let a=f(e);if(a)return a;let n=await t.request({url:`/api/runworkflow/${e}/runs/${r}`,method:"get",params:{...s.usage!==void 0?{usage:s.usage}:{},...s.usage_detail!==void 0?{usage_detail:s.usage_detail}:{}}});if(n.data?.data){let o=n.data.data;return {...n,data:{task_id:"",workflow_run_id:n.data.workflow_run_id||r,status:o.status||"unknown",outputs:o.outputs||{},error:o.error||null,elapsed_time:o.elapsed_time||0,total_tokens:o.total_tokens||0,total_steps:o.total_steps||0,created_at:o.created_at||0,finished_at:o.finished_at||0,...o.usage?{usage:o.usage}:{}}}}return {data:null,error:n.error||{status:n.status,message:"Invalid workflow run detail response structure"},status:n.status}}}}var d=class extends Error{constructor(e,r,s){super(e),this.name="ChatflowStreamError",this.status=r,this.details=s;}};function W(t,e){let r=t.trim();if(!r||r.includes("/"))throw new d(`Invalid ${e}: use a non-empty value without subpaths`,400);return encodeURIComponent(r)}function w(t){return `/api/runchatflow/${W(t,"chatflowName")}`}function T(t,e){let r=t?.trim().replace(/\/+$/,"");return r?`${r}${e}`:e}function C(t,e){return {...t,inputs:t.inputs??{},response_mode:e}}async function A(t){let e=await t.text();if(!e)return null;try{return JSON.parse(e)}catch{return e}}function E(t,e){if(e&&typeof e=="object"){let r=e;for(let s of ["message","error","detail"])if(typeof r[s]=="string"&&r[s])return r[s]}return typeof e=="string"&&e?e:`Chatflow stream request failed with status ${t}`}function I(t=createHttpClient(),e={}){return {async run(r,s){try{return await t.request({url:w(r),method:"post",headers:{"Content-Type":"application/json"},data:C(s,"blocking")})}catch(a){return {data:null,error:{status:400,message:a instanceof Error?a.message:String(a)},status:400}}},async*stream(r,s,a={}){let n=e.fetch??globalThis.fetch?.bind(globalThis);if(typeof n!="function")throw new d("Fetch API not found. Provide ChatflowClientOptions.fetch.",0);let o=new Headers(e.headers);o.set("Accept","text/event-stream"),o.set("Content-Type","application/json");let g=e.getAccessToken?.();g&&o.set("Authorization",`Bearer ${g}`);let i=await n(T(e.baseURL,w(r)),{method:"POST",headers:o,credentials:e.credentials??"include",body:JSON.stringify(C(s,"streaming")),signal:a.signal});if(!i.ok){let l=await A(i);throw i.status===401&&e.onUnauthorized?.(),new d(E(i.status,l),i.status,l)}if(!i.body)throw new d("Chatflow stream response has no body",i.status);let p=i.body.getReader(),k=new TextDecoder,c=[],m=[],R=false,_=createParser({onEvent(l){if(!(!l.data||l.data==="[DONE]"))try{let u=JSON.parse(l.data);u&&typeof u=="object"&&typeof u.event=="string"&&c.push(u);}catch(u){m.push(u instanceof Error?u:new Error(String(u)));}}});try{for(;;){let{done:l,value:u}=await p.read();l?(_.feed(k.decode()),R=!0):_.feed(k.decode(u,{stream:!0}));let y=m.shift();if(y)throw new d(`Failed to parse chatflow SSE event: ${y.message}`,i.status);for(;c.length>0;){let h=c.shift();h&&(yield h);}if(l)break}}finally{R||await p.cancel(),p.releaseLock();}},async stop(r,s,a={}){try{return await t.request({url:`${w(r)}/tasks/${W(s,"taskId")}/stop`,method:"post",headers:{"Content-Type":"application/json"},data:a})}catch(n){return {data:null,error:{status:400,message:n instanceof Error?n.message:String(n)},status:400}}}}}export{d as ChatflowStreamError,I as createChatflowClient,v as createWorkflowClient};//# sourceMappingURL=index.js.map
1
+ import {createHttpClient}from'@amaster.ai/http-client';import {createParser}from'eventsource-parser';function v(r){if(!r)return {inputs:{},response_mode:"blocking",user:"anonymous"};if(typeof r=="object"&&T(r)){let e=r;return {inputs:e.inputs||{},response_mode:e.response_mode||"blocking",user:e.user||"anonymous",files:e.files,trace_id:e.trace_id,usage:e.usage,usage_detail:e.usage_detail,callback:e.callback}}return {inputs:r,response_mode:"blocking",user:"anonymous"}}function T(r){let e=["inputs","response_mode","user","files","trace_id","usage","usage_detail","callback"],s=["inputs","response_mode","user","files","trace_id"],a=Object.keys(r);return s.some(o=>o in r)?true:a.length>0&&a.every(o=>e.includes(o))}function w(r){return !r||r.includes("/")?{data:null,error:{status:400,message:"Invalid workflowName: use workflow YAML filename without extension (no subpaths)"},status:400}:null}function E(r=createHttpClient()){return {async run(e,s){let a=w(e);if(a)return a;let o=v(s),t=await r.request({url:`/api/runworkflow/${e}`,method:"post",headers:{"Content-Type":"application/json"},data:o});if(t.data?.data){let n=t.data.data;return {...t,data:{task_id:t.data.task_id||"",workflow_run_id:t.data.workflow_run_id||"",status:n.status||"unknown",outputs:n.outputs||{},error:n.error||null,elapsed_time:n.elapsed_time||0,total_tokens:n.total_tokens||0,total_steps:n.total_steps||0,created_at:n.created_at||0,finished_at:n.finished_at||0,...n.usage?{usage:n.usage}:{}}}}return {...t,data:null,error:t.error||{status:t.status,message:"Invalid workflow response structure"},status:t.status}},async runAsync(e,s){let a=w(e);if(a)return a;let o=v(s);o.response_mode="async";let t=await r.request({url:`/api/runworkflow/${e}`,method:"post",headers:{"Content-Type":"application/json"},data:o});return t.data?.async_run_id?t:{...t,data:null,error:t.error||{status:t.status,message:"Invalid workflow async run response structure"},status:t.status}},async getAsyncRun(e,s){let a=w(e);if(a)return a;let o=await r.request({url:`/api/runworkflow/${e}/async-runs/${s}`,method:"get"});return o.data?.async_run_id?o:{...o,data:null,error:o.error||{status:o.status,message:"Invalid workflow async run detail response structure"},status:o.status}},async getRun(e,s,a={}){let o=w(e);if(o)return o;let t=await r.request({url:`/api/runworkflow/${e}/runs/${s}`,method:"get",params:{...a.usage!==void 0?{usage:a.usage}:{},...a.usage_detail!==void 0?{usage_detail:a.usage_detail}:{}}});if(t.data?.data){let n=t.data.data;return {...t,data:{task_id:"",workflow_run_id:t.data.workflow_run_id||s,status:n.status||"unknown",outputs:n.outputs||{},error:n.error||null,elapsed_time:n.elapsed_time||0,total_tokens:n.total_tokens||0,total_steps:n.total_steps||0,created_at:n.created_at||0,finished_at:n.finished_at||0,...n.usage?{usage:n.usage}:{}}}}return {...t,data:null,error:t.error||{status:t.status,message:"Invalid workflow run detail response structure"},status:t.status}}}}var d=class extends Error{constructor(e,s,a){super(e),this.name="ChatflowStreamError",this.status=s,this.details=a;}};function S(r,e){let s=r.trim();if(!s||s.includes("/"))throw new d(`Invalid ${e}: use a non-empty value without subpaths`,400);return encodeURIComponent(s)}function m(r){return `/api/runchatflow/${S(r,"chatflowName")}`}function U(r,e){let s=r?.trim().replace(/\/+$/,"");return s?`${s}${e}`:e}function x(r,e){return {...r,inputs:r.inputs??{},response_mode:e}}async function $(r){let e=await r.text();if(!e)return null;try{return JSON.parse(e)}catch{return e}}function D(r,e){if(e&&typeof e=="object"){let s=e;for(let a of ["message","error","detail"])if(typeof s[a]=="string"&&s[a])return s[a]}return typeof e=="string"&&e?e:`Chatflow stream request failed with status ${r}`}function N(r=createHttpClient(),e={}){return {async run(s,a){try{return await r.request({url:m(s),method:"post",headers:{"Content-Type":"application/json"},data:x(a,"blocking")})}catch(o){return {data:null,error:{status:400,message:o instanceof Error?o.message:String(o)},status:400}}},async*stream(s,a,o={}){await e.beforeStream?.();let t=e.requestScope,n=t?.capture(),R=e.fetch??globalThis.fetch?.bind(globalThis);if(typeof R!="function")throw new d("Fetch API not found. Provide ChatflowClientOptions.fetch.",0);let f=new Headers(e.headers);f.set("Accept","text/event-stream"),f.set("Content-Type","application/json");let _=e.getAccessToken?.();if(_&&f.set("Authorization",`Bearer ${_}`),t&&n){let u=t.headers(n,Object.fromEntries(f.entries()));for(let[c,g]of Object.entries(u))f.set(c,g);}let y=typeof AbortController>"u"?void 0:new AbortController,p=()=>y?.abort(),O=t&&n?t.onInvalidate(n,p):void 0;o.signal?.addEventListener("abort",p,{once:true}),o.signal?.aborted&&p();try{let u=await R(U(e.baseURL,m(s)),{method:"POST",headers:f,credentials:e.credentials??"include",body:JSON.stringify(x(a,"streaming")),signal:y?.signal??o.signal??n?.signal});if(n&&t.assertCurrent(n),!u.ok){let l=await $(u);throw u.status===401&&e.onUnauthorized?.(),new d(D(u.status,l),u.status,l)}if(!u.body)throw new d("Chatflow stream response has no body",u.status);let c=u.body.getReader(),g=new TextDecoder,k=[],h=[],b=!1,C=createParser({onEvent(l){if(!(!l.data||l.data==="[DONE]"))try{let i=JSON.parse(l.data);i&&typeof i=="object"&&typeof i.event=="string"&&k.push(i);}catch(i){h.push(i instanceof Error?i:new Error(String(i)));}}});try{for(;;){let{done:l,value:i}=await c.read();n&&t.assertCurrent(n),l?(C.feed(g.decode()),b=!0):C.feed(g.decode(i,{stream:!0}));let W=h.shift();if(W)throw new d(`Failed to parse chatflow SSE event: ${W.message}`,u.status);for(;k.length>0;){let q=k.shift();q&&(n&&t.assertCurrent(n),yield q);}if(l)break}}finally{b||await c.cancel(),c.releaseLock();}}finally{O?.(),o.signal?.removeEventListener("abort",p);}},async stop(s,a,o={}){try{return await r.request({url:`${m(s)}/tasks/${S(a,"taskId")}/stop`,method:"post",headers:{"Content-Type":"application/json"},data:o})}catch(t){return {data:null,error:{status:400,message:t instanceof Error?t.message:String(t)},status:400}}}}}export{d as ChatflowStreamError,N as createChatflowClient,E as createWorkflowClient};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/workflow-client.ts","../src/chatflow-client.ts"],"names":["normalizeRunRequest","inputs","isWorkflowRunRequest","req","value","requestKeys","structuralRequestKeys","keys","key","validateWorkflowName","workflowName","createWorkflowClient","http","createHttpClient","validationError","normalizedRequest","response","innerData","asyncRunId","workflowRunId","options","ChatflowStreamError","message","status","details","validatePathSegment","fieldName","normalized","chatflowPath","chatflowName","resolveRequestURL","baseURL","path","normalizedBaseURL","normalizeRequest","request","responseMode","parseErrorResponse","text","errorMessage","payload","createChatflowClient","error","streamOptions","fetchFn","headers","accessToken","reader","decoder","pendingEvents","parseErrors","completed","parser","createParser","event","parsed","done","parseError","taskId"],"mappings":"qGAgJA,SAASA,EACPC,CAAAA,CACoB,CACpB,GAAI,CAACA,CAAAA,CACH,OAAO,CAAE,MAAA,CAAQ,EAAC,CAAG,aAAA,CAAe,UAAA,CAAY,IAAA,CAAM,WAAY,CAAA,CAGpE,GAAI,OAAOA,GAAW,QAAA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ACR,CAAC,CACH,CAAA,MAASO,CAAAA,CAAO,CAEd,OAAO,CACL,KAAM,IAAA,CACN,KAAA,CAAO,CAAE,MAAA,CAAQ,GAAA,CAAK,OAAA,CAHRA,CAAAA,YAAiB,KAAA,CAAQA,EAAM,OAAA,CAAU,MAAA,CAAOA,CAAK,CAGrC,EAC9B,MAAA,CAAQ,GACV,CACF,CACF,CACF,CACF","file":"index.js","sourcesContent":["import { type ClientResult, createHttpClient, type HttpClient } from \"@amaster.ai/http-client\";\n\nexport type WorkflowResponseMode = \"blocking\" | \"streaming\" | \"async\";\n\nexport type WorkflowInputValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | Record<string, unknown>\n | unknown[];\n\nexport type WorkflowFile = {\n name?: string;\n type?: string;\n url?: string;\n [key: string]: unknown;\n};\n\nexport type WorkflowRunRequest = {\n inputs?: Record<string, WorkflowInputValue>;\n response_mode?: WorkflowResponseMode;\n user?: string;\n files?: WorkflowFile[];\n trace_id?: string;\n usage?: boolean;\n usage_detail?: boolean;\n callback?: WorkflowCallbackConfig;\n};\n\nexport type WorkflowCallbackConfig = {\n name?: string;\n include_outputs?: boolean;\n include_usage?: boolean;\n usage_detail?: boolean;\n};\n\nexport type WorkflowUsageSummary = {\n workflow_run_id: string;\n status: string;\n total_tokens: number;\n workflow_run_total_tokens?: number;\n node_usage_total_tokens?: number;\n billable_total_tokens?: number;\n total_steps: number;\n elapsed_time: number;\n created_at: number | null;\n finished_at: number | null;\n is_finished: boolean;\n};\n\nexport type WorkflowNodeUsage = {\n id: string;\n node_execution_id: string | null;\n index: number;\n node_id: string;\n node_type: string;\n title: string;\n status: string;\n error: string | null;\n elapsed_time: number;\n created_at: number | null;\n finished_at: number | null;\n usage: Record<string, unknown>;\n execution_metadata: Record<string, unknown>;\n};\n\nexport type WorkflowRunUsage = {\n summary: WorkflowUsageSummary;\n estimated_price_by_currency?: Record<string, string>;\n nodes?: WorkflowNodeUsage[];\n};\n\nexport type WorkflowRunResponse<TOutput = Record<string, unknown>> = {\n task_id: string;\n workflow_run_id: string;\n status: string;\n outputs: TOutput;\n error: string | null;\n elapsed_time: number;\n total_tokens: number;\n total_steps: number;\n created_at: number;\n finished_at: number;\n usage?: WorkflowRunUsage;\n};\n\nexport type WorkflowAsyncRunStatus =\n | \"pending\"\n | \"queued\"\n | \"running\"\n | \"succeeded\"\n | \"failed\"\n | \"paused\"\n | \"rate_limited\"\n | \"retrying\"\n | string;\n\nexport type WorkflowAsyncRunResponse = {\n async_run_id: string;\n workflow_trigger_log_id: string;\n workflow_run_id: string | null;\n task_id?: string;\n status: WorkflowAsyncRunStatus;\n queue?: string;\n created_at?: number | null;\n};\n\nexport type WorkflowAsyncRunDetailResponse = WorkflowAsyncRunResponse & {\n workflow_id?: string;\n error?: string | null;\n outputs?: Record<string, unknown> | null;\n elapsed_time?: number | null;\n total_tokens?: number | null;\n triggered_at?: number | null;\n finished_at?: number | null;\n};\n\nexport type WorkflowRunDetailOptions = {\n usage?: boolean;\n usage_detail?: boolean;\n};\n\nexport type WorkflowClient = {\n run<TOutput = Record<string, unknown>>(\n workflowName: string,\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n ): Promise<ClientResult<WorkflowRunResponse<TOutput>>>;\n runAsync(\n workflowName: string,\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n ): Promise<ClientResult<WorkflowAsyncRunResponse>>;\n getAsyncRun(\n workflowName: string,\n asyncRunId: string\n ): Promise<ClientResult<WorkflowAsyncRunDetailResponse>>;\n getRun<TOutput = Record<string, unknown>>(\n workflowName: string,\n workflowRunId: string,\n options?: WorkflowRunDetailOptions\n ): Promise<ClientResult<WorkflowRunResponse<TOutput>>>;\n};\n\nfunction normalizeRunRequest(\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n): WorkflowRunRequest {\n if (!inputs) {\n return { inputs: {}, response_mode: \"blocking\", user: \"anonymous\" };\n }\n\n if (typeof inputs === \"object\" && isWorkflowRunRequest(inputs)) {\n const req = inputs as WorkflowRunRequest;\n return {\n inputs: req.inputs || {},\n response_mode: req.response_mode || \"blocking\",\n user: req.user || \"anonymous\",\n files: req.files,\n trace_id: req.trace_id,\n usage: req.usage,\n usage_detail: req.usage_detail,\n callback: req.callback,\n };\n }\n\n return {\n inputs: inputs as Record<string, WorkflowInputValue>,\n response_mode: \"blocking\",\n user: \"anonymous\",\n };\n}\n\nfunction isWorkflowRunRequest(value: Record<string, unknown>): boolean {\n const requestKeys = [\"inputs\", \"response_mode\", \"user\", \"files\", \"trace_id\", \"usage\", \"usage_detail\", \"callback\"];\n const structuralRequestKeys = [\"inputs\", \"response_mode\", \"user\", \"files\", \"trace_id\"];\n const keys = Object.keys(value);\n\n if (structuralRequestKeys.some((key) => key in value)) {\n return true;\n }\n\n return keys.length > 0 && keys.every((key) => requestKeys.includes(key));\n}\n\nfunction validateWorkflowName(workflowName: string): ClientResult<never> | null {\n if (!workflowName || workflowName.includes(\"/\")) {\n return {\n data: null,\n error: {\n status: 400,\n message:\n \"Invalid workflowName: use workflow YAML filename without extension (no subpaths)\",\n },\n status: 400,\n };\n }\n return null;\n}\n\nexport function createWorkflowClient(http: HttpClient = createHttpClient()): WorkflowClient {\n return {\n async run<TOutput = Record<string, unknown>>(\n workflowName: string,\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n ): Promise<ClientResult<WorkflowRunResponse<TOutput>>> {\n const validationError = validateWorkflowName(workflowName);\n if (validationError) {\n return validationError;\n }\n\n const normalizedRequest = normalizeRunRequest(inputs);\n\n const response = await http.request<{\n data: {\n status: string;\n outputs: TOutput;\n error: string | null;\n elapsed_time: number;\n total_tokens: number;\n total_steps: number;\n created_at: number;\n finished_at: number;\n usage?: WorkflowRunUsage;\n };\n task_id: string;\n workflow_run_id: string;\n }>({\n url: `/api/runworkflow/${workflowName}`,\n method: \"post\",\n headers: { \"Content-Type\": \"application/json\" },\n data: normalizedRequest,\n });\n\n if (response.data?.data) {\n const innerData = response.data.data;\n return {\n ...response,\n data: {\n task_id: response.data.task_id || \"\",\n workflow_run_id: response.data.workflow_run_id || \"\",\n status: innerData.status || \"unknown\",\n outputs: innerData.outputs || ({} as TOutput),\n error: innerData.error || null,\n elapsed_time: innerData.elapsed_time || 0,\n total_tokens: innerData.total_tokens || 0,\n total_steps: innerData.total_steps || 0,\n created_at: innerData.created_at || 0,\n finished_at: innerData.finished_at || 0,\n ...(innerData.usage ? { usage: innerData.usage } : {}),\n },\n };\n }\n\n return {\n data: null,\n error: response.error || {\n status: response.status,\n message: \"Invalid workflow response structure\",\n },\n status: response.status,\n };\n },\n async runAsync(\n workflowName: string,\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n ): Promise<ClientResult<WorkflowAsyncRunResponse>> {\n const validationError = validateWorkflowName(workflowName);\n if (validationError) {\n return validationError;\n }\n\n const normalizedRequest = normalizeRunRequest(inputs);\n normalizedRequest.response_mode = \"async\";\n\n const response = await http.request<WorkflowAsyncRunResponse>({\n url: `/api/runworkflow/${workflowName}`,\n method: \"post\",\n headers: { \"Content-Type\": \"application/json\" },\n data: normalizedRequest,\n });\n\n if (response.data?.async_run_id) {\n return response;\n }\n\n return {\n data: null,\n error: response.error || {\n status: response.status,\n message: \"Invalid workflow async run response structure\",\n },\n status: response.status,\n };\n },\n async getAsyncRun(\n workflowName: string,\n asyncRunId: string\n ): Promise<ClientResult<WorkflowAsyncRunDetailResponse>> {\n const validationError = validateWorkflowName(workflowName);\n if (validationError) {\n return validationError;\n }\n\n const response = await http.request<WorkflowAsyncRunDetailResponse>({\n url: `/api/runworkflow/${workflowName}/async-runs/${asyncRunId}`,\n method: \"get\",\n });\n\n if (response.data?.async_run_id) {\n return response;\n }\n\n return {\n data: null,\n error: response.error || {\n status: response.status,\n message: \"Invalid workflow async run detail response structure\",\n },\n status: response.status,\n };\n },\n async getRun<TOutput = Record<string, unknown>>(\n workflowName: string,\n workflowRunId: string,\n options: WorkflowRunDetailOptions = {}\n ): Promise<ClientResult<WorkflowRunResponse<TOutput>>> {\n const validationError = validateWorkflowName(workflowName);\n if (validationError) {\n return validationError;\n }\n\n const response = await http.request<{\n workflow_run_id: string;\n data: {\n status: string;\n outputs: TOutput;\n error: string | null;\n elapsed_time: number;\n total_tokens: number;\n total_steps: number;\n created_at: number;\n finished_at: number;\n usage?: WorkflowRunUsage;\n };\n }>({\n url: `/api/runworkflow/${workflowName}/runs/${workflowRunId}`,\n method: \"get\",\n params: {\n ...(options.usage !== undefined ? { usage: options.usage } : {}),\n ...(options.usage_detail !== undefined ? { usage_detail: options.usage_detail } : {}),\n },\n });\n\n if (response.data?.data) {\n const innerData = response.data.data;\n return {\n ...response,\n data: {\n task_id: \"\",\n workflow_run_id: response.data.workflow_run_id || workflowRunId,\n status: innerData.status || \"unknown\",\n outputs: innerData.outputs || ({} as TOutput),\n error: innerData.error || null,\n elapsed_time: innerData.elapsed_time || 0,\n total_tokens: innerData.total_tokens || 0,\n total_steps: innerData.total_steps || 0,\n created_at: innerData.created_at || 0,\n finished_at: innerData.finished_at || 0,\n ...(innerData.usage ? { usage: innerData.usage } : {}),\n },\n };\n }\n\n return {\n data: null,\n error: response.error || {\n status: response.status,\n message: \"Invalid workflow run detail response structure\",\n },\n status: response.status,\n };\n },\n };\n}\n","import {\n type ClientResult,\n createHttpClient,\n type HttpClient,\n} from \"@amaster.ai/http-client\";\nimport { createParser } from \"eventsource-parser\";\nimport type { WorkflowFile, WorkflowInputValue } from \"./workflow-client\";\n\nexport type ChatflowRunRequest = {\n inputs?: Record<string, WorkflowInputValue>;\n query: string;\n files?: WorkflowFile[];\n conversation_id?: string;\n user?: string;\n retriever_from?: string;\n auto_generate_name?: boolean;\n workflow_id?: string;\n};\n\nexport type ChatflowBlockingResponse = {\n event?: string;\n task_id: string;\n message_id: string;\n conversation_id: string;\n mode?: string;\n answer: string;\n metadata?: Record<string, unknown>;\n created_at?: number;\n};\n\nexport type ChatflowEvent = {\n event: string;\n task_id?: string;\n message_id?: string;\n conversation_id?: string;\n answer?: string;\n created_at?: number;\n [key: string]: unknown;\n};\n\nexport type ChatflowStopRequest = {\n user?: string;\n};\n\nexport type ChatflowStopResponse = {\n result: string;\n};\n\nexport type ChatflowClientOptions = {\n baseURL?: string;\n headers?: Record<string, string>;\n getAccessToken?: () => string | null | undefined;\n fetch?: typeof globalThis.fetch;\n credentials?: RequestCredentials;\n onUnauthorized?: () => void;\n};\n\nexport type ChatflowStreamOptions = {\n signal?: AbortSignal;\n};\n\nexport type ChatflowClient = {\n run(\n chatflowName: string,\n request: ChatflowRunRequest,\n ): Promise<ClientResult<ChatflowBlockingResponse>>;\n stream(\n chatflowName: string,\n request: ChatflowRunRequest,\n options?: ChatflowStreamOptions,\n ): AsyncGenerator<ChatflowEvent, void, void>;\n stop(\n chatflowName: string,\n taskId: string,\n request?: ChatflowStopRequest,\n ): Promise<ClientResult<ChatflowStopResponse>>;\n};\n\nexport class ChatflowStreamError extends Error {\n readonly status: number;\n readonly details?: unknown;\n\n constructor(message: string, status: number, details?: unknown) {\n super(message);\n this.name = \"ChatflowStreamError\";\n this.status = status;\n this.details = details;\n }\n}\n\nfunction validatePathSegment(value: string, fieldName: string): string {\n const normalized = value.trim();\n if (!normalized || normalized.includes(\"/\")) {\n throw new ChatflowStreamError(\n `Invalid ${fieldName}: use a non-empty value without subpaths`,\n 400,\n );\n }\n return encodeURIComponent(normalized);\n}\n\nfunction chatflowPath(chatflowName: string): string {\n return `/api/runchatflow/${validatePathSegment(chatflowName, \"chatflowName\")}`;\n}\n\nfunction resolveRequestURL(baseURL: string | undefined, path: string): string {\n const normalizedBaseURL = baseURL?.trim().replace(/\\/+$/, \"\");\n return normalizedBaseURL ? `${normalizedBaseURL}${path}` : path;\n}\n\nfunction normalizeRequest(\n request: ChatflowRunRequest,\n responseMode: \"blocking\" | \"streaming\",\n): ChatflowRunRequest & { response_mode: \"blocking\" | \"streaming\" } {\n return {\n ...request,\n inputs: request.inputs ?? {},\n response_mode: responseMode,\n };\n}\n\nasync function parseErrorResponse(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) {\n return null;\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction errorMessage(status: number, details: unknown): string {\n if (details && typeof details === \"object\") {\n const payload = details as Record<string, unknown>;\n for (const key of [\"message\", \"error\", \"detail\"]) {\n if (typeof payload[key] === \"string\" && payload[key]) {\n return payload[key];\n }\n }\n }\n if (typeof details === \"string\" && details) {\n return details;\n }\n return `Chatflow stream request failed with status ${status}`;\n}\n\nexport function createChatflowClient(\n http: HttpClient = createHttpClient(),\n options: ChatflowClientOptions = {},\n): ChatflowClient {\n return {\n async run(chatflowName, request) {\n try {\n return await http.request<ChatflowBlockingResponse>({\n url: chatflowPath(chatflowName),\n method: \"post\",\n headers: { \"Content-Type\": \"application/json\" },\n data: normalizeRequest(request, \"blocking\"),\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n data: null,\n error: { status: 400, message },\n status: 400,\n };\n }\n },\n\n async *stream(chatflowName, request, streamOptions = {}) {\n const fetchFn = options.fetch ?? globalThis.fetch?.bind(globalThis);\n if (typeof fetchFn !== \"function\") {\n throw new ChatflowStreamError(\n \"Fetch API not found. Provide ChatflowClientOptions.fetch.\",\n 0,\n );\n }\n\n const headers = new Headers(options.headers);\n headers.set(\"Accept\", \"text/event-stream\");\n headers.set(\"Content-Type\", \"application/json\");\n const accessToken = options.getAccessToken?.();\n if (accessToken) {\n headers.set(\"Authorization\", `Bearer ${accessToken}`);\n }\n\n const response = await fetchFn(\n resolveRequestURL(options.baseURL, chatflowPath(chatflowName)),\n {\n method: \"POST\",\n headers,\n credentials: options.credentials ?? \"include\",\n body: JSON.stringify(normalizeRequest(request, \"streaming\")),\n signal: streamOptions.signal,\n },\n );\n\n if (!response.ok) {\n const details = await parseErrorResponse(response);\n if (response.status === 401) {\n options.onUnauthorized?.();\n }\n throw new ChatflowStreamError(\n errorMessage(response.status, details),\n response.status,\n details,\n );\n }\n if (!response.body) {\n throw new ChatflowStreamError(\"Chatflow stream response has no body\", response.status);\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const pendingEvents: ChatflowEvent[] = [];\n const parseErrors: Error[] = [];\n let completed = false;\n const parser = createParser({\n onEvent(event) {\n if (!event.data || event.data === \"[DONE]\") {\n return;\n }\n try {\n const parsed = JSON.parse(event.data) as unknown;\n if (\n parsed &&\n typeof parsed === \"object\" &&\n typeof (parsed as Record<string, unknown>).event === \"string\"\n ) {\n pendingEvents.push(parsed as ChatflowEvent);\n }\n } catch (error) {\n parseErrors.push(error instanceof Error ? error : new Error(String(error)));\n }\n },\n });\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n parser.feed(decoder.decode());\n completed = true;\n } else {\n parser.feed(decoder.decode(value, { stream: true }));\n }\n\n const parseError = parseErrors.shift();\n if (parseError) {\n throw new ChatflowStreamError(\n `Failed to parse chatflow SSE event: ${parseError.message}`,\n response.status,\n );\n }\n while (pendingEvents.length > 0) {\n const event = pendingEvents.shift();\n if (event) {\n yield event;\n }\n }\n if (done) {\n break;\n }\n }\n } finally {\n if (!completed) {\n await reader.cancel();\n }\n reader.releaseLock();\n }\n },\n\n async stop(chatflowName, taskId, request = {}) {\n try {\n return await http.request<ChatflowStopResponse>({\n url: `${chatflowPath(chatflowName)}/tasks/${validatePathSegment(taskId, \"taskId\")}/stop`,\n method: \"post\",\n headers: { \"Content-Type\": \"application/json\" },\n data: request,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n data: null,\n error: { status: 400, message },\n status: 400,\n };\n }\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/workflow-client.ts","../src/chatflow-client.ts"],"names":["normalizeRunRequest","inputs","isWorkflowRunRequest","req","value","requestKeys","structuralRequestKeys","keys","key","validateWorkflowName","workflowName","createWorkflowClient","http","createHttpClient","validationError","normalizedRequest","response","innerData","asyncRunId","workflowRunId","options","ChatflowStreamError","message","status","details","validatePathSegment","fieldName","normalized","chatflowPath","chatflowName","resolveRequestURL","baseURL","path","normalizedBaseURL","normalizeRequest","request","responseMode","parseErrorResponse","text","errorMessage","payload","createChatflowClient","error","streamOptions","scope","captured","fetchFn","headers","accessToken","scoped","name","controller","abort","removeScope","reader","decoder","pendingEvents","parseErrors","completed","parser","createParser","event","parsed","done","parseError","taskId"],"mappings":"qGAgJA,SAASA,EACPC,CAAAA,CACoB,CACpB,GAAI,CAACA,EACH,OAAO,CAAE,MAAA,CAAQ,GAAI,aAAA,CAAe,UAAA,CAAY,IAAA,CAAM,WAAY,EAGpE,GAAI,OAAOA,CAAAA,EAAW,QAAA,EAAYC,EAAqBD,CAAM,CAAA,CAAG,CAC9D,IAAME,EAAMF,CAAAA,CACZ,OAAO,CACL,MAAA,CAAQE,EAAI,MAAA,EAAU,EAAC,CACvB,aAAA,CAAeA,EAAI,aAAA,EAAiB,UAAA,CACpC,IAAA,CAAMA,CAAAA,CAAI,MAAQ,WAAA,CAClB,KAAA,CAAOA,CAAAA,CAAI,KAAA,CACX,SAAUA,CAAAA,CAAI,QAAA,CACd,KAAA,CAAOA,CAAAA,CAAI,MACX,YAAA,CAAcA,CAAAA,CAAI,YAAA,CAClB,QAAA,CAAUA,EAAI,QAChB,CACF,CAEA,OAAO,CACL,MAAA,CAAQF,CAAAA,CACR,aAAA,CAAe,UAAA,CACf,KAAM,WACR,CACF,CAEA,SAASC,EAAqBE,CAAAA,CAAyC,CACrE,IAAMC,CAAAA,CAAc,CAAC,QAAA,CAAU,eAAA,CAAiB,MAAA,CAAQ,OAAA,CAAS,WAAY,OAAA,CAAS,cAAA,CAAgB,UAAU,CAAA,CAC1GC,EAAwB,CAAC,QAAA,CAAU,eAAA,CAAiB,MAAA,CAAQ,QAAS,UAAU,CAAA,CAC/EC,CAAAA,CAAO,MAAA,CAAO,KAAKH,CAAK,CAAA,CAE9B,OAAIE,CAAAA,CAAsB,KAAME,CAAAA,EAAQA,CAAAA,IAAOJ,CAAK,CAAA,CAC3C,KAGFG,CAAAA,CAAK,MAAA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AA,CAHRA,CAAAA,YAAiB,KAAA,CAAQA,EAAM,OAAA,CAAU,MAAA,CAAOA,CAAK,CAGrC,EAC9B,MAAA,CAAQ,GACV,CACF,CACF,CACF,CACF","file":"index.js","sourcesContent":["import { type ClientResult, createHttpClient, type HttpClient } from \"@amaster.ai/http-client\";\n\nexport type WorkflowResponseMode = \"blocking\" | \"streaming\" | \"async\";\n\nexport type WorkflowInputValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | Record<string, unknown>\n | unknown[];\n\nexport type WorkflowFile = {\n name?: string;\n type?: string;\n url?: string;\n [key: string]: unknown;\n};\n\nexport type WorkflowRunRequest = {\n inputs?: Record<string, WorkflowInputValue>;\n response_mode?: WorkflowResponseMode;\n user?: string;\n files?: WorkflowFile[];\n trace_id?: string;\n usage?: boolean;\n usage_detail?: boolean;\n callback?: WorkflowCallbackConfig;\n};\n\nexport type WorkflowCallbackConfig = {\n name?: string;\n include_outputs?: boolean;\n include_usage?: boolean;\n usage_detail?: boolean;\n};\n\nexport type WorkflowUsageSummary = {\n workflow_run_id: string;\n status: string;\n total_tokens: number;\n workflow_run_total_tokens?: number;\n node_usage_total_tokens?: number;\n billable_total_tokens?: number;\n total_steps: number;\n elapsed_time: number;\n created_at: number | null;\n finished_at: number | null;\n is_finished: boolean;\n};\n\nexport type WorkflowNodeUsage = {\n id: string;\n node_execution_id: string | null;\n index: number;\n node_id: string;\n node_type: string;\n title: string;\n status: string;\n error: string | null;\n elapsed_time: number;\n created_at: number | null;\n finished_at: number | null;\n usage: Record<string, unknown>;\n execution_metadata: Record<string, unknown>;\n};\n\nexport type WorkflowRunUsage = {\n summary: WorkflowUsageSummary;\n estimated_price_by_currency?: Record<string, string>;\n nodes?: WorkflowNodeUsage[];\n};\n\nexport type WorkflowRunResponse<TOutput = Record<string, unknown>> = {\n task_id: string;\n workflow_run_id: string;\n status: string;\n outputs: TOutput;\n error: string | null;\n elapsed_time: number;\n total_tokens: number;\n total_steps: number;\n created_at: number;\n finished_at: number;\n usage?: WorkflowRunUsage;\n};\n\nexport type WorkflowAsyncRunStatus =\n | \"pending\"\n | \"queued\"\n | \"running\"\n | \"succeeded\"\n | \"failed\"\n | \"paused\"\n | \"rate_limited\"\n | \"retrying\"\n | string;\n\nexport type WorkflowAsyncRunResponse = {\n async_run_id: string;\n workflow_trigger_log_id: string;\n workflow_run_id: string | null;\n task_id?: string;\n status: WorkflowAsyncRunStatus;\n queue?: string;\n created_at?: number | null;\n};\n\nexport type WorkflowAsyncRunDetailResponse = WorkflowAsyncRunResponse & {\n workflow_id?: string;\n error?: string | null;\n outputs?: Record<string, unknown> | null;\n elapsed_time?: number | null;\n total_tokens?: number | null;\n triggered_at?: number | null;\n finished_at?: number | null;\n};\n\nexport type WorkflowRunDetailOptions = {\n usage?: boolean;\n usage_detail?: boolean;\n};\n\nexport type WorkflowClient = {\n run<TOutput = Record<string, unknown>>(\n workflowName: string,\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n ): Promise<ClientResult<WorkflowRunResponse<TOutput>>>;\n runAsync(\n workflowName: string,\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n ): Promise<ClientResult<WorkflowAsyncRunResponse>>;\n getAsyncRun(\n workflowName: string,\n asyncRunId: string\n ): Promise<ClientResult<WorkflowAsyncRunDetailResponse>>;\n getRun<TOutput = Record<string, unknown>>(\n workflowName: string,\n workflowRunId: string,\n options?: WorkflowRunDetailOptions\n ): Promise<ClientResult<WorkflowRunResponse<TOutput>>>;\n};\n\nfunction normalizeRunRequest(\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n): WorkflowRunRequest {\n if (!inputs) {\n return { inputs: {}, response_mode: \"blocking\", user: \"anonymous\" };\n }\n\n if (typeof inputs === \"object\" && isWorkflowRunRequest(inputs)) {\n const req = inputs as WorkflowRunRequest;\n return {\n inputs: req.inputs || {},\n response_mode: req.response_mode || \"blocking\",\n user: req.user || \"anonymous\",\n files: req.files,\n trace_id: req.trace_id,\n usage: req.usage,\n usage_detail: req.usage_detail,\n callback: req.callback,\n };\n }\n\n return {\n inputs: inputs as Record<string, WorkflowInputValue>,\n response_mode: \"blocking\",\n user: \"anonymous\",\n };\n}\n\nfunction isWorkflowRunRequest(value: Record<string, unknown>): boolean {\n const requestKeys = [\"inputs\", \"response_mode\", \"user\", \"files\", \"trace_id\", \"usage\", \"usage_detail\", \"callback\"];\n const structuralRequestKeys = [\"inputs\", \"response_mode\", \"user\", \"files\", \"trace_id\"];\n const keys = Object.keys(value);\n\n if (structuralRequestKeys.some((key) => key in value)) {\n return true;\n }\n\n return keys.length > 0 && keys.every((key) => requestKeys.includes(key));\n}\n\nfunction validateWorkflowName(workflowName: string): ClientResult<never> | null {\n if (!workflowName || workflowName.includes(\"/\")) {\n return {\n data: null,\n error: {\n status: 400,\n message:\n \"Invalid workflowName: use workflow YAML filename without extension (no subpaths)\",\n },\n status: 400,\n };\n }\n return null;\n}\n\nexport function createWorkflowClient(http: HttpClient = createHttpClient()): WorkflowClient {\n return {\n async run<TOutput = Record<string, unknown>>(\n workflowName: string,\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n ): Promise<ClientResult<WorkflowRunResponse<TOutput>>> {\n const validationError = validateWorkflowName(workflowName);\n if (validationError) {\n return validationError;\n }\n\n const normalizedRequest = normalizeRunRequest(inputs);\n\n const response = await http.request<{\n data: {\n status: string;\n outputs: TOutput;\n error: string | null;\n elapsed_time: number;\n total_tokens: number;\n total_steps: number;\n created_at: number;\n finished_at: number;\n usage?: WorkflowRunUsage;\n };\n task_id: string;\n workflow_run_id: string;\n }>({\n url: `/api/runworkflow/${workflowName}`,\n method: \"post\",\n headers: { \"Content-Type\": \"application/json\" },\n data: normalizedRequest,\n });\n\n if (response.data?.data) {\n const innerData = response.data.data;\n return {\n ...response,\n data: {\n task_id: response.data.task_id || \"\",\n workflow_run_id: response.data.workflow_run_id || \"\",\n status: innerData.status || \"unknown\",\n outputs: innerData.outputs || ({} as TOutput),\n error: innerData.error || null,\n elapsed_time: innerData.elapsed_time || 0,\n total_tokens: innerData.total_tokens || 0,\n total_steps: innerData.total_steps || 0,\n created_at: innerData.created_at || 0,\n finished_at: innerData.finished_at || 0,\n ...(innerData.usage ? { usage: innerData.usage } : {}),\n },\n };\n }\n\n return {\n ...response,\n data: null,\n error: response.error || {\n status: response.status,\n message: \"Invalid workflow response structure\",\n },\n status: response.status,\n };\n },\n async runAsync(\n workflowName: string,\n inputs?: Record<string, WorkflowInputValue> | WorkflowRunRequest\n ): Promise<ClientResult<WorkflowAsyncRunResponse>> {\n const validationError = validateWorkflowName(workflowName);\n if (validationError) {\n return validationError;\n }\n\n const normalizedRequest = normalizeRunRequest(inputs);\n normalizedRequest.response_mode = \"async\";\n\n const response = await http.request<WorkflowAsyncRunResponse>({\n url: `/api/runworkflow/${workflowName}`,\n method: \"post\",\n headers: { \"Content-Type\": \"application/json\" },\n data: normalizedRequest,\n });\n\n if (response.data?.async_run_id) {\n return response;\n }\n\n return {\n ...response,\n data: null,\n error: response.error || {\n status: response.status,\n message: \"Invalid workflow async run response structure\",\n },\n status: response.status,\n };\n },\n async getAsyncRun(\n workflowName: string,\n asyncRunId: string\n ): Promise<ClientResult<WorkflowAsyncRunDetailResponse>> {\n const validationError = validateWorkflowName(workflowName);\n if (validationError) {\n return validationError;\n }\n\n const response = await http.request<WorkflowAsyncRunDetailResponse>({\n url: `/api/runworkflow/${workflowName}/async-runs/${asyncRunId}`,\n method: \"get\",\n });\n\n if (response.data?.async_run_id) {\n return response;\n }\n\n return {\n ...response,\n data: null,\n error: response.error || {\n status: response.status,\n message: \"Invalid workflow async run detail response structure\",\n },\n status: response.status,\n };\n },\n async getRun<TOutput = Record<string, unknown>>(\n workflowName: string,\n workflowRunId: string,\n options: WorkflowRunDetailOptions = {}\n ): Promise<ClientResult<WorkflowRunResponse<TOutput>>> {\n const validationError = validateWorkflowName(workflowName);\n if (validationError) {\n return validationError;\n }\n\n const response = await http.request<{\n workflow_run_id: string;\n data: {\n status: string;\n outputs: TOutput;\n error: string | null;\n elapsed_time: number;\n total_tokens: number;\n total_steps: number;\n created_at: number;\n finished_at: number;\n usage?: WorkflowRunUsage;\n };\n }>({\n url: `/api/runworkflow/${workflowName}/runs/${workflowRunId}`,\n method: \"get\",\n params: {\n ...(options.usage !== undefined ? { usage: options.usage } : {}),\n ...(options.usage_detail !== undefined ? { usage_detail: options.usage_detail } : {}),\n },\n });\n\n if (response.data?.data) {\n const innerData = response.data.data;\n return {\n ...response,\n data: {\n task_id: \"\",\n workflow_run_id: response.data.workflow_run_id || workflowRunId,\n status: innerData.status || \"unknown\",\n outputs: innerData.outputs || ({} as TOutput),\n error: innerData.error || null,\n elapsed_time: innerData.elapsed_time || 0,\n total_tokens: innerData.total_tokens || 0,\n total_steps: innerData.total_steps || 0,\n created_at: innerData.created_at || 0,\n finished_at: innerData.finished_at || 0,\n ...(innerData.usage ? { usage: innerData.usage } : {}),\n },\n };\n }\n\n return {\n ...response,\n data: null,\n error: response.error || {\n status: response.status,\n message: \"Invalid workflow run detail response structure\",\n },\n status: response.status,\n };\n },\n };\n}\n","import {\n type ClientResult,\n createHttpClient,\n type HttpClient,\n type RequestScopeController,\n} from \"@amaster.ai/http-client\";\nimport { createParser } from \"eventsource-parser\";\nimport type { WorkflowFile, WorkflowInputValue } from \"./workflow-client\";\n\nexport type ChatflowRunRequest = {\n inputs?: Record<string, WorkflowInputValue>;\n query: string;\n files?: WorkflowFile[];\n conversation_id?: string;\n user?: string;\n retriever_from?: string;\n auto_generate_name?: boolean;\n workflow_id?: string;\n};\n\nexport type ChatflowBlockingResponse = {\n event?: string;\n task_id: string;\n message_id: string;\n conversation_id: string;\n mode?: string;\n answer: string;\n metadata?: Record<string, unknown>;\n created_at?: number;\n};\n\nexport type ChatflowEvent = {\n event: string;\n task_id?: string;\n message_id?: string;\n conversation_id?: string;\n answer?: string;\n created_at?: number;\n [key: string]: unknown;\n};\n\nexport type ChatflowStopRequest = {\n user?: string;\n};\n\nexport type ChatflowStopResponse = {\n result: string;\n};\n\nexport type ChatflowClientOptions = {\n baseURL?: string;\n headers?: Record<string, string>;\n getAccessToken?: () => string | null | undefined;\n fetch?: typeof globalThis.fetch;\n credentials?: RequestCredentials;\n onUnauthorized?: () => void;\n requestScope?: RequestScopeController;\n beforeStream?: () => Promise<void>;\n};\n\nexport type ChatflowStreamOptions = {\n signal?: AbortSignal;\n};\n\nexport type ChatflowClient = {\n run(\n chatflowName: string,\n request: ChatflowRunRequest,\n ): Promise<ClientResult<ChatflowBlockingResponse>>;\n stream(\n chatflowName: string,\n request: ChatflowRunRequest,\n options?: ChatflowStreamOptions,\n ): AsyncGenerator<ChatflowEvent, void, void>;\n stop(\n chatflowName: string,\n taskId: string,\n request?: ChatflowStopRequest,\n ): Promise<ClientResult<ChatflowStopResponse>>;\n};\n\nexport class ChatflowStreamError extends Error {\n readonly status: number;\n readonly details?: unknown;\n\n constructor(message: string, status: number, details?: unknown) {\n super(message);\n this.name = \"ChatflowStreamError\";\n this.status = status;\n this.details = details;\n }\n}\n\nfunction validatePathSegment(value: string, fieldName: string): string {\n const normalized = value.trim();\n if (!normalized || normalized.includes(\"/\")) {\n throw new ChatflowStreamError(\n `Invalid ${fieldName}: use a non-empty value without subpaths`,\n 400,\n );\n }\n return encodeURIComponent(normalized);\n}\n\nfunction chatflowPath(chatflowName: string): string {\n return `/api/runchatflow/${validatePathSegment(chatflowName, \"chatflowName\")}`;\n}\n\nfunction resolveRequestURL(baseURL: string | undefined, path: string): string {\n const normalizedBaseURL = baseURL?.trim().replace(/\\/+$/, \"\");\n return normalizedBaseURL ? `${normalizedBaseURL}${path}` : path;\n}\n\nfunction normalizeRequest(\n request: ChatflowRunRequest,\n responseMode: \"blocking\" | \"streaming\",\n): ChatflowRunRequest & { response_mode: \"blocking\" | \"streaming\" } {\n return {\n ...request,\n inputs: request.inputs ?? {},\n response_mode: responseMode,\n };\n}\n\nasync function parseErrorResponse(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) {\n return null;\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction errorMessage(status: number, details: unknown): string {\n if (details && typeof details === \"object\") {\n const payload = details as Record<string, unknown>;\n for (const key of [\"message\", \"error\", \"detail\"]) {\n if (typeof payload[key] === \"string\" && payload[key]) {\n return payload[key];\n }\n }\n }\n if (typeof details === \"string\" && details) {\n return details;\n }\n return `Chatflow stream request failed with status ${status}`;\n}\n\nexport function createChatflowClient(\n http: HttpClient = createHttpClient(),\n options: ChatflowClientOptions = {},\n): ChatflowClient {\n return {\n async run(chatflowName, request) {\n try {\n return await http.request<ChatflowBlockingResponse>({\n url: chatflowPath(chatflowName),\n method: \"post\",\n headers: { \"Content-Type\": \"application/json\" },\n data: normalizeRequest(request, \"blocking\"),\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n data: null,\n error: { status: 400, message },\n status: 400,\n };\n }\n },\n\n async *stream(chatflowName, request, streamOptions = {}) {\n await options.beforeStream?.();\n const scope = options.requestScope;\n const captured = scope?.capture();\n const fetchFn = options.fetch ?? globalThis.fetch?.bind(globalThis);\n if (typeof fetchFn !== \"function\") {\n throw new ChatflowStreamError(\n \"Fetch API not found. Provide ChatflowClientOptions.fetch.\",\n 0,\n );\n }\n\n const headers = new Headers(options.headers);\n headers.set(\"Accept\", \"text/event-stream\");\n headers.set(\"Content-Type\", \"application/json\");\n const accessToken = options.getAccessToken?.();\n if (accessToken) {\n headers.set(\"Authorization\", `Bearer ${accessToken}`);\n }\n\n if (scope && captured) {\n const scoped = scope.headers(captured, Object.fromEntries(headers.entries()));\n for (const [name, value] of Object.entries(scoped)) headers.set(name, value);\n }\n const controller = typeof AbortController === \"undefined\" ? undefined : new AbortController();\n const abort = () => controller?.abort();\n const removeScope = scope && captured ? scope.onInvalidate(captured, abort) : undefined;\n streamOptions.signal?.addEventListener(\"abort\", abort, { once: true });\n if (streamOptions.signal?.aborted) abort();\n\n try {\n\n const response = await fetchFn(\n resolveRequestURL(options.baseURL, chatflowPath(chatflowName)),\n {\n method: \"POST\",\n headers,\n credentials: options.credentials ?? \"include\",\n body: JSON.stringify(normalizeRequest(request, \"streaming\")),\n signal: controller?.signal ?? streamOptions.signal ?? captured?.signal,\n },\n );\n if (captured) scope!.assertCurrent(captured);\n\n if (!response.ok) {\n const details = await parseErrorResponse(response);\n if (response.status === 401) {\n options.onUnauthorized?.();\n }\n throw new ChatflowStreamError(\n errorMessage(response.status, details),\n response.status,\n details,\n );\n }\n if (!response.body) {\n throw new ChatflowStreamError(\"Chatflow stream response has no body\", response.status);\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const pendingEvents: ChatflowEvent[] = [];\n const parseErrors: Error[] = [];\n let completed = false;\n const parser = createParser({\n onEvent(event) {\n if (!event.data || event.data === \"[DONE]\") {\n return;\n }\n try {\n const parsed = JSON.parse(event.data) as unknown;\n if (\n parsed &&\n typeof parsed === \"object\" &&\n typeof (parsed as Record<string, unknown>).event === \"string\"\n ) {\n pendingEvents.push(parsed as ChatflowEvent);\n }\n } catch (error) {\n parseErrors.push(error instanceof Error ? error : new Error(String(error)));\n }\n },\n });\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (captured) scope!.assertCurrent(captured);\n if (done) {\n parser.feed(decoder.decode());\n completed = true;\n } else {\n parser.feed(decoder.decode(value, { stream: true }));\n }\n\n const parseError = parseErrors.shift();\n if (parseError) {\n throw new ChatflowStreamError(\n `Failed to parse chatflow SSE event: ${parseError.message}`,\n response.status,\n );\n }\n while (pendingEvents.length > 0) {\n const event = pendingEvents.shift();\n if (event) {\n if (captured) scope!.assertCurrent(captured);\n yield event;\n }\n }\n if (done) {\n break;\n }\n }\n } finally {\n if (!completed) {\n await reader.cancel();\n }\n reader.releaseLock();\n }\n } finally {\n removeScope?.();\n streamOptions.signal?.removeEventListener(\"abort\", abort);\n }\n },\n\n async stop(chatflowName, taskId, request = {}) {\n try {\n return await http.request<ChatflowStopResponse>({\n url: `${chatflowPath(chatflowName)}/tasks/${validatePathSegment(taskId, \"taskId\")}/stop`,\n method: \"post\",\n headers: { \"Content-Type\": \"application/json\" },\n data: request,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n data: null,\n error: { status: 400, message },\n status: 400,\n };\n }\n },\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amaster.ai/workflow-client",
3
- "version": "1.1.72",
3
+ "version": "1.1.74",
4
4
  "description": "Workflow execution client",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -31,7 +31,7 @@
31
31
  },
32
32
  "dependencies": {
33
33
  "eventsource-parser": "^3.0.6",
34
- "@amaster.ai/http-client": "1.1.72"
34
+ "@amaster.ai/http-client": "1.1.74"
35
35
  },
36
36
  "peerDependencies": {
37
37
  "axios": "^1.11.0"