UNPKG

@sveltejs/kit

Version:

SvelteKit is the fastest way to build Svelte apps

61 lines (50 loc) • 1.83 kB
import fs from 'node:fs'; import path from 'node:path'; import { pathToFileURL } from 'node:url'; /** * Resolves a peer dependency relative to the current working directory. * * Mainly used to resolve the correct Vite package when an app's SvelteKit is a * linked local repository. * * Duplicated with `packages/adapter-auto` * @param {string} dependency * @param {string} root */ function resolve_peer(dependency, root) { let [name, ...parts] = dependency.split('/'); if (name[0] === '@') name += `/${parts.shift()}`; let dir = root; while (!fs.existsSync(`${dir}/node_modules/${name}/package.json`)) { if (dir === (dir = path.dirname(dir))) { throw new Error( `Could not resolve peer dependency "${name}" relative to your project — please install it and try again.` ); } } const pkg_dir = `${dir}/node_modules/${name}`; const pkg = JSON.parse(fs.readFileSync(`${pkg_dir}/package.json`, 'utf-8')); const subpackage = ['.', ...parts].join('/'); let exported = pkg.exports[subpackage]; while (typeof exported !== 'string') { if (!exported) { throw new Error(`Could not find valid "${subpackage}" export in ${name}/package.json`); } exported = exported['import'] ?? exported['default']; } return path.resolve(pkg_dir, exported); } /** * Resolve a dependency relative to the current working directory, * rather than relative to this package (but falls back to trying that, if necessary) * @param {string} dependency * @param {string} root */ export async function import_peer(dependency, root) { try { return await import(/* @vite-ignore */ pathToFileURL(resolve_peer(dependency, root)).href); } catch { // eslint-disable-next-line kit-node-custom/require-path-to-file-url -- bare package specifier, not a path return await import(/* @vite-ignore */ dependency); } }