sveltejs / kit

web development, streamlined
https://kit.svelte.dev
MIT License
17.81k stars 1.78k forks source link

Volatile paths in generated `tsconfig.json` in monorepo #12140

Open echocrow opened 3 weeks ago

echocrow commented 3 weeks ago

Describe the bug

Running Vite-related tools (e.g. Vitest) in a monorepo may mess up SvelteKit's generated.svelte-kit/tsconfig.json.

Looks like the Vite plugin currently uses process.cwd() in async functions. However, due to a race condition, it's not guaranteed that process.cwd() still points to SvelteKit's package dir by the time the configureServer Vite plugin hook is invoked.

More context from a previous discovery is available in this issue.

Reproduction

https://stackblitz.com/edit/sveltekit-vitest-tsconfig-hijack?file=README.md

Running e.g. vitest or vite build from within packages/my-app will generate .svelte-kit/tsconfig.json as expected.

However, running vitest from the root monorepo dir can cause .svelte-kit/tsconfig.json to be generated with unexpected relative paths pointing to other packages. If SvelteKit dev is running at the same time, that'll also bust the dev preview.

Notable repro logs:

When running e.g. vitest, you'll see the Vite plugin log different values for process.cmd() vs config.root:

[cwd-vs-config-root] process.cwd: /home/projects/sveltekit-vitest-tsconfig-hijack/packages/z-another-app
[cwd-vs-config-root] config.root: /home/projects/sveltekit-vitest-tsconfig-hijack/packages/my-app

Afterwards, .sveltekit/tsconfig.json is still expected to contain:

{
  "compilerOptions": {
    "paths": {
      "$myAlias": ["../src/myAlias"],
      "$myAlias/*": ["../src/myAlias/*"],
      // ...
    },
    "rootDirs": ["..", "./types"],
    // ...
  }
}

However, the actual contents are:

{
  "compilerOptions": {
    "paths": {
      "$myAlias": ["../../z-another-app/src/myAlias"],
      "$myAlias/*": ["../../z-another-app/src/myAlias/*"],
      // ...
    },
    "rootDirs": ["../../z-another-app", "./types"],
    // ...
  }
}

(This is just a stub; other paths in "include" and "exclude" are also affected.)

System Info

(should be irrelevant - below from the Stackblitz repro)

  System:
    OS: Linux 5.0 undefined
    CPU: (6) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 18.18.0 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 10.2.3 - /usr/local/bin/npm
    pnpm: 8.15.3 - /usr/local/bin/pnpm

Severity

serious, but I can work around it

Current workarounds:

Additional Information

A Vitest contributor suggested to use vite_config.root instead of process.cmd()

The Vite config root is available e.g. via server.config.root in the configureServer Vite plugin hook, which could then be passed down as an argument (or some kind of context object).