@pwfabric/embed 1.0.0-rc.1 → 1.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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/render-core.tsx","../src/capabilities-stub.ts","../src/fat.ts","../../core/src/index.ts","../../core/src/errors.ts","../../core/src/logger.ts","../../core/src/errors/ErrorCode.ts","../../core/src/errors/AppError.ts","../../core/src/monitoring/metrics.ts","../../core/src/monitoring/web-vitals.ts","../../core/src/observability/logger.ts","../../core/src/observability/tracer.ts","../../core/src/utils.ts","../../core/src/contract-builder.ts","../../core/src/contracts/passthrough.ts","../../core/src/oauth-scopes.ts","../../core/src/config-schema-builder.ts","../../core/src/state.ts","../../core/src/blocks/types.ts","../../core/src/blocks/layout-schema.ts","../../core/src/blocks/host-imports.ts","../src/thin.ts","../src/build-fat-html.ts","../src/index.ts"],"names":["SurfaceRenderer","generateId","validationError","isCapability","handle","err"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAgLO,SAAS,uBAAuB,OAAA,EAAqC;AAC1E,EAAA,OAAO,wBAAwB,OAAwD,CAAA;AACzF;AAMA,SAAS,mBAAmB,IAAA,EAAkD;AAC5E,EAAA,MAAM,QAAiC,EAAC;AACxC,EAAA,IAAI,IAAA,CAAK,KAAA,KAAU,MAAA,EAAW,KAAA,CAAM,QAAQ,IAAA,CAAK,KAAA;AACjD,EAAA,IAAI,IAAA,CAAK,QAAA,KAAa,MAAA,EAAW,KAAA,CAAM,WAAW,IAAA,CAAK,QAAA;AACvD,EAAA,IAAI,IAAA,CAAK,YAAA,KAAiB,MAAA,EAAW,KAAA,CAAM,eAAe,IAAA,CAAK,YAAA;AAC/D,EAAA,IAAI,IAAA,CAAK,YAAA,KAAiB,MAAA,EAAW,KAAA,CAAM,eAAe,IAAA,CAAK,YAAA;AAC/D,EAAA,IAAI,IAAA,CAAK,WAAA,KAAgB,MAAA,EAAW,K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AA,EAAa;AACnC,EAAA,IAAI,QAAA,CAAS,eAAe,SAAA,EAAW;AACrC,IAAA,QAAA,CAAS,gBAAA,CAAiB,kBAAA,EAAoB,MAAM,QAAA,EAAU,CAAA;AAAA,EAChE,CAAA,MAAO;AAGL,IAAA,cAAA,CAAe,MAAM,UAAU,CAAA;AAAA,EACjC;AACF;AAMO,IAAM,QAAA,GAAW;AAAA,EACtB,MAAA;AAAA,EACA,SAAA;AAAA,EACA,QAAA;AAAA,EACA;AACF;AAEA,IAAO,WAAA,GAAQ","file":"index.js","sourcesContent":["/**\n * Shared mount core for the embed runtime.\n *\n * Wraps the REAL runtime renderer (`SurfaceRenderer` / `DataBoundSurfaceRenderer`,\n * imported as-is from `@pwfabric/runtime`) inside a\n * `DynamicArtifactProvider` and mounts it into a target DOM node with\n * `ReactDOM.createRoot`.\n *\n * Nothing here talks to the network on its own — the caller supplies the\n * already-resolved surface + dynamic block descriptors. Thin mode fetches\n * them first (see `thin.ts`); fat mode passes inline descriptors (see\n * `fat.ts`).\n *\n * @module @pwfabric/embed/render-core\n */\n\nimport * as React from 'react'\nimport * as ReactDOM from 'react-dom/client'\nimport {\n // The aliased export name in the runtime's public `exports` — this IS the\n // canonical `SurfaceRenderer`, re-exported as `BlockSurfaceRenderer` to\n // disambiguate from the surface/* module's own renderer.\n BlockSurfaceRenderer as SurfaceRenderer,\n DataBoundSurfaceRenderer,\n DynamicArtifactProvider,\n surfaceNeedsDataBinding,\n} from '@pwfabric/runtime'\nimport type {\n RenderableSurface,\n DataBoundSurface,\n EntityFacade,\n CapabilityProvider,\n SurfaceEvent,\n ImageAdapter,\n BlockComponentRegistry,\n SurfaceConnectionsValue,\n DataServiceConfig,\n SurfaceDataCache,\n BlockComponentProps,\n} from '@pwfabric/runtime'\nimport type {\n DynamicBlockDescriptor,\n DynamicStarterDescriptor,\n BreakpointName,\n} from '@pwfabric/contracts'\n\n// ============================================================\n// TYPES\n// ============================================================\n\n/**\n * Options accepted by the shared mount. A superset of what both thin and fat\n * mode produce after they have resolved the surface + descriptors.\n */\nexport interface RenderCoreOptions {\n /** Resolved surface to render (blocks + appearance + capabilities). */\n readonly surface: RenderableSurface\n\n /** Dynamic (installed/CDN/inline) block descriptors. */\n readonly dynamicBlocks?: readonly DynamicBlockDescriptor[]\n\n /** Optional dynamic starter descriptors (rarely used in embed). */\n readonly dynamicStarters?: readonly DynamicStarterDescriptor[]\n\n /** App-level light/dark hint passed straight to the renderer. */\n readonly theme?: 'light' | 'dark'\n\n /** Explicit viewport breakpoint override (otherwise auto-detected). */\n readonly viewport?: BreakpointName\n\n /** Capability providers (auth/data/navigation/...). */\n readonly capabilities?: CapabilityProvider[]\n\n /** Entity facade for the platform/entities capability (fat = in-memory). */\n readonly entityFacade?: EntityFacade\n\n /**\n * The surface CONNECTIONS CONTEXT — configured connections +\n * the loaded connector/provider engine registry. When present the render\n * routes `{kind:entity,connector}` data sources through the registry AND\n * exposes the value to blocks via `SurfaceConnectionsContext` (the\n * engine-bridge path, e.g. chat-panel). Absent = today's behavior.\n */\n readonly connections?: SurfaceConnectionsValue\n /**\n * Configuration for the renderer's DataService — the host's own API origin\n * (so the platform store can be called with its cookie and nobody else can)\n * and the token resolver for `authProviderRef`.\n */\n readonly dataServiceConfig?: DataServiceConfig\n /** See DataBoundSurfaceRendererProps — 'gate' withholds the tree until the first fetch, 'immediate' paints at once. */\n readonly loadingStrategy?: 'gate' | 'immediate'\n /** See DataBoundSurfaceRendererProps — yesterday's rows while today's load. */\n readonly dataCache?: SurfaceDataCache\n\n\n /** `live` (default) or `inert` (no auto-refresh, no dispatched actions). */\n readonly interactionMode?: 'live' | 'inert'\n\n /** Base path for links/routing. */\n readonly basePath?: string\n\n /** Image adapter; defaults to plain <img> when omitted. */\n readonly imageAdapter?: ImageAdapter\n\n /** Custom block component overrides (test/preview seams). */\n readonly components?: Partial<BlockComponentRegistry>\n\n /** Surface event callback. */\n readonly onEvent?: (event: SurfaceEvent) => void\n\n /** Grid gap (px) override. */\n readonly gap?: number\n\n /** Surface inner padding (px) override. */\n readonly padding?: number\n\n /**\n * Draw a visible \"rebuild needed\" placeholder for every block type in the\n * surface that has neither a dynamic descriptor nor a component.\n *\n * Off by default, and deliberately so: on a published page an unknown type\n * renders only its children (see the renderer), because a visible\n * placeholder reads as a broken page to a visitor. A live preview is the\n * opposite case — the author has just added a block whose bundle is not in\n * the shipped manifest yet, and an invisible block would look like the edit\n * did nothing. The placeholder is a plain element: nothing is fetched or\n * imported for the missing type.\n */\n readonly placeholderMissingBlocks?: boolean\n}\n\n/**\n * Handle returned by `mountSurface` so the host can later unmount or update.\n */\nexport interface SurfaceMountHandle {\n /** Tear down the React root and free the DOM. */\n unmount(): void\n /** The root DOM node the surface was mounted into. */\n readonly container: HTMLElement\n /**\n * Re-render new surface options into the SAME root — e.g. a client-side\n * page transition. Reuses the root created by `mountSurface` instead of\n * calling `createRoot`/`hydrateRoot` again (which would either throw or\n * discard the existing tree).\n */\n render(opts: RenderCoreOptions): void\n}\n\nexport interface MountSurfaceOptions {\n /**\n * Hydrate existing server-rendered markup already present in `target`\n * (`ReactDOM.hydrateRoot`) instead of a fresh client-only mount\n * (`ReactDOM.createRoot`, which discards whatever DOM was already there).\n * The initial `opts` must produce a tree matching what was server-rendered\n * or React will warn/re-render on mismatch.\n */\n readonly hydrate?: boolean\n}\n\n// ============================================================\n// HELPERS\n// ============================================================\n\n/**\n * Does this surface need the data-bound renderer? The RUNTIME answers —\n * `surfaceNeedsDataBinding` is the same predicate the renderer's own\n * passthrough uses: data sources, `initialState`, declared behaviors,\n * formBindings, or a block `action`.\n *\n * This used to be a second, shorter list (sources + initialState). It had\n * drifted from the renderer's in both directions: a page with only buttons\n * carrying `action` props, or only formBindings, got the plain\n * SurfaceRenderer here — no dispatcher, so the click did nothing and the\n * submit went nowhere.\n */\nexport function needsDataBoundRenderer(surface: RenderableSurface): boolean {\n return surfaceNeedsDataBinding(surface as Parameters<typeof surfaceNeedsDataBinding>[0])\n}\n\n/**\n * Build the props object shared by both renderers, omitting `undefined`\n * keys so `exactOptionalPropertyTypes` stays happy.\n */\nfunction buildRendererProps(opts: RenderCoreOptions): Record<string, unknown> {\n const props: Record<string, unknown> = {}\n if (opts.theme !== undefined) props.theme = opts.theme\n if (opts.viewport !== undefined) props.viewport = opts.viewport\n if (opts.capabilities !== undefined) props.capabilities = opts.capabilities\n if (opts.entityFacade !== undefined) props.entityFacade = opts.entityFacade\n if (opts.connections !== undefined) props.connections = opts.connections\n if (opts.dataServiceConfig !== undefined) props.dataServiceConfig = opts.dataServiceConfig\n if (opts.loadingStrategy !== undefined) props.loadingStrategy = opts.loadingStrategy\n if (opts.dataCache !== undefined) props.dataCache = opts.dataCache\n if (opts.interactionMode !== undefined) props.interactionMode = opts.interactionMode\n if (opts.basePath !== undefined) props.basePath = opts.basePath\n if (opts.imageAdapter !== undefined) props.imageAdapter = opts.imageAdapter\n if (opts.components !== undefined) props.components = opts.components\n if (opts.onEvent !== undefined) props.onEvent = opts.onEvent\n if (opts.gap !== undefined) props.gap = opts.gap\n if (opts.padding !== undefined) props.padding = opts.padding\n return props\n}\n\n// ============================================================\n// MISSING BLOCK TYPES\n// ============================================================\n\n/**\n * Every block type in `surface` that nothing can render: no dynamic\n * descriptor and no component. Walks `blocks` and `children` recursively.\n */\nexport function missingBlockTypes(\n surface: RenderableSurface,\n dynamicBlocks: readonly DynamicBlockDescriptor[] | undefined,\n components: Partial<BlockComponentRegistry> | undefined\n): string[] {\n const known = new Set<string>()\n for (const d of dynamicBlocks ?? []) known.add(d.blockType)\n for (const k of Object.keys(components ?? {})) known.add(k)\n const missing = new Set<string>()\n const walk = (nodes: unknown): void => {\n if (!Array.isArray(nodes)) return\n for (const node of nodes) {\n if (!node || typeof node !== 'object') continue\n const n = node as { type?: unknown; children?: unknown }\n if (typeof n.type === 'string' && n.type && !known.has(n.type)) missing.add(n.type)\n walk(n.children)\n }\n }\n walk((surface as { blocks?: unknown }).blocks)\n return [...missing]\n}\n\n/**\n * The placeholder for a block type whose bundle this page does not have.\n * Static markup only — it never asks for the type's code. Children still\n * render inside it, so a missing container does not hide its subtree.\n */\nexport function RebuildNeededBlock({ block, children }: BlockComponentProps): React.ReactElement {\n return React.createElement(\n 'div',\n {\n 'data-pw-rebuild-needed': block.type,\n role: 'note',\n style: {\n border: '1px dashed currentColor',\n borderRadius: 6,\n padding: 12,\n opacity: 0.7,\n fontSize: 13,\n },\n },\n React.createElement('span', null, `Rebuild needed: \"${block.type}\" is not in this preview yet.`),\n children ?? null\n )\n}\n\nfunction withPlaceholders(opts: RenderCoreOptions): Partial<BlockComponentRegistry> | undefined {\n if (!opts.placeholderMissingBlocks) return opts.components\n const missing = missingBlockTypes(opts.surface, opts.dynamicBlocks, opts.components)\n if (missing.length === 0) return opts.components\n const added = Object.fromEntries(missing.map((t) => [t, RebuildNeededBlock])) as Partial<BlockComponentRegistry>\n return { ...added, ...(opts.components ?? {}) }\n}\n\n// ============================================================\n// ELEMENT FACTORY\n// ============================================================\n\n/**\n * Build the React element tree for a surface — `DynamicArtifactProvider`\n * wrapping the appropriate renderer. Exposed separately from `mountSurface`\n * so it can be used in SSR / test contexts without a DOM root.\n */\nexport function createSurfaceElement(opts: RenderCoreOptions): React.ReactElement {\n // A connections context also requires the data-bound renderer\n // — it is what provides `SurfaceConnectionsContext` (engine-bridge blocks) and\n // routes connector data sources through the registry. A surface with only\n // engine-bridge panels declares no dataSources, so force it on when present.\n const useDataBound = needsDataBoundRenderer(opts.surface) || opts.connections != null\n const components = withPlaceholders(opts)\n const shared = buildRendererProps(components && components !== opts.components ? { ...opts, components } : opts)\n\n const rendererElement = useDataBound\n ? React.createElement(DataBoundSurfaceRenderer, {\n surface: opts.surface as DataBoundSurface,\n ...shared,\n })\n : React.createElement(SurfaceRenderer, {\n surface: opts.surface,\n ...shared,\n })\n\n return React.createElement(\n DynamicArtifactProvider,\n {\n ...(opts.dynamicBlocks && opts.dynamicBlocks.length > 0\n ? { dynamicBlocks: opts.dynamicBlocks }\n : {}),\n ...(opts.dynamicStarters && opts.dynamicStarters.length > 0\n ? { dynamicStarters: opts.dynamicStarters }\n : {}),\n children: rendererElement,\n }\n )\n}\n\n// ============================================================\n// MOUNT\n// ============================================================\n\n/**\n * Resolve a target — an HTMLElement or a CSS selector string — to a node.\n */\nexport function resolveTarget(target: HTMLElement | string): HTMLElement {\n if (typeof target === 'string') {\n const el = document.querySelector(target)\n if (!el) {\n throw new Error(`[pwfabric-embed] target not found: ${target}`)\n }\n return el as HTMLElement\n }\n return target\n}\n\n/**\n * Mount a surface into `target` and return a handle for later teardown or\n * update. Pass `{ hydrate: true }` to attach to existing server-rendered\n * markup instead of discarding it.\n */\nexport function mountSurface(\n target: HTMLElement | string,\n opts: RenderCoreOptions,\n mountOptions?: MountSurfaceOptions\n): SurfaceMountHandle {\n const container = resolveTarget(target)\n const root = mountOptions?.hydrate\n ? ReactDOM.hydrateRoot(container, createSurfaceElement(opts))\n : ReactDOM.createRoot(container)\n if (!mountOptions?.hydrate) root.render(createSurfaceElement(opts))\n return {\n container,\n unmount() {\n root.unmount()\n },\n render(newOpts: RenderCoreOptions) {\n root.render(createSurfaceElement(newOpts))\n },\n }\n}\n","/**\n * Offline capability stubs for fat mode.\n *\n * Fat mode renders with no API and no auth, so any capability the surface\n * declares (entities, navigation, persistence) must be satisfied locally.\n * These factories provide in-memory / no-op implementations:\n *\n * - `createOfflineEntityFacade()` — a real `createEntityFacade()` backed by\n * the in-memory `StaticConnector`, optionally seeded with entity defs +\n * records. CRUD happens entirely in memory.\n * - `createOfflineNavigationProvider()` — a `navigation` CapabilityProvider\n * whose links resolve to in-page anchors (no router).\n * - `staticDataSources()` — turns a record-map of inline data into\n * `platform/persistence` static data sources for the DataBoundSurfaceRenderer.\n *\n * @module @pwfabric/embed/capabilities-stub\n */\n\nimport { createEntityFacade, StaticConnector } from '@pwfabric/runtime'\nimport type { EntityFacade, CapabilityProvider } from '@pwfabric/runtime'\nimport type { EntityDefinition } from '@pwfabric/runtime'\n\n// ============================================================\n// ENTITY FACADE (in-memory CRUD)\n// ============================================================\n\nexport interface OfflineEntitySeed {\n /** Entity definition to register. */\n readonly definition: EntityDefinition\n /** Initial records to load into the static connector. */\n readonly records?: readonly Record<string, unknown>[]\n}\n\n/**\n * Build an entity facade wired to a single in-memory `StaticConnector`.\n * All CRUD performed by the surface happens in memory and is lost on reload —\n * exactly what an offline embed wants.\n */\nexport function createOfflineEntityFacade(seeds?: readonly OfflineEntitySeed[]): EntityFacade {\n const connector = new StaticConnector('offline')\n const facade = createEntityFacade()\n // Register the single static connector under its name.\n facade.connectors.register(connector)\n\n if (seeds) {\n for (const seed of seeds) {\n facade.registerEntity(seed.definition, connector.name)\n if (seed.records) {\n for (const record of seed.records) {\n // Fire-and-forget seed — the static connector resolves synchronously\n // enough for a first render, and errors here are non-fatal.\n void connector.create(seed.definition.id, record)\n }\n }\n }\n }\n\n return facade\n}\n\n// ============================================================\n// NAVIGATION (no-op / in-page)\n// ============================================================\n\n/**\n * A `navigation` capability provider for offline rendering. There is no\n * router, so navigation is reduced to in-page anchors / `window.location`.\n * The provider exposes a `data` payload the navigation-aware blocks read.\n */\nexport function createOfflineNavigationProvider(\n options: { readonly basePath?: string } = {}\n): CapabilityProvider {\n const basePath = options.basePath ?? ''\n return {\n type: 'navigation',\n data: {\n mode: 'offline',\n basePath,\n /** Resolve a href against the base path; absolute/anchor hrefs pass through. */\n resolve(href: string): string {\n if (/^([a-z]+:)?\\/\\//i.test(href) || href.startsWith('#')) return href\n return `${basePath}${href}`\n },\n /** No-op push — offline embeds have no history stack. */\n push(): void {\n /* intentionally inert */\n },\n },\n }\n}\n\n// ============================================================\n// STATIC DATA SOURCES\n// ============================================================\n\n/**\n * Convert a map of `{ sourceId: data }` into the `platform/persistence`\n * capability config shape (static data sources) that the\n * DataBoundSurfaceRenderer consumes. Use this to inline mock/fixture data into\n * a fat embed so REST-bound blocks render without a backend.\n */\nexport function staticPersistenceCapability(\n data: Readonly<Record<string, unknown>>,\n initialState?: Record<string, unknown>\n): CapabilityProvider & { capability: string; config: Record<string, unknown> } {\n const dataSources = Object.entries(data).map(([id, staticData]) => ({\n id,\n kind: 'static' as const,\n staticData,\n }))\n return {\n type: 'data',\n capability: 'platform/persistence',\n config: {\n dataSources,\n ...(initialState ? { initialState } : {}),\n },\n } as CapabilityProvider & { capability: string; config: Record<string, unknown> }\n}\n","/**\n * Fat mode renderer — fully offline.\n *\n * Renders a surface with NO API and NO auth. The surface JSON, its block\n * bundle descriptors, and its appearance are all provided inline by the\n * caller. Capabilities default to the offline stubs (in-memory entity facade,\n * inert navigation), so a surface that declares capabilities still renders.\n *\n * Offline block loading: `DynamicBlockDescriptor.moduleUrl` may be a `data:`\n * URL (or any URL the host can `fetch`). The runtime's `BlockModuleLoader`\n * fetches the bytes, SHA-256-verifies them against `descriptor.integrity`,\n * and `import()`s the resulting Blob URL — all client-side, no server. As long\n * as the descriptors carry inline `data:` module URLs + correct integrity\n * hashes, the whole render is self-contained.\n *\n * @module @pwfabric/embed/fat\n */\n\nimport { mountSurface, type SurfaceMountHandle } from './render-core.js'\nimport { createOfflineEntityFacade, createOfflineNavigationProvider } from './capabilities-stub.js'\nimport { isCapability } from '@pwfabric/runtime/capability'\nimport type { RenderCoreOptions } from './render-core.js'\nimport type {\n EntityFacade,\n CapabilityProvider,\n RenderableSurface,\n SurfaceConnectionsValue,\n DataServiceConfig,\n SurfaceDataCache,\n} from '@pwfabric/runtime'\nimport type { DynamicBlockDescriptor } from '@pwfabric/contracts'\n\n// ============================================================\n// TYPES\n// ============================================================\n\nexport interface RenderFatOptions {\n /** The surface to render (inline JSON). */\n readonly surface: RenderableSurface\n\n /**\n * Block bundle descriptors. `moduleUrl` is typically a `data:text/javascript`\n * URL for full offline self-containment; integrity must match the bytes.\n */\n readonly blocks?: readonly DynamicBlockDescriptor[]\n\n /**\n * Capability providers. When omitted, offline stubs are auto-supplied for\n * any capability the surface declares (entities → in-memory facade,\n * navigation → inert provider).\n */\n readonly capabilities?: CapabilityProvider[]\n\n /** Override the auto-created offline entity facade. */\n readonly entityFacade?: EntityFacade\n\n /**\n * Connector/provider engine registry + configured\n * connections. The runner builds this from the export's shipped engine\n * bundles + the PKCE auth token, so connector panels (chat-panel etc.) run\n * against real engines. Threaded to the data-bound renderer, which exposes it\n * via `SurfaceConnectionsContext`.\n */\n readonly connections?: SurfaceConnectionsValue\n /**\n * How the data layer authenticates its requests.\n *\n * Carries the resolver a pwapp runner supplies for the VISITOR's own\n * session: a source that names an `authProviderRef` gets an\n * `Authorization: Bearer` header for it. Declared here because fat mode is\n * how a published app renders, and a published app behind a sign-in has to\n * fetch its own records as the person who signed in.\n */\n readonly dataServiceConfig?: DataServiceConfig\n readonly loadingStrategy?: 'gate' | 'immediate'\n readonly dataCache?: SurfaceDataCache\n\n /** Inline appearance ref; overrides `surface.appearance` when given. */\n readonly appearance?: RenderableSurface['appearance']\n\n /**\n * Hydrate existing server-rendered markup in `target` instead of a fresh\n * client-only mount. See `MountSurfaceOptions.hydrate`.\n */\n readonly hydrate?: boolean\n\n // Passthrough render options.\n readonly theme?: RenderCoreOptions['theme']\n readonly viewport?: RenderCoreOptions['viewport']\n readonly interactionMode?: RenderCoreOptions['interactionMode']\n readonly basePath?: RenderCoreOptions['basePath']\n readonly imageAdapter?: RenderCoreOptions['imageAdapter']\n readonly components?: RenderCoreOptions['components']\n readonly onEvent?: RenderCoreOptions['onEvent']\n readonly gap?: RenderCoreOptions['gap']\n readonly padding?: RenderCoreOptions['padding']\n /** See `RenderCoreOptions.placeholderMissingBlocks` — preview hosts only. */\n readonly placeholderMissingBlocks?: RenderCoreOptions['placeholderMissingBlocks']\n}\n\n/**\n * The handle fat mode returns. `update` re-renders new fat options into the\n * SAME root, through the same option translation the first mount used — so a\n * host holding fat options (blocks, appearance override, offline stubs) never\n * has to rebuild the core options by hand.\n */\nexport interface FatMountHandle extends SurfaceMountHandle {\n update(opts: RenderFatOptions): void\n}\n\n// ============================================================\n// HELPERS\n// ============================================================\n\nfunction surfaceDeclares(surface: RenderableSurface, capability: string): boolean {\n // Compare CANONICALLY. A receipt may spell a capability short (`entities`)\n // or long (`platform/entities`); a raw `===` misses the short form and this\n // path builds neither the offline navigation provider nor the entity facade —\n // the panel silently stays empty. The three sibling call sites use\n // `isCapability` too.\n return (surface.capabilities ?? []).some((c: { capability?: string }) => isCapability(c, capability))\n}\n\n/**\n * Build the capability list + entity facade for an offline render, supplying\n * stubs for any declared capability the caller didn't provide.\n */\nexport function resolveOfflineCapabilities(opts: RenderFatOptions): {\n capabilities: CapabilityProvider[]\n entityFacade: EntityFacade | undefined\n} {\n const capabilities: CapabilityProvider[] = [...(opts.capabilities ?? [])]\n\n // Navigation stub when declared and not already supplied.\n if (\n surfaceDeclares(opts.surface, 'platform/navigation') &&\n !capabilities.some((c) => c.type === 'navigation')\n ) {\n capabilities.push(\n createOfflineNavigationProvider(opts.basePath ? { basePath: opts.basePath } : {})\n )\n }\n\n // Entity facade: explicit > auto-created (when entities declared).\n let entityFacade = opts.entityFacade\n if (!entityFacade && surfaceDeclares(opts.surface, 'platform/entities')) {\n entityFacade = createOfflineEntityFacade()\n }\n\n return { capabilities, entityFacade }\n}\n\n// ============================================================\n// RENDER\n// ============================================================\n\n/**\n * Translate fat options into the shared core options: offline capability\n * stubs, the appearance override folded into the surface, every passthrough.\n */\nexport function fatCoreOptions(opts: RenderFatOptions): RenderCoreOptions {\n const { capabilities, entityFacade } = resolveOfflineCapabilities(opts)\n\n // `appearance` is a distinct, top-level override — RenderCoreOptions has no\n // separate appearance channel, so the ONLY way it reaches SurfaceRenderer\n // is via `surface.appearance`. Merge it in here (rather than relying on the\n // caller to have baked it into the surface already) so `opts.appearance`\n // actually does what its doc comment says instead of being silently dropped.\n const surface = opts.appearance ? { ...opts.surface, appearance: opts.appearance } : opts.surface\n\n return {\n surface,\n ...(opts.blocks ? { dynamicBlocks: opts.blocks } : {}),\n ...(capabilities.length > 0 ? { capabilities } : {}),\n ...(entityFacade ? { entityFacade } : {}),\n ...(opts.connections ? { connections: opts.connections } : {}),\n // A HAND-COPIED LIST. `RenderFatOptions` declares this and\n // `RenderCoreOptions` accepts it; this line is the copy between them.\n // Without it a pwapp visitor signs in, the gate lifts, and every data\n // request still goes out anonymous — `getAccessToken` is never called\n // because the DataService has no config.\n ...(opts.dataServiceConfig ? { dataServiceConfig: opts.dataServiceConfig } : {}),\n ...(opts.loadingStrategy !== undefined ? { loadingStrategy: opts.loadingStrategy } : {}),\n ...(opts.dataCache !== undefined ? { dataCache: opts.dataCache } : {}),\n ...(opts.theme !== undefined ? { theme: opts.theme } : {}),\n ...(opts.viewport !== undefined ? { viewport: opts.viewport } : {}),\n ...(opts.interactionMode !== undefined ? { interactionMode: opts.interactionMode } : {}),\n ...(opts.basePath !== undefined ? { basePath: opts.basePath } : {}),\n ...(opts.imageAdapter !== undefined ? { imageAdapter: opts.imageAdapter } : {}),\n ...(opts.components !== undefined ? { components: opts.components } : {}),\n ...(opts.onEvent !== undefined ? { onEvent: opts.onEvent } : {}),\n ...(opts.gap !== undefined ? { gap: opts.gap } : {}),\n ...(opts.padding !== undefined ? { padding: opts.padding } : {}),\n ...(opts.placeholderMissingBlocks !== undefined\n ? { placeholderMissingBlocks: opts.placeholderMissingBlocks }\n : {}),\n }\n}\n\n/**\n * Render a surface fully offline into `target`.\n */\nexport function renderFat(\n target: HTMLElement | string,\n opts: RenderFatOptions\n): FatMountHandle {\n const core = fatCoreOptions(opts)\n const handle = mountSurface(target, core, opts.hydrate ? { hydrate: true } : undefined)\n // The offline entity facade the first mount created holds the page's\n // in-memory records. An update that supplies none keeps that one instead of\n // starting from an empty store on every edit.\n const firstFacade = core.entityFacade\n return {\n container: handle.container,\n unmount: () => handle.unmount(),\n render: (next) => handle.render(next),\n update(next: RenderFatOptions) {\n const withFacade = !next.entityFacade && firstFacade ? { ...next, entityFacade: firstFacade } : next\n handle.render(fatCoreOptions(withFacade))\n },\n }\n}\n","/**\n * @pwfabric/core\n *\n * Core functionality and utilities for the PWFabric platform.\n *\n * PHASE0-WS3: Core orchestration layer\n * Platform hardening (errors, monitoring, observability)\n *\n * @module @pwfabric/core\n */\n\n// Re-export contracts for convenience\nexport * from '@pwfabric/contracts'\n\n// Core exports - explicitly exclude conflicting names\nexport {\n PWFabricError,\n ValidationError as CoreValidationError,\n NotFoundError,\n UnauthorizedError,\n ForbiddenError,\n} from './errors.js'\n\nexport { type LogLevel, type LogEntry, Logger, createLogger } from './logger.js'\n\n// Error infrastructure\nexport {\n ErrorCode,\n type ErrorCodeType,\n getHttpStatus,\n isRetryable,\n AppError,\n ValidationAppError,\n NetworkAppError,\n EditorAppError,\n type ErrorContext,\n type SerializedError,\n} from './errors/index.js'\n\n// Monitoring infrastructure\nexport {\n type WebVitalName,\n type MetricRating,\n type Metric,\n type WebVitalMetric,\n type TimingMetric,\n type RenderMetric,\n type PerformanceBudget,\n type MetricsState,\n DEFAULT_BUDGET,\n createMetricsState,\n getRating,\n type WebVitalCallback,\n observeLCP,\n observeFID,\n observeCLS,\n observeTTFB,\n observeINP,\n observeFCP,\n observeAllWebVitals,\n} from './monitoring/index.js'\n\n// Observability infrastructure\nexport {\n type LogContext,\n type ILogger,\n ConsoleLogger,\n createObservabilityLogger,\n type TraceContext,\n type Span,\n type SpanResult,\n createTraceContext,\n createChildContext,\n createSpan,\n extractTraceId,\n injectTraceId,\n} from './observability/index.js'\n\nexport {\n // ok and err are already exported from contracts\n sleep,\n retry,\n generateId,\n} from './utils.js'\n\n// Builders (PHASE0-WS3)\nexport { ContractBuilder, defineContract, anySchema, objectSchema } from './contract-builder.js'\n\n// Canonical contracts\nexport { passthroughContract } from './contracts/passthrough.js'\n\n// Delegated OAuth scope lists — the ONE reader. Three copies of a\n// tolerant reader once split a JSON string into scope-shaped garbage and sent\n// it to Microsoft; consumers import this instead of remembering the rule.\nexport { isScopeToken, readScopeList, type ScopeListReading } from './oauth-scopes.js'\n\nexport { CapabilityBuilder, defineCapability } from './capability-builder.js'\n\nexport {\n FieldBuilder,\n ConfigSchemaBuilder,\n SimpleConfigSchema,\n defineConfigSchema,\n} from './config-schema-builder.js'\n\n// State management (PHASE0-WS3)\nexport {\n type StateStore,\n type StateListener,\n type StateSnapshot,\n type Selector,\n type Transition,\n type StateMachineConfig,\n type StateMachine,\n SimpleStateStore,\n SimpleStateMachine,\n createStateStore,\n computed,\n subscribeToSlice,\n createStateMachine,\n} from './state.js'\n\n// Block ecosystem types and layout schema\n// Block schemas, definitions, rule engine, and React components are in @pwfabric/runtime/blocks (retired standalone package)\nexport {\n // Types\n type BlockCategory,\n type BlockDefinition,\n type Block,\n type ValidationError as BlockValidationError,\n type ValidationResult as BlockValidationResult,\n type CompositionRuleType,\n type CompositionRule,\n MAX_NESTING_DEPTH,\n BLOCK_CATEGORIES,\n // Layout schema\n type BreakpointName,\n type BreakpointDefinition,\n type ResponsiveValue,\n type BlockLayout,\n type PreviewViewport,\n BREAKPOINTS,\n BREAKPOINT_ORDER,\n DEFAULT_BLOCK_LAYOUT,\n VIEWPORT_PRESETS,\n responsiveNumberSchema,\n responsiveBooleanSchema,\n blockLayoutSchema,\n resolveResponsiveValue,\n resolveSpanAtBreakpoint,\n getColumnsAtBreakpoint,\n getBreakpointForWidth,\n // Block host imports — the one list the bundler, the host import maps and the\n // shim files all derive from.\n BLOCK_HOST_IMPORTS,\n blockBundleExternals,\n blockImportMap,\n blockShimFiles,\n blockHostGlobals,\n unseededHostGlobals,\n specifiersForShim,\n type HostImport,\n type HostImportKind,\n type HostSeeding,\n} from './blocks/index.js'\n","/**\n * Custom error classes for PWFabric\n */\n\n/**\n * Base error class for all PWFabric errors\n */\nexport class PWFabricError extends Error {\n public readonly code: string\n public readonly timestamp: Date\n\n constructor(message: string, code: string, options?: ErrorOptions) {\n super(message, options)\n this.name = 'PWFabricError'\n this.code = code\n this.timestamp = new Date()\n }\n}\n\n/**\n * Validation error\n */\nexport class ValidationError extends PWFabricError {\n public readonly field: string | undefined\n\n constructor(message: string, field?: string, options?: ErrorOptions) {\n super(message, 'VALIDATION_ERROR', options)\n this.name = 'ValidationError'\n this.field = field\n }\n}\n\n/**\n * Not found error\n */\nexport class NotFoundError extends PWFabricError {\n public readonly resource: string\n\n constructor(resource: string, options?: ErrorOptions) {\n super(`${resource} not found`, 'NOT_FOUND', options)\n this.name = 'NotFoundError'\n this.resource = resource\n }\n}\n\n/**\n * Unauthorized error\n */\nexport class UnauthorizedError extends PWFabricError {\n constructor(message = 'Unauthorized', options?: ErrorOptions) {\n super(message, 'UNAUTHORIZED', options)\n this.name = 'UnauthorizedError'\n }\n}\n\n/**\n * Forbidden error\n */\nexport class ForbiddenError extends PWFabricError {\n constructor(message = 'Forbidden', options?: ErrorOptions) {\n super(message, 'FORBIDDEN', options)\n this.name = 'ForbiddenError'\n }\n}\n","/**\n * Logger utility for PWFabric\n */\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\nexport interface LogEntry {\n level: LogLevel\n message: string\n timestamp: Date\n context: Record<string, unknown> | undefined\n}\n\n/**\n * Simple logger implementation\n */\nexport class Logger {\n private readonly name: string\n private readonly minLevel: LogLevel\n\n private static readonly levels: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n }\n\n constructor(name: string, minLevel: LogLevel = 'info') {\n this.name = name\n this.minLevel = minLevel\n }\n\n private shouldLog(level: LogLevel): boolean {\n return Logger.levels[level] >= Logger.levels[this.minLevel]\n }\n\n private log(level: LogLevel, message: string, context?: Record<string, unknown>): void {\n if (!this.shouldLog(level)) return\n\n const entry: LogEntry = {\n level,\n message,\n timestamp: new Date(),\n context,\n }\n\n const output = `[${entry.timestamp.toISOString()}] [${level.toUpperCase()}] [${this.name}] ${message}`\n\n if (level === 'error') {\n console.error(output, context ?? '')\n } else if (level === 'warn') {\n console.warn(output, context ?? '')\n } else {\n // Using console.info for debug and info to avoid eslint no-console warning\n // In production, this would be replaced with a proper logging library\n process.stdout.write(output + (context ? ` ${JSON.stringify(context)}` : '') + '\\n')\n }\n }\n\n debug(message: string, context?: Record<string, unknown>): void {\n this.log('debug', message, context)\n }\n\n info(message: string, context?: Record<string, unknown>): void {\n this.log('info', message, context)\n }\n\n warn(message: string, context?: Record<string, unknown>): void {\n this.log('warn', message, context)\n }\n\n error(message: string, context?: Record<string, unknown>): void {\n this.log('error', message, context)\n }\n\n child(name: string): Logger {\n return new Logger(`${this.name}:${name}`, this.minLevel)\n }\n}\n\n/**\n * Create a logger instance\n */\nexport function createLogger(name: string, level?: LogLevel): Logger {\n return new Logger(name, level)\n}\n","/**\n * Error Codes\n *\n * Standardized error codes for PWFabric platform\n *\n * @module @pwfabric/core/errors/ErrorCode\n */\n\n/**\n * Error code categories\n */\nexport const ErrorCode = {\n // Validation errors (1xxx)\n VALIDATION_FAILED: 'VALIDATION_FAILED',\n INVALID_INPUT: 'INVALID_INPUT',\n MISSING_REQUIRED: 'MISSING_REQUIRED',\n INVALID_FORMAT: 'INVALID_FORMAT',\n\n // Network errors (2xxx)\n NETWORK_ERROR: 'NETWORK_ERROR',\n TIMEOUT: 'TIMEOUT',\n CONNECTION_FAILED: 'CONNECTION_FAILED',\n REQUEST_FAILED: 'REQUEST_FAILED',\n\n // Authentication errors (3xxx)\n UNAUTHORIZED: 'UNAUTHORIZED',\n FORBIDDEN: 'FORBIDDEN',\n TOKEN_EXPIRED: 'TOKEN_EXPIRED',\n INVALID_CREDENTIALS: 'INVALID_CREDENTIALS',\n\n // Resource errors (4xxx)\n NOT_FOUND: 'NOT_FOUND',\n ALREADY_EXISTS: 'ALREADY_EXISTS',\n CONFLICT: 'CONFLICT',\n GONE: 'GONE',\n\n // Runtime errors (5xxx)\n RUNTIME_ERROR: 'RUNTIME_ERROR',\n INTERNAL_ERROR: 'INTERNAL_ERROR',\n SERVICE_UNAVAILABLE: 'SERVICE_UNAVAILABLE',\n NOT_IMPLEMENTED: 'NOT_IMPLEMENTED',\n\n // Editor errors (6xxx)\n EDITOR_ERROR: 'EDITOR_ERROR',\n BLOCK_NOT_FOUND: 'BLOCK_NOT_FOUND',\n INVALID_OPERATION: 'INVALID_OPERATION',\n RENDER_ERROR: 'RENDER_ERROR',\n} as const\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]\n\n/**\n * Get HTTP status code for an error code\n */\nexport function getHttpStatus(code: ErrorCode): number {\n switch (code) {\n case ErrorCode.VALIDATION_FAILED:\n case ErrorCode.INVALID_INPUT:\n case ErrorCode.MISSING_REQUIRED:\n case ErrorCode.INVALID_FORMAT:\n return 400\n\n case ErrorCode.UNAUTHORIZED:\n case ErrorCode.TOKEN_EXPIRED:\n case ErrorCode.INVALID_CREDENTIALS:\n return 401\n\n case ErrorCode.FORBIDDEN:\n return 403\n\n case ErrorCode.NOT_FOUND:\n case ErrorCode.BLOCK_NOT_FOUND:\n case ErrorCode.GONE:\n return 404\n\n case ErrorCode.CONFLICT:\n case ErrorCode.ALREADY_EXISTS:\n return 409\n\n case ErrorCode.TIMEOUT:\n return 408\n\n case ErrorCode.SERVICE_UNAVAILABLE:\n return 503\n\n case ErrorCode.NOT_IMPLEMENTED:\n return 501\n\n default:\n return 500\n }\n}\n\n/**\n * Check if error code is retryable\n */\nexport function isRetryable(code: ErrorCode): boolean {\n const retryableCodes: ErrorCode[] = [\n ErrorCode.NETWORK_ERROR,\n ErrorCode.TIMEOUT,\n ErrorCode.CONNECTION_FAILED,\n ErrorCode.SERVICE_UNAVAILABLE,\n ]\n return retryableCodes.includes(code)\n}\n","/**\n * Application Error Classes\n *\n * Custom error class hierarchy with code, message, context, and cause\n *\n * @module @pwfabric/core/errors/AppError\n */\n\nimport { type ErrorCode, getHttpStatus, isRetryable } from './ErrorCode.js'\n\n/**\n * Error context for additional debugging information\n */\nexport type ErrorContext = Readonly<Record<string, unknown>>\n\n/**\n * Serialized error format for API responses\n */\nexport interface SerializedError {\n readonly code: ErrorCode\n readonly message: string\n readonly timestamp: string\n readonly traceId?: string\n readonly context?: ErrorContext\n}\n\n/**\n * Base application error class\n *\n * All application errors should extend this class\n */\nexport class AppError extends Error {\n public readonly code: ErrorCode\n public readonly timestamp: Date\n public readonly context: ErrorContext | undefined\n public readonly isRetryable: boolean\n public readonly httpStatus: number\n\n constructor(\n code: ErrorCode,\n message: string,\n options?: {\n cause?: Error\n context?: ErrorContext\n }\n ) {\n super(message, { cause: options?.cause })\n this.name = 'AppError'\n this.code = code\n this.timestamp = new Date()\n this.context = options?.context\n this.isRetryable = isRetryable(code)\n this.httpStatus = getHttpStatus(code)\n }\n\n /**\n * Serialize error for API response\n */\n toJSON(traceId?: string): SerializedError {\n return {\n code: this.code,\n message: this.message,\n timestamp: this.timestamp.toISOString(),\n ...(traceId && { traceId }),\n ...(this.context && { context: this.context }),\n }\n }\n\n /**\n * Create error from unknown value\n */\n static from(error: unknown, code: ErrorCode = 'RUNTIME_ERROR'): AppError {\n if (error instanceof AppError) {\n return error\n }\n\n if (error instanceof Error) {\n return new AppError(code, error.message, { cause: error })\n }\n\n return new AppError(code, String(error))\n }\n}\n\n/**\n * Validation error for input validation failures\n */\nexport class ValidationAppError extends AppError {\n public readonly field: string | undefined\n\n constructor(\n message: string,\n options?: {\n field?: string\n cause?: Error\n context?: ErrorContext\n }\n ) {\n const baseOptions: { cause?: Error; context?: ErrorContext } = {}\n if (options?.cause) {\n baseOptions.cause = options.cause\n }\n if (options?.context || options?.field) {\n baseOptions.context = { ...options?.context, field: options?.field }\n }\n super('VALIDATION_FAILED', message, baseOptions)\n this.name = 'ValidationAppError'\n this.field = options?.field\n }\n}\n\n/**\n * Network error for connectivity issues\n */\nexport class NetworkAppError extends AppError {\n public readonly url: string | undefined\n public readonly statusCode: number | undefined\n\n constructor(\n message: string,\n options?: {\n url?: string\n statusCode?: number\n cause?: Error\n context?: ErrorContext\n }\n ) {\n const baseOptions: { cause?: Error; context?: ErrorContext } = {}\n if (options?.cause) {\n baseOptions.cause = options.cause\n }\n if (options?.context || options?.url || options?.statusCode) {\n baseOptions.context = {\n ...options?.context,\n url: options?.url,\n statusCode: options?.statusCode,\n }\n }\n super('NETWORK_ERROR', message, baseOptions)\n this.name = 'NetworkAppError'\n this.url = options?.url\n this.statusCode = options?.statusCode\n }\n}\n\n/**\n * Editor error for studio/editor operations\n */\nexport class EditorAppError extends AppError {\n public readonly blockId: string | undefined\n public readonly operation: string | undefined\n\n constructor(\n message: string,\n options?: {\n code?: ErrorCode\n blockId?: string\n operation?: string\n cause?: Error\n context?: ErrorContext\n }\n ) {\n const baseOptions: { cause?: Error; context?: ErrorContext } = {}\n if (options?.cause) {\n baseOptions.cause = options.cause\n }\n if (options?.context || options?.blockId || options?.operation) {\n baseOptions.context = {\n ...options?.context,\n blockId: options?.blockId,\n operation: options?.operation,\n }\n }\n super(options?.code ?? 'EDITOR_ERROR', message, baseOptions)\n this.name = 'EditorAppError'\n this.blockId = options?.blockId\n this.operation = options?.operation\n }\n}\n","/**\n * Performance Metrics Types\n *\n * Type definitions for performance monitoring\n *\n * @module @pwfabric/core/monitoring/metrics\n */\n\n/**\n * Web Vitals metric names\n */\nexport type WebVitalName = 'LCP' | 'FID' | 'CLS' | 'TTFB' | 'INP' | 'FCP'\n\n/**\n * Metric rating\n */\nexport type MetricRating = 'good' | 'needs-improvement' | 'poor'\n\n/**\n * Base metric interface\n */\nexport interface Metric {\n readonly name: string\n readonly value: number\n readonly timestamp: number\n}\n\n/**\n * Web Vital metric\n */\nexport interface WebVitalMetric extends Metric {\n readonly name: WebVitalName\n readonly rating: MetricRating\n readonly delta: number\n readonly entries: readonly PerformanceEntry[]\n}\n\n/**\n * Custom timing metric\n */\nexport interface TimingMetric extends Metric {\n readonly name: string\n readonly duration: number\n readonly startTime: number\n readonly endTime: number\n readonly metadata?: Record<string, unknown> | undefined\n}\n\n/**\n * Component render metric\n */\nexport interface RenderMetric extends Metric {\n readonly name: string\n readonly componentName: string\n readonly renderCount: number\n readonly duration: number\n}\n\n/**\n * Performance budget thresholds\n */\nexport interface PerformanceBudget {\n readonly LCP: number\n readonly FID: number\n readonly CLS: number\n readonly TTFB: number\n readonly INP: number\n}\n\n/**\n * Default performance budgets based on Core Web Vitals thresholds\n */\nexport const DEFAULT_BUDGET: PerformanceBudget = {\n LCP: 2500, // 2.5s\n FID: 100, // 100ms\n CLS: 0.1, // 0.1\n TTFB: 800, // 800ms\n INP: 200, // 200ms\n}\n\n/**\n * Metric collection state\n */\nexport interface MetricsState {\n readonly webVitals: Record<WebVitalName, WebVitalMetric | null>\n readonly timings: readonly TimingMetric[]\n readonly renders: readonly RenderMetric[]\n readonly budget: PerformanceBudget\n}\n\n/**\n * Create initial metrics state\n */\nexport function createMetricsState(budget: Partial<PerformanceBudget> = {}): MetricsState {\n return {\n webVitals: {\n LCP: null,\n FID: null,\n CLS: null,\n TTFB: null,\n INP: null,\n FCP: null,\n },\n timings: [],\n renders: [],\n budget: { ...DEFAULT_BUDGET, ...budget },\n }\n}\n\n/**\n * Get rating for a Web Vital metric\n */\nexport function getRating(name: WebVitalName, value: number): MetricRating {\n const thresholds: Record<WebVitalName, [number, number]> = {\n LCP: [2500, 4000],\n FID: [100, 300],\n CLS: [0.1, 0.25],\n TTFB: [800, 1800],\n INP: [200, 500],\n FCP: [1800, 3000],\n }\n\n const [good, poor] = thresholds[name]\n if (value <= good) return 'good'\n if (value <= poor) return 'needs-improvement'\n return 'poor'\n}\n","/**\n * Web Vitals Collection\n *\n * Collection of Core Web Vitals using Performance API\n *\n * @module @pwfabric/core/monitoring/web-vitals\n */\n\nimport { type WebVitalName, type WebVitalMetric, getRating } from './metrics.js'\n\n/**\n * Callback for when a Web Vital is collected\n */\nexport type WebVitalCallback = (metric: WebVitalMetric) => void\n\n/**\n * Create a Web Vital metric from performance entries\n */\nfunction createWebVitalMetric(\n name: WebVitalName,\n value: number,\n delta: number,\n entries: PerformanceEntry[]\n): WebVitalMetric {\n return {\n name,\n value,\n delta,\n rating: getRating(name, value),\n timestamp: Date.now(),\n entries,\n }\n}\n\n/**\n * Observe Largest Contentful Paint (LCP)\n */\nexport function observeLCP(callback: WebVitalCallback): (() => void) | undefined {\n if (typeof PerformanceObserver === 'undefined') return undefined\n\n let lastValue = 0\n const entries: PerformanceEntry[] = []\n\n const observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n const lcpEntry = entry as PerformanceEntry & { startTime: number }\n entries.push(entry)\n const value = lcpEntry.startTime\n const delta = value - lastValue\n lastValue = value\n callback(createWebVitalMetric('LCP', value, delta, [...entries]))\n }\n })\n\n try {\n observer.observe({ type: 'largest-contentful-paint', buffered: true })\n return () => observer.disconnect()\n } catch {\n return undefined\n }\n}\n\n/**\n * Observe First Input Delay (FID)\n */\nexport function observeFID(callback: WebVitalCallback): (() => void) | undefined {\n if (typeof PerformanceObserver === 'undefined') return undefined\n\n const entries: PerformanceEntry[] = []\n\n const observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n const fidEntry = entry as PerformanceEventTiming\n entries.push(entry)\n const value = fidEntry.processingStart - fidEntry.startTime\n callback(createWebVitalMetric('FID', value, value, [...entries]))\n }\n })\n\n try {\n observer.observe({ type: 'first-input', buffered: true })\n return () => observer.disconnect()\n } catch {\n return undefined\n }\n}\n\n/**\n * Observe Cumulative Layout Shift (CLS)\n */\nexport function observeCLS(callback: WebVitalCallback): (() => void) | undefined {\n if (typeof PerformanceObserver === 'undefined') return undefined\n\n let clsValue = 0\n const entries: PerformanceEntry[] = []\n\n const observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n const layoutShift = entry as PerformanceEntry & {\n hadRecentInput: boolean\n value: number\n }\n if (!layoutShift.hadRecentInput) {\n const delta = layoutShift.value\n clsValue += delta\n entries.push(entry)\n callback(createWebVitalMetric('CLS', clsValue, delta, [...entries]))\n }\n }\n })\n\n try {\n observer.observe({ type: 'layout-shift', buffered: true })\n return () => observer.disconnect()\n } catch {\n return undefined\n }\n}\n\n/**\n * Observe Time to First Byte (TTFB)\n */\nexport function observeTTFB(callback: WebVitalCallback): void {\n if (typeof window === 'undefined' || typeof performance === 'undefined') return\n\n const navigationEntry = performance.getEntriesByType('navigation')[0] as\n | PerformanceNavigationTiming\n | undefined\n\n if (navigationEntry) {\n const value = navigationEntry.responseStart - navigationEntry.requestStart\n callback(createWebVitalMetric('TTFB', value, value, [navigationEntry]))\n }\n}\n\n/**\n * Observe Interaction to Next Paint (INP)\n */\nexport function observeINP(callback: WebVitalCallback): (() => void) | undefined {\n if (typeof PerformanceObserver === 'undefined') return undefined\n\n let maxINP = 0\n const entries: PerformanceEntry[] = []\n\n const observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n const eventEntry = entry as PerformanceEventTiming\n const duration = eventEntry.duration\n if (duration > maxINP) {\n maxINP = duration\n entries.push(entry)\n callback(createWebVitalMetric('INP', duration, duration, [...entries]))\n }\n }\n })\n\n try {\n observer.observe({ type: 'event', buffered: true })\n return () => observer.disconnect()\n } catch {\n return undefined\n }\n}\n\n/**\n * Observe First Contentful Paint (FCP)\n */\nexport function observeFCP(callback: WebVitalCallback): (() => void) | undefined {\n if (typeof PerformanceObserver === 'undefined') return undefined\n\n const entries: PerformanceEntry[] = []\n\n const observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n if (entry.name === 'first-contentful-paint') {\n entries.push(entry)\n const value = entry.startTime\n callback(createWebVitalMetric('FCP', value, value, [...entries]))\n }\n }\n })\n\n try {\n observer.observe({ type: 'paint', buffered: true })\n return () => observer.disconnect()\n } catch {\n return undefined\n }\n}\n\n/**\n * Observe all Web Vitals\n */\nexport function observeAllWebVitals(callback: WebVitalCallback): () => void {\n const cleanups: ((() => void) | undefined)[] = []\n\n cleanups.push(observeLCP(callback))\n cleanups.push(observeFID(callback))\n cleanups.push(observeCLS(callback))\n cleanups.push(observeINP(callback))\n cleanups.push(observeFCP(callback))\n\n // TTFB is synchronous\n observeTTFB(callback)\n\n return () => {\n for (const cleanup of cleanups) {\n cleanup?.()\n }\n }\n}\n","/**\n * Logger Interface\n *\n * Structured logging interface for observability\n *\n * @module @pwfabric/core/observability/logger\n */\n\n/**\n * Log levels\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\n/**\n * Log context\n */\nexport interface LogContext {\n readonly traceId?: string\n readonly [key: string]: unknown\n}\n\n/**\n * Structured log entry\n */\nexport interface LogEntry {\n readonly level: LogLevel\n readonly message: string\n readonly timestamp: string\n readonly name: string\n readonly context?: LogContext\n}\n\n/**\n * Logger interface\n */\nexport interface ILogger {\n debug(message: string, context?: LogContext): void\n info(message: string, context?: LogContext): void\n warn(message: string, context?: LogContext): void\n error(message: string, context?: LogContext): void\n child(name: string): ILogger\n}\n\n/**\n * Log level priority\n */\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n}\n\n/**\n * Environment detection\n */\nfunction isProduction(): boolean {\n if (typeof process !== 'undefined' && process.env) {\n return process.env.NODE_ENV === 'production'\n }\n return false\n}\n\n/**\n * Console logger implementation\n *\n * In development: human-readable format\n * In production: structured JSON format\n */\nexport class ConsoleLogger implements ILogger {\n private readonly name: string\n private readonly minLevel: LogLevel\n private readonly production: boolean\n\n constructor(name: string, minLevel: LogLevel = 'info') {\n this.name = name\n this.minLevel = minLevel\n this.production = isProduction()\n }\n\n private shouldLog(level: LogLevel): boolean {\n return LOG_LEVELS[level] >= LOG_LEVELS[this.minLevel]\n }\n\n private formatEntry(level: LogLevel, message: string, context?: LogContext): LogEntry {\n return {\n level,\n message,\n timestamp: new Date().toISOString(),\n name: this.name,\n ...(context && { context }),\n }\n }\n\n private log(level: LogLevel, message: string, context?: LogContext): void {\n if (!this.shouldLog(level)) return\n\n const entry = this.formatEntry(level, message, context)\n\n if (this.production) {\n // Production: structured JSON\n const output = JSON.stringify(entry)\n if (level === 'error') {\n console.error(output)\n } else if (level === 'warn') {\n console.warn(output)\n } else {\n console.log(output)\n }\n } else {\n // Development: human-readable\n const prefix = `[${entry.timestamp}] [${level.toUpperCase()}] [${this.name}]`\n const output = `${prefix} ${message}`\n\n if (level === 'error') {\n console.error(output, context ?? '')\n } else if (level === 'warn') {\n console.warn(output, context ?? '')\n } else {\n console.log(output, context ?? '')\n }\n }\n }\n\n debug(message: string, context?: LogContext): void {\n this.log('debug', message, context)\n }\n\n info(message: string, context?: LogContext): void {\n this.log('info', message, context)\n }\n\n warn(message: string, context?: LogContext): void {\n this.log('warn', message, context)\n }\n\n error(message: string, context?: LogContext): void {\n this.log('error', message, context)\n }\n\n child(name: string): ILogger {\n return new ConsoleLogger(`${this.name}:${name}`, this.minLevel)\n }\n}\n\n/**\n * Create a logger instance\n */\nexport function createObservabilityLogger(name: string, minLevel?: LogLevel): ILogger {\n return new ConsoleLogger(name, minLevel)\n}\n","/**\n * Trace Context\n *\n * Request tracing for observability\n *\n * @module @pwfabric/core/observability/tracer\n */\n\n/**\n * Trace context\n */\nexport interface TraceContext {\n readonly traceId: string\n readonly spanId: string\n readonly parentSpanId?: string\n readonly startTime: number\n}\n\n/**\n * Span represents a unit of work\n */\nexport interface Span {\n readonly context: TraceContext\n readonly name: string\n readonly startTime: number\n end(): SpanResult\n}\n\n/**\n * Completed span result\n */\nexport interface SpanResult {\n readonly context: TraceContext\n readonly name: string\n readonly startTime: number\n readonly endTime: number\n readonly duration: number\n}\n\n/**\n * Generate a random trace/span ID\n */\nfunction generateId(): string {\n const bytes = new Uint8Array(16)\n if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n crypto.getRandomValues(bytes)\n } else {\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Math.floor(Math.random() * 256)\n }\n }\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/**\n * Create a new trace context\n */\nexport function createTraceContext(parentSpanId?: string): TraceContext {\n const context: TraceContext = {\n traceId: generateId(),\n spanId: generateId().slice(0, 16),\n startTime: Date.now(),\n }\n if (parentSpanId !== undefined) {\n return { ...context, parentSpanId }\n }\n return context\n}\n\n/**\n * Create a child span from existing context\n */\nexport function createChildContext(parent: TraceContext): TraceContext {\n return {\n traceId: parent.traceId,\n spanId: generateId().slice(0, 16),\n parentSpanId: parent.spanId,\n startTime: Date.now(),\n }\n}\n\n/**\n * Create a span for tracing\n */\nexport function createSpan(name: string, parentContext?: TraceContext): Span {\n const context = parentContext ? createChildContext(parentContext) : createTraceContext()\n const startTime = performance.now()\n\n return {\n context,\n name,\n startTime,\n end(): SpanResult {\n const endTime = performance.now()\n return {\n context,\n name,\n startTime,\n endTime,\n duration: endTime - startTime,\n }\n },\n }\n}\n\n/**\n * Extract trace ID from headers\n */\nexport function extractTraceId(\n headers: Headers | Record<string, string | undefined>\n): string | undefined {\n if (headers instanceof Headers) {\n return headers.get('x-trace-id') ?? undefined\n }\n return headers['x-trace-id']\n}\n\n/**\n * Inject trace ID into headers\n */\nexport function injectTraceId(headers: Headers | Record<string, string>, traceId: string): void {\n if (headers instanceof Headers) {\n headers.set('x-trace-id', traceId)\n } else {\n headers['x-trace-id'] = traceId\n }\n}\n","/**\n * Utility functions for PWFabric\n */\n\nimport type { Result } from '@pwfabric/contracts'\n\n/**\n * Create a successful result\n */\nexport function ok<T>(data: T): Result<T, never> {\n return { success: true, data }\n}\n\n/**\n * Create a failed result\n */\nexport function err<E>(error: E): Result<never, E> {\n return { success: false, error }\n}\n\n/**\n * Sleep for a specified duration\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Retry an async operation with exponential backoff\n */\nexport async function retry<T>(\n fn: () => Promise<T>,\n options: {\n maxAttempts?: number\n initialDelay?: number\n maxDelay?: number\n backoffFactor?: number\n } = {}\n): Promise<T> {\n const { maxAttempts = 3, initialDelay = 1000, maxDelay = 30000, backoffFactor = 2 } = options\n\n let lastError: Error | undefined\n let delay = initialDelay\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await fn()\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error))\n\n if (attempt === maxAttempts) {\n throw lastError\n }\n\n await sleep(delay)\n delay = Math.min(delay * backoffFactor, maxDelay)\n }\n }\n\n throw lastError\n}\n\n/**\n * Generate a random ID (for development purposes)\n * In production, use crypto.randomUUID()\n */\nexport function generateId(): string {\n return crypto.randomUUID()\n}\n","/**\n * Contract Builder\n *\n * PHASE0-WS3: Fluent API for building contracts\n *\n * @module @pwfabric/core/contract-builder\n */\n\nimport type {\n Contract,\n ContractId,\n ContractMetadata,\n ContractState,\n ContractError,\n Schema,\n ValidationResult,\n SerializedContract,\n SemanticVersion,\n} from '@pwfabric/contracts'\nimport {\n contractId,\n parseVersion,\n INITIAL_VERSION,\n ok,\n err,\n validationError,\n} from '@pwfabric/contracts'\n\n// ============================================================\n// SIMPLE SCHEMA IMPLEMENTATION\n// ============================================================\n\n/**\n * Minimal schema implementation backed by a validator function.\n */\nclass SimpleSchema<T> implements Schema<T> {\n readonly definition\n private readonly validator: (data: unknown) => ValidationResult<T>\n\n constructor(\n definition: Schema<T>['definition'],\n validator: (data: unknown) => ValidationResult<T>\n ) {\n this.definition = definition\n this.validator = validator\n }\n\n validate(data: unknown): ValidationResult<T> {\n return this.validator(data)\n }\n\n parse(data: unknown): T {\n const result = this.validate(data)\n if (result.success) {\n return result.data\n }\n throw new Error(`Validation failed: ${JSON.stringify(result.error)}`)\n }\n\n safeParse(data: unknown): ValidationResult<T> {\n return this.validate(data)\n }\n\n toJsonSchema(): Record<string, unknown> {\n return { type: 'object' }\n }\n}\n\n/**\n * Create a schema that accepts any value\n */\nexport function anySchema<T = unknown>(): Schema<T> {\n return new SimpleSchema<T>({ type: 'unknown' }, (data) => ok(data as T))\n}\n\n/**\n * Create a schema that validates an object\n */\nexport function objectSchema<T extends Record<string, unknown>>(): Schema<T> {\n return new SimpleSchema<T>({ type: 'object', properties: {}, required: [] }, (data) => {\n if (typeof data !== 'object' || data === null) {\n return err([validationError([], 'Expected object', 'type_error')])\n }\n return ok(data as T)\n })\n}\n\n// ============================================================\n// CONTRACT IMPLEMENTATION\n// ============================================================\n\n/**\n * Simple contract implementation\n */\nclass SimpleContract<TInput, TOutput, TError = ContractError> implements Contract<\n TInput,\n TOutput,\n TError\n> {\n readonly id: ContractId\n readonly version: SemanticVersion\n readonly metadata: ContractMetadata\n readonly input: Schema<TInput>\n readonly output: Schema<TOutput>\n readonly errors: readonly Schema<TError>[]\n\n constructor(config: {\n id: ContractId\n version: SemanticVersion\n metadata: ContractMetadata\n input: Schema<TInput>\n output: Schema<TOutput>\n errors?: readonly Schema<TError>[]\n }) {\n this.id = config.id\n this.version = config.version\n this.metadata = config.metadata\n this.input = config.input\n this.output = config.output\n this.errors = config.errors ?? []\n }\n\n validateInput(data: unknown): ValidationResult<TInput> {\n return this.input.validate(data)\n }\n\n validateOutput(data: unknown): ValidationResult<TOutput> {\n return this.output.validate(data)\n }\n\n validateError(data: unknown): ValidationResult<TError> {\n for (const schema of this.errors) {\n const result = schema.validate(data)\n if (result.success) {\n return result\n }\n }\n return err([validationError([], 'Unknown error type', 'unknown_error')])\n }\n\n serialize(): SerializedContract {\n return {\n id: this.id,\n version: `${this.version.major}.${this.version.minor}.${this.version.patch}`,\n metadata: this.metadata,\n input: {\n version: '1.0.0',\n definition: this.input.definition,\n jsonSchema: this.input.toJsonSchema(),\n },\n output: {\n version: '1.0.0',\n definition: this.output.definition,\n jsonSchema: this.output.toJsonSchema(),\n },\n errors: this.errors.map((e) => ({\n version: '1.0.0',\n definition: e.definition,\n jsonSchema: e.toJsonSchema(),\n })),\n }\n }\n}\n\n// ============================================================\n// CONTRACT BUILDER\n// ============================================================\n\n/**\n * Contract builder for fluent API\n */\nexport class ContractBuilder<TInput = unknown, TOutput = unknown> {\n private _id = ''\n private _version = '0.1.0'\n private _name = ''\n private _description?: string\n private _state: ContractState = 'draft'\n private _tags?: readonly string[]\n private _inputSchema: Schema<TInput> = anySchema<TInput>()\n private _outputSchema: Schema<TOutput> = anySchema<TOutput>()\n\n /**\n * Set the contract ID\n */\n id(id: string): this {\n this._id = id\n return this\n }\n\n /**\n * Set the contract version\n */\n version(version: string): this {\n this._version = version\n return this\n }\n\n /**\n * Set the contract name\n */\n name(name: string): this {\n this._name = name\n return this\n }\n\n /**\n * Set the contract description\n */\n description(description: string): this {\n this._description = description\n return this\n }\n\n /**\n * Set the contract state\n */\n state(state: ContractState): this {\n this._state = state\n return this\n }\n\n /**\n * Set the contract tags\n */\n tags(tags: readonly string[]): this {\n this._tags = tags\n return this\n }\n\n /**\n * Set the input schema\n */\n input<T>(schema: Schema<T>): ContractBuilder<T, TOutput> {\n const builder = this as unknown as ContractBuilder<T, TOutput>\n builder._inputSchema = schema as unknown as Schema<T>\n return builder\n }\n\n /**\n * Set the output schema\n */\n output<T>(schema: Schema<T>): ContractBuilder<TInput, T> {\n const builder = this as unknown as ContractBuilder<TInput, T>\n builder._outputSchema = schema as unknown as Schema<T>\n return builder\n }\n\n /**\n * Build the contract\n */\n build(): Contract<TInput, TOutput> {\n if (!this._id) {\n throw new Error('Contract ID is required')\n }\n if (!this._name) {\n throw new Error('Contract name is required')\n }\n\n const metadata: ContractMetadata = {\n name: this._name,\n state: this._state,\n }\n if (this._description !== undefined) {\n ;(metadata as { description?: string }).description = this._description\n }\n if (this._tags !== undefined) {\n ;(metadata as { tags?: readonly string[] }).tags = this._tags\n }\n\n return new SimpleContract<TInput, TOutput>({\n id: contractId(this._id),\n version: parseVersion(this._version) ?? INITIAL_VERSION,\n metadata,\n input: this._inputSchema,\n output: this._outputSchema,\n })\n }\n}\n\n/**\n * Create a new contract builder\n */\nexport function defineContract<TInput = unknown, TOutput = unknown>(): ContractBuilder<\n TInput,\n TOutput\n> {\n return new ContractBuilder<TInput, TOutput>()\n}\n","/**\n * Passthrough Contract\n *\n * A canonical declaration-only contract used by platform capabilities\n * (persistence, navigation, interaction, entities) that accept any input\n * and produce any output with no schema validation.\n *\n * Moved from `@pwfabric/runtime/capability/platform-capabilities.ts` to\n * `@pwfabric/core/contracts/passthrough` so pwpack-authored capabilities\n * can import it without a runtime dependency.\n *\n * @module @pwfabric/core/contracts/passthrough\n */\n\nimport { defineContract, anySchema } from '../contract-builder.js'\n\nexport const passthroughContract = defineContract()\n .id('platform/passthrough')\n .name('Platform Passthrough')\n .description('Passthrough contract for platform capability declarations')\n .state('stable')\n .input(anySchema())\n .output(anySchema())\n .build()\n","/**\n * Delegated OAuth scope lists — the one reader\n *\n * WHY A STRING IS REFUSED. A scope list stored as a string and split on\n * `/[\\s,]+/` turns the JSON TEXT `[\"Sites.Read.All\",\"User.Read\"]` into\n * `[\"Sites.Read.All\"` and `\"User.Read\"]` — things shaped like scopes that an\n * identity provider refuses (Microsoft Entra: `AADSTS650053 ... asked for\n * scope '[\"Sites.Read.All\"'`).\n *\n * A scope list is a LIST; a string is not a list awaiting a parse, it is a\n * malformed value. Separate readers would each get a chance to disagree,\n * which is why this is one module the consumers import rather than a rule\n * each of them remembers.\n *\n * WHY A READER FORGIVES AND A WRITER DOES NOT. The write boundary rejects\n * outright (HTTP 400 — see the API's scope-shape guard): nothing malformed\n * should enter. A reader, though, runs at render time against rows that are\n * already stored, and a canvas that throws over one bad row is worse than one\n * that shows the row as broken. So it keeps what is usable, sets aside what is\n * not, and RETURNS the rejects so a surface can display them. The original bug\n * survived precisely because nothing ever surfaced them.\n *\n * @module @pwfabric/core/oauth-scopes\n */\n\n/**\n * Characters that cannot appear inside a delegated scope.\n *\n * Deliberately a REJECT-list rather than an allow-list: real scopes come bare\n * (`Sites.Read.All`, `offline_access`), URI-qualified\n * (`https://graph.microsoft.com/Mail.Read`) and app-id-qualified\n * (`api://<guid>/access_as_user`), and an allow-list tight enough to be\n * useful would refuse valid scopes from a provider we have not met yet. What\n * IS refused is what a scope can never contain: whitespace (the OAuth\n * delimiter itself), and the quotes/brackets/commas that betray a stringified\n * array. `[\"Sites.Read.All\"` fails on three counts.\n */\nconst FORBIDDEN_IN_SCOPE = /[\\s\"'[\\]{},\\\\]/\n\n/** Whether a single token is shaped like a delegated OAuth scope. */\nexport function isScopeToken(token: unknown): token is string {\n return typeof token === 'string' && token.length > 0 && !FORBIDDEN_IN_SCOPE.test(token)\n}\n\n/** What a stored scope value turned out to be. */\nexport interface ScopeListReading {\n /** The usable scopes, de-duplicated, first-seen order preserved. */\n readonly scopes: readonly string[]\n /**\n * Entries that are not scopes, as they were stored (stringified). Carried\n * back so a surface can show what it refused instead of silently dropping\n * it — silence is what let the original fault reach Microsoft.\n */\n readonly rejected: readonly string[]\n /**\n * True when the VALUE ITSELF was not a list (most often a JSON string).\n * Distinct from \"a list containing bad entries\": one is a shape error at\n * the field, the other is a content error inside it.\n */\n readonly malformed: boolean\n}\n\nconst EMPTY: ScopeListReading = { scopes: [], rejected: [], malformed: false }\n\n/**\n * Read a stored scope value. Never throws, for any input.\n *\n * `undefined`/`null`/`[]` are an empty list, not a fault — an atom that needs\n * no delegated permission is a normal atom.\n */\nexport function readScopeList(value: unknown): ScopeListReading {\n if (value === undefined || value === null) return EMPTY\n\n if (!Array.isArray(value)) {\n // A string is NOT split — splitting is what manufactures invalid tokens.\n return { scopes: [], rejected: [safeShow(value)], malformed: true }\n }\n\n const scopes: string[] = []\n const rejected: string[] = []\n const seen = new Set<string>()\n\n for (const entry of value) {\n if (isScopeToken(entry)) {\n if (!seen.has(entry)) {\n seen.add(entry)\n scopes.push(entry)\n }\n } else {\n rejected.push(safeShow(entry))\n }\n }\n\n return { scopes, rejected, malformed: false }\n}\n\n/** Render any value for display without throwing (Symbols throw on `String`). */\nfunction safeShow(value: unknown): string {\n try {\n return typeof value === 'string' ? value : String(value)\n } catch {\n return Object.prototype.toString.call(value)\n }\n}\n","/**\n * ConfigSchema Builder\n *\n * Fluent API for building typed configuration schemas.\n *\n * Usage:\n * ```ts\n * const schema = defineConfigSchema<MyConfig>()\n * .field('trackingId', f => f.string().required().label('Tracking ID'))\n * .field('anonymize', f => f.boolean().default(false).label('Anonymize IPs'))\n * .build()\n * ```\n *\n * @module @pwfabric/core/config-schema-builder\n */\n\nimport type {\n ConfigFieldConstraints,\n ConfigFieldDefinition,\n ConfigFieldOption,\n ConfigFieldType,\n ConfigSchema,\n ValidationResult,\n} from '@pwfabric/contracts'\nimport { validationOk, validationErr, validationError } from '@pwfabric/contracts'\n\n// ============================================================\n// FIELD BUILDER\n// ============================================================\n\nexport class FieldBuilder {\n private _type: ConfigFieldType = 'string'\n private _required = false\n private _defaultValue?: unknown\n private _label = ''\n private _description?: string\n private _sensitive?: boolean\n private _options?: ConfigFieldOption[]\n private _constraints?: ConfigFieldConstraints\n\n string(): this {\n this._type = 'string'\n return this\n }\n\n number(): this {\n this._type = 'number'\n return this\n }\n\n boolean(): this {\n this._type = 'boolean'\n return this\n }\n\n select(options: readonly (string | ConfigFieldOption)[]): this {\n this._type = 'select'\n this._options = options.map((o) => (typeof o === 'string' ? { value: o, label: o } : o))\n return this\n }\n\n multiSelect(options: readonly (string | ConfigFieldOption)[]): this {\n this._type = 'multi-select'\n this._options = options.map((o) => (typeof o === 'string' ? { value: o, label: o } : o))\n return this\n }\n\n url(): this {\n this._type = 'url'\n return this\n }\n\n email(): this {\n this._type = 'email'\n return this\n }\n\n json(): this {\n this._type = 'json'\n return this\n }\n\n required(): this {\n this._required = true\n return this\n }\n\n default(value: unknown): this {\n this._defaultValue = value\n return this\n }\n\n label(s: string): this {\n this._label = s\n return this\n }\n\n description(s: string): this {\n this._description = s\n return this\n }\n\n sensitive(): this {\n this._sensitive = true\n return this\n }\n\n min(n: number): this {\n this._constraints = { ...this._constraints, min: n }\n return this\n }\n\n max(n: number): this {\n this._constraints = { ...this._constraints, max: n }\n return this\n }\n\n pattern(s: string, msg?: string): this {\n this._constraints = { ...this._constraints, pattern: s }\n if (msg) {\n this._constraints = { ...this._constraints, patternMessage: msg }\n }\n return this\n }\n\n /** @internal */\n _build(key: string, group: string | undefined, order: number): ConfigFieldDefinition {\n const def: ConfigFieldDefinition = {\n key,\n type: this._type,\n required: this._required,\n label: this._label || key,\n ...(this._defaultValue !== undefined ? { defaultValue: this._defaultValue } : {}),\n ...(this._description !== undefined ? { description: this._description } : {}),\n ...(group !== undefined ? { group } : {}),\n ...(order !== 0 ? { order } : {}),\n ...(this._sensitive === true ? { sensitive: true } : {}),\n ...(this._options !== undefined ? { options: this._options } : {}),\n ...(this._constraints !== undefined ? { constraints: this._constraints } : {}),\n }\n return def\n }\n}\n\n// ============================================================\n// SCHEMA BUILDER\n// ============================================================\n\ninterface PendingField {\n key: string\n factory: (f: FieldBuilder) => FieldBuilder\n group?: string\n}\n\nexport class ConfigSchemaBuilder<TConfig = Record<string, unknown>> {\n private _fields: PendingField[] = []\n\n field(key: string, factory: (f: FieldBuilder) => FieldBuilder): this {\n this._fields.push({ key, factory })\n return this\n }\n\n group(name: string, groupFn: (g: ConfigSchemaGroupBuilder) => void): this {\n const gb = new ConfigSchemaGroupBuilder(name)\n groupFn(gb)\n this._fields.push(...gb._getFields())\n return this\n }\n\n build(): ConfigSchema<TConfig> {\n const fields: ConfigFieldDefinition[] = this._fields.map((pf, idx) => {\n const fb = new FieldBuilder()\n pf.factory(fb)\n return fb._build(pf.key, pf.group, idx)\n })\n return new SimpleConfigSchema<TConfig>(fields)\n }\n}\n\nclass ConfigSchemaGroupBuilder {\n private _fields: PendingField[] = []\n private readonly _name: string\n\n constructor(name: string) {\n this._name = name\n }\n\n field(key: string, factory: (f: FieldBuilder) => FieldBuilder): this {\n this._fields.push({ key, factory, group: this._name })\n return this\n }\n\n /** @internal */\n _getFields(): PendingField[] {\n return this._fields\n }\n}\n\n// ============================================================\n// SIMPLE CONFIG SCHEMA IMPLEMENTATION\n// ============================================================\n\nexport class SimpleConfigSchema<\n TConfig = Record<string, unknown>,\n> implements ConfigSchema<TConfig> {\n readonly fields: readonly ConfigFieldDefinition[]\n\n constructor(fields: ConfigFieldDefinition[]) {\n this.fields = fields\n }\n\n validate(data: unknown): ValidationResult<TConfig> {\n const errors: { path: string[]; message: string; code: string }[] = []\n const record = (typeof data === 'object' && data !== null ? data : {}) as Record<\n string,\n unknown\n >\n\n for (const field of this.fields) {\n const value = record[field.key]\n\n if (value === undefined || value === null || value === '') {\n if (field.required && field.defaultValue === undefined) {\n errors.push(validationError([field.key], `${field.label} is required`, 'required'))\n }\n continue\n }\n\n // Type validation\n const typeError = this.validateType(field, value)\n if (typeError) {\n errors.push(validationError([field.key], typeError, 'type'))\n continue\n }\n\n // Constraint validation\n if (field.constraints) {\n const constraintError = this.validateConstraints(field, value)\n if (constraintError) {\n errors.push(validationError([field.key], constraintError, 'constraint'))\n }\n }\n }\n\n if (errors.length > 0) {\n return validationErr(errors)\n }\n return validationOk(record as TConfig)\n }\n\n applyDefaults(partial: Partial<TConfig>): TConfig {\n const result = { ...partial } as Record<string, unknown>\n for (const field of this.fields) {\n if (result[field.key] === undefined && field.defaultValue !== undefined) {\n result[field.key] = field.defaultValue\n }\n }\n return result as TConfig\n }\n\n private validateType(field: ConfigFieldDefinition, value: unknown): string | null {\n switch (field.type) {\n case 'string':\n case 'url':\n case 'email':\n case 'json':\n if (typeof value !== 'string') {\n return `${field.label} must be a string`\n }\n break\n case 'number':\n if (typeof value !== 'number') {\n return `${field.label} must be a number`\n }\n break\n case 'boolean':\n if (typeof value !== 'boolean') {\n return `${field.label} must be a boolean`\n }\n break\n case 'select':\n if (typeof value !== 'string') {\n return `${field.label} must be a string`\n }\n if (field.options && !field.options.some((o) => o.value === value)) {\n return `${field.label} must be one of: ${field.options.map((o) => o.value).join(', ')}`\n }\n break\n case 'multi-select':\n if (!Array.isArray(value)) {\n return `${field.label} must be an array`\n }\n if (field.options) {\n const valid = new Set(field.options.map((o) => o.value))\n for (const v of value) {\n if (typeof v !== 'string' || !valid.has(v)) {\n return `${field.label} contains invalid option: ${String(v)}`\n }\n }\n }\n break\n }\n return null\n }\n\n private validateConstraints(field: ConfigFieldDefinition, value: unknown): string | null {\n const c = field.constraints\n if (!c) return null\n\n if (typeof value === 'number') {\n if (c.min !== undefined && value < c.min) {\n return `${field.label} must be at least ${String(c.min)}`\n }\n if (c.max !== undefined && value > c.max) {\n return `${field.label} must be at most ${String(c.max)}`\n }\n }\n\n if (typeof value === 'string' && c.pattern) {\n if (!new RegExp(c.pattern).test(value)) {\n return c.patternMessage ?? `${field.label} does not match the required pattern`\n }\n }\n\n return null\n }\n}\n\n// ============================================================\n// ENTRY POINT\n// ============================================================\n\nexport function defineConfigSchema<\n TConfig = Record<string, unknown>,\n>(): ConfigSchemaBuilder<TConfig> {\n return new ConfigSchemaBuilder<TConfig>()\n}\n","/**\n * State Management\n *\n * PHASE0-WS3: Simple state management utilities\n *\n * @module @pwfabric/core/state\n */\n\n// ============================================================\n// STATE STORE INTERFACE\n// ============================================================\n\n/**\n * State change listener\n */\nexport type StateListener<T> = (newState: T, oldState: T) => void\n\n/**\n * State store interface\n */\nexport interface StateStore<T> {\n /**\n * Get the current state\n */\n getState(): T\n\n /**\n * Set the state\n */\n setState(newState: T): void\n\n /**\n * Update the state with a partial update\n */\n updateState(partial: Partial<T>): void\n\n /**\n * Subscribe to state changes\n */\n subscribe(listener: StateListener<T>): () => void\n\n /**\n * Get a snapshot of the state\n */\n snapshot(): StateSnapshot<T>\n}\n\n/**\n * State snapshot\n */\nexport interface StateSnapshot<T> {\n readonly state: T\n readonly timestamp: number\n readonly version: number\n}\n\n// ============================================================\n// SIMPLE STATE STORE IMPLEMENTATION\n// ============================================================\n\n/**\n * Simple in-memory state store\n */\nexport class SimpleStateStore<T extends object> implements StateStore<T> {\n private state: T\n private version = 0\n private listeners = new Set<StateListener<T>>()\n\n constructor(initialState: T) {\n this.state = { ...initialState }\n }\n\n getState(): T {\n return { ...this.state }\n }\n\n setState(newState: T): void {\n const oldState = this.state\n this.state = { ...newState }\n this.version++\n this.notifyListeners(this.state, oldState)\n }\n\n updateState(partial: Partial<T>): void {\n const oldState = this.state\n this.state = { ...this.state, ...partial }\n this.version++\n this.notifyListeners(this.state, oldState)\n }\n\n subscribe(listener: StateListener<T>): () => void {\n this.listeners.add(listener)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n snapshot(): StateSnapshot<T> {\n return {\n state: this.getState(),\n timestamp: Date.now(),\n version: this.version,\n }\n }\n\n private notifyListeners(newState: T, oldState: T): void {\n for (const listener of this.listeners) {\n try {\n listener(newState, oldState)\n } catch {\n // Ignore listener errors\n }\n }\n }\n}\n\n/**\n * Create a new state store\n */\nexport function createStateStore<T extends object>(initialState: T): StateStore<T> {\n return new SimpleStateStore<T>(initialState)\n}\n\n// ============================================================\n// COMPUTED STATE\n// ============================================================\n\n/**\n * Selector function type\n */\nexport type Selector<T, R> = (state: T) => R\n\n/**\n * Create a computed value from a store\n */\nexport function computed<T extends object, R>(\n store: StateStore<T>,\n selector: Selector<T, R>\n): () => R {\n return () => selector(store.getState())\n}\n\n/**\n * Subscribe to a specific slice of state\n */\nexport function subscribeToSlice<T extends object, R>(\n store: StateStore<T>,\n selector: Selector<T, R>,\n listener: StateListener<R>\n): () => void {\n let previousValue = selector(store.getState())\n\n return store.subscribe((newState, oldState) => {\n const newValue = selector(newState)\n const oldValue = selector(oldState)\n\n // Only notify if the selected value changed\n if (newValue !== oldValue) {\n listener(newValue, previousValue)\n previousValue = newValue\n }\n })\n}\n\n// ============================================================\n// STATE MACHINE\n// ============================================================\n\n/**\n * State machine transition\n */\nexport interface Transition<S, E> {\n from: S\n to: S\n event: E\n guard?: () => boolean\n action?: () => void\n}\n\n/**\n * State machine configuration\n */\nexport interface StateMachineConfig<S, E> {\n initial: S\n transitions: Transition<S, E>[]\n}\n\n/**\n * State machine interface\n */\nexport interface StateMachine<S, E> {\n /**\n * Get the current state\n */\n getState(): S\n\n /**\n * Check if an event can be processed\n */\n can(event: E): boolean\n\n /**\n * Process an event\n */\n dispatch(event: E): boolean\n\n /**\n * Subscribe to state changes\n */\n subscribe(listener: StateListener<S>): () => void\n}\n\n/**\n * Simple state machine implementation\n */\nexport class SimpleStateMachine<S, E> implements StateMachine<S, E> {\n private state: S\n private readonly transitions: Transition<S, E>[]\n private listeners = new Set<StateListener<S>>()\n\n constructor(config: StateMachineConfig<S, E>) {\n this.state = config.initial\n this.transitions = config.transitions\n }\n\n getState(): S {\n return this.state\n }\n\n can(event: E): boolean {\n const transition = this.findTransition(event)\n if (!transition) return false\n if (transition.guard && !transition.guard()) return false\n return true\n }\n\n dispatch(event: E): boolean {\n const transition = this.findTransition(event)\n if (!transition) return false\n if (transition.guard && !transition.guard()) return false\n\n const oldState = this.state\n this.state = transition.to\n\n if (transition.action) {\n transition.action()\n }\n\n this.notifyListeners(this.state, oldState)\n return true\n }\n\n subscribe(listener: StateListener<S>): () => void {\n this.listeners.add(listener)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n private findTransition(event: E): Transition<S, E> | undefined {\n return this.transitions.find((t) => t.from === this.state && t.event === event)\n }\n\n private notifyListeners(newState: S, oldState: S): void {\n for (const listener of this.listeners) {\n try {\n listener(newState, oldState)\n } catch {\n // Ignore listener errors\n }\n }\n }\n}\n\n/**\n * Create a state machine\n */\nexport function createStateMachine<S, E>(config: StateMachineConfig<S, E>): StateMachine<S, E> {\n return new SimpleStateMachine<S, E>(config)\n}\n","/**\n * Block Type Definitions\n *\n * Core type definitions for the block ecosystem\n *\n * @module @pwfabric/core/blocks/types\n */\n\nimport type { ZodSchema } from 'zod'\nimport type { BlockLayout } from './layout-schema.js'\n\n// The block instance type is defined in @pwfabric/contracts; re-exported here.\nexport type { Block } from '@pwfabric/contracts'\n\n// ============================================================\n// BLOCK CATEGORIES\n// ============================================================\n\n/**\n * Block category classification.\n *\n * `feedback` is the family of toast, spinner and radial-progress blocks. A\n * block's atom id comes from its directory, and a pack's integrity check\n * requires the category and the directory to agree, so these blocks carry\n * `feedback` rather than being filed under `control`.\n */\nexport type BlockCategory =\n | 'layout'\n | 'panel'\n | 'text'\n | 'data'\n | 'control'\n | 'media'\n | 'form'\n | 'feedback'\n // Categories by SHAPE: `overlay` (modal, drawer, popover, tooltip,\n // command-palette), `container` (card, accordion, tabs, tree-view) and\n // `integration` (app views that own a connection to an outside service:\n // calendar, chat, files…). `panel` remains for packs that still use it.\n | 'overlay'\n | 'container'\n | 'integration'\n\n// ============================================================\n// BLOCK DEFINITION\n// ============================================================\n\n/**\n * Block definition interface\n *\n * Defines the structure and constraints of a block type.\n */\nexport interface BlockDefinition {\n /** Unique block type identifier */\n readonly type: string\n\n /** Human-readable display name */\n readonly name: string\n\n /** Block category for grouping */\n readonly category: BlockCategory\n\n /** Icon character or identifier */\n readonly icon: string\n\n /** Zod schema for props validation */\n readonly schema: ZodSchema\n\n /** Default props for new instances */\n readonly defaultProps: Record<string, unknown>\n\n /** Default layout for new instances (span/offset/order/hidden per breakpoint) */\n readonly defaultLayout?: BlockLayout\n\n /** Whether this block can contain children */\n readonly canHaveChildren: boolean\n\n /**\n * Optional: which child block types this block accepts. The runtime's\n * composition rules enforce it. `allowedChildTraits` is the trait-based\n * alternative, for a block that accepts any child with a given trait.\n */\n readonly allowedChildren?: readonly string[]\n\n /** Optional: Restrict which block types can be parents */\n readonly allowedParents?: readonly string[]\n\n /** open trait vocabulary this block carries (kebab-case). */\n readonly traits?: readonly string[]\n\n /**\n * a child block passes if it carries ANY of these traits.\n * Only meaningful when `canHaveChildren` is true.\n */\n readonly allowedChildTraits?: readonly string[]\n\n /** Optional: Maximum instances allowed in a surface */\n readonly maxInstances?: number\n}\n\n// ============================================================\n// BLOCK INSTANCE\n// ============================================================\n// Block is re-exported from @pwfabric/contracts above.\n\n// ============================================================\n// VALIDATION\n// ============================================================\n\n/**\n * Validation error interface\n */\nexport interface ValidationError {\n /** Error code for programmatic handling */\n readonly code: string\n\n /** Human-readable error message */\n readonly message: string\n\n /** Optional: Associated block ID */\n readonly blockId?: string\n\n /** Optional: Suggestion for fixing the error */\n readonly suggestion?: string\n}\n\n/**\n * Validation result interface\n */\nexport interface ValidationResult {\n /** Whether validation passed */\n readonly valid: boolean\n\n /** List of validation errors */\n readonly errors: readonly ValidationError[]\n}\n\n// ============================================================\n// COMPOSITION RULES\n// ============================================================\n\n/**\n * Composition rule type\n */\nexport type CompositionRuleType =\n | 'max_depth'\n | 'allowed_children'\n | 'allowed_parents'\n | 'required_parent'\n | 'no_children'\n | 'no_self_nesting'\n\n/**\n * Composition rule interface\n */\nexport interface CompositionRule {\n /** Rule type */\n readonly type: CompositionRuleType\n\n /** Rule description */\n readonly description: string\n\n /** Block type this rule applies to (or '*' for all) */\n readonly appliesTo: string | '*'\n\n /** Rule-specific configuration */\n readonly config: Record<string, unknown>\n}\n\n// ============================================================\n// CONSTANTS\n// ============================================================\n\n/**\n * Maximum block nesting depth. SINGLE SOURCE OF TRUTH — every validator and the\n * composer prompt derive from this constant.\n *\n * Canonical rule (enforced identically everywhere): root blocks are at depth 0,\n * and a block is INVALID when its depth `>= MAX_NESTING_DEPTH`. So the deepest\n * legal block sits at depth `MAX_NESTING_DEPTH - 1`, i.e. up to `MAX_NESTING_DEPTH`\n * levels of nesting (root included).\n *\n * Consumers: the runtime rule engine and composition-rules prose\n * (@pwfabric/runtime), and a host's surface validation (MAX_NESTING_EXCEEDED)\n * and composer instructions (\"Max nesting depth: N levels\").\n */\nexport const MAX_NESTING_DEPTH = 10\n\n/**\n * Block categories ordered for display\n */\nexport const BLOCK_CATEGORIES: readonly BlockCategory[] = [\n 'layout',\n 'panel',\n 'text',\n 'data',\n 'control',\n 'media',\n 'form',\n // Last in display order: status and notification chrome, not content.\n 'feedback',\n] as const\n","/**\n * Block Layout Schema\n *\n * Zod schemas for layout validation, per-type default spans,\n * and mobile-first cascade resolution.\n *\n * @module @pwfabric/core/blocks/layout-schema\n */\n\nimport { z } from 'zod'\n\n// ============================================================\n// BREAKPOINT DEFINITIONS\n// ============================================================\n\n/**\n * Named breakpoints aligned with Tailwind CSS conventions\n */\nexport type BreakpointName = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl'\n\n/**\n * Breakpoint definition with min-width and column count\n */\nexport interface BreakpointDefinition {\n readonly name: BreakpointName\n readonly minWidth: number\n readonly columns: number\n readonly label: string\n}\n\n/**\n * Ordered breakpoint definitions (smallest to largest)\n */\nexport const BREAKPOINTS: readonly BreakpointDefinition[] = [\n { name: 'xs', minWidth: 0, columns: 4, label: 'Mobile' },\n { name: 'sm', minWidth: 640, columns: 8, label: 'Mobile Landscape' },\n { name: 'md', minWidth: 768, columns: 8, label: 'Tablet' },\n { name: 'lg', minWidth: 1024, columns: 12, label: 'Desktop' },\n { name: 'xl', minWidth: 1280, columns: 12, label: 'Large Desktop' },\n { name: '2xl', minWidth: 1536, columns: 12, label: 'Extra Large' },\n] as const\n\n/**\n * Ordered breakpoint names for iteration and cascade resolution\n */\nexport const BREAKPOINT_ORDER: readonly BreakpointName[] = [\n 'xs',\n 'sm',\n 'md',\n 'lg',\n 'xl',\n '2xl',\n] as const\n\n// ============================================================\n// RESPONSIVE VALUE TYPE\n// ============================================================\n\n/**\n * A value that can vary per breakpoint.\n */\nexport type ResponsiveValue<T> = Readonly<Partial<Record<BreakpointName, T>>>\n\n// ============================================================\n// BLOCK LAYOUT\n// ============================================================\n\n/**\n * Layout metadata for a block instance.\n */\nexport interface BlockLayout {\n readonly span: ResponsiveValue<number>\n readonly offset?: ResponsiveValue<number>\n readonly order?: ResponsiveValue<number>\n readonly hidden?: ResponsiveValue<boolean>\n /**\n * Per-breakpoint visibility (the `hidden md:flex` equivalent).\n * `hideOn` = breakpoints where the block is hidden; `showOn` = the only\n * breakpoints where it is visible. CSS/media-query driven (see runtime\n * renderer), using the same pixel thresholds as the span system.\n */\n readonly hideOn?: readonly BreakpointName[]\n readonly showOn?: readonly BreakpointName[]\n /**\n * What this block's width belongs to: the surface's measured container, or\n * the screen itself.\n *\n * `container` (default) — respects `--pw-layout-container-max-width`.\n * `viewport` — LEAVES that container and reaches the edge of the screen.\n *\n * Breakpoint-aware, because \"change shape on a narrow screen\" is exactly\n * this: `{ xs: 'viewport', lg: 'container' }`.\n *\n * The engine knows NO words beyond these two. Which region of which shell\n * has which scope is the pack's vocabulary; if the engine memorised it, a\n * second pack could not express itself.\n */\n readonly widthScope?: ResponsiveValue<WidthScope>\n}\n\nexport const DEFAULT_BLOCK_LAYOUT: BlockLayout = {\n span: { xs: 4, sm: 8, md: 8, lg: 12 },\n} as const\n\n// ============================================================\n// VIEWPORT PRESETS\n// ============================================================\n\nexport type PreviewViewport = BreakpointName | 'responsive'\n\nexport const VIEWPORT_PRESETS: Record<\n BreakpointName,\n { readonly width: number; readonly height: 'auto' }\n> = {\n xs: { width: 375, height: 'auto' },\n sm: { width: 640, height: 'auto' },\n md: { width: 768, height: 'auto' },\n lg: { width: 1024, height: 'auto' },\n xl: { width: 1280, height: 'auto' },\n '2xl': { width: 1536, height: 'auto' },\n} as const\n\n// ============================================================\n// ZOD SCHEMAS\n// ============================================================\n\nexport const responsiveNumberSchema = z\n .object({\n xs: z.number().int().min(0).optional(),\n sm: z.number().int().min(0).optional(),\n md: z.number().int().min(0).optional(),\n lg: z.number().int().min(0).optional(),\n xl: z.number().int().min(0).optional(),\n '2xl': z.number().int().min(0).optional(),\n })\n .strict()\n\nexport const responsiveBooleanSchema = z\n .object({\n xs: z.boolean().optional(),\n sm: z.boolean().optional(),\n md: z.boolean().optional(),\n lg: z.boolean().optional(),\n xl: z.boolean().optional(),\n '2xl': z.boolean().optional(),\n })\n .strict()\n\nexport const breakpointNameSchema = z.enum(['xs', 'sm', 'md', 'lg', 'xl', '2xl'])\n\n/**\n * Width scope — the ONLY vocabulary the engine knows on this axis.\n *\n * `container` fits the measured container, `viewport` leaves it. There is no\n * third value: in-between words such as \"half\", \"wide\" or \"full\" belong to a\n * shell's vocabulary and live in the pack. The engine applies only the\n * difference between \"fit the container\" and \"leave the container\".\n */\nexport const widthScopeSchema = z.enum(['container', 'viewport'])\nexport type WidthScope = z.infer<typeof widthScopeSchema>\n\nexport const responsiveWidthScopeSchema = z\n .object({\n xs: widthScopeSchema.optional(),\n sm: widthScopeSchema.optional(),\n md: widthScopeSchema.optional(),\n lg: widthScopeSchema.optional(),\n xl: widthScopeSchema.optional(),\n '2xl': widthScopeSchema.optional(),\n })\n .strict()\n\nexport const blockLayoutSchema = z.object({\n span: responsiveNumberSchema,\n offset: responsiveNumberSchema.optional(),\n order: responsiveNumberSchema.optional(),\n hidden: responsiveBooleanSchema.optional(),\n hideOn: z.array(breakpointNameSchema).optional(),\n showOn: z.array(breakpointNameSchema).optional(),\n widthScope: responsiveWidthScopeSchema.optional(),\n})\n\n// ============================================================\n// CASCADE RESOLUTION\n// ============================================================\n\nexport function resolveResponsiveValue<T>(\n responsive: ResponsiveValue<T> | undefined,\n breakpoint: BreakpointName\n): T | undefined {\n if (!responsive) return undefined\n const targetIndex = BREAKPOINT_ORDER.indexOf(breakpoint)\n for (let i = targetIndex; i >= 0; i--) {\n const bp = BREAKPOINT_ORDER[i]\n if (!bp) continue\n if (responsive[bp] !== undefined) {\n return responsive[bp]\n }\n }\n return undefined\n}\n\nexport function resolveSpanAtBreakpoint(layout: BlockLayout, breakpoint: BreakpointName): number {\n const span = resolveResponsiveValue(layout.span, breakpoint)\n if (span !== undefined) return span\n const bpDef = BREAKPOINTS.find((bp) => bp.name === breakpoint)\n return bpDef?.columns ?? 12\n}\n\nexport function getColumnsAtBreakpoint(breakpoint: BreakpointName): number {\n const bpDef = BREAKPOINTS.find((bp) => bp.name === breakpoint)\n return bpDef?.columns ?? 12\n}\n\nexport function getBreakpointForWidth(width: number): BreakpointName {\n for (let i = BREAKPOINTS.length - 1; i >= 0; i--) {\n const bp = BREAKPOINTS[i]\n if (bp && width >= bp.minWidth) {\n return bp.name\n }\n }\n return 'xs'\n}\n","/**\n * Block Host Imports — what a dynamically loaded block may import, and what the\n * host must therefore provide.\n *\n * WHY THIS EXISTS. A published block is bundled per atom with esbuild and\n * loaded in the browser through `<script type=\"importmap\">` + `import(blob:…)`.\n * Two kinds of import survive that: relative paths to files inside the block's\n * own pack, and a short list of BARE specifiers that are left unbundled for the\n * host to supply. That list appears in three places — the bundler's externals,\n * the host's import map and the shim files the host serves — and a specifier\n * missing from any one of them fails at load time (\"Failed to resolve module\n * specifier\" inside the blob module).\n *\n * This module is that contract, in one place, so the bundler's allowlist, the\n * host's import map and the shim files are all DERIVED and can be checked\n * against each other instead of drifting in silence.\n *\n * WHY NOT IN `@pwfabric/contracts`, where `dynamic-artifact.ts` already lives.\n * The contracts package is treated as immutable after release: every change to\n * its surface, even an additive one, goes through a stricter review. This list has to\n * change whenever a package joins or leaves the allowlist; putting it behind a\n * ceremony is what would recreate the drift it exists to prevent. It lives here,\n * where an additive export is an ordinary minor.\n *\n * @module @pwfabric/core/blocks/host-imports\n */\n\n// ============================================================\n// THE CONTRACT\n// ============================================================\n\n/**\n * How the host hands a shared module to a dynamically loaded block.\n *\n * `global` — the shim re-exports from `globalThis[global]`, which the host seeds\n * from its OWN bundled import. This is the mechanism for anything whose IDENTITY\n * must be shared: one React dispatcher, one event bus, one set of contract\n * values. Two instances of these is not \"slightly wasteful\", it is broken —\n * `useSurfaceEvents` reading a second context makes `emit()` a silent no-op.\n *\n * It is the only kind: every specifier on this list is resolved by the host\n * through a shim reading a global. `zod` included — blocks share the host's\n * single zod instance, because introspection needs the real zod for\n * `instanceof` while walking a schema. A specifier a bundler inlines is simply\n * not external, and so never reaches this list.\n */\nexport type HostImportKind = 'global'\n\n/**\n * WHICH hosts seed a `global` entry. There are two of them and they are not\n * obliged to agree — recording that here keeps a derived gate from calling a\n * deliberate decision a gap.\n *\n * `every-host` — both the app host and the standalone export's IIFE\n * (`@pwfabric/embed`'s `embed-global.ts`) must seed it.\n * `app-host` — the app host seeds it; the standalone export deliberately\n * does NOT. The sdk global is the standing case: the authoring\n * kit is a development-time surface and does not belong in a\n * shipped app export, even though a published block's compiled\n * bundle may still call `defineBlock()` at module-load time.\n * Such a block works in the live canvas and degrades in a\n * standalone export, which is the chosen trade-off.\n * `unseeded` — nothing seeds it yet. The specifier resolves (the shim is\n * served) but its named exports come back `undefined`. That is\n * strictly better than an unresolved bare specifier, which\n * fails the whole module at link time — but it is a gap, and\n * naming it here keeps it visible.\n */\nexport type HostSeeding = 'every-host' | 'app-host' | 'unseeded'\n\n/** One specifier a block may import, and how the host satisfies it. */\nexport interface HostImport {\n /** The bare specifier as it appears in block source and in the bundle. */\n readonly specifier: string\n readonly kind: HostImportKind\n /**\n * The `globalThis` key the shim reads. Present for `kind: 'global'` only.\n * The host seeds it from its own bundled import of the same package.\n */\n readonly global?: string\n /** Which hosts seed {@link HostImport.global}. Present for `kind: 'global'` only. */\n readonly seeding?: HostSeeding\n /**\n * Shim file this specifier resolves to, relative to the host's shim directory.\n * SEVERAL SPECIFIERS MAY SHARE ONE FILE — `@pwfabric/runtime` and its\n * subpaths all resolve to the runtime shim, because what a block imports is\n * a runtime contract, not a package name.\n */\n readonly shim: string\n /** Why this specifier is on the list. Read by humans, not by code. */\n readonly reason: string\n}\n\n/**\n * THE LIST. Order is not significant; every consumer derives from the whole set.\n *\n * Adding an entry is the ONLY supported way to let blocks import something new.\n * The derivation helpers below mean a new entry reaches the bundler's allowlist,\n * every host's import map and every shim file together.\n */\nexport const BLOCK_HOST_IMPORTS: readonly HostImport[] = [\n {\n specifier: 'react',\n kind: 'global',\n global: '__pwfabric_react',\n seeding: 'every-host',\n shim: 'react.mjs',\n reason:\n 'One dispatcher. A second React instance makes every hook in a block throw \"Cannot read properties of null (reading \\'useState\\')\".',\n },\n {\n specifier: 'react/jsx-runtime',\n kind: 'global',\n global: '__pwfabric_jsx_runtime',\n seeding: 'every-host',\n shim: 'react-jsx-runtime.mjs',\n reason:\n 'The automatic JSX transform emits imports from here; it must be the same React. NOTE the global is `__pwfabric_jsx_runtime`, not `…_react_jsx_runtime`; the shim and the seeders read this name.',\n },\n {\n specifier: 'react-dom',\n kind: 'global',\n global: '__pwfabric_react_dom',\n seeding: 'unseeded',\n shim: 'react-dom.mjs',\n reason: 'Blocks that portal or measure reach for react-dom; same-instance rule as React.',\n },\n {\n specifier: '@pwfabric/runtime',\n kind: 'global',\n global: '__pwfabric_runtime',\n seeding: 'every-host',\n shim: 'runtime.mjs',\n reason:\n 'Surface event bus, surface id and connections contexts. A block reading a second context emits into nothing.',\n },\n {\n specifier: '@pwfabric/runtime/data',\n kind: 'global',\n global: '__pwfabric_runtime',\n seeding: 'every-host',\n shim: 'runtime.mjs',\n reason:\n 'A runtime subpath the package root re-exports WHOLESALE, so the root shim serves it exactly — the foundation pack persistence capability imports `createDataService` from here. An import map resolves exact specifiers only: without this entry the import would compile with a HOST_SUBPATH_IMPORT warning and then fail to resolve in the browser. Only subpaths whose every export the root also exports may join; the runtime package has a test that says so.',\n },\n {\n specifier: '@pwfabric/runtime/capability',\n kind: 'global',\n global: '__pwfabric_runtime',\n seeding: 'every-host',\n shim: 'runtime.mjs',\n reason:\n 'A runtime subpath the package root re-exports WHOLESALE, so the root shim serves it exactly — capability atoms import their definition helpers from here. An import map resolves exact specifiers only: without this entry the import would compile with a HOST_SUBPATH_IMPORT warning and then fail to resolve in the browser. Only subpaths whose every export the root also exports may join; the runtime package has a test that says so.',\n },\n {\n specifier: '@pwfabric/runtime/adapters',\n kind: 'global',\n global: '__pwfabric_runtime',\n seeding: 'every-host',\n shim: 'runtime.mjs',\n reason:\n 'A runtime subpath the package root re-exports WHOLESALE, so the root shim serves it exactly — image adapters; a block that renders a responsive image reaches for them here. An import map resolves exact specifiers only: without this entry the import would compile with a HOST_SUBPATH_IMPORT warning and then fail to resolve in the browser. Only subpaths whose every export the root also exports may join; the runtime package has a test that says so.',\n },\n {\n specifier: '@pwfabric/contracts',\n kind: 'global',\n global: '__pwfabric_contracts',\n seeding: 'every-host',\n shim: 'contracts.mjs',\n reason: 'Contract VALUES (enums, constants) must be the host’s, not a second copy.',\n },\n {\n specifier: '@pwfabric/core',\n kind: 'global',\n global: '__pwfabric_core',\n seeding: 'unseeded',\n shim: 'core.mjs',\n reason: 'Block layout helpers and breakpoint constants blocks resolve at render time.',\n },\n {\n specifier: '@pwfabric/authoring',\n kind: 'global',\n global: '__pwfabric_sdk',\n seeding: 'app-host',\n shim: 'sdk@v1.mjs',\n reason:\n 'What the scaffolding emits and a third-party author reads first. A host that does not map it breaks every block that follows the documented path.',\n },\n {\n specifier: 'zod',\n kind: 'global',\n global: '__pwfabric_zod',\n seeding: 'every-host',\n shim: 'zod.mjs',\n reason:\n 'Every block with a prop schema imports it as a value — 81 pack source files take `z`. Shared, not inlined: `zod.mjs` re-exports the host instance, and introspection depends on it being the real zod so `instanceof` holds while walking a schema.',\n },\n] as const\n\n// ============================================================\n// DERIVATIONS — every consumer reads the list through one of these\n// ============================================================\n\n/**\n * The specifiers esbuild must leave bare when bundling an atom.\n *\n * A bundling service's externals list is exactly this: the bundler leaves each\n * specifier bare, and the host's import map resolves it to the shared instance.\n */\nexport function blockBundleExternals(): readonly string[] {\n return BLOCK_HOST_IMPORTS.map((i) => i.specifier)\n}\n\n/**\n * The host's `<script type=\"importmap\">` payload.\n *\n * @param shimBase - URL prefix the shim files are served from, no trailing\n * slash (for example `/_pwfabric/shims`).\n */\nexport function blockImportMap(shimBase: string): { readonly imports: Record<string, string> } {\n const imports: Record<string, string> = {}\n for (const entry of BLOCK_HOST_IMPORTS) {\n imports[entry.specifier] = `${shimBase}/${entry.shim}`\n }\n return { imports }\n}\n\n/** Every distinct shim file the import map can point at. */\nexport function blockShimFiles(): readonly string[] {\n return [...new Set(BLOCK_HOST_IMPORTS.map((i) => i.shim))].sort()\n}\n\n/**\n * The `globalThis` keys a host must seed before any block bundle is imported.\n *\n * A host that renders published blocks assigns each of these from its own\n * bundled import. Missing one does not throw where it is missing — it throws\n * inside a block, later, as an undefined named import.\n */\nexport function blockHostGlobals(host: 'app-host' | 'standalone' = 'app-host'): readonly string[] {\n // The standalone export is NOT the app host with fewer features — it seeds a\n // deliberately smaller set, and asking it for the app host's list would make a\n // gate demand the sdk global it deliberately leaves out. `unseeded`\n // entries belong to neither list: nothing seeds them today, and pretending\n // otherwise would turn a recorded gap into a failing gate nobody can satisfy.\n const wanted: readonly HostSeeding[] =\n host === 'standalone' ? ['every-host'] : ['every-host', 'app-host']\n return [\n ...new Set(\n BLOCK_HOST_IMPORTS.flatMap((i) =>\n i.global && i.seeding && wanted.includes(i.seeding) ? [i.global] : []\n )\n ),\n ].sort()\n}\n\n/** Entries whose global nothing seeds yet — a gap this list refuses to hide. */\nexport function unseededHostGlobals(): readonly HostImport[] {\n return BLOCK_HOST_IMPORTS.filter((i) => i.seeding === 'unseeded')\n}\n\n/**\n * Which specifiers resolve to a given shim file — the reverse of `shim`.\n * A shim generator needs this: one file serves every specifier aliased to it,\n * so it must export the union of what those specifiers' consumers import.\n */\nexport function specifiersForShim(shim: string): readonly string[] {\n return BLOCK_HOST_IMPORTS.filter((i) => i.shim === shim).map((i) => i.specifier)\n}\n","/**\n * Thin mode loader.\n *\n * Fetches a published surface + its render grants from a host API the same\n * way a host application's public surface route does, then normalises the\n * result into the shape `render-core` consumes.\n *\n * The host API serves `GET /api/surfaces/by-slug/:tenant/:slug` (and\n * `GET /api/surfaces/:id/published`). Host API clients are not part of this\n * engine, so this issues the HTTP call with `fetch` and applies the same\n * post-processing a host applies:\n * - `definition.rootBlock.children` (or `definition.blocks`) → runtime blocks,\n * merging each block's stored `layout.span` with `DEFAULT_BLOCK_LAYOUT.span`.\n * - `response.renderGrants[]` → `DynamicBlockDescriptor[]` (publisher\n * 'workspace', unverified) — byte-identical to the host's `mappedDescriptors`.\n * - `definition.theme` / `styleVariables` → an `appearance` ref.\n * - `definition.capabilities` normalised with `required: false` default.\n *\n * @module @pwfabric/embed/thin\n */\n\nimport { DEFAULT_BLOCK_LAYOUT } from '@pwfabric/core'\nimport type { Block } from '@pwfabric/core'\nimport type {\n DynamicBlockDescriptor,\n SurfaceRenderGrant,\n SurfaceTheme,\n SurfaceCapabilityRequirement,\n} from '@pwfabric/contracts'\nimport type { RenderableSurface } from '@pwfabric/runtime'\nimport { isCapability } from '@pwfabric/runtime/capability'\n\n// ============================================================\n// TYPES\n// ============================================================\n\nexport interface ThinAuth {\n /** Bearer token; injected as `Authorization` on the surface fetch and on\n * any REST data sources (matching the host's `ms_access_token` behaviour). */\n readonly accessToken?: string\n /** Send credentials (cookies) with the request. */\n readonly includeCredentials?: boolean\n}\n\nexport interface LoadThinOptions {\n /** API origin, e.g. `https://api.example.com`. */\n readonly apiBaseUrl: string\n /** Optional auth. */\n readonly auth?: ThinAuth\n /** Custom fetch (test injection / non-browser runtime). */\n readonly fetchImpl?: typeof fetch\n}\n\n/**\n * A surface reference: either a `surfaceId` (by-id) or a tenant+surface slug\n * pair (by-slug, the host's path).\n */\nexport type ThinSurfaceRef =\n | { readonly surfaceId: string }\n | { readonly tenantSlug: string; readonly surfaceSlug: string }\n\nexport interface LoadThinResult {\n readonly surface: RenderableSurface\n readonly dynamicBlocks: readonly DynamicBlockDescriptor[]\n readonly surfaceId?: string\n readonly worldId?: string\n /** Surface-level layout hints from the API (maxWidth/gap/padding). */\n readonly layout?: { maxWidth?: number; gap?: number; padding?: number }\n}\n\n// ============================================================\n// API RESPONSE SHAPES (loose — mirror the host's local interfaces)\n// ============================================================\n\ninterface ApiBlockNode {\n id: string\n type: string\n version?: string\n props?: Record<string, unknown>\n layout?: Block['layout']\n style?: Record<string, string>\n children?: ApiBlockNode[]\n}\n\ninterface IncomingCapability {\n capability: string\n required?: boolean\n config?: Record<string, unknown>\n}\n\ninterface SurfaceFetchData {\n surfaceId: string\n worldId: string\n definition: {\n rootBlock?: ApiBlockNode\n blocks?: ApiBlockNode[]\n dataSources?: unknown[]\n state?: Record<string, unknown>\n styleVariables?: Record<string, string>\n theme?: SurfaceTheme\n capabilities?: IncomingCapability[]\n }\n layout?: { maxWidth?: number; gap?: number; padding?: number } | null\n renderGrants?: SurfaceRenderGrant[]\n}\n\n// ============================================================\n// BLOCK CONVERSION (mirror of the host's toRuntimeBlock)\n// ============================================================\n\nfunction toRuntimeBlock(node: ApiBlockNode): Block {\n const storedLayout = node.layout\n const mergedLayout: Block['layout'] = storedLayout\n ? {\n ...storedLayout,\n span: { ...DEFAULT_BLOCK_LAYOUT.span, ...storedLayout.span },\n }\n : DEFAULT_BLOCK_LAYOUT\n\n const base = {\n id: node.id,\n type: node.type,\n props: node.props ?? {},\n layout: mergedLayout,\n ...(node.style ? { style: node.style } : {}),\n }\n\n if (node.children && node.children.length > 0) {\n return { ...base, children: node.children.map(toRuntimeBlock) }\n }\n return base\n}\n\n/**\n * Map render grants → dynamic block descriptors. Byte-identical to the host's\n * `mappedDescriptors` memo: publisher 'workspace', unverified, a minimal\n * marketplace-category definition.\n */\nexport function grantsToDescriptors(\n grants: readonly SurfaceRenderGrant[]\n): DynamicBlockDescriptor[] {\n if (grants.length === 0) return []\n return grants.map((grant) => ({\n blockType: grant.blockType,\n moduleUrl: grant.moduleUrl,\n integrity: grant.integrity,\n publisher: 'workspace',\n publisherVerified: false,\n definition: {\n name: grant.artifactName,\n category: 'marketplace',\n defaultProps: {},\n canHaveChildren: false,\n },\n }))\n}\n\n// ============================================================\n// LOADER\n// ============================================================\n\nfunction buildSurfaceUrl(apiBaseUrl: string, ref: ThinSurfaceRef): string {\n const base = apiBaseUrl.replace(/\\/+$/, '')\n if ('surfaceId' in ref) {\n return `${base}/api/surfaces/${encodeURIComponent(ref.surfaceId)}/published`\n }\n return `${base}/api/surfaces/by-slug/${encodeURIComponent(ref.tenantSlug)}/${encodeURIComponent(\n ref.surfaceSlug\n )}`\n}\n\n/**\n * The API wraps payloads as `{ data, error }` (an `ApiResponse` envelope). Some\n * endpoints return the bare object. Normalise both.\n */\nfunction unwrap(json: unknown): SurfaceFetchData {\n const obj = json as { data?: SurfaceFetchData; error?: { code?: string } }\n if (obj && obj.error) {\n throw new Error(`[pwfabric-embed] surface fetch error: ${obj.error.code ?? 'UNKNOWN'}`)\n }\n if (obj && obj.data) return obj.data\n return json as SurfaceFetchData\n}\n\n/**\n * Fetch + normalise a published surface and its render grants.\n */\nexport async function loadThin(\n ref: ThinSurfaceRef,\n options: LoadThinOptions\n): Promise<LoadThinResult> {\n const doFetch = options.fetchImpl ?? fetch\n const url = buildSurfaceUrl(options.apiBaseUrl, ref)\n\n const headers: Record<string, string> = { accept: 'application/json' }\n const token = options.auth?.accessToken\n if (token) headers.authorization = `Bearer ${token}`\n\n const init: RequestInit = { method: 'GET', headers }\n if (options.auth?.includeCredentials) init.credentials = 'include'\n\n const res = await doFetch(url, init)\n if (!res.ok) {\n throw new Error(`[pwfabric-embed] surface fetch failed: ${res.status} ${res.statusText}`)\n }\n const data = unwrap(await res.json())\n const def = data.definition ?? {}\n\n // Blocks: rootBlock.children OR blocks[], normalised like the host.\n let blocks: Block[] = []\n if (def.rootBlock) {\n blocks = (def.rootBlock.children ?? []).map(toRuntimeBlock)\n } else if (def.blocks) {\n blocks = def.blocks.map(toRuntimeBlock)\n }\n\n // Capabilities normalised with required:false default (host parity).\n const capabilities: SurfaceCapabilityRequirement[] = (def.capabilities ?? []).map((c) => ({\n capability: c.capability,\n required: c.required ?? false,\n ...(c.config !== undefined ? { config: c.config } : {}),\n }))\n\n // Inject Authorization into REST data sources, matching the host's authedSources.\n if (token && Array.isArray(def.dataSources)) {\n const authed = def.dataSources.map((ds) => {\n const d = ds as { kind?: string; headers?: Record<string, string> }\n return d.kind === 'rest'\n ? { ...d, headers: { ...d.headers, Authorization: `Bearer ${token}` } }\n : d\n })\n // Thread data sources through the persistence capability config so the\n // DataBoundSurfaceRenderer picks them up (consolidated shape).\n // Either spelling: a short-form entry that goes unrecognised here does not\n // just get missed, it gets DUPLICATED — the branch below adds a second\n // persistence capability alongside the one already there.\n const existing = capabilities.find((c) => isCapability(c, 'platform/persistence'))\n if (existing) {\n ;(existing as { config?: Record<string, unknown> }).config = {\n ...(existing.config ?? {}),\n dataSources: authed,\n ...(def.state ? { initialState: def.state } : {}),\n }\n } else {\n capabilities.push({\n capability: 'platform/persistence',\n required: false,\n config: { dataSources: authed, ...(def.state ? { initialState: def.state } : {}) },\n })\n }\n }\n\n // Appearance ref: wrap theme + styleVariables (consolidated shape).\n // Config only — the `use` atom id retired with the appearance engine\n //a theme is data, nothing is resolved by reference.\n const appearance: RenderableSurface['appearance'] | undefined =\n def.theme || def.styleVariables\n ? {\n config: {\n ...(def.theme ? { theme: def.theme } : {}),\n ...(def.styleVariables ? { styleVariables: def.styleVariables } : {}),\n },\n }\n : undefined\n\n const surface: RenderableSurface = {\n blocks,\n ...(appearance ? { appearance } : {}),\n ...(capabilities.length > 0 ? { capabilities } : {}),\n id: data.surfaceId,\n }\n\n return {\n surface,\n dynamicBlocks: grantsToDescriptors(data.renderGrants ?? []),\n surfaceId: data.surfaceId,\n worldId: data.worldId,\n ...(data.layout ? { layout: data.layout } : {}),\n }\n}\n","/**\n * Self-contained fat HTML builder.\n *\n * Produces a single HTML string that renders a surface fully offline:\n * - the surface JSON in a `<script type=\"application/pw-surface+json\">` tag,\n * - the block descriptors in `<script type=\"application/pw-blocks+json\">`\n * (with `moduleUrl` left as-is — callers should pass `data:` URLs for true\n * offline self-containment + matching integrity hashes),\n * - the appearance ref in `<script type=\"application/pw-appearance+json\">`,\n * - the bundled `embed.js` IIFE inlined verbatim in a `<script>` tag,\n * - a bootstrap call:\n * `PWFabric.render('#pw-root', { surface }, { mode:'fat', blocks, appearance })`.\n *\n * Pure function — no I/O. The local preview tool reads `dist/embed.js` off\n * disk and passes its contents as `embedJs`; this module never touches the\n * filesystem.\n *\n * @module @pwfabric/embed/build-fat-html\n */\n\nimport type { DynamicBlockDescriptor } from '@pwfabric/contracts'\nimport type { RenderableSurface } from '@pwfabric/runtime'\n\nexport interface BuildFatHtmlOptions {\n /** Surface JSON to inline + render. */\n readonly surface: RenderableSurface\n /** Block descriptors (prefer `data:` moduleUrls for offline). */\n readonly blocks?: readonly DynamicBlockDescriptor[]\n /** Appearance ref (defaults to `surface.appearance`). */\n readonly appearance?: RenderableSurface['appearance']\n /** The full contents of the built `dist/embed.js` IIFE. */\n readonly embedJs: string\n /** `<title>` of the page. */\n readonly title?: string\n /** Optional `lang` attribute. */\n readonly lang?: string\n}\n\n// Char codes for the JS-illegal line/paragraph separators (kept out of source\n// text so the file stays ASCII-clean).\nconst LS = 0x2028\nconst PS = 0x2029\nconst LINE_SEPS = new RegExp(`[${String.fromCharCode(LS)}${String.fromCharCode(PS)}]`, 'g')\n\n/**\n * Escape a JSON payload for safe inlining inside a `<script>` element.\n * Breaks `</script`/HTML-comment sequences and escapes the line/paragraph\n * separators that are invalid in JS string literals.\n */\nfunction safeJson(value: unknown): string {\n return JSON.stringify(value)\n .replace(/</g, '\\\\u003c')\n .replace(/>/g, '\\\\u003e')\n .replace(/&/g, '\\\\u0026')\n .replace(LINE_SEPS, (ch) => '\\\\u' + ch.charCodeAt(0).toString(16).padStart(4, '0'))\n}\n\n/** Minimal HTML-text escaper for the <title>. */\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n}\n\n/**\n * Build a fully self-contained HTML document string.\n */\nexport function buildFatHtml(options: BuildFatHtmlOptions): string {\n const { surface, embedJs } = options\n const blocks = options.blocks ?? []\n const appearance = options.appearance ?? surface.appearance\n const title = options.title ?? 'Surface'\n const lang = options.lang ?? 'en'\n\n const surfaceJson = safeJson(surface)\n const blocksJson = safeJson(blocks)\n const appearanceJson = safeJson(appearance ?? null)\n\n return `<!DOCTYPE html>\n<html lang=\"${lang}\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<title>${escapeHtml(title)}</title>\n<style>html,body{margin:0;padding:0}#pw-root{min-height:100vh}</style>\n</head>\n<body>\n<div id=\"pw-root\"></div>\n<script type=\"application/pw-surface+json\">${surfaceJson}</script>\n<script type=\"application/pw-blocks+json\">${blocksJson}</script>\n<script type=\"application/pw-appearance+json\">${appearanceJson}</script>\n<script>${embedJs}</script>\n<script>\n(function(){\n var surface = JSON.parse(document.querySelector('script[type=\"application/pw-surface+json\"]').textContent);\n var blocks = JSON.parse(document.querySelector('script[type=\"application/pw-blocks+json\"]').textContent);\n var appearance = JSON.parse(document.querySelector('script[type=\"application/pw-appearance+json\"]').textContent);\n PWFabric.render('#pw-root', { surface: surface }, { mode: 'fat', blocks: blocks, appearance: appearance });\n})();\n</script>\n</body>\n</html>`\n}\n","/**\n * @pwfabric/embed\n *\n * Portable embed runtime — renders a PWFabric CanonicalSurface anywhere, using\n * the REAL `SurfaceRenderer` from `@pwfabric/runtime`.\n *\n * Consumed two ways:\n * - as a built artifact — `assembleWebApp` takes the bundle as an `embedJs`\n * string and ships it into every export's `assets/`;\n * - as a dependency — a host API can resolve `dist/embed.js` out of\n * `node_modules` rather than keeping a committed copy (a vendored copy\n * goes stale silently; a package dependency is version-gated).\n *\n * Two modes:\n * - **thin** — fetch surface + render grants from the API (like a hosted surface page).\n * - **fat** — render an inline surface + block bundles + appearance fully\n * offline, no backend.\n *\n * Public entry: `PWFabric.render(target, source, options?)`. A `data-pw-surface`\n * DOM auto-loader is also wired on load.\n *\n * @module @pwfabric/embed\n */\n\nimport { mountSurface, type SurfaceMountHandle, type RenderCoreOptions } from './render-core.js'\nimport { renderFat, type RenderFatOptions } from './fat.js'\nimport { loadThin, type ThinAuth, type ThinSurfaceRef } from './thin.js'\nimport type {\n DynamicBlockDescriptor,\n BreakpointName,\n} from '@pwfabric/contracts'\nimport type {\n CapabilityProvider,\n EntityFacade,\n ImageAdapter,\n SurfaceEvent,\n RenderableSurface,\n BlockComponentRegistry,\n SurfaceConnectionsValue,\n DataServiceConfig,\n SurfaceDataCache,\n} from '@pwfabric/runtime'\n\n// Re-export the building blocks for bundler consumers.\nexport { renderFat, fatCoreOptions } from './fat.js'\nexport { loadThin, grantsToDescriptors } from './thin.js'\nexport { buildFatHtml } from './build-fat-html.js'\nexport type { BuildFatHtmlOptions } from './build-fat-html.js'\nexport {\n mountSurface,\n createSurfaceElement,\n needsDataBoundRenderer,\n resolveTarget,\n missingBlockTypes,\n RebuildNeededBlock,\n} from './render-core.js'\nexport type { RenderCoreOptions, SurfaceMountHandle } from './render-core.js'\nexport type { RenderFatOptions, FatMountHandle } from './fat.js'\nexport type { LoadThinOptions, LoadThinResult, ThinAuth, ThinSurfaceRef } from './thin.js'\nexport {\n createOfflineEntityFacade,\n createOfflineNavigationProvider,\n staticPersistenceCapability,\n} from './capabilities-stub.js'\n\n// ============================================================\n// PUBLIC OPTION TYPES\n// ============================================================\n\nexport type EmbedMode = 'thin' | 'fat'\n\n/**\n * Source: either a reference to fetch (thin) or an inline surface (fat).\n */\nexport type EmbedSource =\n | { readonly surfaceId: string }\n | { readonly tenantSlug: string; readonly surfaceSlug: string }\n | { readonly surface: RenderableSurface }\n\nexport interface EmbedOptions {\n /** `thin` (fetch) or `fat` (inline/offline). Auto-detected from source when omitted. */\n readonly mode?: EmbedMode\n\n // ── thin ──────────────────────────────────────────────\n /** API origin for thin mode (e.g. https://api.example.com). */\n readonly apiBaseUrl?: string\n /** Auth for thin mode. */\n readonly auth?: ThinAuth\n /** Custom fetch implementation (test/non-browser). */\n readonly fetchImpl?: typeof fetch\n\n // ── fat ───────────────────────────────────────────────\n /** Inline block bundle descriptors (fat). */\n readonly blocks?: readonly DynamicBlockDescriptor[]\n /** Inline appearance ref (fat); falls back to surface.appearance. */\n readonly appearance?: RenderableSurface['appearance']\n /** Hydrate existing server-rendered markup instead of a fresh mount (fat). */\n readonly hydrate?: boolean\n /** Capability providers (fat). */\n readonly capabilities?: CapabilityProvider[]\n /** Entity facade override (fat). */\n readonly entityFacade?: EntityFacade\n /** Connector/provider engine registry + connections (fat embed). */\n readonly connections?: SurfaceConnectionsValue\n /**\n * Configuration for the renderer's DataService — the host's own API origin\n * (so the platform store can be called with its cookie and nobody else can)\n * and the token resolver for `authProviderRef`.\n */\n readonly dataServiceConfig?: DataServiceConfig\n readonly loadingStrategy?: 'gate' | 'immediate'\n readonly dataCache?: SurfaceDataCache\n\n\n // ── shared render passthrough ─────────────────────────\n readonly theme?: 'light' | 'dark'\n readonly viewport?: BreakpointName\n readonly basePath?: string\n readonly imageAdapter?: ImageAdapter\n readonly interactionMode?: 'live' | 'inert'\n readonly onEvent?: (event: SurfaceEvent) => void\n readonly gap?: number\n readonly padding?: number\n /** Custom block component overrides (test/preview seams). */\n readonly components?: Partial<BlockComponentRegistry>\n /** Visible placeholder for block types nothing can render (preview hosts). */\n readonly placeholderMissingBlocks?: boolean\n\n // ── lifecycle callbacks ───────────────────────────────\n readonly onReady?: (handle: SurfaceMountHandle) => void\n readonly onError?: (error: unknown) => void\n}\n\n// ============================================================\n// CORE RENDER ENTRY\n// ============================================================\n\nfunction isInlineSurface(source: EmbedSource): source is { surface: RenderableSurface } {\n return 'surface' in source\n}\n\nfunction detectMode(source: EmbedSource, options?: EmbedOptions): EmbedMode {\n if (options?.mode) return options.mode\n return isInlineSurface(source) ? 'fat' : 'thin'\n}\n\n/**\n * Shared render-option assembly from EmbedOptions → RenderCore/RenderFat opts.\n */\nfunction passthrough(options?: EmbedOptions): Partial<RenderCoreOptions> {\n const o = options ?? {}\n return {\n ...(o.theme !== undefined ? { theme: o.theme } : {}),\n ...(o.viewport !== undefined ? { viewport: o.viewport } : {}),\n ...(o.basePath !== undefined ? { basePath: o.basePath } : {}),\n ...(o.imageAdapter !== undefined ? { imageAdapter: o.imageAdapter } : {}),\n ...(o.interactionMode !== undefined ? { interactionMode: o.interactionMode } : {}),\n ...(o.onEvent !== undefined ? { onEvent: o.onEvent } : {}),\n ...(o.gap !== undefined ? { gap: o.gap } : {}),\n ...(o.padding !== undefined ? { padding: o.padding } : {}),\n ...(o.components !== undefined ? { components: o.components } : {}),\n ...(o.loadingStrategy !== undefined ? { loadingStrategy: o.loadingStrategy } : {}),\n ...(o.dataCache !== undefined ? { dataCache: o.dataCache } : {}),\n ...(o.placeholderMissingBlocks !== undefined ? { placeholderMissingBlocks: o.placeholderMissingBlocks } : {}),\n }\n}\n\n/**\n * Render a surface into `target`.\n *\n * @param target An HTMLElement or CSS selector string.\n * @param source `{ surfaceId }` / `{ tenantSlug, surfaceSlug }` (thin) or\n * `{ surface }` (fat).\n * @param options Mode + transport + render options.\n * @returns A promise resolving to the mount handle.\n */\nexport async function render(\n target: HTMLElement | string,\n source: EmbedSource,\n options?: EmbedOptions\n): Promise<SurfaceMountHandle> {\n const o = options ?? {}\n try {\n const mode = detectMode(source, options)\n\n if (mode === 'fat') {\n if (!isInlineSurface(source)) {\n throw new Error('[pwfabric-embed] fat mode requires an inline { surface }')\n }\n const fatOpts: RenderFatOptions = {\n surface: source.surface,\n ...(o.blocks ? { blocks: o.blocks } : {}),\n ...(o.appearance ? { appearance: o.appearance } : {}),\n ...(o.hydrate ? { hydrate: true } : {}),\n ...(o.capabilities ? { capabilities: o.capabilities } : {}),\n ...(o.entityFacade ? { entityFacade: o.entityFacade } : {}),\n ...(o.connections ? { connections: o.connections } : {}),\n ...(o.dataServiceConfig ? { dataServiceConfig: o.dataServiceConfig } : {}),\n ...passthrough(options),\n }\n const handle = renderFat(target, fatOpts)\n o.onReady?.(handle)\n return handle\n }\n\n // thin mode\n if (isInlineSurface(source)) {\n throw new Error('[pwfabric-embed] thin mode requires a { surfaceId } or slug reference')\n }\n if (!o.apiBaseUrl) {\n throw new Error('[pwfabric-embed] thin mode requires `apiBaseUrl`')\n }\n\n const ref: ThinSurfaceRef =\n 'surfaceId' in source\n ? { surfaceId: source.surfaceId }\n : { tenantSlug: (source as { tenantSlug: string }).tenantSlug, surfaceSlug: (source as { surfaceSlug: string }).surfaceSlug }\n const loaded = await loadThin(ref, {\n apiBaseUrl: o.apiBaseUrl,\n ...(o.auth ? { auth: o.auth } : {}),\n ...(o.fetchImpl ? { fetchImpl: o.fetchImpl } : {}),\n })\n\n const core: RenderCoreOptions = {\n surface: loaded.surface,\n ...(loaded.dynamicBlocks.length > 0 ? { dynamicBlocks: loaded.dynamicBlocks } : {}),\n ...(o.capabilities ? { capabilities: o.capabilities } : {}),\n ...(o.entityFacade ? { entityFacade: o.entityFacade } : {}),\n ...(loaded.layout?.gap !== undefined ? { gap: loaded.layout.gap } : {}),\n ...(loaded.layout?.padding !== undefined ? { padding: loaded.layout.padding } : {}),\n ...passthrough(options),\n }\n const handle = mountSurface(target, core)\n o.onReady?.(handle)\n return handle\n } catch (err) {\n if (o.onError) {\n o.onError(err)\n // Re-throw so callers awaiting the promise still observe the failure.\n }\n throw err\n }\n}\n\n// ============================================================\n// DOM AUTO-LOADER (data-pw-surface)\n// ============================================================\n\n/**\n * Scan the DOM for `[data-pw-surface]` containers and render each.\n *\n * Attribute contract:\n * - `data-pw-surface` — surfaceId (thin) OR `\"inline\"` for fat.\n * - `data-pw-mode` — `\"thin\"` | `\"fat\"` (optional; auto-detected).\n * - `data-pw-api` — apiBaseUrl (thin).\n * - `data-pw-tenant` + `data-pw-slug` — slug pair (thin, overrides surfaceId).\n * - `data-pw-theme` — `\"light\"` | `\"dark\"`.\n * - `data-pw-token` — bearer token (thin).\n *\n * For fat/inline rendering the element should contain sibling scripts:\n * `<script type=\"application/pw-surface+json\">…</script>`\n * `<script type=\"application/pw-blocks+json\">…</script>` (optional)\n * `<script type=\"application/pw-appearance+json\">…</script>` (optional)\n */\nfunction readInlineJson<T>(root: ParentNode, type: string): T | undefined {\n const el = root.querySelector(`script[type=\"application/${type}+json\"]`)\n if (!el?.textContent) return undefined\n try {\n return JSON.parse(el.textContent) as T\n } catch {\n return undefined\n }\n}\n\nfunction hydrateElement(el: HTMLElement): void {\n const ds = el.dataset\n const surfaceAttr = ds.pwSurface\n const declaredMode = ds.pwMode as EmbedMode | undefined\n\n // Inline surface scripts may live inside the container or as siblings.\n const scope: ParentNode = el.querySelector('script[type^=\"application/pw-\"]')\n ? el\n : el.parentNode ?? el\n const inlineSurface = readInlineJson<RenderableSurface>(scope, 'pw-surface')\n\n const isFat = declaredMode === 'fat' || (!declaredMode && (surfaceAttr === 'inline' || !!inlineSurface))\n\n const common: EmbedOptions = {\n ...(ds.pwTheme ? { theme: ds.pwTheme as 'light' | 'dark' } : {}),\n }\n\n if (isFat) {\n if (!inlineSurface) {\n // Nothing to render — leave a console hint and bail.\n console.warn('[pwfabric-embed] data-pw-surface=\"inline\" but no inline surface JSON found')\n return\n }\n const blocks = readInlineJson<DynamicBlockDescriptor[]>(scope, 'pw-blocks')\n const appearance = readInlineJson<RenderableSurface['appearance']>(scope, 'pw-appearance')\n void render(el, { surface: inlineSurface }, {\n ...common,\n mode: 'fat',\n ...(blocks ? { blocks } : {}),\n ...(appearance ? { appearance } : {}),\n })\n return\n }\n\n // thin\n const apiBaseUrl = ds.pwApi\n if (!apiBaseUrl) {\n console.warn('[pwfabric-embed] data-pw-surface thin mode requires data-pw-api')\n return\n }\n const auth = ds.pwToken ? { accessToken: ds.pwToken } : undefined\n const source: EmbedSource =\n ds.pwTenant && ds.pwSlug\n ? { tenantSlug: ds.pwTenant, surfaceSlug: ds.pwSlug }\n : { surfaceId: surfaceAttr ?? '' }\n\n void render(el, source, {\n ...common,\n mode: 'thin',\n apiBaseUrl,\n ...(auth ? { auth } : {}),\n })\n}\n\n/**\n * Scan + hydrate all `[data-pw-surface]` elements currently in the document.\n * Idempotent: elements already hydrated (marked with `data-pw-hydrated`) skip.\n */\nexport function autoload(root: ParentNode = document): void {\n const els = root.querySelectorAll<HTMLElement>('[data-pw-surface]')\n els.forEach((el) => {\n if (el.dataset.pwHydrated === 'true') return\n el.dataset.pwHydrated = 'true'\n hydrateElement(el)\n })\n}\n\n// Wire the auto-loader once the DOM is ready (browser only).\nif (typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => autoload())\n } else {\n // Defer to a microtask so a synchronous `PWFabric.render` call right after\n // the script tag still wins ordering if the host prefers manual control.\n queueMicrotask(() => autoload())\n }\n}\n\n// ============================================================\n// NAMESPACE (mirrors the IIFE global `PWFabric`)\n// ============================================================\n\nexport const PWFabric = {\n render,\n renderFat,\n loadThin,\n autoload,\n}\n\nexport default PWFabric\n"]}
1
+ {"version":3,"sources":["../src/render-core.tsx","../src/capabilities-stub.ts","../src/fat.ts","../../core/src/index.ts","../../core/src/errors.ts","../../core/src/logger.ts","../../core/src/errors/ErrorCode.ts","../../core/src/errors/AppError.ts","../../core/src/monitoring/metrics.ts","../../core/src/monitoring/web-vitals.ts","../../core/src/observability/logger.ts","../../core/src/observability/tracer.ts","../../core/src/utils.ts","../../core/src/contract-builder.ts","../../core/src/contracts/passthrough.ts","../../core/src/oauth-scopes.ts","../../core/src/config-schema-builder.ts","../../core/src/state.ts","../../core/src/blocks/types.ts","../../core/src/blocks/layout-schema.ts","../../core/src/blocks/host-imports.ts","../src/thin.ts","../src/build-fat-html.ts","../src/index.ts"],"names":["SurfaceRenderer","generateId","validationError","isCapability","handle","err"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAgLO,SAAS,uBAAuB,OAAA,EAAqC;AAC1E,EAAA,OAAO,wBAAwB,OAAwD,CAAA;AACzF;AAMA,SAAS,mBAAmB,IAAA,EAAkD;AAC5E,EAAA,MAAM,QAAiC,EAAC;AACxC,EAAA,IAAI,IAAA,CAAK,KAAA,KAAU,MAAA,EAAW,KAAA,CAAM,QAAQ,IAAA,CAAK,KAAA;AACjD,EAAA,IAAI,IAAA,CAAK,QAAA,KAAa,MAAA,EAAW,KAAA,CAAM,WAAW,IAAA,CAAK,QAAA;AACvD,EAAA,IAAI,IAAA,CAAK,YAAA,KAAiB,MAAA,EAAW,KAAA,CAAM,eAAe,IAAA,CAAK,YAAA;AAC/D,EAAA,IAAI,IAAA,CAAK,YAAA,KAAiB,MAAA,EAAW,KAAA,CAAM,eAAe,IAAA,CAAK,YAAA;AAC/D,EAAA,IAAI,IAAA,CAAK,WAAA,KAAgB,MAAA,EAAW,KAAA,CAAM,cAAc,IAAA,CAAK,WAAA;AAC7D,EAAA,IAAI,IAAA,CAAK,iBAAA,KAAsB,MAAA,EAAW,KAAA,CAAM,oBAAoB,IAAA,CAAK,iBAAA;AACzE,EAAA,IAAI,IAAA,CAAK,eAAA,KAAoB,MAAA,EAAW,KAAA,CAAM,kBAAkB,IAAA,CAAK,eAAA;AACrE,EAAA,IAAI,IAAA,CAAK,SAAA,KAAc,MAAA,EAAW,KAAA,CAAM,YAAY,IAAA,CAAK,SAAA;AACzD,EAAA,IAAI,IAAA,CAAK,eAAA,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,CAAe,EAAE,CAAA;AAAA,EACnB,CAAC,CAAA;AACH;AAGA,IAAI,OAAO,aAAa,WAAA,EAAa;AACnC,EAAA,IAAI,QAAA,CAAS,eAAe,SAAA,EAAW;AACrC,IAAA,QAAA,CAAS,gBAAA,CAAiB,kBAAA,EAAoB,MAAM,QAAA,EAAU,CAAA;AAAA,EAChE,CAAA,MAAO;AAGL,IAAA,cAAA,CAAe,MAAM,UAAU,CAAA;AAAA,EACjC;AACF;AAMO,IAAM,QAAA,GAAW;AAAA,EACtB,MAAA;AAAA,EACA,SAAA;AAAA,EACA,QAAA;AAAA,EACA;AACF;AAEA,IAAO,WAAA,GAAQ","file":"index.js","sourcesContent":["/**\n * Shared mount core for the embed runtime.\n *\n * Wraps the REAL runtime renderer (`SurfaceRenderer` / `DataBoundSurfaceRenderer`,\n * imported as-is from `@pwfabric/runtime`) inside a\n * `DynamicArtifactProvider` and mounts it into a target DOM node with\n * `ReactDOM.createRoot`.\n *\n * Nothing here talks to the network on its own — the caller supplies the\n * already-resolved surface + dynamic block descriptors. Thin mode fetches\n * them first (see `thin.ts`); fat mode passes inline descriptors (see\n * `fat.ts`).\n *\n * @module @pwfabric/embed/render-core\n */\n\nimport * as React from 'react'\nimport * as ReactDOM from 'react-dom/client'\nimport {\n // The aliased export name in the runtime's public `exports` — this IS the\n // canonical `SurfaceRenderer`, re-exported as `BlockSurfaceRenderer` to\n // disambiguate from the surface/* module's own renderer.\n BlockSurfaceRenderer as SurfaceRenderer,\n DataBoundSurfaceRenderer,\n DynamicArtifactProvider,\n surfaceNeedsDataBinding,\n} from '@pwfabric/runtime'\nimport type {\n RenderableSurface,\n DataBoundSurface,\n EntityFacade,\n CapabilityProvider,\n SurfaceEvent,\n ImageAdapter,\n BlockComponentRegistry,\n SurfaceConnectionsValue,\n DataServiceConfig,\n SurfaceDataCache,\n BlockComponentProps,\n} from '@pwfabric/runtime'\nimport type {\n DynamicBlockDescriptor,\n DynamicStarterDescriptor,\n BreakpointName,\n} from '@pwfabric/contracts'\n\n// ============================================================\n// TYPES\n// ============================================================\n\n/**\n * Options accepted by the shared mount. A superset of what both thin and fat\n * mode produce after they have resolved the surface + descriptors.\n */\nexport interface RenderCoreOptions {\n /** Resolved surface to render (blocks + appearance + capabilities). */\n readonly surface: RenderableSurface\n\n /** Dynamic (installed/CDN/inline) block descriptors. */\n readonly dynamicBlocks?: readonly DynamicBlockDescriptor[]\n\n /** Optional dynamic starter descriptors (rarely used in embed). */\n readonly dynamicStarters?: readonly DynamicStarterDescriptor[]\n\n /** App-level light/dark hint passed straight to the renderer. */\n readonly theme?: 'light' | 'dark'\n\n /** Explicit viewport breakpoint override (otherwise auto-detected). */\n readonly viewport?: BreakpointName\n\n /** Capability providers (auth/data/navigation/...). */\n readonly capabilities?: CapabilityProvider[]\n\n /** Entity facade for the platform/entities capability (fat = in-memory). */\n readonly entityFacade?: EntityFacade\n\n /**\n * The surface CONNECTIONS CONTEXT — configured connections +\n * the loaded connector/provider engine registry. When present the render\n * routes `{kind:entity,connector}` data sources through the registry AND\n * exposes the value to blocks via `SurfaceConnectionsContext` (the\n * engine-bridge path, e.g. chat-panel). Absent = today's behavior.\n */\n readonly connections?: SurfaceConnectionsValue\n /**\n * Configuration for the renderer's DataService — the host's own API origin\n * (so the platform store can be called with its cookie and nobody else can)\n * and the token resolver for `authProviderRef`.\n */\n readonly dataServiceConfig?: DataServiceConfig\n /** See DataBoundSurfaceRendererProps — 'gate' withholds the tree until the first fetch, 'immediate' paints at once. */\n readonly loadingStrategy?: 'gate' | 'immediate'\n /** See DataBoundSurfaceRendererProps — yesterday's rows while today's load. */\n readonly dataCache?: SurfaceDataCache\n\n\n /** `live` (default) or `inert` (no auto-refresh, no dispatched actions). */\n readonly interactionMode?: 'live' | 'inert'\n\n /** Base path for links/routing. */\n readonly basePath?: string\n\n /** Image adapter; defaults to plain <img> when omitted. */\n readonly imageAdapter?: ImageAdapter\n\n /** Custom block component overrides (test/preview seams). */\n readonly components?: Partial<BlockComponentRegistry>\n\n /** Surface event callback. */\n readonly onEvent?: (event: SurfaceEvent) => void\n\n /** Grid gap (px) override. */\n readonly gap?: number\n\n /** Surface inner padding (px) override. */\n readonly padding?: number\n\n /**\n * Draw a visible \"rebuild needed\" placeholder for every block type in the\n * surface that has neither a dynamic descriptor nor a component.\n *\n * Off by default, and deliberately so: on a published page an unknown type\n * renders only its children (see the renderer), because a visible\n * placeholder reads as a broken page to a visitor. A live preview is the\n * opposite case — the author has just added a block whose bundle is not in\n * the shipped manifest yet, and an invisible block would look like the edit\n * did nothing. The placeholder is a plain element: nothing is fetched or\n * imported for the missing type.\n */\n readonly placeholderMissingBlocks?: boolean\n}\n\n/**\n * Handle returned by `mountSurface` so the host can later unmount or update.\n */\nexport interface SurfaceMountHandle {\n /** Tear down the React root and free the DOM. */\n unmount(): void\n /** The root DOM node the surface was mounted into. */\n readonly container: HTMLElement\n /**\n * Re-render new surface options into the SAME root — e.g. a client-side\n * page transition. Reuses the root created by `mountSurface` instead of\n * calling `createRoot`/`hydrateRoot` again (which would either throw or\n * discard the existing tree).\n */\n render(opts: RenderCoreOptions): void\n}\n\nexport interface MountSurfaceOptions {\n /**\n * Hydrate existing server-rendered markup already present in `target`\n * (`ReactDOM.hydrateRoot`) instead of a fresh client-only mount\n * (`ReactDOM.createRoot`, which discards whatever DOM was already there).\n * The initial `opts` must produce a tree matching what was server-rendered\n * or React will warn/re-render on mismatch.\n */\n readonly hydrate?: boolean\n}\n\n// ============================================================\n// HELPERS\n// ============================================================\n\n/**\n * Does this surface need the data-bound renderer? The RUNTIME answers —\n * `surfaceNeedsDataBinding` is the same predicate the renderer's own\n * passthrough uses: data sources, `initialState`, declared behaviors,\n * formBindings, or a block `action`.\n *\n * This used to be a second, shorter list (sources + initialState). It had\n * drifted from the renderer's in both directions: a page with only buttons\n * carrying `action` props, or only formBindings, got the plain\n * SurfaceRenderer here — no dispatcher, so the click did nothing and the\n * submit went nowhere.\n */\nexport function needsDataBoundRenderer(surface: RenderableSurface): boolean {\n return surfaceNeedsDataBinding(surface as Parameters<typeof surfaceNeedsDataBinding>[0])\n}\n\n/**\n * Build the props object shared by both renderers, omitting `undefined`\n * keys so `exactOptionalPropertyTypes` stays happy.\n */\nfunction buildRendererProps(opts: RenderCoreOptions): Record<string, unknown> {\n const props: Record<string, unknown> = {}\n if (opts.theme !== undefined) props.theme = opts.theme\n if (opts.viewport !== undefined) props.viewport = opts.viewport\n if (opts.capabilities !== undefined) props.capabilities = opts.capabilities\n if (opts.entityFacade !== undefined) props.entityFacade = opts.entityFacade\n if (opts.connections !== undefined) props.connections = opts.connections\n if (opts.dataServiceConfig !== undefined) props.dataServiceConfig = opts.dataServiceConfig\n if (opts.loadingStrategy !== undefined) props.loadingStrategy = opts.loadingStrategy\n if (opts.dataCache !== undefined) props.dataCache = opts.dataCache\n if (opts.interactionMode !== undefined) props.interactionMode = opts.interactionMode\n if (opts.basePath !== undefined) props.basePath = opts.basePath\n if (opts.imageAdapter !== undefined) props.imageAdapter = opts.imageAdapter\n if (opts.components !== undefined) props.components = opts.components\n if (opts.onEvent !== undefined) props.onEvent = opts.onEvent\n if (opts.gap !== undefined) props.gap = opts.gap\n if (opts.padding !== undefined) props.padding = opts.padding\n return props\n}\n\n// ============================================================\n// MISSING BLOCK TYPES\n// ============================================================\n\n/**\n * Every block type in `surface` that nothing can render: no dynamic\n * descriptor and no component. Walks `blocks` and `children` recursively.\n */\nexport function missingBlockTypes(\n surface: RenderableSurface,\n dynamicBlocks: readonly DynamicBlockDescriptor[] | undefined,\n components: Partial<BlockComponentRegistry> | undefined\n): string[] {\n const known = new Set<string>()\n for (const d of dynamicBlocks ?? []) known.add(d.blockType)\n for (const k of Object.keys(components ?? {})) known.add(k)\n const missing = new Set<string>()\n const walk = (nodes: unknown): void => {\n if (!Array.isArray(nodes)) return\n for (const node of nodes) {\n if (!node || typeof node !== 'object') continue\n const n = node as { type?: unknown; children?: unknown }\n if (typeof n.type === 'string' && n.type && !known.has(n.type)) missing.add(n.type)\n walk(n.children)\n }\n }\n walk((surface as { blocks?: unknown }).blocks)\n return [...missing]\n}\n\n/**\n * The placeholder for a block type whose bundle this page does not have.\n * Static markup only — it never asks for the type's code. Children still\n * render inside it, so a missing container does not hide its subtree.\n */\nexport function RebuildNeededBlock({ block, children }: BlockComponentProps): React.ReactElement {\n return React.createElement(\n 'div',\n {\n 'data-pw-rebuild-needed': block.type,\n role: 'note',\n style: {\n border: '1px dashed currentColor',\n borderRadius: 6,\n padding: 12,\n opacity: 0.7,\n fontSize: 13,\n },\n },\n React.createElement('span', null, `Rebuild needed: \"${block.type}\" is not in this preview yet.`),\n children ?? null\n )\n}\n\nfunction withPlaceholders(opts: RenderCoreOptions): Partial<BlockComponentRegistry> | undefined {\n if (!opts.placeholderMissingBlocks) return opts.components\n const missing = missingBlockTypes(opts.surface, opts.dynamicBlocks, opts.components)\n if (missing.length === 0) return opts.components\n const added = Object.fromEntries(missing.map((t) => [t, RebuildNeededBlock])) as Partial<BlockComponentRegistry>\n return { ...added, ...(opts.components ?? {}) }\n}\n\n// ============================================================\n// ELEMENT FACTORY\n// ============================================================\n\n/**\n * Build the React element tree for a surface — `DynamicArtifactProvider`\n * wrapping the appropriate renderer. Exposed separately from `mountSurface`\n * so it can be used in SSR / test contexts without a DOM root.\n */\nexport function createSurfaceElement(opts: RenderCoreOptions): React.ReactElement {\n // A connections context also requires the data-bound renderer\n // — it is what provides `SurfaceConnectionsContext` (engine-bridge blocks) and\n // routes connector data sources through the registry. A surface with only\n // engine-bridge panels declares no dataSources, so force it on when present.\n const useDataBound = needsDataBoundRenderer(opts.surface) || opts.connections != null\n const components = withPlaceholders(opts)\n const shared = buildRendererProps(components && components !== opts.components ? { ...opts, components } : opts)\n\n const rendererElement = useDataBound\n ? React.createElement(DataBoundSurfaceRenderer, {\n surface: opts.surface as DataBoundSurface,\n ...shared,\n })\n : React.createElement(SurfaceRenderer, {\n surface: opts.surface,\n ...shared,\n })\n\n return React.createElement(\n DynamicArtifactProvider,\n {\n ...(opts.dynamicBlocks && opts.dynamicBlocks.length > 0\n ? { dynamicBlocks: opts.dynamicBlocks }\n : {}),\n ...(opts.dynamicStarters && opts.dynamicStarters.length > 0\n ? { dynamicStarters: opts.dynamicStarters }\n : {}),\n children: rendererElement,\n }\n )\n}\n\n// ============================================================\n// MOUNT\n// ============================================================\n\n/**\n * Resolve a target — an HTMLElement or a CSS selector string — to a node.\n */\nexport function resolveTarget(target: HTMLElement | string): HTMLElement {\n if (typeof target === 'string') {\n const el = document.querySelector(target)\n if (!el) {\n throw new Error(`[pwfabric-embed] target not found: ${target}`)\n }\n return el as HTMLElement\n }\n return target\n}\n\n/**\n * Mount a surface into `target` and return a handle for later teardown or\n * update. Pass `{ hydrate: true }` to attach to existing server-rendered\n * markup instead of discarding it.\n */\nexport function mountSurface(\n target: HTMLElement | string,\n opts: RenderCoreOptions,\n mountOptions?: MountSurfaceOptions\n): SurfaceMountHandle {\n const container = resolveTarget(target)\n const root = mountOptions?.hydrate\n ? ReactDOM.hydrateRoot(container, createSurfaceElement(opts))\n : ReactDOM.createRoot(container)\n if (!mountOptions?.hydrate) root.render(createSurfaceElement(opts))\n return {\n container,\n unmount() {\n root.unmount()\n },\n render(newOpts: RenderCoreOptions) {\n root.render(createSurfaceElement(newOpts))\n },\n }\n}\n","/**\n * Offline capability stubs for fat mode.\n *\n * Fat mode renders with no API and no auth, so any capability the surface\n * declares (entities, navigation, persistence) must be satisfied locally.\n * These factories provide in-memory / no-op implementations:\n *\n * - `createOfflineEntityFacade()` — a real `createEntityFacade()` backed by\n * the in-memory `StaticConnector`, optionally seeded with entity defs +\n * records. CRUD happens entirely in memory.\n * - `createOfflineNavigationProvider()` — a `navigation` CapabilityProvider\n * whose links resolve to in-page anchors (no router).\n * - `staticDataSources()` — turns a record-map of inline data into\n * `platform/persistence` static data sources for the DataBoundSurfaceRenderer.\n *\n * @module @pwfabric/embed/capabilities-stub\n */\n\nimport { createEntityFacade, StaticConnector } from '@pwfabric/runtime'\nimport type { EntityFacade, CapabilityProvider } from '@pwfabric/runtime'\nimport type { EntityDefinition } from '@pwfabric/runtime'\n\n// ============================================================\n// ENTITY FACADE (in-memory CRUD)\n// ============================================================\n\nexport interface OfflineEntitySeed {\n /** Entity definition to register. */\n readonly definition: EntityDefinition\n /** Initial records to load into the static connector. */\n readonly records?: readonly Record<string, unknown>[]\n}\n\n/**\n * Build an entity facade wired to a single in-memory `StaticConnector`.\n * All CRUD performed by the surface happens in memory and is lost on reload —\n * exactly what an offline embed wants.\n */\nexport function createOfflineEntityFacade(seeds?: readonly OfflineEntitySeed[]): EntityFacade {\n const connector = new StaticConnector('offline')\n const facade = createEntityFacade()\n // Register the single static connector under its name.\n facade.connectors.register(connector)\n\n if (seeds) {\n for (const seed of seeds) {\n facade.registerEntity(seed.definition, connector.name)\n if (seed.records) {\n for (const record of seed.records) {\n // Fire-and-forget seed — the static connector resolves synchronously\n // enough for a first render, and errors here are non-fatal.\n void connector.create(seed.definition.id, record)\n }\n }\n }\n }\n\n return facade\n}\n\n// ============================================================\n// NAVIGATION (no-op / in-page)\n// ============================================================\n\n/**\n * A `navigation` capability provider for offline rendering. There is no\n * router, so navigation is reduced to in-page anchors / `window.location`.\n * The provider exposes a `data` payload the navigation-aware blocks read.\n */\nexport function createOfflineNavigationProvider(\n options: { readonly basePath?: string } = {}\n): CapabilityProvider {\n const basePath = options.basePath ?? ''\n return {\n type: 'navigation',\n data: {\n mode: 'offline',\n basePath,\n /** Resolve a href against the base path; absolute/anchor hrefs pass through. */\n resolve(href: string): string {\n if (/^([a-z]+:)?\\/\\//i.test(href) || href.startsWith('#')) return href\n return `${basePath}${href}`\n },\n /** No-op push — offline embeds have no history stack. */\n push(): void {\n /* intentionally inert */\n },\n },\n }\n}\n\n// ============================================================\n// STATIC DATA SOURCES\n// ============================================================\n\n/**\n * Convert a map of `{ sourceId: data }` into the `platform/persistence`\n * capability config shape (static data sources) that the\n * DataBoundSurfaceRenderer consumes. Use this to inline mock/fixture data into\n * a fat embed so REST-bound blocks render without a backend.\n */\nexport function staticPersistenceCapability(\n data: Readonly<Record<string, unknown>>,\n initialState?: Record<string, unknown>\n): CapabilityProvider & { capability: string; config: Record<string, unknown> } {\n const dataSources = Object.entries(data).map(([id, staticData]) => ({\n id,\n kind: 'static' as const,\n staticData,\n }))\n return {\n type: 'data',\n capability: 'platform/persistence',\n config: {\n dataSources,\n ...(initialState ? { initialState } : {}),\n },\n } as CapabilityProvider & { capability: string; config: Record<string, unknown> }\n}\n","/**\n * Fat mode renderer — fully offline.\n *\n * Renders a surface with NO API and NO auth. The surface JSON, its block\n * bundle descriptors, and its appearance are all provided inline by the\n * caller. Capabilities default to the offline stubs (in-memory entity facade,\n * inert navigation), so a surface that declares capabilities still renders.\n *\n * Offline block loading: `DynamicBlockDescriptor.moduleUrl` may be a `data:`\n * URL (or any URL the host can `fetch`). The runtime's `BlockModuleLoader`\n * fetches the bytes, SHA-256-verifies them against `descriptor.integrity`,\n * and `import()`s the resulting Blob URL — all client-side, no server. As long\n * as the descriptors carry inline `data:` module URLs + correct integrity\n * hashes, the whole render is self-contained.\n *\n * @module @pwfabric/embed/fat\n */\n\nimport { mountSurface, type SurfaceMountHandle } from './render-core.js'\nimport { createOfflineEntityFacade, createOfflineNavigationProvider } from './capabilities-stub.js'\nimport { isCapability } from '@pwfabric/runtime/capability'\nimport type { RenderCoreOptions } from './render-core.js'\nimport type {\n EntityFacade,\n CapabilityProvider,\n RenderableSurface,\n SurfaceConnectionsValue,\n DataServiceConfig,\n SurfaceDataCache,\n} from '@pwfabric/runtime'\nimport type { DynamicBlockDescriptor } from '@pwfabric/contracts'\n\n// ============================================================\n// TYPES\n// ============================================================\n\nexport interface RenderFatOptions {\n /** The surface to render (inline JSON). */\n readonly surface: RenderableSurface\n\n /**\n * Block bundle descriptors. `moduleUrl` is typically a `data:text/javascript`\n * URL for full offline self-containment; integrity must match the bytes.\n */\n readonly blocks?: readonly DynamicBlockDescriptor[]\n\n /**\n * Capability providers. When omitted, offline stubs are auto-supplied for\n * any capability the surface declares (entities → in-memory facade,\n * navigation → inert provider).\n */\n readonly capabilities?: CapabilityProvider[]\n\n /** Override the auto-created offline entity facade. */\n readonly entityFacade?: EntityFacade\n\n /**\n * Connector/provider engine registry + configured\n * connections. The runner builds this from the export's shipped engine\n * bundles + the PKCE auth token, so connector panels (chat-panel etc.) run\n * against real engines. Threaded to the data-bound renderer, which exposes it\n * via `SurfaceConnectionsContext`.\n */\n readonly connections?: SurfaceConnectionsValue\n /**\n * How the data layer authenticates its requests.\n *\n * Carries the resolver a pwapp runner supplies for the VISITOR's own\n * session: a source that names an `authProviderRef` gets an\n * `Authorization: Bearer` header for it. Declared here because fat mode is\n * how a published app renders, and a published app behind a sign-in has to\n * fetch its own records as the person who signed in.\n */\n readonly dataServiceConfig?: DataServiceConfig\n readonly loadingStrategy?: 'gate' | 'immediate'\n readonly dataCache?: SurfaceDataCache\n\n /** Inline appearance ref; overrides `surface.appearance` when given. */\n readonly appearance?: RenderableSurface['appearance']\n\n /**\n * Hydrate existing server-rendered markup in `target` instead of a fresh\n * client-only mount. See `MountSurfaceOptions.hydrate`.\n */\n readonly hydrate?: boolean\n\n // Passthrough render options.\n readonly theme?: RenderCoreOptions['theme']\n readonly viewport?: RenderCoreOptions['viewport']\n readonly interactionMode?: RenderCoreOptions['interactionMode']\n readonly basePath?: RenderCoreOptions['basePath']\n readonly imageAdapter?: RenderCoreOptions['imageAdapter']\n readonly components?: RenderCoreOptions['components']\n readonly onEvent?: RenderCoreOptions['onEvent']\n readonly gap?: RenderCoreOptions['gap']\n readonly padding?: RenderCoreOptions['padding']\n /** See `RenderCoreOptions.placeholderMissingBlocks` — preview hosts only. */\n readonly placeholderMissingBlocks?: RenderCoreOptions['placeholderMissingBlocks']\n}\n\n/**\n * The handle fat mode returns. `update` re-renders new fat options into the\n * SAME root, through the same option translation the first mount used — so a\n * host holding fat options (blocks, appearance override, offline stubs) never\n * has to rebuild the core options by hand.\n */\nexport interface FatMountHandle extends SurfaceMountHandle {\n update(opts: RenderFatOptions): void\n}\n\n// ============================================================\n// HELPERS\n// ============================================================\n\nfunction surfaceDeclares(surface: RenderableSurface, capability: string): boolean {\n // Compare CANONICALLY. A receipt may spell a capability short (`entities`)\n // or long (`platform/entities`); a raw `===` misses the short form and this\n // path builds neither the offline navigation provider nor the entity facade —\n // the panel silently stays empty. The three sibling call sites use\n // `isCapability` too.\n return (surface.capabilities ?? []).some((c: { capability?: string }) => isCapability(c, capability))\n}\n\n/**\n * Build the capability list + entity facade for an offline render, supplying\n * stubs for any declared capability the caller didn't provide.\n */\nexport function resolveOfflineCapabilities(opts: RenderFatOptions): {\n capabilities: CapabilityProvider[]\n entityFacade: EntityFacade | undefined\n} {\n const capabilities: CapabilityProvider[] = [...(opts.capabilities ?? [])]\n\n // Navigation stub when declared and not already supplied.\n if (\n surfaceDeclares(opts.surface, 'platform/navigation') &&\n !capabilities.some((c) => c.type === 'navigation')\n ) {\n capabilities.push(\n createOfflineNavigationProvider(opts.basePath ? { basePath: opts.basePath } : {})\n )\n }\n\n // Entity facade: explicit > auto-created (when entities declared).\n let entityFacade = opts.entityFacade\n if (!entityFacade && surfaceDeclares(opts.surface, 'platform/entities')) {\n entityFacade = createOfflineEntityFacade()\n }\n\n return { capabilities, entityFacade }\n}\n\n// ============================================================\n// RENDER\n// ============================================================\n\n/**\n * Translate fat options into the shared core options: offline capability\n * stubs, the appearance override folded into the surface, every passthrough.\n */\nexport function fatCoreOptions(opts: RenderFatOptions): RenderCoreOptions {\n const { capabilities, entityFacade } = resolveOfflineCapabilities(opts)\n\n // `appearance` is a distinct, top-level override — RenderCoreOptions has no\n // separate appearance channel, so the ONLY way it reaches SurfaceRenderer\n // is via `surface.appearance`. Merge it in here (rather than relying on the\n // caller to have baked it into the surface already) so `opts.appearance`\n // actually does what its doc comment says instead of being silently dropped.\n const surface = opts.appearance ? { ...opts.surface, appearance: opts.appearance } : opts.surface\n\n return {\n surface,\n ...(opts.blocks ? { dynamicBlocks: opts.blocks } : {}),\n ...(capabilities.length > 0 ? { capabilities } : {}),\n ...(entityFacade ? { entityFacade } : {}),\n ...(opts.connections ? { connections: opts.connections } : {}),\n // A HAND-COPIED LIST. `RenderFatOptions` declares this and\n // `RenderCoreOptions` accepts it; this line is the copy between them.\n // Without it a pwapp visitor signs in, the gate lifts, and every data\n // request still goes out anonymous — `getAccessToken` is never called\n // because the DataService has no config.\n ...(opts.dataServiceConfig ? { dataServiceConfig: opts.dataServiceConfig } : {}),\n ...(opts.loadingStrategy !== undefined ? { loadingStrategy: opts.loadingStrategy } : {}),\n ...(opts.dataCache !== undefined ? { dataCache: opts.dataCache } : {}),\n ...(opts.theme !== undefined ? { theme: opts.theme } : {}),\n ...(opts.viewport !== undefined ? { viewport: opts.viewport } : {}),\n ...(opts.interactionMode !== undefined ? { interactionMode: opts.interactionMode } : {}),\n ...(opts.basePath !== undefined ? { basePath: opts.basePath } : {}),\n ...(opts.imageAdapter !== undefined ? { imageAdapter: opts.imageAdapter } : {}),\n ...(opts.components !== undefined ? { components: opts.components } : {}),\n ...(opts.onEvent !== undefined ? { onEvent: opts.onEvent } : {}),\n ...(opts.gap !== undefined ? { gap: opts.gap } : {}),\n ...(opts.padding !== undefined ? { padding: opts.padding } : {}),\n ...(opts.placeholderMissingBlocks !== undefined\n ? { placeholderMissingBlocks: opts.placeholderMissingBlocks }\n : {}),\n }\n}\n\n/**\n * Render a surface fully offline into `target`.\n */\nexport function renderFat(\n target: HTMLElement | string,\n opts: RenderFatOptions\n): FatMountHandle {\n const core = fatCoreOptions(opts)\n const handle = mountSurface(target, core, opts.hydrate ? { hydrate: true } : undefined)\n // The offline entity facade the first mount created holds the page's\n // in-memory records. An update that supplies none keeps that one instead of\n // starting from an empty store on every edit.\n const firstFacade = core.entityFacade\n return {\n container: handle.container,\n unmount: () => handle.unmount(),\n render: (next) => handle.render(next),\n update(next: RenderFatOptions) {\n const withFacade = !next.entityFacade && firstFacade ? { ...next, entityFacade: firstFacade } : next\n handle.render(fatCoreOptions(withFacade))\n },\n }\n}\n","/**\n * @pwfabric/core\n *\n * Core functionality and utilities for the PWFabric platform.\n *\n * PHASE0-WS3: Core orchestration layer\n * Platform hardening (errors, monitoring, observability)\n *\n * @module @pwfabric/core\n */\n\n// Re-export contracts for convenience\nexport * from '@pwfabric/contracts'\n\n// Core exports - explicitly exclude conflicting names\nexport {\n PWFabricError,\n ValidationError as CoreValidationError,\n NotFoundError,\n UnauthorizedError,\n ForbiddenError,\n} from './errors.js'\n\nexport { type LogLevel, type LogEntry, Logger, createLogger } from './logger.js'\n\n// Error infrastructure\nexport {\n ErrorCode,\n type ErrorCodeType,\n getHttpStatus,\n isRetryable,\n AppError,\n ValidationAppError,\n NetworkAppError,\n EditorAppError,\n type ErrorContext,\n type SerializedError,\n} from './errors/index.js'\n\n// Monitoring infrastructure\nexport {\n type WebVitalName,\n type MetricRating,\n type Metric,\n type WebVitalMetric,\n type TimingMetric,\n type RenderMetric,\n type PerformanceBudget,\n type MetricsState,\n DEFAULT_BUDGET,\n createMetricsState,\n getRating,\n type WebVitalCallback,\n observeLCP,\n observeFID,\n observeCLS,\n observeTTFB,\n observeINP,\n observeFCP,\n observeAllWebVitals,\n} from './monitoring/index.js'\n\n// Observability infrastructure\nexport {\n type LogContext,\n type ILogger,\n ConsoleLogger,\n createObservabilityLogger,\n type TraceContext,\n type Span,\n type SpanResult,\n createTraceContext,\n createChildContext,\n createSpan,\n extractTraceId,\n injectTraceId,\n} from './observability/index.js'\n\nexport {\n // ok and err are already exported from contracts\n sleep,\n retry,\n generateId,\n} from './utils.js'\n\n// Builders (PHASE0-WS3)\nexport { ContractBuilder, defineContract, anySchema, objectSchema } from './contract-builder.js'\n\n// Canonical contracts\nexport { passthroughContract } from './contracts/passthrough.js'\n\n// Delegated OAuth scope lists — the ONE reader. Three copies of a\n// tolerant reader once split a JSON string into scope-shaped garbage and sent\n// it to Microsoft; consumers import this instead of remembering the rule.\nexport { isScopeToken, readScopeList, type ScopeListReading } from './oauth-scopes.js'\n\nexport { CapabilityBuilder, defineCapability } from './capability-builder.js'\n\nexport {\n FieldBuilder,\n ConfigSchemaBuilder,\n SimpleConfigSchema,\n defineConfigSchema,\n} from './config-schema-builder.js'\n\n// State management (PHASE0-WS3)\nexport {\n type StateStore,\n type StateListener,\n type StateSnapshot,\n type Selector,\n type Transition,\n type StateMachineConfig,\n type StateMachine,\n SimpleStateStore,\n SimpleStateMachine,\n createStateStore,\n computed,\n subscribeToSlice,\n createStateMachine,\n} from './state.js'\n\n// Block ecosystem types and layout schema\n// Block schemas, definitions, rule engine, and React components are in @pwfabric/runtime/blocks (retired standalone package)\nexport {\n // Types\n type BlockCategory,\n type BlockDefinition,\n type Block,\n type ValidationError as BlockValidationError,\n type ValidationResult as BlockValidationResult,\n type CompositionRuleType,\n type CompositionRule,\n MAX_NESTING_DEPTH,\n BLOCK_CATEGORIES,\n // Layout schema\n type BreakpointName,\n type BreakpointDefinition,\n type ResponsiveValue,\n type BlockLayout,\n type PreviewViewport,\n BREAKPOINTS,\n BREAKPOINT_ORDER,\n DEFAULT_BLOCK_LAYOUT,\n VIEWPORT_PRESETS,\n responsiveNumberSchema,\n responsiveBooleanSchema,\n blockLayoutSchema,\n resolveResponsiveValue,\n resolveSpanAtBreakpoint,\n getColumnsAtBreakpoint,\n getBreakpointForWidth,\n // Block host imports — the one list the bundler, the host import maps and the\n // shim files all derive from.\n BLOCK_HOST_IMPORTS,\n blockBundleExternals,\n blockImportMap,\n blockShimFiles,\n blockHostGlobals,\n unseededHostGlobals,\n specifiersForShim,\n isExportableName,\n shimSource,\n type HostImport,\n type HostImportKind,\n type HostSeeding,\n} from './blocks/index.js'\n","/**\n * Custom error classes for PWFabric\n */\n\n/**\n * Base error class for all PWFabric errors\n */\nexport class PWFabricError extends Error {\n public readonly code: string\n public readonly timestamp: Date\n\n constructor(message: string, code: string, options?: ErrorOptions) {\n super(message, options)\n this.name = 'PWFabricError'\n this.code = code\n this.timestamp = new Date()\n }\n}\n\n/**\n * Validation error\n */\nexport class ValidationError extends PWFabricError {\n public readonly field: string | undefined\n\n constructor(message: string, field?: string, options?: ErrorOptions) {\n super(message, 'VALIDATION_ERROR', options)\n this.name = 'ValidationError'\n this.field = field\n }\n}\n\n/**\n * Not found error\n */\nexport class NotFoundError extends PWFabricError {\n public readonly resource: string\n\n constructor(resource: string, options?: ErrorOptions) {\n super(`${resource} not found`, 'NOT_FOUND', options)\n this.name = 'NotFoundError'\n this.resource = resource\n }\n}\n\n/**\n * Unauthorized error\n */\nexport class UnauthorizedError extends PWFabricError {\n constructor(message = 'Unauthorized', options?: ErrorOptions) {\n super(message, 'UNAUTHORIZED', options)\n this.name = 'UnauthorizedError'\n }\n}\n\n/**\n * Forbidden error\n */\nexport class ForbiddenError extends PWFabricError {\n constructor(message = 'Forbidden', options?: ErrorOptions) {\n super(message, 'FORBIDDEN', options)\n this.name = 'ForbiddenError'\n }\n}\n","/**\n * Logger utility for PWFabric\n */\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\nexport interface LogEntry {\n level: LogLevel\n message: string\n timestamp: Date\n context: Record<string, unknown> | undefined\n}\n\n/**\n * Simple logger implementation\n */\nexport class Logger {\n private readonly name: string\n private readonly minLevel: LogLevel\n\n private static readonly levels: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n }\n\n constructor(name: string, minLevel: LogLevel = 'info') {\n this.name = name\n this.minLevel = minLevel\n }\n\n private shouldLog(level: LogLevel): boolean {\n return Logger.levels[level] >= Logger.levels[this.minLevel]\n }\n\n private log(level: LogLevel, message: string, context?: Record<string, unknown>): void {\n if (!this.shouldLog(level)) return\n\n const entry: LogEntry = {\n level,\n message,\n timestamp: new Date(),\n context,\n }\n\n const output = `[${entry.timestamp.toISOString()}] [${level.toUpperCase()}] [${this.name}] ${message}`\n\n if (level === 'error') {\n console.error(output, context ?? '')\n } else if (level === 'warn') {\n console.warn(output, context ?? '')\n } else {\n // Using console.info for debug and info to avoid eslint no-console warning\n // In production, this would be replaced with a proper logging library\n process.stdout.write(output + (context ? ` ${JSON.stringify(context)}` : '') + '\\n')\n }\n }\n\n debug(message: string, context?: Record<string, unknown>): void {\n this.log('debug', message, context)\n }\n\n info(message: string, context?: Record<string, unknown>): void {\n this.log('info', message, context)\n }\n\n warn(message: string, context?: Record<string, unknown>): void {\n this.log('warn', message, context)\n }\n\n error(message: string, context?: Record<string, unknown>): void {\n this.log('error', message, context)\n }\n\n child(name: string): Logger {\n return new Logger(`${this.name}:${name}`, this.minLevel)\n }\n}\n\n/**\n * Create a logger instance\n */\nexport function createLogger(name: string, level?: LogLevel): Logger {\n return new Logger(name, level)\n}\n","/**\n * Error Codes\n *\n * Standardized error codes for PWFabric platform\n *\n * @module @pwfabric/core/errors/ErrorCode\n */\n\n/**\n * Error code categories\n */\nexport const ErrorCode = {\n // Validation errors (1xxx)\n VALIDATION_FAILED: 'VALIDATION_FAILED',\n INVALID_INPUT: 'INVALID_INPUT',\n MISSING_REQUIRED: 'MISSING_REQUIRED',\n INVALID_FORMAT: 'INVALID_FORMAT',\n\n // Network errors (2xxx)\n NETWORK_ERROR: 'NETWORK_ERROR',\n TIMEOUT: 'TIMEOUT',\n CONNECTION_FAILED: 'CONNECTION_FAILED',\n REQUEST_FAILED: 'REQUEST_FAILED',\n\n // Authentication errors (3xxx)\n UNAUTHORIZED: 'UNAUTHORIZED',\n FORBIDDEN: 'FORBIDDEN',\n TOKEN_EXPIRED: 'TOKEN_EXPIRED',\n INVALID_CREDENTIALS: 'INVALID_CREDENTIALS',\n\n // Resource errors (4xxx)\n NOT_FOUND: 'NOT_FOUND',\n ALREADY_EXISTS: 'ALREADY_EXISTS',\n CONFLICT: 'CONFLICT',\n GONE: 'GONE',\n\n // Runtime errors (5xxx)\n RUNTIME_ERROR: 'RUNTIME_ERROR',\n INTERNAL_ERROR: 'INTERNAL_ERROR',\n SERVICE_UNAVAILABLE: 'SERVICE_UNAVAILABLE',\n NOT_IMPLEMENTED: 'NOT_IMPLEMENTED',\n\n // Editor errors (6xxx)\n EDITOR_ERROR: 'EDITOR_ERROR',\n BLOCK_NOT_FOUND: 'BLOCK_NOT_FOUND',\n INVALID_OPERATION: 'INVALID_OPERATION',\n RENDER_ERROR: 'RENDER_ERROR',\n} as const\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]\n\n/**\n * Get HTTP status code for an error code\n */\nexport function getHttpStatus(code: ErrorCode): number {\n switch (code) {\n case ErrorCode.VALIDATION_FAILED:\n case ErrorCode.INVALID_INPUT:\n case ErrorCode.MISSING_REQUIRED:\n case ErrorCode.INVALID_FORMAT:\n return 400\n\n case ErrorCode.UNAUTHORIZED:\n case ErrorCode.TOKEN_EXPIRED:\n case ErrorCode.INVALID_CREDENTIALS:\n return 401\n\n case ErrorCode.FORBIDDEN:\n return 403\n\n case ErrorCode.NOT_FOUND:\n case ErrorCode.BLOCK_NOT_FOUND:\n case ErrorCode.GONE:\n return 404\n\n case ErrorCode.CONFLICT:\n case ErrorCode.ALREADY_EXISTS:\n return 409\n\n case ErrorCode.TIMEOUT:\n return 408\n\n case ErrorCode.SERVICE_UNAVAILABLE:\n return 503\n\n case ErrorCode.NOT_IMPLEMENTED:\n return 501\n\n default:\n return 500\n }\n}\n\n/**\n * Check if error code is retryable\n */\nexport function isRetryable(code: ErrorCode): boolean {\n const retryableCodes: ErrorCode[] = [\n ErrorCode.NETWORK_ERROR,\n ErrorCode.TIMEOUT,\n ErrorCode.CONNECTION_FAILED,\n ErrorCode.SERVICE_UNAVAILABLE,\n ]\n return retryableCodes.includes(code)\n}\n","/**\n * Application Error Classes\n *\n * Custom error class hierarchy with code, message, context, and cause\n *\n * @module @pwfabric/core/errors/AppError\n */\n\nimport { type ErrorCode, getHttpStatus, isRetryable } from './ErrorCode.js'\n\n/**\n * Error context for additional debugging information\n */\nexport type ErrorContext = Readonly<Record<string, unknown>>\n\n/**\n * Serialized error format for API responses\n */\nexport interface SerializedError {\n readonly code: ErrorCode\n readonly message: string\n readonly timestamp: string\n readonly traceId?: string\n readonly context?: ErrorContext\n}\n\n/**\n * Base application error class\n *\n * All application errors should extend this class\n */\nexport class AppError extends Error {\n public readonly code: ErrorCode\n public readonly timestamp: Date\n public readonly context: ErrorContext | undefined\n public readonly isRetryable: boolean\n public readonly httpStatus: number\n\n constructor(\n code: ErrorCode,\n message: string,\n options?: {\n cause?: Error\n context?: ErrorContext\n }\n ) {\n super(message, { cause: options?.cause })\n this.name = 'AppError'\n this.code = code\n this.timestamp = new Date()\n this.context = options?.context\n this.isRetryable = isRetryable(code)\n this.httpStatus = getHttpStatus(code)\n }\n\n /**\n * Serialize error for API response\n */\n toJSON(traceId?: string): SerializedError {\n return {\n code: this.code,\n message: this.message,\n timestamp: this.timestamp.toISOString(),\n ...(traceId && { traceId }),\n ...(this.context && { context: this.context }),\n }\n }\n\n /**\n * Create error from unknown value\n */\n static from(error: unknown, code: ErrorCode = 'RUNTIME_ERROR'): AppError {\n if (error instanceof AppError) {\n return error\n }\n\n if (error instanceof Error) {\n return new AppError(code, error.message, { cause: error })\n }\n\n return new AppError(code, String(error))\n }\n}\n\n/**\n * Validation error for input validation failures\n */\nexport class ValidationAppError extends AppError {\n public readonly field: string | undefined\n\n constructor(\n message: string,\n options?: {\n field?: string\n cause?: Error\n context?: ErrorContext\n }\n ) {\n const baseOptions: { cause?: Error; context?: ErrorContext } = {}\n if (options?.cause) {\n baseOptions.cause = options.cause\n }\n if (options?.context || options?.field) {\n baseOptions.context = { ...options?.context, field: options?.field }\n }\n super('VALIDATION_FAILED', message, baseOptions)\n this.name = 'ValidationAppError'\n this.field = options?.field\n }\n}\n\n/**\n * Network error for connectivity issues\n */\nexport class NetworkAppError extends AppError {\n public readonly url: string | undefined\n public readonly statusCode: number | undefined\n\n constructor(\n message: string,\n options?: {\n url?: string\n statusCode?: number\n cause?: Error\n context?: ErrorContext\n }\n ) {\n const baseOptions: { cause?: Error; context?: ErrorContext } = {}\n if (options?.cause) {\n baseOptions.cause = options.cause\n }\n if (options?.context || options?.url || options?.statusCode) {\n baseOptions.context = {\n ...options?.context,\n url: options?.url,\n statusCode: options?.statusCode,\n }\n }\n super('NETWORK_ERROR', message, baseOptions)\n this.name = 'NetworkAppError'\n this.url = options?.url\n this.statusCode = options?.statusCode\n }\n}\n\n/**\n * Editor error for studio/editor operations\n */\nexport class EditorAppError extends AppError {\n public readonly blockId: string | undefined\n public readonly operation: string | undefined\n\n constructor(\n message: string,\n options?: {\n code?: ErrorCode\n blockId?: string\n operation?: string\n cause?: Error\n context?: ErrorContext\n }\n ) {\n const baseOptions: { cause?: Error; context?: ErrorContext } = {}\n if (options?.cause) {\n baseOptions.cause = options.cause\n }\n if (options?.context || options?.blockId || options?.operation) {\n baseOptions.context = {\n ...options?.context,\n blockId: options?.blockId,\n operation: options?.operation,\n }\n }\n super(options?.code ?? 'EDITOR_ERROR', message, baseOptions)\n this.name = 'EditorAppError'\n this.blockId = options?.blockId\n this.operation = options?.operation\n }\n}\n","/**\n * Performance Metrics Types\n *\n * Type definitions for performance monitoring\n *\n * @module @pwfabric/core/monitoring/metrics\n */\n\n/**\n * Web Vitals metric names\n */\nexport type WebVitalName = 'LCP' | 'FID' | 'CLS' | 'TTFB' | 'INP' | 'FCP'\n\n/**\n * Metric rating\n */\nexport type MetricRating = 'good' | 'needs-improvement' | 'poor'\n\n/**\n * Base metric interface\n */\nexport interface Metric {\n readonly name: string\n readonly value: number\n readonly timestamp: number\n}\n\n/**\n * Web Vital metric\n */\nexport interface WebVitalMetric extends Metric {\n readonly name: WebVitalName\n readonly rating: MetricRating\n readonly delta: number\n readonly entries: readonly PerformanceEntry[]\n}\n\n/**\n * Custom timing metric\n */\nexport interface TimingMetric extends Metric {\n readonly name: string\n readonly duration: number\n readonly startTime: number\n readonly endTime: number\n readonly metadata?: Record<string, unknown> | undefined\n}\n\n/**\n * Component render metric\n */\nexport interface RenderMetric extends Metric {\n readonly name: string\n readonly componentName: string\n readonly renderCount: number\n readonly duration: number\n}\n\n/**\n * Performance budget thresholds\n */\nexport interface PerformanceBudget {\n readonly LCP: number\n readonly FID: number\n readonly CLS: number\n readonly TTFB: number\n readonly INP: number\n}\n\n/**\n * Default performance budgets based on Core Web Vitals thresholds\n */\nexport const DEFAULT_BUDGET: PerformanceBudget = {\n LCP: 2500, // 2.5s\n FID: 100, // 100ms\n CLS: 0.1, // 0.1\n TTFB: 800, // 800ms\n INP: 200, // 200ms\n}\n\n/**\n * Metric collection state\n */\nexport interface MetricsState {\n readonly webVitals: Record<WebVitalName, WebVitalMetric | null>\n readonly timings: readonly TimingMetric[]\n readonly renders: readonly RenderMetric[]\n readonly budget: PerformanceBudget\n}\n\n/**\n * Create initial metrics state\n */\nexport function createMetricsState(budget: Partial<PerformanceBudget> = {}): MetricsState {\n return {\n webVitals: {\n LCP: null,\n FID: null,\n CLS: null,\n TTFB: null,\n INP: null,\n FCP: null,\n },\n timings: [],\n renders: [],\n budget: { ...DEFAULT_BUDGET, ...budget },\n }\n}\n\n/**\n * Get rating for a Web Vital metric\n */\nexport function getRating(name: WebVitalName, value: number): MetricRating {\n const thresholds: Record<WebVitalName, [number, number]> = {\n LCP: [2500, 4000],\n FID: [100, 300],\n CLS: [0.1, 0.25],\n TTFB: [800, 1800],\n INP: [200, 500],\n FCP: [1800, 3000],\n }\n\n const [good, poor] = thresholds[name]\n if (value <= good) return 'good'\n if (value <= poor) return 'needs-improvement'\n return 'poor'\n}\n","/**\n * Web Vitals Collection\n *\n * Collection of Core Web Vitals using Performance API\n *\n * @module @pwfabric/core/monitoring/web-vitals\n */\n\nimport { type WebVitalName, type WebVitalMetric, getRating } from './metrics.js'\n\n/**\n * Callback for when a Web Vital is collected\n */\nexport type WebVitalCallback = (metric: WebVitalMetric) => void\n\n/**\n * Create a Web Vital metric from performance entries\n */\nfunction createWebVitalMetric(\n name: WebVitalName,\n value: number,\n delta: number,\n entries: PerformanceEntry[]\n): WebVitalMetric {\n return {\n name,\n value,\n delta,\n rating: getRating(name, value),\n timestamp: Date.now(),\n entries,\n }\n}\n\n/**\n * Observe Largest Contentful Paint (LCP)\n */\nexport function observeLCP(callback: WebVitalCallback): (() => void) | undefined {\n if (typeof PerformanceObserver === 'undefined') return undefined\n\n let lastValue = 0\n const entries: PerformanceEntry[] = []\n\n const observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n const lcpEntry = entry as PerformanceEntry & { startTime: number }\n entries.push(entry)\n const value = lcpEntry.startTime\n const delta = value - lastValue\n lastValue = value\n callback(createWebVitalMetric('LCP', value, delta, [...entries]))\n }\n })\n\n try {\n observer.observe({ type: 'largest-contentful-paint', buffered: true })\n return () => observer.disconnect()\n } catch {\n return undefined\n }\n}\n\n/**\n * Observe First Input Delay (FID)\n */\nexport function observeFID(callback: WebVitalCallback): (() => void) | undefined {\n if (typeof PerformanceObserver === 'undefined') return undefined\n\n const entries: PerformanceEntry[] = []\n\n const observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n const fidEntry = entry as PerformanceEventTiming\n entries.push(entry)\n const value = fidEntry.processingStart - fidEntry.startTime\n callback(createWebVitalMetric('FID', value, value, [...entries]))\n }\n })\n\n try {\n observer.observe({ type: 'first-input', buffered: true })\n return () => observer.disconnect()\n } catch {\n return undefined\n }\n}\n\n/**\n * Observe Cumulative Layout Shift (CLS)\n */\nexport function observeCLS(callback: WebVitalCallback): (() => void) | undefined {\n if (typeof PerformanceObserver === 'undefined') return undefined\n\n let clsValue = 0\n const entries: PerformanceEntry[] = []\n\n const observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n const layoutShift = entry as PerformanceEntry & {\n hadRecentInput: boolean\n value: number\n }\n if (!layoutShift.hadRecentInput) {\n const delta = layoutShift.value\n clsValue += delta\n entries.push(entry)\n callback(createWebVitalMetric('CLS', clsValue, delta, [...entries]))\n }\n }\n })\n\n try {\n observer.observe({ type: 'layout-shift', buffered: true })\n return () => observer.disconnect()\n } catch {\n return undefined\n }\n}\n\n/**\n * Observe Time to First Byte (TTFB)\n */\nexport function observeTTFB(callback: WebVitalCallback): void {\n if (typeof window === 'undefined' || typeof performance === 'undefined') return\n\n const navigationEntry = performance.getEntriesByType('navigation')[0] as\n | PerformanceNavigationTiming\n | undefined\n\n if (navigationEntry) {\n const value = navigationEntry.responseStart - navigationEntry.requestStart\n callback(createWebVitalMetric('TTFB', value, value, [navigationEntry]))\n }\n}\n\n/**\n * Observe Interaction to Next Paint (INP)\n */\nexport function observeINP(callback: WebVitalCallback): (() => void) | undefined {\n if (typeof PerformanceObserver === 'undefined') return undefined\n\n let maxINP = 0\n const entries: PerformanceEntry[] = []\n\n const observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n const eventEntry = entry as PerformanceEventTiming\n const duration = eventEntry.duration\n if (duration > maxINP) {\n maxINP = duration\n entries.push(entry)\n callback(createWebVitalMetric('INP', duration, duration, [...entries]))\n }\n }\n })\n\n try {\n observer.observe({ type: 'event', buffered: true })\n return () => observer.disconnect()\n } catch {\n return undefined\n }\n}\n\n/**\n * Observe First Contentful Paint (FCP)\n */\nexport function observeFCP(callback: WebVitalCallback): (() => void) | undefined {\n if (typeof PerformanceObserver === 'undefined') return undefined\n\n const entries: PerformanceEntry[] = []\n\n const observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n if (entry.name === 'first-contentful-paint') {\n entries.push(entry)\n const value = entry.startTime\n callback(createWebVitalMetric('FCP', value, value, [...entries]))\n }\n }\n })\n\n try {\n observer.observe({ type: 'paint', buffered: true })\n return () => observer.disconnect()\n } catch {\n return undefined\n }\n}\n\n/**\n * Observe all Web Vitals\n */\nexport function observeAllWebVitals(callback: WebVitalCallback): () => void {\n const cleanups: ((() => void) | undefined)[] = []\n\n cleanups.push(observeLCP(callback))\n cleanups.push(observeFID(callback))\n cleanups.push(observeCLS(callback))\n cleanups.push(observeINP(callback))\n cleanups.push(observeFCP(callback))\n\n // TTFB is synchronous\n observeTTFB(callback)\n\n return () => {\n for (const cleanup of cleanups) {\n cleanup?.()\n }\n }\n}\n","/**\n * Logger Interface\n *\n * Structured logging interface for observability\n *\n * @module @pwfabric/core/observability/logger\n */\n\n/**\n * Log levels\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\n/**\n * Log context\n */\nexport interface LogContext {\n readonly traceId?: string\n readonly [key: string]: unknown\n}\n\n/**\n * Structured log entry\n */\nexport interface LogEntry {\n readonly level: LogLevel\n readonly message: string\n readonly timestamp: string\n readonly name: string\n readonly context?: LogContext\n}\n\n/**\n * Logger interface\n */\nexport interface ILogger {\n debug(message: string, context?: LogContext): void\n info(message: string, context?: LogContext): void\n warn(message: string, context?: LogContext): void\n error(message: string, context?: LogContext): void\n child(name: string): ILogger\n}\n\n/**\n * Log level priority\n */\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n}\n\n/**\n * Environment detection\n */\nfunction isProduction(): boolean {\n if (typeof process !== 'undefined' && process.env) {\n return process.env.NODE_ENV === 'production'\n }\n return false\n}\n\n/**\n * Console logger implementation\n *\n * In development: human-readable format\n * In production: structured JSON format\n */\nexport class ConsoleLogger implements ILogger {\n private readonly name: string\n private readonly minLevel: LogLevel\n private readonly production: boolean\n\n constructor(name: string, minLevel: LogLevel = 'info') {\n this.name = name\n this.minLevel = minLevel\n this.production = isProduction()\n }\n\n private shouldLog(level: LogLevel): boolean {\n return LOG_LEVELS[level] >= LOG_LEVELS[this.minLevel]\n }\n\n private formatEntry(level: LogLevel, message: string, context?: LogContext): LogEntry {\n return {\n level,\n message,\n timestamp: new Date().toISOString(),\n name: this.name,\n ...(context && { context }),\n }\n }\n\n private log(level: LogLevel, message: string, context?: LogContext): void {\n if (!this.shouldLog(level)) return\n\n const entry = this.formatEntry(level, message, context)\n\n if (this.production) {\n // Production: structured JSON\n const output = JSON.stringify(entry)\n if (level === 'error') {\n console.error(output)\n } else if (level === 'warn') {\n console.warn(output)\n } else {\n console.log(output)\n }\n } else {\n // Development: human-readable\n const prefix = `[${entry.timestamp}] [${level.toUpperCase()}] [${this.name}]`\n const output = `${prefix} ${message}`\n\n if (level === 'error') {\n console.error(output, context ?? '')\n } else if (level === 'warn') {\n console.warn(output, context ?? '')\n } else {\n console.log(output, context ?? '')\n }\n }\n }\n\n debug(message: string, context?: LogContext): void {\n this.log('debug', message, context)\n }\n\n info(message: string, context?: LogContext): void {\n this.log('info', message, context)\n }\n\n warn(message: string, context?: LogContext): void {\n this.log('warn', message, context)\n }\n\n error(message: string, context?: LogContext): void {\n this.log('error', message, context)\n }\n\n child(name: string): ILogger {\n return new ConsoleLogger(`${this.name}:${name}`, this.minLevel)\n }\n}\n\n/**\n * Create a logger instance\n */\nexport function createObservabilityLogger(name: string, minLevel?: LogLevel): ILogger {\n return new ConsoleLogger(name, minLevel)\n}\n","/**\n * Trace Context\n *\n * Request tracing for observability\n *\n * @module @pwfabric/core/observability/tracer\n */\n\n/**\n * Trace context\n */\nexport interface TraceContext {\n readonly traceId: string\n readonly spanId: string\n readonly parentSpanId?: string\n readonly startTime: number\n}\n\n/**\n * Span represents a unit of work\n */\nexport interface Span {\n readonly context: TraceContext\n readonly name: string\n readonly startTime: number\n end(): SpanResult\n}\n\n/**\n * Completed span result\n */\nexport interface SpanResult {\n readonly context: TraceContext\n readonly name: string\n readonly startTime: number\n readonly endTime: number\n readonly duration: number\n}\n\n/**\n * Generate a random trace/span ID\n */\nfunction generateId(): string {\n const bytes = new Uint8Array(16)\n if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n crypto.getRandomValues(bytes)\n } else {\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Math.floor(Math.random() * 256)\n }\n }\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/**\n * Create a new trace context\n */\nexport function createTraceContext(parentSpanId?: string): TraceContext {\n const context: TraceContext = {\n traceId: generateId(),\n spanId: generateId().slice(0, 16),\n startTime: Date.now(),\n }\n if (parentSpanId !== undefined) {\n return { ...context, parentSpanId }\n }\n return context\n}\n\n/**\n * Create a child span from existing context\n */\nexport function createChildContext(parent: TraceContext): TraceContext {\n return {\n traceId: parent.traceId,\n spanId: generateId().slice(0, 16),\n parentSpanId: parent.spanId,\n startTime: Date.now(),\n }\n}\n\n/**\n * Create a span for tracing\n */\nexport function createSpan(name: string, parentContext?: TraceContext): Span {\n const context = parentContext ? createChildContext(parentContext) : createTraceContext()\n const startTime = performance.now()\n\n return {\n context,\n name,\n startTime,\n end(): SpanResult {\n const endTime = performance.now()\n return {\n context,\n name,\n startTime,\n endTime,\n duration: endTime - startTime,\n }\n },\n }\n}\n\n/**\n * Extract trace ID from headers\n */\nexport function extractTraceId(\n headers: Headers | Record<string, string | undefined>\n): string | undefined {\n if (headers instanceof Headers) {\n return headers.get('x-trace-id') ?? undefined\n }\n return headers['x-trace-id']\n}\n\n/**\n * Inject trace ID into headers\n */\nexport function injectTraceId(headers: Headers | Record<string, string>, traceId: string): void {\n if (headers instanceof Headers) {\n headers.set('x-trace-id', traceId)\n } else {\n headers['x-trace-id'] = traceId\n }\n}\n","/**\n * Utility functions for PWFabric\n */\n\nimport type { Result } from '@pwfabric/contracts'\n\n/**\n * Create a successful result\n */\nexport function ok<T>(data: T): Result<T, never> {\n return { success: true, data }\n}\n\n/**\n * Create a failed result\n */\nexport function err<E>(error: E): Result<never, E> {\n return { success: false, error }\n}\n\n/**\n * Sleep for a specified duration\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Retry an async operation with exponential backoff\n */\nexport async function retry<T>(\n fn: () => Promise<T>,\n options: {\n maxAttempts?: number\n initialDelay?: number\n maxDelay?: number\n backoffFactor?: number\n } = {}\n): Promise<T> {\n const { maxAttempts = 3, initialDelay = 1000, maxDelay = 30000, backoffFactor = 2 } = options\n\n let lastError: Error | undefined\n let delay = initialDelay\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await fn()\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error))\n\n if (attempt === maxAttempts) {\n throw lastError\n }\n\n await sleep(delay)\n delay = Math.min(delay * backoffFactor, maxDelay)\n }\n }\n\n throw lastError\n}\n\n/**\n * Generate a random ID (for development purposes)\n * In production, use crypto.randomUUID()\n */\nexport function generateId(): string {\n return crypto.randomUUID()\n}\n","/**\n * Contract Builder\n *\n * PHASE0-WS3: Fluent API for building contracts\n *\n * @module @pwfabric/core/contract-builder\n */\n\nimport type {\n Contract,\n ContractId,\n ContractMetadata,\n ContractState,\n ContractError,\n Schema,\n ValidationResult,\n SerializedContract,\n SemanticVersion,\n} from '@pwfabric/contracts'\nimport {\n contractId,\n parseVersion,\n INITIAL_VERSION,\n ok,\n err,\n validationError,\n} from '@pwfabric/contracts'\n\n// ============================================================\n// SIMPLE SCHEMA IMPLEMENTATION\n// ============================================================\n\n/**\n * Minimal schema implementation backed by a validator function.\n */\nclass SimpleSchema<T> implements Schema<T> {\n readonly definition\n private readonly validator: (data: unknown) => ValidationResult<T>\n\n constructor(\n definition: Schema<T>['definition'],\n validator: (data: unknown) => ValidationResult<T>\n ) {\n this.definition = definition\n this.validator = validator\n }\n\n validate(data: unknown): ValidationResult<T> {\n return this.validator(data)\n }\n\n parse(data: unknown): T {\n const result = this.validate(data)\n if (result.success) {\n return result.data\n }\n throw new Error(`Validation failed: ${JSON.stringify(result.error)}`)\n }\n\n safeParse(data: unknown): ValidationResult<T> {\n return this.validate(data)\n }\n\n toJsonSchema(): Record<string, unknown> {\n return { type: 'object' }\n }\n}\n\n/**\n * Create a schema that accepts any value\n */\nexport function anySchema<T = unknown>(): Schema<T> {\n return new SimpleSchema<T>({ type: 'unknown' }, (data) => ok(data as T))\n}\n\n/**\n * Create a schema that validates an object\n */\nexport function objectSchema<T extends Record<string, unknown>>(): Schema<T> {\n return new SimpleSchema<T>({ type: 'object', properties: {}, required: [] }, (data) => {\n if (typeof data !== 'object' || data === null) {\n return err([validationError([], 'Expected object', 'type_error')])\n }\n return ok(data as T)\n })\n}\n\n// ============================================================\n// CONTRACT IMPLEMENTATION\n// ============================================================\n\n/**\n * Simple contract implementation\n */\nclass SimpleContract<TInput, TOutput, TError = ContractError> implements Contract<\n TInput,\n TOutput,\n TError\n> {\n readonly id: ContractId\n readonly version: SemanticVersion\n readonly metadata: ContractMetadata\n readonly input: Schema<TInput>\n readonly output: Schema<TOutput>\n readonly errors: readonly Schema<TError>[]\n\n constructor(config: {\n id: ContractId\n version: SemanticVersion\n metadata: ContractMetadata\n input: Schema<TInput>\n output: Schema<TOutput>\n errors?: readonly Schema<TError>[]\n }) {\n this.id = config.id\n this.version = config.version\n this.metadata = config.metadata\n this.input = config.input\n this.output = config.output\n this.errors = config.errors ?? []\n }\n\n validateInput(data: unknown): ValidationResult<TInput> {\n return this.input.validate(data)\n }\n\n validateOutput(data: unknown): ValidationResult<TOutput> {\n return this.output.validate(data)\n }\n\n validateError(data: unknown): ValidationResult<TError> {\n for (const schema of this.errors) {\n const result = schema.validate(data)\n if (result.success) {\n return result\n }\n }\n return err([validationError([], 'Unknown error type', 'unknown_error')])\n }\n\n serialize(): SerializedContract {\n return {\n id: this.id,\n version: `${this.version.major}.${this.version.minor}.${this.version.patch}`,\n metadata: this.metadata,\n input: {\n version: '1.0.0',\n definition: this.input.definition,\n jsonSchema: this.input.toJsonSchema(),\n },\n output: {\n version: '1.0.0',\n definition: this.output.definition,\n jsonSchema: this.output.toJsonSchema(),\n },\n errors: this.errors.map((e) => ({\n version: '1.0.0',\n definition: e.definition,\n jsonSchema: e.toJsonSchema(),\n })),\n }\n }\n}\n\n// ============================================================\n// CONTRACT BUILDER\n// ============================================================\n\n/**\n * Contract builder for fluent API\n */\nexport class ContractBuilder<TInput = unknown, TOutput = unknown> {\n private _id = ''\n private _version = '0.1.0'\n private _name = ''\n private _description?: string\n private _state: ContractState = 'draft'\n private _tags?: readonly string[]\n private _inputSchema: Schema<TInput> = anySchema<TInput>()\n private _outputSchema: Schema<TOutput> = anySchema<TOutput>()\n\n /**\n * Set the contract ID\n */\n id(id: string): this {\n this._id = id\n return this\n }\n\n /**\n * Set the contract version\n */\n version(version: string): this {\n this._version = version\n return this\n }\n\n /**\n * Set the contract name\n */\n name(name: string): this {\n this._name = name\n return this\n }\n\n /**\n * Set the contract description\n */\n description(description: string): this {\n this._description = description\n return this\n }\n\n /**\n * Set the contract state\n */\n state(state: ContractState): this {\n this._state = state\n return this\n }\n\n /**\n * Set the contract tags\n */\n tags(tags: readonly string[]): this {\n this._tags = tags\n return this\n }\n\n /**\n * Set the input schema\n */\n input<T>(schema: Schema<T>): ContractBuilder<T, TOutput> {\n const builder = this as unknown as ContractBuilder<T, TOutput>\n builder._inputSchema = schema as unknown as Schema<T>\n return builder\n }\n\n /**\n * Set the output schema\n */\n output<T>(schema: Schema<T>): ContractBuilder<TInput, T> {\n const builder = this as unknown as ContractBuilder<TInput, T>\n builder._outputSchema = schema as unknown as Schema<T>\n return builder\n }\n\n /**\n * Build the contract\n */\n build(): Contract<TInput, TOutput> {\n if (!this._id) {\n throw new Error('Contract ID is required')\n }\n if (!this._name) {\n throw new Error('Contract name is required')\n }\n\n const metadata: ContractMetadata = {\n name: this._name,\n state: this._state,\n }\n if (this._description !== undefined) {\n ;(metadata as { description?: string }).description = this._description\n }\n if (this._tags !== undefined) {\n ;(metadata as { tags?: readonly string[] }).tags = this._tags\n }\n\n return new SimpleContract<TInput, TOutput>({\n id: contractId(this._id),\n version: parseVersion(this._version) ?? INITIAL_VERSION,\n metadata,\n input: this._inputSchema,\n output: this._outputSchema,\n })\n }\n}\n\n/**\n * Create a new contract builder\n */\nexport function defineContract<TInput = unknown, TOutput = unknown>(): ContractBuilder<\n TInput,\n TOutput\n> {\n return new ContractBuilder<TInput, TOutput>()\n}\n","/**\n * Passthrough Contract\n *\n * A canonical declaration-only contract used by platform capabilities\n * (persistence, navigation, interaction, entities) that accept any input\n * and produce any output with no schema validation.\n *\n * Moved from `@pwfabric/runtime/capability/platform-capabilities.ts` to\n * `@pwfabric/core/contracts/passthrough` so pwpack-authored capabilities\n * can import it without a runtime dependency.\n *\n * @module @pwfabric/core/contracts/passthrough\n */\n\nimport { defineContract, anySchema } from '../contract-builder.js'\n\nexport const passthroughContract = defineContract()\n .id('platform/passthrough')\n .name('Platform Passthrough')\n .description('Passthrough contract for platform capability declarations')\n .state('stable')\n .input(anySchema())\n .output(anySchema())\n .build()\n","/**\n * Delegated OAuth scope lists — the one reader\n *\n * WHY A STRING IS REFUSED. A scope list stored as a string and split on\n * `/[\\s,]+/` turns the JSON TEXT `[\"Sites.Read.All\",\"User.Read\"]` into\n * `[\"Sites.Read.All\"` and `\"User.Read\"]` — things shaped like scopes that an\n * identity provider refuses (Microsoft Entra: `AADSTS650053 ... asked for\n * scope '[\"Sites.Read.All\"'`).\n *\n * A scope list is a LIST; a string is not a list awaiting a parse, it is a\n * malformed value. Separate readers would each get a chance to disagree,\n * which is why this is one module the consumers import rather than a rule\n * each of them remembers.\n *\n * WHY A READER FORGIVES AND A WRITER DOES NOT. The write boundary rejects\n * outright (HTTP 400 — see the API's scope-shape guard): nothing malformed\n * should enter. A reader, though, runs at render time against rows that are\n * already stored, and a canvas that throws over one bad row is worse than one\n * that shows the row as broken. So it keeps what is usable, sets aside what is\n * not, and RETURNS the rejects so a surface can display them. The original bug\n * survived precisely because nothing ever surfaced them.\n *\n * @module @pwfabric/core/oauth-scopes\n */\n\n/**\n * Characters that cannot appear inside a delegated scope.\n *\n * Deliberately a REJECT-list rather than an allow-list: real scopes come bare\n * (`Sites.Read.All`, `offline_access`), URI-qualified\n * (`https://graph.microsoft.com/Mail.Read`) and app-id-qualified\n * (`api://<guid>/access_as_user`), and an allow-list tight enough to be\n * useful would refuse valid scopes from a provider we have not met yet. What\n * IS refused is what a scope can never contain: whitespace (the OAuth\n * delimiter itself), and the quotes/brackets/commas that betray a stringified\n * array. `[\"Sites.Read.All\"` fails on three counts.\n */\nconst FORBIDDEN_IN_SCOPE = /[\\s\"'[\\]{},\\\\]/\n\n/** Whether a single token is shaped like a delegated OAuth scope. */\nexport function isScopeToken(token: unknown): token is string {\n return typeof token === 'string' && token.length > 0 && !FORBIDDEN_IN_SCOPE.test(token)\n}\n\n/** What a stored scope value turned out to be. */\nexport interface ScopeListReading {\n /** The usable scopes, de-duplicated, first-seen order preserved. */\n readonly scopes: readonly string[]\n /**\n * Entries that are not scopes, as they were stored (stringified). Carried\n * back so a surface can show what it refused instead of silently dropping\n * it — silence is what let the original fault reach Microsoft.\n */\n readonly rejected: readonly string[]\n /**\n * True when the VALUE ITSELF was not a list (most often a JSON string).\n * Distinct from \"a list containing bad entries\": one is a shape error at\n * the field, the other is a content error inside it.\n */\n readonly malformed: boolean\n}\n\nconst EMPTY: ScopeListReading = { scopes: [], rejected: [], malformed: false }\n\n/**\n * Read a stored scope value. Never throws, for any input.\n *\n * `undefined`/`null`/`[]` are an empty list, not a fault — an atom that needs\n * no delegated permission is a normal atom.\n */\nexport function readScopeList(value: unknown): ScopeListReading {\n if (value === undefined || value === null) return EMPTY\n\n if (!Array.isArray(value)) {\n // A string is NOT split — splitting is what manufactures invalid tokens.\n return { scopes: [], rejected: [safeShow(value)], malformed: true }\n }\n\n const scopes: string[] = []\n const rejected: string[] = []\n const seen = new Set<string>()\n\n for (const entry of value) {\n if (isScopeToken(entry)) {\n if (!seen.has(entry)) {\n seen.add(entry)\n scopes.push(entry)\n }\n } else {\n rejected.push(safeShow(entry))\n }\n }\n\n return { scopes, rejected, malformed: false }\n}\n\n/** Render any value for display without throwing (Symbols throw on `String`). */\nfunction safeShow(value: unknown): string {\n try {\n return typeof value === 'string' ? value : String(value)\n } catch {\n return Object.prototype.toString.call(value)\n }\n}\n","/**\n * ConfigSchema Builder\n *\n * Fluent API for building typed configuration schemas.\n *\n * Usage:\n * ```ts\n * const schema = defineConfigSchema<MyConfig>()\n * .field('trackingId', f => f.string().required().label('Tracking ID'))\n * .field('anonymize', f => f.boolean().default(false).label('Anonymize IPs'))\n * .build()\n * ```\n *\n * @module @pwfabric/core/config-schema-builder\n */\n\nimport type {\n ConfigFieldConstraints,\n ConfigFieldDefinition,\n ConfigFieldOption,\n ConfigFieldType,\n ConfigSchema,\n ValidationResult,\n} from '@pwfabric/contracts'\nimport { validationOk, validationErr, validationError } from '@pwfabric/contracts'\n\n// ============================================================\n// FIELD BUILDER\n// ============================================================\n\nexport class FieldBuilder {\n private _type: ConfigFieldType = 'string'\n private _required = false\n private _defaultValue?: unknown\n private _label = ''\n private _description?: string\n private _sensitive?: boolean\n private _options?: ConfigFieldOption[]\n private _constraints?: ConfigFieldConstraints\n\n string(): this {\n this._type = 'string'\n return this\n }\n\n number(): this {\n this._type = 'number'\n return this\n }\n\n boolean(): this {\n this._type = 'boolean'\n return this\n }\n\n select(options: readonly (string | ConfigFieldOption)[]): this {\n this._type = 'select'\n this._options = options.map((o) => (typeof o === 'string' ? { value: o, label: o } : o))\n return this\n }\n\n multiSelect(options: readonly (string | ConfigFieldOption)[]): this {\n this._type = 'multi-select'\n this._options = options.map((o) => (typeof o === 'string' ? { value: o, label: o } : o))\n return this\n }\n\n url(): this {\n this._type = 'url'\n return this\n }\n\n email(): this {\n this._type = 'email'\n return this\n }\n\n json(): this {\n this._type = 'json'\n return this\n }\n\n required(): this {\n this._required = true\n return this\n }\n\n default(value: unknown): this {\n this._defaultValue = value\n return this\n }\n\n label(s: string): this {\n this._label = s\n return this\n }\n\n description(s: string): this {\n this._description = s\n return this\n }\n\n sensitive(): this {\n this._sensitive = true\n return this\n }\n\n min(n: number): this {\n this._constraints = { ...this._constraints, min: n }\n return this\n }\n\n max(n: number): this {\n this._constraints = { ...this._constraints, max: n }\n return this\n }\n\n pattern(s: string, msg?: string): this {\n this._constraints = { ...this._constraints, pattern: s }\n if (msg) {\n this._constraints = { ...this._constraints, patternMessage: msg }\n }\n return this\n }\n\n /** @internal */\n _build(key: string, group: string | undefined, order: number): ConfigFieldDefinition {\n const def: ConfigFieldDefinition = {\n key,\n type: this._type,\n required: this._required,\n label: this._label || key,\n ...(this._defaultValue !== undefined ? { defaultValue: this._defaultValue } : {}),\n ...(this._description !== undefined ? { description: this._description } : {}),\n ...(group !== undefined ? { group } : {}),\n ...(order !== 0 ? { order } : {}),\n ...(this._sensitive === true ? { sensitive: true } : {}),\n ...(this._options !== undefined ? { options: this._options } : {}),\n ...(this._constraints !== undefined ? { constraints: this._constraints } : {}),\n }\n return def\n }\n}\n\n// ============================================================\n// SCHEMA BUILDER\n// ============================================================\n\ninterface PendingField {\n key: string\n factory: (f: FieldBuilder) => FieldBuilder\n group?: string\n}\n\nexport class ConfigSchemaBuilder<TConfig = Record<string, unknown>> {\n private _fields: PendingField[] = []\n\n field(key: string, factory: (f: FieldBuilder) => FieldBuilder): this {\n this._fields.push({ key, factory })\n return this\n }\n\n group(name: string, groupFn: (g: ConfigSchemaGroupBuilder) => void): this {\n const gb = new ConfigSchemaGroupBuilder(name)\n groupFn(gb)\n this._fields.push(...gb._getFields())\n return this\n }\n\n build(): ConfigSchema<TConfig> {\n const fields: ConfigFieldDefinition[] = this._fields.map((pf, idx) => {\n const fb = new FieldBuilder()\n pf.factory(fb)\n return fb._build(pf.key, pf.group, idx)\n })\n return new SimpleConfigSchema<TConfig>(fields)\n }\n}\n\nclass ConfigSchemaGroupBuilder {\n private _fields: PendingField[] = []\n private readonly _name: string\n\n constructor(name: string) {\n this._name = name\n }\n\n field(key: string, factory: (f: FieldBuilder) => FieldBuilder): this {\n this._fields.push({ key, factory, group: this._name })\n return this\n }\n\n /** @internal */\n _getFields(): PendingField[] {\n return this._fields\n }\n}\n\n// ============================================================\n// SIMPLE CONFIG SCHEMA IMPLEMENTATION\n// ============================================================\n\nexport class SimpleConfigSchema<\n TConfig = Record<string, unknown>,\n> implements ConfigSchema<TConfig> {\n readonly fields: readonly ConfigFieldDefinition[]\n\n constructor(fields: ConfigFieldDefinition[]) {\n this.fields = fields\n }\n\n validate(data: unknown): ValidationResult<TConfig> {\n const errors: { path: string[]; message: string; code: string }[] = []\n const record = (typeof data === 'object' && data !== null ? data : {}) as Record<\n string,\n unknown\n >\n\n for (const field of this.fields) {\n const value = record[field.key]\n\n if (value === undefined || value === null || value === '') {\n if (field.required && field.defaultValue === undefined) {\n errors.push(validationError([field.key], `${field.label} is required`, 'required'))\n }\n continue\n }\n\n // Type validation\n const typeError = this.validateType(field, value)\n if (typeError) {\n errors.push(validationError([field.key], typeError, 'type'))\n continue\n }\n\n // Constraint validation\n if (field.constraints) {\n const constraintError = this.validateConstraints(field, value)\n if (constraintError) {\n errors.push(validationError([field.key], constraintError, 'constraint'))\n }\n }\n }\n\n if (errors.length > 0) {\n return validationErr(errors)\n }\n return validationOk(record as TConfig)\n }\n\n applyDefaults(partial: Partial<TConfig>): TConfig {\n const result = { ...partial } as Record<string, unknown>\n for (const field of this.fields) {\n if (result[field.key] === undefined && field.defaultValue !== undefined) {\n result[field.key] = field.defaultValue\n }\n }\n return result as TConfig\n }\n\n private validateType(field: ConfigFieldDefinition, value: unknown): string | null {\n switch (field.type) {\n case 'string':\n case 'url':\n case 'email':\n case 'json':\n if (typeof value !== 'string') {\n return `${field.label} must be a string`\n }\n break\n case 'number':\n if (typeof value !== 'number') {\n return `${field.label} must be a number`\n }\n break\n case 'boolean':\n if (typeof value !== 'boolean') {\n return `${field.label} must be a boolean`\n }\n break\n case 'select':\n if (typeof value !== 'string') {\n return `${field.label} must be a string`\n }\n if (field.options && !field.options.some((o) => o.value === value)) {\n return `${field.label} must be one of: ${field.options.map((o) => o.value).join(', ')}`\n }\n break\n case 'multi-select':\n if (!Array.isArray(value)) {\n return `${field.label} must be an array`\n }\n if (field.options) {\n const valid = new Set(field.options.map((o) => o.value))\n for (const v of value) {\n if (typeof v !== 'string' || !valid.has(v)) {\n return `${field.label} contains invalid option: ${String(v)}`\n }\n }\n }\n break\n }\n return null\n }\n\n private validateConstraints(field: ConfigFieldDefinition, value: unknown): string | null {\n const c = field.constraints\n if (!c) return null\n\n if (typeof value === 'number') {\n if (c.min !== undefined && value < c.min) {\n return `${field.label} must be at least ${String(c.min)}`\n }\n if (c.max !== undefined && value > c.max) {\n return `${field.label} must be at most ${String(c.max)}`\n }\n }\n\n if (typeof value === 'string' && c.pattern) {\n if (!new RegExp(c.pattern).test(value)) {\n return c.patternMessage ?? `${field.label} does not match the required pattern`\n }\n }\n\n return null\n }\n}\n\n// ============================================================\n// ENTRY POINT\n// ============================================================\n\nexport function defineConfigSchema<\n TConfig = Record<string, unknown>,\n>(): ConfigSchemaBuilder<TConfig> {\n return new ConfigSchemaBuilder<TConfig>()\n}\n","/**\n * State Management\n *\n * PHASE0-WS3: Simple state management utilities\n *\n * @module @pwfabric/core/state\n */\n\n// ============================================================\n// STATE STORE INTERFACE\n// ============================================================\n\n/**\n * State change listener\n */\nexport type StateListener<T> = (newState: T, oldState: T) => void\n\n/**\n * State store interface\n */\nexport interface StateStore<T> {\n /**\n * Get the current state\n */\n getState(): T\n\n /**\n * Set the state\n */\n setState(newState: T): void\n\n /**\n * Update the state with a partial update\n */\n updateState(partial: Partial<T>): void\n\n /**\n * Subscribe to state changes\n */\n subscribe(listener: StateListener<T>): () => void\n\n /**\n * Get a snapshot of the state\n */\n snapshot(): StateSnapshot<T>\n}\n\n/**\n * State snapshot\n */\nexport interface StateSnapshot<T> {\n readonly state: T\n readonly timestamp: number\n readonly version: number\n}\n\n// ============================================================\n// SIMPLE STATE STORE IMPLEMENTATION\n// ============================================================\n\n/**\n * Simple in-memory state store\n */\nexport class SimpleStateStore<T extends object> implements StateStore<T> {\n private state: T\n private version = 0\n private listeners = new Set<StateListener<T>>()\n\n constructor(initialState: T) {\n this.state = { ...initialState }\n }\n\n getState(): T {\n return { ...this.state }\n }\n\n setState(newState: T): void {\n const oldState = this.state\n this.state = { ...newState }\n this.version++\n this.notifyListeners(this.state, oldState)\n }\n\n updateState(partial: Partial<T>): void {\n const oldState = this.state\n this.state = { ...this.state, ...partial }\n this.version++\n this.notifyListeners(this.state, oldState)\n }\n\n subscribe(listener: StateListener<T>): () => void {\n this.listeners.add(listener)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n snapshot(): StateSnapshot<T> {\n return {\n state: this.getState(),\n timestamp: Date.now(),\n version: this.version,\n }\n }\n\n private notifyListeners(newState: T, oldState: T): void {\n for (const listener of this.listeners) {\n try {\n listener(newState, oldState)\n } catch {\n // Ignore listener errors\n }\n }\n }\n}\n\n/**\n * Create a new state store\n */\nexport function createStateStore<T extends object>(initialState: T): StateStore<T> {\n return new SimpleStateStore<T>(initialState)\n}\n\n// ============================================================\n// COMPUTED STATE\n// ============================================================\n\n/**\n * Selector function type\n */\nexport type Selector<T, R> = (state: T) => R\n\n/**\n * Create a computed value from a store\n */\nexport function computed<T extends object, R>(\n store: StateStore<T>,\n selector: Selector<T, R>\n): () => R {\n return () => selector(store.getState())\n}\n\n/**\n * Subscribe to a specific slice of state\n */\nexport function subscribeToSlice<T extends object, R>(\n store: StateStore<T>,\n selector: Selector<T, R>,\n listener: StateListener<R>\n): () => void {\n let previousValue = selector(store.getState())\n\n return store.subscribe((newState, oldState) => {\n const newValue = selector(newState)\n const oldValue = selector(oldState)\n\n // Only notify if the selected value changed\n if (newValue !== oldValue) {\n listener(newValue, previousValue)\n previousValue = newValue\n }\n })\n}\n\n// ============================================================\n// STATE MACHINE\n// ============================================================\n\n/**\n * State machine transition\n */\nexport interface Transition<S, E> {\n from: S\n to: S\n event: E\n guard?: () => boolean\n action?: () => void\n}\n\n/**\n * State machine configuration\n */\nexport interface StateMachineConfig<S, E> {\n initial: S\n transitions: Transition<S, E>[]\n}\n\n/**\n * State machine interface\n */\nexport interface StateMachine<S, E> {\n /**\n * Get the current state\n */\n getState(): S\n\n /**\n * Check if an event can be processed\n */\n can(event: E): boolean\n\n /**\n * Process an event\n */\n dispatch(event: E): boolean\n\n /**\n * Subscribe to state changes\n */\n subscribe(listener: StateListener<S>): () => void\n}\n\n/**\n * Simple state machine implementation\n */\nexport class SimpleStateMachine<S, E> implements StateMachine<S, E> {\n private state: S\n private readonly transitions: Transition<S, E>[]\n private listeners = new Set<StateListener<S>>()\n\n constructor(config: StateMachineConfig<S, E>) {\n this.state = config.initial\n this.transitions = config.transitions\n }\n\n getState(): S {\n return this.state\n }\n\n can(event: E): boolean {\n const transition = this.findTransition(event)\n if (!transition) return false\n if (transition.guard && !transition.guard()) return false\n return true\n }\n\n dispatch(event: E): boolean {\n const transition = this.findTransition(event)\n if (!transition) return false\n if (transition.guard && !transition.guard()) return false\n\n const oldState = this.state\n this.state = transition.to\n\n if (transition.action) {\n transition.action()\n }\n\n this.notifyListeners(this.state, oldState)\n return true\n }\n\n subscribe(listener: StateListener<S>): () => void {\n this.listeners.add(listener)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n private findTransition(event: E): Transition<S, E> | undefined {\n return this.transitions.find((t) => t.from === this.state && t.event === event)\n }\n\n private notifyListeners(newState: S, oldState: S): void {\n for (const listener of this.listeners) {\n try {\n listener(newState, oldState)\n } catch {\n // Ignore listener errors\n }\n }\n }\n}\n\n/**\n * Create a state machine\n */\nexport function createStateMachine<S, E>(config: StateMachineConfig<S, E>): StateMachine<S, E> {\n return new SimpleStateMachine<S, E>(config)\n}\n","/**\n * Block Type Definitions\n *\n * Core type definitions for the block ecosystem\n *\n * @module @pwfabric/core/blocks/types\n */\n\nimport type { ZodSchema } from 'zod'\nimport type { BlockLayout } from './layout-schema.js'\n\n// The block instance type is defined in @pwfabric/contracts; re-exported here.\nexport type { Block } from '@pwfabric/contracts'\n\n// ============================================================\n// BLOCK CATEGORIES\n// ============================================================\n\n/**\n * Block category classification.\n *\n * `feedback` is the family of toast, spinner and radial-progress blocks. A\n * block's atom id comes from its directory, and a pack's integrity check\n * requires the category and the directory to agree, so these blocks carry\n * `feedback` rather than being filed under `control`.\n */\nexport type BlockCategory =\n | 'layout'\n | 'panel'\n | 'text'\n | 'data'\n | 'control'\n | 'media'\n | 'form'\n | 'feedback'\n // Categories by SHAPE: `overlay` (modal, drawer, popover, tooltip,\n // command-palette), `container` (card, accordion, tabs, tree-view) and\n // `integration` (app views that own a connection to an outside service:\n // calendar, chat, files…). `panel` remains for packs that still use it.\n | 'overlay'\n | 'container'\n | 'integration'\n\n// ============================================================\n// BLOCK DEFINITION\n// ============================================================\n\n/**\n * Block definition interface\n *\n * Defines the structure and constraints of a block type.\n */\nexport interface BlockDefinition {\n /** Unique block type identifier */\n readonly type: string\n\n /** Human-readable display name */\n readonly name: string\n\n /** Block category for grouping */\n readonly category: BlockCategory\n\n /** Icon character or identifier */\n readonly icon: string\n\n /** Zod schema for props validation */\n readonly schema: ZodSchema\n\n /** Default props for new instances */\n readonly defaultProps: Record<string, unknown>\n\n /** Default layout for new instances (span/offset/order/hidden per breakpoint) */\n readonly defaultLayout?: BlockLayout\n\n /** Whether this block can contain children */\n readonly canHaveChildren: boolean\n\n /**\n * Optional: which child block types this block accepts. The runtime's\n * composition rules enforce it. `allowedChildTraits` is the trait-based\n * alternative, for a block that accepts any child with a given trait.\n */\n readonly allowedChildren?: readonly string[]\n\n /** Optional: Restrict which block types can be parents */\n readonly allowedParents?: readonly string[]\n\n /** open trait vocabulary this block carries (kebab-case). */\n readonly traits?: readonly string[]\n\n /**\n * a child block passes if it carries ANY of these traits.\n * Only meaningful when `canHaveChildren` is true.\n */\n readonly allowedChildTraits?: readonly string[]\n\n /** Optional: Maximum instances allowed in a surface */\n readonly maxInstances?: number\n}\n\n// ============================================================\n// BLOCK INSTANCE\n// ============================================================\n// Block is re-exported from @pwfabric/contracts above.\n\n// ============================================================\n// VALIDATION\n// ============================================================\n\n/**\n * Validation error interface\n */\nexport interface ValidationError {\n /** Error code for programmatic handling */\n readonly code: string\n\n /** Human-readable error message */\n readonly message: string\n\n /** Optional: Associated block ID */\n readonly blockId?: string\n\n /** Optional: Suggestion for fixing the error */\n readonly suggestion?: string\n}\n\n/**\n * Validation result interface\n */\nexport interface ValidationResult {\n /** Whether validation passed */\n readonly valid: boolean\n\n /** List of validation errors */\n readonly errors: readonly ValidationError[]\n}\n\n// ============================================================\n// COMPOSITION RULES\n// ============================================================\n\n/**\n * Composition rule type\n */\nexport type CompositionRuleType =\n | 'max_depth'\n | 'allowed_children'\n | 'allowed_parents'\n | 'required_parent'\n | 'no_children'\n | 'no_self_nesting'\n\n/**\n * Composition rule interface\n */\nexport interface CompositionRule {\n /** Rule type */\n readonly type: CompositionRuleType\n\n /** Rule description */\n readonly description: string\n\n /** Block type this rule applies to (or '*' for all) */\n readonly appliesTo: string | '*'\n\n /** Rule-specific configuration */\n readonly config: Record<string, unknown>\n}\n\n// ============================================================\n// CONSTANTS\n// ============================================================\n\n/**\n * Maximum block nesting depth. SINGLE SOURCE OF TRUTH — every validator and the\n * composer prompt derive from this constant.\n *\n * Canonical rule (enforced identically everywhere): root blocks are at depth 0,\n * and a block is INVALID when its depth `>= MAX_NESTING_DEPTH`. So the deepest\n * legal block sits at depth `MAX_NESTING_DEPTH - 1`, i.e. up to `MAX_NESTING_DEPTH`\n * levels of nesting (root included).\n *\n * Consumers: the runtime rule engine and composition-rules prose\n * (@pwfabric/runtime), and a host's surface validation (MAX_NESTING_EXCEEDED)\n * and composer instructions (\"Max nesting depth: N levels\").\n */\nexport const MAX_NESTING_DEPTH = 10\n\n/**\n * Block categories ordered for display\n */\nexport const BLOCK_CATEGORIES: readonly BlockCategory[] = [\n 'layout',\n 'panel',\n 'text',\n 'data',\n 'control',\n 'media',\n 'form',\n // Last in display order: status and notification chrome, not content.\n 'feedback',\n] as const\n","/**\n * Block Layout Schema\n *\n * Zod schemas for layout validation, per-type default spans,\n * and mobile-first cascade resolution.\n *\n * @module @pwfabric/core/blocks/layout-schema\n */\n\nimport { z } from 'zod'\n\n// ============================================================\n// BREAKPOINT DEFINITIONS\n// ============================================================\n\n/**\n * Named breakpoints aligned with Tailwind CSS conventions\n */\nexport type BreakpointName = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl'\n\n/**\n * Breakpoint definition with min-width and column count\n */\nexport interface BreakpointDefinition {\n readonly name: BreakpointName\n readonly minWidth: number\n readonly columns: number\n readonly label: string\n}\n\n/**\n * Ordered breakpoint definitions (smallest to largest)\n */\nexport const BREAKPOINTS: readonly BreakpointDefinition[] = [\n { name: 'xs', minWidth: 0, columns: 4, label: 'Mobile' },\n { name: 'sm', minWidth: 640, columns: 8, label: 'Mobile Landscape' },\n { name: 'md', minWidth: 768, columns: 8, label: 'Tablet' },\n { name: 'lg', minWidth: 1024, columns: 12, label: 'Desktop' },\n { name: 'xl', minWidth: 1280, columns: 12, label: 'Large Desktop' },\n { name: '2xl', minWidth: 1536, columns: 12, label: 'Extra Large' },\n] as const\n\n/**\n * Ordered breakpoint names for iteration and cascade resolution\n */\nexport const BREAKPOINT_ORDER: readonly BreakpointName[] = [\n 'xs',\n 'sm',\n 'md',\n 'lg',\n 'xl',\n '2xl',\n] as const\n\n// ============================================================\n// RESPONSIVE VALUE TYPE\n// ============================================================\n\n/**\n * A value that can vary per breakpoint.\n */\nexport type ResponsiveValue<T> = Readonly<Partial<Record<BreakpointName, T>>>\n\n// ============================================================\n// BLOCK LAYOUT\n// ============================================================\n\n/**\n * Layout metadata for a block instance.\n */\nexport interface BlockLayout {\n readonly span: ResponsiveValue<number>\n readonly offset?: ResponsiveValue<number>\n readonly order?: ResponsiveValue<number>\n readonly hidden?: ResponsiveValue<boolean>\n /**\n * Per-breakpoint visibility (the `hidden md:flex` equivalent).\n * `hideOn` = breakpoints where the block is hidden; `showOn` = the only\n * breakpoints where it is visible. CSS/media-query driven (see runtime\n * renderer), using the same pixel thresholds as the span system.\n */\n readonly hideOn?: readonly BreakpointName[]\n readonly showOn?: readonly BreakpointName[]\n /**\n * What this block's width belongs to: the surface's measured container, or\n * the screen itself.\n *\n * `container` (default) — respects `--pw-layout-container-max-width`.\n * `viewport` — LEAVES that container and reaches the edge of the screen.\n *\n * Breakpoint-aware, because \"change shape on a narrow screen\" is exactly\n * this: `{ xs: 'viewport', lg: 'container' }`.\n *\n * The engine knows NO words beyond these two. Which region of which shell\n * has which scope is the pack's vocabulary; if the engine memorised it, a\n * second pack could not express itself.\n */\n readonly widthScope?: ResponsiveValue<WidthScope>\n}\n\nexport const DEFAULT_BLOCK_LAYOUT: BlockLayout = {\n span: { xs: 4, sm: 8, md: 8, lg: 12 },\n} as const\n\n// ============================================================\n// VIEWPORT PRESETS\n// ============================================================\n\nexport type PreviewViewport = BreakpointName | 'responsive'\n\nexport const VIEWPORT_PRESETS: Record<\n BreakpointName,\n { readonly width: number; readonly height: 'auto' }\n> = {\n xs: { width: 375, height: 'auto' },\n sm: { width: 640, height: 'auto' },\n md: { width: 768, height: 'auto' },\n lg: { width: 1024, height: 'auto' },\n xl: { width: 1280, height: 'auto' },\n '2xl': { width: 1536, height: 'auto' },\n} as const\n\n// ============================================================\n// ZOD SCHEMAS\n// ============================================================\n\nexport const responsiveNumberSchema = z\n .object({\n xs: z.number().int().min(0).optional(),\n sm: z.number().int().min(0).optional(),\n md: z.number().int().min(0).optional(),\n lg: z.number().int().min(0).optional(),\n xl: z.number().int().min(0).optional(),\n '2xl': z.number().int().min(0).optional(),\n })\n .strict()\n\nexport const responsiveBooleanSchema = z\n .object({\n xs: z.boolean().optional(),\n sm: z.boolean().optional(),\n md: z.boolean().optional(),\n lg: z.boolean().optional(),\n xl: z.boolean().optional(),\n '2xl': z.boolean().optional(),\n })\n .strict()\n\nexport const breakpointNameSchema = z.enum(['xs', 'sm', 'md', 'lg', 'xl', '2xl'])\n\n/**\n * Width scope — the ONLY vocabulary the engine knows on this axis.\n *\n * `container` fits the measured container, `viewport` leaves it. There is no\n * third value: in-between words such as \"half\", \"wide\" or \"full\" belong to a\n * shell's vocabulary and live in the pack. The engine applies only the\n * difference between \"fit the container\" and \"leave the container\".\n */\nexport const widthScopeSchema = z.enum(['container', 'viewport'])\nexport type WidthScope = z.infer<typeof widthScopeSchema>\n\nexport const responsiveWidthScopeSchema = z\n .object({\n xs: widthScopeSchema.optional(),\n sm: widthScopeSchema.optional(),\n md: widthScopeSchema.optional(),\n lg: widthScopeSchema.optional(),\n xl: widthScopeSchema.optional(),\n '2xl': widthScopeSchema.optional(),\n })\n .strict()\n\nexport const blockLayoutSchema = z.object({\n span: responsiveNumberSchema,\n offset: responsiveNumberSchema.optional(),\n order: responsiveNumberSchema.optional(),\n hidden: responsiveBooleanSchema.optional(),\n hideOn: z.array(breakpointNameSchema).optional(),\n showOn: z.array(breakpointNameSchema).optional(),\n widthScope: responsiveWidthScopeSchema.optional(),\n})\n\n// ============================================================\n// CASCADE RESOLUTION\n// ============================================================\n\nexport function resolveResponsiveValue<T>(\n responsive: ResponsiveValue<T> | undefined,\n breakpoint: BreakpointName\n): T | undefined {\n if (!responsive) return undefined\n const targetIndex = BREAKPOINT_ORDER.indexOf(breakpoint)\n for (let i = targetIndex; i >= 0; i--) {\n const bp = BREAKPOINT_ORDER[i]\n if (!bp) continue\n if (responsive[bp] !== undefined) {\n return responsive[bp]\n }\n }\n return undefined\n}\n\nexport function resolveSpanAtBreakpoint(layout: BlockLayout, breakpoint: BreakpointName): number {\n const span = resolveResponsiveValue(layout.span, breakpoint)\n if (span !== undefined) return span\n const bpDef = BREAKPOINTS.find((bp) => bp.name === breakpoint)\n return bpDef?.columns ?? 12\n}\n\nexport function getColumnsAtBreakpoint(breakpoint: BreakpointName): number {\n const bpDef = BREAKPOINTS.find((bp) => bp.name === breakpoint)\n return bpDef?.columns ?? 12\n}\n\nexport function getBreakpointForWidth(width: number): BreakpointName {\n for (let i = BREAKPOINTS.length - 1; i >= 0; i--) {\n const bp = BREAKPOINTS[i]\n if (bp && width >= bp.minWidth) {\n return bp.name\n }\n }\n return 'xs'\n}\n","/**\n * Block Host Imports — what a dynamically loaded block may import, and what the\n * host must therefore provide.\n *\n * WHY THIS EXISTS. A published block is bundled per atom with esbuild and\n * loaded in the browser through `<script type=\"importmap\">` + `import(blob:…)`.\n * Two kinds of import survive that: relative paths to files inside the block's\n * own pack, and a short list of BARE specifiers that are left unbundled for the\n * host to supply. That list appears in three places — the bundler's externals,\n * the host's import map and the shim files the host serves — and a specifier\n * missing from any one of them fails at load time (\"Failed to resolve module\n * specifier\" inside the blob module).\n *\n * This module is that contract, in one place, so the bundler's allowlist, the\n * host's import map and the shim files are all DERIVED and can be checked\n * against each other instead of drifting in silence.\n *\n * WHY NOT IN `@pwfabric/contracts`, where `dynamic-artifact.ts` already lives.\n * The contracts package is treated as immutable after release: every change to\n * its surface, even an additive one, goes through a stricter review. This list has to\n * change whenever a package joins or leaves the allowlist; putting it behind a\n * ceremony is what would recreate the drift it exists to prevent. It lives here,\n * where an additive export is an ordinary minor.\n *\n * @module @pwfabric/core/blocks/host-imports\n */\n\n// ============================================================\n// THE CONTRACT\n// ============================================================\n\n/**\n * How the host hands a shared module to a dynamically loaded block.\n *\n * `global` — the shim re-exports from `globalThis[global]`, which the host seeds\n * from its OWN bundled import. This is the mechanism for anything whose IDENTITY\n * must be shared: one React dispatcher, one event bus, one set of contract\n * values. Two instances of these is not \"slightly wasteful\", it is broken —\n * `useSurfaceEvents` reading a second context makes `emit()` a silent no-op.\n *\n * It is the only kind: every specifier on this list is resolved by the host\n * through a shim reading a global. `zod` included — blocks share the host's\n * single zod instance, because introspection needs the real zod for\n * `instanceof` while walking a schema. A specifier a bundler inlines is simply\n * not external, and so never reaches this list.\n */\nexport type HostImportKind = 'global'\n\n/**\n * WHICH hosts seed a `global` entry. There are two of them and they are not\n * obliged to agree — recording that here keeps a derived gate from calling a\n * deliberate decision a gap.\n *\n * `every-host` — both the app host and the standalone export's IIFE\n * (`@pwfabric/embed`'s `embed-global.ts`) must seed it.\n * `app-host` — the app host seeds it; the standalone export deliberately\n * does NOT. No entry is in this class today. The sdk global\n * was, until 1.0.0-rc.2: a block written the documented way\n * calls `defineBlock()` when its bundle loads, so a shipped\n * app whose page did not seed the sdk rendered none of them.\n * The renderer bundle carries the authoring kit anyway, so it\n * now seeds it like the rest.\n * `unseeded` — nothing seeds it yet. The specifier resolves (the shim is\n * served) but its named exports come back `undefined`. That is\n * strictly better than an unresolved bare specifier, which\n * fails the whole module at link time — but it is a gap, and\n * naming it here keeps it visible.\n */\nexport type HostSeeding = 'every-host' | 'app-host' | 'unseeded'\n\n/** One specifier a block may import, and how the host satisfies it. */\nexport interface HostImport {\n /** The bare specifier as it appears in block source and in the bundle. */\n readonly specifier: string\n readonly kind: HostImportKind\n /**\n * The `globalThis` key the shim reads. Present for `kind: 'global'` only.\n * The host seeds it from its own bundled import of the same package.\n */\n readonly global?: string\n /** Which hosts seed {@link HostImport.global}. Present for `kind: 'global'` only. */\n readonly seeding?: HostSeeding\n /**\n * Shim file this specifier resolves to, relative to the host's shim directory.\n * SEVERAL SPECIFIERS MAY SHARE ONE FILE — `@pwfabric/runtime` and its\n * subpaths all resolve to the runtime shim, because what a block imports is\n * a runtime contract, not a package name.\n */\n readonly shim: string\n /** Why this specifier is on the list. Read by humans, not by code. */\n readonly reason: string\n}\n\n/**\n * THE LIST. Order is not significant; every consumer derives from the whole set.\n *\n * Adding an entry is the ONLY supported way to let blocks import something new.\n * The derivation helpers below mean a new entry reaches the bundler's allowlist,\n * every host's import map and every shim file together.\n */\nexport const BLOCK_HOST_IMPORTS: readonly HostImport[] = [\n {\n specifier: 'react',\n kind: 'global',\n global: '__pwfabric_react',\n seeding: 'every-host',\n shim: 'react.mjs',\n reason:\n 'One dispatcher. A second React instance makes every hook in a block throw \"Cannot read properties of null (reading \\'useState\\')\".',\n },\n {\n specifier: 'react/jsx-runtime',\n kind: 'global',\n global: '__pwfabric_jsx_runtime',\n seeding: 'every-host',\n shim: 'react-jsx-runtime.mjs',\n reason:\n 'The automatic JSX transform emits imports from here; it must be the same React. NOTE the global is `__pwfabric_jsx_runtime`, not `…_react_jsx_runtime`; the shim and the seeders read this name.',\n },\n {\n specifier: 'react-dom',\n kind: 'global',\n global: '__pwfabric_react_dom',\n seeding: 'unseeded',\n shim: 'react-dom.mjs',\n reason: 'Blocks that portal or measure reach for react-dom; same-instance rule as React.',\n },\n {\n specifier: '@pwfabric/runtime',\n kind: 'global',\n global: '__pwfabric_runtime',\n seeding: 'every-host',\n shim: 'runtime.mjs',\n reason:\n 'Surface event bus, surface id and connections contexts. A block reading a second context emits into nothing.',\n },\n {\n specifier: '@pwfabric/runtime/data',\n kind: 'global',\n global: '__pwfabric_runtime',\n seeding: 'every-host',\n shim: 'runtime.mjs',\n reason:\n 'A runtime subpath the package root re-exports WHOLESALE, so the root shim serves it exactly — the foundation pack persistence capability imports `createDataService` from here. An import map resolves exact specifiers only: without this entry the import would compile with a HOST_SUBPATH_IMPORT warning and then fail to resolve in the browser. Only subpaths whose every export the root also exports may join; the runtime package has a test that says so.',\n },\n {\n specifier: '@pwfabric/runtime/capability',\n kind: 'global',\n global: '__pwfabric_runtime',\n seeding: 'every-host',\n shim: 'runtime.mjs',\n reason:\n 'A runtime subpath the package root re-exports WHOLESALE, so the root shim serves it exactly — capability atoms import their definition helpers from here. An import map resolves exact specifiers only: without this entry the import would compile with a HOST_SUBPATH_IMPORT warning and then fail to resolve in the browser. Only subpaths whose every export the root also exports may join; the runtime package has a test that says so.',\n },\n {\n specifier: '@pwfabric/runtime/adapters',\n kind: 'global',\n global: '__pwfabric_runtime',\n seeding: 'every-host',\n shim: 'runtime.mjs',\n reason:\n 'A runtime subpath the package root re-exports WHOLESALE, so the root shim serves it exactly — image adapters; a block that renders a responsive image reaches for them here. An import map resolves exact specifiers only: without this entry the import would compile with a HOST_SUBPATH_IMPORT warning and then fail to resolve in the browser. Only subpaths whose every export the root also exports may join; the runtime package has a test that says so.',\n },\n {\n specifier: '@pwfabric/contracts',\n kind: 'global',\n global: '__pwfabric_contracts',\n seeding: 'every-host',\n shim: 'contracts.mjs',\n reason: 'Contract VALUES (enums, constants) must be the host’s, not a second copy.',\n },\n {\n specifier: '@pwfabric/core',\n kind: 'global',\n global: '__pwfabric_core',\n seeding: 'unseeded',\n shim: 'core.mjs',\n reason: 'Block layout helpers and breakpoint constants blocks resolve at render time.',\n },\n {\n specifier: '@pwfabric/authoring',\n kind: 'global',\n global: '__pwfabric_sdk',\n seeding: 'every-host',\n shim: 'sdk@v1.mjs',\n reason:\n 'What the scaffolding emits and a third-party author reads first. A host that does not map it breaks every block that follows the documented path.',\n },\n {\n specifier: 'zod',\n kind: 'global',\n global: '__pwfabric_zod',\n seeding: 'every-host',\n shim: 'zod.mjs',\n reason:\n 'Every block with a prop schema imports it as a value — 81 pack source files take `z`. Shared, not inlined: `zod.mjs` re-exports the host instance, and introspection depends on it being the real zod so `instanceof` holds while walking a schema.',\n },\n] as const\n\n// ============================================================\n// DERIVATIONS — every consumer reads the list through one of these\n// ============================================================\n\n/**\n * The specifiers esbuild must leave bare when bundling an atom.\n *\n * A bundling service's externals list is exactly this: the bundler leaves each\n * specifier bare, and the host's import map resolves it to the shared instance.\n */\nexport function blockBundleExternals(): readonly string[] {\n return BLOCK_HOST_IMPORTS.map((i) => i.specifier)\n}\n\n/**\n * The host's `<script type=\"importmap\">` payload.\n *\n * @param shimBase - URL prefix the shim files are served from, no trailing\n * slash (for example `/_pwfabric/shims`).\n */\nexport function blockImportMap(shimBase: string): { readonly imports: Record<string, string> } {\n const imports: Record<string, string> = {}\n for (const entry of BLOCK_HOST_IMPORTS) {\n imports[entry.specifier] = `${shimBase}/${entry.shim}`\n }\n return { imports }\n}\n\n/** Every distinct shim file the import map can point at. */\nexport function blockShimFiles(): readonly string[] {\n return [...new Set(BLOCK_HOST_IMPORTS.map((i) => i.shim))].sort()\n}\n\n/**\n * The `globalThis` keys a host must seed before any block bundle is imported.\n *\n * A host that renders published blocks assigns each of these from its own\n * bundled import. Missing one does not throw where it is missing — it throws\n * inside a block, later, as an undefined named import.\n */\nexport function blockHostGlobals(host: 'app-host' | 'standalone' = 'app-host'): readonly string[] {\n // The standalone export is NOT the app host with fewer features — it seeds a\n // deliberately smaller set, and asking it for the app host's list would make a\n // gate demand the sdk global it deliberately leaves out. `unseeded`\n // entries belong to neither list: nothing seeds them today, and pretending\n // otherwise would turn a recorded gap into a failing gate nobody can satisfy.\n const wanted: readonly HostSeeding[] =\n host === 'standalone' ? ['every-host'] : ['every-host', 'app-host']\n return [\n ...new Set(\n BLOCK_HOST_IMPORTS.flatMap((i) =>\n i.global && i.seeding && wanted.includes(i.seeding) ? [i.global] : []\n )\n ),\n ].sort()\n}\n\n/** Entries whose global nothing seeds yet — a gap this list refuses to hide. */\nexport function unseededHostGlobals(): readonly HostImport[] {\n return BLOCK_HOST_IMPORTS.filter((i) => i.seeding === 'unseeded')\n}\n\n/**\n * Which specifiers resolve to a given shim file — the reverse of `shim`.\n * A shim generator needs this: one file serves every specifier aliased to it,\n * so it must export the union of what those specifiers' consumers import.\n */\nexport function specifiersForShim(shim: string): readonly string[] {\n return BLOCK_HOST_IMPORTS.filter((i) => i.shim === shim).map((i) => i.specifier)\n}\n\n/**\n * Names a shim must not bind even though they parse as identifiers.\n *\n * Reserved words fail the parse outright. `undefined`, `NaN` and `Infinity`\n * are global value properties: `export const { undefined } = m` parses, but\n * it shadows a restricted name (lint refuses it, and some toolchains refuse to\n * parse it), and no block imports them by name. zod exports `undefined` (its\n * `z.undefined()` schema), so a shim built from zod's keys would carry it.\n */\nconst NON_BINDABLE_NAMES = new Set(\n (\n 'break case catch class const continue debugger default delete do else enum export extends false finally for ' +\n 'function if import in instanceof new null return super switch this throw true try typeof var void while with ' +\n 'yield let static implements interface package private protected public await arguments eval ' +\n 'undefined NaN Infinity'\n ).split(' ')\n)\n\n/** Whether `name` can be an `export const { name }` binding in a shim module. */\nexport function isExportableName(name: string): boolean {\n return /^[A-Za-z_$][\\w$]*$/.test(name) && !NON_BINDABLE_NAMES.has(name)\n}\n\n/**\n * Source of one shim module: it re-exports the instance a host seeded on\n * `globalThis[global]`, as a default export and as one named export per entry\n * of `names` that can be a binding (see {@link isExportableName}), deduplicated\n * and sorted. `shim` is a file from {@link blockShimFiles}; the header comment\n * lists the specifiers that resolve to it.\n *\n * Every host serving block bundles writes these files; the names are the\n * host's to supply (an ESM import of a name the shim does not export fails the\n * whole block at link time, so they should be read off the very object the host\n * seeds).\n *\n * A shim whose global every host must seed (`seeding: 'every-host'`) throws a\n * readable error when the global is missing, naming the global and the\n * specifiers: the alternative is a destructuring `TypeError` inside a blob\n * module, which says nothing about the host that forgot to seed it. A shim for\n * an `unseeded` global keeps degrading to `undefined` exports instead.\n */\nexport function shimSource(shim: string, global: string, names: readonly string[]): string {\n const exported = [...new Set(names)].filter(isExportableName).sort()\n const specifiers = specifiersForShim(shim)\n const required = BLOCK_HOST_IMPORTS.some((i) => i.shim === shim && i.seeding === 'every-host')\n const served = specifiers.map((s) => `'${s}'`).join(', ')\n const lines = [\n `// Generated by pwf. Serves ${served} to compiled blocks:`,\n `// re-exports the instance the page seeded on globalThis.${global}.`,\n ]\n if (required) {\n const message = `[pwfabric] globalThis.${global} is not seeded, so ${specifiers.join(', ') || shim} cannot be imported by a block. The host page must seed it before loading block bundles (@pwfabric/embed's embed.js does).`\n lines.push(\n `const m = globalThis.${global}`,\n `if (m == null) throw new Error(${JSON.stringify(message)})`\n )\n } else {\n lines.push(`const m = globalThis.${global} ?? {}`)\n }\n lines.push('export default m')\n if (exported.length > 0) {\n lines.push(`export const {\\n${exported.map((n) => ` ${n},`).join('\\n')}\\n} = m`)\n }\n return `${lines.join('\\n')}\\n`\n}\n","/**\n * Thin mode loader.\n *\n * Fetches a published surface + its render grants from a host API the same\n * way a host application's public surface route does, then normalises the\n * result into the shape `render-core` consumes.\n *\n * The host API serves `GET /api/surfaces/by-slug/:tenant/:slug` (and\n * `GET /api/surfaces/:id/published`). Host API clients are not part of this\n * engine, so this issues the HTTP call with `fetch` and applies the same\n * post-processing a host applies:\n * - `definition.rootBlock.children` (or `definition.blocks`) → runtime blocks,\n * merging each block's stored `layout.span` with `DEFAULT_BLOCK_LAYOUT.span`.\n * - `response.renderGrants[]` → `DynamicBlockDescriptor[]` (publisher\n * 'workspace', unverified) — byte-identical to the host's `mappedDescriptors`.\n * - `definition.theme` / `styleVariables` → an `appearance` ref.\n * - `definition.capabilities` normalised with `required: false` default.\n *\n * @module @pwfabric/embed/thin\n */\n\nimport { DEFAULT_BLOCK_LAYOUT } from '@pwfabric/core'\nimport type { Block } from '@pwfabric/core'\nimport type {\n DynamicBlockDescriptor,\n SurfaceRenderGrant,\n SurfaceTheme,\n SurfaceCapabilityRequirement,\n} from '@pwfabric/contracts'\nimport type { RenderableSurface } from '@pwfabric/runtime'\nimport { isCapability } from '@pwfabric/runtime/capability'\n\n// ============================================================\n// TYPES\n// ============================================================\n\nexport interface ThinAuth {\n /** Bearer token; injected as `Authorization` on the surface fetch and on\n * any REST data sources (matching the host's `ms_access_token` behaviour). */\n readonly accessToken?: string\n /** Send credentials (cookies) with the request. */\n readonly includeCredentials?: boolean\n}\n\nexport interface LoadThinOptions {\n /** API origin, e.g. `https://api.example.com`. */\n readonly apiBaseUrl: string\n /** Optional auth. */\n readonly auth?: ThinAuth\n /** Custom fetch (test injection / non-browser runtime). */\n readonly fetchImpl?: typeof fetch\n}\n\n/**\n * A surface reference: either a `surfaceId` (by-id) or a tenant+surface slug\n * pair (by-slug, the host's path).\n */\nexport type ThinSurfaceRef =\n | { readonly surfaceId: string }\n | { readonly tenantSlug: string; readonly surfaceSlug: string }\n\nexport interface LoadThinResult {\n readonly surface: RenderableSurface\n readonly dynamicBlocks: readonly DynamicBlockDescriptor[]\n readonly surfaceId?: string\n readonly worldId?: string\n /** Surface-level layout hints from the API (maxWidth/gap/padding). */\n readonly layout?: { maxWidth?: number; gap?: number; padding?: number }\n}\n\n// ============================================================\n// API RESPONSE SHAPES (loose — mirror the host's local interfaces)\n// ============================================================\n\ninterface ApiBlockNode {\n id: string\n type: string\n version?: string\n props?: Record<string, unknown>\n layout?: Block['layout']\n style?: Record<string, string>\n children?: ApiBlockNode[]\n}\n\ninterface IncomingCapability {\n capability: string\n required?: boolean\n config?: Record<string, unknown>\n}\n\ninterface SurfaceFetchData {\n surfaceId: string\n worldId: string\n definition: {\n rootBlock?: ApiBlockNode\n blocks?: ApiBlockNode[]\n dataSources?: unknown[]\n state?: Record<string, unknown>\n styleVariables?: Record<string, string>\n theme?: SurfaceTheme\n capabilities?: IncomingCapability[]\n }\n layout?: { maxWidth?: number; gap?: number; padding?: number } | null\n renderGrants?: SurfaceRenderGrant[]\n}\n\n// ============================================================\n// BLOCK CONVERSION (mirror of the host's toRuntimeBlock)\n// ============================================================\n\nfunction toRuntimeBlock(node: ApiBlockNode): Block {\n const storedLayout = node.layout\n const mergedLayout: Block['layout'] = storedLayout\n ? {\n ...storedLayout,\n span: { ...DEFAULT_BLOCK_LAYOUT.span, ...storedLayout.span },\n }\n : DEFAULT_BLOCK_LAYOUT\n\n const base = {\n id: node.id,\n type: node.type,\n props: node.props ?? {},\n layout: mergedLayout,\n ...(node.style ? { style: node.style } : {}),\n }\n\n if (node.children && node.children.length > 0) {\n return { ...base, children: node.children.map(toRuntimeBlock) }\n }\n return base\n}\n\n/**\n * Map render grants → dynamic block descriptors. Byte-identical to the host's\n * `mappedDescriptors` memo: publisher 'workspace', unverified, a minimal\n * marketplace-category definition.\n */\nexport function grantsToDescriptors(\n grants: readonly SurfaceRenderGrant[]\n): DynamicBlockDescriptor[] {\n if (grants.length === 0) return []\n return grants.map((grant) => ({\n blockType: grant.blockType,\n moduleUrl: grant.moduleUrl,\n integrity: grant.integrity,\n publisher: 'workspace',\n publisherVerified: false,\n definition: {\n name: grant.artifactName,\n category: 'marketplace',\n defaultProps: {},\n canHaveChildren: false,\n },\n }))\n}\n\n// ============================================================\n// LOADER\n// ============================================================\n\nfunction buildSurfaceUrl(apiBaseUrl: string, ref: ThinSurfaceRef): string {\n const base = apiBaseUrl.replace(/\\/+$/, '')\n if ('surfaceId' in ref) {\n return `${base}/api/surfaces/${encodeURIComponent(ref.surfaceId)}/published`\n }\n return `${base}/api/surfaces/by-slug/${encodeURIComponent(ref.tenantSlug)}/${encodeURIComponent(\n ref.surfaceSlug\n )}`\n}\n\n/**\n * The API wraps payloads as `{ data, error }` (an `ApiResponse` envelope). Some\n * endpoints return the bare object. Normalise both.\n */\nfunction unwrap(json: unknown): SurfaceFetchData {\n const obj = json as { data?: SurfaceFetchData; error?: { code?: string } }\n if (obj && obj.error) {\n throw new Error(`[pwfabric-embed] surface fetch error: ${obj.error.code ?? 'UNKNOWN'}`)\n }\n if (obj && obj.data) return obj.data\n return json as SurfaceFetchData\n}\n\n/**\n * Fetch + normalise a published surface and its render grants.\n */\nexport async function loadThin(\n ref: ThinSurfaceRef,\n options: LoadThinOptions\n): Promise<LoadThinResult> {\n const doFetch = options.fetchImpl ?? fetch\n const url = buildSurfaceUrl(options.apiBaseUrl, ref)\n\n const headers: Record<string, string> = { accept: 'application/json' }\n const token = options.auth?.accessToken\n if (token) headers.authorization = `Bearer ${token}`\n\n const init: RequestInit = { method: 'GET', headers }\n if (options.auth?.includeCredentials) init.credentials = 'include'\n\n const res = await doFetch(url, init)\n if (!res.ok) {\n throw new Error(`[pwfabric-embed] surface fetch failed: ${res.status} ${res.statusText}`)\n }\n const data = unwrap(await res.json())\n const def = data.definition ?? {}\n\n // Blocks: rootBlock.children OR blocks[], normalised like the host.\n let blocks: Block[] = []\n if (def.rootBlock) {\n blocks = (def.rootBlock.children ?? []).map(toRuntimeBlock)\n } else if (def.blocks) {\n blocks = def.blocks.map(toRuntimeBlock)\n }\n\n // Capabilities normalised with required:false default (host parity).\n const capabilities: SurfaceCapabilityRequirement[] = (def.capabilities ?? []).map((c) => ({\n capability: c.capability,\n required: c.required ?? false,\n ...(c.config !== undefined ? { config: c.config } : {}),\n }))\n\n // Inject Authorization into REST data sources, matching the host's authedSources.\n if (token && Array.isArray(def.dataSources)) {\n const authed = def.dataSources.map((ds) => {\n const d = ds as { kind?: string; headers?: Record<string, string> }\n return d.kind === 'rest'\n ? { ...d, headers: { ...d.headers, Authorization: `Bearer ${token}` } }\n : d\n })\n // Thread data sources through the persistence capability config so the\n // DataBoundSurfaceRenderer picks them up (consolidated shape).\n // Either spelling: a short-form entry that goes unrecognised here does not\n // just get missed, it gets DUPLICATED — the branch below adds a second\n // persistence capability alongside the one already there.\n const existing = capabilities.find((c) => isCapability(c, 'platform/persistence'))\n if (existing) {\n ;(existing as { config?: Record<string, unknown> }).config = {\n ...(existing.config ?? {}),\n dataSources: authed,\n ...(def.state ? { initialState: def.state } : {}),\n }\n } else {\n capabilities.push({\n capability: 'platform/persistence',\n required: false,\n config: { dataSources: authed, ...(def.state ? { initialState: def.state } : {}) },\n })\n }\n }\n\n // Appearance ref: wrap theme + styleVariables (consolidated shape).\n // Config only — the `use` atom id retired with the appearance engine\n //a theme is data, nothing is resolved by reference.\n const appearance: RenderableSurface['appearance'] | undefined =\n def.theme || def.styleVariables\n ? {\n config: {\n ...(def.theme ? { theme: def.theme } : {}),\n ...(def.styleVariables ? { styleVariables: def.styleVariables } : {}),\n },\n }\n : undefined\n\n const surface: RenderableSurface = {\n blocks,\n ...(appearance ? { appearance } : {}),\n ...(capabilities.length > 0 ? { capabilities } : {}),\n id: data.surfaceId,\n }\n\n return {\n surface,\n dynamicBlocks: grantsToDescriptors(data.renderGrants ?? []),\n surfaceId: data.surfaceId,\n worldId: data.worldId,\n ...(data.layout ? { layout: data.layout } : {}),\n }\n}\n","/**\n * Self-contained fat HTML builder.\n *\n * Produces a single HTML string that renders a surface fully offline:\n * - the surface JSON in a `<script type=\"application/pw-surface+json\">` tag,\n * - the block descriptors in `<script type=\"application/pw-blocks+json\">`\n * (with `moduleUrl` left as-is — callers should pass `data:` URLs for true\n * offline self-containment + matching integrity hashes),\n * - the appearance ref in `<script type=\"application/pw-appearance+json\">`,\n * - the bundled `embed.js` IIFE inlined verbatim in a `<script>` tag,\n * - a bootstrap call:\n * `PWFabric.render('#pw-root', { surface }, { mode:'fat', blocks, appearance })`.\n *\n * Pure function — no I/O. The local preview tool reads `dist/embed.js` off\n * disk and passes its contents as `embedJs`; this module never touches the\n * filesystem.\n *\n * @module @pwfabric/embed/build-fat-html\n */\n\nimport type { DynamicBlockDescriptor } from '@pwfabric/contracts'\nimport type { RenderableSurface } from '@pwfabric/runtime'\n\nexport interface BuildFatHtmlOptions {\n /** Surface JSON to inline + render. */\n readonly surface: RenderableSurface\n /** Block descriptors (prefer `data:` moduleUrls for offline). */\n readonly blocks?: readonly DynamicBlockDescriptor[]\n /** Appearance ref (defaults to `surface.appearance`). */\n readonly appearance?: RenderableSurface['appearance']\n /** The full contents of the built `dist/embed.js` IIFE. */\n readonly embedJs: string\n /** `<title>` of the page. */\n readonly title?: string\n /** Optional `lang` attribute. */\n readonly lang?: string\n}\n\n// Char codes for the JS-illegal line/paragraph separators (kept out of source\n// text so the file stays ASCII-clean).\nconst LS = 0x2028\nconst PS = 0x2029\nconst LINE_SEPS = new RegExp(`[${String.fromCharCode(LS)}${String.fromCharCode(PS)}]`, 'g')\n\n/**\n * Escape a JSON payload for safe inlining inside a `<script>` element.\n * Breaks `</script`/HTML-comment sequences and escapes the line/paragraph\n * separators that are invalid in JS string literals.\n */\nfunction safeJson(value: unknown): string {\n return JSON.stringify(value)\n .replace(/</g, '\\\\u003c')\n .replace(/>/g, '\\\\u003e')\n .replace(/&/g, '\\\\u0026')\n .replace(LINE_SEPS, (ch) => '\\\\u' + ch.charCodeAt(0).toString(16).padStart(4, '0'))\n}\n\n/** Minimal HTML-text escaper for the <title>. */\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n}\n\n/**\n * Build a fully self-contained HTML document string.\n */\nexport function buildFatHtml(options: BuildFatHtmlOptions): string {\n const { surface, embedJs } = options\n const blocks = options.blocks ?? []\n const appearance = options.appearance ?? surface.appearance\n const title = options.title ?? 'Surface'\n const lang = options.lang ?? 'en'\n\n const surfaceJson = safeJson(surface)\n const blocksJson = safeJson(blocks)\n const appearanceJson = safeJson(appearance ?? null)\n\n return `<!DOCTYPE html>\n<html lang=\"${lang}\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<title>${escapeHtml(title)}</title>\n<style>html,body{margin:0;padding:0}#pw-root{min-height:100vh}</style>\n</head>\n<body>\n<div id=\"pw-root\"></div>\n<script type=\"application/pw-surface+json\">${surfaceJson}</script>\n<script type=\"application/pw-blocks+json\">${blocksJson}</script>\n<script type=\"application/pw-appearance+json\">${appearanceJson}</script>\n<script>${embedJs}</script>\n<script>\n(function(){\n var surface = JSON.parse(document.querySelector('script[type=\"application/pw-surface+json\"]').textContent);\n var blocks = JSON.parse(document.querySelector('script[type=\"application/pw-blocks+json\"]').textContent);\n var appearance = JSON.parse(document.querySelector('script[type=\"application/pw-appearance+json\"]').textContent);\n PWFabric.render('#pw-root', { surface: surface }, { mode: 'fat', blocks: blocks, appearance: appearance });\n})();\n</script>\n</body>\n</html>`\n}\n","/**\n * @pwfabric/embed\n *\n * Portable embed runtime — renders a PWFabric CanonicalSurface anywhere, using\n * the REAL `SurfaceRenderer` from `@pwfabric/runtime`.\n *\n * Consumed two ways:\n * - as a built artifact — `assembleWebApp` takes the bundle as an `embedJs`\n * string and ships it into every export's `assets/`;\n * - as a dependency — a host API can resolve `dist/embed.js` out of\n * `node_modules` rather than keeping a committed copy (a vendored copy\n * goes stale silently; a package dependency is version-gated).\n *\n * Two modes:\n * - **thin** — fetch surface + render grants from the API (like a hosted surface page).\n * - **fat** — render an inline surface + block bundles + appearance fully\n * offline, no backend.\n *\n * Public entry: `PWFabric.render(target, source, options?)`. A `data-pw-surface`\n * DOM auto-loader is also wired on load.\n *\n * @module @pwfabric/embed\n */\n\nimport { mountSurface, type SurfaceMountHandle, type RenderCoreOptions } from './render-core.js'\nimport { renderFat, type RenderFatOptions } from './fat.js'\nimport { loadThin, type ThinAuth, type ThinSurfaceRef } from './thin.js'\nimport type {\n DynamicBlockDescriptor,\n BreakpointName,\n} from '@pwfabric/contracts'\nimport type {\n CapabilityProvider,\n EntityFacade,\n ImageAdapter,\n SurfaceEvent,\n RenderableSurface,\n BlockComponentRegistry,\n SurfaceConnectionsValue,\n DataServiceConfig,\n SurfaceDataCache,\n} from '@pwfabric/runtime'\n\n// Re-export the building blocks for bundler consumers.\nexport { renderFat, fatCoreOptions } from './fat.js'\nexport { loadThin, grantsToDescriptors } from './thin.js'\nexport { buildFatHtml } from './build-fat-html.js'\nexport type { BuildFatHtmlOptions } from './build-fat-html.js'\nexport {\n mountSurface,\n createSurfaceElement,\n needsDataBoundRenderer,\n resolveTarget,\n missingBlockTypes,\n RebuildNeededBlock,\n} from './render-core.js'\nexport type { RenderCoreOptions, SurfaceMountHandle } from './render-core.js'\nexport type { RenderFatOptions, FatMountHandle } from './fat.js'\nexport type { LoadThinOptions, LoadThinResult, ThinAuth, ThinSurfaceRef } from './thin.js'\nexport {\n createOfflineEntityFacade,\n createOfflineNavigationProvider,\n staticPersistenceCapability,\n} from './capabilities-stub.js'\n\n// ============================================================\n// PUBLIC OPTION TYPES\n// ============================================================\n\nexport type EmbedMode = 'thin' | 'fat'\n\n/**\n * Source: either a reference to fetch (thin) or an inline surface (fat).\n */\nexport type EmbedSource =\n | { readonly surfaceId: string }\n | { readonly tenantSlug: string; readonly surfaceSlug: string }\n | { readonly surface: RenderableSurface }\n\nexport interface EmbedOptions {\n /** `thin` (fetch) or `fat` (inline/offline). Auto-detected from source when omitted. */\n readonly mode?: EmbedMode\n\n // ── thin ──────────────────────────────────────────────\n /** API origin for thin mode (e.g. https://api.example.com). */\n readonly apiBaseUrl?: string\n /** Auth for thin mode. */\n readonly auth?: ThinAuth\n /** Custom fetch implementation (test/non-browser). */\n readonly fetchImpl?: typeof fetch\n\n // ── fat ───────────────────────────────────────────────\n /** Inline block bundle descriptors (fat). */\n readonly blocks?: readonly DynamicBlockDescriptor[]\n /** Inline appearance ref (fat); falls back to surface.appearance. */\n readonly appearance?: RenderableSurface['appearance']\n /** Hydrate existing server-rendered markup instead of a fresh mount (fat). */\n readonly hydrate?: boolean\n /** Capability providers (fat). */\n readonly capabilities?: CapabilityProvider[]\n /** Entity facade override (fat). */\n readonly entityFacade?: EntityFacade\n /** Connector/provider engine registry + connections (fat embed). */\n readonly connections?: SurfaceConnectionsValue\n /**\n * Configuration for the renderer's DataService — the host's own API origin\n * (so the platform store can be called with its cookie and nobody else can)\n * and the token resolver for `authProviderRef`.\n */\n readonly dataServiceConfig?: DataServiceConfig\n readonly loadingStrategy?: 'gate' | 'immediate'\n readonly dataCache?: SurfaceDataCache\n\n\n // ── shared render passthrough ─────────────────────────\n readonly theme?: 'light' | 'dark'\n readonly viewport?: BreakpointName\n readonly basePath?: string\n readonly imageAdapter?: ImageAdapter\n readonly interactionMode?: 'live' | 'inert'\n readonly onEvent?: (event: SurfaceEvent) => void\n readonly gap?: number\n readonly padding?: number\n /** Custom block component overrides (test/preview seams). */\n readonly components?: Partial<BlockComponentRegistry>\n /** Visible placeholder for block types nothing can render (preview hosts). */\n readonly placeholderMissingBlocks?: boolean\n\n // ── lifecycle callbacks ───────────────────────────────\n readonly onReady?: (handle: SurfaceMountHandle) => void\n readonly onError?: (error: unknown) => void\n}\n\n// ============================================================\n// CORE RENDER ENTRY\n// ============================================================\n\nfunction isInlineSurface(source: EmbedSource): source is { surface: RenderableSurface } {\n return 'surface' in source\n}\n\nfunction detectMode(source: EmbedSource, options?: EmbedOptions): EmbedMode {\n if (options?.mode) return options.mode\n return isInlineSurface(source) ? 'fat' : 'thin'\n}\n\n/**\n * Shared render-option assembly from EmbedOptions → RenderCore/RenderFat opts.\n */\nfunction passthrough(options?: EmbedOptions): Partial<RenderCoreOptions> {\n const o = options ?? {}\n return {\n ...(o.theme !== undefined ? { theme: o.theme } : {}),\n ...(o.viewport !== undefined ? { viewport: o.viewport } : {}),\n ...(o.basePath !== undefined ? { basePath: o.basePath } : {}),\n ...(o.imageAdapter !== undefined ? { imageAdapter: o.imageAdapter } : {}),\n ...(o.interactionMode !== undefined ? { interactionMode: o.interactionMode } : {}),\n ...(o.onEvent !== undefined ? { onEvent: o.onEvent } : {}),\n ...(o.gap !== undefined ? { gap: o.gap } : {}),\n ...(o.padding !== undefined ? { padding: o.padding } : {}),\n ...(o.components !== undefined ? { components: o.components } : {}),\n ...(o.loadingStrategy !== undefined ? { loadingStrategy: o.loadingStrategy } : {}),\n ...(o.dataCache !== undefined ? { dataCache: o.dataCache } : {}),\n ...(o.placeholderMissingBlocks !== undefined ? { placeholderMissingBlocks: o.placeholderMissingBlocks } : {}),\n }\n}\n\n/**\n * Render a surface into `target`.\n *\n * @param target An HTMLElement or CSS selector string.\n * @param source `{ surfaceId }` / `{ tenantSlug, surfaceSlug }` (thin) or\n * `{ surface }` (fat).\n * @param options Mode + transport + render options.\n * @returns A promise resolving to the mount handle.\n */\nexport async function render(\n target: HTMLElement | string,\n source: EmbedSource,\n options?: EmbedOptions\n): Promise<SurfaceMountHandle> {\n const o = options ?? {}\n try {\n const mode = detectMode(source, options)\n\n if (mode === 'fat') {\n if (!isInlineSurface(source)) {\n throw new Error('[pwfabric-embed] fat mode requires an inline { surface }')\n }\n const fatOpts: RenderFatOptions = {\n surface: source.surface,\n ...(o.blocks ? { blocks: o.blocks } : {}),\n ...(o.appearance ? { appearance: o.appearance } : {}),\n ...(o.hydrate ? { hydrate: true } : {}),\n ...(o.capabilities ? { capabilities: o.capabilities } : {}),\n ...(o.entityFacade ? { entityFacade: o.entityFacade } : {}),\n ...(o.connections ? { connections: o.connections } : {}),\n ...(o.dataServiceConfig ? { dataServiceConfig: o.dataServiceConfig } : {}),\n ...passthrough(options),\n }\n const handle = renderFat(target, fatOpts)\n o.onReady?.(handle)\n return handle\n }\n\n // thin mode\n if (isInlineSurface(source)) {\n throw new Error('[pwfabric-embed] thin mode requires a { surfaceId } or slug reference')\n }\n if (!o.apiBaseUrl) {\n throw new Error('[pwfabric-embed] thin mode requires `apiBaseUrl`')\n }\n\n const ref: ThinSurfaceRef =\n 'surfaceId' in source\n ? { surfaceId: source.surfaceId }\n : { tenantSlug: (source as { tenantSlug: string }).tenantSlug, surfaceSlug: (source as { surfaceSlug: string }).surfaceSlug }\n const loaded = await loadThin(ref, {\n apiBaseUrl: o.apiBaseUrl,\n ...(o.auth ? { auth: o.auth } : {}),\n ...(o.fetchImpl ? { fetchImpl: o.fetchImpl } : {}),\n })\n\n const core: RenderCoreOptions = {\n surface: loaded.surface,\n ...(loaded.dynamicBlocks.length > 0 ? { dynamicBlocks: loaded.dynamicBlocks } : {}),\n ...(o.capabilities ? { capabilities: o.capabilities } : {}),\n ...(o.entityFacade ? { entityFacade: o.entityFacade } : {}),\n ...(loaded.layout?.gap !== undefined ? { gap: loaded.layout.gap } : {}),\n ...(loaded.layout?.padding !== undefined ? { padding: loaded.layout.padding } : {}),\n ...passthrough(options),\n }\n const handle = mountSurface(target, core)\n o.onReady?.(handle)\n return handle\n } catch (err) {\n if (o.onError) {\n o.onError(err)\n // Re-throw so callers awaiting the promise still observe the failure.\n }\n throw err\n }\n}\n\n// ============================================================\n// DOM AUTO-LOADER (data-pw-surface)\n// ============================================================\n\n/**\n * Scan the DOM for `[data-pw-surface]` containers and render each.\n *\n * Attribute contract:\n * - `data-pw-surface` — surfaceId (thin) OR `\"inline\"` for fat.\n * - `data-pw-mode` — `\"thin\"` | `\"fat\"` (optional; auto-detected).\n * - `data-pw-api` — apiBaseUrl (thin).\n * - `data-pw-tenant` + `data-pw-slug` — slug pair (thin, overrides surfaceId).\n * - `data-pw-theme` — `\"light\"` | `\"dark\"`.\n * - `data-pw-token` — bearer token (thin).\n *\n * For fat/inline rendering the element should contain sibling scripts:\n * `<script type=\"application/pw-surface+json\">…</script>`\n * `<script type=\"application/pw-blocks+json\">…</script>` (optional)\n * `<script type=\"application/pw-appearance+json\">…</script>` (optional)\n */\nfunction readInlineJson<T>(root: ParentNode, type: string): T | undefined {\n const el = root.querySelector(`script[type=\"application/${type}+json\"]`)\n if (!el?.textContent) return undefined\n try {\n return JSON.parse(el.textContent) as T\n } catch {\n return undefined\n }\n}\n\nfunction hydrateElement(el: HTMLElement): void {\n const ds = el.dataset\n const surfaceAttr = ds.pwSurface\n const declaredMode = ds.pwMode as EmbedMode | undefined\n\n // Inline surface scripts may live inside the container or as siblings.\n const scope: ParentNode = el.querySelector('script[type^=\"application/pw-\"]')\n ? el\n : el.parentNode ?? el\n const inlineSurface = readInlineJson<RenderableSurface>(scope, 'pw-surface')\n\n const isFat = declaredMode === 'fat' || (!declaredMode && (surfaceAttr === 'inline' || !!inlineSurface))\n\n const common: EmbedOptions = {\n ...(ds.pwTheme ? { theme: ds.pwTheme as 'light' | 'dark' } : {}),\n }\n\n if (isFat) {\n if (!inlineSurface) {\n // Nothing to render — leave a console hint and bail.\n console.warn('[pwfabric-embed] data-pw-surface=\"inline\" but no inline surface JSON found')\n return\n }\n const blocks = readInlineJson<DynamicBlockDescriptor[]>(scope, 'pw-blocks')\n const appearance = readInlineJson<RenderableSurface['appearance']>(scope, 'pw-appearance')\n void render(el, { surface: inlineSurface }, {\n ...common,\n mode: 'fat',\n ...(blocks ? { blocks } : {}),\n ...(appearance ? { appearance } : {}),\n })\n return\n }\n\n // thin\n const apiBaseUrl = ds.pwApi\n if (!apiBaseUrl) {\n console.warn('[pwfabric-embed] data-pw-surface thin mode requires data-pw-api')\n return\n }\n const auth = ds.pwToken ? { accessToken: ds.pwToken } : undefined\n const source: EmbedSource =\n ds.pwTenant && ds.pwSlug\n ? { tenantSlug: ds.pwTenant, surfaceSlug: ds.pwSlug }\n : { surfaceId: surfaceAttr ?? '' }\n\n void render(el, source, {\n ...common,\n mode: 'thin',\n apiBaseUrl,\n ...(auth ? { auth } : {}),\n })\n}\n\n/**\n * Scan + hydrate all `[data-pw-surface]` elements currently in the document.\n * Idempotent: elements already hydrated (marked with `data-pw-hydrated`) skip.\n */\nexport function autoload(root: ParentNode = document): void {\n const els = root.querySelectorAll<HTMLElement>('[data-pw-surface]')\n els.forEach((el) => {\n if (el.dataset.pwHydrated === 'true') return\n el.dataset.pwHydrated = 'true'\n hydrateElement(el)\n })\n}\n\n// Wire the auto-loader once the DOM is ready (browser only).\nif (typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => autoload())\n } else {\n // Defer to a microtask so a synchronous `PWFabric.render` call right after\n // the script tag still wins ordering if the host prefers manual control.\n queueMicrotask(() => autoload())\n }\n}\n\n// ============================================================\n// NAMESPACE (mirrors the IIFE global `PWFabric`)\n// ============================================================\n\nexport const PWFabric = {\n render,\n renderFat,\n loadThin,\n autoload,\n}\n\nexport default PWFabric\n"]}