npm-dependency-visualizer 0.0.0-stage → 0.1.0

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/package.json CHANGED
@@ -1,6 +1,20 @@
1
- {
2
- "name": "npm-dependency-visualizer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "npm-dependency-visualizer",
3
+ "version": "0.1.0",
4
+ "description": "Visualize npm lockfile dependencies as Markdown and Mermaid",
5
+ "type": "module",
6
+ "bin": {
7
+ "npm-dependency-visualizer": "./cli.js"
8
+ },
9
+ "engines": {
10
+ "node": ">=22.12.0"
11
+ },
12
+ "scripts": {
13
+ "test": "node --test"
14
+ },
15
+ "devDependencies": {
16
+ "jsdom": "26.1.0",
17
+ "marked": "16.4.2",
18
+ "mermaid": "12.3.0"
19
+ }
20
+ }
package/src/errors.js ADDED
@@ -0,0 +1,6 @@
1
+ export class InputError extends Error {
2
+ constructor(message) {
3
+ super(message)
4
+ this.name = 'InputError'
5
+ }
6
+ }
package/src/graph.js ADDED
@@ -0,0 +1,409 @@
1
+ import { InputError } from './errors.js'
2
+
3
+ const has = (object, key) => Object.hasOwn(object, key)
4
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0
5
+
6
+ function parentScope(location) {
7
+ const index = location.lastIndexOf('/node_modules/')
8
+ return index < 0 ? '' : location.slice(0, index)
9
+ }
10
+
11
+ function candidate(scope, name) {
12
+ return `${scope ? `${scope}/` : ''}node_modules/${name}`
13
+ }
14
+
15
+ function isProjectLocation(location) {
16
+ return !location.startsWith('node_modules/') && !location.includes('/node_modules/')
17
+ }
18
+
19
+ function normalizeLocation(value) {
20
+ return value.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '')
21
+ }
22
+
23
+ function patternRegExp(pattern) {
24
+ const segments = normalizeLocation(pattern).split('/')
25
+ const source = segments.map((segment, index) => {
26
+ const last = index === segments.length - 1
27
+ if (segment === '**') return last ? '(?:[^/]+/)*[^/]+' : '(?:[^/]+/)*'
28
+ const body = [...segment].map(character =>
29
+ character === '*' ? '[^/]*' : character === '?' ? '[^/]' : character.replace(/[.+^${}()|[\]\\]/g, '\\$&')).join('')
30
+ return last ? body : `${body}/`
31
+ }).join('')
32
+ return new RegExp(`^${source}$`)
33
+ }
34
+
35
+ export function workspacePatterns(manifest, root) {
36
+ for (const source of [manifest, root]) {
37
+ if (!has(source, 'workspaces')) continue
38
+ const value = source.workspaces
39
+ const patterns = Array.isArray(value) ? value : value?.packages
40
+ return Array.isArray(patterns) ? patterns.filter(pattern => typeof pattern === 'string' && pattern !== '') : []
41
+ }
42
+ return null
43
+ }
44
+
45
+ function workspaceLocations(records, patterns) {
46
+ const include = patterns.filter(pattern => !pattern.startsWith('!')).map(patternRegExp)
47
+ const exclude = patterns.filter(pattern => pattern.startsWith('!')).map(pattern => patternRegExp(pattern.slice(1)))
48
+ return new Set([...records.keys()].filter(location =>
49
+ location !== '' &&
50
+ isProjectLocation(location) &&
51
+ include.some(expression => expression.test(location)) &&
52
+ !exclude.some(expression => expression.test(location))))
53
+ }
54
+
55
+ function findTarget(records, requester, name, peer, isProject) {
56
+ let scope = peer && !isProject(requester) ? parentScope(requester) : requester
57
+ while (true) {
58
+ const location = candidate(scope, name)
59
+ if (records.has(location)) return location
60
+ if (!scope) return null
61
+ scope = parentScope(scope)
62
+ }
63
+ }
64
+
65
+ function installationName(location) {
66
+ const marker = '/node_modules/'
67
+ const index = location.lastIndexOf(marker)
68
+ return index < 0 ? location.slice('node_modules/'.length) : location.slice(index + marker.length)
69
+ }
70
+
71
+ function aliasName(spec) {
72
+ if (!spec.startsWith('npm:')) return null
73
+ const value = spec.slice(4)
74
+ const match = /^(?:(@[^/@\s]+\/[^/@\s]+)|([^/@\s]+))(?:@[^@\s]+)?$/.exec(value)
75
+ return match ? match[1] ?? match[2] : null
76
+ }
77
+
78
+ function declarations(record, includeDev) {
79
+ const result = []
80
+ const optional = record.optionalDependencies ?? {}
81
+
82
+ for (const [name, spec] of Object.entries(record.dependencies ?? {})) {
83
+ if (!has(optional, name)) result.push({ name, spec, role: 'prod', optional: false })
84
+ }
85
+ for (const [name, spec] of Object.entries(optional)) {
86
+ result.push({ name, spec, role: 'optional', optional: true })
87
+ }
88
+ for (const [name, spec] of Object.entries(record.peerDependencies ?? {})) {
89
+ result.push({
90
+ name,
91
+ spec,
92
+ role: 'peer',
93
+ optional: record.peerDependenciesMeta?.[name]?.optional === true,
94
+ })
95
+ }
96
+ if (includeDev) {
97
+ for (const [name, spec] of Object.entries(record.devDependencies ?? {})) {
98
+ result.push({ name, spec, role: 'dev', optional: false })
99
+ }
100
+ }
101
+
102
+ return result.sort((a, b) =>
103
+ compare(a.name, b.name) || compare(a.role, b.role) || compare(a.spec, b.spec))
104
+ }
105
+
106
+ function missingKey(parent, name, role) {
107
+ return `\0missing:${JSON.stringify([parent, name, role])}`
108
+ }
109
+
110
+ function makeDiagnostic(code, severity, message, location = '', name = '', role = '') {
111
+ return { code, severity, message, location, name, role }
112
+ }
113
+
114
+ function locationLabel(location) {
115
+ return location || '(root)'
116
+ }
117
+
118
+ export function buildGraph({ manifest, lockfile, root }, { includeDev = false, workspaces = true, workspace } = {}) {
119
+ const records = new Map(Object.entries(lockfile.packages))
120
+ const nodes = new Map()
121
+ const edges = []
122
+ const incoming = new Map()
123
+ const outgoing = new Map()
124
+ const diagnostics = []
125
+ const excludedBoundaries = []
126
+ const patterns = workspacePatterns(manifest, root)
127
+ const workspaceSet = workspaces && patterns ? workspaceLocations(records, patterns) : new Set()
128
+ const projectRecords = workspaces
129
+ ? [...records.keys()].filter(location => location !== '' && isProjectLocation(location) && !workspaceSet.has(location))
130
+ : [...records.keys()].filter(location => location !== '' && !location.startsWith('node_modules/'))
131
+ const isProject = location => location === '' || workspaceSet.has(location)
132
+ const workspaceTarget = location => {
133
+ const record = records.get(location)
134
+ if (record.link !== true || typeof record.resolved !== 'string') return null
135
+ const resolved = normalizeLocation(record.resolved)
136
+ return workspaceSet.has(resolved) ? resolved : null
137
+ }
138
+ const workspaceNames = new Map()
139
+ for (const location of [...records.keys()].sort(compare)) {
140
+ const target = workspaceTarget(location)
141
+ if (target !== null && !workspaceNames.has(target)) workspaceNames.set(target, installationName(location))
142
+ }
143
+ const workspaceNode = location => {
144
+ const record = records.get(location)
145
+ const name = record.name || workspaceNames.get(location) || location
146
+ return {
147
+ key: location,
148
+ kind: 'workspace',
149
+ location,
150
+ installationName: name,
151
+ actualName: name,
152
+ version: record.version || null,
153
+ }
154
+ }
155
+
156
+ let startKey = ''
157
+ if (workspace !== undefined) {
158
+ if (!workspaces) throw new InputError('--workspace cannot be combined with --no-workspaces')
159
+ const normalized = normalizeLocation(workspace)
160
+ const matches = [...workspaceSet].filter(location =>
161
+ location === normalized || workspaceNode(location).actualName === workspace).sort(compare)
162
+ if (matches.length !== 1) {
163
+ throw new InputError(matches.length
164
+ ? `Workspace ${JSON.stringify(workspace)} is ambiguous: ${matches.join(', ')}`
165
+ : `No workspace named ${JSON.stringify(workspace)}`)
166
+ }
167
+ startKey = matches[0]
168
+ }
169
+
170
+ const rootNode = startKey !== '' ? workspaceNode(startKey) : {
171
+ key: '',
172
+ kind: 'root',
173
+ location: '',
174
+ installationName: manifest.name || root.name || 'root project',
175
+ actualName: manifest.name || root.name || 'root project',
176
+ version: root.version || manifest.version || null,
177
+ }
178
+
179
+ nodes.set(startKey, rootNode)
180
+ incoming.set(startKey, [])
181
+ outgoing.set(startKey, [])
182
+
183
+ if (workspaces) {
184
+ if (projectRecords.length) {
185
+ diagnostics.push(makeDiagnostic(
186
+ 'local-project-excluded',
187
+ 'warning',
188
+ `${projectRecords.length} non-node_modules project records are not workspaces and are excluded.`,
189
+ ))
190
+ }
191
+ } else if (patterns !== null) {
192
+ diagnostics.push(makeDiagnostic(
193
+ 'workspace-excluded',
194
+ 'warning',
195
+ `Workspace projects and links are excluded; ${projectRecords.length} non-node_modules project records are not traversed.`,
196
+ ))
197
+ } else if (projectRecords.length) {
198
+ diagnostics.push(makeDiagnostic(
199
+ 'local-project-excluded',
200
+ 'warning',
201
+ `${projectRecords.length} non-node_modules project records are excluded and not traversed.`,
202
+ ))
203
+ }
204
+
205
+ if (has(manifest, 'overrides')) {
206
+ diagnostics.push(makeDiagnostic(
207
+ 'overrides-present',
208
+ 'warning',
209
+ 'Root overrides are present; edge specifications are original declarations, not computed effective overrides.',
210
+ ))
211
+ }
212
+
213
+ if (!rootNode.version) {
214
+ diagnostics.push(startKey === ''
215
+ ? makeDiagnostic('root-version-missing', 'warning', 'The root project version is not recorded.')
216
+ : makeDiagnostic('workspace-version-missing', 'warning', `Workspace ${startKey} has no recorded version.`, startKey, rootNode.installationName))
217
+ }
218
+
219
+ const addWorkspace = location => {
220
+ const node = workspaceNode(location)
221
+ nodes.set(location, node)
222
+ incoming.set(location, [])
223
+ outgoing.set(location, [])
224
+ if (!node.version) {
225
+ diagnostics.push(makeDiagnostic(
226
+ 'workspace-version-missing',
227
+ 'warning',
228
+ `Workspace ${location} has no recorded version.`,
229
+ location,
230
+ node.installationName,
231
+ ))
232
+ }
233
+ return node
234
+ }
235
+
236
+ // npm installs every workspace's devDependencies, so --include-dev from the
237
+ // root starts traversal at every workspace without synthetic root edges.
238
+ const entryKeys = [startKey]
239
+ if (includeDev && workspace === undefined) {
240
+ for (const location of [...workspaceSet].sort(compare)) {
241
+ addWorkspace(location)
242
+ entryKeys.push(location)
243
+ }
244
+ }
245
+
246
+ const queue = [...entryKeys]
247
+ for (let cursor = 0; cursor < queue.length; cursor++) {
248
+ const source = queue[cursor]
249
+ const record = source === '' ? manifest : records.get(source)
250
+
251
+ for (const dependency of declarations(record, isProject(source) && includeDev)) {
252
+ const { name, spec, role, optional } = dependency
253
+ const found = findTarget(records, source, name, role === 'peer', isProject)
254
+ const target = found === null ? null : workspaceTarget(found) ?? found
255
+
256
+ if (target !== null && records.get(target).link === true) {
257
+ excludedBoundaries.push({ source, name, spec, role, location: target })
258
+ diagnostics.push(makeDiagnostic(
259
+ 'link-excluded',
260
+ 'warning',
261
+ `${locationLabel(source)} declares ${name} (${role}: ${spec}), but ${target} is an excluded workspace or local link.`,
262
+ source,
263
+ name,
264
+ role,
265
+ ))
266
+ continue
267
+ }
268
+
269
+ let targetKey = target
270
+ if (target === null) {
271
+ targetKey = missingKey(source, name, role)
272
+ const privateLocation = role === 'peer' && !isProject(source) ? candidate(source, name) : null
273
+ const privatePeer = privateLocation !== null && records.has(privateLocation)
274
+ nodes.set(targetKey, {
275
+ key: targetKey,
276
+ kind: 'placeholder',
277
+ location: null,
278
+ parent: source,
279
+ installationName: name,
280
+ actualName: null,
281
+ version: null,
282
+ role,
283
+ optional,
284
+ status: privatePeer || !optional ? 'unresolved' : 'not recorded (optional)',
285
+ })
286
+ incoming.set(targetKey, [])
287
+ outgoing.set(targetKey, [])
288
+
289
+ if (privatePeer) {
290
+ diagnostics.push(makeDiagnostic(
291
+ 'peer-private-placement',
292
+ 'error',
293
+ `${locationLabel(source)} requires peer ${name} (${spec}); only the unsupported private candidate ${privateLocation} is recorded.`,
294
+ source,
295
+ name,
296
+ role,
297
+ ))
298
+ } else {
299
+ const description = role === 'peer' && optional ? 'optional peer' : role
300
+ diagnostics.push(makeDiagnostic(
301
+ optional ? 'optional-not-recorded' : 'dependency-unresolved',
302
+ optional ? 'warning' : 'error',
303
+ `${locationLabel(source)} declares ${description} dependency ${name} (${spec}), but no eligible package is recorded.`,
304
+ source,
305
+ name,
306
+ role,
307
+ ))
308
+ }
309
+ } else {
310
+ const packageRecord = records.get(target)
311
+ if (!nodes.has(target) && workspaceSet.has(target)) {
312
+ addWorkspace(target)
313
+ queue.push(target)
314
+ } else if (!nodes.has(target)) {
315
+ const node = {
316
+ key: target,
317
+ kind: 'package',
318
+ location: target,
319
+ installationName: installationName(target),
320
+ recordedName: packageRecord.name || null,
321
+ actualName: packageRecord.name || null,
322
+ version: packageRecord.version || null,
323
+ aliasRequested: false,
324
+ aliasNames: new Set(),
325
+ ambiguousAlias: false,
326
+ }
327
+ nodes.set(target, node)
328
+ incoming.set(target, [])
329
+ outgoing.set(target, [])
330
+ queue.push(target)
331
+ if (!node.version) {
332
+ diagnostics.push(makeDiagnostic(
333
+ 'version-missing',
334
+ 'error',
335
+ `${target} has no recorded selected version.`,
336
+ target,
337
+ node.installationName,
338
+ ))
339
+ }
340
+ }
341
+
342
+ const node = nodes.get(target)
343
+ if (spec.startsWith('npm:') && node.kind === 'package') {
344
+ node.aliasRequested = true
345
+ const actualName = aliasName(spec)
346
+ if (actualName) node.aliasNames.add(actualName)
347
+ else node.ambiguousAlias = true
348
+ }
349
+ }
350
+
351
+ const edge = { source, target: targetKey, name, spec, role, optional }
352
+ edges.push(edge)
353
+ outgoing.get(source).push(edge)
354
+ incoming.get(targetKey).push(edge)
355
+ }
356
+ }
357
+
358
+ for (const node of nodes.values()) {
359
+ if (node.kind !== 'package') continue
360
+ if (!node.recordedName) {
361
+ if (!node.aliasRequested) {
362
+ node.actualName = node.installationName
363
+ } else if (!node.ambiguousAlias && node.aliasNames.size === 1) {
364
+ node.actualName = [...node.aliasNames][0]
365
+ } else {
366
+ node.actualName = null
367
+ diagnostics.push(makeDiagnostic(
368
+ 'alias-name-missing',
369
+ 'warning',
370
+ `${node.location} is an alias whose actual package name is not recorded unambiguously.`,
371
+ node.location,
372
+ node.installationName,
373
+ ))
374
+ }
375
+ }
376
+ delete node.aliasNames
377
+ delete node.ambiguousAlias
378
+ }
379
+
380
+ diagnostics.sort((a, b) =>
381
+ compare(a.code, b.code) ||
382
+ compare(a.location, b.location) ||
383
+ compare(a.name, b.name) ||
384
+ compare(a.role, b.role) ||
385
+ compare(a.message, b.message))
386
+
387
+ return {
388
+ root: rootNode,
389
+ entryKeys,
390
+ lockfileVersion: lockfile.lockfileVersion,
391
+ includeDev,
392
+ nodes,
393
+ edges,
394
+ incoming,
395
+ outgoing,
396
+ diagnostics,
397
+ excludedBoundaries,
398
+ excludedProjectRecords: projectRecords.length,
399
+ workspaces: workspaces && patterns !== null
400
+ ? {
401
+ declared: workspaceSet.size,
402
+ reached: [...nodes.values()].filter(node => node.kind === 'workspace').length,
403
+ entryPoints: entryKeys.length - 1,
404
+ }
405
+ : null,
406
+ workspacesExcluded: !workspaces && patterns !== null,
407
+ exitCode: diagnostics.some(diagnostic => diagnostic.severity === 'error') ? 2 : 0,
408
+ }
409
+ }
package/src/input.js ADDED
@@ -0,0 +1,135 @@
1
+ import { readFile } from 'node:fs/promises'
2
+ import { join } from 'node:path'
3
+ import { isDeepStrictEqual } from 'node:util'
4
+ import { InputError } from './errors.js'
5
+
6
+ const dependencyFields = [
7
+ 'dependencies',
8
+ 'devDependencies',
9
+ 'optionalDependencies',
10
+ 'peerDependencies',
11
+ ]
12
+
13
+ const has = (object, key) => Object.hasOwn(object, key)
14
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value)
15
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0
16
+
17
+ function requireObject(value, label) {
18
+ if (!isObject(value)) {
19
+ throw new InputError(`${label} must be an object`)
20
+ }
21
+ }
22
+
23
+ function validateRecord(record, label) {
24
+ requireObject(record, label)
25
+
26
+ for (const field of ['name', 'version']) {
27
+ if (has(record, field) && typeof record[field] !== 'string') {
28
+ throw new InputError(`${label}.${field} must be a string`)
29
+ }
30
+ }
31
+
32
+ if (has(record, 'link') && typeof record.link !== 'boolean') {
33
+ throw new InputError(`${label}.link must be a boolean`)
34
+ }
35
+
36
+ for (const field of dependencyFields) {
37
+ if (!has(record, field)) continue
38
+ requireObject(record[field], `${label}.${field}`)
39
+ for (const [name, spec] of Object.entries(record[field])) {
40
+ if (!name || typeof spec !== 'string') {
41
+ throw new InputError(`${label}.${field} must map nonempty names to string specifications`)
42
+ }
43
+ }
44
+ }
45
+
46
+ if (has(record, 'peerDependenciesMeta')) {
47
+ requireObject(record.peerDependenciesMeta, `${label}.peerDependenciesMeta`)
48
+ for (const [name, meta] of Object.entries(record.peerDependenciesMeta)) {
49
+ requireObject(meta, `${label}.peerDependenciesMeta[${JSON.stringify(name)}]`)
50
+ if (has(meta, 'optional') && typeof meta.optional !== 'boolean') {
51
+ throw new InputError(`${label}.peerDependenciesMeta[${JSON.stringify(name)}].optional must be a boolean`)
52
+ }
53
+ }
54
+ }
55
+ }
56
+
57
+ function effectiveDependencies(record) {
58
+ const optional = record.optionalDependencies ?? {}
59
+ return Object.fromEntries(
60
+ Object.entries(record.dependencies ?? {}).filter(([name]) => !has(optional, name)),
61
+ )
62
+ }
63
+
64
+ function compareRootDeclarations(manifest, lockedRoot) {
65
+ const fields = [...dependencyFields, 'peerDependenciesMeta']
66
+ const differences = []
67
+
68
+ for (const field of fields) {
69
+ const actual = field === 'dependencies' ? effectiveDependencies(manifest) : manifest[field] ?? {}
70
+ const locked = field === 'dependencies' ? effectiveDependencies(lockedRoot) : lockedRoot[field] ?? {}
71
+ const names = [...new Set([...Object.keys(actual), ...Object.keys(locked)])].sort(compare)
72
+
73
+ for (const name of names) {
74
+ if (!has(actual, name) || !has(locked, name) || !isDeepStrictEqual(actual[name], locked[name])) {
75
+ const describe = (map) => has(map, name) ? JSON.stringify(map[name]) : '(absent)'
76
+ differences.push(
77
+ `${field}[${JSON.stringify(name)}]: package.json ${describe(actual)}, package-lock.json ${describe(locked)}`,
78
+ )
79
+ }
80
+ }
81
+ }
82
+
83
+ if (differences.length) {
84
+ throw new InputError(`Root dependency declarations differ:\n${differences.join('\n')}`)
85
+ }
86
+ }
87
+
88
+ export function validateInputs(manifest, lockfile) {
89
+ validateRecord(manifest, 'package.json')
90
+ requireObject(lockfile, 'package-lock.json')
91
+
92
+ if (lockfile.lockfileVersion !== 2 && lockfile.lockfileVersion !== 3) {
93
+ throw new InputError(
94
+ `Unsupported lockfileVersion ${JSON.stringify(lockfile.lockfileVersion) ?? '(missing)'}; use a version 2 or 3 package-lock.json`,
95
+ )
96
+ }
97
+
98
+ requireObject(lockfile.packages, 'package-lock.json.packages')
99
+ if (!has(lockfile.packages, '')) {
100
+ throw new InputError('package-lock.json.packages must contain the root entry ""')
101
+ }
102
+
103
+ for (const [location, record] of Object.entries(lockfile.packages)) {
104
+ validateRecord(record, `package-lock.json.packages[${JSON.stringify(location)}]`)
105
+ }
106
+
107
+ if (has(manifest, 'overrides')) requireObject(manifest.overrides, 'package.json.overrides')
108
+ compareRootDeclarations(manifest, lockfile.packages[''])
109
+ return { manifest, lockfile, root: lockfile.packages[''] }
110
+ }
111
+
112
+ async function readJson(path, filename) {
113
+ let contents
114
+ try {
115
+ contents = await readFile(path, 'utf8')
116
+ } catch (error) {
117
+ throw new InputError(`Cannot read ${filename}: ${error.message}`)
118
+ }
119
+
120
+ try {
121
+ return JSON.parse(contents)
122
+ } catch (error) {
123
+ if (!(error instanceof SyntaxError)) throw error
124
+ throw new InputError(`Cannot parse ${filename}: ${error.message}`)
125
+ }
126
+ }
127
+
128
+ export async function readInputs(directory) {
129
+ const inputPaths = [join(directory, 'package.json'), join(directory, 'package-lock.json')]
130
+ const [manifest, lockfile] = await Promise.all([
131
+ readJson(inputPaths[0], 'package.json'),
132
+ readJson(inputPaths[1], 'package-lock.json'),
133
+ ])
134
+ return { ...validateInputs(manifest, lockfile), inputPaths }
135
+ }
package/src/output.js ADDED
@@ -0,0 +1,72 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { open, realpath, rename, stat, unlink } from 'node:fs/promises'
3
+ import { basename, dirname, join, resolve } from 'node:path'
4
+ import { InputError } from './errors.js'
5
+
6
+ async function statIfPresent(path) {
7
+ try {
8
+ return await stat(path, { bigint: true })
9
+ } catch (error) {
10
+ if (error.code === 'ENOENT') return null
11
+ throw error
12
+ }
13
+ }
14
+
15
+ async function protectInputs(outputPath, inputPaths) {
16
+ const outputInfo = await statIfPresent(outputPath)
17
+ if (!outputInfo) return
18
+ const outputRealPath = await realpath(outputPath)
19
+
20
+ for (const inputPath of inputPaths) {
21
+ const inputInfo = await stat(inputPath, { bigint: true })
22
+ const sameFile = outputInfo.ino !== 0n &&
23
+ outputInfo.ino === inputInfo.ino && outputInfo.dev === inputInfo.dev
24
+ const inputRealPath = await realpath(inputPath)
25
+ const normalize = path => process.platform === 'win32' ? path.toLowerCase() : path
26
+ if (sameFile || normalize(outputRealPath) === normalize(inputRealPath)) {
27
+ throw new InputError('Output must not overwrite package.json or package-lock.json, including filesystem aliases')
28
+ }
29
+ }
30
+ }
31
+
32
+ export async function writeReport(output, inputPaths, report) {
33
+ const outputPath = resolve(output)
34
+ await protectInputs(outputPath, inputPaths)
35
+ const temporary = join(dirname(outputPath), `.${basename(outputPath)}.${randomUUID()}.tmp`)
36
+ let handle
37
+ let temporaryExists = false
38
+ try {
39
+ handle = await open(temporary, 'wx')
40
+ temporaryExists = true
41
+ await handle.writeFile(report, 'utf8')
42
+ await handle.close()
43
+ handle = null
44
+ await protectInputs(outputPath, inputPaths)
45
+ await rename(temporary, outputPath)
46
+ temporaryExists = false
47
+ } finally {
48
+ try {
49
+ if (handle) await handle.close()
50
+ } finally {
51
+ if (temporaryExists) await unlink(temporary)
52
+ }
53
+ }
54
+ }
55
+
56
+ export async function writeStream(stream, content) {
57
+ await new Promise((resolveWrite, rejectWrite) => {
58
+ const onError = error => {
59
+ stream.off('error', onError)
60
+ rejectWrite(error)
61
+ }
62
+ stream.once('error', onError)
63
+ stream.write(content, error => {
64
+ if (error) {
65
+ rejectWrite(error)
66
+ } else {
67
+ stream.off('error', onError)
68
+ resolveWrite()
69
+ }
70
+ })
71
+ })
72
+ }