diff --git a/build/dist/orgcheck/orgcheck-api.js b/build/dist/orgcheck/orgcheck-api.js index 73c914a2..1b62e313 100644 --- a/build/dist/orgcheck/orgcheck-api.js +++ b/build/dist/orgcheck/orgcheck-api.js @@ -251,11 +251,12 @@ class DataDependenciesFactory { /** * @description Create a new instance of DataDependencies * @param {{ records: Array<{ id: string, name: string, type: string, url: string, refId: string, refName: string, refType: string, refUrl: string }>, errors: Array }} data - * @param {string} whatId + * @param {Array} whatIds * @returns {DataDependencies} */ - static create(data, whatId) { - if (data.errors?.includes(whatId)) { + static create(data, whatIds) { + // Check if at least one of the whatIds is present in the data errors list + if (data.errors?.some(errorId => whatIds.includes(errorId))) { return { hadError: true, using: [], @@ -263,7 +264,9 @@ class DataDependenciesFactory { referencedByTypes: {} }; } - const using = data.records.filter(e => e.id === whatId).map(n => { + // Data can contain a lot of dependencies from other ids, we just want to get the dependencies for the given whatIds + // WhatID is using what? -- Here we are getting the dependencies where the ID is in the whatIds list + const using = data.records.filter(e => whatIds.includes(e.id)).map(n => { return { id: n.refId, name: n.refName, @@ -272,7 +275,8 @@ class DataDependenciesFactory { }; }); const referencedByTypes = {}; - const referenced = data.records.filter(e => e.refId === whatId).map(n => { + // WhatID is referenced where? -- Here we are getting the dependencies where the REFID is in the whatIds list + const referenced = data.records.filter(e => whatIds.includes(e.refId)).map(n => { if (referencedByTypes[n.type] === undefined) { referencedByTypes[n.type] = 1; } else { @@ -7918,10 +7922,14 @@ class DatasetFlows extends Dataset { // Then retreive dependencies logger?.log(`Retrieving dependencies of ${flowDefRecords.length} flow versions...`); - const flowDefinitionsDependencies = await sfdcManager.dependenciesQuery( - await Processor.map(flowDefRecords, (record) => sfdcManager.caseSafeId(record.ActiveVersionId ?? record.LatestVersionId)), - logger - ); + const flowDependenciesIds = []; + await Processor.forEach(flowDefRecords, (record) => { + // Add the ID15 of the most interesting flow version + flowDependenciesIds.push(sfdcManager.caseSafeId(record.ActiveVersionId ?? record.LatestVersionId)); + // Add the ID15 of the flow definition + flowDependenciesIds.push(sfdcManager.caseSafeId(record.Id)); + }); + const flowDefinitionsDependencies = await sfdcManager.dependenciesQuery(flowDependenciesIds, logger); // List of active flows that we need to get information later (with Metadata API) const activeFlowIds = []; @@ -7952,7 +7960,7 @@ class DatasetFlows extends Dataset { }, dependencies: { data: flowDefinitionsDependencies, - idField: 'currentVersionId' + idFields: [ 'id', 'currentVersionId' ] } }); @@ -8265,7 +8273,7 @@ class DataFactoryInstance extends DataFactoryInstanceIntf { } // If dependencies are needed... if (this._isDependenciesNeeded === true && configuration.dependencies) { - row.dependencies = DataDependenciesFactory.create(configuration.dependencies.data, row[configuration.dependencies.idField || 'id']); + row.dependencies = DataDependenciesFactory.create(configuration.dependencies.data, (configuration.dependencies.idFields || ['id']).map(f => row[f])); } // Return the row finally return row; diff --git a/build/dist/orgcheck/orgcheck-api.min.js b/build/dist/orgcheck/orgcheck-api.min.js index 7e6d25b6..938d7c28 100644 --- a/build/dist/orgcheck/orgcheck-api.min.js +++ b/build/dist/orgcheck/orgcheck-api.min.js @@ -1 +1 @@ -"use strict";class e{created}class t{has(e){throw new Error("Not implemented")}get(e){throw new Error("Not implemented")}set(e,t){throw new Error("Not implemented")}details(){throw new Error("Not implemented")}remove(e){throw new Error("Not implemented")}clear(){throw new Error("Not implemented")}}const s=new RegExp("(\\/\\*[\\s\\S]*?\\*\\/|\\/\\/.*\\n|\\n)","gi"),a=new RegExp("(?:public|global)\\s+(?:interface)\\s+\\w+(\\s+(?:extends)\\s+\\w+)?\\s*\\{","i"),r=new RegExp("(?:public|global)\\s+(?:enum)\\s+\\w+\\s*\\{","i"),i=new RegExp("@IsTest\\s*\\(.*SeeAllData=true.*\\)","i"),n=new RegExp("(System.assert(Equals|NotEquals|)\\s*\\(|Assert\\.[a-zA-Z]*\\s*\\()","ig"),o=new RegExp("([A-Za-z0-9-]{1,63}\\.)+[A-Za-z]{2,6}","ig"),l=new RegExp("[,\"'\\s][a-zA-Z0-9]{5}0[a-zA-Z0-9]{9}([a-zA-Z0-9]{3})?[,\"'\\s]","ig"),c=new RegExp("\\[\\s*(?:SELECT|FIND)"),d=new RegExp("(?:insert|update|delete)\\s*(?:\\s\\w+|\\(|\\[)"),p=["salesforce.com",".force."];class g{static RemoveComments(e){return e?.replaceAll(s," ")||""}static IsInterface(e){return null!==e?.match(a)||!1}static IsEnum(e){return null!==e?.match(r)||!1}static FindHardCodedURLs(e){return e?.match(o)?.filter((e=>p.findIndex((t=>e.indexOf(t)>=0))>=0)).sort().filter(((e,t,s)=>t===s.indexOf(e)))}static FindHardCodedIDs(e){return e?.match(l)?.map((e=>e?.substring(1,e?.length-1))).sort().filter(((e,t,s)=>t===s.indexOf(e)))}static IsTestSeeAllData(e){return null!==e?.match(i)||!1}static CountOfAsserts(e){return e?.match(n)?.length||0}static HasSOQL(e){return null!==e?.match(c)||!1}static HasDML(e){return null!==e?.match(d)||!1}}class u{static create(e,t){if(e.errors?.includes(t))return{hadError:!0,using:[],referenced:[],referencedByTypes:{}};const s=e.records.filter((e=>e.id===t)).map((e=>({id:e.refId,name:e.refName,type:e.refType,url:e.refUrl}))),a={};return{hadError:!1,using:s,referenced:e.records.filter((e=>e.refId===t)).map((e=>(void 0===a[e.type]?a[e.type]=1:a[e.type]++,{id:e.id,name:e.name,type:e.type,url:e.url}))),referencedByTypes:a}}}class h{static create(){return new m}}class m{constructor(){this._columnIds=new Set,this._columns=new Map,this._rows=new Map}toDataMatrix(){const e=[];return this._columnIds.forEach((t=>{e.push(this._columns.has(t)?this._columns.get(t):t)})),{columnHeaders:e,rows:Array.from(this._rows.values())}}addValueToProperty(e,t,s){!1===this._rows.has(e)&&this._rows.set(e,{header:{},data:{}}),this._rows.get(e).data[t]=s,this._columnIds.add(t)}hasColumnHeader(e){return this._columns.has(e)}setColumnHeader(e,t){this._columns.set(e,t)}hasRowHeader(e){return this._rows.has(e)&&this._rows.get(e).header}setRowHeader(e,t){!0===this._rows.has(e)?this._rows.get(e).header=t:this._rows.set(e,{header:t,data:{}})}_columnIds;_columns;_rows}class f{static get label(){return console.error("Need to implement static label() method for",this,JSON.stringify(this),this.name),this.name}score;badFields;badReasonIds}class S extends f{dependencies}class E{}class I{getInstance(e){throw new Error("Not implemented")}}class w{create(e){throw new Error("Not implemented")}computeScore(e){throw new Error("Not implemented")}createWithScore(e){throw new Error("Not implemented")}}class P{alias;cacheKey;parameters;constructor(e,t){this.alias=e,this.cacheKey=t,this.parameters=new Map}}class R{log(e,t){throw new TypeError('You need to implement the method "log()"')}ended(e,t){throw new TypeError('You need to implement the method "ended()"')}failed(e,t){throw new TypeError('You need to implement the method "failed()"')}}class T extends R{toSimpleLogger(e){throw new TypeError('You need to implement the method "toSimpleLogger()"')}}class y{currentUsageRatio=0;currentUsagePercentage="";get yellowThresholdPercentage(){return.7}get redThresholdPercentage(){return.9}get isGreenZone(){return this.currentUsageRatio<.7}get isYellowZone(){return this.currentUsageRatio>=.7&&this.currentUsageRatio<.9}get isRedZone(){return this.currentUsageRatio>=.9}}class C{constructor(e){this._apiLimitExtractor=e,this._lastRequestToSalesforce=void 0,this._lastApiUsage=new y}_apiLimitExtractor;_lastRequestToSalesforce;_lastApiUsage;beforeRequest(e){if(this._lastRequestToSalesforce&&Date.now()-this._lastRequestToSalesforce<=6e4&&this._lastApiUsage.isRedZone){const t=new TypeError(`WATCH DOG: Daily API Request limit is ${A(this._lastApiUsage.currentUsageRatio)}%, and our internal threshold is ${A(this._lastApiUsage.redThresholdPercentage)}%. We stop there to keep your org safe.`);throw e&&e(t),t}}afterRequest(e){const t=this._apiLimitExtractor();t&&(this._lastApiUsage.currentUsageRatio=t.used/t.max,this._lastApiUsage.currentUsagePercentage=A(this._lastApiUsage.currentUsageRatio),this._lastRequestToSalesforce=Date.now(),this.beforeRequest(e))}get dailyApiRequestLimitInformation(){return this._lastApiUsage}}const A=(e,t=2)=>(100*e).toFixed(t);class O extends E{static get label(){return"Apex Test Result"}methodName;isSuccessful;runtime;stacktrace;cpuConsumption;asyncCallsConsumption;soslConsumption;soqlConsumption;queryRowsConsumption;dmlRowsConsumption;dmlConsumption}class b extends S{static get label(){return"Apex Class"}id;name;url;apiVersion;package;isTest;isTestSeeAllData;nbSystemAsserts;isAbstract;isClass;isEnum;isInterface;innerClassesCount;isSchedulable;isScheduled;interfaces;extends;methodsCount;testPassedButLongMethods;testFailedMethods;lastTestRunDate;testMethodsRunTime;annotations;specifiedSharing;specifiedAccess;length;hardCodedURLs;hardCodedIDs;needsRecompilation;coverage;relatedTestClassIds;relatedTestClassRefs;relatedClassIds;relatedClassRefs;createdDate;lastModifiedDate}class M{get apiVersion(){throw new Error("Not implemented")}caseSafeId(e){throw new Error("Not implemented")}setupUrl(e,t,s,a){throw new Error("Not implemented")}getObjectType(e,t){throw new Error("Not implemented")}get dailyApiRequestLimitInformation(){throw new Error("Not implemented")}async soqlQuery(e,t){throw new Error("Not implemented")}async dependenciesQuery(e,t){throw new Error("Not implemented")}async readMetadata(e,t){throw new Error("Not implemented")}async readMetadataAtScale(e,t,s,a){throw new Error("Not implemented")}async describeGlobal(e){throw new Error("Not implemented")}async describe(e,t){throw new Error("Not implemented")}async recordCount(e,t){throw new Error("Not implemented")}async runAllTests(e){throw new Error("Not implemented")}async compileClasses(e,t){throw new Error("Not implemented")}}class D{async run(e,t,s,a){throw new TypeError('You need to implement the method "run()"')}}class _{async run(e){throw new TypeError('You need to implement the method "run()"')}clean(e){throw new TypeError('You need to implement the method "clean()"')}}const L={APEXCLASSES:"apex-classes",APEXTRIGGERS:"apex-triggers",APPLICATIONS:"applications",APPPERMISSIONS:"app-permisions",CURRENTUSERPERMISSIONS:"current-user-permissions",CUSTOMFIELDS:"custom-fields",CUSTOMLABELS:"custom-labels",FIELDPERMISSIONS:"field-permissions",FLOWS:"flows",GROUPS:"groups",LIGHTNINGAURACOMPONENTS:"lightning-aura-components",LIGHTNINGPAGES:"lightning-pages",LIGHTNINGWEBCOMPONENTS:"lightning-web-components",OBJECT:"object",OBJECTPERMISSIONS:"object-permissions",OBJECTS:"objects",OBJECTTYPES:"object-types",ORGANIZATION:"org-information",PACKAGES:"packages",PERMISSIONSETS:"permission-sets",PERMISSIONSETLICENSES:"permission-set-licenses",PROFILEPWDPOLICIES:"profile-password-policies",PROFILERESTRICTIONS:"profile-restrictions",PROFILES:"profiles",USERROLES:"user-roles",USERS:"users",VALIDATIONRULES:"validation-rules",VISUALFORCECOMPONENTS:"visual-force-components",VISUALFORCEPAGES:"visual-force-pages",WORKFLOWS:"workflows"};Object.seal(L);class N{static async forEach(e,t){if(!e)return Promise.resolve();if("function"!=typeof t)throw new TypeError("Given iteratee is not a proper Function.");if(!0===Array.isArray(e))return Promise.all(e.map((async e=>(await t(e),null))));if(e instanceof Map==!0){const s=[];return e.forEach(((e,a)=>s.push(new Promise((s=>{t(e,a),s()}))))),Promise.all(s)}throw new TypeError("Given iterable is not a proper Array nor Map.")}static async map(e,t,s){if(!e)return Promise.resolve([]);if(!1===Array.isArray(e))throw new TypeError("Given iterable is not a proper Array.");if("function"!=typeof t)throw new TypeError("Given iteratee is not a proper Function.");if(s&&"function"!=typeof s)throw new TypeError("Given filterIteratee is not a proper Function.");return Promise.all((s?e.filter((e=>s(e))):e).map((async e=>t(e))))}}class x{extract(e,...t){throw new TypeError('You need to implement the method "extract()"')}async transform(e,t,...s){throw new TypeError('You need to implement the method "transform()"')}}class F{async run(e,...t){throw new TypeError('You need to implement the method "run()"')}clean(e,...t){throw new TypeError('You need to implement the method "clean()"')}}const U={ACTIVE_USERS:"active-users",APEX_CLASSES:"apex-classes",APEX_TESTS:"apex-tests",APEX_TRIGGERS:"apex-triggers",APEX_UNCOMPILED:"apex-uncompiled",APP_PERMISSIONS:"app-permissions",CURRENT_USER_PERMISSIONS:"current-user-permissions",CUSTOM_FIELDS:"custom-fields",CUSTOM_LABELS:"custom-labels",FIELD_PERMISSIONS:"field-permissions",FLOWS:"flows",LIGHTNING_AURA_COMPONENTS:"lightning-aura-components",LIGHTNING_PAGES:"lightning-pages",LIGHTNING_WEB_COMPONENTS:"lightning-web-components",OBJECT:"object",OBJECT_PERMISSIONS:"object-permissions",OBJECTS:"objects",OBJECT_TYPES:"object-types",ORGANIZATION:"org-information",PACKAGES:"packages",PERMISSION_SETS:"permission-sets",PERMISSION_SET_LICENSES:"permission-set-licenses",PROCESS_BUILDERS:"process-builders",PROFILE_PWD_POLICIES:"profile-password-policies",PROFILE_RESTRICTIONS:"profile-restrictions",PROFILES:"profiles",PUBLIC_GROUPS:"public-groups",QUEUES:"queues",USER_ROLES:"user-roles",VALIDATION_RULES:"validation-rules",VISUALFORCE_COMPONENTS:"visualforce-components",VISUALFORCE_PAGES:"visualforce-pages",WORKFLOWS:"workflows"};Object.seal(U);const v={ANY_FIELD:"Field",APEX_CLASS:"ApexClass",APEX_TRIGGER:"ApexTrigger",AURA_WEB_COMPONENT:"AuraDefinitionBundle",CUSTOM_BIG_OBJECT:"CustomBigObject",CUSTOM_EVENT:"CustomEvent",CUSTOM_FIELD:"CustomField",CUSTOM_LABEL:"CustomLabel",CUSTOM_METADATA_TYPE:"CustomMetadataType",CUSTOM_OBJECT:"CustomObject",CUSTOM_SETTING:"CustomSetting",CUSTOM_SITE:"CustomSite",CUSTOM_TAB:"CustomTab",EXTERNAL_OBJECT:"ExternalObject",FIELD_SET:"FieldSet",FLOW_DEFINITION:"FlowDefinition",FLOW_VERSION:"Flow",KNOWLEDGE_ARTICLE:"KnowledgeArticle",LIGHTNING_PAGE:"FlexiPage",LIGHTNING_WEB_COMPONENT:"LightningComponentBundle",PAGE_LAYOUT:"Layout",PERMISSION_SET:"PermissionSet",PERMISSION_SET_GROUP:"PermissionSetGroup",PERMISSION_SET_LICENSE:"PermissionSetLicense",PROFILE:"Profile",PUBLIC_GROUP:"PublicGroup",QUEUE:"Queue",RECORD_TYPE:"RecordType",ROLE:"UserRole",TECHNICAL_GROUP:"TechnicalGroup",STANDARD_FIELD:"StandardField",STANDARD_OBJECT:"StandardEntity",STATIC_RESOURCE:"StaticResource",USER:"User",VALIDATION_RULE:"ValidationRule",VISUAL_FORCE_COMPONENT:"ApexComponent",VISUAL_FORCE_PAGE:"ApexPage",WEB_LINK:"WebLink",WORKFLOW_RULE:"WorkflowRule"};Object.seal(v);class G extends S{static get label(){return"Standard or Custom Field"}id;url;name;label;package;description;createdDate;lastModifiedDate;objectId;objectRef;isCustom;tooltip;type;length;isUnique;isEncrypted;isExternalId;isIndexed;defaultValue;isRestrictedPicklist;formula;hardCodedURLs;hardCodedIDs}class $ extends f{static get label(){return"Field Set"}id;label;description;url}class B extends S{static get label(){return"Lightning Page"}id;name;type;package;createdDate;lastModifiedDate;objectId;objectRef;description;url}class W extends f{static get label(){return"SObject Limit"}id;label;remaining;max;used;usedPercentage;type}class V extends E{static get label(){return"SObject Releationship"}name;childObject;fieldName;isCascadeDelete;isRestrictedDelete}class k extends E{static get label(){return"SObject Types"}id;label}const j="StandardEntity",Q="CustomObject",q="ExternalObject",H="CustomSetting",J="CustomMetadataType",Y="CustomEvent",X="KnowledgeArticle",K="CustomBigObject";class z extends f{static get label(){return"Page Layout"}id;name;type;url}class Z extends f{static get label(){return"Record Type"}id;name;developerName;url;isActive;isAvailable;isDefaultRecordTypeMapping;isMaster}class ee extends f{static get label(){return"Validation Rule"}id;name;isActive;description;errorDisplayField;errorMessage;objectId;objectRef;package;createdDate;lastModifiedDate;url}class te extends f{static get label(){return"Web Link"}id;name;hardCodedURLs;hardCodedIDs;type;behavior;package;createdDate;lastModifiedDate;description;url}class se extends E{static get label(){return"SObject"}id;label;labelPlural;isCustom;isFeedEnabled;isMostRecentEnabled;isSearchable;keyPrefix;name;apiname;url;package;typeId;typeRef;description;externalSharingModel;internalSharingModel;apexTriggerIds;apexTriggerRefs;fieldSets;layouts;flexiPages;limits;validationRules;webLinks;standardFields;customFieldIds;customFieldRefs;recordTypes;relationships;recordCount}class ae extends S{static get label(){return"Apex Trigger"}id;name;url;apiVersion;package;length;isActive;beforeInsert;afterInsert;beforeUpdate;afterUpdate;beforeDelete;afterDelete;afterUndelete;objectId;objectRef;hasSOQL;hasDML;hardCodedURLs;hardCodedIDs;createdDate;lastModifiedDate}class re extends S{static get label(){return"Custom Label"}id;name;package;label;category;isProtected;language;value;url;createdDate;lastModifiedDate}class ie extends S{static get label(){return"Flow or Process Builder"}id;name;url;apiVersion;currentVersionId;currentVersionRef;isLatestCurrentVersion;isVersionActive;versionsCount;description;type;isProcessBuilder;createdDate;lastModifiedDate}class ne extends E{id;name;url;version;apiVersion;totalNodeCount;dmlCreateNodeCount;dmlDeleteNodeCount;dmlUpdateNodeCount;screenNodeCount;isActive;description;type;runningMode;createdDate;lastModifiedDate;sobject;triggerType}class oe extends f{static get label(){return"Profile"}id;url;name;description;license;isCustom;package;memberCounts;createdDate;lastModifiedDate;nbFieldPermissions;nbObjectPermissions;type;importantPermissions}class le extends oe{static get label(){return"Permission Set or Permission Set Group"}isGroup;groupId}class ce extends f{static get label(){return"User"}id;url;name;lastLogin;numberFailedLogins;onLightningExperience;lastPasswordChange;profileId;profileRef;aggregateImportantPermissions;permissionSetIds;permissionSetRefs}class de extends f{static get label(){return"Public Group or Queue"}id;url;name;developerName;includeBosses;includeSubordinates;relatedId;nbDirectMembers;directUserIds;directUserRefs;directGroupIds;directGroupRefs;isPublicGroup;isQueue;type}class pe extends S{static get label(){return"Aura Component"}id;name;apiVersion;package;createdDate;lastModifiedDate;description;url}class ge extends S{static get label(){return"Lightning Web Component"}id;name;apiVersion;package;createdDate;lastModifiedDate;description;url}class ue extends f{static get label(){return"Permission Set License"}id;name;totalCount;usedCount;usedPercentage;remainingCount;permissionSetIds;permissionSetRefs;distinctActiveAssigneeCount;status;expirationDate;isAvailableForIntegrations;createdDate;lastModifiedDate;url}class he extends f{static get label(){return"Password Policy from a Profile"}lockoutInterval;maxLoginAttempts;minimumPasswordLength;minimumPasswordLifetime;obscure;passwordComplexity;passwordExpiration;passwordHistory;passwordQuestion;profileName}class me extends f{static get label(){return"Restrictions from Profile"}profileId;profileRef;ipRanges;loginHours}class fe extends E{static get label(){return"IP Range Restriction from Profile"}startAddress;endAddress;description;difference}class Se extends E{static get label(){return"Login Hour Restriction from Profile"}fromTime;toTime;day;difference}class Ee extends f{static get label(){return"Role"}id;name;apiname;url;parentId;parentRef;level;hasParent;activeMembersCount;activeMemberIds;activeMemberRefs;hasActiveMembers}class Ie extends S{static get label(){return"Visualforce Component"}id;name;apiVersion;hardCodedURLs;hardCodedIDs;package;createdDate;lastModifiedDate;description;url}class we extends S{static get label(){return"Visualforce Page"}id;name;apiVersion;hardCodedURLs;hardCodedIDs;isMobileReady;package;createdDate;lastModifiedDate;description;url}class Pe extends f{static get label(){return"Workflow"}id;name;url;description;actions;futureActions;emptyTimeTriggers;isActive;createdDate;lastModifiedDate;hasAction}const Re=(e,t,s=3)=>!!(t&&e&&s)&&(e-t)/3>=s,Te=e=>("number"!=typeof e||0!==e)&&(!e||(0===e.length||"string"==typeof e&&0===e.trim().length)),ye=[{id:0,description:"Not referenced anywhere",formula:e=>!1===e.dependencies?.hadError&&Te(e.dependencies?.referenced),errorMessage:"This component is not referenced anywhere (as we were told by the Dependency API). Please review the need to keep it in your org.",badField:"dependencies.referenced.length",applicable:[re,ie,B,pe,ge,Ie,we]},{id:1,description:"No reference anywhere for custom field",formula:e=>!0===e.isCustom&&!1===e.dependencies?.hadError&&Te(e.dependencies?.referenced),errorMessage:"This custom field is not referenced anywhere (as we were told by the Dependency API). Please review the need to keep it in your org.",badField:"dependencies.referenced.length",applicable:[G]},{id:2,description:"No reference anywhere for apex class",formula:e=>!1===e.isTest&&!1===e.dependencies?.hadError&&Te(e.dependencies?.referenced),errorMessage:"This apex class is not referenced anywhere (as we were told by the Dependency API). Please review the need to keep it in your org.",badField:"dependencies.referenced.length",applicable:[b]},{id:3,description:"Sorry, we had an issue with the Dependency API to gather the dependencies of this item",formula:e=>e.dependencies&&!0===e.dependencies.hadError,errorMessage:"Sorry, we had an issue with the Dependency API to gather the dependencies of this item.",badField:"dependencies.referenced.length",applicable:[G,b,re,ie,B,pe,ge,Ie,we]},{id:4,description:"API Version too old",formula:e=>Re(Ae.CurrentApiVersion,e.apiVersion),errorMessage:"The API version of this component is too old. Please update it to a newest version.",badField:"apiVersion",applicable:[b,ae,ie,pe,ge,we,Ie]},{id:5,description:"No assert in this Apex Test",formula:e=>!0===e.isTest&&0===e.nbSystemAsserts,errorMessage:"This apex test does not contain any assert! Best practices force you to define asserts in tests.",badField:"nbSystemAsserts",applicable:[b]},{id:6,description:"No description",formula:e=>Te(e.description),errorMessage:"This component does not have a description. Best practices force you to use the Description field to give some informative context about why and how it is used/set/govern.",badField:"description",applicable:[ie,B,pe,ge,we,Ie,Pe,te,$,ee]},{id:7,description:"No description for custom component",formula:e=>!0===e.isCustom&&Te(e.description),errorMessage:"This custom component does not have a description. Best practices force you to use the Description field to give some informative context about why and how it is used/set/govern.",badField:"description",applicable:[G,le,oe]},{id:8,description:"No explicit sharing in apex class",formula:e=>!1===e.isTest&&!0===e.isClass&&!e.specifiedSharing,errorMessage:"This Apex Class does not specify a sharing model. Best practices force you to specify with, without or inherit sharing to better control the visibility of the data you process in Apex.",badField:"specifiedSharing",applicable:[b]},{id:9,description:"Schedulable should be scheduled",formula:e=>!1===e.isScheduled&&!0===e.isSchedulable,errorMessage:"This Apex Class implements Schedulable but is not scheduled. What is the point? Is this class still necessary?",badField:"isScheduled",applicable:[b]},{id:10,description:"Not able to compile class",formula:e=>!0===e.needsRecompilation,errorMessage:"This Apex Class can not be compiled for some reason. You should try to recompile it. If the issue remains you need to consider refactorying this class or the classes that it is using.",badField:"name",applicable:[b]},{id:11,description:"No coverage for this class",formula:e=>!1===e.isTest&&(isNaN(e.coverage)||!e.coverage),errorMessage:"This Apex Class does not have any code coverage. Consider launching the corresponding tests that will bring some coverage. If you do not know which test to launch just run them all!",badField:"coverage",applicable:[b]},{id:12,description:"Coverage not enough",formula:e=>e.coverage>0&&e.coverage<.75,errorMessage:"This Apex Class does not have enough code coverage (less than 75% of lines are covered by successful unit tests). Maybe you ran not all the unit tests to cover this class entirely? If you did, then consider augmenting that coverage with new test methods.",badField:"coverage",applicable:[b]},{id:13,description:"At least one testing method failed",formula:e=>!0===e.isTest&&e.testFailedMethods&&e.testFailedMethods.length>0,errorMessage:"This Apex Test Class has at least one failed method.",badField:"testFailedMethods",applicable:[b]},{id:14,description:"Apex trigger should not contain SOQL statement",formula:e=>!0===e.hasSOQL,errorMessage:"This Apex Trigger contains at least one SOQL statement. Best practices force you to move any SOQL statement in dedicated Apex Classes that you would call from the trigger. Please update the code accordingly.",badField:"hasSOQL",applicable:[ae]},{id:15,description:"Apex trigger should not contain DML action",formula:e=>!0===e.hasDML,errorMessage:"This Apex Trigger contains at least one DML action. Best practices force you to move any DML action in dedicated Apex Classes that you would call from the trigger. Please update the code accordingly.",badField:"hasDML",applicable:[ae]},{id:16,description:"Apex Trigger should not contain logic",formula:e=>e.length>5e3,errorMessage:"Due to the massive number of source code (more than 5000 characters) in this Apex Trigger, we suspect that it contains logic. Best practices force you to move any logic in dedicated Apex Classes that you would call from the trigger. Please update the code accordingly.",badField:"length",applicable:[ae]},{id:17,description:"No direct member for this group",formula:e=>!e.nbDirectMembers||0===e.nbDirectMembers,errorMessage:"This public group (or queue) does not contain any direct members (users or sub groups). Is it empty on purpose? Maybe you should review its use in your org...",badField:"nbDirectMembers",applicable:[de]},{id:18,description:"Custom permset or profile with no member",formula:e=>!0===e.isCustom&&0===e.memberCounts,errorMessage:"This custom permission set (or custom profile) has no members. Is it empty on purpose? Maybe you should review its use in your org...",badField:"memberCounts",applicable:[le,oe]},{id:19,description:"Role with no active users",formula:e=>0===e.activeMembersCount,errorMessage:"This role has no active users assigned to it. Is it on purpose? Maybe you should review its use in your org...",badField:"activeMembersCount",applicable:[Ee]},{id:20,description:"Active user not under LEX",formula:e=>!1===e.onLightningExperience,errorMessage:"This user is still using Classic. Time to switch to Lightning for all your users, don't you think?",badField:"onLightningExperience",applicable:[ce]},{id:21,description:"Active user never logged",formula:e=>null===e.lastLogin,errorMessage:"This active user never logged yet. Time to optimize your licence cost!",badField:"lastLogin",applicable:[ce]},{id:22,description:"Workflow with no action",formula:e=>!1===e.hasAction,errorMessage:"This workflow has no action, please review it and potentially remove it.",badField:"hasAction",applicable:[Pe]},{id:23,description:"Workflow with empty time triggered list",formula:e=>e.emptyTimeTriggers.length>0,errorMessage:"This workflow is time triggered but with no time triggered action, please review it.",badField:"emptyTimeTriggers",applicable:[Pe]},{id:24,description:"Password policy with question containing password!",formula:e=>!0===e.passwordQuestion,errorMessage:"This profile password policy allows to have password in the question! Please change that setting as it is clearly a lack of security in your org!",badField:"passwordQuestion",applicable:[he]},{id:25,description:"Password policy with too big expiration",formula:e=>e.passwordExpiration>90,errorMessage:"This profile password policy allows to have password that expires after 90 days. Please consider having a shorter period of time for expiration if you policy.",badField:"passwordExpiration",applicable:[he]},{id:26,description:"Password policy with no expiration",formula:e=>0===e.passwordExpiration,errorMessage:"This profile password policy allows to have password that never expires. Why is that? Do you have this profile for technical users? Please reconsider this setting and use JWT authentication instead for technical users.",badField:"passwordExpiration",applicable:[he]},{id:27,description:"Password history too small",formula:e=>e.passwordHistory<3,errorMessage:"This profile password policy allows users to set their password with a too-short memory. For example, they can keep on using the same different password everytime you ask them to change it. Please increase this setting.",badField:"passwordHistory",applicable:[he]},{id:28,description:"Password minimum size too small",formula:e=>e.minimumPasswordLength<8,errorMessage:"This profile password policy allows users to set passwords with less than 8 charcaters. That minimum length is not strong enough. Please increase this setting.",badField:"minimumPasswordLength",applicable:[he]},{id:29,description:"Password complexity too weak",formula:e=>e.passwordComplexity<3,errorMessage:"This profile password policy allows users to set too-easy passwords. The complexity you choose is not storng enough. Please increase this setting.",badField:"passwordComplexity",applicable:[he]},{id:30,description:"No max login attempts set",formula:e=>void 0===e.maxLoginAttempts,errorMessage:"This profile password policy allows users to try infinitely to log in without locking the access. Please review this setting.",badField:"passwordExpiration",applicable:[he]},{id:31,description:"No lockout period set",formula:e=>void 0===e.lockoutInterval,errorMessage:"This profile password policy does not set a value for any locked out period. Please review this setting.",badField:"lockoutInterval",applicable:[he]},{id:32,description:"IP Range too large",formula:e=>e.ipRanges.filter((e=>e.difference>1e5)).length>0,errorMessage:"This profile includes an IP range that is to wide (more than 100.000 IP addresses!). If you set an IP Range it should be not that large. You could split that range into multiple ones. The risk is that you include an IP that is not part of your company. Please review this setting.",badField:"ipRanges",applicable:[me]},{id:33,description:"Login hours too large",formula:e=>e.loginHours.filter((e=>e.difference>1200)).length>0,errorMessage:"This profile includes a login hour that is to wide (more than 20 hours a day!). If you set a login hour it should reflect the reality. Please review this setting.",badField:"loginHours",applicable:[me]},{id:34,description:"Inactive component",formula:e=>!1===e.isActive,errorMessage:"This component is inactive, so why do not you just remove it from your org?",badField:"isActive",applicable:[ee,Z,ae,Pe]},{id:35,description:"No active version for this flow",formula:e=>!1===e.isVersionActive,errorMessage:"This flow does not have an active version, did you forgot to activate its latest version? or you do not need that flow anymore?",badField:"isVersionActive",applicable:[ie]},{id:36,description:"Too many versions under this flow",formula:e=>e.versionsCount>7,errorMessage:"This flow has more than seven versions. Maybe it is time to do some cleaning in this flow!",badField:"versionsCount",applicable:[ie]},{id:37,description:"Migrate this process builder",formula:e=>"Workflow"===e.currentVersionRef?.type,errorMessage:"Time to migrate this process builder to flow!",badField:"name",applicable:[ie]},{id:38,description:"No description for the current version of a flow",formula:e=>Te(e.currentVersionRef?.description),errorMessage:"This flow's current version does not have a description. Best practices force you to use the Description field to give some informative context about why and how it is used/set/govern.",badField:"currentVersionRef.description",applicable:[ie]},{id:39,description:"API Version too old for the current version of a flow",formula:e=>Re(Ae.CurrentApiVersion,e.currentVersionRef?.apiVersion),errorMessage:"The API version of this flow's current version is too old. Please update it to a newest version.",badField:"currentVersionRef.apiVersion",applicable:[ie]},{id:40,description:"This flow is running without sharing",formula:e=>"SystemModeWithoutSharing"===e.currentVersionRef?.runningMode,errorMessage:"The running mode of this version without sharing. With great power comes great responsabilities. Please check if this is REALLY needed.",badField:"currentVersionRef.runningMode",applicable:[ie]},{id:41,description:"Too many nodes in this version",formula:e=>e.currentVersionRef?.totalNodeCount>100,errorMessage:"There are more than one hundred of nodes in this flow. Please consider using Apex? or cut it into multiple sub flows?",badField:"currentVersionRef.totalNodeCount",applicable:[ie]},{id:42,description:"Near the limit",formula:e=>e.usedPercentage>=.8,errorMessage:"This limit is almost reached (>80%). Please review this.",badField:"usedPercentage",applicable:[W]},{id:43,description:"Almost all licenses are used",formula:e=>void 0!==e.usedPercentage&&e.usedPercentage>=.8,errorMessage:"The number of seats for this license is almost reached (>80%). Please review this.",badField:"usedPercentage",applicable:[ue]},{id:44,description:"You could have licenses to free up",formula:e=>e.remainingCount>0&&e.distinctActiveAssigneeCount!==e.usedCount,errorMessage:"The Used count from that permission set license does not match the number of disctinct active user assigned to the same license. Please check if you could free up some licenses!",badField:"distinctActiveAssigneeCount",applicable:[ue]},{id:45,description:"Role with a level >= 7",formula:e=>e.level>=7,errorMessage:"This role has a level in the Role Hierarchy which is seven or greater. Please reduce the maximum depth of the role hierarchy. Having that much levels has an impact on performance...",badField:"level",applicable:[Ee]},{id:46,description:"Hard-coded URL suspicion in this item",formula:e=>e.hardCodedURLs?.length>0||!1,errorMessage:"The source code of this item contains one or more hard coded URLs pointing to domains like salesforce.com or force.*",badField:"hardCodedURLs",applicable:[b,ae,G,Ie,we,te]},{id:47,description:"Hard-coded Salesforce IDs suspicion in this item",formula:e=>e.hardCodedIDs?.length>0||!1,errorMessage:"The source code of this item contains one or more hard coded Salesforce IDs",badField:"hardCodedIDs",applicable:[b,ae,G,Ie,we,te]},{id:48,description:"At least one successful testing method was very long",formula:e=>!0===e.isTest&&e.testPassedButLongMethods&&e.testPassedButLongMethods.length>0,errorMessage:"This Apex Test Class has at least one successful method which took more than 20 secondes to execute",badField:"testPassedButLongMethods",applicable:[b]}],Ce=new Map(ye.map((e=>[e.id,e]))),Ae={AllScoreRules:ye,GetScoreRule:e=>Ce.get(e),GetScoreRuleDescription:e=>Ce.get(e).description,CurrentApiVersion:(()=>{const e=new Date,t=e.getFullYear(),s=e.getMonth()+1;return 3*(t-2022)+53+(s<=2?0:s<=6?1:s<=10?2:3)})()};Object.freeze(Ae);class Oe extends E{static get label(){return"Application"}id;name;label;package}class be extends E{static get label(){return"Application Permission from Profile or Permission Set"}parentId;parentRef;appId;appRef;isAccessible;isVisible}class Me extends E{static get label(){return"Field Level Security from Profile or Permission Set"}parentId;parentRef;fieldApiName;isRead;isEdit}class De extends f{static get label(){return"Object Permissions from Profile or Permission Set"}parentId;parentRef;objectType;isRead;isCreate;isEdit;isDelete;isViewAll;isModifyAll}class _e extends E{static get label(){return"Organization"}id;name;type;isDeveloperEdition;isSandbox;isTrial;isProduction;localNamespace}class Le extends f{static get label(){return"Package"}id;name;namespace;type}class Ne extends t{_compress;_decompress;_encode;_decode;_storageSetItem;_storageGetItem;_storageRemoveItem;_storageKey;_storageKeys;_storageLength;constructor(e){super(),this._compress=e.compress,this._decompress=e.decompress,this._encode=e.encode,this._decode=e.decode,this._storageSetItem=e.storage.setItem,this._storageGetItem=e.storage.getItem,this._storageRemoveItem=e.storage.removeItem,this._storageKey=e.storage.key,this._storageLength=e.storage.length,this._storageKeys=e.storage.keys}has(e){const t=Ge(e),s=ve(e),a=this._getEntryFromCache(t);if(null===a)this._storageRemoveItem(t),this._storageRemoveItem(s);else{let e=!1;for(let t=0;t!1===e.endsWith("Ref")))),created:e}:{content:t,created:e};try{this._setItemToCache(a,JSON.stringify(i)),this._setItemToCache(s,JSON.stringify(r))}catch(e){this._storageRemoveItem(s),this._storageRemoveItem(a)}}}details(){return this._storageKeys().filter((e=>e.startsWith(Ue))).map((e=>{const t=this._getEntryFromCache(e),s=$e(e);return t?{name:s,isEmpty:0===t.length,isMap:"map"===t.type,length:t.length,created:t.created}:{name:s,isEmpty:!0,isMap:!1,length:0,created:0}}))}remove(e){this._storageRemoveItem(ve(e)),this._storageRemoveItem(Ge(e))}clear(){return this._storageKeys().filter((e=>e.startsWith(xe))).forEach((e=>this._storageRemoveItem(e)))}_setItemToCache=(e,t)=>{let s,a,r;try{s=this._encode(t),a=this._compress(s),r=ke(a),this._storageSetItem(e,r)}catch(t){throw new Error(`Error occured when trying to save the value for key ${e} with: hexValue.length=${r?.length||"N/A"}, compressedValue.length=${a?.length||"N/A"}, encodedValue.length=${s?.length||"N/A"}. Initiale error message was ${t.message}`)}};_getEntryFromCache=e=>{let t=null;try{const s=this._storageGetItem(e);if(s){const e=je(s),a=this._decompress(e);t=this._decode(a)}}catch(t){console.error(`Error occured when trying to get the value for key ${e}`,t)}if(!t)return null;try{const e=JSON.parse(t);return e.created&&Date.now()-e.created>Be?null:e}catch(e){return console.error(`Error occured when trying to parse the string: ${t}`,e),null}}}const xe="OrgCheck",Fe=`${xe}.`,Ue=`${xe}_`,ve=e=>e.startsWith(Fe)?e:Fe+e,Ge=e=>e.startsWith(Ue)?e:Ue+e,$e=e=>e.startsWith(Ue)?e.substring(Ue.length):e.startsWith(Fe)?e.substring(Fe.length):e,Be=864e5,We=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"],Ve=new Array(256);for(let e=0;e<256;e++)Ve[e]=`${We[e>>>4&15]}${We[15&e]}`;const ke=e=>{let t="";for(let s=0,a=e.length;s{const t=[];for(let s=0;s[e.caseSafeId(t.Id),{qualifiedApiName:t.EntityDefinition.QualifiedApiName,isCustomSetting:t.EntityDefinition.IsCustomSetting}]),(e=>!!e.EntityDefinition&&(!Qe.includes(e.EntityDefinition.KeyPrefix)&&!e.EntityDefinition.QualifiedApiName?.endsWith("_hd")))));s?.log(`Retrieving dependencies of ${o.length} custom fields...`);const c=await e.dependenciesQuery(await N.map(o,(t=>e.caseSafeId(t.Id))),s);s?.log(`Calling Tooling API Composite to get more information about these ${l.size} custom fields...`);const d=await e.readMetadataAtScale("CustomField",Array.from(l.keys()),[],s);s?.log(`Parsing ${d.length} custom fields...`);const p=new Map(await N.map(d,(t=>{const s=e.caseSafeId(t.Id),a=l.get(s),r=n.create({properties:{id:s,name:t.DeveloperName,label:t.Metadata.label,package:t.NamespacePrefix||"",description:t.Description,isCustom:!0,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,objectId:a.qualifiedApiName,tooltip:t.InlineHelpText,type:t.Metadata.type,length:t.Metadata.length,isUnique:!0===t.Metadata.unique,isEncrypted:null!==t.Metadata.encryptionScheme&&"None"!==t.Metadata.encryptionScheme,isExternalId:!0===t.Metadata.externalId,isIndexed:!0===t.Metadata.unique||!0===t.Metadata.externalId,defaultValue:t.Metadata.defaultValue,isRestrictedPicklist:t.Metadata.valueSet&&!0===t.Metadata.valueSet.restricted,formula:t.Metadata.formula,url:e.setupUrl(s,v.CUSTOM_FIELD,a.qualifiedApiName,e.getObjectType(a.qualifiedApiName,a.isCustomSetting))},dependencies:{data:c}});if(r.formula){const e=g.RemoveComments(r.formula);r.hardCodedURLs=g.FindHardCodedURLs(e),r.hardCodedIDs=g.FindHardCodedIDs(e)}return n.computeScore(r),[r.id,r]})));return s?.log("Done"),p}}class He extends D{async run(e,t,s){s?.log("Querying Tooling API about ExternalString in the org...");const a=await e.soqlQuery([{tooling:!0,string:"SELECT Id, Name, NamespacePrefix, Category, IsProtected, Language, MasterLabel, Value, CreatedDate, LastModifiedDate FROM ExternalString WHERE ManageableState IN ('installedEditable', 'unmanaged') "}],s),r=t.getInstance(re),i=a[0];s?.log(`Retrieving dependencies of ${i.length} custom labels...`);const n=await e.dependenciesQuery(await N.map(i,(t=>e.caseSafeId(t.Id))),s);s?.log(`Parsing ${i.length} custom labels...`);const o=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.createWithScore({properties:{id:s,name:t.Name,package:t.NamespacePrefix||"",category:t.Category,isProtected:!0===t.IsProtected,language:t.Language,label:t.MasterLabel,value:t.Value,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,url:e.setupUrl(s,v.CUSTOM_LABEL)},dependencies:{data:n}});return[a.id,a]})));return s?.log("Done"),o}}class Je extends D{async run(e,t,s,a){const r=t.getInstance(G),i=t.getInstance($),n=t.getInstance(z),o=t.getInstance(W),l=t.getInstance(ee),c=t.getInstance(te),d=t.getInstance(Z),p=t.getInstance(V),u=t.getInstance(se),h=a?.get("object"),m=h.split("__"),f=3===m.length?m[0]:"",S=await Promise.all([e.describe(h,s),e.soqlQuery([{tooling:!0,string:`SELECT Id, DurableId, DeveloperName, Description, NamespacePrefix, ExternalSharingModel, InternalSharingModel, (SELECT Id FROM ApexTriggers), (SELECT Id, MasterLabel, Description FROM FieldSets), (SELECT Id, Name, LayoutType FROM Layouts), (SELECT DurableId, Label, Max, Remaining, Type FROM Limits), (SELECT Id, Active, Description, ErrorDisplayField, ErrorMessage, ValidationName, NamespacePrefix, CreatedDate, LastModifiedDate FROM ValidationRules), (SELECT Id, Name, Url, LinkType, OpenType, Description, CreatedDate, LastModifiedDate, NamespacePrefix FROM WebLinks) FROM EntityDefinition WHERE QualifiedApiName = '${h}' `+(f?`AND NamespacePrefix = '${f}' `:"")+"LIMIT 1"},{tooling:!0,string:`SELECT DurableId, QualifiedApiName, Description, IsIndexed FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName = '${h}' `+(f?`AND EntityDefinition.NamespacePrefix = '${f}' `:""),queryMoreField:"DurableId"}],s),e.recordCount(h,s)]),E=S[0],I=e.getObjectType(E.name,E.customSetting),w=S[1][0][0];if(!w)throw new TypeError(`No entity definition record found for: ${h}`);const P=S[1][1],R=S[2],T=[],y=new Map;await N.forEach(P,(t=>{if(t&&t.DurableId&&t.DurableId.split&&t.DurableId.includes){const s=e.caseSafeId(t.DurableId.split(".")[1]);t.DurableId?.includes(".00N")?T.push(s):y.set(t.QualifiedApiName,{id:s,description:t.Description,isIndexed:t.IsIndexed})}}));const C=await N.map(E.fields,(t=>{const s=y.get(t.name);return r.createWithScore({properties:{id:s.id,name:t.label,label:t.label,description:s.description,tooltip:t.inlineHelpText,type:t.type,length:t.length,isUnique:t.unique,isEncrypted:t.encrypted,isExternalId:t.externalId,isIndexed:s.isIndexed,defaultValue:t.defaultValue,formula:t.calculatedFormula,url:e.setupUrl(s.id,v.STANDARD_FIELD,w.DurableId,I)}})}),(e=>y.has(e.name))),A=await N.map(w.ApexTriggers?.records,(t=>e.caseSafeId(t.Id))),O=await N.map(w.FieldSets?.records,(t=>i.createWithScore({properties:{id:e.caseSafeId(t.Id),label:t.MasterLabel,description:t.Description,url:e.setupUrl(t.Id,v.FIELD_SET,w.DurableId)}}))),b=await N.map(w.Layouts?.records,(t=>n.createWithScore({properties:{id:e.caseSafeId(t.Id),name:t.Name,type:t.LayoutType,url:e.setupUrl(t.Id,v.PAGE_LAYOUT,w.DurableId)}}))),M=await N.map(w.Limits?.records,(t=>o.createWithScore({properties:{id:e.caseSafeId(t.DurableId),label:t.Label,max:t.Max,remaining:t.Remaining,used:t.Max-t.Remaining,usedPercentage:(t.Max-t.Remaining)/t.Max,type:t.Type}}))),D=await N.map(w.ValidationRules?.records,(t=>l.createWithScore({properties:{id:e.caseSafeId(t.Id),name:t.ValidationName,isActive:t.Active,description:t.Description,errorDisplayField:t.ErrorDisplayField,errorMessage:t.ErrorMessage,package:t.NamespacePrefix||"",createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,url:e.setupUrl(t.Id,v.VALIDATION_RULE)}}))),_=await N.map(w.WebLinks?.records,(t=>c.createWithScore({properties:{id:e.caseSafeId(t.Id),name:t.Name,hardCodedURLs:g.FindHardCodedURLs(t.Url),hardCodedIDs:g.FindHardCodedIDs(t.Url),type:t.LinkType,behavior:t.OpenType,package:t.NamespacePrefix,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,description:t.Description,url:e.setupUrl(t.Id,v.WEB_LINK,w.DurableId)}}))),L=await N.map(E.recordTypeInfos,(t=>d.createWithScore({properties:{id:e.caseSafeId(t.recordTypeId),name:t.name,developerName:t.developerName,isActive:t.active,isAvailable:t.available,isDefaultRecordTypeMapping:t.defaultRecordTypeMapping,isMaster:t.master,url:e.setupUrl(t.recordTypeId,v.RECORD_TYPE,w.DurableId)}}))),x=await N.map(E.childRelationships,(e=>p.createWithScore({properties:{name:e.relationshipName,childObject:e.childSObject,fieldName:e.field,isCascadeDelete:e.cascadeDelete,isRestrictedDelete:e.restrictedDelete}})),(e=>null!==e.relationshipName)),F=u.createWithScore({properties:{id:w.DurableId,label:E.label,labelPlural:E.labelPlural,isCustom:E.custom,isFeedEnabled:E.feedEnabled,isMostRecentEnabled:E.mruEnabled,isSearchable:E.searchable,keyPrefix:E.keyPrefix,name:w.DeveloperName,apiname:E.name,package:w.NamespacePrefix||"",typeId:I,description:w.Description,externalSharingModel:w.ExternalSharingModel,internalSharingModel:w.InternalSharingModel,apexTriggerIds:A,fieldSets:O,limits:M,layouts:b,validationRules:D,webLinks:_,standardFields:C,customFieldIds:T,recordTypes:L,relationships:x,recordCount:R,url:e.setupUrl(w.Id,I)}});return s?.log("Done"),F}}class Ye extends D{async run(e,t,s){s?.log("Querying REST API about ObjectPermissions in the org...");const a=await e.soqlQuery([{string:"SELECT ParentId, Parent.IsOwnedByProfile, Parent.ProfileId, SobjectType, CreatedDate, LastModifiedDate,PermissionsRead, PermissionsCreate, PermissionsEdit, PermissionsDelete, PermissionsViewAllRecords, PermissionsModifyAllRecords FROM ObjectPermissions"}],s),r=t.getInstance(De),i=a[0];s?.log(`Parsing ${i.length} object permissions...`);const n=new Map(await N.map(i,(t=>{const s=r.create({properties:{parentId:e.caseSafeId(!0===t.Parent.IsOwnedByProfile?t.Parent.ProfileId:t.ParentId),objectType:t.SobjectType,isRead:t.PermissionsRead,isCreate:t.PermissionsCreate,isEdit:t.PermissionsEdit,isDelete:t.PermissionsDelete,isViewAll:t.PermissionsViewAllRecords,isModifyAll:t.PermissionsModifyAllRecords,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate}});return[`${s.parentId}_${s.objectType}`,s]}),(e=>null!==e.Parent)));return s?.log("Done"),n}}class Xe extends D{async run(e,t,s){s?.log("Querying REST API about SetupEntityAccess for TabSet in the org...");const a=await e.soqlQuery([{string:"SELECT ApplicationId, IsAccessible, IsVisible FROM AppMenuItem WHERE Type = 'TabSet' "},{string:"SELECT SetupEntityId, ParentId, Parent.IsOwnedByProfile, Parent.ProfileId FROM SetupEntityAccess WHERE SetupEntityType = 'TabSet' "}],s),r=t.getInstance(be),i=a[0],n=a[1];s?.log(`Parsing ${i.length} Application Menu Items...`);const o=new Map(await N.map(i,(t=>[e.caseSafeId(t.ApplicationId),{a:t.IsAccessible,v:t.IsVisible}])));s?.log(`Parsing ${n.length} Application Menu Items...`);const l=new Map(await N.map(n,(t=>{const s=e.caseSafeId(t.SetupEntityId),a=e.caseSafeId(t.Parent.IsOwnedByProfile?t.Parent.ProfileId:t.ParentId),i=o.get(s);return[`${s}-${a}`,r.create({properties:{appId:s,parentId:a,isAccessible:i.a,isVisible:i.v}})]}),(t=>o.has(e.caseSafeId(t.SetupEntityId)))));return s?.log("Done"),l}}class Ke extends D{async run(e,t,s){const a=t.getInstance(se);s?.log("Performing a global describe and in parallel a SOQL query to EntityDefinition...");const r=await Promise.all([e.describeGlobal(s),e.soqlQuery([{string:"SELECT DurableId, NamespacePrefix, DeveloperName, QualifiedApiName, ExternalSharingModel, InternalSharingModel FROM EntityDefinition WHERE keyPrefix <> null AND DeveloperName <> null AND (NOT(keyPrefix IN ('00a', '017', '02c', '0D5', '1CE'))) AND (NOT(QualifiedApiName like '%_hd')) ",tooling:!0,queryMoreField:"DurableId"}],s)]),i=r[0],n=r[1][0],o={},l=await N.map(n,(e=>(o[e.QualifiedApiName]=e,e.QualifiedApiName)));s?.log(`Parsing ${i.length} objects...`);const c=new Map(await N.map(i,(t=>{const s=e.getObjectType(t.name,t.customSetting),r=o[t.name],i=a.create({properties:{id:t.name,label:t.label,name:r.DeveloperName,apiname:t.name,package:r.NamespacePrefix||"",typeId:s,externalSharingModel:r.ExternalSharingModel,internalSharingModel:r.InternalSharingModel,url:e.setupUrl(r.DurableId,s)}});return[i.id,i]}),(e=>!!l?.includes(e.name))));return s?.log("Done"),c}}const ze=[{id:j,label:"Standard Object"},{id:Q,label:"Custom Object"},{id:q,label:"External Object"},{id:H,label:"Custom Setting"},{id:J,label:"Custom Metadata Type"},{id:Y,label:"Platform Event"},{id:X,label:"Knowledge Article"},{id:K,label:"Big Object"}];class Ze extends D{async run(e,t,s){const a=t.getInstance(k);return new Map(ze.map((e=>[e.id,a.create({properties:{id:e.id,label:e.label}})])))}}const et="Production",tt="Developer Edition",st="Sandbox",at="Trial";class rt extends D{async run(e,t,s){s?.log("Querying REST API about Organization in the org...");const a=await e.soqlQuery([{string:"SELECT Id, Name, IsSandbox, OrganizationType, TrialExpirationDate, NamespacePrefix FROM Organization LIMIT 1"}],s);s?.log(`Received result=${JSON.stringify(a)}`),s?.log("We need to get the first result and from there the first record...");const r=a[0][0];s?.log("Parsing the result...");const i=t.getInstance(_e);let n;n="Developer Edition"===r.OrganizationType?tt:!0===r.IsSandbox?st:!1===r.IsSandbox&&r.TrialExpirationDate?at:et;const o=i.create({properties:{id:e.caseSafeId(r.Id),name:r.Name,type:n,isDeveloperEdition:n===tt,isSandbox:n===st,isTrial:n===at,isProduction:n===et,localNamespace:r.NamespacePrefix||""}});return s?.log("Done"),o}}class it extends D{async run(e,t,s,a){const r=a?.get("permissions");s?.log("Querying REST API about UserPermissionAccess in the org...");const i=(await e.soqlQuery([{string:`SELECT ${r.map((e=>`Permissions${e}`)).join(", ")} FROM UserPermissionAccess LIMIT 1`}],s))[0][0];return s?.log("Parsing the results..."),new Map(await N.map(Object.keys(i),(e=>[e,i[e]]),(e=>e.startsWith("Permissions"))))}}class nt extends D{async run(e,t,s){s?.log("Querying Tooling API about InstalledSubscriberPackage and REST API about Organization in the org...");const a=await e.soqlQuery([{tooling:!0,string:"SELECT Id, SubscriberPackage.NamespacePrefix, SubscriberPackage.Name FROM InstalledSubscriberPackage "},{string:"SELECT NamespacePrefix FROM Organization LIMIT 1 "}],s),r=t.getInstance(Le),i=a[0];s?.log(`Parsing ${i.length} installed packages...`);const n=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.create({properties:{id:s,name:t.SubscriberPackage.Name,namespace:t.SubscriberPackage.NamespacePrefix,type:"Installed"}});return[a.id,a]}))),o=a[1][0].NamespacePrefix;return o&&(s?.log(`Adding your local package ${o}...`),n.set(o,r.create({properties:{id:o,name:o,namespace:o,type:"Local"}}))),s?.log("Done"),n}}class ot extends D{async run(e,t,s){s?.log("Querying REST API about PermissionSet, PermissionSetAssignment and PermissionSet (with a PermissionSetGroupId populated) in the org...");const a=await e.soqlQuery([{string:"SELECT Id, Name, Description, IsCustom, License.Name, NamespacePrefix, Type, PermissionsApiEnabled, PermissionsViewSetup, PermissionsModifyAllData, PermissionsViewAllData, CreatedDate, LastModifiedDate FROM PermissionSet WHERE IsOwnedByProfile = FALSE ORDER BY Id LIMIT 2000"},{byPasses:["INVALID_TYPE"],string:"SELECT Id, PermissionSetGroupId, PermissionSetGroup.Description FROM PermissionSet WHERE PermissionSetGroupId != null ORDER BY Id LIMIT 2000"},{string:"SELECT ParentId, COUNT(SobjectType) CountObject FROM ObjectPermissions WHERE Parent.IsOwnedByProfile = FALSE GROUP BY ParentId ORDER BY ParentId LIMIT 2000"},{string:"SELECT ParentId, COUNT(Field) CountField FROM FieldPermissions WHERE Parent.IsOwnedByProfile = FALSE GROUP BY ParentId ORDER BY ParentId LIMIT 2000"},{string:"SELECT PermissionSetId, COUNT(Id) CountAssignment FROM PermissionSetAssignment WHERE PermissionSet.IsOwnedByProfile = FALSE GROUP BY PermissionSetId ORDER BY PermissionSetId LIMIT 2000"}],s),r=a[0],i=a[1],n=a[2],o=a[3],l=a[4],c=t.getInstance(le);s?.log(`Parsing ${r.length} permission sets...`);const d=new Map(await N.map(r,(t=>{const s=e.caseSafeId(t.Id),a="Group"===t.Type,r=c.create({properties:{id:s,name:t.Name,description:t.Description,license:t.License?t.License.Name:"",isCustom:t.IsCustom,package:t.NamespacePrefix||"",memberCounts:0,isGroup:a,type:a?"Permission Set Group":"Permission Set",createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,nbFieldPermissions:0,nbObjectPermissions:0,importantPermissions:{apiEnabled:!0===t.PermissionsApiEnabled,viewSetup:!0===t.PermissionsViewSetup,modifyAllData:!0===t.PermissionsModifyAllData,viewAllData:!0===t.PermissionsViewAllData},url:!1===a?e.setupUrl(s,v.PERMISSION_SET):""}});return[r.id,r]})));return s?.log(`Parsing ${i.length} permission set groups, ${n.length} object permissions and ${o.length} field permissions...`),await Promise.all([N.forEach(i,(t=>{const s=e.caseSafeId(t.Id),a=e.caseSafeId(t.PermissionSetGroupId);if(d.has(s)){const t=d.get(s);t.isGroup=!0,t.groupId=a,t.url=e.setupUrl(a,v.PERMISSION_SET_GROUP)}})),N.forEach(n,(t=>{const s=e.caseSafeId(t.ParentId);if(d.has(s)){d.get(s).nbObjectPermissions=t.CountObject}})),N.forEach(o,(t=>{const s=e.caseSafeId(t.ParentId);if(d.has(s)){d.get(s).nbFieldPermissions=t.CountField}})),N.forEach(l,(t=>{const s=e.caseSafeId(t.PermissionSetId);if(d.has(s)){d.get(s).memberCounts=t.CountAssignment}}))]),s?.log(`Computing the score for ${d.size} permission sets...`),await N.forEach(d,(e=>{c.computeScore(e)})),s?.log("Done"),d}}class lt extends D{async run(e,t,s){s?.log("Querying REST API about PermissionSet with IsOwnedByProfile=true in the org...");const a=await e.soqlQuery([{string:"SELECT ProfileId, Profile.Name, Profile.Description, IsCustom, License.Name, NamespacePrefix, PermissionsApiEnabled, PermissionsViewSetup, PermissionsModifyAllData, PermissionsViewAllData, CreatedDate, LastModifiedDate FROM PermissionSet WHERE isOwnedByProfile = TRUE ORDER BY ProfileId LIMIT 2000"},{string:"SELECT Parent.ProfileId, COUNT(SobjectType) CountObject FROM ObjectPermissions WHERE Parent.IsOwnedByProfile = TRUE GROUP BY Parent.ProfileId ORDER BY Parent.ProfileId LIMIT 2000"},{string:"SELECT Parent.ProfileId, COUNT(Field) CountField FROM FieldPermissions WHERE Parent.IsOwnedByProfile = TRUE GROUP BY Parent.ProfileId ORDER BY Parent.ProfileId LIMIT 2000"},{string:"SELECT PermissionSet.ProfileId, COUNT(Id) CountAssignment FROM PermissionSetAssignment WHERE PermissionSet.IsOwnedByProfile = TRUE GROUP BY PermissionSet.ProfileId ORDER BY PermissionSet.ProfileId LIMIT 2000"}],s),r=a[0],i=a[1],n=a[2],o=a[3],l=t.getInstance(oe);s?.log(`Parsing ${r.length} profiles...`);const c=new Map(await N.map(r,(t=>{const s=e.caseSafeId(t.ProfileId),a=l.create({properties:{id:s,name:t.Profile.Name,description:t.Profile.Description,license:t.License?t.License.Name:"",isCustom:t.IsCustom,package:t.NamespacePrefix||"",memberCounts:0,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,nbFieldPermissions:0,nbObjectPermissions:0,type:"Profile",importantPermissions:{apiEnabled:!0===t.PermissionsApiEnabled,viewSetup:!0===t.PermissionsViewSetup,modifyAllData:!0===t.PermissionsModifyAllData,viewAllData:!0===t.PermissionsViewAllData},url:e.setupUrl(s,v.PROFILE)}});return[a.id,a]})));return s?.log(`Parsing ${i.length} object permissions, ${n.length} field permissions and ${o.length} assignments...`),await Promise.all([N.forEach(i,(t=>{const a=e.caseSafeId(t.ProfileId);if(c.has(a)){c.get(a).nbObjectPermissions=t.CountObject}else s.log(`[objectPermissionRecords] Not Profile found with ID: ${a}, and we had Record=${JSON.stringify(t)}`)})),N.forEach(n,(t=>{const a=e.caseSafeId(t.ProfileId);if(c.has(a)){c.get(a).nbFieldPermissions=t.CountField}else s.log(`[fieldPermissionRecords] Not Profile found with ID: ${a}, and we had Record=${JSON.stringify(t)}`)})),N.forEach(o,(t=>{const a=e.caseSafeId(t.ProfileId);if(c.has(a)){c.get(a).memberCounts=t.CountAssignment}else s.log(`[assignmentRecords] Not Profile found with ID: ${a}, and we had Record=${JSON.stringify(t)}`)}))]),s?.log(`Computing the score for ${c.size} profiles...`),await N.forEach(c,(e=>{l.computeScore(e)})),s?.log("Done"),c}}const ct=e=>e?.split(".").reduce(((e,t,s,a)=>e+Number(t)*Math.pow(255,a.length-1-s)),0),dt=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"];class pt extends D{async run(e,t,s){s?.log("Querying REST API about Profile in the org...");const a=(await e.soqlQuery([{string:"SELECT Id FROM Profile"}],s))[0];s?.log(`Parsing ${a.length} Profiles...`);const r=await N.map(a,(e=>e.Id)),i=t.getInstance(me),n=t.getInstance(fe),o=t.getInstance(Se);s?.log(`Calling Tooling API Composite to get more information about these ${r.length} profiles...`);const l=await e.readMetadataAtScale("Profile",r,["UNKNOWN_EXCEPTION"],s);s?.log(`Parsing ${l.length} profile restrictions...`);const c=new Map(await N.map(l,(async t=>{const s=e.caseSafeId(t.Id);let a,r;a=t.Metadata.loginHours?await N.map(dt,(e=>{const s=t.Metadata.loginHours[e+"Start"],a=t.Metadata.loginHours[e+"End"];return o.create({properties:{day:e,fromTime:("0"+Math.floor(s/60)).slice(-2)+":"+("0"+s%60).slice(-2),toTime:("0"+Math.floor(a/60)).slice(-2)+":"+("0"+a%60).slice(-2),difference:a-s}})})):[],r=t.Metadata.loginIpRanges&&t.Metadata.loginIpRanges.length>0?await N.map(t.Metadata.loginIpRanges,(e=>{const t=ct(e.startAddress),s=ct(e.endAddress);return n.create({properties:{startAddress:e.startAddress,endAddress:e.endAddress,description:e.description||"(empty)",difference:s-t+1}})})):[];const l=i.createWithScore({properties:{profileId:s,ipRanges:r,loginHours:a}});return[l.profileId,l]})));return s?.log("Done"),c}}class gt extends D{async run(e,t,s){s?.log("Querying Metadata API about ProfilePasswordPolicy...");const a=await e.readMetadata([{type:"ProfilePasswordPolicy",members:["*"]}],s),r=a?.get("ProfilePasswordPolicy")||[];if(!r)return new Map;const i=t.getInstance(he);s?.log(`Parsing ${r.length} profile password policies...`);const n=new Map(await N.map(r,(e=>{const t=i.createWithScore({properties:{lockoutInterval:parseInt(e.lockoutInterval,10),maxLoginAttempts:parseInt(e.maxLoginAttempts,10),minimumPasswordLength:parseInt(e.minimumPasswordLength,10),minimumPasswordLifetime:"true"===e.minimumPasswordLifetime,obscure:"true"===e.obscure,passwordComplexity:parseInt(e.passwordComplexity,10),passwordExpiration:parseInt(e.passwordExpiration,10),passwordHistory:parseInt(e.passwordHistory,10),passwordQuestion:"1"===e.passwordQuestion,profileName:e.profile}});return[t.profileName,t]}),(e=>"string"==typeof e.profile&&""!==e.profile)));return s?.log("Done"),n}}class ut extends D{async run(e,t,s){s?.log("Querying REST API about internal active User in the org...");const a=await e.soqlQuery([{string:"SELECT Id, Name, ProfileId, LastLoginDate, LastPasswordChangeDate, NumberOfFailedLogins, UserPreferencesLightningExperiencePreferred, (SELECT PermissionSetId FROM PermissionSetAssignments WHERE PermissionSet.IsOwnedByProfile = false) FROM User WHERE IsActive = true AND ContactId = NULL AND Profile.Id != NULL "}],s),r=t.getInstance(ce),i=a[0];s?.log(`Parsing ${i.length} users...`);const n=new Map(await N.map(i,(async t=>{const s=e.caseSafeId(t.Id),a=await N.map(t?.PermissionSetAssignments?.records,(t=>e.caseSafeId(t.PermissionSetId))),i=r.createWithScore({properties:{id:s,name:t.Name,lastLogin:t.LastLoginDate,numberFailedLogins:t.NumberOfFailedLogins,onLightningExperience:t.UserPreferencesLightningExperiencePreferred,lastPasswordChange:t.LastPasswordChangeDate,profileId:e.caseSafeId(t.ProfileId),permissionSetIds:a,url:e.setupUrl(s,v.USER)}});return[i.id,i]})));return s?.log("Done"),n}}class ht extends D{async run(e,t,s){s?.log("Querying Tooling API about ApexPage in the org...");const a=await e.soqlQuery([{tooling:!0,string:"SELECT Id, Name, ApiVersion, NamespacePrefix, Description, IsAvailableInTouch, Markup, CreatedDate, LastModifiedDate FROM ApexPage WHERE ManageableState IN ('installedEditable', 'unmanaged')"}],s),r=t.getInstance(we),i=a[0];s?.log(`Retrieving dependencies of ${i.length} visualforce pages...`);const n=await e.dependenciesQuery(await N.map(i,(t=>e.caseSafeId(t.Id))),s);s?.log(`Parsing ${i.length} visualforce pages...`);const o=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.create({properties:{id:s,name:t.Name,apiVersion:t.ApiVersion,isMobileReady:t.IsAvailableInTouch,package:t.NamespacePrefix||"",createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,description:t.Description,url:e.setupUrl(s,v.VISUAL_FORCE_PAGE)},dependencies:{data:n}});if(t.Markup){const e=g.RemoveComments(t.Markup);a.hardCodedURLs=g.FindHardCodedURLs(e),a.hardCodedIDs=g.FindHardCodedIDs(e)}return r.computeScore(a),[a.id,a]})));return s?.log("Done"),o}}class mt extends D{async run(e,t,s){s?.log("Querying Tooling API about ApexComponent in the org...");const a=await e.soqlQuery([{tooling:!0,string:"SELECT Id, Name, ApiVersion, NamespacePrefix, Description, Markup, CreatedDate, LastModifiedDate FROM ApexComponent WHERE ManageableState IN ('installedEditable', 'unmanaged') "}],s),r=t.getInstance(Ie),i=a[0];s?.log(`Retrieving dependencies of ${i.length} visualforce components...`);const n=await e.dependenciesQuery(await N.map(i,(t=>e.caseSafeId(t.Id))),s);s?.log(`Parsing ${i.length} visualforce components...`);const o=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.create({properties:{id:s,name:t.Name,apiVersion:t.ApiVersion,package:t.NamespacePrefix||"",createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,description:t.Description,url:e.setupUrl(s,v.VISUAL_FORCE_COMPONENT)},dependencies:{data:n}});if(t.Markup){const e=g.RemoveComments(t.Markup);a.hardCodedURLs=g.FindHardCodedURLs(e),a.hardCodedIDs=g.FindHardCodedIDs(e)}return r.computeScore(a),[a.id,a]})));return s?.log("Done"),o}}class ft extends D{async run(e,t,s){s?.log("Querying Tooling API about AuraDefinitionBundle in the org...");const a=await e.soqlQuery([{tooling:!0,string:"SELECT Id, MasterLabel, ApiVersion, NamespacePrefix, Description, CreatedDate, LastModifiedDate FROM AuraDefinitionBundle WHERE ManageableState IN ('installedEditable', 'unmanaged') "}],s),r=t.getInstance(pe),i=a[0];s?.log(`Retrieving dependencies of ${i.length} lightning aura components...`);const n=await e.dependenciesQuery(await N.map(i,(t=>e.caseSafeId(t.Id))),s);s?.log(`Parsing ${i.length} lightning aura components...`);const o=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.createWithScore({properties:{id:s,name:t.MasterLabel,apiVersion:t.ApiVersion,package:t.NamespacePrefix||"",createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,description:t.Description,url:e.setupUrl(s,v.AURA_WEB_COMPONENT)},dependencies:{data:n}});return[a.id,a]})));return s?.log("Done"),o}}class St extends D{async run(e,t,s){s?.log("Querying Tooling API about LightningComponentBundle in the org...");const a=await e.soqlQuery([{tooling:!0,string:"SELECT Id, MasterLabel, ApiVersion, NamespacePrefix, Description, CreatedDate, LastModifiedDate FROM LightningComponentBundle WHERE ManageableState IN ('installedEditable', 'unmanaged') "}],s),r=t.getInstance(ge),i=a[0];s?.log(`Retrieving dependencies of ${i.length} lightning web components...`);const n=await e.dependenciesQuery(await N.map(i,(t=>e.caseSafeId(t.Id))),s);s?.log(`Parsing ${i.length} lightning web components...`);const o=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.createWithScore({properties:{id:s,name:t.MasterLabel,apiVersion:t.ApiVersion,package:t.NamespacePrefix||"",createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,description:t.Description,url:e.setupUrl(s,v.LIGHTNING_WEB_COMPONENT)},dependencies:{data:n}});return[a.id,a]})));return s?.log("Done"),o}}class Et extends D{async run(e,t,s){s?.log("Querying Tooling API about FlexiPage in the org...");const a=await e.soqlQuery([{tooling:!0,string:"SELECT Id, MasterLabel, EntityDefinition.QualifiedApiName, Type, NamespacePrefix, Description, CreatedDate, LastModifiedDate FROM FlexiPage WHERE ManageableState IN ('installedEditable', 'unmanaged') "}],s),r=t.getInstance(B),i=a[0];s?.log(`Retrieving dependencies of ${i.length} lightning pages...`);const n=await e.dependenciesQuery(await N.map(i,(t=>e.caseSafeId(t.Id))),s);s?.log(`Parsing ${i.length} lightning pages...`);const o=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.createWithScore({properties:{id:s,name:t.MasterLabel,type:t.Type,package:t.NamespacePrefix||"",createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,description:t.Description,objectId:t.EntityDefinition?.QualifiedApiName||"",url:e.setupUrl(s,v.LIGHTNING_PAGE)},dependencies:{data:n}});return[a.id,a]})));return s?.log("Done"),o}}class It extends D{async run(e,t,s){s?.log("Querying REST API about Group in the org...");const a=await e.soqlQuery([{string:"SELECT Id, Name, DeveloperName, DoesIncludeBosses, Type, RelatedId, Related.Name, (SELECT UserOrGroupId From GroupMembers)FROM Group "}],s),r=t.getInstance(de),i=a[0];s?.log(`Parsing ${i.length} groups...`);const n=new Map(await N.map(i,(async t=>{const s=e.caseSafeId(t.Id);let a,i,n,o,l,c;switch(t.Type){case"Regular":case"Queue":a="Regular"===t.Type?v.PUBLIC_GROUP:v.QUEUE,i=t.Name,n=t.DeveloperName,o=t.DoesIncludeBosses;break;case"Role":case"RoleAndSubordinates":case"RoleAndSubordinatesInternal":a=v.ROLE,i=t.Related.Name,l="Role"!==t.Type,c=e.caseSafeId(t.RelatedId);break;default:i=t.Type,a=v.TECHNICAL_GROUP}const d=[],p=[];t.GroupMembers&&t.GroupMembers.records&&t.GroupMembers.records.length>0&&await N.forEach(t.GroupMembers.records,(t=>{const s=e.caseSafeId(t.UserOrGroupId);(s.startsWith("005")?d:p).push(s)}));const g=r.createWithScore({properties:{id:s,name:i,developerName:n,type:a,isPublicGroup:"Regular"===t.Type,isQueue:"Queue"===t.Type,nbDirectMembers:d.length+p.length,directUserIds:d,directGroupIds:p,includeBosses:!0===o,includeSubordinates:!0===l,relatedId:c,url:e.setupUrl(c??s,a)}});return[g.id,g]})));return s?.log("Done"),n}}class wt extends D{async run(e,t,s){s?.log("Querying Tooling API about ApexClass, ApexCodeCoverage, ApexCodeCoverageAggregate and AsyncApexJob in the org...");const a=await e.soqlQuery([{string:"SELECT Id, Name, ApiVersion, NamespacePrefix, Body, LengthWithoutComments, SymbolTable, CreatedDate, LastModifiedDate FROM ApexClass WHERE ManageableState IN ('installedEditable', 'unmanaged') ",tooling:!0},{string:"SELECT ApexClassOrTriggerId, ApexTestClassId FROM ApexCodeCoverage GROUP BY ApexClassOrTriggerId, ApexTestClassId ",queryMoreField:"CreatedDate",tooling:!0},{string:"SELECT ApexClassorTriggerId, NumLinesCovered, NumLinesUncovered, Coverage FROM ApexCodeCoverageAggregate ",tooling:!0},{string:"SELECT ApexClassId FROM AsyncApexJob WHERE JobType = 'ScheduledApex' "},{string:"SELECT id, ApexClassId, MethodName, ApexTestRunResult.CreatedDate, RunTime, Outcome, StackTrace, (SELECT Cpu, AsyncCalls, Sosl, Soql, QueryRows, DmlRows, Dml FROM ApexTestResults LIMIT 1) FROM ApexTestResult WHERE (Outcome != 'Pass' OR RunTime > 20000) AND ApexTestRunResult.Status = 'Completed' AND ApexClass.ManageableState IN ('installedEditable', 'unmanaged') ORDER BY ApexClassId, ApexTestRunResult.CreatedDate desc, MethodName ",tooling:!0}],s),r=t.getInstance(b),i=t.getInstance(O),n=a[0],o=a[1],l=a[2],c=a[3],d=a[4];s?.log(`Retrieving dependencies of ${n.length} apex classes...`);const p=await e.dependenciesQuery(await N.map(n,(t=>e.caseSafeId(t.Id))),s);s?.log(`Parsing ${n.length} apex classes...`);const u=new Map(await N.map(n,(async t=>{const s=e.caseSafeId(t.Id),a=r.create({properties:{id:s,name:t.Name,apiVersion:t.ApiVersion,package:t.NamespacePrefix||"",isTest:!1,isAbstract:!1,isClass:!0,isEnum:!1,isInterface:!1,isSchedulable:!1,isScheduled:!1,length:t.LengthWithoutComments,needsRecompilation:!t.SymbolTable,coverage:0,relatedTestClasses:[],relatedClasses:[],createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,url:e.setupUrl(s,v.APEX_CLASS)},dependencies:{data:p}});if(t.SymbolTable&&(a.innerClassesCount=t.SymbolTable.innerClasses?.length||0,a.interfaces=t.SymbolTable.interfaces,a.isSchedulable=t.SymbolTable.interfaces?.includes("System.Schedulable")??!1,a.methodsCount=t.SymbolTable.methods?.length||0,a.extends=t.SymbolTable.parentClass,t.SymbolTable.tableDeclaration&&(a.annotations=t.SymbolTable.tableDeclaration.annotations?.map((e=>e?.name??e)),await N.forEach(t.SymbolTable.tableDeclaration.modifiers,(e=>{switch(e){case"with sharing":a.specifiedSharing="with";break;case"without sharing":a.specifiedSharing="without";break;case"inherited sharing":a.specifiedSharing="inherited";break;case"public":a.specifiedAccess="public";break;case"private":a.specifiedAccess="private";break;case"global":a.specifiedAccess="global";break;case"virtual":a.specifiedAccess="virtual";break;case"abstract":a.isAbstract=!0;break;case"testMethod":a.isTest=!0;break;default:console.error(`Unsupported modifier in SymbolTable.tableDeclaration: ${e} (ApexClassId=${a.id})`)}})))),t.Body){const e=g.RemoveComments(t.Body);a.isInterface=g.IsInterface(e),a.isEnum=g.IsEnum(e),a.isClass=!1===a.isInterface&&!1===a.isEnum,a.hardCodedURLs=g.FindHardCodedURLs(e),a.hardCodedIDs=g.FindHardCodedIDs(e),!0===a.isTest&&(a.isTestSeeAllData=g.IsTestSeeAllData(e),a.nbSystemAsserts=g.CountOfAsserts(e))}return!0!==a.isEnum&&!0!==a.isInterface||(a.specifiedSharing="Not applicable"),[a.id,a]})));s?.log(`Parsing ${o.length} apex code coverages...`);const h=new Map,m=new Map;return await N.forEach(o,(t=>{const s=e.caseSafeId(t.ApexClassOrTriggerId),a=e.caseSafeId(t.ApexTestClassId);u.has(s)&&(!1===h.has(s)&&h.set(s,new Set),!1===m.has(a)&&m.set(a,new Set),h.get(s).add(a),m.get(a).add(s))})),await N.forEach(h,((e,t)=>{u.has(t)&&(u.get(t).relatedTestClassIds=Array.from(e))})),await N.forEach(m,((e,t)=>{u.has(t)&&(u.get(t).relatedClassIds=Array.from(e))})),s?.log(`Parsing ${l.length} apex code coverage aggregates...`),await N.forEach(l,(t=>{const s=e.caseSafeId(t.ApexClassOrTriggerId);u.has(s)&&(u.get(s).coverage=t.NumLinesCovered/(t.NumLinesCovered+t.NumLinesUncovered))})),s?.log(`Parsing ${c.length} schedule apex classes...`),await N.forEach(c,(t=>{const s=e.caseSafeId(t.ApexClassId);u.has(s)&&(u.get(s).isScheduled=!0)})),s?.log(`Parsing ${d.length} test results...`),await N.forEach(d,(t=>{const s=e.caseSafeId(t.ApexClassId);if(u.has(s)){const e=u.get(s);if(!0===e.isTest&&(e.lastTestRunDate||(e.lastTestRunDate=t.ApexTestRunResult?.CreatedDate,e.testMethodsRunTime=0,e.testPassedButLongMethods=[],e.testFailedMethods=[]),e.lastTestRunDate===t.ApexTestRunResult?.CreatedDate)){const s=i.create({properties:{methodName:t.MethodName,isSuccessful:"Pass"===t.Outcome,runtime:t.RunTime,stacktrace:t.StackTrace}});if(t.ApexTestResults?.records&&t.ApexTestResults.records.length>0){const e=t.ApexTestResults.records[0];e.Cpu>0&&(s.cpuConsumption=e.Cpu),e.AsyncCalls>0&&(s.asyncCallsConsumption=e.AsyncCalls),e.Sosl>0&&(s.soslConsumption=e.Sosl),e.Soql>0&&(s.soqlConsumption=e.Soql),e.QueryRows>0&&(s.queryRowsConsumption=e.QueryRows),e.DmlRows>0&&(s.dmlRowsConsumption=e.DmlRows),e.Dml>0&&(s.dmlConsumption=e.Dml)}e.testMethodsRunTime+=s.runtime,(s.isSuccessful?e.testPassedButLongMethods:e.testFailedMethods).push(s)}}})),await N.forEach(u,(e=>{r.computeScore(e)})),s?.log("Done"),u}}class Pt extends D{async run(e,t,s){s?.log("Querying Tooling API about ApexTrigger in the org...");const a=await e.soqlQuery([{string:"SELECT Id, Name, ApiVersion, Status, NamespacePrefix, Body, UsageBeforeInsert, UsageAfterInsert, UsageBeforeUpdate, UsageAfterUpdate, UsageBeforeDelete, UsageAfterDelete, UsageAfterUndelete, UsageIsBulk, LengthWithoutComments, EntityDefinition.QualifiedApiName, CreatedDate, LastModifiedDate FROM ApexTrigger WHERE ManageableState IN ('installedEditable', 'unmanaged') ",tooling:!0}],s),r=t.getInstance(ae),i=a[0];s?.log(`Retrieving dependencies of ${i.length} apex triggers...`);const n=await e.dependenciesQuery(await N.map(i,(t=>e.caseSafeId(t.Id))),s);s?.log(`Parsing ${i.length} apex triggers...`);const o=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.create({properties:{id:s,name:t.Name,apiVersion:t.ApiVersion,package:t.NamespacePrefix||"",length:t.LengthWithoutComments,isActive:"Active"===t.Status,beforeInsert:t.UsageBeforeInsert,afterInsert:t.UsageAfterInsert,beforeUpdate:t.UsageBeforeUpdate,afterUpdate:t.UsageAfterUpdate,beforeDelete:t.UsageBeforeDelete,afterDelete:t.UsageAfterDelete,afterUndelete:t.UsageAfterUndelete,objectId:e.caseSafeId(t.EntityDefinition?.QualifiedApiName),hasSOQL:!1,hasDML:!1,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,url:e.setupUrl(s,v.APEX_TRIGGER,t.EntityDefinition?.QualifiedApiName)},dependencies:{data:n}});if(t.Body){const e=g.RemoveComments(t.Body);a.hasSOQL=g.HasSOQL(e),a.hasDML=g.HasDML(e),a.hardCodedURLs=g.FindHardCodedURLs(e),a.hardCodedIDs=g.FindHardCodedIDs(e)}return r.computeScore(a),[a.id,a]}),(e=>!!e.EntityDefinition)));return s?.log("Done"),o}}class Rt extends D{async run(e,t,s){s?.log("Querying REST API about UserRole in the org...");const a=await e.soqlQuery([{string:"SELECT Id, DeveloperName, Name, ParentRoleId, (SELECT Id FROM Users WHERE IsActive = true AND ContactId = NULL AND Profile.Id != NULL) FROM UserRole WHERE PortalType = 'None' "}],s),r=t.getInstance(Ee),i=a[0];s?.log(`Parsing ${i.length} user roles...`);const n=new Map,o=[],l=new Map(await N.map(i,(async t=>{const s=e.caseSafeId(t.Id),a=r.create({properties:{id:s,name:t.Name,apiname:t.DeveloperName,parentId:t.ParentRoleId?e.caseSafeId(t.ParentRoleId):void 0,hasParent:!!t.ParentRoleId,activeMembersCount:0,activeMemberIds:[],hasActiveMembers:!1,url:e.setupUrl(s,v.ROLE)}});return!1===a.hasParent?o.push(a):(!1===n.has(a.parentId)&&n.set(a.parentId,[]),n.get(a.parentId).push(a)),await N.forEach(t?.Users?.records,(t=>{a.activeMemberIds.push(e.caseSafeId(t.Id))})),a.activeMembersCount=a.activeMemberIds.length,a.hasActiveMembers=a.activeMemberIds.length>0,[a.id,a]})));return await N.forEach(o,(async e=>{e.level=1,Tt(e,n)})),await N.forEach(l,(async e=>{r.computeScore(e)})),s?.log("Done"),l}}const Tt=(e,t)=>{const s=t.get(e.id);s?.forEach((s=>{s.level=e.level+1,Tt(s,t)}))};class yt extends D{async run(e,t,s){s?.log("Querying Tooling API about FlowDefinition in the org...");const a=await e.soqlQuery([{string:"SELECT Id, MasterLabel, DeveloperName, ApiVersion, Description, ActiveVersionId, LatestVersionId, CreatedDate, LastModifiedDate FROM FlowDefinition",tooling:!0},{string:"SELECT Id, DefinitionId, Status, ProcessType FROM Flow where DefinitionId <> null",tooling:!0}],s),r=t.getInstance(ie),i=t.getInstance(ne),n=a[0],o=a[1];s?.log(`Retrieving dependencies of ${n.length} flow versions...`);const l=await e.dependenciesQuery(await N.map(n,(t=>e.caseSafeId(t.ActiveVersionId??t.LatestVersionId))),s),c=[];s?.log(`Parsing ${n.length} flow definitions...`);const d=new Map(await N.map(n,(t=>{const s=e.caseSafeId(t.Id),a=e.caseSafeId(t.ActiveVersionId),i=e.caseSafeId(t.LatestVersionId),n=r.create({properties:{id:s,name:t.DeveloperName,apiVersion:t.ApiVersion,currentVersionId:a??i,isLatestCurrentVersion:a===i,isVersionActive:!!a,versionsCount:0,description:t.Description,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,url:e.setupUrl(s,v.FLOW_DEFINITION)},dependencies:{data:l,idField:"currentVersionId"}});return c.push(n.currentVersionId),[n.id,n]})));s?.log(`Parsing ${o.length} flow versions...`),await N.forEach(o,(t=>{const s=e.caseSafeId(t.DefinitionId),a=d.get(s);a.versionsCount++,a.type=t.ProcessType})),s?.log(`Calling Tooling API Composite to get more information about these ${c.length} flow versions...`);const p=await e.readMetadataAtScale("Flow",c,["UNKNOWN_EXCEPTION"],s);return s?.log(`Parsing ${p.length} flow versions...`),await N.forEach(p,(async t=>{const s=e.caseSafeId(t.Id),a=e.caseSafeId(t.DefinitionId),r=i.create({properties:{id:s,name:t.FullName,version:t.VersionNumber,apiVersion:t.ApiVersion,totalNodeCount:["actionCalls","apexPluginCalls","assignments","collectionProcessors","decisions","loops","orchestratedStages","recordCreates","recordDeletes","recordLookups","recordRollbacks","recordUpdates","screens","steps","waits"].reduce(((e,s)=>e+t.Metadata[s]?.length||0),0),dmlCreateNodeCount:t.Metadata.recordCreates?.length||0,dmlDeleteNodeCount:t.Metadata.recordDeletes?.length||0,dmlUpdateNodeCount:t.Metadata.recordUpdates?.length||0,screenNodeCount:t.Metadata.screens?.length||0,isActive:"Active"===t.Status,description:t.Description,type:t.ProcessType,runningMode:t.RunInMode,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,url:e.setupUrl(s,v.FLOW_VERSION)}});await N.forEach(t.Metadata.processMetadataValues,(e=>{"ObjectType"===e.name&&(r.sobject=e.value.stringValue),"TriggerType"===e.name&&(r.triggerType=e.value.stringValue)}));d.get(a).currentVersionRef=r})),await N.forEach(d,(e=>r.computeScore(e))),s?.log("Done"),d}}class Ct extends D{async run(e,t,s){s?.log("Querying Tooling API about WorkflowRule in the org...");const a=(await e.soqlQuery([{string:"SELECT Id FROM WorkflowRule",tooling:!0}],s))[0];s?.log(`Parsing ${a.length} Workflow Rules...`);const r=await N.map(a,(e=>e.Id)),i=t.getInstance(Pe);s?.log(`Calling Tooling API Composite to get more information about these ${r.length} workflow rules...`);const n=await e.readMetadataAtScale("WorkflowRule",r,["UNKNOWN_EXCEPTION"],s);s?.log(`Parsing ${n.length} workflows...`);const o=new Map(await N.map(n,(async t=>{const s=e.caseSafeId(t.Id),a=i.create({properties:{id:s,name:t.FullName,description:t.Metadata.description,isActive:t.Metadata.active,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,hasAction:!0,futureActions:[],emptyTimeTriggers:[],url:e.setupUrl(s,v.WORKFLOW_RULE)}}),r=t.Metadata.actions;a.actions=await N.map(r,(e=>({name:e.name,type:e.type})));const n=t.Metadata.workflowTimeTriggers;return await N.forEach(n,(async e=>{const t=e.offsetFromField||"TriggerDate";0===e.actions.length?a.emptyTimeTriggers.push({field:t,delay:`${e.timeLength} ${e.workflowTimeTriggerUnit}`}):await N.forEach(e.actions,(s=>{a.futureActions.push({name:s.name,type:s.type,field:t,delay:`${e.timeLength} ${e.workflowTimeTriggerUnit}`})}))})),a.hasAction=a.actions.length+a.futureActions.length>0,i.computeScore(a),[a.id,a]})));return s?.log("Done"),o}}const At=(e,t)=>Object.prototype.isPrototypeOf.call(t,e);class Ot extends I{_instances;constructor(){super(),this._instances=new Map}getInstance(e){const t=At(e,f),s=At(e,S),a=At(e,E);if(!1===t&&!1===a&&!1===s)throw new TypeError("Given dataClass does not extends Data nor DataWithDependencies nor DataWithoutScoring");return!1===this._instances.has(e)&&this._instances.set(e,new bt(e,t?Ae.AllScoreRules.filter((t=>t.applicable?.includes(e))):[],s)),this._instances.get(e)}}class bt extends w{_dataClass;_scoreRules;_isDependenciesNeeded;constructor(e,t,s){super(),this._dataClass=e,this._scoreRules=t,this._isDependenciesNeeded=s}create(e){if(!e)throw new TypeError("Configuration can't be null.");if(!e.properties)throw new TypeError("Configuration.properties can't be null.");const t=new this._dataClass;return Object.keys(t).forEach((s=>{t[s]=e.properties[s]})),Object.seal(t),this._scoreRules.length>0&&(t.score=0,t.badFields=[],t.badReasonIds=[]),!0===this._isDependenciesNeeded&&e.dependencies&&(t.dependencies=u.create(e.dependencies.data,t[e.dependencies.idField||"id"])),t}computeScore(e){return this._scoreRules.filter((t=>{try{if(!0===t.formula(e))return!0}catch(t){console.error("COMPUTE SCORE",t,e)}return!1})).forEach((t=>{e.score++,e.badFields.push(t.badField),e.badReasonIds.push(t.id)})),e}createWithScore(e){return this.computeScore(this.create(e))}}class Mt extends D{async run(e,t,s){s?.log("Querying REST API about Applications (tab set typed) in the org...");const a=await e.soqlQuery([{string:"SELECT ApplicationId, Name, Label, NamespacePrefix FROM AppMenuItem WHERE Type = 'TabSet' "}],s),r=t.getInstance(Oe),i=a[0];s?.log(`Parsing ${i.length} applications...`);const n=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.ApplicationId);return[s,r.create({properties:{id:s,name:t.Name,label:t.Label,package:t.NamespacePrefix||""}})]})));return s?.log("Done"),n}}class Dt extends D{async run(e,t,s,a){const r=a?.get("object");s?.log("Querying REST API about SetupEntityAccess for TabSet in the org...");const i=await e.soqlQuery([{string:`SELECT Field, PermissionsRead, PermissionsEdit, ParentId, Parent.IsOwnedByProfile, Parent.ProfileId FROM FieldPermissions WHERE SObjectType = '${r}' `}],s),n=t.getInstance(Me),o=i[0];s?.log(`Parsing ${o.length} Field Permissions...`);const l=new Map(await N.map(o,(t=>{const s=e.caseSafeId(t.Parent.IsOwnedByProfile?t.Parent.ProfileId:t.ParentId),a=t.Field.indexOf("."),r=-1===a?t.Field:t.Field.substring(a+1),i=n.create({properties:{fieldApiName:r,parentId:s,isRead:t.PermissionsRead,isEdit:t.PermissionsEdit}});return[`${t.Field}-${s}`,i]})));return s?.log("Done"),l}}class _t extends D{async run(e,t,s){s?.log("Querying Tooling API about Validaiton Rules in the org...");const a=await e.soqlQuery([{string:"SELECT Id, Active, Description, ErrorDisplayField, ErrorMessage, ValidationName, EntityDefinition.QualifiedApiName, NamespacePrefix, CreatedDate, LastModifiedDate FROM ValidationRule",tooling:!0}],s),r=t.getInstance(ee),i=a[0];s?.log(`Parsing ${i.length} validation rules...`);const n=new Map(await N.map(i,(async t=>{const s=e.caseSafeId(t.Id),a=r.createWithScore({properties:{id:e.caseSafeId(s),name:t.ValidationName,isActive:t.Active,package:t.NamespacePrefix||"",description:t.Description,errorDisplayField:t.ErrorDisplayField,errorMessage:t.ErrorMessage,objectId:t.EntityDefinition?.QualifiedApiName,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,url:e.setupUrl(s,v.VALIDATION_RULE)}});return[a.id,a]})));return s?.log("Done"),n}}class Lt extends D{async run(e,t,s){s?.log("Querying REST API about PermissionSetLicenses in the org...");const a=await e.soqlQuery([{string:"SELECT Id, MasterLabel, CreatedDate, LastModifiedDate, TotalLicenses, Status, ExpirationDate, UsedLicenses, IsAvailableForIntegrations FROM PermissionSetLicense "},{string:"SELECT Id, LicenseId FROM PermissionSet WHERE IsOwnedByProfile = false AND LicenseId <> NULL "},{string:"SELECT AssigneeId, PermissionSet.LicenseId FROM PermissionSetAssignment WHERE Assignee.IsActive = TRUE AND PermissionSet.LicenseId <> NULL AND PermissionSet.IsOwnedByProfile = FALSE ORDER BY PermissionSetId "}],s),r=t.getInstance(ue),i=a[0],n=a[1],o=a[2];s?.log(`Parsing ${i.length} permission sets licenses...`);const l=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.create({properties:{id:s,name:t.MasterLabel,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,totalCount:t.TotalLicenses,usedCount:t.UsedLicenses,usedPercentage:0!==t.TotalLicenses?t.UsedLicenses/t.TotalLicenses:void 0,remainingCount:t.TotalLicenses-t.UsedLicenses,permissionSetIds:[],distinctActiveAssigneeCount:0,status:t.Status,expirationDate:t.ExpirationDate,isAvailableForIntegrations:t.IsAvailableForIntegrations,url:e.setupUrl(s,v.PERMISSION_SET_LICENSE)}});return[a.id,a]})));s?.log(`Parsing ${o.length} Permission Sets with a link to a License...`);const c=new Map;return await N.forEach(o,(t=>{if(t.PermissionSet&&t.PermissionSet.LicenseId&&t.PermissionSet.LicenseId.startsWith("0PL")){const s=e.caseSafeId(t.PermissionSet.LicenseId),a=e.caseSafeId(t.AssigneeId);!1===c.has(s)&&c.set(s,new Set),c.get(s).add(a),l.get(s).distinctActiveAssigneeCount=c.get(s).size}})),s?.log(`Parsing ${n.length} Permission Sets with a link to a License...`),await N.forEach(n,(t=>{const s=e.caseSafeId(t.Id),a=e.caseSafeId(t.LicenseId);l.has(a)&&l.get(a).permissionSetIds.push(s)})),s?.log(`Computing the score for ${l.size} permission set licenses...`),await N.forEach(l,(e=>{r.computeScore(e)})),s?.log("Done"),l}}class Nt extends _{_datasets;_datasetPromisesCache;_dataCache;_sfdcManager;_logger;_dataFactory;constructor(e,t,s){if(super(),e instanceof M==!1)throw new TypeError("The given sfdcManager is not an instance of SalesforceManagerIntf.");if(s instanceof T==!1)throw new TypeError("The given logger is not an instance of LoggerIntf.");this._sfdcManager=e,this._logger=s,this._dataCache=t,this._datasets=new Map,this._datasetPromisesCache=new Map,this._dataFactory=new Ot,this._datasets.set(L.APEXCLASSES,new wt),this._datasets.set(L.APEXTRIGGERS,new Pt),this._datasets.set(L.APPLICATIONS,new Mt),this._datasets.set(L.APPPERMISSIONS,new Xe),this._datasets.set(L.CURRENTUSERPERMISSIONS,new it),this._datasets.set(L.CUSTOMFIELDS,new qe),this._datasets.set(L.CUSTOMLABELS,new He),this._datasets.set(L.FIELDPERMISSIONS,new Dt),this._datasets.set(L.FLOWS,new yt),this._datasets.set(L.GROUPS,new It),this._datasets.set(L.LIGHTNINGAURACOMPONENTS,new ft),this._datasets.set(L.LIGHTNINGPAGES,new Et),this._datasets.set(L.LIGHTNINGWEBCOMPONENTS,new St),this._datasets.set(L.OBJECT,new Je),this._datasets.set(L.OBJECTPERMISSIONS,new Ye),this._datasets.set(L.OBJECTS,new Ke),this._datasets.set(L.OBJECTTYPES,new Ze),this._datasets.set(L.ORGANIZATION,new rt),this._datasets.set(L.PACKAGES,new nt),this._datasets.set(L.PERMISSIONSETS,new ot),this._datasets.set(L.PERMISSIONSETLICENSES,new Lt),this._datasets.set(L.PROFILEPWDPOLICIES,new gt),this._datasets.set(L.PROFILERESTRICTIONS,new pt),this._datasets.set(L.PROFILES,new lt),this._datasets.set(L.USERROLES,new Rt),this._datasets.set(L.USERS,new ut),this._datasets.set(L.VALIDATIONRULES,new _t),this._datasets.set(L.VISUALFORCECOMPONENTS,new mt),this._datasets.set(L.VISUALFORCEPAGES,new ht),this._datasets.set(L.WORKFLOWS,new Ct)}async run(e){if(e instanceof Array==!1)throw new TypeError("The given datasets is not an instance of Array.");return new Map(await Promise.all(e.map((e=>{const t="string"==typeof e?e:e.alias,s="string"==typeof e?e:e.cacheKey,a="string"==typeof e?void 0:e.parameters,r=`DATASET ${t}`;return!1===this._datasetPromisesCache.has(s)&&this._datasetPromisesCache.set(s,new Promise(((e,i)=>{this._logger.log(r,`Checking the data cache for key=${s}...`),!0===this._dataCache.has(s)?(this._logger.ended(r,"There was data in data cache, we use it!"),e([t,this._dataCache.get(s)])):(this._logger.log(r,"There was no data in data cache. Let's retrieve data."),this._datasets.get(t).run(this._sfdcManager,this._dataFactory,this._logger.toSimpleLogger(r),a).then((a=>{this._dataCache.set(s,a),this._logger.ended(r,`Data retrieved and saved in cache with key=${s}`),e([t,a])})).catch((e=>{this._logger.failed(r,e),i(e)})))}))),this._datasetPromisesCache.get(s)}))))}clean(e){if(e instanceof Array==!1)throw new TypeError("The given datasets is not an instance of Array.");e.forEach((e=>{const t="string"==typeof e?e:e.cacheKey;this._dataCache.remove(t),this._datasetPromisesCache.delete(t)}))}}class xt extends T{_logger;_operationNames;_countSuccesses;_countFailures;constructor(e){super(),this._logger=e,this._countSuccesses=0,this._countFailures=0,this._operationNames=new Map}log(e,t){Ft(e,"LOG",t),this._logger?.log(e,t),this._operationNames.set(e,0)}ended(e,t){Ft(e,"ENDED",t),this._countSuccesses++,this._logger?.ended(e,t),this._operationNames.set(e,1)}failed(e,t){Ft(e,"FAILED",t),this._countFailures++,this._logger?.failed(e,t),this._operationNames.set(e,2)}toSimpleLogger(e){const t=this._logger;return{log:s=>{Ft(e,"LOG",s),t?.log(e,s)},debug:t=>{Ft(e,"DEBUG",t)}}}}const Ft=(e,t,s="...")=>{console.error(`${(new Date).toISOString()} - ${e} - ${t} - ${s}`)};class Ut extends x{extract(e){return[L.USERS,L.PROFILES,L.PERMISSIONSETS]}async transform(e,t){const s=e.get(L.USERS),a=e.get(L.PROFILES),r=e.get(L.PERMISSIONSETS);if(!s)throw new Error("RecipeActiveUsers: Data from dataset alias 'USERS' was undefined.");if(!a)throw new Error("RecipeActiveUsers: Data from dataset alias 'PROFILES' was undefined.");if(!r)throw new Error("RecipeActiveUsers: Data from dataset alias 'PERMISSIONSETS' was undefined.");return await N.forEach(s,(async e=>{e.profileRef=a.get(e.profileId),e.permissionSetRefs=await N.map(e.permissionSetIds,(e=>r.get(e)),(e=>r.has(e))),e.aggregateImportantPermissions={},e.profileRef?.importantPermissions&&Object.keys(e.profileRef.importantPermissions).filter((t=>!0===e.profileRef.importantPermissions[t])).forEach((t=>{e.aggregateImportantPermissions[t]=[e.profileRef]})),await N.forEach(e.permissionSetRefs,(t=>{Object.keys(t.importantPermissions).filter((e=>!0===t.importantPermissions[e])).forEach((s=>{e.aggregateImportantPermissions[s]||(e.aggregateImportantPermissions[s]=[]),e.aggregateImportantPermissions[s].push(t)}))}))})),[...s.values()]}}class vt extends x{extract(e){return[L.APEXCLASSES]}async transform(e,t,s){const a=e.get(L.APEXCLASSES);if(!a)throw new Error("RecipeApexClasses: Data from dataset alias 'APEXCLASSES' was undefined.");const r=[];return await N.forEach(a,(async e=>{const t=await Promise.all([N.map(e.relatedTestClassIds,(e=>a.get(e))),N.map(e.relatedClassIds,(e=>a.get(e)))]);e.relatedTestClassRefs=t[0],e.relatedClassRefs=t[1],"*"!==s&&e.package!==s||!1!==e.isTest||!1!==e.needsRecompilation||r.push(e)})),r}}class Gt extends x{extract(e){return[L.APEXTRIGGERS,L.OBJECTS]}async transform(e,t,s){const a=e.get(L.APEXTRIGGERS),r=e.get(L.OBJECTS);if(!a)throw new Error("RecipeApexTriggers: Data from dataset alias 'APEXTRIGGERS' was undefined.");if(!r)throw new Error("RecipeApexTriggers: Data from dataset alias 'OBJECTS' was undefined.");const i=[];return await N.forEach(a,(e=>{e.objectRef=r.get(e.objectId),"*"!==s&&e.package!==s||i.push(e)})),i}}class $t extends x{extract(e){return[L.APPLICATIONS,L.APPPERMISSIONS,L.PROFILES,L.PERMISSIONSETS]}async transform(e,t,s){const a=e.get(L.APPLICATIONS),r=e.get(L.APPPERMISSIONS),i=e.get(L.PROFILES),n=e.get(L.PERMISSIONSETS);if(!a)throw new Error("RecipeAppPermissions: Data from dataset alias 'APPLICATIONS' was undefined.");if(!r)throw new Error("RecipeAppPermissions: Data from dataset alias 'APPPERMISSIONS' was undefined.");if(!i)throw new Error("RecipeAppPermissions :Data from dataset alias 'PROFILES' was undefined.");if(!n)throw new Error("RecipeAppPermissions: Data from dataset alias 'PERMISSIONSETS' was undefined.");const o=h.create();return await N.forEach(r,(e=>{e.appRef=a.get(e.appId),!0===e.parentId.startsWith("0PS")?e.parentRef=n.get(e.parentId):e.parentRef=i.get(e.parentId),"*"!==s&&e.parentRef.package!==s&&e.appRef.appPackage!==s||(!1===o.hasRowHeader(e.parentId)&&o.setRowHeader(e.parentId,e.parentRef),!1===o.hasColumnHeader(e.appId)&&o.setColumnHeader(e.appId,e.appRef),o.addValueToProperty(e.parentId,e.appId,(e.isAccessible?"A":"")+(e.isVisible?"V":"")))})),o.toDataMatrix()}}class Bt extends x{extract(e,t){const s=new P(L.CURRENTUSERPERMISSIONS,L.CURRENTUSERPERMISSIONS);return s.parameters.set("permissions",t),[s]}async transform(e,t){const s=e.get(L.CURRENTUSERPERMISSIONS);if(!s)throw new Error("RecipeCurrentUserPermissions: Data from dataset alias 'CURRENTUSERPERMISSIONS' was undefined.");return s}}class Wt extends x{extract(e){return[L.CUSTOMFIELDS,L.OBJECTTYPES,L.OBJECTS]}async transform(e,t,s,a,r){const i=e.get(L.OBJECTTYPES),n=e.get(L.OBJECTS),o=e.get(L.CUSTOMFIELDS);if(!i)throw new Error("RecipeCustomFields: Data from dataset alias 'OBJECTTYPES' was undefined.");if(!n)throw new Error("RecipeCustomFields: Data from dataset alias 'OBJECTS' was undefined.");if(!o)throw new Error("RecipeCustomFields: Data from dataset alias 'CUSTOMFIELDS' was undefined.");const l=[];return await N.forEach(o,(e=>{const t=n.get(e.objectId);t&&!t.typeRef&&(t.typeRef=i.get(t.typeId)),e.objectRef=t,"*"!==s&&e.package!==s||"*"!==a&&e.objectRef?.typeRef?.id!==a||"*"!==r&&e.objectRef?.apiname!==r||l.push(e)})),l}}class Vt extends x{extract(e){return[L.CUSTOMLABELS]}async transform(e,t,s){const a=e.get(L.CUSTOMLABELS);if(!a)throw new Error("RecipeCustomLabels: Data from dataset alias 'CUSTOMLABELS' was undefined.");const r=[];return await N.forEach(a,(e=>{"*"!==s&&e.package!==s||r.push(e)})),r}}class kt extends x{extract(e){return[L.FLOWS]}async transform(e,t){const s=e.get(L.FLOWS);if(!s)throw new Error("RecipeFlows: Data from dataset alias 'FLOWS' was undefined.");const a=[];return await N.forEach(s,(e=>{"Workflow"!==e.type&&a.push(e)})),a}}class jt extends x{extract(e){return[L.LIGHTNINGAURACOMPONENTS]}async transform(e,t,s){const a=e.get(L.LIGHTNINGAURACOMPONENTS);if(!a)throw new Error("RecipeLightningAuraComponents: Data from dataset alias 'LIGHTNINGAURACOMPONENTS' was undefined.");const r=[];return await N.forEach(a,(e=>{"*"!==s&&e.package!==s||r.push(e)})),r}}class Qt extends x{extract(e){return[L.LIGHTNINGPAGES,L.OBJECTS]}async transform(e,t,s){const a=e.get(L.LIGHTNINGPAGES),r=e.get(L.OBJECTS);if(!a)throw new Error("RecipeLightningPages: Data from dataset alias 'LIGHTNINGPAGES' was undefined.");if(!r)throw new Error("RecipeLightningPages: Data from dataset alias 'OBJECTS' was undefined.");const i=[];return await N.forEach(a,(e=>{e.objectId&&(e.objectRef=r.get(e.objectId)),"*"!==s&&e.package!==s||i.push(e)})),i}}class qt extends x{extract(e){return[L.LIGHTNINGWEBCOMPONENTS]}async transform(e,t,s){const a=e.get(L.LIGHTNINGWEBCOMPONENTS);if(!a)throw new Error("RecipeLightningWebComponents: Data from dataset alias 'LIGHTNINGWEBCOMPONENTS' was undefined.");const r=[];return await N.forEach(a,(e=>{"*"!==s&&e.package!==s||r.push(e)})),r}}class Ht extends x{extract(e,t){const s=new P(L.OBJECT,`${L.OBJECT}_${t}`),a=new P(L.CUSTOMFIELDS,`${L.CUSTOMFIELDS}_${t}`);return s.parameters.set("object",t),a.parameters.set("object",t),[s,L.OBJECTTYPES,L.APEXTRIGGERS,L.LIGHTNINGPAGES,a]}async transform(e,t){const s=e.get(L.OBJECTTYPES),a=e.get(L.OBJECT),r=e.get(L.APEXTRIGGERS),i=e.get(L.LIGHTNINGPAGES),n=e.get(L.CUSTOMFIELDS);if(!s)throw new Error("RecipeObject: Data from dataset alias 'OBJECTTYPES' was undefined.");if(!a)throw new Error("RecipeObject: Data from dataset alias 'OBJECT' was undefined.");if(!r)throw new Error("RecipeObject: Data from dataset alias 'APEXTRIGGERS' was undefined.");if(!i)throw new Error("RecipeObject: Data from dataset alias 'LIGHTNINGPAGES' was undefined.");if(!n)throw new Error("RecipeObject: Data from dataset alias 'CUSTOMFIELDS' was undefined.");a.typeRef=s.get(a.typeId),a.flexiPages=[];const o=await Promise.all([N.map(a.apexTriggerIds,(e=>{const t=r.get(e);return t.objectRef=a,t}),(e=>r.has(e))),N.forEach(i,(e=>{e.objectId===a.id&&a.flexiPages.push(e)})),N.map(a.customFieldIds,(e=>{const t=n.get(e);return t.objectRef=a,t}),(e=>n.has(e)))]);return a.apexTriggerRefs=o[0],a.customFieldRefs=o[2],a}}class Jt extends x{extract(e){return[L.OBJECTPERMISSIONS,L.PROFILES,L.PERMISSIONSETS]}async transform(e,t,s){const a=e.get(L.OBJECTPERMISSIONS),r=e.get(L.PROFILES),i=e.get(L.PERMISSIONSETS);if(!a)throw new Error("RecipeObjectPermissions: Data from dataset alias 'OBJECTPERMISSIONS' was undefined.");if(!r)throw new Error("RecipeObjectPermissions: Data from dataset alias 'PROFILES' was undefined.");if(!i)throw new Error("RecipeObjectPermissions: Data from dataset alias 'PERMISSIONSETS' was undefined.");const n=h.create();return await N.forEach(a,(e=>{!0===e.parentId.startsWith("0PS")?e.parentRef=i.get(e.parentId):e.parentRef=r.get(e.parentId),"*"!==s&&e.parentRef.package!==s||(!1===n.hasRowHeader(e.parentId)&&n.setRowHeader(e.parentId,e.parentRef),n.addValueToProperty(e.parentId,e.objectType,(e.isCreate?"C":"")+(e.isRead?"R":"")+(e.isEdit?"U":"")+(e.isDelete?"D":"")+(e.isViewAll?"v":"")+(e.isModifyAll?"m":"")))})),n.toDataMatrix()}}class Yt extends x{extract(e){return[L.OBJECTTYPES,L.OBJECTS]}async transform(e,t,s,a){const r=e.get(L.OBJECTTYPES),i=e.get(L.OBJECTS);if(!r)throw new Error("RecipeObjects: Data from dataset alias 'OBJECTTYPES' was undefined.");if(!i)throw new Error("RecipeObjects: Data from dataset alias 'OBJECTS' was undefined.");const n=[];return await N.forEach(i,(e=>{e.typeRef=r.get(e.typeId),"*"!==s&&e.package!==s||"*"!==a&&e.typeRef?.id!==a||n.push(e)})),n.sort(((e,t)=>e.label{"*"!==s&&e.package!==s||r.push(e)})),r}}class es extends x{extract(e){return[L.FLOWS]}async transform(e,t){const s=e.get(L.FLOWS);if(!s)throw new Error("RecipeProcessBuilders: Data from dataset alias 'FLOWS' was undefined.");const a=[];return await N.forEach(s,(e=>{"Workflow"===e.type&&a.push(e)})),a}}class ts extends x{extract(e){return[L.PROFILEPWDPOLICIES]}async transform(e,t){const s=e.get(L.PROFILEPWDPOLICIES);if(!s)throw new Error("RecipeProfilePasswordPolicies: Data from dataset alias 'PROFILEPWDPOLICIES' was undefined.");return[...s.values()]}}class ss extends x{extract(e){return[L.PROFILES,L.PROFILERESTRICTIONS]}async transform(e,t,s){const a=e.get(L.PROFILES),r=e.get(L.PROFILERESTRICTIONS);if(!a)throw new Error("RecipeProfileRestrictions: Data from dataset alias 'PROFILES' was undefined.");if(!r)throw new Error("RecipeProfileRestrictions: Data from dataset alias 'PROFILERESTRICTIONS' was undefined.");const i=[];return await N.forEach(r,(e=>{e.profileRef=a.get(e.profileId),"*"!==s&&e.profileRef?.package!==s||i.push(e)})),i}}class as extends x{extract(e){return[L.PROFILES]}async transform(e,t,s){const a=e.get(L.PROFILES);if(!a)throw new Error("RecipeProfiles: Data from dataset alias 'PROFILES' was undefined.");const r=[];return await N.forEach(a,(e=>{"*"!==s&&e.package!==s||r.push(e)})),r}}class rs extends x{extract(e){return[L.USERS,L.GROUPS]}async transform(e,t){const s=e.get(L.GROUPS),a=e.get(L.USERS);if(!s)throw new Error("RecipePublicGroups: Data from dataset alias 'GROUPS' was undefined.");if(!a)throw new Error("RecipePublicGroups: Data from dataset alias 'USERS' was undefined.");const r=[];return await N.forEach(s,(async e=>{e.directUserRefs=await N.map(e.directUserIds,(e=>a.get(e)),(e=>a.has(e))),e.directGroupRefs=await N.map(e.directGroupIds,(e=>s.get(e)),(e=>s.has(e))),!0===e.isPublicGroup&&r.push(e)})),r}}class is extends x{extract(e){return[L.USERS,L.GROUPS]}async transform(e,t){const s=e.get(L.GROUPS),a=e.get(L.USERS);if(!s)throw new Error("RecipeQueues: Data from dataset alias 'GROUPS' was undefined.");if(!a)throw new Error("RecipeQueues: Data from dataset alias 'USERS' was undefined.");const r=[];return await N.forEach(s,(async e=>{e.directUserRefs=await N.map(e.directUserIds,(e=>a.get(e)),(e=>a.has(e))),e.directGroupRefs=await N.map(e.directGroupIds,(e=>s.get(e)),(e=>s.has(e))),!0===e.isQueue&&r.push(e)})),r}}class ns extends x{extract(e){return[L.USERROLES,L.USERS]}async transform(e,t){const s=e.get(L.USERROLES),a=e.get(L.USERS);if(!s)throw new Error("RecipeUserRoles: Data from dataset alias 'USERROLES' was undefined.");if(!a)throw new Error("RecipeUserRoles: Data from dataset alias 'USERS' was undefined.");return await N.forEach(s,(async e=>{!0===e.hasActiveMembers&&(e.activeMemberRefs=await N.map(e.activeMemberIds,(e=>a.get(e)))),!0===e.hasParent&&(e.parentRef=s.get(e.parentId))})),[...s.values()]}}class os extends x{extract(e){return[L.VISUALFORCECOMPONENTS]}async transform(e,t,s){const a=e.get(L.VISUALFORCECOMPONENTS);if(!a)throw new Error("RecipeVisualForceComponents: Data from dataset alias 'VISUALFORCECOMPONENTS' was undefined.");const r=[];return await N.forEach(a,(e=>{"*"!==s&&e.package!==s||r.push(e)})),r}}class ls extends x{extract(e){return[L.VISUALFORCEPAGES]}async transform(e,t,s){const a=e.get(L.VISUALFORCEPAGES);if(!a)throw new Error("RecipeVisualForcePages: Data from dataset alias 'VISUALFORCEPAGES' was undefined.");const r=[];return await N.forEach(a,(e=>{"*"!==s&&e.package!==s||r.push(e)})),r}}class cs extends x{extract(e){return[L.WORKFLOWS]}async transform(e,t){const s=e.get(L.WORKFLOWS);if(!s)throw new Error("RecipeWorkflows: Data from dataset alias 'WORKFLOWS' was undefined.");return[...s.values()]}}class ds extends x{extract(e){return[L.APEXCLASSES]}async transform(e,t,s){const a=e.get(L.APEXCLASSES);if(!a)throw new Error("RecipeApexTests: Data from dataset alias 'APEXCLASSES' was undefined.");const r=[];return await N.forEach(a,(async e=>{const t=await Promise.all([N.map(e.relatedTestClassIds,(e=>a.get(e))),N.map(e.relatedClassIds,(e=>a.get(e)))]);e.relatedTestClassRefs=t[0],e.relatedClassRefs=t[1],"*"!==s&&e.package!==s||!0!==e.isTest||!1!==e.needsRecompilation||r.push(e)})),r}}class ps extends x{extract(e){return[L.APEXCLASSES]}async transform(e,t,s){const a=e.get(L.APEXCLASSES);if(!a)throw new Error("RecipeApexUncompiled: Data from dataset alias 'APEXCLASSES' was undefined.");const r=[];return await N.forEach(a,(async e=>{const t=await Promise.all([N.map(e.relatedTestClassIds,(e=>a.get(e))),N.map(e.relatedClassIds,(e=>a.get(e)))]);e.relatedTestClassRefs=t[0],e.relatedClassRefs=t[1],"*"!==s&&e.package!==s||!0!==e.needsRecompilation||r.push(e)})),r}}class gs extends x{extract(e,t){const s=new P(L.FIELDPERMISSIONS,`${L.FIELDPERMISSIONS}_${t}`);return s.parameters.set("object",t),[s,L.PROFILES,L.PERMISSIONSETS]}async transform(e,t,s,a){const r=e.get(L.FIELDPERMISSIONS),i=e.get(L.PROFILES),n=e.get(L.PERMISSIONSETS);if(!r)throw new Error("RecipeFieldPermissions: Data from dataset alias 'FIELDPERMISSIONS' was undefined.");if(!i)throw new Error("RecipeFieldPermissions: Data from dataset alias 'PROFILES' was undefined.");if(!n)throw new Error("RecipeFieldPermissions: Data from dataset alias 'PERMISSIONSETS' was undefined.");const o=h.create();return await N.forEach(r,(e=>{!0===e.parentId.startsWith("0PS")?e.parentRef=n.get(e.parentId):e.parentRef=i.get(e.parentId),"*"!==a&&e.parentRef.package!==a||(!1===o.hasRowHeader(e.parentId)&&o.setRowHeader(e.parentId,e.parentRef),o.addValueToProperty(e.parentId,e.fieldApiName,(e.isRead?"R":"")+(e.isEdit?"U":"")))})),o.toDataMatrix()}}class us extends x{extract(e){return[L.VALIDATIONRULES,L.OBJECTTYPES,L.OBJECTS]}async transform(e,t,s,a,r){const i=e.get(L.OBJECTTYPES),n=e.get(L.OBJECTS),o=e.get(L.VALIDATIONRULES);if(!i)throw new Error("RecipeValidationRules: Data from dataset alias 'OBJECTTYPES' was undefined.");if(!n)throw new Error("RecipeValidationRules: Data from dataset alias 'OBJECTS' was undefined.");if(!o)throw new Error("RecipeValidationRules: Data from dataset alias 'VALIDATIONRULES' was undefined.");const l=[];return await N.forEach(o,(e=>{const t=n.get(e.objectId);t&&!t.typeRef&&(t.typeRef=i.get(t.typeId)),e.objectRef=t,"*"!==s&&e.package!==s||"*"!==a&&e.objectRef?.typeRef?.id!==a||"*"!==r&&e.objectRef?.apiname!==r||l.push(e)})),l}}class hs extends x{extract(e){return[L.PERMISSIONSETLICENSES,L.PERMISSIONSETS]}async transform(e,t){const s=e.get(L.PERMISSIONSETLICENSES),a=e.get(L.PERMISSIONSETS);if(!s)throw new Error("RecipePermissionSetLicenses: Data from dataset alias 'PERMISSIONSETLICENSES' was undefined.");if(!a)throw new Error("RecipePermissionSetLicenses: Data from dataset alias 'PERMISSIONSETS' was undefined.");return await N.forEach(s,(async e=>{e.permissionSetRefs=await N.map(e.permissionSetIds,(e=>a.get(e)),(e=>a.has(e)))})),[...s.values()]}}class ms extends F{_logger;_recipes;_datasetManager;constructor(e,t){if(super(),e instanceof _==!1)throw new TypeError("The given datasetManager is not an instance of DatasetManagerIntf.");if(t instanceof T==!1)throw new TypeError("The given logger is not an instance of LoggerIntf.");this._datasetManager=e,this._logger=t,this._recipes=new Map,this._recipes.set(U.ACTIVE_USERS,new Ut),this._recipes.set(U.APEX_CLASSES,new vt),this._recipes.set(U.APEX_TESTS,new ds),this._recipes.set(U.APEX_TRIGGERS,new Gt),this._recipes.set(U.APEX_UNCOMPILED,new ps),this._recipes.set(U.APP_PERMISSIONS,new $t),this._recipes.set(U.CURRENT_USER_PERMISSIONS,new Bt),this._recipes.set(U.CUSTOM_FIELDS,new Wt),this._recipes.set(U.CUSTOM_LABELS,new Vt),this._recipes.set(U.FIELD_PERMISSIONS,new gs),this._recipes.set(U.FLOWS,new kt),this._recipes.set(U.LIGHTNING_AURA_COMPONENTS,new jt),this._recipes.set(U.LIGHTNING_PAGES,new Qt),this._recipes.set(U.LIGHTNING_WEB_COMPONENTS,new qt),this._recipes.set(U.OBJECT,new Ht),this._recipes.set(U.OBJECT_PERMISSIONS,new Jt),this._recipes.set(U.OBJECTS,new Yt),this._recipes.set(U.OBJECT_TYPES,new Xt),this._recipes.set(U.ORGANIZATION,new Kt),this._recipes.set(U.PACKAGES,new zt),this._recipes.set(U.PERMISSION_SETS,new Zt),this._recipes.set(U.PERMISSION_SET_LICENSES,new hs),this._recipes.set(U.PROCESS_BUILDERS,new es),this._recipes.set(U.PROFILE_PWD_POLICIES,new ts),this._recipes.set(U.PROFILE_RESTRICTIONS,new ss),this._recipes.set(U.PROFILES,new as),this._recipes.set(U.PUBLIC_GROUPS,new rs),this._recipes.set(U.QUEUES,new is),this._recipes.set(U.USER_ROLES,new ns),this._recipes.set(U.VALIDATION_RULES,new us),this._recipes.set(U.VISUALFORCE_COMPONENTS,new os),this._recipes.set(U.VISUALFORCE_PAGES,new ls),this._recipes.set(U.WORKFLOWS,new cs)}async run(e,...t){if(!1===this._recipes.has(e))throw new TypeError(`The given alias (${e}) does not correspond to a registered recipe.`);const s=`RECIPE ${e}`,a=this._recipes.get(e);let r,i,n;this._logger.log(s,"How many datasets this recipe has?");try{r=a.extract(this._logger.toSimpleLogger(s),...t)}catch(e){throw this._logger.failed(s,e),e}this._logger.log(s,`This recipe has ${r?.length} ${r?.length>1?"datasets":"dataset"}: ${r.map((e=>e instanceof P?e.alias:e)).join(", ")}...`);try{i=await this._datasetManager.run(r)}catch(e){throw this._logger.failed(s,e),e}this._logger.log(s,"Datasets information successfuly retrieved!"),this._logger.log(s,"This recipe will now transform all this information...");try{n=await a.transform(i,this._logger.toSimpleLogger(s),...t)}catch(e){throw this._logger.failed(s,e),e}return this._logger.ended(s,"Transformation successfuly done!"),n}clean(e,...t){if(!1===this._recipes.has(e))throw new TypeError(`The given alias (${e}) does not correspond to a registered recipe.`);const s=`RECIPE ${e}`,a=this._recipes.get(e);let r;this._logger.log(s,"How many datasets this recipe has?");try{r=a.extract(this._logger.toSimpleLogger(s),...t)}catch(e){throw this._logger.failed(s,e),e}this._logger.log(s,`This recipe has ${r?.length} ${r?.length>1?"datasets":"dataset"}: ${r.map((e=>e instanceof P?e.alias:e)).join(", ")}...`),this._logger.log(s,"Clean all datasets...");try{this._datasetManager.clean(r)}catch(e){throw this._logger.failed(s,e),e}this._logger.ended(s,"Datasets succesfully cleaned!")}}const fs=2e3;class Ss extends M{_apiVersion;_watchDog;_connection;constructor(e,t){super(),this._apiVersion=Ae.CurrentApiVersion;const s=new e.Connection({accessToken:t,version:this._apiVersion+".0",maxRequest:15});this._watchDog=new C((()=>({used:s.limitInfo?.apiUsage?.used,max:s.limitInfo?.apiUsage?.limit}))),this._connection=s}get apiVersion(){return this._apiVersion}caseSafeId(e){return e&&18===e.length?e.substr(0,15):e}setupUrl(e,t,s,a){if(!e)return"";switch(t){case v.STANDARD_FIELD:case v.CUSTOM_FIELD:case v.ANY_FIELD:switch(a){case v.STANDARD_OBJECT:case v.CUSTOM_OBJECT:case v.KNOWLEDGE_ARTICLE:return"/lightning/setup/ObjectManager/"+(s?`${s}/FieldsAndRelationships/${e}/view`:`page?address=%2F${e}`);case v.CUSTOM_BIG_OBJECT:return`/lightning/setup/BigObjects/page?address=%2F${e}%3Fsetupid%3DBigObjects`;case v.CUSTOM_EVENT:return`/lightning/setup/EventObjects/page?address=%2F${e}%3Fsetupid%3DEventObjects`;case v.CUSTOM_SETTING:return`/lightning/setup/CustomSettings/page?address=%2F${e}%3Fsetupid%3DCustomSettings`;case v.CUSTOM_METADATA_TYPE:return`/lightning/setup/CustomMetadata/page?address=%2F${e}%3Fsetupid%3DCustomMetadata`;case v.EXTERNAL_OBJECT:return`/lightning/setup/ExternalObjects/page?address=%2F${e}%3Fsetupid%3DExternalObjects`;default:return`/lightning/setup/ObjectManager/page?address=%2F${e}`}case v.STANDARD_OBJECT:case v.CUSTOM_OBJECT:case v.KNOWLEDGE_ARTICLE:return`/lightning/setup/ObjectManager/${e}/Details/view`;case v.CUSTOM_BIG_OBJECT:return`/lightning/setup/BigObjects/page?address=%2F${e}%3Fsetupid%3DBigObjects`;case v.CUSTOM_EVENT:return`/lightning/setup/EventObjects/page?address=%2F${e}%3Fsetupid%3DEventObjects`;case v.CUSTOM_SETTING:return`/lightning/setup/CustomSettings/page?address=%2F${e}%3Fsetupid%3DCustomSettings`;case v.CUSTOM_METADATA_TYPE:return`/lightning/setup/CustomMetadata/page?address=%2F${e}%3Fsetupid%3DCustomMetadata`;case v.EXTERNAL_OBJECT:return`/lightning/setup/ExternalObjects/page?address=%2F${e}%3Fsetupid%3DExternalObjects`;case v.PAGE_LAYOUT:return"/lightning/setup/ObjectManager/"+(s?`${s}/PageLayouts/${e}/view`:`page?address=%2F${e}`);case v.VALIDATION_RULE:return`/lightning/setup/ObjectManager/page?address=%2F${e}`;case v.WEB_LINK:return"/lightning/setup/ObjectManager/"+(s?`${s}/ButtonsLinksActions/${e}/view`:`page?address=%2F${e}`);case v.RECORD_TYPE:return"/lightning/setup/ObjectManager/"+(s?`${s}/RecordTypes/${e}/view`:`page?address=%2F${e}`);case v.APEX_TRIGGER:return"/lightning/setup/ObjectManager/"+(s?`${s}/ApexTriggers/${e}/view`:`page?address=%2F${e}`);case v.FIELD_SET:return"/lightning/setup/ObjectManager/"+(s?`${s}/FieldSets/${e}/view`:`page?address=%2F${e}`);case v.USER:return`/lightning/setup/ManageUsers/page?address=%2F${e}%3Fnoredirect%3D1%26isUserEntityOverride%3D1`;case v.PROFILE:return`/lightning/setup/EnhancedProfiles/page?address=%2F${e}`;case v.PERMISSION_SET:return`/lightning/setup/PermSets/page?address=%2F${e}`;case v.PERMISSION_SET_LICENSE:return`/lightning/setup/PermissionSetLicense/page?address=%2F${e}`;case v.PERMISSION_SET_GROUP:return`/lightning/setup/PermSetGroups/page?address=%2F${e}`;case v.ROLE:return`/lightning/setup/Roles/page?address=%2F${e}`;case v.PUBLIC_GROUP:return`/lightning/setup/PublicGroups/page?address=%2Fsetup%2Fown%2Fgroupdetail.jsp%3Fid%3D${e}`;case v.QUEUE:return`/lightning/setup/Queues/page?address=%2Fp%2Fown%2FQueue%2Fd%3Fid%3D${e}`;case v.TECHNICAL_GROUP:return"";case v.CUSTOM_LABEL:return`/lightning/setup/ExternalStrings/page?address=%2F${e}`;case v.STATIC_RESOURCE:return`/lightning/setup/StaticResources/page?address=%2F${e}`;case v.CUSTOM_SITE:return`/servlet/networks/switch?networkId=${e}&startURL=%2FcommunitySetup%2FcwApp.app%23%2Fc%2Fhome&`;case v.CUSTOM_TAB:return`/lightning/setup/CustomTabs/page?address=%2F${e}`;case v.FLOW_VERSION:return`/builder_platform_interaction/flowBuilder.app?flowId=${e}`;case v.FLOW_DEFINITION:return`/${e}`;case v.WORKFLOW_RULE:return`/lightning/setup/WorkflowRules/page?address=%2F${e}&nodeId=WorkflowRules`;case v.VISUAL_FORCE_PAGE:return`/lightning/setup/ApexPages/page?address=%2F${e}`;case v.VISUAL_FORCE_COMPONENT:return`/lightning/setup/ApexComponent/page?address=%2F${e}`;case v.AURA_WEB_COMPONENT:case v.LIGHTNING_WEB_COMPONENT:return`/lightning/setup/LightningComponentBundles/page?address=%2F${e}`;case v.LIGHTNING_PAGE:return"/lightning/setup/ObjectManager/"+(s?`${s}/LightningPages/${e}/view`:`page?address=%2F${e}`);case v.APEX_CLASS:return`/lightning/setup/ApexClasses/page?address=%2F${e}`;default:return console.error(`Type <${t}> not supported yet. Returning "/id" as url. FYI, id was <${e}>, parentId was <${s}> and parentType was <${a}>`),`/${e}`}}getObjectType(e,t){return!0===t?H:e.endsWith("__c")?Q:e.endsWith("__x")?q:e.endsWith("__mdt")?J:e.endsWith("__e")?Y:e.endsWith("__ka")?X:e.endsWith("__b")?K:j}get dailyApiRequestLimitInformation(){return this._watchDog.dailyApiRequestLimitInformation}async _standardSOQLQuery(e,t,s,a){const r=!0===e?this._connection.tooling:this._connection,i=[],n=async e=>{let s;this._watchDog?.beforeRequest(),s=void 0===e?await r.query(t,{autoFetch:!1,headers:{"Sforce-Query-Options":"batchSize=2000"}}):await r.queryMore(e),a(s?.records?.length||0),this._watchDog?.afterRequest(),i.push(...s.records),!1===s.done&&await n(s.nextRecordsUrl)};try{return await n(),i}catch(e){if(s&&s.includes&&s.includes(e.errorCode))return[];throw Object.assign(e,{context:{when:"While running a SOQL query with the standard queryMore",what:t}})}}async _customSOQLQuery(e,t,s,a){const r=!0===e?this._connection.tooling:this._connection,i=[],n=t.indexOf(" FROM "),o=t.indexOf(" GROUP BY "),l=-1!==o,c=async e=>{let d;e||!1!==l||(e="000000000000000000"),d=!1===l?`${t} AND ${s} > '${e}' ORDER BY ${s} LIMIT 2000`:`${t.substring(0,n)}, MAX(${s}) qmField ${t.substring(n,o)} `+(e?`WHERE ${s} > ${e} `:"")+`${t.substring(o)} `+`ORDER BY MAX(${s}) LIMIT 2000`,this._watchDog?.beforeRequest();const p=await r.query(d,{autoFetch:!1,headers:{"Sforce-Query-Options":"batchSize=2000"}});if(a(p?.records?.length||0),this._watchDog?.afterRequest(),i.push(...p.records),p.records.length>=fs){const e=i[i.length-1];!1===l?await c(e[s]):await c(e.qmField)}};try{return await c(),i}catch(e){throw Object.assign(e,{context:{when:"While running a SOQL query with the custom queryMore",what:t}})}}async soqlQuery(e,t){t?.log(`Preparing ${e.length} SOQL ${e.length>1?"queries":"query"}...`);let s=0,a=0;const r=[],i=[],n=[],o=[],l=()=>{t?.log(`Processing ${e.length} SOQL ${e.length>1?"queries":"query"}... 🎥 Records retrieved: ${s}, 🙌 Number of QueryMore calls done: ${a}, ⏳ Pending: (${r.length}) on [${r.join(", ")}], ✅ Done: (${i.length}) on [${i.join(", ")}], ❌ Error: (${n.length}) on [${n.join(", ")}]`)},c=e=>{a++,s+=e,l()},d=await Promise.allSettled(e.map((async e=>{const t=e.string.lastIndexOf("FROM ")+5,s=e.string.indexOf(" ",t),a=e.string.substring(t,-1===s?e.string.length:s);let d;r.push(a);try{d=e.queryMoreField?await this._customSOQLQuery(e.tooling,e.string,e.queryMoreField,c):await this._standardSOQLQuery(e.tooling,e.string,e.byPasses,c),i.push(a)}catch(e){throw n.push(a),o.push(e),e}finally{const e=r.indexOf(a);e>-1&&r.splice(e,1),l()}return d})));if(t?.log(`Done running ${e.length} SOQL ${e.length>1?"queries":"query"}.`),o.length>0)return Promise.reject(o[0]);const p=d.filter((e=>"fulfilled"===e.status)).map((e=>e.value));return Promise.resolve(p)}async dependenciesQuery(e,t){this._watchDog?.beforeRequest(),t?.log(`Starting to call Tooling API for dependency API call of ${e.length} item(s)...`);const s=[];let a;for(let t=0;t{try{const t=await this._connection.tooling.request({url:"/tooling/composite",method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}});return this._watchDog?.afterRequest(),i++,t}catch(e){n++}finally{r--,t?.log(`Processing ${s.length} Tooling composite queries... Pending: ${r}, Done: ${i}, Error: ${n}`)}})));t?.log("Got all the results");const l=[],c=[],d=new Set;return o.forEach((s=>{s.compositeResponse.forEach((s=>{if(200===s.httpStatusCode)t?.log(`This response had a code: 200 so we add the ${s?.body?.records?.length} records`),l.push(...s.body.records.map((e=>{const t=this.caseSafeId(e.MetadataComponentId),s=this.caseSafeId(e.RefMetadataComponentId),a=`${t}-${s}`;return d.has(a)?null:(d.add(a),{id:t,name:e.MetadataComponentName,type:e.MetadataComponentType,url:this.setupUrl(t,e.MetadataComponentType),refId:s,refName:e.RefMetadataComponentName,refType:e.RefMetadataComponentType,refUrl:this.setupUrl(s,e.RefMetadataComponentType)})})).filter((e=>null!==e)));else{const a=s.body[0].errorCode;if("UNKNOWN_EXCEPTION"!==a){t?.log(`This response had a code: ${a}`);const r=new TypeError(`One of the request had an issue with HTTP errorCode=${a}`);throw Object.assign(r,{context:{when:"Calling Composite Tooling API to get dependencies.",what:{ids:e,body:s.body}}})}t?.log(`This response had a code: ${a}`),c.push(...e)}}))})),{records:l,errors:c}}async readMetadata(e,t){this._watchDog?.beforeRequest(),t?.log(`Starting to call Metadata API for ${e.length} types...`),await Promise.all(e.filter((e=>e.members?.includes("*"))).map((async e=>{try{const t=await this._connection.metadata.list([{type:e.type}],this._apiVersion);this._watchDog?.afterRequest(),e.members=e.members.filter((e=>"*"!==e)),Es(t).forEach((t=>{e.members.push(t.fullName)}))}catch(s){throw t?.log(`The method metadata.list returned an error: ${JSON.stringify(s)}`),Object.assign(s,{context:{when:"Calling Metadata API to get a list of metadata.",what:{type:e.type,apiVersion:this._apiVersion}}})}})));const s=[],a=new Map;return e.forEach((e=>{for(t?.log(`Init the response array for this type: ${e.type}`),a.set(e.type,[]),t?.log(`Starting looping for type ${e.type} and metadata.members.length=${e.members.length}`);e.members.length>0;){const r=e.members.splice(0,10);s.push(new Promise((async(s,i)=>{t?.log(`Try to call metadata read for type ${e.type} and currentMembers=${r}`);try{const t=await this._connection.metadata.read(e.type,r);this._watchDog?.afterRequest(),a.get(e.type).push(...Es(t)),s()}catch(s){t?.log(`The method metadata.read returned an error: ${JSON.stringify(s)}`),i(Object.assign(s,{context:{when:"Calling Metadata API to read a list of metadata.",what:{type:e.type,pendingMembers:e.members,membersInProcess:r}}}))}})))}})),t?.log(`Calling all promises: ${s.length}`),await Promise.all(s),t?.log(`All promises ended and response is like: ${JSON.stringify(Array.from(a.entries()))}`),a}async readMetadataAtScale(e,t,s,a){this._watchDog?.beforeRequest();const r=[];let i;t.forEach(((t,s)=>{i&&5!==i.compositeRequest.length||(i={allOrNone:!1,compositeRequest:[]},r.push(i)),i.compositeRequest.push({method:"GET",url:`/services/data/v${this._apiVersion}.0/tooling/sobjects/${e}/${t}`,referenceId:`chunk${s}`})}));const n=await Promise.all(r.map((e=>(this._watchDog?.afterRequest(),this._connection.tooling.request({url:"/tooling/composite",method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}}))))),o=[];return n.forEach((a=>{a.compositeResponse.forEach((a=>{if(200===a.httpStatusCode)o.push(a.body);else{const r=a.body[0].errorCode;if(s&&s.includes&&!1===s.includes(r)){const s=new TypeError(`One of the request for type=${e} had an issue with HTTP errorCode=${r}`);throw Object.assign(s,{context:{when:"Calling Composite Tooling API to get metadata at scale.",what:{type:e,ids:t,body:a.body}}})}}}))})),o}async describeGlobal(e){this._watchDog?.beforeRequest();const t=await this._connection.describeGlobal();return t.sobjects.push(Is),this._watchDog?.afterRequest(),t.sobjects}async describe(e,t){if("Activity"===e)return Is;this._watchDog?.beforeRequest();const s=await this._connection.describe(e);return this._watchDog?.afterRequest(),s}async recordCount(e,t){this._watchDog?.beforeRequest();const s=await this._connection.request({url:`/limits/recordCount?sObjects=${e}`,method:"GET"});return this._watchDog?.afterRequest(),Array.isArray(s?.sObjects)&&1===s?.sObjects.length?s?.sObjects[0].count:0}async runAllTests(e){this._watchDog?.beforeRequest();const t=await this._connection.request({url:"/tooling/runTestsAsynchronous",method:"POST",body:'{ "testLevel": "RunLocalTests", "skipCodeCoverage": false }',headers:{"Content-Type":"application/json"}});return this._watchDog?.afterRequest(),t}async compileClasses(e,t){this._watchDog?.beforeRequest();const s=await this.readMetadataAtScale(v.APEX_CLASS,e,[],t);this._watchDog?.beforeRequest();const a=Date.now(),r=[];let i,n=0;s.filter((e=>e.Body)).forEach((e=>{i&&5!==i.compositeRequest.length||(n++,i={allOrNone:!1,compositeRequest:[{method:"POST",url:`/services/data/v${this._apiVersion}.0/tooling/sobjects/MetadataContainer`,referenceId:"container",body:{Name:`container-${a}-${n}`}},{method:"POST",url:`/services/data/v${this._apiVersion}.0/tooling/sobjects/ContainerAsyncRequest`,referenceId:"request",body:{MetadataContainerId:"@{container.id}",IsCheckOnly:!0}}]},r.push(i)),i.compositeRequest.push({method:"POST",url:`/services/data/v${this._apiVersion}.0/tooling/sobjects/ApexClassMember`,referenceId:e.Id,body:{MetadataContainerId:"@{container.id}",ContentEntityId:e.Id,Body:e.Body}})}));const o=r.map((e=>(this._watchDog?.afterRequest(),this._connection.tooling.request({url:"/tooling/composite",method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}})))),l=await Promise.all(o);return this._watchDog?.afterRequest(),l}}const Es=e=>e?Array.isArray(e)?e:[e]:[],Is={name:"Activity",label:"Activity",labelPlural:"Activities",customSetting:!1,custom:!1,keyPrefix:"00T"};exports.API=class{get version(){return"Boron [B,5]"}get salesforceApiVersion(){return this._sfdcManager.apiVersion}_recipeManager;_datasetManager;_sfdcManager;_cacheManager;_logger;_usageTermsAcceptedManually;constructor(e,t,s,a,r,i){this._logger=new xt(i),this._sfdcManager=new Ss(t,e),this._cacheManager=new Ne({compress:r.compress,decompress:r.decompress,encode:a.encode,decode:a.decode,storage:s}),this._datasetManager=new Nt(this._sfdcManager,this._cacheManager,this._logger),this._recipeManager=new ms(this._datasetManager,this._logger),this._usageTermsAcceptedManually=!1}removeAllFromCache(){this._cacheManager.clear()}getCacheInformation(){return this._cacheManager.details()}getScoreRule(e){return Ae.AllScoreRules[e]}getAllScoreRules(){return Ae.AllScoreRules}getAllScoreRulesAsDataMatrix(){const e=h.create();return Ae.AllScoreRules.forEach((t=>{e.setRowHeader(`${t.id}`,t),t.applicable.forEach((s=>{e.addValueToProperty(`${t.id}`,s.label,"true")}))})),e.toDataMatrix()}get dailyApiRequestLimitInformation(){return this._sfdcManager.dailyApiRequestLimitInformation}async runAllTestsAsync(){return this._sfdcManager.runAllTests(this._logger.toSimpleLogger("Run All Tests"))}async compileClasses(e){return this._sfdcManager.compileClasses(e,this._logger.toSimpleLogger(`Compile ${e.length} class(es)`))}async getOrganizationInformation(){return await this._recipeManager.run(U.ORGANIZATION)}async checkUsageTerms(){return!0!==(await this.getOrganizationInformation()).isProduction||!1!==this._usageTermsAcceptedManually}wereUsageTermsAcceptedManually(){return this._usageTermsAcceptedManually}acceptUsageTermsManually(){this._usageTermsAcceptedManually=!0}async checkCurrentUserPermissions(){const e=await this._recipeManager.run(U.CURRENT_USER_PERMISSIONS,["ModifyAllData","AuthorApex","ApiEnabled","InstallPackaging"]);if(!1===e.get("ModifyAllData")||!1===e.get("AuthorApex")||!1===e.get("ApiEnabled")||!1===e.get("InstallPackaging"))throw new TypeError(`Current User Permission Access is not enough to run the application

- Modify All Data (Create, edit, and delete all organization data, regardless of sharing settings) [PermissionsModifyAllData] is set to ${e.get("PermissionsModifyAllData")}
- Author Apex (Create Apex classes and triggers) [PermissionsAuthorApex] is set to ${e.get("PermissionsAuthorApex")}
- API Enabled (Access any Salesforce.com API) [PermissionsApiEnabled] is set to ${e.get("PermissionsApiEnabled")}
- Download AppExchange Packages (Install or uninstall AppExchange packages as system administrators) [PermissionsInstallPackaging] is set to ${e.get("PermissionsInstallPackaging")}
`);return!0}async getPackages(){return await this._recipeManager.run(U.PACKAGES)}removeAllPackagesFromCache(){this._recipeManager.clean(U.PACKAGES)}async getObjectTypes(){return await this._recipeManager.run(U.OBJECT_TYPES)}async getObjects(e,t){return await this._recipeManager.run(U.OBJECTS,e,t)}removeAllObjectsFromCache(){this._recipeManager.clean(U.OBJECTS)}async getObject(e){return await this._recipeManager.run(U.OBJECT,e)}removeObjectFromCache(e){this._recipeManager.clean(U.OBJECT,e)}async getObjectPermissionsPerParent(e){return await this._recipeManager.run(U.OBJECT_PERMISSIONS,e)}removeAllObjectPermissionsFromCache(){this._recipeManager.clean(U.OBJECT_PERMISSIONS)}async getApplicationPermissionsPerParent(e){return await this._recipeManager.run(U.APP_PERMISSIONS,e)}removeAllAppPermissionsFromCache(){this._recipeManager.clean(U.APP_PERMISSIONS)}async getCustomFields(e,t,s){return await this._recipeManager.run(U.CUSTOM_FIELDS,e,t,s)}removeAllCustomFieldsFromCache(){this._recipeManager.clean(U.CUSTOM_FIELDS)}async getPermissionSets(e){return await this._recipeManager.run(U.PERMISSION_SETS,e)}removeAllPermSetsFromCache(){this._recipeManager.clean(U.PERMISSION_SETS)}async getPermissionSetLicenses(){return await this._recipeManager.run(U.PERMISSION_SET_LICENSES)}removeAllPermSetLicensesFromCache(){this._recipeManager.clean(U.PERMISSION_SET_LICENSES)}async getProfiles(e){return await this._recipeManager.run(U.PROFILES,e)}removeAllProfilesFromCache(){this._recipeManager.clean(U.PROFILES)}async getProfileRestrictions(e){return await this._recipeManager.run(U.PROFILE_RESTRICTIONS,e)}removeAllProfileRestrictionsFromCache(){this._recipeManager.clean(U.PROFILE_RESTRICTIONS)}async getProfilePasswordPolicies(){return await this._recipeManager.run(U.PROFILE_PWD_POLICIES)}removeAllProfilePasswordPoliciesFromCache(){this._recipeManager.clean(U.PROFILE_PWD_POLICIES)}async getActiveUsers(){return await this._recipeManager.run(U.ACTIVE_USERS)}removeAllActiveUsersFromCache(){this._recipeManager.clean(U.ACTIVE_USERS)}async getCustomLabels(e){return await this._recipeManager.run(U.CUSTOM_LABELS,e)}removeAllCustomLabelsFromCache(){this._recipeManager.clean(U.CUSTOM_LABELS)}async getLightningWebComponents(e){return await this._recipeManager.run(U.LIGHTNING_WEB_COMPONENTS,e)}removeAllLightningWebComponentsFromCache(){this._recipeManager.clean(U.LIGHTNING_WEB_COMPONENTS)}async getLightningAuraComponents(e){return await this._recipeManager.run(U.LIGHTNING_AURA_COMPONENTS,e)}removeAllLightningAuraComponentsFromCache(){this._recipeManager.clean(U.LIGHTNING_AURA_COMPONENTS)}async getLightningPages(e){return await this._recipeManager.run(U.LIGHTNING_PAGES,e)}removeAllLightningPagesFromCache(){this._recipeManager.clean(U.LIGHTNING_PAGES)}async getVisualForceComponents(e){return await this._recipeManager.run(U.VISUALFORCE_COMPONENTS,e)}removeAllVisualForceComponentsFromCache(){this._recipeManager.clean(U.VISUALFORCE_COMPONENTS)}async getVisualForcePages(e){return await this._recipeManager.run(U.VISUALFORCE_PAGES,e)}removeAllVisualForcePagesFromCache(){this._recipeManager.clean(U.VISUALFORCE_PAGES)}async getPublicGroups(){return await this._recipeManager.run(U.PUBLIC_GROUPS)}removeAllPublicGroupsFromCache(){this._recipeManager.clean(U.PUBLIC_GROUPS)}async getQueues(){return await this._recipeManager.run(U.QUEUES)}removeAllQueuesFromCache(){this._recipeManager.clean(U.QUEUES)}async getApexClasses(e){return await this._recipeManager.run(U.APEX_CLASSES,e)}removeAllApexClassesFromCache(){this._recipeManager.clean(U.APEX_CLASSES)}async getApexTests(e){return await this._recipeManager.run(U.APEX_TESTS,e)}removeAllApexTestsFromCache(){this._recipeManager.clean(U.APEX_TESTS)}async getApexTriggers(e){return await this._recipeManager.run(U.APEX_TRIGGERS,e)}removeAllApexTriggersFromCache(){this._recipeManager.clean(U.APEX_TRIGGERS)}async getApexUncompiled(e){return await this._recipeManager.run(U.APEX_UNCOMPILED,e)}removeAllApexUncompiledFromCache(){this._recipeManager.clean(U.APEX_UNCOMPILED)}async getRoles(){return await this._recipeManager.run(U.USER_ROLES)}removeAllRolesFromCache(){this._recipeManager.clean(U.USER_ROLES)}async getRolesTree(){const e=await this.getRoles(),t=new Map,s="__i am root__";return e.forEach((e=>{!1===t.has(e.id)&&t.set(e.id,{id:e.id});const a=t.get(e.id);a.record||(a.record=e);const r=!0===e.hasParent?e.parentId:s;!1===t.has(r)&&t.set(r,{id:r});const i=t.get(r);i.children||(i.children=[]),i.children.push(a)})),t.get(s)}async getWorkflows(){return await this._recipeManager.run(U.WORKFLOWS)}removeAllWorkflowsFromCache(){this._recipeManager.clean(U.WORKFLOWS)}async getFieldPermissionsPerParent(e,t){return await this._recipeManager.run(U.FIELD_PERMISSIONS,e,t)}removeAllFieldPermissionsFromCache(){this._recipeManager.clean(U.FIELD_PERMISSIONS)}async getFlows(){return await this._recipeManager.run(U.FLOWS)}removeAllFlowsFromCache(){this._recipeManager.clean(U.FLOWS)}async getProcessBuilders(){return await this._recipeManager.run(U.PROCESS_BUILDERS)}removeAllProcessBuildersFromCache(){this._recipeManager.clean(U.PROCESS_BUILDERS)}async getValidationRules(e,t,s){return await this._recipeManager.run(U.VALIDATION_RULES,e,t,s)}removeAllValidationRulesFromCache(){this._recipeManager.clean(U.VALIDATION_RULES)}},exports.BasicLoggerIntf=R,exports.CodeScanner=g,exports.Data=f,exports.DataCacheItem=class{name;isEmpty;isMap;length;created},exports.DataCacheManagerIntf=t,exports.DataDependencies=class{hadError;using;referenced;referencedByTypes},exports.DataDependenciesFactory=u,exports.DataDependencyItem=class{id;name;type;url},exports.DataFactoryInstanceIntf=w,exports.DataFactoryIntf=I,exports.DataItemInCache=class extends e{content},exports.DataMatrix=class{columnHeaders;rows},exports.DataMatrixColumnHeader=class{id;ref},exports.DataMatrixFactory=h,exports.DataMatrixRow=class{header;data},exports.DataMatrixWorking=m,exports.DataWithDependencies=S,exports.DataWithoutScoring=E,exports.Dataset=D,exports.DatasetAliases=L,exports.DatasetManagerIntf=_,exports.DatasetRunInformation=P,exports.ItemInCache=e,exports.LoggerIntf=T,exports.MetadataItemInCache=class extends e{type;length},exports.OBJECTTYPE_ID_CUSTOM_BIG_OBJECT=K,exports.OBJECTTYPE_ID_CUSTOM_EVENT=Y,exports.OBJECTTYPE_ID_CUSTOM_EXTERNAL_SOBJECT=q,exports.OBJECTTYPE_ID_CUSTOM_METADATA_TYPE=J,exports.OBJECTTYPE_ID_CUSTOM_SETTING=H,exports.OBJECTTYPE_ID_CUSTOM_SOBJECT=Q,exports.OBJECTTYPE_ID_KNOWLEDGE_ARTICLE=X,exports.OBJECTTYPE_ID_STANDARD_SOBJECT=j,exports.Processor=N,exports.Recipe=x,exports.RecipeAliases=U,exports.RecipeManagerIntf=F,exports.SFDC_ApexClass=b,exports.SFDC_ApexTestMethodResult=O,exports.SFDC_ApexTrigger=ae,exports.SFDC_AppPermission=be,exports.SFDC_Application=Oe,exports.SFDC_CustomLabel=re,exports.SFDC_Field=G,exports.SFDC_FieldPermission=Me,exports.SFDC_FieldSet=$,exports.SFDC_Flow=ie,exports.SFDC_FlowVersion=ne,exports.SFDC_Group=de,exports.SFDC_LightningAuraComponent=pe,exports.SFDC_LightningPage=B,exports.SFDC_LightningWebComponent=ge,exports.SFDC_Limit=W,exports.SFDC_Object=se,exports.SFDC_ObjectPermission=De,exports.SFDC_ObjectRelationShip=V,exports.SFDC_ObjectType=k,exports.SFDC_Organization=_e,exports.SFDC_Package=Le,exports.SFDC_PageLayout=z,exports.SFDC_PermissionSet=le,exports.SFDC_PermissionSetLicense=ue,exports.SFDC_Profile=oe,exports.SFDC_ProfileIpRangeRestriction=fe,exports.SFDC_ProfileLoginHourRestriction=Se,exports.SFDC_ProfilePasswordPolicy=he,exports.SFDC_ProfileRestrictions=me,exports.SFDC_RecordType=Z,exports.SFDC_User=ce,exports.SFDC_UserRole=Ee,exports.SFDC_ValidationRule=ee,exports.SFDC_VisualForceComponent=Ie,exports.SFDC_VisualForcePage=we,exports.SFDC_WebLink=te,exports.SFDC_Workflow=Pe,exports.SalesforceManagerIntf=M,exports.SalesforceMetadataRequest=class{type;members},exports.SalesforceMetadataTypes=v,exports.SalesforceQueryRequest=class{string;tooling;byPasses;queryMoreField},exports.SalesforceUsageInformation=y,exports.SalesforceWatchDog=C,exports.ScoreRule=class{id;description;formula;errorMessage;badField;applicable},exports.SecretSauce=Ae,exports.SimpleLoggerIntf=class{log(e){throw new TypeError('You need to implement the method "log()"')}debug(e){throw new TypeError('You need to implement the method "debug()"')}}; +"use strict";class e{created}class t{has(e){throw new Error("Not implemented")}get(e){throw new Error("Not implemented")}set(e,t){throw new Error("Not implemented")}details(){throw new Error("Not implemented")}remove(e){throw new Error("Not implemented")}clear(){throw new Error("Not implemented")}}const s=new RegExp("(\\/\\*[\\s\\S]*?\\*\\/|\\/\\/.*\\n|\\n)","gi"),a=new RegExp("(?:public|global)\\s+(?:interface)\\s+\\w+(\\s+(?:extends)\\s+\\w+)?\\s*\\{","i"),r=new RegExp("(?:public|global)\\s+(?:enum)\\s+\\w+\\s*\\{","i"),i=new RegExp("@IsTest\\s*\\(.*SeeAllData=true.*\\)","i"),n=new RegExp("(System.assert(Equals|NotEquals|)\\s*\\(|Assert\\.[a-zA-Z]*\\s*\\()","ig"),o=new RegExp("([A-Za-z0-9-]{1,63}\\.)+[A-Za-z]{2,6}","ig"),l=new RegExp("[,\"'\\s][a-zA-Z0-9]{5}0[a-zA-Z0-9]{9}([a-zA-Z0-9]{3})?[,\"'\\s]","ig"),c=new RegExp("\\[\\s*(?:SELECT|FIND)"),d=new RegExp("(?:insert|update|delete)\\s*(?:\\s\\w+|\\(|\\[)"),p=["salesforce.com",".force."];class g{static RemoveComments(e){return e?.replaceAll(s," ")||""}static IsInterface(e){return null!==e?.match(a)||!1}static IsEnum(e){return null!==e?.match(r)||!1}static FindHardCodedURLs(e){return e?.match(o)?.filter((e=>p.findIndex((t=>e.indexOf(t)>=0))>=0)).sort().filter(((e,t,s)=>t===s.indexOf(e)))}static FindHardCodedIDs(e){return e?.match(l)?.map((e=>e?.substring(1,e?.length-1))).sort().filter(((e,t,s)=>t===s.indexOf(e)))}static IsTestSeeAllData(e){return null!==e?.match(i)||!1}static CountOfAsserts(e){return e?.match(n)?.length||0}static HasSOQL(e){return null!==e?.match(c)||!1}static HasDML(e){return null!==e?.match(d)||!1}}class u{static create(e,t){if(e.errors?.some((e=>t.includes(e))))return{hadError:!0,using:[],referenced:[],referencedByTypes:{}};const s=e.records.filter((e=>t.includes(e.id))).map((e=>({id:e.refId,name:e.refName,type:e.refType,url:e.refUrl}))),a={};return{hadError:!1,using:s,referenced:e.records.filter((e=>t.includes(e.refId))).map((e=>(void 0===a[e.type]?a[e.type]=1:a[e.type]++,{id:e.id,name:e.name,type:e.type,url:e.url}))),referencedByTypes:a}}}class h{static create(){return new m}}class m{constructor(){this._columnIds=new Set,this._columns=new Map,this._rows=new Map}toDataMatrix(){const e=[];return this._columnIds.forEach((t=>{e.push(this._columns.has(t)?this._columns.get(t):t)})),{columnHeaders:e,rows:Array.from(this._rows.values())}}addValueToProperty(e,t,s){!1===this._rows.has(e)&&this._rows.set(e,{header:{},data:{}}),this._rows.get(e).data[t]=s,this._columnIds.add(t)}hasColumnHeader(e){return this._columns.has(e)}setColumnHeader(e,t){this._columns.set(e,t)}hasRowHeader(e){return this._rows.has(e)&&this._rows.get(e).header}setRowHeader(e,t){!0===this._rows.has(e)?this._rows.get(e).header=t:this._rows.set(e,{header:t,data:{}})}_columnIds;_columns;_rows}class f{static get label(){return console.error("Need to implement static label() method for",this,JSON.stringify(this),this.name),this.name}score;badFields;badReasonIds}class S extends f{dependencies}class E{}class I{getInstance(e){throw new Error("Not implemented")}}class w{create(e){throw new Error("Not implemented")}computeScore(e){throw new Error("Not implemented")}createWithScore(e){throw new Error("Not implemented")}}class P{alias;cacheKey;parameters;constructor(e,t){this.alias=e,this.cacheKey=t,this.parameters=new Map}}class R{log(e,t){throw new TypeError('You need to implement the method "log()"')}ended(e,t){throw new TypeError('You need to implement the method "ended()"')}failed(e,t){throw new TypeError('You need to implement the method "failed()"')}}class T extends R{toSimpleLogger(e){throw new TypeError('You need to implement the method "toSimpleLogger()"')}}class y{currentUsageRatio=0;currentUsagePercentage="";get yellowThresholdPercentage(){return.7}get redThresholdPercentage(){return.9}get isGreenZone(){return this.currentUsageRatio<.7}get isYellowZone(){return this.currentUsageRatio>=.7&&this.currentUsageRatio<.9}get isRedZone(){return this.currentUsageRatio>=.9}}class C{constructor(e){this._apiLimitExtractor=e,this._lastRequestToSalesforce=void 0,this._lastApiUsage=new y}_apiLimitExtractor;_lastRequestToSalesforce;_lastApiUsage;beforeRequest(e){if(this._lastRequestToSalesforce&&Date.now()-this._lastRequestToSalesforce<=6e4&&this._lastApiUsage.isRedZone){const t=new TypeError(`WATCH DOG: Daily API Request limit is ${A(this._lastApiUsage.currentUsageRatio)}%, and our internal threshold is ${A(this._lastApiUsage.redThresholdPercentage)}%. We stop there to keep your org safe.`);throw e&&e(t),t}}afterRequest(e){const t=this._apiLimitExtractor();t&&(this._lastApiUsage.currentUsageRatio=t.used/t.max,this._lastApiUsage.currentUsagePercentage=A(this._lastApiUsage.currentUsageRatio),this._lastRequestToSalesforce=Date.now(),this.beforeRequest(e))}get dailyApiRequestLimitInformation(){return this._lastApiUsage}}const A=(e,t=2)=>(100*e).toFixed(t);class O extends E{static get label(){return"Apex Test Result"}methodName;isSuccessful;runtime;stacktrace;cpuConsumption;asyncCallsConsumption;soslConsumption;soqlConsumption;queryRowsConsumption;dmlRowsConsumption;dmlConsumption}class b extends S{static get label(){return"Apex Class"}id;name;url;apiVersion;package;isTest;isTestSeeAllData;nbSystemAsserts;isAbstract;isClass;isEnum;isInterface;innerClassesCount;isSchedulable;isScheduled;interfaces;extends;methodsCount;testPassedButLongMethods;testFailedMethods;lastTestRunDate;testMethodsRunTime;annotations;specifiedSharing;specifiedAccess;length;hardCodedURLs;hardCodedIDs;needsRecompilation;coverage;relatedTestClassIds;relatedTestClassRefs;relatedClassIds;relatedClassRefs;createdDate;lastModifiedDate}class M{get apiVersion(){throw new Error("Not implemented")}caseSafeId(e){throw new Error("Not implemented")}setupUrl(e,t,s,a){throw new Error("Not implemented")}getObjectType(e,t){throw new Error("Not implemented")}get dailyApiRequestLimitInformation(){throw new Error("Not implemented")}async soqlQuery(e,t){throw new Error("Not implemented")}async dependenciesQuery(e,t){throw new Error("Not implemented")}async readMetadata(e,t){throw new Error("Not implemented")}async readMetadataAtScale(e,t,s,a){throw new Error("Not implemented")}async describeGlobal(e){throw new Error("Not implemented")}async describe(e,t){throw new Error("Not implemented")}async recordCount(e,t){throw new Error("Not implemented")}async runAllTests(e){throw new Error("Not implemented")}async compileClasses(e,t){throw new Error("Not implemented")}}class D{async run(e,t,s,a){throw new TypeError('You need to implement the method "run()"')}}class _{async run(e){throw new TypeError('You need to implement the method "run()"')}clean(e){throw new TypeError('You need to implement the method "clean()"')}}const L={APEXCLASSES:"apex-classes",APEXTRIGGERS:"apex-triggers",APPLICATIONS:"applications",APPPERMISSIONS:"app-permisions",CURRENTUSERPERMISSIONS:"current-user-permissions",CUSTOMFIELDS:"custom-fields",CUSTOMLABELS:"custom-labels",FIELDPERMISSIONS:"field-permissions",FLOWS:"flows",GROUPS:"groups",LIGHTNINGAURACOMPONENTS:"lightning-aura-components",LIGHTNINGPAGES:"lightning-pages",LIGHTNINGWEBCOMPONENTS:"lightning-web-components",OBJECT:"object",OBJECTPERMISSIONS:"object-permissions",OBJECTS:"objects",OBJECTTYPES:"object-types",ORGANIZATION:"org-information",PACKAGES:"packages",PERMISSIONSETS:"permission-sets",PERMISSIONSETLICENSES:"permission-set-licenses",PROFILEPWDPOLICIES:"profile-password-policies",PROFILERESTRICTIONS:"profile-restrictions",PROFILES:"profiles",USERROLES:"user-roles",USERS:"users",VALIDATIONRULES:"validation-rules",VISUALFORCECOMPONENTS:"visual-force-components",VISUALFORCEPAGES:"visual-force-pages",WORKFLOWS:"workflows"};Object.seal(L);class N{static async forEach(e,t){if(!e)return Promise.resolve();if("function"!=typeof t)throw new TypeError("Given iteratee is not a proper Function.");if(!0===Array.isArray(e))return Promise.all(e.map((async e=>(await t(e),null))));if(e instanceof Map==!0){const s=[];return e.forEach(((e,a)=>s.push(new Promise((s=>{t(e,a),s()}))))),Promise.all(s)}throw new TypeError("Given iterable is not a proper Array nor Map.")}static async map(e,t,s){if(!e)return Promise.resolve([]);if(!1===Array.isArray(e))throw new TypeError("Given iterable is not a proper Array.");if("function"!=typeof t)throw new TypeError("Given iteratee is not a proper Function.");if(s&&"function"!=typeof s)throw new TypeError("Given filterIteratee is not a proper Function.");return Promise.all((s?e.filter((e=>s(e))):e).map((async e=>t(e))))}}class x{extract(e,...t){throw new TypeError('You need to implement the method "extract()"')}async transform(e,t,...s){throw new TypeError('You need to implement the method "transform()"')}}class F{async run(e,...t){throw new TypeError('You need to implement the method "run()"')}clean(e,...t){throw new TypeError('You need to implement the method "clean()"')}}const U={ACTIVE_USERS:"active-users",APEX_CLASSES:"apex-classes",APEX_TESTS:"apex-tests",APEX_TRIGGERS:"apex-triggers",APEX_UNCOMPILED:"apex-uncompiled",APP_PERMISSIONS:"app-permissions",CURRENT_USER_PERMISSIONS:"current-user-permissions",CUSTOM_FIELDS:"custom-fields",CUSTOM_LABELS:"custom-labels",FIELD_PERMISSIONS:"field-permissions",FLOWS:"flows",LIGHTNING_AURA_COMPONENTS:"lightning-aura-components",LIGHTNING_PAGES:"lightning-pages",LIGHTNING_WEB_COMPONENTS:"lightning-web-components",OBJECT:"object",OBJECT_PERMISSIONS:"object-permissions",OBJECTS:"objects",OBJECT_TYPES:"object-types",ORGANIZATION:"org-information",PACKAGES:"packages",PERMISSION_SETS:"permission-sets",PERMISSION_SET_LICENSES:"permission-set-licenses",PROCESS_BUILDERS:"process-builders",PROFILE_PWD_POLICIES:"profile-password-policies",PROFILE_RESTRICTIONS:"profile-restrictions",PROFILES:"profiles",PUBLIC_GROUPS:"public-groups",QUEUES:"queues",USER_ROLES:"user-roles",VALIDATION_RULES:"validation-rules",VISUALFORCE_COMPONENTS:"visualforce-components",VISUALFORCE_PAGES:"visualforce-pages",WORKFLOWS:"workflows"};Object.seal(U);const v={ANY_FIELD:"Field",APEX_CLASS:"ApexClass",APEX_TRIGGER:"ApexTrigger",AURA_WEB_COMPONENT:"AuraDefinitionBundle",CUSTOM_BIG_OBJECT:"CustomBigObject",CUSTOM_EVENT:"CustomEvent",CUSTOM_FIELD:"CustomField",CUSTOM_LABEL:"CustomLabel",CUSTOM_METADATA_TYPE:"CustomMetadataType",CUSTOM_OBJECT:"CustomObject",CUSTOM_SETTING:"CustomSetting",CUSTOM_SITE:"CustomSite",CUSTOM_TAB:"CustomTab",EXTERNAL_OBJECT:"ExternalObject",FIELD_SET:"FieldSet",FLOW_DEFINITION:"FlowDefinition",FLOW_VERSION:"Flow",KNOWLEDGE_ARTICLE:"KnowledgeArticle",LIGHTNING_PAGE:"FlexiPage",LIGHTNING_WEB_COMPONENT:"LightningComponentBundle",PAGE_LAYOUT:"Layout",PERMISSION_SET:"PermissionSet",PERMISSION_SET_GROUP:"PermissionSetGroup",PERMISSION_SET_LICENSE:"PermissionSetLicense",PROFILE:"Profile",PUBLIC_GROUP:"PublicGroup",QUEUE:"Queue",RECORD_TYPE:"RecordType",ROLE:"UserRole",TECHNICAL_GROUP:"TechnicalGroup",STANDARD_FIELD:"StandardField",STANDARD_OBJECT:"StandardEntity",STATIC_RESOURCE:"StaticResource",USER:"User",VALIDATION_RULE:"ValidationRule",VISUAL_FORCE_COMPONENT:"ApexComponent",VISUAL_FORCE_PAGE:"ApexPage",WEB_LINK:"WebLink",WORKFLOW_RULE:"WorkflowRule"};Object.seal(v);class G extends S{static get label(){return"Standard or Custom Field"}id;url;name;label;package;description;createdDate;lastModifiedDate;objectId;objectRef;isCustom;tooltip;type;length;isUnique;isEncrypted;isExternalId;isIndexed;defaultValue;isRestrictedPicklist;formula;hardCodedURLs;hardCodedIDs}class $ extends f{static get label(){return"Field Set"}id;label;description;url}class B extends S{static get label(){return"Lightning Page"}id;name;type;package;createdDate;lastModifiedDate;objectId;objectRef;description;url}class W extends f{static get label(){return"SObject Limit"}id;label;remaining;max;used;usedPercentage;type}class V extends E{static get label(){return"SObject Releationship"}name;childObject;fieldName;isCascadeDelete;isRestrictedDelete}class k extends E{static get label(){return"SObject Types"}id;label}const j="StandardEntity",Q="CustomObject",q="ExternalObject",H="CustomSetting",J="CustomMetadataType",Y="CustomEvent",X="KnowledgeArticle",K="CustomBigObject";class z extends f{static get label(){return"Page Layout"}id;name;type;url}class Z extends f{static get label(){return"Record Type"}id;name;developerName;url;isActive;isAvailable;isDefaultRecordTypeMapping;isMaster}class ee extends f{static get label(){return"Validation Rule"}id;name;isActive;description;errorDisplayField;errorMessage;objectId;objectRef;package;createdDate;lastModifiedDate;url}class te extends f{static get label(){return"Web Link"}id;name;hardCodedURLs;hardCodedIDs;type;behavior;package;createdDate;lastModifiedDate;description;url}class se extends E{static get label(){return"SObject"}id;label;labelPlural;isCustom;isFeedEnabled;isMostRecentEnabled;isSearchable;keyPrefix;name;apiname;url;package;typeId;typeRef;description;externalSharingModel;internalSharingModel;apexTriggerIds;apexTriggerRefs;fieldSets;layouts;flexiPages;limits;validationRules;webLinks;standardFields;customFieldIds;customFieldRefs;recordTypes;relationships;recordCount}class ae extends S{static get label(){return"Apex Trigger"}id;name;url;apiVersion;package;length;isActive;beforeInsert;afterInsert;beforeUpdate;afterUpdate;beforeDelete;afterDelete;afterUndelete;objectId;objectRef;hasSOQL;hasDML;hardCodedURLs;hardCodedIDs;createdDate;lastModifiedDate}class re extends S{static get label(){return"Custom Label"}id;name;package;label;category;isProtected;language;value;url;createdDate;lastModifiedDate}class ie extends S{static get label(){return"Flow or Process Builder"}id;name;url;apiVersion;currentVersionId;currentVersionRef;isLatestCurrentVersion;isVersionActive;versionsCount;description;type;isProcessBuilder;createdDate;lastModifiedDate}class ne extends E{id;name;url;version;apiVersion;totalNodeCount;dmlCreateNodeCount;dmlDeleteNodeCount;dmlUpdateNodeCount;screenNodeCount;isActive;description;type;runningMode;createdDate;lastModifiedDate;sobject;triggerType}class oe extends f{static get label(){return"Profile"}id;url;name;description;license;isCustom;package;memberCounts;createdDate;lastModifiedDate;nbFieldPermissions;nbObjectPermissions;type;importantPermissions}class le extends oe{static get label(){return"Permission Set or Permission Set Group"}isGroup;groupId}class ce extends f{static get label(){return"User"}id;url;name;lastLogin;numberFailedLogins;onLightningExperience;lastPasswordChange;profileId;profileRef;aggregateImportantPermissions;permissionSetIds;permissionSetRefs}class de extends f{static get label(){return"Public Group or Queue"}id;url;name;developerName;includeBosses;includeSubordinates;relatedId;nbDirectMembers;directUserIds;directUserRefs;directGroupIds;directGroupRefs;isPublicGroup;isQueue;type}class pe extends S{static get label(){return"Aura Component"}id;name;apiVersion;package;createdDate;lastModifiedDate;description;url}class ge extends S{static get label(){return"Lightning Web Component"}id;name;apiVersion;package;createdDate;lastModifiedDate;description;url}class ue extends f{static get label(){return"Permission Set License"}id;name;totalCount;usedCount;usedPercentage;remainingCount;permissionSetIds;permissionSetRefs;distinctActiveAssigneeCount;status;expirationDate;isAvailableForIntegrations;createdDate;lastModifiedDate;url}class he extends f{static get label(){return"Password Policy from a Profile"}lockoutInterval;maxLoginAttempts;minimumPasswordLength;minimumPasswordLifetime;obscure;passwordComplexity;passwordExpiration;passwordHistory;passwordQuestion;profileName}class me extends f{static get label(){return"Restrictions from Profile"}profileId;profileRef;ipRanges;loginHours}class fe extends E{static get label(){return"IP Range Restriction from Profile"}startAddress;endAddress;description;difference}class Se extends E{static get label(){return"Login Hour Restriction from Profile"}fromTime;toTime;day;difference}class Ee extends f{static get label(){return"Role"}id;name;apiname;url;parentId;parentRef;level;hasParent;activeMembersCount;activeMemberIds;activeMemberRefs;hasActiveMembers}class Ie extends S{static get label(){return"Visualforce Component"}id;name;apiVersion;hardCodedURLs;hardCodedIDs;package;createdDate;lastModifiedDate;description;url}class we extends S{static get label(){return"Visualforce Page"}id;name;apiVersion;hardCodedURLs;hardCodedIDs;isMobileReady;package;createdDate;lastModifiedDate;description;url}class Pe extends f{static get label(){return"Workflow"}id;name;url;description;actions;futureActions;emptyTimeTriggers;isActive;createdDate;lastModifiedDate;hasAction}const Re=(e,t,s=3)=>!!(t&&e&&s)&&(e-t)/3>=s,Te=e=>("number"!=typeof e||0!==e)&&(!e||(0===e.length||"string"==typeof e&&0===e.trim().length)),ye=[{id:0,description:"Not referenced anywhere",formula:e=>!1===e.dependencies?.hadError&&Te(e.dependencies?.referenced),errorMessage:"This component is not referenced anywhere (as we were told by the Dependency API). Please review the need to keep it in your org.",badField:"dependencies.referenced.length",applicable:[re,ie,B,pe,ge,Ie,we]},{id:1,description:"No reference anywhere for custom field",formula:e=>!0===e.isCustom&&!1===e.dependencies?.hadError&&Te(e.dependencies?.referenced),errorMessage:"This custom field is not referenced anywhere (as we were told by the Dependency API). Please review the need to keep it in your org.",badField:"dependencies.referenced.length",applicable:[G]},{id:2,description:"No reference anywhere for apex class",formula:e=>!1===e.isTest&&!1===e.dependencies?.hadError&&Te(e.dependencies?.referenced),errorMessage:"This apex class is not referenced anywhere (as we were told by the Dependency API). Please review the need to keep it in your org.",badField:"dependencies.referenced.length",applicable:[b]},{id:3,description:"Sorry, we had an issue with the Dependency API to gather the dependencies of this item",formula:e=>e.dependencies&&!0===e.dependencies.hadError,errorMessage:"Sorry, we had an issue with the Dependency API to gather the dependencies of this item.",badField:"dependencies.referenced.length",applicable:[G,b,re,ie,B,pe,ge,Ie,we]},{id:4,description:"API Version too old",formula:e=>Re(Ae.CurrentApiVersion,e.apiVersion),errorMessage:"The API version of this component is too old. Please update it to a newest version.",badField:"apiVersion",applicable:[b,ae,ie,pe,ge,we,Ie]},{id:5,description:"No assert in this Apex Test",formula:e=>!0===e.isTest&&0===e.nbSystemAsserts,errorMessage:"This apex test does not contain any assert! Best practices force you to define asserts in tests.",badField:"nbSystemAsserts",applicable:[b]},{id:6,description:"No description",formula:e=>Te(e.description),errorMessage:"This component does not have a description. Best practices force you to use the Description field to give some informative context about why and how it is used/set/govern.",badField:"description",applicable:[ie,B,pe,ge,we,Ie,Pe,te,$,ee]},{id:7,description:"No description for custom component",formula:e=>!0===e.isCustom&&Te(e.description),errorMessage:"This custom component does not have a description. Best practices force you to use the Description field to give some informative context about why and how it is used/set/govern.",badField:"description",applicable:[G,le,oe]},{id:8,description:"No explicit sharing in apex class",formula:e=>!1===e.isTest&&!0===e.isClass&&!e.specifiedSharing,errorMessage:"This Apex Class does not specify a sharing model. Best practices force you to specify with, without or inherit sharing to better control the visibility of the data you process in Apex.",badField:"specifiedSharing",applicable:[b]},{id:9,description:"Schedulable should be scheduled",formula:e=>!1===e.isScheduled&&!0===e.isSchedulable,errorMessage:"This Apex Class implements Schedulable but is not scheduled. What is the point? Is this class still necessary?",badField:"isScheduled",applicable:[b]},{id:10,description:"Not able to compile class",formula:e=>!0===e.needsRecompilation,errorMessage:"This Apex Class can not be compiled for some reason. You should try to recompile it. If the issue remains you need to consider refactorying this class or the classes that it is using.",badField:"name",applicable:[b]},{id:11,description:"No coverage for this class",formula:e=>!1===e.isTest&&(isNaN(e.coverage)||!e.coverage),errorMessage:"This Apex Class does not have any code coverage. Consider launching the corresponding tests that will bring some coverage. If you do not know which test to launch just run them all!",badField:"coverage",applicable:[b]},{id:12,description:"Coverage not enough",formula:e=>e.coverage>0&&e.coverage<.75,errorMessage:"This Apex Class does not have enough code coverage (less than 75% of lines are covered by successful unit tests). Maybe you ran not all the unit tests to cover this class entirely? If you did, then consider augmenting that coverage with new test methods.",badField:"coverage",applicable:[b]},{id:13,description:"At least one testing method failed",formula:e=>!0===e.isTest&&e.testFailedMethods&&e.testFailedMethods.length>0,errorMessage:"This Apex Test Class has at least one failed method.",badField:"testFailedMethods",applicable:[b]},{id:14,description:"Apex trigger should not contain SOQL statement",formula:e=>!0===e.hasSOQL,errorMessage:"This Apex Trigger contains at least one SOQL statement. Best practices force you to move any SOQL statement in dedicated Apex Classes that you would call from the trigger. Please update the code accordingly.",badField:"hasSOQL",applicable:[ae]},{id:15,description:"Apex trigger should not contain DML action",formula:e=>!0===e.hasDML,errorMessage:"This Apex Trigger contains at least one DML action. Best practices force you to move any DML action in dedicated Apex Classes that you would call from the trigger. Please update the code accordingly.",badField:"hasDML",applicable:[ae]},{id:16,description:"Apex Trigger should not contain logic",formula:e=>e.length>5e3,errorMessage:"Due to the massive number of source code (more than 5000 characters) in this Apex Trigger, we suspect that it contains logic. Best practices force you to move any logic in dedicated Apex Classes that you would call from the trigger. Please update the code accordingly.",badField:"length",applicable:[ae]},{id:17,description:"No direct member for this group",formula:e=>!e.nbDirectMembers||0===e.nbDirectMembers,errorMessage:"This public group (or queue) does not contain any direct members (users or sub groups). Is it empty on purpose? Maybe you should review its use in your org...",badField:"nbDirectMembers",applicable:[de]},{id:18,description:"Custom permset or profile with no member",formula:e=>!0===e.isCustom&&0===e.memberCounts,errorMessage:"This custom permission set (or custom profile) has no members. Is it empty on purpose? Maybe you should review its use in your org...",badField:"memberCounts",applicable:[le,oe]},{id:19,description:"Role with no active users",formula:e=>0===e.activeMembersCount,errorMessage:"This role has no active users assigned to it. Is it on purpose? Maybe you should review its use in your org...",badField:"activeMembersCount",applicable:[Ee]},{id:20,description:"Active user not under LEX",formula:e=>!1===e.onLightningExperience,errorMessage:"This user is still using Classic. Time to switch to Lightning for all your users, don't you think?",badField:"onLightningExperience",applicable:[ce]},{id:21,description:"Active user never logged",formula:e=>null===e.lastLogin,errorMessage:"This active user never logged yet. Time to optimize your licence cost!",badField:"lastLogin",applicable:[ce]},{id:22,description:"Workflow with no action",formula:e=>!1===e.hasAction,errorMessage:"This workflow has no action, please review it and potentially remove it.",badField:"hasAction",applicable:[Pe]},{id:23,description:"Workflow with empty time triggered list",formula:e=>e.emptyTimeTriggers.length>0,errorMessage:"This workflow is time triggered but with no time triggered action, please review it.",badField:"emptyTimeTriggers",applicable:[Pe]},{id:24,description:"Password policy with question containing password!",formula:e=>!0===e.passwordQuestion,errorMessage:"This profile password policy allows to have password in the question! Please change that setting as it is clearly a lack of security in your org!",badField:"passwordQuestion",applicable:[he]},{id:25,description:"Password policy with too big expiration",formula:e=>e.passwordExpiration>90,errorMessage:"This profile password policy allows to have password that expires after 90 days. Please consider having a shorter period of time for expiration if you policy.",badField:"passwordExpiration",applicable:[he]},{id:26,description:"Password policy with no expiration",formula:e=>0===e.passwordExpiration,errorMessage:"This profile password policy allows to have password that never expires. Why is that? Do you have this profile for technical users? Please reconsider this setting and use JWT authentication instead for technical users.",badField:"passwordExpiration",applicable:[he]},{id:27,description:"Password history too small",formula:e=>e.passwordHistory<3,errorMessage:"This profile password policy allows users to set their password with a too-short memory. For example, they can keep on using the same different password everytime you ask them to change it. Please increase this setting.",badField:"passwordHistory",applicable:[he]},{id:28,description:"Password minimum size too small",formula:e=>e.minimumPasswordLength<8,errorMessage:"This profile password policy allows users to set passwords with less than 8 charcaters. That minimum length is not strong enough. Please increase this setting.",badField:"minimumPasswordLength",applicable:[he]},{id:29,description:"Password complexity too weak",formula:e=>e.passwordComplexity<3,errorMessage:"This profile password policy allows users to set too-easy passwords. The complexity you choose is not storng enough. Please increase this setting.",badField:"passwordComplexity",applicable:[he]},{id:30,description:"No max login attempts set",formula:e=>void 0===e.maxLoginAttempts,errorMessage:"This profile password policy allows users to try infinitely to log in without locking the access. Please review this setting.",badField:"passwordExpiration",applicable:[he]},{id:31,description:"No lockout period set",formula:e=>void 0===e.lockoutInterval,errorMessage:"This profile password policy does not set a value for any locked out period. Please review this setting.",badField:"lockoutInterval",applicable:[he]},{id:32,description:"IP Range too large",formula:e=>e.ipRanges.filter((e=>e.difference>1e5)).length>0,errorMessage:"This profile includes an IP range that is to wide (more than 100.000 IP addresses!). If you set an IP Range it should be not that large. You could split that range into multiple ones. The risk is that you include an IP that is not part of your company. Please review this setting.",badField:"ipRanges",applicable:[me]},{id:33,description:"Login hours too large",formula:e=>e.loginHours.filter((e=>e.difference>1200)).length>0,errorMessage:"This profile includes a login hour that is to wide (more than 20 hours a day!). If you set a login hour it should reflect the reality. Please review this setting.",badField:"loginHours",applicable:[me]},{id:34,description:"Inactive component",formula:e=>!1===e.isActive,errorMessage:"This component is inactive, so why do not you just remove it from your org?",badField:"isActive",applicable:[ee,Z,ae,Pe]},{id:35,description:"No active version for this flow",formula:e=>!1===e.isVersionActive,errorMessage:"This flow does not have an active version, did you forgot to activate its latest version? or you do not need that flow anymore?",badField:"isVersionActive",applicable:[ie]},{id:36,description:"Too many versions under this flow",formula:e=>e.versionsCount>7,errorMessage:"This flow has more than seven versions. Maybe it is time to do some cleaning in this flow!",badField:"versionsCount",applicable:[ie]},{id:37,description:"Migrate this process builder",formula:e=>"Workflow"===e.currentVersionRef?.type,errorMessage:"Time to migrate this process builder to flow!",badField:"name",applicable:[ie]},{id:38,description:"No description for the current version of a flow",formula:e=>Te(e.currentVersionRef?.description),errorMessage:"This flow's current version does not have a description. Best practices force you to use the Description field to give some informative context about why and how it is used/set/govern.",badField:"currentVersionRef.description",applicable:[ie]},{id:39,description:"API Version too old for the current version of a flow",formula:e=>Re(Ae.CurrentApiVersion,e.currentVersionRef?.apiVersion),errorMessage:"The API version of this flow's current version is too old. Please update it to a newest version.",badField:"currentVersionRef.apiVersion",applicable:[ie]},{id:40,description:"This flow is running without sharing",formula:e=>"SystemModeWithoutSharing"===e.currentVersionRef?.runningMode,errorMessage:"The running mode of this version without sharing. With great power comes great responsabilities. Please check if this is REALLY needed.",badField:"currentVersionRef.runningMode",applicable:[ie]},{id:41,description:"Too many nodes in this version",formula:e=>e.currentVersionRef?.totalNodeCount>100,errorMessage:"There are more than one hundred of nodes in this flow. Please consider using Apex? or cut it into multiple sub flows?",badField:"currentVersionRef.totalNodeCount",applicable:[ie]},{id:42,description:"Near the limit",formula:e=>e.usedPercentage>=.8,errorMessage:"This limit is almost reached (>80%). Please review this.",badField:"usedPercentage",applicable:[W]},{id:43,description:"Almost all licenses are used",formula:e=>void 0!==e.usedPercentage&&e.usedPercentage>=.8,errorMessage:"The number of seats for this license is almost reached (>80%). Please review this.",badField:"usedPercentage",applicable:[ue]},{id:44,description:"You could have licenses to free up",formula:e=>e.remainingCount>0&&e.distinctActiveAssigneeCount!==e.usedCount,errorMessage:"The Used count from that permission set license does not match the number of disctinct active user assigned to the same license. Please check if you could free up some licenses!",badField:"distinctActiveAssigneeCount",applicable:[ue]},{id:45,description:"Role with a level >= 7",formula:e=>e.level>=7,errorMessage:"This role has a level in the Role Hierarchy which is seven or greater. Please reduce the maximum depth of the role hierarchy. Having that much levels has an impact on performance...",badField:"level",applicable:[Ee]},{id:46,description:"Hard-coded URL suspicion in this item",formula:e=>e.hardCodedURLs?.length>0||!1,errorMessage:"The source code of this item contains one or more hard coded URLs pointing to domains like salesforce.com or force.*",badField:"hardCodedURLs",applicable:[b,ae,G,Ie,we,te]},{id:47,description:"Hard-coded Salesforce IDs suspicion in this item",formula:e=>e.hardCodedIDs?.length>0||!1,errorMessage:"The source code of this item contains one or more hard coded Salesforce IDs",badField:"hardCodedIDs",applicable:[b,ae,G,Ie,we,te]},{id:48,description:"At least one successful testing method was very long",formula:e=>!0===e.isTest&&e.testPassedButLongMethods&&e.testPassedButLongMethods.length>0,errorMessage:"This Apex Test Class has at least one successful method which took more than 20 secondes to execute",badField:"testPassedButLongMethods",applicable:[b]}],Ce=new Map(ye.map((e=>[e.id,e]))),Ae={AllScoreRules:ye,GetScoreRule:e=>Ce.get(e),GetScoreRuleDescription:e=>Ce.get(e).description,CurrentApiVersion:(()=>{const e=new Date,t=e.getFullYear(),s=e.getMonth()+1;return 3*(t-2022)+53+(s<=2?0:s<=6?1:s<=10?2:3)})()};Object.freeze(Ae);class Oe extends E{static get label(){return"Application"}id;name;label;package}class be extends E{static get label(){return"Application Permission from Profile or Permission Set"}parentId;parentRef;appId;appRef;isAccessible;isVisible}class Me extends E{static get label(){return"Field Level Security from Profile or Permission Set"}parentId;parentRef;fieldApiName;isRead;isEdit}class De extends f{static get label(){return"Object Permissions from Profile or Permission Set"}parentId;parentRef;objectType;isRead;isCreate;isEdit;isDelete;isViewAll;isModifyAll}class _e extends E{static get label(){return"Organization"}id;name;type;isDeveloperEdition;isSandbox;isTrial;isProduction;localNamespace}class Le extends f{static get label(){return"Package"}id;name;namespace;type}class Ne extends t{_compress;_decompress;_encode;_decode;_storageSetItem;_storageGetItem;_storageRemoveItem;_storageKey;_storageKeys;_storageLength;constructor(e){super(),this._compress=e.compress,this._decompress=e.decompress,this._encode=e.encode,this._decode=e.decode,this._storageSetItem=e.storage.setItem,this._storageGetItem=e.storage.getItem,this._storageRemoveItem=e.storage.removeItem,this._storageKey=e.storage.key,this._storageLength=e.storage.length,this._storageKeys=e.storage.keys}has(e){const t=Ge(e),s=ve(e),a=this._getEntryFromCache(t);if(null===a)this._storageRemoveItem(t),this._storageRemoveItem(s);else{let e=!1;for(let t=0;t!1===e.endsWith("Ref")))),created:e}:{content:t,created:e};try{this._setItemToCache(a,JSON.stringify(i)),this._setItemToCache(s,JSON.stringify(r))}catch(e){this._storageRemoveItem(s),this._storageRemoveItem(a)}}}details(){return this._storageKeys().filter((e=>e.startsWith(Ue))).map((e=>{const t=this._getEntryFromCache(e),s=$e(e);return t?{name:s,isEmpty:0===t.length,isMap:"map"===t.type,length:t.length,created:t.created}:{name:s,isEmpty:!0,isMap:!1,length:0,created:0}}))}remove(e){this._storageRemoveItem(ve(e)),this._storageRemoveItem(Ge(e))}clear(){return this._storageKeys().filter((e=>e.startsWith(xe))).forEach((e=>this._storageRemoveItem(e)))}_setItemToCache=(e,t)=>{let s,a,r;try{s=this._encode(t),a=this._compress(s),r=ke(a),this._storageSetItem(e,r)}catch(t){throw new Error(`Error occured when trying to save the value for key ${e} with: hexValue.length=${r?.length||"N/A"}, compressedValue.length=${a?.length||"N/A"}, encodedValue.length=${s?.length||"N/A"}. Initiale error message was ${t.message}`)}};_getEntryFromCache=e=>{let t=null;try{const s=this._storageGetItem(e);if(s){const e=je(s),a=this._decompress(e);t=this._decode(a)}}catch(t){console.error(`Error occured when trying to get the value for key ${e}`,t)}if(!t)return null;try{const e=JSON.parse(t);return e.created&&Date.now()-e.created>Be?null:e}catch(e){return console.error(`Error occured when trying to parse the string: ${t}`,e),null}}}const xe="OrgCheck",Fe=`${xe}.`,Ue=`${xe}_`,ve=e=>e.startsWith(Fe)?e:Fe+e,Ge=e=>e.startsWith(Ue)?e:Ue+e,$e=e=>e.startsWith(Ue)?e.substring(Ue.length):e.startsWith(Fe)?e.substring(Fe.length):e,Be=864e5,We=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"],Ve=new Array(256);for(let e=0;e<256;e++)Ve[e]=`${We[e>>>4&15]}${We[15&e]}`;const ke=e=>{let t="";for(let s=0,a=e.length;s{const t=[];for(let s=0;s[e.caseSafeId(t.Id),{qualifiedApiName:t.EntityDefinition.QualifiedApiName,isCustomSetting:t.EntityDefinition.IsCustomSetting}]),(e=>!!e.EntityDefinition&&(!Qe.includes(e.EntityDefinition.KeyPrefix)&&!e.EntityDefinition.QualifiedApiName?.endsWith("_hd")))));s?.log(`Retrieving dependencies of ${o.length} custom fields...`);const c=await e.dependenciesQuery(await N.map(o,(t=>e.caseSafeId(t.Id))),s);s?.log(`Calling Tooling API Composite to get more information about these ${l.size} custom fields...`);const d=await e.readMetadataAtScale("CustomField",Array.from(l.keys()),[],s);s?.log(`Parsing ${d.length} custom fields...`);const p=new Map(await N.map(d,(t=>{const s=e.caseSafeId(t.Id),a=l.get(s),r=n.create({properties:{id:s,name:t.DeveloperName,label:t.Metadata.label,package:t.NamespacePrefix||"",description:t.Description,isCustom:!0,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,objectId:a.qualifiedApiName,tooltip:t.InlineHelpText,type:t.Metadata.type,length:t.Metadata.length,isUnique:!0===t.Metadata.unique,isEncrypted:null!==t.Metadata.encryptionScheme&&"None"!==t.Metadata.encryptionScheme,isExternalId:!0===t.Metadata.externalId,isIndexed:!0===t.Metadata.unique||!0===t.Metadata.externalId,defaultValue:t.Metadata.defaultValue,isRestrictedPicklist:t.Metadata.valueSet&&!0===t.Metadata.valueSet.restricted,formula:t.Metadata.formula,url:e.setupUrl(s,v.CUSTOM_FIELD,a.qualifiedApiName,e.getObjectType(a.qualifiedApiName,a.isCustomSetting))},dependencies:{data:c}});if(r.formula){const e=g.RemoveComments(r.formula);r.hardCodedURLs=g.FindHardCodedURLs(e),r.hardCodedIDs=g.FindHardCodedIDs(e)}return n.computeScore(r),[r.id,r]})));return s?.log("Done"),p}}class He extends D{async run(e,t,s){s?.log("Querying Tooling API about ExternalString in the org...");const a=await e.soqlQuery([{tooling:!0,string:"SELECT Id, Name, NamespacePrefix, Category, IsProtected, Language, MasterLabel, Value, CreatedDate, LastModifiedDate FROM ExternalString WHERE ManageableState IN ('installedEditable', 'unmanaged') "}],s),r=t.getInstance(re),i=a[0];s?.log(`Retrieving dependencies of ${i.length} custom labels...`);const n=await e.dependenciesQuery(await N.map(i,(t=>e.caseSafeId(t.Id))),s);s?.log(`Parsing ${i.length} custom labels...`);const o=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.createWithScore({properties:{id:s,name:t.Name,package:t.NamespacePrefix||"",category:t.Category,isProtected:!0===t.IsProtected,language:t.Language,label:t.MasterLabel,value:t.Value,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,url:e.setupUrl(s,v.CUSTOM_LABEL)},dependencies:{data:n}});return[a.id,a]})));return s?.log("Done"),o}}class Je extends D{async run(e,t,s,a){const r=t.getInstance(G),i=t.getInstance($),n=t.getInstance(z),o=t.getInstance(W),l=t.getInstance(ee),c=t.getInstance(te),d=t.getInstance(Z),p=t.getInstance(V),u=t.getInstance(se),h=a?.get("object"),m=h.split("__"),f=3===m.length?m[0]:"",S=await Promise.all([e.describe(h,s),e.soqlQuery([{tooling:!0,string:`SELECT Id, DurableId, DeveloperName, Description, NamespacePrefix, ExternalSharingModel, InternalSharingModel, (SELECT Id FROM ApexTriggers), (SELECT Id, MasterLabel, Description FROM FieldSets), (SELECT Id, Name, LayoutType FROM Layouts), (SELECT DurableId, Label, Max, Remaining, Type FROM Limits), (SELECT Id, Active, Description, ErrorDisplayField, ErrorMessage, ValidationName, NamespacePrefix, CreatedDate, LastModifiedDate FROM ValidationRules), (SELECT Id, Name, Url, LinkType, OpenType, Description, CreatedDate, LastModifiedDate, NamespacePrefix FROM WebLinks) FROM EntityDefinition WHERE QualifiedApiName = '${h}' `+(f?`AND NamespacePrefix = '${f}' `:"")+"LIMIT 1"},{tooling:!0,string:`SELECT DurableId, QualifiedApiName, Description, IsIndexed FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName = '${h}' `+(f?`AND EntityDefinition.NamespacePrefix = '${f}' `:""),queryMoreField:"DurableId"}],s),e.recordCount(h,s)]),E=S[0],I=e.getObjectType(E.name,E.customSetting),w=S[1][0][0];if(!w)throw new TypeError(`No entity definition record found for: ${h}`);const P=S[1][1],R=S[2],T=[],y=new Map;await N.forEach(P,(t=>{if(t&&t.DurableId&&t.DurableId.split&&t.DurableId.includes){const s=e.caseSafeId(t.DurableId.split(".")[1]);t.DurableId?.includes(".00N")?T.push(s):y.set(t.QualifiedApiName,{id:s,description:t.Description,isIndexed:t.IsIndexed})}}));const C=await N.map(E.fields,(t=>{const s=y.get(t.name);return r.createWithScore({properties:{id:s.id,name:t.label,label:t.label,description:s.description,tooltip:t.inlineHelpText,type:t.type,length:t.length,isUnique:t.unique,isEncrypted:t.encrypted,isExternalId:t.externalId,isIndexed:s.isIndexed,defaultValue:t.defaultValue,formula:t.calculatedFormula,url:e.setupUrl(s.id,v.STANDARD_FIELD,w.DurableId,I)}})}),(e=>y.has(e.name))),A=await N.map(w.ApexTriggers?.records,(t=>e.caseSafeId(t.Id))),O=await N.map(w.FieldSets?.records,(t=>i.createWithScore({properties:{id:e.caseSafeId(t.Id),label:t.MasterLabel,description:t.Description,url:e.setupUrl(t.Id,v.FIELD_SET,w.DurableId)}}))),b=await N.map(w.Layouts?.records,(t=>n.createWithScore({properties:{id:e.caseSafeId(t.Id),name:t.Name,type:t.LayoutType,url:e.setupUrl(t.Id,v.PAGE_LAYOUT,w.DurableId)}}))),M=await N.map(w.Limits?.records,(t=>o.createWithScore({properties:{id:e.caseSafeId(t.DurableId),label:t.Label,max:t.Max,remaining:t.Remaining,used:t.Max-t.Remaining,usedPercentage:(t.Max-t.Remaining)/t.Max,type:t.Type}}))),D=await N.map(w.ValidationRules?.records,(t=>l.createWithScore({properties:{id:e.caseSafeId(t.Id),name:t.ValidationName,isActive:t.Active,description:t.Description,errorDisplayField:t.ErrorDisplayField,errorMessage:t.ErrorMessage,package:t.NamespacePrefix||"",createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,url:e.setupUrl(t.Id,v.VALIDATION_RULE)}}))),_=await N.map(w.WebLinks?.records,(t=>c.createWithScore({properties:{id:e.caseSafeId(t.Id),name:t.Name,hardCodedURLs:g.FindHardCodedURLs(t.Url),hardCodedIDs:g.FindHardCodedIDs(t.Url),type:t.LinkType,behavior:t.OpenType,package:t.NamespacePrefix,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,description:t.Description,url:e.setupUrl(t.Id,v.WEB_LINK,w.DurableId)}}))),L=await N.map(E.recordTypeInfos,(t=>d.createWithScore({properties:{id:e.caseSafeId(t.recordTypeId),name:t.name,developerName:t.developerName,isActive:t.active,isAvailable:t.available,isDefaultRecordTypeMapping:t.defaultRecordTypeMapping,isMaster:t.master,url:e.setupUrl(t.recordTypeId,v.RECORD_TYPE,w.DurableId)}}))),x=await N.map(E.childRelationships,(e=>p.createWithScore({properties:{name:e.relationshipName,childObject:e.childSObject,fieldName:e.field,isCascadeDelete:e.cascadeDelete,isRestrictedDelete:e.restrictedDelete}})),(e=>null!==e.relationshipName)),F=u.createWithScore({properties:{id:w.DurableId,label:E.label,labelPlural:E.labelPlural,isCustom:E.custom,isFeedEnabled:E.feedEnabled,isMostRecentEnabled:E.mruEnabled,isSearchable:E.searchable,keyPrefix:E.keyPrefix,name:w.DeveloperName,apiname:E.name,package:w.NamespacePrefix||"",typeId:I,description:w.Description,externalSharingModel:w.ExternalSharingModel,internalSharingModel:w.InternalSharingModel,apexTriggerIds:A,fieldSets:O,limits:M,layouts:b,validationRules:D,webLinks:_,standardFields:C,customFieldIds:T,recordTypes:L,relationships:x,recordCount:R,url:e.setupUrl(w.Id,I)}});return s?.log("Done"),F}}class Ye extends D{async run(e,t,s){s?.log("Querying REST API about ObjectPermissions in the org...");const a=await e.soqlQuery([{string:"SELECT ParentId, Parent.IsOwnedByProfile, Parent.ProfileId, SobjectType, CreatedDate, LastModifiedDate,PermissionsRead, PermissionsCreate, PermissionsEdit, PermissionsDelete, PermissionsViewAllRecords, PermissionsModifyAllRecords FROM ObjectPermissions"}],s),r=t.getInstance(De),i=a[0];s?.log(`Parsing ${i.length} object permissions...`);const n=new Map(await N.map(i,(t=>{const s=r.create({properties:{parentId:e.caseSafeId(!0===t.Parent.IsOwnedByProfile?t.Parent.ProfileId:t.ParentId),objectType:t.SobjectType,isRead:t.PermissionsRead,isCreate:t.PermissionsCreate,isEdit:t.PermissionsEdit,isDelete:t.PermissionsDelete,isViewAll:t.PermissionsViewAllRecords,isModifyAll:t.PermissionsModifyAllRecords,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate}});return[`${s.parentId}_${s.objectType}`,s]}),(e=>null!==e.Parent)));return s?.log("Done"),n}}class Xe extends D{async run(e,t,s){s?.log("Querying REST API about SetupEntityAccess for TabSet in the org...");const a=await e.soqlQuery([{string:"SELECT ApplicationId, IsAccessible, IsVisible FROM AppMenuItem WHERE Type = 'TabSet' "},{string:"SELECT SetupEntityId, ParentId, Parent.IsOwnedByProfile, Parent.ProfileId FROM SetupEntityAccess WHERE SetupEntityType = 'TabSet' "}],s),r=t.getInstance(be),i=a[0],n=a[1];s?.log(`Parsing ${i.length} Application Menu Items...`);const o=new Map(await N.map(i,(t=>[e.caseSafeId(t.ApplicationId),{a:t.IsAccessible,v:t.IsVisible}])));s?.log(`Parsing ${n.length} Application Menu Items...`);const l=new Map(await N.map(n,(t=>{const s=e.caseSafeId(t.SetupEntityId),a=e.caseSafeId(t.Parent.IsOwnedByProfile?t.Parent.ProfileId:t.ParentId),i=o.get(s);return[`${s}-${a}`,r.create({properties:{appId:s,parentId:a,isAccessible:i.a,isVisible:i.v}})]}),(t=>o.has(e.caseSafeId(t.SetupEntityId)))));return s?.log("Done"),l}}class Ke extends D{async run(e,t,s){const a=t.getInstance(se);s?.log("Performing a global describe and in parallel a SOQL query to EntityDefinition...");const r=await Promise.all([e.describeGlobal(s),e.soqlQuery([{string:"SELECT DurableId, NamespacePrefix, DeveloperName, QualifiedApiName, ExternalSharingModel, InternalSharingModel FROM EntityDefinition WHERE keyPrefix <> null AND DeveloperName <> null AND (NOT(keyPrefix IN ('00a', '017', '02c', '0D5', '1CE'))) AND (NOT(QualifiedApiName like '%_hd')) ",tooling:!0,queryMoreField:"DurableId"}],s)]),i=r[0],n=r[1][0],o={},l=await N.map(n,(e=>(o[e.QualifiedApiName]=e,e.QualifiedApiName)));s?.log(`Parsing ${i.length} objects...`);const c=new Map(await N.map(i,(t=>{const s=e.getObjectType(t.name,t.customSetting),r=o[t.name],i=a.create({properties:{id:t.name,label:t.label,name:r.DeveloperName,apiname:t.name,package:r.NamespacePrefix||"",typeId:s,externalSharingModel:r.ExternalSharingModel,internalSharingModel:r.InternalSharingModel,url:e.setupUrl(r.DurableId,s)}});return[i.id,i]}),(e=>!!l?.includes(e.name))));return s?.log("Done"),c}}const ze=[{id:j,label:"Standard Object"},{id:Q,label:"Custom Object"},{id:q,label:"External Object"},{id:H,label:"Custom Setting"},{id:J,label:"Custom Metadata Type"},{id:Y,label:"Platform Event"},{id:X,label:"Knowledge Article"},{id:K,label:"Big Object"}];class Ze extends D{async run(e,t,s){const a=t.getInstance(k);return new Map(ze.map((e=>[e.id,a.create({properties:{id:e.id,label:e.label}})])))}}const et="Production",tt="Developer Edition",st="Sandbox",at="Trial";class rt extends D{async run(e,t,s){s?.log("Querying REST API about Organization in the org...");const a=await e.soqlQuery([{string:"SELECT Id, Name, IsSandbox, OrganizationType, TrialExpirationDate, NamespacePrefix FROM Organization LIMIT 1"}],s);s?.log(`Received result=${JSON.stringify(a)}`),s?.log("We need to get the first result and from there the first record...");const r=a[0][0];s?.log("Parsing the result...");const i=t.getInstance(_e);let n;n="Developer Edition"===r.OrganizationType?tt:!0===r.IsSandbox?st:!1===r.IsSandbox&&r.TrialExpirationDate?at:et;const o=i.create({properties:{id:e.caseSafeId(r.Id),name:r.Name,type:n,isDeveloperEdition:n===tt,isSandbox:n===st,isTrial:n===at,isProduction:n===et,localNamespace:r.NamespacePrefix||""}});return s?.log("Done"),o}}class it extends D{async run(e,t,s,a){const r=a?.get("permissions");s?.log("Querying REST API about UserPermissionAccess in the org...");const i=(await e.soqlQuery([{string:`SELECT ${r.map((e=>`Permissions${e}`)).join(", ")} FROM UserPermissionAccess LIMIT 1`}],s))[0][0];return s?.log("Parsing the results..."),new Map(await N.map(Object.keys(i),(e=>[e,i[e]]),(e=>e.startsWith("Permissions"))))}}class nt extends D{async run(e,t,s){s?.log("Querying Tooling API about InstalledSubscriberPackage and REST API about Organization in the org...");const a=await e.soqlQuery([{tooling:!0,string:"SELECT Id, SubscriberPackage.NamespacePrefix, SubscriberPackage.Name FROM InstalledSubscriberPackage "},{string:"SELECT NamespacePrefix FROM Organization LIMIT 1 "}],s),r=t.getInstance(Le),i=a[0];s?.log(`Parsing ${i.length} installed packages...`);const n=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.create({properties:{id:s,name:t.SubscriberPackage.Name,namespace:t.SubscriberPackage.NamespacePrefix,type:"Installed"}});return[a.id,a]}))),o=a[1][0].NamespacePrefix;return o&&(s?.log(`Adding your local package ${o}...`),n.set(o,r.create({properties:{id:o,name:o,namespace:o,type:"Local"}}))),s?.log("Done"),n}}class ot extends D{async run(e,t,s){s?.log("Querying REST API about PermissionSet, PermissionSetAssignment and PermissionSet (with a PermissionSetGroupId populated) in the org...");const a=await e.soqlQuery([{string:"SELECT Id, Name, Description, IsCustom, License.Name, NamespacePrefix, Type, PermissionsApiEnabled, PermissionsViewSetup, PermissionsModifyAllData, PermissionsViewAllData, CreatedDate, LastModifiedDate FROM PermissionSet WHERE IsOwnedByProfile = FALSE ORDER BY Id LIMIT 2000"},{byPasses:["INVALID_TYPE"],string:"SELECT Id, PermissionSetGroupId, PermissionSetGroup.Description FROM PermissionSet WHERE PermissionSetGroupId != null ORDER BY Id LIMIT 2000"},{string:"SELECT ParentId, COUNT(SobjectType) CountObject FROM ObjectPermissions WHERE Parent.IsOwnedByProfile = FALSE GROUP BY ParentId ORDER BY ParentId LIMIT 2000"},{string:"SELECT ParentId, COUNT(Field) CountField FROM FieldPermissions WHERE Parent.IsOwnedByProfile = FALSE GROUP BY ParentId ORDER BY ParentId LIMIT 2000"},{string:"SELECT PermissionSetId, COUNT(Id) CountAssignment FROM PermissionSetAssignment WHERE PermissionSet.IsOwnedByProfile = FALSE GROUP BY PermissionSetId ORDER BY PermissionSetId LIMIT 2000"}],s),r=a[0],i=a[1],n=a[2],o=a[3],l=a[4],c=t.getInstance(le);s?.log(`Parsing ${r.length} permission sets...`);const d=new Map(await N.map(r,(t=>{const s=e.caseSafeId(t.Id),a="Group"===t.Type,r=c.create({properties:{id:s,name:t.Name,description:t.Description,license:t.License?t.License.Name:"",isCustom:t.IsCustom,package:t.NamespacePrefix||"",memberCounts:0,isGroup:a,type:a?"Permission Set Group":"Permission Set",createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,nbFieldPermissions:0,nbObjectPermissions:0,importantPermissions:{apiEnabled:!0===t.PermissionsApiEnabled,viewSetup:!0===t.PermissionsViewSetup,modifyAllData:!0===t.PermissionsModifyAllData,viewAllData:!0===t.PermissionsViewAllData},url:!1===a?e.setupUrl(s,v.PERMISSION_SET):""}});return[r.id,r]})));return s?.log(`Parsing ${i.length} permission set groups, ${n.length} object permissions and ${o.length} field permissions...`),await Promise.all([N.forEach(i,(t=>{const s=e.caseSafeId(t.Id),a=e.caseSafeId(t.PermissionSetGroupId);if(d.has(s)){const t=d.get(s);t.isGroup=!0,t.groupId=a,t.url=e.setupUrl(a,v.PERMISSION_SET_GROUP)}})),N.forEach(n,(t=>{const s=e.caseSafeId(t.ParentId);if(d.has(s)){d.get(s).nbObjectPermissions=t.CountObject}})),N.forEach(o,(t=>{const s=e.caseSafeId(t.ParentId);if(d.has(s)){d.get(s).nbFieldPermissions=t.CountField}})),N.forEach(l,(t=>{const s=e.caseSafeId(t.PermissionSetId);if(d.has(s)){d.get(s).memberCounts=t.CountAssignment}}))]),s?.log(`Computing the score for ${d.size} permission sets...`),await N.forEach(d,(e=>{c.computeScore(e)})),s?.log("Done"),d}}class lt extends D{async run(e,t,s){s?.log("Querying REST API about PermissionSet with IsOwnedByProfile=true in the org...");const a=await e.soqlQuery([{string:"SELECT ProfileId, Profile.Name, Profile.Description, IsCustom, License.Name, NamespacePrefix, PermissionsApiEnabled, PermissionsViewSetup, PermissionsModifyAllData, PermissionsViewAllData, CreatedDate, LastModifiedDate FROM PermissionSet WHERE isOwnedByProfile = TRUE ORDER BY ProfileId LIMIT 2000"},{string:"SELECT Parent.ProfileId, COUNT(SobjectType) CountObject FROM ObjectPermissions WHERE Parent.IsOwnedByProfile = TRUE GROUP BY Parent.ProfileId ORDER BY Parent.ProfileId LIMIT 2000"},{string:"SELECT Parent.ProfileId, COUNT(Field) CountField FROM FieldPermissions WHERE Parent.IsOwnedByProfile = TRUE GROUP BY Parent.ProfileId ORDER BY Parent.ProfileId LIMIT 2000"},{string:"SELECT PermissionSet.ProfileId, COUNT(Id) CountAssignment FROM PermissionSetAssignment WHERE PermissionSet.IsOwnedByProfile = TRUE GROUP BY PermissionSet.ProfileId ORDER BY PermissionSet.ProfileId LIMIT 2000"}],s),r=a[0],i=a[1],n=a[2],o=a[3],l=t.getInstance(oe);s?.log(`Parsing ${r.length} profiles...`);const c=new Map(await N.map(r,(t=>{const s=e.caseSafeId(t.ProfileId),a=l.create({properties:{id:s,name:t.Profile.Name,description:t.Profile.Description,license:t.License?t.License.Name:"",isCustom:t.IsCustom,package:t.NamespacePrefix||"",memberCounts:0,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,nbFieldPermissions:0,nbObjectPermissions:0,type:"Profile",importantPermissions:{apiEnabled:!0===t.PermissionsApiEnabled,viewSetup:!0===t.PermissionsViewSetup,modifyAllData:!0===t.PermissionsModifyAllData,viewAllData:!0===t.PermissionsViewAllData},url:e.setupUrl(s,v.PROFILE)}});return[a.id,a]})));return s?.log(`Parsing ${i.length} object permissions, ${n.length} field permissions and ${o.length} assignments...`),await Promise.all([N.forEach(i,(t=>{const a=e.caseSafeId(t.ProfileId);if(c.has(a)){c.get(a).nbObjectPermissions=t.CountObject}else s.log(`[objectPermissionRecords] Not Profile found with ID: ${a}, and we had Record=${JSON.stringify(t)}`)})),N.forEach(n,(t=>{const a=e.caseSafeId(t.ProfileId);if(c.has(a)){c.get(a).nbFieldPermissions=t.CountField}else s.log(`[fieldPermissionRecords] Not Profile found with ID: ${a}, and we had Record=${JSON.stringify(t)}`)})),N.forEach(o,(t=>{const a=e.caseSafeId(t.ProfileId);if(c.has(a)){c.get(a).memberCounts=t.CountAssignment}else s.log(`[assignmentRecords] Not Profile found with ID: ${a}, and we had Record=${JSON.stringify(t)}`)}))]),s?.log(`Computing the score for ${c.size} profiles...`),await N.forEach(c,(e=>{l.computeScore(e)})),s?.log("Done"),c}}const ct=e=>e?.split(".").reduce(((e,t,s,a)=>e+Number(t)*Math.pow(255,a.length-1-s)),0),dt=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"];class pt extends D{async run(e,t,s){s?.log("Querying REST API about Profile in the org...");const a=(await e.soqlQuery([{string:"SELECT Id FROM Profile"}],s))[0];s?.log(`Parsing ${a.length} Profiles...`);const r=await N.map(a,(e=>e.Id)),i=t.getInstance(me),n=t.getInstance(fe),o=t.getInstance(Se);s?.log(`Calling Tooling API Composite to get more information about these ${r.length} profiles...`);const l=await e.readMetadataAtScale("Profile",r,["UNKNOWN_EXCEPTION"],s);s?.log(`Parsing ${l.length} profile restrictions...`);const c=new Map(await N.map(l,(async t=>{const s=e.caseSafeId(t.Id);let a,r;a=t.Metadata.loginHours?await N.map(dt,(e=>{const s=t.Metadata.loginHours[e+"Start"],a=t.Metadata.loginHours[e+"End"];return o.create({properties:{day:e,fromTime:("0"+Math.floor(s/60)).slice(-2)+":"+("0"+s%60).slice(-2),toTime:("0"+Math.floor(a/60)).slice(-2)+":"+("0"+a%60).slice(-2),difference:a-s}})})):[],r=t.Metadata.loginIpRanges&&t.Metadata.loginIpRanges.length>0?await N.map(t.Metadata.loginIpRanges,(e=>{const t=ct(e.startAddress),s=ct(e.endAddress);return n.create({properties:{startAddress:e.startAddress,endAddress:e.endAddress,description:e.description||"(empty)",difference:s-t+1}})})):[];const l=i.createWithScore({properties:{profileId:s,ipRanges:r,loginHours:a}});return[l.profileId,l]})));return s?.log("Done"),c}}class gt extends D{async run(e,t,s){s?.log("Querying Metadata API about ProfilePasswordPolicy...");const a=await e.readMetadata([{type:"ProfilePasswordPolicy",members:["*"]}],s),r=a?.get("ProfilePasswordPolicy")||[];if(!r)return new Map;const i=t.getInstance(he);s?.log(`Parsing ${r.length} profile password policies...`);const n=new Map(await N.map(r,(e=>{const t=i.createWithScore({properties:{lockoutInterval:parseInt(e.lockoutInterval,10),maxLoginAttempts:parseInt(e.maxLoginAttempts,10),minimumPasswordLength:parseInt(e.minimumPasswordLength,10),minimumPasswordLifetime:"true"===e.minimumPasswordLifetime,obscure:"true"===e.obscure,passwordComplexity:parseInt(e.passwordComplexity,10),passwordExpiration:parseInt(e.passwordExpiration,10),passwordHistory:parseInt(e.passwordHistory,10),passwordQuestion:"1"===e.passwordQuestion,profileName:e.profile}});return[t.profileName,t]}),(e=>"string"==typeof e.profile&&""!==e.profile)));return s?.log("Done"),n}}class ut extends D{async run(e,t,s){s?.log("Querying REST API about internal active User in the org...");const a=await e.soqlQuery([{string:"SELECT Id, Name, ProfileId, LastLoginDate, LastPasswordChangeDate, NumberOfFailedLogins, UserPreferencesLightningExperiencePreferred, (SELECT PermissionSetId FROM PermissionSetAssignments WHERE PermissionSet.IsOwnedByProfile = false) FROM User WHERE IsActive = true AND ContactId = NULL AND Profile.Id != NULL "}],s),r=t.getInstance(ce),i=a[0];s?.log(`Parsing ${i.length} users...`);const n=new Map(await N.map(i,(async t=>{const s=e.caseSafeId(t.Id),a=await N.map(t?.PermissionSetAssignments?.records,(t=>e.caseSafeId(t.PermissionSetId))),i=r.createWithScore({properties:{id:s,name:t.Name,lastLogin:t.LastLoginDate,numberFailedLogins:t.NumberOfFailedLogins,onLightningExperience:t.UserPreferencesLightningExperiencePreferred,lastPasswordChange:t.LastPasswordChangeDate,profileId:e.caseSafeId(t.ProfileId),permissionSetIds:a,url:e.setupUrl(s,v.USER)}});return[i.id,i]})));return s?.log("Done"),n}}class ht extends D{async run(e,t,s){s?.log("Querying Tooling API about ApexPage in the org...");const a=await e.soqlQuery([{tooling:!0,string:"SELECT Id, Name, ApiVersion, NamespacePrefix, Description, IsAvailableInTouch, Markup, CreatedDate, LastModifiedDate FROM ApexPage WHERE ManageableState IN ('installedEditable', 'unmanaged')"}],s),r=t.getInstance(we),i=a[0];s?.log(`Retrieving dependencies of ${i.length} visualforce pages...`);const n=await e.dependenciesQuery(await N.map(i,(t=>e.caseSafeId(t.Id))),s);s?.log(`Parsing ${i.length} visualforce pages...`);const o=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.create({properties:{id:s,name:t.Name,apiVersion:t.ApiVersion,isMobileReady:t.IsAvailableInTouch,package:t.NamespacePrefix||"",createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,description:t.Description,url:e.setupUrl(s,v.VISUAL_FORCE_PAGE)},dependencies:{data:n}});if(t.Markup){const e=g.RemoveComments(t.Markup);a.hardCodedURLs=g.FindHardCodedURLs(e),a.hardCodedIDs=g.FindHardCodedIDs(e)}return r.computeScore(a),[a.id,a]})));return s?.log("Done"),o}}class mt extends D{async run(e,t,s){s?.log("Querying Tooling API about ApexComponent in the org...");const a=await e.soqlQuery([{tooling:!0,string:"SELECT Id, Name, ApiVersion, NamespacePrefix, Description, Markup, CreatedDate, LastModifiedDate FROM ApexComponent WHERE ManageableState IN ('installedEditable', 'unmanaged') "}],s),r=t.getInstance(Ie),i=a[0];s?.log(`Retrieving dependencies of ${i.length} visualforce components...`);const n=await e.dependenciesQuery(await N.map(i,(t=>e.caseSafeId(t.Id))),s);s?.log(`Parsing ${i.length} visualforce components...`);const o=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.create({properties:{id:s,name:t.Name,apiVersion:t.ApiVersion,package:t.NamespacePrefix||"",createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,description:t.Description,url:e.setupUrl(s,v.VISUAL_FORCE_COMPONENT)},dependencies:{data:n}});if(t.Markup){const e=g.RemoveComments(t.Markup);a.hardCodedURLs=g.FindHardCodedURLs(e),a.hardCodedIDs=g.FindHardCodedIDs(e)}return r.computeScore(a),[a.id,a]})));return s?.log("Done"),o}}class ft extends D{async run(e,t,s){s?.log("Querying Tooling API about AuraDefinitionBundle in the org...");const a=await e.soqlQuery([{tooling:!0,string:"SELECT Id, MasterLabel, ApiVersion, NamespacePrefix, Description, CreatedDate, LastModifiedDate FROM AuraDefinitionBundle WHERE ManageableState IN ('installedEditable', 'unmanaged') "}],s),r=t.getInstance(pe),i=a[0];s?.log(`Retrieving dependencies of ${i.length} lightning aura components...`);const n=await e.dependenciesQuery(await N.map(i,(t=>e.caseSafeId(t.Id))),s);s?.log(`Parsing ${i.length} lightning aura components...`);const o=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.createWithScore({properties:{id:s,name:t.MasterLabel,apiVersion:t.ApiVersion,package:t.NamespacePrefix||"",createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,description:t.Description,url:e.setupUrl(s,v.AURA_WEB_COMPONENT)},dependencies:{data:n}});return[a.id,a]})));return s?.log("Done"),o}}class St extends D{async run(e,t,s){s?.log("Querying Tooling API about LightningComponentBundle in the org...");const a=await e.soqlQuery([{tooling:!0,string:"SELECT Id, MasterLabel, ApiVersion, NamespacePrefix, Description, CreatedDate, LastModifiedDate FROM LightningComponentBundle WHERE ManageableState IN ('installedEditable', 'unmanaged') "}],s),r=t.getInstance(ge),i=a[0];s?.log(`Retrieving dependencies of ${i.length} lightning web components...`);const n=await e.dependenciesQuery(await N.map(i,(t=>e.caseSafeId(t.Id))),s);s?.log(`Parsing ${i.length} lightning web components...`);const o=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.createWithScore({properties:{id:s,name:t.MasterLabel,apiVersion:t.ApiVersion,package:t.NamespacePrefix||"",createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,description:t.Description,url:e.setupUrl(s,v.LIGHTNING_WEB_COMPONENT)},dependencies:{data:n}});return[a.id,a]})));return s?.log("Done"),o}}class Et extends D{async run(e,t,s){s?.log("Querying Tooling API about FlexiPage in the org...");const a=await e.soqlQuery([{tooling:!0,string:"SELECT Id, MasterLabel, EntityDefinition.QualifiedApiName, Type, NamespacePrefix, Description, CreatedDate, LastModifiedDate FROM FlexiPage WHERE ManageableState IN ('installedEditable', 'unmanaged') "}],s),r=t.getInstance(B),i=a[0];s?.log(`Retrieving dependencies of ${i.length} lightning pages...`);const n=await e.dependenciesQuery(await N.map(i,(t=>e.caseSafeId(t.Id))),s);s?.log(`Parsing ${i.length} lightning pages...`);const o=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.createWithScore({properties:{id:s,name:t.MasterLabel,type:t.Type,package:t.NamespacePrefix||"",createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,description:t.Description,objectId:t.EntityDefinition?.QualifiedApiName||"",url:e.setupUrl(s,v.LIGHTNING_PAGE)},dependencies:{data:n}});return[a.id,a]})));return s?.log("Done"),o}}class It extends D{async run(e,t,s){s?.log("Querying REST API about Group in the org...");const a=await e.soqlQuery([{string:"SELECT Id, Name, DeveloperName, DoesIncludeBosses, Type, RelatedId, Related.Name, (SELECT UserOrGroupId From GroupMembers)FROM Group "}],s),r=t.getInstance(de),i=a[0];s?.log(`Parsing ${i.length} groups...`);const n=new Map(await N.map(i,(async t=>{const s=e.caseSafeId(t.Id);let a,i,n,o,l,c;switch(t.Type){case"Regular":case"Queue":a="Regular"===t.Type?v.PUBLIC_GROUP:v.QUEUE,i=t.Name,n=t.DeveloperName,o=t.DoesIncludeBosses;break;case"Role":case"RoleAndSubordinates":case"RoleAndSubordinatesInternal":a=v.ROLE,i=t.Related.Name,l="Role"!==t.Type,c=e.caseSafeId(t.RelatedId);break;default:i=t.Type,a=v.TECHNICAL_GROUP}const d=[],p=[];t.GroupMembers&&t.GroupMembers.records&&t.GroupMembers.records.length>0&&await N.forEach(t.GroupMembers.records,(t=>{const s=e.caseSafeId(t.UserOrGroupId);(s.startsWith("005")?d:p).push(s)}));const g=r.createWithScore({properties:{id:s,name:i,developerName:n,type:a,isPublicGroup:"Regular"===t.Type,isQueue:"Queue"===t.Type,nbDirectMembers:d.length+p.length,directUserIds:d,directGroupIds:p,includeBosses:!0===o,includeSubordinates:!0===l,relatedId:c,url:e.setupUrl(c??s,a)}});return[g.id,g]})));return s?.log("Done"),n}}class wt extends D{async run(e,t,s){s?.log("Querying Tooling API about ApexClass, ApexCodeCoverage, ApexCodeCoverageAggregate and AsyncApexJob in the org...");const a=await e.soqlQuery([{string:"SELECT Id, Name, ApiVersion, NamespacePrefix, Body, LengthWithoutComments, SymbolTable, CreatedDate, LastModifiedDate FROM ApexClass WHERE ManageableState IN ('installedEditable', 'unmanaged') ",tooling:!0},{string:"SELECT ApexClassOrTriggerId, ApexTestClassId FROM ApexCodeCoverage GROUP BY ApexClassOrTriggerId, ApexTestClassId ",queryMoreField:"CreatedDate",tooling:!0},{string:"SELECT ApexClassorTriggerId, NumLinesCovered, NumLinesUncovered, Coverage FROM ApexCodeCoverageAggregate ",tooling:!0},{string:"SELECT ApexClassId FROM AsyncApexJob WHERE JobType = 'ScheduledApex' "},{string:"SELECT id, ApexClassId, MethodName, ApexTestRunResult.CreatedDate, RunTime, Outcome, StackTrace, (SELECT Cpu, AsyncCalls, Sosl, Soql, QueryRows, DmlRows, Dml FROM ApexTestResults LIMIT 1) FROM ApexTestResult WHERE (Outcome != 'Pass' OR RunTime > 20000) AND ApexTestRunResult.Status = 'Completed' AND ApexClass.ManageableState IN ('installedEditable', 'unmanaged') ORDER BY ApexClassId, ApexTestRunResult.CreatedDate desc, MethodName ",tooling:!0}],s),r=t.getInstance(b),i=t.getInstance(O),n=a[0],o=a[1],l=a[2],c=a[3],d=a[4];s?.log(`Retrieving dependencies of ${n.length} apex classes...`);const p=await e.dependenciesQuery(await N.map(n,(t=>e.caseSafeId(t.Id))),s);s?.log(`Parsing ${n.length} apex classes...`);const u=new Map(await N.map(n,(async t=>{const s=e.caseSafeId(t.Id),a=r.create({properties:{id:s,name:t.Name,apiVersion:t.ApiVersion,package:t.NamespacePrefix||"",isTest:!1,isAbstract:!1,isClass:!0,isEnum:!1,isInterface:!1,isSchedulable:!1,isScheduled:!1,length:t.LengthWithoutComments,needsRecompilation:!t.SymbolTable,coverage:0,relatedTestClasses:[],relatedClasses:[],createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,url:e.setupUrl(s,v.APEX_CLASS)},dependencies:{data:p}});if(t.SymbolTable&&(a.innerClassesCount=t.SymbolTable.innerClasses?.length||0,a.interfaces=t.SymbolTable.interfaces,a.isSchedulable=t.SymbolTable.interfaces?.includes("System.Schedulable")??!1,a.methodsCount=t.SymbolTable.methods?.length||0,a.extends=t.SymbolTable.parentClass,t.SymbolTable.tableDeclaration&&(a.annotations=t.SymbolTable.tableDeclaration.annotations?.map((e=>e?.name??e)),await N.forEach(t.SymbolTable.tableDeclaration.modifiers,(e=>{switch(e){case"with sharing":a.specifiedSharing="with";break;case"without sharing":a.specifiedSharing="without";break;case"inherited sharing":a.specifiedSharing="inherited";break;case"public":a.specifiedAccess="public";break;case"private":a.specifiedAccess="private";break;case"global":a.specifiedAccess="global";break;case"virtual":a.specifiedAccess="virtual";break;case"abstract":a.isAbstract=!0;break;case"testMethod":a.isTest=!0;break;default:console.error(`Unsupported modifier in SymbolTable.tableDeclaration: ${e} (ApexClassId=${a.id})`)}})))),t.Body){const e=g.RemoveComments(t.Body);a.isInterface=g.IsInterface(e),a.isEnum=g.IsEnum(e),a.isClass=!1===a.isInterface&&!1===a.isEnum,a.hardCodedURLs=g.FindHardCodedURLs(e),a.hardCodedIDs=g.FindHardCodedIDs(e),!0===a.isTest&&(a.isTestSeeAllData=g.IsTestSeeAllData(e),a.nbSystemAsserts=g.CountOfAsserts(e))}return!0!==a.isEnum&&!0!==a.isInterface||(a.specifiedSharing="Not applicable"),[a.id,a]})));s?.log(`Parsing ${o.length} apex code coverages...`);const h=new Map,m=new Map;return await N.forEach(o,(t=>{const s=e.caseSafeId(t.ApexClassOrTriggerId),a=e.caseSafeId(t.ApexTestClassId);u.has(s)&&(!1===h.has(s)&&h.set(s,new Set),!1===m.has(a)&&m.set(a,new Set),h.get(s).add(a),m.get(a).add(s))})),await N.forEach(h,((e,t)=>{u.has(t)&&(u.get(t).relatedTestClassIds=Array.from(e))})),await N.forEach(m,((e,t)=>{u.has(t)&&(u.get(t).relatedClassIds=Array.from(e))})),s?.log(`Parsing ${l.length} apex code coverage aggregates...`),await N.forEach(l,(t=>{const s=e.caseSafeId(t.ApexClassOrTriggerId);u.has(s)&&(u.get(s).coverage=t.NumLinesCovered/(t.NumLinesCovered+t.NumLinesUncovered))})),s?.log(`Parsing ${c.length} schedule apex classes...`),await N.forEach(c,(t=>{const s=e.caseSafeId(t.ApexClassId);u.has(s)&&(u.get(s).isScheduled=!0)})),s?.log(`Parsing ${d.length} test results...`),await N.forEach(d,(t=>{const s=e.caseSafeId(t.ApexClassId);if(u.has(s)){const e=u.get(s);if(!0===e.isTest&&(e.lastTestRunDate||(e.lastTestRunDate=t.ApexTestRunResult?.CreatedDate,e.testMethodsRunTime=0,e.testPassedButLongMethods=[],e.testFailedMethods=[]),e.lastTestRunDate===t.ApexTestRunResult?.CreatedDate)){const s=i.create({properties:{methodName:t.MethodName,isSuccessful:"Pass"===t.Outcome,runtime:t.RunTime,stacktrace:t.StackTrace}});if(t.ApexTestResults?.records&&t.ApexTestResults.records.length>0){const e=t.ApexTestResults.records[0];e.Cpu>0&&(s.cpuConsumption=e.Cpu),e.AsyncCalls>0&&(s.asyncCallsConsumption=e.AsyncCalls),e.Sosl>0&&(s.soslConsumption=e.Sosl),e.Soql>0&&(s.soqlConsumption=e.Soql),e.QueryRows>0&&(s.queryRowsConsumption=e.QueryRows),e.DmlRows>0&&(s.dmlRowsConsumption=e.DmlRows),e.Dml>0&&(s.dmlConsumption=e.Dml)}e.testMethodsRunTime+=s.runtime,(s.isSuccessful?e.testPassedButLongMethods:e.testFailedMethods).push(s)}}})),await N.forEach(u,(e=>{r.computeScore(e)})),s?.log("Done"),u}}class Pt extends D{async run(e,t,s){s?.log("Querying Tooling API about ApexTrigger in the org...");const a=await e.soqlQuery([{string:"SELECT Id, Name, ApiVersion, Status, NamespacePrefix, Body, UsageBeforeInsert, UsageAfterInsert, UsageBeforeUpdate, UsageAfterUpdate, UsageBeforeDelete, UsageAfterDelete, UsageAfterUndelete, UsageIsBulk, LengthWithoutComments, EntityDefinition.QualifiedApiName, CreatedDate, LastModifiedDate FROM ApexTrigger WHERE ManageableState IN ('installedEditable', 'unmanaged') ",tooling:!0}],s),r=t.getInstance(ae),i=a[0];s?.log(`Retrieving dependencies of ${i.length} apex triggers...`);const n=await e.dependenciesQuery(await N.map(i,(t=>e.caseSafeId(t.Id))),s);s?.log(`Parsing ${i.length} apex triggers...`);const o=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.create({properties:{id:s,name:t.Name,apiVersion:t.ApiVersion,package:t.NamespacePrefix||"",length:t.LengthWithoutComments,isActive:"Active"===t.Status,beforeInsert:t.UsageBeforeInsert,afterInsert:t.UsageAfterInsert,beforeUpdate:t.UsageBeforeUpdate,afterUpdate:t.UsageAfterUpdate,beforeDelete:t.UsageBeforeDelete,afterDelete:t.UsageAfterDelete,afterUndelete:t.UsageAfterUndelete,objectId:e.caseSafeId(t.EntityDefinition?.QualifiedApiName),hasSOQL:!1,hasDML:!1,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,url:e.setupUrl(s,v.APEX_TRIGGER,t.EntityDefinition?.QualifiedApiName)},dependencies:{data:n}});if(t.Body){const e=g.RemoveComments(t.Body);a.hasSOQL=g.HasSOQL(e),a.hasDML=g.HasDML(e),a.hardCodedURLs=g.FindHardCodedURLs(e),a.hardCodedIDs=g.FindHardCodedIDs(e)}return r.computeScore(a),[a.id,a]}),(e=>!!e.EntityDefinition)));return s?.log("Done"),o}}class Rt extends D{async run(e,t,s){s?.log("Querying REST API about UserRole in the org...");const a=await e.soqlQuery([{string:"SELECT Id, DeveloperName, Name, ParentRoleId, (SELECT Id FROM Users WHERE IsActive = true AND ContactId = NULL AND Profile.Id != NULL) FROM UserRole WHERE PortalType = 'None' "}],s),r=t.getInstance(Ee),i=a[0];s?.log(`Parsing ${i.length} user roles...`);const n=new Map,o=[],l=new Map(await N.map(i,(async t=>{const s=e.caseSafeId(t.Id),a=r.create({properties:{id:s,name:t.Name,apiname:t.DeveloperName,parentId:t.ParentRoleId?e.caseSafeId(t.ParentRoleId):void 0,hasParent:!!t.ParentRoleId,activeMembersCount:0,activeMemberIds:[],hasActiveMembers:!1,url:e.setupUrl(s,v.ROLE)}});return!1===a.hasParent?o.push(a):(!1===n.has(a.parentId)&&n.set(a.parentId,[]),n.get(a.parentId).push(a)),await N.forEach(t?.Users?.records,(t=>{a.activeMemberIds.push(e.caseSafeId(t.Id))})),a.activeMembersCount=a.activeMemberIds.length,a.hasActiveMembers=a.activeMemberIds.length>0,[a.id,a]})));return await N.forEach(o,(async e=>{e.level=1,Tt(e,n)})),await N.forEach(l,(async e=>{r.computeScore(e)})),s?.log("Done"),l}}const Tt=(e,t)=>{const s=t.get(e.id);s?.forEach((s=>{s.level=e.level+1,Tt(s,t)}))};class yt extends D{async run(e,t,s){s?.log("Querying Tooling API about FlowDefinition in the org...");const a=await e.soqlQuery([{string:"SELECT Id, MasterLabel, DeveloperName, ApiVersion, Description, ActiveVersionId, LatestVersionId, CreatedDate, LastModifiedDate FROM FlowDefinition",tooling:!0},{string:"SELECT Id, DefinitionId, Status, ProcessType FROM Flow where DefinitionId <> null",tooling:!0}],s),r=t.getInstance(ie),i=t.getInstance(ne),n=a[0],o=a[1];s?.log(`Retrieving dependencies of ${n.length} flow versions...`);const l=[];await N.forEach(n,(t=>{l.push(e.caseSafeId(t.ActiveVersionId??t.LatestVersionId)),l.push(e.caseSafeId(t.Id))}));const c=await e.dependenciesQuery(l,s),d=[];s?.log(`Parsing ${n.length} flow definitions...`);const p=new Map(await N.map(n,(t=>{const s=e.caseSafeId(t.Id),a=e.caseSafeId(t.ActiveVersionId),i=e.caseSafeId(t.LatestVersionId),n=r.create({properties:{id:s,name:t.DeveloperName,apiVersion:t.ApiVersion,currentVersionId:a??i,isLatestCurrentVersion:a===i,isVersionActive:!!a,versionsCount:0,description:t.Description,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,url:e.setupUrl(s,v.FLOW_DEFINITION)},dependencies:{data:c,idFields:["id","currentVersionId"]}});return d.push(n.currentVersionId),[n.id,n]})));s?.log(`Parsing ${o.length} flow versions...`),await N.forEach(o,(t=>{const s=e.caseSafeId(t.DefinitionId),a=p.get(s);a.versionsCount++,a.type=t.ProcessType})),s?.log(`Calling Tooling API Composite to get more information about these ${d.length} flow versions...`);const g=await e.readMetadataAtScale("Flow",d,["UNKNOWN_EXCEPTION"],s);return s?.log(`Parsing ${g.length} flow versions...`),await N.forEach(g,(async t=>{const s=e.caseSafeId(t.Id),a=e.caseSafeId(t.DefinitionId),r=i.create({properties:{id:s,name:t.FullName,version:t.VersionNumber,apiVersion:t.ApiVersion,totalNodeCount:["actionCalls","apexPluginCalls","assignments","collectionProcessors","decisions","loops","orchestratedStages","recordCreates","recordDeletes","recordLookups","recordRollbacks","recordUpdates","screens","steps","waits"].reduce(((e,s)=>e+t.Metadata[s]?.length||0),0),dmlCreateNodeCount:t.Metadata.recordCreates?.length||0,dmlDeleteNodeCount:t.Metadata.recordDeletes?.length||0,dmlUpdateNodeCount:t.Metadata.recordUpdates?.length||0,screenNodeCount:t.Metadata.screens?.length||0,isActive:"Active"===t.Status,description:t.Description,type:t.ProcessType,runningMode:t.RunInMode,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,url:e.setupUrl(s,v.FLOW_VERSION)}});await N.forEach(t.Metadata.processMetadataValues,(e=>{"ObjectType"===e.name&&(r.sobject=e.value.stringValue),"TriggerType"===e.name&&(r.triggerType=e.value.stringValue)}));p.get(a).currentVersionRef=r})),await N.forEach(p,(e=>r.computeScore(e))),s?.log("Done"),p}}class Ct extends D{async run(e,t,s){s?.log("Querying Tooling API about WorkflowRule in the org...");const a=(await e.soqlQuery([{string:"SELECT Id FROM WorkflowRule",tooling:!0}],s))[0];s?.log(`Parsing ${a.length} Workflow Rules...`);const r=await N.map(a,(e=>e.Id)),i=t.getInstance(Pe);s?.log(`Calling Tooling API Composite to get more information about these ${r.length} workflow rules...`);const n=await e.readMetadataAtScale("WorkflowRule",r,["UNKNOWN_EXCEPTION"],s);s?.log(`Parsing ${n.length} workflows...`);const o=new Map(await N.map(n,(async t=>{const s=e.caseSafeId(t.Id),a=i.create({properties:{id:s,name:t.FullName,description:t.Metadata.description,isActive:t.Metadata.active,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,hasAction:!0,futureActions:[],emptyTimeTriggers:[],url:e.setupUrl(s,v.WORKFLOW_RULE)}}),r=t.Metadata.actions;a.actions=await N.map(r,(e=>({name:e.name,type:e.type})));const n=t.Metadata.workflowTimeTriggers;return await N.forEach(n,(async e=>{const t=e.offsetFromField||"TriggerDate";0===e.actions.length?a.emptyTimeTriggers.push({field:t,delay:`${e.timeLength} ${e.workflowTimeTriggerUnit}`}):await N.forEach(e.actions,(s=>{a.futureActions.push({name:s.name,type:s.type,field:t,delay:`${e.timeLength} ${e.workflowTimeTriggerUnit}`})}))})),a.hasAction=a.actions.length+a.futureActions.length>0,i.computeScore(a),[a.id,a]})));return s?.log("Done"),o}}const At=(e,t)=>Object.prototype.isPrototypeOf.call(t,e);class Ot extends I{_instances;constructor(){super(),this._instances=new Map}getInstance(e){const t=At(e,f),s=At(e,S),a=At(e,E);if(!1===t&&!1===a&&!1===s)throw new TypeError("Given dataClass does not extends Data nor DataWithDependencies nor DataWithoutScoring");return!1===this._instances.has(e)&&this._instances.set(e,new bt(e,t?Ae.AllScoreRules.filter((t=>t.applicable?.includes(e))):[],s)),this._instances.get(e)}}class bt extends w{_dataClass;_scoreRules;_isDependenciesNeeded;constructor(e,t,s){super(),this._dataClass=e,this._scoreRules=t,this._isDependenciesNeeded=s}create(e){if(!e)throw new TypeError("Configuration can't be null.");if(!e.properties)throw new TypeError("Configuration.properties can't be null.");const t=new this._dataClass;return Object.keys(t).forEach((s=>{t[s]=e.properties[s]})),Object.seal(t),this._scoreRules.length>0&&(t.score=0,t.badFields=[],t.badReasonIds=[]),!0===this._isDependenciesNeeded&&e.dependencies&&(t.dependencies=u.create(e.dependencies.data,(e.dependencies.idFields||["id"]).map((e=>t[e])))),t}computeScore(e){return this._scoreRules.filter((t=>{try{if(!0===t.formula(e))return!0}catch(t){console.error("COMPUTE SCORE",t,e)}return!1})).forEach((t=>{e.score++,e.badFields.push(t.badField),e.badReasonIds.push(t.id)})),e}createWithScore(e){return this.computeScore(this.create(e))}}class Mt extends D{async run(e,t,s){s?.log("Querying REST API about Applications (tab set typed) in the org...");const a=await e.soqlQuery([{string:"SELECT ApplicationId, Name, Label, NamespacePrefix FROM AppMenuItem WHERE Type = 'TabSet' "}],s),r=t.getInstance(Oe),i=a[0];s?.log(`Parsing ${i.length} applications...`);const n=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.ApplicationId);return[s,r.create({properties:{id:s,name:t.Name,label:t.Label,package:t.NamespacePrefix||""}})]})));return s?.log("Done"),n}}class Dt extends D{async run(e,t,s,a){const r=a?.get("object");s?.log("Querying REST API about SetupEntityAccess for TabSet in the org...");const i=await e.soqlQuery([{string:`SELECT Field, PermissionsRead, PermissionsEdit, ParentId, Parent.IsOwnedByProfile, Parent.ProfileId FROM FieldPermissions WHERE SObjectType = '${r}' `}],s),n=t.getInstance(Me),o=i[0];s?.log(`Parsing ${o.length} Field Permissions...`);const l=new Map(await N.map(o,(t=>{const s=e.caseSafeId(t.Parent.IsOwnedByProfile?t.Parent.ProfileId:t.ParentId),a=t.Field.indexOf("."),r=-1===a?t.Field:t.Field.substring(a+1),i=n.create({properties:{fieldApiName:r,parentId:s,isRead:t.PermissionsRead,isEdit:t.PermissionsEdit}});return[`${t.Field}-${s}`,i]})));return s?.log("Done"),l}}class _t extends D{async run(e,t,s){s?.log("Querying Tooling API about Validaiton Rules in the org...");const a=await e.soqlQuery([{string:"SELECT Id, Active, Description, ErrorDisplayField, ErrorMessage, ValidationName, EntityDefinition.QualifiedApiName, NamespacePrefix, CreatedDate, LastModifiedDate FROM ValidationRule",tooling:!0}],s),r=t.getInstance(ee),i=a[0];s?.log(`Parsing ${i.length} validation rules...`);const n=new Map(await N.map(i,(async t=>{const s=e.caseSafeId(t.Id),a=r.createWithScore({properties:{id:e.caseSafeId(s),name:t.ValidationName,isActive:t.Active,package:t.NamespacePrefix||"",description:t.Description,errorDisplayField:t.ErrorDisplayField,errorMessage:t.ErrorMessage,objectId:t.EntityDefinition?.QualifiedApiName,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,url:e.setupUrl(s,v.VALIDATION_RULE)}});return[a.id,a]})));return s?.log("Done"),n}}class Lt extends D{async run(e,t,s){s?.log("Querying REST API about PermissionSetLicenses in the org...");const a=await e.soqlQuery([{string:"SELECT Id, MasterLabel, CreatedDate, LastModifiedDate, TotalLicenses, Status, ExpirationDate, UsedLicenses, IsAvailableForIntegrations FROM PermissionSetLicense "},{string:"SELECT Id, LicenseId FROM PermissionSet WHERE IsOwnedByProfile = false AND LicenseId <> NULL "},{string:"SELECT AssigneeId, PermissionSet.LicenseId FROM PermissionSetAssignment WHERE Assignee.IsActive = TRUE AND PermissionSet.LicenseId <> NULL AND PermissionSet.IsOwnedByProfile = FALSE ORDER BY PermissionSetId "}],s),r=t.getInstance(ue),i=a[0],n=a[1],o=a[2];s?.log(`Parsing ${i.length} permission sets licenses...`);const l=new Map(await N.map(i,(t=>{const s=e.caseSafeId(t.Id),a=r.create({properties:{id:s,name:t.MasterLabel,createdDate:t.CreatedDate,lastModifiedDate:t.LastModifiedDate,totalCount:t.TotalLicenses,usedCount:t.UsedLicenses,usedPercentage:0!==t.TotalLicenses?t.UsedLicenses/t.TotalLicenses:void 0,remainingCount:t.TotalLicenses-t.UsedLicenses,permissionSetIds:[],distinctActiveAssigneeCount:0,status:t.Status,expirationDate:t.ExpirationDate,isAvailableForIntegrations:t.IsAvailableForIntegrations,url:e.setupUrl(s,v.PERMISSION_SET_LICENSE)}});return[a.id,a]})));s?.log(`Parsing ${o.length} Permission Sets with a link to a License...`);const c=new Map;return await N.forEach(o,(t=>{if(t.PermissionSet&&t.PermissionSet.LicenseId&&t.PermissionSet.LicenseId.startsWith("0PL")){const s=e.caseSafeId(t.PermissionSet.LicenseId),a=e.caseSafeId(t.AssigneeId);!1===c.has(s)&&c.set(s,new Set),c.get(s).add(a),l.get(s).distinctActiveAssigneeCount=c.get(s).size}})),s?.log(`Parsing ${n.length} Permission Sets with a link to a License...`),await N.forEach(n,(t=>{const s=e.caseSafeId(t.Id),a=e.caseSafeId(t.LicenseId);l.has(a)&&l.get(a).permissionSetIds.push(s)})),s?.log(`Computing the score for ${l.size} permission set licenses...`),await N.forEach(l,(e=>{r.computeScore(e)})),s?.log("Done"),l}}class Nt extends _{_datasets;_datasetPromisesCache;_dataCache;_sfdcManager;_logger;_dataFactory;constructor(e,t,s){if(super(),e instanceof M==!1)throw new TypeError("The given sfdcManager is not an instance of SalesforceManagerIntf.");if(s instanceof T==!1)throw new TypeError("The given logger is not an instance of LoggerIntf.");this._sfdcManager=e,this._logger=s,this._dataCache=t,this._datasets=new Map,this._datasetPromisesCache=new Map,this._dataFactory=new Ot,this._datasets.set(L.APEXCLASSES,new wt),this._datasets.set(L.APEXTRIGGERS,new Pt),this._datasets.set(L.APPLICATIONS,new Mt),this._datasets.set(L.APPPERMISSIONS,new Xe),this._datasets.set(L.CURRENTUSERPERMISSIONS,new it),this._datasets.set(L.CUSTOMFIELDS,new qe),this._datasets.set(L.CUSTOMLABELS,new He),this._datasets.set(L.FIELDPERMISSIONS,new Dt),this._datasets.set(L.FLOWS,new yt),this._datasets.set(L.GROUPS,new It),this._datasets.set(L.LIGHTNINGAURACOMPONENTS,new ft),this._datasets.set(L.LIGHTNINGPAGES,new Et),this._datasets.set(L.LIGHTNINGWEBCOMPONENTS,new St),this._datasets.set(L.OBJECT,new Je),this._datasets.set(L.OBJECTPERMISSIONS,new Ye),this._datasets.set(L.OBJECTS,new Ke),this._datasets.set(L.OBJECTTYPES,new Ze),this._datasets.set(L.ORGANIZATION,new rt),this._datasets.set(L.PACKAGES,new nt),this._datasets.set(L.PERMISSIONSETS,new ot),this._datasets.set(L.PERMISSIONSETLICENSES,new Lt),this._datasets.set(L.PROFILEPWDPOLICIES,new gt),this._datasets.set(L.PROFILERESTRICTIONS,new pt),this._datasets.set(L.PROFILES,new lt),this._datasets.set(L.USERROLES,new Rt),this._datasets.set(L.USERS,new ut),this._datasets.set(L.VALIDATIONRULES,new _t),this._datasets.set(L.VISUALFORCECOMPONENTS,new mt),this._datasets.set(L.VISUALFORCEPAGES,new ht),this._datasets.set(L.WORKFLOWS,new Ct)}async run(e){if(e instanceof Array==!1)throw new TypeError("The given datasets is not an instance of Array.");return new Map(await Promise.all(e.map((e=>{const t="string"==typeof e?e:e.alias,s="string"==typeof e?e:e.cacheKey,a="string"==typeof e?void 0:e.parameters,r=`DATASET ${t}`;return!1===this._datasetPromisesCache.has(s)&&this._datasetPromisesCache.set(s,new Promise(((e,i)=>{this._logger.log(r,`Checking the data cache for key=${s}...`),!0===this._dataCache.has(s)?(this._logger.ended(r,"There was data in data cache, we use it!"),e([t,this._dataCache.get(s)])):(this._logger.log(r,"There was no data in data cache. Let's retrieve data."),this._datasets.get(t).run(this._sfdcManager,this._dataFactory,this._logger.toSimpleLogger(r),a).then((a=>{this._dataCache.set(s,a),this._logger.ended(r,`Data retrieved and saved in cache with key=${s}`),e([t,a])})).catch((e=>{this._logger.failed(r,e),i(e)})))}))),this._datasetPromisesCache.get(s)}))))}clean(e){if(e instanceof Array==!1)throw new TypeError("The given datasets is not an instance of Array.");e.forEach((e=>{const t="string"==typeof e?e:e.cacheKey;this._dataCache.remove(t),this._datasetPromisesCache.delete(t)}))}}class xt extends T{_logger;_operationNames;_countSuccesses;_countFailures;constructor(e){super(),this._logger=e,this._countSuccesses=0,this._countFailures=0,this._operationNames=new Map}log(e,t){Ft(e,"LOG",t),this._logger?.log(e,t),this._operationNames.set(e,0)}ended(e,t){Ft(e,"ENDED",t),this._countSuccesses++,this._logger?.ended(e,t),this._operationNames.set(e,1)}failed(e,t){Ft(e,"FAILED",t),this._countFailures++,this._logger?.failed(e,t),this._operationNames.set(e,2)}toSimpleLogger(e){const t=this._logger;return{log:s=>{Ft(e,"LOG",s),t?.log(e,s)},debug:t=>{Ft(e,"DEBUG",t)}}}}const Ft=(e,t,s="...")=>{console.error(`${(new Date).toISOString()} - ${e} - ${t} - ${s}`)};class Ut extends x{extract(e){return[L.USERS,L.PROFILES,L.PERMISSIONSETS]}async transform(e,t){const s=e.get(L.USERS),a=e.get(L.PROFILES),r=e.get(L.PERMISSIONSETS);if(!s)throw new Error("RecipeActiveUsers: Data from dataset alias 'USERS' was undefined.");if(!a)throw new Error("RecipeActiveUsers: Data from dataset alias 'PROFILES' was undefined.");if(!r)throw new Error("RecipeActiveUsers: Data from dataset alias 'PERMISSIONSETS' was undefined.");return await N.forEach(s,(async e=>{e.profileRef=a.get(e.profileId),e.permissionSetRefs=await N.map(e.permissionSetIds,(e=>r.get(e)),(e=>r.has(e))),e.aggregateImportantPermissions={},e.profileRef?.importantPermissions&&Object.keys(e.profileRef.importantPermissions).filter((t=>!0===e.profileRef.importantPermissions[t])).forEach((t=>{e.aggregateImportantPermissions[t]=[e.profileRef]})),await N.forEach(e.permissionSetRefs,(t=>{Object.keys(t.importantPermissions).filter((e=>!0===t.importantPermissions[e])).forEach((s=>{e.aggregateImportantPermissions[s]||(e.aggregateImportantPermissions[s]=[]),e.aggregateImportantPermissions[s].push(t)}))}))})),[...s.values()]}}class vt extends x{extract(e){return[L.APEXCLASSES]}async transform(e,t,s){const a=e.get(L.APEXCLASSES);if(!a)throw new Error("RecipeApexClasses: Data from dataset alias 'APEXCLASSES' was undefined.");const r=[];return await N.forEach(a,(async e=>{const t=await Promise.all([N.map(e.relatedTestClassIds,(e=>a.get(e))),N.map(e.relatedClassIds,(e=>a.get(e)))]);e.relatedTestClassRefs=t[0],e.relatedClassRefs=t[1],"*"!==s&&e.package!==s||!1!==e.isTest||!1!==e.needsRecompilation||r.push(e)})),r}}class Gt extends x{extract(e){return[L.APEXTRIGGERS,L.OBJECTS]}async transform(e,t,s){const a=e.get(L.APEXTRIGGERS),r=e.get(L.OBJECTS);if(!a)throw new Error("RecipeApexTriggers: Data from dataset alias 'APEXTRIGGERS' was undefined.");if(!r)throw new Error("RecipeApexTriggers: Data from dataset alias 'OBJECTS' was undefined.");const i=[];return await N.forEach(a,(e=>{e.objectRef=r.get(e.objectId),"*"!==s&&e.package!==s||i.push(e)})),i}}class $t extends x{extract(e){return[L.APPLICATIONS,L.APPPERMISSIONS,L.PROFILES,L.PERMISSIONSETS]}async transform(e,t,s){const a=e.get(L.APPLICATIONS),r=e.get(L.APPPERMISSIONS),i=e.get(L.PROFILES),n=e.get(L.PERMISSIONSETS);if(!a)throw new Error("RecipeAppPermissions: Data from dataset alias 'APPLICATIONS' was undefined.");if(!r)throw new Error("RecipeAppPermissions: Data from dataset alias 'APPPERMISSIONS' was undefined.");if(!i)throw new Error("RecipeAppPermissions :Data from dataset alias 'PROFILES' was undefined.");if(!n)throw new Error("RecipeAppPermissions: Data from dataset alias 'PERMISSIONSETS' was undefined.");const o=h.create();return await N.forEach(r,(e=>{e.appRef=a.get(e.appId),!0===e.parentId.startsWith("0PS")?e.parentRef=n.get(e.parentId):e.parentRef=i.get(e.parentId),"*"!==s&&e.parentRef.package!==s&&e.appRef.appPackage!==s||(!1===o.hasRowHeader(e.parentId)&&o.setRowHeader(e.parentId,e.parentRef),!1===o.hasColumnHeader(e.appId)&&o.setColumnHeader(e.appId,e.appRef),o.addValueToProperty(e.parentId,e.appId,(e.isAccessible?"A":"")+(e.isVisible?"V":"")))})),o.toDataMatrix()}}class Bt extends x{extract(e,t){const s=new P(L.CURRENTUSERPERMISSIONS,L.CURRENTUSERPERMISSIONS);return s.parameters.set("permissions",t),[s]}async transform(e,t){const s=e.get(L.CURRENTUSERPERMISSIONS);if(!s)throw new Error("RecipeCurrentUserPermissions: Data from dataset alias 'CURRENTUSERPERMISSIONS' was undefined.");return s}}class Wt extends x{extract(e){return[L.CUSTOMFIELDS,L.OBJECTTYPES,L.OBJECTS]}async transform(e,t,s,a,r){const i=e.get(L.OBJECTTYPES),n=e.get(L.OBJECTS),o=e.get(L.CUSTOMFIELDS);if(!i)throw new Error("RecipeCustomFields: Data from dataset alias 'OBJECTTYPES' was undefined.");if(!n)throw new Error("RecipeCustomFields: Data from dataset alias 'OBJECTS' was undefined.");if(!o)throw new Error("RecipeCustomFields: Data from dataset alias 'CUSTOMFIELDS' was undefined.");const l=[];return await N.forEach(o,(e=>{const t=n.get(e.objectId);t&&!t.typeRef&&(t.typeRef=i.get(t.typeId)),e.objectRef=t,"*"!==s&&e.package!==s||"*"!==a&&e.objectRef?.typeRef?.id!==a||"*"!==r&&e.objectRef?.apiname!==r||l.push(e)})),l}}class Vt extends x{extract(e){return[L.CUSTOMLABELS]}async transform(e,t,s){const a=e.get(L.CUSTOMLABELS);if(!a)throw new Error("RecipeCustomLabels: Data from dataset alias 'CUSTOMLABELS' was undefined.");const r=[];return await N.forEach(a,(e=>{"*"!==s&&e.package!==s||r.push(e)})),r}}class kt extends x{extract(e){return[L.FLOWS]}async transform(e,t){const s=e.get(L.FLOWS);if(!s)throw new Error("RecipeFlows: Data from dataset alias 'FLOWS' was undefined.");const a=[];return await N.forEach(s,(e=>{"Workflow"!==e.type&&a.push(e)})),a}}class jt extends x{extract(e){return[L.LIGHTNINGAURACOMPONENTS]}async transform(e,t,s){const a=e.get(L.LIGHTNINGAURACOMPONENTS);if(!a)throw new Error("RecipeLightningAuraComponents: Data from dataset alias 'LIGHTNINGAURACOMPONENTS' was undefined.");const r=[];return await N.forEach(a,(e=>{"*"!==s&&e.package!==s||r.push(e)})),r}}class Qt extends x{extract(e){return[L.LIGHTNINGPAGES,L.OBJECTS]}async transform(e,t,s){const a=e.get(L.LIGHTNINGPAGES),r=e.get(L.OBJECTS);if(!a)throw new Error("RecipeLightningPages: Data from dataset alias 'LIGHTNINGPAGES' was undefined.");if(!r)throw new Error("RecipeLightningPages: Data from dataset alias 'OBJECTS' was undefined.");const i=[];return await N.forEach(a,(e=>{e.objectId&&(e.objectRef=r.get(e.objectId)),"*"!==s&&e.package!==s||i.push(e)})),i}}class qt extends x{extract(e){return[L.LIGHTNINGWEBCOMPONENTS]}async transform(e,t,s){const a=e.get(L.LIGHTNINGWEBCOMPONENTS);if(!a)throw new Error("RecipeLightningWebComponents: Data from dataset alias 'LIGHTNINGWEBCOMPONENTS' was undefined.");const r=[];return await N.forEach(a,(e=>{"*"!==s&&e.package!==s||r.push(e)})),r}}class Ht extends x{extract(e,t){const s=new P(L.OBJECT,`${L.OBJECT}_${t}`),a=new P(L.CUSTOMFIELDS,`${L.CUSTOMFIELDS}_${t}`);return s.parameters.set("object",t),a.parameters.set("object",t),[s,L.OBJECTTYPES,L.APEXTRIGGERS,L.LIGHTNINGPAGES,a]}async transform(e,t){const s=e.get(L.OBJECTTYPES),a=e.get(L.OBJECT),r=e.get(L.APEXTRIGGERS),i=e.get(L.LIGHTNINGPAGES),n=e.get(L.CUSTOMFIELDS);if(!s)throw new Error("RecipeObject: Data from dataset alias 'OBJECTTYPES' was undefined.");if(!a)throw new Error("RecipeObject: Data from dataset alias 'OBJECT' was undefined.");if(!r)throw new Error("RecipeObject: Data from dataset alias 'APEXTRIGGERS' was undefined.");if(!i)throw new Error("RecipeObject: Data from dataset alias 'LIGHTNINGPAGES' was undefined.");if(!n)throw new Error("RecipeObject: Data from dataset alias 'CUSTOMFIELDS' was undefined.");a.typeRef=s.get(a.typeId),a.flexiPages=[];const o=await Promise.all([N.map(a.apexTriggerIds,(e=>{const t=r.get(e);return t.objectRef=a,t}),(e=>r.has(e))),N.forEach(i,(e=>{e.objectId===a.id&&a.flexiPages.push(e)})),N.map(a.customFieldIds,(e=>{const t=n.get(e);return t.objectRef=a,t}),(e=>n.has(e)))]);return a.apexTriggerRefs=o[0],a.customFieldRefs=o[2],a}}class Jt extends x{extract(e){return[L.OBJECTPERMISSIONS,L.PROFILES,L.PERMISSIONSETS]}async transform(e,t,s){const a=e.get(L.OBJECTPERMISSIONS),r=e.get(L.PROFILES),i=e.get(L.PERMISSIONSETS);if(!a)throw new Error("RecipeObjectPermissions: Data from dataset alias 'OBJECTPERMISSIONS' was undefined.");if(!r)throw new Error("RecipeObjectPermissions: Data from dataset alias 'PROFILES' was undefined.");if(!i)throw new Error("RecipeObjectPermissions: Data from dataset alias 'PERMISSIONSETS' was undefined.");const n=h.create();return await N.forEach(a,(e=>{!0===e.parentId.startsWith("0PS")?e.parentRef=i.get(e.parentId):e.parentRef=r.get(e.parentId),"*"!==s&&e.parentRef.package!==s||(!1===n.hasRowHeader(e.parentId)&&n.setRowHeader(e.parentId,e.parentRef),n.addValueToProperty(e.parentId,e.objectType,(e.isCreate?"C":"")+(e.isRead?"R":"")+(e.isEdit?"U":"")+(e.isDelete?"D":"")+(e.isViewAll?"v":"")+(e.isModifyAll?"m":"")))})),n.toDataMatrix()}}class Yt extends x{extract(e){return[L.OBJECTTYPES,L.OBJECTS]}async transform(e,t,s,a){const r=e.get(L.OBJECTTYPES),i=e.get(L.OBJECTS);if(!r)throw new Error("RecipeObjects: Data from dataset alias 'OBJECTTYPES' was undefined.");if(!i)throw new Error("RecipeObjects: Data from dataset alias 'OBJECTS' was undefined.");const n=[];return await N.forEach(i,(e=>{e.typeRef=r.get(e.typeId),"*"!==s&&e.package!==s||"*"!==a&&e.typeRef?.id!==a||n.push(e)})),n.sort(((e,t)=>e.label{"*"!==s&&e.package!==s||r.push(e)})),r}}class es extends x{extract(e){return[L.FLOWS]}async transform(e,t){const s=e.get(L.FLOWS);if(!s)throw new Error("RecipeProcessBuilders: Data from dataset alias 'FLOWS' was undefined.");const a=[];return await N.forEach(s,(e=>{"Workflow"===e.type&&a.push(e)})),a}}class ts extends x{extract(e){return[L.PROFILEPWDPOLICIES]}async transform(e,t){const s=e.get(L.PROFILEPWDPOLICIES);if(!s)throw new Error("RecipeProfilePasswordPolicies: Data from dataset alias 'PROFILEPWDPOLICIES' was undefined.");return[...s.values()]}}class ss extends x{extract(e){return[L.PROFILES,L.PROFILERESTRICTIONS]}async transform(e,t,s){const a=e.get(L.PROFILES),r=e.get(L.PROFILERESTRICTIONS);if(!a)throw new Error("RecipeProfileRestrictions: Data from dataset alias 'PROFILES' was undefined.");if(!r)throw new Error("RecipeProfileRestrictions: Data from dataset alias 'PROFILERESTRICTIONS' was undefined.");const i=[];return await N.forEach(r,(e=>{e.profileRef=a.get(e.profileId),"*"!==s&&e.profileRef?.package!==s||i.push(e)})),i}}class as extends x{extract(e){return[L.PROFILES]}async transform(e,t,s){const a=e.get(L.PROFILES);if(!a)throw new Error("RecipeProfiles: Data from dataset alias 'PROFILES' was undefined.");const r=[];return await N.forEach(a,(e=>{"*"!==s&&e.package!==s||r.push(e)})),r}}class rs extends x{extract(e){return[L.USERS,L.GROUPS]}async transform(e,t){const s=e.get(L.GROUPS),a=e.get(L.USERS);if(!s)throw new Error("RecipePublicGroups: Data from dataset alias 'GROUPS' was undefined.");if(!a)throw new Error("RecipePublicGroups: Data from dataset alias 'USERS' was undefined.");const r=[];return await N.forEach(s,(async e=>{e.directUserRefs=await N.map(e.directUserIds,(e=>a.get(e)),(e=>a.has(e))),e.directGroupRefs=await N.map(e.directGroupIds,(e=>s.get(e)),(e=>s.has(e))),!0===e.isPublicGroup&&r.push(e)})),r}}class is extends x{extract(e){return[L.USERS,L.GROUPS]}async transform(e,t){const s=e.get(L.GROUPS),a=e.get(L.USERS);if(!s)throw new Error("RecipeQueues: Data from dataset alias 'GROUPS' was undefined.");if(!a)throw new Error("RecipeQueues: Data from dataset alias 'USERS' was undefined.");const r=[];return await N.forEach(s,(async e=>{e.directUserRefs=await N.map(e.directUserIds,(e=>a.get(e)),(e=>a.has(e))),e.directGroupRefs=await N.map(e.directGroupIds,(e=>s.get(e)),(e=>s.has(e))),!0===e.isQueue&&r.push(e)})),r}}class ns extends x{extract(e){return[L.USERROLES,L.USERS]}async transform(e,t){const s=e.get(L.USERROLES),a=e.get(L.USERS);if(!s)throw new Error("RecipeUserRoles: Data from dataset alias 'USERROLES' was undefined.");if(!a)throw new Error("RecipeUserRoles: Data from dataset alias 'USERS' was undefined.");return await N.forEach(s,(async e=>{!0===e.hasActiveMembers&&(e.activeMemberRefs=await N.map(e.activeMemberIds,(e=>a.get(e)))),!0===e.hasParent&&(e.parentRef=s.get(e.parentId))})),[...s.values()]}}class os extends x{extract(e){return[L.VISUALFORCECOMPONENTS]}async transform(e,t,s){const a=e.get(L.VISUALFORCECOMPONENTS);if(!a)throw new Error("RecipeVisualForceComponents: Data from dataset alias 'VISUALFORCECOMPONENTS' was undefined.");const r=[];return await N.forEach(a,(e=>{"*"!==s&&e.package!==s||r.push(e)})),r}}class ls extends x{extract(e){return[L.VISUALFORCEPAGES]}async transform(e,t,s){const a=e.get(L.VISUALFORCEPAGES);if(!a)throw new Error("RecipeVisualForcePages: Data from dataset alias 'VISUALFORCEPAGES' was undefined.");const r=[];return await N.forEach(a,(e=>{"*"!==s&&e.package!==s||r.push(e)})),r}}class cs extends x{extract(e){return[L.WORKFLOWS]}async transform(e,t){const s=e.get(L.WORKFLOWS);if(!s)throw new Error("RecipeWorkflows: Data from dataset alias 'WORKFLOWS' was undefined.");return[...s.values()]}}class ds extends x{extract(e){return[L.APEXCLASSES]}async transform(e,t,s){const a=e.get(L.APEXCLASSES);if(!a)throw new Error("RecipeApexTests: Data from dataset alias 'APEXCLASSES' was undefined.");const r=[];return await N.forEach(a,(async e=>{const t=await Promise.all([N.map(e.relatedTestClassIds,(e=>a.get(e))),N.map(e.relatedClassIds,(e=>a.get(e)))]);e.relatedTestClassRefs=t[0],e.relatedClassRefs=t[1],"*"!==s&&e.package!==s||!0!==e.isTest||!1!==e.needsRecompilation||r.push(e)})),r}}class ps extends x{extract(e){return[L.APEXCLASSES]}async transform(e,t,s){const a=e.get(L.APEXCLASSES);if(!a)throw new Error("RecipeApexUncompiled: Data from dataset alias 'APEXCLASSES' was undefined.");const r=[];return await N.forEach(a,(async e=>{const t=await Promise.all([N.map(e.relatedTestClassIds,(e=>a.get(e))),N.map(e.relatedClassIds,(e=>a.get(e)))]);e.relatedTestClassRefs=t[0],e.relatedClassRefs=t[1],"*"!==s&&e.package!==s||!0!==e.needsRecompilation||r.push(e)})),r}}class gs extends x{extract(e,t){const s=new P(L.FIELDPERMISSIONS,`${L.FIELDPERMISSIONS}_${t}`);return s.parameters.set("object",t),[s,L.PROFILES,L.PERMISSIONSETS]}async transform(e,t,s,a){const r=e.get(L.FIELDPERMISSIONS),i=e.get(L.PROFILES),n=e.get(L.PERMISSIONSETS);if(!r)throw new Error("RecipeFieldPermissions: Data from dataset alias 'FIELDPERMISSIONS' was undefined.");if(!i)throw new Error("RecipeFieldPermissions: Data from dataset alias 'PROFILES' was undefined.");if(!n)throw new Error("RecipeFieldPermissions: Data from dataset alias 'PERMISSIONSETS' was undefined.");const o=h.create();return await N.forEach(r,(e=>{!0===e.parentId.startsWith("0PS")?e.parentRef=n.get(e.parentId):e.parentRef=i.get(e.parentId),"*"!==a&&e.parentRef.package!==a||(!1===o.hasRowHeader(e.parentId)&&o.setRowHeader(e.parentId,e.parentRef),o.addValueToProperty(e.parentId,e.fieldApiName,(e.isRead?"R":"")+(e.isEdit?"U":"")))})),o.toDataMatrix()}}class us extends x{extract(e){return[L.VALIDATIONRULES,L.OBJECTTYPES,L.OBJECTS]}async transform(e,t,s,a,r){const i=e.get(L.OBJECTTYPES),n=e.get(L.OBJECTS),o=e.get(L.VALIDATIONRULES);if(!i)throw new Error("RecipeValidationRules: Data from dataset alias 'OBJECTTYPES' was undefined.");if(!n)throw new Error("RecipeValidationRules: Data from dataset alias 'OBJECTS' was undefined.");if(!o)throw new Error("RecipeValidationRules: Data from dataset alias 'VALIDATIONRULES' was undefined.");const l=[];return await N.forEach(o,(e=>{const t=n.get(e.objectId);t&&!t.typeRef&&(t.typeRef=i.get(t.typeId)),e.objectRef=t,"*"!==s&&e.package!==s||"*"!==a&&e.objectRef?.typeRef?.id!==a||"*"!==r&&e.objectRef?.apiname!==r||l.push(e)})),l}}class hs extends x{extract(e){return[L.PERMISSIONSETLICENSES,L.PERMISSIONSETS]}async transform(e,t){const s=e.get(L.PERMISSIONSETLICENSES),a=e.get(L.PERMISSIONSETS);if(!s)throw new Error("RecipePermissionSetLicenses: Data from dataset alias 'PERMISSIONSETLICENSES' was undefined.");if(!a)throw new Error("RecipePermissionSetLicenses: Data from dataset alias 'PERMISSIONSETS' was undefined.");return await N.forEach(s,(async e=>{e.permissionSetRefs=await N.map(e.permissionSetIds,(e=>a.get(e)),(e=>a.has(e)))})),[...s.values()]}}class ms extends F{_logger;_recipes;_datasetManager;constructor(e,t){if(super(),e instanceof _==!1)throw new TypeError("The given datasetManager is not an instance of DatasetManagerIntf.");if(t instanceof T==!1)throw new TypeError("The given logger is not an instance of LoggerIntf.");this._datasetManager=e,this._logger=t,this._recipes=new Map,this._recipes.set(U.ACTIVE_USERS,new Ut),this._recipes.set(U.APEX_CLASSES,new vt),this._recipes.set(U.APEX_TESTS,new ds),this._recipes.set(U.APEX_TRIGGERS,new Gt),this._recipes.set(U.APEX_UNCOMPILED,new ps),this._recipes.set(U.APP_PERMISSIONS,new $t),this._recipes.set(U.CURRENT_USER_PERMISSIONS,new Bt),this._recipes.set(U.CUSTOM_FIELDS,new Wt),this._recipes.set(U.CUSTOM_LABELS,new Vt),this._recipes.set(U.FIELD_PERMISSIONS,new gs),this._recipes.set(U.FLOWS,new kt),this._recipes.set(U.LIGHTNING_AURA_COMPONENTS,new jt),this._recipes.set(U.LIGHTNING_PAGES,new Qt),this._recipes.set(U.LIGHTNING_WEB_COMPONENTS,new qt),this._recipes.set(U.OBJECT,new Ht),this._recipes.set(U.OBJECT_PERMISSIONS,new Jt),this._recipes.set(U.OBJECTS,new Yt),this._recipes.set(U.OBJECT_TYPES,new Xt),this._recipes.set(U.ORGANIZATION,new Kt),this._recipes.set(U.PACKAGES,new zt),this._recipes.set(U.PERMISSION_SETS,new Zt),this._recipes.set(U.PERMISSION_SET_LICENSES,new hs),this._recipes.set(U.PROCESS_BUILDERS,new es),this._recipes.set(U.PROFILE_PWD_POLICIES,new ts),this._recipes.set(U.PROFILE_RESTRICTIONS,new ss),this._recipes.set(U.PROFILES,new as),this._recipes.set(U.PUBLIC_GROUPS,new rs),this._recipes.set(U.QUEUES,new is),this._recipes.set(U.USER_ROLES,new ns),this._recipes.set(U.VALIDATION_RULES,new us),this._recipes.set(U.VISUALFORCE_COMPONENTS,new os),this._recipes.set(U.VISUALFORCE_PAGES,new ls),this._recipes.set(U.WORKFLOWS,new cs)}async run(e,...t){if(!1===this._recipes.has(e))throw new TypeError(`The given alias (${e}) does not correspond to a registered recipe.`);const s=`RECIPE ${e}`,a=this._recipes.get(e);let r,i,n;this._logger.log(s,"How many datasets this recipe has?");try{r=a.extract(this._logger.toSimpleLogger(s),...t)}catch(e){throw this._logger.failed(s,e),e}this._logger.log(s,`This recipe has ${r?.length} ${r?.length>1?"datasets":"dataset"}: ${r.map((e=>e instanceof P?e.alias:e)).join(", ")}...`);try{i=await this._datasetManager.run(r)}catch(e){throw this._logger.failed(s,e),e}this._logger.log(s,"Datasets information successfuly retrieved!"),this._logger.log(s,"This recipe will now transform all this information...");try{n=await a.transform(i,this._logger.toSimpleLogger(s),...t)}catch(e){throw this._logger.failed(s,e),e}return this._logger.ended(s,"Transformation successfuly done!"),n}clean(e,...t){if(!1===this._recipes.has(e))throw new TypeError(`The given alias (${e}) does not correspond to a registered recipe.`);const s=`RECIPE ${e}`,a=this._recipes.get(e);let r;this._logger.log(s,"How many datasets this recipe has?");try{r=a.extract(this._logger.toSimpleLogger(s),...t)}catch(e){throw this._logger.failed(s,e),e}this._logger.log(s,`This recipe has ${r?.length} ${r?.length>1?"datasets":"dataset"}: ${r.map((e=>e instanceof P?e.alias:e)).join(", ")}...`),this._logger.log(s,"Clean all datasets...");try{this._datasetManager.clean(r)}catch(e){throw this._logger.failed(s,e),e}this._logger.ended(s,"Datasets succesfully cleaned!")}}const fs=2e3;class Ss extends M{_apiVersion;_watchDog;_connection;constructor(e,t){super(),this._apiVersion=Ae.CurrentApiVersion;const s=new e.Connection({accessToken:t,version:this._apiVersion+".0",maxRequest:15});this._watchDog=new C((()=>({used:s.limitInfo?.apiUsage?.used,max:s.limitInfo?.apiUsage?.limit}))),this._connection=s}get apiVersion(){return this._apiVersion}caseSafeId(e){return e&&18===e.length?e.substr(0,15):e}setupUrl(e,t,s,a){if(!e)return"";switch(t){case v.STANDARD_FIELD:case v.CUSTOM_FIELD:case v.ANY_FIELD:switch(a){case v.STANDARD_OBJECT:case v.CUSTOM_OBJECT:case v.KNOWLEDGE_ARTICLE:return"/lightning/setup/ObjectManager/"+(s?`${s}/FieldsAndRelationships/${e}/view`:`page?address=%2F${e}`);case v.CUSTOM_BIG_OBJECT:return`/lightning/setup/BigObjects/page?address=%2F${e}%3Fsetupid%3DBigObjects`;case v.CUSTOM_EVENT:return`/lightning/setup/EventObjects/page?address=%2F${e}%3Fsetupid%3DEventObjects`;case v.CUSTOM_SETTING:return`/lightning/setup/CustomSettings/page?address=%2F${e}%3Fsetupid%3DCustomSettings`;case v.CUSTOM_METADATA_TYPE:return`/lightning/setup/CustomMetadata/page?address=%2F${e}%3Fsetupid%3DCustomMetadata`;case v.EXTERNAL_OBJECT:return`/lightning/setup/ExternalObjects/page?address=%2F${e}%3Fsetupid%3DExternalObjects`;default:return`/lightning/setup/ObjectManager/page?address=%2F${e}`}case v.STANDARD_OBJECT:case v.CUSTOM_OBJECT:case v.KNOWLEDGE_ARTICLE:return`/lightning/setup/ObjectManager/${e}/Details/view`;case v.CUSTOM_BIG_OBJECT:return`/lightning/setup/BigObjects/page?address=%2F${e}%3Fsetupid%3DBigObjects`;case v.CUSTOM_EVENT:return`/lightning/setup/EventObjects/page?address=%2F${e}%3Fsetupid%3DEventObjects`;case v.CUSTOM_SETTING:return`/lightning/setup/CustomSettings/page?address=%2F${e}%3Fsetupid%3DCustomSettings`;case v.CUSTOM_METADATA_TYPE:return`/lightning/setup/CustomMetadata/page?address=%2F${e}%3Fsetupid%3DCustomMetadata`;case v.EXTERNAL_OBJECT:return`/lightning/setup/ExternalObjects/page?address=%2F${e}%3Fsetupid%3DExternalObjects`;case v.PAGE_LAYOUT:return"/lightning/setup/ObjectManager/"+(s?`${s}/PageLayouts/${e}/view`:`page?address=%2F${e}`);case v.VALIDATION_RULE:return`/lightning/setup/ObjectManager/page?address=%2F${e}`;case v.WEB_LINK:return"/lightning/setup/ObjectManager/"+(s?`${s}/ButtonsLinksActions/${e}/view`:`page?address=%2F${e}`);case v.RECORD_TYPE:return"/lightning/setup/ObjectManager/"+(s?`${s}/RecordTypes/${e}/view`:`page?address=%2F${e}`);case v.APEX_TRIGGER:return"/lightning/setup/ObjectManager/"+(s?`${s}/ApexTriggers/${e}/view`:`page?address=%2F${e}`);case v.FIELD_SET:return"/lightning/setup/ObjectManager/"+(s?`${s}/FieldSets/${e}/view`:`page?address=%2F${e}`);case v.USER:return`/lightning/setup/ManageUsers/page?address=%2F${e}%3Fnoredirect%3D1%26isUserEntityOverride%3D1`;case v.PROFILE:return`/lightning/setup/EnhancedProfiles/page?address=%2F${e}`;case v.PERMISSION_SET:return`/lightning/setup/PermSets/page?address=%2F${e}`;case v.PERMISSION_SET_LICENSE:return`/lightning/setup/PermissionSetLicense/page?address=%2F${e}`;case v.PERMISSION_SET_GROUP:return`/lightning/setup/PermSetGroups/page?address=%2F${e}`;case v.ROLE:return`/lightning/setup/Roles/page?address=%2F${e}`;case v.PUBLIC_GROUP:return`/lightning/setup/PublicGroups/page?address=%2Fsetup%2Fown%2Fgroupdetail.jsp%3Fid%3D${e}`;case v.QUEUE:return`/lightning/setup/Queues/page?address=%2Fp%2Fown%2FQueue%2Fd%3Fid%3D${e}`;case v.TECHNICAL_GROUP:return"";case v.CUSTOM_LABEL:return`/lightning/setup/ExternalStrings/page?address=%2F${e}`;case v.STATIC_RESOURCE:return`/lightning/setup/StaticResources/page?address=%2F${e}`;case v.CUSTOM_SITE:return`/servlet/networks/switch?networkId=${e}&startURL=%2FcommunitySetup%2FcwApp.app%23%2Fc%2Fhome&`;case v.CUSTOM_TAB:return`/lightning/setup/CustomTabs/page?address=%2F${e}`;case v.FLOW_VERSION:return`/builder_platform_interaction/flowBuilder.app?flowId=${e}`;case v.FLOW_DEFINITION:return`/${e}`;case v.WORKFLOW_RULE:return`/lightning/setup/WorkflowRules/page?address=%2F${e}&nodeId=WorkflowRules`;case v.VISUAL_FORCE_PAGE:return`/lightning/setup/ApexPages/page?address=%2F${e}`;case v.VISUAL_FORCE_COMPONENT:return`/lightning/setup/ApexComponent/page?address=%2F${e}`;case v.AURA_WEB_COMPONENT:case v.LIGHTNING_WEB_COMPONENT:return`/lightning/setup/LightningComponentBundles/page?address=%2F${e}`;case v.LIGHTNING_PAGE:return"/lightning/setup/ObjectManager/"+(s?`${s}/LightningPages/${e}/view`:`page?address=%2F${e}`);case v.APEX_CLASS:return`/lightning/setup/ApexClasses/page?address=%2F${e}`;default:return console.error(`Type <${t}> not supported yet. Returning "/id" as url. FYI, id was <${e}>, parentId was <${s}> and parentType was <${a}>`),`/${e}`}}getObjectType(e,t){return!0===t?H:e.endsWith("__c")?Q:e.endsWith("__x")?q:e.endsWith("__mdt")?J:e.endsWith("__e")?Y:e.endsWith("__ka")?X:e.endsWith("__b")?K:j}get dailyApiRequestLimitInformation(){return this._watchDog.dailyApiRequestLimitInformation}async _standardSOQLQuery(e,t,s,a){const r=!0===e?this._connection.tooling:this._connection,i=[],n=async e=>{let s;this._watchDog?.beforeRequest(),s=void 0===e?await r.query(t,{autoFetch:!1,headers:{"Sforce-Query-Options":"batchSize=2000"}}):await r.queryMore(e),a(s?.records?.length||0),this._watchDog?.afterRequest(),i.push(...s.records),!1===s.done&&await n(s.nextRecordsUrl)};try{return await n(),i}catch(e){if(s&&s.includes&&s.includes(e.errorCode))return[];throw Object.assign(e,{context:{when:"While running a SOQL query with the standard queryMore",what:t}})}}async _customSOQLQuery(e,t,s,a){const r=!0===e?this._connection.tooling:this._connection,i=[],n=t.indexOf(" FROM "),o=t.indexOf(" GROUP BY "),l=-1!==o,c=async e=>{let d;e||!1!==l||(e="000000000000000000"),d=!1===l?`${t} AND ${s} > '${e}' ORDER BY ${s} LIMIT 2000`:`${t.substring(0,n)}, MAX(${s}) qmField ${t.substring(n,o)} `+(e?`WHERE ${s} > ${e} `:"")+`${t.substring(o)} `+`ORDER BY MAX(${s}) LIMIT 2000`,this._watchDog?.beforeRequest();const p=await r.query(d,{autoFetch:!1,headers:{"Sforce-Query-Options":"batchSize=2000"}});if(a(p?.records?.length||0),this._watchDog?.afterRequest(),i.push(...p.records),p.records.length>=fs){const e=i[i.length-1];!1===l?await c(e[s]):await c(e.qmField)}};try{return await c(),i}catch(e){throw Object.assign(e,{context:{when:"While running a SOQL query with the custom queryMore",what:t}})}}async soqlQuery(e,t){t?.log(`Preparing ${e.length} SOQL ${e.length>1?"queries":"query"}...`);let s=0,a=0;const r=[],i=[],n=[],o=[],l=()=>{t?.log(`Processing ${e.length} SOQL ${e.length>1?"queries":"query"}... 🎥 Records retrieved: ${s}, 🙌 Number of QueryMore calls done: ${a}, ⏳ Pending: (${r.length}) on [${r.join(", ")}], ✅ Done: (${i.length}) on [${i.join(", ")}], ❌ Error: (${n.length}) on [${n.join(", ")}]`)},c=e=>{a++,s+=e,l()},d=await Promise.allSettled(e.map((async e=>{const t=e.string.lastIndexOf("FROM ")+5,s=e.string.indexOf(" ",t),a=e.string.substring(t,-1===s?e.string.length:s);let d;r.push(a);try{d=e.queryMoreField?await this._customSOQLQuery(e.tooling,e.string,e.queryMoreField,c):await this._standardSOQLQuery(e.tooling,e.string,e.byPasses,c),i.push(a)}catch(e){throw n.push(a),o.push(e),e}finally{const e=r.indexOf(a);e>-1&&r.splice(e,1),l()}return d})));if(t?.log(`Done running ${e.length} SOQL ${e.length>1?"queries":"query"}.`),o.length>0)return Promise.reject(o[0]);const p=d.filter((e=>"fulfilled"===e.status)).map((e=>e.value));return Promise.resolve(p)}async dependenciesQuery(e,t){this._watchDog?.beforeRequest(),t?.log(`Starting to call Tooling API for dependency API call of ${e.length} item(s)...`);const s=[];let a;for(let t=0;t{try{const t=await this._connection.tooling.request({url:"/tooling/composite",method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}});return this._watchDog?.afterRequest(),i++,t}catch(e){n++}finally{r--,t?.log(`Processing ${s.length} Tooling composite queries... Pending: ${r}, Done: ${i}, Error: ${n}`)}})));t?.log("Got all the results");const l=[],c=[],d=new Set;return o.forEach((s=>{s.compositeResponse.forEach((s=>{if(200===s.httpStatusCode)t?.log(`This response had a code: 200 so we add the ${s?.body?.records?.length} records`),l.push(...s.body.records.map((e=>{const t=this.caseSafeId(e.MetadataComponentId),s=this.caseSafeId(e.RefMetadataComponentId),a=`${t}-${s}`;return d.has(a)?null:(d.add(a),{id:t,name:e.MetadataComponentName,type:e.MetadataComponentType,url:this.setupUrl(t,e.MetadataComponentType),refId:s,refName:e.RefMetadataComponentName,refType:e.RefMetadataComponentType,refUrl:this.setupUrl(s,e.RefMetadataComponentType)})})).filter((e=>null!==e)));else{const a=s.body[0].errorCode;if("UNKNOWN_EXCEPTION"!==a){t?.log(`This response had a code: ${a}`);const r=new TypeError(`One of the request had an issue with HTTP errorCode=${a}`);throw Object.assign(r,{context:{when:"Calling Composite Tooling API to get dependencies.",what:{ids:e,body:s.body}}})}t?.log(`This response had a code: ${a}`),c.push(...e)}}))})),{records:l,errors:c}}async readMetadata(e,t){this._watchDog?.beforeRequest(),t?.log(`Starting to call Metadata API for ${e.length} types...`),await Promise.all(e.filter((e=>e.members?.includes("*"))).map((async e=>{try{const t=await this._connection.metadata.list([{type:e.type}],this._apiVersion);this._watchDog?.afterRequest(),e.members=e.members.filter((e=>"*"!==e)),Es(t).forEach((t=>{e.members.push(t.fullName)}))}catch(s){throw t?.log(`The method metadata.list returned an error: ${JSON.stringify(s)}`),Object.assign(s,{context:{when:"Calling Metadata API to get a list of metadata.",what:{type:e.type,apiVersion:this._apiVersion}}})}})));const s=[],a=new Map;return e.forEach((e=>{for(t?.log(`Init the response array for this type: ${e.type}`),a.set(e.type,[]),t?.log(`Starting looping for type ${e.type} and metadata.members.length=${e.members.length}`);e.members.length>0;){const r=e.members.splice(0,10);s.push(new Promise((async(s,i)=>{t?.log(`Try to call metadata read for type ${e.type} and currentMembers=${r}`);try{const t=await this._connection.metadata.read(e.type,r);this._watchDog?.afterRequest(),a.get(e.type).push(...Es(t)),s()}catch(s){t?.log(`The method metadata.read returned an error: ${JSON.stringify(s)}`),i(Object.assign(s,{context:{when:"Calling Metadata API to read a list of metadata.",what:{type:e.type,pendingMembers:e.members,membersInProcess:r}}}))}})))}})),t?.log(`Calling all promises: ${s.length}`),await Promise.all(s),t?.log(`All promises ended and response is like: ${JSON.stringify(Array.from(a.entries()))}`),a}async readMetadataAtScale(e,t,s,a){this._watchDog?.beforeRequest();const r=[];let i;t.forEach(((t,s)=>{i&&5!==i.compositeRequest.length||(i={allOrNone:!1,compositeRequest:[]},r.push(i)),i.compositeRequest.push({method:"GET",url:`/services/data/v${this._apiVersion}.0/tooling/sobjects/${e}/${t}`,referenceId:`chunk${s}`})}));const n=await Promise.all(r.map((e=>(this._watchDog?.afterRequest(),this._connection.tooling.request({url:"/tooling/composite",method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}}))))),o=[];return n.forEach((a=>{a.compositeResponse.forEach((a=>{if(200===a.httpStatusCode)o.push(a.body);else{const r=a.body[0].errorCode;if(s&&s.includes&&!1===s.includes(r)){const s=new TypeError(`One of the request for type=${e} had an issue with HTTP errorCode=${r}`);throw Object.assign(s,{context:{when:"Calling Composite Tooling API to get metadata at scale.",what:{type:e,ids:t,body:a.body}}})}}}))})),o}async describeGlobal(e){this._watchDog?.beforeRequest();const t=await this._connection.describeGlobal();return t.sobjects.push(Is),this._watchDog?.afterRequest(),t.sobjects}async describe(e,t){if("Activity"===e)return Is;this._watchDog?.beforeRequest();const s=await this._connection.describe(e);return this._watchDog?.afterRequest(),s}async recordCount(e,t){this._watchDog?.beforeRequest();const s=await this._connection.request({url:`/limits/recordCount?sObjects=${e}`,method:"GET"});return this._watchDog?.afterRequest(),Array.isArray(s?.sObjects)&&1===s?.sObjects.length?s?.sObjects[0].count:0}async runAllTests(e){this._watchDog?.beforeRequest();const t=await this._connection.request({url:"/tooling/runTestsAsynchronous",method:"POST",body:'{ "testLevel": "RunLocalTests", "skipCodeCoverage": false }',headers:{"Content-Type":"application/json"}});return this._watchDog?.afterRequest(),t}async compileClasses(e,t){this._watchDog?.beforeRequest();const s=await this.readMetadataAtScale(v.APEX_CLASS,e,[],t);this._watchDog?.beforeRequest();const a=Date.now(),r=[];let i,n=0;s.filter((e=>e.Body)).forEach((e=>{i&&5!==i.compositeRequest.length||(n++,i={allOrNone:!1,compositeRequest:[{method:"POST",url:`/services/data/v${this._apiVersion}.0/tooling/sobjects/MetadataContainer`,referenceId:"container",body:{Name:`container-${a}-${n}`}},{method:"POST",url:`/services/data/v${this._apiVersion}.0/tooling/sobjects/ContainerAsyncRequest`,referenceId:"request",body:{MetadataContainerId:"@{container.id}",IsCheckOnly:!0}}]},r.push(i)),i.compositeRequest.push({method:"POST",url:`/services/data/v${this._apiVersion}.0/tooling/sobjects/ApexClassMember`,referenceId:e.Id,body:{MetadataContainerId:"@{container.id}",ContentEntityId:e.Id,Body:e.Body}})}));const o=r.map((e=>(this._watchDog?.afterRequest(),this._connection.tooling.request({url:"/tooling/composite",method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}})))),l=await Promise.all(o);return this._watchDog?.afterRequest(),l}}const Es=e=>e?Array.isArray(e)?e:[e]:[],Is={name:"Activity",label:"Activity",labelPlural:"Activities",customSetting:!1,custom:!1,keyPrefix:"00T"};exports.API=class{get version(){return"Boron [B,5]"}get salesforceApiVersion(){return this._sfdcManager.apiVersion}_recipeManager;_datasetManager;_sfdcManager;_cacheManager;_logger;_usageTermsAcceptedManually;constructor(e,t,s,a,r,i){this._logger=new xt(i),this._sfdcManager=new Ss(t,e),this._cacheManager=new Ne({compress:r.compress,decompress:r.decompress,encode:a.encode,decode:a.decode,storage:s}),this._datasetManager=new Nt(this._sfdcManager,this._cacheManager,this._logger),this._recipeManager=new ms(this._datasetManager,this._logger),this._usageTermsAcceptedManually=!1}removeAllFromCache(){this._cacheManager.clear()}getCacheInformation(){return this._cacheManager.details()}getScoreRule(e){return Ae.AllScoreRules[e]}getAllScoreRules(){return Ae.AllScoreRules}getAllScoreRulesAsDataMatrix(){const e=h.create();return Ae.AllScoreRules.forEach((t=>{e.setRowHeader(`${t.id}`,t),t.applicable.forEach((s=>{e.addValueToProperty(`${t.id}`,s.label,"true")}))})),e.toDataMatrix()}get dailyApiRequestLimitInformation(){return this._sfdcManager.dailyApiRequestLimitInformation}async runAllTestsAsync(){return this._sfdcManager.runAllTests(this._logger.toSimpleLogger("Run All Tests"))}async compileClasses(e){return this._sfdcManager.compileClasses(e,this._logger.toSimpleLogger(`Compile ${e.length} class(es)`))}async getOrganizationInformation(){return await this._recipeManager.run(U.ORGANIZATION)}async checkUsageTerms(){return!0!==(await this.getOrganizationInformation()).isProduction||!1!==this._usageTermsAcceptedManually}wereUsageTermsAcceptedManually(){return this._usageTermsAcceptedManually}acceptUsageTermsManually(){this._usageTermsAcceptedManually=!0}async checkCurrentUserPermissions(){const e=await this._recipeManager.run(U.CURRENT_USER_PERMISSIONS,["ModifyAllData","AuthorApex","ApiEnabled","InstallPackaging"]);if(!1===e.get("ModifyAllData")||!1===e.get("AuthorApex")||!1===e.get("ApiEnabled")||!1===e.get("InstallPackaging"))throw new TypeError(`Current User Permission Access is not enough to run the application

- Modify All Data (Create, edit, and delete all organization data, regardless of sharing settings) [PermissionsModifyAllData] is set to ${e.get("PermissionsModifyAllData")}
- Author Apex (Create Apex classes and triggers) [PermissionsAuthorApex] is set to ${e.get("PermissionsAuthorApex")}
- API Enabled (Access any Salesforce.com API) [PermissionsApiEnabled] is set to ${e.get("PermissionsApiEnabled")}
- Download AppExchange Packages (Install or uninstall AppExchange packages as system administrators) [PermissionsInstallPackaging] is set to ${e.get("PermissionsInstallPackaging")}
`);return!0}async getPackages(){return await this._recipeManager.run(U.PACKAGES)}removeAllPackagesFromCache(){this._recipeManager.clean(U.PACKAGES)}async getObjectTypes(){return await this._recipeManager.run(U.OBJECT_TYPES)}async getObjects(e,t){return await this._recipeManager.run(U.OBJECTS,e,t)}removeAllObjectsFromCache(){this._recipeManager.clean(U.OBJECTS)}async getObject(e){return await this._recipeManager.run(U.OBJECT,e)}removeObjectFromCache(e){this._recipeManager.clean(U.OBJECT,e)}async getObjectPermissionsPerParent(e){return await this._recipeManager.run(U.OBJECT_PERMISSIONS,e)}removeAllObjectPermissionsFromCache(){this._recipeManager.clean(U.OBJECT_PERMISSIONS)}async getApplicationPermissionsPerParent(e){return await this._recipeManager.run(U.APP_PERMISSIONS,e)}removeAllAppPermissionsFromCache(){this._recipeManager.clean(U.APP_PERMISSIONS)}async getCustomFields(e,t,s){return await this._recipeManager.run(U.CUSTOM_FIELDS,e,t,s)}removeAllCustomFieldsFromCache(){this._recipeManager.clean(U.CUSTOM_FIELDS)}async getPermissionSets(e){return await this._recipeManager.run(U.PERMISSION_SETS,e)}removeAllPermSetsFromCache(){this._recipeManager.clean(U.PERMISSION_SETS)}async getPermissionSetLicenses(){return await this._recipeManager.run(U.PERMISSION_SET_LICENSES)}removeAllPermSetLicensesFromCache(){this._recipeManager.clean(U.PERMISSION_SET_LICENSES)}async getProfiles(e){return await this._recipeManager.run(U.PROFILES,e)}removeAllProfilesFromCache(){this._recipeManager.clean(U.PROFILES)}async getProfileRestrictions(e){return await this._recipeManager.run(U.PROFILE_RESTRICTIONS,e)}removeAllProfileRestrictionsFromCache(){this._recipeManager.clean(U.PROFILE_RESTRICTIONS)}async getProfilePasswordPolicies(){return await this._recipeManager.run(U.PROFILE_PWD_POLICIES)}removeAllProfilePasswordPoliciesFromCache(){this._recipeManager.clean(U.PROFILE_PWD_POLICIES)}async getActiveUsers(){return await this._recipeManager.run(U.ACTIVE_USERS)}removeAllActiveUsersFromCache(){this._recipeManager.clean(U.ACTIVE_USERS)}async getCustomLabels(e){return await this._recipeManager.run(U.CUSTOM_LABELS,e)}removeAllCustomLabelsFromCache(){this._recipeManager.clean(U.CUSTOM_LABELS)}async getLightningWebComponents(e){return await this._recipeManager.run(U.LIGHTNING_WEB_COMPONENTS,e)}removeAllLightningWebComponentsFromCache(){this._recipeManager.clean(U.LIGHTNING_WEB_COMPONENTS)}async getLightningAuraComponents(e){return await this._recipeManager.run(U.LIGHTNING_AURA_COMPONENTS,e)}removeAllLightningAuraComponentsFromCache(){this._recipeManager.clean(U.LIGHTNING_AURA_COMPONENTS)}async getLightningPages(e){return await this._recipeManager.run(U.LIGHTNING_PAGES,e)}removeAllLightningPagesFromCache(){this._recipeManager.clean(U.LIGHTNING_PAGES)}async getVisualForceComponents(e){return await this._recipeManager.run(U.VISUALFORCE_COMPONENTS,e)}removeAllVisualForceComponentsFromCache(){this._recipeManager.clean(U.VISUALFORCE_COMPONENTS)}async getVisualForcePages(e){return await this._recipeManager.run(U.VISUALFORCE_PAGES,e)}removeAllVisualForcePagesFromCache(){this._recipeManager.clean(U.VISUALFORCE_PAGES)}async getPublicGroups(){return await this._recipeManager.run(U.PUBLIC_GROUPS)}removeAllPublicGroupsFromCache(){this._recipeManager.clean(U.PUBLIC_GROUPS)}async getQueues(){return await this._recipeManager.run(U.QUEUES)}removeAllQueuesFromCache(){this._recipeManager.clean(U.QUEUES)}async getApexClasses(e){return await this._recipeManager.run(U.APEX_CLASSES,e)}removeAllApexClassesFromCache(){this._recipeManager.clean(U.APEX_CLASSES)}async getApexTests(e){return await this._recipeManager.run(U.APEX_TESTS,e)}removeAllApexTestsFromCache(){this._recipeManager.clean(U.APEX_TESTS)}async getApexTriggers(e){return await this._recipeManager.run(U.APEX_TRIGGERS,e)}removeAllApexTriggersFromCache(){this._recipeManager.clean(U.APEX_TRIGGERS)}async getApexUncompiled(e){return await this._recipeManager.run(U.APEX_UNCOMPILED,e)}removeAllApexUncompiledFromCache(){this._recipeManager.clean(U.APEX_UNCOMPILED)}async getRoles(){return await this._recipeManager.run(U.USER_ROLES)}removeAllRolesFromCache(){this._recipeManager.clean(U.USER_ROLES)}async getRolesTree(){const e=await this.getRoles(),t=new Map,s="__i am root__";return e.forEach((e=>{!1===t.has(e.id)&&t.set(e.id,{id:e.id});const a=t.get(e.id);a.record||(a.record=e);const r=!0===e.hasParent?e.parentId:s;!1===t.has(r)&&t.set(r,{id:r});const i=t.get(r);i.children||(i.children=[]),i.children.push(a)})),t.get(s)}async getWorkflows(){return await this._recipeManager.run(U.WORKFLOWS)}removeAllWorkflowsFromCache(){this._recipeManager.clean(U.WORKFLOWS)}async getFieldPermissionsPerParent(e,t){return await this._recipeManager.run(U.FIELD_PERMISSIONS,e,t)}removeAllFieldPermissionsFromCache(){this._recipeManager.clean(U.FIELD_PERMISSIONS)}async getFlows(){return await this._recipeManager.run(U.FLOWS)}removeAllFlowsFromCache(){this._recipeManager.clean(U.FLOWS)}async getProcessBuilders(){return await this._recipeManager.run(U.PROCESS_BUILDERS)}removeAllProcessBuildersFromCache(){this._recipeManager.clean(U.PROCESS_BUILDERS)}async getValidationRules(e,t,s){return await this._recipeManager.run(U.VALIDATION_RULES,e,t,s)}removeAllValidationRulesFromCache(){this._recipeManager.clean(U.VALIDATION_RULES)}},exports.BasicLoggerIntf=R,exports.CodeScanner=g,exports.Data=f,exports.DataCacheItem=class{name;isEmpty;isMap;length;created},exports.DataCacheManagerIntf=t,exports.DataDependencies=class{hadError;using;referenced;referencedByTypes},exports.DataDependenciesFactory=u,exports.DataDependencyItem=class{id;name;type;url},exports.DataFactoryInstanceIntf=w,exports.DataFactoryIntf=I,exports.DataItemInCache=class extends e{content},exports.DataMatrix=class{columnHeaders;rows},exports.DataMatrixColumnHeader=class{id;ref},exports.DataMatrixFactory=h,exports.DataMatrixRow=class{header;data},exports.DataMatrixWorking=m,exports.DataWithDependencies=S,exports.DataWithoutScoring=E,exports.Dataset=D,exports.DatasetAliases=L,exports.DatasetManagerIntf=_,exports.DatasetRunInformation=P,exports.ItemInCache=e,exports.LoggerIntf=T,exports.MetadataItemInCache=class extends e{type;length},exports.OBJECTTYPE_ID_CUSTOM_BIG_OBJECT=K,exports.OBJECTTYPE_ID_CUSTOM_EVENT=Y,exports.OBJECTTYPE_ID_CUSTOM_EXTERNAL_SOBJECT=q,exports.OBJECTTYPE_ID_CUSTOM_METADATA_TYPE=J,exports.OBJECTTYPE_ID_CUSTOM_SETTING=H,exports.OBJECTTYPE_ID_CUSTOM_SOBJECT=Q,exports.OBJECTTYPE_ID_KNOWLEDGE_ARTICLE=X,exports.OBJECTTYPE_ID_STANDARD_SOBJECT=j,exports.Processor=N,exports.Recipe=x,exports.RecipeAliases=U,exports.RecipeManagerIntf=F,exports.SFDC_ApexClass=b,exports.SFDC_ApexTestMethodResult=O,exports.SFDC_ApexTrigger=ae,exports.SFDC_AppPermission=be,exports.SFDC_Application=Oe,exports.SFDC_CustomLabel=re,exports.SFDC_Field=G,exports.SFDC_FieldPermission=Me,exports.SFDC_FieldSet=$,exports.SFDC_Flow=ie,exports.SFDC_FlowVersion=ne,exports.SFDC_Group=de,exports.SFDC_LightningAuraComponent=pe,exports.SFDC_LightningPage=B,exports.SFDC_LightningWebComponent=ge,exports.SFDC_Limit=W,exports.SFDC_Object=se,exports.SFDC_ObjectPermission=De,exports.SFDC_ObjectRelationShip=V,exports.SFDC_ObjectType=k,exports.SFDC_Organization=_e,exports.SFDC_Package=Le,exports.SFDC_PageLayout=z,exports.SFDC_PermissionSet=le,exports.SFDC_PermissionSetLicense=ue,exports.SFDC_Profile=oe,exports.SFDC_ProfileIpRangeRestriction=fe,exports.SFDC_ProfileLoginHourRestriction=Se,exports.SFDC_ProfilePasswordPolicy=he,exports.SFDC_ProfileRestrictions=me,exports.SFDC_RecordType=Z,exports.SFDC_User=ce,exports.SFDC_UserRole=Ee,exports.SFDC_ValidationRule=ee,exports.SFDC_VisualForceComponent=Ie,exports.SFDC_VisualForcePage=we,exports.SFDC_WebLink=te,exports.SFDC_Workflow=Pe,exports.SalesforceManagerIntf=M,exports.SalesforceMetadataRequest=class{type;members},exports.SalesforceMetadataTypes=v,exports.SalesforceQueryRequest=class{string;tooling;byPasses;queryMoreField},exports.SalesforceUsageInformation=y,exports.SalesforceWatchDog=C,exports.ScoreRule=class{id;description;formula;errorMessage;badField;applicable},exports.SecretSauce=Ae,exports.SimpleLoggerIntf=class{log(e){throw new TypeError('You need to implement the method "log()"')}debug(e){throw new TypeError('You need to implement the method "debug()"')}}; diff --git a/build/src/api/core/orgcheck-api-data-dependencies-factory.js b/build/src/api/core/orgcheck-api-data-dependencies-factory.js index 39df8ce4..3cbd4343 100644 --- a/build/src/api/core/orgcheck-api-data-dependencies-factory.js +++ b/build/src/api/core/orgcheck-api-data-dependencies-factory.js @@ -8,11 +8,12 @@ export class DataDependenciesFactory { /** * @description Create a new instance of DataDependencies * @param {{ records: Array<{ id: string, name: string, type: string, url: string, refId: string, refName: string, refType: string, refUrl: string }>, errors: Array }} data - * @param {string} whatId + * @param {Array} whatIds * @returns {DataDependencies} */ - static create(data, whatId) { - if (data.errors?.includes(whatId)) { + static create(data, whatIds) { + // Check if at least one of the whatIds is present in the data errors list + if (data.errors?.some(errorId => whatIds.includes(errorId))) { return { hadError: true, using: [], @@ -20,7 +21,9 @@ export class DataDependenciesFactory { referencedByTypes: {} }; } - const using = data.records.filter(e => e.id === whatId).map(n => { + // Data can contain a lot of dependencies from other ids, we just want to get the dependencies for the given whatIds + // WhatID is using what? -- Here we are getting the dependencies where the ID is in the whatIds list + const using = data.records.filter(e => whatIds.includes(e.id)).map(n => { return { id: n.refId, name: n.refName, @@ -29,7 +32,8 @@ export class DataDependenciesFactory { }; }); const referencedByTypes = {}; - const referenced = data.records.filter(e => e.refId === whatId).map(n => { + // WhatID is referenced where? -- Here we are getting the dependencies where the REFID is in the whatIds list + const referenced = data.records.filter(e => whatIds.includes(e.refId)).map(n => { if (referencedByTypes[n.type] === undefined) { referencedByTypes[n.type] = 1; } else { diff --git a/build/src/api/core/orgcheck-api-datafactory-impl.js b/build/src/api/core/orgcheck-api-datafactory-impl.js index da93045d..bd20ec55 100644 --- a/build/src/api/core/orgcheck-api-datafactory-impl.js +++ b/build/src/api/core/orgcheck-api-datafactory-impl.js @@ -125,7 +125,7 @@ export class DataFactoryInstance extends DataFactoryInstanceIntf { } // If dependencies are needed... if (this._isDependenciesNeeded === true && configuration.dependencies) { - row.dependencies = DataDependenciesFactory.create(configuration.dependencies.data, row[configuration.dependencies.idField || 'id']); + row.dependencies = DataDependenciesFactory.create(configuration.dependencies.data, (configuration.dependencies.idFields || ['id']).map(f => row[f])); } // Return the row finally return row; diff --git a/build/src/api/dataset/orgcheck-api-dataset-flows.js b/build/src/api/dataset/orgcheck-api-dataset-flows.js index 8d6cec2e..07f2f735 100644 --- a/build/src/api/dataset/orgcheck-api-dataset-flows.js +++ b/build/src/api/dataset/orgcheck-api-dataset-flows.js @@ -40,10 +40,14 @@ export class DatasetFlows extends Dataset { // Then retreive dependencies logger?.log(`Retrieving dependencies of ${flowDefRecords.length} flow versions...`); - const flowDefinitionsDependencies = await sfdcManager.dependenciesQuery( - await Processor.map(flowDefRecords, (record) => sfdcManager.caseSafeId(record.ActiveVersionId ?? record.LatestVersionId)), - logger - ); + const flowDependenciesIds = []; + await Processor.forEach(flowDefRecords, (record) => { + // Add the ID15 of the most interesting flow version + flowDependenciesIds.push(sfdcManager.caseSafeId(record.ActiveVersionId ?? record.LatestVersionId)); + // Add the ID15 of the flow definition + flowDependenciesIds.push(sfdcManager.caseSafeId(record.Id)); + }); + const flowDefinitionsDependencies = await sfdcManager.dependenciesQuery(flowDependenciesIds, logger); // List of active flows that we need to get information later (with Metadata API) const activeFlowIds = []; @@ -74,7 +78,7 @@ export class DatasetFlows extends Dataset { }, dependencies: { data: flowDefinitionsDependencies, - idField: 'currentVersionId' + idFields: [ 'id', 'currentVersionId' ] } }); diff --git a/build/test/api/unit/orgcheck-api-datadependencies.unit.test.js b/build/test/api/unit/orgcheck-api-datadependencies.unit.test.js index 85404d67..7d3f9622 100644 --- a/build/test/api/unit/orgcheck-api-datadependencies.unit.test.js +++ b/build/test/api/unit/orgcheck-api-datadependencies.unit.test.js @@ -53,7 +53,7 @@ describe('tests.api.unit.DataDependencies', () => { describe('Using a predefined set of relationship (001), make sure the using, referenced and refByTypes properties for Apex Class 001 are well defined', () => { // In the relationShip 001, ApexClass001 uses ApexClass002 and CustomField001 and is referenced in ApexClass003 and CustomField002. - const dataDep = DataDependenciesFactory.create({ records: RELATIONSHIP_001, errors: [] }, APEXCLASS_001.id); + const dataDep = DataDependenciesFactory.create({ records: RELATIONSHIP_001, errors: [] }, [ APEXCLASS_001.id ]); it('checks if using property is well defined', () => { const using = dataDep.using; @@ -85,7 +85,7 @@ describe('tests.api.unit.DataDependencies', () => { describe('Using a predefined set of relationship (001), make sure the using, referenced and refByTypes properties for Apex Class 002 are well defined', () => { // In the relationShip 001, ApexClass002 uses ApexClass003 and is referenced in ApexClass001. - const dataDep = DataDependenciesFactory.create({ records: RELATIONSHIP_001, errors: [] }, APEXCLASS_002.id); + const dataDep = DataDependenciesFactory.create({ records: RELATIONSHIP_001, errors: [] }, [ APEXCLASS_002.id ]); it('checks if using property is well defined', () => { const using = dataDep.using; @@ -114,7 +114,7 @@ describe('tests.api.unit.DataDependencies', () => { describe('Using a predefined set of relationship (001), make sure the using, referenced and refByTypes properties for Custom Field 001 are well defined', () => { // In the relationShip 001, CustomField001 uses CustomField002 and is referenced in ApexClass001. - const dataDep = DataDependenciesFactory.create({ records: RELATIONSHIP_001, errors: [] }, CUSTOMFIELD_001.id); + const dataDep = DataDependenciesFactory.create({ records: RELATIONSHIP_001, errors: [] }, [ CUSTOMFIELD_001.id ]); it('checks if using property is well defined', () => { const using = dataDep.using; @@ -143,7 +143,7 @@ describe('tests.api.unit.DataDependencies', () => { describe('Using a predefined set of relationship (002), make sure the using, referenced and refByTypes properties for Custom Field 001 are well defined', () => { // In the relationShip 002, CustomField001 uses nothing and is referenced in 4 page layouts and in ApexClass001. - const dataDep = DataDependenciesFactory.create({ records: RELATIONSHIP_002, errors: [] }, CUSTOMFIELD_001.id); + const dataDep = DataDependenciesFactory.create({ records: RELATIONSHIP_002, errors: [] }, [ CUSTOMFIELD_001.id ]); it('checks if using property is well defined', () => { const using = dataDep.using; diff --git a/force-app/main/default/lwc/orgcheckApp/libs/orgcheck-api.js b/force-app/main/default/lwc/orgcheckApp/libs/orgcheck-api.js index 73c914a2..1b62e313 100644 --- a/force-app/main/default/lwc/orgcheckApp/libs/orgcheck-api.js +++ b/force-app/main/default/lwc/orgcheckApp/libs/orgcheck-api.js @@ -251,11 +251,12 @@ class DataDependenciesFactory { /** * @description Create a new instance of DataDependencies * @param {{ records: Array<{ id: string, name: string, type: string, url: string, refId: string, refName: string, refType: string, refUrl: string }>, errors: Array }} data - * @param {string} whatId + * @param {Array} whatIds * @returns {DataDependencies} */ - static create(data, whatId) { - if (data.errors?.includes(whatId)) { + static create(data, whatIds) { + // Check if at least one of the whatIds is present in the data errors list + if (data.errors?.some(errorId => whatIds.includes(errorId))) { return { hadError: true, using: [], @@ -263,7 +264,9 @@ class DataDependenciesFactory { referencedByTypes: {} }; } - const using = data.records.filter(e => e.id === whatId).map(n => { + // Data can contain a lot of dependencies from other ids, we just want to get the dependencies for the given whatIds + // WhatID is using what? -- Here we are getting the dependencies where the ID is in the whatIds list + const using = data.records.filter(e => whatIds.includes(e.id)).map(n => { return { id: n.refId, name: n.refName, @@ -272,7 +275,8 @@ class DataDependenciesFactory { }; }); const referencedByTypes = {}; - const referenced = data.records.filter(e => e.refId === whatId).map(n => { + // WhatID is referenced where? -- Here we are getting the dependencies where the REFID is in the whatIds list + const referenced = data.records.filter(e => whatIds.includes(e.refId)).map(n => { if (referencedByTypes[n.type] === undefined) { referencedByTypes[n.type] = 1; } else { @@ -7918,10 +7922,14 @@ class DatasetFlows extends Dataset { // Then retreive dependencies logger?.log(`Retrieving dependencies of ${flowDefRecords.length} flow versions...`); - const flowDefinitionsDependencies = await sfdcManager.dependenciesQuery( - await Processor.map(flowDefRecords, (record) => sfdcManager.caseSafeId(record.ActiveVersionId ?? record.LatestVersionId)), - logger - ); + const flowDependenciesIds = []; + await Processor.forEach(flowDefRecords, (record) => { + // Add the ID15 of the most interesting flow version + flowDependenciesIds.push(sfdcManager.caseSafeId(record.ActiveVersionId ?? record.LatestVersionId)); + // Add the ID15 of the flow definition + flowDependenciesIds.push(sfdcManager.caseSafeId(record.Id)); + }); + const flowDefinitionsDependencies = await sfdcManager.dependenciesQuery(flowDependenciesIds, logger); // List of active flows that we need to get information later (with Metadata API) const activeFlowIds = []; @@ -7952,7 +7960,7 @@ class DatasetFlows extends Dataset { }, dependencies: { data: flowDefinitionsDependencies, - idField: 'currentVersionId' + idFields: [ 'id', 'currentVersionId' ] } }); @@ -8265,7 +8273,7 @@ class DataFactoryInstance extends DataFactoryInstanceIntf { } // If dependencies are needed... if (this._isDependenciesNeeded === true && configuration.dependencies) { - row.dependencies = DataDependenciesFactory.create(configuration.dependencies.data, row[configuration.dependencies.idField || 'id']); + row.dependencies = DataDependenciesFactory.create(configuration.dependencies.data, (configuration.dependencies.idFields || ['id']).map(f => row[f])); } // Return the row finally return row; diff --git a/force-app/main/default/lwc/orgcheckDependencyLink/libs/orgcheck-api.js b/force-app/main/default/lwc/orgcheckDependencyLink/libs/orgcheck-api.js index 73c914a2..1b62e313 100644 --- a/force-app/main/default/lwc/orgcheckDependencyLink/libs/orgcheck-api.js +++ b/force-app/main/default/lwc/orgcheckDependencyLink/libs/orgcheck-api.js @@ -251,11 +251,12 @@ class DataDependenciesFactory { /** * @description Create a new instance of DataDependencies * @param {{ records: Array<{ id: string, name: string, type: string, url: string, refId: string, refName: string, refType: string, refUrl: string }>, errors: Array }} data - * @param {string} whatId + * @param {Array} whatIds * @returns {DataDependencies} */ - static create(data, whatId) { - if (data.errors?.includes(whatId)) { + static create(data, whatIds) { + // Check if at least one of the whatIds is present in the data errors list + if (data.errors?.some(errorId => whatIds.includes(errorId))) { return { hadError: true, using: [], @@ -263,7 +264,9 @@ class DataDependenciesFactory { referencedByTypes: {} }; } - const using = data.records.filter(e => e.id === whatId).map(n => { + // Data can contain a lot of dependencies from other ids, we just want to get the dependencies for the given whatIds + // WhatID is using what? -- Here we are getting the dependencies where the ID is in the whatIds list + const using = data.records.filter(e => whatIds.includes(e.id)).map(n => { return { id: n.refId, name: n.refName, @@ -272,7 +275,8 @@ class DataDependenciesFactory { }; }); const referencedByTypes = {}; - const referenced = data.records.filter(e => e.refId === whatId).map(n => { + // WhatID is referenced where? -- Here we are getting the dependencies where the REFID is in the whatIds list + const referenced = data.records.filter(e => whatIds.includes(e.refId)).map(n => { if (referencedByTypes[n.type] === undefined) { referencedByTypes[n.type] = 1; } else { @@ -7918,10 +7922,14 @@ class DatasetFlows extends Dataset { // Then retreive dependencies logger?.log(`Retrieving dependencies of ${flowDefRecords.length} flow versions...`); - const flowDefinitionsDependencies = await sfdcManager.dependenciesQuery( - await Processor.map(flowDefRecords, (record) => sfdcManager.caseSafeId(record.ActiveVersionId ?? record.LatestVersionId)), - logger - ); + const flowDependenciesIds = []; + await Processor.forEach(flowDefRecords, (record) => { + // Add the ID15 of the most interesting flow version + flowDependenciesIds.push(sfdcManager.caseSafeId(record.ActiveVersionId ?? record.LatestVersionId)); + // Add the ID15 of the flow definition + flowDependenciesIds.push(sfdcManager.caseSafeId(record.Id)); + }); + const flowDefinitionsDependencies = await sfdcManager.dependenciesQuery(flowDependenciesIds, logger); // List of active flows that we need to get information later (with Metadata API) const activeFlowIds = []; @@ -7952,7 +7960,7 @@ class DatasetFlows extends Dataset { }, dependencies: { data: flowDefinitionsDependencies, - idField: 'currentVersionId' + idFields: [ 'id', 'currentVersionId' ] } }); @@ -8265,7 +8273,7 @@ class DataFactoryInstance extends DataFactoryInstanceIntf { } // If dependencies are needed... if (this._isDependenciesNeeded === true && configuration.dependencies) { - row.dependencies = DataDependenciesFactory.create(configuration.dependencies.data, row[configuration.dependencies.idField || 'id']); + row.dependencies = DataDependenciesFactory.create(configuration.dependencies.data, (configuration.dependencies.idFields || ['id']).map(f => row[f])); } // Return the row finally return row; diff --git a/force-app/main/default/lwc/orgcheckDependencyViewer/libs/orgcheck-api.js b/force-app/main/default/lwc/orgcheckDependencyViewer/libs/orgcheck-api.js index 73c914a2..1b62e313 100644 --- a/force-app/main/default/lwc/orgcheckDependencyViewer/libs/orgcheck-api.js +++ b/force-app/main/default/lwc/orgcheckDependencyViewer/libs/orgcheck-api.js @@ -251,11 +251,12 @@ class DataDependenciesFactory { /** * @description Create a new instance of DataDependencies * @param {{ records: Array<{ id: string, name: string, type: string, url: string, refId: string, refName: string, refType: string, refUrl: string }>, errors: Array }} data - * @param {string} whatId + * @param {Array} whatIds * @returns {DataDependencies} */ - static create(data, whatId) { - if (data.errors?.includes(whatId)) { + static create(data, whatIds) { + // Check if at least one of the whatIds is present in the data errors list + if (data.errors?.some(errorId => whatIds.includes(errorId))) { return { hadError: true, using: [], @@ -263,7 +264,9 @@ class DataDependenciesFactory { referencedByTypes: {} }; } - const using = data.records.filter(e => e.id === whatId).map(n => { + // Data can contain a lot of dependencies from other ids, we just want to get the dependencies for the given whatIds + // WhatID is using what? -- Here we are getting the dependencies where the ID is in the whatIds list + const using = data.records.filter(e => whatIds.includes(e.id)).map(n => { return { id: n.refId, name: n.refName, @@ -272,7 +275,8 @@ class DataDependenciesFactory { }; }); const referencedByTypes = {}; - const referenced = data.records.filter(e => e.refId === whatId).map(n => { + // WhatID is referenced where? -- Here we are getting the dependencies where the REFID is in the whatIds list + const referenced = data.records.filter(e => whatIds.includes(e.refId)).map(n => { if (referencedByTypes[n.type] === undefined) { referencedByTypes[n.type] = 1; } else { @@ -7918,10 +7922,14 @@ class DatasetFlows extends Dataset { // Then retreive dependencies logger?.log(`Retrieving dependencies of ${flowDefRecords.length} flow versions...`); - const flowDefinitionsDependencies = await sfdcManager.dependenciesQuery( - await Processor.map(flowDefRecords, (record) => sfdcManager.caseSafeId(record.ActiveVersionId ?? record.LatestVersionId)), - logger - ); + const flowDependenciesIds = []; + await Processor.forEach(flowDefRecords, (record) => { + // Add the ID15 of the most interesting flow version + flowDependenciesIds.push(sfdcManager.caseSafeId(record.ActiveVersionId ?? record.LatestVersionId)); + // Add the ID15 of the flow definition + flowDependenciesIds.push(sfdcManager.caseSafeId(record.Id)); + }); + const flowDefinitionsDependencies = await sfdcManager.dependenciesQuery(flowDependenciesIds, logger); // List of active flows that we need to get information later (with Metadata API) const activeFlowIds = []; @@ -7952,7 +7960,7 @@ class DatasetFlows extends Dataset { }, dependencies: { data: flowDefinitionsDependencies, - idField: 'currentVersionId' + idFields: [ 'id', 'currentVersionId' ] } }); @@ -8265,7 +8273,7 @@ class DataFactoryInstance extends DataFactoryInstanceIntf { } // If dependencies are needed... if (this._isDependenciesNeeded === true && configuration.dependencies) { - row.dependencies = DataDependenciesFactory.create(configuration.dependencies.data, row[configuration.dependencies.idField || 'id']); + row.dependencies = DataDependenciesFactory.create(configuration.dependencies.data, (configuration.dependencies.idFields || ['id']).map(f => row[f])); } // Return the row finally return row; diff --git a/force-app/main/default/lwc/orgcheckExtendedDatatable/libs/orgcheck-api.js b/force-app/main/default/lwc/orgcheckExtendedDatatable/libs/orgcheck-api.js index 73c914a2..1b62e313 100644 --- a/force-app/main/default/lwc/orgcheckExtendedDatatable/libs/orgcheck-api.js +++ b/force-app/main/default/lwc/orgcheckExtendedDatatable/libs/orgcheck-api.js @@ -251,11 +251,12 @@ class DataDependenciesFactory { /** * @description Create a new instance of DataDependencies * @param {{ records: Array<{ id: string, name: string, type: string, url: string, refId: string, refName: string, refType: string, refUrl: string }>, errors: Array }} data - * @param {string} whatId + * @param {Array} whatIds * @returns {DataDependencies} */ - static create(data, whatId) { - if (data.errors?.includes(whatId)) { + static create(data, whatIds) { + // Check if at least one of the whatIds is present in the data errors list + if (data.errors?.some(errorId => whatIds.includes(errorId))) { return { hadError: true, using: [], @@ -263,7 +264,9 @@ class DataDependenciesFactory { referencedByTypes: {} }; } - const using = data.records.filter(e => e.id === whatId).map(n => { + // Data can contain a lot of dependencies from other ids, we just want to get the dependencies for the given whatIds + // WhatID is using what? -- Here we are getting the dependencies where the ID is in the whatIds list + const using = data.records.filter(e => whatIds.includes(e.id)).map(n => { return { id: n.refId, name: n.refName, @@ -272,7 +275,8 @@ class DataDependenciesFactory { }; }); const referencedByTypes = {}; - const referenced = data.records.filter(e => e.refId === whatId).map(n => { + // WhatID is referenced where? -- Here we are getting the dependencies where the REFID is in the whatIds list + const referenced = data.records.filter(e => whatIds.includes(e.refId)).map(n => { if (referencedByTypes[n.type] === undefined) { referencedByTypes[n.type] = 1; } else { @@ -7918,10 +7922,14 @@ class DatasetFlows extends Dataset { // Then retreive dependencies logger?.log(`Retrieving dependencies of ${flowDefRecords.length} flow versions...`); - const flowDefinitionsDependencies = await sfdcManager.dependenciesQuery( - await Processor.map(flowDefRecords, (record) => sfdcManager.caseSafeId(record.ActiveVersionId ?? record.LatestVersionId)), - logger - ); + const flowDependenciesIds = []; + await Processor.forEach(flowDefRecords, (record) => { + // Add the ID15 of the most interesting flow version + flowDependenciesIds.push(sfdcManager.caseSafeId(record.ActiveVersionId ?? record.LatestVersionId)); + // Add the ID15 of the flow definition + flowDependenciesIds.push(sfdcManager.caseSafeId(record.Id)); + }); + const flowDefinitionsDependencies = await sfdcManager.dependenciesQuery(flowDependenciesIds, logger); // List of active flows that we need to get information later (with Metadata API) const activeFlowIds = []; @@ -7952,7 +7960,7 @@ class DatasetFlows extends Dataset { }, dependencies: { data: flowDefinitionsDependencies, - idField: 'currentVersionId' + idFields: [ 'id', 'currentVersionId' ] } }); @@ -8265,7 +8273,7 @@ class DataFactoryInstance extends DataFactoryInstanceIntf { } // If dependencies are needed... if (this._isDependenciesNeeded === true && configuration.dependencies) { - row.dependencies = DataDependenciesFactory.create(configuration.dependencies.data, row[configuration.dependencies.idField || 'id']); + row.dependencies = DataDependenciesFactory.create(configuration.dependencies.data, (configuration.dependencies.idFields || ['id']).map(f => row[f])); } // Return the row finally return row; diff --git a/force-app/main/default/staticresources/OrgCheck_SR.resource b/force-app/main/default/staticresources/OrgCheck_SR.resource index 422228a1..43e1d6a2 100644 Binary files a/force-app/main/default/staticresources/OrgCheck_SR.resource and b/force-app/main/default/staticresources/OrgCheck_SR.resource differ