Skip to content
Draft
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
12 changes: 12 additions & 0 deletions docs/recipe-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -985,6 +985,18 @@ created test tables and before test discovery and execution. Any dependency
`plugins_loaded` callbacks registered during that load are invoked once after
dependency activation.

`extra_themes` declares theme dependencies for the PHPUnit builder, using the
same shape as `inputs.extra_themes` (`source`/`sourcePath`, `slug`/`mountSlug`,
`activate`). Themes mount under `/wordpress/wp-content/themes/<slug>` and the
builder passes them to `wordpress.phpunit` as `dependency-themes-json`. In
managed bootstrap mode the `activate: true` theme becomes the active theme
(`template`/`stylesheet` options, including a child theme's parent) after
dependency plugins load, its `functions.php` (child first, then parent) is
loaded, and its `after_setup_theme` and `init` callbacks run before fixtures and
tests. Do not pass themes through `extra_plugins`: validation reports a
theme-shaped `extra_plugins` source (a `style.css` with `Theme Name:` and no
plugin entry file) and points to `extra_themes`.

Set `databaseType` to `mysql` when managed PHPUnit tests require MySQL semantics.
The builder provisions a disposable MySQL service, maps its canonical `DB_*`
outputs into the runtime, and writes those values into `wp-tests-config.php`.
Expand Down
4 changes: 3 additions & 1 deletion packages/cli/src/commands/recipe-build.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { readFile, writeFile } from "node:fs/promises"
import { buildGenericAbilityRuntimeRunRecipe, buildRuntimePackageRunRecipe, buildWordPressBenchRecipe, buildWordPressPhpunitRecipe, compileRecipeTemplate, type GenericAbilityRuntimeRunOptions, type RecipeTemplateInput, type RuntimePackageRunRecipeOptions, type RuntimeWorkerCount, type RuntimeWordPressInstallMode, type WorkspaceRecipe, type WorkspaceRecipeExtraPlugin, type WorkspaceRecipeMount, type WorkspaceRecipePHPWasmExtensionManifest, type WorkspaceRecipeRuntimeBackendPackage, type WorkspaceRecipeRuntimeService, type WorkspaceRecipeStep } from "@automattic/wp-codebox-core"
import { buildGenericAbilityRuntimeRunRecipe, buildRuntimePackageRunRecipe, buildWordPressBenchRecipe, buildWordPressPhpunitRecipe, compileRecipeTemplate, type GenericAbilityRuntimeRunOptions, type RecipeTemplateInput, type RuntimePackageRunRecipeOptions, type RuntimeWorkerCount, type RuntimeWordPressInstallMode, type WorkspaceRecipe, type WorkspaceRecipeExtraPlugin, type WorkspaceRecipeExtraTheme, type WorkspaceRecipeMount, type WorkspaceRecipePHPWasmExtensionManifest, type WorkspaceRecipeRuntimeBackendPackage, type WorkspaceRecipeRuntimeService, type WorkspaceRecipeStep } from "@automattic/wp-codebox-core"

interface RecipeBuildOptions {
recipeType: "phpunit" | "bench" | "template" | "generic-ability-runtime-run" | "runtime-package-run"
Expand All @@ -19,6 +19,7 @@ interface WordPressPhpunitBuilderOptions {
mounts?: WorkspaceRecipeMount[]
services?: WorkspaceRecipeRuntimeService[]
extra_plugins?: WorkspaceRecipeExtraPlugin[]
extra_themes?: WorkspaceRecipeExtraTheme[]
pluginSource?: string
pluginSlug: string
cwd?: string
Expand Down Expand Up @@ -92,6 +93,7 @@ function buildRecipe(recipeType: RecipeBuildOptions["recipeType"], options: Word
mounts: Array.isArray(phpunitOptions.mounts) ? phpunitOptions.mounts : [],
services: Array.isArray(phpunitOptions.services) ? phpunitOptions.services : [],
extra_plugins: Array.isArray(phpunitOptions.extra_plugins) ? phpunitOptions.extra_plugins : [],
extra_themes: Array.isArray(phpunitOptions.extra_themes) ? phpunitOptions.extra_themes : [],
pluginSource: stringOrUndefined(phpunitOptions.pluginSource),
pluginSlug: requiredString(phpunitOptions.pluginSlug, "pluginSlug"),
cwd: stringOrUndefined(phpunitOptions.cwd),
Expand Down
25 changes: 24 additions & 1 deletion packages/cli/src/recipe-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -745,7 +745,12 @@ export async function validateWorkspaceRecipeSemantics(recipe: WorkspaceRecipe,
}

if (pluginMountedSource && !localZipSource) {
await validateExistingFile(join(pluginMountedSource, pluginFile.slice(slug.length + 1)), `${path}.pluginFile`, addIssue)
const pluginEntryPath = join(pluginMountedSource, pluginFile.slice(slug.length + 1))
if (!await isExistingFile(pluginEntryPath) && await looksLikeThemeDirectory(pluginMountedSource)) {
addIssue("missing-path", `${path}.pluginFile`, `File does not exist: ${pluginEntryPath}. The extra_plugins source ${pluginMountedSource} looks like a theme (style.css declares Theme Name:), not a plugin; declare it under inputs.extra_themes (or the phpunit builder's extra_themes option) instead of extra_plugins.`)
continue
}
await validateExistingFile(pluginEntryPath, `${path}.pluginFile`, addIssue)
}
}

Expand Down Expand Up @@ -2094,6 +2099,24 @@ async function validateExistingBackendPackageSource(path: string, issuePath: str
addIssue("missing-backend-package-source", issuePath, `Runtime backend package source must be an existing file or directory: ${path}`)
}

async function isExistingFile(path: string): Promise<boolean> {
try {
return (await stat(path)).isFile()
} catch {
return false
}
}

/** True when a directory carries a theme style.css header (`Theme Name:`). */
export async function looksLikeThemeDirectory(directory: string): Promise<boolean> {
try {
const styleCss = await readFile(join(directory, "style.css"), "utf8")
return /^[ \t/*#@]*Theme Name\s*:/im.test(styleCss.slice(0, 8192))
} catch {
return false
}
}

async function validateExistingFile(path: string, issuePath: string, addIssue: (code: string, path: string, message: string) => void): Promise<void> {
try {
const result = await stat(path)
Expand Down
72 changes: 71 additions & 1 deletion packages/runtime-core/src/recipe-builders.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { RuntimePreviewSpec, RuntimeWorkerCount, RuntimeWordPressInstallMode, WorkspaceRecipe, WorkspaceRecipeExtraPlugin, WorkspaceRecipeMount, WorkspaceRecipePHPWasmExtensionManifest, WorkspaceRecipeRuntimeBackendPackage, WorkspaceRecipeRuntimeService, WorkspaceRecipeStep } from "./runtime-contracts.js"
import type { RuntimePreviewSpec, RuntimeWorkerCount, RuntimeWordPressInstallMode, WorkspaceRecipe, WorkspaceRecipeExtraPlugin, WorkspaceRecipeExtraTheme, WorkspaceRecipeMount, WorkspaceRecipePHPWasmExtensionManifest, WorkspaceRecipeRuntimeBackendPackage, WorkspaceRecipeRuntimeService, WorkspaceRecipeStep } from "./runtime-contracts.js"
import { commandArg, commandJsonArg, commandStringListArg } from "./command-codecs.js"
export { buildRuntimePackageRunRecipe, CODEBOX_RUN_RUNTIME_PACKAGE_ABILITY, RUNTIME_PACKAGE_ARTIFACT_DECLARATION_SCHEMA, RUNTIME_PACKAGE_EXECUTION_INPUT_SCHEMA, RUNTIME_PACKAGE_EXECUTION_RESULT_SCHEMA, RUNTIME_PACKAGE_OUTPUT_PROJECTION_SCHEMA, runtimePackageExecutionInput, type RuntimePackageArtifactDeclaration, type RuntimePackageExecutionInput, type RuntimePackageOutputProjection, type RuntimePackageRunRecipeOptions } from "./runtime-package-execution.js"
export { RUNTIME_PACKAGE_DIAGNOSTIC_SCHEMA, RUNTIME_PACKAGE_RESULT_SCHEMA, RUNTIME_PACKAGE_TASK_SCHEMA, normalizeRuntimePackageResult, normalizeRuntimePackageTask, validateRuntimePackageTask, type RuntimePackageDiagnostic, type RuntimePackageResult, type RuntimePackageTask } from "./runtime-package-contracts.js"
Expand All @@ -25,6 +25,13 @@ export interface WordPressPhpunitRecipeOptions {
mounts?: WorkspaceRecipeMount[]
services?: WorkspaceRecipeRuntimeService[]
extra_plugins?: WorkspaceRecipeExtraPlugin[]
/**
* Theme dependencies, same shape as recipe `inputs.extra_themes`. Themes are
* mounted under wp-content/themes/<slug>; the `activate: true` theme becomes
* the active theme for the managed PHPUnit bootstrap so its functions.php
* (and its parent's, for child themes) loads before component tests run.
*/
extra_themes?: WorkspaceRecipeExtraTheme[]
pluginSource?: string
pluginSlug: string
cwd?: string
Expand Down Expand Up @@ -79,6 +86,7 @@ export function buildWordPressPhpunitRecipe(options: WordPressPhpunitRecipeOptio
const autoloadFile = options.autoloadFile ?? (options.bootstrapMode === "project" ? "" : "/wp-codebox-vendor/autoload.php")
const services = phpunitRuntimeServices(options.databaseType, options.services)
const extraPlugins = normalizeExtraPlugins(options.extra_plugins)
const extraThemes = normalizeExtraThemes(options.extra_themes)
if (options.databaseType === "mdi-native") {
const nativePlugin = nativeMdiPlugin(extraPlugins)
const nativeIndex = extraPlugins.findIndex((plugin) => plugin.slug === "markdown-database-integration")
Expand All @@ -104,6 +112,7 @@ export function buildWordPressPhpunitRecipe(options: WordPressPhpunitRecipeOptio
},
inputs: {
extra_plugins: extraPlugins,
...(extraThemes.length > 0 ? { extra_themes: extraThemes } : {}),
...(services.length > 0 ? { services } : {}),
mounts: normalizeRecipeMounts([
...(options.pluginSource ? [{ source: options.pluginSource, target: pluginTarget } satisfies WorkspaceRecipeMount] : []),
Expand Down Expand Up @@ -131,6 +140,7 @@ export function buildWordPressPhpunitRecipe(options: WordPressPhpunitRecipeOptio
commandArg("phpunit-xml-default", options.phpunitXml === undefined ? "1" : ""),
commandStringListArg("dependency-mounts", options.dependencyMounts ?? []),
commandJsonArg("dependency-plugins-json", phpunitDependencyPlugins(options.dependencyMounts ?? [], extraPlugins)),
...(extraThemes.length > 0 ? [commandJsonArg("dependency-themes-json", phpunitDependencyThemes(extraThemes))] : []),
commandJsonArg("bootstrap-files-json", options.bootstrapFiles ?? []),
commandJsonArg("preload-files-json", options.preloadFiles ?? []),
commandJsonArg("phpunit-args-json", options.phpunitArgs ?? []),
Expand Down Expand Up @@ -162,6 +172,46 @@ function phpunitDependencyPlugins(mounts: readonly string[], plugins: readonly W
})
}

export interface PhpunitDependencyTheme {
slug: string
path: string
activate: boolean
}

/**
* Projects recipe extra_themes into the managed PHPUnit bootstrap contract.
* Slugs follow the recipe source contract: mountSlug, then slug, then the
* local source directory basename.
*/
export function phpunitDependencyThemes(themes: readonly WorkspaceRecipeExtraTheme[]): PhpunitDependencyTheme[] {
if (themes.filter((theme) => theme.activate === true).length > 1) {
throw new Error("buildWordPressPhpunitRecipe extra_themes permits at most one active theme")
}
const seen = new Set<string>()
return themes.map((theme, index) => {
const slug = phpunitDependencyThemeSlug(theme, index)
if (seen.has(slug)) {
throw new Error(`buildWordPressPhpunitRecipe extra_themes slugs must be unique: ${slug}`)
}
seen.add(slug)
return { slug, path: `/wordpress/wp-content/themes/${slug}`, activate: theme.activate === true }
})
}

function phpunitDependencyThemeSlug(theme: WorkspaceRecipeExtraTheme, index: number): string {
const explicit = theme.mountSlug ?? theme.slug
const inferred = explicit ?? (theme.source ?? theme.sourcePath ?? "")
.replace(/[?#].*$/, "")
.replace(/[\\/]+$/g, "")
.split(/[\\/]/)
.pop()
const slug = (inferred ?? "").trim()
if (!/^[a-z0-9][a-z0-9_-]*$/i.test(slug)) {
throw new Error(`buildWordPressPhpunitRecipe extra_themes[${index}] requires a theme directory slug (set slug or mountSlug): ${slug || "<empty>"}`)
}
return slug
}

function nativeMdiPlugin(plugins: readonly WorkspaceRecipeExtraPlugin[]): WorkspaceRecipeExtraPlugin {
const candidates = plugins.filter((plugin) => plugin.slug === "markdown-database-integration")
if (candidates.length > 1) {
Expand Down Expand Up @@ -334,6 +384,26 @@ function normalizeExtraPlugins(plugins: readonly WorkspaceRecipeExtraPlugin[] =
})
}

function normalizeExtraThemes(themes: readonly WorkspaceRecipeExtraTheme[] = []): WorkspaceRecipeExtraTheme[] {
const normalized = themes.map((theme, index) => {
if (!theme || typeof theme !== "object") {
throw new Error(`Recipe extra theme ${index} must be an object`)
}
if ((typeof theme.source !== "string" || !theme.source) && (typeof theme.sourcePath !== "string" || !theme.sourcePath)) {
throw new Error(`Recipe extra theme ${index} requires source`)
}
const entry: WorkspaceRecipeExtraTheme = {}
for (const key of ["source", "sourcePath", "sourceRoot", "sourceSubpath", "sourceSubdir", "originalSource", "slug", "mountSlug", "activate", "sha256", "metadata"] as const) {
if (theme[key] !== undefined) {
(entry as Record<string, unknown>)[key] = theme[key]
}
}
return entry
})
phpunitDependencyThemes(normalized)
return normalized
}

function blueprintWithWpConfigDefines(blueprint: unknown, defines: JsonObject): unknown {
const defineKeys = Object.keys(defines)
if (defineKeys.length === 0) {
Expand Down
Loading
Loading