Build codeless artifacts through the pluginsdk packer

The codeless build, declarative validation and tar.zst packer moved to
block/pluginsdk/bnp (v0.3.10). ninja plugin build and publish call
sdkbnp.BuildCodeless; the wasm build keeps DESCRIBE extraction and uses
the SDK helpers over os.DirFS. weareblissful and the wasm fixture build
to the same sha256 as before. ADR 0003.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Alex Dunmow 2026-11-19 23:31:10 +08:00
parent 3e8444cc52
commit ab21eb4e88
17 changed files with 116 additions and 1128 deletions

View File

@ -38,7 +38,7 @@ make safety-check # cd ../check-safety && go run . ../cli
## `.bnp` artifacts
A `.bnp` is a **zstd-compressed tar** (NOT gzip — `tar tzf` won't read it; use
`tar tf` or `ninja plugin verify`). `internal/bnp` owns build+verify; wasm
`tar tf` or `ninja plugin verify`). `internal/bnp` owns the wasm build and verify; the codeless build, declarative validation and the packer live in `block/pluginsdk/bnp` (ADR 0003); wasm
plugins and codeless plugins/themes both pack into one. Optionally packs a root
`preview.png` and a `screenshots/` dir (validated: png/jpg/jpeg/webp, ≤8MB/file,
≤12 files, no subdirs). `internal/shot` renders pages via chromedp for

View File

@ -21,6 +21,7 @@ import (
"git.dev.alexdunmow.com/block/cli/internal/bnp"
"git.dev.alexdunmow.com/block/cli/internal/creds"
"git.dev.alexdunmow.com/block/cli/internal/orchclient"
sdkbnp "git.dev.alexdunmow.com/block/pluginsdk/bnp"
)
func newPluginCmd() *cobra.Command {
@ -771,11 +772,11 @@ func newPluginPublishCmd() *cobra.Command {
if err != nil {
return err
}
var res *bnp.BuildResult
var res *sdkbnp.BuildResult
if isCodeless {
res, err = bnp.BuildCodeless(context.Background(), bnp.BuildOptions{Dir: "."})
res, err = sdkbnp.BuildCodeless(sdkbnp.BuildOptions{Dir: "."})
} else {
res, err = bnp.Build(context.Background(), bnp.BuildOptions{Dir: "."})
res, err = bnp.Build(context.Background(), sdkbnp.BuildOptions{Dir: "."})
}
if err != nil {
return fmt.Errorf("build .bnp: %w", err)

View File

@ -8,6 +8,7 @@ import (
"github.com/spf13/cobra"
"git.dev.alexdunmow.com/block/cli/internal/bnp"
sdkbnp "git.dev.alexdunmow.com/block/pluginsdk/bnp"
)
func newPluginBuildCmd() *cobra.Command {
@ -34,11 +35,11 @@ plus wazero. This replaces the in-container .so compile.`,
if codeless && !isCodeless {
return fmt.Errorf("--codeless asserted but %s contains Go source — a codeless plugin has no code (delete the Go or drop the flag)", dir)
}
var res *bnp.BuildResult
var res *sdkbnp.BuildResult
if isCodeless {
res, err = bnp.BuildCodeless(context.Background(), bnp.BuildOptions{Dir: dir, Output: output})
res, err = sdkbnp.BuildCodeless(sdkbnp.BuildOptions{Dir: dir, Output: output})
} else {
res, err = bnp.Build(context.Background(), bnp.BuildOptions{Dir: dir, Output: output})
res, err = bnp.Build(context.Background(), sdkbnp.BuildOptions{Dir: dir, Output: output})
}
if err != nil {
return err
@ -74,7 +75,7 @@ plugin.mod. Prints a named reason for each malformed class.`,
return cmd
}
func printBuildSummary(r *bnp.BuildResult) {
func printBuildSummary(r *sdkbnp.BuildResult) {
hooks := "(none)"
if len(r.Hooks) > 0 {
hooks = strings.Join(r.Hooks, ", ")

View File

@ -11,6 +11,7 @@ import (
abiv1 "git.dev.alexdunmow.com/block/pluginsdk/abi/v1"
"git.dev.alexdunmow.com/block/cli/internal/bnp"
sdkbnp "git.dev.alexdunmow.com/block/pluginsdk/bnp"
"github.com/klauspost/compress/zstd"
"google.golang.org/protobuf/proto"
)
@ -39,7 +40,7 @@ func TestPluginBuildAndVerify(t *testing.T) {
}
out := filepath.Join(t.TempDir(), "wasmfixture-0.0.1.bnp")
res, err := bnp.Build(context.Background(), bnp.BuildOptions{
res, err := bnp.Build(context.Background(), sdkbnp.BuildOptions{
Dir: fixtureDir(t, "fixture"),
Output: out,
})
@ -104,7 +105,7 @@ func TestPluginBuildDefaultOutputName(t *testing.T) {
if err := os.Chdir(tmp); err != nil {
t.Fatalf("chdir: %v", err)
}
res, err := bnp.Build(context.Background(), bnp.BuildOptions{Dir: dir})
res, err := bnp.Build(context.Background(), sdkbnp.BuildOptions{Dir: dir})
if err != nil {
t.Fatalf("build: %v", err)
}
@ -123,7 +124,7 @@ func TestPluginBuildCapabilityInRegisterFails(t *testing.T) {
t.Skip("compiles a wasm module; skipped in -short")
}
out := filepath.Join(t.TempDir(), "capfixture.bnp")
_, err := bnp.Build(context.Background(), bnp.BuildOptions{
_, err := bnp.Build(context.Background(), sdkbnp.BuildOptions{
Dir: fixtureDir(t, "capfixture"),
Output: out,
})

View File

@ -0,0 +1,28 @@
# Codeless builds use the pluginsdk packer
The orchestrator's website factory needs to pack a codeless `.bnp` in its own
process, and Go's `internal` rule kept the CLI's packer out of reach. The
codeless build, the declarative validation and the tar.zst packer moved to the
public `bnp` package of `block/pluginsdk` (pluginsdk ADR 0009, v0.3.10).
Decision: `ninja plugin build` and `ninja plugin publish` call
`sdkbnp.BuildCodeless` for a codeless repo. The wasm build in `internal/bnp`
keeps compiling the guest and extracting its manifest through DESCRIBE, then
uses the same SDK helpers over `os.DirFS` for `manifest.yaml` folding,
`blocks/` and `seed/` validation, directory collection, presentation members
and packing. `BuildOptions` and `BuildResult` come from the SDK. Repo
classification (`IsCodelessRepo`), `ninja plugin verify` and
`CodelessHookViolation` stay in the CLI.
Consequences:
- The CLI and the orchestrator produce identical bytes for the same tree. The
weareblissful site and the wasm test fixture build to the same sha256 before
and after the change.
- The pluginsdk pin moves from v0.3.7 to v0.3.10.
- Codeless validation and packing tests live in pluginsdk; the CLI keeps the
build plus `Verify` round trips.
Keywords: plugin CLI, codeless, BuildCodeless, BuildCodelessFS, pluginsdk bnp,
sdkbnp, packArtifact, Pack, os.DirFS, manifest.yaml, BNP, tar.zst,
byte-identical build, website factory, WO-076

6
go.mod
View File

@ -5,14 +5,13 @@ go 1.26.4
require (
connectrpc.com/connect v1.20.0
git.dev.alexdunmow.com/block/core v0.20.6
git.dev.alexdunmow.com/block/pluginsdk v0.3.7
git.dev.alexdunmow.com/block/pluginsdk v0.3.10
github.com/chromedp/cdproto v0.0.0-20260321001828-e3e3800016bc
github.com/chromedp/chromedp v0.15.1
github.com/klauspost/compress v1.18.6
github.com/spf13/cobra v1.10.2
github.com/tetratelabs/wazero v1.12.0
google.golang.org/protobuf v1.36.11
gopkg.in/yaml.v3 v3.0.1
)
require (
@ -27,11 +26,10 @@ require (
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.10.0 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/rogpeppe/go-internal v1.16.0 // indirect
github.com/spf13/pflag v1.0.9 // indirect
golang.org/x/mod v0.37.0 // indirect
golang.org/x/net v0.56.0 // indirect
golang.org/x/sys v0.46.0 // indirect
golang.org/x/text v0.38.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

5
go.sum
View File

@ -2,8 +2,8 @@ connectrpc.com/connect v1.20.0 h1:6TNDAB+WeNd2uolWNlYczB5E0KNNaVMNUEx8JEUsPmQ=
connectrpc.com/connect v1.20.0/go.mod h1:A2ygJrukXwWy32vkCAAHNVguZrqZ+jeZ9rGRnGR4dN4=
git.dev.alexdunmow.com/block/core v0.20.6 h1:/f6zP1SKz44ftE5hVDOU4hJvl6TLz3vufGSkqvc2cSg=
git.dev.alexdunmow.com/block/core v0.20.6/go.mod h1:G3MNnwiM4i9roLamhs9DAlVO2mXiYAlTRQoHPpw1AmI=
git.dev.alexdunmow.com/block/pluginsdk v0.3.7 h1:PUT1YElhXre43m1UejDabSqRPAnx1BV7BEWKpG++7Rs=
git.dev.alexdunmow.com/block/pluginsdk v0.3.7/go.mod h1:Z+eG+WZxAP0jfreLqlGcc0kkWKt8RWevzWyWn8d+dhM=
git.dev.alexdunmow.com/block/pluginsdk v0.3.10 h1:Hh864yQnXAAMMh9uCuOjCS4ZrXwHh1nnW15hksrWNkY=
git.dev.alexdunmow.com/block/pluginsdk v0.3.10/go.mod h1:SAXv5Lv8mJIZHjAmDSe1LnMsftEdmVIy32T5BpGfgwg=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/chromedp/cdproto v0.0.0-20260321001828-e3e3800016bc h1:wkN/LMi5vc60pBRWx6qpbk/aEvq3/ZVNpnMvsw8PVVU=
@ -13,7 +13,6 @@ github.com/chromedp/chromedp v0.15.1/go.mod h1:CdTHtUqD/dqaFw/cvFWtTydoEQS44wLBu
github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=

View File

@ -4,6 +4,7 @@ import (
"bytes"
"context"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
@ -12,17 +13,14 @@ import (
"strconv"
abiv1 "git.dev.alexdunmow.com/block/pluginsdk/abi/v1"
sdkbnp "git.dev.alexdunmow.com/block/pluginsdk/bnp"
"git.dev.alexdunmow.com/block/pluginsdk/egress"
core "git.dev.alexdunmow.com/block/pluginsdk/plugin"
"google.golang.org/protobuf/proto"
)
// Required top-level artifact members (mirrors the CMS reader).
const (
fileWasm = "plugin.wasm"
fileMod = "plugin.mod"
fileManifest = "manifest.pb"
)
// fileWasm is the guest module member of a wasm artifact (mirrors the CMS reader).
const fileWasm = "plugin.wasm"
// minGoMajor/minGoMinor is the lowest Go toolchain that can emit reactor-mode
// (`-buildmode=c-shared`) wasip1 modules the guest shim relies on.
@ -31,44 +29,10 @@ const (
minGoMinor = 24
)
// BuildOptions configures Build.
type BuildOptions struct {
// Dir is the plugin repo root (holds plugin.mod and the main Go package).
Dir string
// Output is the destination .bnp path. Empty → "<name>-<version>.bnp" in
// the current working directory.
Output string
}
// BuildResult summarizes a produced artifact for the CLI summary table.
type BuildResult struct {
OutputPath string
Name string
Version string
// Codeless marks a declarative artifact (no plugin.wasm, WO-WZ-020).
Codeless bool
WasmBytes int64
ManifestBytes int64
ArtifactBytes int64 // on-disk .bnp size
UncompBytes int64 // sum of packed file sizes
BlockCount int
TemplateCount int
AdminPages int
JobTypes int
Hooks []string
DataDir bool
IncludedDirs []string
// PreviewIncluded/ScreenshotCount report the packed presentation members
// (root preview.png + screenshots/); the registry ingests these into the
// plugin's gallery at publish.
PreviewIncluded bool
ScreenshotCount int
}
// Build compiles the plugin in opts.Dir to wasm, extracts its manifest, and
// packs a .bnp. No Docker/podman: the whole pipeline is the local Go
// toolchain + wazero + tar.zst.
func Build(ctx context.Context, opts BuildOptions) (*BuildResult, error) {
func Build(ctx context.Context, opts sdkbnp.BuildOptions) (*sdkbnp.BuildResult, error) {
dir := opts.Dir
if dir == "" {
dir = "."
@ -78,8 +42,8 @@ func Build(ctx context.Context, opts BuildOptions) (*BuildResult, error) {
return nil, fmt.Errorf("resolve dir: %w", err)
}
modPath := filepath.Join(dir, fileMod)
modBytes, err := os.ReadFile(modPath)
fsys := os.DirFS(dir)
modBytes, err := fs.ReadFile(fsys, sdkbnp.FileMod)
if err != nil {
return nil, fmt.Errorf("read plugin.mod (is %s a plugin repo?): %w", dir, err)
}
@ -160,9 +124,9 @@ func Build(ctx context.Context, opts BuildOptions) (*BuildResult, error) {
// manifest.pb (not packed separately, same as codeless). The templates/
// dir carrying the .ninjatpl sources already rides the optional-dir
// pack below. A repo with NO manifest.yaml is a no-op here
// (applyManifestYAML returns nil on os.IsNotExist), so an existing
// (ApplyManifestYAML returns nil on fs.ErrNotExist), so an existing
// pure-wasm plugin builds byte-for-byte as before.
if err := applyManifestYAML(dir, manifest); err != nil {
if err := sdkbnp.ApplyManifestYAML(fsys, manifest); err != nil {
return nil, err
}
if err := ValidateLoadOnceManifest(manifest); err != nil {
@ -178,33 +142,33 @@ func Build(ctx context.Context, opts BuildOptions) (*BuildResult, error) {
}
// 5. Assemble artifact entries.
entries := []packEntry{
{ArtifactPath: fileWasm, Source: wasmPath},
{ArtifactPath: fileMod, Source: modPath},
{ArtifactPath: fileManifest, Data: manifestBytes},
entries := []sdkbnp.Entry{
{ArtifactPath: fileWasm, Data: wasm},
{ArtifactPath: sdkbnp.FileMod, Data: modBytes},
{ArtifactPath: sdkbnp.FileManifest, Data: manifestBytes},
}
var includedDirs []string
// dir-name → source subpath. web ships the Module Federation build output
// (web/dist) flattened under web/ so the reader's dirExists("web") fires.
optional := []struct{ artifact, src string }{
{dirBlocks, dirBlocks},
{dirTemplates, dirTemplates},
{dirSeed, dirSeed},
{sdkbnp.DirBlocks, sdkbnp.DirBlocks},
{sdkbnp.DirTemplates, sdkbnp.DirTemplates},
{sdkbnp.DirSeed, sdkbnp.DirSeed},
{"migrations", "migrations"},
{"schemas", "schemas"},
{"assets", "assets"},
{"web", filepath.Join("web", "dist")},
{"web", "web/dist"},
}
// Declarative dirs ride along on wasm artifacts too (a reduced plugin may
// mix definition-backed blocks with logic); validate them identically.
if _, err := validateBlocksDir(dir); err != nil {
if _, err := sdkbnp.ValidateBlocksDir(fsys); err != nil {
return nil, err
}
if err := validateSeedDir(dir); err != nil {
if err := sdkbnp.ValidateSeedDir(fsys); err != nil {
return nil, err
}
for _, o := range optional {
dirEntries, has, dErr := collectDir(filepath.Join(dir, o.src), o.artifact)
dirEntries, has, dErr := sdkbnp.CollectDir(fsys, o.src, o.artifact)
if dErr != nil {
return nil, dErr
}
@ -213,13 +177,13 @@ func Build(ctx context.Context, opts BuildOptions) (*BuildResult, error) {
includedDirs = append(includedDirs, o.artifact)
}
}
presEntries, previewIncluded, screenshotCount, err := presentationEntries(dir)
presEntries, previewIncluded, screenshotCount, err := sdkbnp.PresentationEntries(fsys)
if err != nil {
return nil, err
}
entries = append(entries, presEntries...)
if screenshotCount > 0 {
includedDirs = append(includedDirs, dirScreenshots)
includedDirs = append(includedDirs, sdkbnp.DirScreenshots)
}
// 6. Pack.
@ -227,7 +191,7 @@ func Build(ctx context.Context, opts BuildOptions) (*BuildResult, error) {
if outPath == "" {
outPath = fmt.Sprintf("%s-%s.bnp", mod.Plugin.Name, mod.Plugin.Version)
}
uncomp, err := packArtifact(outPath, entries)
uncomp, err := packArtifact(outPath, fsys, entries)
if err != nil {
return nil, err
}
@ -238,7 +202,7 @@ func Build(ctx context.Context, opts BuildOptions) (*BuildResult, error) {
}
wasmInfo, _ := os.Stat(wasmPath)
return &BuildResult{
return &sdkbnp.BuildResult{
OutputPath: outPath,
Name: manifest.GetName(),
Version: manifest.GetVersion(),

View File

@ -1,157 +1,18 @@
package bnp
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
abiv1 "git.dev.alexdunmow.com/block/pluginsdk/abi/v1"
core "git.dev.alexdunmow.com/block/pluginsdk/plugin"
"google.golang.org/protobuf/proto"
"gopkg.in/yaml.v3"
sdkbnp "git.dev.alexdunmow.com/block/pluginsdk/bnp"
)
// Codeless artifacts (WO-WZ-020): a .bnp with NO plugin.wasm — pure
// declaration the host runs. Classification is by repo shape: a plugin repo
// with no Go source builds codeless; a repo with Go builds wasm as always
// (a converted repo DELETES its Go — that's the point). Both artifact kinds
// may carry blocks/, templates/, and seed/; codeless just has nothing else.
// Declarative artifact dirs shared by both build paths.
const (
dirBlocks = "blocks"
dirTemplates = "templates"
dirSeed = "seed"
)
// manifestYAMLName is the optional root-level declarative manifest source for
// codeless plugins (the counterpart of what DESCRIBE captures from Go code).
const manifestYAMLName = "manifest.yaml"
// manifestYAML mirrors the declarative PluginManifest fields a codeless
// plugin can set. File-valued keys are paths relative to the repo root.
type manifestYAML struct {
ThemePresets string `yaml:"theme_presets"` // JSON file
BundledFonts string `yaml:"bundled_fonts"` // JSON file
SettingsSchema string `yaml:"settings_schema"` // JSON file
MasterPages string `yaml:"master_pages"` // JSON file ([]masterPageJSON)
RequiredIconPacks []string `yaml:"required_icon_packs"`
SystemTemplates []struct {
Key string `yaml:"key"`
Title string `yaml:"title"`
Description string `yaml:"description"`
} `yaml:"system_templates"`
PageTemplates []struct {
System string `yaml:"system"`
Key string `yaml:"key"`
Title string `yaml:"title"`
Description string `yaml:"description"`
Slots []string `yaml:"slots"`
} `yaml:"page_templates"`
// TemplateOverrides declare theme-scoped overrides of builtin block
// rendering. Source convention: templates/overrides/<template>/<block>.ninjatpl,
// rendered host-side with the block's content map as the template context.
TemplateOverrides []struct {
Template string `yaml:"template"` // template/system key the override binds to
Block string `yaml:"block"` // builtin block key being overridden
} `yaml:"template_overrides"`
// EmailWrappers declare branded email wrappers per system key. Source
// convention: templates/email/<system>.ninjatpl, rendered host-side with
// body/colors/site/unsubscribe_url/preview_text in the context (emit the
// pre-rendered body with |safe).
EmailWrappers []string `yaml:"email_wrappers"`
CSS *struct {
NpmPackages map[string]string `yaml:"npm_packages"`
CSSDirectives []string `yaml:"css_directives"`
InputCSSAppend string `yaml:"input_css_append"`
} `yaml:"css"`
Dependencies []struct {
Plugin string `yaml:"plugin"`
MinVersion string `yaml:"min_version"`
Required bool `yaml:"required"`
} `yaml:"dependencies"`
}
// masterPageJSON mirrors abiv1.MasterPageDefinition for the declarative file.
type masterPageJSON struct {
Key string `json:"key"`
Title string `json:"title"`
PageTemplates []string `json:"page_templates"`
Blocks []struct {
BlockKey string `json:"block_key"`
Title string `json:"title"`
Content map[string]any `json:"content"`
HTMLContent *string `json:"html_content"`
Slot string `json:"slot"`
SortOrder int32 `json:"sort_order"`
} `json:"blocks"`
}
// blocksYAML is the structural mirror of the CMS blocks.yaml manifest
// (cms blocks.LoadManifest) — a deliberate light duplication, same as the
// Verify↔reader pairing: the packer validates shape and file presence; full
// semantic validation (schema/template/provider checks) runs at install.
type blocksYAML struct {
Blocks []struct {
Key string `yaml:"key"`
Title string `yaml:"title"`
Description string `yaml:"description"`
Category string `yaml:"category"`
Schema string `yaml:"schema"`
Template string `yaml:"template"`
SampleData string `yaml:"sample_data"`
Providers []string `yaml:"providers"`
RequiredTags []string `yaml:"required_tags"`
Aliases []string `yaml:"aliases"`
} `yaml:"blocks"`
}
// seedJSON is the declarative seed schema (seed/seed.json). Applied by the
// host at load via the WO-WZ-019 provisioner (idempotent).
type seedJSON struct {
Settings *struct {
Merge map[string]any `json:"merge"`
Override map[string]any `json:"override"`
Ensure map[string]any `json:"ensure"`
} `json:"settings"`
Media []struct {
ID string `json:"id"` // UUID, required (deterministic media key)
File string `json:"file"`
Alt string `json:"alt"`
Folder string `json:"folder"`
} `json:"media"`
Pages []struct {
Slug string `json:"slug"`
ParentSlug string `json:"parent_slug"`
Title string `json:"title"`
TemplateKey string `json:"template_key"`
ReconcileBlocks bool `json:"reconcile_blocks"`
ReconcileTemplate bool `json:"reconcile_template"`
Blocks []struct {
BlockKey string `json:"block_key"`
Title string `json:"title"`
Content map[string]any `json:"content"`
HTMLContent *string `json:"html_content"`
Slot string `json:"slot"`
SortOrder int32 `json:"sort_order"`
} `json:"blocks"`
} `json:"pages"`
MenuItems []struct {
Menu string `json:"menu"`
Label string `json:"label"`
URL string `json:"url"`
PageSlug string `json:"page_slug"`
SortOrder int32 `json:"sort_order"`
} `json:"menu_items"`
}
// IsCodelessRepo reports whether dir is a declarative plugin repo: it has a
// plugin.mod but no Go source at the root (the wasm main package's home).
func IsCodelessRepo(dir string) (bool, error) {
if _, err := os.Stat(filepath.Join(dir, fileMod)); err != nil {
if _, err := os.Stat(filepath.Join(dir, sdkbnp.FileMod)); err != nil {
return false, fmt.Errorf("read plugin.mod (is %s a plugin repo?): %w", dir, err)
}
entries, err := os.ReadDir(dir)
@ -165,364 +26,3 @@ func IsCodelessRepo(dir string) (bool, error) {
}
return true, nil
}
// BuildCodeless synthesizes manifest.pb from plugin.mod + the declarative
// files and packs a codeless .bnp (no plugin.wasm, no DESCRIBE probe).
func BuildCodeless(_ context.Context, opts BuildOptions) (*BuildResult, error) {
dir := opts.Dir
if dir == "" {
dir = "."
}
dir, err := filepath.Abs(dir)
if err != nil {
return nil, fmt.Errorf("resolve dir: %w", err)
}
modPath := filepath.Join(dir, fileMod)
modBytes, err := os.ReadFile(modPath)
if err != nil {
return nil, fmt.Errorf("read plugin.mod: %w", err)
}
mod, err := core.ParseModFull(modBytes)
if err != nil {
return nil, fmt.Errorf("parse plugin.mod: %w", err)
}
if mod.Plugin.Name == "" || mod.Plugin.Version == "" {
return nil, fmt.Errorf("plugin.mod must set both name and version")
}
if mod.Plugin.DataDir {
return nil, fmt.Errorf("codeless plugin cannot request data_dir — there is no code to use it")
}
if len(mod.Plugin.PublicRoutes) > 0 || mod.Plugin.Sitemap {
return nil, fmt.Errorf("codeless plugin cannot declare public_routes or sitemap: there is no HTTP handler to serve them")
}
manifest := &abiv1.PluginManifest{
AbiVersion: hostAbiVersion,
Name: mod.Plugin.Name,
Version: mod.Plugin.Version,
Codeless: true,
}
blockCount, err := validateBlocksDir(dir)
if err != nil {
return nil, err
}
if err := validateSeedDir(dir); err != nil {
return nil, err
}
if err := applyManifestYAML(dir, manifest); err != nil {
return nil, err
}
manifestBytes, err := proto.Marshal(manifest)
if err != nil {
return nil, fmt.Errorf("marshal manifest.pb: %w", err)
}
entries := []packEntry{
{ArtifactPath: fileMod, Source: modPath},
{ArtifactPath: fileManifest, Data: manifestBytes},
}
var includedDirs []string
optional := []struct{ artifact, src string }{
{dirBlocks, dirBlocks},
{dirTemplates, dirTemplates},
{dirSeed, dirSeed},
{"migrations", "migrations"},
{"schemas", "schemas"},
{"assets", "assets"},
}
for _, o := range optional {
dirEntries, has, dErr := collectDir(filepath.Join(dir, o.src), o.artifact)
if dErr != nil {
return nil, dErr
}
if has {
entries = append(entries, dirEntries...)
includedDirs = append(includedDirs, o.artifact)
}
}
presEntries, previewIncluded, screenshotCount, err := presentationEntries(dir)
if err != nil {
return nil, err
}
entries = append(entries, presEntries...)
if screenshotCount > 0 {
includedDirs = append(includedDirs, dirScreenshots)
}
outPath := opts.Output
if outPath == "" {
outPath = fmt.Sprintf("%s-%s.bnp", mod.Plugin.Name, mod.Plugin.Version)
}
uncomp, err := packArtifact(outPath, entries)
if err != nil {
return nil, err
}
artInfo, err := os.Stat(outPath)
if err != nil {
return nil, fmt.Errorf("stat artifact: %w", err)
}
return &BuildResult{
OutputPath: outPath,
Name: manifest.GetName(),
Version: manifest.GetVersion(),
Codeless: true,
ManifestBytes: int64(len(manifestBytes)),
ArtifactBytes: artInfo.Size(),
UncompBytes: uncomp,
BlockCount: blockCount,
IncludedDirs: includedDirs,
PreviewIncluded: previewIncluded,
ScreenshotCount: screenshotCount,
}, nil
}
// validateBlocksDir structurally validates blocks/blocks.yaml when present:
// every entry has key/title/schema/template, referenced files exist within
// blocks/, and schemas are valid JSON. Returns the block count (0 when the
// dir is absent).
func validateBlocksDir(dir string) (int, error) {
root := filepath.Join(dir, dirBlocks)
manifestPath := filepath.Join(root, "blocks.yaml")
if _, err := os.Stat(root); os.IsNotExist(err) {
return 0, nil
}
raw, err := os.ReadFile(manifestPath)
if err != nil {
return 0, fmt.Errorf("blocks/ present but blocks.yaml unreadable: %w", err)
}
var bf blocksYAML
if err := yaml.Unmarshal(raw, &bf); err != nil {
return 0, fmt.Errorf("parse blocks/blocks.yaml: %w", err)
}
seen := map[string]bool{}
for i, b := range bf.Blocks {
if b.Key == "" {
return 0, fmt.Errorf("blocks.yaml: entry %d has no key", i)
}
if seen[b.Key] {
return 0, fmt.Errorf("blocks.yaml: duplicate key %q", b.Key)
}
seen[b.Key] = true
if b.Title == "" || b.Schema == "" || b.Template == "" {
return 0, fmt.Errorf("blocks.yaml: %q must declare title, schema, and template", b.Key)
}
for _, f := range []string{b.Schema, b.Template, b.SampleData} {
if f == "" {
continue
}
if err := fileWithin(root, f); err != nil {
return 0, fmt.Errorf("blocks.yaml: %q: %w", b.Key, err)
}
}
schemaRaw, err := os.ReadFile(filepath.Join(root, b.Schema))
if err != nil {
return 0, fmt.Errorf("blocks.yaml: %q schema: %w", b.Key, err)
}
if !json.Valid(schemaRaw) {
return 0, fmt.Errorf("blocks.yaml: %q schema %s is not valid JSON", b.Key, b.Schema)
}
}
return len(bf.Blocks), nil
}
// validateSeedDir validates seed/seed.json when the dir is present: it
// parses, media entries carry an id + an existing file, pages carry slugs.
func validateSeedDir(dir string) error {
root := filepath.Join(dir, dirSeed)
if _, err := os.Stat(root); os.IsNotExist(err) {
return nil
}
raw, err := os.ReadFile(filepath.Join(root, "seed.json"))
if err != nil {
return fmt.Errorf("seed/ present but seed.json unreadable: %w", err)
}
var sf seedJSON
if err := json.Unmarshal(raw, &sf); err != nil {
return fmt.Errorf("parse seed/seed.json: %w", err)
}
for i, m := range sf.Media {
if m.ID == "" || m.File == "" {
return fmt.Errorf("seed.json: media entry %d needs both id and file", i)
}
if err := fileWithin(root, m.File); err != nil {
return fmt.Errorf("seed.json: media %q: %w", m.ID, err)
}
}
for i, p := range sf.Pages {
if p.Slug == "" || p.Title == "" {
return fmt.Errorf("seed.json: page entry %d needs slug and title", i)
}
}
for i, mi := range sf.MenuItems {
if mi.Menu == "" || mi.Label == "" {
return fmt.Errorf("seed.json: menu item %d needs menu and label", i)
}
}
return nil
}
// applyManifestYAML folds the optional root manifest.yaml into the manifest.
func applyManifestYAML(dir string, m *abiv1.PluginManifest) error {
raw, err := os.ReadFile(filepath.Join(dir, manifestYAMLName))
if os.IsNotExist(err) {
return nil
}
if err != nil {
return fmt.Errorf("read %s: %w", manifestYAMLName, err)
}
var my manifestYAML
if err := yaml.Unmarshal(raw, &my); err != nil {
return fmt.Errorf("parse %s: %w", manifestYAMLName, err)
}
readJSONFile := func(rel, what string) ([]byte, error) {
if rel == "" {
return nil, nil
}
if err := fileWithin(dir, rel); err != nil {
return nil, fmt.Errorf("%s: %s: %w", manifestYAMLName, what, err)
}
b, err := os.ReadFile(filepath.Join(dir, rel))
if err != nil {
return nil, fmt.Errorf("%s: %s: %w", manifestYAMLName, what, err)
}
if !json.Valid(b) {
return nil, fmt.Errorf("%s: %s %s is not valid JSON", manifestYAMLName, what, rel)
}
return b, nil
}
// Only overwrite a field when manifest.yaml actually declares it. For a
// codeless build the manifest starts empty, so an undeclared key leaving the
// field at its proto zero is identical to the old unconditional assignment.
// For a mixed-form wasm build the manifest already carries the guest's
// DESCRIBE output, so these guards are what keep an undeclared key from
// WIPING a guest-populated field (theme_presets/bundled_fonts/etc.) —
// declarative keys supplement/override, they never clear (WO-WZ-021).
if my.ThemePresets != "" {
if m.ThemePresets, err = readJSONFile(my.ThemePresets, "theme_presets"); err != nil {
return err
}
}
if my.BundledFonts != "" {
if m.BundledFonts, err = readJSONFile(my.BundledFonts, "bundled_fonts"); err != nil {
return err
}
}
if my.SettingsSchema != "" {
if m.SettingsSchema, err = readJSONFile(my.SettingsSchema, "settings_schema"); err != nil {
return err
}
}
if len(my.RequiredIconPacks) > 0 {
m.RequiredIconPacks = my.RequiredIconPacks
}
if my.CSS != nil {
m.CssManifest = &abiv1.CssManifest{
NpmPackages: my.CSS.NpmPackages,
CssDirectives: my.CSS.CSSDirectives,
InputCssAppend: my.CSS.InputCSSAppend,
}
}
for _, d := range my.Dependencies {
m.Dependencies = append(m.Dependencies, &abiv1.Dependency{
Plugin: d.Plugin, MinVersion: d.MinVersion, Required: d.Required,
})
}
for _, st := range my.SystemTemplates {
if st.Key == "" || st.Title == "" {
return fmt.Errorf("%s: system_templates entries need key and title", manifestYAMLName)
}
m.SystemTemplates = append(m.SystemTemplates, &abiv1.SystemTemplateMeta{
Key: st.Key, Title: st.Title, Description: st.Description,
})
}
for _, pt := range my.PageTemplates {
if pt.System == "" || pt.Key == "" || pt.Title == "" {
return fmt.Errorf("%s: page_templates entries need system, key, and title", manifestYAMLName)
}
// Layout source convention: templates/<system>/<key>.ninjatpl,
// rendered host-side (core/docs/codeless-bnp.md).
rel := filepath.Join(dirTemplates, pt.System, pt.Key+".ninjatpl")
if err := fileWithin(dir, rel); err != nil {
return fmt.Errorf("%s: page template %s/%s: %w", manifestYAMLName, pt.System, pt.Key, err)
}
m.PageTemplates = append(m.PageTemplates, &abiv1.PageTemplateMeta{
SystemKey: pt.System, Key: pt.Key, Title: pt.Title,
Description: pt.Description, Slots: pt.Slots,
})
}
for _, to := range my.TemplateOverrides {
if to.Template == "" || to.Block == "" {
return fmt.Errorf("%s: template_overrides entries need template and block", manifestYAMLName)
}
rel := filepath.Join(dirTemplates, "overrides", to.Template, to.Block+".ninjatpl")
if err := fileWithin(dir, rel); err != nil {
return fmt.Errorf("%s: template override %s/%s: %w", manifestYAMLName, to.Template, to.Block, err)
}
m.BlockTemplateOverrides = append(m.BlockTemplateOverrides, &abiv1.BlockTemplateOverride{
TemplateKey: to.Template, BlockKey: to.Block,
})
}
for _, ek := range my.EmailWrappers {
if ek == "" {
return fmt.Errorf("%s: email_wrappers entries must be non-empty system keys", manifestYAMLName)
}
rel := filepath.Join(dirTemplates, "email", ek+".ninjatpl")
if err := fileWithin(dir, rel); err != nil {
return fmt.Errorf("%s: email wrapper %s: %w", manifestYAMLName, ek, err)
}
m.EmailWrapperSystemKeys = append(m.EmailWrapperSystemKeys, ek)
}
if my.MasterPages != "" {
mpRaw, err := readJSONFile(my.MasterPages, "master_pages")
if err != nil {
return err
}
var mps []masterPageJSON
if err := json.Unmarshal(mpRaw, &mps); err != nil {
return fmt.Errorf("%s: master_pages %s: %w", manifestYAMLName, my.MasterPages, err)
}
for _, mp := range mps {
def := &abiv1.MasterPageDefinition{
Key: mp.Key, Title: mp.Title, PageTemplates: mp.PageTemplates,
}
for _, b := range mp.Blocks {
contentJSON, err := json.Marshal(b.Content)
if err != nil {
return fmt.Errorf("master page %q block %q: %w", mp.Key, b.BlockKey, err)
}
def.Blocks = append(def.Blocks, &abiv1.MasterPageBlock{
BlockKey: b.BlockKey, Title: b.Title, ContentJson: contentJSON,
HtmlContent: b.HTMLContent, Slot: b.Slot, SortOrder: b.SortOrder,
})
}
m.MasterPages = append(m.MasterPages, def)
}
}
return nil
}
// fileWithin ensures rel names an existing regular file inside root (no
// traversal escapes).
func fileWithin(root, rel string) error {
clean := filepath.Clean(rel)
if filepath.IsAbs(clean) || strings.HasPrefix(clean, "..") {
return fmt.Errorf("path %q escapes the plugin directory", rel)
}
fi, err := os.Stat(filepath.Join(root, clean))
if err != nil {
return fmt.Errorf("referenced file %q: %w", rel, err)
}
if !fi.Mode().IsRegular() {
return fmt.Errorf("referenced path %q is not a regular file", rel)
}
return nil
}

View File

@ -1,12 +1,12 @@
package bnp
import (
"context"
"os"
"path/filepath"
"testing"
abiv1 "git.dev.alexdunmow.com/block/pluginsdk/abi/v1"
sdkbnp "git.dev.alexdunmow.com/block/pluginsdk/bnp"
)
// writeFixture lays out a minimal codeless plugin repo.
@ -60,7 +60,7 @@ func TestCodelessBuildAndVerifyRoundTrip(t *testing.T) {
}
out := filepath.Join(t.TempDir(), "fixture-theme-0.1.0.bnp")
res, err := BuildCodeless(context.Background(), BuildOptions{Dir: dir, Output: out})
res, err := sdkbnp.BuildCodeless(sdkbnp.BuildOptions{Dir: dir, Output: out})
if err != nil {
t.Fatalf("BuildCodeless: %v", err)
}
@ -112,61 +112,24 @@ func TestIsCodelessRepoFalseWithGoSource(t *testing.T) {
}
}
func TestCodelessBuildRejectsBadDeclarations(t *testing.T) {
cases := []struct {
name string
files map[string]string
}{
{"bad blocks yaml", map[string]string{
"plugin.mod": "[plugin]\nname = \"x\"\nversion = \"0.1.0\"\n",
"blocks/blocks.yaml": "blocks:\n - key: hero\n", // missing title/schema/template
}},
{"missing template file", map[string]string{
"plugin.mod": "[plugin]\nname = \"x\"\nversion = \"0.1.0\"\n",
"blocks/blocks.yaml": "blocks:\n - key: hero\n title: Hero\n" +
" schema: hero.schema.json\n template: missing.ninjatpl\n",
"blocks/hero.schema.json": `{}`,
}},
{"seed media without id", map[string]string{
"plugin.mod": "[plugin]\nname = \"x\"\nversion = \"0.1.0\"\n",
"seed/seed.json": `{"media":[{"file":"a.jpg"}]}`,
"seed/a.jpg": "x",
}},
{"data_dir grant", map[string]string{
"plugin.mod": "[plugin]\nname = \"x\"\nversion = \"0.1.0\"\ndata_dir = true\n",
}},
{"public_routes claim", map[string]string{
"plugin.mod": "[plugin]\nname = \"x\"\nversion = \"0.1.0\"\n" +
"public_routes = [{ path = \"/area\", prefix = true }]\n",
}},
{"sitemap flag", map[string]string{
"plugin.mod": "[plugin]\nname = \"x\"\nversion = \"0.1.0\"\nsitemap = true\n",
}},
{"override missing template file", map[string]string{
"plugin.mod": "[plugin]\nname = \"x\"\nversion = \"0.1.0\"\n",
"manifest.yaml": "template_overrides:\n - template: x\n block: heading\n",
}},
{"override missing block key", map[string]string{
"plugin.mod": "[plugin]\nname = \"x\"\nversion = \"0.1.0\"\n",
"manifest.yaml": "template_overrides:\n - template: x\n",
"templates/overrides/x/heading.ninjatpl": `<h1>{{ text }}</h1>`,
}},
{"email wrapper missing template file", map[string]string{
"plugin.mod": "[plugin]\nname = \"x\"\nversion = \"0.1.0\"\n",
"manifest.yaml": "email_wrappers: [x]\n",
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
writeFixture(t, dir, tc.files)
_, err := BuildCodeless(context.Background(), BuildOptions{
Dir: dir, Output: filepath.Join(t.TempDir(), "x.bnp"),
func TestVerifyCountsCodelessPresentationMembers(t *testing.T) {
dir := codelessFixture(t)
writeFixture(t, dir, map[string]string{
"preview.png": "not-really-png-but-bytes",
"screenshots/01-home.png": "home-bytes",
"screenshots/02-blog.jpg": "blog-bytes",
"screenshots/03-page.webp": "page-bytes",
})
if err == nil {
t.Fatal("BuildCodeless succeeded; want error")
out := filepath.Join(t.TempDir(), "fixture-theme-0.1.0.bnp")
if _, err := sdkbnp.BuildCodeless(sdkbnp.BuildOptions{Dir: dir, Output: out}); err != nil {
t.Fatalf("BuildCodeless: %v", err)
}
})
v, err := Verify(out)
if err != nil {
t.Fatalf("Verify: %v", err)
}
if !v.HasPreview || v.ScreenshotCount != 3 {
t.Errorf("verify preview=%t screenshots=%d; want true/3", v.HasPreview, v.ScreenshotCount)
}
}

View File

@ -7,6 +7,7 @@ import (
"testing"
abiv1 "git.dev.alexdunmow.com/block/pluginsdk/abi/v1"
sdkbnp "git.dev.alexdunmow.com/block/pluginsdk/bnp"
"google.golang.org/protobuf/proto"
)
@ -51,10 +52,10 @@ func TestVerifyRejectsDuplicateLoadOnceKeys(t *testing.T) {
t.Fatalf("marshal manifest: %v", err)
}
out := filepath.Join(t.TempDir(), "fixture.bnp")
_, err = packArtifact(out, []packEntry{
_, err = packArtifact(out, nil, []sdkbnp.Entry{
{ArtifactPath: fileWasm, Data: []byte("wasm")},
{ArtifactPath: fileMod, Data: []byte("[plugin]\nname = \"fixture\"\nversion = \"1.0.0\"\n")},
{ArtifactPath: fileManifest, Data: manifestBytes},
{ArtifactPath: sdkbnp.FileMod, Data: []byte("[plugin]\nname = \"fixture\"\nversion = \"1.0.0\"\n")},
{ArtifactPath: sdkbnp.FileManifest, Data: manifestBytes},
})
if err != nil {
t.Fatalf("pack artifact: %v", err)

View File

@ -6,6 +6,7 @@ import (
"testing"
abiv1 "git.dev.alexdunmow.com/block/pluginsdk/abi/v1"
sdkbnp "git.dev.alexdunmow.com/block/pluginsdk/bnp"
"google.golang.org/protobuf/proto"
)
@ -96,10 +97,10 @@ func TestVerifyRejectsMCPDescriptorsWithoutRuntimeHandler(t *testing.T) {
t.Fatalf("marshal manifest: %v", err)
}
out := filepath.Join(t.TempDir(), "wiki.bnp")
_, err = packArtifact(out, []packEntry{
_, err = packArtifact(out, nil, []sdkbnp.Entry{
{ArtifactPath: fileWasm, Data: []byte("wasm")},
{ArtifactPath: fileMod, Data: []byte("[plugin]\nname = \"wiki\"\nscope = \"@ninja\"\nversion = \"0.1.12\"\n")},
{ArtifactPath: fileManifest, Data: manifestBytes},
{ArtifactPath: sdkbnp.FileMod, Data: []byte("[plugin]\nname = \"wiki\"\nscope = \"@ninja\"\nversion = \"0.1.12\"\n")},
{ArtifactPath: sdkbnp.FileManifest, Data: manifestBytes},
})
if err != nil {
t.Fatalf("pack artifact: %v", err)

View File

@ -1,79 +0,0 @@
package bnp
import (
"testing"
abiv1 "git.dev.alexdunmow.com/block/pluginsdk/abi/v1"
)
// TestApplyManifestYAMLSupplementsWithoutWiping proves the WO-WZ-021 mixed-form
// builder semantics: folding manifest.yaml onto a manifest that already carries
// guest DESCRIBE output SUPPLEMENTS the declarative surfaces and OVERRIDES only
// the keys it actually declares — an undeclared scalar key never wipes a
// guest-populated field.
func TestApplyManifestYAMLSupplementsWithoutWiping(t *testing.T) {
dir := t.TempDir()
writeFixture(t, dir, map[string]string{
"manifest.yaml": "" +
"bundled_fonts: fonts.json\n" +
"page_templates:\n" +
" - {system: blog, key: listing, title: Listing}\n" +
"email_wrappers: [newsletter]\n",
"fonts.json": `{"fonts":["Inter"]}`,
"templates/blog/listing.ninjatpl": `<main>{{ title }}</main>`,
"templates/email/newsletter.ninjatpl": `<table>{{ body|safe }}</table>`,
})
// Simulate a guest DESCRIBE result: theme_presets set by the guest, plus a
// guest-rendered page template the manifest.yaml does NOT list.
m := &abiv1.PluginManifest{
AbiVersion: 1,
Name: "fixture-mixed",
Version: "0.1.0",
ThemePresets: []byte(`{"guest":true}`),
PageTemplates: []*abiv1.PageTemplateMeta{
{SystemKey: "blog", Key: "guestonly", Title: "Guest Only"},
},
}
if err := applyManifestYAML(dir, m); err != nil {
t.Fatalf("applyManifestYAML: %v", err)
}
// Undeclared theme_presets must be PRESERVED, not wiped to nil.
if string(m.ThemePresets) != `{"guest":true}` {
t.Errorf("theme_presets wiped/altered: %q", string(m.ThemePresets))
}
// Declared bundled_fonts folded in.
if string(m.BundledFonts) != `{"fonts":["Inter"]}` {
t.Errorf("bundled_fonts = %q", string(m.BundledFonts))
}
// Declared page template appended alongside the guest one (2 total).
if len(m.PageTemplates) != 2 {
t.Fatalf("page templates = %d, want 2 (guest + declarative)", len(m.PageTemplates))
}
// Declared email wrapper folded in.
if len(m.EmailWrapperSystemKeys) != 1 || m.EmailWrapperSystemKeys[0] != "newsletter" {
t.Errorf("email wrappers = %v", m.EmailWrapperSystemKeys)
}
}
// TestWasmBuildFoldsManifestYAML end-to-end: a repo with Go source AND a
// manifest.yaml builds a (non-codeless) wasm artifact whose manifest.pb carries
// the folded declarative surfaces. The absence of a manifest.yaml is a no-op —
// covered by every existing wasm build test.
func TestApplyManifestYAMLNoFileIsNoop(t *testing.T) {
dir := t.TempDir() // no manifest.yaml
m := &abiv1.PluginManifest{
AbiVersion: 1,
Name: "fixture-pure",
Version: "0.1.0",
ThemePresets: []byte(`{"guest":true}`),
}
if err := applyManifestYAML(dir, m); err != nil {
t.Fatalf("applyManifestYAML (no file): %v", err)
}
if string(m.ThemePresets) != `{"guest":true}` {
t.Errorf("no-manifest.yaml build mutated the manifest: %q", string(m.ThemePresets))
}
}

View File

@ -1,138 +1,20 @@
package bnp
import (
"archive/tar"
"fmt"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"github.com/klauspost/compress/zstd"
sdkbnp "git.dev.alexdunmow.com/block/pluginsdk/bnp"
)
// packEntry is one file destined for the artifact: its path inside the .bnp
// (always forward-slash relative) and either literal Data or a Source file to
// stream from.
type packEntry struct {
ArtifactPath string
Data []byte
Source string
}
// packArtifact writes entries as a zstd-compressed tar to outPath. Entries are
// sorted by artifact path for a deterministic archive. Directory entries are
// synthesized as needed so the reader's dirExists checks fire for
// migrations/, schemas/, assets/, web/.
func packArtifact(outPath string, entries []packEntry) (int64, error) {
sort.Slice(entries, func(i, j int) bool { return entries[i].ArtifactPath < entries[j].ArtifactPath })
// packArtifact writes entries as a .bnp to outPath, reading Source entries
// from fsys.
func packArtifact(outPath string, fsys fs.FS, entries []sdkbnp.Entry) (int64, error) {
out, err := os.Create(outPath)
if err != nil {
return 0, fmt.Errorf("create %s: %w", outPath, err)
}
defer func() { _ = out.Close() }()
enc, err := zstd.NewWriter(out, zstd.WithEncoderLevel(zstd.SpeedDefault))
if err != nil {
return 0, err
}
tw := tar.NewWriter(enc)
seenDir := map[string]bool{}
writeDir := func(dir string) error {
if dir == "" || dir == "." || seenDir[dir] {
return nil
}
seenDir[dir] = true
return tw.WriteHeader(&tar.Header{
Name: dir + "/",
Typeflag: tar.TypeDir,
Mode: 0o755,
})
}
var total int64
for _, e := range entries {
name := filepath.ToSlash(e.ArtifactPath)
// Ensure parent directories exist as explicit entries.
for _, d := range parentDirs(name) {
if err := writeDir(d); err != nil {
return 0, fmt.Errorf("write dir header %q: %w", d, err)
}
}
var data []byte
if e.Source != "" {
data, err = os.ReadFile(e.Source)
if err != nil {
return 0, fmt.Errorf("read %s: %w", e.Source, err)
}
} else {
data = e.Data
}
if err := tw.WriteHeader(&tar.Header{
Name: name,
Typeflag: tar.TypeReg,
Mode: 0o644,
Size: int64(len(data)),
}); err != nil {
return 0, fmt.Errorf("write header %q: %w", name, err)
}
if _, err := tw.Write(data); err != nil {
return 0, fmt.Errorf("write %q: %w", name, err)
}
total += int64(len(data))
}
if err := tw.Close(); err != nil {
return 0, fmt.Errorf("close tar: %w", err)
}
if err := enc.Close(); err != nil {
return 0, fmt.Errorf("close zstd: %w", err)
}
return total, nil
}
// parentDirs returns the ancestor directories of a forward-slash path, from
// shallowest to deepest ("a/b/c.txt" → ["a", "a/b"]).
func parentDirs(name string) []string {
var dirs []string
parts := strings.Split(name, "/")
for i := 1; i < len(parts); i++ {
dirs = append(dirs, strings.Join(parts[:i], "/"))
}
return dirs
}
// collectDir returns pack entries for every regular file under root, mapped
// under artifactPrefix. Symlinks and irregular files are skipped. Returns
// (entries, hadFiles).
func collectDir(root, artifactPrefix string) ([]packEntry, bool, error) {
info, err := os.Stat(root)
if err != nil || !info.IsDir() {
return nil, false, nil //nolint:nilerr // absent optional dir is not an error
}
var entries []packEntry
walkErr := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() || !d.Type().IsRegular() {
return nil
}
rel, err := filepath.Rel(root, path)
if err != nil {
return err
}
entries = append(entries, packEntry{
ArtifactPath: artifactPrefix + "/" + filepath.ToSlash(rel),
Source: path,
})
return nil
})
if walkErr != nil {
return nil, false, fmt.Errorf("walk %s: %w", root, walkErr)
}
return entries, len(entries) > 0, nil
return sdkbnp.Pack(out, fsys, entries)
}

View File

@ -1,121 +0,0 @@
package bnp
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
)
// Presentation members: a root preview.png plus an optional screenshots/ dir.
// Neither ships behavior — the registry ingests them at publish into the
// plugin's managed gallery (spec 2026-07-05-registry-presentation-reviews).
// The .so-era source archives carried preview.png implicitly; the .bnp
// packers dropped it, which silently wiped previews on republish — these
// entries restore that and add the multi-screenshot surface.
const (
filePreview = "preview.png"
dirScreenshots = "screenshots"
// maxScreenshotBytes caps one presentation image (registry gallery cap).
maxScreenshotBytes = 8 << 20
// maxScreenshotFiles caps the screenshots/ dir (registry gallery cap).
maxScreenshotFiles = 12
)
// screenshotExtOK reports whether a filename carries an accepted gallery
// image extension.
func screenshotExtOK(name string) bool {
switch strings.ToLower(filepath.Ext(name)) {
case ".png", ".jpg", ".jpeg", ".webp":
return true
}
return false
}
// validateScreenshotsDir checks the optional screenshots/ dir: accepted
// extensions only, ≤ maxScreenshotBytes per file, ≤ maxScreenshotFiles total,
// no subdirectories or irregular files. Returns the file count (0 when the
// dir is absent).
func validateScreenshotsDir(dir string) (int, error) {
root := filepath.Join(dir, dirScreenshots)
info, err := os.Stat(root)
if os.IsNotExist(err) {
return 0, nil
}
if err != nil {
return 0, fmt.Errorf("stat %s/: %w", dirScreenshots, err)
}
if !info.IsDir() {
return 0, fmt.Errorf("%s exists but is not a directory", dirScreenshots)
}
entries, err := os.ReadDir(root)
if err != nil {
return 0, fmt.Errorf("read %s/: %w", dirScreenshots, err)
}
count := 0
for _, e := range entries {
if e.IsDir() {
return 0, fmt.Errorf("%s/%s: subdirectories are not allowed in screenshots/", dirScreenshots, e.Name())
}
fi, err := e.Info()
if err != nil {
return 0, fmt.Errorf("%s/%s: %w", dirScreenshots, e.Name(), err)
}
if !fi.Mode().IsRegular() {
return 0, fmt.Errorf("%s/%s: not a regular file", dirScreenshots, e.Name())
}
if !screenshotExtOK(e.Name()) {
return 0, fmt.Errorf("%s/%s: unsupported image type (allowed: .png .jpg .jpeg .webp)", dirScreenshots, e.Name())
}
if fi.Size() > maxScreenshotBytes {
return 0, fmt.Errorf("%s/%s: %d bytes exceeds the %d MB per-image cap", dirScreenshots, e.Name(), fi.Size(), maxScreenshotBytes>>20)
}
count++
}
if count > maxScreenshotFiles {
return 0, fmt.Errorf("%s/ holds %d images; the gallery cap is %d", dirScreenshots, count, maxScreenshotFiles)
}
return count, nil
}
// presentationEntries validates and returns pack entries for the optional
// root preview.png and screenshots/ dir. Both are optional; absence is not an
// error.
func presentationEntries(dir string) (entries []packEntry, previewIncluded bool, screenshotCount int, err error) {
previewPath := filepath.Join(dir, filePreview)
if fi, statErr := os.Stat(previewPath); statErr == nil {
if !fi.Mode().IsRegular() {
return nil, false, 0, fmt.Errorf("%s is not a regular file", filePreview)
}
if fi.Size() > maxScreenshotBytes {
return nil, false, 0, fmt.Errorf("%s: %d bytes exceeds the %d MB per-image cap", filePreview, fi.Size(), maxScreenshotBytes>>20)
}
entries = append(entries, packEntry{ArtifactPath: filePreview, Source: previewPath})
previewIncluded = true
}
screenshotCount, err = validateScreenshotsDir(dir)
if err != nil {
return nil, false, 0, err
}
if screenshotCount > 0 {
root := filepath.Join(dir, dirScreenshots)
files, readErr := os.ReadDir(root)
if readErr != nil {
return nil, false, 0, fmt.Errorf("read %s/: %w", dirScreenshots, readErr)
}
names := make([]string, 0, len(files))
for _, f := range files {
names = append(names, f.Name())
}
sort.Strings(names)
for _, name := range names {
entries = append(entries, packEntry{
ArtifactPath: dirScreenshots + "/" + name,
Source: filepath.Join(root, name),
})
}
}
return entries, previewIncluded, screenshotCount, nil
}

View File

@ -1,152 +0,0 @@
package bnp
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
// presentationFixture extends the codeless fixture with a root preview.png
// and a screenshots/ dir.
func presentationFixture(t *testing.T) string {
t.Helper()
dir := codelessFixture(t)
writeFixture(t, dir, map[string]string{
"preview.png": "not-really-png-but-bytes",
"screenshots/01-home.png": "home-bytes",
"screenshots/02-blog.jpg": "blog-bytes",
"screenshots/03-page.webp": "page-bytes",
})
return dir
}
func TestCodelessBuildPacksPresentationMembers(t *testing.T) {
dir := presentationFixture(t)
out := filepath.Join(t.TempDir(), "fixture-theme-0.1.0.bnp")
res, err := BuildCodeless(context.Background(), BuildOptions{Dir: dir, Output: out})
if err != nil {
t.Fatalf("BuildCodeless: %v", err)
}
if !res.PreviewIncluded || res.ScreenshotCount != 3 {
t.Errorf("result preview=%t screenshots=%d; want true/3", res.PreviewIncluded, res.ScreenshotCount)
}
found := false
for _, d := range res.IncludedDirs {
if d == dirScreenshots {
found = true
}
}
if !found {
t.Errorf("IncludedDirs %v missing %q", res.IncludedDirs, dirScreenshots)
}
v, err := Verify(out)
if err != nil {
t.Fatalf("Verify: %v", err)
}
if !v.HasPreview || v.ScreenshotCount != 3 {
t.Errorf("verify preview=%t screenshots=%d; want true/3", v.HasPreview, v.ScreenshotCount)
}
}
func TestCodelessBuildWithoutPresentationMembers(t *testing.T) {
dir := codelessFixture(t)
out := filepath.Join(t.TempDir(), "fixture-theme-0.1.0.bnp")
res, err := BuildCodeless(context.Background(), BuildOptions{Dir: dir, Output: out})
if err != nil {
t.Fatalf("BuildCodeless: %v", err)
}
if res.PreviewIncluded || res.ScreenshotCount != 0 {
t.Errorf("result preview=%t screenshots=%d; want false/0", res.PreviewIncluded, res.ScreenshotCount)
}
v, err := Verify(out)
if err != nil {
t.Fatalf("Verify: %v", err)
}
if v.HasPreview || v.ScreenshotCount != 0 {
t.Errorf("verify preview=%t screenshots=%d; want false/0", v.HasPreview, v.ScreenshotCount)
}
}
func TestValidateScreenshotsDirRejections(t *testing.T) {
build := func(t *testing.T, mutate func(dir string)) error {
t.Helper()
dir := codelessFixture(t)
mutate(dir)
out := filepath.Join(t.TempDir(), "out.bnp")
_, err := BuildCodeless(context.Background(), BuildOptions{Dir: dir, Output: out})
return err
}
t.Run("bad extension", func(t *testing.T) {
err := build(t, func(dir string) {
writeFixture(t, dir, map[string]string{"screenshots/readme.txt": "nope"})
})
if err == nil || !strings.Contains(err.Error(), "unsupported image type") {
t.Fatalf("err = %v; want unsupported image type", err)
}
})
t.Run("subdirectory", func(t *testing.T) {
err := build(t, func(dir string) {
writeFixture(t, dir, map[string]string{"screenshots/sub/x.png": "nope"})
})
if err == nil || !strings.Contains(err.Error(), "subdirectories are not allowed") {
t.Fatalf("err = %v; want subdirectory rejection", err)
}
})
t.Run("too many", func(t *testing.T) {
err := build(t, func(dir string) {
files := map[string]string{}
for i := range maxScreenshotFiles + 1 {
files[fmt.Sprintf("screenshots/%02d.png", i)] = "x"
}
writeFixture(t, dir, files)
})
if err == nil || !strings.Contains(err.Error(), "gallery cap") {
t.Fatalf("err = %v; want gallery cap rejection", err)
}
})
t.Run("oversized image", func(t *testing.T) {
err := build(t, func(dir string) {
big := filepath.Join(dir, dirScreenshots, "big.png")
if mkErr := os.MkdirAll(filepath.Dir(big), 0o755); mkErr != nil {
t.Fatal(mkErr)
}
f, cErr := os.Create(big)
if cErr != nil {
t.Fatal(cErr)
}
if tErr := f.Truncate(maxScreenshotBytes + 1); tErr != nil {
t.Fatal(tErr)
}
_ = f.Close()
})
if err == nil || !strings.Contains(err.Error(), "per-image cap") {
t.Fatalf("err = %v; want per-image cap rejection", err)
}
})
t.Run("oversized preview", func(t *testing.T) {
err := build(t, func(dir string) {
big := filepath.Join(dir, filePreview)
f, cErr := os.Create(big)
if cErr != nil {
t.Fatal(cErr)
}
if tErr := f.Truncate(maxScreenshotBytes + 1); tErr != nil {
t.Fatal(tErr)
}
_ = f.Close()
})
if err == nil || !strings.Contains(err.Error(), "per-image cap") {
t.Fatalf("err = %v; want per-image cap rejection", err)
}
})
}

View File

@ -13,6 +13,7 @@ import (
"strings"
abiv1 "git.dev.alexdunmow.com/block/pluginsdk/abi/v1"
sdkbnp "git.dev.alexdunmow.com/block/pluginsdk/bnp"
"github.com/klauspost/compress/zstd"
"google.golang.org/protobuf/proto"
)
@ -75,13 +76,13 @@ func Verify(bnpPath string) (*VerifyResult, error) {
return nil, err
}
for _, req := range []string{fileMod, fileManifest} {
for _, req := range []string{sdkbnp.FileMod, sdkbnp.FileManifest} {
if !fileRegular(filepath.Join(destDir, req)) {
return nil, fmt.Errorf("bnp: artifact missing required %s", req)
}
}
manifestBytes, err := os.ReadFile(filepath.Join(destDir, fileManifest))
manifestBytes, err := os.ReadFile(filepath.Join(destDir, sdkbnp.FileManifest))
if err != nil {
return nil, fmt.Errorf("bnp: read manifest.pb: %w", err)
}
@ -110,7 +111,7 @@ func Verify(bnpPath string) (*VerifyResult, error) {
return nil, errors.New("bnp: manifest has empty name")
}
modBytes, err := os.ReadFile(filepath.Join(destDir, fileMod))
modBytes, err := os.ReadFile(filepath.Join(destDir, sdkbnp.FileMod))
if err != nil {
return nil, fmt.Errorf("bnp: read plugin.mod: %w", err)
}
@ -139,11 +140,11 @@ func Verify(bnpPath string) (*VerifyResult, error) {
HasSchemas: dirExists(filepath.Join(destDir, "schemas")),
HasAssets: dirExists(filepath.Join(destDir, "assets")),
HasWeb: dirExists(filepath.Join(destDir, "web")),
HasBlocks: dirExists(filepath.Join(destDir, dirBlocks)),
HasTemplates: dirExists(filepath.Join(destDir, dirTemplates)),
HasSeed: dirExists(filepath.Join(destDir, dirSeed)),
HasPreview: fileRegular(filepath.Join(destDir, filePreview)),
ScreenshotCount: countScreenshots(filepath.Join(destDir, dirScreenshots)),
HasBlocks: dirExists(filepath.Join(destDir, sdkbnp.DirBlocks)),
HasTemplates: dirExists(filepath.Join(destDir, sdkbnp.DirTemplates)),
HasSeed: dirExists(filepath.Join(destDir, sdkbnp.DirSeed)),
HasPreview: fileRegular(filepath.Join(destDir, sdkbnp.FilePreview)),
ScreenshotCount: countScreenshots(filepath.Join(destDir, sdkbnp.DirScreenshots)),
}, nil
}
@ -156,7 +157,7 @@ func countScreenshots(root string) int {
}
n := 0
for _, e := range entries {
if !e.IsDir() && screenshotExtOK(e.Name()) {
if !e.IsDir() && sdkbnp.ScreenshotExtOK(e.Name()) {
n++
}
}
@ -217,7 +218,7 @@ func ReadManifest(bnpPath string) (*abiv1.PluginManifest, error) {
if err := extractTarZst(f, destDir); err != nil {
return nil, err
}
b, err := os.ReadFile(filepath.Join(destDir, fileManifest))
b, err := os.ReadFile(filepath.Join(destDir, sdkbnp.FileManifest))
if err != nil {
return nil, fmt.Errorf("bnp: read manifest.pb: %w", err)
}