Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/pnpm-native-build-approvals.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@tanstack/create': patch
---

Write pnpm native build approvals to pnpm-workspace.yaml for pnpm 11 while retaining package.json approvals for pnpm 9 and 10. Preserve existing workspace configuration when adding integrations.

Keep ordinary pnpm 9 dependency additions working when creating a new standalone workspace, without changing existing monorepo root checks or explicit project settings.
1 change: 1 addition & 0 deletions packages/create/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
"parse-gitignore": "^2.0.0",
"prettier": "^3.5.0",
"rimraf": "^6.0.1",
"yaml": "^2.8.2",
"zod": "^3.24.2"
},
"devDependencies": {
Expand Down
23 changes: 21 additions & 2 deletions packages/create/src/add-to-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ import {
recursivelyGatherFilesFromEnvironment,
} from './file-helpers.js'
import { mergePackageJSON } from './package-json.js'
import {
mergePnpmWorkspace,
pnpmBuildDependencies,
standalonePnpmNpmrc,
} from './pnpm-workspace.js'
import { runSpecialSteps } from './special-steps/index.js'
import { loadStarter } from './custom-add-ons/starter.js'
import { setupIntent } from './integrations/intent.js'
Expand Down Expand Up @@ -141,7 +146,7 @@ function assertNoExclusiveAddOnConflicts(addOns: Array<AddOn>) {

async function runCreateApp(options: Required<Options>) {
const { environment, output } = createMemoryEnvironment(options.targetDir)
await createApp(environment, options)
await createApp(environment, options, { existingProject: true })
return output
}

Expand Down Expand Up @@ -214,6 +219,20 @@ export async function writeFiles(
for (const [relativeFile, generatedContents] of Object.entries(
relativeOutputFiles,
)) {
if (relativeFile === 'pnpm-workspace.yaml') {
const generatedPackage = relativeOutputFiles['package.json']
if (generatedPackage) {
const currentPackage = currentFiles['package.json'] ? JSON.parse(currentFiles['package.json']) : {}
const mergedPackage = mergePackageJSON(currentPackage, JSON.parse(generatedPackage))
relativeOutputFiles[relativeFile] = await mergePnpmWorkspace(currentFiles[relativeFile] ?? generatedContents, pnpmBuildDependencies(mergedPackage), pnpmBuildDependencies(currentPackage))
const npmrc = await standalonePnpmNpmrc(
currentFiles[relativeFile],
relativeOutputFiles[relativeFile],
relativeOutputFiles['.npmrc'] ?? currentFiles['.npmrc'],
)
if (npmrc !== undefined) relativeOutputFiles['.npmrc'] = npmrc
}
}
if (
ENV_FILE_NAMES.has(basename(relativeFile)) &&
relativeFile in currentFiles
Expand Down Expand Up @@ -270,7 +289,7 @@ export async function writeFiles(
await environment.readFile(resolve(cwd, file)),
)
const newJSON = mergePackageJSON(currentJson, JSON.parse(contents))
environment.writeFile(
await environment.writeFile(
resolve(cwd, file),
JSON.stringify(newJSON, null, 2),
)
Expand Down
25 changes: 22 additions & 3 deletions packages/create/src/create-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
validatePackageManagerSupport,
} from './package-manager.js'
import { createPackageJSON } from './package-json.js'
import { writePnpmWorkspace } from './pnpm-workspace.js'
import { resolvePackageJSONLatest } from './npm-resolver.js'
import { createTemplateFile } from './template-file.js'
import { installShadcnComponents } from './integrations/shadcn.js'
Expand Down Expand Up @@ -64,7 +65,14 @@ function stripExamplesFromOptions(options: Options): Options {
}
}

async function writeFiles(environment: Environment, options: Options) {
async function writeFiles(
environment: Environment,
options: Options,
context: { existingProject?: boolean } = {},
) {
const workspaceWasPresent = environment.exists(
resolve(options.targetDir, 'pnpm-workspace.yaml'),
)
const templateFileFromContent = createTemplateFile(environment, options)

async function writeFileBundle(bundle: FileBundleHandler) {
Expand Down Expand Up @@ -134,6 +142,13 @@ async function writeFiles(environment: Environment, options: Options) {
message: 'Writing package.json...',
})
const packageJSON = await resolvePackageJSONLatest(createPackageJSON(options))
await writePnpmWorkspace(
environment,
resolve(options.targetDir, 'pnpm-workspace.yaml'),
options.packageManager,
packageJSON,
{ ...context, workspaceWasPresent },
)
await environment.writeFile(
resolve(options.targetDir, './package.json'),
JSON.stringify(packageJSON, null, 2),
Expand Down Expand Up @@ -476,12 +491,16 @@ Please read the README.md file for information on ${readmeDescription}${errorSta
)
}

export async function createApp(environment: Environment, options: Options) {
export async function createApp(
environment: Environment,
options: Options,
context: { existingProject?: boolean } = {},
) {
validatePackageManagerSupport(options.packageManager, options.chosenAddOns)
const effectiveOptions = stripExamplesFromOptions(normalizeAndValidateBundlerOptions(options))

environment.startRun()
await writeFiles(environment, effectiveOptions)
await writeFiles(environment, effectiveOptions, context)
await seedEnvValues(environment, effectiveOptions)
await writeEnvExample(environment, effectiveOptions)
await runCommandsAndInstallDependencies(environment, effectiveOptions)
Expand Down
25 changes: 22 additions & 3 deletions packages/create/src/edge-create-app.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createPackageJSON } from './edge-package-json.js'
import { writePnpmWorkspace } from './pnpm-workspace.js'
import { createTemplateFile } from './edge-template-file.js'
import { formatCommand } from './utils.js'
import { isBase64, isDemoFilePath } from './edge-file-helpers.js'
Expand Down Expand Up @@ -61,7 +62,14 @@ function stripExamplesFromOptions(options: Options): Options {
}
}

async function writeFiles(environment: Environment, options: Options) {
async function writeFiles(
environment: Environment,
options: Options,
context: { existingProject?: boolean } = {},
) {
const workspaceWasPresent = environment.exists(
joinPaths(options.targetDir, 'pnpm-workspace.yaml'),
)
const templateFileFromContent = createTemplateFile(environment, options)

async function writeFileBundle(bundle: FileBundleHandler) {
Expand Down Expand Up @@ -130,6 +138,13 @@ async function writeFiles(environment: Environment, options: Options) {
message: 'Writing package.json...',
})
const packageJSON = await resolvePackageJSONLatest(createPackageJSON(options))
await writePnpmWorkspace(
environment,
joinPaths(options.targetDir, 'pnpm-workspace.yaml'),
options.packageManager,
packageJSON,
{ ...context, workspaceWasPresent },
)
await environment.writeFile(
joinPaths(options.targetDir, './package.json'),
JSON.stringify(packageJSON, null, 2),
Expand Down Expand Up @@ -592,12 +607,16 @@ Please read the README.md file for information on ${readmeDescription}${errorSta
)
}

export async function createApp(environment: Environment, options: Options) {
export async function createApp(
environment: Environment,
options: Options,
context: { existingProject?: boolean } = {},
) {
validatePackageManagerSupport(options.packageManager, options.chosenAddOns)
const effectiveOptions = stripExamplesFromOptions(normalizeAndValidateBundlerOptions(options))

environment.startRun()
await writeFiles(environment, effectiveOptions)
await writeFiles(environment, effectiveOptions, context)
await seedEnvValues(environment, effectiveOptions)
await writeEnvExample(environment, effectiveOptions)
await runCommandsAndInstallDependencies(environment, effectiveOptions)
Expand Down
119 changes: 119 additions & 0 deletions packages/create/src/pnpm-workspace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { dirnamePath, joinPaths } from './edge-path.js'
import type { Environment } from './types.js'

export function pnpmBuildDependencies(
packageJSON: Record<string, unknown>,
): Array<string> {
const pnpm = packageJSON.pnpm
if (!pnpm || typeof pnpm !== 'object' || !('onlyBuiltDependencies' in pnpm))
return []
return Array.isArray(pnpm.onlyBuiltDependencies)
? pnpm.onlyBuiltDependencies.filter(
(name): name is string => typeof name === 'string',
)
: []
}

export async function mergePnpmWorkspace(
existing: string | undefined,
dependencies: ReadonlyArray<string>,
existingDependencies: ReadonlyArray<string> = [],
): Promise<string> {
const { Document, isMap, isScalar, isSeq, parseDocument } = await import(
'yaml'
)
const doc =
existing === undefined ? new Document({}) : parseDocument(existing)
if (doc.errors.length)
throw new Error(`Invalid pnpm-workspace.yaml: ${doc.errors[0].message}`)
if (doc.contents !== null && !isMap(doc.contents))
throw new Error('pnpm-workspace.yaml must contain a mapping')
if (!doc.has('packages')) doc.set('packages', doc.createNode(['.']))
const legacy = doc.get('onlyBuiltDependencies', true)
const names = new Set(dependencies)
if (isSeq(legacy)) {
for (const item of legacy.items)
if (isScalar(item) && typeof item.value === 'string')
names.add(item.value)
}
const approvals = doc.get('allowBuilds', true)
if (approvals !== undefined && !isMap(approvals))
throw new Error('pnpm allowBuilds must contain a mapping')
// Existing denials and version/pattern rules are user policy, do not broaden them.
const customPolicy =
isMap(approvals) &&
approvals.items.some(
({ key, value }) =>
!isScalar(key) ||
typeof key.value !== 'string' ||
/[*?{}[\]]|.+@/.test(key.value.replace(/^@/, '')) ||
!isScalar(value) ||
typeof value.value !== 'boolean',
)
const missing = [...names].filter(
(name) =>
(!isMap(approvals) || !approvals.has(name)) &&
!(customPolicy && existingDependencies.includes(name)),
)
if (customPolicy && missing.length)
throw new Error(
`Update the existing pnpm allowBuilds policy for: ${missing.join(', ')}`,
)
if (!approvals) doc.set('allowBuilds', doc.createNode({}))
for (const name of missing) doc.setIn(['allowBuilds', name], true)
return doc.toString()
}

export async function writePnpmWorkspace(
environment: Environment,
path: string,
packageManager: string,
packageJSON: Record<string, unknown>,
context: { existingProject?: boolean; workspaceWasPresent?: boolean } = {},
) {
const dependencies = pnpmBuildDependencies(packageJSON)
if (packageManager !== 'pnpm' || !dependencies.length) return
const existing = environment.exists(path)
? await environment.readFile(path)
: undefined
const workspace = await mergePnpmWorkspace(existing, dependencies)
await environment.writeFile(path, workspace)
if (
!context.existingProject &&
!(context.workspaceWasPresent ?? existing !== undefined)
) {
const npmrcPath = joinPaths(dirnamePath(path), '.npmrc')
const npmrc = environment.exists(npmrcPath)
? await environment.readFile(npmrcPath)
: undefined
const compatible = await standalonePnpmNpmrc(undefined, workspace, npmrc)
if (compatible !== undefined)
await environment.writeFile(npmrcPath, compatible)
}
}

export async function standalonePnpmNpmrc(
previousWorkspace: string | undefined,
workspace: string,
npmrc: string | undefined,
): Promise<string | undefined> {
if (previousWorkspace !== undefined) return undefined
const { isScalar, isSeq, parseDocument } = await import('yaml')
const packages = parseDocument(workspace).get('packages', true)
if (
!isSeq(packages) ||
packages.items.length !== 1 ||
!isScalar(packages.items[0]) ||
packages.items[0].value !== '.'
)
return undefined
const content = npmrc ?? ''
const bom = content.startsWith('\uFEFF') ? '\uFEFF' : ''
const body = bom ? content.slice(1) : content
// Only inspect the global INI section and preserve explicit user values.
const globalSection = body.split(/^\s*\[/m, 1)[0]
if (/^\s*["']?ignore-workspace-root-check["']?\s*=/im.test(globalSection))
return content
// pnpm 9 does not read this setting from pnpm-workspace.yaml.
return `${bom}ignore-workspace-root-check=true\n${body}`
Comment thread
tannerlinsley marked this conversation as resolved.
Resolved
}
Loading
Loading