@exodus/stasis-core 1.0.0-beta.1 → 1.0.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/brotli.js CHANGED
@@ -1,21 +1,20 @@
1
1
  import { constants as zlibConstants } from 'node:zlib'
2
2
 
3
- import { assert } from './util.js'
3
+ import { assert, isBrotliQuality, parseBrotliQuality } from './util.js'
4
4
 
5
- // Brotli's default quality is 11 (max) and the encoder is superlinear in input
6
- // size, so on a multi-MB source bundle it dominates write time. Tests that
7
- // bundle real-world dependency trees can override this via the env var to keep
8
- // runs fast; the output is still a valid .br at any quality. Production code
9
- // pays the default cost in exchange for the best ratio.
10
- //
11
- // Kept out of `util.js` so that importing the generic helpers there (`sortPaths`,
12
- // `assertRealPathWithinBase`, …) doesn't transitively load `node:zlib`. Only the
13
- // code that actually compresses a bundle (`state.js`, `stasis bundle`) reaches
14
- // for this, and that code already imports zlib directly.
15
- export function brotliOptions() {
5
+ // Default brotli quality; 11 (max) costs far more for a marginal gain over 9.
6
+ export const DEFAULT_BROTLI_QUALITY = 9
7
+
8
+ export function brotliOptions(quality) {
9
+ if (quality !== undefined) {
10
+ assert(isBrotliQuality(quality), `brotli quality must be an integer 0..11, got ${quality}`)
11
+ }
16
12
  const raw = process.env.EXODUS_STASIS_BROTLI_QUALITY
17
- if (!raw) return undefined
18
- const n = Number(raw)
19
- assert(Number.isInteger(n) && n >= 0 && n <= 11, `EXODUS_STASIS_BROTLI_QUALITY must be an integer 0..11, got ${raw}`)
20
- return { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: n } }
13
+ if (raw) {
14
+ const n = parseBrotliQuality('EXODUS_STASIS_BROTLI_QUALITY', raw)
15
+ assert(quality === undefined || quality === n,
16
+ `brotli quality ${quality} conflicts with EXODUS_STASIS_BROTLI_QUALITY=${raw}`)
17
+ quality = n
18
+ }
19
+ return { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: quality ?? DEFAULT_BROTLI_QUALITY } }
21
20
  }
@@ -0,0 +1,379 @@
1
+ import { isUtf8 } from 'node:buffer'
2
+ import { dirname, join, posix, relative, resolve } from 'node:path'
3
+
4
+ import { isValidRepoField } from './bundle.js'
5
+ import { isPackageString, isSubpackage, posixPathEscapes } from './artifact-util.js'
6
+ import { diskHost } from './host.js'
7
+ import { assertRealPathWithinBase, hasNodeModulesSegment, relativeEscapes, splitNodeModulesPath, toPosix } from './util.js'
8
+
9
+ // Text as Node reads a package.json: UTF-8, past a byte order mark.
10
+ const utf8 = new TextDecoder()
11
+ export const packageJSONText = (bytes) => utf8.decode(bytes)
12
+
13
+ export function packageType(file, host = diskHost) {
14
+ const pkg = host.findPackageJSON(file)
15
+ if (!pkg) return null
16
+ try {
17
+ const type = JSON.parse(packageJSONText(host.readFile(pkg))).type
18
+ return type === 'module' || type === 'commonjs' ? type : null
19
+ } catch {
20
+ return null
21
+ }
22
+ }
23
+
24
+ // Directories where a package keeps copies of OTHER packages, each under a package.json of its own,
25
+ // by the host package's name (so any install layout or alias matches), package-relative. A package.json
26
+ // below one is a vendored package's: it names that package, not its host, so a file it covers is its
27
+ // host's (State#locateModule holds it to nothing), listed under that package in the host record's
28
+ // `vendored`. Maintained list: add only a confirmed upstream vendoring layout, with its reason.
29
+ const VENDOR_DIRS = {
30
+ __proto__: null,
31
+ next: ['dist/compiled'], // the dependencies Next.js compiles in, ~140, each with a trimmed package.json
32
+ }
33
+ const VENDOR_DIR_LIST = Object.values(VENDOR_DIRS).flat()
34
+
35
+ // Whether a package-relative path is below any package's vendor dir: no need to read whose it is otherwise.
36
+ const inAnyVendorDir = (rel) => VENDOR_DIR_LIST.some((dir) => rel.startsWith(`${dir}/`))
37
+
38
+ // The vendor dir of the package named `name` that its file `rel` (package-relative, POSIX) is below, or undefined.
39
+ export const vendorDirOf = (name, rel) => VENDOR_DIRS[name]?.find((dir) => rel.startsWith(`${dir}/`))
40
+
41
+ // The package vendored under `vendorDir` (package-relative) that a file `rel` of its host is in: walking
42
+ // up from the file, while below the vendor dir, the first package.json with a `name`, which `read(dir)`
43
+ // gives (null where there is none) -> `vendored` { dir, name, version? }, undefined where none has a name
44
+ // or its name is no package string (a version that is none is left out). `below`: whether any package.json
45
+ // there covers the file at all.
46
+ export function vendoredPackageOf(rel, vendorDir, read) {
47
+ let below = false
48
+ for (let dir = posix.dirname(rel); dir.startsWith(`${vendorDir}/`); dir = posix.dirname(dir)) {
49
+ const pkg = read(dir)
50
+ if (pkg === null) continue
51
+ below = true
52
+ if (pkg?.name === undefined) continue // a `{"type":"module"}` marker inside the vendored package
53
+ if (!isPackageString(pkg.name)) return { below }
54
+ return { below, vendored: { dir, name: pkg.name, ...(isPackageString(pkg.version) ? { version: pkg.version } : {}) } }
55
+ }
56
+ return { below }
57
+ }
58
+
59
+ // The nearest package.json with a `name` above a file `rel` of a package (package-relative, POSIX), below the
60
+ // package's own, walking past `{"type":"module"}` markers, each read by `read(dir)` (null where there is
61
+ // none) -> { dir, pkg }, or undefined where there is none.
62
+ export function namedManifestOf(rel, read) {
63
+ for (let dir = posix.dirname(rel); dir !== '.'; dir = posix.dirname(dir)) {
64
+ const pkg = read(dir)
65
+ if (pkg?.name !== undefined) return { dir, pkg }
66
+ }
67
+ return undefined
68
+ }
69
+
70
+ // Nearest package.json (walking up) that identifies a bucket; pkgDir is relative to baseDir ("."
71
+ // at the root). Inside node_modules both name and version are required; a workspace package
72
+ // outside node_modules may omit version (the name alone claims the bucket, matching
73
+ // State#locateModule), and a node_modules one's `ecosystem` (npm) and `repo`, where its `repository`
74
+ // names a GitHub one (packageRepo). Null if none. A malformed one is walked past, or with `strict` throws
75
+ // (its files would otherwise land in the parent package); `check`, `host`: see readPackageJson.
76
+ // A file in a vendored package (vendorDirOf) is its host's, as State#locateModule has it, with the
77
+ // package as the record's `vendored` would list it, `{ [dir]: { name, version? } }` (vendoredPackageOf);
78
+ // so is one in a subpackage (isSubpackage), its package.json walked past, as `subpackages`.
79
+ export function findPackageMetadata(baseDir, fileRelPath, { strict = false, check, host = diskHost } = {}) {
80
+ const nm = splitNodeModulesPath(toPosix(fileRelPath))
81
+ if (nm !== null && inAnyVendorDir(nm.rel)) {
82
+ const read = (rel) => readPackageJson(baseDir, rel, { strict, check, host })
83
+ const pkg = read(`${nm.dir}/package.json`)
84
+ const vendorDir = pkg?.name && pkg.version ? vendorDirOf(pkg.name, nm.rel) : undefined
85
+ const { below, vendored } = vendorDir === undefined ? {} : vendoredPackageOf(nm.rel, vendorDir, (sub) => read(`${nm.dir}/${sub}/package.json`))
86
+ if (below) {
87
+ const repo = packageRepo(pkg)
88
+ const { dir: sub, ...identity } = vendored ?? {}
89
+ return { pkgDir: nm.dir, name: pkg.name, version: pkg.version, ecosystem: 'npm', ...(repo === undefined ? {} : { repo }), ...(vendored === undefined ? {} : { vendored: { [sub]: identity } }) }
90
+ }
91
+ }
92
+ // The subpackage the file is in, where its nearest package.json with a name (past `{"type":"module"}`
93
+ // markers, as namedManifestOf walks) is one's, as the record's `subpackages` would list it.
94
+ let subpackages
95
+ let nearest = true
96
+ for (let dir = dirname(fileRelPath); ; dir = dirname(dir)) {
97
+ const pkg = readPackageJson(baseDir, toPosix(join(dir, 'package.json')), { strict, check, host })
98
+ const inNodeModules = hasNodeModulesSegment(toPosix(dir))
99
+ const sub = pkg?.name && nm !== null ? hostSubpackageDir(baseDir, nm.dir, toPosix(dir), pkg.name, { strict, check, host }) : undefined
100
+ if (sub !== undefined) {
101
+ if (nearest) subpackages = { [sub]: { name: pkg.name, ...(isPackageString(pkg.version) ? { version: pkg.version } : {}) } }
102
+ nearest = false
103
+ continue
104
+ }
105
+ if (pkg?.name) nearest = false
106
+ if (pkg?.name && (pkg.version || !inNodeModules)) {
107
+ const repo = inNodeModules ? packageRepo(pkg) : undefined
108
+ const own = toPosix(dir) === nm?.dir ? subpackages : undefined // the subpackage's package, not one above it
109
+ // `?? undefined` folds a literal `"version": null` into the one absent-version spelling.
110
+ return { pkgDir: dir, name: pkg.name, version: pkg.version ?? undefined, ...(inNodeModules ? { ecosystem: 'npm' } : {}), ...(repo === undefined ? {} : { repo }), ...(own === undefined ? {} : { subpackages: own }) }
111
+ }
112
+ if (dir === '.' || dir === '/' || dir === '' || dirname(dir) === dir) return null
113
+ }
114
+ }
115
+
116
+ // The directory, package-relative, of the package.json naming `manifestName` at `dir` (project-relative,
117
+ // POSIX) where it is a subpackage (isSubpackage) of the package at `pkgDir`; else undefined. The package's
118
+ // own package.json is read only where the name ends in that directory.
119
+ function hostSubpackageDir(baseDir, pkgDir, dir, manifestName, options) {
120
+ if (!dir.startsWith(`${pkgDir}/`)) return undefined
121
+ const sub = dir.slice(pkgDir.length + 1)
122
+ if (typeof manifestName !== 'string' || !manifestName.endsWith(`/${sub}`)) return undefined
123
+ return isSubpackage(manifestName, readPackageJson(baseDir, `${pkgDir}/package.json`, options)?.name, sub) ? sub : undefined
124
+ }
125
+
126
+ // The error codes that mean nothing is at a path.
127
+ export const NO_ENTRY = new Set(['ENOENT', 'ENOTDIR'])
128
+
129
+ // Why `file` can't be read, where `host.stat` gave null, or null when nothing is there (a missing
130
+ // path, one through a file, a link to nothing). host.stat answers null for any failure, as Node's
131
+ // module lookup does; real stat tells them apart: a link loop, a directory that may not be searched
132
+ // or a name too long is something there that can't be read, and a read meets the same error.
133
+ function readFailure(host, file) {
134
+ try {
135
+ host.readFile(file)
136
+ } catch (err) {
137
+ return NO_ENTRY.has(err.code) ? null : err
138
+ }
139
+ return new Error(`${file} could be read but not stat'ed`)
140
+ }
141
+
142
+ // host.stat as real stat answers: null only when nothing is there (readFailure); anything else that
143
+ // can't be stat'ed throws, naming the file `label`.
144
+ export function statStrict(host, file, label) {
145
+ const stat = host.stat(file)
146
+ if (stat !== null) return stat
147
+ const failure = readFailure(host, file)
148
+ if (failure === null) return null
149
+ throw new Error(`${label}: can't be read (${failure.code ?? failure.message})`, { cause: failure })
150
+ }
151
+
152
+ // host.stat for a package.json, as Node's lookups read one: null when nothing is there, and one that
153
+ // can't be read (a link loop, a directory that may not be searched) throws ERR_INVALID_PACKAGE_CONFIG,
154
+ // as Node refuses it.
155
+ export function packageJSONStat(host, file) {
156
+ const stat = host.stat(file)
157
+ if (stat !== null) return stat
158
+ const cause = readFailure(host, file)
159
+ if (cause === null) return null
160
+ throw Object.assign(new Error(`Cannot read package config ${file}: ${cause.code ?? cause.message}.`, { cause }), { code: 'ERR_INVALID_PACKAGE_CONFIG' })
161
+ }
162
+
163
+ // `file`'s bytes, read through `host`, or null when there's no file (a directory counts as none).
164
+ // It's read only when it's a regular file: a FIFO, a socket, a device or a link to one
165
+ // (`/dev/stdin`) throws, naming it `label`, rather than stalling or reading the process's input, and
166
+ // so does one there that can't be read (statStrict).
167
+ export function readRegularFileOrNull(file, label, host = diskHost) {
168
+ const stat = statStrict(host, file, label)
169
+ if (stat === null || stat.isDirectory()) return null
170
+ if (!stat.isFile()) throw new Error(`${label}: not a regular file`)
171
+ return host.readFile(file)
172
+ }
173
+
174
+ // The package.json at `rel` (under `baseDir`), parsed (a leading byte-order mark skipped, as npm
175
+ // and Node skip it), read through `host`; null when there's none (a directory counts as none), or
176
+ // when it doesn't parse, isn't a regular file or can't be read -- unless `strict`, then that throws
177
+ // (only nothing there is no package.json, as Node reads one: statStrict), saying where
178
+ // with the parser's line and column but never its message, which quotes the text (a file that isn't
179
+ // JSON may be anything, a secret included). `check(rel)`, when given, sees the path before it is
180
+ // read, and may throw to refuse it.
181
+ export function readPackageJson(baseDir, rel, { strict = false, check, host = diskHost } = {}) {
182
+ const file = join(baseDir, rel)
183
+ const stat = strict ? statStrict(host, file, rel) : host.stat(file)
184
+ if (stat === null || stat.isDirectory()) return null
185
+ check?.(rel)
186
+ try {
187
+ // A FIFO, a socket or a device (or a link to one) is never read: it could stall the bundle.
188
+ if (!stat.isFile()) throw new Error(`${rel}: not a regular file`)
189
+ const bytes = host.readFile(file)
190
+ // Strict, it's read as the file's own text or not at all; lenient lookups decode it as they always
191
+ // have (a stray byte as U+FFFD).
192
+ if (strict && !isUtf8(bytes)) throw new Error(`${rel}: not valid UTF-8`)
193
+ return parseJson(packageJSONText(bytes), rel)
194
+ } catch (err) {
195
+ if (strict) throw err
196
+ return null
197
+ }
198
+ }
199
+
200
+ // JSON.parse, throwing where the text breaks (the parser's line and column) but never the parser's
201
+ // message, which quotes the text.
202
+ function parseJson(text, rel) {
203
+ try {
204
+ return JSON.parse(text)
205
+ } catch (err) {
206
+ const at = /\(line \d+ column \d+\)/u.exec(err.message)?.[0]
207
+ // eslint-disable-next-line preserve-caught-error -- the parser's error quotes the file
208
+ throw new Error(`${rel} is not valid JSON${at ? ` ${at}` : ''}`)
209
+ }
210
+ }
211
+
212
+ export function normalizeEntries(entries, cwd) {
213
+ const baseDir = resolve(cwd)
214
+ return entries.map((e) => {
215
+ const rel = toPosix(relative(baseDir, resolve(cwd, e)))
216
+ if (relativeEscapes(rel)) throw new Error(`Entry escapes baseDir: ${e}`)
217
+ return rel.replace(/^\.\//u, '')
218
+ })
219
+ }
220
+
221
+ // Bytes of a bundled module's `package.json`, or null to skip when it's absent; one that can't be
222
+ // read (statStrict) or isn't UTF-8 aborts (never silently skipped).
223
+ export function readModuleManifest({ baseDir, realBase, rel, host = diskHost } = {}) {
224
+ const absolute = join(baseDir, rel)
225
+ if (statStrict(host, absolute, rel) === null) return null
226
+ assertRealPathWithinBase(realBase, baseDir, rel, host)
227
+ const buf = host.readFile(absolute)
228
+ if (!isUtf8(buf)) throw new Error(`package.json is not valid UTF-8: ${rel}`)
229
+ return buf
230
+ }
231
+
232
+ // Never throws: a missing/unreadable/malformed file yields null.
233
+ export function readJson(file, host = diskHost) {
234
+ try {
235
+ return JSON.parse(packageJSONText(host.readFile(file)))
236
+ } catch {
237
+ return null
238
+ }
239
+ }
240
+
241
+ // `owner/name` from a package.json `repository` (GitHub URL or shorthand), else null. A `#committish`
242
+ // npm lets it name is no part of the repo; a URL's userinfo holds only what RFC 3986 allows there, so
243
+ // a `?` or `\` ending the authority early (`https://evil.example?@github.com/a/b`) isn't GitHub's. An
244
+ // scp-like `git@github.com:owner/name` is taken behind an `ssh://` too (`git+ssh://git@github.com:o/n`),
245
+ // as package.json files spell it. The host is GitHub's with a `www.` too, which is stripped.
246
+ export function parseGithubRepository(url) {
247
+ if (typeof url !== 'string') return null
248
+ const match = /^(?:github:|(?:git\+)?(?:(?:https?|ssh|git):\/\/(?:[\w.~%!$&'()*+,;=:-]*@)?(?:www\.)?github\.com(?::\d+)?\/|ssh:\/\/(?:[\w.~%!$&'()*+,;=-]*@)?(?:www\.)?github\.com:|(?:[^@/:]+@)?(?:www\.)?github\.com:))?([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/iu.exec(url.trim().replace(/#.*$/su, ''))
249
+ // Must also pass the bundle format's `github` check.
250
+ const github = match && `${match[1]}/${match[2]}`
251
+ return github && isValidRepoField('github', github) ? github : null
252
+ }
253
+
254
+ // Best-effort `origin` url: literal match of git's own `.git/config` layout, no parsing.
255
+ const GIT_ORIGIN_URL = '[remote "origin"]\n\turl = '
256
+ export function gitOriginUrl(text) {
257
+ const at = text?.indexOf(GIT_ORIGIN_URL) ?? -1
258
+ if (at === -1) return null
259
+ const start = at + GIT_ORIGIN_URL.length
260
+ const end = text.indexOf('\n', start)
261
+ return text.slice(start, end === -1 ? undefined : end).trim() || null
262
+ }
263
+
264
+ // The text of `file`, or null. Read through `host` (never the --fs-patched fs), it is never captured.
265
+ export const readText = (host, file) => {
266
+ try {
267
+ return host.readFile(file).toString('utf8')
268
+ } catch {
269
+ return null
270
+ }
271
+ }
272
+
273
+ // Dir of a `https://github.com/<github>/tree/<branch>/<dir>` homepage (one-segment branch).
274
+ export function githubHomepageDirectory(homepage, github) {
275
+ if (typeof homepage !== 'string') return undefined
276
+ const match = /^https?:\/\/(?:www\.)?github\.com\/([^/]+\/[^/]+)\/tree\/[^/#?]+\/([^#?]+)/iu.exec(homepage.trim())
277
+ if (!match || match[1].toLowerCase() !== github.toLowerCase()) return undefined
278
+ try {
279
+ return decodeURIComponent(match[2])
280
+ } catch {
281
+ return undefined
282
+ }
283
+ }
284
+
285
+ // `{ directory }` where it is a valid one, else `{}`.
286
+ const repoLocation = (directory) => (isValidRepoField('directory', directory) ? { directory } : {})
287
+
288
+ // Whether a declared path is the repository's root: nothing but empty and `.` parts (`./`, `/.`).
289
+ const isRootPath = (path) => path.replaceAll('\\', '/').split('/').every((part) => part === '' || part === '.')
290
+
291
+ // A package.json's declared `base` (its `repository.directory`) joined with `rel` as a `repoLocation`;
292
+ // `{}` where none is declared (unknown, not the root), or where `base` has a `..` part, whatever it
293
+ // would come to (`a/..` is no claim on the root). Its empty and `.` parts are dropped, and one that
294
+ // comes to the root (`''`, `.`, `./`, `/`, `/.`) is the root, `''`. Windows users write `base` with
295
+ // `\`: metadata, not a name on disk, so its `\` is taken for a separator.
296
+ const declaredLocation = (base, rel) => {
297
+ if (typeof base !== 'string') return {}
298
+ const path = base.replaceAll('\\', '/')
299
+ if (path.split('/').includes('..')) return {}
300
+ const directory = posix.join(path, rel).replace(/^\/+|\/+$/gu, '')
301
+ return repoLocation(directory === '.' ? '' : directory)
302
+ }
303
+
304
+ // Git and common dirs, following a worktree/submodule `.git` file.
305
+ function gitDirs(dotGit, host) {
306
+ const pointer = readText(host, dotGit) // null for a `.git` directory (EISDIR)
307
+ const gitDir = pointer?.startsWith('gitdir: ') ? resolve(dirname(dotGit), pointer.slice('gitdir: '.length).trim()) : dotGit
308
+ const common = readText(host, join(gitDir, 'commondir'))?.trim()
309
+ return { gitDir, commonDir: common ? resolve(gitDir, common) : gitDir }
310
+ }
311
+
312
+ // HEAD's commit: detached sha, loose ref, or packed-refs; undefined unless a valid sha.
313
+ function gitHeadCommit({ gitDir, commonDir }, host) {
314
+ const head = readText(host, join(gitDir, 'HEAD'))?.trim()
315
+ if (!head) return undefined
316
+ let commit = head
317
+ if (head.startsWith('ref: ')) {
318
+ const ref = head.slice('ref: '.length)
319
+ if (!ref.startsWith('refs/') || posixPathEscapes(ref)) return undefined
320
+ commit = readText(host, join(commonDir, ref))?.trim() ??
321
+ readText(host, join(commonDir, 'packed-refs'))?.split('\n').find((line) => line.endsWith(` ${ref}`))?.split(' ')[0]
322
+ }
323
+ return isValidRepoField('commit', commit) ? commit : undefined
324
+ }
325
+
326
+ // HEAD's commit of the git checkout at `dir` (gitHeadCommit), its `.git` a directory or the `gitdir:`
327
+ // file of a submodule or worktree; undefined where it holds none. Read through `host`, under `.git`
328
+ // alone; git never runs.
329
+ export function checkoutCommit(dir, host = diskHost) {
330
+ const dotGit = join(dir, '.git')
331
+ return host.stat(dotGit) === null ? undefined : gitHeadCommit(gitDirs(dotGit, host), host)
332
+ }
333
+
334
+ // A parsed package.json's `repository` url (the string shorthand, or its `url`), or undefined.
335
+ function repositoryUrl(json) {
336
+ const repository = json?.repository
337
+ const url = typeof repository === 'string' ? repository : repository?.url
338
+ return typeof url === 'string' ? url : undefined
339
+ }
340
+
341
+ // The `repo` a parsed package.json's `repository` names for `rel`, a directory below it ('' for its
342
+ // own): `github` from its GitHub URL or shorthand, and `directory` from `repository.directory` joined
343
+ // with `rel` (declaredLocation); undefined where it names no GitHub repository.
344
+ export function packageRepo(json, rel = '') {
345
+ const github = parseGithubRepository(repositoryUrl(json))
346
+ if (!github) return undefined
347
+ let base = json.repository.directory
348
+ // Often unset; fall back to a GitHub tree `homepage`, which places a package below the root, never
349
+ // at it: only `repository.directory` declares the root (`/tree/main/.` declares nothing).
350
+ if (typeof base !== 'string') {
351
+ base = githubHomepageDirectory(json.homepage, github)
352
+ if (base !== undefined && isRootPath(base)) base = undefined
353
+ }
354
+ return { github, ...declaredLocation(base, rel) }
355
+ }
356
+
357
+ // Bundle `repo` for `dir`: git origin/HEAD at the work tree root, with `dir`'s place in it (`''` at
358
+ // the root), else nearest package.json `repository` (packageRepo).
359
+ export function detectRepo(dir, host = diskHost) {
360
+ const start = resolve(dir)
361
+ let pkg = null // null: no package.json `repository` seen yet; undefined: one seen, not GitHub
362
+ for (let cursor = start; ; cursor = dirname(cursor)) {
363
+ const rel = toPosix(relative(cursor, start))
364
+ if (pkg === null) {
365
+ const json = readJson(join(cursor, 'package.json'), host)
366
+ if (repositoryUrl(json) !== undefined) pkg = packageRepo(json, rel)
367
+ }
368
+ const dotGit = join(cursor, '.git')
369
+ if (host.stat(dotGit) !== null) {
370
+ const dirs = gitDirs(dotGit, host)
371
+ const github = parseGithubRepository(gitOriginUrl(readText(host, join(dirs.commonDir, 'config'))))
372
+ if (github) return stripUndefined({ github, ...repoLocation(rel), commit: gitHeadCommit(dirs, host) })
373
+ return pkg ?? undefined
374
+ }
375
+ if (dirname(cursor) === cursor) return pkg ?? undefined
376
+ }
377
+ }
378
+
379
+ const stripUndefined = (obj) => Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined))