Open History to see the last commit
1import { dirnamePath, joinPaths } from './edge-path.js'
2import type { Environment } from './types.js'
3
4export function pnpmBuildDependencies(
5 packageJSON: Record<string, unknown>,
6): Array<string> {
7 const pnpm = packageJSON.pnpm
8 if (!pnpm || typeof pnpm !== 'object' || !('onlyBuiltDependencies' in pnpm))
9 return []
10 return Array.isArray(pnpm.onlyBuiltDependencies)
11 ? pnpm.onlyBuiltDependencies.filter(
12 (name): name is string => typeof name === 'string',
13 )
14 : []
15}
16
17export async function mergePnpmWorkspace(
18 existing: string | undefined,
19 dependencies: ReadonlyArray<string>,
20 existingDependencies: ReadonlyArray<string> = [],
21): Promise<string> {
22 const { Document, isMap, isScalar, isSeq, parseDocument } = await import(
23 'yaml'
24 )
25 const doc =
26 existing === undefined ? new Document({}) : parseDocument(existing)
27 if (doc.errors.length)
28 throw new Error(`Invalid pnpm-workspace.yaml: ${doc.errors[0].message}`)
29 if (doc.contents !== null && !isMap(doc.contents))
30 throw new Error('pnpm-workspace.yaml must contain a mapping')
31 if (!doc.has('packages')) doc.set('packages', doc.createNode(['.']))
32 const legacy = doc.get('onlyBuiltDependencies', true)
33 const names = new Set(dependencies)
34 if (isSeq(legacy)) {
35 for (const item of legacy.items)
36 if (isScalar(item) && typeof item.value === 'string')
37 names.add(item.value)
38 }
39 const approvals = doc.get('allowBuilds', true)
40 if (approvals !== undefined && !isMap(approvals))
41 throw new Error('pnpm allowBuilds must contain a mapping')
42 // Existing denials and version/pattern rules are user policy, do not broaden them.
43 const customPolicy =
44 isMap(approvals) &&
45 approvals.items.some(
46 ({ key, value }) =>
47 !isScalar(key) ||
48 typeof key.value !== 'string' ||
49 /[*?{}[\]]|.+@/.test(key.value.replace(/^@/, '')) ||
50 !isScalar(value) ||
51 typeof value.value !== 'boolean',
52 )
53 const missing = [...names].filter(
54 (name) =>
55 (!isMap(approvals) || !approvals.has(name)) &&
56 !(customPolicy && existingDependencies.includes(name)),
57 )
58 if (customPolicy && missing.length)
59 throw new Error(
60 `Update the existing pnpm allowBuilds policy for: ${missing.join(', ')}`,
61 )
62 if (!approvals) doc.set('allowBuilds', doc.createNode({}))
63 for (const name of missing) doc.setIn(['allowBuilds', name], true)
64 return doc.toString()
65}
66
67export async function writePnpmWorkspace(
68 environment: Environment,
69 path: string,
70 packageManager: string,
71 packageJSON: Record<string, unknown>,
72 context: { existingProject?: boolean; workspaceWasPresent?: boolean } = {},
73) {
74 const dependencies = pnpmBuildDependencies(packageJSON)
75 if (packageManager !== 'pnpm' || !dependencies.length) return
76 const existing = environment.exists(path)
77 ? await environment.readFile(path)
78 : undefined
79 const workspace = await mergePnpmWorkspace(existing, dependencies)
80 await environment.writeFile(path, workspace)
81 if (
82 !context.existingProject &&
83 !(context.workspaceWasPresent ?? existing !== undefined)
84 ) {
85 const npmrcPath = joinPaths(dirnamePath(path), '.npmrc')
86 const npmrc = environment.exists(npmrcPath)
87 ? await environment.readFile(npmrcPath)
88 : undefined
89 const compatible = await standalonePnpmNpmrc(undefined, workspace, npmrc)
90 if (compatible !== undefined)
91 await environment.writeFile(npmrcPath, compatible)
92 }
93}
94
95export async function standalonePnpmNpmrc(
96 previousWorkspace: string | undefined,
97 workspace: string,
98 npmrc: string | undefined,
99): Promise<string | undefined> {
100 if (previousWorkspace !== undefined) return undefined
101 const { isScalar, isSeq, parseDocument } = await import('yaml')
102 const packages = parseDocument(workspace).get('packages', true)
103 if (
104 !isSeq(packages) ||
105 packages.items.length !== 1 ||
106 !isScalar(packages.items[0]) ||
107 packages.items[0].value !== '.'
108 )
109 return undefined
110 const content = npmrc ?? ''
111 const bom = content.startsWith('\uFEFF') ? '\uFEFF' : ''
112 const body = bom ? content.slice(1) : content
113 // Only inspect the global INI section and preserve explicit user values.
114 const globalSection = body.split(/^\s*\[/m, 1)[0]
115 if (/^\s*["']?ignore-workspace-root-check["']?\s*=/im.test(globalSection))
116 return content
117 // pnpm 9 does not read this setting from pnpm-workspace.yaml.
118 return `${bom}ignore-workspace-root-check=true\n${body}`
119}