@stackone/core 4.2.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,__name=(e,n)=>t(e,`name`,{value:n,configurable:!0}),n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,__copyProps=(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},__toESM=(n,r,a)=>(a=n==null?{}:e(i(n)),__copyProps(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let o=require("@stackone/utils"),s=require("@stackone/expressions"),c=require("@stackone/transport"),l=require("@aws-sdk/client-lambda"),u=require("node:stream"),d=require("mime-types");d=__toESM(d);let f=require("saml"),p=require("uuid"),m=require("@stackone/redaction"),h=require("node:crypto"),g=require("jose"),_=require("form-data");_=__toESM(_);const v=[`context`,`inputs`,`steps`,`intermediateSteps`,`iterator`,`result`],buildExpressionContext=(e,t={})=>{let n=t.includeCredentials??e.context?.flowType===`refresh_authentication`,r=v.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{});return n&&`credentials`in e&&(r.credentials=e.credentials),r},y={hris:{title:`HRIS`,key:`hris`,description:`Human Resource Information System`},crm:{title:`CRM`,key:`crm`,description:`Customer Relationship Management`},ats:{title:`ATS`,key:`ats`,description:`Applicant Tracking System`},lms:{title:`LMS`,key:`lms`,description:`Learning Management System`},marketing:{title:`Marketing`,key:`marketing`,description:`Marketing`},filestorage:{title:`File Storage`,key:`filestorage`,description:`File Storage`},iam:{title:`IAM`,key:`iam`,description:`Identity and Access Management`},internal:{title:`Internal`,key:`internal`,description:`Category for internal actions`},action:{title:`Action`,key:`action`,description:`Action`}},getCategoryDetails=e=>y[e.toLowerCase()]??null,isValidCategory=e=>!!y[e.toLowerCase()],b=(0,o.encodeToBase64)(`so1!`),x=RegExp(`(?<!\\\\):`,`g`),S=RegExp(`(?<!\\\\),`,`g`);var C=class CoreError extends Error{constructor({category:e,name:t,type:n,context:r,message:i}){super(i),this.name=t??`CoreError`,this.type=n,this.category=e,this.context=r,Error.captureStackTrace&&Error.captureStackTrace(this,CoreError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.category}-${this.name} [${this.type}]${e}`}},BaseCompositeIdError=class extends C{constructor(e,t,n){super({category:`CompositeId`,name:t??`BaseCompositeIdError`,type:e,message:n})}},CompositeIdMissingHeaderError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_MISSING_HEADER_ERROR`,`CompositeIdMissingHeaderError`,e??`Invalid compositeId, missing header`)}},CompositeIdMissingBodyError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_MISSING_BODY_ERROR`,`CompositeIdMissingBodyError`,e??`Invalid compositeId, missing body`)}},CompositeIdUnknownIdentifierError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_UNKNOWN_IDENTIFIER_ERROR`,`CompositeIdUnknownIdentifierError`,e??`Invalid compositeId, unknown identifier`)}},CompositeIdUnsupportedVersionError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_UNSUPPORTED_VERSION_ERROR`,`CompositeIdUnsupportedVersionError`,e??`Invalid compositeId, unsupported version`)}};const isSingleIdentifier=e=>!(0,o.isMissing)(e)&&`value`in e&&e.value!==void 0,isMultipleIdentifier=e=>!(0,o.isMissing)(e)&&`identifiers`in e&&e.identifiers!==void 0,encodeCompositeId=(e,t={version:1})=>{if(t.version===1)return encodeIdV1(getComposedIdV1(e,t.aliases));throw new CompositeIdUnsupportedVersionError(`Cannot generate ID, unsupported version number: ${t.version}`)},decodeCompositeId=(e,t={version:1})=>{let n=decodeId(e,t),r={};return n&&n.split(S).forEach(e=>{let[n,i]=e.split(x),a=getOriginalKey(n,t.aliases??{});r[a]=unescapeValue(i)}),r},getComposedIdV1=(e,t={})=>{if(isSingleIdentifier(e))return getSingleIdentifierString({identifier:e,compositeIdAliases:t,isSoleIdentifier:!0});if(isMultipleIdentifier(e))return e.identifiers.map(e=>getSingleIdentifierString({identifier:e,compositeIdAliases:t,isSoleIdentifier:!1})).join(`,`);throw new CompositeIdUnknownIdentifierError},getSingleIdentifierString=({identifier:e,compositeIdAliases:t,isSoleIdentifier:n})=>[n?`id`:t[e.key]||e.key,escapeValue(e.value)].filter(Boolean).join(`:`),getOriginalKey=(e,t)=>Object.keys(t).find(n=>t[n]===e)??e,decodeId=(e,t)=>{if(t.version===1)return decodeIdV1(e);throw new CompositeIdUnsupportedVersionError(`Cannot decode ID, unsupported version number: ${t.version}`)},encodeIdV1=e=>`${b}${(0,o.encodeToBase64)(e)}`,decodeIdV1=e=>{if(!e.startsWith(b))throw new CompositeIdMissingHeaderError(`Trying to decode an ID without the header: ${e}`);let t=e.split(b)[1];if(!t)throw new CompositeIdMissingBodyError(`Trying to decode an ID without a body: ${e}`);return(0,o.decodeFromBase64)(t)},escapeValue=e=>[`,`,`:`].reduce((e,t)=>e.replace(t,`\\`+t),e),unescapeValue=e=>[`,`,`:`].reduce((e,t)=>{let n=`\\`+t;return e.replace(RegExp(`\\\\`+n,`g`),t)},e),isCompositeId=e=>(0,o.isMissing)(e)?!1:e.startsWith(b),w=/\$\{([^}]+)\}/,T=`must be a bare JEXL expression and must not contain '{{', '}}', or an interpolation`,isBareJexl=e=>!e.includes(`{{`)&&!e.includes(`}}`)&&!w.test(e),computeDataSyncFingerprint=e=>{let{incremental:t}=e;return(0,o.getContentHash)({indexField:Array.isArray(e.indexField)?e.indexField:[e.indexField],incremental:t?{type:t.type,iteratorKey:t.iterator.key,iteratorIn:t.iterator.in,format:`format`in t?t.format:null}:null})},evaluateExternalAccountIdExtractor=(e,t)=>{let n=e.events?.externalAccountIdExtractor;if((0,o.isMissing)(n)||typeof n.result!=`string`||n.result.trim().length===0)return;let r=(0,s.safeEvaluate)(`{{${n.result.trim()}}}`,t);if(!(0,o.isMissing)(r)){if(typeof r==`string`){let e=r.trim();return e.length>0?e:void 0}if(typeof r==`number`||typeof r==`bigint`||typeof r==`boolean`)return String(r)}},resolveEvents=(e,t)=>{if(e===void 0)return[t.body];if((0,o.notMissing)(e)&&typeof e!=`string`)throw Error(`events.router.itemsPath must be a string, received ${typeof e}`);let n=(0,o.notMissing)(e)?e.trim():``;if(n.length===0)throw Error(`events.router.itemsPath is declared but must not be blank`);if(!isBareJexl(n))throw Error(`Failed to evaluate events.router.itemsPath: ${n}. It ${T}`);let r;try{r=(0,s.evaluate)(`{{${n}}}`,t,{throwOnEvalError:!0})}catch(e){throw Error(`Failed to evaluate events.router.itemsPath: ${n}. ${e.message}`)}if((0,o.isMissing)(r))throw Error(`Failed to evaluate events.router.itemsPath: ${n}. The path resolved to nothing. Check it against the delivery payload, and put rules that match the whole delivery under events.router.delivery`);if(!Array.isArray(r))throw Error(`Failed to evaluate events.router.itemsPath: ${n}. It did not resolve to a list of events`);return r},firstMatch=(e,t)=>{for(let n of e){if(typeof n.when!=`string`)throw Error(`events.router rule when must be a string, received ${typeof n.when}`);let e=n.when.trim();if(e.length===0)continue;let r=(0,s.safeEvaluate)(`{{${e}}}`,t);if(r===null||r===!1||r===void 0)continue;let i=(0,o.isMissing)(n.then.input)?void 0:Object.fromEntries(Object.entries(n.then.input).map(([e,n])=>{if(typeof n!=`string`)throw Error(`events.router rule input ${e} must be a string, received ${typeof n}`);let r=n.trim();if(r.length===0)return[e,void 0];try{return[e,(0,s.evaluate)(`{{${r}}}`,t)]}catch(t){throw Error(`Failed to evaluate events.router rule input ${e}: ${r}. ${t.message}`)}}));return{action:n.then.action,input:i,event:t.event,eventIndex:t.eventIndex}}},evaluateEventRouter=(e,t)=>{let n=e.events?.router;if((0,o.isMissing)(n))return{matches:[],totalEvents:0};if((0,o.notMissing)(n.delivery)){let e=firstMatch(n.delivery,{...t,event:t.body,eventIndex:0});if((0,o.notMissing)(e))return{matches:[e],totalEvents:1}}let r=resolveEvents(n.itemsPath,t),i=[];return r.forEach((e,r)=>{let a=firstMatch(n.rules,{...t,event:e,eventIndex:r});(0,o.notMissing)(a)&&i.push(a)}),{matches:i,totalEvents:r.length}},E={email:/^[^\s@]+@(?=[^\s@]+\.[^\s@])[^\s@]+$/,url:/^https?:\/\/[^\s/?#]+(?:[/?#]\S*)?$/,uri:/^[a-zA-Z][a-zA-Z0-9+.-]*:\S+$/,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,date:/^\d{4}-\d{2}-\d{2}$/,datetime:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}(?::?\d{2})?)?$/},D={employment_status:[`active`,`inactive`,`terminated`,`pending`,`leave`],employment_type:[`full_time`,`part_time`,`contractor`,`intern`,`temporary`],gender:[`male`,`female`,`non_binary`,`other`,`prefer_not_to_say`],marital_status:[`single`,`married`,`divorced`,`widowed`,`domestic_partnership`]},getInputEnumValues=e=>D[e],isValidEnumRef=e=>e in D,O=[`preview`,`beta`,`ga`,`deprecated`,`internal`],k=[`auth`,`downstream-change`,`bug-fix`,`new-actions`],A=[`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`test`,`event`,`unknown`],j=[`read`,`write`,`delete`,`search`,`execute`],M=[`native`,`unified`],N=[`body`,`query`,`path`,`headers`],P=[`email`,`url`,`uuid`,`date`,`datetime`,`uri`],F=[`string`,`number`,`boolean`,`datetime_string`,`object`,`enum`],I=[`sync`,`async`],L=(0,o.zStrictObject)({r:o.z.record(o.z.string(),(0,o.zStrictObject)({n:o.z.number().optional().nullable(),c:o.z.string().optional().nullable(),p:o.z.number().optional().nullable()})),v:o.z.number(),t:o.z.number()}),R=(0,o.zStrictObject)({remote:o.z.record(o.z.string(),(0,o.zStrictObject)({pageNumber:o.z.number().optional(),providerPageCursor:o.z.string().optional(),position:o.z.number().optional()})),version:o.z.number(),timestamp:o.z.number()}),minifyCursor=e=>(0,o.encodeToBase64)(JSON.stringify(minifyCursorObject(e))),minifyCursorObject=e=>{let{remote:t,version:n,timestamp:r}=e;return{r:Object.fromEntries(Object.entries(t).map(([e,{pageNumber:t,providerPageCursor:n,position:r}])=>[e,{n:t,c:n,p:r}])),v:n,t:r}},expandCursor=e=>{try{if((0,o.isString)(e)){let t=(0,o.decodeFromBase64)(e),n=JSON.parse(t);return expandCursorObject(L.parse(n))}else return R.parse(e),e}catch{return null}},expandCursorObject=e=>{let{r:t,v:n,t:r}=e;return{remote:Object.fromEntries(Object.entries(t).map(([e,{n:t,c:n,p:r}])=>[e,{pageNumber:t,providerPageCursor:n,position:r}])),version:n,timestamp:r}},areCursorsEqual=(e,t)=>{let n=typeof e==`string`?expandCursor(e):e,r=typeof t==`string`?expandCursor(t):t;if(n===null||r===null)return n===r;let{timestamp:i,...a}=n,{timestamp:s,...c}=r;return(0,o.getContentHash)(a)===(0,o.getContentHash)(c)},isCursorEmpty=({cursor:e,ignoreStepIndex:t})=>(0,o.isMissing)(e)?!0:Object.keys(e?.remote??{}).reduce((n,r)=>{let i=e?.remote?.[r];return((0,o.isMissing)(t)||r!==t.toString())&&(n=n&&(0,o.isMissing)(i.pageNumber)&&(0,o.isMissing)(i.position)&&(0,o.isMissing)(i.providerPageCursor)),n},!0),updateCursor=({cursor:e,stepIndex:t,pageNumber:n,providerPageCursor:r,position:i})=>{let a={pageNumber:n??void 0,providerPageCursor:r??void 0,position:i??void 0},s=(0,o.isMissing)(n)&&(0,o.isMissing)(r)&&(0,o.isMissing)(i);return(0,o.isMissing)(e)?{remote:s?{}:{[t]:a},version:2,timestamp:Date.now()}:s?(delete e.remote[t],e):{...e,remote:{...e.remote,[t]:a}}},isCoreError=e=>e instanceof C;function stripPaginationParams(e,t){let n=getPaginationKeys(t);if(n.length===0)return e;let r=getIteratorLocation(t);if(!r)return e;let i=e[r];if(!i||typeof i!=`object`)return e;let a={...i};for(let e of n)delete a[e];return{...e,[r]:a}}function getPaginationKeys(e){switch(e.type){case`cursor`:return[e.iterator.key];case`offset`:{let t=e;return[t.iterator.offsetKey,t.iterator.limitKey]}case`page`:{let t=e,n=[t.iterator.pageKey];return t.iterator.pageSizeKey&&n.push(t.iterator.pageSizeKey),n}default:return[]}}function getIteratorLocation(e){if(`iterator`in e&&typeof e.iterator==`object`&&e.iterator!==null)return e.iterator.in}function stripIncrementalParams(e,t){if(!t)return e;let{key:n,in:r}=t.iterator,i=e[r];if(!i||typeof i!=`object`)return e;let a={...i};return delete a[n],{...e,[r]:a}}const z={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},B={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},V={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},H={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},browserUseStepFunction=async()=>{throw Error(`browser_use step function cannot be executed synchronously — actions using this step must have executionMode: "async" so they are dispatched to the Temporal workflow runtime`)},U=o.z.object({startUrl:o.z.string().url().meta({description:`URL where the browser session begins.`}),systemPrompt:o.z.string().optional().meta({description:`Author-defined preamble, persona, and guardrails applied to every invocation.`}),viewport:(0,o.zStrictObject)({width:o.z.number().int().positive().meta({description:`Viewport width in pixels.`}),height:o.z.number().int().positive().meta({description:`Viewport height in pixels.`})}).optional().meta({description:`Browser viewport dimensions.`}),locale:o.z.string().optional().meta({description:`Locale the browser session runs in.`}),budgets:(0,o.zStrictObject)({maxDurationMs:o.z.number().int().positive().meta({description:`Maximum task duration in milliseconds.`}),maxSteps:o.z.number().int().positive().meta({description:`Maximum number of steps the agent may take.`})}).meta({description:`Execution limits the task must run within.`}),auth:(0,o.zStrictObject)({sensitiveKeys:o.z.array(o.z.string().min(1)).optional().meta({description:`Credential keys masked from the LLM and substituted only at the typing layer.`}),requiresSession:o.z.boolean().optional().meta({description:`Reserved for tasks that need a pre-authenticated browser session rather than form substitution. Not yet in use.`}),allowedDomains:o.z.array(o.z.string().min(1)).optional().meta({description:`Overrides the default allowed-domains policy, for auth flows that cross a domain boundary.`})}).optional().meta({description:`Credential handling for the browser task.`})}),W=o.z.unknown(),G=(0,o.zStrictObject)({lambdaName:o.z.string().meta({description:`Name or ARN of the Lambda function to invoke.`}),region:o.z.string().optional().meta({description:`AWS region the Lambda function runs in.`}),endpoint:o.z.string().optional().meta({description:`Custom Lambda service endpoint URL to call instead of the default.`}),invocationType:o.z.enum([`RequestResponse`,`Event`,`DryRun`]).optional().meta({description:"How the Lambda is invoked. `RequestResponse` waits synchronously for the Lambda response, `Event` fires asynchronously and returns no response body, and `DryRun` validates parameters and permissions without invoking the function."}),qualifier:o.z.string().optional().meta({description:`Function version or alias to invoke.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Payload field name.`}),value:o.z.unknown().meta({description:`Payload field value. Supports expressions.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the field only when it evaluates true.`})}).array().optional().meta({description:`Key/value pairs combined into the JSON payload sent to the Lambda function`}),dataKey:o.z.string().optional().meta({description:`Path to the field in the Lambda response to extract as data.`})}),K=(0,o.zStrictObject)({data:o.z.unknown().optional().meta({description:"The parsed Lambda response payload, or the value at `dataKey` when `dataKey` is set."}),raw:o.z.unknown().optional().meta({description:"The full Lambda invocation result, including the parsed `payload`, `statusCode`, and `executedVersion`."}),statusCode:o.z.number().meta({description:`HTTP status code of the Lambda invocation.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`}),executedVersion:o.z.string().optional().meta({description:`Version of the Lambda function that was invoked.`})}).optional(),ee=(0,o.zStrictObject)({strategy:o.z.literal(`aws4`),service:o.z.string(),region:o.z.string().optional()}),q=(0,o.zStrictObject)({strategy:o.z.literal(`hmac`),algorithm:o.z.enum([`sha1`,`sha256`,`sha512`]).optional(),headerName:o.z.string().optional(),prefix:o.z.string().optional(),dateFormat:o.z.enum([`iso8601`,`rfc2822`]).optional(),includeHost:o.z.boolean().optional(),includeBodyHash:o.z.boolean().optional(),outputFormat:o.z.enum([`header`,`basic`]).optional(),username:o.z.string().optional()}),J=o.z.discriminatedUnion(`strategy`,[ee,q]),te=(0,o.zStrictObject)({type:o.z.literal(`none`),signing:J.optional(),redirectUri:o.z.string().optional()}),Y=(0,o.zStrictObject)({type:o.z.literal(`basic`),username:o.z.string().optional(),password:o.z.string().optional(),encoding:o.z.string().optional(),redirectUri:o.z.string().optional()}),X=(0,o.zStrictObject)({type:o.z.literal(`bearer`),token:o.z.string(),includeBearer:o.z.boolean().optional().default(!0),redirectUri:o.z.string().optional()}),ne=new Set([`accessToken`,`refreshToken`,`idToken`,`clientId`,`clientSecret`,`authentication_config_key`,`environment`]),re=(0,o.zStrictObject)({type:o.z.literal(`oauth2`),authorizationUrl:o.z.string().optional(),redirectUri:o.z.string().optional(),authorizationParams:o.z.record(o.z.string(),o.z.string()).optional(),tokenUrl:o.z.string().optional(),tokenParams:o.z.record(o.z.string(),o.z.string()).optional(),tokenExpiresIn:o.z.number().optional(),tokenRefreshExpiresIn:o.z.number().optional(),token:o.z.string(),includeBearer:o.z.boolean().optional().default(!0),scopes:o.z.string().optional(),scopeDelimiter:o.z.string().optional(),customHeaders:o.z.record(o.z.string(),o.z.string()).optional(),pkce:o.z.boolean().optional(),additionalTokenFields:o.z.record(o.z.string(),o.z.string().optional()).optional(),callbackParams:o.z.record(o.z.string(),o.z.string().min(1)).superRefine((e,t)=>{for(let[n,r]of Object.entries(e))ne.has(r)&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[n],message:`callbackParams must not target reserved credential key "${r}"`})}).optional(),issuer:o.z.string().optional(),tokenResponse:(0,o.zStrictObject)({acceptTokenTypes:o.z.array(o.z.string()).optional(),accessToken:o.z.string().min(1).optional(),refreshToken:o.z.string().min(1).optional()}).optional()}),Z=o.z.discriminatedUnion(`type`,[te,Y,X,re]),ie=(0,o.zStrictObject)({certs:o.z.string().array().optional().meta({description:`PEM-encoded client certificates for mutual TLS. Each entry is a raw or base64-encoded PEM certificate.`}),keys:o.z.string().array().optional().meta({description:`PEM-encoded client private keys for mutual TLS. Each entry is a raw or base64-encoded PEM private key.`})}).optional(),ae=o.z.object({baseUrl:o.z.string().optional().meta({description:`Overrides the connector's base URL for the download.`}),url:o.z.string().meta({description:`Download endpoint path appended to the base URL.`}),method:o.z.enum(c.HttpMethods).optional().default(`get`).meta({description:`HTTP method to use for the download.`}),authorization:Z.optional().meta({description:`Overrides the connector's default authentication for this request.`}),responseMode:o.z.enum([`buffer`,`stream`]).optional().default(`buffer`).meta({description:`How the file is returned: buffer downloads it fully into memory, stream returns a readable stream for piping to the client.`}),responseType:o.z.enum([`arraybuffer`,`blob`,`text`,`json`]).optional().default(`arraybuffer`).meta({description:`Underlying HTTP response type requested. Used only when responseMode is buffer.`}),encoding:o.z.enum([`base64`,`utf8`,`binary`,`raw`,`none`]).optional().default(`base64`).meta({description:`Encoding applied to the returned data when responseMode is buffer. Use none to return a raw Buffer.`}),response:(0,o.zStrictObject)({dataKey:o.z.string().optional().meta({description:`JSONPath to the file content within a JSON-wrapped response.`}),fileNameKey:o.z.string().optional().meta({description:`JSONPath to the filename within a JSON-wrapped response.`}),contentTypeKey:o.z.string().optional().meta({description:`JSONPath to the content type within a JSON-wrapped response.`}),contentType:o.z.string().optional().meta({description:"Fallback content type used when the JSON response exposes none to extract. `contentTypeKey` wins if it resolves."}),contentIsBase64:o.z.boolean().optional().default(!1).meta({description:`Whether the content in the JSON response is already base64 encoded.`}),urlKey:o.z.string().optional().meta({description:`JSONPath to a download URL in the response to follow for the file.`}),forwardAuth:o.z.boolean().optional().default(!1).meta({description:`Whether to forward authentication headers to the secondary download request when following urlKey.`})}).optional().meta({description:`Options for extracting file content from a JSON-wrapped response.`}),maxRedirects:o.z.number().optional().default(5).meta({description:`Maximum number of redirects to follow.`}),followRedirects:o.z.boolean().optional().default(!0).meta({description:`Whether to follow HTTP redirects.`}),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional().meta({description:`Remaps matching provider error responses to different statuses or messages.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the request parameter.`}),value:o.z.unknown().meta({description:`Value of the parameter. Supports expressions.`}),in:o.z.enum(c.RequestParameterLocations).meta({description:`Where to send the parameter: query, body, or headers.`}),spread:o.z.boolean().optional().meta({description:`Merges the value's object entries into the target location instead of setting a single named field.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the parameter only when it evaluates true.`}),arrayFormat:o.z.enum(c.QueryArrayFormats).optional().meta({description:`How array values are serialized in the query string: repeat, brackets, comma, or stringify.`})}).array().optional().meta({description:"Additional request parameters sent as query params, headers, or the request body, per each entry's `in`."})}),oe=(0,o.zStrictObject)({data:o.z.union([o.z.string(),o.z.instanceof(Buffer)]).optional().meta({description:'Downloaded file content. A string in the format set by the `encoding` input (base64 by default), or a raw binary Buffer when `encoding: "none"`. Absent when `responseMode: "stream"` (content is piped via the stream output instead).'}),raw:o.z.unknown().optional().meta({description:`The raw provider response before parsing.`}),statusCode:o.z.number().meta({description:`HTTP status code of the provider response.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`}),headers:o.z.record(o.z.string(),o.z.union([o.z.string(),o.z.array(o.z.string())])).optional().meta({description:`All response headers returned with the download.`}),contentDisposition:o.z.string().optional().meta({description:`Content-Disposition header value for the client to use.`}),fileMetadata:(0,o.zStrictObject)({contentType:o.z.string().optional().meta({description:`MIME type of the downloaded file.`}),contentLength:o.z.number().optional().meta({description:`Size of the file in bytes.`}),fileName:o.z.string().optional().meta({description:`Name of the downloaded file.`}),lastModified:o.z.string().optional().meta({description:`Last-modified timestamp reported for the file.`}),etag:o.z.string().optional().meta({description:`Entity tag identifying the file version.`})}).optional().meta({description:`File metadata extracted from response headers or a JSON-wrapped response.`}),finalUrl:o.z.string().optional().meta({description:`Final URL the file was downloaded from after redirects or a followed link.`})}).optional(),se=o.z.object({event:o.z.object({eventType:o.z.string().meta({description:`Name of the event type being emitted.`}),eventId:o.z.coerce.string().optional().meta({description:`Unique identifier for this event.`}),eventDate:o.z.coerce.string().optional().meta({description:`Timestamp for when the event occurred.`}),data:o.z.unknown().optional().meta({description:`Normalized payload carried by the event.`})}).optional().meta({description:`The event to emit.`})}),ce=o.z.record(o.z.string(),o.z.unknown()).meta({description:"The input parameters other than `event`, returned as the step output."}),sanitizeRaw=e=>{let t={};return e.status!=null&&(t.status=e.status),e.data!==void 0&&(t.data=e.data),e.headers!=null&&(t.headers=e.headers),e.requestUrl!=null&&(t.requestUrl=e.requestUrl),e.message!=null&&(t.message=e.message),t},isSerializedBuffer=e=>typeof e==`object`&&!!e&&e.type===`Buffer`&&Array.isArray(e.data),decodeBinaryBody=e=>{let t;if(Buffer.isBuffer(e)?t=e.toString(`utf8`):e instanceof ArrayBuffer?t=new TextDecoder().decode(new Uint8Array(e)):ArrayBuffer.isView(e)?t=new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):isSerializedBuffer(e)&&(t=Buffer.from(e.data).toString(`utf8`)),t===void 0)return e;try{return JSON.parse(t)}catch{return t}},decodeResponseBody=e=>({...e,data:decodeBinaryBody(e.data)}),isHttpLikeError=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`,extractTopLevelMessage=e=>{if(typeof e.message==`string`&&e.message.trim().length>0)return e.message},extractNestedErrorMessage=e=>{if(e.error!=null&&typeof e.error==`object`&&!Array.isArray(e.error)&&typeof e.error.message==`string`)return e.error.message;if(typeof e.error==`string`&&e.error.length>0)return e.error;if(typeof e.error_description==`string`&&e.error_description.length>0)return e.error_description},extractErrorMessage=(e,t)=>{let n=e.data;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=extractTopLevelMessage(n);if(e!=null)return e}if(typeof e.message==`string`&&e.message.length>0)return e.message;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=extractNestedErrorMessage(n);if(e!=null)return e}if(Array.isArray(n)&&n.length>0){let e=n[0];if(typeof e==`object`&&e&&!Array.isArray(e)){let t=e,n=extractTopLevelMessage(t)??extractNestedErrorMessage(t);if(n!=null)return n}}return typeof n==`string`&&n.length>0?n:t},buildStepErrorOutput=(e,t)=>{if(e instanceof c.HttpResponseError){let n=e.message,r=decodeResponseBody(e.response);return{block:t,successful:!1,errors:[(0,c.serializeHttpResponseError)(e)],output:{statusCode:r?.status??500,message:extractErrorMessage(r,n),data:r?.data,raw:sanitizeRaw(r)}}}if(isHttpLikeError(e)){let n=decodeResponseBody(e.response),r=e instanceof Error?e.message:`HTTP error: ${n.status??500}`;return{block:t,successful:!1,errors:[(0,c.serializeHttpResponseError)(e)],output:{statusCode:n.status??500,message:extractErrorMessage(n,r),data:n.data,raw:sanitizeRaw(n)}}}return e instanceof Error?{block:t,successful:!1,errors:[(0,c.serializeHttpResponseError)(e)],output:{statusCode:500,message:e.message}}:{block:t,successful:!1,errors:[(0,c.serializeHttpResponseError)(e)],output:{statusCode:500,message:String(e)}}},isAwsCredentials=e=>!!e&&typeof e.accessKeyId==`string`&&typeof e.secretAccessKey==`string`,buildLambdaClientConfig=({region:e,endpoint:t,credentials:n})=>({region:e,...t?{endpoint:t}:{},...isAwsCredentials(n)?{credentials:{accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey,sessionToken:typeof n.sessionToken==`string`?n.sessionToken:void 0}}:t?{credentials:{accessKeyId:`local`,secretAccessKey:`local`}}:{}}),defaultClientFactory=e=>new l.LambdaClient(e),invokeLambda=async({lambdaName:e,payload:t,region:n,endpoint:r,invocationType:i=`RequestResponse`,qualifier:a,credentials:o,clientFactory:s=defaultClientFactory})=>{let c=s(buildLambdaClientConfig({region:n,endpoint:r,credentials:o})),u=new l.InvokeCommand({FunctionName:e,InvocationType:i,Qualifier:a,Payload:t?Buffer.from(JSON.stringify(t)):void 0}),d=await c.send(u),f=d.Payload?Buffer.from(d.Payload).toString(`utf-8`):``,p;if(f.length===0)p=void 0;else try{p=JSON.parse(f)}catch{p=f}return{statusCode:d.StatusCode??200,payload:p,functionError:d.FunctionError,executedVersion:d.ExecutedVersion}},le=/\${[^}]+}/,isJsonPathLike=e=>{let t=e.trimStart();return t.startsWith(`$.`)||t.startsWith(`$[`)},hasExpressionMarker=e=>(0,s.isExpression)(e)||le.test(e)||isJsonPathLike(e),buildDataKeyExpression=e=>(0,s.isExpression)(e)||e.trimStart().startsWith(`$`)?e:`$.${e}`,ue=__name((e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`||!e)return e;try{let n=(0,s.evaluate)(buildDataKeyExpression(t),e);if(n!==void 0)return n}catch{}return e[t]},`resolveDataKey`),buildPayloadFromArgs=e=>{if(!(!e||e.length===0))return e.reduce((e,t)=>(e[t.name]=t.value,e),{})},codeExecutionLambdaStepFunction=async({block:e,params:t},n=invokeLambda)=>{let r=t?.args,i=Array.isArray(r)?r:void 0,isPlainObject=e=>typeof e==`object`&&!!e,a=i?i.filter(t=>{if(!isPlainObject(t))return!0;let n=t.condition;return typeof n!=`string`||(0,s.safeEvaluate)(n,e)===!0}).map(e=>isPlainObject(e)?{...e,condition:void 0}:e):void 0,o=t?.dataKey,c=typeof o==`string`&&!le.test(o),l=t?.qualifier,u=typeof l==`string`&&!hasExpressionMarker(l),d={...t?(0,s.safeEvaluateRecord)(i===void 0?t:{...t,args:a},e):{},...c?{dataKey:o}:{},...u?{qualifier:l}:{}},f;try{f=G.parse(d)}catch(t){return buildStepErrorOutput(t,e)}let{lambdaName:p,region:m,endpoint:h,invocationType:g,qualifier:_,args:v,dataKey:y}=f,b;try{b=await n({lambdaName:p,payload:buildPayloadFromArgs(v),region:m,endpoint:h,invocationType:g,qualifier:_,credentials:e.credentials})}catch(t){return buildStepErrorOutput(t,e)}if(b.functionError){let t=typeof b.payload==`object`&&b.payload!==null&&`errorMessage`in b.payload&&typeof b.payload.errorMessage==`string`?b.payload.errorMessage:`Lambda function error: ${b.functionError}`;return{block:e,successful:!1,errors:[{message:t,kind:`lambda_function_error`,functionError:b.functionError}],output:{statusCode:b.statusCode,message:t,data:b.payload,raw:b}}}return{block:e,successful:!0,output:{data:y?ue(b.payload,y):b.payload,raw:b,statusCode:b.statusCode,executedVersion:b.executedVersion}}},buildRequestContext=e=>({accountSecureId:e.context.accountSecureId,projectSecureId:e.context.projectSecureId,organizationId:e.context.organizationId,environment:e.context.environment,authConfigKey:e.context.authenticationType,provider:e.connector?.key,service:e.context.category,resource:e.connector?.key,action:e.action?.id}),downloadFileStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n}=t,r=n?n.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,i=t?(0,s.safeEvaluateRecord)({...t,args:r},e):{},a={...i,customErrors:t?.customErrors},{baseUrl:l,url:u,method:d,authorization:f,args:p,responseMode:m,responseType:h,encoding:g,response:_,maxRedirects:v,followRedirects:y}=ae.parse(a),b=i?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,x=p?(0,c.parseRequestParameters)(p):{query:{},body:{},headers:{}},S=typeof x?.body==`string`?void 0:x?.body,C=(0,c.createAuthorizationHeaders)((0,o.notMissing)(f)?f:Z.parse(b)),w={...x?.headers??{},...C},T=e.connector?.rateLimit,E=e.connector?.concurrency,D=T!==void 0||E!==void 0?{rateLimits:T,concurrency:E}:void 0,O=buildRequestContext(e);if(m===`stream`)return performStreamDownload({block:e,httpClient:e.httpClient,baseUrl:l??``,url:u,method:d,headers:w,queryParams:x?.query,body:S,maxRedirects:y?v:0,requestConfig:D,context:O,response:_,responseType:h,authHeaders:C});try{return{block:e,successful:!0,output:await performDownload({httpClient:e.httpClient,baseUrl:l??``,url:u,method:d,headers:w,queryParams:x?.query,body:S,responseType:h,encoding:g,response:_,maxRedirects:y?v:0,requestConfig:D,context:O,authHeaders:C})}}catch(t){return buildStepErrorOutput(t,e)}},performStreamDownload=async e=>{let{block:t,httpClient:n,baseUrl:r,url:i,method:a,headers:s,queryParams:c,body:l,maxRedirects:d,requestConfig:f,context:p,response:m,responseType:h,authHeaders:g}=e,_=`${r}${i}`;if(!_.startsWith(`http://`)&&!_.startsWith(`https://`))throw Error(`Invalid URL: "${_}". URL must be absolute (start with http:// or https://). Either provide a baseUrl or ensure url is a complete URL.`);if((0,o.notMissing)(m?.dataKey)||(0,o.notMissing)(m?.urlKey))try{let e=await performDownload({httpClient:n,baseUrl:r,url:i,method:a,headers:s,queryParams:c,body:l,responseType:h??`arraybuffer`,encoding:`none`,response:m,maxRedirects:d,requestConfig:f,context:p,authHeaders:g??{}}),_=Buffer.isBuffer(e.data)?e.data:Buffer.from(e.data),v={...e.fileMetadata,contentLength:_.length};return{block:t,successful:!0,streamOutput:{stream:u.Readable.from(_),headers:(0,o.notMissing)(v.contentType)?{"content-type":v.contentType}:{},contentDisposition:e.contentDisposition,fileMetadata:v}}}catch(e){return buildStepErrorOutput(e,t)}if(!n.requestStream)throw Error(`HTTP client does not support streaming. Either implement requestStream method or use responseMode: "buffer".`);try{let e=await n.requestStream({url:_,method:a,headers:s,queryParams:c,payload:l,maxRedirects:d,requestConfig:f,context:p}),r=extractFileMetadata(e.headers),i=buildContentDisposition(r);return{block:t,successful:!0,streamOutput:{stream:e.stream,headers:e.headers,contentDisposition:i,fileMetadata:r}}}catch(e){return buildStepErrorOutput(e,t)}},performDownload=async e=>{let{httpClient:t,baseUrl:n,url:r,method:i,headers:a,queryParams:o,body:s,responseType:c,encoding:l,response:u,maxRedirects:d,requestConfig:f,context:p,authHeaders:m}=e,h=`${n}${r}`;if(!h.startsWith(`http://`)&&!h.startsWith(`https://`))throw Error(`Invalid URL: "${h}". URL must be absolute (start with http:// or https://). Either provide a baseUrl or ensure url is a complete URL.`);let g=u?.urlKey||u?.dataKey?`json`:c,_=await t.request({url:h,method:i,headers:a,queryParams:o,payload:s,responseType:g===`json`?void 0:g,maxRedirects:d,requestConfig:f,context:p});if(u?.urlKey||u?.dataKey)return handleJsonResponse({httpClient:t,result:_,response:u,encoding:l,maxRedirects:d,requestConfig:f,context:p,authHeaders:m});let v=encodeFileData(_.data,l),y=extractFileMetadata(_.headers),b=buildContentDisposition(y);return{data:v,raw:_,statusCode:_?.status,message:_?.message,headers:_.headers,contentDisposition:b,fileMetadata:y,finalUrl:_?.requestUrl}},handleJsonResponse=async e=>{let{httpClient:t,result:n,response:r,encoding:i,maxRedirects:a,requestConfig:s,context:c,authHeaders:l}=e,u=n.data;if(r.urlKey){let e=extractValueByPath(u,r.urlKey);if(typeof e==`string`){let n=await t.request({url:e,method:`get`,headers:r.forwardAuth?l:{},responseType:`arraybuffer`,maxRedirects:a,requestConfig:s,context:c}),d=encodeFileData(n.data,i),f=extractFileMetadata(n.headers);if(r.fileNameKey){let e=extractValueByPath(u,r.fileNameKey);typeof e==`string`&&(f.fileName=e)}if(r.contentTypeKey){let e=extractValueByPath(u,r.contentTypeKey);typeof e==`string`&&(f.contentType=e)}(0,o.isMissing)(f.contentType)&&(0,o.notMissing)(r.contentType)&&(f.contentType=r.contentType);let p=buildContentDisposition(f);return{data:d,raw:n,statusCode:n?.status,message:n?.message,headers:n.headers,contentDisposition:p,fileMetadata:f,finalUrl:e}}}if(r.dataKey){let e=extractValueByPath(u,r.dataKey);if((0,o.isMissing)(e))throw Error(`No file content found at path: ${r.dataKey}`);let t;if(typeof e==`string`)t=r.contentIsBase64?i===`base64`?e:i===`none`?Buffer.from(e,`base64`):Buffer.from(e,`base64`).toString(i===`raw`?`binary`:i):encodeFileData(e,i);else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))t=encodeFileData(e,i);else throw Error(`Unexpected file content type at path: ${r.dataKey}`);let a={};if(r.fileNameKey){let e=extractValueByPath(u,r.fileNameKey);typeof e==`string`&&(a.fileName=e)}if(r.contentTypeKey){let e=extractValueByPath(u,r.contentTypeKey);typeof e==`string`&&(a.contentType=e)}(0,o.isMissing)(a.contentType)&&(0,o.notMissing)(r.contentType)&&(a.contentType=r.contentType);let s=buildContentDisposition(a);return{data:t,raw:n,statusCode:n?.status,message:n?.message,headers:n.headers,contentDisposition:s,fileMetadata:a}}throw Error(`JSON response handling requires either urlKey or dataKey to be specified`)},extractValueByPath=(e,t)=>{let n=(t.startsWith(`$.`)?t.slice(2):t).split(`.`),r=e;for(let e of n){if((0,o.isMissing)(r)||typeof r!=`object`)return;r=r[e]}return r},encodeFileData=(e,t)=>{if(t===`none`)return e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof e==`string`?Buffer.from(e):Buffer.from(JSON.stringify(e));if(t===`raw`)return typeof e==`string`?e:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?Buffer.from(e).toString(`binary`):JSON.stringify(e);if(typeof e==`string`)return t===`base64`?Buffer.from(e).toString(`base64`):e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){let n=Buffer.from(e);switch(t){case`base64`:return n.toString(`base64`);case`utf8`:return n.toString(`utf8`);default:return n.toString(`binary`)}}return JSON.stringify(e)},extractFileMetadata=e=>{let t=(0,o.isString)(e[`content-type`])?e[`content-type`]:void 0,n=(0,o.isString)(e[`content-length`])?e[`content-length`]:void 0,r=(0,o.isString)(e[`content-disposition`])?e[`content-disposition`]:void 0,i=(0,o.isString)(e[`last-modified`])?e[`last-modified`]:void 0,a=(0,o.isString)(e.etag)?e.etag:void 0,s=n?parseInt(n,10):void 0,c=extractFileName(r);return{contentType:t,contentLength:Number.isNaN(s)?void 0:s,fileName:c,lastModified:i,etag:a}},extractFileName=e=>{if(!e)return;let t=e.match(/filename\*=(?:UTF-8''|utf-8'')([^;\s]+)/i);if(t&&t[1])try{return decodeURIComponent(t[1])}catch{}let n=e.match(/filename=["']([^"']+)["']/);if(n&&n[1])return n[1];let r=e.match(/filename=([^;\s]+)/);if(r&&r[1])return r[1]},buildContentDisposition=e=>{let{fileName:t,contentType:n}=e,r=`attachment`;if(t)r=`attachment; filename="${t}"; filename*=UTF-8''${encodeURIComponent(t).replace(/['()]/g,escape)}`;else if(n){let e=getExtensionFromContentType(n);e&&(r=`attachment; filename="download.${e}"`)}return r},getExtensionFromContentType=e=>{let t=e.split(`;`)[0].trim().toLowerCase();return d.default.extension(t)||void 0},emitEventStepFunction=async({block:e,params:t})=>{let n=t?(0,s.safeEvaluateRecord)(t,e):{},{event:r}=se.parse(n);if(r&&e.emitEvent)try{await e.emitEvent({eventType:r.eventType,eventId:r.eventId,eventDate:r.eventDate,data:r.data})}catch(t){throw e.logger?.error({code:`EmitEventError`,message:`emitEvent callback failed: ${t.message}`}),t}else r&&!e.emitEvent&&e.logger?.warning({message:`emit_event step executed but no emitEvent callback provided on the block`});let{event:i,...a}=n;return{block:{...e},successful:!0,output:a}},de=o.z.object({stepsDataToGroup:o.z.array(o.z.string()).meta({description:`IDs of the steps whose output data should be grouped together.`}),isSingleRecord:o.z.boolean().optional().meta({description:`When true, returns a single record keyed by step ID, otherwise an array merged per key across steps.`})}),fe=o.z.object({data:o.z.unknown().meta({description:`The combined output data grouped from the referenced steps.`})}),groupDataStepFunction=async({block:e,params:t})=>{let{stepsDataToGroup:n,isSingleRecord:r}=de.parse(t),i=n.reduce((t,n)=>{let i=e.steps?.[n]?.output?.data;return i?r?{...t,[n]:{...i}}:(Object.keys(i).forEach(e=>{t[e]={...(0,o.notMissing)(t[e])?t[e]:{},[n]:{...i[e]}}}),t):t},{});return{block:{...e},successful:!0,output:{data:r?i:Object.values(i)}}},pe=__name(async({block:e})=>{let t=e?.fieldConfigs,n=[],r=e.steps;if(!t||e?.debug?.custom_mappings===`disabled`||!r)return{block:e,successful:!0};let i=buildExpressionContext(e),a;if(Array.isArray(e.result)){let o=e.result.length;a=e.result.map((e,a)=>{let s=me(e,t,extractSingleRecordBlockStepData(r,o,a),i);return n.push(...s.errors||[]),s.record})}else{let o=me(e.result,t,r,i);a=o.record,n.push(...o.errors||[])}return{block:{...e,result:a},successful:!0,errors:Object.keys(n).length>0?n:void 0}},`mapFieldsStepFunction`),extractSingleRecordBlockStepData=(e,t,n)=>Object.entries(e).reduce((e,[r,i])=>{let a=i?.output?.data;return Array.isArray(a)&&a.length===t?e[r]={output:{data:a[n]}}:e[r]=i,e},{}),me=__name((e,t,n,r)=>{if(!e||!n)return{record:e};let i={...r,unified:{...e},...typeof n==`object`?n:{}},a={},o=[],s={...e};for(let n of t){let{error:t,value:r}=he(i,e.id,n);if(t){o.push(t);continue}n.custom?a[n.targetFieldKey]=r:s[n.targetFieldKey]=r}return{record:{...s,unified_custom_fields:Object.keys(a).length>0?a:void 0},errors:o.length>0?o:void 0}},`mapSingleRecord`),he=__name((e,t,n)=>{let{expression:r,targetFieldKey:i}=n;if(!r)return{error:{message:`Expression is empty`,id:t,targetField:i}};let a;try{a=(0,s.evaluate)(r,e)}catch{return{error:{message:`Invalid expression`,id:t,targetField:i}}}return a===void 0?{error:{message:`Expression returned no value`,id:t,targetField:i}}:{value:a}},`extractFieldValue`),getEnumMatcher=e=>{switch(e){case`country_alpha2code_by_alpha2code`:return o.getCountryAlpha2CodeByAlpha2Code;case`country_alpha3code_by_alpha3code`:return o.getCountryAlpha3CodeByAlpha3Code;case`country_code_by_country_code`:return o.getCountryCodeByCountryCode;case`country_name_by_country_name`:return o.getCountryNameByCountryName;case`country_name_by_alpha3code`:return o.getCountryNameByAlpha3Code;case`country_name_by_alpha2code`:return o.getCountryNameByAlpha2Code;case`country_name_by_country_code`:return o.getCountryNameByCountryCode;case`country_alpha3code_by_alpha2code`:return o.getCountryAlpha3CodeByAlpha2Code;case`country_alpha3code_by_country_name`:return o.getCountryAlpha3CodeByCountryName;case`country_alpha3code_by_country_code`:return o.getCountryAlpha3CodeByCountryCode;case`country_alpha2code_by_alpha3code`:return o.getCountryAlpha2CodeByAlpha3Code;case`country_alpha2code_by_country_name`:return o.getCountryAlpha2CodeByCountryName;case`country_alpha2code_by_country_code`:return o.getCountryAlpha2CodeByCountryCode;case`country_code_by_alpha2code`:return o.getCountryCodeByAlpha2Code;case`country_code_by_alpha3code`:return o.getCountryCodeByAlpha3Code;case`country_code_by_country_name`:return o.getCountryCodeByCountryName;case`country_subdivisions_by_alpha2code`:return o.getCountrySubDivisionsByAlpha2Code;case`country_subdivision_code_by_subdivision_name`:return o.getCountrySubDivisionCodeBySubDivisionName;case`country_alpha2code_by_citizenship`:return o.getCountryAlpha2CodeByCitizenship;case`country_subdivision_name_by_subdivision_code`:return o.getCountrySubDivisionNameBySubDivisionCode;case`document_file_format_from_extension`:return o.getDocumentFileFormatFromExtension;default:return}},ge=(0,o.zStrictObject)({targetFieldKey:o.z.string().meta({description:`Name of the output field to produce.`}),alias:o.z.string().optional().meta({description:`Alias for this field's component in composite identifiers. Not used for source lookup.`}),expression:o.z.string().optional().meta({description:`JEXL expression that computes the field's value.`}),values:o.z.unknown().optional().meta({description:`Inline values used to populate the field when no expression is given.`}),type:o.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]).meta({description:"Declared output type of the mapped value, where `enum` resolves through the matcher, `object` maps its nested `properties`, and primitives are cast by a later `typecast` step rather than here."}),array:o.z.boolean().default(!1).meta({description:`Whether the field holds an array of the given type.`}),custom:o.z.boolean().default(!1).meta({description:`Whether the field is a custom, non-unified field.`}),hidden:o.z.boolean().default(!1).meta({description:`Currently not in use.`}),enumMapper:(0,o.zStrictObject)({matcher:o.z.string().or((0,o.zStrictObject)({matchExpression:o.z.string().meta({description:`JEXL expression matched against the source value.`}),value:o.z.string().meta({description:`Enum value to use when the expression matches.`})}).array()).meta({description:`Either the name of a built-in matcher, or a list of match rules mapping source values to enum values.`})}).optional().meta({description:`Rules for mapping source values onto enum values.`}),properties:o.z.lazy(()=>ge).array().optional().meta({description:`Nested field mappings for object-typed fields.`}),requiredScopes:o.z.string().array().optional().meta({description:`Scopes that must be granted for the field to be included.`})}),_e=o.z.object({fields:ge.array().meta({description:`Field mapping definitions applied to the source data.`}),dataSource:o.z.string().meta({description:`Reference to the source data to transform.`}),externalSources:o.z.record(o.z.string(),o.z.string()).optional().meta({description:`Additional named data sources referenced by mapping expressions.`})}),ve=o.z.object({data:o.z.unknown().meta({description:`The mapped fields produced from the source data.`})}),mergeSourceWithState=(e,t)=>(0,o.isObject)(e)?{...t,...e}:e,mapFieldsStepFunction=async({block:e,params:t})=>{let n=[],{fields:r,dataSource:i,externalSources:a}=_e.parse(t),o=buildExpressionContext(e,{includeCredentials:!0}),c=(0,s.evaluate)(i,o);if(!r||!i||e?.debug?.custom_mappings===`disabled`||!c)return{block:e,successful:!0};let l=Object.keys(a??{})?.reduce((e,t)=>(e[t]=(0,s.evaluate)(a?.[t],o),e),{}),u;if(Array.isArray(c))u=c.map(e=>{let t=Q(r,{...e,external:l},o);return n.push(...t?.errors||[]),t?.record});else{let e=Q(r,{...c,external:l},o);u=e?.record,n.push(...e?.errors||[])}return{block:{...e},successful:!0,output:{data:u},errors:Object.keys(n).length>0?n:void 0}},handleObjectArrayFromValues=(e,t,n,r)=>{if(Array.isArray(e.values))return e.values.map(i=>{let a=evaluateExpressionsInObject(i,t),s=Q(e.properties,a,r);return(0,o.notMissing)(s?.errors)&&n.push(...s.errors),s?.record}).filter(Boolean)},handleObjectArrayFromExpression=(e,t,n,r,i)=>{if(e.expression)try{let t=(0,s.evaluate)(e.expression,n);if(Array.isArray(t))return t.map(t=>{let n=Q(e.properties,t,i);return(0,o.notMissing)(n?.errors)&&r.push(...n.errors),n?.record}).filter(Boolean);{let n=Q(e.properties,t,i);return(0,o.notMissing)(n?.errors)&&r.push(...n.errors),n?.record}}catch{r.push({message:`Invalid expression`,id:t?.id,targetField:e.targetFieldKey});return}},handleSingleObject=(e,t,n,r)=>{let i=(0,o.notMissing)(e.values)?e.values:t,a=Q(e.properties,i,r);return(0,o.notMissing)(a?.errors)&&n.push(...a.errors),a?.record},ye=__name((e,t,n,r,i)=>{if(!(0,o.isMissing)(e.properties))return e.array&&Array.isArray(e.values)?handleObjectArrayFromValues(e,n,r,i):e.array&&e.expression?handleObjectArrayFromExpression(e,t,n,r,i):handleSingleObject(e,t,r,i)},`handleObjectField`),Q=__name((e,t,n)=>{if(!t)return;let r=mergeSourceWithState(t,n),i={},a=[],o={};for(let s of e){let e;if(s.type===`object`){if(e=ye(s,t,r,a,n),e===void 0)continue}else{let{error:n,value:i}=extractFieldValue(r,t?.id,s);if(e=i,n){a.push(n);continue}}s.custom?i[s.targetFieldKey]=e:o[s.targetFieldKey]=e}let s=Object.keys(i).length>0?{unified_custom_fields:i}:{};return{record:{...o,...s},errors:a.length>0?a:void 0}},`mapSingleRecord`),evaluateExpressionsInObject=(e,t)=>{if(e==null)return e;if(typeof e==`string`){if((0,s.isValidExpression)(e))try{return(0,s.evaluate)(e,t)}catch{return e}return e}if(Array.isArray(e))return e.map(e=>evaluateExpressionsInObject(e,t));if(typeof e==`object`){let n={...e};for(let[e,r]of Object.entries(n))n[e]=evaluateExpressionsInObject(r,t);return n}return e},extractFieldValue=(e,t,n)=>{switch(n.type){case`string`:case`number`:case`boolean`:case`datetime_string`:return be(n,t,e);case`enum`:return evaluateEnumValue(n,t,e);default:return{error:{message:`Invalid type`,id:t,targetField:n.targetFieldKey}}}},be=__name((e,t,n)=>{if(!e.expression)return{error:{message:`Expression is empty`,id:t,targetField:e.targetFieldKey}};let r;try{r=(0,s.evaluate)(e.expression,n)}catch{return{error:{message:`Invalid expression`,id:t,targetField:e.targetFieldKey}}}return r===void 0?{error:{message:`Expression returned no value`,id:t,targetField:e.targetFieldKey}}:{value:r}},`evaluateValue`),evaluateEnumValue=(e,t,n)=>{let r=be(e,t,n),i=(0,o.notMissing)(r.value)?r.value:null;if(e.enumMapper===void 0)return{error:{message:`Enum mapper was not defined`,id:t,targetField:e.targetFieldKey}};let a=e.enumMapper.matcher;if((0,o.isString)(a)){let n=getEnumMatcher(a);return(0,o.notMissing)(n)?{value:{value:((0,o.notMissing)(i)?n(i):null)??`unmapped_value`,source_value:i}}:{error:{message:`The built-in matcher "${a}" is not supported`,id:t,targetField:e.targetFieldKey}}}for(let e of a){let{matchExpression:t,value:r}=e;if((0,s.evaluate)(t,n)===!0)return{value:{value:r,source_value:i}}}return{value:{value:`unmapped_value`,source_value:i}}},xe=o.z.object({baseUrl:o.z.string().optional().meta({description:`Overrides the connector's base URL for the MCP server.`}),url:o.z.string().optional().meta({description:`MCP server endpoint path.`}),method:o.z.enum([`tools/call`,`tools/list`]).default(`tools/call`).meta({description:"The MCP method to call. Either `tools/call` or `tools/list`."}),toolName:o.z.string().optional().meta({description:`Name of the tool to call. Required when method is tools/call.`}),timeout:o.z.number().int().positive().optional().meta({description:`Request timeout in milliseconds.`}),authorization:Z.optional().meta({description:`Overrides the connector's default authentication for this request.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the argument.`}),value:o.z.unknown().meta({description:`Value of the argument. Supports expressions.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the argument only when it evaluates true.`})}).array().optional().meta({description:`Arguments passed to the MCP tool call.`})}).refine(e=>e.method!==`tools/call`||!!e.toolName,{message:`The 'toolName' parameter is required when method is 'tools/call'`,path:[`toolName`]}),Se=(0,o.zStrictObject)({data:o.z.unknown().optional().meta({description:"The parsed MCP response. For `tools/call` it holds the tool result, for `tools/list` it holds the list of tools."}),raw:o.z.unknown().optional().meta({description:`The raw MCP response before parsing.`}),statusCode:o.z.number().meta({description:`Returns 200 for success, or 502 when the tool returns an error.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`})}).optional(),buildMcpClient=e=>new c.McpClient(e),buildToolArguments=e=>(e??[]).reduce((e,t)=>(e[t.name]=t.value,e),{}),parseJsonText=e=>{try{return JSON.parse(e)}catch{return e}},resolveToolData=e=>{if((0,o.notMissing)(e.structuredContent))return e.structuredContent;let[t,...n]=e.content;return n.length===0&&t?.type===`text`&&typeof t.text==`string`?parseJsonText(t.text):e.content},extractTextMessage=e=>e.content.find(e=>typeof e.text==`string`)?.text,mcpRequestStepFunction=async({block:e,params:t},n=buildMcpClient)=>{let r=t?.args,i=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?(0,s.safeEvaluateRecord)({...t,args:i},e):{},l;try{l=xe.parse(a)}catch(t){return buildStepErrorOutput(t,e)}let{baseUrl:u,url:d,method:f,toolName:p,timeout:m,authorization:h,args:g}=l,_=`${u??``}${d??``}`;if(!_)return buildStepErrorOutput(Error(`MCP server URL is missing: set the connector baseUrl or the step url parameter`),e);let v=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,y;try{y=(0,c.createAuthorizationHeaders)((0,o.notMissing)(h)?h:Z.parse(v??{type:`none`}))}catch(t){return buildStepErrorOutput(t,e)}let b=e.connector?.rateLimit,x=e.connector?.concurrency,S=n({serverUrl:_,headers:y,timeout:m,requestConfig:b!==void 0||x!==void 0?{rateLimits:b,concurrency:x}:void 0,context:buildRequestContext(e)});try{if(f===`tools/list`){let t=await S.listTools();return{block:e,successful:!0,output:{data:t.tools,raw:t,statusCode:200}}}if(!p)return buildStepErrorOutput(Error(`The 'toolName' parameter is required when method is 'tools/call'`),e);let t=await S.callTool({name:p,arguments:buildToolArguments(g)});if(t.isError){let n=extractTextMessage(t)??`MCP tool '${p}' returned an error`;return{block:e,successful:!1,errors:[{message:n,kind:`mcp_tool_error`,toolName:p}],output:{statusCode:502,message:n,data:resolveToolData(t),raw:t}}}return{block:e,successful:!0,output:{data:resolveToolData(t),raw:t,statusCode:200}}}catch(t){return buildStepErrorOutput(t,e)}finally{await S.close().catch(()=>void 0)}},generateSamlAssertion=async({cert:e,key:t,issuer:n,lifetime:r,clientId:i,nameId:a,tokenEndpoint:o,audience:s,nameIdentifierFormat:c,createSamlFn:l=e=>f.Saml20.create(e),sleepFn:u=e=>new Promise(t=>setTimeout(t,e))})=>{let d={api_key:i},m={cert:e,key:generatePrivateKey(t),issuer:n,lifetimeInSeconds:r,audiences:s,attributes:d,nameIdentifier:a,nameIdentifierFormat:c,recipient:o,sessionIndex:`_`+(0,p.v4)()},h=Buffer.from(l(m)).toString(`base64`);return await u(1e3),h},generatePrivateKey=e=>{let t=Buffer.from(e,`base64`).toString(`utf-8`).split(`###`);if(t.length!==2)throw Error(`Invalid private key`);let n=t[0];return Buffer.from(`-----BEGIN PRIVATE KEY-----
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,__name=(e,n)=>t(e,`name`,{value:n,configurable:!0}),n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,__copyProps=(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},__toESM=(n,r,a)=>(a=n==null?{}:e(i(n)),__copyProps(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let o=require("@stackone/utils"),s=require("@stackone/expressions"),c=require("@stackone/transport"),l=require("@aws-sdk/client-lambda"),u=require("node:stream"),d=require("mime-types");d=__toESM(d);let f=require("saml"),p=require("uuid"),m=require("@stackone/redaction"),h=require("node:crypto"),g=require("jose"),_=require("form-data");_=__toESM(_);const v=[`context`,`inputs`,`steps`,`intermediateSteps`,`iterator`,`result`],buildExpressionContext=(e,t={})=>{let n=t.includeCredentials??e.context?.flowType===`refresh_authentication`,r=v.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{});return n&&`credentials`in e&&(r.credentials=e.credentials),r},y={hris:{title:`HRIS`,key:`hris`,description:`Human Resource Information System`},crm:{title:`CRM`,key:`crm`,description:`Customer Relationship Management`},ats:{title:`ATS`,key:`ats`,description:`Applicant Tracking System`},lms:{title:`LMS`,key:`lms`,description:`Learning Management System`},marketing:{title:`Marketing`,key:`marketing`,description:`Marketing`},filestorage:{title:`File Storage`,key:`filestorage`,description:`File Storage`},iam:{title:`IAM`,key:`iam`,description:`Identity and Access Management`},internal:{title:`Internal`,key:`internal`,description:`Category for internal actions`},action:{title:`Action`,key:`action`,description:`Action`}},getCategoryDetails=e=>y[e.toLowerCase()]??null,isValidCategory=e=>!!y[e.toLowerCase()],b=(0,o.encodeToBase64)(`so1!`),x=RegExp(`(?<!\\\\):`,`g`),S=RegExp(`(?<!\\\\),`,`g`);var C=class CoreError extends Error{constructor({category:e,name:t,type:n,context:r,message:i}){super(i),this.name=t??`CoreError`,this.type=n,this.category=e,this.context=r,Error.captureStackTrace&&Error.captureStackTrace(this,CoreError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.category}-${this.name} [${this.type}]${e}`}},BaseCompositeIdError=class extends C{constructor(e,t,n){super({category:`CompositeId`,name:t??`BaseCompositeIdError`,type:e,message:n})}},CompositeIdMissingHeaderError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_MISSING_HEADER_ERROR`,`CompositeIdMissingHeaderError`,e??`Invalid compositeId, missing header`)}},CompositeIdMissingBodyError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_MISSING_BODY_ERROR`,`CompositeIdMissingBodyError`,e??`Invalid compositeId, missing body`)}},CompositeIdUnknownIdentifierError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_UNKNOWN_IDENTIFIER_ERROR`,`CompositeIdUnknownIdentifierError`,e??`Invalid compositeId, unknown identifier`)}},CompositeIdUnsupportedVersionError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_UNSUPPORTED_VERSION_ERROR`,`CompositeIdUnsupportedVersionError`,e??`Invalid compositeId, unsupported version`)}};const isSingleIdentifier=e=>!(0,o.isMissing)(e)&&`value`in e&&e.value!==void 0,isMultipleIdentifier=e=>!(0,o.isMissing)(e)&&`identifiers`in e&&e.identifiers!==void 0,encodeCompositeId=(e,t={version:1})=>{if(t.version===1)return encodeIdV1(getComposedIdV1(e,t.aliases));throw new CompositeIdUnsupportedVersionError(`Cannot generate ID, unsupported version number: ${t.version}`)},decodeCompositeId=(e,t={version:1})=>{let n=decodeId(e,t),r={};return n&&n.split(S).forEach(e=>{let[n,i]=e.split(x),a=getOriginalKey(n,t.aliases??{});r[a]=unescapeValue(i)}),r},getComposedIdV1=(e,t={})=>{if(isSingleIdentifier(e))return getSingleIdentifierString({identifier:e,compositeIdAliases:t,isSoleIdentifier:!0});if(isMultipleIdentifier(e))return e.identifiers.map(e=>getSingleIdentifierString({identifier:e,compositeIdAliases:t,isSoleIdentifier:!1})).join(`,`);throw new CompositeIdUnknownIdentifierError},getSingleIdentifierString=({identifier:e,compositeIdAliases:t,isSoleIdentifier:n})=>[n?`id`:t[e.key]||e.key,escapeValue(e.value)].filter(Boolean).join(`:`),getOriginalKey=(e,t)=>Object.keys(t).find(n=>t[n]===e)??e,decodeId=(e,t)=>{if(t.version===1)return decodeIdV1(e);throw new CompositeIdUnsupportedVersionError(`Cannot decode ID, unsupported version number: ${t.version}`)},encodeIdV1=e=>`${b}${(0,o.encodeToBase64)(e)}`,decodeIdV1=e=>{if(!e.startsWith(b))throw new CompositeIdMissingHeaderError(`Trying to decode an ID without the header: ${e}`);let t=e.split(b)[1];if(!t)throw new CompositeIdMissingBodyError(`Trying to decode an ID without a body: ${e}`);return(0,o.decodeFromBase64)(t)},escapeValue=e=>[`,`,`:`].reduce((e,t)=>e.replace(t,`\\`+t),e),unescapeValue=e=>[`,`,`:`].reduce((e,t)=>{let n=`\\`+t;return e.replace(RegExp(`\\\\`+n,`g`),t)},e),isCompositeId=e=>(0,o.isMissing)(e)?!1:e.startsWith(b),w=/\$\{([^}]+)\}/,T=`must be a bare JEXL expression and must not contain '{{', '}}', or an interpolation`,isBareJexl=e=>!e.includes(`{{`)&&!e.includes(`}}`)&&!w.test(e),computeDataSyncFingerprint=e=>{let{incremental:t}=e;return(0,o.getContentHash)({indexField:Array.isArray(e.indexField)?e.indexField:[e.indexField],incremental:t?{type:t.type,iteratorKey:t.iterator.key,iteratorIn:t.iterator.in,format:`format`in t?t.format:null}:null})},evaluateExternalAccountIdExtractor=(e,t)=>{let n=e.events?.externalAccountIdExtractor;if((0,o.isMissing)(n)||typeof n.result!=`string`||n.result.trim().length===0)return;let r=(0,s.safeEvaluate)(`{{${n.result.trim()}}}`,t);if(!(0,o.isMissing)(r)){if(typeof r==`string`){let e=r.trim();return e.length>0?e:void 0}if(typeof r==`number`||typeof r==`bigint`||typeof r==`boolean`)return String(r)}},resolveEvents=(e,t)=>{if(e===void 0)return[t.body];if((0,o.notMissing)(e)&&typeof e!=`string`)throw Error(`events.router.itemsPath must be a string, received ${typeof e}`);let n=(0,o.notMissing)(e)?e.trim():``;if(n.length===0)throw Error(`events.router.itemsPath is declared but must not be blank`);if(!isBareJexl(n))throw Error(`Failed to evaluate events.router.itemsPath: ${n}. It ${T}`);let r;try{r=(0,s.evaluate)(`{{${n}}}`,t,{throwOnEvalError:!0})}catch(e){throw Error(`Failed to evaluate events.router.itemsPath: ${n}. ${e.message}`)}if((0,o.isMissing)(r))throw Error(`Failed to evaluate events.router.itemsPath: ${n}. The path resolved to nothing. Check it against the delivery payload, and put rules that match the whole delivery under events.router.delivery`);if(!Array.isArray(r))throw Error(`Failed to evaluate events.router.itemsPath: ${n}. It did not resolve to a list of events`);return r},firstMatch=(e,t)=>{for(let n of e){if(typeof n.when!=`string`)throw Error(`events.router rule when must be a string, received ${typeof n.when}`);let e=n.when.trim();if(e.length===0)continue;let r=(0,s.safeEvaluate)(`{{${e}}}`,t);if(r===null||r===!1||r===void 0)continue;let i=(0,o.isMissing)(n.then.input)?void 0:Object.fromEntries(Object.entries(n.then.input).map(([e,n])=>{if(typeof n!=`string`)throw Error(`events.router rule input ${e} must be a string, received ${typeof n}`);let r=n.trim();if(r.length===0)return[e,void 0];try{return[e,(0,s.evaluate)(`{{${r}}}`,t)]}catch(t){throw Error(`Failed to evaluate events.router rule input ${e}: ${r}. ${t.message}`)}}));return{action:n.then.action,input:i,event:t.event,eventIndex:t.eventIndex}}},evaluateEventRouter=(e,t)=>{let n=e.events?.router;if((0,o.isMissing)(n))return{matches:[],totalEvents:0};if((0,o.notMissing)(n.delivery)){let e=firstMatch(n.delivery,{...t,event:t.body,eventIndex:0});if((0,o.notMissing)(e))return{matches:[e],totalEvents:1}}let r=resolveEvents(n.itemsPath,t),i=[];return r.forEach((e,r)=>{let a=firstMatch(n.rules,{...t,event:e,eventIndex:r});(0,o.notMissing)(a)&&i.push(a)}),{matches:i,totalEvents:r.length}},E={email:/^[^\s@]+@(?=[^\s@]+\.[^\s@])[^\s@]+$/,url:/^https?:\/\/[^\s/?#]+(?:[/?#]\S*)?$/,uri:/^[a-zA-Z][a-zA-Z0-9+.-]*:\S+$/,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,date:/^\d{4}-\d{2}-\d{2}$/,datetime:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}(?::?\d{2})?)?$/},D={employment_status:[`active`,`inactive`,`terminated`,`pending`,`leave`],employment_type:[`full_time`,`part_time`,`contractor`,`intern`,`temporary`],gender:[`male`,`female`,`non_binary`,`other`,`prefer_not_to_say`],marital_status:[`single`,`married`,`divorced`,`widowed`,`domestic_partnership`]},getInputEnumValues=e=>D[e],isValidEnumRef=e=>e in D,O=[`preview`,`beta`,`ga`,`deprecated`,`internal`],k=[`auth`,`downstream-change`,`bug-fix`,`new-actions`],A=[`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`test`,`event`,`unknown`],j=[`read`,`write`,`delete`,`search`,`execute`],M=[`native`,`unified`],N=[`body`,`query`,`path`,`headers`],P=[`email`,`url`,`uuid`,`date`,`datetime`,`uri`],F=[`string`,`number`,`boolean`,`datetime_string`,`object`,`enum`],I=[`sync`,`async`],L=(0,o.zStrictObject)({r:o.z.record(o.z.string(),(0,o.zStrictObject)({n:o.z.number().optional().nullable(),c:o.z.string().optional().nullable(),p:o.z.number().optional().nullable()})),v:o.z.number(),t:o.z.number()}),R=(0,o.zStrictObject)({remote:o.z.record(o.z.string(),(0,o.zStrictObject)({pageNumber:o.z.number().optional(),providerPageCursor:o.z.string().optional(),position:o.z.number().optional()})),version:o.z.number(),timestamp:o.z.number()}),minifyCursor=e=>(0,o.encodeToBase64)(JSON.stringify(minifyCursorObject(e))),minifyCursorObject=e=>{let{remote:t,version:n,timestamp:r}=e;return{r:Object.fromEntries(Object.entries(t).map(([e,{pageNumber:t,providerPageCursor:n,position:r}])=>[e,{n:t,c:n,p:r}])),v:n,t:r}},expandCursor=e=>{try{if((0,o.isString)(e)){let t=(0,o.decodeFromBase64)(e),n=JSON.parse(t);return expandCursorObject(L.parse(n))}else return R.parse(e),e}catch{return null}},expandCursorObject=e=>{let{r:t,v:n,t:r}=e;return{remote:Object.fromEntries(Object.entries(t).map(([e,{n:t,c:n,p:r}])=>[e,{pageNumber:t,providerPageCursor:n,position:r}])),version:n,timestamp:r}},areCursorsEqual=(e,t)=>{let n=typeof e==`string`?expandCursor(e):e,r=typeof t==`string`?expandCursor(t):t;if(n===null||r===null)return n===r;let{timestamp:i,...a}=n,{timestamp:s,...c}=r;return(0,o.getContentHash)(a)===(0,o.getContentHash)(c)},isCursorEmpty=({cursor:e,ignoreStepIndex:t})=>(0,o.isMissing)(e)?!0:Object.keys(e?.remote??{}).reduce((n,r)=>{let i=e?.remote?.[r];return((0,o.isMissing)(t)||r!==t.toString())&&(n=n&&(0,o.isMissing)(i.pageNumber)&&(0,o.isMissing)(i.position)&&(0,o.isMissing)(i.providerPageCursor)),n},!0),updateCursor=({cursor:e,stepIndex:t,pageNumber:n,providerPageCursor:r,position:i})=>{let a={pageNumber:n??void 0,providerPageCursor:r??void 0,position:i??void 0},s=(0,o.isMissing)(n)&&(0,o.isMissing)(r)&&(0,o.isMissing)(i);return(0,o.isMissing)(e)?{remote:s?{}:{[t]:a},version:2,timestamp:Date.now()}:s?(delete e.remote[t],e):{...e,remote:{...e.remote,[t]:a}}},isCoreError=e=>e instanceof C;function stripPaginationParams(e,t){let n=getPaginationKeys(t);if(n.length===0)return e;let r=getIteratorLocation(t);if(!r)return e;let i=e[r];if(!i||typeof i!=`object`)return e;let a={...i};for(let e of n)delete a[e];return{...e,[r]:a}}function getPaginationKeys(e){switch(e.type){case`cursor`:return[e.iterator.key];case`offset`:{let t=e;return[t.iterator.offsetKey,t.iterator.limitKey]}case`page`:{let t=e,n=[t.iterator.pageKey];return t.iterator.pageSizeKey&&n.push(t.iterator.pageSizeKey),n}default:return[]}}function getIteratorLocation(e){if(`iterator`in e&&typeof e.iterator==`object`&&e.iterator!==null)return e.iterator.in}function stripIncrementalParams(e,t){if(!t)return e;let{key:n,in:r}=t.iterator,i=e[r];if(!i||typeof i!=`object`)return e;let a={...i};return delete a[n],{...e,[r]:a}}const z=[`ui`,`mcp`,`runtime`],B=(0,o.zStrictObject)({description:o.z.string().trim().min(1),impact:o.z.array(o.z.enum(z)).optional()}),V=new Set([`optional`,`nullable`,`default`,`readonly`,`nonoptional`,`catch`]),firstMeta=e=>{let t=e,n=new Set;for(;t&&!n.has(t);){n.add(t);let e=t.meta?.();if(e)return e;let r=t._zod?.def;t=r&&V.has(r.type)?r.innerType:void 0}},collectFieldMetaIssues=e=>{let t=[],n=new Set,check=(e,n)=>{let r=firstMeta(e);if(!r){t.push({path:n,kind:`missing-description`});return}let i=B.safeParse(r);i.success||t.push({path:n,kind:`invalid-meta`,meta:r,errors:i.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`)})},walk=(e,t)=>{if(!e||n.has(e))return;n.add(e);let r=e._zod?.def;if(r)if(r.type===`object`)for(let[e,n]of Object.entries(r.shape??{}))check(n,`${t}.${e}`),walk(n,`${t}.${e}`);else V.has(r.type)?walk(r.innerType,t):r.type===`array`?walk(r.element,`${t}[]`):r.options?r.options.forEach((e,n)=>walk(e,`${t}|${n}`)):r.type===`record`?walk(r.valueType,`${t}.*`):r.type===`lazy`?walk(r.getter?.(),t):r.type===`pipe`&&(walk(r.in,t),walk(r.out,t))};return walk(e,`$`),t},H={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},U={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},ee={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},W={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},browserUseStepFunction=async()=>{throw Error(`browser_use step function cannot be executed synchronously — actions using this step must have executionMode: "async" so they are dispatched to the Temporal workflow runtime`)},G=o.z.object({startUrl:o.z.string().url().meta({description:`URL where the browser session begins.`}),systemPrompt:o.z.string().optional().meta({description:`Author-defined preamble, persona, and guardrails applied to every invocation.`}),viewport:(0,o.zStrictObject)({width:o.z.number().int().positive().meta({description:`Viewport width in pixels.`}),height:o.z.number().int().positive().meta({description:`Viewport height in pixels.`})}).optional().meta({description:`Browser viewport dimensions.`}),locale:o.z.string().optional().meta({description:`Locale the browser session runs in.`}),budgets:(0,o.zStrictObject)({maxDurationMs:o.z.number().int().positive().meta({description:`Maximum task duration in milliseconds.`}),maxSteps:o.z.number().int().positive().meta({description:`Maximum number of steps the agent may take.`})}).meta({description:`Execution limits the task must run within.`}),auth:(0,o.zStrictObject)({sensitiveKeys:o.z.array(o.z.string().min(1)).optional().meta({description:`Credential keys masked from the LLM and substituted only at the typing layer.`}),requiresSession:o.z.boolean().optional().meta({description:`Reserved for tasks that need a pre-authenticated browser session rather than form substitution. Not yet in use.`}),allowedDomains:o.z.array(o.z.string().min(1)).optional().meta({description:`Overrides the default allowed-domains policy, for auth flows that cross a domain boundary.`})}).optional().meta({description:`Credential handling for the browser task.`})}),K=o.z.unknown(),q=(0,o.zStrictObject)({lambdaName:o.z.string().meta({description:`Name or ARN of the Lambda function to invoke.`}),region:o.z.string().optional().meta({description:`AWS region the Lambda function runs in.`}),endpoint:o.z.string().optional().meta({description:`Custom Lambda service endpoint URL to call instead of the default.`}),invocationType:o.z.enum([`RequestResponse`,`Event`,`DryRun`]).optional().meta({description:"How the Lambda is invoked. `RequestResponse` waits synchronously for the Lambda response, `Event` fires asynchronously and returns no response body, and `DryRun` validates parameters and permissions without invoking the function."}),qualifier:o.z.string().optional().meta({description:`Function version or alias to invoke.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Payload field name.`}),value:o.z.unknown().meta({description:`Payload field value. Supports expressions.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the field only when it evaluates true.`})}).array().optional().meta({description:`Key/value pairs combined into the JSON payload sent to the Lambda function`}),dataKey:o.z.string().optional().meta({description:`Path to the field in the Lambda response to extract as data.`})}),J=(0,o.zStrictObject)({data:o.z.unknown().optional().meta({description:"The parsed Lambda response payload, or the value at `dataKey` when `dataKey` is set."}),raw:o.z.unknown().optional().meta({description:"The full Lambda invocation result, including the parsed `payload`, `statusCode`, and `executedVersion`."}),statusCode:o.z.number().meta({description:`HTTP status code of the Lambda invocation.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`}),executedVersion:o.z.string().optional().meta({description:`Version of the Lambda function that was invoked.`})}).optional(),te=(0,o.zStrictObject)({strategy:o.z.literal(`aws4`).meta({description:`Signs requests with AWS Signature Version 4.`}),service:o.z.string().meta({description:"AWS service name used in the signing credential scope. For example `s3` or `execute-api`."}),region:o.z.string().optional().meta({description:"AWS region used in the signing credential scope. Falls back to the credential region or `us-east-1` when omitted."})}),Y=(0,o.zStrictObject)({strategy:o.z.literal(`hmac`).meta({description:`Signs requests with an HMAC signature over a canonical request string.`}),algorithm:o.z.enum([`sha1`,`sha256`,`sha512`]).optional().meta({description:"Hash algorithm for the HMAC signature. Defaults to `sha256`."}),headerName:o.z.string().optional().meta({description:"Header the signature is written into. Defaults to `X-Signature`."}),prefix:o.z.string().optional().meta({description:"Prefix prepended to the signature value in the header. Defaults to `hmac-<algorithm>`."}),dateFormat:o.z.enum([`iso8601`,`rfc2822`]).optional().meta({description:"Timestamp format used in the signed string. Either `iso8601` (default) or `rfc2822`."}),includeHost:o.z.boolean().optional().meta({description:"Include the request hostname in the signed canonical string. Defaults to `false`."}),includeBodyHash:o.z.boolean().optional().meta({description:"Hash the request body into the signed string, defaulting to `true`. When `false`, form-urlencoded body params are folded into the canonical string instead."}),outputFormat:o.z.enum([`header`,`basic`]).optional().meta({description:"Where the signature is emitted. `header` writes a signature header and `basic` writes an HTTP Basic `Authorization` header."}),username:o.z.string().optional().meta({description:"Username paired with the signature when `outputFormat` is `basic`."})}),X=o.z.discriminatedUnion(`strategy`,[te,Y]),ne=(0,o.zStrictObject)({type:o.z.literal(`none`).meta({description:`Sends requests without an authorization header.`}),signing:X.optional().meta({description:`Optional request signing applied to outgoing requests. Selects AWS SigV4 or HMAC signing.`}),redirectUri:o.z.string().optional().meta({description:`OAuth callback URL carried as connect-time metadata. Not used when authorizing requests.`})}),re=(0,o.zStrictObject)({type:o.z.literal(`basic`).meta({description:`Configures HTTP Basic authentication.`}),username:o.z.string().optional().meta({description:`Username for HTTP Basic authentication.`}),password:o.z.string().optional().meta({description:`Password for HTTP Basic authentication.`}),encoding:o.z.string().optional().meta({description:"Encoding applied to the `username:password` pair. Defaults to `base64`."}),redirectUri:o.z.string().optional().meta({description:`OAuth callback URL carried as connect-time metadata. Not used when authorizing requests.`})}),ie=(0,o.zStrictObject)({type:o.z.literal(`bearer`).meta({description:`Configures bearer token authentication.`}),token:o.z.string().meta({description:`Token sent on each request. Supports expressions.`}),includeBearer:o.z.boolean().optional().default(!0).meta({description:"Prefix the token with `Bearer ` in the `Authorization` header. Defaults to `true`."}),redirectUri:o.z.string().optional().meta({description:`OAuth callback URL carried as connect-time metadata. Not used when authorizing requests.`})}),ae=new Set([`accessToken`,`refreshToken`,`idToken`,`clientId`,`clientSecret`,`authentication_config_key`,`environment`]),oe=(0,o.zStrictObject)({type:o.z.literal(`oauth2`).meta({description:`Configures OAuth 2.0 authentication.`}),authorizationUrl:o.z.string().optional().meta({description:`Provider authorization endpoint where the user grants access.`}),redirectUri:o.z.string().optional().meta({description:`Overrides the OAuth callback URL. The computed callback URL can be seen on the connector profile.`}),authorizationParams:o.z.record(o.z.string(),o.z.string()).optional().meta({description:`Extra query parameters appended to the authorization URL. Values support expressions.`}),tokenUrl:o.z.string().optional().meta({description:`Provider token endpoint used to exchange the authorization code and to refresh tokens.`}),tokenParams:o.z.record(o.z.string(),o.z.string()).optional().meta({description:`Extra parameters sent to the token endpoint. Values support expressions.`}),tokenExpiresIn:o.z.number().optional().meta({description:`Access token lifetime in seconds.`}),tokenRefreshExpiresIn:o.z.number().optional().meta({description:`Refresh token lifetime in seconds.`}),token:o.z.string().meta({description:`Expression that resolves the access token sent on each request.`}),includeBearer:o.z.boolean().optional().default(!0).meta({description:"Prefix the token with `Bearer ` in the `Authorization` header. Defaults to `true`."}),scopes:o.z.string().optional().meta({description:`OAuth scopes requested during authorization.`}),scopeDelimiter:o.z.string().optional().meta({description:`Delimiter used to separate scopes when requesting authorization.`}),customHeaders:o.z.record(o.z.string(),o.z.string()).optional().meta({description:`Additional HTTP headers sent with token endpoint requests.`}),pkce:o.z.boolean().optional().meta({description:`Enable PKCE for the authorization code flow.`}),additionalTokenFields:o.z.record(o.z.string(),o.z.string().optional()).optional().meta({description:`Extra credential fields to read from the token endpoint response. Each key is a credential name and each value an expression.`}),callbackParams:o.z.record(o.z.string(),o.z.string().min(1)).superRefine((e,t)=>{for(let[n,r]of Object.entries(e))ae.has(r)&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[n],message:`callbackParams must not target reserved credential key "${r}"`})}).optional().meta({description:`Maps OAuth callback query parameter names to the credential keys their values are stored under. Cannot target reserved credential keys.`}),issuer:o.z.string().optional().meta({description:`OpenID Connect issuer identifier for the provider.`}),tokenResponse:(0,o.zStrictObject)({acceptTokenTypes:o.z.array(o.z.string()).optional().meta({description:"Allowlist of `token_type` values to accept from the token endpoint beyond `Bearer` and `DPoP`. Matched case-insensitively."}),accessToken:o.z.string().min(1).optional().meta({description:"Expression locating the access token in the token endpoint response. Takes precedence over the standard `access_token` field when it resolves to a non-empty string."}),refreshToken:o.z.string().min(1).optional().meta({description:"Expression locating the refresh token in the token endpoint response. Takes precedence over the standard `refresh_token` field when it resolves to a non-empty string."})}).optional().meta({description:`Adjusts how a non-standard token endpoint response is parsed.`})}),Z=o.z.discriminatedUnion(`type`,[ne,re,ie,oe]),se=(0,o.zStrictObject)({certs:o.z.string().array().optional().meta({description:`PEM-encoded client certificates for mutual TLS. Each entry is a raw or base64-encoded PEM certificate.`}),keys:o.z.string().array().optional().meta({description:`PEM-encoded client private keys for mutual TLS. Each entry is a raw or base64-encoded PEM private key.`})}).optional(),ce=o.z.object({baseUrl:o.z.string().optional().meta({description:`Overrides the connector's base URL for the download.`}),url:o.z.string().meta({description:`Download endpoint path appended to the base URL.`}),method:o.z.enum(c.HttpMethods).optional().default(`get`).meta({description:`HTTP method to use for the download.`}),authorization:Z.optional().meta({description:`Overrides the connector's default authentication for this request.`}),responseMode:o.z.enum([`buffer`,`stream`]).optional().default(`buffer`).meta({description:`How the file is returned: buffer downloads it fully into memory, stream returns a readable stream for piping to the client.`}),responseType:o.z.enum([`arraybuffer`,`blob`,`text`,`json`]).optional().default(`arraybuffer`).meta({description:`Underlying HTTP response type requested. Used only when responseMode is buffer.`}),encoding:o.z.enum([`base64`,`utf8`,`binary`,`raw`,`none`]).optional().default(`base64`).meta({description:`Encoding applied to the returned data when responseMode is buffer. Use none to return a raw Buffer.`}),response:(0,o.zStrictObject)({dataKey:o.z.string().optional().meta({description:`JSONPath to the file content within a JSON-wrapped response.`}),fileNameKey:o.z.string().optional().meta({description:`JSONPath to the filename within a JSON-wrapped response.`}),contentTypeKey:o.z.string().optional().meta({description:`JSONPath to the content type within a JSON-wrapped response.`}),contentType:o.z.string().optional().meta({description:"Fallback content type used when the JSON response exposes none to extract. `contentTypeKey` wins if it resolves."}),contentIsBase64:o.z.boolean().optional().default(!1).meta({description:`Whether the content in the JSON response is already base64 encoded.`}),urlKey:o.z.string().optional().meta({description:`JSONPath to a download URL in the response to follow for the file.`}),forwardAuth:o.z.boolean().optional().default(!1).meta({description:`Whether to forward authentication headers to the secondary download request when following urlKey.`})}).optional().meta({description:`Options for extracting file content from a JSON-wrapped response.`}),maxRedirects:o.z.number().optional().default(5).meta({description:`Maximum number of redirects to follow.`}),followRedirects:o.z.boolean().optional().default(!0).meta({description:`Whether to follow HTTP redirects.`}),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional().meta({description:`Remaps matching provider error responses to different statuses or messages.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the request parameter.`}),value:o.z.unknown().meta({description:`Value of the parameter. Supports expressions.`}),in:o.z.enum(c.RequestParameterLocations).meta({description:`Where to send the parameter: query, body, or headers.`}),spread:o.z.boolean().optional().meta({description:`Merges the value's object entries into the target location instead of setting a single named field.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the parameter only when it evaluates true.`}),arrayFormat:o.z.enum(c.QueryArrayFormats).optional().meta({description:`How array values are serialized in the query string: repeat, brackets, comma, or stringify.`})}).array().optional().meta({description:"Additional request parameters sent as query params, headers, or the request body, per each entry's `in`."})}),le=(0,o.zStrictObject)({data:o.z.union([o.z.string(),o.z.instanceof(Buffer)]).optional().meta({description:'Downloaded file content. A string in the format set by the `encoding` input (base64 by default), or a raw binary Buffer when `encoding: "none"`. Absent when `responseMode: "stream"` (content is piped via the stream output instead).'}),raw:o.z.unknown().optional().meta({description:`The raw provider response before parsing.`}),statusCode:o.z.number().meta({description:`HTTP status code of the provider response.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`}),headers:o.z.record(o.z.string(),o.z.union([o.z.string(),o.z.array(o.z.string())])).optional().meta({description:`All response headers returned with the download.`}),contentDisposition:o.z.string().optional().meta({description:`Content-Disposition header value for the client to use.`}),fileMetadata:(0,o.zStrictObject)({contentType:o.z.string().optional().meta({description:`MIME type of the downloaded file.`}),contentLength:o.z.number().optional().meta({description:`Size of the file in bytes.`}),fileName:o.z.string().optional().meta({description:`Name of the downloaded file.`}),lastModified:o.z.string().optional().meta({description:`Last-modified timestamp reported for the file.`}),etag:o.z.string().optional().meta({description:`Entity tag identifying the file version.`})}).optional().meta({description:`File metadata extracted from response headers or a JSON-wrapped response.`}),finalUrl:o.z.string().optional().meta({description:`Final URL the file was downloaded from after redirects or a followed link.`})}).optional(),ue=o.z.object({event:o.z.object({eventType:o.z.string().meta({description:`Name of the event type being emitted.`}),eventId:o.z.coerce.string().optional().meta({description:`Unique identifier for this event.`}),eventDate:o.z.coerce.string().optional().meta({description:`Timestamp for when the event occurred.`}),data:o.z.unknown().optional().meta({description:`Normalized payload carried by the event.`})}).optional().meta({description:`The event to emit.`})}),de=o.z.record(o.z.string(),o.z.unknown()).meta({description:"The input parameters other than `event`, returned as the step output."}),sanitizeRaw=e=>{let t={};return e.status!=null&&(t.status=e.status),e.data!==void 0&&(t.data=e.data),e.headers!=null&&(t.headers=e.headers),e.requestUrl!=null&&(t.requestUrl=e.requestUrl),e.message!=null&&(t.message=e.message),t},isSerializedBuffer=e=>typeof e==`object`&&!!e&&e.type===`Buffer`&&Array.isArray(e.data),decodeBinaryBody=e=>{let t;if(Buffer.isBuffer(e)?t=e.toString(`utf8`):e instanceof ArrayBuffer?t=new TextDecoder().decode(new Uint8Array(e)):ArrayBuffer.isView(e)?t=new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):isSerializedBuffer(e)&&(t=Buffer.from(e.data).toString(`utf8`)),t===void 0)return e;try{return JSON.parse(t)}catch{return t}},decodeResponseBody=e=>({...e,data:decodeBinaryBody(e.data)}),isHttpLikeError=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`,extractTopLevelMessage=e=>{if(typeof e.message==`string`&&e.message.trim().length>0)return e.message},extractNestedErrorMessage=e=>{if(e.error!=null&&typeof e.error==`object`&&!Array.isArray(e.error)&&typeof e.error.message==`string`)return e.error.message;if(typeof e.error==`string`&&e.error.length>0)return e.error;if(typeof e.error_description==`string`&&e.error_description.length>0)return e.error_description},extractErrorMessage=(e,t)=>{let n=e.data;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=extractTopLevelMessage(n);if(e!=null)return e}if(typeof e.message==`string`&&e.message.length>0)return e.message;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=extractNestedErrorMessage(n);if(e!=null)return e}if(Array.isArray(n)&&n.length>0){let e=n[0];if(typeof e==`object`&&e&&!Array.isArray(e)){let t=e,n=extractTopLevelMessage(t)??extractNestedErrorMessage(t);if(n!=null)return n}}return typeof n==`string`&&n.length>0?n:t},buildStepErrorOutput=(e,t)=>{if(e instanceof c.HttpResponseError){let n=e.message,r=decodeResponseBody(e.response);return{block:t,successful:!1,errors:[(0,c.serializeHttpResponseError)(e)],output:{statusCode:r?.status??500,message:extractErrorMessage(r,n),data:r?.data,raw:sanitizeRaw(r)}}}if(isHttpLikeError(e)){let n=decodeResponseBody(e.response),r=e instanceof Error?e.message:`HTTP error: ${n.status??500}`;return{block:t,successful:!1,errors:[(0,c.serializeHttpResponseError)(e)],output:{statusCode:n.status??500,message:extractErrorMessage(n,r),data:n.data,raw:sanitizeRaw(n)}}}return e instanceof Error?{block:t,successful:!1,errors:[(0,c.serializeHttpResponseError)(e)],output:{statusCode:500,message:e.message}}:{block:t,successful:!1,errors:[(0,c.serializeHttpResponseError)(e)],output:{statusCode:500,message:String(e)}}},isAwsCredentials=e=>!!e&&typeof e.accessKeyId==`string`&&typeof e.secretAccessKey==`string`,buildLambdaClientConfig=({region:e,endpoint:t,credentials:n})=>({region:e,...t?{endpoint:t}:{},...isAwsCredentials(n)?{credentials:{accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey,sessionToken:typeof n.sessionToken==`string`?n.sessionToken:void 0}}:t?{credentials:{accessKeyId:`local`,secretAccessKey:`local`}}:{}}),defaultClientFactory=e=>new l.LambdaClient(e),invokeLambda=async({lambdaName:e,payload:t,region:n,endpoint:r,invocationType:i=`RequestResponse`,qualifier:a,credentials:o,clientFactory:s=defaultClientFactory})=>{let c=s(buildLambdaClientConfig({region:n,endpoint:r,credentials:o})),u=new l.InvokeCommand({FunctionName:e,InvocationType:i,Qualifier:a,Payload:t?Buffer.from(JSON.stringify(t)):void 0}),d=await c.send(u),f=d.Payload?Buffer.from(d.Payload).toString(`utf-8`):``,p;if(f.length===0)p=void 0;else try{p=JSON.parse(f)}catch{p=f}return{statusCode:d.StatusCode??200,payload:p,functionError:d.FunctionError,executedVersion:d.ExecutedVersion}},fe=/\${[^}]+}/,isJsonPathLike=e=>{let t=e.trimStart();return t.startsWith(`$.`)||t.startsWith(`$[`)},hasExpressionMarker=e=>(0,s.isExpression)(e)||fe.test(e)||isJsonPathLike(e),buildDataKeyExpression=e=>(0,s.isExpression)(e)||e.trimStart().startsWith(`$`)?e:`$.${e}`,pe=__name((e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`||!e)return e;try{let n=(0,s.evaluate)(buildDataKeyExpression(t),e);if(n!==void 0)return n}catch{}return e[t]},`resolveDataKey`),buildPayloadFromArgs=e=>{if(!(!e||e.length===0))return e.reduce((e,t)=>(e[t.name]=t.value,e),{})},codeExecutionLambdaStepFunction=async({block:e,params:t},n=invokeLambda)=>{let r=t?.args,i=Array.isArray(r)?r:void 0,isPlainObject=e=>typeof e==`object`&&!!e,a=i?i.filter(t=>{if(!isPlainObject(t))return!0;let n=t.condition;return typeof n!=`string`||(0,s.safeEvaluate)(n,e)===!0}).map(e=>isPlainObject(e)?{...e,condition:void 0}:e):void 0,o=t?.dataKey,c=typeof o==`string`&&!fe.test(o),l=t?.qualifier,u=typeof l==`string`&&!hasExpressionMarker(l),d={...t?(0,s.safeEvaluateRecord)(i===void 0?t:{...t,args:a},e):{},...c?{dataKey:o}:{},...u?{qualifier:l}:{}},f;try{f=q.parse(d)}catch(t){return buildStepErrorOutput(t,e)}let{lambdaName:p,region:m,endpoint:h,invocationType:g,qualifier:_,args:v,dataKey:y}=f,b;try{b=await n({lambdaName:p,payload:buildPayloadFromArgs(v),region:m,endpoint:h,invocationType:g,qualifier:_,credentials:e.credentials})}catch(t){return buildStepErrorOutput(t,e)}if(b.functionError){let t=typeof b.payload==`object`&&b.payload!==null&&`errorMessage`in b.payload&&typeof b.payload.errorMessage==`string`?b.payload.errorMessage:`Lambda function error: ${b.functionError}`;return{block:e,successful:!1,errors:[{message:t,kind:`lambda_function_error`,functionError:b.functionError}],output:{statusCode:b.statusCode,message:t,data:b.payload,raw:b}}}return{block:e,successful:!0,output:{data:y?pe(b.payload,y):b.payload,raw:b,statusCode:b.statusCode,executedVersion:b.executedVersion}}},buildRequestContext=e=>({accountSecureId:e.context.accountSecureId,projectSecureId:e.context.projectSecureId,organizationId:e.context.organizationId,environment:e.context.environment,authConfigKey:e.context.authenticationType,provider:e.connector?.key,service:e.context.category,resource:e.connector?.key,action:e.action?.id}),downloadFileStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n}=t,r=n?n.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,i=t?(0,s.safeEvaluateRecord)({...t,args:r},e):{},a={...i,customErrors:t?.customErrors},{baseUrl:l,url:u,method:d,authorization:f,args:p,responseMode:m,responseType:h,encoding:g,response:_,maxRedirects:v,followRedirects:y}=ce.parse(a),b=i?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,x=p?(0,c.parseRequestParameters)(p):{query:{},body:{},headers:{}},S=typeof x?.body==`string`?void 0:x?.body,C=(0,c.createAuthorizationHeaders)((0,o.notMissing)(f)?f:Z.parse(b)),w={...x?.headers??{},...C},T=e.connector?.rateLimit,E=e.connector?.concurrency,D=T!==void 0||E!==void 0?{rateLimits:T,concurrency:E}:void 0,O=buildRequestContext(e);if(m===`stream`)return performStreamDownload({block:e,httpClient:e.httpClient,baseUrl:l??``,url:u,method:d,headers:w,queryParams:x?.query,body:S,maxRedirects:y?v:0,requestConfig:D,context:O,response:_,responseType:h,authHeaders:C});try{return{block:e,successful:!0,output:await performDownload({httpClient:e.httpClient,baseUrl:l??``,url:u,method:d,headers:w,queryParams:x?.query,body:S,responseType:h,encoding:g,response:_,maxRedirects:y?v:0,requestConfig:D,context:O,authHeaders:C})}}catch(t){return buildStepErrorOutput(t,e)}},performStreamDownload=async e=>{let{block:t,httpClient:n,baseUrl:r,url:i,method:a,headers:s,queryParams:c,body:l,maxRedirects:d,requestConfig:f,context:p,response:m,responseType:h,authHeaders:g}=e,_=`${r}${i}`;if(!_.startsWith(`http://`)&&!_.startsWith(`https://`))throw Error(`Invalid URL: "${_}". URL must be absolute (start with http:// or https://). Either provide a baseUrl or ensure url is a complete URL.`);if((0,o.notMissing)(m?.dataKey)||(0,o.notMissing)(m?.urlKey))try{let e=await performDownload({httpClient:n,baseUrl:r,url:i,method:a,headers:s,queryParams:c,body:l,responseType:h??`arraybuffer`,encoding:`none`,response:m,maxRedirects:d,requestConfig:f,context:p,authHeaders:g??{}}),_=Buffer.isBuffer(e.data)?e.data:Buffer.from(e.data),v={...e.fileMetadata,contentLength:_.length};return{block:t,successful:!0,streamOutput:{stream:u.Readable.from(_),headers:(0,o.notMissing)(v.contentType)?{"content-type":v.contentType}:{},contentDisposition:e.contentDisposition,fileMetadata:v}}}catch(e){return buildStepErrorOutput(e,t)}if(!n.requestStream)throw Error(`HTTP client does not support streaming. Either implement requestStream method or use responseMode: "buffer".`);try{let e=await n.requestStream({url:_,method:a,headers:s,queryParams:c,payload:l,maxRedirects:d,requestConfig:f,context:p}),r=extractFileMetadata(e.headers),i=buildContentDisposition(r);return{block:t,successful:!0,streamOutput:{stream:e.stream,headers:e.headers,contentDisposition:i,fileMetadata:r}}}catch(e){return buildStepErrorOutput(e,t)}},performDownload=async e=>{let{httpClient:t,baseUrl:n,url:r,method:i,headers:a,queryParams:o,body:s,responseType:c,encoding:l,response:u,maxRedirects:d,requestConfig:f,context:p,authHeaders:m}=e,h=`${n}${r}`;if(!h.startsWith(`http://`)&&!h.startsWith(`https://`))throw Error(`Invalid URL: "${h}". URL must be absolute (start with http:// or https://). Either provide a baseUrl or ensure url is a complete URL.`);let g=u?.urlKey||u?.dataKey?`json`:c,_=await t.request({url:h,method:i,headers:a,queryParams:o,payload:s,responseType:g===`json`?void 0:g,maxRedirects:d,requestConfig:f,context:p});if(u?.urlKey||u?.dataKey)return handleJsonResponse({httpClient:t,result:_,response:u,encoding:l,maxRedirects:d,requestConfig:f,context:p,authHeaders:m});let v=encodeFileData(_.data,l),y=extractFileMetadata(_.headers),b=buildContentDisposition(y);return{data:v,raw:_,statusCode:_?.status,message:_?.message,headers:_.headers,contentDisposition:b,fileMetadata:y,finalUrl:_?.requestUrl}},handleJsonResponse=async e=>{let{httpClient:t,result:n,response:r,encoding:i,maxRedirects:a,requestConfig:s,context:c,authHeaders:l}=e,u=n.data;if(r.urlKey){let e=extractValueByPath(u,r.urlKey);if(typeof e==`string`){let n=await t.request({url:e,method:`get`,headers:r.forwardAuth?l:{},responseType:`arraybuffer`,maxRedirects:a,requestConfig:s,context:c}),d=encodeFileData(n.data,i),f=extractFileMetadata(n.headers);if(r.fileNameKey){let e=extractValueByPath(u,r.fileNameKey);typeof e==`string`&&(f.fileName=e)}if(r.contentTypeKey){let e=extractValueByPath(u,r.contentTypeKey);typeof e==`string`&&(f.contentType=e)}(0,o.isMissing)(f.contentType)&&(0,o.notMissing)(r.contentType)&&(f.contentType=r.contentType);let p=buildContentDisposition(f);return{data:d,raw:n,statusCode:n?.status,message:n?.message,headers:n.headers,contentDisposition:p,fileMetadata:f,finalUrl:e}}}if(r.dataKey){let e=extractValueByPath(u,r.dataKey);if((0,o.isMissing)(e))throw Error(`No file content found at path: ${r.dataKey}`);let t;if(typeof e==`string`)t=r.contentIsBase64?i===`base64`?e:i===`none`?Buffer.from(e,`base64`):Buffer.from(e,`base64`).toString(i===`raw`?`binary`:i):encodeFileData(e,i);else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))t=encodeFileData(e,i);else throw Error(`Unexpected file content type at path: ${r.dataKey}`);let a={};if(r.fileNameKey){let e=extractValueByPath(u,r.fileNameKey);typeof e==`string`&&(a.fileName=e)}if(r.contentTypeKey){let e=extractValueByPath(u,r.contentTypeKey);typeof e==`string`&&(a.contentType=e)}(0,o.isMissing)(a.contentType)&&(0,o.notMissing)(r.contentType)&&(a.contentType=r.contentType);let s=buildContentDisposition(a);return{data:t,raw:n,statusCode:n?.status,message:n?.message,headers:n.headers,contentDisposition:s,fileMetadata:a}}throw Error(`JSON response handling requires either urlKey or dataKey to be specified`)},extractValueByPath=(e,t)=>{let n=(t.startsWith(`$.`)?t.slice(2):t).split(`.`),r=e;for(let e of n){if((0,o.isMissing)(r)||typeof r!=`object`)return;r=r[e]}return r},encodeFileData=(e,t)=>{if(t===`none`)return e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof e==`string`?Buffer.from(e):Buffer.from(JSON.stringify(e));if(t===`raw`)return typeof e==`string`?e:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?Buffer.from(e).toString(`binary`):JSON.stringify(e);if(typeof e==`string`)return t===`base64`?Buffer.from(e).toString(`base64`):e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){let n=Buffer.from(e);switch(t){case`base64`:return n.toString(`base64`);case`utf8`:return n.toString(`utf8`);default:return n.toString(`binary`)}}return JSON.stringify(e)},extractFileMetadata=e=>{let t=(0,o.isString)(e[`content-type`])?e[`content-type`]:void 0,n=(0,o.isString)(e[`content-length`])?e[`content-length`]:void 0,r=(0,o.isString)(e[`content-disposition`])?e[`content-disposition`]:void 0,i=(0,o.isString)(e[`last-modified`])?e[`last-modified`]:void 0,a=(0,o.isString)(e.etag)?e.etag:void 0,s=n?parseInt(n,10):void 0,c=extractFileName(r);return{contentType:t,contentLength:Number.isNaN(s)?void 0:s,fileName:c,lastModified:i,etag:a}},extractFileName=e=>{if(!e)return;let t=e.match(/filename\*=(?:UTF-8''|utf-8'')([^;\s]+)/i);if(t&&t[1])try{return decodeURIComponent(t[1])}catch{}let n=e.match(/filename=["']([^"']+)["']/);if(n&&n[1])return n[1];let r=e.match(/filename=([^;\s]+)/);if(r&&r[1])return r[1]},buildContentDisposition=e=>{let{fileName:t,contentType:n}=e,r=`attachment`;if(t)r=`attachment; filename="${t}"; filename*=UTF-8''${encodeURIComponent(t).replace(/['()]/g,escape)}`;else if(n){let e=getExtensionFromContentType(n);e&&(r=`attachment; filename="download.${e}"`)}return r},getExtensionFromContentType=e=>{let t=e.split(`;`)[0].trim().toLowerCase();return d.default.extension(t)||void 0},emitEventStepFunction=async({block:e,params:t})=>{let n=t?(0,s.safeEvaluateRecord)(t,e):{},{event:r}=ue.parse(n);if(r&&e.emitEvent)try{await e.emitEvent({eventType:r.eventType,eventId:r.eventId,eventDate:r.eventDate,data:r.data})}catch(t){throw e.logger?.error({code:`EmitEventError`,message:`emitEvent callback failed: ${t.message}`}),t}else r&&!e.emitEvent&&e.logger?.warning({message:`emit_event step executed but no emitEvent callback provided on the block`});let{event:i,...a}=n;return{block:{...e},successful:!0,output:a}},me=o.z.object({stepsDataToGroup:o.z.array(o.z.string()).meta({description:`IDs of the steps whose output data should be grouped together.`}),isSingleRecord:o.z.boolean().optional().meta({description:`When true, returns a single record keyed by step ID, otherwise an array merged per key across steps.`})}),he=o.z.object({data:o.z.unknown().meta({description:`The combined output data grouped from the referenced steps.`})}),groupDataStepFunction=async({block:e,params:t})=>{let{stepsDataToGroup:n,isSingleRecord:r}=me.parse(t),i=n.reduce((t,n)=>{let i=e.steps?.[n]?.output?.data;return i?r?{...t,[n]:{...i}}:(Object.keys(i).forEach(e=>{t[e]={...(0,o.notMissing)(t[e])?t[e]:{},[n]:{...i[e]}}}),t):t},{});return{block:{...e},successful:!0,output:{data:r?i:Object.values(i)}}},ge=__name(async({block:e})=>{let t=e?.fieldConfigs,n=[],r=e.steps;if(!t||e?.debug?.custom_mappings===`disabled`||!r)return{block:e,successful:!0};let i=buildExpressionContext(e),a;if(Array.isArray(e.result)){let o=e.result.length;a=e.result.map((e,a)=>{let s=_e(e,t,extractSingleRecordBlockStepData(r,o,a),i);return n.push(...s.errors||[]),s.record})}else{let o=_e(e.result,t,r,i);a=o.record,n.push(...o.errors||[])}return{block:{...e,result:a},successful:!0,errors:Object.keys(n).length>0?n:void 0}},`mapFieldsStepFunction`),extractSingleRecordBlockStepData=(e,t,n)=>Object.entries(e).reduce((e,[r,i])=>{let a=i?.output?.data;return Array.isArray(a)&&a.length===t?e[r]={output:{data:a[n]}}:e[r]=i,e},{}),_e=__name((e,t,n,r)=>{if(!e||!n)return{record:e};let i={...r,unified:{...e},...typeof n==`object`?n:{}},a={},o=[],s={...e};for(let n of t){let{error:t,value:r}=ve(i,e.id,n);if(t){o.push(t);continue}n.custom?a[n.targetFieldKey]=r:s[n.targetFieldKey]=r}return{record:{...s,unified_custom_fields:Object.keys(a).length>0?a:void 0},errors:o.length>0?o:void 0}},`mapSingleRecord`),ve=__name((e,t,n)=>{let{expression:r,targetFieldKey:i}=n;if(!r)return{error:{message:`Expression is empty`,id:t,targetField:i}};let a;try{a=(0,s.evaluate)(r,e)}catch{return{error:{message:`Invalid expression`,id:t,targetField:i}}}return a===void 0?{error:{message:`Expression returned no value`,id:t,targetField:i}}:{value:a}},`extractFieldValue`),getEnumMatcher=e=>{switch(e){case`country_alpha2code_by_alpha2code`:return o.getCountryAlpha2CodeByAlpha2Code;case`country_alpha3code_by_alpha3code`:return o.getCountryAlpha3CodeByAlpha3Code;case`country_code_by_country_code`:return o.getCountryCodeByCountryCode;case`country_name_by_country_name`:return o.getCountryNameByCountryName;case`country_name_by_alpha3code`:return o.getCountryNameByAlpha3Code;case`country_name_by_alpha2code`:return o.getCountryNameByAlpha2Code;case`country_name_by_country_code`:return o.getCountryNameByCountryCode;case`country_alpha3code_by_alpha2code`:return o.getCountryAlpha3CodeByAlpha2Code;case`country_alpha3code_by_country_name`:return o.getCountryAlpha3CodeByCountryName;case`country_alpha3code_by_country_code`:return o.getCountryAlpha3CodeByCountryCode;case`country_alpha2code_by_alpha3code`:return o.getCountryAlpha2CodeByAlpha3Code;case`country_alpha2code_by_country_name`:return o.getCountryAlpha2CodeByCountryName;case`country_alpha2code_by_country_code`:return o.getCountryAlpha2CodeByCountryCode;case`country_code_by_alpha2code`:return o.getCountryCodeByAlpha2Code;case`country_code_by_alpha3code`:return o.getCountryCodeByAlpha3Code;case`country_code_by_country_name`:return o.getCountryCodeByCountryName;case`country_subdivisions_by_alpha2code`:return o.getCountrySubDivisionsByAlpha2Code;case`country_subdivision_code_by_subdivision_name`:return o.getCountrySubDivisionCodeBySubDivisionName;case`country_alpha2code_by_citizenship`:return o.getCountryAlpha2CodeByCitizenship;case`country_subdivision_name_by_subdivision_code`:return o.getCountrySubDivisionNameBySubDivisionCode;case`document_file_format_from_extension`:return o.getDocumentFileFormatFromExtension;default:return}},ye=(0,o.zStrictObject)({targetFieldKey:o.z.string().meta({description:`Name of the output field to produce.`}),alias:o.z.string().optional().meta({description:`Alias for this field's component in composite identifiers. Not used for source lookup.`}),expression:o.z.string().optional().meta({description:`JEXL expression that computes the field's value.`}),values:o.z.unknown().optional().meta({description:`Inline values used to populate the field when no expression is given.`}),type:o.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]).meta({description:"Declared output type of the mapped value, where `enum` resolves through the matcher, `object` maps its nested `properties`, and primitives are cast by a later `typecast` step rather than here."}),array:o.z.boolean().default(!1).meta({description:`Whether the field holds an array of the given type.`}),custom:o.z.boolean().default(!1).meta({description:`Whether the field is a custom, non-unified field.`}),hidden:o.z.boolean().default(!1).meta({description:`Currently not in use.`}),enumMapper:(0,o.zStrictObject)({matcher:o.z.string().or((0,o.zStrictObject)({matchExpression:o.z.string().meta({description:`JEXL expression matched against the source value.`}),value:o.z.string().meta({description:`Enum value to use when the expression matches.`})}).array()).meta({description:`Either the name of a built-in matcher, or a list of match rules mapping source values to enum values.`})}).optional().meta({description:`Rules for mapping source values onto enum values.`}),properties:o.z.lazy(()=>ye).array().optional().meta({description:`Nested field mappings for object-typed fields.`}),requiredScopes:o.z.string().array().optional().meta({description:`Scopes that must be granted for the field to be included.`})}),be=o.z.object({fields:ye.array().meta({description:`Field mapping definitions applied to the source data.`}),dataSource:o.z.string().meta({description:`Reference to the source data to transform.`}),externalSources:o.z.record(o.z.string(),o.z.string()).optional().meta({description:`Additional named data sources referenced by mapping expressions.`})}),xe=o.z.object({data:o.z.unknown().meta({description:`The mapped fields produced from the source data.`})}),mergeSourceWithState=(e,t)=>(0,o.isObject)(e)?{...t,...e}:e,mapFieldsStepFunction=async({block:e,params:t})=>{let n=[],{fields:r,dataSource:i,externalSources:a}=be.parse(t),o=buildExpressionContext(e,{includeCredentials:!0}),c=(0,s.evaluate)(i,o);if(!r||!i||e?.debug?.custom_mappings===`disabled`||!c)return{block:e,successful:!0};let l=Object.keys(a??{})?.reduce((e,t)=>(e[t]=(0,s.evaluate)(a?.[t],o),e),{}),u;if(Array.isArray(c))u=c.map(e=>{let t=Q(r,{...e,external:l},o);return n.push(...t?.errors||[]),t?.record});else{let e=Q(r,{...c,external:l},o);u=e?.record,n.push(...e?.errors||[])}return{block:{...e},successful:!0,output:{data:u},errors:Object.keys(n).length>0?n:void 0}},handleObjectArrayFromValues=(e,t,n,r)=>{if(Array.isArray(e.values))return e.values.map(i=>{let a=evaluateExpressionsInObject(i,t),s=Q(e.properties,a,r);return(0,o.notMissing)(s?.errors)&&n.push(...s.errors),s?.record}).filter(Boolean)},handleObjectArrayFromExpression=(e,t,n,r,i)=>{if(e.expression)try{let t=(0,s.evaluate)(e.expression,n);if(Array.isArray(t))return t.map(t=>{let n=Q(e.properties,t,i);return(0,o.notMissing)(n?.errors)&&r.push(...n.errors),n?.record}).filter(Boolean);{let n=Q(e.properties,t,i);return(0,o.notMissing)(n?.errors)&&r.push(...n.errors),n?.record}}catch{r.push({message:`Invalid expression`,id:t?.id,targetField:e.targetFieldKey});return}},handleSingleObject=(e,t,n,r)=>{let i=(0,o.notMissing)(e.values)?e.values:t,a=Q(e.properties,i,r);return(0,o.notMissing)(a?.errors)&&n.push(...a.errors),a?.record},Se=__name((e,t,n,r,i)=>{if(!(0,o.isMissing)(e.properties))return e.array&&Array.isArray(e.values)?handleObjectArrayFromValues(e,n,r,i):e.array&&e.expression?handleObjectArrayFromExpression(e,t,n,r,i):handleSingleObject(e,t,r,i)},`handleObjectField`),Q=__name((e,t,n)=>{if(!t)return;let r=mergeSourceWithState(t,n),i={},a=[],o={};for(let s of e){let e;if(s.type===`object`){if(e=Se(s,t,r,a,n),e===void 0)continue}else{let{error:n,value:i}=extractFieldValue(r,t?.id,s);if(e=i,n){a.push(n);continue}}s.custom?i[s.targetFieldKey]=e:o[s.targetFieldKey]=e}let s=Object.keys(i).length>0?{unified_custom_fields:i}:{};return{record:{...o,...s},errors:a.length>0?a:void 0}},`mapSingleRecord`),evaluateExpressionsInObject=(e,t)=>{if(e==null)return e;if(typeof e==`string`){if((0,s.isValidExpression)(e))try{return(0,s.evaluate)(e,t)}catch{return e}return e}if(Array.isArray(e))return e.map(e=>evaluateExpressionsInObject(e,t));if(typeof e==`object`){let n={...e};for(let[e,r]of Object.entries(n))n[e]=evaluateExpressionsInObject(r,t);return n}return e},extractFieldValue=(e,t,n)=>{switch(n.type){case`string`:case`number`:case`boolean`:case`datetime_string`:return Ce(n,t,e);case`enum`:return evaluateEnumValue(n,t,e);default:return{error:{message:`Invalid type`,id:t,targetField:n.targetFieldKey}}}},Ce=__name((e,t,n)=>{if(!e.expression)return{error:{message:`Expression is empty`,id:t,targetField:e.targetFieldKey}};let r;try{r=(0,s.evaluate)(e.expression,n)}catch{return{error:{message:`Invalid expression`,id:t,targetField:e.targetFieldKey}}}return r===void 0?{error:{message:`Expression returned no value`,id:t,targetField:e.targetFieldKey}}:{value:r}},`evaluateValue`),evaluateEnumValue=(e,t,n)=>{let r=Ce(e,t,n),i=(0,o.notMissing)(r.value)?r.value:null;if(e.enumMapper===void 0)return{error:{message:`Enum mapper was not defined`,id:t,targetField:e.targetFieldKey}};let a=e.enumMapper.matcher;if((0,o.isString)(a)){let n=getEnumMatcher(a);return(0,o.notMissing)(n)?{value:{value:((0,o.notMissing)(i)?n(i):null)??`unmapped_value`,source_value:i}}:{error:{message:`The built-in matcher "${a}" is not supported`,id:t,targetField:e.targetFieldKey}}}for(let e of a){let{matchExpression:t,value:r}=e;if((0,s.evaluate)(t,n)===!0)return{value:{value:r,source_value:i}}}return{value:{value:`unmapped_value`,source_value:i}}},we=o.z.object({baseUrl:o.z.string().optional().meta({description:`Overrides the connector's base URL for the MCP server.`}),url:o.z.string().optional().meta({description:`MCP server endpoint path.`}),method:o.z.enum([`tools/call`,`tools/list`]).default(`tools/call`).meta({description:"The MCP method to call. Either `tools/call` or `tools/list`."}),toolName:o.z.string().optional().meta({description:`Name of the tool to call. Required when method is tools/call.`}),timeout:o.z.number().int().positive().optional().meta({description:`Request timeout in milliseconds.`}),authorization:Z.optional().meta({description:`Overrides the connector's default authentication for this request.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the argument.`}),value:o.z.unknown().meta({description:`Value of the argument. Supports expressions.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the argument only when it evaluates true.`})}).array().optional().meta({description:`Arguments passed to the MCP tool call.`})}).refine(e=>e.method!==`tools/call`||!!e.toolName,{message:`The 'toolName' parameter is required when method is 'tools/call'`,path:[`toolName`]}),Te=(0,o.zStrictObject)({data:o.z.unknown().optional().meta({description:"The parsed MCP response. For `tools/call` it holds the tool result, for `tools/list` it holds the list of tools."}),raw:o.z.unknown().optional().meta({description:`The raw MCP response before parsing.`}),statusCode:o.z.number().meta({description:`Returns 200 for success, or 502 when the tool returns an error.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`})}).optional(),buildMcpClient=e=>new c.McpClient(e),buildToolArguments=e=>(e??[]).reduce((e,t)=>(e[t.name]=t.value,e),{}),parseJsonText=e=>{try{return JSON.parse(e)}catch{return e}},resolveToolData=e=>{if((0,o.notMissing)(e.structuredContent))return e.structuredContent;let[t,...n]=e.content;return n.length===0&&t?.type===`text`&&typeof t.text==`string`?parseJsonText(t.text):e.content},extractTextMessage=e=>e.content.find(e=>typeof e.text==`string`)?.text,mcpRequestStepFunction=async({block:e,params:t},n=buildMcpClient)=>{let r=t?.args,i=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?(0,s.safeEvaluateRecord)({...t,args:i},e):{},l;try{l=we.parse(a)}catch(t){return buildStepErrorOutput(t,e)}let{baseUrl:u,url:d,method:f,toolName:p,timeout:m,authorization:h,args:g}=l,_=`${u??``}${d??``}`;if(!_)return buildStepErrorOutput(Error(`MCP server URL is missing: set the connector baseUrl or the step url parameter`),e);let v=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,y;try{y=(0,c.createAuthorizationHeaders)((0,o.notMissing)(h)?h:Z.parse(v??{type:`none`}))}catch(t){return buildStepErrorOutput(t,e)}let b=e.connector?.rateLimit,x=e.connector?.concurrency,S=n({serverUrl:_,headers:y,timeout:m,requestConfig:b!==void 0||x!==void 0?{rateLimits:b,concurrency:x}:void 0,context:buildRequestContext(e)});try{if(f===`tools/list`){let t=await S.listTools();return{block:e,successful:!0,output:{data:t.tools,raw:t,statusCode:200}}}if(!p)return buildStepErrorOutput(Error(`The 'toolName' parameter is required when method is 'tools/call'`),e);let t=await S.callTool({name:p,arguments:buildToolArguments(g)});if(t.isError){let n=extractTextMessage(t)??`MCP tool '${p}' returned an error`;return{block:e,successful:!1,errors:[{message:n,kind:`mcp_tool_error`,toolName:p}],output:{statusCode:502,message:n,data:resolveToolData(t),raw:t}}}return{block:e,successful:!0,output:{data:resolveToolData(t),raw:t,statusCode:200}}}catch(t){return buildStepErrorOutput(t,e)}finally{await S.close().catch(()=>void 0)}},generateSamlAssertion=async({cert:e,key:t,issuer:n,lifetime:r,clientId:i,nameId:a,tokenEndpoint:o,audience:s,nameIdentifierFormat:c,createSamlFn:l=e=>f.Saml20.create(e),sleepFn:u=e=>new Promise(t=>setTimeout(t,e))})=>{let d={api_key:i},m={cert:e,key:generatePrivateKey(t),issuer:n,lifetimeInSeconds:r,audiences:s,attributes:d,nameIdentifier:a,nameIdentifierFormat:c,recipient:o,sessionIndex:`_`+(0,p.v4)()},h=Buffer.from(l(m)).toString(`base64`);return await u(1e3),h},generatePrivateKey=e=>{let t=Buffer.from(e,`base64`).toString(`utf-8`).split(`###`);if(t.length!==2)throw Error(`Invalid private key`);let n=t[0];return Buffer.from(`-----BEGIN PRIVATE KEY-----
2
2
  ${n}
3
- -----END PRIVATE KEY-----`)},$=__name(e=>{let t=e.trim();return t.startsWith(`{{`)&&t.endsWith(`}}`)},`isJexlExpression`),Ce=__name((e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`||!e)return e;let n=(0,s.safeEvaluate)($(t)?t:`$.${t}`,e);return n===void 0?e[t]:n},`resolveDataKey`),resolveFromHeaders=(e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`)return null;if($(t)){let n=(0,s.safeEvaluate)(t,e);return typeof n==`string`&&n!==``||typeof n==`number`?n:null}let n=t.toLowerCase(),[,r]=Object.entries(e).find(([e])=>e?.toLowerCase()===n)??[];if(Array.isArray(r)){let e=r.find(e=>typeof e==`string`&&e!==``||typeof e==`number`);return typeof e==`string`||typeof e==`number`?e:null}return typeof r==`string`&&r!==``||typeof r==`number`?r:null},resolveFromData=(e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`||!e)return null;let n=(0,s.safeEvaluate)($(t)?t:`$.${t}`,e);return(0,o.isMissing)(n)?null:typeof n==`string`||typeof n==`number`||typeof n==`object`?n:null},preserveJexlResponseKeys=(e,t)=>{let{nextKey:n,dataKey:r}=e?.response??{},i=n&&$(n),a=r&&$(r);return!i&&!a?t:{...t??{},...i?{nextKey:n}:{},...a?{dataKey:r}:{}}},we=o.z.object({baseUrl:o.z.string().meta({description:`Base URL the paginated requests are made against.`}),url:o.z.string().meta({description:`Endpoint path appended to the base URL.`}),method:o.z.enum(c.HttpMethods).meta({description:`HTTP method to use: get, post, put, patch, or delete.`}),authorization:Z.optional().meta({description:`Overrides the connector's default authentication for this request.`}),saml:(0,o.zStrictObject)({objectKey:o.z.string().meta({description:`Request body key under which the generated base64 SAML assertion is placed.`}),key:o.z.string().meta({description:`Base64-encoded private key used to sign the SAML assertion.`}),clientId:o.z.string().meta({description:`Client identifier included as the api_key attribute in the assertion.`}),cert:o.z.unknown().optional().meta({description:`Signing certificate for the SAML assertion.`}),issuer:o.z.string().optional().meta({description:`Issuer identifier declared in the assertion.`}),lifetime:o.z.number().optional().meta({description:`Assertion validity window in seconds.`}),nameId:o.z.string().optional().meta({description:`Subject NameID identifying the authenticating principal.`}),audience:o.z.string().optional().meta({description:`Intended audience for the assertion.`}),nameIdentifierFormat:o.z.string().optional().meta({description:`Format URI for the subject NameID.`}),tokenEndpoint:o.z.string().optional().meta({description:`Recipient token endpoint the assertion is addressed to.`})}).optional().meta({description:`Generates a signed SAML assertion and merges it into the request body for token exchange.`}),response:(0,o.zStrictObject)({indexField:o.z.string().optional().meta({description:`Field used to key results when returning an indexed map.`}),dataKey:o.z.string().optional().meta({description:`Path to the records array in the response. A path that resolves to a non-array or resolves to nothing is treated as an empty page, so the step succeeds with the records collected so far and logs a warning.`}),nextKey:o.z.string().optional().meta({description:`Path to the next-page token or cursor in the response.`}),nextKeyIn:o.z.enum([`data`,`headers`]).optional().meta({description:`Where the next-page token is read from: the response data or headers.`})}).optional().meta({description:`Controls how each page response is parsed and paginated.`}),iterator:(0,o.zStrictObject)({key:o.z.string().meta({description:`Request field name that carries the page token, offset, or number.`}),in:o.z.enum([`query`,`body`]).meta({description:`Where the pagination field is sent: query or body.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that continues pagination only while it evaluates true.`}),mode:o.z.enum([`cursor`,`offset`,`page`]).optional().meta({description:"Pagination strategy. `cursor` sends the returned next token back as the key and stops when none returns. `offset` advances the key by the number of records consumed. `page` increments the page number and stops on an empty or repeated page. Every mode also stops once `page_size` records are gathered or `iterator.condition` is false."}),startPage:o.z.number().int().min(0).max(2**53-1).optional().meta({description:`First page number to request. Valid only in page mode.`}),maxPage:o.z.number().int().positive().max(1e4).optional().meta({description:"Highest page number allowed in `page` mode. Requesting a higher page fails the step with an error."})}).superRefine((e,t)=>{e.startPage!==void 0&&e.mode!==`page`&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`startPage`],message:`startPage is only valid when iterator.mode is "page"`}),e.maxPage!==void 0&&e.mode!==`page`&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`maxPage`],message:`maxPage is only valid when iterator.mode is "page"`});let n=e.maxPage??1e3;e.mode===`page`&&(e.startPage??1)>n&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`startPage`],message:`startPage must not exceed maxPage (${n})`})}).meta({description:`Controls how subsequent pages are requested.`}),cursor:(0,o.zStrictObject)({token:o.z.string().optional().nullable().meta({description:`Cursor token from the previous page used to fetch the next one.`}),position:o.z.number().optional().nullable().meta({description:`Numeric offset or page position carried over from the previous page.`})}).optional().meta({description:`Pagination position carried over from the previous page request.`}),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional().meta({description:`Remaps matching provider error responses to different statuses or messages.`}),encodeQueryParams:o.z.boolean().optional().meta({description:`Whether to URL-encode query parameter values before sending.`}),cacheTTL:o.z.number().int().nonnegative().optional().meta({description:`Minutes to serve each page from the shared per-account response cache. 0 or omitted disables caching.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the request parameter.`}),value:o.z.unknown().meta({description:`Value of the parameter. Supports expressions.`}),in:o.z.enum(c.RequestParameterLocations).meta({description:`Where to send the parameter: query, body, or headers.`}),spread:o.z.boolean().optional().meta({description:`Merges the value's object entries into the target location instead of setting a single named field.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the parameter only when it evaluates true.`}),arrayFormat:o.z.enum(c.QueryArrayFormats).optional().meta({description:`How array values are serialized in the query string: repeat, brackets, comma, or stringify.`})}).array().optional().meta({description:`Request parameters to send as query, body, or header values.`})}),Te=(0,o.zStrictObject)({data:o.z.unknown().optional().meta({description:`Records accumulated across the fetched pages.`}),raw:o.z.unknown().optional().meta({description:`The raw provider response before parsing.`}),statusCode:o.z.number().meta({description:`HTTP status code of the provider response.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`}),next:o.z.string().optional().nullable().meta({description:`Pagination cursor for the next page, or null when no further pages remain.`}),position:o.z.number().optional().meta({description:`Numeric offset or page position reached, for offset and page pagination modes.`})}).optional(),paginatedRequestStepFunction=async({block:e,params:t})=>{let n=c.RequestClientFactory.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=Number(e.inputs?.page_size),a=Number.isNaN(i)?25:i,l=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,u=t?(0,s.safeEvaluateRecord)({...t,args:l},e):{},d={...u,customErrors:t?.customErrors,iterator:{...u?.iterator??{},condition:t?.iterator?.condition},response:preserveJexlResponseKeys(t,u?.response)},f=d.authorization;if((0,o.notMissing)(f)){let t=Z.safeParse(f);if(!t.success)return buildStepErrorOutput(Error(invalidStepAuthorizationMessage(t.error)),e)}let{baseUrl:p,url:m,method:h,response:g,authorization:_,iterator:v,cursor:y,customErrors:b,encodeQueryParams:x,args:S,saml:C,cacheTTL:w}=we.parse(d),T=u?.authentication?.[e.context.authenticationType]?.[e.context.environment],E=T?.authorization,D=T?.certificates,O=D?(0,c.buildHttpsAgent)(D):void 0,k=(0,o.notMissing)(_)?_:Z.parse(E);if(k.type===`none`&&(0,o.notMissing)(k.signing))return buildStepErrorOutput(Error(`authorization.signing is not supported on paginated_request steps — every page changes the query string, so the signature would have to be recomputed per page; use a request step instead`),e);let A=S?(0,c.parseRequestParameters)(S):{query:{},body:{},headers:{}},j=(0,c.createAuthorizationHeaders)(k),M={...A?.headers??{},...j},N=e.connector?.rateLimit,P=e.connector?.concurrency,F=N!==void 0||P!==void 0?{rateLimits:N,concurrency:P}:void 0,I=buildRequestContext(e),L=(0,o.notMissing)(C)?{[C.objectKey]:await generateSamlAssertion({key:C.key,clientId:C.clientId,cert:C.cert,issuer:C.issuer,lifetime:C.lifetime,audience:C.audience,nameId:C.nameId,nameIdentifierFormat:C.nameIdentifierFormat,tokenEndpoint:C.tokenEndpoint})}:{},R=v.mode===`offset`,z=v.mode===`page`,B=v.maxPage??1e3,V=B+1,H=z?resolveInitialPage(y?.token,v.startPage??1):y?.token??null,U=null,W=null,G=[],K=[],ee=[],q=a,J=y?.position??0,te=!0,Y=!0,X=!0,ne=null;do{if(z&&Number(H)>V)return buildStepErrorOutput(maxPageExceededError(B,H),e);te?te=!1:R||(J=0),H===null?R&&(v.in===`query`?A.query[v.key]=J.toString():v.in===`body`&&(Array.isArray(A.body)||(A.body[v.key]=J))):v.in===`query`?(0,o.isObject)(H)?Object.entries(H).forEach(([e,t])=>{A.query[`${v.key}[${e}]`]=t?.toString()??``}):A.query[v.key]=H.toString():v.in===`body`&&(Array.isArray(A.body)||(A.body[v.key]=H));let t;try{t=await n.performRequest({httpClient:e.httpClient,url:`${p}${m}`,queryParams:{...A?.query},encodeQueryParams:x,method:h,headers:{...M},body:Array.isArray(A?.body)?A.body:{...typeof A?.body==`string`?void 0:A?.body,...L},customErrorConfigs:b,requestConfig:F,httpsAgent:O,credentials:e.credentials,context:I,cacheTTL:w})}catch(t){return buildStepErrorOutput(t,e)}if(U=H,K=g?.dataKey?Ce(t.data,g.dataKey):t.data,!Array.isArray(K)){let n=z?` at page ${U}`:``,r=g?.dataKey?` at "${g.dataKey}"`:``,i=K===null?`null`:typeof K;e.logger?.warning({message:`Pagination stopped${n}: expected an array of records${r} but received ${i}; treating it as an empty page`}),ee.push(t),W=t?.status,Y=!0;break}if(z){let t=(0,o.getContentHash)(K);if(t===ne){e.logger?.warning({message:`Pagination stopped at page ${U}: the provider returned the previous page again, so the page number is not advancing`}),Y=!0;break}ne=t}if(z&&Number(U)>B&&K.length>0)return buildStepErrorOutput(maxPageExceededError(B,U),e);let r=R?K?.slice(0,q):K?.slice(J,J+q);q-=r.length,J+=r.length,ee.push(t),G=G.concat(r),W=t?.status,H=z?incrementPage(Number(U)):Ee({result:t,response:g}),X=(0,o.notMissing)(v.condition)?(0,s.safeEvaluate)(v.condition,t.data)===!0:!0;let i=J>=(K?.length??0),c=(0,o.notMissing)(g?.nextKey),l=r.length===K.length&&q===0;!R&&(c||z)&&i&&(J=0,U=H),Y=R?!X||(0,o.isMissing)(H)&&G.length<a:z?i&&(!X||G.length<a):c?i&&((0,o.isMissing)(H)||!X):!X||(0,o.isMissing)(H)&&G.length<a||l}while((R||(0,o.notMissing)(H))&&X&&G.length<a&&K?.length>0);let re=De(G,g),ie=Y?void 0:U;return{block:e,successful:!0,output:{data:re,raw:ee,statusCode:W,next:z&&typeof ie==`number`?ie.toString():ie,position:Y?void 0:J}}},resolveInitialPage=(e,t)=>{let n=Number(e);return Number.isSafeInteger(n)&&n>=t?n:t},incrementPage=e=>e+1,maxPageExceededError=(e,t)=>Error(`Pagination exceeded iterator.maxPage (${e}) at page ${t}`),invalidStepAuthorizationMessage=e=>`step authorization is invalid, check its credential expressions resolve for this account: ${e.issues.map(e=>e.message).join(`; `)}`,Ee=__name(({result:e,response:t})=>{if((0,o.isMissing)(t?.nextKey))return null;let n=t?.nextKeyIn??`data`,r=t?.nextKey;return n===`headers`?resolveFromHeaders(e.headers,r):resolveFromData(e.data,r)},`resolveNextIterator`),De=__name((e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Oe=o.z.object({baseUrl:o.z.string().optional().meta({description:`Overrides the connector's base URL for this request.`}),url:o.z.string().meta({description:`Endpoint path appended to the base URL.`}),method:o.z.enum(c.HttpMethods).meta({description:`HTTP method to use: get, post, put, patch, or delete.`}),authorization:Z.optional().meta({description:`Overrides the connector's default authentication for this request.`}),certificates:ie.meta({description:`Client TLS certificates and keys for mutual TLS connections.`}),saml:(0,o.zStrictObject)({objectKey:o.z.string().meta({description:`Request body key under which the generated base64 SAML assertion is placed.`}),key:o.z.string().meta({description:`Base64-encoded private key used to sign the SAML assertion.`}),clientId:o.z.string().meta({description:`Client identifier included as the api_key attribute in the assertion.`}),cert:o.z.unknown().optional().meta({description:`Signing certificate for the SAML assertion.`}),issuer:o.z.string().optional().meta({description:`Issuer identifier declared in the assertion.`}),lifetime:o.z.number().optional().meta({description:`Assertion validity window in seconds.`}),nameId:o.z.string().optional().meta({description:`Subject NameID identifying the authenticating principal.`}),audience:o.z.string().optional().meta({description:`Intended audience for the assertion.`}),nameIdentifierFormat:o.z.string().optional().meta({description:`Format URI for the subject NameID.`}),tokenEndpoint:o.z.string().optional().meta({description:`Recipient token endpoint the assertion is addressed to.`})}).optional().meta({description:`Generates a signed SAML assertion and merges it into the request body for token exchange.`}),response:(0,o.zStrictObject)({collection:o.z.boolean().optional().meta({description:`Whether to treat the response payload as a collection of records to index.`}),indexField:o.z.string().optional().meta({description:`Field used to key results when returning an indexed map.`}),dataKey:o.z.string().optional().meta({description:`Path to the field in the response holding the records to extract.`})}).optional().meta({description:`Controls how the raw response is parsed into step output data.`}),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional().meta({description:`Remaps matching provider error responses to different statuses or messages.`}),encodeQueryParams:o.z.boolean().optional().meta({description:`Whether to URL-encode query parameter values before sending.`}),cacheTTL:o.z.number().int().nonnegative().optional().meta({description:`Minutes to serve this request from the shared per-account response cache. 0 or omitted disables caching.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the request parameter.`}),value:o.z.unknown().meta({description:`Value of the parameter. Supports expressions.`}),in:o.z.enum(c.RequestParameterLocations).meta({description:`Where to send the parameter: query, body, or headers.`}),spread:o.z.boolean().optional().meta({description:`Merges the value's object entries into the target location instead of setting a single named field.`}),inline:o.z.boolean().optional().meta({description:`Sends the string value as the raw request body. Valid only as the sole in: body argument.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the parameter only when it evaluates true.`}),arrayFormat:o.z.enum(c.QueryArrayFormats).optional().meta({description:`How array values are serialized in the query string: repeat, brackets, comma, or stringify.`})}).array().optional().meta({description:`Request parameters to send as query, body, or header values.`})}).superRefine((e,t)=>{let n=e.args??[],r=n.map((e,t)=>({arg:e,index:t})).filter(({arg:e})=>e.inline===!0),i=n.filter(e=>e.in===`body`).length;if(n.forEach((e,n)=>{e.inline===!0&&e.in!==`body`&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline is only valid when in is "body", got "${e.in}"`}),e.inline===!0&&e.spread&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with spread`})}),r.length>0&&i>1)for(let{arg:e,index:n}of r)t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: an inline body arg must be the only "in: body" arg, found ${i}; arg conditions are not considered`});if(r.length>0&&e.saml!==void 0)for(let{arg:e,index:n}of r)t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with the saml parameter`});if(r.length>0&&e.cacheTTL!==void 0&&e.cacheTTL>0)for(let{arg:e,index:n}of r)t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with a nonzero cacheTTL`});for(let{arg:e,index:n}of r)typeof e.value==`string`?e.value.length===0&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`value`],message:`args.${e.name}: inline value must be a non-empty string, got an empty string`}):t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`value`],message:`args.${e.name}: inline value must be a non-empty string, got ${typeof e.value}`})}),ke=(0,o.zStrictObject)({data:o.z.unknown().optional().meta({description:`The parsed response payload extracted from the provider response.`}),raw:o.z.unknown().optional().meta({description:`The raw provider response before parsing.`}),statusCode:o.z.number().meta({description:`HTTP status code of the provider response.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`})}).optional(),isJexlExpression=e=>{let t=e.trim();return t.startsWith(`{{`)&&t.endsWith(`}}`)},isErrorWithResponseBody=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`&&`body`in e.response,isErrorWithResponseConfigData=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`&&`config`in e.response&&e.response.config!=null&&typeof e.response.config==`object`&&`data`in e.response.config,requestStepFunction=async({block:e,params:t})=>{let n=c.RequestClientFactory.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?.response?.dataKey,l=a&&isJexlExpression(a),u=t?(0,s.safeEvaluateRecord)({...t,args:i},e):{},d={...u,customErrors:t?.customErrors,response:l?{...u?.response??{},dataKey:a}:u?.response},{baseUrl:f,url:p,method:h,response:g,authorization:_,certificates:v,customErrors:y,encodeQueryParams:b,args:x,saml:S,cacheTTL:C}=Oe.parse(d),w=u?.authentication?.[e.context.authenticationType]?.[e.context.environment],T=w?.authorization,E=v??w?.certificates,D=E?(0,c.buildHttpsAgent)(E):void 0,O=x?(0,c.parseRequestParameters)(x):{query:{},body:{},headers:{}},k=x?.some(e=>e.in===`body`&&e.inline===!0)??!1,A=(0,o.notMissing)(_)?_:Z.parse(T),j=(0,c.createAuthorizationHeaders)(A),M={...O?.headers??{},...j},N=e.connector?.rateLimit,P=e.connector?.concurrency,F=N!==void 0||P!==void 0?{rateLimits:N,concurrency:P}:void 0,I=(0,o.notMissing)(S)?{[S.objectKey]:await generateSamlAssertion({key:S.key,clientId:S.clientId,cert:S.cert,issuer:S.issuer,lifetime:S.lifetime,audience:S.audience,nameId:S.nameId,nameIdentifierFormat:S.nameIdentifierFormat,tokenEndpoint:S.tokenEndpoint})}:{},L=typeof O?.body==`string`||Array.isArray(O?.body)?O?.body:{...O?.body,...I};if(A.type===`none`&&A.signing?.strategy){if(b===!1)return buildStepErrorOutput(Error(`encodeQueryParams: false is not supported when a request signing strategy is configured — signed canonical would not match the wire query`),e);let t=A.signing,n=e.credentials??{};try{let e=(0,c.getSigningStrategy)(t.strategy);if(!e)throw Error(`Signing strategy "${t.strategy}" is not registered`);let r=e({method:h,url:`${f}${p}`,headers:M,query:O?.query??{},body:L},n,t);Object.assign(M,r)}catch(t){return buildStepErrorOutput(t,e)}}let R;try{R=await n.performRequest({httpClient:e.httpClient,url:`${f}${p}`,queryParams:O?.query,encodeQueryParams:b,method:h,headers:M,body:L,customErrorConfigs:y,requestConfig:F,httpsAgent:D,credentials:e.credentials,context:buildRequestContext(e),cacheTTL:C})}catch(t){return k&&(isErrorWithResponseBody(t)&&(t.response.body=m.REDACT_CENSOR),isErrorWithResponseConfigData(t)&&(t.response.config.data=m.REDACT_CENSOR)),buildStepErrorOutput(t,e)}return{block:e,successful:!0,output:{data:Ae(g?.dataKey?resolveDataKey(R.data,g.dataKey):R.data,g),raw:k&&R&&`body`in R?{...R,body:m.REDACT_CENSOR}:R,statusCode:R?.status,message:R?.message}}},resolveDataKey=(e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`||!e)return e;let n=(0,s.safeEvaluate)(isJexlExpression(t)?t:`$.${t}`,e);return n===void 0?e[t]:n},Ae=__name((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),je=o.z.union([o.z.string(),o.z.number()]),Me=(0,o.zStrictObject)({algorithm:o.z.literal(`RS256`).meta({description:`Signing algorithm. Only RS256 is supported.`}),privateKey:o.z.string().meta({description:`PEM-encoded private key used to sign the token.`}),claims:o.z.record(o.z.string(),je).meta({description:"Claims to include in the JWT payload, such as `iss`, `scope`, and `aud`. `iat` and `exp` are required numbers with `exp` after `iat`, and accept `now` or `now+<N>s|m|h` tokens."})}),Ne=(0,o.zStrictObject)({token:o.z.string().meta({description:`The signed JWT.`}),expiresIn:o.z.number().meta({description:`Token lifetime in seconds.`}),publicKeyFingerprint:o.z.string().meta({description:`Fingerprint of the public key matching the signing key.`})}),computePublicKeyFingerprint=e=>{let t=e.export({format:`der`,type:`spki`});return`SHA256:${(0,h.createHash)(`sha256`).update(t).digest(`base64`)}`},Pe=/^now$/,Fe=/^now\+(?<amount>\d+)(?<unit>[smh])$/,Ie=`{publicKeyFingerprint}`,Le={s:1,m:60,h:3600},Re=new Set([`iat`,`exp`,`nbf`]),resolveClaimValue=(e,t,{now:n,publicKeyFingerprint:r})=>{if(typeof t==`number`)return t;let i=t.includes(Ie)?t.split(Ie).join(r):t;if(!Re.has(e))return i;if(Pe.test(i))return n;let a=i.match(Fe);return a?.groups?n+Number(a.groups.amount)*Le[a.groups.unit]:i},signJwtStepFunction=async({block:e,params:t})=>{try{let n=t?(0,s.safeEvaluateRecord)(t,e):void 0,{algorithm:r,privateKey:i,claims:a}=Me.parse(n),o=(0,h.createPrivateKey)(i),c=computePublicKeyFingerprint((0,h.createPublicKey)(o)),l=Math.floor(Date.now()/1e3),u={};for(let[e,t]of Object.entries(a))u[e]=resolveClaimValue(e,t,{now:l,publicKeyFingerprint:c});let{iat:d,exp:f}=u;if(typeof d!=`number`||typeof f!=`number`)throw Error(`signJwt requires numeric 'iat' and 'exp' claims (use 'now' / 'now+<N>s|m|h' tokens, or pass numbers directly)`);if(f<=d)throw Error(`signJwt requires 'exp' to be greater than 'iat'`);let p=await new g.SignJWT(u).setProtectedHeader({alg:r}).sign(o);return{block:{...e},successful:!0,output:{token:p,expiresIn:f-d,publicKeyFingerprint:c}}}catch(t){return buildStepErrorOutput(t,e)}},ze=o.z.object({baseUrl:o.z.string().optional().meta({description:`Overrides the connector's base URL for the SOAP service.`}),url:o.z.string().meta({description:`SOAP endpoint path appended to the base URL.`}),method:o.z.enum(c.HttpMethods).meta({description:`HTTP method to use for the SOAP call, typically post.`}),authorization:o.z.discriminatedUnion(`type`,[(0,o.zStrictObject)({type:o.z.literal(`none`).meta({description:`Selects no authentication.`})}),(0,o.zStrictObject)({type:o.z.literal(`basic`).meta({description:`Selects HTTP basic authentication.`}),username:o.z.string().optional().meta({description:`Username for basic authentication.`}),password:o.z.string().optional().meta({description:`Password for basic authentication.`}),encoding:o.z.string().optional().meta({description:`Encoding applied to the username and password, such as base64.`})}),(0,o.zStrictObject)({type:o.z.literal(`bearer`).meta({description:`Selects bearer token authentication.`}),token:o.z.string().meta({description:`Bearer token sent with the request.`}),includeBearer:o.z.boolean().optional().default(!0).meta({description:"Whether to prefix the token with `Bearer ` in the header. Defaults to true."})}),(0,o.zStrictObject)({type:o.z.literal(`oauth2`).meta({description:`Selects OAuth 2.0 authentication.`}),token:o.z.string().meta({description:`OAuth 2.0 access token sent with the request.`}),includeBearer:o.z.boolean().optional().default(!0).meta({description:"Whether to prefix the token with `Bearer ` in the header. Defaults to true."})})]).optional().meta({description:`Overrides the connector's default authentication for this request.`}),envelope:o.z.union([o.z.string(),o.z.record(o.z.string(),o.z.unknown())]).optional().meta({description:`SOAP envelope template, as a string or object, used to build the request body.`}),namespaces:o.z.strictObject({namespaceIdentifier:o.z.string().meta({description:`XML namespace prefix.`}),namespace:o.z.string().meta({description:`Namespace URI bound to the prefix.`})}).array().optional().meta({description:`XML namespace declarations added to the SOAP envelope.`}),soapOperation:o.z.string().optional().meta({description:`Name of the SOAP operation to invoke.`}),soapAction:o.z.string().optional().meta({description:`Value sent in the SOAPAction HTTP header.`}),useSoapContext:o.z.boolean().optional().default(!0).meta({description:`Whether to wrap the request using the SOAP context.`}),response:(0,o.zStrictObject)({collection:o.z.boolean().optional().meta({description:`Currently not in use.`}),indexField:o.z.string().optional().meta({description:`Field used to key results when returning an indexed map.`}),dataKey:o.z.string().optional().meta({description:`Path to the records array within the response.`}),nextKey:o.z.string().optional().meta({description:`Path to the next-page token or cursor in the response.`}),nextKeyIn:o.z.enum([`data`,`headers`]).optional().meta({description:`Where the next-page token is read from: the response data or headers.`})}).optional().meta({description:`Controls how each page response is parsed and paginated.`}),iterator:(0,o.zStrictObject)({key:o.z.string().meta({description:`Request field name that carries the page token or number.`}),in:o.z.enum([`query`,`body`]).meta({description:`Where the pagination field is sent: query or body.`})}).meta({description:`Controls how subsequent pages are requested.`}),cursor:(0,o.zStrictObject)({token:o.z.string().optional().nullable().meta({description:`Cursor token from the previous page used to fetch the next one.`}),position:o.z.number().optional().nullable().meta({description:`How far into the previous page was read, so this request resumes from there.`})}).optional().meta({description:`Pagination position carried over from the previous page request.`}),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional().meta({description:`Remaps matching provider error responses to different statuses or messages.`}),encodeQueryParams:o.z.boolean().optional().meta({description:`Whether to URL-encode query parameter values before sending.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the request parameter.`}),value:o.z.unknown().meta({description:`Value of the parameter. Supports expressions.`}),in:o.z.enum(c.RequestParameterLocations).meta({description:`Where to send the parameter: query, body, or headers.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the parameter only when it evaluates true.`}),arrayFormat:o.z.enum(c.QueryArrayFormats).optional().meta({description:`How array values are serialized in the query string: repeat, brackets, comma, or stringify.`})}).array().optional().meta({description:`Request parameters to send as query, body, or header values.`})}),Be=(0,o.zStrictObject)({data:o.z.unknown().optional().meta({description:`Records accumulated across the fetched pages.`}),raw:o.z.unknown().optional().meta({description:`The raw provider response before parsing.`}),statusCode:o.z.number().meta({description:`HTTP status code of the provider response.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`}),next:o.z.string().optional().nullable().meta({description:"Cursor token for the next page. Null means the next request continues from `position` in the current page, and it is omitted when no pages remain."}),position:o.z.number().optional().meta({description:`How far into the current page has been read, saved in the cursor so the next request resumes from there.`})}).optional(),soapPaginatedRequestStepFunction=async({block:e,params:t})=>{let n=c.RequestClientFactory.build(`soap`);if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=Number(e.inputs?.page_size),a=Number.isNaN(i)?25:i,l=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,u=t?(0,s.safeEvaluateRecord)({...t,args:l},e):{},d={...u,customErrors:t?.customErrors,response:preserveJexlResponseKeys(t,u?.response)},f=t?.envelope,{baseUrl:p,url:m,method:h,response:g,iterator:_,cursor:v,authorization:y,customErrors:b,encodeQueryParams:x,args:S,soapOperation:C,namespaces:w,soapAction:T,useSoapContext:E}=ze.parse(d),D=u?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,O=S?(0,c.parseRequestParameters)(S):{query:{},body:{},headers:{}},k=(0,c.createAuthorizationHeaders)((0,o.notMissing)(y)?y:Z.parse(D)),A={...O?.headers??{},...k},j=e.connector?.rateLimit,M=e.connector?.concurrency,N={...j!==void 0||M!==void 0?{rateLimits:j,concurrency:M}:void 0,soapOperation:C,namespaces:w,soapAction:T,soapContext:E?{username:e.credentials?.username,password:e.credentials?.password}:void 0},P=v?.token??null,F=null,I=null,L=[],R=[],z=[],B=a,V=v?.position??0,H=!0,U;do{H?H=!1:V=0,P!==null&&(_.in===`query`?O.query[_.key]=P.toString():_.in===`body`&&(O.body[_.key]=P));let t;try{t=await n.performRequest({httpClient:e.httpClient,url:`${p}${m}`,queryParams:{...O?.query},encodeQueryParams:x,method:h,headers:A,body:O?.body,customErrorConfigs:b,requestConfig:{...N,...(0,o.notMissing)(f)&&{envelope:evaluateEnvelope(f,e,P)}},credentials:e.credentials,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}F=P,R=g?.dataKey?Ce(t.data,g.dataKey):t.data,Array.isArray(R)||(R=R?[R]:[]);let r=R?.slice(V,V+B);B-=r.length,V+=r.length,z.push(t),L=L.concat(r),I=t?.status,P=resolveNextIterator({result:t,response:g});let i=V>=(R?.length??0),s=(0,o.notMissing)(g?.nextKey),c=r.length===R.length&&B===0;s&&i&&(V=0,F=P),U=s?i&&(0,o.isMissing)(P):(0,o.isMissing)(P)&&L.length<a||c}while((0,o.notMissing)(P)&&L.length<a&&R?.length>0);return{block:e,successful:!0,output:{data:Ve(L,g),raw:z,statusCode:I,next:U?void 0:stringifyCursorToken(F),position:U?void 0:V}}},stringifyCursorToken=e=>e===null?null:String(e),evaluateEnvelope=(e,t,n)=>{let r={...t,pageIterator:n};return typeof e==`string`?(0,s.safeEvaluate)(e,r):(0,s.safeEvaluateRecord)(e,r)},resolveNextIterator=({result:e,response:t})=>{if((0,o.isMissing)(t?.nextKey))return null;let n=t?.nextKeyIn??`data`,r=t?.nextKey,i=n===`headers`?resolveFromHeaders(e.headers,r):resolveFromData(e.data,r);return typeof i==`string`||typeof i==`number`?i:null},Ve=__name((e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),He=o.z.object({baseUrl:o.z.string().optional().meta({description:`Overrides the connector's base URL for the SOAP service.`}),url:o.z.string().meta({description:`SOAP endpoint path appended to the base URL.`}),method:o.z.enum(c.HttpMethods).meta({description:`HTTP method to use for the SOAP call, typically post.`}),authorization:Z.optional().meta({description:`Overrides the connector's default authentication for this request.`}),envelope:o.z.union([o.z.string(),o.z.record(o.z.string(),o.z.unknown())]).optional().meta({description:`SOAP envelope template, as a string or object, used to build the request body.`}),namespaces:o.z.strictObject({namespaceIdentifier:o.z.string().meta({description:`XML namespace prefix.`}),namespace:o.z.string().meta({description:`Namespace URI bound to the prefix.`})}).array().optional().meta({description:`XML namespace declarations added to the SOAP envelope.`}),soapOperation:o.z.string().optional().meta({description:`Name of the SOAP operation to invoke.`}),soapAction:o.z.string().optional().meta({description:`Value sent in the SOAPAction HTTP header.`}),useSoapContext:o.z.boolean().optional().default(!0).meta({description:`Whether to wrap the request using the SOAP context.`}),response:(0,o.zStrictObject)({collection:o.z.boolean().optional().meta({description:`Whether to treat the response payload as a collection of records to index.`}),indexField:o.z.string().optional().meta({description:`Field used to key results when returning an indexed map.`}),dataKey:o.z.string().optional().meta({description:`Top-level response key holding the records to extract.`})}).optional().meta({description:`Controls how the raw response is parsed into step output data.`}),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional().meta({description:`Remaps matching provider error responses to different statuses or messages.`}),encodeQueryParams:o.z.boolean().optional().meta({description:`Whether to URL-encode query parameter values before sending.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the request parameter.`}),value:o.z.unknown().meta({description:`Value of the parameter. Supports expressions.`}),in:o.z.enum(c.RequestParameterLocations).meta({description:`Where to send the parameter: query, body, or headers.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the parameter only when it evaluates true.`}),arrayFormat:o.z.enum(c.QueryArrayFormats).optional().meta({description:`How array values are serialized in the query string: repeat, brackets, comma, or stringify.`})}).array().optional().meta({description:`Request parameters to send as query, body, or header values.`})}),Ue=(0,o.zStrictObject)({data:o.z.unknown().optional().meta({description:`The parsed response payload extracted from the SOAP response.`}),raw:o.z.unknown().optional().meta({description:`The raw provider response before parsing.`}),statusCode:o.z.number().meta({description:`HTTP status code of the provider response.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`})}).optional(),soapRequestStepFunction=async({block:e,params:t})=>{let n=c.RequestClientFactory.build(`soap`);if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?(0,s.safeEvaluateRecord)({...t,args:i},e):{},l={...a,customErrors:t?.customErrors},{baseUrl:u,url:d,method:f,response:p,authorization:m,customErrors:h,encodeQueryParams:g,args:_,soapOperation:v,namespaces:y,envelope:b,soapAction:x,useSoapContext:S}=He.parse(l),C=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,w=_?(0,c.parseRequestParameters)(_):{query:{},body:{},headers:{}},T=(0,c.createAuthorizationHeaders)((0,o.notMissing)(m)?m:Z.parse(C)),E={...w?.headers??{},...T},D=e.connector?.rateLimit,O=e.connector?.concurrency,k={...D!==void 0||O!==void 0?{rateLimits:D,concurrency:O}:void 0,soapOperation:v,namespaces:y,envelope:b,soapAction:x,soapContext:S?{username:e.credentials?.username,password:e.credentials?.password}:void 0},A;try{A=await n.performRequest({httpClient:e.httpClient,url:`${u}${d}`,queryParams:w?.query,encodeQueryParams:g,method:f,headers:E,body:w?.body,customErrorConfigs:h,requestConfig:k,credentials:e.credentials,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}return{block:e,successful:!0,output:{data:We(p?.dataKey?A.data[p?.dataKey]:A.data,p),raw:A,statusCode:A?.status,message:A?.message}}},We=__name((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Ge=o.z.object({values:o.z.string().or(o.z.record(o.z.string(),o.z.unknown())).or(o.z.array(o.z.unknown())).meta({description:`Static values to return, as an object, an array, or an expression string.`})}),Ke=o.z.object({data:o.z.unknown().meta({description:`The static values returned by the step.`})}),staticValuesStepFunction=async({block:e,params:t})=>{let{values:n}=Ge.parse(t),r=Array.isArray(n)?n.map(t=>evaluateValue(t,e)):evaluateValue(n,e);return{block:{...e},successful:!0,output:{data:r}}},evaluateValue=(e,t)=>(0,o.isString)(e)?(0,s.safeEvaluate)(e,t):(0,o.isObject)(e)?(0,s.safeEvaluateRecord)(e,t):e,qe=o.z.object({targetFieldKey:o.z.string().meta({description:`Key of the field to cast.`}),type:o.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]).meta({description:`Target data type to cast the field to.`}),array:o.z.boolean().default(!1).meta({description:"Whether the field holds an array of the given type. A primitive array is passed through unchanged, and an object array still has each element processed through `properties`."}),custom:o.z.boolean().default(!1).meta({description:`Whether the field is a custom, non-unified field.`}),hidden:o.z.boolean().default(!1).meta({description:`Currently not in use.`}),properties:o.z.lazy(()=>qe).array().optional().meta({description:`Nested field casts applied when the type is object.`}),requiredScopes:o.z.string().array().optional().meta({description:`Scopes that must be granted for the field to be included.`})}),Je=o.z.object({fields:qe.array().optional().meta({description:`Definitions of the fields to cast.`}),dataSource:o.z.string().meta({description:`Reference to the source data to cast.`})}),Ye=o.z.object({data:o.z.unknown().meta({description:`The source data with fields cast to their target types.`})});let Xe=function(e){return e.String=`string`,e.Number=`number`,e.Boolean=`boolean`,e.DateTimeString=`datetime_string`,e}({});const typecast=({value:e,type:t,format:n})=>{if((0,o.isMissing)(e))return null;switch(t){case`string`:return(0,o.safeParseToString)({value:e});case`number`:return(0,o.safeParseToNumber)({value:e});case`boolean`:return(0,o.safeParseToBoolean)({value:e});case`datetime_string`:return(0,o.safeParseToDateTimeString)({value:e,format:n});default:return e}},isFieldSupportedType=e=>Object.values(Xe).includes(e),Ze=__name(async({block:e})=>{let t=e?.fieldConfigs;if(!t||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let n;return n=Array.isArray(e.result)?e.result.map(e=>Qe(e,t)):Qe(e.result,t),{block:{...e,result:n},successful:!0}},`typecastStepFunction`),Qe=__name((e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i}=t;isFieldSupportedType(i)&&(!t.custom&&(0,o.notMissing)(n[r])?n[r]=typecast({value:e[r],type:i}):n.unified_custom_fields&&(0,o.notMissing)(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=typecast({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},`mapSingleRecord`),typecastStepFunction=async({block:e,params:t})=>{let{fields:n,dataSource:r}=Je.parse(t),i=(0,s.evaluate)(r,buildExpressionContext(e));if(!n||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let a;return a=Array.isArray(i)?i.map(e=>mapSingleRecord(e,n)):mapSingleRecord(i,n),{block:{...e},successful:!0,output:{data:a}}},handleObjectField=(e,t)=>!e.properties||!t?t:Array.isArray(t)?t.map(t=>typeof t==`object`&&t?mapSingleRecord(t,e.properties):t):typeof t==`object`&&t?mapSingleRecord(t,e.properties):t,mapSingleRecord=(e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i,array:a}=t;i===`object`?!t.custom&&(0,o.notMissing)(n[r])?n[r]=handleObjectField(t,e[r]):n.unified_custom_fields&&(0,o.notMissing)(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=handleObjectField(t,e.unified_custom_fields?.[r])):isFieldSupportedType(i)&&(!t.custom&&(0,o.notMissing)(n[r])?(!a||!Array.isArray(n[r]))&&(n[r]=typecast({value:e[r],type:i})):n.unified_custom_fields&&(0,o.notMissing)(n.unified_custom_fields?.[r])&&(!a||!Array.isArray(n.unified_custom_fields[r]))&&(n.unified_custom_fields[r]=typecast({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},$e=(0,o.zStrictObject)({content:o.z.string().meta({description:`The file content as base64 encoded string`}),contentType:o.z.string().optional().meta({description:`The MIME type for the binary content (defaults to application/octet-stream)`})}),et=o.z.object({baseUrl:o.z.string().optional().meta({description:`Overrides the connector's base URL for the upload.`}),url:o.z.string().meta({description:`Upload endpoint path appended to the base URL.`}),method:o.z.enum(c.HttpMethods).default(`post`).meta({description:`HTTP method to use for the upload.`}),authorization:Z.optional().meta({description:`Overrides the connector's default authentication for this request.`}),binaryContent:$e.meta({description:`Raw binary content for octet-stream uploads`}),response:(0,o.zStrictObject)({collection:o.z.boolean().optional().meta({description:`Whether to treat the response payload as a collection of records to index.`}),indexField:o.z.string().optional().meta({description:`Field used to key results when returning an indexed map.`}),dataKey:o.z.string().optional().meta({description:`Top-level response key holding the records to extract.`})}).optional().meta({description:`Controls how the raw response is parsed into step output data.`}),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional().meta({description:`Remaps matching provider error responses to different statuses or messages.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the request parameter.`}),value:o.z.unknown().meta({description:`Value of the parameter. Supports expressions.`}),in:o.z.enum(c.RequestParameterLocations).meta({description:`Where to send the parameter: query, body, or headers.`}),spread:o.z.boolean().optional().meta({description:`Merges the value's object entries into the target location instead of setting a single named field.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the parameter only when it evaluates true.`}),arrayFormat:o.z.enum(c.QueryArrayFormats).optional().meta({description:`How array values are serialized in the query string: repeat, brackets, comma, or stringify.`})}).array().optional().meta({description:`Additional request parameters (query params, headers)`})}),tt=(0,o.zStrictObject)({data:o.z.unknown().optional().meta({description:`The parsed response payload from the upload.`}),raw:o.z.unknown().optional().meta({description:`The raw provider response before parsing.`}),statusCode:o.z.number().meta({description:`HTTP status code of the provider response.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`})}).optional(),uploadBinaryStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n}=t,r=n?n.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,i=t?(0,s.safeEvaluateRecord)({...t,args:r},e):{},a={...i,customErrors:t?.customErrors},{baseUrl:l,url:u,method:d,response:f,authorization:p,binaryContent:m,args:h,customErrors:g}=et.parse(a),_=i?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,v=h?(0,c.parseRequestParameters)(h):{query:{},body:{},headers:{}},y=(0,c.createAuthorizationHeaders)((0,o.notMissing)(p)?p:Z.parse(_)),b=Buffer.from(m.content,`base64`),x={"content-type":m.contentType??`application/octet-stream`,...v?.headers??{},...y},S=e.connector?.rateLimit,C=e.connector?.concurrency,w=S!==void 0||C!==void 0?{rateLimits:S,concurrency:C}:void 0,T;try{T=await e.httpClient.request({url:`${l??``}${u}`,method:d,headers:x,queryParams:v?.query,payload:b,requestConfig:w,context:buildRequestContext(e)})}catch(t){let n=t;return{block:e,successful:!1,errors:[(0,c.serializeHttpResponseError)(t)],output:{statusCode:n?.response?.status??500,message:n?.response?.message}}}let E=(0,c.translateCustomError)(T,g,e.credentials);return(0,c.isFailedStatusCode)(E?.status)?{block:e,successful:!1,errors:[(0,c.serializeHttpResponseError)(new c.HttpResponseError(E,E.message))],output:{statusCode:E.status,message:E.message}}:{block:e,successful:!0,output:{data:nt(f?.dataKey?E.data[f?.dataKey]:E.data,f),raw:E,statusCode:E?.status,message:E?.message}}},nt=__name((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),rt=(0,o.zStrictObject)({fieldName:o.z.string().meta({description:`The form field name for the file`}),content:o.z.string().meta({description:`The file content as base64 encoded string`}),filename:o.z.string().meta({description:`The filename to use in the upload`}),contentType:o.z.string().optional().meta({description:`The MIME type of the file (e.g., "image/png", "application/pdf")`})}),it=o.z.object({baseUrl:o.z.string().optional().meta({description:`Overrides the connector's base URL for the upload.`}),url:o.z.string().meta({description:`Upload endpoint path appended to the base URL.`}),method:o.z.enum(c.HttpMethods).default(`post`).meta({description:`HTTP method to use for the upload.`}),authorization:Z.optional().meta({description:`Overrides the connector's default authentication for this request.`}),file:rt.meta({description:`The file to upload`}),additionalFields:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the form field.`}),value:o.z.unknown().meta({description:`Value of the form field.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the field only when it evaluates true.`}),contentType:o.z.string().optional().meta({description:`The MIME type for this form field (e.g., "application/json")`})}).array().optional().meta({description:`Additional form fields to include in the multipart request`}),response:(0,o.zStrictObject)({collection:o.z.boolean().optional().meta({description:`Whether to treat the response payload as a collection of records to index.`}),indexField:o.z.string().optional().meta({description:`Field used to key results when returning an indexed map.`}),dataKey:o.z.string().optional().meta({description:`Top-level response key holding the records to extract.`})}).optional().meta({description:`Controls how the raw response is parsed into step output data.`}),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional().meta({description:`Remaps matching provider error responses to different statuses or messages.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the request parameter.`}),value:o.z.unknown().meta({description:`Value of the parameter. Supports expressions.`}),in:o.z.enum(c.RequestParameterLocations).meta({description:`Where to send the parameter: query, body, or headers.`}),spread:o.z.boolean().optional().meta({description:`Merges the value's object entries into the target location instead of setting a single named field.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the parameter only when it evaluates true.`}),arrayFormat:o.z.enum(c.QueryArrayFormats).optional().meta({description:`How array values are serialized in the query string: repeat, brackets, comma, or stringify.`})}).array().optional().meta({description:`Additional request parameters (query params, headers)`})}),at=(0,o.zStrictObject)({data:o.z.unknown().optional().meta({description:`The parsed response payload from the upload.`}),raw:o.z.unknown().optional().meta({description:`The raw provider response before parsing.`}),statusCode:o.z.number().meta({description:`HTTP status code of the provider response.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`})}).optional(),uploadFileStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n,additionalFields:r}=t,i=n?n.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,l=t?(0,s.safeEvaluateRecord)({...t,args:i,additionalFields:a},e):{},u={...l,customErrors:t?.customErrors},{baseUrl:d,url:f,method:p,response:m,authorization:h,file:g,additionalFields:v,args:y,customErrors:b}=it.parse(u),x=l?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,S=y?(0,c.parseRequestParameters)(y):{query:{},body:{},headers:{}},C=(0,c.createAuthorizationHeaders)((0,o.notMissing)(h)?h:Z.parse(x)),w=new _.default;if(v)for(let e of v){let t=typeof e.value==`object`?JSON.stringify(e.value):String(e.value);w.append(e.name,t,e.contentType?{contentType:e.contentType}:void 0)}let T=Buffer.from(g.content,`base64`);w.append(g.fieldName,T,{filename:g.filename,contentType:g.contentType});let E={...w.getHeaders(),...S?.headers??{},...C},D=e.connector?.rateLimit,O=e.connector?.concurrency,k=D!==void 0||O!==void 0?{rateLimits:D,concurrency:O}:void 0,A;try{A=await e.httpClient.request({url:`${d??``}${f}`,method:p,headers:E,queryParams:S?.query,payload:w,requestConfig:k,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}let j=(0,c.translateCustomError)(A,b,e.credentials);return(0,c.isFailedStatusCode)(j?.status)?buildStepErrorOutput(new c.HttpResponseError(j,j.message),e):{block:e,successful:!0,output:{data:indexResponseData(m?.dataKey?j.data[m?.dataKey]:j.data,m),raw:j,statusCode:j?.status,message:j?.message}}},indexResponseData=(e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e};let ot=function(e){return e.TYPECAST=`typecast`,e.MAP_FIELDS=`map_fields`,e.GROUP_DATA=`group_data`,e.REQUEST=`request`,e.PAGINATED_REQUEST=`paginated_request`,e.SOAP_REQUEST=`soap_request`,e.SOAP_PAGINATED_REQUEST=`soap_paginated_request`,e.STATIC_VALUES=`static_values`,e.UPLOAD_FILE=`upload_file`,e.UPLOAD_BINARY=`upload_binary`,e.DOWNLOAD_FILE=`download_file`,e.EMIT_EVENT=`emit_event`,e.BROWSER_USE=`browser_use`,e.CODE_EXECUTION_LAMBDA=`code_execution_lambda`,e.SIGN_JWT=`sign_jwt`,e.MCP_REQUEST=`mcp_request`,e}({});const st={typecast:{v1:{fn:Ze},v2:{fn:typecastStepFunction,inputSchema:Je,outputSchema:Ye}},map_fields:{v1:{fn:pe},v2:{fn:mapFieldsStepFunction,inputSchema:_e,outputSchema:ve}},request:{v1:{fn:requestStepFunction,inputSchema:Oe,outputSchema:ke}},group_data:{v1:{fn:groupDataStepFunction,inputSchema:de,outputSchema:fe}},paginated_request:{v1:{fn:paginatedRequestStepFunction,inputSchema:we,outputSchema:Te}},soap_request:{v1:{fn:soapRequestStepFunction,inputSchema:He,outputSchema:Ue}},soap_paginated_request:{v1:{fn:soapPaginatedRequestStepFunction,inputSchema:ze,outputSchema:Be}},static_values:{v1:{fn:staticValuesStepFunction,inputSchema:Ge,outputSchema:Ke}},upload_file:{v1:{fn:uploadFileStepFunction,inputSchema:it,outputSchema:at}},upload_binary:{v1:{fn:uploadBinaryStepFunction,inputSchema:et,outputSchema:tt}},download_file:{v1:{fn:downloadFileStepFunction,inputSchema:ae,outputSchema:oe}},emit_event:{v1:{fn:emitEventStepFunction,inputSchema:se,outputSchema:ce}},browser_use:{v1:{fn:browserUseStepFunction,inputSchema:U,outputSchema:W}},code_execution_lambda:{v1:{fn:codeExecutionLambdaStepFunction,inputSchema:G,outputSchema:K}},sign_jwt:{v1:{fn:signJwtStepFunction,inputSchema:Me,outputSchema:Ne}},mcp_request:{v1:{fn:mcpRequestStepFunction,inputSchema:xe,outputSchema:Se}}},formatZodIssues=(e,t,n)=>e instanceof o.z.ZodError?e.issues.map(e=>({...e,kind:t,functionName:n})):[{kind:t,functionName:n,message:e?.message??`unknown error`}],stepFunctionEnhancedWithSchemasValidation=(e,t)=>async({block:n,params:r})=>{try{e.inputSchema&&e.inputSchema.parse(r)}catch(e){return{block:n,successful:!1,errors:formatZodIssues(e,`input_schema_validation`,t)}}let i=await e.fn({block:n,params:r});try{e.outputSchema&&e.outputSchema.parse(i.output)}catch(e){return{block:n,successful:!1,errors:formatZodIssues(e,`output_schema_validation`,t)}}return i},ct={build({functionName:e,version:t=`1`,validateSchemas:n=!1,stepFunctionsList:r=st}){let i=r?.[e]?.[`v${t}`];if(!i)throw Error(`Unknown step function: ${e} v${t}`);return n?{...i,fn:stepFunctionEnhancedWithSchemasValidation(i,e)}:i}},isForeachStep=e=>`iterator`in e&&typeof e.iterator==`string`;exports.AUTHORIZATION_SCHEMA=Z,exports.ActionTypes=A,exports.AuthType=H,exports.BARE_JEXL_REQUIREMENT=T,exports.BROWSER_USE_INPUT_PARAMS=U,exports.BROWSER_USE_OUTPUT=W,exports.CODE_EXECUTION_LAMBDA_INPUT_PARAMS=G,exports.CODE_EXECUTION_LAMBDA_OUTPUT=K,exports.COMPOSITE_ID_LATEST_VERSION=1,exports.ChangelogLabels=k,exports.CoreError=C,exports.DOWNLOAD_FILE_INPUT_PARAMS=ae,exports.DOWNLOAD_FILE_OUTPUT=oe,exports.EMIT_EVENT_INPUT_PARAMS=se,exports.EMIT_EVENT_OUTPUT=ce,exports.Effects=j,exports.ExecutionModes=I,exports.FORMAT_PATTERNS=E,exports.GROUP_DATA_INPUT_PARAMS=de,exports.GROUP_DATA_OUTPUT=fe,exports.INPUT_ENUM_REGISTRY=D,exports.InputFormats=P,exports.InputLocations=N,exports.InputTypes=F,exports.MAP_FIELDS_INPUT_PARAMS=_e,exports.MAP_FIELDS_OUTPUT=ve,exports.MCP_REQUEST_INPUT_PARAMS=xe,exports.MCP_REQUEST_OUTPUT=Se,exports.PAGINATED_REQUEST_INPUT_PARAMS=we,exports.PAGINATED_REQUEST_OUTPUT=Te,exports.REQUEST_INPUT_PARAMS=Oe,exports.REQUEST_OUTPUT=ke,exports.ReleaseStages=O,exports.SIGN_JWT_INPUT_PARAMS=Me,exports.SIGN_JWT_OUTPUT=Ne,exports.SOAP_PAGINATED_REQUEST_INPUT_PARAMS=ze,exports.SOAP_PAGINATED_REQUEST_OUTPUT=Be,exports.SOAP_REQUEST_INPUT_PARAMS=He,exports.SOAP_REQUEST_OUTPUT=Ue,exports.STATIC_VALUES_INPUT_PARAMS=Ge,exports.STATIC_VALUES_OUTPUT=Ke,exports.SchemaTypes=M,exports.SourceType=z,exports.StepFunctionName=ot,exports.StepFunctionsFactory=ct,exports.StepFunctionsRegistry=st,exports.StreamType=V,exports.TYPECAST_INPUT_PARAMS=Je,exports.TYPECAST_OUTPUT=Ye,exports.TransportType=B,exports.UPLOAD_BINARY_INPUT_PARAMS=et,exports.UPLOAD_BINARY_OUTPUT=tt,exports.UPLOAD_FILE_INPUT_PARAMS=it,exports.UPLOAD_FILE_OUTPUT=at,exports.areCursorsEqual=areCursorsEqual,exports.buildExpressionContext=buildExpressionContext,exports.computeDataSyncFingerprint=computeDataSyncFingerprint,exports.decodeCompositeId=decodeCompositeId,exports.encodeCompositeId=encodeCompositeId,exports.evaluateEventRouter=evaluateEventRouter,exports.evaluateExternalAccountIdExtractor=evaluateExternalAccountIdExtractor,exports.expandCursor=expandCursor,exports.getCategoryDetails=getCategoryDetails,exports.getInputEnumValues=getInputEnumValues,exports.getIteratorLocation=getIteratorLocation,exports.getPaginationKeys=getPaginationKeys,exports.isBareJexl=isBareJexl,exports.isCompositeId=isCompositeId,exports.isCoreError=isCoreError,exports.isCursorEmpty=isCursorEmpty,exports.isForeachStep=isForeachStep,exports.isValidCategory=isValidCategory,exports.isValidEnumRef=isValidEnumRef,exports.minifyCursor=minifyCursor,exports.stripIncrementalParams=stripIncrementalParams,exports.stripPaginationParams=stripPaginationParams,exports.updateCursor=updateCursor;
3
+ -----END PRIVATE KEY-----`)},$=__name(e=>{let t=e.trim();return t.startsWith(`{{`)&&t.endsWith(`}}`)},`isJexlExpression`),Ee=__name((e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`||!e)return e;let n=(0,s.safeEvaluate)($(t)?t:`$.${t}`,e);return n===void 0?e[t]:n},`resolveDataKey`),resolveFromHeaders=(e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`)return null;if($(t)){let n=(0,s.safeEvaluate)(t,e);return typeof n==`string`&&n!==``||typeof n==`number`?n:null}let n=t.toLowerCase(),[,r]=Object.entries(e).find(([e])=>e?.toLowerCase()===n)??[];if(Array.isArray(r)){let e=r.find(e=>typeof e==`string`&&e!==``||typeof e==`number`);return typeof e==`string`||typeof e==`number`?e:null}return typeof r==`string`&&r!==``||typeof r==`number`?r:null},resolveFromData=(e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`||!e)return null;let n=(0,s.safeEvaluate)($(t)?t:`$.${t}`,e);return(0,o.isMissing)(n)?null:typeof n==`string`||typeof n==`number`||typeof n==`object`?n:null},preserveJexlResponseKeys=(e,t)=>{let{nextKey:n,dataKey:r}=e?.response??{},i=n&&$(n),a=r&&$(r);return!i&&!a?t:{...t??{},...i?{nextKey:n}:{},...a?{dataKey:r}:{}}},De=o.z.object({baseUrl:o.z.string().meta({description:`Base URL the paginated requests are made against.`}),url:o.z.string().meta({description:`Endpoint path appended to the base URL.`}),method:o.z.enum(c.HttpMethods).meta({description:`HTTP method to use: get, post, put, patch, or delete.`}),authorization:Z.optional().meta({description:`Overrides the connector's default authentication for this request.`}),saml:(0,o.zStrictObject)({objectKey:o.z.string().meta({description:`Request body key under which the generated base64 SAML assertion is placed.`}),key:o.z.string().meta({description:`Base64-encoded private key used to sign the SAML assertion.`}),clientId:o.z.string().meta({description:`Client identifier included as the api_key attribute in the assertion.`}),cert:o.z.unknown().optional().meta({description:`Signing certificate for the SAML assertion.`}),issuer:o.z.string().optional().meta({description:`Issuer identifier declared in the assertion.`}),lifetime:o.z.number().optional().meta({description:`Assertion validity window in seconds.`}),nameId:o.z.string().optional().meta({description:`Subject NameID identifying the authenticating principal.`}),audience:o.z.string().optional().meta({description:`Intended audience for the assertion.`}),nameIdentifierFormat:o.z.string().optional().meta({description:`Format URI for the subject NameID.`}),tokenEndpoint:o.z.string().optional().meta({description:`Recipient token endpoint the assertion is addressed to.`})}).optional().meta({description:`Generates a signed SAML assertion and merges it into the request body for token exchange.`}),response:(0,o.zStrictObject)({indexField:o.z.string().optional().meta({description:`Field used to key results when returning an indexed map.`}),dataKey:o.z.string().optional().meta({description:`Path to the records array in the response. A path that resolves to a non-array or resolves to nothing is treated as an empty page, so the step succeeds with the records collected so far and logs a warning.`}),nextKey:o.z.string().optional().meta({description:`Path to the next-page token or cursor in the response.`}),nextKeyIn:o.z.enum([`data`,`headers`]).optional().meta({description:`Where the next-page token is read from: the response data or headers.`})}).optional().meta({description:`Controls how each page response is parsed and paginated.`}),iterator:(0,o.zStrictObject)({key:o.z.string().meta({description:`Request field name that carries the page token, offset, or number.`}),in:o.z.enum([`query`,`body`]).meta({description:`Where the pagination field is sent: query or body.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that continues pagination only while it evaluates true.`}),mode:o.z.enum([`cursor`,`offset`,`page`]).optional().meta({description:"Pagination strategy. `cursor` sends the returned next token back as the key and stops when none returns. `offset` advances the key by the number of records consumed. `page` increments the page number and stops on an empty or repeated page. Every mode also stops once `page_size` records are gathered or `iterator.condition` is false."}),startPage:o.z.number().int().min(0).max(2**53-1).optional().meta({description:`First page number to request. Valid only in page mode.`}),maxPage:o.z.number().int().positive().max(1e4).optional().meta({description:"Highest page number allowed in `page` mode. Requesting a higher page fails the step with an error."})}).superRefine((e,t)=>{e.startPage!==void 0&&e.mode!==`page`&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`startPage`],message:`startPage is only valid when iterator.mode is "page"`}),e.maxPage!==void 0&&e.mode!==`page`&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`maxPage`],message:`maxPage is only valid when iterator.mode is "page"`});let n=e.maxPage??1e3;e.mode===`page`&&(e.startPage??1)>n&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`startPage`],message:`startPage must not exceed maxPage (${n})`})}).meta({description:`Controls how subsequent pages are requested.`}),cursor:(0,o.zStrictObject)({token:o.z.string().optional().nullable().meta({description:`Cursor token from the previous page used to fetch the next one.`}),position:o.z.number().optional().nullable().meta({description:`Numeric offset or page position carried over from the previous page.`})}).optional().meta({description:`Pagination position carried over from the previous page request.`}),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional().meta({description:`Remaps matching provider error responses to different statuses or messages.`}),encodeQueryParams:o.z.boolean().optional().meta({description:`Whether to URL-encode query parameter values before sending.`}),cacheTTL:o.z.number().int().nonnegative().optional().meta({description:`Minutes to serve each page from the shared per-account response cache. 0 or omitted disables caching.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the request parameter.`}),value:o.z.unknown().meta({description:`Value of the parameter. Supports expressions.`}),in:o.z.enum(c.RequestParameterLocations).meta({description:`Where to send the parameter: query, body, or headers.`}),spread:o.z.boolean().optional().meta({description:`Merges the value's object entries into the target location instead of setting a single named field.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the parameter only when it evaluates true.`}),arrayFormat:o.z.enum(c.QueryArrayFormats).optional().meta({description:`How array values are serialized in the query string: repeat, brackets, comma, or stringify.`})}).array().optional().meta({description:`Request parameters to send as query, body, or header values.`})}),Oe=(0,o.zStrictObject)({data:o.z.unknown().optional().meta({description:`Records accumulated across the fetched pages.`}),raw:o.z.unknown().optional().meta({description:`The raw provider response before parsing.`}),statusCode:o.z.number().meta({description:`HTTP status code of the provider response.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`}),next:o.z.string().optional().nullable().meta({description:`Pagination cursor for the next page, or null when no further pages remain.`}),position:o.z.number().optional().meta({description:`Numeric offset or page position reached, for offset and page pagination modes.`})}).optional(),paginatedRequestStepFunction=async({block:e,params:t})=>{let n=c.RequestClientFactory.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=Number(e.inputs?.page_size),a=Number.isNaN(i)?25:i,l=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,u=t?(0,s.safeEvaluateRecord)({...t,args:l},e):{},d={...u,customErrors:t?.customErrors,iterator:{...u?.iterator??{},condition:t?.iterator?.condition},response:preserveJexlResponseKeys(t,u?.response)},f=d.authorization;if((0,o.notMissing)(f)){let t=Z.safeParse(f);if(!t.success)return buildStepErrorOutput(Error(invalidStepAuthorizationMessage(t.error)),e)}let{baseUrl:p,url:m,method:h,response:g,authorization:_,iterator:v,cursor:y,customErrors:b,encodeQueryParams:x,args:S,saml:C,cacheTTL:w}=De.parse(d),T=u?.authentication?.[e.context.authenticationType]?.[e.context.environment],E=T?.authorization,D=T?.certificates,O=D?(0,c.buildHttpsAgent)(D):void 0,k=(0,o.notMissing)(_)?_:Z.parse(E);if(k.type===`none`&&(0,o.notMissing)(k.signing))return buildStepErrorOutput(Error(`authorization.signing is not supported on paginated_request steps — every page changes the query string, so the signature would have to be recomputed per page; use a request step instead`),e);let A=S?(0,c.parseRequestParameters)(S):{query:{},body:{},headers:{}},j=(0,c.createAuthorizationHeaders)(k),M={...A?.headers??{},...j},N=e.connector?.rateLimit,P=e.connector?.concurrency,F=N!==void 0||P!==void 0?{rateLimits:N,concurrency:P}:void 0,I=buildRequestContext(e),L=(0,o.notMissing)(C)?{[C.objectKey]:await generateSamlAssertion({key:C.key,clientId:C.clientId,cert:C.cert,issuer:C.issuer,lifetime:C.lifetime,audience:C.audience,nameId:C.nameId,nameIdentifierFormat:C.nameIdentifierFormat,tokenEndpoint:C.tokenEndpoint})}:{},R=v.mode===`offset`,z=v.mode===`page`,B=v.maxPage??1e3,V=B+1,H=z?resolveInitialPage(y?.token,v.startPage??1):y?.token??null,U=null,ee=null,W=[],G=[],K=[],q=a,J=y?.position??0,te=!0,Y=!0,X=!0,ne=null;do{if(z&&Number(H)>V)return buildStepErrorOutput(maxPageExceededError(B,H),e);te?te=!1:R||(J=0),H===null?R&&(v.in===`query`?A.query[v.key]=J.toString():v.in===`body`&&(Array.isArray(A.body)||(A.body[v.key]=J))):v.in===`query`?(0,o.isObject)(H)?Object.entries(H).forEach(([e,t])=>{A.query[`${v.key}[${e}]`]=t?.toString()??``}):A.query[v.key]=H.toString():v.in===`body`&&(Array.isArray(A.body)||(A.body[v.key]=H));let t;try{t=await n.performRequest({httpClient:e.httpClient,url:`${p}${m}`,queryParams:{...A?.query},encodeQueryParams:x,method:h,headers:{...M},body:Array.isArray(A?.body)?A.body:{...typeof A?.body==`string`?void 0:A?.body,...L},customErrorConfigs:b,requestConfig:F,httpsAgent:O,credentials:e.credentials,context:I,cacheTTL:w})}catch(t){return buildStepErrorOutput(t,e)}if(U=H,G=g?.dataKey?Ee(t.data,g.dataKey):t.data,!Array.isArray(G)){let n=z?` at page ${U}`:``,r=g?.dataKey?` at "${g.dataKey}"`:``,i=G===null?`null`:typeof G;e.logger?.warning({message:`Pagination stopped${n}: expected an array of records${r} but received ${i}; treating it as an empty page`}),K.push(t),ee=t?.status,Y=!0;break}if(z){let t=(0,o.getContentHash)(G);if(t===ne){e.logger?.warning({message:`Pagination stopped at page ${U}: the provider returned the previous page again, so the page number is not advancing`}),Y=!0;break}ne=t}if(z&&Number(U)>B&&G.length>0)return buildStepErrorOutput(maxPageExceededError(B,U),e);let r=R?G?.slice(0,q):G?.slice(J,J+q);q-=r.length,J+=r.length,K.push(t),W=W.concat(r),ee=t?.status,H=z?incrementPage(Number(U)):ke({result:t,response:g}),X=(0,o.notMissing)(v.condition)?(0,s.safeEvaluate)(v.condition,t.data)===!0:!0;let i=J>=(G?.length??0),c=(0,o.notMissing)(g?.nextKey),l=r.length===G.length&&q===0;!R&&(c||z)&&i&&(J=0,U=H),Y=R?!X||(0,o.isMissing)(H)&&W.length<a:z?i&&(!X||W.length<a):c?i&&((0,o.isMissing)(H)||!X):!X||(0,o.isMissing)(H)&&W.length<a||l}while((R||(0,o.notMissing)(H))&&X&&W.length<a&&G?.length>0);let re=Ae(W,g),ie=Y?void 0:U;return{block:e,successful:!0,output:{data:re,raw:K,statusCode:ee,next:z&&typeof ie==`number`?ie.toString():ie,position:Y?void 0:J}}},resolveInitialPage=(e,t)=>{let n=Number(e);return Number.isSafeInteger(n)&&n>=t?n:t},incrementPage=e=>e+1,maxPageExceededError=(e,t)=>Error(`Pagination exceeded iterator.maxPage (${e}) at page ${t}`),invalidStepAuthorizationMessage=e=>`step authorization is invalid, check its credential expressions resolve for this account: ${e.issues.map(e=>e.message).join(`; `)}`,ke=__name(({result:e,response:t})=>{if((0,o.isMissing)(t?.nextKey))return null;let n=t?.nextKeyIn??`data`,r=t?.nextKey;return n===`headers`?resolveFromHeaders(e.headers,r):resolveFromData(e.data,r)},`resolveNextIterator`),Ae=__name((e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),je=o.z.object({baseUrl:o.z.string().optional().meta({description:`Overrides the connector's base URL for this request.`}),url:o.z.string().meta({description:`Endpoint path appended to the base URL.`}),method:o.z.enum(c.HttpMethods).meta({description:`HTTP method to use: get, post, put, patch, or delete.`}),authorization:Z.optional().meta({description:`Overrides the connector's default authentication for this request.`}),certificates:se.meta({description:`Client TLS certificates and keys for mutual TLS connections.`}),saml:(0,o.zStrictObject)({objectKey:o.z.string().meta({description:`Request body key under which the generated base64 SAML assertion is placed.`}),key:o.z.string().meta({description:`Base64-encoded private key used to sign the SAML assertion.`}),clientId:o.z.string().meta({description:`Client identifier included as the api_key attribute in the assertion.`}),cert:o.z.unknown().optional().meta({description:`Signing certificate for the SAML assertion.`}),issuer:o.z.string().optional().meta({description:`Issuer identifier declared in the assertion.`}),lifetime:o.z.number().optional().meta({description:`Assertion validity window in seconds.`}),nameId:o.z.string().optional().meta({description:`Subject NameID identifying the authenticating principal.`}),audience:o.z.string().optional().meta({description:`Intended audience for the assertion.`}),nameIdentifierFormat:o.z.string().optional().meta({description:`Format URI for the subject NameID.`}),tokenEndpoint:o.z.string().optional().meta({description:`Recipient token endpoint the assertion is addressed to.`})}).optional().meta({description:`Generates a signed SAML assertion and merges it into the request body for token exchange.`}),response:(0,o.zStrictObject)({collection:o.z.boolean().optional().meta({description:`Whether to treat the response payload as a collection of records to index.`}),indexField:o.z.string().optional().meta({description:`Field used to key results when returning an indexed map.`}),dataKey:o.z.string().optional().meta({description:`Path to the field in the response holding the records to extract.`})}).optional().meta({description:`Controls how the raw response is parsed into step output data.`}),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional().meta({description:`Remaps matching provider error responses to different statuses or messages.`}),encodeQueryParams:o.z.boolean().optional().meta({description:`Whether to URL-encode query parameter values before sending.`}),cacheTTL:o.z.number().int().nonnegative().optional().meta({description:`Minutes to serve this request from the shared per-account response cache. 0 or omitted disables caching.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the request parameter.`}),value:o.z.unknown().meta({description:`Value of the parameter. Supports expressions.`}),in:o.z.enum(c.RequestParameterLocations).meta({description:`Where to send the parameter: query, body, or headers.`}),spread:o.z.boolean().optional().meta({description:`Merges the value's object entries into the target location instead of setting a single named field.`}),inline:o.z.boolean().optional().meta({description:`Sends the string value as the raw request body. Valid only as the sole in: body argument.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the parameter only when it evaluates true.`}),arrayFormat:o.z.enum(c.QueryArrayFormats).optional().meta({description:`How array values are serialized in the query string: repeat, brackets, comma, or stringify.`})}).array().optional().meta({description:`Request parameters to send as query, body, or header values.`})}).superRefine((e,t)=>{let n=e.args??[],r=n.map((e,t)=>({arg:e,index:t})).filter(({arg:e})=>e.inline===!0),i=n.filter(e=>e.in===`body`).length;if(n.forEach((e,n)=>{e.inline===!0&&e.in!==`body`&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline is only valid when in is "body", got "${e.in}"`}),e.inline===!0&&e.spread&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with spread`})}),r.length>0&&i>1)for(let{arg:e,index:n}of r)t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: an inline body arg must be the only "in: body" arg, found ${i}; arg conditions are not considered`});if(r.length>0&&e.saml!==void 0)for(let{arg:e,index:n}of r)t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with the saml parameter`});if(r.length>0&&e.cacheTTL!==void 0&&e.cacheTTL>0)for(let{arg:e,index:n}of r)t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with a nonzero cacheTTL`});for(let{arg:e,index:n}of r)typeof e.value==`string`?e.value.length===0&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`value`],message:`args.${e.name}: inline value must be a non-empty string, got an empty string`}):t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`value`],message:`args.${e.name}: inline value must be a non-empty string, got ${typeof e.value}`})}),Me=(0,o.zStrictObject)({data:o.z.unknown().optional().meta({description:`The parsed response payload extracted from the provider response.`}),raw:o.z.unknown().optional().meta({description:`The raw provider response before parsing.`}),statusCode:o.z.number().meta({description:`HTTP status code of the provider response.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`})}).optional(),isJexlExpression=e=>{let t=e.trim();return t.startsWith(`{{`)&&t.endsWith(`}}`)},isErrorWithResponseBody=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`&&`body`in e.response,isErrorWithResponseConfigData=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`&&`config`in e.response&&e.response.config!=null&&typeof e.response.config==`object`&&`data`in e.response.config,requestStepFunction=async({block:e,params:t})=>{let n=c.RequestClientFactory.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?.response?.dataKey,l=a&&isJexlExpression(a),u=t?(0,s.safeEvaluateRecord)({...t,args:i},e):{},d={...u,customErrors:t?.customErrors,response:l?{...u?.response??{},dataKey:a}:u?.response},{baseUrl:f,url:p,method:h,response:g,authorization:_,certificates:v,customErrors:y,encodeQueryParams:b,args:x,saml:S,cacheTTL:C}=je.parse(d),w=u?.authentication?.[e.context.authenticationType]?.[e.context.environment],T=w?.authorization,E=v??w?.certificates,D=E?(0,c.buildHttpsAgent)(E):void 0,O=x?(0,c.parseRequestParameters)(x):{query:{},body:{},headers:{}},k=x?.some(e=>e.in===`body`&&e.inline===!0)??!1,A=(0,o.notMissing)(_)?_:Z.parse(T),j=(0,c.createAuthorizationHeaders)(A),M={...O?.headers??{},...j},N=e.connector?.rateLimit,P=e.connector?.concurrency,F=N!==void 0||P!==void 0?{rateLimits:N,concurrency:P}:void 0,I=(0,o.notMissing)(S)?{[S.objectKey]:await generateSamlAssertion({key:S.key,clientId:S.clientId,cert:S.cert,issuer:S.issuer,lifetime:S.lifetime,audience:S.audience,nameId:S.nameId,nameIdentifierFormat:S.nameIdentifierFormat,tokenEndpoint:S.tokenEndpoint})}:{},L=typeof O?.body==`string`||Array.isArray(O?.body)?O?.body:{...O?.body,...I};if(A.type===`none`&&A.signing?.strategy){if(b===!1)return buildStepErrorOutput(Error(`encodeQueryParams: false is not supported when a request signing strategy is configured — signed canonical would not match the wire query`),e);let t=A.signing,n=e.credentials??{};try{let e=(0,c.getSigningStrategy)(t.strategy);if(!e)throw Error(`Signing strategy "${t.strategy}" is not registered`);let r=e({method:h,url:`${f}${p}`,headers:M,query:O?.query??{},body:L},n,t);Object.assign(M,r)}catch(t){return buildStepErrorOutput(t,e)}}let R;try{R=await n.performRequest({httpClient:e.httpClient,url:`${f}${p}`,queryParams:O?.query,encodeQueryParams:b,method:h,headers:M,body:L,customErrorConfigs:y,requestConfig:F,httpsAgent:D,credentials:e.credentials,context:buildRequestContext(e),cacheTTL:C})}catch(t){return k&&(isErrorWithResponseBody(t)&&(t.response.body=m.REDACT_CENSOR),isErrorWithResponseConfigData(t)&&(t.response.config.data=m.REDACT_CENSOR)),buildStepErrorOutput(t,e)}return{block:e,successful:!0,output:{data:Ne(g?.dataKey?resolveDataKey(R.data,g.dataKey):R.data,g),raw:k&&R&&`body`in R?{...R,body:m.REDACT_CENSOR}:R,statusCode:R?.status,message:R?.message}}},resolveDataKey=(e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`||!e)return e;let n=(0,s.safeEvaluate)(isJexlExpression(t)?t:`$.${t}`,e);return n===void 0?e[t]:n},Ne=__name((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Pe=o.z.union([o.z.string(),o.z.number()]),Fe=(0,o.zStrictObject)({algorithm:o.z.literal(`RS256`).meta({description:`Signing algorithm. Only RS256 is supported.`}),privateKey:o.z.string().meta({description:`PEM-encoded private key used to sign the token.`}),claims:o.z.record(o.z.string(),Pe).meta({description:"Claims to include in the JWT payload, such as `iss`, `scope`, and `aud`. `iat` and `exp` are required numbers with `exp` after `iat`, and accept `now` or `now+<N>s|m|h` tokens."})}),Ie=(0,o.zStrictObject)({token:o.z.string().meta({description:`The signed JWT.`}),expiresIn:o.z.number().meta({description:`Token lifetime in seconds.`}),publicKeyFingerprint:o.z.string().meta({description:`Fingerprint of the public key matching the signing key.`})}),computePublicKeyFingerprint=e=>{let t=e.export({format:`der`,type:`spki`});return`SHA256:${(0,h.createHash)(`sha256`).update(t).digest(`base64`)}`},Le=/^now$/,Re=/^now\+(?<amount>\d+)(?<unit>[smh])$/,ze=`{publicKeyFingerprint}`,Be={s:1,m:60,h:3600},Ve=new Set([`iat`,`exp`,`nbf`]),resolveClaimValue=(e,t,{now:n,publicKeyFingerprint:r})=>{if(typeof t==`number`)return t;let i=t.includes(ze)?t.split(ze).join(r):t;if(!Ve.has(e))return i;if(Le.test(i))return n;let a=i.match(Re);return a?.groups?n+Number(a.groups.amount)*Be[a.groups.unit]:i},signJwtStepFunction=async({block:e,params:t})=>{try{let n=t?(0,s.safeEvaluateRecord)(t,e):void 0,{algorithm:r,privateKey:i,claims:a}=Fe.parse(n),o=(0,h.createPrivateKey)(i),c=computePublicKeyFingerprint((0,h.createPublicKey)(o)),l=Math.floor(Date.now()/1e3),u={};for(let[e,t]of Object.entries(a))u[e]=resolveClaimValue(e,t,{now:l,publicKeyFingerprint:c});let{iat:d,exp:f}=u;if(typeof d!=`number`||typeof f!=`number`)throw Error(`signJwt requires numeric 'iat' and 'exp' claims (use 'now' / 'now+<N>s|m|h' tokens, or pass numbers directly)`);if(f<=d)throw Error(`signJwt requires 'exp' to be greater than 'iat'`);let p=await new g.SignJWT(u).setProtectedHeader({alg:r}).sign(o);return{block:{...e},successful:!0,output:{token:p,expiresIn:f-d,publicKeyFingerprint:c}}}catch(t){return buildStepErrorOutput(t,e)}},He=o.z.object({baseUrl:o.z.string().optional().meta({description:`Overrides the connector's base URL for the SOAP service.`}),url:o.z.string().meta({description:`SOAP endpoint path appended to the base URL.`}),method:o.z.enum(c.HttpMethods).meta({description:`HTTP method to use for the SOAP call, typically post.`}),authorization:o.z.discriminatedUnion(`type`,[(0,o.zStrictObject)({type:o.z.literal(`none`).meta({description:`Selects no authentication.`})}),(0,o.zStrictObject)({type:o.z.literal(`basic`).meta({description:`Selects HTTP basic authentication.`}),username:o.z.string().optional().meta({description:`Username for basic authentication.`}),password:o.z.string().optional().meta({description:`Password for basic authentication.`}),encoding:o.z.string().optional().meta({description:`Encoding applied to the username and password, such as base64.`})}),(0,o.zStrictObject)({type:o.z.literal(`bearer`).meta({description:`Selects bearer token authentication.`}),token:o.z.string().meta({description:`Bearer token sent with the request.`}),includeBearer:o.z.boolean().optional().default(!0).meta({description:"Whether to prefix the token with `Bearer ` in the header. Defaults to true."})}),(0,o.zStrictObject)({type:o.z.literal(`oauth2`).meta({description:`Selects OAuth 2.0 authentication.`}),token:o.z.string().meta({description:`OAuth 2.0 access token sent with the request.`}),includeBearer:o.z.boolean().optional().default(!0).meta({description:"Whether to prefix the token with `Bearer ` in the header. Defaults to true."})})]).optional().meta({description:`Overrides the connector's default authentication for this request.`}),envelope:o.z.union([o.z.string(),o.z.record(o.z.string(),o.z.unknown())]).optional().meta({description:`SOAP envelope template, as a string or object, used to build the request body.`}),namespaces:o.z.strictObject({namespaceIdentifier:o.z.string().meta({description:`XML namespace prefix.`}),namespace:o.z.string().meta({description:`Namespace URI bound to the prefix.`})}).array().optional().meta({description:`XML namespace declarations added to the SOAP envelope.`}),soapOperation:o.z.string().optional().meta({description:`Name of the SOAP operation to invoke.`}),soapAction:o.z.string().optional().meta({description:`Value sent in the SOAPAction HTTP header.`}),useSoapContext:o.z.boolean().optional().default(!0).meta({description:`Whether to wrap the request using the SOAP context.`}),response:(0,o.zStrictObject)({collection:o.z.boolean().optional().meta({description:`Currently not in use.`}),indexField:o.z.string().optional().meta({description:`Field used to key results when returning an indexed map.`}),dataKey:o.z.string().optional().meta({description:`Path to the records array within the response.`}),nextKey:o.z.string().optional().meta({description:`Path to the next-page token or cursor in the response.`}),nextKeyIn:o.z.enum([`data`,`headers`]).optional().meta({description:`Where the next-page token is read from: the response data or headers.`})}).optional().meta({description:`Controls how each page response is parsed and paginated.`}),iterator:(0,o.zStrictObject)({key:o.z.string().meta({description:`Request field name that carries the page token or number.`}),in:o.z.enum([`query`,`body`]).meta({description:`Where the pagination field is sent: query or body.`})}).meta({description:`Controls how subsequent pages are requested.`}),cursor:(0,o.zStrictObject)({token:o.z.string().optional().nullable().meta({description:`Cursor token from the previous page used to fetch the next one.`}),position:o.z.number().optional().nullable().meta({description:`How far into the previous page was read, so this request resumes from there.`})}).optional().meta({description:`Pagination position carried over from the previous page request.`}),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional().meta({description:`Remaps matching provider error responses to different statuses or messages.`}),encodeQueryParams:o.z.boolean().optional().meta({description:`Whether to URL-encode query parameter values before sending.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the request parameter.`}),value:o.z.unknown().meta({description:`Value of the parameter. Supports expressions.`}),in:o.z.enum(c.RequestParameterLocations).meta({description:`Where to send the parameter: query, body, or headers.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the parameter only when it evaluates true.`}),arrayFormat:o.z.enum(c.QueryArrayFormats).optional().meta({description:`How array values are serialized in the query string: repeat, brackets, comma, or stringify.`})}).array().optional().meta({description:`Request parameters to send as query, body, or header values.`})}),Ue=(0,o.zStrictObject)({data:o.z.unknown().optional().meta({description:`Records accumulated across the fetched pages.`}),raw:o.z.unknown().optional().meta({description:`The raw provider response before parsing.`}),statusCode:o.z.number().meta({description:`HTTP status code of the provider response.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`}),next:o.z.string().optional().nullable().meta({description:"Cursor token for the next page. Null means the next request continues from `position` in the current page, and it is omitted when no pages remain."}),position:o.z.number().optional().meta({description:`How far into the current page has been read, saved in the cursor so the next request resumes from there.`})}).optional(),soapPaginatedRequestStepFunction=async({block:e,params:t})=>{let n=c.RequestClientFactory.build(`soap`);if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=Number(e.inputs?.page_size),a=Number.isNaN(i)?25:i,l=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,u=t?(0,s.safeEvaluateRecord)({...t,args:l},e):{},d={...u,customErrors:t?.customErrors,response:preserveJexlResponseKeys(t,u?.response)},f=t?.envelope,{baseUrl:p,url:m,method:h,response:g,iterator:_,cursor:v,authorization:y,customErrors:b,encodeQueryParams:x,args:S,soapOperation:C,namespaces:w,soapAction:T,useSoapContext:E}=He.parse(d),D=u?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,O=S?(0,c.parseRequestParameters)(S):{query:{},body:{},headers:{}},k=(0,c.createAuthorizationHeaders)((0,o.notMissing)(y)?y:Z.parse(D)),A={...O?.headers??{},...k},j=e.connector?.rateLimit,M=e.connector?.concurrency,N={...j!==void 0||M!==void 0?{rateLimits:j,concurrency:M}:void 0,soapOperation:C,namespaces:w,soapAction:T,soapContext:E?{username:e.credentials?.username,password:e.credentials?.password}:void 0},P=v?.token??null,F=null,I=null,L=[],R=[],z=[],B=a,V=v?.position??0,H=!0,U;do{H?H=!1:V=0,P!==null&&(_.in===`query`?O.query[_.key]=P.toString():_.in===`body`&&(O.body[_.key]=P));let t;try{t=await n.performRequest({httpClient:e.httpClient,url:`${p}${m}`,queryParams:{...O?.query},encodeQueryParams:x,method:h,headers:A,body:O?.body,customErrorConfigs:b,requestConfig:{...N,...(0,o.notMissing)(f)&&{envelope:evaluateEnvelope(f,e,P)}},credentials:e.credentials,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}F=P,R=g?.dataKey?Ee(t.data,g.dataKey):t.data,Array.isArray(R)||(R=R?[R]:[]);let r=R?.slice(V,V+B);B-=r.length,V+=r.length,z.push(t),L=L.concat(r),I=t?.status,P=resolveNextIterator({result:t,response:g});let i=V>=(R?.length??0),s=(0,o.notMissing)(g?.nextKey),c=r.length===R.length&&B===0;s&&i&&(V=0,F=P),U=s?i&&(0,o.isMissing)(P):(0,o.isMissing)(P)&&L.length<a||c}while((0,o.notMissing)(P)&&L.length<a&&R?.length>0);return{block:e,successful:!0,output:{data:We(L,g),raw:z,statusCode:I,next:U?void 0:stringifyCursorToken(F),position:U?void 0:V}}},stringifyCursorToken=e=>e===null?null:String(e),evaluateEnvelope=(e,t,n)=>{let r={...t,pageIterator:n};return typeof e==`string`?(0,s.safeEvaluate)(e,r):(0,s.safeEvaluateRecord)(e,r)},resolveNextIterator=({result:e,response:t})=>{if((0,o.isMissing)(t?.nextKey))return null;let n=t?.nextKeyIn??`data`,r=t?.nextKey,i=n===`headers`?resolveFromHeaders(e.headers,r):resolveFromData(e.data,r);return typeof i==`string`||typeof i==`number`?i:null},We=__name((e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Ge=o.z.object({baseUrl:o.z.string().optional().meta({description:`Overrides the connector's base URL for the SOAP service.`}),url:o.z.string().meta({description:`SOAP endpoint path appended to the base URL.`}),method:o.z.enum(c.HttpMethods).meta({description:`HTTP method to use for the SOAP call, typically post.`}),authorization:Z.optional().meta({description:`Overrides the connector's default authentication for this request.`}),envelope:o.z.union([o.z.string(),o.z.record(o.z.string(),o.z.unknown())]).optional().meta({description:`SOAP envelope template, as a string or object, used to build the request body.`}),namespaces:o.z.strictObject({namespaceIdentifier:o.z.string().meta({description:`XML namespace prefix.`}),namespace:o.z.string().meta({description:`Namespace URI bound to the prefix.`})}).array().optional().meta({description:`XML namespace declarations added to the SOAP envelope.`}),soapOperation:o.z.string().optional().meta({description:`Name of the SOAP operation to invoke.`}),soapAction:o.z.string().optional().meta({description:`Value sent in the SOAPAction HTTP header.`}),useSoapContext:o.z.boolean().optional().default(!0).meta({description:`Whether to wrap the request using the SOAP context.`}),response:(0,o.zStrictObject)({collection:o.z.boolean().optional().meta({description:`Whether to treat the response payload as a collection of records to index.`}),indexField:o.z.string().optional().meta({description:`Field used to key results when returning an indexed map.`}),dataKey:o.z.string().optional().meta({description:`Top-level response key holding the records to extract.`})}).optional().meta({description:`Controls how the raw response is parsed into step output data.`}),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional().meta({description:`Remaps matching provider error responses to different statuses or messages.`}),encodeQueryParams:o.z.boolean().optional().meta({description:`Whether to URL-encode query parameter values before sending.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the request parameter.`}),value:o.z.unknown().meta({description:`Value of the parameter. Supports expressions.`}),in:o.z.enum(c.RequestParameterLocations).meta({description:`Where to send the parameter: query, body, or headers.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the parameter only when it evaluates true.`}),arrayFormat:o.z.enum(c.QueryArrayFormats).optional().meta({description:`How array values are serialized in the query string: repeat, brackets, comma, or stringify.`})}).array().optional().meta({description:`Request parameters to send as query, body, or header values.`})}),Ke=(0,o.zStrictObject)({data:o.z.unknown().optional().meta({description:`The parsed response payload extracted from the SOAP response.`}),raw:o.z.unknown().optional().meta({description:`The raw provider response before parsing.`}),statusCode:o.z.number().meta({description:`HTTP status code of the provider response.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`})}).optional(),soapRequestStepFunction=async({block:e,params:t})=>{let n=c.RequestClientFactory.build(`soap`);if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?(0,s.safeEvaluateRecord)({...t,args:i},e):{},l={...a,customErrors:t?.customErrors},{baseUrl:u,url:d,method:f,response:p,authorization:m,customErrors:h,encodeQueryParams:g,args:_,soapOperation:v,namespaces:y,envelope:b,soapAction:x,useSoapContext:S}=Ge.parse(l),C=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,w=_?(0,c.parseRequestParameters)(_):{query:{},body:{},headers:{}},T=(0,c.createAuthorizationHeaders)((0,o.notMissing)(m)?m:Z.parse(C)),E={...w?.headers??{},...T},D=e.connector?.rateLimit,O=e.connector?.concurrency,k={...D!==void 0||O!==void 0?{rateLimits:D,concurrency:O}:void 0,soapOperation:v,namespaces:y,envelope:b,soapAction:x,soapContext:S?{username:e.credentials?.username,password:e.credentials?.password}:void 0},A;try{A=await n.performRequest({httpClient:e.httpClient,url:`${u}${d}`,queryParams:w?.query,encodeQueryParams:g,method:f,headers:E,body:w?.body,customErrorConfigs:h,requestConfig:k,credentials:e.credentials,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}return{block:e,successful:!0,output:{data:qe(p?.dataKey?A.data[p?.dataKey]:A.data,p),raw:A,statusCode:A?.status,message:A?.message}}},qe=__name((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Je=o.z.object({values:o.z.string().or(o.z.record(o.z.string(),o.z.unknown())).or(o.z.array(o.z.unknown())).meta({description:`Static values to return, as an object, an array, or an expression string.`})}),Ye=o.z.object({data:o.z.unknown().meta({description:`The static values returned by the step.`})}),staticValuesStepFunction=async({block:e,params:t})=>{let{values:n}=Je.parse(t),r=Array.isArray(n)?n.map(t=>evaluateValue(t,e)):evaluateValue(n,e);return{block:{...e},successful:!0,output:{data:r}}},evaluateValue=(e,t)=>(0,o.isString)(e)?(0,s.safeEvaluate)(e,t):(0,o.isObject)(e)?(0,s.safeEvaluateRecord)(e,t):e,Xe=o.z.object({targetFieldKey:o.z.string().meta({description:`Key of the field to cast.`}),type:o.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]).meta({description:`Target data type to cast the field to.`}),array:o.z.boolean().default(!1).meta({description:"Whether the field holds an array of the given type. A primitive array is passed through unchanged, and an object array still has each element processed through `properties`."}),custom:o.z.boolean().default(!1).meta({description:`Whether the field is a custom, non-unified field.`}),hidden:o.z.boolean().default(!1).meta({description:`Currently not in use.`}),properties:o.z.lazy(()=>Xe).array().optional().meta({description:`Nested field casts applied when the type is object.`}),requiredScopes:o.z.string().array().optional().meta({description:`Scopes that must be granted for the field to be included.`})}),Ze=o.z.object({fields:Xe.array().optional().meta({description:`Definitions of the fields to cast.`}),dataSource:o.z.string().meta({description:`Reference to the source data to cast.`})}),Qe=o.z.object({data:o.z.unknown().meta({description:`The source data with fields cast to their target types.`})});let $e=function(e){return e.String=`string`,e.Number=`number`,e.Boolean=`boolean`,e.DateTimeString=`datetime_string`,e}({});const typecast=({value:e,type:t,format:n})=>{if((0,o.isMissing)(e))return null;switch(t){case`string`:return(0,o.safeParseToString)({value:e});case`number`:return(0,o.safeParseToNumber)({value:e});case`boolean`:return(0,o.safeParseToBoolean)({value:e});case`datetime_string`:return(0,o.safeParseToDateTimeString)({value:e,format:n});default:return e}},isFieldSupportedType=e=>Object.values($e).includes(e),et=__name(async({block:e})=>{let t=e?.fieldConfigs;if(!t||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let n;return n=Array.isArray(e.result)?e.result.map(e=>tt(e,t)):tt(e.result,t),{block:{...e,result:n},successful:!0}},`typecastStepFunction`),tt=__name((e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i}=t;isFieldSupportedType(i)&&(!t.custom&&(0,o.notMissing)(n[r])?n[r]=typecast({value:e[r],type:i}):n.unified_custom_fields&&(0,o.notMissing)(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=typecast({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},`mapSingleRecord`),typecastStepFunction=async({block:e,params:t})=>{let{fields:n,dataSource:r}=Ze.parse(t),i=(0,s.evaluate)(r,buildExpressionContext(e));if(!n||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let a;return a=Array.isArray(i)?i.map(e=>mapSingleRecord(e,n)):mapSingleRecord(i,n),{block:{...e},successful:!0,output:{data:a}}},handleObjectField=(e,t)=>!e.properties||!t?t:Array.isArray(t)?t.map(t=>typeof t==`object`&&t?mapSingleRecord(t,e.properties):t):typeof t==`object`&&t?mapSingleRecord(t,e.properties):t,mapSingleRecord=(e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i,array:a}=t;i===`object`?!t.custom&&(0,o.notMissing)(n[r])?n[r]=handleObjectField(t,e[r]):n.unified_custom_fields&&(0,o.notMissing)(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=handleObjectField(t,e.unified_custom_fields?.[r])):isFieldSupportedType(i)&&(!t.custom&&(0,o.notMissing)(n[r])?(!a||!Array.isArray(n[r]))&&(n[r]=typecast({value:e[r],type:i})):n.unified_custom_fields&&(0,o.notMissing)(n.unified_custom_fields?.[r])&&(!a||!Array.isArray(n.unified_custom_fields[r]))&&(n.unified_custom_fields[r]=typecast({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},nt=(0,o.zStrictObject)({content:o.z.string().meta({description:`The file content as base64 encoded string`}),contentType:o.z.string().optional().meta({description:`The MIME type for the binary content (defaults to application/octet-stream)`})}),rt=o.z.object({baseUrl:o.z.string().optional().meta({description:`Overrides the connector's base URL for the upload.`}),url:o.z.string().meta({description:`Upload endpoint path appended to the base URL.`}),method:o.z.enum(c.HttpMethods).default(`post`).meta({description:`HTTP method to use for the upload.`}),authorization:Z.optional().meta({description:`Overrides the connector's default authentication for this request.`}),binaryContent:nt.meta({description:`Raw binary content for octet-stream uploads`}),response:(0,o.zStrictObject)({collection:o.z.boolean().optional().meta({description:`Whether to treat the response payload as a collection of records to index.`}),indexField:o.z.string().optional().meta({description:`Field used to key results when returning an indexed map.`}),dataKey:o.z.string().optional().meta({description:`Top-level response key holding the records to extract.`})}).optional().meta({description:`Controls how the raw response is parsed into step output data.`}),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional().meta({description:`Remaps matching provider error responses to different statuses or messages.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the request parameter.`}),value:o.z.unknown().meta({description:`Value of the parameter. Supports expressions.`}),in:o.z.enum(c.RequestParameterLocations).meta({description:`Where to send the parameter: query, body, or headers.`}),spread:o.z.boolean().optional().meta({description:`Merges the value's object entries into the target location instead of setting a single named field.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the parameter only when it evaluates true.`}),arrayFormat:o.z.enum(c.QueryArrayFormats).optional().meta({description:`How array values are serialized in the query string: repeat, brackets, comma, or stringify.`})}).array().optional().meta({description:`Additional request parameters (query params, headers)`})}),it=(0,o.zStrictObject)({data:o.z.unknown().optional().meta({description:`The parsed response payload from the upload.`}),raw:o.z.unknown().optional().meta({description:`The raw provider response before parsing.`}),statusCode:o.z.number().meta({description:`HTTP status code of the provider response.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`})}).optional(),uploadBinaryStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n}=t,r=n?n.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,i=t?(0,s.safeEvaluateRecord)({...t,args:r},e):{},a={...i,customErrors:t?.customErrors},{baseUrl:l,url:u,method:d,response:f,authorization:p,binaryContent:m,args:h,customErrors:g}=rt.parse(a),_=i?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,v=h?(0,c.parseRequestParameters)(h):{query:{},body:{},headers:{}},y=(0,c.createAuthorizationHeaders)((0,o.notMissing)(p)?p:Z.parse(_)),b=Buffer.from(m.content,`base64`),x={"content-type":m.contentType??`application/octet-stream`,...v?.headers??{},...y},S=e.connector?.rateLimit,C=e.connector?.concurrency,w=S!==void 0||C!==void 0?{rateLimits:S,concurrency:C}:void 0,T;try{T=await e.httpClient.request({url:`${l??``}${u}`,method:d,headers:x,queryParams:v?.query,payload:b,requestConfig:w,context:buildRequestContext(e)})}catch(t){let n=t;return{block:e,successful:!1,errors:[(0,c.serializeHttpResponseError)(t)],output:{statusCode:n?.response?.status??500,message:n?.response?.message}}}let E=(0,c.translateCustomError)(T,g,e.credentials);return(0,c.isFailedStatusCode)(E?.status)?{block:e,successful:!1,errors:[(0,c.serializeHttpResponseError)(new c.HttpResponseError(E,E.message))],output:{statusCode:E.status,message:E.message}}:{block:e,successful:!0,output:{data:at(f?.dataKey?E.data[f?.dataKey]:E.data,f),raw:E,statusCode:E?.status,message:E?.message}}},at=__name((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),ot=(0,o.zStrictObject)({fieldName:o.z.string().meta({description:`The form field name for the file`}),content:o.z.string().meta({description:`The file content as base64 encoded string`}),filename:o.z.string().meta({description:`The filename to use in the upload`}),contentType:o.z.string().optional().meta({description:`The MIME type of the file (e.g., "image/png", "application/pdf")`})}),st=o.z.object({baseUrl:o.z.string().optional().meta({description:`Overrides the connector's base URL for the upload.`}),url:o.z.string().meta({description:`Upload endpoint path appended to the base URL.`}),method:o.z.enum(c.HttpMethods).default(`post`).meta({description:`HTTP method to use for the upload.`}),authorization:Z.optional().meta({description:`Overrides the connector's default authentication for this request.`}),file:ot.meta({description:`The file to upload`}),additionalFields:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the form field.`}),value:o.z.unknown().meta({description:`Value of the form field.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the field only when it evaluates true.`}),contentType:o.z.string().optional().meta({description:`The MIME type for this form field (e.g., "application/json")`})}).array().optional().meta({description:`Additional form fields to include in the multipart request`}),response:(0,o.zStrictObject)({collection:o.z.boolean().optional().meta({description:`Whether to treat the response payload as a collection of records to index.`}),indexField:o.z.string().optional().meta({description:`Field used to key results when returning an indexed map.`}),dataKey:o.z.string().optional().meta({description:`Top-level response key holding the records to extract.`})}).optional().meta({description:`Controls how the raw response is parsed into step output data.`}),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional().meta({description:`Remaps matching provider error responses to different statuses or messages.`}),args:(0,o.zStrictObject)({name:o.z.string().meta({description:`Name of the request parameter.`}),value:o.z.unknown().meta({description:`Value of the parameter. Supports expressions.`}),in:o.z.enum(c.RequestParameterLocations).meta({description:`Where to send the parameter: query, body, or headers.`}),spread:o.z.boolean().optional().meta({description:`Merges the value's object entries into the target location instead of setting a single named field.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that includes the parameter only when it evaluates true.`}),arrayFormat:o.z.enum(c.QueryArrayFormats).optional().meta({description:`How array values are serialized in the query string: repeat, brackets, comma, or stringify.`})}).array().optional().meta({description:`Additional request parameters (query params, headers)`})}),ct=(0,o.zStrictObject)({data:o.z.unknown().optional().meta({description:`The parsed response payload from the upload.`}),raw:o.z.unknown().optional().meta({description:`The raw provider response before parsing.`}),statusCode:o.z.number().meta({description:`HTTP status code of the provider response.`}),message:o.z.string().optional().meta({description:`Status or error message from the response.`})}).optional(),uploadFileStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n,additionalFields:r}=t,i=n?n.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,l=t?(0,s.safeEvaluateRecord)({...t,args:i,additionalFields:a},e):{},u={...l,customErrors:t?.customErrors},{baseUrl:d,url:f,method:p,response:m,authorization:h,file:g,additionalFields:v,args:y,customErrors:b}=st.parse(u),x=l?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,S=y?(0,c.parseRequestParameters)(y):{query:{},body:{},headers:{}},C=(0,c.createAuthorizationHeaders)((0,o.notMissing)(h)?h:Z.parse(x)),w=new _.default;if(v)for(let e of v){let t=typeof e.value==`object`?JSON.stringify(e.value):String(e.value);w.append(e.name,t,e.contentType?{contentType:e.contentType}:void 0)}let T=Buffer.from(g.content,`base64`);w.append(g.fieldName,T,{filename:g.filename,contentType:g.contentType});let E={...w.getHeaders(),...S?.headers??{},...C},D=e.connector?.rateLimit,O=e.connector?.concurrency,k=D!==void 0||O!==void 0?{rateLimits:D,concurrency:O}:void 0,A;try{A=await e.httpClient.request({url:`${d??``}${f}`,method:p,headers:E,queryParams:S?.query,payload:w,requestConfig:k,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}let j=(0,c.translateCustomError)(A,b,e.credentials);return(0,c.isFailedStatusCode)(j?.status)?buildStepErrorOutput(new c.HttpResponseError(j,j.message),e):{block:e,successful:!0,output:{data:indexResponseData(m?.dataKey?j.data[m?.dataKey]:j.data,m),raw:j,statusCode:j?.status,message:j?.message}}},indexResponseData=(e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e};let lt=function(e){return e.TYPECAST=`typecast`,e.MAP_FIELDS=`map_fields`,e.GROUP_DATA=`group_data`,e.REQUEST=`request`,e.PAGINATED_REQUEST=`paginated_request`,e.SOAP_REQUEST=`soap_request`,e.SOAP_PAGINATED_REQUEST=`soap_paginated_request`,e.STATIC_VALUES=`static_values`,e.UPLOAD_FILE=`upload_file`,e.UPLOAD_BINARY=`upload_binary`,e.DOWNLOAD_FILE=`download_file`,e.EMIT_EVENT=`emit_event`,e.BROWSER_USE=`browser_use`,e.CODE_EXECUTION_LAMBDA=`code_execution_lambda`,e.SIGN_JWT=`sign_jwt`,e.MCP_REQUEST=`mcp_request`,e}({});const ut={typecast:{v1:{fn:et},v2:{fn:typecastStepFunction,inputSchema:Ze,outputSchema:Qe}},map_fields:{v1:{fn:ge},v2:{fn:mapFieldsStepFunction,inputSchema:be,outputSchema:xe}},request:{v1:{fn:requestStepFunction,inputSchema:je,outputSchema:Me}},group_data:{v1:{fn:groupDataStepFunction,inputSchema:me,outputSchema:he}},paginated_request:{v1:{fn:paginatedRequestStepFunction,inputSchema:De,outputSchema:Oe}},soap_request:{v1:{fn:soapRequestStepFunction,inputSchema:Ge,outputSchema:Ke}},soap_paginated_request:{v1:{fn:soapPaginatedRequestStepFunction,inputSchema:He,outputSchema:Ue}},static_values:{v1:{fn:staticValuesStepFunction,inputSchema:Je,outputSchema:Ye}},upload_file:{v1:{fn:uploadFileStepFunction,inputSchema:st,outputSchema:ct}},upload_binary:{v1:{fn:uploadBinaryStepFunction,inputSchema:rt,outputSchema:it}},download_file:{v1:{fn:downloadFileStepFunction,inputSchema:ce,outputSchema:le}},emit_event:{v1:{fn:emitEventStepFunction,inputSchema:ue,outputSchema:de}},browser_use:{v1:{fn:browserUseStepFunction,inputSchema:G,outputSchema:K}},code_execution_lambda:{v1:{fn:codeExecutionLambdaStepFunction,inputSchema:q,outputSchema:J}},sign_jwt:{v1:{fn:signJwtStepFunction,inputSchema:Fe,outputSchema:Ie}},mcp_request:{v1:{fn:mcpRequestStepFunction,inputSchema:we,outputSchema:Te}}},formatZodIssues=(e,t,n)=>e instanceof o.z.ZodError?e.issues.map(e=>({...e,kind:t,functionName:n})):[{kind:t,functionName:n,message:e?.message??`unknown error`}],stepFunctionEnhancedWithSchemasValidation=(e,t)=>async({block:n,params:r})=>{try{e.inputSchema&&e.inputSchema.parse(r)}catch(e){return{block:n,successful:!1,errors:formatZodIssues(e,`input_schema_validation`,t)}}let i=await e.fn({block:n,params:r});try{e.outputSchema&&e.outputSchema.parse(i.output)}catch(e){return{block:n,successful:!1,errors:formatZodIssues(e,`output_schema_validation`,t)}}return i},dt={build({functionName:e,version:t=`1`,validateSchemas:n=!1,stepFunctionsList:r=ut}){let i=r?.[e]?.[`v${t}`];if(!i)throw Error(`Unknown step function: ${e} v${t}`);return n?{...i,fn:stepFunctionEnhancedWithSchemasValidation(i,e)}:i}},isForeachStep=e=>`iterator`in e&&typeof e.iterator==`string`;exports.AUTHORIZATION_SCHEMA=Z,exports.ActionTypes=A,exports.AuthType=W,exports.BARE_JEXL_REQUIREMENT=T,exports.BROWSER_USE_INPUT_PARAMS=G,exports.BROWSER_USE_OUTPUT=K,exports.CODE_EXECUTION_LAMBDA_INPUT_PARAMS=q,exports.CODE_EXECUTION_LAMBDA_OUTPUT=J,exports.COMPOSITE_ID_LATEST_VERSION=1,exports.ChangelogLabels=k,exports.CoreError=C,exports.DOWNLOAD_FILE_INPUT_PARAMS=ce,exports.DOWNLOAD_FILE_OUTPUT=le,exports.EMIT_EVENT_INPUT_PARAMS=ue,exports.EMIT_EVENT_OUTPUT=de,exports.Effects=j,exports.ExecutionModes=I,exports.FIELD_META_SCHEMA=B,exports.FORMAT_PATTERNS=E,exports.GROUP_DATA_INPUT_PARAMS=me,exports.GROUP_DATA_OUTPUT=he,exports.IMPACT_TARGETS=z,exports.INPUT_ENUM_REGISTRY=D,exports.InputFormats=P,exports.InputLocations=N,exports.InputTypes=F,exports.MAP_FIELDS_INPUT_PARAMS=be,exports.MAP_FIELDS_OUTPUT=xe,exports.MCP_REQUEST_INPUT_PARAMS=we,exports.MCP_REQUEST_OUTPUT=Te,exports.PAGINATED_REQUEST_INPUT_PARAMS=De,exports.PAGINATED_REQUEST_OUTPUT=Oe,exports.REQUEST_INPUT_PARAMS=je,exports.REQUEST_OUTPUT=Me,exports.ReleaseStages=O,exports.SIGN_JWT_INPUT_PARAMS=Fe,exports.SIGN_JWT_OUTPUT=Ie,exports.SOAP_PAGINATED_REQUEST_INPUT_PARAMS=He,exports.SOAP_PAGINATED_REQUEST_OUTPUT=Ue,exports.SOAP_REQUEST_INPUT_PARAMS=Ge,exports.SOAP_REQUEST_OUTPUT=Ke,exports.STATIC_VALUES_INPUT_PARAMS=Je,exports.STATIC_VALUES_OUTPUT=Ye,exports.SchemaTypes=M,exports.SourceType=H,exports.StepFunctionName=lt,exports.StepFunctionsFactory=dt,exports.StepFunctionsRegistry=ut,exports.StreamType=ee,exports.TYPECAST_INPUT_PARAMS=Ze,exports.TYPECAST_OUTPUT=Qe,exports.TransportType=U,exports.UPLOAD_BINARY_INPUT_PARAMS=rt,exports.UPLOAD_BINARY_OUTPUT=it,exports.UPLOAD_FILE_INPUT_PARAMS=st,exports.UPLOAD_FILE_OUTPUT=ct,exports.areCursorsEqual=areCursorsEqual,exports.buildExpressionContext=buildExpressionContext,exports.collectFieldMetaIssues=collectFieldMetaIssues,exports.computeDataSyncFingerprint=computeDataSyncFingerprint,exports.decodeCompositeId=decodeCompositeId,exports.encodeCompositeId=encodeCompositeId,exports.evaluateEventRouter=evaluateEventRouter,exports.evaluateExternalAccountIdExtractor=evaluateExternalAccountIdExtractor,exports.expandCursor=expandCursor,exports.getCategoryDetails=getCategoryDetails,exports.getInputEnumValues=getInputEnumValues,exports.getIteratorLocation=getIteratorLocation,exports.getPaginationKeys=getPaginationKeys,exports.isBareJexl=isBareJexl,exports.isCompositeId=isCompositeId,exports.isCoreError=isCoreError,exports.isCursorEmpty=isCursorEmpty,exports.isForeachStep=isForeachStep,exports.isValidCategory=isValidCategory,exports.isValidEnumRef=isValidEnumRef,exports.minifyCursor=minifyCursor,exports.stripIncrementalParams=stripIncrementalParams,exports.stripPaginationParams=stripPaginationParams,exports.updateCursor=updateCursor;