Fix the new dependency check for pasted snippets

Review the AI's codeEasy12 min

Your task

An AI gave you a working TypeScript snippet that imports axios, though your codebase uses the built-in fetch. Pasting it in adds a package to package.json that nobody chose. Your team's check lists every package a snippet would add that is not already approved.

An assistant wrote flag_new_dependencies(snippet_imports, approved_packages). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • snippet_imports: the import paths in the snippet, such as axios, lodash/merge, ./utils/http or node:fs.
  • approved_packages: the package names your team has approved.
  • Return the package names to flag, each once, sorted.

Rules the tests check:

  • Ignore an empty import, and any import that starts with ./, ../ or node:. Those are your own files and Node built-ins.
  • Find the package name of each other import:
    • If it starts with @, it is a scoped package: the name is everything before the second /, or the whole import if it has fewer than 2 /.
    • Otherwise the name is everything before the first /, or the whole import if it has no /.
  • Ignore an import whose package name is empty.
  • Flag a package name unless approved_packages contains exactly that name.
  • Return each flagged name once, sorted as plain strings in ascending order.

Examples

flag_new_dependencies(snippet_imports: list[str], approved_packages: list[str]) -> list[str]
Example 1
Inputflag_new_dependencies(["axios", "./utils/http", "node:fs"], ["react", "zod"])
Output["axios"]
Example 2
Inputflag_new_dependencies(["react", "react-dom/client"], ["react", "react-dom"])
Output[]