Regex declaration scanner misses `var` declarations after `for (const [a, b] of …)`
## Description
`excludeRE[3]` (`/\b(?:const|let|var)\s+?(\[.*?\]|\{.*?\}|.+?)\s*?[=;\n]/gs`) fails to recognise local `var` declarations when they appear after a `for (const [a, b] of …)` destructuring loop under specific code shapes. This causes `injectImports` to inject a duplicate import, which then breaks bundlers with:
```
Error: The symbol "getCookieLocale" has already been declared
```
## Root cause
For `const [index, browserCode]`, the `\[.*?\]` branch matches the opening `[`. It then needs `]\s*?[=;\n]` to close, but the next token after `]` is ` of `, which doesn't satisfy `[=;\n]`. Because the `s` (dotall) flag is set, `.*?` extends across newlines looking for any `]` followed by `=`, `;`, or `\n`.
If every intermediate `]` is followed by `.` (e.g. `.split("-")[0].toLowerCase()`) and a matching `]\n` only appears **after** the `var getCookieLocale` declaration (e.g. `meta: []`), the single regex match swallows the declaration. `getCookieLocale` is never added to the exclude set, unimport treats it as an unresolved identifier, and injects `import { getCookieLocale } from '…'`.
### 4 required ingredients
1. `for (const [a, b] of …)` triggers the `\[.*?\]` branch
2. Between the destructuring `]` and the var declaration, every `]` is followed by `.` (not `=`, `;`, or `\n`), so the regex cannot close the bracket match
3. A `]` followed by `\n` **after** the var declaration (like `meta: []`) gives the regex a valid but pathologically long match that swallows the declaration
4. A call-site usage of the identifier (e.g. `getCookieLocale(…)`) so that `matchRE` registers it as a candidate for auto-import injection
## Reproduction
https://stackblitz.com/edit/stackblitz-starters-wbvlnckm?file=package.json
`npm run dev`
## Real-world trigger
https://github.com/nuxt-modules/og-image/actions/runs/24226647536/job/70729058061
```ts
FAIL e2e test/e2e/i18n.test.ts [ test/e2e/i18n.test.ts ]
Error: Transform failed with 2 errors:
/home/runner/work/og-image/og-image/test/fixtures/i18n/.nuxt/test/c2hdp4/dist/server/_nuxt/composables-n0lOCdiC.js:555:4: ERROR: The symbol "getCookieLocale" has already been declared
/home/runner/work/og-image/og-image/test/fixtures/i18n/.nuxt/test/c2hdp4/dist/server/_nuxt/composables-n0lOCdiC.js:557:4: ERROR: The symbol "getHeaderLocale" has already been declared
❯ failureErrorWithLog node_modules/.pnpm/esbuild@0.27.7/node_modules/esbuild/lib/main.js:1748:15
❯ node_modules/.pnpm/esbuild@0.27.7/node_modules/esbuild/lib/main.js:1017:50
❯ responseCallbacks.<computed> node_modules/.pnpm/esbuild@0.27.7/node_modules/esbuild/lib/main.js:884:9
❯ handleIncomingPacket node_modules/.pnpm/esbuild@0.27.7/node_modules/esbuild/lib/main.js:939:12
❯ Socket.readFromStdout node_modules/.pnpm/esbuild@0.27.7/node_modules/esbuild/lib/main.js:862:7
```
关闭于 2026-04-13 1 条评论