From c3dde4c5f012db9cc0424ec5073279f0988c979d Mon Sep 17 00:00:00 2001 From: Rahul Gawale Date: Thu, 20 Jun 2024 21:02:38 +0530 Subject: [PATCH] Added Child relations and updated readme --- .changeset/fluffy-sheep-vanish.md | 10 ++++ .github/workflows/main.yml | 17 +++--- .github/workflows/publish.yml | 19 ++++--- .prettierrc | 2 +- README.md | 94 +++++++++++++++++++++++++++---- package.json | 4 +- src/data/ftypesc.ts | 19 ++++++- src/generator.ts | 85 +++++++++++++++++++--------- src/objectInfoFetcher.ts | 44 +++++++++------ src/types.ts | 78 +++++++++++++++---------- 10 files changed, 265 insertions(+), 107 deletions(-) create mode 100644 .changeset/fluffy-sheep-vanish.md diff --git a/.changeset/fluffy-sheep-vanish.md b/.changeset/fluffy-sheep-vanish.md new file mode 100644 index 0000000..ef9eecc --- /dev/null +++ b/.changeset/fluffy-sheep-vanish.md @@ -0,0 +1,10 @@ +--- +'@forcetrails/sobject-types': minor +--- + +- Added Support for Child Relationships +- Fixed Picklist Value autocomplete +- Added Index.ts +- Added base interface for SObject +- Fixed code formatting inconsistency +- Updated Readme.md diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 5097989..c63e052 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -1,21 +1,22 @@ name: CI + on: push: branches: - - "**" + - '**' jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - uses: pnpm/action-setup@v2 - with: - version: 7 - - uses: actions/setup-node@v3 + + - name: Setup Node.js environment + uses: actions/setup-node@v3 with: node-version: 16.x - cache: "pnpm" + # Optionally, configure npm cache if needed + # cache: "npm" - - run: pnpm install --frozen-lockfile - - run: pnpm run lint && pnpm run build \ No newline at end of file + - run: npm install --frozen-lockfile + - run: npm run build diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index e7cc1ea..1a41e8f 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,4 +1,5 @@ name: Publish + on: workflow_run: workflows: [CI] @@ -17,20 +18,22 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - uses: pnpm/action-setup@v2 - with: - version: 7 - - uses: actions/setup-node@v3 + + # Remove pnpm setup and replace with npm setup + - name: Setup Node.js environment + uses: actions/setup-node@v3 with: node-version: 16.x - cache: "pnpm" + # Optionally, configure npm cache if needed + # cache: "npm" + + - run: npm install --frozen-lockfile - - run: pnpm install --frozen-lockfile - name: Create Release Pull Request or Publish id: changesets uses: changesets/action@v1 with: - publish: pnpm run release + publish: npm run release env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - NPM_TOKEN: ${{ secrets.NPM_TOKEN }} \ No newline at end of file + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.prettierrc b/.prettierrc index 2024d7d..1a54ffb 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,5 +1,5 @@ { "tabWidth": 2, "useTabs": false, - "singleQuote": false + "singleQuote": true } \ No newline at end of file diff --git a/README.md b/README.md index d3dcad7..85b5f11 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ## Overview -The `@forcetrails/sobject-types` Tool is a command-line utility built to automate the generation of TypeScript definition files (.d.ts) for Salesforce objects. These definition files are crucial for projects containing TypeScript LWC components or LWC components with JSDocs, providing type safety and autocompletion support. +The `@forcetrails/sobject-types` Tool is a command-line utility built to automate the generation of TypeScript definition files (`.ts`) for Salesforce objects. These definition files are crucial for projects containing TypeScript LWC components or LWC components with JSDocs, providing type safety and autocompletion support. The tool fetches metadata for specified Salesforce objects, extracts fields and their corresponding data types, and generates TypeScript interfaces that mirror the structure of these Salesforce objects. @@ -24,34 +24,99 @@ npm i @forcetrails/sobject-types #### 2. Configure Salesforce Connection: - Update the `./ftypes/ftypesc.json` file with your Salesforce credentials and desired configuration (e.g., Salesforce objects to generate .d.ts files for, output directory). +Update the `./ftypes/ftypesc.json` file with your Salesforce credentials and desired configuration (e.g., Salesforce objects to generate `.ts` files for, output directory). #### 3. Run the command + ```bash npx ftypes ``` +#### 4. Update TypeScript Config (Required if you are using TypeScript LWC Components) + +- Update the `tsconfig.json` to include the output folder i.e. `./ftypes` by default to add paths for `@sobject-types`. + +```json +{ + "compilerOptions": { + // ... + "paths": { + "@sobject-types/*": ["./.ftypes/typings/*"] + } + } + // ... other config. +} +``` + +#### 5. Start Using Types - TypeScript (Required if you are using TypeScript LWC Components) + +```ts +// 1. -----> import type +import { Account } from '@sobject-types/Index'; + +import { LightningElement, api } from 'lwc'; + +export default class TodoItem extends LightningElement { + // 2. -----> use type + account: Account = { + ChildAccounts: [], + CleanStatus: 'NotFound', + Type: 'Channel Partner / Reseller', + Industry: '', + Ownership: 'Other', + Rating: 'Cold', + }; +} +``` + +#### 6. Start Using Types - JavaScript & JSDoc + +```js +// 1. -----> Import the type +/** + * @typedef {import('./.ftypes/typings/Index.ts').Account} Account + */ +import { LightningElement, api } from 'lwc'; +export default class TodoItem extends LightningElement { + // 2. -----> Use the Type + /** + * @type Account + */ + account = { + ChildAccounts: [], + CleanStatus: 'NotFound', + Type: 'Channel Partner / Reseller', + Industry: '', + Ownership: 'Other', + Rating: 'Cold', + }; +} +``` + ## Usage ### Commands -- `ftypes init` Initialize the ftypes configuration -- `ftypes list` List all sObjects from config file -- `ftypes config` Show config contents -- `ftypes set-target-org ` Set the default Salesforce organization username in `./ftypes/ftypesc.json`. **This is alias of already authenticated Salesforce org from sf auth -- `ftypes add ` Add type definitions for a specific object -- `ftypes refresh ` Add type definitions for a specific object(s) -- `ftypes` Generate Typings for all SObjects from config +- `ftypes init` Initialize the ftypes configuration +- `ftypes list` List all sObjects from config file +- `ftypes config` Show config contents +- `ftypes set-target-org ` Set the default Salesforce organization username in `./ftypes/ftypesc.json`. \*\*This is alias of already authenticated Salesforce org from sf auth +- `ftypes add ` Add type definitions for a specific object +- `ftypes refresh ` Add type definitions for a specific object(s) +- `ftypes` Generate Typings for all SObjects from config ### Examples + #### 1. Init `ftypes` project with default configuration: ```bash ftypes init ``` + This command creates `.ftypes` file in the current work directory and adds default configuration for types generation -#### 2. Generate `.d.ts` file for all objects mentioned config: +#### 2. Generate `.ts` file for all objects mentioned config: + ```bash ftypes ``` @@ -61,6 +126,7 @@ ftypes ```bash ftypes add Account ``` + This command adds `Account` object to config list and generates Types for account object #### 4. Refresh typings of existing Object: @@ -68,13 +134,15 @@ This command adds `Account` object to config list and generates Types for accoun ```bash ftypes refresh Account ``` -This command regenerates `Account.d.ts` in the specified output directory. + +This command regenerates `Account.ts` in the specified output directory. ### 5. List all configured Salesforce objects: ```bash ftypes list ``` + Lists all Salesforce objects configured in config file(`./ftypes/ftypesc.json`). #### 6. Set default Salesforce organization username: @@ -82,6 +150,7 @@ Lists all Salesforce objects configured in config file(`./ftypes/ftypesc.json`). ```bash ftypes set-target-org my-sf-org ``` + Sets defaultusername in `./ftypes/ftypesc.json` to `my-sf-org` in your sfdx project. #### 7. Display contents of (`./ftypes/ftypesc.json`): @@ -89,6 +158,7 @@ Sets defaultusername in `./ftypes/ftypesc.json` to `my-sf-org` in your sfdx proj ```bash ftypes configs ``` + Displays the contents of the configuration file (`./ftypes/ftypesc.json`). -More features coming soon... \ No newline at end of file +More features coming soon... diff --git a/package.json b/package.json index f9ab5d3..3a3aaa3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@forcetrails/sobject-types", - "version": "0.2.0", + "version": "0.3.0", "description": "SObject and Field Types for Lightning Web Components TypeScript or JSDOC, to enable Type Safety and Intellisense", "repository": { "type": "git", @@ -39,4 +39,4 @@ "tsup": "^8.1.0", "typescript": "^5.4.5" } -} +} \ No newline at end of file diff --git a/src/data/ftypesc.ts b/src/data/ftypesc.ts index 718da4e..7ad65bc 100644 --- a/src/data/ftypesc.ts +++ b/src/data/ftypesc.ts @@ -15,4 +15,21 @@ export const config = { outputDir: "./.ftypes/typings", defaultusername: "gunguna-dev", sfdxDir: "../.sfdx/sfdx-config.json" -}; \ No newline at end of file +}; + +export const BaseTypesFileName = 'BaseTypes.ts'; +export const BaseTypes = `// base Types class +export interface SObject { + Id?: string; + Name?: string; + CreatedById?: string; + LastModifiedById?: string; + OwnerId?: string; + CreatedDate?: Date | string; + LastModifiedDate?: Date | string; + SystemModstamp?: Date | string; + IsDeleted?: boolean; + [key: string]: any; // Additional fields +}`; + +export const IndexFileName = 'Index.ts'; \ No newline at end of file diff --git a/src/generator.ts b/src/generator.ts index 418adae..4e1b29e 100644 --- a/src/generator.ts +++ b/src/generator.ts @@ -1,20 +1,21 @@ -import { PicklistResult, SObjectFieldSchema, SObjectSchema } from "./types"; +import { getConfig } from "./config"; +import { Config, PicklistResult, SObjectFieldSchema, SObjectSchema } from "./types"; + +export function generateTypes(sObjectDef: SObjectSchema, config: Config) { -export function generateTypes(sObjectDef: SObjectSchema) { - const a: SObjectSchema = { - fields: [], - name: "test", - label: "test" - } const fields = sObjectDef.fields; const picklistTypes = getPicklistTypes(sObjectDef.name, fields); + const relations = generateChildRelations(sObjectDef, config); + let tsContent = ` +import { SObject } from './BaseTypes'; +${relations.imports} // picklist types ${picklistTypes.typeDefs.join('\n')} -declare module "@sobject-types/${sObjectDef.name}"{\n - export interface ${sObjectDef.name} {\n`; + +export interface ${sObjectDef.name} extends SObject {\n`; fields.forEach((field, i) => { let fieldType: string; @@ -28,11 +29,13 @@ declare module "@sobject-types/${sObjectDef.name}"{\n // const optional = field.nillable ? '?' : ''; const readOnly = field.calculated || field.autoNumber ? "readonly " : ""; tsContent += `${additionalFieldInfo(field)}\n`; - tsContent += ` ${readOnly}${fieldName}?: ${fieldType};\n`; + tsContent += ` ${readOnly}${fieldName}?: ${fieldType};\n`; }); - tsContent += ` } - }\n`; + tsContent += relations.childrenDef; + + // close object + tsContent += `}\n`; return tsContent; } @@ -64,7 +67,7 @@ function mapFieldType(salesforceType: string) { // dates case 'date': case 'datetime': - return 'Date'; + return 'Date | string'; // other default: @@ -88,7 +91,7 @@ function getPicklistTypes(objName: string, field: SObjectFieldSchema[]) { field.filter(f => f.type === "picklist").forEach(f => { let tName = `${objName}_${f.name}_Picklist`; - picklistTypes.typeDefs.push(`type ${tName} = ${buildPicklist(f)}${f.restrictedPicklist === true ? '' : ' | string'};`) + picklistTypes.typeDefs.push(`type ${tName} = ${buildPicklist(f)}${f.restrictedPicklist === true ? '' : ' | (string & {})'};`) picklistTypes.typeNames.set(f.name, tName); }) @@ -97,19 +100,47 @@ function getPicklistTypes(objName: string, field: SObjectFieldSchema[]) { function additionalFieldInfo(field: SObjectFieldSchema) { let moreInfo = ""; - moreInfo += field.calculated ? "\n @Formula" : ""; - moreInfo += field.referenceTo && field.referenceTo.length > 0 ? `\n @Related To ${field.referenceTo?.join(",")}` : ""; - moreInfo += field.relationshipName ? `\n @Relationship-Name ${field.relationshipName}` : ""; - moreInfo += field.unique ? `\n @Unique` : ""; - moreInfo += field.autoNumber ? `\n @Auto Number` : ""; - - const cmt = ` /** - @label ${field.label} - @type ${field.type} - @nillable ${field.nillable} - @Create ${field.createable} - @Update ${field.updateable} - ${moreInfo}*/`; + moreInfo += field.calculated ? "\n * @Formula" : ""; + moreInfo += field.referenceTo && field.referenceTo.length > 0 ? `\n * @RelatedTo - ${field.referenceTo?.join(",")}` : ""; + moreInfo += field.relationshipName ? `\n * @RelationshipName - ${field.relationshipName}` : ""; + moreInfo += field.unique ? `\n * @Unique` : ""; + moreInfo += field.autoNumber ? `\n * @Auto Number` : ""; + + const cmt = ` /** + * @label ${field.label} + * @type ${field.type} + * @nillable ${field.nillable} + * @Create ${field.createable} + * @Update ${field.updateable} + ${moreInfo} */`; return cmt; +} + +function generateChildRelations(object: SObjectSchema, config: Config) { + let childrenDef = "\n // Child relationships\n"; + let imports = ''; + object.childRelationships?.forEach(child => { + + if (child.relationshipName) { + const childType = config.sObjects.includes(child.childSObject) ? + child.childSObject : "SObject" + + if (childType !== 'SObject' && childType !== object.name) { + imports += `import { ${childType} } from './${childType}';\n`; + } + + childrenDef += ` + /** + * @Object - ${child.childSObject} + * @Field - ${child.field} + * @cascadeDelete - ${child.cascadeDelete} + * @restrictedDelete - ${child.restrictedDelete} + * */ + ${child.relationshipName}?: ${childType}[];\n` + + } + }) + + return { childrenDef, imports }; } \ No newline at end of file diff --git a/src/objectInfoFetcher.ts b/src/objectInfoFetcher.ts index 6a9ee5a..1d8b04d 100644 --- a/src/objectInfoFetcher.ts +++ b/src/objectInfoFetcher.ts @@ -6,11 +6,12 @@ import { Config, SObjectSchema } from './types'; import { generateTypes } from './generator'; import logger from './logger'; import { scriptName } from './types'; +import { BaseTypes, BaseTypesFileName, IndexFileName } from './data/ftypesc'; interface CommandOutPut { - status: number, - result: any, - warning: any + status: number; + result: any; + warning: any; } /** @@ -62,10 +63,10 @@ export async function generateSobjectTypes(config: Config, obj: string) { logger.info("name: " + objMetadata.name); logger.info("#fields: " + objMetadata.fields.length); - const filename = path.resolve(config.outputDir, obj + '.d.ts'); - const types = generateTypes(objMetadata); + const filename = path.resolve(config.outputDir, obj + '.ts'); + const types = generateTypes(objMetadata, config); // create output folder if not exists - ensureDirectoryExists(config.outputDir); + await ensureDirectoryExists(config.outputDir); await saveToFile(filename, types); return { success: true, message: `Successfully processed ${obj}` }; } else { @@ -78,22 +79,11 @@ export async function generateSobjectTypes(config: Config, obj: string) { } } -export async function generateAllTypes() { +export async function generateAllTypesParallel() { try { const config = await getConfig(); - await createDirectoryRecursive(config.outputDir); - for (const obj of config.sObjects) { - generateSobjectTypes(config, obj); - } - } catch (error) { - logger.error(`Error listing sObjects: ${(error as Error).message}`); - } -} -export async function generateAllTypesParallel() { - try { - const config = await getConfig(); if (config) { await createDirectoryRecursive(config.outputDir, true); @@ -109,8 +99,26 @@ export async function generateAllTypesParallel() { logger.error(result.message); } }); + + // generate base types + await generateBaseTypes(config); + await generateIndex(config); } } catch (error) { logger.error(`Error listing sObjects: ${(error as Error).message}`); } } + +async function generateBaseTypes(config: Config) { + const file = path.resolve(config.outputDir, BaseTypesFileName); + await saveToFile(file, BaseTypes); +} + +async function generateIndex(config: Config) { + let index = `export * from './BaseTypes';\n`; + config.sObjects.forEach(obj => { + index += `export * from './${obj}';\n` + }) + const indexFile = path.resolve(config.outputDir, IndexFileName); + await saveToFile(indexFile, index); +} \ No newline at end of file diff --git a/src/types.ts b/src/types.ts index 90a0791..a3c009a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,34 +1,52 @@ export type NullableNumber = number | null | undefined; export interface SObjectSchema { - fields: SObjectFieldSchema[], - name: string, - label: string, - [key: string]: any + fields: SObjectFieldSchema[]; + childRelationships?: ChildRelationShip[]; + name: string; + label: string; + urls: URLS; + [key: string]: any; +} + +export interface URLS { + uiNewRecord: string; + [key: string]: string; +} + +export interface ChildRelationShip { + cascadeDelete: boolean; + childSObject: string; + deprecatedAndHidden: boolean; + field: string; + junctionIdListNames: []; + junctionReferenceTo: []; + relationshipName: string; + restrictedDelete: boolean; } export interface SObjectFieldSchema { - label: string, - name: string, - type: FieldType, - nillable: boolean, - createable: boolean, - updateable: boolean, - unique: boolean, - autoNumber: boolean, - calculated?: boolean - picklistValues?: PicklistValueSchema[], - referenceTo?: string[], - restrictedPicklist?: boolean, - [key: string]: any + label: string; + name: string; + type: FieldType; + nillable: boolean; + createable: boolean; + updateable: boolean; + unique: boolean; + autoNumber: boolean; + calculated?: boolean; + picklistValues?: PicklistValueSchema[]; + referenceTo?: string[]; + restrictedPicklist?: boolean; + [key: string]: any; } export interface PicklistValueSchema { - active: boolean, - defaultValue: boolean, - label: string, - validFor: string[] | null, - value: string + active: boolean; + defaultValue: boolean; + label: string; + validFor: string[] | null; + value: string; } export type FieldType = 'picklist' | @@ -47,20 +65,20 @@ export type FieldType = 'picklist' | 'any' export interface PicklistResult { - typeDefs: string[], - typeNames: Map + typeDefs: string[]; + typeNames: Map; } export interface SfdxConfig { - defaultusername: string + defaultusername: string; } export interface Config { - sObjects: string[], - sfPath: string, - outputDir: string, - defaultusername: string, - sfdxDir: string + sObjects: string[]; + sfPath: string; + outputDir: string; + defaultusername: string; + sfdxDir: string; } export const scriptName = 'ftypes'; \ No newline at end of file