@pwfabric/authoring 1.2.0 → 2.0.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
@@ -7,7 +7,7 @@ props are inferred from its zod schema. It re-exports `@pwfabric/runtime`.
7
7
  ## Install
8
8
 
9
9
  ```bash
10
- pnpm add @pwfabric/authoring @pwfabric/runtime @pwfabric/contracts zod@3 react react-dom
10
+ pnpm add @pwfabric/authoring @pwfabric/runtime @pwfabric/contracts zod@4 react react-dom
11
11
  pnpm add -D typescript @types/react
12
12
  ```
13
13
 
@@ -95,7 +95,7 @@ function coerceBlockName(name, type) {
95
95
  function warnOnSchemaMismatch(type, schema, defaultProps) {
96
96
  const result = schema.safeParse(defaultProps);
97
97
  if (!result.success) {
98
- const errors = result.error.errors.map((e) => `${e.path.join('.')}: ${e.message}`).join(', ');
98
+ const errors = result.error.issues.map((e) => `${e.path.map(String).join('.')}: ${e.message}`).join(', ');
99
99
  console.warn(`[pwfabric] block "${type}": defaultProps do not match schema (${errors}). Fix at authoring.`);
100
100
  }
101
101
  }
@@ -278,7 +278,7 @@ export function createBlockInstance(definition, id, props, children) {
278
278
  // Validate merged props
279
279
  const result = definition.schema.safeParse(mergedProps);
280
280
  if (!result.success) {
281
- const errors = result.error.errors.map((e) => `${e.path.join('.')}: ${e.message}`).join(', ');
281
+ const errors = result.error.issues.map((e) => `${e.path.map(String).join('.')}: ${e.message}`).join(', ');
282
282
  throw new Error(`Invalid block props: ${errors}`);
283
283
  }
284
284
  const instance = {
@@ -1 +1 @@
1
- {"version":3,"file":"define-block.js","sourceRoot":"","sources":["../src/define-block.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,CAAC,EAAmC,MAAM,KAAK,CAAA;AACxD,OAAO,EAAE,aAAa,EAAkB,MAAM,OAAO,CAAA;AAGrD,+DAA+D;AAC/D,aAAa;AACb,+DAA+D;AAE/D;;;;G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U,CAAC,YAAY;QAC1B,GAAG,KAAK;KACC,CAAA;IAEX,wBAAwB;IACxB,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW,CAAC,CAAA;IACvD,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAC7F,MAAM,IAAI,KAAK,CAAC,wBAAwB,MAAM,EAAE,CAAC,CAAA;IACnD,CAAC;IAED,MAAM,QAAQ,GAA4E;QACxF,EAAE;QACF,IAAI,EAAE,UAAU,CAAC,IAAI;QACrB,KAAK,EAAE,MAAM,CAAC,IAAc;KAC7B,CAAA;IAED,IAAI,QAAQ,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpC,IAAI,CAAC,UAAU,CAAC,eAAe,EAAE,CAAC;YAChC,MAAM,IAAI,KAAK,CAAC,eAAe,UAAU,CAAC,IAAI,wBAAwB,CAAC,CAAA;QACzE,CAAC;QACD,QAAQ,CAAC,QAAQ,GAAG,QAAQ,CAAA;IAC9B,CAAC;IAED,OAAO,QAAQ,CAAA;AACjB,CAAC","sourcesContent":["/**\n * defineBlock API\n *\n * Create type-safe custom block definitions with Zod schemas.\n *\n * @module @pwfabric/authoring/define-block\n *\n * @example\n * ```typescript\n * import { defineBlock } from '@pwfabric/authoring'\n * import { z } from 'zod'\n *\n * export const MyBlock = defineBlock({\n * type: 'my-block',\n * name: 'My Block',\n * schema: z.object({ title: z.string() }),\n * defaultProps: { title: 'Default' },\n * component: ({ props }) => <div>{props.title}</div>\n * })\n * ```\n */\n\nimport { z, type ZodSchema, type ZodTypeAny } from 'zod'\nimport { createElement, type ReactNode } from 'react'\nimport type { CustomBlockOptions, CustomBlockDefinition, SchemaProps } from './types.js'\n\n// ============================================================\n// VALIDATION\n// ============================================================\n\n/**\n * Validate block type identifier\n *\n * Must be kebab-case, 2-50 characters, start with letter.\n */\nfunction validateBlockType(type: string): void {\n if (typeof type !== 'string') {\n throw new Error('Block type must be a string')\n }\n\n if (type.length < 2 || type.length > 50) {\n throw new Error('Block type must be 2-50 characters')\n }\n\n const kebabCaseRegex = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/\n if (!kebabCaseRegex.test(type)) {\n throw new Error(\n `Block type \"${type}\" must be kebab-case (lowercase letters, numbers, hyphens, starting with a letter)`\n )\n }\n\n // Reserved types (core block types)\n const reservedTypes = [\n 'container',\n 'grid',\n 'text',\n 'heading',\n 'button',\n 'image',\n 'form',\n 'input',\n 'link',\n 'icon',\n 'badge',\n 'code',\n 'divider',\n 'list',\n 'table',\n 'avatar',\n 'tooltip',\n 'accordion',\n 'tabs',\n 'dropdown',\n 'modal',\n ]\n\n if (reservedTypes.includes(type)) {\n throw new Error(`Block type \"${type}\" is reserved. Use a unique type for custom blocks.`)\n }\n}\n\n/**\n * field-severity policy — `name` is a COSMETIC display label, NOT the\n * block's identity. It must never be a hard/fatal error: coerce a missing or\n * invalid name to the block `type` and warn. (`type` is the identity and stays\n * HARD — see validateBlockType.) This is the runtime SOFT half of the end-to-end\n * stitch; the authoring/install GATE applies the same policy via\n * validateBlockDefinition() below. Matches the already-tolerant render meta path\n * (installed-block-meta.descriptorToSnapshot), removing the \"valid-but-not-\n * renderable\" divergence where this throw crashed a block at render.\n */\nfunction coerceBlockName(name: unknown, type: string): string {\n if (typeof name === 'string' && name.length >= 1 && name.length <= 100) {\n return name\n }\n console.warn(\n `[pwfabric] block \"${type}\": invalid name (${typeof name}) — falling back to type. ` +\n `Names are cosmetic; fix at authoring, never fatal at render.`\n )\n return type\n}\n\n/**\n * Warn (never throw) when defaultProps don't satisfy the schema.\n * the renderer degrades, it does not crash. A mismatch is an authoring defect\n * to flag, not a render-time fatality (the registry already falls back to\n * defaultProps on a failed parse).\n */\nfunction warnOnSchemaMismatch(\n type: string,\n schema: ZodSchema<unknown>,\n defaultProps: Record<string, unknown>\n): void {\n const result = schema.safeParse(defaultProps)\n if (!result.success) {\n const errors = result.error.errors.map((e) => `${e.path.join('.')}: ${e.message}`).join(', ')\n console.warn(`[pwfabric] block \"${type}\": defaultProps do not match schema (${errors}). Fix at authoring.`)\n }\n}\n\n/**\n * render-degrade fallback: a block whose `component` is missing must\n * not white-screen the canvas. Render a visible placeholder instead of throwing.\n */\nfunction placeholderComponent(type: string): () => ReactNode {\n return function MissingBlock(): ReactNode {\n return createElement(\n 'div',\n {\n 'data-pw-placeholder': type,\n style: {\n padding: '8px 12px',\n border: '1px dashed #c0392b',\n borderRadius: '6px',\n color: '#c0392b',\n font: '12px system-ui, sans-serif',\n },\n },\n `Block \"${type}\" has no component`\n )\n }\n}\n\n// ============================================================\n// DEFINE BLOCK\n// ============================================================\n\n/**\n * Define a custom block with type-safe Zod schema validation\n *\n * Creates a reusable block definition that can be registered with\n * CustomBlockRegistry and used with SurfaceRenderer.\n *\n * @param options - Block definition options\n * @returns A frozen, type-safe custom block definition\n *\n * @example\n * ```typescript\n * import { defineBlock } from '@pwfabric/authoring'\n * import { z } from 'zod'\n *\n * // Define a pricing card block\n * const PricingCard = defineBlock({\n * type: 'pricing-card',\n * name: 'Pricing Card',\n * category: 'content',\n * schema: z.object({\n * title: z.string(),\n * price: z.number(),\n * currency: z.string().default('USD'),\n * features: z.array(z.string()),\n * highlighted: z.boolean().default(false),\n * }),\n * defaultProps: {\n * title: 'Basic Plan',\n * price: 9.99,\n * currency: 'USD',\n * features: ['Feature 1', 'Feature 2'],\n * highlighted: false,\n * },\n * component: ({ props }) => (\n * <div className={props.highlighted ? 'highlighted' : ''}>\n * <h3>{props.title}</h3>\n * <p>{props.currency} {props.price}</p>\n * <ul>\n * {props.features.map((f, i) => <li key={i}>{f}</li>)}\n * </ul>\n * </div>\n * ),\n * })\n * ```\n */\nexport function defineBlock<TSchema extends ZodTypeAny>(\n options: CustomBlockOptions<TSchema>\n): CustomBlockDefinition<SchemaProps<TSchema>> {\n type TProps = SchemaProps<TSchema>\n // the renderer DEGRADES, it never throws. `type` is the identity\n // → HARD (throws). Every other required field falls back + warns so a single\n // malformed block can't white-screen the canvas. The authoring/publish gate is\n // where these are rejected early; render stays graceful.\n validateBlockType(options.type)\n const safeName = coerceBlockName(options.name, options.type)\n\n // schema — missing → passthrough (props pass through unvalidated) + warn.\n let schema = options.schema as ZodSchema<TProps> | undefined\n if (!schema) {\n console.warn(\n `[pwfabric] block \"${options.type}\": no schema — using a passthrough (props unvalidated). ` +\n `Add a schema at authoring; this is degraded render, not a fix.`\n )\n schema = z.object({}).passthrough() as unknown as ZodSchema<TProps>\n }\n\n // defaultProps — missing → {} + warn.\n let defaultProps = options.defaultProps\n if (!defaultProps) {\n console.warn(`[pwfabric] block \"${options.type}\": no defaultProps — using {}.`)\n defaultProps = {} as TProps\n }\n\n // component — missing → visible placeholder + warn (not a thrown white-screen).\n let component = options.component\n if (typeof component !== 'function') {\n console.warn(`[pwfabric] block \"${options.type}\": no component — rendering a placeholder.`)\n component = placeholderComponent(options.type) as typeof options.component\n }\n\n // Defaults vs schema: warn, never throw.\n warnOnSchemaMismatch(options.type, schema, defaultProps)\n\n // Build the definition with defaults\n const definition = {\n type: options.type,\n name: safeName,\n category: options.category ?? 'content',\n icon: options.icon ?? '◆',\n schema,\n defaultProps,\n canHaveChildren: options.canHaveChildren ?? false,\n component,\n // Only include optional properties if they're defined\n ...(options.allowedChildren !== undefined && { allowedChildren: options.allowedChildren }),\n ...(options.allowedParents !== undefined && { allowedParents: options.allowedParents }),\n ...(options.traits !== undefined && { traits: options.traits }),\n ...(options.allowedChildTraits !== undefined && {\n allowedChildTraits: options.allowedChildTraits,\n }),\n ...(options.maxInstances !== undefined && { maxInstances: options.maxInstances }),\n } as CustomBlockDefinition<TProps>\n\n // Return a frozen definition to prevent mutations\n return Object.freeze(definition)\n}\n\n// ============================================================\n// DEFINITION GATE (single-source field policy)\n// ============================================================\n\n/** A reported issue from {@link validateBlockDefinition}. */\nexport interface BlockDefinitionIssue {\n field: 'type' | 'name'\n code: string\n severity: 'error' | 'warning'\n message: string\n}\n\n/**\n * Single source of truth for block-definition field severity, used by\n * the AUTHORING / INSTALL gate (packaging, manifest validation, host\n * install). Non-throwing reporter — the SAME stitch defineBlock applies at\n * runtime, surfaced as structured issues so callers can REJECT identity\n * problems (`type`, severity=error) and merely WARN on cosmetic ones (`name`,\n * severity=warning). Keeping this the one place the policy lives is what makes\n * the treatment identical end-to-end (authoring → install → runtime → render).\n */\nexport function validateBlockDefinition(options: { type?: unknown; name?: unknown }): BlockDefinitionIssue[] {\n const issues: BlockDefinitionIssue[] = []\n // type — block IDENTITY → HARD (error). Mirrors validateBlockType's rules.\n const t = options.type\n if (typeof t !== 'string') {\n issues.push({ field: 'type', code: 'BLOCK_TYPE_NOT_STRING', severity: 'error', message: 'Block type must be a string' })\n } else if (t.length < 2 || t.length > 50) {\n issues.push({ field: 'type', code: 'BLOCK_TYPE_LENGTH', severity: 'error', message: 'Block type must be 2-50 characters' })\n } else if (!/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(t)) {\n issues.push({ field: 'type', code: 'BLOCK_TYPE_FORMAT', severity: 'error', message: `Block type \"${t}\" must be kebab-case` })\n }\n // name — cosmetic label → SOFT (warning). Never blocks; coerced to type at runtime.\n const n = options.name\n if (typeof n !== 'string' || n.length < 1 || n.length > 100) {\n issues.push({ field: 'name', code: 'BLOCK_NAME_INVALID', severity: 'warning', message: 'Block name should be a 1-100 char string; falls back to type' })\n }\n return issues\n}\n\n// ============================================================\n// UTILITY FUNCTIONS\n// ============================================================\n\n/**\n * Check if a value is a custom block definition\n */\nexport function isCustomBlockDefinition(value: unknown): value is CustomBlockDefinition {\n if (!value || typeof value !== 'object') {\n return false\n }\n\n const def = value as Partial<CustomBlockDefinition>\n return (\n typeof def.type === 'string' &&\n typeof def.name === 'string' &&\n typeof def.category === 'string' &&\n typeof def.schema === 'object' &&\n typeof def.defaultProps === 'object' &&\n typeof def.component === 'function'\n )\n}\n\n/**\n * Create a block instance from a custom block definition\n *\n * @param definition - The block definition\n * @param id - Unique block ID\n * @param props - Optional props override (merged with defaults)\n * @param children - Optional children blocks\n */\nexport function createBlockInstance<TProps extends Record<string, unknown>>(\n definition: CustomBlockDefinition<TProps>,\n id: string,\n props?: Partial<TProps>,\n children?: readonly { id: string; type: string; props: Record<string, unknown> }[]\n): { id: string; type: string; props: TProps; children?: typeof children } {\n const mergedProps = {\n ...definition.defaultProps,\n ...props,\n } as TProps\n\n // Validate merged props\n const result = definition.schema.safeParse(mergedProps)\n if (!result.success) {\n const errors = result.error.errors.map((e) => `${e.path.join('.')}: ${e.message}`).join(', ')\n throw new Error(`Invalid block props: ${errors}`)\n }\n\n const instance: { id: string; type: string; props: TProps; children?: typeof children } = {\n id,\n type: definition.type,\n props: result.data as TProps,\n }\n\n if (children && children.length > 0) {\n if (!definition.canHaveChildren) {\n throw new Error(`Block type \"${definition.type}\" cannot have children`)\n }\n instance.children = children\n }\n\n return instance\n}\n"]}
1
+ {"version":3,"file":"define-block.js","sourceRoot":"","sources":["../src/define-block.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,CAAC,EAAmC,MAAM,KAAK,CAAA;AACxD,OAAO,EAAE,aAAa,EAAkB,MAAM,OAAO,CAAA;AAGrD,+DAA+D;AAC/D,aAAa;AACb,+DAA+D;AAE/D;;;;GAIG;AACH,SAAS,iBAAiB,CAAC,IAAY;IACrC,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC7B,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAA;IAChD,CAAC;IAED,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,MAAM,GAA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B,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QACzG,MAAM,IAAI,KAAK,CAAC,wBAAwB,MAAM,EAAE,CAAC,CAAA;IACnD,CAAC;IAED,MAAM,QAAQ,GAA4E;QACxF,EAAE;QACF,IAAI,EAAE,UAAU,CAAC,IAAI;QACrB,KAAK,EAAE,MAAM,CAAC,IAAc;KAC7B,CAAA;IAED,IAAI,QAAQ,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpC,IAAI,CAAC,UAAU,CAAC,eAAe,EAAE,CAAC;YAChC,MAAM,IAAI,KAAK,CAAC,eAAe,UAAU,CAAC,IAAI,wBAAwB,CAAC,CAAA;QACzE,CAAC;QACD,QAAQ,CAAC,QAAQ,GAAG,QAAQ,CAAA;IAC9B,CAAC;IAED,OAAO,QAAQ,CAAA;AACjB,CAAC","sourcesContent":["/**\n * defineBlock API\n *\n * Create type-safe custom block definitions with Zod schemas.\n *\n * @module @pwfabric/authoring/define-block\n *\n * @example\n * ```typescript\n * import { defineBlock } from '@pwfabric/authoring'\n * import { z } from 'zod'\n *\n * export const MyBlock = defineBlock({\n * type: 'my-block',\n * name: 'My Block',\n * schema: z.object({ title: z.string() }),\n * defaultProps: { title: 'Default' },\n * component: ({ props }) => <div>{props.title}</div>\n * })\n * ```\n */\n\nimport { z, type ZodSchema, type ZodTypeAny } from 'zod'\nimport { createElement, type ReactNode } from 'react'\nimport type { CustomBlockOptions, CustomBlockDefinition, SchemaProps } from './types.js'\n\n// ============================================================\n// VALIDATION\n// ============================================================\n\n/**\n * Validate block type identifier\n *\n * Must be kebab-case, 2-50 characters, start with letter.\n */\nfunction validateBlockType(type: string): void {\n if (typeof type !== 'string') {\n throw new Error('Block type must be a string')\n }\n\n if (type.length < 2 || type.length > 50) {\n throw new Error('Block type must be 2-50 characters')\n }\n\n const kebabCaseRegex = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/\n if (!kebabCaseRegex.test(type)) {\n throw new Error(\n `Block type \"${type}\" must be kebab-case (lowercase letters, numbers, hyphens, starting with a letter)`\n )\n }\n\n // Reserved types (core block types)\n const reservedTypes = [\n 'container',\n 'grid',\n 'text',\n 'heading',\n 'button',\n 'image',\n 'form',\n 'input',\n 'link',\n 'icon',\n 'badge',\n 'code',\n 'divider',\n 'list',\n 'table',\n 'avatar',\n 'tooltip',\n 'accordion',\n 'tabs',\n 'dropdown',\n 'modal',\n ]\n\n if (reservedTypes.includes(type)) {\n throw new Error(`Block type \"${type}\" is reserved. Use a unique type for custom blocks.`)\n }\n}\n\n/**\n * field-severity policy — `name` is a COSMETIC display label, NOT the\n * block's identity. It must never be a hard/fatal error: coerce a missing or\n * invalid name to the block `type` and warn. (`type` is the identity and stays\n * HARD — see validateBlockType.) This is the runtime SOFT half of the end-to-end\n * stitch; the authoring/install GATE applies the same policy via\n * validateBlockDefinition() below. Matches the already-tolerant render meta path\n * (installed-block-meta.descriptorToSnapshot), removing the \"valid-but-not-\n * renderable\" divergence where this throw crashed a block at render.\n */\nfunction coerceBlockName(name: unknown, type: string): string {\n if (typeof name === 'string' && name.length >= 1 && name.length <= 100) {\n return name\n }\n console.warn(\n `[pwfabric] block \"${type}\": invalid name (${typeof name}) — falling back to type. ` +\n `Names are cosmetic; fix at authoring, never fatal at render.`\n )\n return type\n}\n\n/**\n * Warn (never throw) when defaultProps don't satisfy the schema.\n * the renderer degrades, it does not crash. A mismatch is an authoring defect\n * to flag, not a render-time fatality (the registry already falls back to\n * defaultProps on a failed parse).\n */\nfunction warnOnSchemaMismatch(\n type: string,\n schema: ZodSchema<unknown>,\n defaultProps: Record<string, unknown>\n): void {\n const result = schema.safeParse(defaultProps)\n if (!result.success) {\n const errors = result.error.issues.map((e) => `${e.path.map(String).join('.')}: ${e.message}`).join(', ')\n console.warn(`[pwfabric] block \"${type}\": defaultProps do not match schema (${errors}). Fix at authoring.`)\n }\n}\n\n/**\n * render-degrade fallback: a block whose `component` is missing must\n * not white-screen the canvas. Render a visible placeholder instead of throwing.\n */\nfunction placeholderComponent(type: string): () => ReactNode {\n return function MissingBlock(): ReactNode {\n return createElement(\n 'div',\n {\n 'data-pw-placeholder': type,\n style: {\n padding: '8px 12px',\n border: '1px dashed #c0392b',\n borderRadius: '6px',\n color: '#c0392b',\n font: '12px system-ui, sans-serif',\n },\n },\n `Block \"${type}\" has no component`\n )\n }\n}\n\n// ============================================================\n// DEFINE BLOCK\n// ============================================================\n\n/**\n * Define a custom block with type-safe Zod schema validation\n *\n * Creates a reusable block definition that can be registered with\n * CustomBlockRegistry and used with SurfaceRenderer.\n *\n * @param options - Block definition options\n * @returns A frozen, type-safe custom block definition\n *\n * @example\n * ```typescript\n * import { defineBlock } from '@pwfabric/authoring'\n * import { z } from 'zod'\n *\n * // Define a pricing card block\n * const PricingCard = defineBlock({\n * type: 'pricing-card',\n * name: 'Pricing Card',\n * category: 'content',\n * schema: z.object({\n * title: z.string(),\n * price: z.number(),\n * currency: z.string().default('USD'),\n * features: z.array(z.string()),\n * highlighted: z.boolean().default(false),\n * }),\n * defaultProps: {\n * title: 'Basic Plan',\n * price: 9.99,\n * currency: 'USD',\n * features: ['Feature 1', 'Feature 2'],\n * highlighted: false,\n * },\n * component: ({ props }) => (\n * <div className={props.highlighted ? 'highlighted' : ''}>\n * <h3>{props.title}</h3>\n * <p>{props.currency} {props.price}</p>\n * <ul>\n * {props.features.map((f, i) => <li key={i}>{f}</li>)}\n * </ul>\n * </div>\n * ),\n * })\n * ```\n */\nexport function defineBlock<TSchema extends ZodTypeAny>(\n options: CustomBlockOptions<TSchema>\n): CustomBlockDefinition<SchemaProps<TSchema>> {\n type TProps = SchemaProps<TSchema>\n // the renderer DEGRADES, it never throws. `type` is the identity\n // → HARD (throws). Every other required field falls back + warns so a single\n // malformed block can't white-screen the canvas. The authoring/publish gate is\n // where these are rejected early; render stays graceful.\n validateBlockType(options.type)\n const safeName = coerceBlockName(options.name, options.type)\n\n // schema — missing → passthrough (props pass through unvalidated) + warn.\n let schema = options.schema as ZodSchema<TProps> | undefined\n if (!schema) {\n console.warn(\n `[pwfabric] block \"${options.type}\": no schema — using a passthrough (props unvalidated). ` +\n `Add a schema at authoring; this is degraded render, not a fix.`\n )\n schema = z.object({}).passthrough() as unknown as ZodSchema<TProps>\n }\n\n // defaultProps — missing → {} + warn.\n let defaultProps = options.defaultProps\n if (!defaultProps) {\n console.warn(`[pwfabric] block \"${options.type}\": no defaultProps — using {}.`)\n defaultProps = {} as TProps\n }\n\n // component — missing → visible placeholder + warn (not a thrown white-screen).\n let component = options.component\n if (typeof component !== 'function') {\n console.warn(`[pwfabric] block \"${options.type}\": no component — rendering a placeholder.`)\n component = placeholderComponent(options.type) as typeof options.component\n }\n\n // Defaults vs schema: warn, never throw.\n warnOnSchemaMismatch(options.type, schema, defaultProps)\n\n // Build the definition with defaults\n const definition = {\n type: options.type,\n name: safeName,\n category: options.category ?? 'content',\n icon: options.icon ?? '◆',\n schema,\n defaultProps,\n canHaveChildren: options.canHaveChildren ?? false,\n component,\n // Only include optional properties if they're defined\n ...(options.allowedChildren !== undefined && { allowedChildren: options.allowedChildren }),\n ...(options.allowedParents !== undefined && { allowedParents: options.allowedParents }),\n ...(options.traits !== undefined && { traits: options.traits }),\n ...(options.allowedChildTraits !== undefined && {\n allowedChildTraits: options.allowedChildTraits,\n }),\n ...(options.maxInstances !== undefined && { maxInstances: options.maxInstances }),\n } as CustomBlockDefinition<TProps>\n\n // Return a frozen definition to prevent mutations\n return Object.freeze(definition)\n}\n\n// ============================================================\n// DEFINITION GATE (single-source field policy)\n// ============================================================\n\n/** A reported issue from {@link validateBlockDefinition}. */\nexport interface BlockDefinitionIssue {\n field: 'type' | 'name'\n code: string\n severity: 'error' | 'warning'\n message: string\n}\n\n/**\n * Single source of truth for block-definition field severity, used by\n * the AUTHORING / INSTALL gate (packaging, manifest validation, host\n * install). Non-throwing reporter — the SAME stitch defineBlock applies at\n * runtime, surfaced as structured issues so callers can REJECT identity\n * problems (`type`, severity=error) and merely WARN on cosmetic ones (`name`,\n * severity=warning). Keeping this the one place the policy lives is what makes\n * the treatment identical end-to-end (authoring → install → runtime → render).\n */\nexport function validateBlockDefinition(options: { type?: unknown; name?: unknown }): BlockDefinitionIssue[] {\n const issues: BlockDefinitionIssue[] = []\n // type — block IDENTITY → HARD (error). Mirrors validateBlockType's rules.\n const t = options.type\n if (typeof t !== 'string') {\n issues.push({ field: 'type', code: 'BLOCK_TYPE_NOT_STRING', severity: 'error', message: 'Block type must be a string' })\n } else if (t.length < 2 || t.length > 50) {\n issues.push({ field: 'type', code: 'BLOCK_TYPE_LENGTH', severity: 'error', message: 'Block type must be 2-50 characters' })\n } else if (!/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(t)) {\n issues.push({ field: 'type', code: 'BLOCK_TYPE_FORMAT', severity: 'error', message: `Block type \"${t}\" must be kebab-case` })\n }\n // name — cosmetic label → SOFT (warning). Never blocks; coerced to type at runtime.\n const n = options.name\n if (typeof n !== 'string' || n.length < 1 || n.length > 100) {\n issues.push({ field: 'name', code: 'BLOCK_NAME_INVALID', severity: 'warning', message: 'Block name should be a 1-100 char string; falls back to type' })\n }\n return issues\n}\n\n// ============================================================\n// UTILITY FUNCTIONS\n// ============================================================\n\n/**\n * Check if a value is a custom block definition\n */\nexport function isCustomBlockDefinition(value: unknown): value is CustomBlockDefinition {\n if (!value || typeof value !== 'object') {\n return false\n }\n\n const def = value as Partial<CustomBlockDefinition>\n return (\n typeof def.type === 'string' &&\n typeof def.name === 'string' &&\n typeof def.category === 'string' &&\n typeof def.schema === 'object' &&\n typeof def.defaultProps === 'object' &&\n typeof def.component === 'function'\n )\n}\n\n/**\n * Create a block instance from a custom block definition\n *\n * @param definition - The block definition\n * @param id - Unique block ID\n * @param props - Optional props override (merged with defaults)\n * @param children - Optional children blocks\n */\nexport function createBlockInstance<TProps extends Record<string, unknown>>(\n definition: CustomBlockDefinition<TProps>,\n id: string,\n props?: Partial<TProps>,\n children?: readonly { id: string; type: string; props: Record<string, unknown> }[]\n): { id: string; type: string; props: TProps; children?: typeof children } {\n const mergedProps = {\n ...definition.defaultProps,\n ...props,\n } as TProps\n\n // Validate merged props\n const result = definition.schema.safeParse(mergedProps)\n if (!result.success) {\n const errors = result.error.issues.map((e) => `${e.path.map(String).join('.')}: ${e.message}`).join(', ')\n throw new Error(`Invalid block props: ${errors}`)\n }\n\n const instance: { id: string; type: string; props: TProps; children?: typeof children } = {\n id,\n type: definition.type,\n props: result.data as TProps,\n }\n\n if (children && children.length > 0) {\n if (!definition.canHaveChildren) {\n throw new Error(`Block type \"${definition.type}\" cannot have children`)\n }\n instance.children = children\n }\n\n return instance\n}\n"]}
@@ -79,8 +79,8 @@ function validateConfig(config, schema) {
79
79
  config: result.data,
80
80
  };
81
81
  }
82
- const errors = result.error.errors.map((e) => ({
83
- path: e.path.join('.'),
82
+ const errors = result.error.issues.map((e) => ({
83
+ path: e.path.map(String).join('.'),
84
84
  message: e.message,
85
85
  }));
86
86
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"define-factory.js","sourceRoot":"","sources":["../src/define-factory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAIH,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAA;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAA;AAUxD,+DAA+D;AAC/D,gBAAgB;AAChB,+DAA+D;AAE/D,IAAI,SAAS,GAAG,CAAC,CAAA;AAEjB;;GAEG;AACH,SAAS,eAAe,CAAC,IAAY;IACnC,SAAS,IAAI,CAAC,CAAA;IACd,OAAO,GAAG,IAAI,IAAI,SAAS,IAAI,I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CAC7B,MAAwB,EACxB,iBAA0C,EAAE;IAE5C,OAAO;QACL,EAAE,EAAE,eAAe,CAAC,WAAW,CAAC;QAChC,IAAI,EAAE,WAAW;QACjB,KAAK,EAAE;YACL,SAAS,EAAE,QAAQ;YACnB,GAAG,EAAE,EAAE;YACP,GAAG,cAAc;SAClB;QACD,MAAM,EAAE,aAAa,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,aAAa,IAAI,oBAAoB;QAC7E,QAAQ,EAAE,CAAC,GAAG,MAAM,CAAC;KACtB,CAAA;AACH,CAAC","sourcesContent":["/**\n * defineFactory API\n *\n * Create factory functions that generate block compositions.\n *\n * @module @pwfabric/authoring/define-factory\n *\n * @example\n * ```typescript\n * import { defineFactory } from '@pwfabric/authoring'\n * import { z } from 'zod'\n *\n * const MyPageFactory = defineFactory({\n * id: 'my-page',\n * name: 'My Page Factory',\n * configSchema: z.object({\n * title: z.string(),\n * subtitle: z.string().optional(),\n * }),\n * build: (config) => [\n * { type: 'heading', props: { text: config.title, level: 'h1' } },\n * { type: 'text', props: { content: config.subtitle ?? '' } },\n * ]\n * })\n * ```\n */\n\nimport type { ZodSchema } from 'zod'\nimport type { Block } from '@pwfabric/core'\nimport { DEFAULT_BLOCK_LAYOUT } from '@pwfabric/core'\nimport { blockRegistry } from '@pwfabric/runtime/blocks'\nimport type {\n FactoryOptions,\n FactoryDefinition,\n FactoryConfig,\n FactoryValidationResult,\n FactoryValidationError,\n BlockSpec,\n} from './types.js'\n\n// ============================================================\n// ID GENERATION\n// ============================================================\n\nlet idCounter = 0\n\n/**\n * Generate a unique block ID\n */\nfunction generateBlockId(type: string): string {\n idCounter += 1\n return `${type}-${idCounter}-${Date.now().toString(36)}`\n}\n\n/**\n * Reset the ID counter (useful for testing)\n */\nexport function resetIdCounter(): void {\n idCounter = 0\n}\n\n// ============================================================\n// VALIDATION\n// ============================================================\n\n/**\n * Validate factory identifier\n */\nfunction validateFactoryId(id: string): void {\n if (typeof id !== 'string') {\n throw new Error('Factory id must be a string')\n }\n\n if (id.length < 2 || id.length > 50) {\n throw new Error('Factory id must be 2-50 characters')\n }\n\n const kebabCaseRegex = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/\n if (!kebabCaseRegex.test(id)) {\n throw new Error(\n `Factory id \"${id}\" must be kebab-case (lowercase letters, numbers, hyphens, starting with a letter)`\n )\n }\n}\n\n/**\n * Validate factory config against schema\n */\nfunction validateConfig<TConfig extends FactoryConfig>(\n config: unknown,\n schema?: ZodSchema<TConfig>\n): FactoryValidationResult<TConfig> {\n if (!schema) {\n // No schema, accept any config\n return {\n valid: true,\n config: config as TConfig,\n }\n }\n\n const result = schema.safeParse(config)\n if (result.success) {\n return {\n valid: true,\n config: result.data,\n }\n }\n\n const errors: FactoryValidationError[] = result.error.errors.map((e) => ({\n path: e.path.join('.'),\n message: e.message,\n }))\n\n return {\n valid: false,\n errors,\n }\n}\n\n// ============================================================\n// BLOCK SPEC TO BLOCK\n// ============================================================\n\n/**\n * Convert a BlockSpec (without id) to a Block (with id)\n */\nfunction specToBlock(spec: BlockSpec): Block {\n const block: Block = {\n id: generateBlockId(spec.type),\n type: spec.type,\n props: spec.props,\n layout: blockRegistry.get(spec.type)?.defaultLayout ?? DEFAULT_BLOCK_LAYOUT,\n }\n\n if (spec.children && spec.children.length > 0) {\n return {\n ...block,\n children: spec.children.map(specToBlock),\n }\n }\n\n return block\n}\n\n// ============================================================\n// DEFINE FACTORY\n// ============================================================\n\n/**\n * Define a factory function that generates block compositions\n *\n * Factories allow you to create reusable block patterns that can be\n * customized with configuration. They automatically generate unique\n * block IDs and validate configuration against an optional schema.\n *\n * @param options - Factory definition options\n * @returns A frozen factory definition\n *\n * @example\n * ```typescript\n * import { defineFactory } from '@pwfabric/authoring'\n * import { z } from 'zod'\n *\n * // Define a pricing section factory\n * const PricingSectionFactory = defineFactory({\n * id: 'pricing-section',\n * name: 'Pricing Section',\n * description: 'Create a pricing section with multiple tiers',\n * configSchema: z.object({\n * title: z.string(),\n * tiers: z.array(z.object({\n * name: z.string(),\n * price: z.number(),\n * features: z.array(z.string()),\n * })),\n * }),\n * build: (config) => [\n * {\n * type: 'container',\n * props: { direction: 'column', gap: 32 },\n * children: [\n * { type: 'heading', props: { text: config.title, level: 'h2' } },\n * {\n * type: 'grid',\n * props: { columns: config.tiers.length },\n * children: config.tiers.map((tier) => ({\n * type: 'pricing-card',\n * props: {\n * title: tier.name,\n * price: tier.price,\n * features: tier.features,\n * },\n * })),\n * },\n * ],\n * },\n * ],\n * })\n *\n * // Use the factory\n * const blocks = PricingSectionFactory.build({\n * title: 'Choose Your Plan',\n * tiers: [\n * { name: 'Basic', price: 9, features: ['Feature 1'] },\n * { name: 'Pro', price: 29, features: ['Feature 1', 'Feature 2'] },\n * ],\n * })\n * ```\n */\nexport function defineFactory<TConfig extends FactoryConfig = FactoryConfig>(\n options: FactoryOptions<TConfig>\n): FactoryDefinition<TConfig> {\n // Validate required fields\n validateFactoryId(options.id)\n\n if (typeof options.build !== 'function') {\n throw new Error('Factory build function is required')\n }\n\n // Create the build wrapper that converts specs to blocks\n const buildWithIds = (config: TConfig): readonly Block[] => {\n const specs = options.build(config)\n return specs.map(specToBlock)\n }\n\n // Create the validation function\n const validateConfigFn = (config: unknown): FactoryValidationResult<TConfig> => {\n return validateConfig(config, options.configSchema)\n }\n\n const definition = {\n id: options.id,\n name: options.name ?? options.id,\n description: options.description ?? '',\n build: buildWithIds,\n validateConfig: validateConfigFn,\n // Only include configSchema if it's defined\n ...(options.configSchema !== undefined && { configSchema: options.configSchema }),\n } as FactoryDefinition<TConfig>\n\n return Object.freeze(definition)\n}\n\n// ============================================================\n// UTILITY FUNCTIONS\n// ============================================================\n\n/**\n * Check if a value is a factory definition\n */\nexport function isFactoryDefinition(value: unknown): value is FactoryDefinition {\n if (!value || typeof value !== 'object') {\n return false\n }\n\n const def = value as Partial<FactoryDefinition>\n return (\n typeof def.id === 'string' &&\n typeof def.name === 'string' &&\n typeof def.build === 'function' &&\n typeof def.validateConfig === 'function'\n )\n}\n\n/**\n * Compose multiple factory outputs into a single block array\n *\n * @param factories - Array of factory output block arrays\n * @returns Combined block array\n */\nexport function composeFactoryOutputs(\n ...factories: readonly (readonly Block[])[]\n): readonly Block[] {\n return factories.flat()\n}\n\n/**\n * Wrap factory output in a container block\n *\n * @param blocks - Factory output blocks\n * @param containerProps - Props for the wrapper container\n * @returns Single container block with children\n */\nexport function wrapInContainer(\n blocks: readonly Block[],\n containerProps: Record<string, unknown> = {}\n): Block {\n return {\n id: generateBlockId('container'),\n type: 'container',\n props: {\n direction: 'column',\n gap: 24,\n ...containerProps,\n },\n layout: blockRegistry.get('container')?.defaultLayout ?? DEFAULT_BLOCK_LAYOUT,\n children: [...blocks],\n }\n}\n"]}
1
+ {"version":3,"file":"define-factory.js","sourceRoot":"","sources":["../src/define-factory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAIH,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAA;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAA;AAUxD,+DAA+D;AAC/D,gBAAgB;AAChB,+DAA+D;AAE/D,IAAI,SAAS,GAAG,CAAC,CAAA;AAEjB;;GAEG;AACH,SAAS,eAAe,CAAC,IAAY;IACnC,SAAS,IAAI,CAAC,CAAA;IACd,OAAO,GAAG,IAAI,IAAI,SAAS,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAA;AAC1D,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,cAAc;IAC5B,SAAS,GAAG,CAAC,CAAA;AACf,CAAC;AAED,+DAA+D;AAC/D,aAAa;AACb,+DAA+D;AAE/D;;GAEG;AACH,SAAS,iBAAiB,CAAC,EAAU;IACnC,IAAI,OAAO,EAAE,KAAK,QAAQ,EAAE,CAAC;QAC3B,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAA;IAChD,CAA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AC;KACtB,CAAA;AACH,CAAC","sourcesContent":["/**\n * defineFactory API\n *\n * Create factory functions that generate block compositions.\n *\n * @module @pwfabric/authoring/define-factory\n *\n * @example\n * ```typescript\n * import { defineFactory } from '@pwfabric/authoring'\n * import { z } from 'zod'\n *\n * const MyPageFactory = defineFactory({\n * id: 'my-page',\n * name: 'My Page Factory',\n * configSchema: z.object({\n * title: z.string(),\n * subtitle: z.string().optional(),\n * }),\n * build: (config) => [\n * { type: 'heading', props: { text: config.title, level: 'h1' } },\n * { type: 'text', props: { content: config.subtitle ?? '' } },\n * ]\n * })\n * ```\n */\n\nimport type { ZodSchema } from 'zod'\nimport type { Block } from '@pwfabric/core'\nimport { DEFAULT_BLOCK_LAYOUT } from '@pwfabric/core'\nimport { blockRegistry } from '@pwfabric/runtime/blocks'\nimport type {\n FactoryOptions,\n FactoryDefinition,\n FactoryConfig,\n FactoryValidationResult,\n FactoryValidationError,\n BlockSpec,\n} from './types.js'\n\n// ============================================================\n// ID GENERATION\n// ============================================================\n\nlet idCounter = 0\n\n/**\n * Generate a unique block ID\n */\nfunction generateBlockId(type: string): string {\n idCounter += 1\n return `${type}-${idCounter}-${Date.now().toString(36)}`\n}\n\n/**\n * Reset the ID counter (useful for testing)\n */\nexport function resetIdCounter(): void {\n idCounter = 0\n}\n\n// ============================================================\n// VALIDATION\n// ============================================================\n\n/**\n * Validate factory identifier\n */\nfunction validateFactoryId(id: string): void {\n if (typeof id !== 'string') {\n throw new Error('Factory id must be a string')\n }\n\n if (id.length < 2 || id.length > 50) {\n throw new Error('Factory id must be 2-50 characters')\n }\n\n const kebabCaseRegex = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/\n if (!kebabCaseRegex.test(id)) {\n throw new Error(\n `Factory id \"${id}\" must be kebab-case (lowercase letters, numbers, hyphens, starting with a letter)`\n )\n }\n}\n\n/**\n * Validate factory config against schema\n */\nfunction validateConfig<TConfig extends FactoryConfig>(\n config: unknown,\n schema?: ZodSchema<TConfig>\n): FactoryValidationResult<TConfig> {\n if (!schema) {\n // No schema, accept any config\n return {\n valid: true,\n config: config as TConfig,\n }\n }\n\n const result = schema.safeParse(config)\n if (result.success) {\n return {\n valid: true,\n config: result.data,\n }\n }\n\n const errors: FactoryValidationError[] = result.error.issues.map((e) => ({\n path: e.path.map(String).join('.'),\n message: e.message,\n }))\n\n return {\n valid: false,\n errors,\n }\n}\n\n// ============================================================\n// BLOCK SPEC TO BLOCK\n// ============================================================\n\n/**\n * Convert a BlockSpec (without id) to a Block (with id)\n */\nfunction specToBlock(spec: BlockSpec): Block {\n const block: Block = {\n id: generateBlockId(spec.type),\n type: spec.type,\n props: spec.props,\n layout: blockRegistry.get(spec.type)?.defaultLayout ?? DEFAULT_BLOCK_LAYOUT,\n }\n\n if (spec.children && spec.children.length > 0) {\n return {\n ...block,\n children: spec.children.map(specToBlock),\n }\n }\n\n return block\n}\n\n// ============================================================\n// DEFINE FACTORY\n// ============================================================\n\n/**\n * Define a factory function that generates block compositions\n *\n * Factories allow you to create reusable block patterns that can be\n * customized with configuration. They automatically generate unique\n * block IDs and validate configuration against an optional schema.\n *\n * @param options - Factory definition options\n * @returns A frozen factory definition\n *\n * @example\n * ```typescript\n * import { defineFactory } from '@pwfabric/authoring'\n * import { z } from 'zod'\n *\n * // Define a pricing section factory\n * const PricingSectionFactory = defineFactory({\n * id: 'pricing-section',\n * name: 'Pricing Section',\n * description: 'Create a pricing section with multiple tiers',\n * configSchema: z.object({\n * title: z.string(),\n * tiers: z.array(z.object({\n * name: z.string(),\n * price: z.number(),\n * features: z.array(z.string()),\n * })),\n * }),\n * build: (config) => [\n * {\n * type: 'container',\n * props: { direction: 'column', gap: 32 },\n * children: [\n * { type: 'heading', props: { text: config.title, level: 'h2' } },\n * {\n * type: 'grid',\n * props: { columns: config.tiers.length },\n * children: config.tiers.map((tier) => ({\n * type: 'pricing-card',\n * props: {\n * title: tier.name,\n * price: tier.price,\n * features: tier.features,\n * },\n * })),\n * },\n * ],\n * },\n * ],\n * })\n *\n * // Use the factory\n * const blocks = PricingSectionFactory.build({\n * title: 'Choose Your Plan',\n * tiers: [\n * { name: 'Basic', price: 9, features: ['Feature 1'] },\n * { name: 'Pro', price: 29, features: ['Feature 1', 'Feature 2'] },\n * ],\n * })\n * ```\n */\nexport function defineFactory<TConfig extends FactoryConfig = FactoryConfig>(\n options: FactoryOptions<TConfig>\n): FactoryDefinition<TConfig> {\n // Validate required fields\n validateFactoryId(options.id)\n\n if (typeof options.build !== 'function') {\n throw new Error('Factory build function is required')\n }\n\n // Create the build wrapper that converts specs to blocks\n const buildWithIds = (config: TConfig): readonly Block[] => {\n const specs = options.build(config)\n return specs.map(specToBlock)\n }\n\n // Create the validation function\n const validateConfigFn = (config: unknown): FactoryValidationResult<TConfig> => {\n return validateConfig(config, options.configSchema)\n }\n\n const definition = {\n id: options.id,\n name: options.name ?? options.id,\n description: options.description ?? '',\n build: buildWithIds,\n validateConfig: validateConfigFn,\n // Only include configSchema if it's defined\n ...(options.configSchema !== undefined && { configSchema: options.configSchema }),\n } as FactoryDefinition<TConfig>\n\n return Object.freeze(definition)\n}\n\n// ============================================================\n// UTILITY FUNCTIONS\n// ============================================================\n\n/**\n * Check if a value is a factory definition\n */\nexport function isFactoryDefinition(value: unknown): value is FactoryDefinition {\n if (!value || typeof value !== 'object') {\n return false\n }\n\n const def = value as Partial<FactoryDefinition>\n return (\n typeof def.id === 'string' &&\n typeof def.name === 'string' &&\n typeof def.build === 'function' &&\n typeof def.validateConfig === 'function'\n )\n}\n\n/**\n * Compose multiple factory outputs into a single block array\n *\n * @param factories - Array of factory output block arrays\n * @returns Combined block array\n */\nexport function composeFactoryOutputs(\n ...factories: readonly (readonly Block[])[]\n): readonly Block[] {\n return factories.flat()\n}\n\n/**\n * Wrap factory output in a container block\n *\n * @param blocks - Factory output blocks\n * @param containerProps - Props for the wrapper container\n * @returns Single container block with children\n */\nexport function wrapInContainer(\n blocks: readonly Block[],\n containerProps: Record<string, unknown> = {}\n): Block {\n return {\n id: generateBlockId('container'),\n type: 'container',\n props: {\n direction: 'column',\n gap: 24,\n ...containerProps,\n },\n layout: blockRegistry.get('container')?.defaultLayout ?? DEFAULT_BLOCK_LAYOUT,\n children: [...blocks],\n }\n}\n"]}
@@ -24,10 +24,10 @@ export function validateProps(props, schema) {
24
24
  errors: [],
25
25
  };
26
26
  }
27
- const errors = result.error.errors.map((e) => ({
27
+ const errors = result.error.issues.map((e) => ({
28
28
  code: 'VALIDATION_ERROR',
29
29
  message: e.message,
30
- path: e.path.join('.'),
30
+ path: e.path.map(String).join('.'),
31
31
  }));
32
32
  return {
33
33
  valid: false,
@@ -1 +1 @@
1
- {"version":3,"file":"validation.js","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAYH,+DAA+D;AAC/D,mBAAmB;AACnB,+DAA+D;AAE/D;;;;;;GAMG;AACH,MAAM,UAAU,aAAa,CAC3B,KAAc,EACd,MAAyB;IAEzB,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;IAEtC,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;QACnB,OAAO;YACL,KAAK,EAAE,IAAI;YACX,KAAK,EAAE,MAAM,CAAC,IAAI;YAClB,MAAM,EAAE,EAAE;SACX,CAAA;IACH,CAAC;IAED,MAAM,MAAM,GAA2B,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QACrE,IAAI,EAAE,kBAAkB;QACxB,OAAO,EAAE,CAAC,CAAC,OAAO;QAClB,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;KACvB,CAAC,CAAC,CAAA;IAEH,OAAO;QACL,KAAK,EAAE,KAAK;QACZ,MAAM;KACP,CAAA;AACH,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,yBAAyB,CACvC,KAAc,EACd,MAAyB,EACzB,YAAoB;IA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Utilities\n *\n * Schema validation utilities for custom blocks.\n *\n * @module @pwfabric/authoring/validation\n */\n\nimport type { ZodSchema } from 'zod'\nimport type { Block } from '@pwfabric/core'\nimport type {\n CustomBlockDefinition,\n BlockValidationResult,\n BlockValidationError,\n PropsValidationResult,\n ICustomBlockRegistry,\n} from './types.js'\n\n// ============================================================\n// PROPS VALIDATION\n// ============================================================\n\n/**\n * Validate props against a Zod schema\n *\n * @param props - The props to validate\n * @param schema - The Zod schema to validate against\n * @returns Validation result with validated props or errors\n */\nexport function validateProps<TProps extends Record<string, unknown>>(\n props: unknown,\n schema: ZodSchema<TProps>\n): PropsValidationResult<TProps> {\n const result = schema.safeParse(props)\n\n if (result.success) {\n return {\n valid: true,\n props: result.data,\n errors: [],\n }\n }\n\n const errors: BlockValidationError[] = result.error.errors.map((e) => ({\n code: 'VALIDATION_ERROR',\n message: e.message,\n path: e.path.join('.'),\n }))\n\n return {\n valid: false,\n errors,\n }\n}\n\n/**\n * Validate props with defaults applied\n *\n * If validation fails, returns the default props.\n *\n * @param props - The props to validate\n * @param schema - The Zod schema\n * @param defaultProps - Default props to use if validation fails\n * @returns Validated props or defaults\n */\nexport function validatePropsWithDefaults<TProps extends Record<string, unknown>>(\n props: unknown,\n schema: ZodSchema<TProps>,\n defaultProps: TProps\n): TProps {\n const result = schema.safeParse(props)\n return result.success ? result.data : defaultProps\n}\n\n// ============================================================\n// BLOCK VALIDATION\n// ============================================================\n\n/**\n * Validate a block against its definition\n *\n * @param block - The block to validate\n * @param definition - The block definition\n * @returns Validation result\n */\nexport function validateBlock<TProps extends Record<string, unknown>>(\n block: Block,\n definition: CustomBlockDefinition<TProps>\n): BlockValidationResult {\n const errors: BlockValidationError[] = []\n\n // Validate type matches\n if (block.type !== definition.type) {\n errors.push({\n code: 'TYPE_MISMATCH',\n message: `Expected block type \"${definition.type}\", got \"${block.type}\"`,\n })\n return { valid: false, errors }\n }\n\n // Validate props\n const propsResult = validateProps(block.props, definition.schema)\n if (!propsResult.valid) {\n errors.push(...propsResult.errors)\n }\n\n // Validate children constraints\n if (block.children && block.children.length > 0) {\n if (!definition.canHaveChildren) {\n errors.push({\n code: 'CHILDREN_NOT_ALLOWED',\n message: `Block type \"${definition.type}\" cannot have children`,\n })\n }\n\n if (definition.allowedChildren && definition.allowedChildren.length > 0) {\n for (const child of block.children) {\n if (!definition.allowedChildren.includes(child.type)) {\n errors.push({\n code: 'INVALID_CHILD_TYPE',\n message: `Block type \"${child.type}\" is not allowed as a child of \"${definition.type}\"`,\n path: `children.${child.id}`,\n })\n }\n }\n }\n }\n\n if (errors.length > 0) {\n return { valid: false, errors }\n }\n\n return {\n valid: true,\n block: {\n ...block,\n props: propsResult.props ?? block.props,\n },\n errors: [],\n }\n}\n\n/**\n * Validate a block tree against a registry of definitions\n *\n * Recursively validates all blocks in the tree.\n *\n * @param blocks - The blocks to validate\n * @param registry - The block registry\n * @returns Array of validation errors (empty if all valid)\n */\nexport function validateBlockTree(\n blocks: readonly Block[],\n registry: ICustomBlockRegistry\n): readonly BlockValidationError[] {\n const errors: BlockValidationError[] = []\n\n function validateRecursive(block: Block, path: string): void {\n const definition = registry.get(block.type)\n\n if (!definition) {\n // Not a custom block, skip validation\n // (could be a built-in block type)\n if (block.children) {\n block.children.forEach((child: Block, index: number) => {\n validateRecursive(child, `${path}.children[${index}]`)\n })\n }\n return\n }\n\n const result = validateBlock(block, definition)\n if (!result.valid) {\n errors.push(\n ...result.errors.map((e) => ({\n ...e,\n path: e.path ? `${path}.${e.path}` : path,\n }))\n )\n }\n\n if (block.children) {\n block.children.forEach((child: Block, index: number) => {\n validateRecursive(child, `${path}.children[${index}]`)\n })\n }\n }\n\n blocks.forEach((block, index) => {\n validateRecursive(block, `blocks[${index}]`)\n })\n\n return errors\n}\n\n// ============================================================\n// SCHEMA UTILITIES\n// ============================================================\n\n/**\n * Create a validation function for a specific block type\n *\n * @param definition - The block definition\n * @returns A validation function\n */\nexport function createBlockValidator<TProps extends Record<string, unknown>>(\n definition: CustomBlockDefinition<TProps>\n): (block: Block) => BlockValidationResult {\n return (block: Block) => validateBlock(block, definition)\n}\n\n/**\n * Create a props validation function for a specific schema\n *\n * @param schema - The Zod schema\n * @returns A validation function\n */\nexport function createPropsValidator<TProps extends Record<string, unknown>>(\n schema: ZodSchema<TProps>\n): (props: unknown) => PropsValidationResult<TProps> {\n return (props: unknown) => validateProps(props, schema)\n}\n\n// ============================================================\n// ERROR FORMATTING\n// ============================================================\n\n/**\n * Format validation errors as a human-readable string\n *\n * @param errors - The validation errors\n * @returns Formatted error string\n */\nexport function formatValidationErrors(errors: readonly BlockValidationError[]): string {\n if (errors.length === 0) {\n return 'No errors'\n }\n\n return errors\n .map((e) => {\n const path = e.path ? ` at ${e.path}` : ''\n return `[${e.code}]${path}: ${e.message}`\n })\n .join('\\n')\n}\n\n/**\n * Check if a validation result has errors\n */\nexport function hasErrors(result: BlockValidationResult | PropsValidationResult): boolean {\n return !result.valid && result.errors.length > 0\n}\n\n// ============================================================\n// TYPE GUARDS\n// ============================================================\n\n/**\n * Check if a value is a valid Block\n */\nexport function isBlock(value: unknown): value is Block {\n if (!value || typeof value !== 'object') {\n return false\n }\n\n const block = value as Partial<Block>\n return (\n typeof block.id === 'string' &&\n typeof block.type === 'string' &&\n typeof block.props === 'object'\n )\n}\n\n/**\n * Check if a value is a valid Block array\n */\nexport function isBlockArray(value: unknown): value is Block[] {\n return Array.isArray(value) && value.every(isBlock)\n}\n"]}
1
+ {"version":3,"file":"validation.js","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAYH,+DAA+D;AAC/D,mBAAmB;AACnB,+DAA+D;AAE/D;;;;;;GAMG;AACH,MAAM,UAAU,aAAa,CAC3B,KAAc,EACd,MAAyB;IAEzB,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;IAEtC,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;QACnB,OAAO;YACL,KAAK,EAAE,I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;AAE/D;;GAEG;AACH,MAAM,UAAU,OAAO,CAAC,KAAc;IACpC,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACxC,OAAO,KAAK,CAAA;IACd,CAAC;IAED,MAAM,KAAK,GAAG,KAAuB,CAAA;IACrC,OAAO,CACL,OAAO,KAAK,CAAC,EAAE,KAAK,QAAQ;QAC5B,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;QAC9B,OAAO,KAAK,CAAC,KAAK,KAAK,QAAQ,CAChC,CAAA;AACH,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,YAAY,CAAC,KAAc;IACzC,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;AACrD,CAAC","sourcesContent":["/**\n * Validation Utilities\n *\n * Schema validation utilities for custom blocks.\n *\n * @module @pwfabric/authoring/validation\n */\n\nimport type { ZodSchema } from 'zod'\nimport type { Block } from '@pwfabric/core'\nimport type {\n CustomBlockDefinition,\n BlockValidationResult,\n BlockValidationError,\n PropsValidationResult,\n ICustomBlockRegistry,\n} from './types.js'\n\n// ============================================================\n// PROPS VALIDATION\n// ============================================================\n\n/**\n * Validate props against a Zod schema\n *\n * @param props - The props to validate\n * @param schema - The Zod schema to validate against\n * @returns Validation result with validated props or errors\n */\nexport function validateProps<TProps extends Record<string, unknown>>(\n props: unknown,\n schema: ZodSchema<TProps>\n): PropsValidationResult<TProps> {\n const result = schema.safeParse(props)\n\n if (result.success) {\n return {\n valid: true,\n props: result.data,\n errors: [],\n }\n }\n\n const errors: BlockValidationError[] = result.error.issues.map((e) => ({\n code: 'VALIDATION_ERROR',\n message: e.message,\n path: e.path.map(String).join('.'),\n }))\n\n return {\n valid: false,\n errors,\n }\n}\n\n/**\n * Validate props with defaults applied\n *\n * If validation fails, returns the default props.\n *\n * @param props - The props to validate\n * @param schema - The Zod schema\n * @param defaultProps - Default props to use if validation fails\n * @returns Validated props or defaults\n */\nexport function validatePropsWithDefaults<TProps extends Record<string, unknown>>(\n props: unknown,\n schema: ZodSchema<TProps>,\n defaultProps: TProps\n): TProps {\n const result = schema.safeParse(props)\n return result.success ? result.data : defaultProps\n}\n\n// ============================================================\n// BLOCK VALIDATION\n// ============================================================\n\n/**\n * Validate a block against its definition\n *\n * @param block - The block to validate\n * @param definition - The block definition\n * @returns Validation result\n */\nexport function validateBlock<TProps extends Record<string, unknown>>(\n block: Block,\n definition: CustomBlockDefinition<TProps>\n): BlockValidationResult {\n const errors: BlockValidationError[] = []\n\n // Validate type matches\n if (block.type !== definition.type) {\n errors.push({\n code: 'TYPE_MISMATCH',\n message: `Expected block type \"${definition.type}\", got \"${block.type}\"`,\n })\n return { valid: false, errors }\n }\n\n // Validate props\n const propsResult = validateProps(block.props, definition.schema)\n if (!propsResult.valid) {\n errors.push(...propsResult.errors)\n }\n\n // Validate children constraints\n if (block.children && block.children.length > 0) {\n if (!definition.canHaveChildren) {\n errors.push({\n code: 'CHILDREN_NOT_ALLOWED',\n message: `Block type \"${definition.type}\" cannot have children`,\n })\n }\n\n if (definition.allowedChildren && definition.allowedChildren.length > 0) {\n for (const child of block.children) {\n if (!definition.allowedChildren.includes(child.type)) {\n errors.push({\n code: 'INVALID_CHILD_TYPE',\n message: `Block type \"${child.type}\" is not allowed as a child of \"${definition.type}\"`,\n path: `children.${child.id}`,\n })\n }\n }\n }\n }\n\n if (errors.length > 0) {\n return { valid: false, errors }\n }\n\n return {\n valid: true,\n block: {\n ...block,\n props: propsResult.props ?? block.props,\n },\n errors: [],\n }\n}\n\n/**\n * Validate a block tree against a registry of definitions\n *\n * Recursively validates all blocks in the tree.\n *\n * @param blocks - The blocks to validate\n * @param registry - The block registry\n * @returns Array of validation errors (empty if all valid)\n */\nexport function validateBlockTree(\n blocks: readonly Block[],\n registry: ICustomBlockRegistry\n): readonly BlockValidationError[] {\n const errors: BlockValidationError[] = []\n\n function validateRecursive(block: Block, path: string): void {\n const definition = registry.get(block.type)\n\n if (!definition) {\n // Not a custom block, skip validation\n // (could be a built-in block type)\n if (block.children) {\n block.children.forEach((child: Block, index: number) => {\n validateRecursive(child, `${path}.children[${index}]`)\n })\n }\n return\n }\n\n const result = validateBlock(block, definition)\n if (!result.valid) {\n errors.push(\n ...result.errors.map((e) => ({\n ...e,\n path: e.path ? `${path}.${e.path}` : path,\n }))\n )\n }\n\n if (block.children) {\n block.children.forEach((child: Block, index: number) => {\n validateRecursive(child, `${path}.children[${index}]`)\n })\n }\n }\n\n blocks.forEach((block, index) => {\n validateRecursive(block, `blocks[${index}]`)\n })\n\n return errors\n}\n\n// ============================================================\n// SCHEMA UTILITIES\n// ============================================================\n\n/**\n * Create a validation function for a specific block type\n *\n * @param definition - The block definition\n * @returns A validation function\n */\nexport function createBlockValidator<TProps extends Record<string, unknown>>(\n definition: CustomBlockDefinition<TProps>\n): (block: Block) => BlockValidationResult {\n return (block: Block) => validateBlock(block, definition)\n}\n\n/**\n * Create a props validation function for a specific schema\n *\n * @param schema - The Zod schema\n * @returns A validation function\n */\nexport function createPropsValidator<TProps extends Record<string, unknown>>(\n schema: ZodSchema<TProps>\n): (props: unknown) => PropsValidationResult<TProps> {\n return (props: unknown) => validateProps(props, schema)\n}\n\n// ============================================================\n// ERROR FORMATTING\n// ============================================================\n\n/**\n * Format validation errors as a human-readable string\n *\n * @param errors - The validation errors\n * @returns Formatted error string\n */\nexport function formatValidationErrors(errors: readonly BlockValidationError[]): string {\n if (errors.length === 0) {\n return 'No errors'\n }\n\n return errors\n .map((e) => {\n const path = e.path ? ` at ${e.path}` : ''\n return `[${e.code}]${path}: ${e.message}`\n })\n .join('\\n')\n}\n\n/**\n * Check if a validation result has errors\n */\nexport function hasErrors(result: BlockValidationResult | PropsValidationResult): boolean {\n return !result.valid && result.errors.length > 0\n}\n\n// ============================================================\n// TYPE GUARDS\n// ============================================================\n\n/**\n * Check if a value is a valid Block\n */\nexport function isBlock(value: unknown): value is Block {\n if (!value || typeof value !== 'object') {\n return false\n }\n\n const block = value as Partial<Block>\n return (\n typeof block.id === 'string' &&\n typeof block.type === 'string' &&\n typeof block.props === 'object'\n )\n}\n\n/**\n * Check if a value is a valid Block array\n */\nexport function isBlockArray(value: unknown): value is Block[] {\n return Array.isArray(value) && value.every(isBlock)\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pwfabric/authoring",
3
- "version": "1.2.0",
3
+ "version": "2.0.0",
4
4
  "description": "Authoring surface for PWFabric — define blocks, factories and capabilities",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -32,22 +32,22 @@
32
32
  "node": ">=22"
33
33
  },
34
34
  "dependencies": {
35
- "@pwfabric/contracts": "1.2.0",
36
- "@pwfabric/core": "1.2.0",
37
- "@pwfabric/runtime": "1.2.0"
35
+ "@pwfabric/core": "2.0.0",
36
+ "@pwfabric/contracts": "2.0.0",
37
+ "@pwfabric/runtime": "2.0.0"
38
38
  },
39
39
  "peerDependencies": {
40
40
  "react": "^18.0.0 || ^19.0.0",
41
- "zod": "^3.23.0"
41
+ "zod": "^4.6.6"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@types/node": "^22.0.0",
45
45
  "@types/react": "^19.0.0",
46
- "@vitest/coverage-v8": "^2.1.9",
46
+ "@vitest/coverage-v8": "^4.1.12",
47
47
  "react": "^19.0.0",
48
48
  "typescript": "^5.4.0",
49
- "vitest": "^2.0.0",
50
- "zod": "^3.25.76"
49
+ "vitest": "^4.1.12",
50
+ "zod": "^4.6.7"
51
51
  },
52
52
  "publishConfig": {
53
53
  "access": "public"