@stackone/core 1.74.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -3,7 +3,6 @@ import http from "node:http";
3
3
  import https from "node:https";
4
4
  import * as zod_v40 from "zod/v4";
5
5
  import * as zod_v4_core0 from "zod/v4/core";
6
- import { IOlapClient } from "@stackone/olap";
7
6
 
8
7
  //#region src/categories/types.d.ts
9
8
  type Category = 'hris' | 'crm' | 'ats' | 'lms' | 'marketing' | 'filestorage' | 'internal' | 'action';
@@ -464,6 +463,10 @@ declare const stepFunctions: {
464
463
  indexField: zod_v40.ZodOptional<zod_v40.ZodString>;
465
464
  dataKey: zod_v40.ZodOptional<zod_v40.ZodString>;
466
465
  nextKey: zod_v40.ZodOptional<zod_v40.ZodString>;
466
+ nextKeyIn: zod_v40.ZodOptional<zod_v40.ZodEnum<{
467
+ data: "data";
468
+ headers: "headers";
469
+ }>>;
467
470
  }, zod_v4_core0.$strict>>;
468
471
  iterator: zod_v40.ZodObject<{
469
472
  key: zod_v40.ZodString;
@@ -517,6 +520,65 @@ declare const stepFunctions: {
517
520
  };
518
521
  };
519
522
  //#endregion
523
+ //#region ../olap/src/olap/olapOptions.d.ts
524
+ type OlapOptions = {
525
+ logs?: LogsOptions;
526
+ advanced?: AdvancedOptions;
527
+ };
528
+ type LogsOptions = {
529
+ enabled?: boolean;
530
+ };
531
+ type AdvancedOptions = {
532
+ enabled?: boolean;
533
+ ttl?: number;
534
+ errorsOnly?: boolean;
535
+ };
536
+ //#endregion
537
+ //#region ../olap/src/types.d.ts
538
+ interface IOlapClient {
539
+ recordAction(actionResult: ActionResult, options?: OlapOptions): void;
540
+ recordStep(stepResult: StepResult, options?: OlapOptions): void;
541
+ }
542
+ type ActionResult = {
543
+ actionRunId: string;
544
+ actionId: string;
545
+ connectorKey: string;
546
+ connectorVersion: string;
547
+ actionType: string;
548
+ mode?: string;
549
+ category?: string;
550
+ organizationId: string;
551
+ projectSecureId: string;
552
+ accountSecureId: string;
553
+ originOwnerId?: string;
554
+ originOwnerName?: string;
555
+ httpMethod?: string;
556
+ url?: string;
557
+ path?: string;
558
+ sourceId?: string;
559
+ sourceType?: string;
560
+ sourceValue?: string;
561
+ resource?: string;
562
+ subResource?: string;
563
+ childResource?: string;
564
+ status?: string;
565
+ message?: string;
566
+ outputs?: unknown;
567
+ startTime?: Date;
568
+ endTime?: Date;
569
+ };
570
+ type StepResult = {
571
+ actionRunId: string;
572
+ stepId: string;
573
+ status?: string;
574
+ message?: string;
575
+ outputs?: unknown;
576
+ errors?: unknown;
577
+ skipped?: boolean;
578
+ startTime?: Date;
579
+ endTime?: Date;
580
+ };
581
+ //#endregion
520
582
  //#region src/cursor/types.d.ts
521
583
  type Position = {
522
584
  pageNumber?: number | null;
@@ -557,7 +619,7 @@ type Block = {
557
619
  olapClient?: IOlapClient;
558
620
  settings?: Settings;
559
621
  logger?: ILogger;
560
- operation?: Operation;
622
+ action?: Action;
561
623
  credentials?: Credentials;
562
624
  outputs?: unknown;
563
625
  nextCursor?: Cursor | null;
@@ -578,7 +640,7 @@ type BlockContext = {
578
640
  connectorVersion: string;
579
641
  category: Category;
580
642
  schema?: string;
581
- operationType: OperationType;
643
+ actionType: ActionType;
582
644
  authenticationType: string;
583
645
  environment: string;
584
646
  actionRunId?: string;
@@ -701,8 +763,8 @@ type Connector = {
701
763
  description: string;
702
764
  categories?: Category[];
703
765
  authentication?: Authentication;
704
- operations?: {
705
- [operationId: string]: Operation;
766
+ actions?: {
767
+ [actionId: string]: Action;
706
768
  };
707
769
  rateLimit?: RateLimitConfig;
708
770
  concurrency?: ConcurrencyConfig;
@@ -711,7 +773,7 @@ type Connector = {
711
773
  type Assets = {
712
774
  icon: string;
713
775
  };
714
- type OperationType = 'list' | 'get' | 'create' | 'update' | 'delete' | 'custom' | 'refresh_token' | 'test' | 'unknown';
776
+ type ActionType = 'list' | 'get' | 'create' | 'update' | 'delete' | 'custom' | 'refresh_token' | 'test' | 'unknown';
715
777
  type InputLocation = 'body' | 'query' | 'path' | 'headers';
716
778
  type Input = {
717
779
  name: string;
@@ -722,7 +784,7 @@ type Input = {
722
784
  array?: boolean;
723
785
  properties?: Omit<Input, 'in'>[];
724
786
  };
725
- type Operation = {
787
+ type Action = {
726
788
  id: string;
727
789
  categories: Category[];
728
790
  label: string;
@@ -731,7 +793,7 @@ type Operation = {
731
793
  schemaType: 'native' | 'unified';
732
794
  endpoint?: string;
733
795
  context?: string;
734
- operationType: OperationType;
796
+ actionType: ActionType;
735
797
  tags?: string[];
736
798
  releaseStage?: ReleaseStage;
737
799
  entrypointUrl?: string;
@@ -742,8 +804,8 @@ type Operation = {
742
804
  };
743
805
  result?: string | Record<string, unknown>;
744
806
  responses: {
745
- success: OperationResponse;
746
- errors: Record<number, OperationResponse>;
807
+ success: ActionResponse;
808
+ errors: Record<number, ActionResponse>;
747
809
  };
748
810
  cursor: {
749
811
  enabled: boolean;
@@ -772,7 +834,7 @@ type SyncFilterConfig = {
772
834
  initialLoopbackPeriod: string;
773
835
  incrementalLoopbackPeriod: string;
774
836
  };
775
- type OperationResponse = {
837
+ type ActionResponse = {
776
838
  statusCode: number;
777
839
  description?: string;
778
840
  };
@@ -795,8 +857,8 @@ type SupportConfig = {
795
857
  link: string;
796
858
  description?: string;
797
859
  };
798
- type TestOperationConfig = {
799
- operation: Operation;
860
+ type TestActionConfig = {
861
+ action: Action;
800
862
  condition?: string;
801
863
  required: boolean;
802
864
  };
@@ -814,9 +876,9 @@ type AuthenticationConfig = {
814
876
  setupFields?: AuthenticationField[];
815
877
  refreshAuthentication?: {
816
878
  schedule?: string;
817
- operation: Operation;
879
+ action: Action;
818
880
  };
819
- testOperations?: TestOperationConfig[];
881
+ testActions?: TestActionConfig[];
820
882
  };
821
883
  type Authentication = {
822
884
  [authType: string]: {
@@ -929,4 +991,4 @@ type Account = {
929
991
  projectSecureId: string;
930
992
  };
931
993
  //#endregion
932
- export { AUTHENTICATION_SCHEMA, type Account, type Assets, type Authentication, type AuthenticationConfig, type AuthenticationField, type Block, type BlockContext, type BlockIndexedRecord, COMPOSITE_ID_LATEST_VERSION, type Category, type CompositeIdentifier, type CompositeIdentifierConfig, type CompositeIdentifierConnectorConfig, type Connector, CoreError, type Cursor, type FieldConfig, type Input, type InputLocation, type Operation, type OperationResponse, type OperationType, type ReleaseStage, ReleaseStages, type Schema, type SchemaField, type Settings, type Step, type StepFunction, StepFunctionName, type StepFunctionOutput, type StepFunctionParams, StepFunctionsFactory, stepFunctions as StepFunctionsRegistry, type StepsSnapshots, type SupportConfig, type TestOperationConfig, areCursorsEqual, decodeCompositeId, encodeCompositeId, expandCursor, getCategoryDetails, isCompositeId, isCoreError, isCursorEmpty, isValidCategory, minifyCursor, updateCursor };
994
+ export { AUTHENTICATION_SCHEMA, type Account, type Action, type ActionResponse, type ActionType, type Assets, type Authentication, type AuthenticationConfig, type AuthenticationField, type Block, type BlockContext, type BlockIndexedRecord, COMPOSITE_ID_LATEST_VERSION, type Category, type CompositeIdentifier, type CompositeIdentifierConfig, type CompositeIdentifierConnectorConfig, type Connector, CoreError, type Cursor, type FieldConfig, type Input, type InputLocation, type ReleaseStage, ReleaseStages, type Schema, type SchemaField, type Settings, type Step, type StepFunction, StepFunctionName, type StepFunctionOutput, type StepFunctionParams, StepFunctionsFactory, stepFunctions as StepFunctionsRegistry, type StepsSnapshots, type SupportConfig, type TestActionConfig, areCursorsEqual, decodeCompositeId, encodeCompositeId, expandCursor, getCategoryDetails, isCompositeId, isCoreError, isCursorEmpty, isValidCategory, minifyCursor, updateCursor };
package/dist/index.d.ts CHANGED
@@ -3,7 +3,6 @@ import http from "node:http";
3
3
  import https from "node:https";
4
4
  import * as zod_v40 from "zod/v4";
5
5
  import * as zod_v4_core0 from "zod/v4/core";
6
- import { IOlapClient } from "@stackone/olap";
7
6
 
8
7
  //#region src/categories/types.d.ts
9
8
  type Category = 'hris' | 'crm' | 'ats' | 'lms' | 'marketing' | 'filestorage' | 'internal' | 'action';
@@ -464,6 +463,10 @@ declare const stepFunctions: {
464
463
  indexField: zod_v40.ZodOptional<zod_v40.ZodString>;
465
464
  dataKey: zod_v40.ZodOptional<zod_v40.ZodString>;
466
465
  nextKey: zod_v40.ZodOptional<zod_v40.ZodString>;
466
+ nextKeyIn: zod_v40.ZodOptional<zod_v40.ZodEnum<{
467
+ data: "data";
468
+ headers: "headers";
469
+ }>>;
467
470
  }, zod_v4_core0.$strict>>;
468
471
  iterator: zod_v40.ZodObject<{
469
472
  key: zod_v40.ZodString;
@@ -517,6 +520,65 @@ declare const stepFunctions: {
517
520
  };
518
521
  };
519
522
  //#endregion
523
+ //#region ../olap/src/olap/olapOptions.d.ts
524
+ type OlapOptions = {
525
+ logs?: LogsOptions;
526
+ advanced?: AdvancedOptions;
527
+ };
528
+ type LogsOptions = {
529
+ enabled?: boolean;
530
+ };
531
+ type AdvancedOptions = {
532
+ enabled?: boolean;
533
+ ttl?: number;
534
+ errorsOnly?: boolean;
535
+ };
536
+ //#endregion
537
+ //#region ../olap/src/types.d.ts
538
+ interface IOlapClient {
539
+ recordAction(actionResult: ActionResult, options?: OlapOptions): void;
540
+ recordStep(stepResult: StepResult, options?: OlapOptions): void;
541
+ }
542
+ type ActionResult = {
543
+ actionRunId: string;
544
+ actionId: string;
545
+ connectorKey: string;
546
+ connectorVersion: string;
547
+ actionType: string;
548
+ mode?: string;
549
+ category?: string;
550
+ organizationId: string;
551
+ projectSecureId: string;
552
+ accountSecureId: string;
553
+ originOwnerId?: string;
554
+ originOwnerName?: string;
555
+ httpMethod?: string;
556
+ url?: string;
557
+ path?: string;
558
+ sourceId?: string;
559
+ sourceType?: string;
560
+ sourceValue?: string;
561
+ resource?: string;
562
+ subResource?: string;
563
+ childResource?: string;
564
+ status?: string;
565
+ message?: string;
566
+ outputs?: unknown;
567
+ startTime?: Date;
568
+ endTime?: Date;
569
+ };
570
+ type StepResult = {
571
+ actionRunId: string;
572
+ stepId: string;
573
+ status?: string;
574
+ message?: string;
575
+ outputs?: unknown;
576
+ errors?: unknown;
577
+ skipped?: boolean;
578
+ startTime?: Date;
579
+ endTime?: Date;
580
+ };
581
+ //#endregion
520
582
  //#region src/cursor/types.d.ts
521
583
  type Position = {
522
584
  pageNumber?: number | null;
@@ -557,7 +619,7 @@ type Block = {
557
619
  olapClient?: IOlapClient;
558
620
  settings?: Settings;
559
621
  logger?: ILogger;
560
- operation?: Operation;
622
+ action?: Action;
561
623
  credentials?: Credentials;
562
624
  outputs?: unknown;
563
625
  nextCursor?: Cursor | null;
@@ -578,7 +640,7 @@ type BlockContext = {
578
640
  connectorVersion: string;
579
641
  category: Category;
580
642
  schema?: string;
581
- operationType: OperationType;
643
+ actionType: ActionType;
582
644
  authenticationType: string;
583
645
  environment: string;
584
646
  actionRunId?: string;
@@ -701,8 +763,8 @@ type Connector = {
701
763
  description: string;
702
764
  categories?: Category[];
703
765
  authentication?: Authentication;
704
- operations?: {
705
- [operationId: string]: Operation;
766
+ actions?: {
767
+ [actionId: string]: Action;
706
768
  };
707
769
  rateLimit?: RateLimitConfig;
708
770
  concurrency?: ConcurrencyConfig;
@@ -711,7 +773,7 @@ type Connector = {
711
773
  type Assets = {
712
774
  icon: string;
713
775
  };
714
- type OperationType = 'list' | 'get' | 'create' | 'update' | 'delete' | 'custom' | 'refresh_token' | 'test' | 'unknown';
776
+ type ActionType = 'list' | 'get' | 'create' | 'update' | 'delete' | 'custom' | 'refresh_token' | 'test' | 'unknown';
715
777
  type InputLocation = 'body' | 'query' | 'path' | 'headers';
716
778
  type Input = {
717
779
  name: string;
@@ -722,7 +784,7 @@ type Input = {
722
784
  array?: boolean;
723
785
  properties?: Omit<Input, 'in'>[];
724
786
  };
725
- type Operation = {
787
+ type Action = {
726
788
  id: string;
727
789
  categories: Category[];
728
790
  label: string;
@@ -731,7 +793,7 @@ type Operation = {
731
793
  schemaType: 'native' | 'unified';
732
794
  endpoint?: string;
733
795
  context?: string;
734
- operationType: OperationType;
796
+ actionType: ActionType;
735
797
  tags?: string[];
736
798
  releaseStage?: ReleaseStage;
737
799
  entrypointUrl?: string;
@@ -742,8 +804,8 @@ type Operation = {
742
804
  };
743
805
  result?: string | Record<string, unknown>;
744
806
  responses: {
745
- success: OperationResponse;
746
- errors: Record<number, OperationResponse>;
807
+ success: ActionResponse;
808
+ errors: Record<number, ActionResponse>;
747
809
  };
748
810
  cursor: {
749
811
  enabled: boolean;
@@ -772,7 +834,7 @@ type SyncFilterConfig = {
772
834
  initialLoopbackPeriod: string;
773
835
  incrementalLoopbackPeriod: string;
774
836
  };
775
- type OperationResponse = {
837
+ type ActionResponse = {
776
838
  statusCode: number;
777
839
  description?: string;
778
840
  };
@@ -795,8 +857,8 @@ type SupportConfig = {
795
857
  link: string;
796
858
  description?: string;
797
859
  };
798
- type TestOperationConfig = {
799
- operation: Operation;
860
+ type TestActionConfig = {
861
+ action: Action;
800
862
  condition?: string;
801
863
  required: boolean;
802
864
  };
@@ -814,9 +876,9 @@ type AuthenticationConfig = {
814
876
  setupFields?: AuthenticationField[];
815
877
  refreshAuthentication?: {
816
878
  schedule?: string;
817
- operation: Operation;
879
+ action: Action;
818
880
  };
819
- testOperations?: TestOperationConfig[];
881
+ testActions?: TestActionConfig[];
820
882
  };
821
883
  type Authentication = {
822
884
  [authType: string]: {
@@ -929,4 +991,4 @@ type Account = {
929
991
  projectSecureId: string;
930
992
  };
931
993
  //#endregion
932
- export { AUTHENTICATION_SCHEMA, type Account, type Assets, type Authentication, type AuthenticationConfig, type AuthenticationField, type Block, type BlockContext, type BlockIndexedRecord, COMPOSITE_ID_LATEST_VERSION, type Category, type CompositeIdentifier, type CompositeIdentifierConfig, type CompositeIdentifierConnectorConfig, type Connector, CoreError, type Cursor, type FieldConfig, type Input, type InputLocation, type Operation, type OperationResponse, type OperationType, type ReleaseStage, ReleaseStages, type Schema, type SchemaField, type Settings, type Step, type StepFunction, StepFunctionName, type StepFunctionOutput, type StepFunctionParams, StepFunctionsFactory, stepFunctions as StepFunctionsRegistry, type StepsSnapshots, type SupportConfig, type TestOperationConfig, areCursorsEqual, decodeCompositeId, encodeCompositeId, expandCursor, getCategoryDetails, isCompositeId, isCoreError, isCursorEmpty, isValidCategory, minifyCursor, updateCursor };
994
+ export { AUTHENTICATION_SCHEMA, type Account, type Action, type ActionResponse, type ActionType, type Assets, type Authentication, type AuthenticationConfig, type AuthenticationField, type Block, type BlockContext, type BlockIndexedRecord, COMPOSITE_ID_LATEST_VERSION, type Category, type CompositeIdentifier, type CompositeIdentifierConfig, type CompositeIdentifierConnectorConfig, type Connector, CoreError, type Cursor, type FieldConfig, type Input, type InputLocation, type ReleaseStage, ReleaseStages, type Schema, type SchemaField, type Settings, type Step, type StepFunction, StepFunctionName, type StepFunctionOutput, type StepFunctionParams, StepFunctionsFactory, stepFunctions as StepFunctionsRegistry, type StepsSnapshots, type SupportConfig, type TestActionConfig, areCursorsEqual, decodeCompositeId, encodeCompositeId, expandCursor, getCategoryDetails, isCompositeId, isCoreError, isCursorEmpty, isValidCategory, minifyCursor, updateCursor };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=s(require(`@stackone/utils`)),l=s(require(`@stackone/expressions`)),u=s(require(`@stackone/transport`)),d={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`},internal:{title:`Internal`,key:`internal`,description:`Category for internal operations`},action:{title:`Action`,key:`action`,description:`Action`}},f=e=>{let t=d[e.toLowerCase()];return t??null},p=e=>!!d[e.toLowerCase()],m=`so1!`,h=(0,c.encodeToBase64)(m),g=`:`,_=`,`,v=RegExp(`(?<!\\\\)${g}`,`g`),y=RegExp(`(?<!\\\\)${_}`,`g`),b=1;var x=class e extends Error{type;category;context;constructor({category:t,name:n,type:r,context:i,message:a}){super(a),this.name=n??`CoreError`,this.type=r,this.category=t,this.context=i,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.category}-${this.name} [${this.type}]${e}`}},S=class extends x{constructor(e,t,n){super({category:`CompositeId`,name:t??`BaseCompositeIdError`,type:e,message:n})}},C=class extends S{constructor(e){super(`COMPOSITE_ID_MISSING_HEADER_ERROR`,`CompositeIdMissingHeaderError`,e??`Invalid compositeId, missing header`)}},w=class extends S{constructor(e){super(`COMPOSITE_ID_MISSING_BODY_ERROR`,`CompositeIdMissingBodyError`,e??`Invalid compositeId, missing body`)}},T=class extends S{constructor(e){super(`COMPOSITE_ID_UNKNOWN_IDENTIFIER_ERROR`,`CompositeIdUnknownIdentifierError`,e??`Invalid compositeId, unknown identifier`)}},E=class extends S{constructor(e){super(`COMPOSITE_ID_UNSUPPORTED_VERSION_ERROR`,`CompositeIdUnsupportedVersionError`,e??`Invalid compositeId, unsupported version`)}};const D=e=>!(0,c.isMissing)(e)&&`value`in e&&e.value!==void 0,O=e=>!(0,c.isMissing)(e)&&`identifiers`in e&&e.identifiers!==void 0,k=(e,t={version:b})=>{if(t.version===1)return F(j(e,t.aliases));throw new E(`Cannot generate ID, unsupported version number: ${t.version}`)},A=(e,t={version:b})=>{let n=P(e,t),r={};return n&&n.split(y).forEach(e=>{let[n,i]=e.split(v),a=N(n,t.aliases??{});r[a]=ee(i)}),r},j=(e,t={})=>{if(D(e))return M({identifier:e,compositeIdAliases:t,isSoleIdentifier:!0});if(O(e))return e.identifiers.map(e=>M({identifier:e,compositeIdAliases:t,isSoleIdentifier:!1})).join(_);throw new T},M=({identifier:e,compositeIdAliases:t,isSoleIdentifier:n})=>{let r=n?`id`:t[e.key]||e.key;return[r,L(e.value)].filter(Boolean).join(g)},N=(e,t)=>Object.keys(t).find(n=>t[n]===e)??e,P=(e,t)=>{if(t.version===1)return I(e);throw new E(`Cannot decode ID, unsupported version number: ${t.version}`)},F=e=>`${h}${(0,c.encodeToBase64)(e)}`,I=e=>{if(!e.startsWith(h))throw new C(`Trying to decode an ID without the header: ${e}`);let t=e.split(h)[1];if(!t)throw new w(`Trying to decode an ID without a body: ${e}`);return(0,c.decodeFromBase64)(t)},L=e=>[_,g].reduce((e,t)=>e.replace(t,`\\`+t),e),ee=e=>[_,g].reduce((e,t)=>{let n=`\\`+t;return e.replace(RegExp(`\\\\`+n,`g`),t)},e),te=e=>(0,c.isMissing)(e)?!1:e.startsWith(h),ne=[`preview`,`beta`,`ga`,`deprecated`],re=(0,c.zStrictObject)({r:c.z.record(c.z.string(),(0,c.zStrictObject)({n:c.z.number().optional().nullable(),c:c.z.string().optional().nullable(),p:c.z.number().optional().nullable()})),v:c.z.number(),t:c.z.number()}),ie=(0,c.zStrictObject)({remote:c.z.record(c.z.string(),(0,c.zStrictObject)({pageNumber:c.z.number().optional(),providerPageCursor:c.z.string().optional(),position:c.z.number().optional()})),version:c.z.number(),timestamp:c.z.number()}),ae=e=>(0,c.encodeToBase64)(JSON.stringify(oe(e))),oe=e=>{let{remote:t,version:n,timestamp:r}=e,i=Object.fromEntries(Object.entries(t).map(([e,{pageNumber:t,providerPageCursor:n,position:r}])=>[e,{n:t,c:n,p:r}])),a={r:i,v:n,t:r};return a},R=e=>{try{if((0,c.isString)(e)){let t=(0,c.decodeFromBase64)(e),n=JSON.parse(t),r=re.parse(n);return se(r)}else return ie.parse(e),e}catch{return null}},se=e=>{let{r:t,v:n,t:r}=e,i=Object.fromEntries(Object.entries(t).map(([e,{n:t,c:n,p:r}])=>[e,{pageNumber:t,providerPageCursor:n,position:r}])),a={remote:i,version:n,timestamp:r};return a},ce=(e,t)=>{let n=typeof e==`string`?R(e):e,r=typeof t==`string`?R(t):t;if(n===null||r===null)return n===r;let{timestamp:i,...a}=n,{timestamp:o,...s}=r;return(0,c.getContentHash)(a)===(0,c.getContentHash)(s)},le=({cursor:e,ignoreStepIndex:t})=>(0,c.isMissing)(e)?!0:Object.keys(e?.remote??{}).reduce((n,r)=>{let i=e?.remote?.[r];return((0,c.isMissing)(t)||r!==t.toString())&&(n=n&&(0,c.isMissing)(i.pageNumber)&&(0,c.isMissing)(i.position)&&(0,c.isMissing)(i.providerPageCursor)),n},!0),ue=({cursor:e,stepIndex:t,pageNumber:n,providerPageCursor:r,position:i})=>{let a={pageNumber:n??void 0,providerPageCursor:r??void 0,position:i??void 0},o=(0,c.isMissing)(n)&&(0,c.isMissing)(r)&&(0,c.isMissing)(i);return(0,c.isMissing)(e)?{remote:o?{}:{[t]:a},version:2,timestamp:Date.now()}:o?(delete e.remote[t],e):{...e,remote:{...e.remote,[t]:a}}},de=e=>e instanceof x,z=c.z.object({stepsDataToGroup:c.z.array(c.z.string()),isSingleRecord:c.z.boolean().optional()}),fe=c.z.object({data:c.z.unknown()}),pe=async({block:e,params:t})=>{let{stepsDataToGroup:n,isSingleRecord:r}=z.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=>{let r=(0,c.notMissing)(t[e])?t[e]:{};t[e]={...r,[n]:{...i[e]}}}),t):t},{});return{block:{...e},successful:!0,output:{data:r?i:Object.values(i)}}},me=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;if(Array.isArray(e.result)){let a=e.result.length;i=e.result.map((e,i)=>{let o=he(r,a,i),s=B(e,t,o);return n.push(...s.errors||[]),s.record})}else{let a=B(e.result,t,r);i=a.record,n.push(...a.errors||[])}return{block:{...e,result:i},successful:!0,errors:Object.keys(n).length>0?n:void 0}},he=(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},{}),B=(e,t,n)=>{if(!e||!n)return{record:e};let r={unified:{...e},...typeof n==`object`?n:{}},i={},a=[],o={...e};for(let n of t){let{error:t,value:s}=ge(r,e.id,n);if(t){a.push(t);continue}n.custom?i[n.targetFieldKey]=s:o[n.targetFieldKey]=s}return{record:{...o,unified_custom_fields:Object.keys(i).length>0?i:void 0},errors:a.length>0?a:void 0}},ge=(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,l.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}},_e=e=>{switch(e){case`country_alpha2code_by_alpha2code`:return c.getCountryAlpha2CodeByAlpha2Code;case`country_alpha3code_by_alpha3code`:return c.getCountryAlpha3CodeByAlpha3Code;case`country_code_by_country_code`:return c.getCountryCodeByCountryCode;case`country_name_by_country_name`:return c.getCountryNameByCountryName;case`country_name_by_alpha3code`:return c.getCountryNameByAlpha3Code;case`country_name_by_alpha2code`:return c.getCountryNameByAlpha2Code;case`country_name_by_country_code`:return c.getCountryNameByCountryCode;case`country_alpha3code_by_alpha2code`:return c.getCountryAlpha3CodeByAlpha2Code;case`country_alpha3code_by_country_name`:return c.getCountryAlpha3CodeByCountryName;case`country_alpha3code_by_country_code`:return c.getCountryAlpha3CodeByCountryCode;case`country_alpha2code_by_alpha3code`:return c.getCountryAlpha2CodeByAlpha3Code;case`country_alpha2code_by_country_name`:return c.getCountryAlpha2CodeByCountryName;case`country_alpha2code_by_country_code`:return c.getCountryAlpha2CodeByCountryCode;case`country_code_by_alpha2code`:return c.getCountryCodeByAlpha2Code;case`country_code_by_alpha3code`:return c.getCountryCodeByAlpha3Code;case`country_code_by_country_name`:return c.getCountryCodeByCountryName;case`country_subdivisions_by_alpha2code`:return c.getCountrySubDivisionsByAlpha2Code;case`country_subdivision_code_by_subdivision_name`:return c.getCountrySubDivisionCodeBySubDivisionName;case`country_alpha2code_by_citizenship`:return c.getCountryAlpha2CodeByCitizenship;case`country_subdivision_name_by_subdivision_code`:return c.getCountrySubDivisionNameBySubDivisionCode;case`document_file_format_from_extension`:return c.getDocumentFileFormatFromExtension;default:return}},V=(0,c.zStrictObject)({targetFieldKey:c.z.string(),alias:c.z.string().optional(),expression:c.z.string().optional(),values:c.z.unknown().optional(),type:c.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:c.z.boolean().default(!1),custom:c.z.boolean().default(!1),hidden:c.z.boolean().default(!1),enumMapper:(0,c.zStrictObject)({matcher:c.z.string().or((0,c.zStrictObject)({matchExpression:c.z.string(),value:c.z.string()}).array())}).optional(),properties:c.z.lazy(()=>V).array().optional()}),H=c.z.object({fields:V.array(),dataSource:c.z.string(),externalSources:c.z.record(c.z.string(),c.z.string()).optional()}),ve=c.z.object({data:c.z.unknown()}),ye=async({block:e,params:t})=>{let n=[],{fields:r,dataSource:i,externalSources:a}=H.parse(t),o=(0,l.evaluate)(i,e);if(!r||!i||e?.debug?.custom_mappings===`disabled`||!o)return{block:e,successful:!0};let s=Object.keys(a??{})?.reduce((t,n)=>(t[n]=(0,l.evaluate)(a?.[n],e),t),{}),c;if(Array.isArray(o))c=o.map(e=>{let t=U(r,{...e,external:s});return n.push(...t?.errors||[]),t?.record});else{let e=U(r,{...o,external:s});c=e?.record,n.push(...e?.errors||[])}return{block:{...e},successful:!0,output:{data:c},errors:Object.keys(n).length>0?n:void 0}},be=(e,t,n)=>{if(Array.isArray(e.values))return e.values.map(r=>{let i=W(r,t),a=U(e.properties,i);return(0,c.notMissing)(a?.errors)&&n.push(...a.errors),a?.record}).filter(Boolean)},xe=(e,t,n)=>{if(e.expression)try{let r=(0,l.evaluate)(e.expression,t);if(Array.isArray(r))return r.map(t=>{let r=U(e.properties,t);return(0,c.notMissing)(r?.errors)&&n.push(...r.errors),r?.record}).filter(Boolean);{let t=U(e.properties,r);return(0,c.notMissing)(t?.errors)&&n.push(...t.errors),t?.record}}catch{n.push({message:`Invalid expression`,id:t?.id,targetField:e.targetFieldKey});return}},Se=(e,t,n)=>{let r=(0,c.notMissing)(e.values)?e.values:t,i=U(e.properties,r);return(0,c.notMissing)(i?.errors)&&n.push(...i.errors),i?.record},Ce=(e,t,n)=>{if(!(0,c.isMissing)(e.properties))return e.array&&Array.isArray(e.values)?be(e,t,n):e.array&&e.expression?xe(e,t,n):Se(e,t,n)},U=(e,t)=>{if(!t)return;let n={},r=[],i={};for(let a of e){let e;if(a.type===`object`){if(e=Ce(a,t,r),e===void 0)continue}else{let{error:n,value:i}=we(t,t?.id,a);if(e=i,n){r.push(n);continue}}a.custom?n[a.targetFieldKey]=e:i[a.targetFieldKey]=e}let a=Object.keys(n).length>0?{unified_custom_fields:n}:{};return{record:{...i,...a},errors:r.length>0?r:void 0}},W=(e,t)=>{if(e==null)return e;if(typeof e==`string`){if((0,l.isValidExpression)(e))try{return(0,l.evaluate)(e,t)}catch{return e}return e}if(Array.isArray(e))return e.map(e=>W(e,t));if(typeof e==`object`){let n={...e};for(let[e,r]of Object.entries(n))n[e]=W(r,t);return n}return e},we=(e,t,n)=>{switch(n.type){case`string`:case`number`:case`boolean`:case`datetime_string`:return G(n,t,e);case`enum`:return Te(n,t,e);default:return{error:{message:`Invalid type`,id:t,targetField:n.targetFieldKey}}}},G=(e,t,n)=>{if(!e.expression)return{error:{message:`Expression is empty`,id:t,targetField:e.targetFieldKey}};let r;try{r=(0,l.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}},Te=(e,t,n)=>{let r=G(e,t,n),i=(0,c.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,c.isString)(a)){let n=_e(a);if((0,c.notMissing)(n)){let e=(0,c.notMissing)(i)?n(i):null;return{value:{value:e??`unmapped_value`,source_value:i}}}else return{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,a=(0,l.evaluate)(t,n);if(a===!0)return{value:{value:r,source_value:i}}}return{value:{value:`unmapped_value`,source_value:i}}},Ee=(0,c.zStrictObject)({type:c.z.literal(`none`)}),De=(0,c.zStrictObject)({type:c.z.literal(`basic`),username:c.z.string().optional(),password:c.z.string().optional(),encoding:c.z.string().optional()}),Oe=(0,c.zStrictObject)({type:c.z.literal(`bearer`),token:c.z.string(),includeBearer:c.z.boolean().optional().default(!0)}),ke=(0,c.zStrictObject)({type:c.z.literal(`oauth2`),authorizationUrl:c.z.string().optional(),authorizationParams:c.z.record(c.z.string(),c.z.string()).optional(),tokenUrl:c.z.string().optional(),tokenParams:c.z.record(c.z.string(),c.z.string()).optional(),tokenExpiresIn:c.z.number().optional(),tokenRefreshExpiresIn:c.z.number().optional(),token:c.z.string(),includeBearer:c.z.boolean().optional().default(!0),scopes:c.z.string().optional(),scopeDelimiter:c.z.string().optional(),customHeaders:c.z.record(c.z.string(),c.z.string()).optional(),pkce:c.z.boolean().optional()}),Ae=c.z.discriminatedUnion(`type`,[Ee,De,Oe,ke]),K=c.z.object({baseUrl:c.z.string(),url:c.z.string(),method:c.z.enum(u.HttpMethods),response:(0,c.zStrictObject)({indexField:c.z.string().optional(),dataKey:c.z.string().optional(),nextKey:c.z.string().optional()}).optional(),iterator:(0,c.zStrictObject)({key:c.z.string(),in:c.z.enum(u.RequestParameterLocations)}),cursor:(0,c.zStrictObject)({token:c.z.string().optional().nullable(),position:c.z.number().optional().nullable()}).optional(),customErrors:u.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),args:(0,c.zStrictObject)({name:c.z.string(),value:c.z.unknown(),in:c.z.enum(u.RequestParameterLocations),condition:c.z.string().optional()}).array().optional()}),je=(0,c.zStrictObject)({data:c.z.unknown().optional(),raw:c.z.unknown().optional(),statusCode:c.z.number(),message:c.z.string().optional(),next:c.z.string().optional().nullable(),position:c.z.number().optional()}).optional(),Me=25,Ne=async({block:e,params:t})=>{let n=u.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)?Me:i,o=r?r.filter(t=>!t.condition||(0,l.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,s=t?(0,l.safeEvaluateRecord)({...t,args:o},e):{},d={...s,customErrors:t?.customErrors},{baseUrl:f,url:p,method:m,response:h,iterator:g,cursor:_,customErrors:v,args:y}=K.parse(d),b=s?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,x=Ae.parse(b),S=y?(0,u.parseRequestParameters)(y):{query:{},body:{},headers:{}},C=(0,u.createAuthorizationHeaders)(x),w={...S?.headers??{},...C},T=e.connector?.rateLimit,E=e.connector?.concurrency,D=T!==void 0||E!==void 0?{rateLimit:T,concurrency:E}:void 0,O=_?.token??null,k=null,A=null,j=[],M=[],N=[],P=a,F=_?.position??0,I=!0,L=!0;do{I?I=!1:F=0,O!==null&&(g.in===`query`?S.query[g.key]=O.toString():g.in===`body`&&(S.body[g.key]=O));let t;try{t=await n.performRequest({httpClient:e.httpClient,url:`${f}${p}`,queryParams:S?.query,method:m,headers:w,body:S?.body,customErrorConfigs:v,requestConfig:D})}catch(t){let n=t;return{block:e,successful:!1,errors:[(0,u.serializeHttpResponseError)(t)],output:{statusCode:n?.response?.status??500,message:n?.response?.message}}}k=O,M=h?.dataKey?t.data[h?.dataKey]:t.data;let r=M?.slice(F,F+P);P-=r.length,F+=r.length,N.push(t),j=j.concat(r),A=t?.status,O=h?.nextKey?t.data[h?.nextKey]:void 0,r.length===M.length&&P===0&&(F=0,k=O),L=(0,c.isMissing)(O)&&j.length<a}while((0,c.notMissing)(O)&&j.length<a&&M?.length>0);let ee=Pe(j,h);return{block:e,successful:!0,output:{data:ee,raw:N,statusCode:A,next:L?void 0:k,position:L?void 0:F}}},Pe=(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},Fe=(0,c.zStrictObject)({type:c.z.literal(`none`)}),Ie=(0,c.zStrictObject)({type:c.z.literal(`basic`),username:c.z.string().optional(),password:c.z.string().optional(),encoding:c.z.string().optional()}),Le=(0,c.zStrictObject)({type:c.z.literal(`bearer`),token:c.z.string(),includeBearer:c.z.boolean().optional().default(!0)}),Re=(0,c.zStrictObject)({type:c.z.literal(`oauth2`),authorizationUrl:c.z.string().optional(),authorizationParams:c.z.record(c.z.string(),c.z.string()).optional(),tokenUrl:c.z.string().optional(),tokenParams:c.z.record(c.z.string(),c.z.string()).optional(),tokenExpiresIn:c.z.number().optional(),tokenRefreshExpiresIn:c.z.number().optional(),token:c.z.string(),includeBearer:c.z.boolean().optional().default(!0),scopes:c.z.string().optional(),scopeDelimiter:c.z.string().optional(),customHeaders:c.z.record(c.z.string(),c.z.string()).optional(),pkce:c.z.boolean().optional()}),q=c.z.discriminatedUnion(`type`,[Fe,Ie,Le,Re]),ze=c.z.object({baseUrl:c.z.string().optional(),url:c.z.string(),method:c.z.enum(u.HttpMethods),authorization:q.optional(),response:(0,c.zStrictObject)({collection:c.z.boolean().optional(),indexField:c.z.string().optional(),dataKey:c.z.string().optional()}).optional(),customErrors:u.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),args:(0,c.zStrictObject)({name:c.z.string(),value:c.z.unknown(),in:c.z.enum(u.RequestParameterLocations),condition:c.z.string().optional()}).array().optional()}),Be=(0,c.zStrictObject)({data:c.z.unknown().optional(),raw:c.z.unknown().optional(),statusCode:c.z.number(),message:c.z.string().optional()}).optional(),Ve=async({block:e,params:t})=>{let n=u.RequestClientFactory.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||(0,l.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?(0,l.safeEvaluateRecord)({...t,args:i},e):{},o={...a,customErrors:t?.customErrors},{baseUrl:s,url:d,method:f,response:p,authorization:m,customErrors:h,args:g}=ze.parse(o),_=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,v=g?(0,u.parseRequestParameters)(g):{query:{},body:{},headers:{}},y=(0,c.notMissing)(m)?m:q.parse(_),b=(0,u.createAuthorizationHeaders)(y),x={...v?.headers??{},...b},S=e.connector?.rateLimit,C=e.connector?.concurrency,w=S!==void 0||C!==void 0?{rateLimit:S,concurrency:C}:void 0,T;try{T=await n.performRequest({httpClient:e.httpClient,url:`${s}${d}`,queryParams:v?.query,method:f,headers:x,body:v?.body,customErrorConfigs:h,requestConfig:w})}catch(t){let n=t;return{block:e,successful:!1,errors:[(0,u.serializeHttpResponseError)(t)],output:{statusCode:n?.response?.status??500,message:n?.response?.message}}}let E=p?.dataKey?T.data[p?.dataKey]:T.data,D=He(E,p);return{block:e,successful:!0,output:{data:D,raw:T,statusCode:T?.status,message:T?.message}}},He=(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},Ue=c.z.object({values:c.z.string().or(c.z.record(c.z.string(),c.z.unknown())).or(c.z.array(c.z.unknown()))}),We=c.z.object({data:c.z.unknown()}),Ge=async({block:e,params:t})=>{let{values:n}=Ue.parse(t),r=Array.isArray(n)?n.map(t=>Ke(t,e)):Ke(n,e);return{block:{...e},successful:!0,output:{data:r}}},Ke=(e,t)=>(0,c.isString)(e)?(0,l.safeEvaluate)(e,t):(0,c.isObject)(e)?(0,l.safeEvaluateRecord)(e,t):e,J=c.z.object({targetFieldKey:c.z.string(),type:c.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:c.z.boolean().default(!1),custom:c.z.boolean().default(!1),hidden:c.z.boolean().default(!1),properties:c.z.lazy(()=>J).array().optional()}),qe=c.z.object({fields:J.array().optional(),dataSource:c.z.string()}),Je=c.z.object({data:c.z.unknown()});let Y=function(e){return e.String=`string`,e.Number=`number`,e.Boolean=`boolean`,e.DateTimeString=`datetime_string`,e}({});const X=({value:e,type:t,format:n})=>{if((0,c.isMissing)(e))return null;switch(t){case Y.String:return(0,c.safeParseToString)({value:e});case Y.Number:return(0,c.safeParseToNumber)({value:e});case Y.Boolean:return(0,c.safeParseToBoolean)({value:e});case Y.DateTimeString:return(0,c.safeParseToDateTimeString)({value:e,format:n});default:return e}},Ye=e=>{let t=Object.values(Y);return t.includes(e)},Xe=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=>Ze(e,t)):Ze(e.result,t),{block:{...e,result:n},successful:!0}},Ze=(e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i}=t;Ye(i)&&(!t.custom&&(0,c.notMissing)(n[r])?n[r]=X({value:e[r],type:i}):n.unified_custom_fields&&(0,c.notMissing)(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=X({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},Qe=async({block:e,params:t})=>{let{fields:n,dataSource:r}=qe.parse(t),i=(0,l.evaluate)(r,e);if(!n||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let a;return a=Array.isArray(i)?i.map(e=>Z(e,n)):Z(i,n),{block:{...e},successful:!0,output:{data:a}}},$e=(e,t)=>!e.properties||!t?t:Array.isArray(t)?t.map(t=>typeof t==`object`&&t?Z(t,e.properties):t):typeof t==`object`&&t?Z(t,e.properties):t,Z=(e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i,array:a}=t;i===`object`?!t.custom&&(0,c.notMissing)(n[r])?n[r]=$e(t,e[r]):n.unified_custom_fields&&(0,c.notMissing)(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=$e(t,e.unified_custom_fields?.[r])):Ye(i)&&(!t.custom&&(0,c.notMissing)(n[r])?(!a||!Array.isArray(n[r]))&&(n[r]=X({value:e[r],type:i})):n.unified_custom_fields&&(0,c.notMissing)(n.unified_custom_fields?.[r])&&(!a||!Array.isArray(n.unified_custom_fields[r]))&&(n.unified_custom_fields[r]=X({value:e.unified_custom_fields?.[r],type:i})))}),{...n}};let Q=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.STATIC_VALUES=`static_values`,e}({});const $={[Q.TYPECAST]:{v1:{fn:Xe},v2:{fn:Qe,inputSchema:qe,outputSchema:Je}},[Q.MAP_FIELDS]:{v1:{fn:me},v2:{fn:ye,inputSchema:H,outputSchema:ve}},[Q.REQUEST]:{v1:{fn:Ve,inputSchema:ze,outputSchema:Be}},[Q.GROUP_DATA]:{v1:{fn:pe,inputSchema:z,outputSchema:fe}},[Q.PAGINATED_REQUEST]:{v1:{fn:Ne,inputSchema:K,outputSchema:je}},[Q.STATIC_VALUES]:{v1:{fn:Ge,inputSchema:Ue,outputSchema:We}}},et=(e,t)=>async({block:n,params:r})=>{try{e.inputSchema&&e.inputSchema.parse(r)}catch(e){return{block:n,successful:!1,errors:[{message:`Input parameters for ${t} are invalid: ${e?.message}`}]}}let i=await e.fn({block:n,params:r});try{e.outputSchema&&e.outputSchema.parse(i.output)}catch{return{block:n,successful:!1,errors:[{message:`Output data of ${t} has unexpected format`}]}}return i},tt={build({functionName:e,version:t=`1`,validateSchemas:n=!1,stepFunctionsList:r=$}){let i=r?.[e]?.[`v${t}`];if(!i)throw Error(`Unknown step function: ${e} v${t}`);return n?{...i,fn:et(i,e)}:i}};exports.AUTHENTICATION_SCHEMA=q,exports.COMPOSITE_ID_LATEST_VERSION=b,exports.CoreError=x,exports.ReleaseStages=ne,exports.StepFunctionName=Q,exports.StepFunctionsFactory=tt,exports.StepFunctionsRegistry=$,exports.areCursorsEqual=ce,exports.decodeCompositeId=A,exports.encodeCompositeId=k,exports.expandCursor=R,exports.getCategoryDetails=f,exports.isCompositeId=te,exports.isCoreError=de,exports.isCursorEmpty=le,exports.isValidCategory=p,exports.minifyCursor=ae,exports.updateCursor=ue;
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=s(require(`@stackone/utils`)),l=s(require(`@stackone/expressions`)),u=s(require(`@stackone/transport`)),d={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`},internal:{title:`Internal`,key:`internal`,description:`Category for internal actions`},action:{title:`Action`,key:`action`,description:`Action`}},f=e=>{let t=d[e.toLowerCase()];return t??null},p=e=>!!d[e.toLowerCase()],m=`so1!`,h=(0,c.encodeToBase64)(m),g=`:`,_=`,`,v=RegExp(`(?<!\\\\)${g}`,`g`),y=RegExp(`(?<!\\\\)${_}`,`g`),b=1;var x=class e extends Error{type;category;context;constructor({category:t,name:n,type:r,context:i,message:a}){super(a),this.name=n??`CoreError`,this.type=r,this.category=t,this.context=i,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.category}-${this.name} [${this.type}]${e}`}},S=class extends x{constructor(e,t,n){super({category:`CompositeId`,name:t??`BaseCompositeIdError`,type:e,message:n})}},C=class extends S{constructor(e){super(`COMPOSITE_ID_MISSING_HEADER_ERROR`,`CompositeIdMissingHeaderError`,e??`Invalid compositeId, missing header`)}},w=class extends S{constructor(e){super(`COMPOSITE_ID_MISSING_BODY_ERROR`,`CompositeIdMissingBodyError`,e??`Invalid compositeId, missing body`)}},T=class extends S{constructor(e){super(`COMPOSITE_ID_UNKNOWN_IDENTIFIER_ERROR`,`CompositeIdUnknownIdentifierError`,e??`Invalid compositeId, unknown identifier`)}},E=class extends S{constructor(e){super(`COMPOSITE_ID_UNSUPPORTED_VERSION_ERROR`,`CompositeIdUnsupportedVersionError`,e??`Invalid compositeId, unsupported version`)}};const D=e=>!(0,c.isMissing)(e)&&`value`in e&&e.value!==void 0,O=e=>!(0,c.isMissing)(e)&&`identifiers`in e&&e.identifiers!==void 0,k=(e,t={version:b})=>{if(t.version===1)return F(j(e,t.aliases));throw new E(`Cannot generate ID, unsupported version number: ${t.version}`)},A=(e,t={version:b})=>{let n=P(e,t),r={};return n&&n.split(y).forEach(e=>{let[n,i]=e.split(v),a=N(n,t.aliases??{});r[a]=ee(i)}),r},j=(e,t={})=>{if(D(e))return M({identifier:e,compositeIdAliases:t,isSoleIdentifier:!0});if(O(e))return e.identifiers.map(e=>M({identifier:e,compositeIdAliases:t,isSoleIdentifier:!1})).join(_);throw new T},M=({identifier:e,compositeIdAliases:t,isSoleIdentifier:n})=>{let r=n?`id`:t[e.key]||e.key;return[r,L(e.value)].filter(Boolean).join(g)},N=(e,t)=>Object.keys(t).find(n=>t[n]===e)??e,P=(e,t)=>{if(t.version===1)return I(e);throw new E(`Cannot decode ID, unsupported version number: ${t.version}`)},F=e=>`${h}${(0,c.encodeToBase64)(e)}`,I=e=>{if(!e.startsWith(h))throw new C(`Trying to decode an ID without the header: ${e}`);let t=e.split(h)[1];if(!t)throw new w(`Trying to decode an ID without a body: ${e}`);return(0,c.decodeFromBase64)(t)},L=e=>[_,g].reduce((e,t)=>e.replace(t,`\\`+t),e),ee=e=>[_,g].reduce((e,t)=>{let n=`\\`+t;return e.replace(RegExp(`\\\\`+n,`g`),t)},e),te=e=>(0,c.isMissing)(e)?!1:e.startsWith(h),ne=[`preview`,`beta`,`ga`,`deprecated`],re=(0,c.zStrictObject)({r:c.z.record(c.z.string(),(0,c.zStrictObject)({n:c.z.number().optional().nullable(),c:c.z.string().optional().nullable(),p:c.z.number().optional().nullable()})),v:c.z.number(),t:c.z.number()}),ie=(0,c.zStrictObject)({remote:c.z.record(c.z.string(),(0,c.zStrictObject)({pageNumber:c.z.number().optional(),providerPageCursor:c.z.string().optional(),position:c.z.number().optional()})),version:c.z.number(),timestamp:c.z.number()}),ae=e=>(0,c.encodeToBase64)(JSON.stringify(oe(e))),oe=e=>{let{remote:t,version:n,timestamp:r}=e,i=Object.fromEntries(Object.entries(t).map(([e,{pageNumber:t,providerPageCursor:n,position:r}])=>[e,{n:t,c:n,p:r}])),a={r:i,v:n,t:r};return a},R=e=>{try{if((0,c.isString)(e)){let t=(0,c.decodeFromBase64)(e),n=JSON.parse(t),r=re.parse(n);return se(r)}else return ie.parse(e),e}catch{return null}},se=e=>{let{r:t,v:n,t:r}=e,i=Object.fromEntries(Object.entries(t).map(([e,{n:t,c:n,p:r}])=>[e,{pageNumber:t,providerPageCursor:n,position:r}])),a={remote:i,version:n,timestamp:r};return a},ce=(e,t)=>{let n=typeof e==`string`?R(e):e,r=typeof t==`string`?R(t):t;if(n===null||r===null)return n===r;let{timestamp:i,...a}=n,{timestamp:o,...s}=r;return(0,c.getContentHash)(a)===(0,c.getContentHash)(s)},le=({cursor:e,ignoreStepIndex:t})=>(0,c.isMissing)(e)?!0:Object.keys(e?.remote??{}).reduce((n,r)=>{let i=e?.remote?.[r];return((0,c.isMissing)(t)||r!==t.toString())&&(n=n&&(0,c.isMissing)(i.pageNumber)&&(0,c.isMissing)(i.position)&&(0,c.isMissing)(i.providerPageCursor)),n},!0),ue=({cursor:e,stepIndex:t,pageNumber:n,providerPageCursor:r,position:i})=>{let a={pageNumber:n??void 0,providerPageCursor:r??void 0,position:i??void 0},o=(0,c.isMissing)(n)&&(0,c.isMissing)(r)&&(0,c.isMissing)(i);return(0,c.isMissing)(e)?{remote:o?{}:{[t]:a},version:2,timestamp:Date.now()}:o?(delete e.remote[t],e):{...e,remote:{...e.remote,[t]:a}}},de=e=>e instanceof x,z=c.z.object({stepsDataToGroup:c.z.array(c.z.string()),isSingleRecord:c.z.boolean().optional()}),fe=c.z.object({data:c.z.unknown()}),pe=async({block:e,params:t})=>{let{stepsDataToGroup:n,isSingleRecord:r}=z.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=>{let r=(0,c.notMissing)(t[e])?t[e]:{};t[e]={...r,[n]:{...i[e]}}}),t):t},{});return{block:{...e},successful:!0,output:{data:r?i:Object.values(i)}}},me=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;if(Array.isArray(e.result)){let a=e.result.length;i=e.result.map((e,i)=>{let o=he(r,a,i),s=B(e,t,o);return n.push(...s.errors||[]),s.record})}else{let a=B(e.result,t,r);i=a.record,n.push(...a.errors||[])}return{block:{...e,result:i},successful:!0,errors:Object.keys(n).length>0?n:void 0}},he=(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},{}),B=(e,t,n)=>{if(!e||!n)return{record:e};let r={unified:{...e},...typeof n==`object`?n:{}},i={},a=[],o={...e};for(let n of t){let{error:t,value:s}=ge(r,e.id,n);if(t){a.push(t);continue}n.custom?i[n.targetFieldKey]=s:o[n.targetFieldKey]=s}return{record:{...o,unified_custom_fields:Object.keys(i).length>0?i:void 0},errors:a.length>0?a:void 0}},ge=(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,l.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}},_e=e=>{switch(e){case`country_alpha2code_by_alpha2code`:return c.getCountryAlpha2CodeByAlpha2Code;case`country_alpha3code_by_alpha3code`:return c.getCountryAlpha3CodeByAlpha3Code;case`country_code_by_country_code`:return c.getCountryCodeByCountryCode;case`country_name_by_country_name`:return c.getCountryNameByCountryName;case`country_name_by_alpha3code`:return c.getCountryNameByAlpha3Code;case`country_name_by_alpha2code`:return c.getCountryNameByAlpha2Code;case`country_name_by_country_code`:return c.getCountryNameByCountryCode;case`country_alpha3code_by_alpha2code`:return c.getCountryAlpha3CodeByAlpha2Code;case`country_alpha3code_by_country_name`:return c.getCountryAlpha3CodeByCountryName;case`country_alpha3code_by_country_code`:return c.getCountryAlpha3CodeByCountryCode;case`country_alpha2code_by_alpha3code`:return c.getCountryAlpha2CodeByAlpha3Code;case`country_alpha2code_by_country_name`:return c.getCountryAlpha2CodeByCountryName;case`country_alpha2code_by_country_code`:return c.getCountryAlpha2CodeByCountryCode;case`country_code_by_alpha2code`:return c.getCountryCodeByAlpha2Code;case`country_code_by_alpha3code`:return c.getCountryCodeByAlpha3Code;case`country_code_by_country_name`:return c.getCountryCodeByCountryName;case`country_subdivisions_by_alpha2code`:return c.getCountrySubDivisionsByAlpha2Code;case`country_subdivision_code_by_subdivision_name`:return c.getCountrySubDivisionCodeBySubDivisionName;case`country_alpha2code_by_citizenship`:return c.getCountryAlpha2CodeByCitizenship;case`country_subdivision_name_by_subdivision_code`:return c.getCountrySubDivisionNameBySubDivisionCode;case`document_file_format_from_extension`:return c.getDocumentFileFormatFromExtension;default:return}},V=(0,c.zStrictObject)({targetFieldKey:c.z.string(),alias:c.z.string().optional(),expression:c.z.string().optional(),values:c.z.unknown().optional(),type:c.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:c.z.boolean().default(!1),custom:c.z.boolean().default(!1),hidden:c.z.boolean().default(!1),enumMapper:(0,c.zStrictObject)({matcher:c.z.string().or((0,c.zStrictObject)({matchExpression:c.z.string(),value:c.z.string()}).array())}).optional(),properties:c.z.lazy(()=>V).array().optional()}),H=c.z.object({fields:V.array(),dataSource:c.z.string(),externalSources:c.z.record(c.z.string(),c.z.string()).optional()}),ve=c.z.object({data:c.z.unknown()}),ye=async({block:e,params:t})=>{let n=[],{fields:r,dataSource:i,externalSources:a}=H.parse(t),o=(0,l.evaluate)(i,e);if(!r||!i||e?.debug?.custom_mappings===`disabled`||!o)return{block:e,successful:!0};let s=Object.keys(a??{})?.reduce((t,n)=>(t[n]=(0,l.evaluate)(a?.[n],e),t),{}),c;if(Array.isArray(o))c=o.map(e=>{let t=U(r,{...e,external:s});return n.push(...t?.errors||[]),t?.record});else{let e=U(r,{...o,external:s});c=e?.record,n.push(...e?.errors||[])}return{block:{...e},successful:!0,output:{data:c},errors:Object.keys(n).length>0?n:void 0}},be=(e,t,n)=>{if(Array.isArray(e.values))return e.values.map(r=>{let i=W(r,t),a=U(e.properties,i);return(0,c.notMissing)(a?.errors)&&n.push(...a.errors),a?.record}).filter(Boolean)},xe=(e,t,n)=>{if(e.expression)try{let r=(0,l.evaluate)(e.expression,t);if(Array.isArray(r))return r.map(t=>{let r=U(e.properties,t);return(0,c.notMissing)(r?.errors)&&n.push(...r.errors),r?.record}).filter(Boolean);{let t=U(e.properties,r);return(0,c.notMissing)(t?.errors)&&n.push(...t.errors),t?.record}}catch{n.push({message:`Invalid expression`,id:t?.id,targetField:e.targetFieldKey});return}},Se=(e,t,n)=>{let r=(0,c.notMissing)(e.values)?e.values:t,i=U(e.properties,r);return(0,c.notMissing)(i?.errors)&&n.push(...i.errors),i?.record},Ce=(e,t,n)=>{if(!(0,c.isMissing)(e.properties))return e.array&&Array.isArray(e.values)?be(e,t,n):e.array&&e.expression?xe(e,t,n):Se(e,t,n)},U=(e,t)=>{if(!t)return;let n={},r=[],i={};for(let a of e){let e;if(a.type===`object`){if(e=Ce(a,t,r),e===void 0)continue}else{let{error:n,value:i}=we(t,t?.id,a);if(e=i,n){r.push(n);continue}}a.custom?n[a.targetFieldKey]=e:i[a.targetFieldKey]=e}let a=Object.keys(n).length>0?{unified_custom_fields:n}:{};return{record:{...i,...a},errors:r.length>0?r:void 0}},W=(e,t)=>{if(e==null)return e;if(typeof e==`string`){if((0,l.isValidExpression)(e))try{return(0,l.evaluate)(e,t)}catch{return e}return e}if(Array.isArray(e))return e.map(e=>W(e,t));if(typeof e==`object`){let n={...e};for(let[e,r]of Object.entries(n))n[e]=W(r,t);return n}return e},we=(e,t,n)=>{switch(n.type){case`string`:case`number`:case`boolean`:case`datetime_string`:return G(n,t,e);case`enum`:return Te(n,t,e);default:return{error:{message:`Invalid type`,id:t,targetField:n.targetFieldKey}}}},G=(e,t,n)=>{if(!e.expression)return{error:{message:`Expression is empty`,id:t,targetField:e.targetFieldKey}};let r;try{r=(0,l.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}},Te=(e,t,n)=>{let r=G(e,t,n),i=(0,c.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,c.isString)(a)){let n=_e(a);if((0,c.notMissing)(n)){let e=(0,c.notMissing)(i)?n(i):null;return{value:{value:e??`unmapped_value`,source_value:i}}}else return{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,a=(0,l.evaluate)(t,n);if(a===!0)return{value:{value:r,source_value:i}}}return{value:{value:`unmapped_value`,source_value:i}}},Ee=[`data`,`headers`],De=(0,c.zStrictObject)({type:c.z.literal(`none`)}),Oe=(0,c.zStrictObject)({type:c.z.literal(`basic`),username:c.z.string().optional(),password:c.z.string().optional(),encoding:c.z.string().optional()}),ke=(0,c.zStrictObject)({type:c.z.literal(`bearer`),token:c.z.string(),includeBearer:c.z.boolean().optional().default(!0)}),Ae=(0,c.zStrictObject)({type:c.z.literal(`oauth2`),authorizationUrl:c.z.string().optional(),authorizationParams:c.z.record(c.z.string(),c.z.string()).optional(),tokenUrl:c.z.string().optional(),tokenParams:c.z.record(c.z.string(),c.z.string()).optional(),tokenExpiresIn:c.z.number().optional(),tokenRefreshExpiresIn:c.z.number().optional(),token:c.z.string(),includeBearer:c.z.boolean().optional().default(!0),scopes:c.z.string().optional(),scopeDelimiter:c.z.string().optional(),customHeaders:c.z.record(c.z.string(),c.z.string()).optional(),pkce:c.z.boolean().optional()}),je=c.z.discriminatedUnion(`type`,[De,Oe,ke,Ae]),K=c.z.object({baseUrl:c.z.string(),url:c.z.string(),method:c.z.enum(u.HttpMethods),response:(0,c.zStrictObject)({indexField:c.z.string().optional(),dataKey:c.z.string().optional(),nextKey:c.z.string().optional(),nextKeyIn:c.z.enum(Ee).optional()}).optional(),iterator:(0,c.zStrictObject)({key:c.z.string(),in:c.z.enum(u.RequestParameterLocations)}),cursor:(0,c.zStrictObject)({token:c.z.string().optional().nullable(),position:c.z.number().optional().nullable()}).optional(),customErrors:u.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),args:(0,c.zStrictObject)({name:c.z.string(),value:c.z.unknown(),in:c.z.enum(u.RequestParameterLocations),condition:c.z.string().optional()}).array().optional()}),Me=(0,c.zStrictObject)({data:c.z.unknown().optional(),raw:c.z.unknown().optional(),statusCode:c.z.number(),message:c.z.string().optional(),next:c.z.string().optional().nullable(),position:c.z.number().optional()}).optional(),Ne=25,Pe=async({block:e,params:t})=>{let n=u.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)?Ne:i,o=r?r.filter(t=>!t.condition||(0,l.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,s=t?(0,l.safeEvaluateRecord)({...t,args:o},e):{},d={...s,customErrors:t?.customErrors},{baseUrl:f,url:p,method:m,response:h,iterator:g,cursor:_,customErrors:v,args:y}=K.parse(d),b=s?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,x=je.parse(b),S=y?(0,u.parseRequestParameters)(y):{query:{},body:{},headers:{}},C=(0,u.createAuthorizationHeaders)(x),w={...S?.headers??{},...C},T=e.connector?.rateLimit,E=e.connector?.concurrency,D=T!==void 0||E!==void 0?{rateLimit:T,concurrency:E}:void 0,O=_?.token??null,k=null,A=null,j=[],M=[],N=[],P=a,F=_?.position??0,I=!0,L=!0;do{I?I=!1:F=0,O!==null&&(g.in===`query`?S.query[g.key]=O.toString():g.in===`body`&&(S.body[g.key]=O));let t;try{t=await n.performRequest({httpClient:e.httpClient,url:`${f}${p}`,queryParams:S?.query,method:m,headers:w,body:S?.body,customErrorConfigs:v,requestConfig:D})}catch(t){let n=t;return{block:e,successful:!1,errors:[(0,u.serializeHttpResponseError)(t)],output:{statusCode:n?.response?.status??500,message:n?.response?.message}}}k=O,M=h?.dataKey?t.data[h?.dataKey]:t.data;let r=M?.slice(F,F+P);P-=r.length,F+=r.length,N.push(t),j=j.concat(r),A=t?.status,O=Fe({result:t,response:h}),r.length===M.length&&P===0&&(F=0,k=O),L=(0,c.isMissing)(O)&&j.length<a}while((0,c.notMissing)(O)&&j.length<a&&M?.length>0);let ee=Re(j,h);return{block:e,successful:!0,output:{data:ee,raw:N,statusCode:A,next:L?void 0:k,position:L?void 0:F}}},Fe=({result:e,response:t})=>{if((0,c.isMissing)(t?.nextKey))return null;let n=t?.nextKeyIn??`data`,r=t?.nextKey;return n===`headers`?Ie(e.headers,r):Le(e.data,r)},Ie=(e,t)=>{if((0,c.isMissing)(e)||typeof e!=`object`)return 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},Le=(e,t)=>{if((0,c.isMissing)(e)||typeof e!=`object`||!e)return null;let n=e[t];return(0,c.isMissing)(n)?null:typeof n==`string`||typeof n==`number`?n:null},Re=(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},ze=(0,c.zStrictObject)({type:c.z.literal(`none`)}),Be=(0,c.zStrictObject)({type:c.z.literal(`basic`),username:c.z.string().optional(),password:c.z.string().optional(),encoding:c.z.string().optional()}),Ve=(0,c.zStrictObject)({type:c.z.literal(`bearer`),token:c.z.string(),includeBearer:c.z.boolean().optional().default(!0)}),He=(0,c.zStrictObject)({type:c.z.literal(`oauth2`),authorizationUrl:c.z.string().optional(),authorizationParams:c.z.record(c.z.string(),c.z.string()).optional(),tokenUrl:c.z.string().optional(),tokenParams:c.z.record(c.z.string(),c.z.string()).optional(),tokenExpiresIn:c.z.number().optional(),tokenRefreshExpiresIn:c.z.number().optional(),token:c.z.string(),includeBearer:c.z.boolean().optional().default(!0),scopes:c.z.string().optional(),scopeDelimiter:c.z.string().optional(),customHeaders:c.z.record(c.z.string(),c.z.string()).optional(),pkce:c.z.boolean().optional()}),q=c.z.discriminatedUnion(`type`,[ze,Be,Ve,He]),Ue=c.z.object({baseUrl:c.z.string().optional(),url:c.z.string(),method:c.z.enum(u.HttpMethods),authorization:q.optional(),response:(0,c.zStrictObject)({collection:c.z.boolean().optional(),indexField:c.z.string().optional(),dataKey:c.z.string().optional()}).optional(),customErrors:u.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),args:(0,c.zStrictObject)({name:c.z.string(),value:c.z.unknown(),in:c.z.enum(u.RequestParameterLocations),condition:c.z.string().optional()}).array().optional()}),We=(0,c.zStrictObject)({data:c.z.unknown().optional(),raw:c.z.unknown().optional(),statusCode:c.z.number(),message:c.z.string().optional()}).optional(),Ge=async({block:e,params:t})=>{let n=u.RequestClientFactory.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||(0,l.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?(0,l.safeEvaluateRecord)({...t,args:i},e):{},o={...a,customErrors:t?.customErrors},{baseUrl:s,url:d,method:f,response:p,authorization:m,customErrors:h,args:g}=Ue.parse(o),_=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,v=g?(0,u.parseRequestParameters)(g):{query:{},body:{},headers:{}},y=(0,c.notMissing)(m)?m:q.parse(_),b=(0,u.createAuthorizationHeaders)(y),x={...v?.headers??{},...b},S=e.connector?.rateLimit,C=e.connector?.concurrency,w=S!==void 0||C!==void 0?{rateLimit:S,concurrency:C}:void 0,T;try{T=await n.performRequest({httpClient:e.httpClient,url:`${s}${d}`,queryParams:v?.query,method:f,headers:x,body:v?.body,customErrorConfigs:h,requestConfig:w})}catch(t){let n=t;return{block:e,successful:!1,errors:[(0,u.serializeHttpResponseError)(t)],output:{statusCode:n?.response?.status??500,message:n?.response?.message}}}let E=p?.dataKey?T.data[p?.dataKey]:T.data,D=Ke(E,p);return{block:e,successful:!0,output:{data:D,raw:T,statusCode:T?.status,message:T?.message}}},Ke=(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},qe=c.z.object({values:c.z.string().or(c.z.record(c.z.string(),c.z.unknown())).or(c.z.array(c.z.unknown()))}),Je=c.z.object({data:c.z.unknown()}),Ye=async({block:e,params:t})=>{let{values:n}=qe.parse(t),r=Array.isArray(n)?n.map(t=>J(t,e)):J(n,e);return{block:{...e},successful:!0,output:{data:r}}},J=(e,t)=>(0,c.isString)(e)?(0,l.safeEvaluate)(e,t):(0,c.isObject)(e)?(0,l.safeEvaluateRecord)(e,t):e,Xe=c.z.object({targetFieldKey:c.z.string(),type:c.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:c.z.boolean().default(!1),custom:c.z.boolean().default(!1),hidden:c.z.boolean().default(!1),properties:c.z.lazy(()=>Xe).array().optional()}),Ze=c.z.object({fields:Xe.array().optional(),dataSource:c.z.string()}),Qe=c.z.object({data:c.z.unknown()});let Y=function(e){return e.String=`string`,e.Number=`number`,e.Boolean=`boolean`,e.DateTimeString=`datetime_string`,e}({});const X=({value:e,type:t,format:n})=>{if((0,c.isMissing)(e))return null;switch(t){case Y.String:return(0,c.safeParseToString)({value:e});case Y.Number:return(0,c.safeParseToNumber)({value:e});case Y.Boolean:return(0,c.safeParseToBoolean)({value:e});case Y.DateTimeString:return(0,c.safeParseToDateTimeString)({value:e,format:n});default:return e}},$e=e=>{let t=Object.values(Y);return t.includes(e)},et=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}},tt=(e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i}=t;$e(i)&&(!t.custom&&(0,c.notMissing)(n[r])?n[r]=X({value:e[r],type:i}):n.unified_custom_fields&&(0,c.notMissing)(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=X({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},nt=async({block:e,params:t})=>{let{fields:n,dataSource:r}=Ze.parse(t),i=(0,l.evaluate)(r,e);if(!n||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let a;return a=Array.isArray(i)?i.map(e=>Z(e,n)):Z(i,n),{block:{...e},successful:!0,output:{data:a}}},rt=(e,t)=>!e.properties||!t?t:Array.isArray(t)?t.map(t=>typeof t==`object`&&t?Z(t,e.properties):t):typeof t==`object`&&t?Z(t,e.properties):t,Z=(e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i,array:a}=t;i===`object`?!t.custom&&(0,c.notMissing)(n[r])?n[r]=rt(t,e[r]):n.unified_custom_fields&&(0,c.notMissing)(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=rt(t,e.unified_custom_fields?.[r])):$e(i)&&(!t.custom&&(0,c.notMissing)(n[r])?(!a||!Array.isArray(n[r]))&&(n[r]=X({value:e[r],type:i})):n.unified_custom_fields&&(0,c.notMissing)(n.unified_custom_fields?.[r])&&(!a||!Array.isArray(n.unified_custom_fields[r]))&&(n.unified_custom_fields[r]=X({value:e.unified_custom_fields?.[r],type:i})))}),{...n}};let Q=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.STATIC_VALUES=`static_values`,e}({});const $={[Q.TYPECAST]:{v1:{fn:et},v2:{fn:nt,inputSchema:Ze,outputSchema:Qe}},[Q.MAP_FIELDS]:{v1:{fn:me},v2:{fn:ye,inputSchema:H,outputSchema:ve}},[Q.REQUEST]:{v1:{fn:Ge,inputSchema:Ue,outputSchema:We}},[Q.GROUP_DATA]:{v1:{fn:pe,inputSchema:z,outputSchema:fe}},[Q.PAGINATED_REQUEST]:{v1:{fn:Pe,inputSchema:K,outputSchema:Me}},[Q.STATIC_VALUES]:{v1:{fn:Ye,inputSchema:qe,outputSchema:Je}}},it=(e,t)=>async({block:n,params:r})=>{try{e.inputSchema&&e.inputSchema.parse(r)}catch(e){return{block:n,successful:!1,errors:[{message:`Input parameters for ${t} are invalid: ${e?.message}`}]}}let i=await e.fn({block:n,params:r});try{e.outputSchema&&e.outputSchema.parse(i.output)}catch{return{block:n,successful:!1,errors:[{message:`Output data of ${t} has unexpected format`}]}}return i},at={build({functionName:e,version:t=`1`,validateSchemas:n=!1,stepFunctionsList:r=$}){let i=r?.[e]?.[`v${t}`];if(!i)throw Error(`Unknown step function: ${e} v${t}`);return n?{...i,fn:it(i,e)}:i}};exports.AUTHENTICATION_SCHEMA=q,exports.COMPOSITE_ID_LATEST_VERSION=b,exports.CoreError=x,exports.ReleaseStages=ne,exports.StepFunctionName=Q,exports.StepFunctionsFactory=at,exports.StepFunctionsRegistry=$,exports.areCursorsEqual=ce,exports.decodeCompositeId=A,exports.encodeCompositeId=k,exports.expandCursor=R,exports.getCategoryDetails=f,exports.isCompositeId=te,exports.isCoreError=de,exports.isCursorEmpty=le,exports.isValidCategory=p,exports.minifyCursor=ae,exports.updateCursor=ue;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{decodeFromBase64 as e,encodeToBase64 as t,getContentHash as n,getCountryAlpha2CodeByAlpha2Code as r,getCountryAlpha2CodeByAlpha3Code as i,getCountryAlpha2CodeByCitizenship as a,getCountryAlpha2CodeByCountryCode as o,getCountryAlpha2CodeByCountryName as s,getCountryAlpha3CodeByAlpha2Code as c,getCountryAlpha3CodeByAlpha3Code as l,getCountryAlpha3CodeByCountryCode as u,getCountryAlpha3CodeByCountryName as d,getCountryCodeByAlpha2Code as f,getCountryCodeByAlpha3Code as p,getCountryCodeByCountryCode as m,getCountryCodeByCountryName as h,getCountryNameByAlpha2Code as g,getCountryNameByAlpha3Code as _,getCountryNameByCountryCode as v,getCountryNameByCountryName as y,getCountrySubDivisionCodeBySubDivisionName as b,getCountrySubDivisionNameBySubDivisionCode as x,getCountrySubDivisionsByAlpha2Code as S,getDocumentFileFormatFromExtension as C,isMissing as w,isObject as ee,isString as T,notMissing as E,safeParseToBoolean as D,safeParseToDateTimeString as O,safeParseToNumber as k,safeParseToString as A,z as j,zStrictObject as M}from"@stackone/utils";import{evaluate as N,isValidExpression as P,safeEvaluate as F,safeEvaluateRecord as I}from"@stackone/expressions";import{CUSTOM_ERROR_CONFIG_SCHEMA as L,HttpMethods as R,RequestClientFactory as te,RequestParameterLocations as z,createAuthorizationHeaders as ne,parseRequestParameters as re,serializeHttpResponseError as ie}from"@stackone/transport";const ae={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`},internal:{title:`Internal`,key:`internal`,description:`Category for internal operations`},action:{title:`Action`,key:`action`,description:`Action`}},oe=e=>{let t=ae[e.toLowerCase()];return t??null},se=e=>!!ae[e.toLowerCase()],ce=`so1!`,B=t(ce),V=`:`,H=`,`,le=RegExp(`(?<!\\\\)${V}`,`g`),ue=RegExp(`(?<!\\\\)${H}`,`g`),U=1;var W=class e extends Error{type;category;context;constructor({category:t,name:n,type:r,context:i,message:a}){super(a),this.name=n??`CoreError`,this.type=r,this.category=t,this.context=i,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.category}-${this.name} [${this.type}]${e}`}},G=class extends W{constructor(e,t,n){super({category:`CompositeId`,name:t??`BaseCompositeIdError`,type:e,message:n})}},de=class extends G{constructor(e){super(`COMPOSITE_ID_MISSING_HEADER_ERROR`,`CompositeIdMissingHeaderError`,e??`Invalid compositeId, missing header`)}},fe=class extends G{constructor(e){super(`COMPOSITE_ID_MISSING_BODY_ERROR`,`CompositeIdMissingBodyError`,e??`Invalid compositeId, missing body`)}},pe=class extends G{constructor(e){super(`COMPOSITE_ID_UNKNOWN_IDENTIFIER_ERROR`,`CompositeIdUnknownIdentifierError`,e??`Invalid compositeId, unknown identifier`)}},me=class extends G{constructor(e){super(`COMPOSITE_ID_UNSUPPORTED_VERSION_ERROR`,`CompositeIdUnsupportedVersionError`,e??`Invalid compositeId, unsupported version`)}};const he=e=>!w(e)&&`value`in e&&e.value!==void 0,ge=e=>!w(e)&&`identifiers`in e&&e.identifiers!==void 0,_e=(e,t={version:U})=>{if(t.version===1)return Ce(ye(e,t.aliases));throw new me(`Cannot generate ID, unsupported version number: ${t.version}`)},ve=(e,t={version:U})=>{let n=Se(e,t),r={};return n&&n.split(ue).forEach(e=>{let[n,i]=e.split(le),a=xe(n,t.aliases??{});r[a]=Ee(i)}),r},ye=(e,t={})=>{if(he(e))return be({identifier:e,compositeIdAliases:t,isSoleIdentifier:!0});if(ge(e))return e.identifiers.map(e=>be({identifier:e,compositeIdAliases:t,isSoleIdentifier:!1})).join(H);throw new pe},be=({identifier:e,compositeIdAliases:t,isSoleIdentifier:n})=>{let r=n?`id`:t[e.key]||e.key;return[r,Te(e.value)].filter(Boolean).join(V)},xe=(e,t)=>Object.keys(t).find(n=>t[n]===e)??e,Se=(e,t)=>{if(t.version===1)return we(e);throw new me(`Cannot decode ID, unsupported version number: ${t.version}`)},Ce=e=>`${B}${t(e)}`,we=t=>{if(!t.startsWith(B))throw new de(`Trying to decode an ID without the header: ${t}`);let n=t.split(B)[1];if(!n)throw new fe(`Trying to decode an ID without a body: ${t}`);return e(n)},Te=e=>[H,V].reduce((e,t)=>e.replace(t,`\\`+t),e),Ee=e=>[H,V].reduce((e,t)=>{let n=`\\`+t;return e.replace(RegExp(`\\\\`+n,`g`),t)},e),De=e=>w(e)?!1:e.startsWith(B),Oe=[`preview`,`beta`,`ga`,`deprecated`],ke=M({r:j.record(j.string(),M({n:j.number().optional().nullable(),c:j.string().optional().nullable(),p:j.number().optional().nullable()})),v:j.number(),t:j.number()}),Ae=M({remote:j.record(j.string(),M({pageNumber:j.number().optional(),providerPageCursor:j.string().optional(),position:j.number().optional()})),version:j.number(),timestamp:j.number()}),je=e=>t(JSON.stringify(Me(e))),Me=e=>{let{remote:t,version:n,timestamp:r}=e,i=Object.fromEntries(Object.entries(t).map(([e,{pageNumber:t,providerPageCursor:n,position:r}])=>[e,{n:t,c:n,p:r}])),a={r:i,v:n,t:r};return a},K=t=>{try{if(T(t)){let n=e(t),r=JSON.parse(n),i=ke.parse(r);return Ne(i)}else return Ae.parse(t),t}catch{return null}},Ne=e=>{let{r:t,v:n,t:r}=e,i=Object.fromEntries(Object.entries(t).map(([e,{n:t,c:n,p:r}])=>[e,{pageNumber:t,providerPageCursor:n,position:r}])),a={remote:i,version:n,timestamp:r};return a},Pe=(e,t)=>{let r=typeof e==`string`?K(e):e,i=typeof t==`string`?K(t):t;if(r===null||i===null)return r===i;let{timestamp:a,...o}=r,{timestamp:s,...c}=i;return n(o)===n(c)},Fe=({cursor:e,ignoreStepIndex:t})=>w(e)?!0:Object.keys(e?.remote??{}).reduce((n,r)=>{let i=e?.remote?.[r];return(w(t)||r!==t.toString())&&(n=n&&w(i.pageNumber)&&w(i.position)&&w(i.providerPageCursor)),n},!0),Ie=({cursor:e,stepIndex:t,pageNumber:n,providerPageCursor:r,position:i})=>{let a={pageNumber:n??void 0,providerPageCursor:r??void 0,position:i??void 0},o=w(n)&&w(r)&&w(i);return w(e)?{remote:o?{}:{[t]:a},version:2,timestamp:Date.now()}:o?(delete e.remote[t],e):{...e,remote:{...e.remote,[t]:a}}},Le=e=>e instanceof W,Re=j.object({stepsDataToGroup:j.array(j.string()),isSingleRecord:j.boolean().optional()}),ze=j.object({data:j.unknown()}),Be=async({block:e,params:t})=>{let{stepsDataToGroup:n,isSingleRecord:r}=Re.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=>{let r=E(t[e])?t[e]:{};t[e]={...r,[n]:{...i[e]}}}),t):t},{});return{block:{...e},successful:!0,output:{data:r?i:Object.values(i)}}},Ve=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;if(Array.isArray(e.result)){let a=e.result.length;i=e.result.map((e,i)=>{let o=He(r,a,i),s=Ue(e,t,o);return n.push(...s.errors||[]),s.record})}else{let a=Ue(e.result,t,r);i=a.record,n.push(...a.errors||[])}return{block:{...e,result:i},successful:!0,errors:Object.keys(n).length>0?n:void 0}},He=(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},{}),Ue=(e,t,n)=>{if(!e||!n)return{record:e};let r={unified:{...e},...typeof n==`object`?n:{}},i={},a=[],o={...e};for(let n of t){let{error:t,value:s}=We(r,e.id,n);if(t){a.push(t);continue}n.custom?i[n.targetFieldKey]=s:o[n.targetFieldKey]=s}return{record:{...o,unified_custom_fields:Object.keys(i).length>0?i:void 0},errors:a.length>0?a:void 0}},We=(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=N(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}},Ge=e=>{switch(e){case`country_alpha2code_by_alpha2code`:return r;case`country_alpha3code_by_alpha3code`:return l;case`country_code_by_country_code`:return m;case`country_name_by_country_name`:return y;case`country_name_by_alpha3code`:return _;case`country_name_by_alpha2code`:return g;case`country_name_by_country_code`:return v;case`country_alpha3code_by_alpha2code`:return c;case`country_alpha3code_by_country_name`:return d;case`country_alpha3code_by_country_code`:return u;case`country_alpha2code_by_alpha3code`:return i;case`country_alpha2code_by_country_name`:return s;case`country_alpha2code_by_country_code`:return o;case`country_code_by_alpha2code`:return f;case`country_code_by_alpha3code`:return p;case`country_code_by_country_name`:return h;case`country_subdivisions_by_alpha2code`:return S;case`country_subdivision_code_by_subdivision_name`:return b;case`country_alpha2code_by_citizenship`:return a;case`country_subdivision_name_by_subdivision_code`:return x;case`document_file_format_from_extension`:return C;default:return}},Ke=M({targetFieldKey:j.string(),alias:j.string().optional(),expression:j.string().optional(),values:j.unknown().optional(),type:j.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:j.boolean().default(!1),custom:j.boolean().default(!1),hidden:j.boolean().default(!1),enumMapper:M({matcher:j.string().or(M({matchExpression:j.string(),value:j.string()}).array())}).optional(),properties:j.lazy(()=>Ke).array().optional()}),qe=j.object({fields:Ke.array(),dataSource:j.string(),externalSources:j.record(j.string(),j.string()).optional()}),Je=j.object({data:j.unknown()}),Ye=async({block:e,params:t})=>{let n=[],{fields:r,dataSource:i,externalSources:a}=qe.parse(t),o=N(i,e);if(!r||!i||e?.debug?.custom_mappings===`disabled`||!o)return{block:e,successful:!0};let s=Object.keys(a??{})?.reduce((t,n)=>(t[n]=N(a?.[n],e),t),{}),c;if(Array.isArray(o))c=o.map(e=>{let t=q(r,{...e,external:s});return n.push(...t?.errors||[]),t?.record});else{let e=q(r,{...o,external:s});c=e?.record,n.push(...e?.errors||[])}return{block:{...e},successful:!0,output:{data:c},errors:Object.keys(n).length>0?n:void 0}},Xe=(e,t,n)=>{if(Array.isArray(e.values))return e.values.map(r=>{let i=J(r,t),a=q(e.properties,i);return E(a?.errors)&&n.push(...a.errors),a?.record}).filter(Boolean)},Ze=(e,t,n)=>{if(e.expression)try{let r=N(e.expression,t);if(Array.isArray(r))return r.map(t=>{let r=q(e.properties,t);return E(r?.errors)&&n.push(...r.errors),r?.record}).filter(Boolean);{let t=q(e.properties,r);return E(t?.errors)&&n.push(...t.errors),t?.record}}catch{n.push({message:`Invalid expression`,id:t?.id,targetField:e.targetFieldKey});return}},Qe=(e,t,n)=>{let r=E(e.values)?e.values:t,i=q(e.properties,r);return E(i?.errors)&&n.push(...i.errors),i?.record},$e=(e,t,n)=>{if(!w(e.properties))return e.array&&Array.isArray(e.values)?Xe(e,t,n):e.array&&e.expression?Ze(e,t,n):Qe(e,t,n)},q=(e,t)=>{if(!t)return;let n={},r=[],i={};for(let a of e){let e;if(a.type===`object`){if(e=$e(a,t,r),e===void 0)continue}else{let{error:n,value:i}=et(t,t?.id,a);if(e=i,n){r.push(n);continue}}a.custom?n[a.targetFieldKey]=e:i[a.targetFieldKey]=e}let a=Object.keys(n).length>0?{unified_custom_fields:n}:{};return{record:{...i,...a},errors:r.length>0?r:void 0}},J=(e,t)=>{if(e==null)return e;if(typeof e==`string`){if(P(e))try{return N(e,t)}catch{return e}return e}if(Array.isArray(e))return e.map(e=>J(e,t));if(typeof e==`object`){let n={...e};for(let[e,r]of Object.entries(n))n[e]=J(r,t);return n}return e},et=(e,t,n)=>{switch(n.type){case`string`:case`number`:case`boolean`:case`datetime_string`:return tt(n,t,e);case`enum`:return nt(n,t,e);default:return{error:{message:`Invalid type`,id:t,targetField:n.targetFieldKey}}}},tt=(e,t,n)=>{if(!e.expression)return{error:{message:`Expression is empty`,id:t,targetField:e.targetFieldKey}};let r;try{r=N(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}},nt=(e,t,n)=>{let r=tt(e,t,n),i=E(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(T(a)){let n=Ge(a);if(E(n)){let e=E(i)?n(i):null;return{value:{value:e??`unmapped_value`,source_value:i}}}else return{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,a=N(t,n);if(a===!0)return{value:{value:r,source_value:i}}}return{value:{value:`unmapped_value`,source_value:i}}},rt=M({type:j.literal(`none`)}),it=M({type:j.literal(`basic`),username:j.string().optional(),password:j.string().optional(),encoding:j.string().optional()}),at=M({type:j.literal(`bearer`),token:j.string(),includeBearer:j.boolean().optional().default(!0)}),ot=M({type:j.literal(`oauth2`),authorizationUrl:j.string().optional(),authorizationParams:j.record(j.string(),j.string()).optional(),tokenUrl:j.string().optional(),tokenParams:j.record(j.string(),j.string()).optional(),tokenExpiresIn:j.number().optional(),tokenRefreshExpiresIn:j.number().optional(),token:j.string(),includeBearer:j.boolean().optional().default(!0),scopes:j.string().optional(),scopeDelimiter:j.string().optional(),customHeaders:j.record(j.string(),j.string()).optional(),pkce:j.boolean().optional()}),st=j.discriminatedUnion(`type`,[rt,it,at,ot]),ct=j.object({baseUrl:j.string(),url:j.string(),method:j.enum(R),response:M({indexField:j.string().optional(),dataKey:j.string().optional(),nextKey:j.string().optional()}).optional(),iterator:M({key:j.string(),in:j.enum(z)}),cursor:M({token:j.string().optional().nullable(),position:j.number().optional().nullable()}).optional(),customErrors:L.array().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(z),condition:j.string().optional()}).array().optional()}),lt=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional(),next:j.string().optional().nullable(),position:j.number().optional()}).optional(),ut=25,dt=async({block:e,params:t})=>{let n=te.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)?ut:i,o=r?r.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,s=t?I({...t,args:o},e):{},c={...s,customErrors:t?.customErrors},{baseUrl:l,url:u,method:d,response:f,iterator:p,cursor:m,customErrors:h,args:g}=ct.parse(c),_=s?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,v=st.parse(_),y=g?re(g):{query:{},body:{},headers:{}},b=ne(v),x={...y?.headers??{},...b},S=e.connector?.rateLimit,C=e.connector?.concurrency,ee=S!==void 0||C!==void 0?{rateLimit:S,concurrency:C}:void 0,T=m?.token??null,D=null,O=null,k=[],A=[],j=[],M=a,P=m?.position??0,F=!0,L=!0;do{F?F=!1:P=0,T!==null&&(p.in===`query`?y.query[p.key]=T.toString():p.in===`body`&&(y.body[p.key]=T));let t;try{t=await n.performRequest({httpClient:e.httpClient,url:`${l}${u}`,queryParams:y?.query,method:d,headers:x,body:y?.body,customErrorConfigs:h,requestConfig:ee})}catch(t){let n=t;return{block:e,successful:!1,errors:[ie(t)],output:{statusCode:n?.response?.status??500,message:n?.response?.message}}}D=T,A=f?.dataKey?t.data[f?.dataKey]:t.data;let r=A?.slice(P,P+M);M-=r.length,P+=r.length,j.push(t),k=k.concat(r),O=t?.status,T=f?.nextKey?t.data[f?.nextKey]:void 0,r.length===A.length&&M===0&&(P=0,D=T),L=w(T)&&k.length<a}while(E(T)&&k.length<a&&A?.length>0);let R=ft(k,f);return{block:e,successful:!0,output:{data:R,raw:j,statusCode:O,next:L?void 0:D,position:L?void 0:P}}},ft=(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},pt=M({type:j.literal(`none`)}),mt=M({type:j.literal(`basic`),username:j.string().optional(),password:j.string().optional(),encoding:j.string().optional()}),ht=M({type:j.literal(`bearer`),token:j.string(),includeBearer:j.boolean().optional().default(!0)}),gt=M({type:j.literal(`oauth2`),authorizationUrl:j.string().optional(),authorizationParams:j.record(j.string(),j.string()).optional(),tokenUrl:j.string().optional(),tokenParams:j.record(j.string(),j.string()).optional(),tokenExpiresIn:j.number().optional(),tokenRefreshExpiresIn:j.number().optional(),token:j.string(),includeBearer:j.boolean().optional().default(!0),scopes:j.string().optional(),scopeDelimiter:j.string().optional(),customHeaders:j.record(j.string(),j.string()).optional(),pkce:j.boolean().optional()}),Y=j.discriminatedUnion(`type`,[pt,mt,ht,gt]),_t=j.object({baseUrl:j.string().optional(),url:j.string(),method:j.enum(R),authorization:Y.optional(),response:M({collection:j.boolean().optional(),indexField:j.string().optional(),dataKey:j.string().optional()}).optional(),customErrors:L.array().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(z),condition:j.string().optional()}).array().optional()}),vt=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional()}).optional(),yt=async({block:e,params:t})=>{let n=te.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?I({...t,args:i},e):{},o={...a,customErrors:t?.customErrors},{baseUrl:s,url:c,method:l,response:u,authorization:d,customErrors:f,args:p}=_t.parse(o),m=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,h=p?re(p):{query:{},body:{},headers:{}},g=E(d)?d:Y.parse(m),_=ne(g),v={...h?.headers??{},..._},y=e.connector?.rateLimit,b=e.connector?.concurrency,x=y!==void 0||b!==void 0?{rateLimit:y,concurrency:b}:void 0,S;try{S=await n.performRequest({httpClient:e.httpClient,url:`${s}${c}`,queryParams:h?.query,method:l,headers:v,body:h?.body,customErrorConfigs:f,requestConfig:x})}catch(t){let n=t;return{block:e,successful:!1,errors:[ie(t)],output:{statusCode:n?.response?.status??500,message:n?.response?.message}}}let C=u?.dataKey?S.data[u?.dataKey]:S.data,w=bt(C,u);return{block:e,successful:!0,output:{data:w,raw:S,statusCode:S?.status,message:S?.message}}},bt=(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},xt=j.object({values:j.string().or(j.record(j.string(),j.unknown())).or(j.array(j.unknown()))}),St=j.object({data:j.unknown()}),Ct=async({block:e,params:t})=>{let{values:n}=xt.parse(t),r=Array.isArray(n)?n.map(t=>wt(t,e)):wt(n,e);return{block:{...e},successful:!0,output:{data:r}}},wt=(e,t)=>T(e)?F(e,t):ee(e)?I(e,t):e,Tt=j.object({targetFieldKey:j.string(),type:j.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:j.boolean().default(!1),custom:j.boolean().default(!1),hidden:j.boolean().default(!1),properties:j.lazy(()=>Tt).array().optional()}),Et=j.object({fields:Tt.array().optional(),dataSource:j.string()}),Dt=j.object({data:j.unknown()});let X=function(e){return e.String=`string`,e.Number=`number`,e.Boolean=`boolean`,e.DateTimeString=`datetime_string`,e}({});const Z=({value:e,type:t,format:n})=>{if(w(e))return null;switch(t){case X.String:return A({value:e});case X.Number:return k({value:e});case X.Boolean:return D({value:e});case X.DateTimeString:return O({value:e,format:n});default:return e}},Ot=e=>{let t=Object.values(X);return t.includes(e)},kt=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=>At(e,t)):At(e.result,t),{block:{...e,result:n},successful:!0}},At=(e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i}=t;Ot(i)&&(!t.custom&&E(n[r])?n[r]=Z({value:e[r],type:i}):n.unified_custom_fields&&E(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=Z({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},jt=async({block:e,params:t})=>{let{fields:n,dataSource:r}=Et.parse(t),i=N(r,e);if(!n||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let a;return a=Array.isArray(i)?i.map(e=>Q(e,n)):Q(i,n),{block:{...e},successful:!0,output:{data:a}}},Mt=(e,t)=>!e.properties||!t?t:Array.isArray(t)?t.map(t=>typeof t==`object`&&t?Q(t,e.properties):t):typeof t==`object`&&t?Q(t,e.properties):t,Q=(e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i,array:a}=t;i===`object`?!t.custom&&E(n[r])?n[r]=Mt(t,e[r]):n.unified_custom_fields&&E(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=Mt(t,e.unified_custom_fields?.[r])):Ot(i)&&(!t.custom&&E(n[r])?(!a||!Array.isArray(n[r]))&&(n[r]=Z({value:e[r],type:i})):n.unified_custom_fields&&E(n.unified_custom_fields?.[r])&&(!a||!Array.isArray(n.unified_custom_fields[r]))&&(n.unified_custom_fields[r]=Z({value:e.unified_custom_fields?.[r],type:i})))}),{...n}};let $=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.STATIC_VALUES=`static_values`,e}({});const Nt={[$.TYPECAST]:{v1:{fn:kt},v2:{fn:jt,inputSchema:Et,outputSchema:Dt}},[$.MAP_FIELDS]:{v1:{fn:Ve},v2:{fn:Ye,inputSchema:qe,outputSchema:Je}},[$.REQUEST]:{v1:{fn:yt,inputSchema:_t,outputSchema:vt}},[$.GROUP_DATA]:{v1:{fn:Be,inputSchema:Re,outputSchema:ze}},[$.PAGINATED_REQUEST]:{v1:{fn:dt,inputSchema:ct,outputSchema:lt}},[$.STATIC_VALUES]:{v1:{fn:Ct,inputSchema:xt,outputSchema:St}}},Pt=(e,t)=>async({block:n,params:r})=>{try{e.inputSchema&&e.inputSchema.parse(r)}catch(e){return{block:n,successful:!1,errors:[{message:`Input parameters for ${t} are invalid: ${e?.message}`}]}}let i=await e.fn({block:n,params:r});try{e.outputSchema&&e.outputSchema.parse(i.output)}catch{return{block:n,successful:!1,errors:[{message:`Output data of ${t} has unexpected format`}]}}return i},Ft={build({functionName:e,version:t=`1`,validateSchemas:n=!1,stepFunctionsList:r=Nt}){let i=r?.[e]?.[`v${t}`];if(!i)throw Error(`Unknown step function: ${e} v${t}`);return n?{...i,fn:Pt(i,e)}:i}};export{Y as AUTHENTICATION_SCHEMA,U as COMPOSITE_ID_LATEST_VERSION,W as CoreError,Oe as ReleaseStages,$ as StepFunctionName,Ft as StepFunctionsFactory,Nt as StepFunctionsRegistry,Pe as areCursorsEqual,ve as decodeCompositeId,_e as encodeCompositeId,K as expandCursor,oe as getCategoryDetails,De as isCompositeId,Le as isCoreError,Fe as isCursorEmpty,se as isValidCategory,je as minifyCursor,Ie as updateCursor};
1
+ import{decodeFromBase64 as e,encodeToBase64 as t,getContentHash as n,getCountryAlpha2CodeByAlpha2Code as r,getCountryAlpha2CodeByAlpha3Code as i,getCountryAlpha2CodeByCitizenship as a,getCountryAlpha2CodeByCountryCode as o,getCountryAlpha2CodeByCountryName as s,getCountryAlpha3CodeByAlpha2Code as c,getCountryAlpha3CodeByAlpha3Code as l,getCountryAlpha3CodeByCountryCode as u,getCountryAlpha3CodeByCountryName as d,getCountryCodeByAlpha2Code as f,getCountryCodeByAlpha3Code as p,getCountryCodeByCountryCode as m,getCountryCodeByCountryName as h,getCountryNameByAlpha2Code as g,getCountryNameByAlpha3Code as _,getCountryNameByCountryCode as v,getCountryNameByCountryName as y,getCountrySubDivisionCodeBySubDivisionName as b,getCountrySubDivisionNameBySubDivisionCode as x,getCountrySubDivisionsByAlpha2Code as S,getDocumentFileFormatFromExtension as C,isMissing as w,isObject as ee,isString as T,notMissing as E,safeParseToBoolean as D,safeParseToDateTimeString as O,safeParseToNumber as k,safeParseToString as A,z as j,zStrictObject as M}from"@stackone/utils";import{evaluate as N,isValidExpression as P,safeEvaluate as F,safeEvaluateRecord as I}from"@stackone/expressions";import{CUSTOM_ERROR_CONFIG_SCHEMA as L,HttpMethods as R,RequestClientFactory as te,RequestParameterLocations as z,createAuthorizationHeaders as ne,parseRequestParameters as re,serializeHttpResponseError as ie}from"@stackone/transport";const ae={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`},internal:{title:`Internal`,key:`internal`,description:`Category for internal actions`},action:{title:`Action`,key:`action`,description:`Action`}},oe=e=>{let t=ae[e.toLowerCase()];return t??null},se=e=>!!ae[e.toLowerCase()],ce=`so1!`,B=t(ce),V=`:`,H=`,`,le=RegExp(`(?<!\\\\)${V}`,`g`),ue=RegExp(`(?<!\\\\)${H}`,`g`),U=1;var W=class e extends Error{type;category;context;constructor({category:t,name:n,type:r,context:i,message:a}){super(a),this.name=n??`CoreError`,this.type=r,this.category=t,this.context=i,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.category}-${this.name} [${this.type}]${e}`}},G=class extends W{constructor(e,t,n){super({category:`CompositeId`,name:t??`BaseCompositeIdError`,type:e,message:n})}},de=class extends G{constructor(e){super(`COMPOSITE_ID_MISSING_HEADER_ERROR`,`CompositeIdMissingHeaderError`,e??`Invalid compositeId, missing header`)}},fe=class extends G{constructor(e){super(`COMPOSITE_ID_MISSING_BODY_ERROR`,`CompositeIdMissingBodyError`,e??`Invalid compositeId, missing body`)}},pe=class extends G{constructor(e){super(`COMPOSITE_ID_UNKNOWN_IDENTIFIER_ERROR`,`CompositeIdUnknownIdentifierError`,e??`Invalid compositeId, unknown identifier`)}},me=class extends G{constructor(e){super(`COMPOSITE_ID_UNSUPPORTED_VERSION_ERROR`,`CompositeIdUnsupportedVersionError`,e??`Invalid compositeId, unsupported version`)}};const he=e=>!w(e)&&`value`in e&&e.value!==void 0,ge=e=>!w(e)&&`identifiers`in e&&e.identifiers!==void 0,_e=(e,t={version:U})=>{if(t.version===1)return Ce(ye(e,t.aliases));throw new me(`Cannot generate ID, unsupported version number: ${t.version}`)},ve=(e,t={version:U})=>{let n=Se(e,t),r={};return n&&n.split(ue).forEach(e=>{let[n,i]=e.split(le),a=xe(n,t.aliases??{});r[a]=Ee(i)}),r},ye=(e,t={})=>{if(he(e))return be({identifier:e,compositeIdAliases:t,isSoleIdentifier:!0});if(ge(e))return e.identifiers.map(e=>be({identifier:e,compositeIdAliases:t,isSoleIdentifier:!1})).join(H);throw new pe},be=({identifier:e,compositeIdAliases:t,isSoleIdentifier:n})=>{let r=n?`id`:t[e.key]||e.key;return[r,Te(e.value)].filter(Boolean).join(V)},xe=(e,t)=>Object.keys(t).find(n=>t[n]===e)??e,Se=(e,t)=>{if(t.version===1)return we(e);throw new me(`Cannot decode ID, unsupported version number: ${t.version}`)},Ce=e=>`${B}${t(e)}`,we=t=>{if(!t.startsWith(B))throw new de(`Trying to decode an ID without the header: ${t}`);let n=t.split(B)[1];if(!n)throw new fe(`Trying to decode an ID without a body: ${t}`);return e(n)},Te=e=>[H,V].reduce((e,t)=>e.replace(t,`\\`+t),e),Ee=e=>[H,V].reduce((e,t)=>{let n=`\\`+t;return e.replace(RegExp(`\\\\`+n,`g`),t)},e),De=e=>w(e)?!1:e.startsWith(B),Oe=[`preview`,`beta`,`ga`,`deprecated`],ke=M({r:j.record(j.string(),M({n:j.number().optional().nullable(),c:j.string().optional().nullable(),p:j.number().optional().nullable()})),v:j.number(),t:j.number()}),Ae=M({remote:j.record(j.string(),M({pageNumber:j.number().optional(),providerPageCursor:j.string().optional(),position:j.number().optional()})),version:j.number(),timestamp:j.number()}),je=e=>t(JSON.stringify(Me(e))),Me=e=>{let{remote:t,version:n,timestamp:r}=e,i=Object.fromEntries(Object.entries(t).map(([e,{pageNumber:t,providerPageCursor:n,position:r}])=>[e,{n:t,c:n,p:r}])),a={r:i,v:n,t:r};return a},K=t=>{try{if(T(t)){let n=e(t),r=JSON.parse(n),i=ke.parse(r);return Ne(i)}else return Ae.parse(t),t}catch{return null}},Ne=e=>{let{r:t,v:n,t:r}=e,i=Object.fromEntries(Object.entries(t).map(([e,{n:t,c:n,p:r}])=>[e,{pageNumber:t,providerPageCursor:n,position:r}])),a={remote:i,version:n,timestamp:r};return a},Pe=(e,t)=>{let r=typeof e==`string`?K(e):e,i=typeof t==`string`?K(t):t;if(r===null||i===null)return r===i;let{timestamp:a,...o}=r,{timestamp:s,...c}=i;return n(o)===n(c)},Fe=({cursor:e,ignoreStepIndex:t})=>w(e)?!0:Object.keys(e?.remote??{}).reduce((n,r)=>{let i=e?.remote?.[r];return(w(t)||r!==t.toString())&&(n=n&&w(i.pageNumber)&&w(i.position)&&w(i.providerPageCursor)),n},!0),Ie=({cursor:e,stepIndex:t,pageNumber:n,providerPageCursor:r,position:i})=>{let a={pageNumber:n??void 0,providerPageCursor:r??void 0,position:i??void 0},o=w(n)&&w(r)&&w(i);return w(e)?{remote:o?{}:{[t]:a},version:2,timestamp:Date.now()}:o?(delete e.remote[t],e):{...e,remote:{...e.remote,[t]:a}}},Le=e=>e instanceof W,Re=j.object({stepsDataToGroup:j.array(j.string()),isSingleRecord:j.boolean().optional()}),ze=j.object({data:j.unknown()}),Be=async({block:e,params:t})=>{let{stepsDataToGroup:n,isSingleRecord:r}=Re.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=>{let r=E(t[e])?t[e]:{};t[e]={...r,[n]:{...i[e]}}}),t):t},{});return{block:{...e},successful:!0,output:{data:r?i:Object.values(i)}}},Ve=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;if(Array.isArray(e.result)){let a=e.result.length;i=e.result.map((e,i)=>{let o=He(r,a,i),s=Ue(e,t,o);return n.push(...s.errors||[]),s.record})}else{let a=Ue(e.result,t,r);i=a.record,n.push(...a.errors||[])}return{block:{...e,result:i},successful:!0,errors:Object.keys(n).length>0?n:void 0}},He=(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},{}),Ue=(e,t,n)=>{if(!e||!n)return{record:e};let r={unified:{...e},...typeof n==`object`?n:{}},i={},a=[],o={...e};for(let n of t){let{error:t,value:s}=We(r,e.id,n);if(t){a.push(t);continue}n.custom?i[n.targetFieldKey]=s:o[n.targetFieldKey]=s}return{record:{...o,unified_custom_fields:Object.keys(i).length>0?i:void 0},errors:a.length>0?a:void 0}},We=(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=N(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}},Ge=e=>{switch(e){case`country_alpha2code_by_alpha2code`:return r;case`country_alpha3code_by_alpha3code`:return l;case`country_code_by_country_code`:return m;case`country_name_by_country_name`:return y;case`country_name_by_alpha3code`:return _;case`country_name_by_alpha2code`:return g;case`country_name_by_country_code`:return v;case`country_alpha3code_by_alpha2code`:return c;case`country_alpha3code_by_country_name`:return d;case`country_alpha3code_by_country_code`:return u;case`country_alpha2code_by_alpha3code`:return i;case`country_alpha2code_by_country_name`:return s;case`country_alpha2code_by_country_code`:return o;case`country_code_by_alpha2code`:return f;case`country_code_by_alpha3code`:return p;case`country_code_by_country_name`:return h;case`country_subdivisions_by_alpha2code`:return S;case`country_subdivision_code_by_subdivision_name`:return b;case`country_alpha2code_by_citizenship`:return a;case`country_subdivision_name_by_subdivision_code`:return x;case`document_file_format_from_extension`:return C;default:return}},Ke=M({targetFieldKey:j.string(),alias:j.string().optional(),expression:j.string().optional(),values:j.unknown().optional(),type:j.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:j.boolean().default(!1),custom:j.boolean().default(!1),hidden:j.boolean().default(!1),enumMapper:M({matcher:j.string().or(M({matchExpression:j.string(),value:j.string()}).array())}).optional(),properties:j.lazy(()=>Ke).array().optional()}),qe=j.object({fields:Ke.array(),dataSource:j.string(),externalSources:j.record(j.string(),j.string()).optional()}),Je=j.object({data:j.unknown()}),Ye=async({block:e,params:t})=>{let n=[],{fields:r,dataSource:i,externalSources:a}=qe.parse(t),o=N(i,e);if(!r||!i||e?.debug?.custom_mappings===`disabled`||!o)return{block:e,successful:!0};let s=Object.keys(a??{})?.reduce((t,n)=>(t[n]=N(a?.[n],e),t),{}),c;if(Array.isArray(o))c=o.map(e=>{let t=q(r,{...e,external:s});return n.push(...t?.errors||[]),t?.record});else{let e=q(r,{...o,external:s});c=e?.record,n.push(...e?.errors||[])}return{block:{...e},successful:!0,output:{data:c},errors:Object.keys(n).length>0?n:void 0}},Xe=(e,t,n)=>{if(Array.isArray(e.values))return e.values.map(r=>{let i=J(r,t),a=q(e.properties,i);return E(a?.errors)&&n.push(...a.errors),a?.record}).filter(Boolean)},Ze=(e,t,n)=>{if(e.expression)try{let r=N(e.expression,t);if(Array.isArray(r))return r.map(t=>{let r=q(e.properties,t);return E(r?.errors)&&n.push(...r.errors),r?.record}).filter(Boolean);{let t=q(e.properties,r);return E(t?.errors)&&n.push(...t.errors),t?.record}}catch{n.push({message:`Invalid expression`,id:t?.id,targetField:e.targetFieldKey});return}},Qe=(e,t,n)=>{let r=E(e.values)?e.values:t,i=q(e.properties,r);return E(i?.errors)&&n.push(...i.errors),i?.record},$e=(e,t,n)=>{if(!w(e.properties))return e.array&&Array.isArray(e.values)?Xe(e,t,n):e.array&&e.expression?Ze(e,t,n):Qe(e,t,n)},q=(e,t)=>{if(!t)return;let n={},r=[],i={};for(let a of e){let e;if(a.type===`object`){if(e=$e(a,t,r),e===void 0)continue}else{let{error:n,value:i}=et(t,t?.id,a);if(e=i,n){r.push(n);continue}}a.custom?n[a.targetFieldKey]=e:i[a.targetFieldKey]=e}let a=Object.keys(n).length>0?{unified_custom_fields:n}:{};return{record:{...i,...a},errors:r.length>0?r:void 0}},J=(e,t)=>{if(e==null)return e;if(typeof e==`string`){if(P(e))try{return N(e,t)}catch{return e}return e}if(Array.isArray(e))return e.map(e=>J(e,t));if(typeof e==`object`){let n={...e};for(let[e,r]of Object.entries(n))n[e]=J(r,t);return n}return e},et=(e,t,n)=>{switch(n.type){case`string`:case`number`:case`boolean`:case`datetime_string`:return tt(n,t,e);case`enum`:return nt(n,t,e);default:return{error:{message:`Invalid type`,id:t,targetField:n.targetFieldKey}}}},tt=(e,t,n)=>{if(!e.expression)return{error:{message:`Expression is empty`,id:t,targetField:e.targetFieldKey}};let r;try{r=N(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}},nt=(e,t,n)=>{let r=tt(e,t,n),i=E(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(T(a)){let n=Ge(a);if(E(n)){let e=E(i)?n(i):null;return{value:{value:e??`unmapped_value`,source_value:i}}}else return{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,a=N(t,n);if(a===!0)return{value:{value:r,source_value:i}}}return{value:{value:`unmapped_value`,source_value:i}}},rt=[`data`,`headers`],it=M({type:j.literal(`none`)}),at=M({type:j.literal(`basic`),username:j.string().optional(),password:j.string().optional(),encoding:j.string().optional()}),ot=M({type:j.literal(`bearer`),token:j.string(),includeBearer:j.boolean().optional().default(!0)}),st=M({type:j.literal(`oauth2`),authorizationUrl:j.string().optional(),authorizationParams:j.record(j.string(),j.string()).optional(),tokenUrl:j.string().optional(),tokenParams:j.record(j.string(),j.string()).optional(),tokenExpiresIn:j.number().optional(),tokenRefreshExpiresIn:j.number().optional(),token:j.string(),includeBearer:j.boolean().optional().default(!0),scopes:j.string().optional(),scopeDelimiter:j.string().optional(),customHeaders:j.record(j.string(),j.string()).optional(),pkce:j.boolean().optional()}),ct=j.discriminatedUnion(`type`,[it,at,ot,st]),lt=j.object({baseUrl:j.string(),url:j.string(),method:j.enum(R),response:M({indexField:j.string().optional(),dataKey:j.string().optional(),nextKey:j.string().optional(),nextKeyIn:j.enum(rt).optional()}).optional(),iterator:M({key:j.string(),in:j.enum(z)}),cursor:M({token:j.string().optional().nullable(),position:j.number().optional().nullable()}).optional(),customErrors:L.array().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(z),condition:j.string().optional()}).array().optional()}),ut=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional(),next:j.string().optional().nullable(),position:j.number().optional()}).optional(),dt=25,ft=async({block:e,params:t})=>{let n=te.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)?dt:i,o=r?r.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,s=t?I({...t,args:o},e):{},c={...s,customErrors:t?.customErrors},{baseUrl:l,url:u,method:d,response:f,iterator:p,cursor:m,customErrors:h,args:g}=lt.parse(c),_=s?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,v=ct.parse(_),y=g?re(g):{query:{},body:{},headers:{}},b=ne(v),x={...y?.headers??{},...b},S=e.connector?.rateLimit,C=e.connector?.concurrency,ee=S!==void 0||C!==void 0?{rateLimit:S,concurrency:C}:void 0,T=m?.token??null,D=null,O=null,k=[],A=[],j=[],M=a,P=m?.position??0,F=!0,L=!0;do{F?F=!1:P=0,T!==null&&(p.in===`query`?y.query[p.key]=T.toString():p.in===`body`&&(y.body[p.key]=T));let t;try{t=await n.performRequest({httpClient:e.httpClient,url:`${l}${u}`,queryParams:y?.query,method:d,headers:x,body:y?.body,customErrorConfigs:h,requestConfig:ee})}catch(t){let n=t;return{block:e,successful:!1,errors:[ie(t)],output:{statusCode:n?.response?.status??500,message:n?.response?.message}}}D=T,A=f?.dataKey?t.data[f?.dataKey]:t.data;let r=A?.slice(P,P+M);M-=r.length,P+=r.length,j.push(t),k=k.concat(r),O=t?.status,T=pt({result:t,response:f}),r.length===A.length&&M===0&&(P=0,D=T),L=w(T)&&k.length<a}while(E(T)&&k.length<a&&A?.length>0);let R=gt(k,f);return{block:e,successful:!0,output:{data:R,raw:j,statusCode:O,next:L?void 0:D,position:L?void 0:P}}},pt=({result:e,response:t})=>{if(w(t?.nextKey))return null;let n=t?.nextKeyIn??`data`,r=t?.nextKey;return n===`headers`?mt(e.headers,r):ht(e.data,r)},mt=(e,t)=>{if(w(e)||typeof e!=`object`)return 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},ht=(e,t)=>{if(w(e)||typeof e!=`object`||!e)return null;let n=e[t];return w(n)?null:typeof n==`string`||typeof n==`number`?n:null},gt=(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},_t=M({type:j.literal(`none`)}),vt=M({type:j.literal(`basic`),username:j.string().optional(),password:j.string().optional(),encoding:j.string().optional()}),yt=M({type:j.literal(`bearer`),token:j.string(),includeBearer:j.boolean().optional().default(!0)}),bt=M({type:j.literal(`oauth2`),authorizationUrl:j.string().optional(),authorizationParams:j.record(j.string(),j.string()).optional(),tokenUrl:j.string().optional(),tokenParams:j.record(j.string(),j.string()).optional(),tokenExpiresIn:j.number().optional(),tokenRefreshExpiresIn:j.number().optional(),token:j.string(),includeBearer:j.boolean().optional().default(!0),scopes:j.string().optional(),scopeDelimiter:j.string().optional(),customHeaders:j.record(j.string(),j.string()).optional(),pkce:j.boolean().optional()}),Y=j.discriminatedUnion(`type`,[_t,vt,yt,bt]),xt=j.object({baseUrl:j.string().optional(),url:j.string(),method:j.enum(R),authorization:Y.optional(),response:M({collection:j.boolean().optional(),indexField:j.string().optional(),dataKey:j.string().optional()}).optional(),customErrors:L.array().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(z),condition:j.string().optional()}).array().optional()}),St=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional()}).optional(),Ct=async({block:e,params:t})=>{let n=te.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?I({...t,args:i},e):{},o={...a,customErrors:t?.customErrors},{baseUrl:s,url:c,method:l,response:u,authorization:d,customErrors:f,args:p}=xt.parse(o),m=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,h=p?re(p):{query:{},body:{},headers:{}},g=E(d)?d:Y.parse(m),_=ne(g),v={...h?.headers??{},..._},y=e.connector?.rateLimit,b=e.connector?.concurrency,x=y!==void 0||b!==void 0?{rateLimit:y,concurrency:b}:void 0,S;try{S=await n.performRequest({httpClient:e.httpClient,url:`${s}${c}`,queryParams:h?.query,method:l,headers:v,body:h?.body,customErrorConfigs:f,requestConfig:x})}catch(t){let n=t;return{block:e,successful:!1,errors:[ie(t)],output:{statusCode:n?.response?.status??500,message:n?.response?.message}}}let C=u?.dataKey?S.data[u?.dataKey]:S.data,w=wt(C,u);return{block:e,successful:!0,output:{data:w,raw:S,statusCode:S?.status,message:S?.message}}},wt=(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},Tt=j.object({values:j.string().or(j.record(j.string(),j.unknown())).or(j.array(j.unknown()))}),Et=j.object({data:j.unknown()}),Dt=async({block:e,params:t})=>{let{values:n}=Tt.parse(t),r=Array.isArray(n)?n.map(t=>Ot(t,e)):Ot(n,e);return{block:{...e},successful:!0,output:{data:r}}},Ot=(e,t)=>T(e)?F(e,t):ee(e)?I(e,t):e,kt=j.object({targetFieldKey:j.string(),type:j.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:j.boolean().default(!1),custom:j.boolean().default(!1),hidden:j.boolean().default(!1),properties:j.lazy(()=>kt).array().optional()}),At=j.object({fields:kt.array().optional(),dataSource:j.string()}),jt=j.object({data:j.unknown()});let X=function(e){return e.String=`string`,e.Number=`number`,e.Boolean=`boolean`,e.DateTimeString=`datetime_string`,e}({});const Z=({value:e,type:t,format:n})=>{if(w(e))return null;switch(t){case X.String:return A({value:e});case X.Number:return k({value:e});case X.Boolean:return D({value:e});case X.DateTimeString:return O({value:e,format:n});default:return e}},Mt=e=>{let t=Object.values(X);return t.includes(e)},Nt=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=>Pt(e,t)):Pt(e.result,t),{block:{...e,result:n},successful:!0}},Pt=(e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i}=t;Mt(i)&&(!t.custom&&E(n[r])?n[r]=Z({value:e[r],type:i}):n.unified_custom_fields&&E(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=Z({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},Ft=async({block:e,params:t})=>{let{fields:n,dataSource:r}=At.parse(t),i=N(r,e);if(!n||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let a;return a=Array.isArray(i)?i.map(e=>Q(e,n)):Q(i,n),{block:{...e},successful:!0,output:{data:a}}},It=(e,t)=>!e.properties||!t?t:Array.isArray(t)?t.map(t=>typeof t==`object`&&t?Q(t,e.properties):t):typeof t==`object`&&t?Q(t,e.properties):t,Q=(e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i,array:a}=t;i===`object`?!t.custom&&E(n[r])?n[r]=It(t,e[r]):n.unified_custom_fields&&E(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=It(t,e.unified_custom_fields?.[r])):Mt(i)&&(!t.custom&&E(n[r])?(!a||!Array.isArray(n[r]))&&(n[r]=Z({value:e[r],type:i})):n.unified_custom_fields&&E(n.unified_custom_fields?.[r])&&(!a||!Array.isArray(n.unified_custom_fields[r]))&&(n.unified_custom_fields[r]=Z({value:e.unified_custom_fields?.[r],type:i})))}),{...n}};let $=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.STATIC_VALUES=`static_values`,e}({});const Lt={[$.TYPECAST]:{v1:{fn:Nt},v2:{fn:Ft,inputSchema:At,outputSchema:jt}},[$.MAP_FIELDS]:{v1:{fn:Ve},v2:{fn:Ye,inputSchema:qe,outputSchema:Je}},[$.REQUEST]:{v1:{fn:Ct,inputSchema:xt,outputSchema:St}},[$.GROUP_DATA]:{v1:{fn:Be,inputSchema:Re,outputSchema:ze}},[$.PAGINATED_REQUEST]:{v1:{fn:ft,inputSchema:lt,outputSchema:ut}},[$.STATIC_VALUES]:{v1:{fn:Dt,inputSchema:Tt,outputSchema:Et}}},Rt=(e,t)=>async({block:n,params:r})=>{try{e.inputSchema&&e.inputSchema.parse(r)}catch(e){return{block:n,successful:!1,errors:[{message:`Input parameters for ${t} are invalid: ${e?.message}`}]}}let i=await e.fn({block:n,params:r});try{e.outputSchema&&e.outputSchema.parse(i.output)}catch{return{block:n,successful:!1,errors:[{message:`Output data of ${t} has unexpected format`}]}}return i},zt={build({functionName:e,version:t=`1`,validateSchemas:n=!1,stepFunctionsList:r=Lt}){let i=r?.[e]?.[`v${t}`];if(!i)throw Error(`Unknown step function: ${e} v${t}`);return n?{...i,fn:Rt(i,e)}:i}};export{Y as AUTHENTICATION_SCHEMA,U as COMPOSITE_ID_LATEST_VERSION,W as CoreError,Oe as ReleaseStages,$ as StepFunctionName,zt as StepFunctionsFactory,Lt as StepFunctionsRegistry,Pe as areCursorsEqual,ve as decodeCompositeId,_e as encodeCompositeId,K as expandCursor,oe as getCategoryDetails,De as isCompositeId,Le as isCoreError,Fe as isCursorEmpty,se as isValidCategory,je as minifyCursor,Ie as updateCursor};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/core",
3
- "version": "1.74.0",
3
+ "version": "2.0.0",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",