@stackone/connect-sdk 1.59.2 → 1.60.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.d.mts CHANGED
@@ -615,6 +615,7 @@ type ValidationError = {
615
615
  declare const validateYamlConnector: (yamlFileContents: string) => {
616
616
  success: boolean;
617
617
  errors?: ValidationError[];
618
+ connector?: Connector;
618
619
  };
619
620
  //#endregion
620
621
  //#region src/errors/types.d.ts
package/dist/index.d.ts CHANGED
@@ -615,6 +615,7 @@ type ValidationError = {
615
615
  declare const validateYamlConnector: (yamlFileContents: string) => {
616
616
  success: boolean;
617
617
  errors?: ValidationError[];
618
+ connector?: Connector;
618
619
  };
619
620
  //#endregion
620
621
  //#region src/errors/types.d.ts
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=s(require(`@stackone/utils`)),l=s(require(`fs`)),u=s(require(`path`)),d=s(require(`path-to-regexp`)),f=s(require(`@stackone/core`)),p=s(require(`@stackone/transport`)),m=s(require(`yaml`)),h=s(require(`@stackone/expressions`)),g=async({connector:e,inputs:t,context:n,operation:r,credentials:i,nextCursor:a,logger:o,getHttpClient:s})=>{if((0,c.isMissing)(s))throw Error(`getHttpClient function is required`);let l=await s();return{connector:e,inputs:t,fieldConfigs:[],context:n,operation:r,credentials:i,nextCursor:a,httpClient:l,logger:o}},_=e=>{if(!e.endsWith(`.s1.yaml`))throw Error(`File must have .s1.yaml extension`);try{let t=(0,l.readFileSync)(e,`utf8`);if(!t.includes(`:`)||!t.includes(`$ref:`))return t;let n=t.split(`
2
2
  `),r=v(n,(0,u.dirname)(e));return r.join(`
3
3
  `)}catch(e){throw Error(`Failed to process YAML file: ${e.message}`)}},v=(e,t)=>{let n=[];for(let r of e)if(y(r)){let e=r.match(/^(\s*)/)?.[1]?.length||0,i=r.split(`:`)[1]?.trim(),a=b(i,t),o=a.map(t=>` `.repeat(e)+t);n.push(...o)}else n.push(r);return n},y=e=>e.includes(`$ref:`),b=(e,t)=>{let n=(0,u.resolve)((0,u.join)(t,`${e.replaceAll(`'`,``)}.s1.partial.yaml`));try{let e=(0,l.readFileSync)(n,`utf8`);return e.split(`
4
- `).filter(e=>e.trim()!==``)}catch(t){throw Error(`Failed to load partial file '${e}': ${t.message}`)}},x=(e,t,n)=>{let r=n.toUpperCase();if(!e.operations)return;let i=Object.values(e.operations).filter(e=>(0,c.notMissing)(e.endpoint)).map(e=>({operationId:e.id,endpoint:e.endpoint})),a=C(t,r,i);if(a)return{operation:e.operations?.[a.operationId],params:a.params}},S=e=>{let t=e.startsWith(`/`)?e.slice(1):e,n=t.endsWith(`/`)?t.slice(0,-1):t;return n},C=(e,t,n)=>{let r=S(e);for(let e of n)if(e.endpoint?.startsWith(t)){let n=e.endpoint.replace(`${t} `,``).trim(),i=(0,d.match)(S(n)),a=i(S(r));if(a!==!1)return{operationId:e.operationId,path:e.endpoint,params:a.params}}},w=(e,t)=>t?.startsWith(`${e}_`)?t:`${e}_${t}`,ee=(e,t)=>{let n=`${e.key}_`,r=t.startsWith(n)?t:`${n}${t}`;return e.operations?.[r]};var T=class e extends Error{errorType;constructor(t,n){super(n),this.name=`InternalConnectSDKError`,this.errorType=t,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},E=class extends T{line;constructor(e,t){super(`INVALID_YAML_FILE_ERROR`,t),this.name=`InvalidYamlFileError`,this.line=e??1}},D=class extends T{issues;constructor(e,t){super(`SCHEMA_VALIDATION_ERROR`,t),this.name=`SchemaValidationError`,this.issues=e}},O=class extends T{operationId;stepId;functionName;functionVersion;constructor(e,t,n,r=`1`){let i=`Invalid Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the function name and version are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION`,i),this.name=`InvalidStepFunctionError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r}},k=class extends T{operationId;stepId;functionName;functionVersion;issues;constructor(e,t,n,r=`1`,i){let a=`Invalid parameters for Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the parameters are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION_PARAMS`,a),this.name=`InvalidStepFunctionParamsError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r,this.issues=i,this.message=a}};const A=25,j=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`refresh_token`:return{statusCode:200,description:`The refresh token operation was executed successfully.`};case`unknown`:return{statusCode:200};default:throw Error(`Unknown operation type: ${e}`)}},te=()=>{let e={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.`}};return e},ne={key:c.z.string(),label:c.z.string(),required:c.z.boolean().optional().default(!1),secret:c.z.boolean().optional().default(!1),readOnly:c.z.boolean().optional().default(!1),placeholder:c.z.string().optional(),description:c.z.string().optional(),tooltip:c.z.string().optional()},re=c.z.discriminatedUnion(`type`,[(0,c.zStrictObject)({...ne,type:c.z.enum([`text`,`password`])}),(0,c.zStrictObject)({...ne,type:c.z.literal(`select`),options:(0,c.zStrictObject)({value:c.z.string(),label:c.z.string()}).array()})]),M=(0,c.zStrictObject)({targetFieldKey:c.z.string(),alias:c.z.string().optional(),expression:c.z.string().optional(),values:c.z.unknown().optional(),type:c.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:c.z.boolean().default(!1),custom:c.z.boolean().default(!1),hidden:c.z.boolean().default(!1),enumMapper:(0,c.zStrictObject)({matcher:c.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`,`document_file_format_from_extension`]).or((0,c.zStrictObject)({matchExpression:c.z.string(),value:c.z.string()}).array())}).optional(),properties:c.z.lazy(()=>M).array().optional()}),N=(0,c.zStrictObject)({name:c.z.string(),type:c.z.enum([`string`,`number`,`boolean`,`datetime_string`,`object`]),required:c.z.boolean(),description:c.z.string(),array:c.z.boolean().optional().default(!1),in:c.z.enum([`body`,`query`,`path`,`headers`]),properties:c.z.lazy(()=>N.omit({in:!0})).array().optional()}),P=(0,c.zStrictObject)({operationId:c.z.string(),categories:c.z.string().array(),operationType:c.z.enum([`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`unknown`]),schema:c.z.string().optional(),schemaType:c.z.enum([`native`,`unified`]).optional().default(`native`),entrypointUrl:c.z.string().optional(),entrypointHttpMethod:c.z.string().optional(),label:c.z.string(),description:c.z.string(),tags:c.z.string().array().optional(),context:c.z.string().optional(),responses:(0,c.zStrictObject)({statusCode:c.z.number(),description:c.z.string()}).array().optional(),inputs:N.array().optional(),cursor:(0,c.zStrictObject)({enabled:c.z.boolean(),pageSize:c.z.number()}).optional(),compositeIdentifiers:(0,c.zStrictObject)({enabled:c.z.boolean(),version:c.z.number().optional(),fields:(0,c.zStrictObject)({targetFieldKey:c.z.string(),remote:c.z.string().optional(),components:c.z.string().array()}).array().optional()}).optional(),scheduledJobs:(0,c.zStrictObject)({enabled:c.z.boolean(),type:c.z.enum([`data_sync`]),schedule:c.z.string(),description:c.z.string(),requestParams:(0,c.zStrictObject)({fields:c.z.string().array().optional(),expand:c.z.string().array().optional(),filter:c.z.record(c.z.string(),c.z.string()).optional()}).optional(),syncFilter:(0,c.zStrictObject)({name:c.z.enum([`updated_after`,`created_after`]),initialLoopbackPeriod:c.z.string(),incrementalLoopbackPeriod:c.z.string()}).optional()}).array().optional(),fieldConfigs:M.array().optional(),steps:(0,c.zStrictObject)({stepId:c.z.string(),description:c.z.string(),stepFunction:(0,c.zStrictObject)({functionName:c.z.string(),version:c.z.string().optional(),parameters:c.z.record(c.z.string(),c.z.unknown())}),condition:c.z.string().optional(),ignoreError:c.z.boolean().optional()}).array(),result:c.z.string().or(c.z.record(c.z.string(),c.z.unknown())).optional()}),ie=(0,c.zStrictObject)({schedule:c.z.string().optional(),operation:P.extend({operationType:c.z.literal(`refresh_token`)})}),ae=(0,c.zStrictObject)({mainRatelimit:c.z.number(),subPools:c.z.array((0,c.zStrictObject)({subPoolKey:c.z.string(),urlPattern:c.z.string(),rateLimit:c.z.number()})).optional(),mappedRateLimitErrors:c.z.array((0,c.zStrictObject)({errorStatus:c.z.number(),errorMessage:c.z.string(),errorMessagePath:c.z.string().optional(),retryAfterPath:c.z.string().optional(),retryAfterUnit:c.z.union([c.z.literal(`seconds`),c.z.literal(`milliseconds`),c.z.literal(`date`)]).optional(),retryAfterValue:c.z.number().optional()})).optional()}),oe=(0,c.zStrictObject)({mainMaxConcurrency:c.z.number(),subPools:c.z.array((0,c.zStrictObject)({subPoolKey:c.z.string(),urlPattern:c.z.string(),maxConcurrency:c.z.number()})).optional()}),se=(0,c.zStrictObject)({StackOne:c.z.string(),info:(0,c.zStrictObject)({title:c.z.string(),version:c.z.string(),key:c.z.string(),assets:(0,c.zStrictObject)({icon:c.z.string()}),description:c.z.string()}),context:c.z.string().optional(),baseUrl:c.z.string(),authentication:c.z.record(c.z.string(),(0,c.zStrictObject)({type:c.z.string(),label:c.z.string(),authorization:f.AUTHENTICATION_SCHEMA,environments:(0,c.zStrictObject)({key:c.z.string(),name:c.z.string()}).array(),support:(0,c.zStrictObject)({link:c.z.string(),description:c.z.string().optional()}),configFields:re.array().optional(),setupFields:re.array().optional(),refreshAuthentication:ie.optional(),testOperations:(0,c.zStrictObject)({operation:c.z.string().or(P),condition:c.z.string().optional(),required:c.z.boolean().default(!0)}).array().optional()})).array().optional(),operations:P.array().optional(),rateLimit:ae.optional(),concurrency:oe.optional()}).strict();function F(e){try{let t=(0,m.parse)(e),n=Ce(se,t),r={title:n.info.title,version:n.info.version,key:n.info.key,assets:n.info.assets,description:n.info.description,context:n.context,rateLimit:n.rateLimit,concurrency:n.concurrency},i=ue(n),a={baseUrl:n.baseUrl,authentication:I(i)},o=ge(n,a);return r.operations=o,ce(n.info.key,i,o,a),r.authentication=i,(0,c.notMissing)(o)&&(r.categories=le(Object.values(o))),r}catch(e){if(e instanceof T)throw e;let t=e.message,n=t.match(/at line (\d+)/),r=n?parseInt(n[1],10):1;throw new E(r,t)}}const I=e=>{let t={};for(let[n,r]of Object.entries(e))if(r&&typeof r==`object`){let{setupFields:e,configFields:i,support:a,refreshAuthentication:o,testOperations:s,...c}=r;t[n]=I(c)}else t[n]=r;return t},ce=(e,t,n,r)=>{if(!(!t||!n))for(let i of Object.values(t))for(let t of Object.values(i)){let i=t.testOperations;t.testOperations=i?.map(t=>{if((0,c.notMissing)(t.operation))if(typeof t.operation==`string`){let r=w(e,t.operation),i=Object.values(n).find(e=>e.id===r);if(i)return{...t,operation:i}}else{let n=w(e,t.operation.operationId),i=L(n,t.operation,r);return{...t,operation:i}}return t})}},le=e=>{let t=e.reduce((e,t)=>{for(let n of t.categories)e.add(n);return e},new Set);return Array.from(t)},ue=e=>{let t={};for(let n of e.authentication??[]){let[r]=Object.keys(n),i=n[r].environments.reduce((t,i)=>{let{key:a,name:o}=i,{environments:s,refreshAuthentication:l,testOperations:u,...d}=n[r],f=(0,c.notMissing)(l)?{schedule:l.schedule,operation:L(w(e.info.key,l.operation.operationId),l.operation)}:void 0;return t[a]={...d,refreshAuthentication:f,envKey:a,envName:o,testOperations:u},t},{});t[r]=i}return t},de=e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0,fe=e=>e.operationType===`list`?`GET /${e.schema}`:`GET /${e.schema}/:id`,pe=e=>{if(e.operationType!==`refresh_token`)return e.entrypointHttpMethod??`get`},me=e=>{if(!(e.operationType===`refresh_token`||(0,c.isMissing)(e.schema)))return e.operationType===`list`?`/${e.schema}`:`/${e.schema}/:id`},he=e=>{let t={success:j(e.operationType),errors:te()},n=e.responses?.reduce((e,t)=>{let n=(0,p.isSuccessStatusCode)(t.statusCode);return n?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e},t);return n??t},ge=(e,t)=>{let n=e.operations?.reduce((n,r)=>{let i=de(r),a=fe(r),o=i??a,s=w(e.info.key,r.operationId);return n[s]=L(s,r,t,o),n},{});return n},L=(e,t,n,r)=>{let i=me(t),a=he(t),o=ye(t),s=t.inputs||[];o.enabled&&(s?.push({type:`string`,name:`page_size`,in:`query`,required:!1,description:`Number of items to return per page`,array:!1}),s?.push({type:`string`,name:`next`,in:`query`,required:!1,description:`Token for the next page of results`,array:!1}));let c=pe(t);return{id:e,categories:t.categories,label:t.label,description:t.description,operationType:t.operationType,schemaType:t.schemaType??`native`,entrypointUrl:t.entrypointUrl??i,entrypointHttpMethod:c,endpoint:r,tags:t.tags,context:t.context,responses:a,cursor:o,compositeIdentifiers:be(t),scheduledJobs:xe(t),inputs:s,steps:t.steps.reduce((e,r)=>{let{customErrors:i,...a}=r.stepFunction.parameters??{},o={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{...Se({stepFunctionName:r.stepFunction.functionName,baseRequestParams:n,customErrors:i}),...r.stepFunction.functionName===`map_fields`||r.stepFunction.functionName===`typecast`?{fields:a.fields??t.fieldConfigs}:{},...a}}};return _e(t.operationId,o),e[r.stepId]=o,e},{}),result:t.result}},_e=(e,t)=>{let n=t.stepFunction.version??`1`,r=f.StepFunctionsRegistry[t.stepFunction.functionName]?.[`v${n}`];if(!r)throw new O(e,t.id,t.stepFunction.functionName,n);let i=r.inputSchema;i&&we(i,t.stepFunction.params,e,t.id,t.stepFunction.functionName,n)},R=(e,t)=>{if(!e.inputs)return{};let n=ve(e.inputs),r=c.z.object(n).parse(t);return{...r.headers??{},...r.query??{},...r.path??{},...r.body??{}}},ve=e=>{let t=e.reduce((e,t)=>(e[t.in]||(e[t.in]=[]),e[t.in].push(t),e),{}),n={};for(let[e,r]of Object.entries(t)){let t={};for(let e of r){let n=z(e);e.description&&(n=n.describe(e.description)),e.required||(n=n.optional()),t[e.name]=n}Object.keys(t).length>0&&(n[e]=c.z.object(t))}return n},z=e=>{let t;switch(e.type){case`string`:case`datetime_string`:t=c.z.string();break;case`number`:t=c.z.number();break;case`boolean`:t=c.z.boolean();break;case`object`:if(e.properties&&e.properties.length>0){let n={};for(let t of e.properties){let e=z(t);t.description&&(e=e.describe(t.description)),t.required||(e=e.optional()),n[t.name]=e}t=c.z.object(n)}else t=c.z.record(c.z.string(),c.z.unknown());break;default:t=c.z.unknown()}return e.array&&(t=c.z.array(t)),t},ye=e=>{let t=e.operationType===`list`,n=e.cursor??{enabled:t,pageSize:A};return{enabled:n.enabled&&t,pageSize:n.pageSize}},be=e=>{if(e.operationType===`refresh_token`)return{enabled:!1};if((0,c.isMissing)(e.compositeIdentifiers)){let t=e.fieldConfigs?.find(e=>e.targetFieldKey===`id`),n=(0,c.notMissing)(t)?[{targetFieldKey:t.targetFieldKey,remote:`id`,components:[{name:t.targetFieldKey,alias:t.alias}]}]:void 0;return{enabled:!0,version:f.COMPOSITE_ID_LATEST_VERSION,fields:n}}let t=[];for(let n of e.compositeIdentifiers?.fields??[]){let r=n.components.map(t=>{let n=e.fieldConfigs?.find(e=>e.targetFieldKey===t);return{name:t,alias:n?.alias}});t.push({targetFieldKey:n.targetFieldKey,remote:n.remote,components:r})}return{enabled:e.compositeIdentifiers.enabled,version:e.compositeIdentifiers.version,fields:t.length>0?t:void 0}},xe=e=>{if(!(0,c.isMissing)(e.scheduledJobs))return e.scheduledJobs},Se=({stepFunctionName:e,baseRequestParams:t,customErrors:n={}})=>{if(e===`request`||e===`paginated_request`){let e=[{receivedStatus:500,targetStatus:502}],r=n&&Array.isArray(n)?n:[],i=[...r,...e];return{...t,customErrors:i}}else return{}},Ce=(e,t)=>{let n=e.safeParse(t);if(n.success)return n.data;{let e=n.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new D(e,`Invalid connector schema`)}},we=(e,t,n,r,i,a)=>{let o=e.safeParse(t);if(o.success)return o.data;{let e=o.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new k(n,r,i,a,e)}},B=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return;let r=e.authentication?.[t]?.[n]?.refreshAuthentication?.operation;if((0,c.notMissing)(r))return{operation:r,params:{}}},Te=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return!1;let r=B(e,t,n);return(0,c.notMissing)(r)},Ee=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenExpiresIn},De=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenRefreshExpiresIn},Oe=e=>{try{return F(e),{success:!0}}catch(t){if(t instanceof D){let n=t.issues,r=[];return n.forEach(t=>{let n=t?.keys?.[0],i=(0,c.isMissing)(n)?t.path:[...t.path,n],a=ke(i,e);r.push({line:a,message:t.message,field:i.join(`.`)})}),{success:!1,errors:r}}else if(t instanceof E)return{success:!1,errors:[{line:t.line,message:`The YAML connector file is not valid. Please check the syntax and structure.`,field:void 0}]};else if(t instanceof O){let n=V(t.operationId,t.stepId,t.functionName,!1,e);return{success:!1,errors:[{line:n,message:t.message,field:void 0}]}}else if(t instanceof k){let n=t.issues,r=[];return n.forEach(n=>{let i=n?.keys?.[0],a=(0,c.isMissing)(i)?n.path:[...n.path,i],o=V(t.operationId,t.stepId,t.functionName,!0,e);r.push({line:o,message:n.message,field:a.join(`.`)})}),{success:!1,errors:r}}}return{success:!1,errors:[{line:1,message:`An unknown error occurred while parsing the connector.`,field:void 0}]}},ke=(e,t)=>{let n=t.split(`
4
+ `).filter(e=>e.trim()!==``)}catch(t){throw Error(`Failed to load partial file '${e}': ${t.message}`)}},x=(e,t,n)=>{let r=n.toUpperCase();if(!e.operations)return;let i=Object.values(e.operations).filter(e=>(0,c.notMissing)(e.endpoint)).map(e=>({operationId:e.id,endpoint:e.endpoint})),a=C(t,r,i);if(a)return{operation:e.operations?.[a.operationId],params:a.params}},S=e=>{let t=e.startsWith(`/`)?e.slice(1):e,n=t.endsWith(`/`)?t.slice(0,-1):t;return n},C=(e,t,n)=>{let r=S(e);for(let e of n)if(e.endpoint?.startsWith(t)){let n=e.endpoint.replace(`${t} `,``).trim(),i=(0,d.match)(S(n)),a=i(S(r));if(a!==!1)return{operationId:e.operationId,path:e.endpoint,params:a.params}}},w=(e,t)=>t?.startsWith(`${e}_`)?t:`${e}_${t}`,ee=(e,t)=>{let n=`${e.key}_`,r=t.startsWith(n)?t:`${n}${t}`;return e.operations?.[r]};var T=class e extends Error{errorType;constructor(t,n){super(n),this.name=`InternalConnectSDKError`,this.errorType=t,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},E=class extends T{line;constructor(e,t){super(`INVALID_YAML_FILE_ERROR`,t),this.name=`InvalidYamlFileError`,this.line=e??1}},D=class extends T{issues;constructor(e,t){super(`SCHEMA_VALIDATION_ERROR`,t),this.name=`SchemaValidationError`,this.issues=e}},O=class extends T{operationId;stepId;functionName;functionVersion;constructor(e,t,n,r=`1`){let i=`Invalid Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the function name and version are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION`,i),this.name=`InvalidStepFunctionError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r}},k=class extends T{operationId;stepId;functionName;functionVersion;issues;constructor(e,t,n,r=`1`,i){let a=`Invalid parameters for Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the parameters are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION_PARAMS`,a),this.name=`InvalidStepFunctionParamsError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r,this.issues=i,this.message=a}};const A=25,j=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`refresh_token`:return{statusCode:200,description:`The refresh token operation was executed successfully.`};case`unknown`:return{statusCode:200};default:throw Error(`Unknown operation type: ${e}`)}},te=()=>{let e={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.`}};return e},ne={key:c.z.string(),label:c.z.string(),required:c.z.boolean().optional().default(!1),secret:c.z.boolean().optional().default(!1),readOnly:c.z.boolean().optional().default(!1),placeholder:c.z.string().optional(),description:c.z.string().optional(),tooltip:c.z.string().optional()},re=c.z.discriminatedUnion(`type`,[(0,c.zStrictObject)({...ne,type:c.z.enum([`text`,`password`])}),(0,c.zStrictObject)({...ne,type:c.z.literal(`select`),options:(0,c.zStrictObject)({value:c.z.string(),label:c.z.string()}).array()})]),M=(0,c.zStrictObject)({targetFieldKey:c.z.string(),alias:c.z.string().optional(),expression:c.z.string().optional(),values:c.z.unknown().optional(),type:c.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:c.z.boolean().default(!1),custom:c.z.boolean().default(!1),hidden:c.z.boolean().default(!1),enumMapper:(0,c.zStrictObject)({matcher:c.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`,`document_file_format_from_extension`]).or((0,c.zStrictObject)({matchExpression:c.z.string(),value:c.z.string()}).array())}).optional(),properties:c.z.lazy(()=>M).array().optional()}),N=(0,c.zStrictObject)({name:c.z.string(),type:c.z.enum([`string`,`number`,`boolean`,`datetime_string`,`object`]),required:c.z.boolean(),description:c.z.string(),array:c.z.boolean().optional().default(!1),in:c.z.enum([`body`,`query`,`path`,`headers`]),properties:c.z.lazy(()=>N.omit({in:!0})).array().optional()}),P=(0,c.zStrictObject)({operationId:c.z.string(),categories:c.z.string().array(),operationType:c.z.enum([`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`unknown`]),schema:c.z.string().optional(),schemaType:c.z.enum([`native`,`unified`]).optional().default(`native`),entrypointUrl:c.z.string().optional(),entrypointHttpMethod:c.z.string().optional(),label:c.z.string(),description:c.z.string(),tags:c.z.string().array().optional(),context:c.z.string().optional(),responses:(0,c.zStrictObject)({statusCode:c.z.number(),description:c.z.string()}).array().optional(),inputs:N.array().optional(),cursor:(0,c.zStrictObject)({enabled:c.z.boolean(),pageSize:c.z.number()}).optional(),compositeIdentifiers:(0,c.zStrictObject)({enabled:c.z.boolean(),version:c.z.number().optional(),fields:(0,c.zStrictObject)({targetFieldKey:c.z.string(),remote:c.z.string().optional(),components:c.z.string().array()}).array().optional()}).optional(),scheduledJobs:(0,c.zStrictObject)({enabled:c.z.boolean(),type:c.z.enum([`data_sync`]),schedule:c.z.string(),description:c.z.string(),requestParams:(0,c.zStrictObject)({fields:c.z.string().array().optional(),expand:c.z.string().array().optional(),filter:c.z.record(c.z.string(),c.z.string()).optional()}).optional(),syncFilter:(0,c.zStrictObject)({name:c.z.enum([`updated_after`,`created_after`]),initialLoopbackPeriod:c.z.string(),incrementalLoopbackPeriod:c.z.string()}).optional()}).array().optional(),fieldConfigs:M.array().optional(),steps:(0,c.zStrictObject)({stepId:c.z.string(),description:c.z.string(),stepFunction:(0,c.zStrictObject)({functionName:c.z.string(),version:c.z.string().optional(),parameters:c.z.record(c.z.string(),c.z.unknown())}),condition:c.z.string().optional(),ignoreError:c.z.boolean().optional()}).array(),result:c.z.string().or(c.z.record(c.z.string(),c.z.unknown())).optional()}),ie=(0,c.zStrictObject)({schedule:c.z.string().optional(),operation:P.extend({operationType:c.z.literal(`refresh_token`)})}),ae=(0,c.zStrictObject)({mainRatelimit:c.z.number(),subPools:c.z.array((0,c.zStrictObject)({subPoolKey:c.z.string(),urlPattern:c.z.string(),rateLimit:c.z.number()})).optional(),mappedRateLimitErrors:c.z.array((0,c.zStrictObject)({errorStatus:c.z.number(),errorMessage:c.z.string(),errorMessagePath:c.z.string().optional(),retryAfterPath:c.z.string().optional(),retryAfterUnit:c.z.union([c.z.literal(`seconds`),c.z.literal(`milliseconds`),c.z.literal(`date`)]).optional(),retryAfterValue:c.z.number().optional()})).optional()}),oe=(0,c.zStrictObject)({mainMaxConcurrency:c.z.number(),subPools:c.z.array((0,c.zStrictObject)({subPoolKey:c.z.string(),urlPattern:c.z.string(),maxConcurrency:c.z.number()})).optional()}),se=(0,c.zStrictObject)({StackOne:c.z.string(),info:(0,c.zStrictObject)({title:c.z.string(),version:c.z.string(),key:c.z.string(),assets:(0,c.zStrictObject)({icon:c.z.string()}),description:c.z.string()}),context:c.z.string().optional(),baseUrl:c.z.string(),authentication:c.z.record(c.z.string(),(0,c.zStrictObject)({type:c.z.string(),label:c.z.string(),authorization:f.AUTHENTICATION_SCHEMA,environments:(0,c.zStrictObject)({key:c.z.string(),name:c.z.string()}).array(),support:(0,c.zStrictObject)({link:c.z.string(),description:c.z.string().optional()}),configFields:re.array().optional(),setupFields:re.array().optional(),refreshAuthentication:ie.optional(),testOperations:(0,c.zStrictObject)({operation:c.z.string().or(P),condition:c.z.string().optional(),required:c.z.boolean().default(!0)}).array().optional()})).array().optional(),operations:P.array().optional(),rateLimit:ae.optional(),concurrency:oe.optional()}).strict();function F(e){try{let t=(0,m.parse)(e),n=Ce(se,t),r={title:n.info.title,version:n.info.version,key:n.info.key,assets:n.info.assets,description:n.info.description,context:n.context,rateLimit:n.rateLimit,concurrency:n.concurrency},i=ue(n),a={baseUrl:n.baseUrl,authentication:I(i)},o=ge(n,a);return r.operations=o,ce(n.info.key,i,o,a),r.authentication=i,(0,c.notMissing)(o)&&(r.categories=le(Object.values(o))),r}catch(e){if(e instanceof T)throw e;let t=e.message,n=t.match(/at line (\d+)/),r=n?parseInt(n[1],10):1;throw new E(r,t)}}const I=e=>{let t={};for(let[n,r]of Object.entries(e))if(r&&typeof r==`object`){let{setupFields:e,configFields:i,support:a,refreshAuthentication:o,testOperations:s,...c}=r;t[n]=I(c)}else t[n]=r;return t},ce=(e,t,n,r)=>{if(!(!t||!n))for(let i of Object.values(t))for(let t of Object.values(i)){let i=t.testOperations;t.testOperations=i?.map(t=>{if((0,c.notMissing)(t.operation))if(typeof t.operation==`string`){let r=w(e,t.operation),i=Object.values(n).find(e=>e.id===r);if(i)return{...t,operation:i}}else{let n=w(e,t.operation.operationId),i=L(n,t.operation,r);return{...t,operation:i}}return t})}},le=e=>{let t=e.reduce((e,t)=>{for(let n of t.categories)e.add(n);return e},new Set);return Array.from(t)},ue=e=>{let t={};for(let n of e.authentication??[]){let[r]=Object.keys(n),i=n[r].environments.reduce((t,i)=>{let{key:a,name:o}=i,{environments:s,refreshAuthentication:l,testOperations:u,...d}=n[r],f=(0,c.notMissing)(l)?{schedule:l.schedule,operation:L(w(e.info.key,l.operation.operationId),l.operation)}:void 0;return t[a]={...d,refreshAuthentication:f,envKey:a,envName:o,testOperations:u},t},{});t[r]=i}return t},de=e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0,fe=e=>e.operationType===`list`?`GET /${e.schema}`:`GET /${e.schema}/:id`,pe=e=>{if(e.operationType!==`refresh_token`)return e.entrypointHttpMethod??`get`},me=e=>{if(!(e.operationType===`refresh_token`||(0,c.isMissing)(e.schema)))return e.operationType===`list`?`/${e.schema}`:`/${e.schema}/:id`},he=e=>{let t={success:j(e.operationType),errors:te()},n=e.responses?.reduce((e,t)=>{let n=(0,p.isSuccessStatusCode)(t.statusCode);return n?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e},t);return n??t},ge=(e,t)=>{let n=e.operations?.reduce((n,r)=>{let i=de(r),a=fe(r),o=i??a,s=w(e.info.key,r.operationId);return n[s]=L(s,r,t,o),n},{});return n},L=(e,t,n,r)=>{let i=me(t),a=he(t),o=ye(t),s=t.inputs||[];o.enabled&&(s?.push({type:`string`,name:`page_size`,in:`query`,required:!1,description:`Number of items to return per page`,array:!1}),s?.push({type:`string`,name:`next`,in:`query`,required:!1,description:`Token for the next page of results`,array:!1}));let c=pe(t);return{id:e,categories:t.categories,label:t.label,description:t.description,operationType:t.operationType,schemaType:t.schemaType??`native`,entrypointUrl:t.entrypointUrl??i,entrypointHttpMethod:c,endpoint:r,tags:t.tags,context:t.context,responses:a,cursor:o,compositeIdentifiers:be(t),scheduledJobs:xe(t),inputs:s,steps:t.steps.reduce((e,r)=>{let{customErrors:i,...a}=r.stepFunction.parameters??{},o={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{...Se({stepFunctionName:r.stepFunction.functionName,baseRequestParams:n,customErrors:i}),...r.stepFunction.functionName===`map_fields`||r.stepFunction.functionName===`typecast`?{fields:a.fields??t.fieldConfigs}:{},...a}}};return _e(t.operationId,o),e[r.stepId]=o,e},{}),result:t.result}},_e=(e,t)=>{let n=t.stepFunction.version??`1`,r=f.StepFunctionsRegistry[t.stepFunction.functionName]?.[`v${n}`];if(!r)throw new O(e,t.id,t.stepFunction.functionName,n);let i=r.inputSchema;i&&we(i,t.stepFunction.params,e,t.id,t.stepFunction.functionName,n)},R=(e,t)=>{if(!e.inputs)return{};let n=ve(e.inputs),r=c.z.object(n).parse(t);return{...r.headers??{},...r.query??{},...r.path??{},...r.body??{}}},ve=e=>{let t=e.reduce((e,t)=>(e[t.in]||(e[t.in]=[]),e[t.in].push(t),e),{}),n={};for(let[e,r]of Object.entries(t)){let t={};for(let e of r){let n=z(e);e.description&&(n=n.describe(e.description)),e.required||(n=n.optional()),t[e.name]=n}Object.keys(t).length>0&&(n[e]=c.z.object(t))}return n},z=e=>{let t;switch(e.type){case`string`:case`datetime_string`:t=c.z.string();break;case`number`:t=c.z.number();break;case`boolean`:t=c.z.boolean();break;case`object`:if(e.properties&&e.properties.length>0){let n={};for(let t of e.properties){let e=z(t);t.description&&(e=e.describe(t.description)),t.required||(e=e.optional()),n[t.name]=e}t=c.z.object(n)}else t=c.z.record(c.z.string(),c.z.unknown());break;default:t=c.z.unknown()}return e.array&&(t=c.z.array(t)),t},ye=e=>{let t=e.operationType===`list`,n=e.cursor??{enabled:t,pageSize:A};return{enabled:n.enabled&&t,pageSize:n.pageSize}},be=e=>{if(e.operationType===`refresh_token`)return{enabled:!1};if((0,c.isMissing)(e.compositeIdentifiers)){let t=e.fieldConfigs?.find(e=>e.targetFieldKey===`id`),n=(0,c.notMissing)(t)?[{targetFieldKey:t.targetFieldKey,remote:`id`,components:[{name:t.targetFieldKey,alias:t.alias}]}]:void 0;return{enabled:!0,version:f.COMPOSITE_ID_LATEST_VERSION,fields:n}}let t=[];for(let n of e.compositeIdentifiers?.fields??[]){let r=n.components.map(t=>{let n=e.fieldConfigs?.find(e=>e.targetFieldKey===t);return{name:t,alias:n?.alias}});t.push({targetFieldKey:n.targetFieldKey,remote:n.remote,components:r})}return{enabled:e.compositeIdentifiers.enabled,version:e.compositeIdentifiers.version,fields:t.length>0?t:void 0}},xe=e=>{if(!(0,c.isMissing)(e.scheduledJobs))return e.scheduledJobs},Se=({stepFunctionName:e,baseRequestParams:t,customErrors:n={}})=>{if(e===`request`||e===`paginated_request`){let e=[{receivedStatus:500,targetStatus:502}],r=n&&Array.isArray(n)?n:[],i=[...r,...e];return{...t,customErrors:i}}else return{}},Ce=(e,t)=>{let n=e.safeParse(t);if(n.success)return n.data;{let e=n.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new D(e,`Invalid connector schema`)}},we=(e,t,n,r,i,a)=>{let o=e.safeParse(t);if(o.success)return o.data;{let e=o.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new k(n,r,i,a,e)}},B=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return;let r=e.authentication?.[t]?.[n]?.refreshAuthentication?.operation;if((0,c.notMissing)(r))return{operation:r,params:{}}},Te=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return!1;let r=B(e,t,n);return(0,c.notMissing)(r)},Ee=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenExpiresIn},De=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenRefreshExpiresIn},Oe=e=>{try{let t=F(e);return{success:!0,connector:t}}catch(t){if(t instanceof D){let n=t.issues,r=[];return n.forEach(t=>{let n=t?.keys?.[0],i=(0,c.isMissing)(n)?t.path:[...t.path,n],a=ke(i,e);r.push({line:a,message:t.message,field:i.join(`.`)})}),{success:!1,errors:r}}else if(t instanceof E)return{success:!1,errors:[{line:t.line,message:`The YAML connector file is not valid. Please check the syntax and structure.`,field:void 0}]};else if(t instanceof O){let n=V(t.operationId,t.stepId,t.functionName,!1,e);return{success:!1,errors:[{line:n,message:t.message,field:void 0}]}}else if(t instanceof k){let n=t.issues,r=[];return n.forEach(n=>{let i=n?.keys?.[0],a=(0,c.isMissing)(i)?n.path:[...n.path,i],o=V(t.operationId,t.stepId,t.functionName,!0,e);r.push({line:o,message:n.message,field:a.join(`.`)})}),{success:!1,errors:r}}}return{success:!1,errors:[{line:1,message:`An unknown error occurred while parsing the connector.`,field:void 0}]}},ke=(e,t)=>{let n=t.split(`
5
5
  `),r=0,i=-1,a=0;for(let t=0;t<n.length;t++){let o=n[t],s=o.match(/^(\s*)/)?.[1]?.length||0,l=o.replace(`- `,``).trim();if(l.startsWith(`#`)||l===``||s<=i)continue;let u=(0,c.notMissing)(e[r])?`${String(e[r])}`:``;if((0,c.isMissing)(u))return a+1;if(isNaN(Number(u))){if(l.startsWith(`${u}:`)){if(r===e.length-1)return t+1;i=s,a=t,r++}}else{let e=parseInt(u,10),i=-1;for(let o=t;o<n.length;o++){let s=n[o],c=s.trim();if(c.startsWith(`-`)&&i++,i===e){r++,a=t,t--;break}else t++}}}return a+1},V=(e,t,n,r,i)=>{let a=i.split(`
6
6
  `),o=1,s=null,l=null;for(let i=0;i<a.length;i++){let u=a[i],d=u.trim();if((0,c.isMissing)(s)&&d===`- operationId: ${e}`){s=e,o=i+1;continue}if((0,c.notMissing)(s)&&(0,c.isMissing)(l)&&d===`- stepId: ${t}`){l=t,o=i+1;continue}if((0,c.notMissing)(s)&&(0,c.notMissing)(l)&&!r&&d.startsWith(`functionName: ${n}`)||(0,c.notMissing)(s)&&(0,c.notMissing)(l)&&r&&d===`parameters:`)return o=i+1,o}return o};var H=class e extends Error{errorType;context;constructor(t,n,r){super(r),this.name=`ConnectSDKError`,this.errorType=t,this.context=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},Ae=class extends H{constructor(e,t){super(`CONNECTOR_PARSE_ERROR`,e,t),this.name=`ConnectorParseError`}},U=class extends H{constructor(e,t){super(`MISSING_OPERATION_ERROR`,e,t),this.name=`MissingOperationError`}},je=class extends H{constructor(e,t){super(`INVALID_OPERATION_INPUTS_ERROR`,e,t),this.name=`InvalidOperationInputsError`}},Me=class extends H{constructor(e,t){super(`INVALID_CURSOR_ERROR`,e,t),this.name=`InvalidCursorError`}};const W=(e,t)=>{let n=Object.keys(e.authentication??{}).map(t=>({type:`custom`,label:e.authentication?.[t].production?.label||`Custom`,key:t})),r=Object.values(e?.operations??{}).map(e=>({id:e.id,description:e.description.replace(/\b\w/g,e=>e.toUpperCase()),label:e.label.replace(/\b\w/g,e=>e.toUpperCase()),schema_type:e.schemaType,tags:e.tags,authentication:n,operation_details:t?.includes(`operation_details`)?e:void 0}));return{version:e.version,name:e.title,key:e.key,icon:e.assets?.icon,description:e.description,authentication:n,actions:r}},Ne=(e,t)=>e.map(e=>W(e,t)),Pe=`stackone://internal//`,G=`${Pe}refresh_token`,Fe=async({block:e,stepFunctionName:t,params:n,buildStepFunction:r=f.StepFunctionsFactory.build})=>{let i=r({functionName:t}).fn,a=await i({block:e,params:n}),o=t===f.StepFunctionName.MAP_FIELDS?{[f.StepFunctionName.MAP_FIELDS.toString()]:{output:{data:a.block.result},errors:a.errors,successful:a.successful}}:{};return{...a.block,steps:{...a?.block?.steps??{},...o}}},K=({category:e,connectorKey:t,connectorVersion:n,authConfigKey:r,environment:i=`production`,operation:a,accountSecureId:o,projectSecureId:s})=>({projectSecureId:s,accountSecureId:o,connectorKey:t,connectorVersion:n,category:e,service:``,resource:``,schema:a?.schema?.key,operationType:a?.operationType??`unknown`,authenticationType:r,environment:i}),Ie=(e,t,n)=>e.authentication?.[t]?.[n]?.testOperations,Le=e=>{let t=e.operation?.compositeIdentifiers,n={...e.inputs??{}};if(!t?.enabled||(0,c.isMissing)(n))return e;let r=t.fields?.reduce((e,t)=>(t.components.forEach(t=>{t.alias&&(e[t.name]=t.alias)}),e),{}),i={version:t.version??f.COMPOSITE_ID_LATEST_VERSION,aliases:r};return q(n,i,e.logger),{...e,inputs:n}},q=(e,t,n)=>{for(let r in e){let i=e[r];if(typeof i==`string`||Array.isArray(i)&&i.every(e=>typeof e==`string`))Ue(i,r,e,t,n);else if(Array.isArray(i))for(let e of i)q(e,t,n);else typeof i==`object`&&i&&q(i,t,n)}},Re=(e,t,n,r)=>{let i=[],a=[];for(let o of e)try{let e=(0,f.decodeCompositeId)(o,n);i.push(e)}catch(e){r?.debug({message:`Received ${t} with invalid composite ID, assuming it is not a composite ID`,category:`processCompositeId`,context:{key:t,inputElement:o,compositeIdentifierConfig:n,error:e}}),a.push(o)}return{compositeIdComponents:i,nonCompositeIds:a}},ze=(e,t,n,r)=>{let i=n.filter(e=>Object.keys(e).length>1);i.length>0&&(e.decoded_ids={...e.decoded_ids??{},[t]:r?i:i[0]})},Be=e=>{let t=Object.values(e);return t.length===1&&(typeof t[0]==`string`||typeof t[0]==`number`)},Ve=(e,t,n,r,i)=>{n.every(Be)&&(i?e[t]=[...n.map(e=>Object.values(e)[0]),...r]:n.length>0&&(e[t]=Object.values(n[0])[0]))},He=(e,t,n)=>{e instanceof f.CoreError&&e.type===`COMPOSITE_ID_MISSING_HEADER_ERROR`?n?.debug({message:`Received ${t} with no composite ID header, assuming it is not a composite ID`}):n?.warning({message:`Error processing composite ID for ${t}, ignoring it`,error:e})},Ue=(e,t,n,r,i)=>{try{let a=Array.isArray(e),o=a?e:[e];if(o.length===0)return;let{compositeIdComponents:s,nonCompositeIds:c}=Re(o,t,r,i);ze(n,t,s,a),Ve(n,t,s,c,a)}catch(e){He(e,t,i)}},J=`remote_`,We=e=>{let t=e.operation?.compositeIdentifiers;if(!t?.enabled)return e;let n=`data`,r=e.outputs?.[n];if((0,c.isMissing)(r))return e;let i=Array.isArray(r)?r.map(e=>Ge(e,t)):Ge(r,t);return{...e,outputs:{...e.outputs??{},[n]:i}}},Ge=(e,t)=>{let n=Ke(e,t),r=Y(n);return{...e,...(0,c.isObject)(r)?r:{}}},Ke=(e,t)=>{let n=t.version??f.COMPOSITE_ID_LATEST_VERSION,r={};return t.fields?.forEach(t=>{let i={},a=[];t.components.forEach(t=>{t.alias&&(i[t.name]=t.alias),a.push({key:t.name,value:e[t.name]})});let o=a.length===1?a[0]:{identifiers:a},s={version:n,aliases:Object.keys(i).length>0?i:void 0},c=(0,f.encodeCompositeId)(o,s);r[t.targetFieldKey]=c,t.remote&&(r[`${J}${t.remote}`]=e[t.remote])}),{...e,...r}},qe=e=>e===`id`||/.+_id(s)?$/.test(e),Je=e=>Array.isArray(e)&&e.every(e=>(0,c.isString)(e)&&e.length>0),Ye=(e,t)=>(0,f.isCompositeId)(e)||t.startsWith(J),Xe=(e,t)=>{try{return(0,f.encodeCompositeId)({key:e,value:t},{version:f.COMPOSITE_ID_LATEST_VERSION})}catch{return t}},Ze=(e,t,n)=>{let r=t.map(t=>(0,c.isString)(t)&&t.length>0&&!(0,f.isCompositeId)(t)?Xe(e,t):t);n[e]=r,n[`${J}${e}`]=t},Qe=(e,t,n)=>{if(Ye(t,e))return;let r=(0,f.encodeCompositeId)({key:e,value:t},{version:f.COMPOSITE_ID_LATEST_VERSION});n[e]=r,n[`remote_${e}`]=t},$e=(e,t,n)=>{Je(t)?Ze(e,t,n):(0,c.isString)(t)&&t.length>0&&Qe(e,t,n)},Y=e=>{if(Array.isArray(e))return e.map(e=>Y(e));if(!(0,c.isObject)(e))return e;let t={...e};for(let[n,r]of Object.entries(e))((0,c.isObject)(r)||Array.isArray(r)&&r.length>0&&(0,c.isObject)(r[0]))&&(t[n]=Y(r)),qe(n)&&$e(n,r,t);return t},et=(e,t)=>{let n=Number(e.inputs?.page_size),r=(0,c.notMissing)(e.inputs?.page_size)&&(0,c.isNumber)(n)&&!Number.isNaN(n)?n:e.operation?.cursor?.pageSize??t;return r},tt=(e,t,n,r)=>{let i=(0,c.isMissing)(e)?void 0:e.data,a=Object.keys(n).length+1,o=(0,f.isCursorEmpty)({cursor:r,ignoreStepIndex:a});if(!(0,c.isObject)(e)||(0,c.isMissing)(i)||(i?.length??0)<=t)return{result:e,next:(0,c.notMissing)(r)&&!o?(0,f.minifyCursor)(r):null};let s=r?.remote?.[a]?.pageNumber??1,l=(s-1)*t,u=l+t,d=i.slice(l,u),p=i.length>u||!o,m=(0,f.updateCursor)({cursor:r,stepIndex:a,pageNumber:s+1});return{result:{...e,data:d},next:p?(0,f.minifyCursor)(m):null}},X=async({block:e,buildStepFunction:t=f.StepFunctionsFactory.build,virtualPaginateResultFn:n=tt,encodeResultCompositeIds:r=We,decodeInputCompositeIds:i=Le})=>{let a=i(e),o=await st({block:a,buildStepFunction:t,virtualPaginateResultFn:n});return r(o)},nt=(e,t)=>e.condition?!(0,h.safeEvaluate)(e.condition,t):!1,rt=(e,t,n)=>{let r=e.stepFunction,i=f.StepFunctionsRegistry[e.stepFunction.functionName]?.[`v${e.stepFunction.version??1}`],a=(0,c.notMissing)(i?.inputSchema?.shape)?`cursor`in i?.inputSchema?.shape:!1;return t.operation?.cursor.enabled&&a?{...r.params??{},cursor:{token:t.nextCursor?.remote?.[n]?.providerPageCursor,position:t.nextCursor?.remote?.[n]?.position}}:r.params??{}},it=(e,t,n,r,i)=>{let a=Z({block:e,stepId:t,successful:!1,functionOutput:n}),o=r.ignoreError??!1;return o||(i.hasFatalError=!0,i.errorStatusCode??=n.output?.statusCode??500),a},at=async(e,t,n,r,i,a)=>{let o=n[e],s=o.stepFunction,c=a.buildStepFunction({functionName:s.functionName,version:s.version,validateSchemas:!0}).fn;if(nt(o,r))return Z({block:r,stepId:e,successful:!0,skipped:!0,message:`Step skipped due to condition not met.`});if(i.hasFatalError)return Z({block:r,stepId:e,successful:!1,skipped:!0,message:`Step skipped due to previous error.`});let l=rt(o,r,t),u=await c({block:r,params:l});if(u.successful===!1)return it(r,e,u,o,i);let d=r.operation?.cursor.enabled?(0,f.updateCursor)({cursor:r.nextCursor,stepIndex:t,providerPageCursor:u.output?.next,position:u.output?.position}):void 0;return Z({block:{...u.block,nextCursor:d},stepId:e,functionOutput:u})},ot=(e,t,n,r,i)=>{let a=!n.hasFatalError,o=a?e.operation?.responses.success.statusCode??200:n.errorStatusCode??500,s=(0,c.notMissing)(i)&&(0,c.isObject)(i.result)?{next:i.next,...i.result}:r;return{...t,outputs:s,response:{successful:a,statusCode:o,message:a?void 0:e.operation?.responses?.errors?.[o]?.description??p.HttpErrorMessages?.[o]??`Error while processing the request`}}},st=async({block:e,buildStepFunction:t=f.StepFunctionsFactory.build,virtualPaginateResultFn:n=tt})=>{let r=e.operation?.steps||{},i={...e},a=Object.keys(r),o=et(e,A),s={hasFatalError:!1,errorStatusCode:null},c={block:e,buildStepFunction:t,virtualPaginateResultFn:n};for(let[e,t]of a.entries())i=await at(t,e,r,i,s,c);let l=e.operation?.result?ct(e.operation.result,i):void 0,u=e.operation?.cursor.enabled?n(l,o,r,i.nextCursor):void 0;return ot(e,i,s,l,u)},ct=(e,t)=>(0,c.isObject)(e)?(0,h.safeEvaluateRecord)(e,t):(0,h.safeEvaluate)(e,t),Z=({block:e,stepId:t,successful:n,functionOutput:r,skipped:i,message:a})=>({...e,steps:{...e.steps,[t]:{successful:n??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:i,message:a}}}),Q=async e=>{let{pathParams:t={},queryParams:n={},body:r={},headers:i={},parseConnector:a=F,parseOperationInputsFn:o=R,createBlockContextFn:s=K,createBlockFn:l=g,runStepOperationFn:u=X,getOperationFromUrlFn:d=x,getOperationForRefreshAuthenticationFn:f=B,getTestOperationsFn:p=Ie,mode:m,account:_,connector:v,getHttpClient:y,logger:b,category:S,...C}=e,w=_.authConfigKey,T=_.environment??`production`,E=_.secureId,D=_.projectSecureId,O=_.credentials,k=s({category:S??`action`,connectorKey:_.providerKey,connectorVersion:_.providerVersion,authConfigKey:w,environment:T,accountSecureId:E,projectSecureId:D}),A;try{A=(0,c.isString)(v)?a(v):v}catch{throw new Ae(k,`Error while parsing connector`)}let j={connector:A,context:k,credentials:O,logger:b,getHttpClient:y};if(m===`operation_id`){let{operationId:e}=C,a=ee(A,e);if((0,c.isMissing)(a))throw new U(k,`No matching operation found`);return await $({operation:a,blockContext:k,queryParams:n,pathParams:t,body:r,headers:i,parseOperationInputsFn:o,createBlockFn:l,createBlockParams:j,runStepOperationFn:u})}else if(m===`test_operations`){let e=p(A,w,T);if((0,c.isMissing)(e)||e.length===0)return lt(l,j);k.operationType=`test`;for(let t of e){let e=await l({...j,inputs:void 0,operation:t.operation,nextCursor:void 0}),n=(0,c.notMissing)(t.condition)?(0,h.evaluate)(t.condition,e):!0;if(!n)continue;let r=await u({block:e});if(((0,c.isMissing)(r?.response?.successful)||!r.response.successful)&&t.required)return b?.error({code:`TestOperationFailed`,message:`Test operation "${t.operation.id}" failed with error: ${r?.response?.message}`}),ut(l,j)}return lt(l,j)}else if(m===`refresh_authentication`){let e=f(A,w,T);if((0,c.isMissing)(e))throw new U(k,`No matching operation found`);return await $({operation:e.operation,blockContext:k,queryParams:n,pathParams:e.params,body:r,headers:i,parseOperationInputsFn:o,createBlockFn:l,createBlockParams:j,runStepOperationFn:u})}else if(m===`path`){let{path:e,method:t}=C,a=d(A,e,t);if((0,c.isMissing)(a))throw new U(k,`No matching operation found`);return await $({operation:a.operation,blockContext:k,queryParams:n,pathParams:a.params,body:r,headers:i,parseOperationInputsFn:o,createBlockFn:l,createBlockParams:j,runStepOperationFn:u})}else return ut(l,j)},$=async e=>{let{operation:t,blockContext:n,queryParams:r,pathParams:i,body:a,headers:o,parseOperationInputsFn:s,createBlockFn:c,createBlockParams:l,runStepOperationFn:u}=e;n.operationType=t.operationType,n.schema=t.schema?.key;let d=dt(r,n),f;try{f=s(t,{path:i,query:r,body:a,headers:o})}catch{throw new je(n,`Error while parsing operation inputs`)}let p=await c({...l,inputs:f,operation:t,nextCursor:d});return await u({block:p})},lt=async(e,t)=>{let n=await e({...t,inputs:void 0,operation:void 0,nextCursor:void 0});return{...n,response:{successful:!0,statusCode:200}}},ut=async(e,t)=>{let n=await e({...t,inputs:void 0,operation:void 0,nextCursor:void 0});return{...n,response:{successful:!1,statusCode:500}}},dt=(e,t)=>{let n=e?.next,r=(0,c.notMissing)(n)&&t.operationType===`list`?(0,f.expandCursor)(n):void 0;if(r===null)throw new Me(t,`Invalid cursor.`);return r},ft=async({operationId:e,account:t,connector:n,pathParams:r={},queryParams:i={},body:a={},headers:o={},logger:s,getHttpClient:c,parseConnector:l=F,parseOperationInputsFn:u=R,createBlockContextFn:d=K,createBlockFn:f=g,runStepOperationFn:p=X})=>Q({mode:`operation_id`,operationId:e,account:t,connector:n,pathParams:r,queryParams:i,body:a,headers:o,logger:s,getHttpClient:c,parseConnector:l,parseOperationInputsFn:u,createBlockContextFn:d,createBlockFn:f,runStepOperationFn:p}),pt=async({account:e,connector:t,category:n,path:r,method:i=`get`,queryParams:a={},body:o,headers:s,logger:c,getHttpClient:l,parseConnector:u=F,getOperationFromUrlFn:d=x,getOperationForRefreshAuthenticationFn:f=B,parseOperationInputsFn:p=R,createBlockContextFn:m=K,createBlockFn:h=g,runStepOperationFn:_=X})=>{let v=mt(r),y=v?await Q({mode:`refresh_authentication`,account:e,connector:t,getOperationForRefreshAuthenticationFn:f,parseConnector:u,logger:c,getHttpClient:l,parseOperationInputsFn:p,createBlockContextFn:m,createBlockFn:h,runStepOperationFn:_}):await Q({mode:`path`,account:e,category:n,connector:t,path:r,method:i,queryParams:a,body:o,headers:s,getOperationFromUrlFn:d,parseConnector:u,logger:c,getHttpClient:l,parseOperationInputsFn:p,createBlockContextFn:m,createBlockFn:h,runStepOperationFn:_});return y},mt=e=>e===G,ht=async({account:e,connector:t,logger:n,getHttpClient:r,parseConnector:i=F,getTestOperationsFn:a=Ie,createBlockContextFn:o=K,createBlockFn:s=g,runStepOperationFn:c=X})=>{let l=await Q({mode:`test_operations`,account:e,connector:t,logger:n,getHttpClient:r,parseConnector:i,getTestOperationsFn:a,createBlockContextFn:o,createBlockFn:s,runStepOperationFn:c});return l?.response?.successful??!1};exports.ConnectSDKError=H,exports.REFRESH_TOKEN_OPERATION_PATH=G,exports.createBlock=g,exports.executeStepFunction=Fe,exports.getActionsMeta=W,exports.getActionsMetaFromConnectors=Ne,exports.getOperationFromUrl=x,exports.getRefreshTokenExpiresIn=De,exports.getTokenExpiresIn=Ee,exports.loadConnector=_,exports.parseOperationInputs=R,exports.parseYamlConnector=F,exports.runAction=Q,exports.runConnectorAction=ft,exports.runConnectorOperation=pt,exports.runStepOperation=X,exports.runTestOperations=ht,exports.supportsRefreshAuthentication=Te,exports.validateYamlConnector=Oe;
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import{isMissing as e,isNumber as t,isObject as n,isString as r,notMissing as i,z as a,zStrictObject as o}from"@stackone/utils";import{readFileSync as s}from"fs";import{dirname as c,join as l,resolve as u}from"path";import{match as d}from"path-to-regexp";import{AUTHENTICATION_SCHEMA as f,COMPOSITE_ID_LATEST_VERSION as p,CoreError as m,StepFunctionName as h,StepFunctionsFactory as g,StepFunctionsRegistry as _,decodeCompositeId as v,encodeCompositeId as y,expandCursor as b,isCompositeId as x,isCursorEmpty as S,minifyCursor as C,updateCursor as w}from"@stackone/core";import{HttpErrorMessages as ee,isSuccessStatusCode as te}from"@stackone/transport";import{parse as T}from"yaml";import{evaluate as ne,safeEvaluate as E,safeEvaluateRecord as D}from"@stackone/expressions";const O=async({connector:t,inputs:n,context:r,operation:i,credentials:a,nextCursor:o,logger:s,getHttpClient:c})=>{if(e(c))throw Error(`getHttpClient function is required`);let l=await c();return{connector:t,inputs:n,fieldConfigs:[],context:r,operation:i,credentials:a,nextCursor:o,httpClient:l,logger:s}},k=e=>{if(!e.endsWith(`.s1.yaml`))throw Error(`File must have .s1.yaml extension`);try{let t=s(e,`utf8`);if(!t.includes(`:`)||!t.includes(`$ref:`))return t;let n=t.split(`
2
2
  `),r=re(n,c(e));return r.join(`
3
3
  `)}catch(e){throw Error(`Failed to process YAML file: ${e.message}`)}},re=(e,t)=>{let n=[];for(let r of e)if(ie(r)){let e=r.match(/^(\s*)/)?.[1]?.length||0,i=r.split(`:`)[1]?.trim(),a=ae(i,t),o=a.map(t=>` `.repeat(e)+t);n.push(...o)}else n.push(r);return n},ie=e=>e.includes(`$ref:`),ae=(e,t)=>{let n=u(l(t,`${e.replaceAll(`'`,``)}.s1.partial.yaml`));try{let e=s(n,`utf8`);return e.split(`
4
- `).filter(e=>e.trim()!==``)}catch(t){throw Error(`Failed to load partial file '${e}': ${t.message}`)}},A=(e,t,n)=>{let r=n.toUpperCase();if(!e.operations)return;let a=Object.values(e.operations).filter(e=>i(e.endpoint)).map(e=>({operationId:e.id,endpoint:e.endpoint})),o=oe(t,r,a);if(o)return{operation:e.operations?.[o.operationId],params:o.params}},j=e=>{let t=e.startsWith(`/`)?e.slice(1):e,n=t.endsWith(`/`)?t.slice(0,-1):t;return n},oe=(e,t,n)=>{let r=j(e);for(let e of n)if(e.endpoint?.startsWith(t)){let n=e.endpoint.replace(`${t} `,``).trim(),i=d(j(n)),a=i(j(r));if(a!==!1)return{operationId:e.operationId,path:e.endpoint,params:a.params}}},M=(e,t)=>t?.startsWith(`${e}_`)?t:`${e}_${t}`,se=(e,t)=>{let n=`${e.key}_`,r=t.startsWith(n)?t:`${n}${t}`;return e.operations?.[r]};var N=class e extends Error{errorType;constructor(t,n){super(n),this.name=`InternalConnectSDKError`,this.errorType=t,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},P=class extends N{line;constructor(e,t){super(`INVALID_YAML_FILE_ERROR`,t),this.name=`InvalidYamlFileError`,this.line=e??1}},ce=class extends N{issues;constructor(e,t){super(`SCHEMA_VALIDATION_ERROR`,t),this.name=`SchemaValidationError`,this.issues=e}},F=class extends N{operationId;stepId;functionName;functionVersion;constructor(e,t,n,r=`1`){let i=`Invalid Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the function name and version are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION`,i),this.name=`InvalidStepFunctionError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r}},le=class extends N{operationId;stepId;functionName;functionVersion;issues;constructor(e,t,n,r=`1`,i){let a=`Invalid parameters for Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the parameters are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION_PARAMS`,a),this.name=`InvalidStepFunctionParamsError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r,this.issues=i,this.message=a}};const ue=25,de=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`refresh_token`:return{statusCode:200,description:`The refresh token operation was executed successfully.`};case`unknown`:return{statusCode:200};default:throw Error(`Unknown operation type: ${e}`)}},fe=()=>{let e={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.`}};return e},I={key:a.string(),label:a.string(),required:a.boolean().optional().default(!1),secret:a.boolean().optional().default(!1),readOnly:a.boolean().optional().default(!1),placeholder:a.string().optional(),description:a.string().optional(),tooltip:a.string().optional()},L=a.discriminatedUnion(`type`,[o({...I,type:a.enum([`text`,`password`])}),o({...I,type:a.literal(`select`),options:o({value:a.string(),label:a.string()}).array()})]),pe=o({targetFieldKey:a.string(),alias:a.string().optional(),expression:a.string().optional(),values:a.unknown().optional(),type:a.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:a.boolean().default(!1),custom:a.boolean().default(!1),hidden:a.boolean().default(!1),enumMapper:o({matcher:a.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`,`document_file_format_from_extension`]).or(o({matchExpression:a.string(),value:a.string()}).array())}).optional(),properties:a.lazy(()=>pe).array().optional()}),me=o({name:a.string(),type:a.enum([`string`,`number`,`boolean`,`datetime_string`,`object`]),required:a.boolean(),description:a.string(),array:a.boolean().optional().default(!1),in:a.enum([`body`,`query`,`path`,`headers`]),properties:a.lazy(()=>me.omit({in:!0})).array().optional()}),R=o({operationId:a.string(),categories:a.string().array(),operationType:a.enum([`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`unknown`]),schema:a.string().optional(),schemaType:a.enum([`native`,`unified`]).optional().default(`native`),entrypointUrl:a.string().optional(),entrypointHttpMethod:a.string().optional(),label:a.string(),description:a.string(),tags:a.string().array().optional(),context:a.string().optional(),responses:o({statusCode:a.number(),description:a.string()}).array().optional(),inputs:me.array().optional(),cursor:o({enabled:a.boolean(),pageSize:a.number()}).optional(),compositeIdentifiers:o({enabled:a.boolean(),version:a.number().optional(),fields:o({targetFieldKey:a.string(),remote:a.string().optional(),components:a.string().array()}).array().optional()}).optional(),scheduledJobs:o({enabled:a.boolean(),type:a.enum([`data_sync`]),schedule:a.string(),description:a.string(),requestParams:o({fields:a.string().array().optional(),expand:a.string().array().optional(),filter:a.record(a.string(),a.string()).optional()}).optional(),syncFilter:o({name:a.enum([`updated_after`,`created_after`]),initialLoopbackPeriod:a.string(),incrementalLoopbackPeriod:a.string()}).optional()}).array().optional(),fieldConfigs:pe.array().optional(),steps:o({stepId:a.string(),description:a.string(),stepFunction:o({functionName:a.string(),version:a.string().optional(),parameters:a.record(a.string(),a.unknown())}),condition:a.string().optional(),ignoreError:a.boolean().optional()}).array(),result:a.string().or(a.record(a.string(),a.unknown())).optional()}),he=o({schedule:a.string().optional(),operation:R.extend({operationType:a.literal(`refresh_token`)})}),ge=o({mainRatelimit:a.number(),subPools:a.array(o({subPoolKey:a.string(),urlPattern:a.string(),rateLimit:a.number()})).optional(),mappedRateLimitErrors:a.array(o({errorStatus:a.number(),errorMessage:a.string(),errorMessagePath:a.string().optional(),retryAfterPath:a.string().optional(),retryAfterUnit:a.union([a.literal(`seconds`),a.literal(`milliseconds`),a.literal(`date`)]).optional(),retryAfterValue:a.number().optional()})).optional()}),_e=o({mainMaxConcurrency:a.number(),subPools:a.array(o({subPoolKey:a.string(),urlPattern:a.string(),maxConcurrency:a.number()})).optional()}),ve=o({StackOne:a.string(),info:o({title:a.string(),version:a.string(),key:a.string(),assets:o({icon:a.string()}),description:a.string()}),context:a.string().optional(),baseUrl:a.string(),authentication:a.record(a.string(),o({type:a.string(),label:a.string(),authorization:f,environments:o({key:a.string(),name:a.string()}).array(),support:o({link:a.string(),description:a.string().optional()}),configFields:L.array().optional(),setupFields:L.array().optional(),refreshAuthentication:he.optional(),testOperations:o({operation:a.string().or(R),condition:a.string().optional(),required:a.boolean().default(!0)}).array().optional()})).array().optional(),operations:R.array().optional(),rateLimit:ge.optional(),concurrency:_e.optional()}).strict();function z(e){try{let t=T(e),n=Ie(ve,t),r={title:n.info.title,version:n.info.version,key:n.info.key,assets:n.info.assets,description:n.info.description,context:n.context,rateLimit:n.rateLimit,concurrency:n.concurrency},a=Se(n),o={baseUrl:n.baseUrl,authentication:ye(a)},s=Oe(n,o);return r.operations=s,be(n.info.key,a,s,o),r.authentication=a,i(s)&&(r.categories=xe(Object.values(s))),r}catch(e){if(e instanceof N)throw e;let t=e.message,n=t.match(/at line (\d+)/),r=n?parseInt(n[1],10):1;throw new P(r,t)}}const ye=e=>{let t={};for(let[n,r]of Object.entries(e))if(r&&typeof r==`object`){let{setupFields:e,configFields:i,support:a,refreshAuthentication:o,testOperations:s,...c}=r;t[n]=ye(c)}else t[n]=r;return t},be=(e,t,n,r)=>{if(!(!t||!n))for(let a of Object.values(t))for(let t of Object.values(a)){let a=t.testOperations;t.testOperations=a?.map(t=>{if(i(t.operation))if(typeof t.operation==`string`){let r=M(e,t.operation),i=Object.values(n).find(e=>e.id===r);if(i)return{...t,operation:i}}else{let n=M(e,t.operation.operationId),i=B(n,t.operation,r);return{...t,operation:i}}return t})}},xe=e=>{let t=e.reduce((e,t)=>{for(let n of t.categories)e.add(n);return e},new Set);return Array.from(t)},Se=e=>{let t={};for(let n of e.authentication??[]){let[r]=Object.keys(n),a=n[r].environments.reduce((t,a)=>{let{key:o,name:s}=a,{environments:c,refreshAuthentication:l,testOperations:u,...d}=n[r],f=i(l)?{schedule:l.schedule,operation:B(M(e.info.key,l.operation.operationId),l.operation)}:void 0;return t[o]={...d,refreshAuthentication:f,envKey:o,envName:s,testOperations:u},t},{});t[r]=a}return t},Ce=e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0,we=e=>e.operationType===`list`?`GET /${e.schema}`:`GET /${e.schema}/:id`,Te=e=>{if(e.operationType!==`refresh_token`)return e.entrypointHttpMethod??`get`},Ee=t=>{if(!(t.operationType===`refresh_token`||e(t.schema)))return t.operationType===`list`?`/${t.schema}`:`/${t.schema}/:id`},De=e=>{let t={success:de(e.operationType),errors:fe()},n=e.responses?.reduce((e,t)=>{let n=te(t.statusCode);return n?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e},t);return n??t},Oe=(e,t)=>{let n=e.operations?.reduce((n,r)=>{let i=Ce(r),a=we(r),o=i??a,s=M(e.info.key,r.operationId);return n[s]=B(s,r,t,o),n},{});return n},B=(e,t,n,r)=>{let i=Ee(t),a=De(t),o=Me(t),s=t.inputs||[];o.enabled&&(s?.push({type:`string`,name:`page_size`,in:`query`,required:!1,description:`Number of items to return per page`,array:!1}),s?.push({type:`string`,name:`next`,in:`query`,required:!1,description:`Token for the next page of results`,array:!1}));let c=Te(t);return{id:e,categories:t.categories,label:t.label,description:t.description,operationType:t.operationType,schemaType:t.schemaType??`native`,entrypointUrl:t.entrypointUrl??i,entrypointHttpMethod:c,endpoint:r,tags:t.tags,context:t.context,responses:a,cursor:o,compositeIdentifiers:Ne(t),scheduledJobs:Pe(t),inputs:s,steps:t.steps.reduce((e,r)=>{let{customErrors:i,...a}=r.stepFunction.parameters??{},o={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{...Fe({stepFunctionName:r.stepFunction.functionName,baseRequestParams:n,customErrors:i}),...r.stepFunction.functionName===`map_fields`||r.stepFunction.functionName===`typecast`?{fields:a.fields??t.fieldConfigs}:{},...a}}};return ke(t.operationId,o),e[r.stepId]=o,e},{}),result:t.result}},ke=(e,t)=>{let n=t.stepFunction.version??`1`,r=_[t.stepFunction.functionName]?.[`v${n}`];if(!r)throw new F(e,t.id,t.stepFunction.functionName,n);let i=r.inputSchema;i&&Le(i,t.stepFunction.params,e,t.id,t.stepFunction.functionName,n)},V=(e,t)=>{if(!e.inputs)return{};let n=Ae(e.inputs),r=a.object(n).parse(t);return{...r.headers??{},...r.query??{},...r.path??{},...r.body??{}}},Ae=e=>{let t=e.reduce((e,t)=>(e[t.in]||(e[t.in]=[]),e[t.in].push(t),e),{}),n={};for(let[e,r]of Object.entries(t)){let t={};for(let e of r){let n=je(e);e.description&&(n=n.describe(e.description)),e.required||(n=n.optional()),t[e.name]=n}Object.keys(t).length>0&&(n[e]=a.object(t))}return n},je=e=>{let t;switch(e.type){case`string`:case`datetime_string`:t=a.string();break;case`number`:t=a.number();break;case`boolean`:t=a.boolean();break;case`object`:if(e.properties&&e.properties.length>0){let n={};for(let t of e.properties){let e=je(t);t.description&&(e=e.describe(t.description)),t.required||(e=e.optional()),n[t.name]=e}t=a.object(n)}else t=a.record(a.string(),a.unknown());break;default:t=a.unknown()}return e.array&&(t=a.array(t)),t},Me=e=>{let t=e.operationType===`list`,n=e.cursor??{enabled:t,pageSize:ue};return{enabled:n.enabled&&t,pageSize:n.pageSize}},Ne=t=>{if(t.operationType===`refresh_token`)return{enabled:!1};if(e(t.compositeIdentifiers)){let e=t.fieldConfigs?.find(e=>e.targetFieldKey===`id`),n=i(e)?[{targetFieldKey:e.targetFieldKey,remote:`id`,components:[{name:e.targetFieldKey,alias:e.alias}]}]:void 0;return{enabled:!0,version:p,fields:n}}let n=[];for(let e of t.compositeIdentifiers?.fields??[]){let r=e.components.map(e=>{let n=t.fieldConfigs?.find(t=>t.targetFieldKey===e);return{name:e,alias:n?.alias}});n.push({targetFieldKey:e.targetFieldKey,remote:e.remote,components:r})}return{enabled:t.compositeIdentifiers.enabled,version:t.compositeIdentifiers.version,fields:n.length>0?n:void 0}},Pe=t=>{if(!e(t.scheduledJobs))return t.scheduledJobs},Fe=({stepFunctionName:e,baseRequestParams:t,customErrors:n={}})=>{if(e===`request`||e===`paginated_request`){let e=[{receivedStatus:500,targetStatus:502}],r=n&&Array.isArray(n)?n:[],i=[...r,...e];return{...t,customErrors:i}}else return{}},Ie=(e,t)=>{let n=e.safeParse(t);if(n.success)return n.data;{let e=n.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new ce(e,`Invalid connector schema`)}},Le=(e,t,n,r,i,a)=>{let o=e.safeParse(t);if(o.success)return o.data;{let e=o.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new le(n,r,i,a,e)}},H=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return;let r=e.authentication?.[t]?.[n]?.refreshAuthentication?.operation;if(i(r))return{operation:r,params:{}}},Re=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return!1;let r=H(e,t,n);return i(r)},ze=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenExpiresIn},Be=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenRefreshExpiresIn},Ve=t=>{try{return z(t),{success:!0}}catch(n){if(n instanceof ce){let r=n.issues,i=[];return r.forEach(n=>{let r=n?.keys?.[0],a=e(r)?n.path:[...n.path,r],o=He(a,t);i.push({line:o,message:n.message,field:a.join(`.`)})}),{success:!1,errors:i}}else if(n instanceof P)return{success:!1,errors:[{line:n.line,message:`The YAML connector file is not valid. Please check the syntax and structure.`,field:void 0}]};else if(n instanceof F){let e=U(n.operationId,n.stepId,n.functionName,!1,t);return{success:!1,errors:[{line:e,message:n.message,field:void 0}]}}else if(n instanceof le){let r=n.issues,i=[];return r.forEach(r=>{let a=r?.keys?.[0],o=e(a)?r.path:[...r.path,a],s=U(n.operationId,n.stepId,n.functionName,!0,t);i.push({line:s,message:r.message,field:o.join(`.`)})}),{success:!1,errors:i}}}return{success:!1,errors:[{line:1,message:`An unknown error occurred while parsing the connector.`,field:void 0}]}},He=(t,n)=>{let r=n.split(`
4
+ `).filter(e=>e.trim()!==``)}catch(t){throw Error(`Failed to load partial file '${e}': ${t.message}`)}},A=(e,t,n)=>{let r=n.toUpperCase();if(!e.operations)return;let a=Object.values(e.operations).filter(e=>i(e.endpoint)).map(e=>({operationId:e.id,endpoint:e.endpoint})),o=oe(t,r,a);if(o)return{operation:e.operations?.[o.operationId],params:o.params}},j=e=>{let t=e.startsWith(`/`)?e.slice(1):e,n=t.endsWith(`/`)?t.slice(0,-1):t;return n},oe=(e,t,n)=>{let r=j(e);for(let e of n)if(e.endpoint?.startsWith(t)){let n=e.endpoint.replace(`${t} `,``).trim(),i=d(j(n)),a=i(j(r));if(a!==!1)return{operationId:e.operationId,path:e.endpoint,params:a.params}}},M=(e,t)=>t?.startsWith(`${e}_`)?t:`${e}_${t}`,se=(e,t)=>{let n=`${e.key}_`,r=t.startsWith(n)?t:`${n}${t}`;return e.operations?.[r]};var N=class e extends Error{errorType;constructor(t,n){super(n),this.name=`InternalConnectSDKError`,this.errorType=t,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},P=class extends N{line;constructor(e,t){super(`INVALID_YAML_FILE_ERROR`,t),this.name=`InvalidYamlFileError`,this.line=e??1}},ce=class extends N{issues;constructor(e,t){super(`SCHEMA_VALIDATION_ERROR`,t),this.name=`SchemaValidationError`,this.issues=e}},F=class extends N{operationId;stepId;functionName;functionVersion;constructor(e,t,n,r=`1`){let i=`Invalid Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the function name and version are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION`,i),this.name=`InvalidStepFunctionError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r}},le=class extends N{operationId;stepId;functionName;functionVersion;issues;constructor(e,t,n,r=`1`,i){let a=`Invalid parameters for Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the parameters are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION_PARAMS`,a),this.name=`InvalidStepFunctionParamsError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r,this.issues=i,this.message=a}};const ue=25,de=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`refresh_token`:return{statusCode:200,description:`The refresh token operation was executed successfully.`};case`unknown`:return{statusCode:200};default:throw Error(`Unknown operation type: ${e}`)}},fe=()=>{let e={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.`}};return e},I={key:a.string(),label:a.string(),required:a.boolean().optional().default(!1),secret:a.boolean().optional().default(!1),readOnly:a.boolean().optional().default(!1),placeholder:a.string().optional(),description:a.string().optional(),tooltip:a.string().optional()},L=a.discriminatedUnion(`type`,[o({...I,type:a.enum([`text`,`password`])}),o({...I,type:a.literal(`select`),options:o({value:a.string(),label:a.string()}).array()})]),pe=o({targetFieldKey:a.string(),alias:a.string().optional(),expression:a.string().optional(),values:a.unknown().optional(),type:a.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:a.boolean().default(!1),custom:a.boolean().default(!1),hidden:a.boolean().default(!1),enumMapper:o({matcher:a.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`,`document_file_format_from_extension`]).or(o({matchExpression:a.string(),value:a.string()}).array())}).optional(),properties:a.lazy(()=>pe).array().optional()}),me=o({name:a.string(),type:a.enum([`string`,`number`,`boolean`,`datetime_string`,`object`]),required:a.boolean(),description:a.string(),array:a.boolean().optional().default(!1),in:a.enum([`body`,`query`,`path`,`headers`]),properties:a.lazy(()=>me.omit({in:!0})).array().optional()}),R=o({operationId:a.string(),categories:a.string().array(),operationType:a.enum([`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`unknown`]),schema:a.string().optional(),schemaType:a.enum([`native`,`unified`]).optional().default(`native`),entrypointUrl:a.string().optional(),entrypointHttpMethod:a.string().optional(),label:a.string(),description:a.string(),tags:a.string().array().optional(),context:a.string().optional(),responses:o({statusCode:a.number(),description:a.string()}).array().optional(),inputs:me.array().optional(),cursor:o({enabled:a.boolean(),pageSize:a.number()}).optional(),compositeIdentifiers:o({enabled:a.boolean(),version:a.number().optional(),fields:o({targetFieldKey:a.string(),remote:a.string().optional(),components:a.string().array()}).array().optional()}).optional(),scheduledJobs:o({enabled:a.boolean(),type:a.enum([`data_sync`]),schedule:a.string(),description:a.string(),requestParams:o({fields:a.string().array().optional(),expand:a.string().array().optional(),filter:a.record(a.string(),a.string()).optional()}).optional(),syncFilter:o({name:a.enum([`updated_after`,`created_after`]),initialLoopbackPeriod:a.string(),incrementalLoopbackPeriod:a.string()}).optional()}).array().optional(),fieldConfigs:pe.array().optional(),steps:o({stepId:a.string(),description:a.string(),stepFunction:o({functionName:a.string(),version:a.string().optional(),parameters:a.record(a.string(),a.unknown())}),condition:a.string().optional(),ignoreError:a.boolean().optional()}).array(),result:a.string().or(a.record(a.string(),a.unknown())).optional()}),he=o({schedule:a.string().optional(),operation:R.extend({operationType:a.literal(`refresh_token`)})}),ge=o({mainRatelimit:a.number(),subPools:a.array(o({subPoolKey:a.string(),urlPattern:a.string(),rateLimit:a.number()})).optional(),mappedRateLimitErrors:a.array(o({errorStatus:a.number(),errorMessage:a.string(),errorMessagePath:a.string().optional(),retryAfterPath:a.string().optional(),retryAfterUnit:a.union([a.literal(`seconds`),a.literal(`milliseconds`),a.literal(`date`)]).optional(),retryAfterValue:a.number().optional()})).optional()}),_e=o({mainMaxConcurrency:a.number(),subPools:a.array(o({subPoolKey:a.string(),urlPattern:a.string(),maxConcurrency:a.number()})).optional()}),ve=o({StackOne:a.string(),info:o({title:a.string(),version:a.string(),key:a.string(),assets:o({icon:a.string()}),description:a.string()}),context:a.string().optional(),baseUrl:a.string(),authentication:a.record(a.string(),o({type:a.string(),label:a.string(),authorization:f,environments:o({key:a.string(),name:a.string()}).array(),support:o({link:a.string(),description:a.string().optional()}),configFields:L.array().optional(),setupFields:L.array().optional(),refreshAuthentication:he.optional(),testOperations:o({operation:a.string().or(R),condition:a.string().optional(),required:a.boolean().default(!0)}).array().optional()})).array().optional(),operations:R.array().optional(),rateLimit:ge.optional(),concurrency:_e.optional()}).strict();function z(e){try{let t=T(e),n=Ie(ve,t),r={title:n.info.title,version:n.info.version,key:n.info.key,assets:n.info.assets,description:n.info.description,context:n.context,rateLimit:n.rateLimit,concurrency:n.concurrency},a=Se(n),o={baseUrl:n.baseUrl,authentication:ye(a)},s=Oe(n,o);return r.operations=s,be(n.info.key,a,s,o),r.authentication=a,i(s)&&(r.categories=xe(Object.values(s))),r}catch(e){if(e instanceof N)throw e;let t=e.message,n=t.match(/at line (\d+)/),r=n?parseInt(n[1],10):1;throw new P(r,t)}}const ye=e=>{let t={};for(let[n,r]of Object.entries(e))if(r&&typeof r==`object`){let{setupFields:e,configFields:i,support:a,refreshAuthentication:o,testOperations:s,...c}=r;t[n]=ye(c)}else t[n]=r;return t},be=(e,t,n,r)=>{if(!(!t||!n))for(let a of Object.values(t))for(let t of Object.values(a)){let a=t.testOperations;t.testOperations=a?.map(t=>{if(i(t.operation))if(typeof t.operation==`string`){let r=M(e,t.operation),i=Object.values(n).find(e=>e.id===r);if(i)return{...t,operation:i}}else{let n=M(e,t.operation.operationId),i=B(n,t.operation,r);return{...t,operation:i}}return t})}},xe=e=>{let t=e.reduce((e,t)=>{for(let n of t.categories)e.add(n);return e},new Set);return Array.from(t)},Se=e=>{let t={};for(let n of e.authentication??[]){let[r]=Object.keys(n),a=n[r].environments.reduce((t,a)=>{let{key:o,name:s}=a,{environments:c,refreshAuthentication:l,testOperations:u,...d}=n[r],f=i(l)?{schedule:l.schedule,operation:B(M(e.info.key,l.operation.operationId),l.operation)}:void 0;return t[o]={...d,refreshAuthentication:f,envKey:o,envName:s,testOperations:u},t},{});t[r]=a}return t},Ce=e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0,we=e=>e.operationType===`list`?`GET /${e.schema}`:`GET /${e.schema}/:id`,Te=e=>{if(e.operationType!==`refresh_token`)return e.entrypointHttpMethod??`get`},Ee=t=>{if(!(t.operationType===`refresh_token`||e(t.schema)))return t.operationType===`list`?`/${t.schema}`:`/${t.schema}/:id`},De=e=>{let t={success:de(e.operationType),errors:fe()},n=e.responses?.reduce((e,t)=>{let n=te(t.statusCode);return n?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e},t);return n??t},Oe=(e,t)=>{let n=e.operations?.reduce((n,r)=>{let i=Ce(r),a=we(r),o=i??a,s=M(e.info.key,r.operationId);return n[s]=B(s,r,t,o),n},{});return n},B=(e,t,n,r)=>{let i=Ee(t),a=De(t),o=Me(t),s=t.inputs||[];o.enabled&&(s?.push({type:`string`,name:`page_size`,in:`query`,required:!1,description:`Number of items to return per page`,array:!1}),s?.push({type:`string`,name:`next`,in:`query`,required:!1,description:`Token for the next page of results`,array:!1}));let c=Te(t);return{id:e,categories:t.categories,label:t.label,description:t.description,operationType:t.operationType,schemaType:t.schemaType??`native`,entrypointUrl:t.entrypointUrl??i,entrypointHttpMethod:c,endpoint:r,tags:t.tags,context:t.context,responses:a,cursor:o,compositeIdentifiers:Ne(t),scheduledJobs:Pe(t),inputs:s,steps:t.steps.reduce((e,r)=>{let{customErrors:i,...a}=r.stepFunction.parameters??{},o={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{...Fe({stepFunctionName:r.stepFunction.functionName,baseRequestParams:n,customErrors:i}),...r.stepFunction.functionName===`map_fields`||r.stepFunction.functionName===`typecast`?{fields:a.fields??t.fieldConfigs}:{},...a}}};return ke(t.operationId,o),e[r.stepId]=o,e},{}),result:t.result}},ke=(e,t)=>{let n=t.stepFunction.version??`1`,r=_[t.stepFunction.functionName]?.[`v${n}`];if(!r)throw new F(e,t.id,t.stepFunction.functionName,n);let i=r.inputSchema;i&&Le(i,t.stepFunction.params,e,t.id,t.stepFunction.functionName,n)},V=(e,t)=>{if(!e.inputs)return{};let n=Ae(e.inputs),r=a.object(n).parse(t);return{...r.headers??{},...r.query??{},...r.path??{},...r.body??{}}},Ae=e=>{let t=e.reduce((e,t)=>(e[t.in]||(e[t.in]=[]),e[t.in].push(t),e),{}),n={};for(let[e,r]of Object.entries(t)){let t={};for(let e of r){let n=je(e);e.description&&(n=n.describe(e.description)),e.required||(n=n.optional()),t[e.name]=n}Object.keys(t).length>0&&(n[e]=a.object(t))}return n},je=e=>{let t;switch(e.type){case`string`:case`datetime_string`:t=a.string();break;case`number`:t=a.number();break;case`boolean`:t=a.boolean();break;case`object`:if(e.properties&&e.properties.length>0){let n={};for(let t of e.properties){let e=je(t);t.description&&(e=e.describe(t.description)),t.required||(e=e.optional()),n[t.name]=e}t=a.object(n)}else t=a.record(a.string(),a.unknown());break;default:t=a.unknown()}return e.array&&(t=a.array(t)),t},Me=e=>{let t=e.operationType===`list`,n=e.cursor??{enabled:t,pageSize:ue};return{enabled:n.enabled&&t,pageSize:n.pageSize}},Ne=t=>{if(t.operationType===`refresh_token`)return{enabled:!1};if(e(t.compositeIdentifiers)){let e=t.fieldConfigs?.find(e=>e.targetFieldKey===`id`),n=i(e)?[{targetFieldKey:e.targetFieldKey,remote:`id`,components:[{name:e.targetFieldKey,alias:e.alias}]}]:void 0;return{enabled:!0,version:p,fields:n}}let n=[];for(let e of t.compositeIdentifiers?.fields??[]){let r=e.components.map(e=>{let n=t.fieldConfigs?.find(t=>t.targetFieldKey===e);return{name:e,alias:n?.alias}});n.push({targetFieldKey:e.targetFieldKey,remote:e.remote,components:r})}return{enabled:t.compositeIdentifiers.enabled,version:t.compositeIdentifiers.version,fields:n.length>0?n:void 0}},Pe=t=>{if(!e(t.scheduledJobs))return t.scheduledJobs},Fe=({stepFunctionName:e,baseRequestParams:t,customErrors:n={}})=>{if(e===`request`||e===`paginated_request`){let e=[{receivedStatus:500,targetStatus:502}],r=n&&Array.isArray(n)?n:[],i=[...r,...e];return{...t,customErrors:i}}else return{}},Ie=(e,t)=>{let n=e.safeParse(t);if(n.success)return n.data;{let e=n.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new ce(e,`Invalid connector schema`)}},Le=(e,t,n,r,i,a)=>{let o=e.safeParse(t);if(o.success)return o.data;{let e=o.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new le(n,r,i,a,e)}},H=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return;let r=e.authentication?.[t]?.[n]?.refreshAuthentication?.operation;if(i(r))return{operation:r,params:{}}},Re=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return!1;let r=H(e,t,n);return i(r)},ze=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenExpiresIn},Be=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenRefreshExpiresIn},Ve=t=>{try{let e=z(t);return{success:!0,connector:e}}catch(n){if(n instanceof ce){let r=n.issues,i=[];return r.forEach(n=>{let r=n?.keys?.[0],a=e(r)?n.path:[...n.path,r],o=He(a,t);i.push({line:o,message:n.message,field:a.join(`.`)})}),{success:!1,errors:i}}else if(n instanceof P)return{success:!1,errors:[{line:n.line,message:`The YAML connector file is not valid. Please check the syntax and structure.`,field:void 0}]};else if(n instanceof F){let e=U(n.operationId,n.stepId,n.functionName,!1,t);return{success:!1,errors:[{line:e,message:n.message,field:void 0}]}}else if(n instanceof le){let r=n.issues,i=[];return r.forEach(r=>{let a=r?.keys?.[0],o=e(a)?r.path:[...r.path,a],s=U(n.operationId,n.stepId,n.functionName,!0,t);i.push({line:s,message:r.message,field:o.join(`.`)})}),{success:!1,errors:i}}}return{success:!1,errors:[{line:1,message:`An unknown error occurred while parsing the connector.`,field:void 0}]}},He=(t,n)=>{let r=n.split(`
5
5
  `),a=0,o=-1,s=0;for(let n=0;n<r.length;n++){let c=r[n],l=c.match(/^(\s*)/)?.[1]?.length||0,u=c.replace(`- `,``).trim();if(u.startsWith(`#`)||u===``||l<=o)continue;let d=i(t[a])?`${String(t[a])}`:``;if(e(d))return s+1;if(isNaN(Number(d))){if(u.startsWith(`${d}:`)){if(a===t.length-1)return n+1;o=l,s=n,a++}}else{let e=parseInt(d,10),t=-1;for(let i=n;i<r.length;i++){let o=r[i],c=o.trim();if(c.startsWith(`-`)&&t++,t===e){a++,s=n,n--;break}else n++}}}return s+1},U=(t,n,r,a,o)=>{let s=o.split(`
6
6
  `),c=1,l=null,u=null;for(let o=0;o<s.length;o++){let d=s[o],f=d.trim();if(e(l)&&f===`- operationId: ${t}`){l=t,c=o+1;continue}if(i(l)&&e(u)&&f===`- stepId: ${n}`){u=n,c=o+1;continue}if(i(l)&&i(u)&&!a&&f.startsWith(`functionName: ${r}`)||i(l)&&i(u)&&a&&f===`parameters:`)return c=o+1,c}return c};var W=class e extends Error{errorType;context;constructor(t,n,r){super(r),this.name=`ConnectSDKError`,this.errorType=t,this.context=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},Ue=class extends W{constructor(e,t){super(`CONNECTOR_PARSE_ERROR`,e,t),this.name=`ConnectorParseError`}},G=class extends W{constructor(e,t){super(`MISSING_OPERATION_ERROR`,e,t),this.name=`MissingOperationError`}},We=class extends W{constructor(e,t){super(`INVALID_OPERATION_INPUTS_ERROR`,e,t),this.name=`InvalidOperationInputsError`}},Ge=class extends W{constructor(e,t){super(`INVALID_CURSOR_ERROR`,e,t),this.name=`InvalidCursorError`}};const Ke=(e,t)=>{let n=Object.keys(e.authentication??{}).map(t=>({type:`custom`,label:e.authentication?.[t].production?.label||`Custom`,key:t})),r=Object.values(e?.operations??{}).map(e=>({id:e.id,description:e.description.replace(/\b\w/g,e=>e.toUpperCase()),label:e.label.replace(/\b\w/g,e=>e.toUpperCase()),schema_type:e.schemaType,tags:e.tags,authentication:n,operation_details:t?.includes(`operation_details`)?e:void 0}));return{version:e.version,name:e.title,key:e.key,icon:e.assets?.icon,description:e.description,authentication:n,actions:r}},qe=(e,t)=>e.map(e=>Ke(e,t)),Je=`stackone://internal//`,Ye=`${Je}refresh_token`,Xe=async({block:e,stepFunctionName:t,params:n,buildStepFunction:r=g.build})=>{let i=r({functionName:t}).fn,a=await i({block:e,params:n}),o=t===h.MAP_FIELDS?{[h.MAP_FIELDS.toString()]:{output:{data:a.block.result},errors:a.errors,successful:a.successful}}:{};return{...a.block,steps:{...a?.block?.steps??{},...o}}},K=({category:e,connectorKey:t,connectorVersion:n,authConfigKey:r,environment:i=`production`,operation:a,accountSecureId:o,projectSecureId:s})=>({projectSecureId:s,accountSecureId:o,connectorKey:t,connectorVersion:n,category:e,service:``,resource:``,schema:a?.schema?.key,operationType:a?.operationType??`unknown`,authenticationType:r,environment:i}),Ze=(e,t,n)=>e.authentication?.[t]?.[n]?.testOperations,Qe=t=>{let n=t.operation?.compositeIdentifiers,r={...t.inputs??{}};if(!n?.enabled||e(r))return t;let i=n.fields?.reduce((e,t)=>(t.components.forEach(t=>{t.alias&&(e[t.name]=t.alias)}),e),{}),a={version:n.version??p,aliases:i};return q(r,a,t.logger),{...t,inputs:r}},q=(e,t,n)=>{for(let r in e){let i=e[r];if(typeof i==`string`||Array.isArray(i)&&i.every(e=>typeof e==`string`))it(i,r,e,t,n);else if(Array.isArray(i))for(let e of i)q(e,t,n);else typeof i==`object`&&i&&q(i,t,n)}},$e=(e,t,n,r)=>{let i=[],a=[];for(let o of e)try{let e=v(o,n);i.push(e)}catch(e){r?.debug({message:`Received ${t} with invalid composite ID, assuming it is not a composite ID`,category:`processCompositeId`,context:{key:t,inputElement:o,compositeIdentifierConfig:n,error:e}}),a.push(o)}return{compositeIdComponents:i,nonCompositeIds:a}},et=(e,t,n,r)=>{let i=n.filter(e=>Object.keys(e).length>1);i.length>0&&(e.decoded_ids={...e.decoded_ids??{},[t]:r?i:i[0]})},tt=e=>{let t=Object.values(e);return t.length===1&&(typeof t[0]==`string`||typeof t[0]==`number`)},nt=(e,t,n,r,i)=>{n.every(tt)&&(i?e[t]=[...n.map(e=>Object.values(e)[0]),...r]:n.length>0&&(e[t]=Object.values(n[0])[0]))},rt=(e,t,n)=>{e instanceof m&&e.type===`COMPOSITE_ID_MISSING_HEADER_ERROR`?n?.debug({message:`Received ${t} with no composite ID header, assuming it is not a composite ID`}):n?.warning({message:`Error processing composite ID for ${t}, ignoring it`,error:e})},it=(e,t,n,r,i)=>{try{let a=Array.isArray(e),o=a?e:[e];if(o.length===0)return;let{compositeIdComponents:s,nonCompositeIds:c}=$e(o,t,r,i);et(n,t,s,a),nt(n,t,s,c,a)}catch(e){rt(e,t,i)}},J=`remote_`,at=t=>{let n=t.operation?.compositeIdentifiers;if(!n?.enabled)return t;let r=`data`,i=t.outputs?.[r];if(e(i))return t;let a=Array.isArray(i)?i.map(e=>ot(e,n)):ot(i,n);return{...t,outputs:{...t.outputs??{},[r]:a}}},ot=(e,t)=>{let r=st(e,t),i=Y(r);return{...e,...n(i)?i:{}}},st=(e,t)=>{let n=t.version??p,r={};return t.fields?.forEach(t=>{let i={},a=[];t.components.forEach(t=>{t.alias&&(i[t.name]=t.alias),a.push({key:t.name,value:e[t.name]})});let o=a.length===1?a[0]:{identifiers:a},s={version:n,aliases:Object.keys(i).length>0?i:void 0},c=y(o,s);r[t.targetFieldKey]=c,t.remote&&(r[`${J}${t.remote}`]=e[t.remote])}),{...e,...r}},ct=e=>e===`id`||/.+_id(s)?$/.test(e),lt=e=>Array.isArray(e)&&e.every(e=>r(e)&&e.length>0),ut=(e,t)=>x(e)||t.startsWith(J),dt=(e,t)=>{try{return y({key:e,value:t},{version:p})}catch{return t}},ft=(e,t,n)=>{let i=t.map(t=>r(t)&&t.length>0&&!x(t)?dt(e,t):t);n[e]=i,n[`${J}${e}`]=t},pt=(e,t,n)=>{if(ut(t,e))return;let r=y({key:e,value:t},{version:p});n[e]=r,n[`remote_${e}`]=t},mt=(e,t,n)=>{lt(t)?ft(e,t,n):r(t)&&t.length>0&&pt(e,t,n)},Y=e=>{if(Array.isArray(e))return e.map(e=>Y(e));if(!n(e))return e;let t={...e};for(let[r,i]of Object.entries(e))(n(i)||Array.isArray(i)&&i.length>0&&n(i[0]))&&(t[r]=Y(i)),ct(r)&&mt(r,i,t);return t},ht=(e,n)=>{let r=Number(e.inputs?.page_size),a=i(e.inputs?.page_size)&&t(r)&&!Number.isNaN(r)?r:e.operation?.cursor?.pageSize??n;return a},gt=(t,r,a,o)=>{let s=e(t)?void 0:t.data,c=Object.keys(a).length+1,l=S({cursor:o,ignoreStepIndex:c});if(!n(t)||e(s)||(s?.length??0)<=r)return{result:t,next:i(o)&&!l?C(o):null};let u=o?.remote?.[c]?.pageNumber??1,d=(u-1)*r,f=d+r,p=s.slice(d,f),m=s.length>f||!l,h=w({cursor:o,stepIndex:c,pageNumber:u+1});return{result:{...t,data:p},next:m?C(h):null}},X=async({block:e,buildStepFunction:t=g.build,virtualPaginateResultFn:n=gt,encodeResultCompositeIds:r=at,decodeInputCompositeIds:i=Qe})=>{let a=i(e),o=await St({block:a,buildStepFunction:t,virtualPaginateResultFn:n});return r(o)},_t=(e,t)=>e.condition?!E(e.condition,t):!1,vt=(e,t,n)=>{let r=e.stepFunction,a=_[e.stepFunction.functionName]?.[`v${e.stepFunction.version??1}`],o=i(a?.inputSchema?.shape)?`cursor`in a?.inputSchema?.shape:!1;return t.operation?.cursor.enabled&&o?{...r.params??{},cursor:{token:t.nextCursor?.remote?.[n]?.providerPageCursor,position:t.nextCursor?.remote?.[n]?.position}}:r.params??{}},yt=(e,t,n,r,i)=>{let a=Z({block:e,stepId:t,successful:!1,functionOutput:n}),o=r.ignoreError??!1;return o||(i.hasFatalError=!0,i.errorStatusCode??=n.output?.statusCode??500),a},bt=async(e,t,n,r,i,a)=>{let o=n[e],s=o.stepFunction,c=a.buildStepFunction({functionName:s.functionName,version:s.version,validateSchemas:!0}).fn;if(_t(o,r))return Z({block:r,stepId:e,successful:!0,skipped:!0,message:`Step skipped due to condition not met.`});if(i.hasFatalError)return Z({block:r,stepId:e,successful:!1,skipped:!0,message:`Step skipped due to previous error.`});let l=vt(o,r,t),u=await c({block:r,params:l});if(u.successful===!1)return yt(r,e,u,o,i);let d=r.operation?.cursor.enabled?w({cursor:r.nextCursor,stepIndex:t,providerPageCursor:u.output?.next,position:u.output?.position}):void 0;return Z({block:{...u.block,nextCursor:d},stepId:e,functionOutput:u})},xt=(e,t,r,a,o)=>{let s=!r.hasFatalError,c=s?e.operation?.responses.success.statusCode??200:r.errorStatusCode??500,l=i(o)&&n(o.result)?{next:o.next,...o.result}:a;return{...t,outputs:l,response:{successful:s,statusCode:c,message:s?void 0:e.operation?.responses?.errors?.[c]?.description??ee?.[c]??`Error while processing the request`}}},St=async({block:e,buildStepFunction:t=g.build,virtualPaginateResultFn:n=gt})=>{let r=e.operation?.steps||{},i={...e},a=Object.keys(r),o=ht(e,ue),s={hasFatalError:!1,errorStatusCode:null},c={block:e,buildStepFunction:t,virtualPaginateResultFn:n};for(let[e,t]of a.entries())i=await bt(t,e,r,i,s,c);let l=e.operation?.result?Ct(e.operation.result,i):void 0,u=e.operation?.cursor.enabled?n(l,o,r,i.nextCursor):void 0;return xt(e,i,s,l,u)},Ct=(e,t)=>n(e)?D(e,t):E(e,t),Z=({block:e,stepId:t,successful:n,functionOutput:r,skipped:i,message:a})=>({...e,steps:{...e.steps,[t]:{successful:n??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:i,message:a}}}),Q=async t=>{let{pathParams:n={},queryParams:a={},body:o={},headers:s={},parseConnector:c=z,parseOperationInputsFn:l=V,createBlockContextFn:u=K,createBlockFn:d=O,runStepOperationFn:f=X,getOperationFromUrlFn:p=A,getOperationForRefreshAuthenticationFn:m=H,getTestOperationsFn:h=Ze,mode:g,account:_,connector:v,getHttpClient:y,logger:b,category:x,...S}=t,C=_.authConfigKey,w=_.environment??`production`,ee=_.secureId,te=_.projectSecureId,T=_.credentials,E=u({category:x??`action`,connectorKey:_.providerKey,connectorVersion:_.providerVersion,authConfigKey:C,environment:w,accountSecureId:ee,projectSecureId:te}),D;try{D=r(v)?c(v):v}catch{throw new Ue(E,`Error while parsing connector`)}let k={connector:D,context:E,credentials:T,logger:b,getHttpClient:y};if(g===`operation_id`){let{operationId:t}=S,r=se(D,t);if(e(r))throw new G(E,`No matching operation found`);return await $({operation:r,blockContext:E,queryParams:a,pathParams:n,body:o,headers:s,parseOperationInputsFn:l,createBlockFn:d,createBlockParams:k,runStepOperationFn:f})}else if(g===`test_operations`){let t=h(D,C,w);if(e(t)||t.length===0)return wt(d,k);E.operationType=`test`;for(let n of t){let t=await d({...k,inputs:void 0,operation:n.operation,nextCursor:void 0}),r=i(n.condition)?ne(n.condition,t):!0;if(!r)continue;let a=await f({block:t});if((e(a?.response?.successful)||!a.response.successful)&&n.required)return b?.error({code:`TestOperationFailed`,message:`Test operation "${n.operation.id}" failed with error: ${a?.response?.message}`}),Tt(d,k)}return wt(d,k)}else if(g===`refresh_authentication`){let t=m(D,C,w);if(e(t))throw new G(E,`No matching operation found`);return await $({operation:t.operation,blockContext:E,queryParams:a,pathParams:t.params,body:o,headers:s,parseOperationInputsFn:l,createBlockFn:d,createBlockParams:k,runStepOperationFn:f})}else if(g===`path`){let{path:t,method:n}=S,r=p(D,t,n);if(e(r))throw new G(E,`No matching operation found`);return await $({operation:r.operation,blockContext:E,queryParams:a,pathParams:r.params,body:o,headers:s,parseOperationInputsFn:l,createBlockFn:d,createBlockParams:k,runStepOperationFn:f})}else return Tt(d,k)},$=async e=>{let{operation:t,blockContext:n,queryParams:r,pathParams:i,body:a,headers:o,parseOperationInputsFn:s,createBlockFn:c,createBlockParams:l,runStepOperationFn:u}=e;n.operationType=t.operationType,n.schema=t.schema?.key;let d=Et(r,n),f;try{f=s(t,{path:i,query:r,body:a,headers:o})}catch{throw new We(n,`Error while parsing operation inputs`)}let p=await c({...l,inputs:f,operation:t,nextCursor:d});return await u({block:p})},wt=async(e,t)=>{let n=await e({...t,inputs:void 0,operation:void 0,nextCursor:void 0});return{...n,response:{successful:!0,statusCode:200}}},Tt=async(e,t)=>{let n=await e({...t,inputs:void 0,operation:void 0,nextCursor:void 0});return{...n,response:{successful:!1,statusCode:500}}},Et=(e,t)=>{let n=e?.next,r=i(n)&&t.operationType===`list`?b(n):void 0;if(r===null)throw new Ge(t,`Invalid cursor.`);return r},Dt=async({operationId:e,account:t,connector:n,pathParams:r={},queryParams:i={},body:a={},headers:o={},logger:s,getHttpClient:c,parseConnector:l=z,parseOperationInputsFn:u=V,createBlockContextFn:d=K,createBlockFn:f=O,runStepOperationFn:p=X})=>Q({mode:`operation_id`,operationId:e,account:t,connector:n,pathParams:r,queryParams:i,body:a,headers:o,logger:s,getHttpClient:c,parseConnector:l,parseOperationInputsFn:u,createBlockContextFn:d,createBlockFn:f,runStepOperationFn:p}),Ot=async({account:e,connector:t,category:n,path:r,method:i=`get`,queryParams:a={},body:o,headers:s,logger:c,getHttpClient:l,parseConnector:u=z,getOperationFromUrlFn:d=A,getOperationForRefreshAuthenticationFn:f=H,parseOperationInputsFn:p=V,createBlockContextFn:m=K,createBlockFn:h=O,runStepOperationFn:g=X})=>{let _=kt(r),v=_?await Q({mode:`refresh_authentication`,account:e,connector:t,getOperationForRefreshAuthenticationFn:f,parseConnector:u,logger:c,getHttpClient:l,parseOperationInputsFn:p,createBlockContextFn:m,createBlockFn:h,runStepOperationFn:g}):await Q({mode:`path`,account:e,category:n,connector:t,path:r,method:i,queryParams:a,body:o,headers:s,getOperationFromUrlFn:d,parseConnector:u,logger:c,getHttpClient:l,parseOperationInputsFn:p,createBlockContextFn:m,createBlockFn:h,runStepOperationFn:g});return v},kt=e=>e===Ye,At=async({account:e,connector:t,logger:n,getHttpClient:r,parseConnector:i=z,getTestOperationsFn:a=Ze,createBlockContextFn:o=K,createBlockFn:s=O,runStepOperationFn:c=X})=>{let l=await Q({mode:`test_operations`,account:e,connector:t,logger:n,getHttpClient:r,parseConnector:i,getTestOperationsFn:a,createBlockContextFn:o,createBlockFn:s,runStepOperationFn:c});return l?.response?.successful??!1};export{W as ConnectSDKError,Ye as REFRESH_TOKEN_OPERATION_PATH,O as createBlock,Xe as executeStepFunction,Ke as getActionsMeta,qe as getActionsMetaFromConnectors,A as getOperationFromUrl,Be as getRefreshTokenExpiresIn,ze as getTokenExpiresIn,k as loadConnector,V as parseOperationInputs,z as parseYamlConnector,Q as runAction,Dt as runConnectorAction,Ot as runConnectorOperation,X as runStepOperation,At as runTestOperations,Re as supportsRefreshAuthentication,Ve as validateYamlConnector};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/connect-sdk",
3
- "version": "1.59.2",
3
+ "version": "1.60.0",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",