11import path from 'path' ;
2-
2+ import json5 from 'json5' ;
3+ import fs from 'node:fs' ;
34import findUp from 'find-up' ;
45
56export interface PackageInfo {
@@ -8,7 +9,7 @@ export interface PackageInfo {
89 dirname : string ;
910}
1011
11- function getClosestPackageInfo ( directory : string ) {
12+ function getClosestPackageInfo ( directory : string ) : PackageInfo | undefined {
1213 const packageJsonPath = findUp . sync ( 'package.json' , {
1314 cwd : directory ,
1415 } ) ;
@@ -24,6 +25,38 @@ function getClosestPackageInfo(directory: string) {
2425 }
2526}
2627
28+ function getClosestDenoJson ( directory : string ) : PackageInfo | undefined {
29+ const denoJsonPath = findUp . sync ( 'deno.json' , {
30+ cwd : directory ,
31+ } ) ;
32+
33+ if ( denoJsonPath ) {
34+ const { name } = require ( denoJsonPath ) ;
35+
36+ return {
37+ name,
38+ path : denoJsonPath ,
39+ dirname : path . dirname ( denoJsonPath ) ,
40+ } ;
41+ }
42+
43+ // Deno also supports `deno.jsonc`
44+ const denoJsoncPath = findUp . sync ( 'deno.jsonc' , {
45+ cwd : directory ,
46+ } ) ;
47+
48+ if ( denoJsoncPath ) {
49+ const { name } = json5 . parse ( fs . readFileSync ( denoJsoncPath , 'utf-8' ) ) ;
50+
51+ return {
52+ name,
53+ path : denoJsoncPath ,
54+ dirname : path . dirname ( denoJsoncPath ) ,
55+ } ;
56+ }
57+ }
58+
59+ const isDeno = typeof process . versions . deno === 'string' ;
2760const packageInfoCache = new Map < string , PackageInfo > ( ) ;
2861
2962export function getPackageInfo ( cwd ?: string | null ) : PackageInfo {
@@ -34,15 +67,34 @@ export function getPackageInfo(cwd?: string | null): PackageInfo {
3467 return cachedValue ;
3568 }
3669
37- let packageInfo = getClosestPackageInfo ( resolvedCwd ) ;
70+ let packageInfo : PackageInfo | undefined ;
3871
39- while ( packageInfo && ! packageInfo . name ) {
40- packageInfo = getClosestPackageInfo (
41- path . resolve ( packageInfo . dirname , '..' ) ,
42- ) ;
72+ // Deno projects don't necessarily have a package.json
73+ if ( isDeno ) {
74+ packageInfo = getClosestDenoJson ( resolvedCwd ) ;
75+
76+ // No need to look further as nested deno.json files is not supported
77+ // in Deno without being a workspace member. If they are a workspace
78+ // member, they are expected to have the `name` field anyway.
79+ }
80+
81+ if ( ! packageInfo ) {
82+ packageInfo = getClosestPackageInfo ( resolvedCwd ) ;
83+
84+ while ( packageInfo && ! packageInfo . name ) {
85+ packageInfo = getClosestPackageInfo (
86+ path . resolve ( packageInfo . dirname , '..' ) ,
87+ ) ;
88+ }
4389 }
4490
4591 if ( ! packageInfo || ! packageInfo . name ) {
92+ if ( isDeno ) {
93+ throw new Error (
94+ `Couldn't find parent deno.json, deno.jsonc or package.json with a name field from '${ resolvedCwd } '` ,
95+ ) ;
96+ }
97+
4698 throw new Error (
4799 `Couldn't find parent package.json with a name field from '${ resolvedCwd } '` ,
48100 ) ;
0 commit comments