@stackone/connect-sdk 1.27.0 → 1.29.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.es.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{StepFunctionsFactory as e,StepFunctionName as t,isCursorEmpty as o,minifyCursor as r,updateCursor as n,AUTHENTICATION_SCHEMA as s,COMPOSITE_ID_LATEST_VERSION as i,expandCursor as a}from"@stackone/core";import{safeEvaluate as c,safeEvaluateRecord as p}from"@stackone/expressions";import{notMissing as u,isNumber as d,isMissing as l,isObject as y,isString as g}from"@stackone/utils";import{HttpClientManager as m,isSuccessStatusCode as b}from"@stackone/transport";import{match as f}from"path-to-regexp";import{parse as h}from"yaml";import{z as _}from"zod";const v=async({block:o,stepFunctionName:r,params:n,buildStepFunction:s=e.build})=>{const i=s({functionName:r}).fn,a=await i({block:o,params:n}),c=r===t.MAP_FIELDS?{[t.MAP_FIELDS.toString()]:{output:{data:a.block.result},errors:a.errors,successful:a.successful}}:{};return{...a.block,steps:{...a?.block?.steps??{},...c}}},k=(e,t,s,i)=>{const a=l(e)?void 0:e.data,c=Object.keys(s).length+1,p=o({cursor:i,ignoreStepIndex:c});if(!y(e)||l(a)||(a?.length??0)<=t)return{result:e,next:u(i)&&!p?r(i):null};const d=i?.remote?.[c]?.pageNumber??1,g=(d-1)*t,m=g+t,b=a.slice(g,m),f=a.length>m||!p,h=n({cursor:i,stepIndex:c,pageNumber:d+1});return{result:{...e,data:b},next:f?r(h):null}},C=async({block:t,buildStepFunction:o=e.build,virtualPaginateResultFn:r=k})=>await I({block:t,buildStepFunction:o,virtualPaginateResultFn:r}),I=async({block:t,buildStepFunction:o=e.build,virtualPaginateResultFn:r=k})=>{const s=t.operation?.steps||{};let i={...t};const a=Object.keys(s),p=((e,t)=>{const o=Number(e.inputs?.page_size);return u(e.inputs?.page_size)&&d(o)&&!Number.isNaN(o)?o:e.operation?.cursor?.pageSize??t})(t,25);let l=!1,g=null;for(const[e,t]of a.entries()){const r=s[t],a=r.stepFunction,p=o({functionName:a.functionName,version:a.version,validateSchemas:!0}).fn;if(r.condition&&!c(r.condition,i)){i=F({block:i,stepId:t,successful:!0,skipped:!0,message:"Step skipped due to condition not met."});continue}if(l){i=F({block:i,stepId:t,successful:!1,skipped:!0,message:"Step skipped due to previous error."});continue}const u=i.operation?.cursor.enabled?{...a.params,cursor:{token:i.nextCursor?.remote?.[e]?.providerPageCursor,position:i.nextCursor?.remote?.[e]?.position}}:a.params,d=await p({block:i,params:u});if(!1===d.successful){i=F({block:i,stepId:t,successful:!1,functionOutput:d});(r.ignoreError??!1)||(l=!0,g??=d.output?.statusCode??500)}else{const o=i.operation?.cursor.enabled?n({cursor:i.nextCursor,stepIndex:e,providerPageCursor:d.output?.next,position:d.output?.position}):void 0;i=F({block:{...d.block,nextCursor:o},stepId:t,functionOutput:d})}}const m=t.operation?.result?w(t.operation.result,i):void 0,b=t.operation?.cursor.enabled?r(m,p,s,i.nextCursor):void 0,f=!l,h=f?t.operation?.responses.success.statusCode??200:g??500,_=u(b)&&y(b.result)?{next:b.next,...b.result}:m;return{...i,outputs:_,response:{successful:f,statusCode:h,message:f?void 0:t.operation?.responses?.errors?.[h]?.description??"Error while processing the request"}}},w=(e,t)=>y(e)?p(e,t):c(e,t),F=({block:e,stepId:t,successful:o,functionOutput:r,skipped:n,message:s})=>({...e,steps:{...e.steps,[t]:{successful:o??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:n,message:s}}}),S=async({inputs:e,context:t,operation:o,credentials:r,nextCursor:n,logger:s,getHttpClient:i=async()=>m.getInstance()})=>({inputs:e,fieldConfigs:[],context:t,operation:o,credentials:r,nextCursor:n,httpClient:await i(),logger:s}),x=({category:e,connectorKey:t,connectorVersion:o,authConfigKey:r,environment:n="production",operation:s,accountSecureId:i,projectSecureId:a})=>({projectSecureId:a,accountSecureId:i,connectorKey:t,connectorVersion:o,category:e,service:"",resource:"",schema:s?.schema?.key,operationType:s?.operationType??"unknown",authenticationType:r,environment:n}),j=(e,t,o)=>{const r=o.toUpperCase();if(!e.operations)return;const n=Object.keys(e.operations),s=O(t,r,n);return s?{operation:e.operations?.[s.path],params:s.params}:void 0},E=e=>{const t=e.startsWith("/")?e.slice(1):e;return t.endsWith("/")?t.slice(0,-1):t},O=(e,t,o)=>{const r=E(e);for(const e of o)if(e.startsWith(t)){const o=e.replace(`${t} `,"").trim(),n=f(E(o))(E(r));if(!1!==n)return{path:e,params:n.params}}},T=e=>{switch(e){case"list":return{statusCode:200,description:"The list of records was retrieved."};case"get":return{statusCode:200,description:"The record with the given identifier was retrieved."};case"create":return{statusCode:201,description:"The record was created successfully."};case"update":return{statusCode:200,description:"The record was updated successfully."};case"delete":return{statusCode:204,description:"The record was deleted successfully."};case"custom":return{statusCode:200,description:"The operation was executed successfully."};case"unknown":return{statusCode:200};default:throw new Error(`Unknown operation type: ${e}`)}},N={key:_.string(),label:_.string(),required:_.boolean().optional().default(!1),secret:_.boolean().optional().default(!1),readOnly:_.boolean().optional().default(!1),placeholder:_.string().optional(),description:_.string().optional(),tooltip:_.string().optional()},R=_.discriminatedUnion("type",[_.object({...N,type:_.enum(["text","password"])}),_.object({...N,type:_.literal("select"),options:_.object({value:_.string(),label:_.string()}).array()})]),K=_.object({operationId:_.string(),categories:_.string().array(),operationType:_.enum(["list","get","create","update","delete","custom","unknown"]),schema:_.string().optional(),entrypointUrl:_.string().optional(),entrypointHttpMethod:_.string().optional(),description:_.string(),responses:_.object({statusCode:_.number(),description:_.string()}).array().optional(),inputs:_.object({name:_.string(),type:_.string(),required:_.boolean(),description:_.string(),in:_.string()}).array().optional(),cursor:_.object({enabled:_.boolean(),pageSize:_.number()}).optional(),compositeIdentifiers:_.object({enabled:_.boolean(),version:_.number().optional(),fields:_.object({targetFieldKey:_.string(),remote:_.string().optional(),components:_.string().array()}).array().optional()}).optional(),fieldConfigs:_.object({targetFieldKey:_.string(),alias:_.string().optional(),expression:_.string(),type:_.enum(["string","number","boolean","datetime_string","enum"]),custom:_.boolean().default(!1),hidden:_.boolean().default(!1),enumMapper:_.object({matcher:_.enum(["country_alpha2code_by_alpha2code","country_alpha3code_by_alpha3code","country_code_by_country_code","country_name_by_country_name","country_name_by_alpha3code","country_name_by_alpha2code","country_name_by_country_code","country_alpha3code_by_alpha2code","country_alpha3code_by_country_name","country_alpha3code_by_country_code","country_alpha2code_by_alpha3code","country_alpha2code_by_country_name","country_alpha2code_by_country_code","country_code_by_alpha2code","country_code_by_alpha3code","country_code_by_country_name","country_subdivisions_by_alpha2code","country_subdivision_code_by_subdivision_name","country_alpha2code_by_citizenship","country_subdivision_name_by_subdivision_code"]).or(_.object({matchExpression:_.string(),value:_.string()}).array())}).optional()}).array().optional(),steps:_.object({stepId:_.string(),description:_.string(),stepFunction:_.object({functionName:_.string(),version:_.string().optional(),parameters:_.record(_.string(),_.unknown())}),condition:_.string().optional(),ignoreError:_.boolean().optional()}).array(),result:_.string().or(_.record(_.string(),_.unknown())).optional()}),U=_.object({StackOne:_.string(),info:_.object({title:_.string(),version:_.string(),key:_.string(),description:_.string().optional()}),baseUrl:_.string(),authentication:_.record(_.string(),_.object({type:_.string(),label:_.string(),authorization:s,environments:_.object({key:_.string(),name:_.string()}).array(),support:_.object({link:_.string(),description:_.string().optional()}),configFields:R.array().optional(),setupFields:R.array().optional(),testOperationsIds:_.string().array().optional()})).array().optional(),operations:K.array().optional()});function q(e){try{const t=h(e),o=U.parse(t),r={title:o.info.title,version:o.info.version,key:o.info.key,description:o.info.description},n=$(o),s={baseUrl:o.baseUrl,authentication:P(n)},i=M(o,s);return r.operations=i,r.authentication=n,u(i)&&(r.categories=z(Object.values(i))),r}catch(e){throw new Error(`Error parsing YAML file: ${e.message}`)}}const P=e=>{const t={};for(const[o,r]of Object.entries(e))if(r&&"object"==typeof r){const{setupFields:e,configFields:n,support:s,testOperationsIds:i,...a}=r;t[o]=P(a)}else t[o]=r;return t},z=e=>{const t=e.reduce(((e,t)=>{for(const o of t.categories)e.add(o);return e}),new Set);return Array.from(t)},$=e=>{const t={};for(const o of e.authentication??[]){const[e]=Object.keys(o),r=o[e].environments.reduce(((t,r)=>{const{key:n,name:s}=r,{environments:i,...a}=o[e];return t[n]={...a,envKey:n,envName:s},t}),{});t[e]=r}return t},M=(e,t)=>{const o=e.operations?.reduce(((e,o)=>{const r=(e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0)(o),n=(e=>"list"===e.operationType?`GET /${e.schema}`:`GET /${e.schema}/:id`)(o),s=(e=>"list"===e.operationType?`/${e.schema}`:`/${e.schema}/:id`)(o),i=(e=>{const t={success:T(e.operationType),errors:{400:{statusCode:400,description:"Invalid request."},401:{statusCode:401,description:"Unauthorized access."},403:{statusCode:403,description:"Forbidden."},404:{statusCode:404,description:"Resource not found."},500:{statusCode:500,description:"Server error while executing the request."}}},o=e.responses?.reduce(((e,t)=>(b(t.statusCode)?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e)),t);return o??t})(o),a=V(o),c=o.inputs||[];return a.enabled&&c?.push({type:"string",name:"page_size",in:"query",required:!1,description:"Number of items to return per page"}),e[r??n]={id:o.operationId,categories:o.categories,description:o.description,operationType:o.operationType,entrypointUrl:o.entrypointUrl??s,entrypointHttpMethod:o.entrypointHttpMethod??"get",responses:i,cursor:a,compositeIdentifiers:D(o),inputs:c,steps:o.steps.reduce(((e,r)=>(e[r.stepId]={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{..."request"===r.stepFunction.functionName||"paginated_request"===r.stepFunction.functionName?t:{},..."map_fields"===r.stepFunction.functionName||"typecast"===r.stepFunction.functionName?{fields:o.fieldConfigs}:{},...r.stepFunction.parameters}}},e)),{}),result:o.result},e}),{});return o},A=(e,t)=>{if(!e.inputs)return{};const o=L(e.inputs).parse(t);return{...o.headers??{},...o.query??{},...o.path??{},...o.body??{}}},H=e=>{const t={};return e.forEach((e=>{let o;switch(e.type.toLowerCase()){case"string":o=_.string();break;case"number":o=_.number();break;case"boolean":o=_.boolean();break;default:o=_.any()}t[e.name]=e.required?o:o.optional()})),_.object(t)},L=e=>{const t=e.filter((e=>"path"===e.in)),o=e.filter((e=>"query"===e.in)),r=e.filter((e=>"body"===e.in)),n=e.filter((e=>"headers"===e.in));return _.object({path:H(t).optional(),query:H(o).optional(),body:H(r).optional(),headers:H(n).optional()})},V=e=>{const t="list"===e.operationType,o=e.cursor??{enabled:t,pageSize:25};return{enabled:o.enabled&&t,pageSize:o.pageSize}},D=e=>{if(l(e.compositeIdentifiers)){const t=e.fieldConfigs?.find((e=>"id"===e.targetFieldKey)),o=u(t)?[{targetFieldKey:t.targetFieldKey,remote:"id",components:[{name:t.targetFieldKey,alias:t.alias}]}]:void 0;return{enabled:!0,version:i,fields:o}}const t=[];for(const o of e.compositeIdentifiers?.fields??[]){const r=o.components.map((t=>{const o=e.fieldConfigs?.find((e=>e.targetFieldKey===t));return{name:t,alias:o?.alias}}));t.push({targetFieldKey:o.targetFieldKey,remote:o.remote,components:r})}return{enabled:e.compositeIdentifiers.enabled,version:e.compositeIdentifiers.version,fields:t.length>0?t:void 0}};class G extends Error{constructor(e,t,o){super(o),this.name="ConnectSDKError",this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,G)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}}class W extends G{constructor(e,t){super("CONNECTOR_PARSE_ERROR",e,t),this.name="ConnectorParseError"}}class B extends G{constructor(e,t){super("MISSING_OPERATION_ERROR",e,t),this.name="MissingOperationError"}}class Y extends G{constructor(e,t){super("INVALID_OPERATION_INPUTS_ERROR",e,t),this.name="InvalidOperationInputsError"}}class J extends G{constructor(e,t){super("INVALID_CURSOR_ERROR",e,t),this.name="InvalidCursorError"}}const Q=async({account:e,connector:t,category:o,path:r,method:n="get",queryParams:s,body:i,headers:a,logger:c,parseConnector:p=q,getOperationFromUrlFn:u=j,parseOperationInputsFn:d=A,createBlockContextFn:y=x,createBlockFn:m=S,runStepOperationFn:b=C})=>{const f=e.authConfigKey,h=e.environment??"production",_=e.secureId,v=e.projectSecureId,k=e.credentials,I=y({category:o,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:f,environment:h,accountSecureId:_,projectSecureId:v});let w;try{w=g(t)?p(t):t}catch{throw new W(I,"Error while parsing connector")}const F=u(w,r,n);if(l(F))throw new B(I,"No matching operation found");I.operationType=F.operation.operationType,I.schema=F.operation.schema?.key;const E=X(s,I);let O;try{O=d(F.operation,{query:s,body:i,headers:a,path:F.params})}catch{throw new Y(I,"Error while parsing operation inputs")}const T=await m({inputs:O,context:I,operation:F.operation,credentials:k,nextCursor:E,logger:c});return await b({block:T})},X=(e,t)=>{const o=e?.next,r=u(o)&&"list"===t.operationType?a(o):void 0;if(null===r)throw new J(t,"Invalid cursor.");return r};export{G as ConnectSDKError,S as createBlock,v as executeStepFunction,j as getOperationFromUrl,A as parseOperationInputs,q as parseYamlConnector,Q as runConnectorOperation,C as runStepOperation};
|
|
1
|
+
import{StepFunctionsFactory as e,StepFunctionName as t,COMPOSITE_ID_LATEST_VERSION as o,encodeCompositeId as r,isCompositeId as n,isCursorEmpty as s,minifyCursor as i,updateCursor as a,AUTHENTICATION_SCHEMA as c,expandCursor as p}from"@stackone/core";import{safeEvaluate as u,safeEvaluateRecord as d}from"@stackone/expressions";import{isMissing as l,isObject as y,isString as m,notMissing as g,isNumber as f}from"@stackone/utils";import{HttpClientManager as b,isSuccessStatusCode as h}from"@stackone/transport";import{match as _}from"path-to-regexp";import{parse as v}from"yaml";import{z as k}from"zod";const C=async({block:o,stepFunctionName:r,params:n,buildStepFunction:s=e.build})=>{const i=s({functionName:r}).fn,a=await i({block:o,params:n}),c=r===t.MAP_FIELDS?{[t.MAP_FIELDS.toString()]:{output:{data:a.block.result},errors:a.errors,successful:a.successful}}:{};return{...a.block,steps:{...a?.block?.steps??{},...c}}},I="remote_",F=e=>{const t=e.operation?.compositeIdentifiers;if(!t?.enabled)return e;const o="data",r=e.outputs?.[o];if(l(r))return e;const n=Array.isArray(r)?r.map((e=>w(e,t))):w(r,t);return{...e,outputs:{...e.outputs??{},[o]:n}}},w=(e,t)=>{const o=S(e,t),r=x(o);return{...e,...y(r)?r:{}}},S=(e,t)=>{const n=t.version??o,s={};return t.fields?.forEach((t=>{const o={},i=[];t.components.forEach((t=>{t.alias&&(o[t.name]=t.alias),i.push({key:t.name,value:e[t.name]})}));const a=1===i.length?i[0]:{identifiers:i},c={version:n,aliases:Object.keys(o).length>0?o:void 0},p=r(a,c);s[t.targetFieldKey]=p,t.remote&&(s[`${I}${t.remote}`]=e[t.remote])})),{...e,...s}},x=e=>{if(Array.isArray(e))return e.map((e=>x(e)));if(!y(e))return e;const t={...e};for(const[s,i]of Object.entries(e))if((y(i)||Array.isArray(i)&&i.length>0&&y(i[0]))&&(t[s]=x(i)),"id"===s||/.+_id(s)?$/.test(s))if(Array.isArray(i)&&i.every((e=>m(e)&&e.length>0))){const e=i.map((e=>{if(m(e)&&e.length>0&&!n(e))try{return r({key:s,value:e},{version:o})}catch{return e}return e}));t[s]=e,t[`${I}${s}`]=i}else if(m(i)&&i.length>0){if(n(i)||s.startsWith(I))continue;const e=r({key:s,value:i},{version:o});t[s]=e,t[`remote_${s}`]=i}return t},j=(e,t,o,r)=>{const n=l(e)?void 0:e.data,c=Object.keys(o).length+1,p=s({cursor:r,ignoreStepIndex:c});if(!y(e)||l(n)||(n?.length??0)<=t)return{result:e,next:g(r)&&!p?i(r):null};const u=r?.remote?.[c]?.pageNumber??1,d=(u-1)*t,m=d+t,f=n.slice(d,m),b=n.length>m||!p,h=a({cursor:r,stepIndex:c,pageNumber:u+1});return{result:{...e,data:f},next:b?i(h):null}},E=async({block:t,buildStepFunction:o=e.build,virtualPaginateResultFn:r=j,encodeResultCompositeIds:n=F})=>n(await O({block:t,buildStepFunction:o,virtualPaginateResultFn:r})),O=async({block:t,buildStepFunction:o=e.build,virtualPaginateResultFn:r=j})=>{const n=t.operation?.steps||{};let s={...t};const i=Object.keys(n),c=((e,t)=>{const o=Number(e.inputs?.page_size);return g(e.inputs?.page_size)&&f(o)&&!Number.isNaN(o)?o:e.operation?.cursor?.pageSize??t})(t,25);let p=!1,d=null;for(const[e,t]of i.entries()){const r=n[t],i=r.stepFunction,c=o({functionName:i.functionName,version:i.version,validateSchemas:!0}).fn;if(r.condition&&!u(r.condition,s)){s=N({block:s,stepId:t,successful:!0,skipped:!0,message:"Step skipped due to condition not met."});continue}if(p){s=N({block:s,stepId:t,successful:!1,skipped:!0,message:"Step skipped due to previous error."});continue}const l=s.operation?.cursor.enabled?{...i.params,cursor:{token:s.nextCursor?.remote?.[e]?.providerPageCursor,position:s.nextCursor?.remote?.[e]?.position}}:i.params,y=await c({block:s,params:l});if(!1===y.successful){s=N({block:s,stepId:t,successful:!1,functionOutput:y});(r.ignoreError??!1)||(p=!0,d??=y.output?.statusCode??500)}else{const o=s.operation?.cursor.enabled?a({cursor:s.nextCursor,stepIndex:e,providerPageCursor:y.output?.next,position:y.output?.position}):void 0;s=N({block:{...y.block,nextCursor:o},stepId:t,functionOutput:y})}}const l=t.operation?.result?T(t.operation.result,s):void 0,m=t.operation?.cursor.enabled?r(l,c,n,s.nextCursor):void 0,b=!p,h=b?t.operation?.responses.success.statusCode??200:d??500,_=g(m)&&y(m.result)?{next:m.next,...m.result}:l;return{...s,outputs:_,response:{successful:b,statusCode:h,message:b?void 0:t.operation?.responses?.errors?.[h]?.description??"Error while processing the request"}}},T=(e,t)=>y(e)?d(e,t):u(e,t),N=({block:e,stepId:t,successful:o,functionOutput:r,skipped:n,message:s})=>({...e,steps:{...e.steps,[t]:{successful:o??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:n,message:s}}}),R=async({inputs:e,context:t,operation:o,credentials:r,nextCursor:n,logger:s,getHttpClient:i=async()=>b.getInstance()})=>({inputs:e,fieldConfigs:[],context:t,operation:o,credentials:r,nextCursor:n,httpClient:await i(),logger:s}),K=({category:e,connectorKey:t,connectorVersion:o,authConfigKey:r,environment:n="production",operation:s,accountSecureId:i,projectSecureId:a})=>({projectSecureId:a,accountSecureId:i,connectorKey:t,connectorVersion:o,category:e,service:"",resource:"",schema:s?.schema?.key,operationType:s?.operationType??"unknown",authenticationType:r,environment:n}),$=(e,t,o)=>{const r=o.toUpperCase();if(!e.operations)return;const n=Object.keys(e.operations),s=U(t,r,n);return s?{operation:e.operations?.[s.path],params:s.params}:void 0},A=e=>{const t=e.startsWith("/")?e.slice(1):e;return t.endsWith("/")?t.slice(0,-1):t},U=(e,t,o)=>{const r=A(e);for(const e of o)if(e.startsWith(t)){const o=e.replace(`${t} `,"").trim(),n=_(A(o))(A(r));if(!1!==n)return{path:e,params:n.params}}},q=e=>{switch(e){case"list":return{statusCode:200,description:"The list of records was retrieved."};case"get":return{statusCode:200,description:"The record with the given identifier was retrieved."};case"create":return{statusCode:201,description:"The record was created successfully."};case"update":return{statusCode:200,description:"The record was updated successfully."};case"delete":return{statusCode:204,description:"The record was deleted successfully."};case"custom":return{statusCode:200,description:"The operation was executed successfully."};case"unknown":return{statusCode:200};default:throw new Error(`Unknown operation type: ${e}`)}},P={key:k.string(),label:k.string(),required:k.boolean().optional().default(!1),secret:k.boolean().optional().default(!1),readOnly:k.boolean().optional().default(!1),placeholder:k.string().optional(),description:k.string().optional(),tooltip:k.string().optional()},z=k.discriminatedUnion("type",[k.object({...P,type:k.enum(["text","password"])}),k.object({...P,type:k.literal("select"),options:k.object({value:k.string(),label:k.string()}).array()})]),M=k.object({operationId:k.string(),categories:k.string().array(),operationType:k.enum(["list","get","create","update","delete","custom","unknown"]),schema:k.string().optional(),entrypointUrl:k.string().optional(),entrypointHttpMethod:k.string().optional(),description:k.string(),responses:k.object({statusCode:k.number(),description:k.string()}).array().optional(),inputs:k.object({name:k.string(),type:k.string(),required:k.boolean(),description:k.string(),in:k.string()}).array().optional(),cursor:k.object({enabled:k.boolean(),pageSize:k.number()}).optional(),compositeIdentifiers:k.object({enabled:k.boolean(),version:k.number().optional(),fields:k.object({targetFieldKey:k.string(),remote:k.string().optional(),components:k.string().array()}).array().optional()}).optional(),fieldConfigs:k.object({targetFieldKey:k.string(),alias:k.string().optional(),expression:k.string(),type:k.enum(["string","number","boolean","datetime_string","enum"]),custom:k.boolean().default(!1),hidden:k.boolean().default(!1),enumMapper:k.object({matcher:k.enum(["country_alpha2code_by_alpha2code","country_alpha3code_by_alpha3code","country_code_by_country_code","country_name_by_country_name","country_name_by_alpha3code","country_name_by_alpha2code","country_name_by_country_code","country_alpha3code_by_alpha2code","country_alpha3code_by_country_name","country_alpha3code_by_country_code","country_alpha2code_by_alpha3code","country_alpha2code_by_country_name","country_alpha2code_by_country_code","country_code_by_alpha2code","country_code_by_alpha3code","country_code_by_country_name","country_subdivisions_by_alpha2code","country_subdivision_code_by_subdivision_name","country_alpha2code_by_citizenship","country_subdivision_name_by_subdivision_code"]).or(k.object({matchExpression:k.string(),value:k.string()}).array())}).optional()}).array().optional(),steps:k.object({stepId:k.string(),description:k.string(),stepFunction:k.object({functionName:k.string(),version:k.string().optional(),parameters:k.record(k.string(),k.unknown())}),condition:k.string().optional(),ignoreError:k.boolean().optional()}).array(),result:k.string().or(k.record(k.string(),k.unknown())).optional()}),H=k.object({StackOne:k.string(),info:k.object({title:k.string(),version:k.string(),key:k.string(),description:k.string().optional()}),baseUrl:k.string(),authentication:k.record(k.string(),k.object({type:k.string(),label:k.string(),authorization:c,environments:k.object({key:k.string(),name:k.string()}).array(),support:k.object({link:k.string(),description:k.string().optional()}),configFields:z.array().optional(),setupFields:z.array().optional(),testOperationsIds:k.string().array().optional()})).array().optional(),operations:M.array().optional()});function L(e){try{const t=v(e),o=H.parse(t),r={title:o.info.title,version:o.info.version,key:o.info.key,description:o.info.description},n=W(o),s={baseUrl:o.baseUrl,authentication:V(n)},i=G(o,s);return r.operations=i,r.authentication=n,g(i)&&(r.categories=D(Object.values(i))),r}catch(e){throw new Error(`Error parsing YAML file: ${e.message}`)}}const V=e=>{const t={};for(const[o,r]of Object.entries(e))if(r&&"object"==typeof r){const{setupFields:e,configFields:n,support:s,testOperationsIds:i,...a}=r;t[o]=V(a)}else t[o]=r;return t},D=e=>{const t=e.reduce(((e,t)=>{for(const o of t.categories)e.add(o);return e}),new Set);return Array.from(t)},W=e=>{const t={};for(const o of e.authentication??[]){const[e]=Object.keys(o),r=o[e].environments.reduce(((t,r)=>{const{key:n,name:s}=r,{environments:i,...a}=o[e];return t[n]={...a,envKey:n,envName:s},t}),{});t[e]=r}return t},G=(e,t)=>{const o=e.operations?.reduce(((e,o)=>{const r=(e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0)(o),n=(e=>"list"===e.operationType?`GET /${e.schema}`:`GET /${e.schema}/:id`)(o),s=(e=>"list"===e.operationType?`/${e.schema}`:`/${e.schema}/:id`)(o),i=(e=>{const t={success:q(e.operationType),errors:{400:{statusCode:400,description:"Invalid request."},401:{statusCode:401,description:"Unauthorized access."},403:{statusCode:403,description:"Forbidden."},404:{statusCode:404,description:"Resource not found."},500:{statusCode:500,description:"Server error while executing the request."}}},o=e.responses?.reduce(((e,t)=>(h(t.statusCode)?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e)),t);return o??t})(o),a=Q(o),c=o.inputs||[];return a.enabled&&c?.push({type:"string",name:"page_size",in:"query",required:!1,description:"Number of items to return per page"}),e[r??n]={id:o.operationId,categories:o.categories,description:o.description,operationType:o.operationType,entrypointUrl:o.entrypointUrl??s,entrypointHttpMethod:o.entrypointHttpMethod??"get",responses:i,cursor:a,compositeIdentifiers:X(o),inputs:c,steps:o.steps.reduce(((e,r)=>(e[r.stepId]={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{..."request"===r.stepFunction.functionName||"paginated_request"===r.stepFunction.functionName?t:{},..."map_fields"===r.stepFunction.functionName||"typecast"===r.stepFunction.functionName?{fields:o.fieldConfigs}:{},...r.stepFunction.parameters}}},e)),{}),result:o.result},e}),{});return o},B=(e,t)=>{if(!e.inputs)return{};const o=J(e.inputs).parse(t);return{...o.headers??{},...o.query??{},...o.path??{},...o.body??{}}},Y=e=>{const t={};return e.forEach((e=>{let o;switch(e.type.toLowerCase()){case"string":o=k.string();break;case"number":o=k.number();break;case"boolean":o=k.boolean();break;default:o=k.any()}t[e.name]=e.required?o:o.optional()})),k.object(t)},J=e=>{const t=e.filter((e=>"path"===e.in)),o=e.filter((e=>"query"===e.in)),r=e.filter((e=>"body"===e.in)),n=e.filter((e=>"headers"===e.in));return k.object({path:Y(t).optional(),query:Y(o).optional(),body:Y(r).optional(),headers:Y(n).optional()})},Q=e=>{const t="list"===e.operationType,o=e.cursor??{enabled:t,pageSize:25};return{enabled:o.enabled&&t,pageSize:o.pageSize}},X=e=>{if(l(e.compositeIdentifiers)){const t=e.fieldConfigs?.find((e=>"id"===e.targetFieldKey)),r=g(t)?[{targetFieldKey:t.targetFieldKey,remote:"id",components:[{name:t.targetFieldKey,alias:t.alias}]}]:void 0;return{enabled:!0,version:o,fields:r}}const t=[];for(const o of e.compositeIdentifiers?.fields??[]){const r=o.components.map((t=>{const o=e.fieldConfigs?.find((e=>e.targetFieldKey===t));return{name:t,alias:o?.alias}}));t.push({targetFieldKey:o.targetFieldKey,remote:o.remote,components:r})}return{enabled:e.compositeIdentifiers.enabled,version:e.compositeIdentifiers.version,fields:t.length>0?t:void 0}};class Z extends Error{constructor(e,t,o){super(o),this.name="ConnectSDKError",this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,Z)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}}class ee extends Z{constructor(e,t){super("CONNECTOR_PARSE_ERROR",e,t),this.name="ConnectorParseError"}}class te extends Z{constructor(e,t){super("MISSING_OPERATION_ERROR",e,t),this.name="MissingOperationError"}}class oe extends Z{constructor(e,t){super("INVALID_OPERATION_INPUTS_ERROR",e,t),this.name="InvalidOperationInputsError"}}class re extends Z{constructor(e,t){super("INVALID_CURSOR_ERROR",e,t),this.name="InvalidCursorError"}}const ne=async({account:e,connector:t,category:o,path:r,method:n="get",queryParams:s,body:i,headers:a,logger:c,parseConnector:p=L,getOperationFromUrlFn:u=$,parseOperationInputsFn:d=B,createBlockContextFn:y=K,createBlockFn:g=R,runStepOperationFn:f=E})=>{const b=e.authConfigKey,h=e.environment??"production",_=e.secureId,v=e.projectSecureId,k=e.credentials,C=y({category:o,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:b,environment:h,accountSecureId:_,projectSecureId:v});let I;try{I=m(t)?p(t):t}catch{throw new ee(C,"Error while parsing connector")}const F=u(I,r,n);if(l(F))throw new te(C,"No matching operation found");C.operationType=F.operation.operationType,C.schema=F.operation.schema?.key;const w=se(s,C);let S;try{S=d(F.operation,{query:s,body:i,headers:a,path:F.params})}catch{throw new oe(C,"Error while parsing operation inputs")}const x=await g({inputs:S,context:C,operation:F.operation,credentials:k,nextCursor:w,logger:c});return await f({block:x})},se=(e,t)=>{const o=e?.next,r=g(o)&&"list"===t.operationType?p(o):void 0;if(null===r)throw new re(t,"Invalid cursor.");return r};export{Z as ConnectSDKError,R as createBlock,C as executeStepFunction,$ as getOperationFromUrl,B as parseOperationInputs,L as parseYamlConnector,ne as runConnectorOperation,E as runStepOperation};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("@stackone/core"),t=require("@stackone/expressions"),o=require("@stackone/utils"),r=require("@stackone/transport"),n=require("path-to-regexp"),s=require("yaml"),i=require("zod");const a=(t,r,n,s)=>{const i=o.isMissing(t)?void 0:t.data,a=Object.keys(n).length+1,c=e.isCursorEmpty({cursor:s,ignoreStepIndex:a});if(!o.isObject(t)||o.isMissing(i)||(i?.length??0)<=r)return{result:t,next:o.notMissing(s)&&!c?e.minifyCursor(s):null};const p=s?.remote?.[a]?.pageNumber??1,u=(p-1)*r,d=u+r,l=i.slice(u,d),y=i.length>d||!c,g=e.updateCursor({cursor:s,stepIndex:a,pageNumber:p+1});return{result:{...t,data:l},next:y?e.minifyCursor(g):null}},c=async({block:t,buildStepFunction:o=e.StepFunctionsFactory.build,virtualPaginateResultFn:r=a})=>await p({block:t,buildStepFunction:o,virtualPaginateResultFn:r}),p=async({block:r,buildStepFunction:n=e.StepFunctionsFactory.build,virtualPaginateResultFn:s=a})=>{const i=r.operation?.steps||{};let c={...r};const p=Object.keys(i),l=((e,t)=>{const r=Number(e.inputs?.page_size);return o.notMissing(e.inputs?.page_size)&&o.isNumber(r)&&!Number.isNaN(r)?r:e.operation?.cursor?.pageSize??t})(r,25);let y=!1,g=null;for(const[o,r]of p.entries()){const s=i[r],a=s.stepFunction,p=n({functionName:a.functionName,version:a.version,validateSchemas:!0}).fn;if(s.condition&&!t.safeEvaluate(s.condition,c)){c=d({block:c,stepId:r,successful:!0,skipped:!0,message:"Step skipped due to condition not met."});continue}if(y){c=d({block:c,stepId:r,successful:!1,skipped:!0,message:"Step skipped due to previous error."});continue}const u=c.operation?.cursor.enabled?{...a.params,cursor:{token:c.nextCursor?.remote?.[o]?.providerPageCursor,position:c.nextCursor?.remote?.[o]?.position}}:a.params,l=await p({block:c,params:u});if(!1===l.successful){c=d({block:c,stepId:r,successful:!1,functionOutput:l});(s.ignoreError??!1)||(y=!0,g??=l.output?.statusCode??500)}else{const t=c.operation?.cursor.enabled?e.updateCursor({cursor:c.nextCursor,stepIndex:o,providerPageCursor:l.output?.next,position:l.output?.position}):void 0;c=d({block:{...l.block,nextCursor:t},stepId:r,functionOutput:l})}}const m=r.operation?.result?u(r.operation.result,c):void 0,b=r.operation?.cursor.enabled?s(m,l,i,c.nextCursor):void 0,f=!y,h=f?r.operation?.responses.success.statusCode??200:g??500,z=o.notMissing(b)&&o.isObject(b.result)?{next:b.next,...b.result}:m;return{...c,outputs:z,response:{successful:f,statusCode:h,message:f?void 0:r.operation?.responses?.errors?.[h]?.description??"Error while processing the request"}}},u=(e,r)=>o.isObject(e)?t.safeEvaluateRecord(e,r):t.safeEvaluate(e,r),d=({block:e,stepId:t,successful:o,functionOutput:r,skipped:n,message:s})=>({...e,steps:{...e.steps,[t]:{successful:o??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:n,message:s}}}),l=async({inputs:e,context:t,operation:o,credentials:n,nextCursor:s,logger:i,getHttpClient:a=async()=>r.HttpClientManager.getInstance()})=>({inputs:e,fieldConfigs:[],context:t,operation:o,credentials:n,nextCursor:s,httpClient:await a(),logger:i}),y=({category:e,connectorKey:t,connectorVersion:o,authConfigKey:r,environment:n="production",operation:s,accountSecureId:i,projectSecureId:a})=>({projectSecureId:a,accountSecureId:i,connectorKey:t,connectorVersion:o,category:e,service:"",resource:"",schema:s?.schema?.key,operationType:s?.operationType??"unknown",authenticationType:r,environment:n}),g=(e,t,o)=>{const r=o.toUpperCase();if(!e.operations)return;const n=Object.keys(e.operations),s=b(t,r,n);return s?{operation:e.operations?.[s.path],params:s.params}:void 0},m=e=>{const t=e.startsWith("/")?e.slice(1):e;return t.endsWith("/")?t.slice(0,-1):t},b=(e,t,o)=>{const r=m(e);for(const e of o)if(e.startsWith(t)){const o=e.replace(`${t} `,"").trim(),s=n.match(m(o))(m(r));if(!1!==s)return{path:e,params:s.params}}},f=e=>{switch(e){case"list":return{statusCode:200,description:"The list of records was retrieved."};case"get":return{statusCode:200,description:"The record with the given identifier was retrieved."};case"create":return{statusCode:201,description:"The record was created successfully."};case"update":return{statusCode:200,description:"The record was updated successfully."};case"delete":return{statusCode:204,description:"The record was deleted successfully."};case"custom":return{statusCode:200,description:"The operation was executed successfully."};case"unknown":return{statusCode:200};default:throw new Error(`Unknown operation type: ${e}`)}},h={key:i.z.string(),label:i.z.string(),required:i.z.boolean().optional().default(!1),secret:i.z.boolean().optional().default(!1),readOnly:i.z.boolean().optional().default(!1),placeholder:i.z.string().optional(),description:i.z.string().optional(),tooltip:i.z.string().optional()},z=i.z.discriminatedUnion("type",[i.z.object({...h,type:i.z.enum(["text","password"])}),i.z.object({...h,type:i.z.literal("select"),options:i.z.object({value:i.z.string(),label:i.z.string()}).array()})]),_=i.z.object({operationId:i.z.string(),categories:i.z.string().array(),operationType:i.z.enum(["list","get","create","update","delete","custom","unknown"]),schema:i.z.string().optional(),entrypointUrl:i.z.string().optional(),entrypointHttpMethod:i.z.string().optional(),description:i.z.string(),responses:i.z.object({statusCode:i.z.number(),description:i.z.string()}).array().optional(),inputs:i.z.object({name:i.z.string(),type:i.z.string(),required:i.z.boolean(),description:i.z.string(),in:i.z.string()}).array().optional(),cursor:i.z.object({enabled:i.z.boolean(),pageSize:i.z.number()}).optional(),compositeIdentifiers:i.z.object({enabled:i.z.boolean(),version:i.z.number().optional(),fields:i.z.object({targetFieldKey:i.z.string(),remote:i.z.string().optional(),components:i.z.string().array()}).array().optional()}).optional(),fieldConfigs:i.z.object({targetFieldKey:i.z.string(),alias:i.z.string().optional(),expression:i.z.string(),type:i.z.enum(["string","number","boolean","datetime_string","enum"]),custom:i.z.boolean().default(!1),hidden:i.z.boolean().default(!1),enumMapper:i.z.object({matcher:i.z.enum(["country_alpha2code_by_alpha2code","country_alpha3code_by_alpha3code","country_code_by_country_code","country_name_by_country_name","country_name_by_alpha3code","country_name_by_alpha2code","country_name_by_country_code","country_alpha3code_by_alpha2code","country_alpha3code_by_country_name","country_alpha3code_by_country_code","country_alpha2code_by_alpha3code","country_alpha2code_by_country_name","country_alpha2code_by_country_code","country_code_by_alpha2code","country_code_by_alpha3code","country_code_by_country_name","country_subdivisions_by_alpha2code","country_subdivision_code_by_subdivision_name","country_alpha2code_by_citizenship","country_subdivision_name_by_subdivision_code"]).or(i.z.object({matchExpression:i.z.string(),value:i.z.string()}).array())}).optional()}).array().optional(),steps:i.z.object({stepId:i.z.string(),description:i.z.string(),stepFunction:i.z.object({functionName:i.z.string(),version:i.z.string().optional(),parameters:i.z.record(i.z.string(),i.z.unknown())}),condition:i.z.string().optional(),ignoreError:i.z.boolean().optional()}).array(),result:i.z.string().or(i.z.record(i.z.string(),i.z.unknown())).optional()}),C=i.z.object({StackOne:i.z.string(),info:i.z.object({title:i.z.string(),version:i.z.string(),key:i.z.string(),description:i.z.string().optional()}),baseUrl:i.z.string(),authentication:i.z.record(i.z.string(),i.z.object({type:i.z.string(),label:i.z.string(),authorization:e.AUTHENTICATION_SCHEMA,environments:i.z.object({key:i.z.string(),name:i.z.string()}).array(),support:i.z.object({link:i.z.string(),description:i.z.string().optional()}),configFields:z.array().optional(),setupFields:z.array().optional(),testOperationsIds:i.z.string().array().optional()})).array().optional(),operations:_.array().optional()});function v(e){try{const t=s.parse(e),r=C.parse(t),n={title:r.info.title,version:r.info.version,key:r.info.key,description:r.info.description},i=S(r),a={baseUrl:r.baseUrl,authentication:k(i)},c=F(r,a);return n.operations=c,n.authentication=i,o.notMissing(c)&&(n.categories=I(Object.values(c))),n}catch(e){throw new Error(`Error parsing YAML file: ${e.message}`)}}const k=e=>{const t={};for(const[o,r]of Object.entries(e))if(r&&"object"==typeof r){const{setupFields:e,configFields:n,support:s,testOperationsIds:i,...a}=r;t[o]=k(a)}else t[o]=r;return t},I=e=>{const t=e.reduce(((e,t)=>{for(const o of t.categories)e.add(o);return e}),new Set);return Array.from(t)},S=e=>{const t={};for(const o of e.authentication??[]){const[e]=Object.keys(o),r=o[e].environments.reduce(((t,r)=>{const{key:n,name:s}=r,{environments:i,...a}=o[e];return t[n]={...a,envKey:n,envName:s},t}),{});t[e]=r}return t},F=(e,t)=>{const o=e.operations?.reduce(((e,o)=>{const n=(e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0)(o),s=(e=>"list"===e.operationType?`GET /${e.schema}`:`GET /${e.schema}/:id`)(o),i=(e=>"list"===e.operationType?`/${e.schema}`:`/${e.schema}/:id`)(o),a=(e=>{const t={success:f(e.operationType),errors:{400:{statusCode:400,description:"Invalid request."},401:{statusCode:401,description:"Unauthorized access."},403:{statusCode:403,description:"Forbidden."},404:{statusCode:404,description:"Resource not found."},500:{statusCode:500,description:"Server error while executing the request."}}},o=e.responses?.reduce(((e,t)=>(r.isSuccessStatusCode(t.statusCode)?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e)),t);return o??t})(o),c=O(o),p=o.inputs||[];return c.enabled&&p?.push({type:"string",name:"page_size",in:"query",required:!1,description:"Number of items to return per page"}),e[n??s]={id:o.operationId,categories:o.categories,description:o.description,operationType:o.operationType,entrypointUrl:o.entrypointUrl??i,entrypointHttpMethod:o.entrypointHttpMethod??"get",responses:a,cursor:c,compositeIdentifiers:j(o),inputs:p,steps:o.steps.reduce(((e,r)=>(e[r.stepId]={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{..."request"===r.stepFunction.functionName||"paginated_request"===r.stepFunction.functionName?t:{},..."map_fields"===r.stepFunction.functionName||"typecast"===r.stepFunction.functionName?{fields:o.fieldConfigs}:{},...r.stepFunction.parameters}}},e)),{}),result:o.result},e}),{});return o},x=(e,t)=>{if(!e.inputs)return{};const o=w(e.inputs).parse(t);return{...o.headers??{},...o.query??{},...o.path??{},...o.body??{}}},E=e=>{const t={};return e.forEach((e=>{let o;switch(e.type.toLowerCase()){case"string":o=i.z.string();break;case"number":o=i.z.number();break;case"boolean":o=i.z.boolean();break;default:o=i.z.any()}t[e.name]=e.required?o:o.optional()})),i.z.object(t)},w=e=>{const t=e.filter((e=>"path"===e.in)),o=e.filter((e=>"query"===e.in)),r=e.filter((e=>"body"===e.in)),n=e.filter((e=>"headers"===e.in));return i.z.object({path:E(t).optional(),query:E(o).optional(),body:E(r).optional(),headers:E(n).optional()})},O=e=>{const t="list"===e.operationType,o=e.cursor??{enabled:t,pageSize:25};return{enabled:o.enabled&&t,pageSize:o.pageSize}},j=t=>{if(o.isMissing(t.compositeIdentifiers)){const r=t.fieldConfigs?.find((e=>"id"===e.targetFieldKey)),n=o.notMissing(r)?[{targetFieldKey:r.targetFieldKey,remote:"id",components:[{name:r.targetFieldKey,alias:r.alias}]}]:void 0;return{enabled:!0,version:e.COMPOSITE_ID_LATEST_VERSION,fields:n}}const r=[];for(const e of t.compositeIdentifiers?.fields??[]){const o=e.components.map((e=>{const o=t.fieldConfigs?.find((t=>t.targetFieldKey===e));return{name:e,alias:o?.alias}}));r.push({targetFieldKey:e.targetFieldKey,remote:e.remote,components:o})}return{enabled:t.compositeIdentifiers.enabled,version:t.compositeIdentifiers.version,fields:r.length>0?r:void 0}};class T extends Error{constructor(e,t,o){super(o),this.name="ConnectSDKError",this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,T)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}}class N extends T{constructor(e,t){super("CONNECTOR_PARSE_ERROR",e,t),this.name="ConnectorParseError"}}class M extends T{constructor(e,t){super("MISSING_OPERATION_ERROR",e,t),this.name="MissingOperationError"}}class R extends T{constructor(e,t){super("INVALID_OPERATION_INPUTS_ERROR",e,t),this.name="InvalidOperationInputsError"}}class q extends T{constructor(e,t){super("INVALID_CURSOR_ERROR",e,t),this.name="InvalidCursorError"}}const K=(t,r)=>{const n=t?.next,s=o.notMissing(n)&&"list"===r.operationType?e.expandCursor(n):void 0;if(null===s)throw new q(r,"Invalid cursor.");return s};exports.ConnectSDKError=T,exports.createBlock=l,exports.executeStepFunction=async({block:t,stepFunctionName:o,params:r,buildStepFunction:n=e.StepFunctionsFactory.build})=>{const s=n({functionName:o}).fn,i=await s({block:t,params:r}),a=o===e.StepFunctionName.MAP_FIELDS?{[e.StepFunctionName.MAP_FIELDS.toString()]:{output:{data:i.block.result},errors:i.errors,successful:i.successful}}:{};return{...i.block,steps:{...i?.block?.steps??{},...a}}},exports.getOperationFromUrl=g,exports.parseOperationInputs=x,exports.parseYamlConnector=v,exports.runConnectorOperation=async({account:e,connector:t,category:r,path:n,method:s="get",queryParams:i,body:a,headers:p,logger:u,parseConnector:d=v,getOperationFromUrlFn:m=g,parseOperationInputsFn:b=x,createBlockContextFn:f=y,createBlockFn:h=l,runStepOperationFn:z=c})=>{const _=e.authConfigKey,C=e.environment??"production",k=e.secureId,I=e.projectSecureId,S=e.credentials,F=f({category:r,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:_,environment:C,accountSecureId:k,projectSecureId:I});let E;try{E=o.isString(t)?d(t):t}catch{throw new N(F,"Error while parsing connector")}const w=m(E,n,s);if(o.isMissing(w))throw new M(F,"No matching operation found");F.operationType=w.operation.operationType,F.schema=w.operation.schema?.key;const O=K(i,F);let j;try{j=b(w.operation,{query:i,body:a,headers:p,path:w.params})}catch{throw new R(F,"Error while parsing operation inputs")}const T=await h({inputs:j,context:F,operation:w.operation,credentials:S,nextCursor:O,logger:u});return await z({block:T})},exports.runStepOperation=c;
|
|
1
|
+
"use strict";var e=require("@stackone/core"),t=require("@stackone/expressions"),o=require("@stackone/utils"),r=require("@stackone/transport"),n=require("path-to-regexp"),s=require("yaml"),i=require("zod");const a="remote_",c=e=>{const t=e.operation?.compositeIdentifiers;if(!t?.enabled)return e;const r="data",n=e.outputs?.[r];if(o.isMissing(n))return e;const s=Array.isArray(n)?n.map((e=>u(e,t))):u(n,t);return{...e,outputs:{...e.outputs??{},[r]:s}}},u=(e,t)=>{const r=p(e,t),n=d(r);return{...e,...o.isObject(n)?n:{}}},p=(t,o)=>{const r=o.version??e.COMPOSITE_ID_LATEST_VERSION,n={};return o.fields?.forEach((o=>{const s={},i=[];o.components.forEach((e=>{e.alias&&(s[e.name]=e.alias),i.push({key:e.name,value:t[e.name]})}));const c=1===i.length?i[0]:{identifiers:i},u={version:r,aliases:Object.keys(s).length>0?s:void 0},p=e.encodeCompositeId(c,u);n[o.targetFieldKey]=p,o.remote&&(n[`${a}${o.remote}`]=t[o.remote])})),{...t,...n}},d=t=>{if(Array.isArray(t))return t.map((e=>d(e)));if(!o.isObject(t))return t;const r={...t};for(const[n,s]of Object.entries(t))if((o.isObject(s)||Array.isArray(s)&&s.length>0&&o.isObject(s[0]))&&(r[n]=d(s)),"id"===n||/.+_id(s)?$/.test(n))if(Array.isArray(s)&&s.every((e=>o.isString(e)&&e.length>0))){const t=s.map((t=>{if(o.isString(t)&&t.length>0&&!e.isCompositeId(t))try{return e.encodeCompositeId({key:n,value:t},{version:e.COMPOSITE_ID_LATEST_VERSION})}catch{return t}return t}));r[n]=t,r[`${a}${n}`]=s}else if(o.isString(s)&&s.length>0){if(e.isCompositeId(s)||n.startsWith(a))continue;const t=e.encodeCompositeId({key:n,value:s},{version:e.COMPOSITE_ID_LATEST_VERSION});r[n]=t,r[`remote_${n}`]=s}return r},l=(t,r,n,s)=>{const i=o.isMissing(t)?void 0:t.data,a=Object.keys(n).length+1,c=e.isCursorEmpty({cursor:s,ignoreStepIndex:a});if(!o.isObject(t)||o.isMissing(i)||(i?.length??0)<=r)return{result:t,next:o.notMissing(s)&&!c?e.minifyCursor(s):null};const u=s?.remote?.[a]?.pageNumber??1,p=(u-1)*r,d=p+r,l=i.slice(p,d),y=i.length>d||!c,g=e.updateCursor({cursor:s,stepIndex:a,pageNumber:u+1});return{result:{...t,data:l},next:y?e.minifyCursor(g):null}},y=async({block:t,buildStepFunction:o=e.StepFunctionsFactory.build,virtualPaginateResultFn:r=l,encodeResultCompositeIds:n=c})=>n(await g({block:t,buildStepFunction:o,virtualPaginateResultFn:r})),g=async({block:r,buildStepFunction:n=e.StepFunctionsFactory.build,virtualPaginateResultFn:s=l})=>{const i=r.operation?.steps||{};let a={...r};const c=Object.keys(i),u=((e,t)=>{const r=Number(e.inputs?.page_size);return o.notMissing(e.inputs?.page_size)&&o.isNumber(r)&&!Number.isNaN(r)?r:e.operation?.cursor?.pageSize??t})(r,25);let p=!1,d=null;for(const[o,r]of c.entries()){const s=i[r],c=s.stepFunction,u=n({functionName:c.functionName,version:c.version,validateSchemas:!0}).fn;if(s.condition&&!t.safeEvaluate(s.condition,a)){a=b({block:a,stepId:r,successful:!0,skipped:!0,message:"Step skipped due to condition not met."});continue}if(p){a=b({block:a,stepId:r,successful:!1,skipped:!0,message:"Step skipped due to previous error."});continue}const l=a.operation?.cursor.enabled?{...c.params,cursor:{token:a.nextCursor?.remote?.[o]?.providerPageCursor,position:a.nextCursor?.remote?.[o]?.position}}:c.params,y=await u({block:a,params:l});if(!1===y.successful){a=b({block:a,stepId:r,successful:!1,functionOutput:y});(s.ignoreError??!1)||(p=!0,d??=y.output?.statusCode??500)}else{const t=a.operation?.cursor.enabled?e.updateCursor({cursor:a.nextCursor,stepIndex:o,providerPageCursor:y.output?.next,position:y.output?.position}):void 0;a=b({block:{...y.block,nextCursor:t},stepId:r,functionOutput:y})}}const y=r.operation?.result?m(r.operation.result,a):void 0,g=r.operation?.cursor.enabled?s(y,u,i,a.nextCursor):void 0,f=!p,h=f?r.operation?.responses.success.statusCode??200:d??500,z=o.notMissing(g)&&o.isObject(g.result)?{next:g.next,...g.result}:y;return{...a,outputs:z,response:{successful:f,statusCode:h,message:f?void 0:r.operation?.responses?.errors?.[h]?.description??"Error while processing the request"}}},m=(e,r)=>o.isObject(e)?t.safeEvaluateRecord(e,r):t.safeEvaluate(e,r),b=({block:e,stepId:t,successful:o,functionOutput:r,skipped:n,message:s})=>({...e,steps:{...e.steps,[t]:{successful:o??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:n,message:s}}}),f=async({inputs:e,context:t,operation:o,credentials:n,nextCursor:s,logger:i,getHttpClient:a=async()=>r.HttpClientManager.getInstance()})=>({inputs:e,fieldConfigs:[],context:t,operation:o,credentials:n,nextCursor:s,httpClient:await a(),logger:i}),h=({category:e,connectorKey:t,connectorVersion:o,authConfigKey:r,environment:n="production",operation:s,accountSecureId:i,projectSecureId:a})=>({projectSecureId:a,accountSecureId:i,connectorKey:t,connectorVersion:o,category:e,service:"",resource:"",schema:s?.schema?.key,operationType:s?.operationType??"unknown",authenticationType:r,environment:n}),z=(e,t,o)=>{const r=o.toUpperCase();if(!e.operations)return;const n=Object.keys(e.operations),s=C(t,r,n);return s?{operation:e.operations?.[s.path],params:s.params}:void 0},_=e=>{const t=e.startsWith("/")?e.slice(1):e;return t.endsWith("/")?t.slice(0,-1):t},C=(e,t,o)=>{const r=_(e);for(const e of o)if(e.startsWith(t)){const o=e.replace(`${t} `,"").trim(),s=n.match(_(o))(_(r));if(!1!==s)return{path:e,params:s.params}}},v=e=>{switch(e){case"list":return{statusCode:200,description:"The list of records was retrieved."};case"get":return{statusCode:200,description:"The record with the given identifier was retrieved."};case"create":return{statusCode:201,description:"The record was created successfully."};case"update":return{statusCode:200,description:"The record was updated successfully."};case"delete":return{statusCode:204,description:"The record was deleted successfully."};case"custom":return{statusCode:200,description:"The operation was executed successfully."};case"unknown":return{statusCode:200};default:throw new Error(`Unknown operation type: ${e}`)}},I={key:i.z.string(),label:i.z.string(),required:i.z.boolean().optional().default(!1),secret:i.z.boolean().optional().default(!1),readOnly:i.z.boolean().optional().default(!1),placeholder:i.z.string().optional(),description:i.z.string().optional(),tooltip:i.z.string().optional()},S=i.z.discriminatedUnion("type",[i.z.object({...I,type:i.z.enum(["text","password"])}),i.z.object({...I,type:i.z.literal("select"),options:i.z.object({value:i.z.string(),label:i.z.string()}).array()})]),k=i.z.object({operationId:i.z.string(),categories:i.z.string().array(),operationType:i.z.enum(["list","get","create","update","delete","custom","unknown"]),schema:i.z.string().optional(),entrypointUrl:i.z.string().optional(),entrypointHttpMethod:i.z.string().optional(),description:i.z.string(),responses:i.z.object({statusCode:i.z.number(),description:i.z.string()}).array().optional(),inputs:i.z.object({name:i.z.string(),type:i.z.string(),required:i.z.boolean(),description:i.z.string(),in:i.z.string()}).array().optional(),cursor:i.z.object({enabled:i.z.boolean(),pageSize:i.z.number()}).optional(),compositeIdentifiers:i.z.object({enabled:i.z.boolean(),version:i.z.number().optional(),fields:i.z.object({targetFieldKey:i.z.string(),remote:i.z.string().optional(),components:i.z.string().array()}).array().optional()}).optional(),fieldConfigs:i.z.object({targetFieldKey:i.z.string(),alias:i.z.string().optional(),expression:i.z.string(),type:i.z.enum(["string","number","boolean","datetime_string","enum"]),custom:i.z.boolean().default(!1),hidden:i.z.boolean().default(!1),enumMapper:i.z.object({matcher:i.z.enum(["country_alpha2code_by_alpha2code","country_alpha3code_by_alpha3code","country_code_by_country_code","country_name_by_country_name","country_name_by_alpha3code","country_name_by_alpha2code","country_name_by_country_code","country_alpha3code_by_alpha2code","country_alpha3code_by_country_name","country_alpha3code_by_country_code","country_alpha2code_by_alpha3code","country_alpha2code_by_country_name","country_alpha2code_by_country_code","country_code_by_alpha2code","country_code_by_alpha3code","country_code_by_country_name","country_subdivisions_by_alpha2code","country_subdivision_code_by_subdivision_name","country_alpha2code_by_citizenship","country_subdivision_name_by_subdivision_code"]).or(i.z.object({matchExpression:i.z.string(),value:i.z.string()}).array())}).optional()}).array().optional(),steps:i.z.object({stepId:i.z.string(),description:i.z.string(),stepFunction:i.z.object({functionName:i.z.string(),version:i.z.string().optional(),parameters:i.z.record(i.z.string(),i.z.unknown())}),condition:i.z.string().optional(),ignoreError:i.z.boolean().optional()}).array(),result:i.z.string().or(i.z.record(i.z.string(),i.z.unknown())).optional()}),O=i.z.object({StackOne:i.z.string(),info:i.z.object({title:i.z.string(),version:i.z.string(),key:i.z.string(),description:i.z.string().optional()}),baseUrl:i.z.string(),authentication:i.z.record(i.z.string(),i.z.object({type:i.z.string(),label:i.z.string(),authorization:e.AUTHENTICATION_SCHEMA,environments:i.z.object({key:i.z.string(),name:i.z.string()}).array(),support:i.z.object({link:i.z.string(),description:i.z.string().optional()}),configFields:S.array().optional(),setupFields:S.array().optional(),testOperationsIds:i.z.string().array().optional()})).array().optional(),operations:k.array().optional()});function E(e){try{const t=s.parse(e),r=O.parse(t),n={title:r.info.title,version:r.info.version,key:r.info.key,description:r.info.description},i=T(r),a={baseUrl:r.baseUrl,authentication:F(i)},c=j(r,a);return n.operations=c,n.authentication=i,o.notMissing(c)&&(n.categories=x(Object.values(c))),n}catch(e){throw new Error(`Error parsing YAML file: ${e.message}`)}}const F=e=>{const t={};for(const[o,r]of Object.entries(e))if(r&&"object"==typeof r){const{setupFields:e,configFields:n,support:s,testOperationsIds:i,...a}=r;t[o]=F(a)}else t[o]=r;return t},x=e=>{const t=e.reduce(((e,t)=>{for(const o of t.categories)e.add(o);return e}),new Set);return Array.from(t)},T=e=>{const t={};for(const o of e.authentication??[]){const[e]=Object.keys(o),r=o[e].environments.reduce(((t,r)=>{const{key:n,name:s}=r,{environments:i,...a}=o[e];return t[n]={...a,envKey:n,envName:s},t}),{});t[e]=r}return t},j=(e,t)=>{const o=e.operations?.reduce(((e,o)=>{const n=(e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0)(o),s=(e=>"list"===e.operationType?`GET /${e.schema}`:`GET /${e.schema}/:id`)(o),i=(e=>"list"===e.operationType?`/${e.schema}`:`/${e.schema}/:id`)(o),a=(e=>{const t={success:v(e.operationType),errors:{400:{statusCode:400,description:"Invalid request."},401:{statusCode:401,description:"Unauthorized access."},403:{statusCode:403,description:"Forbidden."},404:{statusCode:404,description:"Resource not found."},500:{statusCode:500,description:"Server error while executing the request."}}},o=e.responses?.reduce(((e,t)=>(r.isSuccessStatusCode(t.statusCode)?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e)),t);return o??t})(o),c=R(o),u=o.inputs||[];return c.enabled&&u?.push({type:"string",name:"page_size",in:"query",required:!1,description:"Number of items to return per page"}),e[n??s]={id:o.operationId,categories:o.categories,description:o.description,operationType:o.operationType,entrypointUrl:o.entrypointUrl??i,entrypointHttpMethod:o.entrypointHttpMethod??"get",responses:a,cursor:c,compositeIdentifiers:A(o),inputs:u,steps:o.steps.reduce(((e,r)=>(e[r.stepId]={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{..."request"===r.stepFunction.functionName||"paginated_request"===r.stepFunction.functionName?t:{},..."map_fields"===r.stepFunction.functionName||"typecast"===r.stepFunction.functionName?{fields:o.fieldConfigs}:{},...r.stepFunction.parameters}}},e)),{}),result:o.result},e}),{});return o},w=(e,t)=>{if(!e.inputs)return{};const o=M(e.inputs).parse(t);return{...o.headers??{},...o.query??{},...o.path??{},...o.body??{}}},N=e=>{const t={};return e.forEach((e=>{let o;switch(e.type.toLowerCase()){case"string":o=i.z.string();break;case"number":o=i.z.number();break;case"boolean":o=i.z.boolean();break;default:o=i.z.any()}t[e.name]=e.required?o:o.optional()})),i.z.object(t)},M=e=>{const t=e.filter((e=>"path"===e.in)),o=e.filter((e=>"query"===e.in)),r=e.filter((e=>"body"===e.in)),n=e.filter((e=>"headers"===e.in));return i.z.object({path:N(t).optional(),query:N(o).optional(),body:N(r).optional(),headers:N(n).optional()})},R=e=>{const t="list"===e.operationType,o=e.cursor??{enabled:t,pageSize:25};return{enabled:o.enabled&&t,pageSize:o.pageSize}},A=t=>{if(o.isMissing(t.compositeIdentifiers)){const r=t.fieldConfigs?.find((e=>"id"===e.targetFieldKey)),n=o.notMissing(r)?[{targetFieldKey:r.targetFieldKey,remote:"id",components:[{name:r.targetFieldKey,alias:r.alias}]}]:void 0;return{enabled:!0,version:e.COMPOSITE_ID_LATEST_VERSION,fields:n}}const r=[];for(const e of t.compositeIdentifiers?.fields??[]){const o=e.components.map((e=>{const o=t.fieldConfigs?.find((t=>t.targetFieldKey===e));return{name:e,alias:o?.alias}}));r.push({targetFieldKey:e.targetFieldKey,remote:e.remote,components:o})}return{enabled:t.compositeIdentifiers.enabled,version:t.compositeIdentifiers.version,fields:r.length>0?r:void 0}};class q extends Error{constructor(e,t,o){super(o),this.name="ConnectSDKError",this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,q)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}}class K extends q{constructor(e,t){super("CONNECTOR_PARSE_ERROR",e,t),this.name="ConnectorParseError"}}class U extends q{constructor(e,t){super("MISSING_OPERATION_ERROR",e,t),this.name="MissingOperationError"}}class $ extends q{constructor(e,t){super("INVALID_OPERATION_INPUTS_ERROR",e,t),this.name="InvalidOperationInputsError"}}class P extends q{constructor(e,t){super("INVALID_CURSOR_ERROR",e,t),this.name="InvalidCursorError"}}const D=(t,r)=>{const n=t?.next,s=o.notMissing(n)&&"list"===r.operationType?e.expandCursor(n):void 0;if(null===s)throw new P(r,"Invalid cursor.");return s};exports.ConnectSDKError=q,exports.createBlock=f,exports.executeStepFunction=async({block:t,stepFunctionName:o,params:r,buildStepFunction:n=e.StepFunctionsFactory.build})=>{const s=n({functionName:o}).fn,i=await s({block:t,params:r}),a=o===e.StepFunctionName.MAP_FIELDS?{[e.StepFunctionName.MAP_FIELDS.toString()]:{output:{data:i.block.result},errors:i.errors,successful:i.successful}}:{};return{...i.block,steps:{...i?.block?.steps??{},...a}}},exports.getOperationFromUrl=z,exports.parseOperationInputs=w,exports.parseYamlConnector=E,exports.runConnectorOperation=async({account:e,connector:t,category:r,path:n,method:s="get",queryParams:i,body:a,headers:c,logger:u,parseConnector:p=E,getOperationFromUrlFn:d=z,parseOperationInputsFn:l=w,createBlockContextFn:g=h,createBlockFn:m=f,runStepOperationFn:b=y})=>{const _=e.authConfigKey,C=e.environment??"production",v=e.secureId,I=e.projectSecureId,S=e.credentials,k=g({category:r,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:_,environment:C,accountSecureId:v,projectSecureId:I});let O;try{O=o.isString(t)?p(t):t}catch{throw new K(k,"Error while parsing connector")}const F=d(O,n,s);if(o.isMissing(F))throw new U(k,"No matching operation found");k.operationType=F.operation.operationType,k.schema=F.operation.schema?.key;const x=D(i,k);let T;try{T=l(F.operation,{query:i,body:a,headers:c,path:F.params})}catch{throw new $(k,"Error while parsing operation inputs")}const j=await m({inputs:T,context:k,operation:F.operation,credentials:S,nextCursor:x,logger:u});return await b({block:j})},exports.runStepOperation=y;
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { Block, StepFunctionsFactory } from '@stackone/core';
|
|
2
|
+
import { encodeResultCompositeIdentifiers } from '../compositeIds/outputs';
|
|
2
3
|
import { virtualPaginateResult } from '../pagination/virtualPagination';
|
|
3
|
-
export declare const runStepOperation: ({ block, buildStepFunction, virtualPaginateResultFn, }: {
|
|
4
|
+
export declare const runStepOperation: ({ block, buildStepFunction, virtualPaginateResultFn, encodeResultCompositeIds, }: {
|
|
4
5
|
block: Block;
|
|
5
6
|
buildStepFunction?: typeof StepFunctionsFactory.build;
|
|
6
7
|
virtualPaginateResultFn?: typeof virtualPaginateResult;
|
|
8
|
+
encodeResultCompositeIds?: typeof encodeResultCompositeIdentifiers;
|
|
7
9
|
}) => Promise<Block>;
|