Skip to content

feat(cli): ship a starter base for bare Payload apps - #448

Merged
Ducksss merged 1 commit into
devfrom
claude/base-bundle
Aug 9, 2026
Merged

Ducksss merged 1 commit into
devfrom
claude/base-bundle

Conversation

@Ducksss

@Ducksss Ducksss commented Aug 9, 2026 •

Copy link
Copy Markdown
Owner

Supersedes #446 (base branch went stale after the stack merged; GitHub's retarget API errored repeatedly). Same commit, rebased onto dev.

payload-components add has always required a repo shaped like the official
Payload website starter. A project scaffolded by create-payload-app fails
detection before any block is even considered: no blocks renderer, no Pages
collection with a layout field, and none of the primitives installed blocks
import. #442 removed the hardcoded-path blocker and explicitly deferred this one.

What it ships

payload-components init --scaffold copies eight files and registers two
collections:

File Why
src/utilities/ui.ts cn() — imported by 69 of the shipped source files
src/fields/link.ts, src/fields/linkGroup.ts the link field blocks compose for calls to action (22)
src/components/Link/index.tsx CMSLink, which renders a stored link (30)
src/components/Media/index.tsx Media, which renders an upload (38)
src/collections/Media.ts the media collection those uploads live in
src/collections/Pages/index.ts the layout blocks field installs register into
src/blocks/RenderBlocks.tsx the renderer map installs wire into

The surface is this small because the research narrowed it: across all 154 shipped
source files there are exactly four consumer imports outside shadcn UI, and
Media is used with exactly two props at all 46 of its call sites.

Three deliberate choices

It reproduces the starter's shape, so it needs no target of its own. A
scaffolded project detects as payload-website-starter, because that is honestly
what it now is. An earlier draft of this change added a third support-matrix
target and widened supportedTargets across all 67 manifests — that turned out to
be pure churn once the test showed detection already succeeding, and was dropped.

Nothing is overwritten. A project that already has its own cn, Media, or
Pages collection keeps it, and a re-run creates nothing. Files are copied through
the same guarded helper --localized already uses — not through shadcn, because
these are not catalog components and must never appear in the catalog.

A config it cannot parse is reported, not rewritten. Registering the
collections is text-anchored on collections: [. Without that anchor the command
prints the two lines to add rather than guessing at the shape of someone's
buildConfig call — that is precisely the kind of edit nobody could review.

The primitives are intentionally thinner than the starter's: CMSLink renders
through next/link and cn rather than a Button a bare app does not have, and
Media covers the two props blocks actually pass, falling back to a plain img
when the upload has no intrinsic dimensions.

Known limitation — please weigh this

This is target code that cannot be typechecked in this repository.
payload-components/source is excluded from tsc and there is no payload
dependency here, by design.

Coverage proves the bundle turns an undetectable project into a detected one, that
it is idempotent, that it never clobbers, and that the config patch is correct in
all three branches. It does not prove the copied code compiles against a
real Payload app. That needs a test:fresh scenario — scaffold a blank app,
init --scaffold, install a block, stop at tsc --noEmit — which needs network
and a database and is not in this change. getCreatePayloadAppArgs already
hardcodes -t website as a one-line seam for it.

It is also worth saying plainly: this duplicates code the official Payload website
starter owns, and that is a real maintenance burden and a divergence risk. It is
why #442 deferred it. If you would rather point bare-app users at the website
starter instead, this PR is the thing to drop.

Verification

Step Result
lint · format:check · tsc · test:registry 0
test:int 505 passed, 1 skipped (+7 for the bundle)
test:e2e (production mode) 397 passed, all 5 batches

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added payload-components init --scaffold to set up starter files in bare Payload projects.
    • Added reusable link, media, block-rendering, UI, and page-management components.
    • Added Pages and Media collection configuration.
    • Scaffold setup preserves existing files and supports safe, repeatable reruns.
  • Documentation

    • Documented scaffold setup, supported projects, generated files, configuration behavior, and limitations.
  • Tests

    • Added integration coverage for scaffolding, collection registration, project detection, and idempotent behavior.

`payload-components add` has always required a repo shaped like the official
Payload website starter. A project scaffolded by `create-payload-app` fails
detection before any block is even considered: no blocks renderer, no Pages
collection with a `layout` field, and none of the primitives installed blocks
import. PR #442 removed the hardcoded-path blocker; this removes the last one.

`payload-components init --scaffold` copies eight files and registers two
collections. The surface is small because the research narrowed it: across all
154 shipped source files there are exactly four consumer imports outside shadcn
UI — `cn` (69 files), `Media` (38), `CMSLink` (30), `linkGroup` (22) — and `Media`
is used with exactly two props at all 46 of its call sites.

Three deliberate choices:

- **It reproduces the starter's shape, so it needs no target of its own.** A
  scaffolded project detects as `payload-website-starter`, because that is
  honestly what it now is. An earlier draft added a third support-matrix target
  and widened `supportedTargets` across all 67 manifests; that turned out to be
  pure churn and was dropped.
- **Nothing is overwritten.** A project that already has its own `cn`, `Media`,
  or Pages collection keeps it, and a re-run creates nothing. Files are copied
  through the same guarded helper `--localized` uses, not through shadcn — these
  are not catalog components and must never appear in the catalog.
- **A config it cannot parse is reported, not rewritten.** Registering the
  collections is text-anchored on `collections: [`; without that anchor the
  command prints the two lines to add rather than guessing at the shape of
  someone's `buildConfig` call.

The primitives are intentionally thinner than the starter's: `CMSLink` renders
through `next/link` and `cn` rather than a `Button` a bare app does not have, and
`Media` covers the two props blocks actually pass. They are the consumer's code
after install — the CLI does not track or update them.

Known limitation: this is target code that cannot be typechecked in this
repository (payload-components/source is excluded from tsc, and there is no
`payload` dependency here). Coverage proves the bundle turns an undetectable
project into a detected one, that it is idempotent, and that it never clobbers.
Proving it *compiles* against a real Payload app needs a fresh-smoke scenario —
network plus a database — which is not in this change.

Co-Authored-By: Claude Opus 5 <[email protected]>
Copilot AI lite review requested due to automatic review settings August 9, 2026 13:13
@vercel

vercel Bot commented Aug 9, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
payload-components Building Building Preview Aug 9, 2026 1:13pm
payload-components-97bf Building Building Preview Aug 9, 2026 1:13pm

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Aug 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The CLI now supports init --scaffold for bare Payload applications. It installs shared starter components, preserves existing files, registers Pages and Media collections when possible, and documents idempotent reruns and configuration limitations.

Changes

Scaffolded Payload starter

Layer / File(s) Summary
Starter component contracts and implementations
payload-components/source/base/...
Adds block rendering, Pages and Media collections, CMS links, media rendering, reusable link fields, and the cn utility.
Base bundle copying and collection registration
tools/payload-components/base-bundle.ts, tools/payload-components/component-files.ts
Copies missing starter files, reports skipped files, provides required dependencies, and patches supported Payload configurations.
CLI flag and initialization flow
tools/payload-components/cli.ts, tools/payload-components/commands/init.ts
Adds --scaffold, validates its use with init, installs the starter base, detects configurations, and reports next steps.
Scaffold validation and usage documentation
tests/int/*, README.md, content/docs/cli.mdx
Tests copying, preservation, reruns, collection registration, unsupported configurations, and flag defaults. Documents scaffold behavior and limitations.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant initCommand
  participant Shadcn
  participant BaseBundle
  participant PayloadConfig
  CLI->>initCommand: pass scaffold=true
  initCommand->>Shadcn: initialize UI setup
  Shadcn-->>initCommand: return package manager
  initCommand->>BaseBundle: copy starter files
  BaseBundle-->>initCommand: report created and skipped files
  initCommand->>PayloadConfig: detect and register collections
  PayloadConfig-->>initCommand: report registration status
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: adding a starter base for bare Payload applications through the CLI.
Description check ✅ Passed The description thoroughly explains the feature, implementation choices, limitations, and verification results, although it omits the template checklist sections.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/base-bundle

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@content/docs/cli.mdx`:
- Around line 353-356: Update the fallback documentation sentence in the CLI
instructions to state that the command prints three lines to add, reflecting the
two imports and one collections entry.

In `@payload-components/source/base/blocks/RenderBlocks.tsx`:
- Line 39: Update the Block render in RenderBlocks to use each block’s stored ID
as the React key, falling back to index only when no ID is available. Preserve
the existing block props and rendering behavior.
- Around line 27-29: Update the block type validation in RenderBlocks so it
checks only own properties of blockComponents rather than using the
inherited-property-inclusive in operator. Preserve the existing null return for
missing or unregistered block types, including names such as "constructor" and
"toString".
- Around line 13-15: Update RenderBlocksProps to derive blocks from the
generated Page type instead of the ad hoc blockType/id shape, and type
blockComponents with an explicit registry keyed to the generated block
definitions. Remove unsafe casts while preserving the existing rendering
behavior, and verify the resulting types against generated Payload types.

In `@payload-components/source/base/fields/linkGroup.ts`:
- Around line 20-33: Type generatedLinkGroup as ArrayField and validate its
shape against the Payload array-field scaffold before merging. Restrict the
overrides parameter to array-specific metadata so callers cannot replace name,
type, or fields. Update the merge in the link-group generator to return the
typed ArrayField directly, removing the `as Field` assertion.

In `@tools/payload-components/base-bundle.ts`:
- Around line 71-79: Update the config-patching logic around
CONFIG_COLLECTIONS_ANCHOR to parse a supported static configuration shape and
identify the actual collections array, rather than relying on regex matches
across source. Derive imports and array entries independently, and return the
existing no-collections-array result without writing when the array cannot be
safely identified.
- Around line 85-93: Derive collection import paths relative to the selected
Payload config instead of hard-coding ./collections paths. In
tools/payload-components/base-bundle.ts lines 85-93, update the automatic import
generation around the missing collection handling and configFileRelPath; in
tools/payload-components/commands/init.ts lines 113-120, apply the same
configFileRelPath-based calculation to the manual fallback instructions so both
root-config and src-config projects reference the correct collections.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 06087834-4568-4e8c-bca1-84d0fb65cd31

📥 Commits

Reviewing files that changed from the base of the PR and between 19bcbb4 and 0c8d260.

📒 Files selected for processing (16)
  • README.md
  • content/docs/cli.mdx
  • payload-components/source/base/blocks/RenderBlocks.tsx
  • payload-components/source/base/collections/Media.ts
  • payload-components/source/base/collections/Pages/index.ts
  • payload-components/source/base/components/Link/index.tsx
  • payload-components/source/base/components/Media/index.tsx
  • payload-components/source/base/fields/link.ts
  • payload-components/source/base/fields/linkGroup.ts
  • payload-components/source/base/utilities/ui.ts
  • tests/int/payload-components-base-bundle.int.spec.ts
  • tests/int/payload-components-cli.int.spec.ts
  • tools/payload-components/base-bundle.ts
  • tools/payload-components/cli.ts
  • tools/payload-components/commands/init.ts
  • tools/payload-components/component-files.ts

Comment thread content/docs/cli.mdx
Comment on lines +353 to +356
Nothing is overwritten. A project that already has its own `cn`, `Media`, or Pages
collection keeps it, and re-running the command creates nothing. If your Payload config
has no readable `collections: [` array, the command prints the two lines to add rather
than rewriting a `buildConfig` call it could not parse.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Correct the fallback instruction count.

The command prints three lines: two imports and one collections entry. Replace “the two lines to add” with “the three lines to add” or list the required additions.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@content/docs/cli.mdx` around lines 353 - 356, Update the fallback
documentation sentence in the CLI instructions to state that the command prints
three lines to add, reflecting the two imports and one collections entry.

Comment on lines +13 to +15
type RenderBlocksProps = {
blocks?: Array<{ blockType?: string; id?: null | string }> | null
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Repo files around RenderBlocks:"
git ls-files | rg '(^|/)RenderBlocks\.tsx$|payload-components/source/base/blocks' || true

echo
echo "RenderBlocks.tsx content:"
if [ -f payload-components/source/base/blocks/RenderBlocks.tsx ]; then
  nl -ba payload-components/source/base/blocks/RenderBlocks.tsx | sed -n '1,120p'
else
  fd -a RenderBlocks.tsx . | sed -n '1,50p'
fi

echo
echo "Search for generated Page type / block registry usage:"
rg -n "type Page|interface Page|ComponentTypeMap|blockComponents|RenderBlocksProps|blocks\\?:" payload-components source . 2>/dev/null | sed -n '1,200p'

echo
echo "Find base block imports/usages:"
rg -n "RenderBlocks|renderBlocks|blocks" payload-components/source -g '*.ts' -g '*.tsx' | sed -n '1,240p'

Repository: Ducksss/payload-components

Length of output: 319


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "RenderBlocks.tsx content:"
awk '{printf "%5d\t%s\n", NR, $0}' payload-components/source/base/blocks/RenderBlocks.tsx | sed -n '1,120p'

echo
echo "Search generated Page type / block registry usage:"
rg -n "type Page|interface Page|ComponentTypeMap|blockComponents|RenderBlocksProps|blocks\\?:" payload-components source . 2>/dev/null | sed -n '1,240p'

echo
echo "Search RenderBlocks blockType/id occurrences in ts/tsx:"
rg -n "RenderBlocks|renderBlocks|blockComponents|blockType|blocks" payload-components/source payload-components -g '*.ts' -g '*.tsx' | sed -n '1,320p'

Repository: Ducksss/payload-components

Length of output: 10287


Use generated Payload block types instead of unsafe casts.

blocks still only declares blockType and id, so every stored block prop is passed through unchecked. Derive blocks from the generated Page type, and give blockComponents an explicit registry type so installed block field shapes remain schema-checked. Validate this against generated Payload types in a scaffolded project before relying on it.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@payload-components/source/base/blocks/RenderBlocks.tsx` around lines 13 - 15,
Update RenderBlocksProps to derive blocks from the generated Page type instead
of the ad hoc blockType/id shape, and type blockComponents with an explicit
registry keyed to the generated block definitions. Remove unsafe casts while
preserving the existing rendering behavior, and verify the resulting types
against generated Payload types.

Source: Coding guidelines

Comment on lines +27 to +29
if (!blockType || !(blockType in blockComponents)) {
return null
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Check registered block types without inherited properties.

blockType in blockComponents accepts inherited names such as "constructor" and "toString". An unknown stored block can then render an unintended function instead of returning null.

Proposed fix
-        if (!blockType || !(blockType in blockComponents)) {
+        if (!blockType || !Object.prototype.hasOwnProperty.call(blockComponents, blockType)) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (!blockType || !(blockType in blockComponents)) {
return null
}
if (!blockType || !Object.prototype.hasOwnProperty.call(blockComponents, blockType)) {
return null
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@payload-components/source/base/blocks/RenderBlocks.tsx` around lines 27 - 29,
Update the block type validation in RenderBlocks so it checks only own
properties of blockComponents rather than using the inherited-property-inclusive
in operator. Preserve the existing null return for missing or unregistered block
types, including names such as "constructor" and "toString".

return null
}

return <Block key={index} {...block} />

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use the stored block ID as the React key.

The array index changes when editors reorder or remove blocks. React can then retain state for the wrong block. Use the Payload block ID and retain the index only as a fallback.

Proposed fix
-        return <Block key={index} {...block} />
+        return <Block key={block.id ?? index} {...block} />
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return <Block key={index} {...block} />
return <Block key={block.id ?? index} {...block} />
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@payload-components/source/base/blocks/RenderBlocks.tsx` at line 39, Update
the Block render in RenderBlocks to use each block’s stored ID as the React key,
falling back to index only when no ID is available. Preserve the existing block
props and rendering behavior.

Comment on lines +20 to +33
const generatedLinkGroup: Field = {
name: 'links',
type: 'array',
admin: {
initCollapsed: true,
},
fields: [
link({
appearances,
}),
],
}

return { ...generatedLinkGroup, ...overrides } as Field

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== files =="
fd -a 'linkGroup\.ts|package\.json|package-lock\.json|pnpm-lock\.yaml|yarn.lock' . | sed 's#^\./##' | head -200

echo "== target file =="
if [ -f payload-components/source/base/fields/linkGroup.ts ]; then
  cat -n payload-components/source/base/fields/linkGroup.ts
fi

echo "== package versions =="
python3 - <<'PY'
import json, pathlib
for p in pathlib.Path('.').rglob('package.json'):
    if 'node_modules' in p.parts or '.next' in p.parts:
        continue
    try:
        data=json.loads(p.read_text())
    except Exception as e:
        continue
    deps={}
    for sec in ('dependencies','devDependencies','peerDependencies'):
        deps.update(data.get(sec,{}) or {})
    if 'payload' in deps or '`@payloadcms/bundler-vite`' in deps or '`@payloadcms/next`' in deps:
        print(p)
        for k,v in sorted(deps.items()):
            if 'payload' in k:
                print(f"  {k}: {v}")
PY

Repository: Ducksss/payload-components

Length of output: 1550


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== root package deps =="
python3 - <<'PY'
import json
from pathlib import Path
p=Path('package.json')
data=json.loads(p.read_text())
for sec in ('dependencies','devDependencies','peerDependencies','workspaces'):
    val=data.get(sec)
    if val is not None:
        print(sec, type(val).__name__)
        if isinstance(val, dict):
            for k,v in sorted(val.items()):
                if 'payload' in k:
                    print(f"{k}: {v}")
        else:
            print(val)
PY

echo "== payload mentions =="
rg -n "payload-components|generatedLinkGroup|type ArrayField|interface ArrayField|class ArrayField|Record<string, unknown>|Field" payload-components/source package.json pnpm-lock.yaml 2>/dev/null | head -200

echo "== linkGroup calls =="
rg -n "linkGroup\(" payload-components/source 2>/dev/null | head -200

Repository: Ducksss/payload-components

Length of output: 25790


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== pnpm package lock payload deps =="
python3 - <<'PY'
from pathlib import Path
text = Path("pnpm-lock.yaml").read_text(errors="replace").split("\n")
for i,line in enumerate(text):
    if "payload" in line.lower() or "payload-components" in line:
        print(f"{i+1}: {line}")
PY

echo "== check local type definitions if installed =="
node - <<'JS'
try {
  const payload = require.resolve('payload/package.json', {paths:[process.cwd()]})
  console.log('payload package:', payload)
} catch (e) {
  console.log('payload package not resolvable', e.code, e.message)
}
try {
  const pkg = require('./package.json')
  console.log(pkg.devDependencies?.payload || pkg.dependencies?.payload || 'no payload in root');
} catch (e) {
  console.log('package read error', e.message)
}
JS

echo "== sample producer call sites =="
for f in \
  payload-components/source/blocks/FeatureCardsMedia/config.ts \
  payload-components/source/blocks/KinoGrid/config.ts \
  payload-components/source/blocks/shared/heroFields.ts
do
  [ -f "$f" ] && { echo "--- $f"; sed -n '1,90p' "$f" | cat -n; }
done

Repository: Ducksss/payload-components

Length of output: 3697


Type generated fields as ArrayField.

overrides currently allows replacement of name, type, and fields, while line 33 asserts the merged object back to Field. Declare the generated value as ArrayField, restrict overrides to array metadata only, and return the typed field without as Field.

Validate the typed value against a Payload scaffold before merge.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@payload-components/source/base/fields/linkGroup.ts` around lines 20 - 33,
Type generatedLinkGroup as ArrayField and validate its shape against the Payload
array-field scaffold before merging. Restrict the overrides parameter to
array-specific metadata so callers cannot replace name, type, or fields. Update
the merge in the link-group generator to return the typed ArrayField directly,
removing the `as Field` assertion.

Source: Coding guidelines

Comment on lines +71 to +79
const anchor = CONFIG_COLLECTIONS_ANCHOR.exec(source)

if (!anchor || anchor.index === undefined) {
return { patched: false, reason: 'no-collections-array' as const }
}

const missing = (['Pages', 'Media'] as const).filter(
(collection) => !new RegExp(`\\b${collection}\\b`).test(source),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Inspect the actual collections array before modifying the config.

CONFIG_COLLECTIONS_ANCHOR can match a comment or string literal. The whole-source Pages and Media checks can also treat an import or comment as registration. For example, an existing Pages import with collections: [] leaves Pages out of the array.

Parse a supported static config shape and derive imports and array entries independently. If the array cannot be identified safely, return no-collections-array without writing the file.

🧰 Tools
🪛 ast-grep (0.45.0)

[warning] 77-77: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(\\b${collection}\\b)
Note: [CWE-1333] Inefficient Regular Expression Complexity

(regexp-from-variable)

🪛 OpenGrep (1.26.0)

[ERROR] 71-71: Dynamic command passed to child_process.exec/execSync. Use child_process.execFile or spawn with an argument array instead.

(coderabbit.command-injection.exec-js)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/payload-components/base-bundle.ts` around lines 71 - 79, Update the
config-patching logic around CONFIG_COLLECTIONS_ANCHOR to parse a supported
static configuration shape and identify the actual collections array, rather
than relying on regex matches across source. Derive imports and array entries
independently, and return the existing no-collections-array result without
writing when the array cannot be safely identified.

Comment on lines +85 to +93
const imports = missing
.map((collection) =>
collection === 'Pages'
? "import { Pages } from './collections/Pages'"
: "import { Media } from './collections/Media'",
)
.join('\n')
const insertAt = anchor.index + anchor[0].length
const patched = `${imports}\n${source.slice(0, insertAt)}${missing.join(', ')}, ${source.slice(insertAt)}`

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use paths relative to the selected Payload config.

The scaffold supports root payload.config.ts, but both registration paths hard-code imports for a config under src/. Root-config projects then reference nonexistent ./collections modules.

  • tools/payload-components/base-bundle.ts#L85-L93: derive automatic collection imports from configFileRelPath.
  • tools/payload-components/commands/init.ts#L113-L120: derive manual fallback instructions from configFileRelPath.
📍 Affects 2 files
  • tools/payload-components/base-bundle.ts#L85-L93 (this comment)
  • tools/payload-components/commands/init.ts#L113-L120
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/payload-components/base-bundle.ts` around lines 85 - 93, Derive
collection import paths relative to the selected Payload config instead of
hard-coding ./collections paths. In tools/payload-components/base-bundle.ts
lines 85-93, update the automatic import generation around the missing
collection handling and configFileRelPath; in
tools/payload-components/commands/init.ts lines 113-120, apply the same
configFileRelPath-based calculation to the manual fallback instructions so both
root-config and src-config projects reference the correct collections.

@Ducksss
Ducksss merged commit 20d59ba into dev Aug 9, 2026
12 checks passed
@Ducksss
Ducksss deleted the claude/base-bundle branch August 9, 2026 13:25
Ducksss added a commit that referenced this pull request Aug 9, 2026
#443 caught something this branch missed. postcss is declared TWICE —
as a direct devDependency and as a pnpm override — and the original
commit only moved the override.

Dependabot raised GHSA-fxqj-rqcc-2cmp against both manifest paths for
exactly that reason: one alert on pnpm-lock.yaml (the resolution) and a
second on package.json (the declared devDependency range). The override
already forced the tree to 8.5.23, so nothing was actually resolving
vulnerable — but the declaration was still an exact pin on 8.5.18, and
the package.json alert tracks the declaration.

Also merges origin/dev, which has moved to 1.3.0 (#442, #447, #448,
#449) since this branch was cut.

Verified against current dev: lint, format:check, source:build,
tsc --noEmit, test:registry all clean, and 505 int tests passing.
pnpm install --frozen-lockfile passes, so the lockfile and manifest
agree the way CI checks them.

Co-Authored-By: Claude Opus 5 <[email protected]>
Ducksss added a commit that referenced this pull request Aug 9, 2026
…ble pins (#444)

* security(deps): unstick the js-yaml and postcss overrides off vulnerable pins

Both pins had gone stale the same way fast-uri did in #441: the override
version that was patched when it was written now sits inside the
advisory's widened range, so the pin was holding the tree ON a known
vulnerable version rather than off one.

  js-yaml   pin 4.3.0   GHSA-5p4m-2wfm-xmqj (high)   >= 4.0.0, < 4.3.1
  postcss   pin 8.5.18  GHSA-fxqj-rqcc-2cmp (medium) <= 8.5.22

Bumps js-yaml to 4.3.1 and postcss to 8.5.23, and widens the js-yaml
range key from <4.3.0 to <4.3.1 so the override still covers everything
the advisory does.

Both surfaced on main the moment #437 promoted, because Dependabot only
reports against the default branch. They will not close until this
reaches main in turn.

Verified: lint, format:check, source:build, tsc --noEmit clean, and
381 int tests passing.

Co-Authored-By: Claude Opus 5 <[email protected]>

* security(deps): bump the postcss devDependency alongside the override

#443 caught something this branch missed. postcss is declared TWICE —
as a direct devDependency and as a pnpm override — and the original
commit only moved the override.

Dependabot raised GHSA-fxqj-rqcc-2cmp against both manifest paths for
exactly that reason: one alert on pnpm-lock.yaml (the resolution) and a
second on package.json (the declared devDependency range). The override
already forced the tree to 8.5.23, so nothing was actually resolving
vulnerable — but the declaration was still an exact pin on 8.5.18, and
the package.json alert tracks the declaration.

Also merges origin/dev, which has moved to 1.3.0 (#442, #447, #448,
#449) since this branch was cut.

Verified against current dev: lint, format:check, source:build,
tsc --noEmit, test:registry all clean, and 505 int tests passing.
pnpm install --frozen-lockfile passes, so the lockfile and manifest
agree the way CI checks them.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Ducksss added a commit that referenced this pull request Aug 9, 2026
… bare-app smoke (#458)

#448 shipped the starter base bundle with a stated gap: it is target code this
repository cannot typecheck, because payload-components/source is excluded from
tsc and there is no `payload` dependency here. Coverage proved the bundle made an
undetectable project detectable, was idempotent, and never clobbered — it did not
prove the copied code compiles.

This adds the scenario that proves it, and it found three real bugs on its first
run. Two of them shipped in v1.3.0.

**The base renderer corrupted itself on install.** `RenderBlocks.tsx` declared
`const blockComponents = {}` with both braces on one line, so the fragment
patcher — which inserts a block's entry on the line above the closing brace —
wrote the entry *above the declaration*. Two installs produced a file that does
not parse. Fixed by shipping the multi-line shape the patcher assumes.

**The patcher could do that to any consumer.** `const blockComponents = {}`
satisfies the detection anchor, so a real project written that way passed
detection and got a corrupted file. The patcher now breaks a same-line object
open instead of inserting above it, with a regression test.

**The base renderer did not typecheck once populated.** Indexing the object
literal types as `never` while the map is empty, which is the only state this
repository could ever see, and stops compiling the moment a block is installed.
The lookup now widens to `unknown` and narrows back through a real runtime check.

**`init --scaffold` reported success on a half-initialized project.** `shadcn
init` can exit 0 without writing components.json — a declined prompt, or a
non-interactive shell that cannot answer one. The command scaffolded on top of
that and printed next steps for a project that still could not install anything.
It now stops and says what to do. It also skips shadcn init entirely when
components.json already exists, which makes the command idempotent.

**Documented prerequisite.** Every installed block is Tailwind-classed and
`shadcn init` refuses without a Tailwind config, which the blank
create-payload-app template does not ship. That was always true of the registry;
the website starter simply hid it. It is now stated where a bare-app user reads.

The scenario runs as `pnpm test:fresh -- --scenario bare`: scaffold a blank
project, assert it really is bare, install the packed CLI, set up Tailwind and
shadcn, run `init --scaffold`, install two blocks chosen to exercise all four
consumer primitives, and stop at `tsc --noEmit`. It skips seed, build, boot, and
Playwright — roughly a third of the website scenario's runtime for the one thing
that could not be checked anywhere else. `--scenario website` keeps the old
behaviour and `all` runs both, which is the default.

Co-authored-by: Claude Opus 5 <[email protected]>

This branch was successfully deployed

2 active deployments
Preview – payload-components — 0c8d2604 Deployed Aug 9, 2026 by vercel[bot]
Preview – payload-components-97bf — 0c8d2604 Deployed Aug 9, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants