blockprint 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -58,6 +58,14 @@ Renders a config against a registry. `config` is `unknown` on purpose — the ou
58
58
 
59
59
  The default fallback renders a warning box in development and `null` in production — a page that wants visible failure in production must pass its own `fallback`.
60
60
 
61
+ Fail-soft options:
62
+
63
+ - `onFallback={(info) => …}` — telemetry hook for entries that fall back (reason, type, props, index). Invoked synchronously so it works in Server Components, and deduped per Renderer instance on `(reason, type, index)` — unstable config identities don't re-fire it. Expect one call per environment (server + hydration) and possible doubling under StrictMode in development.
64
+ - `invalidConfigFallback={<ErrorState />}` — rendered instead of throwing when the outer config shape is invalid. Without it the Renderer throws `ConfigError`, so boundary-less apps fail loudly rather than silently blank.
65
+ - `catchBlockErrors` — wraps each block in an error boundary: a block that throws while rendering becomes a `render-error` fallback instead of taking the page down, and recovers when its entry changes. **Client-side containment only**: React error boundaries do not catch during server rendering and do not exist in Server Components (enabling this there throws a descriptive error); SSR totality remains your blocks' responsibility.
66
+
67
+ > **Upgrading from ≤ 0.2**: `FallbackProps` gained a third member, `{ reason: "render-error", error }`. Custom fallbacks that narrowed with a two-way ternary must handle it — switch on `reason` exhaustively. See [CHANGELOG](https://github.com/terzidest/blockprint/blob/main/CHANGELOG.md).
68
+
61
69
  The optional `wrapBlock={(node, entry, index) => …}` prop wraps every rendered entry — blocks and fallbacks alike — with access to the config entry and its index. This is the hook point for visual-editing overlays, analytics boundaries, or per-block chrome.
62
70
 
63
71
  A common recipe — shared section chrome, deep-link anchors, and analytics attributes in one place instead of repeated in every block:
@@ -84,6 +92,58 @@ Rendering and schema validation are memoised per `(config, registry)` identity
84
92
 
85
93
  The boundary validator, exported for consumers who want to fail at fetch time rather than render time. Throws `ConfigError` with the entry index and reason.
86
94
 
95
+ ### Manifests — block definitions without components
96
+
97
+ When more than one app needs to know your blocks (an admin, a server, tests), define them once, component-free, and join components only where rendering happens:
98
+
99
+ ```ts
100
+ // packages/blocks-contract — imports blockprint/config only, no React
101
+ import { defineBlock } from "blockprint/config";
102
+
103
+ export const hero = defineBlock({
104
+ schema: heroSchema, // required; the manifest's reason to exist
105
+ label: "Hero",
106
+ defaults: { title: "A headline…" }, // typed as the schema's INPUT
107
+ summary: (props) => props.title, // receives the schema's OUTPUT
108
+ fields: { title: { label: "Headline" } }, // shallow editor metadata, uninterpreted
109
+ });
110
+
111
+ export const manifest = { hero, categoryTiles, productStrip };
112
+ ```
113
+
114
+ ```tsx
115
+ // the rendering app — the only place components exist
116
+ import { createRegistry } from "blockprint";
117
+ import { manifest } from "@yours/blocks-contract";
118
+
119
+ const registry = createRegistry(manifest, {
120
+ hero: Hero,
121
+ categoryTiles: CategoryTiles,
122
+ productStrip: ProductStrip,
123
+ });
124
+ ```
125
+
126
+ The join is checked per key: a component requiring a prop its schema doesn't produce, a missing component, or an extra component are all compile errors on the offending key. Editors and servers import the manifest (labels, defaults, summaries, `InputOf`/`OutputOf` types) and never touch component modules.
127
+
128
+ ### `validateConfig(manifest, config)` — headless, total
129
+
130
+ Per-entry validation for save endpoints, tests, loaders, and editors. **Never throws:**
131
+
132
+ ```ts
133
+ import { validateConfig } from "blockprint/config";
134
+
135
+ const report = validateConfig(manifest, untrustedInput);
136
+ report.ok; // outer shape valid and no entry failed validation
137
+ report.error; // outer-shape failure message, if any
138
+ report.entries; // per entry: { ok: true, value } | { ok: false, reason, issues? }
139
+ report.unknownTypes; // distinct unregistered types — NOT counted as failure:
140
+ // unknown blocks are the renderer's fallback case, and
141
+ // whether to accept them is the caller's policy
142
+ report.duplicateIds; // ids appearing more than once
143
+ ```
144
+
145
+ The Renderer applies the same per-entry semantics, so what validates at save time is what renders.
146
+
87
147
  ### `blockprint/config` — the React-free entry point
88
148
 
89
149
  Backends that store and validate configs want exactly `parseConfig` and nothing React-shaped. The `blockprint/config` subpath exports `parseConfig`, `ConfigError`, and the `BlockConfig` / `StandardSchemaV1` types with **no React requirement** (the React peer dependency is marked optional):
@@ -1,5 +1,8 @@
1
1
  import type { ComponentType, ReactNode } from "react";
2
2
  import type { BlockConfig, BlocksShape, FallbackProps, Registry } from "./types.js";
3
+ export type FallbackInfo = FallbackProps & {
4
+ index: number;
5
+ };
3
6
  export interface RendererProps<T extends BlocksShape> {
4
7
  /** Untrusted input; the outer shape is validated internally. */
5
8
  config: unknown;
@@ -11,5 +14,29 @@ export interface RendererProps<T extends BlocksShape> {
11
14
  * overlays, analytics boundaries, or per-block chrome.
12
15
  */
13
16
  wrapBlock?: (node: ReactNode, entry: BlockConfig, index: number) => ReactNode;
17
+ /**
18
+ * Telemetry hook for entries that resolve to a fallback (and render errors
19
+ * caught by catchBlockErrors). Invoked synchronously so it works in Server
20
+ * Components, and deduped per Renderer instance on (reason, type, index) —
21
+ * so unstable config identities don't re-fire it. Expect one call per
22
+ * environment (server render + client hydration), and possible doubling
23
+ * under StrictMode in development.
24
+ */
25
+ onFallback?: (info: FallbackInfo) => void;
26
+ /**
27
+ * Rendered instead of throwing when the outer config shape is invalid.
28
+ * Without it, invalid outer shape throws ConfigError (the default, so
29
+ * boundary-less apps fail loudly rather than silently blank).
30
+ */
31
+ invalidConfigFallback?: ReactNode;
32
+ /**
33
+ * Wrap every block in an error boundary: a block that throws while
34
+ * rendering becomes a `render-error` fallback instead of taking the page
35
+ * down, and recovers when the entry changes. Client-side containment only —
36
+ * React error boundaries do not catch during server rendering, and class
37
+ * boundaries do not exist in Server Components, so enabling this outside a
38
+ * client environment throws a descriptive error.
39
+ */
40
+ catchBlockErrors?: boolean;
14
41
  }
15
- export declare function Renderer<T extends BlocksShape>({ config, registry, fallback, wrapBlock, }: RendererProps<T>): ReactNode;
42
+ export declare function Renderer<T extends BlocksShape>({ config, registry, fallback, wrapBlock, onFallback, invalidConfigFallback, catchBlockErrors, }: RendererProps<T>): ReactNode;
package/dist/Renderer.js CHANGED
@@ -1,10 +1,16 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { Fragment, useMemo } from "react";
3
- import { parseConfig } from "./parseConfig.js";
3
+ // Namespace import: React.Component must only be touched lazily — the
4
+ // react-server condition's build exports useMemo/Fragment but NOT Component,
5
+ // and the main entry must stay loadable from Server Components.
6
+ import * as React from "react";
7
+ import { parseConfig, ConfigError } from "./parseConfig.js";
8
+ import { validateProps } from "./validateProps.js";
4
9
  import { DefaultFallback } from "./fallback.js";
5
10
  import { isDev } from "./env.js";
6
- // StrictMode double-invokes render (and therefore the memo) in development;
7
- // remember what we've already warned about so each duplicate id logs once.
11
+ // Module-global on purpose: this is a config-authoring diagnostic, not a
12
+ // per-instance signal — a second Renderer repeating the same duplicate id
13
+ // will not re-warn. StrictMode double-invokes are deduped by the same set.
8
14
  const warnedDuplicateIds = new Set();
9
15
  // `memo`/`forwardRef` components are exotic objects, not functions, so the
10
16
  // bare-vs-definition split must discriminate on the `component` key.
@@ -14,7 +20,7 @@ function resolveDef(def) {
14
20
  }
15
21
  return { component: def };
16
22
  }
17
- function prepare(config, registry) {
23
+ function prepare(config, registry, emitFallback) {
18
24
  const entries = parseConfig(config);
19
25
  const seenKeys = new Set();
20
26
  return entries.map((entry, index) => {
@@ -27,78 +33,118 @@ function prepare(config, registry) {
27
33
  key = `${key}__dup${index}`;
28
34
  }
29
35
  seenKeys.add(key);
36
+ const toFallback = (fallbackProps) => {
37
+ emitFallback({ ...fallbackProps, index });
38
+ return { key, entry, kind: "fallback", fallbackProps };
39
+ };
30
40
  if (!Object.hasOwn(registry.blocks, entry.type)) {
31
- return {
32
- key,
33
- entry,
34
- kind: "fallback",
35
- fallbackProps: {
36
- reason: "unknown-type",
37
- type: entry.type,
38
- props: entry.props,
39
- },
40
- };
41
+ return toFallback({
42
+ reason: "unknown-type",
43
+ type: entry.type,
44
+ props: entry.props,
45
+ });
41
46
  }
42
47
  const { component, schema } = resolveDef(registry.blocks[entry.type]);
43
48
  if (!schema) {
44
- return {
45
- key,
46
- entry,
47
- kind: "block",
48
- component,
49
+ return { key, entry, kind: "block", component, props: entry.props };
50
+ }
51
+ const validation = validateProps(schema, entry.props);
52
+ if (!validation.ok) {
53
+ return toFallback({
54
+ reason: "invalid-props",
55
+ type: entry.type,
49
56
  props: entry.props,
50
- };
57
+ issues: validation.issues,
58
+ });
51
59
  }
52
- const result = schema["~standard"].validate(entry.props);
53
- // React render is synchronous; async schemas are a config mistake and
54
- // are contained like any other invalid block.
55
- if (result instanceof Promise) {
56
- return {
57
- key,
58
- entry,
59
- kind: "fallback",
60
- fallbackProps: {
61
- reason: "invalid-props",
62
- type: entry.type,
63
- props: entry.props,
64
- issues: [
65
- {
66
- message: "schema validated asynchronously; blockprint only supports synchronous schemas",
67
- },
68
- ],
69
- },
70
- };
60
+ return { key, entry, kind: "block", component, props: validation.value };
61
+ });
62
+ }
63
+ let LazyBoundary;
64
+ /**
65
+ * The boundary class is created on first use so React.Component is never
66
+ * touched at module load — the react-server build doesn't export it.
67
+ */
68
+ function getBlockBoundary() {
69
+ if (LazyBoundary)
70
+ return LazyBoundary;
71
+ const Base = React.Component;
72
+ if (typeof Base !== "function") {
73
+ throw new Error("blockprint: catchBlockErrors requires a client React environment — error boundaries are not available in Server Components");
74
+ }
75
+ class BlockBoundary extends Base {
76
+ state = { hasError: false };
77
+ static getDerivedStateFromError(error) {
78
+ return { hasError: true, error };
71
79
  }
72
- if (result.issues) {
73
- return {
74
- key,
75
- entry,
76
- kind: "fallback",
77
- fallbackProps: {
78
- reason: "invalid-props",
79
- type: entry.type,
80
- props: entry.props,
81
- issues: result.issues,
82
- },
83
- };
80
+ componentDidCatch(error) {
81
+ this.props.onError?.(error);
84
82
  }
85
- return {
86
- key,
87
- entry,
88
- kind: "block",
89
- component,
90
- props: result.value,
91
- };
92
- });
83
+ componentDidUpdate(previous) {
84
+ if (this.state.hasError && previous.resetKey !== this.props.resetKey) {
85
+ this.setState({ hasError: false, error: undefined });
86
+ }
87
+ }
88
+ render() {
89
+ return this.state.hasError
90
+ ? this.props.renderFallback(this.state.error)
91
+ : this.props.children;
92
+ }
93
+ }
94
+ LazyBoundary = BlockBoundary;
95
+ return LazyBoundary;
93
96
  }
94
- export function Renderer({ config, registry, fallback, wrapBlock, }) {
97
+ export function Renderer({ config, registry, fallback, wrapBlock, onFallback, invalidConfigFallback, catchBlockErrors, }) {
95
98
  const Fallback = fallback ?? DefaultFallback;
96
- // Parsing and schema validation run once per (config, registry) identity,
97
- // not on every render; a consumer recreating the config array each render
98
- // opts out of the caching, not the correctness.
99
- const prepared = useMemo(() => prepare(config, registry), [config, registry]);
100
- return prepared.map((item, index) => {
101
- const node = item.kind === "block" ? (_jsx(item.component, { ...item.props })) : (_jsx(Fallback, { ...item.fallbackProps }));
99
+ // Per-instance dedupe for onFallback: unstable config identities (inline
100
+ // arrays, `x ?? []`) re-run the memo, but telemetry fires at most once per
101
+ // (reason, type, index) for the life of this Renderer instance.
102
+ const firedFallbacks = useMemo(() => new Set(), []);
103
+ // Parsing and schema validation run once per (config, registry) identity.
104
+ // onFallback is deliberately not a dependency: it is only invoked inside a
105
+ // recompute, which always closes over the current render's value — listing
106
+ // it would defeat the memo for inline callbacks.
107
+ const prepared = useMemo(() => {
108
+ const emitFallback = (info) => {
109
+ const dedupeKey = `${info.reason}:${info.type}:${info.index}`;
110
+ if (firedFallbacks.has(dedupeKey))
111
+ return;
112
+ firedFallbacks.add(dedupeKey);
113
+ onFallback?.(info);
114
+ };
115
+ try {
116
+ return { entries: prepare(config, registry, emitFallback) };
117
+ }
118
+ catch (error) {
119
+ if (error instanceof ConfigError)
120
+ return { configError: error };
121
+ throw error;
122
+ }
123
+ // eslint-disable-next-line react-hooks/exhaustive-deps
124
+ }, [config, registry]);
125
+ if ("configError" in prepared) {
126
+ if (invalidConfigFallback !== undefined)
127
+ return invalidConfigFallback;
128
+ throw prepared.configError;
129
+ }
130
+ const Boundary = catchBlockErrors ? getBlockBoundary() : undefined;
131
+ return prepared.entries.map((item, index) => {
132
+ let node = item.kind === "block" ? (_jsx(item.component, { ...item.props })) : (_jsx(Fallback, { ...item.fallbackProps }));
133
+ if (Boundary && item.kind === "block") {
134
+ node = (_jsx(Boundary, { resetKey: item.entry, renderFallback: (error) => (_jsx(Fallback, { reason: "render-error", type: item.entry.type, props: item.entry.props, error: error })), onError: (error) => {
135
+ const dedupeKey = `render-error:${item.entry.type}:${index}`;
136
+ if (firedFallbacks.has(dedupeKey))
137
+ return;
138
+ firedFallbacks.add(dedupeKey);
139
+ onFallback?.({
140
+ reason: "render-error",
141
+ type: item.entry.type,
142
+ props: item.entry.props,
143
+ error,
144
+ index,
145
+ });
146
+ }, children: node }));
147
+ }
102
148
  // The key lives on a Fragment so it survives whatever wrapBlock returns.
103
149
  return (_jsx(Fragment, { children: wrapBlock ? wrapBlock(node, item.entry, index) : node }, item.key));
104
150
  });
@@ -0,0 +1,16 @@
1
+ /**
2
+ * React-free config types. Everything reachable from the `blockprint/config`
3
+ * entry must resolve without React's type definitions installed — keep this
4
+ * module (and its importers in config land) free of react imports, even
5
+ * type-only ones.
6
+ */
7
+ /**
8
+ * A single entry as it arrives from a CMS. Deliberately open: `type` is any
9
+ * string, because untrusted configs may contain types the registry has never
10
+ * seen — those route to the fallback instead of crashing.
11
+ */
12
+ export interface BlockConfig {
13
+ type: string;
14
+ props?: unknown;
15
+ id?: string | number;
16
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * React-free config types. Everything reachable from the `blockprint/config`
3
+ * entry must resolve without React's type definitions installed — keep this
4
+ * module (and its importers in config land) free of react imports, even
5
+ * type-only ones.
6
+ */
7
+ export {};
package/dist/config.d.ts CHANGED
@@ -1,9 +1,13 @@
1
1
  /**
2
- * React-free entry point (`blockprint/config`): the boundary validator and
3
- * config types, importable from Node backends without a React peer. Keep
4
- * this module (and its imports) free of React — servers validating stored
5
- * configs want exactly this and nothing more.
2
+ * React-free entry point (`blockprint/config`): the boundary validator, the
3
+ * manifest system, and headless config validation — importable from Node
4
+ * backends and editor apps without a React peer. Keep this module's import
5
+ * graph free of React, including type-only imports.
6
6
  */
7
7
  export { parseConfig, ConfigError } from "./parseConfig.js";
8
- export type { BlockConfig } from "./types.js";
8
+ export { defineBlock } from "./manifest.js";
9
+ export type { BlockDefinition, FieldMeta, FieldsFor, InputOf, Manifest, OutputOf, } from "./manifest.js";
10
+ export { validateConfig } from "./validateConfig.js";
11
+ export type { ValidatedEntry, ValidationReport } from "./validateConfig.js";
12
+ export type { BlockConfig } from "./block-config.js";
9
13
  export type { StandardSchemaV1 } from "./standard-schema.js";
package/dist/config.js CHANGED
@@ -1,7 +1,9 @@
1
1
  /**
2
- * React-free entry point (`blockprint/config`): the boundary validator and
3
- * config types, importable from Node backends without a React peer. Keep
4
- * this module (and its imports) free of React — servers validating stored
5
- * configs want exactly this and nothing more.
2
+ * React-free entry point (`blockprint/config`): the boundary validator, the
3
+ * manifest system, and headless config validation — importable from Node
4
+ * backends and editor apps without a React peer. Keep this module's import
5
+ * graph free of React, including type-only imports.
6
6
  */
7
7
  export { parseConfig, ConfigError } from "./parseConfig.js";
8
+ export { defineBlock } from "./manifest.js";
9
+ export { validateConfig } from "./validateConfig.js";
@@ -1,6 +1,7 @@
1
1
  import type { ComponentType } from "react";
2
2
  import type { StandardSchemaV1 } from "./standard-schema.js";
3
3
  import type { BlocksShape, Registry } from "./types.js";
4
+ import type { Manifest, OutputOf } from "./manifest.js";
4
5
  /**
5
6
  * Maps every compatible entry to `unknown` (an identity when intersected) and
6
7
  * every entry whose schema output is not assignable to its component's props
@@ -15,4 +16,23 @@ export type ValidateBlocks<T extends BlocksShape> = {
15
16
  schema: `schema output is not assignable to props of '${K & string}'`;
16
17
  } : unknown;
17
18
  };
19
+ /**
20
+ * One component per manifest key, each able to accept its schema's output.
21
+ * Contravariance does the per-key checking: a component requiring a prop the
22
+ * schema doesn't produce fails on that key.
23
+ */
24
+ export type ComponentsFor<M extends Manifest> = {
25
+ [K in keyof M]: ComponentType<OutputOf<M[K]>>;
26
+ };
27
+ /** Rejects component keys that have no manifest entry. */
28
+ export type NoExtraComponents<C, M> = {
29
+ [K in Exclude<keyof C, keyof M>]: never;
30
+ };
31
+ export type JoinedShape<M extends Manifest, C extends ComponentsFor<M>> = {
32
+ [K in keyof M]: {
33
+ component: C[K];
34
+ schema: M[K]["schema"];
35
+ };
36
+ };
18
37
  export declare function createRegistry<T extends BlocksShape>(blocks: T & ValidateBlocks<T>): Registry<T>;
38
+ export declare function createRegistry<M extends Manifest, C extends ComponentsFor<M>>(manifest: M, components: C & NoExtraComponents<C, M>): Registry<JoinedShape<M, C>>;
@@ -1,3 +1,17 @@
1
- export function createRegistry(blocks) {
1
+ export function createRegistry(first, components) {
2
+ if (components === undefined) {
3
+ return { blocks: first };
4
+ }
5
+ const blocks = {};
6
+ for (const key of Object.keys(first)) {
7
+ const component = components[key];
8
+ if (component === undefined) {
9
+ throw new Error(`createRegistry: no component provided for manifest block '${key}'`);
10
+ }
11
+ blocks[key] = {
12
+ component,
13
+ schema: first[key].schema,
14
+ };
15
+ }
2
16
  return { blocks: blocks };
3
17
  }
package/dist/env.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  /**
2
2
  * True outside production builds. Guarded so a browser without a bundler
3
- * defining `process` gets `false` instead of a ReferenceError.
3
+ * defining `process` gets `false` instead of a ReferenceError — deliberately
4
+ * fail-quiet: a bundler-less browser is treated as production (silent
5
+ * default fallback, no dev warnings).
4
6
  */
5
7
  export declare function isDev(): boolean;
package/dist/env.js CHANGED
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * True outside production builds. Guarded so a browser without a bundler
3
- * defining `process` gets `false` instead of a ReferenceError.
3
+ * defining `process` gets `false` instead of a ReferenceError — deliberately
4
+ * fail-quiet: a bundler-less browser is treated as production (silent
5
+ * default fallback, no dev warnings).
4
6
  */
5
7
  export function isDev() {
6
8
  return typeof process !== "undefined" && process.env.NODE_ENV !== "production";
package/dist/fallback.js CHANGED
@@ -6,7 +6,11 @@ export function DefaultFallback(props) {
6
6
  }
7
7
  const detail = props.reason === "invalid-props"
8
8
  ? props.issues.map((issue) => issue.message).join("; ")
9
- : "no component registered for this type";
9
+ : props.reason === "render-error"
10
+ ? props.error instanceof Error
11
+ ? props.error.message
12
+ : String(props.error)
13
+ : "no component registered for this type";
10
14
  return (_jsxs("div", { role: "note", style: {
11
15
  border: "1px dashed #c00",
12
16
  borderRadius: 4,
package/dist/index.d.ts CHANGED
@@ -1,6 +1,11 @@
1
1
  export { createRegistry } from "./createRegistry.js";
2
2
  export { Renderer } from "./Renderer.js";
3
- export type { RendererProps } from "./Renderer.js";
3
+ export type { RendererProps, FallbackInfo } from "./Renderer.js";
4
4
  export { parseConfig, ConfigError } from "./parseConfig.js";
5
+ export { defineBlock } from "./manifest.js";
6
+ export type { BlockDefinition, FieldMeta, FieldsFor, InputOf, Manifest, OutputOf, } from "./manifest.js";
7
+ export { validateConfig } from "./validateConfig.js";
8
+ export type { ValidatedEntry, ValidationReport } from "./validateConfig.js";
9
+ export type { ComponentsFor, JoinedShape } from "./createRegistry.js";
5
10
  export type { BlockConfig, BlockDef, BlocksShape, ConfigFor, FallbackProps, InputFor, PropsFor, Registry, } from "./types.js";
6
11
  export type { StandardSchemaV1 } from "./standard-schema.js";
package/dist/index.js CHANGED
@@ -1,3 +1,5 @@
1
1
  export { createRegistry } from "./createRegistry.js";
2
2
  export { Renderer } from "./Renderer.js";
3
3
  export { parseConfig, ConfigError } from "./parseConfig.js";
4
+ export { defineBlock } from "./manifest.js";
5
+ export { validateConfig } from "./validateConfig.js";
@@ -0,0 +1,43 @@
1
+ import type { StandardSchemaV1 } from "./standard-schema.js";
2
+ /**
3
+ * Editor metadata for one field of a block's input. blockprint stores this
4
+ * and does not interpret it — form generation decides what the keys mean.
5
+ * Shallow by design: nested paths are out of scope.
6
+ */
7
+ export interface FieldMeta {
8
+ label?: string;
9
+ help?: string;
10
+ widget?: string;
11
+ [key: string]: unknown;
12
+ }
13
+ export type FieldsFor<S extends StandardSchemaV1> = StandardSchemaV1.InferInput<S> extends Record<string, any> ? {
14
+ [K in keyof StandardSchemaV1.InferInput<S> & string]?: FieldMeta;
15
+ } : never;
16
+ /**
17
+ * A component-free block definition: everything an admin, a server, or a
18
+ * test needs to know about a block, importable without the component.
19
+ */
20
+ export interface BlockDefinition<S extends StandardSchemaV1 = StandardSchemaV1> {
21
+ readonly schema: S;
22
+ /** Display name; falls back to the manifest key. */
23
+ readonly label?: string;
24
+ /** Starting props for a newly inserted block, in the schema's INPUT shape. */
25
+ readonly defaults?: StandardSchemaV1.InferInput<S>;
26
+ /** One-line description of an instance, from the schema's OUTPUT shape. */
27
+ readonly summary?: (props: StandardSchemaV1.InferOutput<S>) => string;
28
+ readonly fields?: FieldsFor<S>;
29
+ /** Reserved for future migration tooling. */
30
+ readonly version?: number;
31
+ }
32
+ export type Manifest = Record<string, BlockDefinition<any>>;
33
+ /** The rendered/validated props of a definition (schema OUTPUT). */
34
+ export type OutputOf<D extends BlockDefinition<any>> = StandardSchemaV1.InferOutput<D["schema"]>;
35
+ /** The authorable props of a definition (schema INPUT; defaults optional). */
36
+ export type InputOf<D extends BlockDefinition<any>> = StandardSchemaV1.InferInput<D["schema"]>;
37
+ /**
38
+ * Identity at runtime; the generic captures the schema so defaults check
39
+ * against the schema's input and summary receives its output.
40
+ */
41
+ export declare function defineBlock<S extends StandardSchemaV1>(definition: BlockDefinition<S> & {
42
+ schema: S;
43
+ }): BlockDefinition<S>;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Identity at runtime; the generic captures the schema so defaults check
3
+ * against the schema's input and summary receives its output.
4
+ */
5
+ export function defineBlock(definition) {
6
+ return definition;
7
+ }
@@ -1,4 +1,4 @@
1
- import type { BlockConfig } from "./types.js";
1
+ import type { BlockConfig } from "./block-config.js";
2
2
  export declare class ConfigError extends Error {
3
3
  constructor(message: string);
4
4
  }
package/dist/types.d.ts CHANGED
@@ -18,16 +18,7 @@ export type PropsOfDef<D> = D extends {
18
18
  export interface Registry<T extends BlocksShape> {
19
19
  readonly blocks: T;
20
20
  }
21
- /**
22
- * A single entry as it arrives from a CMS. Deliberately open: `type` is any
23
- * string, because untrusted configs may contain types the registry has never
24
- * seen — those route to the fallback instead of crashing.
25
- */
26
- export interface BlockConfig {
27
- type: string;
28
- props?: unknown;
29
- id?: string | number;
30
- }
21
+ export type { BlockConfig } from "./block-config.js";
31
22
  /**
32
23
  * The props a consumer may author for a definition. With a schema this is the
33
24
  * schema's INPUT type — authored configs are pre-validation data, so fields
@@ -69,4 +60,10 @@ export type FallbackProps = {
69
60
  type: string;
70
61
  props: unknown;
71
62
  issues: ReadonlyArray<StandardSchemaV1.Issue>;
63
+ } | {
64
+ /** A block component threw while rendering (catchBlockErrors only). */
65
+ reason: "render-error";
66
+ type: string;
67
+ props: unknown;
68
+ error: unknown;
72
69
  };
@@ -0,0 +1,43 @@
1
+ import type { BlockConfig } from "./block-config.js";
2
+ import type { Manifest } from "./manifest.js";
3
+ import type { StandardSchemaV1 } from "./standard-schema.js";
4
+ export type ValidatedEntry = {
5
+ index: number;
6
+ entry: BlockConfig;
7
+ ok: true;
8
+ value: unknown;
9
+ } | {
10
+ index: number;
11
+ entry: BlockConfig;
12
+ ok: false;
13
+ reason: "unknown-type";
14
+ } | {
15
+ index: number;
16
+ entry: BlockConfig;
17
+ ok: false;
18
+ reason: "invalid-props" | "async-schema";
19
+ issues: ReadonlyArray<StandardSchemaV1.Issue>;
20
+ };
21
+ export interface ValidationReport {
22
+ /**
23
+ * Outer shape valid and no entry failed validation. Unknown types do NOT
24
+ * flip this — they are the renderer's fallback case and whether they are
25
+ * acceptable is the caller's policy (check `unknownTypes` for strictness).
26
+ */
27
+ ok: boolean;
28
+ /** Outer-shape failure; when present, `entries` is empty. */
29
+ error?: {
30
+ message: string;
31
+ };
32
+ entries: ValidatedEntry[];
33
+ /** Distinct types with no manifest entry, in order of first appearance. */
34
+ unknownTypes: string[];
35
+ /** Ids appearing more than once, in order of first duplication. */
36
+ duplicateIds: Array<string | number>;
37
+ }
38
+ /**
39
+ * Total, headless validation of an untrusted config against a manifest —
40
+ * never throws. One function for save-time validation, tests, loaders, and
41
+ * editors; the Renderer applies the same per-entry semantics.
42
+ */
43
+ export declare function validateConfig(manifest: Manifest, config: unknown): ValidationReport;
@@ -0,0 +1,53 @@
1
+ import { parseConfig, ConfigError } from "./parseConfig.js";
2
+ import { validateProps } from "./validateProps.js";
3
+ /**
4
+ * Total, headless validation of an untrusted config against a manifest —
5
+ * never throws. One function for save-time validation, tests, loaders, and
6
+ * editors; the Renderer applies the same per-entry semantics.
7
+ */
8
+ export function validateConfig(manifest, config) {
9
+ let parsed;
10
+ try {
11
+ parsed = parseConfig(config);
12
+ }
13
+ catch (error) {
14
+ return {
15
+ ok: false,
16
+ error: {
17
+ message: error instanceof ConfigError ? error.message : String(error),
18
+ },
19
+ entries: [],
20
+ unknownTypes: [],
21
+ duplicateIds: [],
22
+ };
23
+ }
24
+ const unknownTypes = [];
25
+ const duplicateIds = [];
26
+ const seenIds = new Set();
27
+ const entries = parsed.map((entry, index) => {
28
+ if (entry.id !== undefined) {
29
+ if (seenIds.has(entry.id) && !duplicateIds.includes(entry.id)) {
30
+ duplicateIds.push(entry.id);
31
+ }
32
+ seenIds.add(entry.id);
33
+ }
34
+ if (!Object.hasOwn(manifest, entry.type)) {
35
+ if (!unknownTypes.includes(entry.type))
36
+ unknownTypes.push(entry.type);
37
+ return { index, entry, ok: false, reason: "unknown-type" };
38
+ }
39
+ const validation = validateProps(manifest[entry.type].schema, entry.props);
40
+ if (!validation.ok) {
41
+ return {
42
+ index,
43
+ entry,
44
+ ok: false,
45
+ reason: validation.reason,
46
+ issues: validation.issues,
47
+ };
48
+ }
49
+ return { index, entry, ok: true, value: validation.value };
50
+ });
51
+ const ok = entries.every((item) => item.ok || item.reason === "unknown-type");
52
+ return { ok, entries, unknownTypes, duplicateIds };
53
+ }
@@ -0,0 +1,15 @@
1
+ import type { StandardSchemaV1 } from "./standard-schema.js";
2
+ export type PropsValidation = {
3
+ ok: true;
4
+ value: unknown;
5
+ } | {
6
+ ok: false;
7
+ reason: "invalid-props" | "async-schema";
8
+ issues: ReadonlyArray<StandardSchemaV1.Issue>;
9
+ };
10
+ /**
11
+ * The single semantics for validating one block's props against its schema,
12
+ * shared by the Renderer and the headless validateConfig. Synchronous by
13
+ * contract: an async schema is a config mistake, reported as such.
14
+ */
15
+ export declare function validateProps(schema: StandardSchemaV1<unknown, any>, props: unknown): PropsValidation;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The single semantics for validating one block's props against its schema,
3
+ * shared by the Renderer and the headless validateConfig. Synchronous by
4
+ * contract: an async schema is a config mistake, reported as such.
5
+ */
6
+ export function validateProps(schema, props) {
7
+ const result = schema["~standard"].validate(props);
8
+ if (result instanceof Promise) {
9
+ return {
10
+ ok: false,
11
+ reason: "async-schema",
12
+ issues: [
13
+ {
14
+ message: "schema validated asynchronously; blockprint only supports synchronous schemas",
15
+ },
16
+ ],
17
+ };
18
+ }
19
+ if (result.issues) {
20
+ return { ok: false, reason: "invalid-props", issues: result.issues };
21
+ }
22
+ return { ok: true, value: result.value };
23
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blockprint",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Typed, config-driven block renderer for React. Render arbitrary UI trees from untrusted JSON with compile-time registry safety and runtime schema validation.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://blockprint.terzidest.com",