@amaster.ai/workflow-client 1.1.58 → 1.1.59-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +59 -1
- package/dist/index.d.ts +59 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +7 -4
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var httpClient=require('@amaster.ai/http-client');function
|
|
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
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/workflow-client.ts"],"names":["normalizeRunRequest","inputs","isWorkflowRunRequest","req","value","requestKeys","structuralRequestKeys","keys","key","validateWorkflowName","workflowName","createWorkflowClient","http","createHttpClient","validationError","normalizedRequest","response","innerData","asyncRunId","workflowRunId","options"],"mappings":"+DAgJA,SAASA,CAAAA,CACPC,CAAAA,CACoB,CACpB,GAAI,CAACA,CAAAA,CACH,OAAO,CAAE,OAAQ,EAAC,CAAG,aAAA,CAAe,UAAA,CAAY,IAAA,CAAM,WAAY,CAAA,CAGpE,GAAI,OAAOA,CAAAA,EAAW,QAAA,EAAYC,CAAAA,CAAqBD,CAAM,CAAA,CAAG,CAC9D,IAAME,EAAMF,CAAAA,CACZ,OAAO,CACL,MAAA,CAAQE,CAAAA,CAAI,MAAA,EAAU,EAAC,CACvB,aAAA,CAAeA,CAAAA,CAAI,aAAA,EAAiB,UAAA,CACpC,IAAA,CAAMA,CAAAA,CAAI,IAAA,EAAQ,WAAA,CAClB,MAAOA,CAAAA,CAAI,KAAA,CACX,QAAA,CAAUA,CAAAA,CAAI,QAAA,CACd,KAAA,CAAOA,CAAAA,CAAI,KAAA,CACX,aAAcA,CAAAA,CAAI,YAAA,CAClB,QAAA,CAAUA,CAAAA,CAAI,QAChB,CACF,CAEA,OAAO,CACL,MAAA,CAAQF,CAAAA,CACR,aAAA,CAAe,UAAA,CACf,IAAA,CAAM,WACR,CACF,CAEA,SAASC,CAAAA,CAAqBE,CAAAA,CAAyC,CACrE,IAAMC,CAAAA,CAAc,CAAC,QAAA,CAAU,gBAAiB,MAAA,CAAQ,OAAA,CAAS,UAAA,CAAY,OAAA,CAAS,cAAA,CAAgB,UAAU,CAAA,CAC1GC,CAAAA,CAAwB,CAAC,QAAA,CAAU,eAAA,CAAiB,MAAA,CAAQ,OAAA,CAAS,UAAU,CAAA,CAC/EC,CAAAA,CAAO,OAAO,IAAA,CAAKH,CAAK,CAAA,CAE9B,OAAIE,CAAAA,CAAsB,IAAA,CAAME,CAAAA,EAAQA,CAAAA,IAAOJ,CAAK,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AAA,EAAM,IAAA,CAAM,CACvB,IAAMC,CAAAA,CAAYD,CAAAA,CAAS,KAAK,IAAA,CAChC,OAAO,CACL,GAAGA,CAAAA,CACH,IAAA,CAAM,CACJ,OAAA,CAAS,GACT,eAAA,CAAiBA,CAAAA,CAAS,IAAA,CAAK,eAAA,EAAmBG,CAAAA,CAClD,MAAA,CAAQF,CAAAA,CAAU,MAAA,EAAU,SAAA,CAC5B,OAAA,CAASA,CAAAA,CAAU,OAAA,EAAY,EAAC,CAChC,KAAA,CAAOA,CAAAA,CAAU,OAAS,IAAA,CAC1B,YAAA,CAAcA,CAAAA,CAAU,YAAA,EAAgB,CAAA,CACxC,YAAA,CAAcA,CAAAA,CAAU,YAAA,EAAgB,EACxC,WAAA,CAAaA,CAAAA,CAAU,WAAA,EAAe,CAAA,CACtC,UAAA,CAAYA,CAAAA,CAAU,UAAA,EAAc,CAAA,CACpC,YAAaA,CAAAA,CAAU,WAAA,EAAe,CAAA,CACtC,GAAIA,CAAAA,CAAU,KAAA,CAAQ,CAAE,KAAA,CAAOA,CAAAA,CAAU,KAAM,CAAA,CAAI,EACrD,CACF,CACF,CAEA,OAAO,CACL,IAAA,CAAM,IAAA,CACN,KAAA,CAAOD,CAAAA,CAAS,KAAA,EAAS,CACvB,MAAA,CAAQA,EAAS,MAAA,CACjB,OAAA,CAAS,gDACX,CAAA,CACA,MAAA,CAAQA,CAAAA,CAAS,MACnB,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"]}
|
|
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,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,EAAYC,CAAAA,CAAqBD,CAAM,CAAA,CAAG,CAC9D,IAAME,CAAAA,CAAMF,CAAAA,CACZ,OAAO,CACL,MAAA,CAAQE,CAAAA,CAAI,MAAA,EAAU,EAAC,CACvB,aAAA,CAAeA,CAAAA,CAAI,eAAiB,UAAA,CACpC,IAAA,CAAMA,CAAAA,CAAI,IAAA,EAAQ,WAAA,CAClB,KAAA,CAAOA,CAAAA,CAAI,KAAA,CACX,SAAUA,CAAAA,CAAI,QAAA,CACd,KAAA,CAAOA,CAAAA,CAAI,KAAA,CACX,YAAA,CAAcA,CAAAA,CAAI,YAAA,CAClB,SAAUA,CAAAA,CAAI,QAChB,CACF,CAEA,OAAO,C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AA,CAAY,KAAA,EAAM,CACrC,GAAIO,CAAAA,CACF,MAAM,IAAIpC,CAAAA,CACR,CAAA,oCAAA,EAAuCoC,CAAAA,CAAW,OAAO,CAAA,CAAA,CACzDzC,CAAAA,CAAS,MACX,CAAA,CAEF,KAAOiC,CAAAA,CAAc,MAAA,CAAS,CAAA,EAAG,CAC/B,IAAMK,CAAAA,CAAQL,CAAAA,CAAc,KAAA,GACxBK,CAAAA,GACF,MAAMA,CAAAA,EAEV,CACA,GAAIE,CAAAA,CACF,KAEJ,CACF,QAAE,CACKL,CAAAA,EACH,MAAMJ,CAAAA,CAAO,MAAA,EAAO,CAEtBA,CAAAA,CAAO,WAAA,GACT,CACF,CAAA,CAEA,MAAM,IAAA,CAAKlB,CAAAA,CAAc6B,CAAAA,CAAQvB,CAAAA,CAAU,GAAI,CAC7C,GAAI,CACF,OAAO,MAAMvB,CAAAA,CAAK,OAAA,CAA8B,CAC9C,IAAK,CAAA,EAAGgB,CAAAA,CAAaC,CAAY,CAAC,CAAA,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"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -101,4 +101,62 @@ type WorkflowClient = {
|
|
|
101
101
|
};
|
|
102
102
|
declare function createWorkflowClient(http?: HttpClient): WorkflowClient;
|
|
103
103
|
|
|
104
|
-
|
|
104
|
+
type ChatflowRunRequest = {
|
|
105
|
+
inputs?: Record<string, WorkflowInputValue>;
|
|
106
|
+
query: string;
|
|
107
|
+
files?: WorkflowFile[];
|
|
108
|
+
conversation_id?: string;
|
|
109
|
+
user?: string;
|
|
110
|
+
retriever_from?: string;
|
|
111
|
+
auto_generate_name?: boolean;
|
|
112
|
+
workflow_id?: string;
|
|
113
|
+
};
|
|
114
|
+
type ChatflowBlockingResponse = {
|
|
115
|
+
event?: string;
|
|
116
|
+
task_id: string;
|
|
117
|
+
message_id: string;
|
|
118
|
+
conversation_id: string;
|
|
119
|
+
mode?: string;
|
|
120
|
+
answer: string;
|
|
121
|
+
metadata?: Record<string, unknown>;
|
|
122
|
+
created_at?: number;
|
|
123
|
+
};
|
|
124
|
+
type ChatflowEvent = {
|
|
125
|
+
event: string;
|
|
126
|
+
task_id?: string;
|
|
127
|
+
message_id?: string;
|
|
128
|
+
conversation_id?: string;
|
|
129
|
+
answer?: string;
|
|
130
|
+
created_at?: number;
|
|
131
|
+
[key: string]: unknown;
|
|
132
|
+
};
|
|
133
|
+
type ChatflowStopRequest = {
|
|
134
|
+
user?: string;
|
|
135
|
+
};
|
|
136
|
+
type ChatflowStopResponse = {
|
|
137
|
+
result: string;
|
|
138
|
+
};
|
|
139
|
+
type ChatflowClientOptions = {
|
|
140
|
+
baseURL?: string;
|
|
141
|
+
headers?: Record<string, string>;
|
|
142
|
+
getAccessToken?: () => string | null | undefined;
|
|
143
|
+
fetch?: typeof globalThis.fetch;
|
|
144
|
+
credentials?: RequestCredentials;
|
|
145
|
+
onUnauthorized?: () => void;
|
|
146
|
+
};
|
|
147
|
+
type ChatflowStreamOptions = {
|
|
148
|
+
signal?: AbortSignal;
|
|
149
|
+
};
|
|
150
|
+
type ChatflowClient = {
|
|
151
|
+
run(chatflowName: string, request: ChatflowRunRequest): Promise<ClientResult<ChatflowBlockingResponse>>;
|
|
152
|
+
stream(chatflowName: string, request: ChatflowRunRequest, options?: ChatflowStreamOptions): AsyncGenerator<ChatflowEvent, void, void>;
|
|
153
|
+
stop(chatflowName: string, taskId: string, request?: ChatflowStopRequest): Promise<ClientResult<ChatflowStopResponse>>;
|
|
154
|
+
};
|
|
155
|
+
declare class ChatflowStreamError extends Error {
|
|
156
|
+
readonly status: number;
|
|
157
|
+
readonly details?: unknown;
|
|
158
|
+
constructor(message: string, status: number, details?: unknown);
|
|
159
|
+
}
|
|
160
|
+
declare function createChatflowClient(http?: HttpClient, options?: ChatflowClientOptions): ChatflowClient;
|
|
161
|
+
|
|
162
|
+
export { type ChatflowBlockingResponse, type ChatflowClient, type ChatflowClientOptions, type ChatflowEvent, type ChatflowRunRequest, type ChatflowStopRequest, type ChatflowStopResponse, ChatflowStreamError, type ChatflowStreamOptions, type WorkflowAsyncRunDetailResponse, type WorkflowAsyncRunResponse, type WorkflowAsyncRunStatus, type WorkflowCallbackConfig, type WorkflowClient, type WorkflowFile, type WorkflowInputValue, type WorkflowNodeUsage, type WorkflowResponseMode, type WorkflowRunDetailOptions, type WorkflowRunRequest, type WorkflowRunResponse, type WorkflowRunUsage, type WorkflowUsageSummary, createChatflowClient, createWorkflowClient };
|
package/dist/index.d.ts
CHANGED
|
@@ -101,4 +101,62 @@ type WorkflowClient = {
|
|
|
101
101
|
};
|
|
102
102
|
declare function createWorkflowClient(http?: HttpClient): WorkflowClient;
|
|
103
103
|
|
|
104
|
-
|
|
104
|
+
type ChatflowRunRequest = {
|
|
105
|
+
inputs?: Record<string, WorkflowInputValue>;
|
|
106
|
+
query: string;
|
|
107
|
+
files?: WorkflowFile[];
|
|
108
|
+
conversation_id?: string;
|
|
109
|
+
user?: string;
|
|
110
|
+
retriever_from?: string;
|
|
111
|
+
auto_generate_name?: boolean;
|
|
112
|
+
workflow_id?: string;
|
|
113
|
+
};
|
|
114
|
+
type ChatflowBlockingResponse = {
|
|
115
|
+
event?: string;
|
|
116
|
+
task_id: string;
|
|
117
|
+
message_id: string;
|
|
118
|
+
conversation_id: string;
|
|
119
|
+
mode?: string;
|
|
120
|
+
answer: string;
|
|
121
|
+
metadata?: Record<string, unknown>;
|
|
122
|
+
created_at?: number;
|
|
123
|
+
};
|
|
124
|
+
type ChatflowEvent = {
|
|
125
|
+
event: string;
|
|
126
|
+
task_id?: string;
|
|
127
|
+
message_id?: string;
|
|
128
|
+
conversation_id?: string;
|
|
129
|
+
answer?: string;
|
|
130
|
+
created_at?: number;
|
|
131
|
+
[key: string]: unknown;
|
|
132
|
+
};
|
|
133
|
+
type ChatflowStopRequest = {
|
|
134
|
+
user?: string;
|
|
135
|
+
};
|
|
136
|
+
type ChatflowStopResponse = {
|
|
137
|
+
result: string;
|
|
138
|
+
};
|
|
139
|
+
type ChatflowClientOptions = {
|
|
140
|
+
baseURL?: string;
|
|
141
|
+
headers?: Record<string, string>;
|
|
142
|
+
getAccessToken?: () => string | null | undefined;
|
|
143
|
+
fetch?: typeof globalThis.fetch;
|
|
144
|
+
credentials?: RequestCredentials;
|
|
145
|
+
onUnauthorized?: () => void;
|
|
146
|
+
};
|
|
147
|
+
type ChatflowStreamOptions = {
|
|
148
|
+
signal?: AbortSignal;
|
|
149
|
+
};
|
|
150
|
+
type ChatflowClient = {
|
|
151
|
+
run(chatflowName: string, request: ChatflowRunRequest): Promise<ClientResult<ChatflowBlockingResponse>>;
|
|
152
|
+
stream(chatflowName: string, request: ChatflowRunRequest, options?: ChatflowStreamOptions): AsyncGenerator<ChatflowEvent, void, void>;
|
|
153
|
+
stop(chatflowName: string, taskId: string, request?: ChatflowStopRequest): Promise<ClientResult<ChatflowStopResponse>>;
|
|
154
|
+
};
|
|
155
|
+
declare class ChatflowStreamError extends Error {
|
|
156
|
+
readonly status: number;
|
|
157
|
+
readonly details?: unknown;
|
|
158
|
+
constructor(message: string, status: number, details?: unknown);
|
|
159
|
+
}
|
|
160
|
+
declare function createChatflowClient(http?: HttpClient, options?: ChatflowClientOptions): ChatflowClient;
|
|
161
|
+
|
|
162
|
+
export { type ChatflowBlockingResponse, type ChatflowClient, type ChatflowClientOptions, type ChatflowEvent, type ChatflowRunRequest, type ChatflowStopRequest, type ChatflowStopResponse, ChatflowStreamError, type ChatflowStreamOptions, type WorkflowAsyncRunDetailResponse, type WorkflowAsyncRunResponse, type WorkflowAsyncRunStatus, type WorkflowCallbackConfig, type WorkflowClient, type WorkflowFile, type WorkflowInputValue, type WorkflowNodeUsage, type WorkflowResponseMode, type WorkflowRunDetailOptions, type WorkflowRunRequest, type WorkflowRunResponse, type WorkflowRunUsage, type WorkflowUsageSummary, createChatflowClient, createWorkflowClient };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {createHttpClient}from'@amaster.ai/http-client';function
|
|
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
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/workflow-client.ts"],"names":["normalizeRunRequest","inputs","isWorkflowRunRequest","req","value","requestKeys","structuralRequestKeys","keys","key","validateWorkflowName","workflowName","createWorkflowClient","http","createHttpClient","validationError","normalizedRequest","response","innerData","asyncRunId","workflowRunId","options"],"mappings":"uDAgJA,SAASA,CAAAA,CACPC,CAAAA,CACoB,CACpB,GAAI,CAACA,CAAAA,CACH,OAAO,CAAE,OAAQ,EAAC,CAAG,aAAA,CAAe,UAAA,CAAY,IAAA,CAAM,WAAY,CAAA,CAGpE,GAAI,OAAOA,CAAAA,EAAW,QAAA,EAAYC,CAAAA,CAAqBD,CAAM,CAAA,CAAG,CAC9D,IAAME,EAAMF,CAAAA,CACZ,OAAO,CACL,MAAA,CAAQE,CAAAA,CAAI,MAAA,EAAU,EAAC,CACvB,aAAA,CAAeA,CAAAA,CAAI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A,CACtC,UAAA,CAAYA,CAAAA,CAAU,UAAA,EAAc,CAAA,CACpC,YAAaA,CAAAA,CAAU,WAAA,EAAe,CAAA,CACtC,GAAIA,CAAAA,CAAU,KAAA,CAAQ,CAAE,KAAA,CAAOA,CAAAA,CAAU,KAAM,CAAA,CAAI,EACrD,CACF,CACF,CAEA,OAAO,CACL,IAAA,CAAM,IAAA,CACN,KAAA,CAAOD,CAAAA,CAAS,KAAA,EAAS,CACvB,MAAA,CAAQA,EAAS,MAAA,CACjB,OAAA,CAAS,gDACX,CAAA,CACA,MAAA,CAAQA,CAAAA,CAAS,MACnB,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"]}
|
|
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,EAAYC,CAAAA,CAAqBD,CAAM,CAAA,CAAG,CAC9D,IAAME,CAAAA,CAAMF,CAAAA,CACZ,OAAO,CACL,MAAA,CAAQE,CAAAA,CAAI,MAAA,EAAU,EAAC,CACvB,aAAA,CAAeA,CAAAA,CAAI,eAAiB,UAAA,CACpC,IAAA,CAAMA,CAAAA,CAAI,IAAA,EAAQ,WAAA,CAClB,KAAA,CAAOA,CAAAA,CAAI,KAAA,CACX,SAAUA,CAAAA,CAAI,QAAA,CACd,KAAA,CAAOA,CAAAA,CAAI,KAAA,CACX,YAAA,CAAcA,CAAAA,CAAI,YAAA,CAClB,SAAUA,CAAAA,CAAI,QAChB,CACF,CAEA,OAAO,CACL,MAAA,CAAQF,CAAAA,CACR,cAAe,UAAA,CACf,IAAA,CAAM,WACR,CACF,CAEA,SAASC,CAAAA,CAAqBE,CAAAA,CAAyC,CACrE,IAAMC,CAAAA,CAAc,CAAC,QAAA,CAAU,eAAA,CAAiB,MAAA,CAAQ,OAAA,CAAS,UAAA,CAAY,QAAS,cAAA,CAAgB,UAAU,CAAA,CAC1GC,CAAAA,CAAwB,CAAC,QAAA,CAAU,eAAA,CAAiB,MAAA,CAAQ,QAAS,UAAU,CAAA,CAC/EC,CAAAA,CAAO,MAAA,CAAO,IAAA,CAAKH,CAAK,CAAA,CAE9B,OAAIE,EAAsB,IAAA,CAAME,CAAAA,EAAQA,CAAAA,IAAOJ,CAAK,CAAA,CAC3C,IAAA,CAGFG,CAAAA,CAAK,MAAA,CAAS,G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AU,GAAI,CAC7C,GAAI,CACF,OAAO,MAAMvB,CAAAA,CAAK,OAAA,CAA8B,CAC9C,IAAK,CAAA,EAAGgB,CAAAA,CAAaC,CAAY,CAAC,CAAA,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.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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amaster.ai/workflow-client",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.59-beta.0",
|
|
4
4
|
"description": "Workflow execution client",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -30,7 +30,8 @@
|
|
|
30
30
|
"registry": "https://registry.npmjs.org/"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"
|
|
33
|
+
"eventsource-parser": "^3.0.6",
|
|
34
|
+
"@amaster.ai/http-client": "1.1.59-beta.0"
|
|
34
35
|
},
|
|
35
36
|
"peerDependencies": {
|
|
36
37
|
"axios": "^1.11.0"
|
|
@@ -38,12 +39,14 @@
|
|
|
38
39
|
"devDependencies": {
|
|
39
40
|
"axios": "^1.11.0",
|
|
40
41
|
"tsup": "^8.3.5",
|
|
41
|
-
"typescript": "~5.7.2"
|
|
42
|
+
"typescript": "~5.7.2",
|
|
43
|
+
"vitest": "^1.0.0"
|
|
42
44
|
},
|
|
43
45
|
"scripts": {
|
|
44
46
|
"build": "tsup",
|
|
45
47
|
"dev": "tsup --watch",
|
|
46
48
|
"clean": "rm -rf dist *.tsbuildinfo",
|
|
47
|
-
"type-check": "tsc --noEmit"
|
|
49
|
+
"type-check": "tsc --noEmit",
|
|
50
|
+
"test": "vitest run"
|
|
48
51
|
}
|
|
49
52
|
}
|