Skip to content

Conversation

@lionhummer
Copy link

Please explain how to summarize this PR for the Changelog:

This PR adds a couple of new options for the automap plugin:

onSuccess?: (event: FlatfileEvent) => void

Option for callback in success case

allColumnsMustBeMapped?: 'none' | 'both' | 'only-source' | 'only-target'

Option that enables a check prior to the accuracy verification, to check if there are any unmatched columns (source or target sheet, none or both)

filenameOnCheck?: string
filenameOnStart?: string
filenameOnSuccess?: string
filenameOnFailure?: string

Options to override the file name on update

disableFileNameUpdateOnSuccess?: boolean
disableFileNameUpdateOnFailure?: boolean

Options to disbale updating the file name on success or failure of automap plugin

Tell code reviewer how and what to test:

automap({
        accuracy: "confident",
        debug: false,
        defaultTargetSheet: "clients",
        matchFilename: /.*/,
        onFailure: (event: any) => {
          notify("Automap failed", "error", event.context.spaceId); 
        }
}),

These changes are backwards competible. So the above usage should result in the same behaviour as before.

automap({
        accuracy: "confident",
        allColumnsMustBeMapped: 'both',
        debug: false,
        defaultTargetSheet: "clients",
        filenameOnCheck: "Checking {{fileName}}",
        filenameOnStart: "Mapping {{fileName}} to {{destinationSheetName}}",
        filenameOnSuccess: "✅ [Automapped] {{fileName}} to {{destinationSheetName}}",
        filenameOnFailure: "❌ [Automap failed] {{fileName}} to {{destinationSheetName}}",
        matchFilename: /.*/,
        onSuccess: (event: any) => {
          console.log("success")
        },
        onFailure: (event: any) => {
          console.log("fail")
        }
}),

Setting those new options should result in:

  1. Filename after extraction is changed to pattern in fileNameOnCheck
  2. Filename after auto mapping is started should change to pattern in filenameOnStart
  3. Filename after auto mapping succeeded should change to pattern in filenameOnSuccess
  4. Filename after auto mapping failed should change to pattern in filenameOnFailure

Mapping should fail for files where either the source sheet or the destination sheet have unmatched columns

Console messages should be outputted in success and failure case.

@flatfile-nullify
Copy link

flatfile-nullify bot commented Jan 31, 2025

Nullify Code Vulnerabilities

1 findings found in this pull request

🔴 CRITICAL 🟡 HIGH 🔵 MEDIUM ⚪ LOW
0 0 1 0

You can find a list of all findings here

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 31, 2025

Walkthrough

The pull request introduces enhancements to the @flatfile/plugin-automap by adding new configuration options and improving file handling capabilities. The changes include a new onSuccess callback, expanded options for handling unmapped columns, and more flexible file name management. The modifications provide users with greater control over the mapping process, allowing custom actions on successful completion and more granular control over file naming across different stages of processing.

Changes

File Change Summary
.changeset/fair-cobras-flow.md Added changelog entry for new plugin features
plugins/automap/src/automap.plugin.ts - Added defaultOptions function to process and set default configuration
- Updated AutomapOptions interface with new properties for column mapping, file naming, and success handling
plugins/automap/src/automap.service.ts - Added verifyMappedColumns method to validate mapped columns
- Enhanced updateFileName method with async support and stage-based updates
- Introduced new utility methods for file name resolution and variable replacement

Suggested reviewers

  • apoddubn
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (6)
plugins/automap/src/automap.service.ts (5)

47-48: Consider inverting the condition for clarity.
Currently, the code returns if the filename does not match, and otherwise calls updateFileName('check'). Reversing the condition can make the control flow more intuitive.

-if (!this.isFileNameMatch(file)) {
-  return
-} else  {
-  await this.updateFileName('check', file.id)
-}
+if (this.isFileNameMatch(file)) {
+  await this.updateFileName('check', file.id)
+}
🧰 Tools
🪛 GitHub Actions: Lint

[warning] Code formatting does not meet Prettier standards. Run Prettier with --write to fix.


201-203: Ensure missing sheet handling is explicit.
Currently, if the workbook has no matching sheet, sheetName becomes undefined. Consider logging or handling that case explicitly for easier debugging.

🧰 Tools
🪛 GitHub Actions: Lint

[warning] Code formatting does not meet Prettier standards. Run Prettier with --write to fix.


Line range hint 257-344: Consolidate repeated success/failure handling.
The logic in the switch statement for “confident” vs. “exact” accuracy repeats file name updates, logging, and callback invocation for success/failure. Consider extracting the success/failure sequences into helper methods to reduce duplication.

- await this.updateFileName('success', file.id, sheetName)
- if (!this.isNil(this.options.onSuccess)) {
-   this.options.onSuccess(event)
- }
+ await this.handleSuccess(file, sheetName, event)

... // similarly for failure
🧰 Tools
🪛 GitHub Actions: Lint

[warning] Code formatting does not meet Prettier standards. Run Prettier with --write to fix.


515-523: Use global replacement if placeholders can appear multiple times.
Currently, .replace('{{fileName}}', ...) only replaces the first occurrence. If the user supplies multiple {{fileName}} placeholders, only one is replaced.

-fileName = fileName.replace('{{fileName}}', variables.fileName)
+const re = new RegExp('{{fileName}}', 'g')
+fileName = fileName.replace(re, variables.fileName)
🧰 Tools
🪛 GitHub Actions: Lint

[warning] Code formatting does not meet Prettier standards. Run Prettier with --write to fix.


525-541: Optional chaining for safer checks.
Instead of if (match && match[1]), you can use optional chaining for more concise code.

-if (match && match[1]) {
+if (match?.[1]) {
  return match[1].trim();
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 535-535: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🪛 GitHub Actions: Lint

[warning] Code formatting does not meet Prettier standards. Run Prettier with --write to fix.

plugins/automap/src/automap.plugin.ts (1)

Line range hint 1-88: Run Prettier to fix formatting.
A pipeline warning indicates code does not meet Prettier standards. Please run prettier --write to resolve.

🧰 Tools
🪛 GitHub Actions: Lint

[warning] Code formatting does not meet Prettier standards. Run Prettier with --write to fix.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6a3518a and 0e52746.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json, !**/*.json
📒 Files selected for processing (3)
  • .changeset/fair-cobras-flow.md (1 hunks)
  • plugins/automap/src/automap.plugin.ts (3 hunks)
  • plugins/automap/src/automap.service.ts (8 hunks)
🧰 Additional context used
🪛 LanguageTool
.changeset/fair-cobras-flow.md

[uncategorized] ~6-~6: Although a hyphen is possible, it is not necessary in a compound modifier in which the first word is an adverb that ends in ‘ly’.
Context: ...re is no unmatched columns (none, both, only-source, only-target) Add options to change fil...

(HYPHENATED_LY_ADVERB_ADJECTIVE)


[uncategorized] ~6-~6: Although a hyphen is possible, it is not necessary in a compound modifier in which the first word is an adverb that ends in ‘ly’.
Context: ...tched columns (none, both, only-source, only-target) Add options to change file name in suc...

(HYPHENATED_LY_ADVERB_ADJECTIVE)

🪛 GitHub Actions: Lint
plugins/automap/src/automap.plugin.ts

[warning] Code formatting does not meet Prettier standards. Run Prettier with --write to fix.

plugins/automap/src/automap.service.ts

[warning] Code formatting does not meet Prettier standards. Run Prettier with --write to fix.

🪛 Biome (1.9.4)
plugins/automap/src/automap.service.ts

[error] 535-535: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Setup
  • GitHub Check: Nullify Dependencies
🔇 Additional comments (8)
plugins/automap/src/automap.service.ts (3)

133-137: File name update on job creation looks correct.
The logic to update the file name upon job initialization is consistent with the chosen “start” stage and destination sheet name.

🧰 Tools
🪛 GitHub Actions: Lint

[warning] Code formatting does not meet Prettier standards. Run Prettier with --write to fix.


223-227: Verify correct file selection in multi-file scenarios.
This approach selects the first file found that matches the current workbook. If multiple files share the same workbook, ensure that this logic is indeed what you want (i.e., that you truly want the first match).

Would you like me to generate a script to scan the repository for all references to files.list() calls, to confirm consistent usage and potential filtering of multiple files?

🧰 Tools
🪛 GitHub Actions: Lint

[warning] Code formatting does not meet Prettier standards. Run Prettier with --write to fix.


421-447: Column matching approach looks good.
The logic in verifyMappedColumns is straightforward, systematically checking for unmapped fields according to the configured mode.

🧰 Tools
🪛 GitHub Actions: Lint

[warning] Code formatting does not meet Prettier standards. Run Prettier with --write to fix.

plugins/automap/src/automap.plugin.ts (4)

10-11: Instantiating service with defaulted options looks good.
Calling defaultOptions before creating the AutomapService ensures consistent defaults.

🧰 Tools
🪛 GitHub Actions: Lint

[warning] Code formatting does not meet Prettier standards. Run Prettier with --write to fix.


25-35: Documentation of new fields is clear.
The doc comments for the new properties (e.g., allColumnsMustBeMapped, disableFileNameUpdateOnSuccess) are well structured. No major issues found.

🧰 Tools
🪛 GitHub Actions: Lint

[warning] Code formatting does not meet Prettier standards. Run Prettier with --write to fix.


44-54: New interface properties align with usage.
The additions to AutomapOptions match the code in automap.service.ts. This satisfies the new feature requirements.

🧰 Tools
🪛 GitHub Actions: Lint

[warning] Code formatting does not meet Prettier standards. Run Prettier with --write to fix.


57-86: Defaulting strategy is well implemented.
Applying defaults and ensuring {{fileName}} is included in each pattern is correct. Consider also verifying {{destinationSheetName}} presence if it's required.

🧰 Tools
🪛 GitHub Actions: Lint

[warning] Code formatting does not meet Prettier standards. Run Prettier with --write to fix.

.changeset/fair-cobras-flow.md (1)

1-8: Minor style note regarding hyphen usage.
Static analysis flags “only-source” and “only-target” for hyphenation, but these are valid identifiers in this context. It’s safe to ignore the “HYPHENATED_LY_ADVERB_ADJECTIVE” suggestion since these are literal config values.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~6-~6: Although a hyphen is possible, it is not necessary in a compound modifier in which the first word is an adverb that ends in ‘ly’.
Context: ...re is no unmatched columns (none, both, only-source, only-target) Add options to change fil...

(HYPHENATED_LY_ADVERB_ADJECTIVE)


[uncategorized] ~6-~6: Although a hyphen is possible, it is not necessary in a compound modifier in which the first word is an adverb that ends in ‘ly’.
Context: ...tched columns (none, both, only-source, only-target) Add options to change file name in suc...

(HYPHENATED_LY_ADVERB_ADJECTIVE)

Comment on lines 472 to 508
private async updateFileName(
stage: 'manual' | 'check' | 'start' | 'success' | 'failure',
fileId: string,
fileName: string
destinationSheetName?: string
): Promise<Flatfile.FileResponse> {
return api.files.update(fileId, { name: fileName })

const file = await api.files.get(fileId)
const currentFileName = file.data.name
let newFileName = ''
if(this.options.disableFileNameUpdate) {
return
}

if(stage === 'check') {
newFileName = this.resolveVariablesInFileName(this.options.filenameOnCheck, {fileName: currentFileName})
return api.files.update(fileId, { name: newFileName })
}

if(stage === 'start') {
const oldFileName = this.getFileNameFromOldFileName(this.options.filenameOnCheck, currentFileName)
newFileName = this.resolveVariablesInFileName(this.options.filenameOnStart, {fileName: oldFileName, destinationSheetName: destinationSheetName})
return api.files.update(fileId, { name: newFileName })
}

if(stage === 'success' && !this.options.disableFileNameUpdateOnSuccess) {
const oldFileName = this.getFileNameFromOldFileName(this.options.filenameOnStart, currentFileName)
newFileName = this.resolveVariablesInFileName(this.options.filenameOnSuccess, {fileName: oldFileName, destinationSheetName: destinationSheetName})
return api.files.update(fileId, { name: newFileName })
}

if(stage === 'failure' && !this.options.disableFileNameUpdateOnFailure) {
const oldFileName = this.getFileNameFromOldFileName(this.options.filenameOnStart, currentFileName)
newFileName = this.resolveVariablesInFileName(this.options.filenameOnFailure, {fileName: oldFileName, destinationSheetName: destinationSheetName})
return api.files.update(fileId, { name: newFileName })
}

return
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Return type mismatch could cause confusion.
This method defines a return type of Promise<Flatfile.FileResponse>, but there's a path that returns undefined. Consider widening the return type or always returning a FileResponse.

-): Promise<Flatfile.FileResponse> {
+): Promise<Flatfile.FileResponse | void> {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private async updateFileName(
stage: 'manual' | 'check' | 'start' | 'success' | 'failure',
fileId: string,
fileName: string
destinationSheetName?: string
): Promise<Flatfile.FileResponse> {
return api.files.update(fileId, { name: fileName })
const file = await api.files.get(fileId)
const currentFileName = file.data.name
let newFileName = ''
if(this.options.disableFileNameUpdate) {
return
}
if(stage === 'check') {
newFileName = this.resolveVariablesInFileName(this.options.filenameOnCheck, {fileName: currentFileName})
return api.files.update(fileId, { name: newFileName })
}
if(stage === 'start') {
const oldFileName = this.getFileNameFromOldFileName(this.options.filenameOnCheck, currentFileName)
newFileName = this.resolveVariablesInFileName(this.options.filenameOnStart, {fileName: oldFileName, destinationSheetName: destinationSheetName})
return api.files.update(fileId, { name: newFileName })
}
if(stage === 'success' && !this.options.disableFileNameUpdateOnSuccess) {
const oldFileName = this.getFileNameFromOldFileName(this.options.filenameOnStart, currentFileName)
newFileName = this.resolveVariablesInFileName(this.options.filenameOnSuccess, {fileName: oldFileName, destinationSheetName: destinationSheetName})
return api.files.update(fileId, { name: newFileName })
}
if(stage === 'failure' && !this.options.disableFileNameUpdateOnFailure) {
const oldFileName = this.getFileNameFromOldFileName(this.options.filenameOnStart, currentFileName)
newFileName = this.resolveVariablesInFileName(this.options.filenameOnFailure, {fileName: oldFileName, destinationSheetName: destinationSheetName})
return api.files.update(fileId, { name: newFileName })
}
return
private async updateFileName(
stage: 'manual' | 'check' | 'start' | 'success' | 'failure',
fileId: string,
destinationSheetName?: string
): Promise<Flatfile.FileResponse | void> {
const file = await api.files.get(fileId)
const currentFileName = file.data.name
let newFileName = ''
if(this.options.disableFileNameUpdate) {
return
}
if(stage === 'check') {
newFileName = this.resolveVariablesInFileName(this.options.filenameOnCheck, {fileName: currentFileName})
return api.files.update(fileId, { name: newFileName })
}
if(stage === 'start') {
const oldFileName = this.getFileNameFromOldFileName(this.options.filenameOnCheck, currentFileName)
newFileName = this.resolveVariablesInFileName(this.options.filenameOnStart, {fileName: oldFileName, destinationSheetName: destinationSheetName})
return api.files.update(fileId, { name: newFileName })
}
if(stage === 'success' && !this.options.disableFileNameUpdateOnSuccess) {
const oldFileName = this.getFileNameFromOldFileName(this.options.filenameOnStart, currentFileName)
newFileName = this.resolveVariablesInFileName(this.options.filenameOnSuccess, {fileName: oldFileName, destinationSheetName: destinationSheetName})
return api.files.update(fileId, { name: newFileName })
}
if(stage === 'failure' && !this.options.disableFileNameUpdateOnFailure) {
const oldFileName = this.getFileNameFromOldFileName(this.options.filenameOnStart, currentFileName)
newFileName = this.resolveVariablesInFileName(this.options.filenameOnFailure, {fileName: oldFileName, destinationSheetName: destinationSheetName})
return api.files.update(fileId, { name: newFileName })
}
return
🧰 Tools
🪛 GitHub Actions: Lint

[warning] Code formatting does not meet Prettier standards. Run Prettier with --write to fix.

)

// Create a safe regex pattern that matches the exact structure
const safeRegex = new RegExp(`^${beforeRegex}(.*?)${afterRegex}$`)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nullify Code Language: TypeScript 🔵 MEDIUM Severity CWE-185

Javascript dos rule non literal regexp

The RegExp constructor was called with a non-literal value. If an adversary were able to
supply a malicious regex, they could cause a Regular Expression Denial of Service (ReDoS)
against the application. In Node applications, this could cause the entire application to no
longer be responsive to other users' requests.

To remediate this issue, never allow user-supplied regular expressions. Instead, the regular
expression should be hardcoded. If this is not possible, consider using an alternative regular
expression engine such as node-re2. RE2 is a safe alternative
that does not support backtracking, which is what leads to ReDoS.

Example using re2 which does not support backtracking (Note: it is still recommended to
never use user-supplied input):

// Import the re2 module
const RE2 = require('re2');

function match(userSuppliedRegex, userInput) {
    // Create a RE2 object with the user supplied regex, this is relatively safe
    // due to RE2 not supporting backtracking which can be abused to cause long running
    // queries
    var re = new RE2(userSuppliedRegex);
    // Execute the regular expression against some userInput
    var result = re.exec(userInput);
    // Work with the result
}

For more information on Regular Expression DoS see:

Reply with /nullify to interact with me like another developer
(you will need to refresh the page for updates)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (7)
plugins/automap/src/automap.plugin.ts (3)

10-11: Consider using type assertion for defaulted options.

The defaultOptions function returns a complete AutomapOptions object, but TypeScript doesn't track this. Consider using type assertion to maintain type safety:

-  const optionsDefaulted = defaultOptions(options)
+  const optionsDefaulted = defaultOptions(options) as Required<AutomapOptions>

44-59: Consider grouping related options using nested interfaces.

The interface has grown with many related properties. Consider organizing them into nested interfaces for better maintainability:

+interface FileNameOptions {
+  readonly disableFileNameUpdate?: boolean
+  readonly disableFileNameUpdateOnSuccess?: boolean
+  readonly disableFileNameUpdateOnFailure?: boolean
+  readonly filenameOnCheck?: string
+  readonly filenameOnStart?: string
+  readonly filenameOnSuccess?: string
+  readonly filenameOnFailure?: string
+}

 export interface AutomapOptions {
   readonly accuracy: 'confident' | 'exact'
   readonly debug?: boolean
   readonly defaultTargetSheet?:
     | string
     | ((fileName?: string, event?: FlatfileEvent) => string | Promise<string>)
   readonly matchFilename?: RegExp
   readonly allColumnsMustBeMapped?:
     | 'none'
     | 'both'
     | 'only-source'
     | 'only-target'
   readonly onSuccess?: (event: FlatfileEvent) => void
   readonly onFailure?: (event: FlatfileEvent) => void
   readonly targetWorkbook?: string
-  readonly disableFileNameUpdate?: boolean
-  readonly disableFileNameUpdateOnSuccess?: boolean
-  readonly disableFileNameUpdateOnFailure?: boolean
-  readonly filenameOnCheck?: string
-  readonly filenameOnStart?: string
-  readonly filenameOnSuccess?: string
-  readonly filenameOnFailure?: string
+  readonly fileNameOptions?: FileNameOptions
 }

77-95: Reduce code duplication in filename pattern handling.

The code for checking and appending {{fileName}} is repeated four times. Consider extracting this into a helper function:

+  private ensureFileNameVariable(pattern: string): string {
+    return pattern.includes('{{fileName}}') ? pattern : `${pattern} {{fileName}}`
+  }

   if (!defaultedOptions.filenameOnCheck.includes('{{fileName}}')) {
-    defaultedOptions.filenameOnCheck =
-      defaultedOptions.filenameOnCheck + ' {{fileName}}'
+    defaultedOptions.filenameOnCheck = ensureFileNameVariable(defaultedOptions.filenameOnCheck)
   }
   // Apply similar changes to other filename patterns
plugins/automap/src/automap.service.ts (4)

46-47: Add error handling for file name updates.

The file name updates could fail but errors are not handled. Consider wrapping these in try-catch blocks:

   } else {
-    await this.updateFileName('check', file.id)
+    try {
+      await this.updateFileName('check', file.id)
+    } catch (error) {
+      logWarn('@flatfile/plugin-automap', `Failed to update file name: ${error}`)
+    }
   }

   // Similar changes for the other updateFileName call

Also applies to: 132-133


398-425: Simplify column mapping verification logic.

The current implementation can be simplified using early returns and object mapping:

   private verifyMappedColumns(plan: Flatfile.JobExecutionPlan): boolean {
-    let mappedColumnsVerified = false
-
-    if (this.options.allColumnsMustBeMapped === 'none') {
-      mappedColumnsVerified = true
-    }
-    if (
-      this.options.allColumnsMustBeMapped === 'both' &&
-      plan.unmappedDestinationFields?.length === 0 &&
-      plan.unmappedSourceFields?.length === 0
-    ) {
-      mappedColumnsVerified = true
-    }
-    if (
-      this.options.allColumnsMustBeMapped === 'only-source' &&
-      plan.unmappedSourceFields?.length === 0
-    ) {
-      mappedColumnsVerified = true
-    }
-    if (
-      this.options.allColumnsMustBeMapped === 'only-target' &&
-      plan.unmappedDestinationFields?.length === 0
-    ) {
-      mappedColumnsVerified = true
-    }
-
-    return mappedColumnsVerified
+    const verificationMap = {
+      'none': () => true,
+      'both': () => 
+        plan.unmappedDestinationFields?.length === 0 &&
+        plan.unmappedSourceFields?.length === 0,
+      'only-source': () => 
+        plan.unmappedSourceFields?.length === 0,
+      'only-target': () => 
+        plan.unmappedDestinationFields?.length === 0
+    }
+    
+    return verificationMap[this.options.allColumnsMustBeMapped]?.() ?? false
   }

449-454: Improve return type clarity.

The method's return type is confusing as flagged by static analysis. Consider using undefined instead of void:

   private async updateFileName(
     stage: 'manual' | 'check' | 'start' | 'success' | 'failure',
     fileId: string,
     destinationSheetName?: string
-  ): Promise<Flatfile.FileResponse | void> {
+  ): Promise<Flatfile.FileResponse | undefined> {
🧰 Tools
🪛 Biome (1.9.4)

[error] 453-453: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)


512-526: Add input validation for file name variables.

The method should validate inputs to prevent potential issues:

   private resolveVariablesInFileName(
     fileName: string,
     variables: { destinationSheetName?: string; fileName?: string }
   ): string {
+    if (!fileName) {
+      throw new Error('fileName is required')
+    }
     // Rest of the code...
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0e52746 and be6c718.

📒 Files selected for processing (2)
  • plugins/automap/src/automap.plugin.ts (3 hunks)
  • plugins/automap/src/automap.service.ts (7 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
plugins/automap/src/automap.service.ts

[error] 453-453: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Setup
  • GitHub Check: Nullify Dependencies

Comment on lines +528 to +576
private async getFileNameFromOldFileName(
pattern: string,
filename: string
): Promise<string> {
try {
// Find the position of {{fileName}} in the pattern
const fileNameMatch = pattern.match(/{{fileName}}/)
if (!fileNameMatch) {
return filename
}

// Get the text before and after {{fileName}}
const beforePattern = pattern.substring(0, fileNameMatch.index)
const afterPattern = pattern.substring(
fileNameMatch.index + '{{fileName}}'.length
)

// Escape special characters in the before/after patterns
const beforeRegex = this.escapeRegExp(beforePattern)
const afterRegex = this.escapeRegExp(afterPattern).replace(
this.escapeRegExp('{{destinationSheetName}}'),
'.*?'
)

// Create a safe regex pattern that matches the exact structure
const safeRegex = new RegExp(`^${beforeRegex}(.*?)${afterRegex}$`)

// Add timeout protection
const MAX_EXECUTION_TIME = 100
const timeoutPromise = new Promise<string>((_, reject) => {
setTimeout(() => reject(new Error('Regex timeout')), MAX_EXECUTION_TIME)
})

const matchPromise = new Promise<string>((resolve) => {
const match = filename.match(safeRegex)
if (match?.[1]) {
resolve(match[1].trim())
} else {
resolve(filename)
}
})

return Promise.race([matchPromise, timeoutPromise])
.then((result) => result)
.catch(() => filename)
} catch (error) {
return filename
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Address potential ReDoS vulnerability.

The method constructs a regex from user input which could lead to ReDoS attacks. Consider adding input validation and using a safe regex library:

+  private validatePattern(pattern: string): boolean {
+    return pattern.length < 1000 && !/[^\w\s{{}}]/.test(pattern)
+  }

   private async getFileNameFromOldFileName(
     pattern: string,
     filename: string
   ): Promise<string> {
     try {
+      if (!this.validatePattern(pattern)) {
+        return filename
+      }
       // Rest of the code...
     }
   }

Also consider using a safe regex library like RE2 as suggested by the static analysis tool.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private async getFileNameFromOldFileName(
pattern: string,
filename: string
): Promise<string> {
try {
// Find the position of {{fileName}} in the pattern
const fileNameMatch = pattern.match(/{{fileName}}/)
if (!fileNameMatch) {
return filename
}
// Get the text before and after {{fileName}}
const beforePattern = pattern.substring(0, fileNameMatch.index)
const afterPattern = pattern.substring(
fileNameMatch.index + '{{fileName}}'.length
)
// Escape special characters in the before/after patterns
const beforeRegex = this.escapeRegExp(beforePattern)
const afterRegex = this.escapeRegExp(afterPattern).replace(
this.escapeRegExp('{{destinationSheetName}}'),
'.*?'
)
// Create a safe regex pattern that matches the exact structure
const safeRegex = new RegExp(`^${beforeRegex}(.*?)${afterRegex}$`)
// Add timeout protection
const MAX_EXECUTION_TIME = 100
const timeoutPromise = new Promise<string>((_, reject) => {
setTimeout(() => reject(new Error('Regex timeout')), MAX_EXECUTION_TIME)
})
const matchPromise = new Promise<string>((resolve) => {
const match = filename.match(safeRegex)
if (match?.[1]) {
resolve(match[1].trim())
} else {
resolve(filename)
}
})
return Promise.race([matchPromise, timeoutPromise])
.then((result) => result)
.catch(() => filename)
} catch (error) {
return filename
}
}
private validatePattern(pattern: string): boolean {
return pattern.length < 1000 && !/[^\w\s{{}}]/.test(pattern)
}
private async getFileNameFromOldFileName(
pattern: string,
filename: string
): Promise<string> {
try {
if (!this.validatePattern(pattern)) {
return filename
}
// Find the position of {{fileName}} in the pattern
const fileNameMatch = pattern.match(/{{fileName}}/)
if (!fileNameMatch) {
return filename
}
// Get the text before and after {{fileName}}
const beforePattern = pattern.substring(0, fileNameMatch.index)
const afterPattern = pattern.substring(
fileNameMatch.index + '{{fileName}}'.length
)
// Escape special characters in the before/after patterns
const beforeRegex = this.escapeRegExp(beforePattern)
const afterRegex = this.escapeRegExp(afterPattern).replace(
this.escapeRegExp('{{destinationSheetName}}'),
'.*?'
)
// Create a safe regex pattern that matches the exact structure
const safeRegex = new RegExp(`^${beforeRegex}(.*?)${afterRegex}$`)
// Add timeout protection
const MAX_EXECUTION_TIME = 100
const timeoutPromise = new Promise<string>((_, reject) => {
setTimeout(() => reject(new Error('Regex timeout')), MAX_EXECUTION_TIME)
})
const matchPromise = new Promise<string>((resolve) => {
const match = filename.match(safeRegex)
if (match?.[1]) {
resolve(match[1].trim())
} else {
resolve(filename)
}
})
return Promise.race([matchPromise, timeoutPromise])
.then((result) => result)
.catch(() => filename)
} catch (error) {
return filename
}
}

Copy link
Contributor

@carlbrugger carlbrugger left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good work 👍🏼 Let make it a major release.

@@ -0,0 +1,8 @@
---
'@flatfile/plugin-automap': minor
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let change this to a major

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants