@stackone/connect-sdk 1.24.0 → 1.25.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 +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
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,expandCursor as i}from"@stackone/core";import{safeEvaluate as a,safeEvaluateRecord as c}from"@stackone/expressions";import{notMissing as p,isNumber as u,isMissing as d,isObject as l,isString as y}from"@stackone/utils";import{HttpClientManager as g,isSuccessStatusCode as m}from"@stackone/transport";import{match as b}from"path-to-regexp";import{parse as h}from"yaml";import{z as f}from"zod";const _=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=d(e)?void 0:e.data,c=Object.keys(s).length+1,u=o({cursor:i,ignoreStepIndex:c});if(!l(e)||d(a)||(a?.length??0)<=t)return{result:e,next:p(i)&&!u?r(i):null};const y=i?.remote?.[c]?.pageNumber??1,g=(y-1)*t,m=g+t,b=a.slice(g,m),h=a.length>m||!u,f=n({cursor:i,stepIndex:c,pageNumber:y+1});return{result:{...e,data:b},next:h?r(f):null}},v=async({block:t,buildStepFunction:o=e.build,virtualPaginateResultFn:r=k})=>await C({block:t,buildStepFunction:o,virtualPaginateResultFn:r}),C=async({block:t,buildStepFunction:o=e.build,virtualPaginateResultFn:r=k})=>{const s=t.operation?.steps||{};let i={...t};const c=Object.keys(s),d=((e,t)=>{const o=Number(e.inputs?.page_size);return p(e.inputs?.page_size)&&u(o)&&!Number.isNaN(o)?o:e.operation?.cursor?.pageSize??t})(t,25);let y=!1,g=null;for(const[e,t]of c.entries()){const r=s[t],c=r.stepFunction,p=o({functionName:c.functionName,version:c.version,validateSchemas:!0}).fn;if(r.condition&&!a(r.condition,i)){i=w({block:i,stepId:t,successful:!0,skipped:!0,message:"Step skipped due to condition not met."});continue}if(y){i=w({block:i,stepId:t,successful:!1,skipped:!0,message:"Step skipped due to previous error."});continue}const u=i.operation?.cursor.enabled?{...c.params,cursor:{token:i.nextCursor?.remote?.[e]?.providerPageCursor,position:i.nextCursor?.remote?.[e]?.position}}:c.params,d=await p({block:i,params:u});if(!1===d.successful){i=w({block:i,stepId:t,successful:!1,functionOutput:d});(r.ignoreError??!1)||(y=!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=w({block:{...d.block,nextCursor:o},stepId:t,functionOutput:d})}}const m=t.operation?.result?I(t.operation.result,i):void 0,b=t.operation?.cursor.enabled?r(m,d,s,i.nextCursor):void 0,h=!y,f=h?t.operation?.responses.success.statusCode??200:g??500,_=p(b)&&l(b.result)?{next:b.next,...b.result}:m;return{...i,outputs:_,response:{successful:h,statusCode:f,message:h?void 0:t.operation?.responses?.errors?.[f]?.description??"Error while processing the request"}}},I=(e,t)=>l(e)?c(e,t):a(e,t),w=({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()=>g.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}),E=(e,t,o)=>{const r=o.toUpperCase();if(!e.operations)return;const n=Object.keys(e.operations),s=j(t,r,n);return s?{operation:e.operations?.[s.path],params:s.params}:void 0},F=e=>{const t=e.startsWith("/")?e.slice(1):e;return t.endsWith("/")?t.slice(0,-1):t},j=(e,t,o)=>{const r=F(e);for(const e of o)if(e.startsWith(t)){const o=e.replace(`${t} `,"").trim(),n=b(F(o))(F(r));if(!1!==n)return{path:e,params:n.params}}},O=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}`)}},T={key:f.string(),label:f.string(),required:f.boolean().optional().default(!1),secret:f.boolean().optional().default(!1),readOnly:f.boolean().optional().default(!1),placeholder:f.string().optional(),description:f.string().optional(),tooltip:f.string().optional()},N=f.discriminatedUnion("type",[f.object({...T,type:f.enum(["text","password"])}),f.object({...T,type:f.literal("select"),options:f.object({value:f.string(),label:f.string()}).array()})]),R=f.object({operationId:f.string(),categories:f.string().array(),operationType:f.enum(["list","get","create","update","delete","custom","unknown"]),schema:f.string().optional(),entrypointUrl:f.string().optional(),entrypointHttpMethod:f.string().optional(),description:f.string(),responses:f.object({statusCode:f.number(),description:f.string()}).array().optional(),inputs:f.object({name:f.string(),type:f.string(),required:f.boolean(),description:f.string(),in:f.string()}).array().optional(),cursor:f.object({enabled:f.boolean(),pageSize:f.number()}).optional(),fieldConfigs:f.object({targetFieldKey:f.string(),expression:f.string(),type:f.enum(["string","number","boolean","datetime_string","enum"]),isUnified:f.boolean(),enumMapper:f.object({matcher:f.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(f.object({matchExpression:f.string(),value:f.string()}).array())}).optional()}).array().optional(),steps:f.object({stepId:f.string(),description:f.string(),stepFunction:f.object({functionName:f.string(),version:f.string().optional(),parameters:f.record(f.string(),f.unknown())}),condition:f.string().optional(),ignoreError:f.boolean().optional()}).array(),result:f.string().or(f.record(f.string(),f.unknown())).optional()}),U=f.object({StackOne:f.string(),info:f.object({title:f.string(),version:f.string(),key:f.string(),description:f.string().optional()}),baseUrl:f.string(),authentication:f.record(f.string(),f.object({type:f.string(),label:f.string(),authorization:s,environments:f.object({key:f.string(),name:f.string()}).array(),support:f.object({link:f.string(),description:f.string().optional()}),configFields:N.array().optional(),setupFields:N.array().optional(),testOperationsIds:f.string().array().optional()})).array().optional(),operations:R.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,p(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:O(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)=>(m(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=L(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,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},K=(e,t)=>{if(!e.inputs)return{};const o=H(e.inputs).parse(t);return{...o.headers??{},...o.query??{},...o.path??{},...o.body??{}}},A=e=>{const t={};return e.forEach((e=>{let o;switch(e.type.toLowerCase()){case"string":o=f.string();break;case"number":o=f.number();break;case"boolean":o=f.boolean();break;default:o=f.any()}t[e.name]=e.required?o:o.optional()})),f.object(t)},H=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 f.object({path:A(t).optional(),query:A(o).optional(),body:A(r).optional(),headers:A(n).optional()})},L=e=>{const t="list"===e.operationType,o=e.cursor??{enabled:t,pageSize:25};return{enabled:o.enabled&&t,pageSize:o.pageSize}};class V extends Error{constructor(e,t,o){super(o),this.name="ConnectSDKError",this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,V)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}}class D extends V{constructor(e,t){super("CONNECTOR_PARSE_ERROR",e,t),this.name="ConnectorParseError"}}class G extends V{constructor(e,t){super("MISSING_OPERATION_ERROR",e,t),this.name="MissingOperationError"}}class W extends V{constructor(e,t){super("INVALID_OPERATION_INPUTS_ERROR",e,t),this.name="InvalidOperationInputsError"}}class B extends V{constructor(e,t){super("INVALID_CURSOR_ERROR",e,t),this.name="InvalidCursorError"}}const Y=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=E,parseOperationInputsFn:l=K,createBlockContextFn:g=x,createBlockFn:m=S,runStepOperationFn:b=v})=>{const h=e.authConfigKey,f=e.environment??"production",_=e.secureId,k=e.projectSecureId,C=e.credentials,I=g({category:o,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:h,environment:f,accountSecureId:_,projectSecureId:k});let w;try{w=y(t)?p(t):t}catch{throw new D(I,"Error while parsing connector")}const F=u(w,r,n);if(d(F))throw new G(I,"No matching operation found");I.operationType=F.operation.operationType,I.schema=F.operation.schema?.key;const j=J(s,I);let O;try{O=l(F.operation,{query:s,body:i,headers:a,path:F.params})}catch{throw new W(I,"Error while parsing operation inputs")}const T=await m({inputs:O,context:I,operation:F.operation,credentials:C,nextCursor:j,logger:c});return await b({block:T})},J=(e,t)=>{const o=e?.next,r=p(o)&&"list"===t.operationType?i(o):void 0;if(null===r)throw new B(t,"Invalid cursor.");return r};export{V as ConnectSDKError,S as createBlock,_ as executeStepFunction,E as getOperationFromUrl,K as parseOperationInputs,q as parseYamlConnector,Y as runConnectorOperation,v as runStepOperation};
|
|
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 h}from"path-to-regexp";import{parse as f}from"yaml";import{z as _}from"zod";const k=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}}},v=(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),h=a.length>m||!p,f=n({cursor:i,stepIndex:c,pageNumber:d+1});return{result:{...e,data:b},next:h?r(f):null}},C=async({block:t,buildStepFunction:o=e.build,virtualPaginateResultFn:r=v})=>await I({block:t,buildStepFunction:o,virtualPaginateResultFn:r}),I=async({block:t,buildStepFunction:o=e.build,virtualPaginateResultFn:r=v})=>{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=S({block:i,stepId:t,successful:!0,skipped:!0,message:"Step skipped due to condition not met."});continue}if(l){i=S({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=S({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=S({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,h=!l,f=h?t.operation?.responses.success.statusCode??200:g??500,_=u(b)&&y(b.result)?{next:b.next,...b.result}:m;return{...i,outputs:_,response:{successful:h,statusCode:f,message:h?void 0:t.operation?.responses?.errors?.[f]?.description??"Error while processing the request"}}},w=(e,t)=>y(e)?p(e,t):c(e,t),S=({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}}}),x=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}),E=({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}),F=(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},j=e=>{const t=e.startsWith("/")?e.slice(1):e;return t.endsWith("/")?t.slice(0,-1):t},O=(e,t,o)=>{const r=j(e);for(const e of o)if(e.startsWith(t)){const o=e.replace(`${t} `,"").trim(),n=h(j(o))(j(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()})]),U=_.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(),fieldConfigs:_.object({targetFieldKey:_.string(),expression:_.string(),type:_.enum(["string","number","boolean","datetime_string","enum"]),isUnified:_.boolean(),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()}),q=_.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:U.array().optional()});function P(e){try{const t=f(e),o=q.parse(t),r={title:o.info.title,version:o.info.version,key:o.info.key,description:o.info.description},n=M(o),s={baseUrl:o.baseUrl,authentication:z(n)},i=K(o,s);return r.operations=i,r.authentication=n,u(i)&&(r.categories=$(Object.values(i))),r}catch(e){throw new Error(`Error parsing YAML file: ${e.message}`)}}const z=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]=z(a)}else t[o]=r;return t},$=e=>{const t=e.reduce(((e,t)=>{for(const o of t.categories)e.add(o);return e}),new Set);return Array.from(t)},M=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},K=(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),a=(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),c=V(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[r??n]={id:o.operationId,categories:o.categories,description:o.description,operationType:o.operationType,entrypointUrl:o.entrypointUrl??s,entrypointHttpMethod:o.entrypointHttpMethod??"get",responses:a,cursor:c,compositeIdentifiers:{enabled:!1,version:i},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},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}};class D extends Error{constructor(e,t,o){super(o),this.name="ConnectSDKError",this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,D)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}}class G extends D{constructor(e,t){super("CONNECTOR_PARSE_ERROR",e,t),this.name="ConnectorParseError"}}class W extends D{constructor(e,t){super("MISSING_OPERATION_ERROR",e,t),this.name="MissingOperationError"}}class B extends D{constructor(e,t){super("INVALID_OPERATION_INPUTS_ERROR",e,t),this.name="InvalidOperationInputsError"}}class Y extends D{constructor(e,t){super("INVALID_CURSOR_ERROR",e,t),this.name="InvalidCursorError"}}const J=async({account:e,connector:t,category:o,path:r,method:n="get",queryParams:s,body:i,headers:a,logger:c,parseConnector:p=P,getOperationFromUrlFn:u=F,parseOperationInputsFn:d=A,createBlockContextFn:y=E,createBlockFn:m=x,runStepOperationFn:b=C})=>{const h=e.authConfigKey,f=e.environment??"production",_=e.secureId,k=e.projectSecureId,v=e.credentials,I=y({category:o,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:h,environment:f,accountSecureId:_,projectSecureId:k});let w;try{w=g(t)?p(t):t}catch{throw new G(I,"Error while parsing connector")}const S=u(w,r,n);if(l(S))throw new W(I,"No matching operation found");I.operationType=S.operation.operationType,I.schema=S.operation.schema?.key;const j=Q(s,I);let O;try{O=d(S.operation,{query:s,body:i,headers:a,path:S.params})}catch{throw new B(I,"Error while parsing operation inputs")}const T=await m({inputs:O,context:I,operation:S.operation,credentials:v,nextCursor:j,logger:c});return await b({block:T})},Q=(e,t)=>{const o=e?.next,r=u(o)&&"list"===t.operationType?a(o):void 0;if(null===r)throw new Y(t,"Invalid cursor.");return r};export{D as ConnectSDKError,x as createBlock,k as executeStepFunction,F as getOperationFromUrl,A as parseOperationInputs,P as parseYamlConnector,J as runConnectorOperation,C 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 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}},c=async({block:t,buildStepFunction:o=e.StepFunctionsFactory.build,virtualPaginateResultFn:r=a})=>await u({block:t,buildStepFunction:o,virtualPaginateResultFn:r}),u=async({block:r,buildStepFunction:n=e.StepFunctionsFactory.build,virtualPaginateResultFn:s=a})=>{const i=r.operation?.steps||{};let c={...r};const u=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 u.entries()){const s=i[r],a=s.stepFunction,u=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 p=c.operation?.cursor.enabled?{...a.params,cursor:{token:c.nextCursor?.remote?.[o]?.providerPageCursor,position:c.nextCursor?.remote?.[o]?.position}}:a.params,l=await u({block:c,params:p});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 b=r.operation?.result?p(r.operation.result,c):void 0,m=r.operation?.cursor.enabled?s(b,l,i,c.nextCursor):void 0,h=!y,z=h?r.operation?.responses.success.statusCode??200:g??500,f=o.notMissing(m)&&o.isObject(m.result)?{next:m.next,...m.result}:b;return{...c,outputs:f,response:{successful:h,statusCode:z,message:h?void 0:r.operation?.responses?.errors?.[z]?.description??"Error while processing the request"}}},p=(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=m(t,r,n);return s?{operation:e.operations?.[s.path],params:s.params}:void 0},b=e=>{const t=e.startsWith("/")?e.slice(1):e;return t.endsWith("/")?t.slice(0,-1):t},m=(e,t,o)=>{const r=b(e);for(const e of o)if(e.startsWith(t)){const o=e.replace(`${t} `,"").trim(),s=n.match(b(o))(b(r));if(!1!==s)return{path:e,params:s.params}}},h=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}`)}},z={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()},f=i.z.discriminatedUnion("type",[i.z.object({...z,type:i.z.enum(["text","password"])}),i.z.object({...z,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(),fieldConfigs:i.z.object({targetFieldKey:i.z.string(),expression:i.z.string(),type:i.z.enum(["string","number","boolean","datetime_string","enum"]),isUnified:i.z.boolean(),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:f.array().optional(),setupFields:f.array().optional(),testOperationsIds:i.z.string().array().optional()})).array().optional(),operations:_.array().optional()});function k(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=x(r),a={baseUrl:r.baseUrl,authentication:v(i)},c=I(r,a);return n.operations=c,n.authentication=i,o.notMissing(c)&&(n.categories=S(Object.values(c))),n}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},S=e=>{const t=e.reduce(((e,t)=>{for(const o of t.categories)e.add(o);return e}),new Set);return Array.from(t)},x=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},I=(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:h(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),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,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},F=(e,t)=>{if(!e.inputs)return{};const o=E(e.inputs).parse(t);return{...o.headers??{},...o.query??{},...o.path??{},...o.body??{}}},w=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)},E=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:w(t).optional(),query:w(o).optional(),body:w(r).optional(),headers:w(n).optional()})},O=e=>{const t="list"===e.operationType,o=e.cursor??{enabled:t,pageSize:25};return{enabled:o.enabled&&t,pageSize:o.pageSize}};class j extends Error{constructor(e,t,o){super(o),this.name="ConnectSDKError",this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,j)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}}class N extends j{constructor(e,t){super("CONNECTOR_PARSE_ERROR",e,t),this.name="ConnectorParseError"}}class T extends j{constructor(e,t){super("MISSING_OPERATION_ERROR",e,t),this.name="MissingOperationError"}}class R extends j{constructor(e,t){super("INVALID_OPERATION_INPUTS_ERROR",e,t),this.name="InvalidOperationInputsError"}}class q extends j{constructor(e,t){super("INVALID_CURSOR_ERROR",e,t),this.name="InvalidCursorError"}}const M=(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=j,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=F,exports.parseYamlConnector=k,exports.runConnectorOperation=async({account:e,connector:t,category:r,path:n,method:s="get",queryParams:i,body:a,headers:u,logger:p,parseConnector:d=k,getOperationFromUrlFn:b=g,parseOperationInputsFn:m=F,createBlockContextFn:h=y,createBlockFn:z=l,runStepOperationFn:f=c})=>{const _=e.authConfigKey,C=e.environment??"production",v=e.secureId,S=e.projectSecureId,x=e.credentials,I=h({category:r,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:_,environment:C,accountSecureId:v,projectSecureId:S});let w;try{w=o.isString(t)?d(t):t}catch{throw new N(I,"Error while parsing connector")}const E=b(w,n,s);if(o.isMissing(E))throw new T(I,"No matching operation found");I.operationType=E.operation.operationType,I.schema=E.operation.schema?.key;const O=M(i,I);let j;try{j=m(E.operation,{query:i,body:a,headers:u,path:E.params})}catch{throw new R(I,"Error while parsing operation inputs")}const q=await z({inputs:j,context:I,operation:E.operation,credentials:x,nextCursor:O,logger:p});return await f({block:q})},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=(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}},c=async({block:t,buildStepFunction:o=e.StepFunctionsFactory.build,virtualPaginateResultFn:r=a})=>await u({block:t,buildStepFunction:o,virtualPaginateResultFn:r}),u=async({block:r,buildStepFunction:n=e.StepFunctionsFactory.build,virtualPaginateResultFn:s=a})=>{const i=r.operation?.steps||{};let c={...r};const u=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 u.entries()){const s=i[r],a=s.stepFunction,u=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 p=c.operation?.cursor.enabled?{...a.params,cursor:{token:c.nextCursor?.remote?.[o]?.providerPageCursor,position:c.nextCursor?.remote?.[o]?.position}}:a.params,l=await u({block:c,params:p});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 b=r.operation?.result?p(r.operation.result,c):void 0,m=r.operation?.cursor.enabled?s(b,l,i,c.nextCursor):void 0,h=!y,z=h?r.operation?.responses.success.statusCode??200:g??500,f=o.notMissing(m)&&o.isObject(m.result)?{next:m.next,...m.result}:b;return{...c,outputs:f,response:{successful:h,statusCode:z,message:h?void 0:r.operation?.responses?.errors?.[z]?.description??"Error while processing the request"}}},p=(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=m(t,r,n);return s?{operation:e.operations?.[s.path],params:s.params}:void 0},b=e=>{const t=e.startsWith("/")?e.slice(1):e;return t.endsWith("/")?t.slice(0,-1):t},m=(e,t,o)=>{const r=b(e);for(const e of o)if(e.startsWith(t)){const o=e.replace(`${t} `,"").trim(),s=n.match(b(o))(b(r));if(!1!==s)return{path:e,params:s.params}}},h=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}`)}},z={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()},f=i.z.discriminatedUnion("type",[i.z.object({...z,type:i.z.enum(["text","password"])}),i.z.object({...z,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(),fieldConfigs:i.z.object({targetFieldKey:i.z.string(),expression:i.z.string(),type:i.z.enum(["string","number","boolean","datetime_string","enum"]),isUnified:i.z.boolean(),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:f.array().optional(),setupFields:f.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=I(r),a={baseUrl:r.baseUrl,authentication:k(i)},c=x(r,a);return n.operations=c,n.authentication=i,o.notMissing(c)&&(n.categories=S(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},S=e=>{const t=e.reduce(((e,t)=>{for(const o of t.categories)e.add(o);return e}),new Set);return Array.from(t)},I=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},x=(t,o)=>{const n=t.operations?.reduce(((t,n)=>{const s=(e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0)(n),i=(e=>"list"===e.operationType?`GET /${e.schema}`:`GET /${e.schema}/:id`)(n),a=(e=>"list"===e.operationType?`/${e.schema}`:`/${e.schema}/:id`)(n),c=(e=>{const t={success:h(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})(n),u=O(n),p=n.inputs||[];return u.enabled&&p?.push({type:"string",name:"page_size",in:"query",required:!1,description:"Number of items to return per page"}),t[s??i]={id:n.operationId,categories:n.categories,description:n.description,operationType:n.operationType,entrypointUrl:n.entrypointUrl??a,entrypointHttpMethod:n.entrypointHttpMethod??"get",responses:c,cursor:u,compositeIdentifiers:{enabled:!1,version:e.COMPOSITE_ID_LATEST_VERSION},inputs:p,steps:n.steps.reduce(((e,t)=>(e[t.stepId]={id:t.stepId,description:t.description,condition:t.condition,ignoreError:t.ignoreError,stepFunction:{functionName:t.stepFunction.functionName,version:t.stepFunction.version,params:{..."request"===t.stepFunction.functionName||"paginated_request"===t.stepFunction.functionName?o:{},..."map_fields"===t.stepFunction.functionName||"typecast"===t.stepFunction.functionName?{fields:n.fieldConfigs}:{},...t.stepFunction.parameters}}},e)),{}),result:n.result},t}),{});return n},E=(e,t)=>{if(!e.inputs)return{};const o=w(e.inputs).parse(t);return{...o.headers??{},...o.query??{},...o.path??{},...o.body??{}}},F=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:F(t).optional(),query:F(o).optional(),body:F(r).optional(),headers:F(n).optional()})},O=e=>{const t="list"===e.operationType,o=e.cursor??{enabled:t,pageSize:25};return{enabled:o.enabled&&t,pageSize:o.pageSize}};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 j 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 M=(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=E,exports.parseYamlConnector=v,exports.runConnectorOperation=async({account:e,connector:t,category:r,path:n,method:s="get",queryParams:i,body:a,headers:u,logger:p,parseConnector:d=v,getOperationFromUrlFn:b=g,parseOperationInputsFn:m=E,createBlockContextFn:h=y,createBlockFn:z=l,runStepOperationFn:f=c})=>{const _=e.authConfigKey,C=e.environment??"production",k=e.secureId,S=e.projectSecureId,I=e.credentials,x=h({category:r,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:_,environment:C,accountSecureId:k,projectSecureId:S});let F;try{F=o.isString(t)?d(t):t}catch{throw new N(x,"Error while parsing connector")}const w=b(F,n,s);if(o.isMissing(w))throw new j(x,"No matching operation found");x.operationType=w.operation.operationType,x.schema=w.operation.schema?.key;const O=M(i,x);let T;try{T=m(w.operation,{query:i,body:a,headers:u,path:w.params})}catch{throw new R(x,"Error while parsing operation inputs")}const q=await z({inputs:T,context:x,operation:w.operation,credentials:I,nextCursor:O,logger:p});return await f({block:q})},exports.runStepOperation=c;
|