File tree Expand file tree Collapse file tree 2 files changed +48
-1
lines changed
Expand file tree Collapse file tree 2 files changed +48
-1
lines changed Original file line number Diff line number Diff line change 11import { existsSync } from "node:fs" ;
2- import { join } from "node:path" ;
2+ import { dirname , join } from "node:path" ;
33import { fileURLToPath , pathToFileURL } from "node:url" ;
44
55declare const __dirname : string | undefined ;
@@ -36,10 +36,41 @@ const moduleUrl = (() => {
3636 return deriveModuleUrl ( meta , resolvedFilename ) ;
3737} ) ( ) ;
3838
39+ function findPackageRootFrom ( startDir : string ) : string | null {
40+ let current = startDir ;
41+
42+ while ( true ) {
43+ const packageJsonPath = join ( current , "package.json" ) ;
44+ if ( existsSync ( packageJsonPath ) ) {
45+ return current ;
46+ }
47+
48+ const parent = dirname ( current ) ;
49+ if ( parent === current ) {
50+ return null ;
51+ }
52+
53+ current = parent ;
54+ }
55+ }
56+
3957function resolvePackageRoot (
4058 moduleHref : string | undefined ,
4159 dirname : string | undefined ,
4260) : string {
61+ const normalizedDir =
62+ dirname ??
63+ ( moduleHref != null
64+ ? fileURLToPath ( new URL ( "." , moduleHref ) )
65+ : undefined ) ;
66+
67+ if ( normalizedDir ) {
68+ const detectedRoot = findPackageRootFrom ( normalizedDir ) ;
69+ if ( detectedRoot ) {
70+ return detectedRoot ;
71+ }
72+ }
73+
4374 if ( dirname ) {
4475 return join ( dirname , ".." , ".." , ".." ) ;
4576 }
Original file line number Diff line number Diff line change @@ -105,4 +105,20 @@ describe("resolve-binary", () => {
105105 const derivedFromCwd = resolvePackageRoot ( undefined , undefined ) ;
106106 expect ( derivedFromCwd ) . toBe ( process . cwd ( ) ) ;
107107 } ) ;
108+
109+ it ( "detects package root when compiled assets live directly inside dist" , async ( ) => {
110+ const projectRoot = join ( sharedTempDir , "pkg-flat" ) ;
111+ const distDir = join ( projectRoot , "dist" ) ;
112+
113+ await mkdir ( distDir , { recursive : true } ) ;
114+ await writeFile ( join ( projectRoot , "package.json" ) , "{}" ) ;
115+
116+ const { resolvePackageRoot } = await importResolver ( ) ;
117+ const derived = resolvePackageRoot (
118+ pathToFileURL ( join ( distDir , "index.cjs" ) ) . href ,
119+ distDir ,
120+ ) ;
121+
122+ expect ( derived ) . toBe ( projectRoot ) ;
123+ } ) ;
108124} ) ;
You can’t perform that action at this time.
0 commit comments