@bgub/fig-dom 2.1.0 → 2.2.1

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/CHANGELOG.md CHANGED
@@ -1,3 +1,11 @@
1
+ ## @bgub/fig-dom@2.2.0
2
+
3
+ ### Stream transfer dependencies after the reveal
4
+
5
+ Streamed Suspense data now sends a read's `transfer` dependencies after the boundary's reveal instead of ahead of it, so their size no longer delays the reveal. A marker for each key goes ahead of the reveal. The browser holds a load of a marked key until the key's form arrives, and the form seeds that load as `transferred`. If the document finishes loading without the form, the load runs without one. A seeded TanStack DB collection therefore still imports its rows and sync metadata before its sync starts. Shell reads, `getData()`, and Payload data rows are unchanged.
6
+
7
+ A direct reader in another boundary can receive a queued dependency form without waiting for the original boundary to finish. Queued forms also remain available to `takeData()`, and each form is delivered only once.
8
+
1
9
  ## @bgub/fig-dom@2.1.0
2
10
 
3
11
  ### Add intentional browser-only rendering
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./renderer-BPuY1pdy.js";import{STREAMED_DATA_PROPERTY as s,assertPayloadCodecMatches as c,createPortalNode as l,decodePayloadDataEntries as u,jsonPayloadCodec as d,loadContextCapabilities as f,readBrowser as p}from"@bgub/fig/internal";import{dataResource as m,readData as h}from"@bgub/fig";import{decodePayloadStream as g}from"@bgub/fig/payload";function _(e,t,n){let r=e.ownerDocument??e,i=r[s]??={},a=i[t];if(a!==void 0&&!Array.isArray(a))return;let o={push(...e){for(let t of e)n.hydrateMissing(u(t))}};return i[t]=o,a!==void 0&&o.push(...a),()=>{i[t]===o&&delete i[t]}}const v=()=>void 0;async function y(e,t,r={}){let{signal:i}=t;if(i.aborted)throw await e.body?.cancel().catch(v),b(i);if(!e.ok)throw await e.body?.cancel().catch(v),Error(`Payload request failed with status ${e.status}.`);let a=e.body;if(a===null)throw Error(`Payload response did not include a body.`);try{c(d,e.headers.get(`content-type`))}catch(e){throw await a.cancel().catch(v),e}let o=f(t);return g(a,{hydrate:o?.hydrate,onHoleError:o?.attributeError,onStreamDone:e=>{},prepareAssets:r.prepareAssets??(e=>n(e)),retainAssets:r.retainAssets,resolveClientReference:r.resolveClientReference,signal:i})}function b(e){return e.reason??Error(`Payload request aborted.`)}function x(e){let t=new WeakMap,n=1;function r(e){if(e===null)return null;if(e===void 0)return[`undefined`];if(typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isNaN(e)?[`number`,`NaN`]:e===1/0?[`number`,`Infinity`]:e===-1/0?[`number`,`-Infinity`]:Object.is(e,-0)?[`number`,`-0`]:e;if(typeof e==`bigint`)return[`bigint`,e.toString()];if(typeof e==`symbol`){let t=Symbol.keyFor(e);if(t===void 0)throw Error(`Only global Symbol.for symbols can be serialized.`);return[`symbol`,t]}if(typeof e==`function`)throw Error(`Functions cannot be serialized into the payload.`);if(e instanceof Date){let t=e.toJSON();if(t===null)throw Error(`Invalid Date values cannot be serialized.`);return[`date`,t]}let i=t.get(e);if(i!==void 0)return[`ref`,i];let a=n++;if(t.set(e,a),Array.isArray(e))return[`array`,a,e.map(r)];if(e instanceof Map)return[`map`,a,Array.from(e,([e,t])=>[r(e),r(t)])];if(e instanceof Set)return[`set`,a,Array.from(e,r)];let o=Object.getPrototypeOf(e);if(o!==Object.prototype&&o!==null)throw Error(`Cannot serialize ${o?.constructor?.name??`object`} into the payload.`);let s=e;return[`object`,a,Object.keys(s).sort().map(e=>[e,r(s[e])])]}return r(e)}function S(e){let t=t=>{let n=C(t);return[...e.key,e.cacheKey===void 0?n:e.cacheKey(t)]},n=m({debugArgs:e.cacheKey===void 0?void 0:C,key:t,load:async(n,r)=>{let i=await e.load(n,{key:f(r)?.key??t(n),signal:r.signal});return y(i instanceof Response?i:new Response(i.stream,{headers:{"content-type":i.contentType}}),r,{prepareAssets:e.prepareAssets??e.load.prepareAssets,resolveClientReference:e.resolveClientReference??e.load.resolveClientReference,retainAssets:e.retainAssets??e.load.retainAssets})}}),r=Object.assign(function(e){return w(e),h(r,e)},n);return Object.defineProperty(r,"displayName",{configurable:!0,value:`Payload(${e.key[0]})`}),r}function C(e){return w(e),x(e)}function w(e){if(Object.hasOwn(e,`children`))throw Error(`Payload components do not accept children.`)}function T(e){p(e)}const E=o.flushSync;function D(e,t){let n=o.createRoot(e,t);return i(e,{run:e=>n.data.run(e)}),A(n,e)}function O(e,t,n){let r=o.hydrateRoot(e,t,n);return i(e,{hydrate:(t,n)=>o.hydrateTarget(e,t,n),run:e=>r.data.run(e)}),A(r,e,_(e,n?.identifierPrefix??``,r.data))}function k(e,t,n=null){return l(e,t,n)}function A(e,n,r){return{...e,unmount:()=>{r?.(),e.unmount(),t(n)}}}export{r as composeBind,S as createPayloadComponent,k as createPortal,D as createRoot,E as flushSync,a as hostBinding,O as hydrateRoot,n as insertAssetResources,e as on,T as readBrowser};
1
+ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./renderer-BPuY1pdy.js";import{STREAMED_DATA_PROPERTY as s,assertPayloadCodecMatches as c,createPortalNode as l,decodePayloadDataEntries as u,jsonPayloadCodec as d,loadContextCapabilities as f,readBrowser as p}from"@bgub/fig/internal";import{dataResource as m,readData as h}from"@bgub/fig";import{decodePayloadStream as g}from"@bgub/fig/payload";function _(e,t,n){let r=e.ownerDocument??e,i=r,a=i[s]??={},o=a[t];if(o!==void 0&&!Array.isArray(o))return;let c=r.readyState===`loading`,l={push(...e){for(let t of e){let e=[],r=[];for(let n of t)`pending`in n?e.push(n.key):r.push(n);c&&e.length>0&&n.awaitTransferForms(e),r.length>0&&n.hydrateMissing(u(r))}}},d=()=>{c=!1,n.releaseTransferForms()};return a[t]=l,o!==void 0&&l.push(...o),c&&r.addEventListener(`DOMContentLoaded`,d,{once:!0}),()=>{c&&r.removeEventListener(`DOMContentLoaded`,d),a[t]===l&&delete a[t]}}const v=()=>void 0;async function y(e,t,r={}){let{signal:i}=t;if(i.aborted)throw await e.body?.cancel().catch(v),b(i);if(!e.ok)throw await e.body?.cancel().catch(v),Error(`Payload request failed with status ${e.status}.`);let a=e.body;if(a===null)throw Error(`Payload response did not include a body.`);try{c(d,e.headers.get(`content-type`))}catch(e){throw await a.cancel().catch(v),e}let o=f(t);return g(a,{hydrate:o?.hydrate,onHoleError:o?.attributeError,onStreamDone:e=>{},prepareAssets:r.prepareAssets??(e=>n(e)),retainAssets:r.retainAssets,resolveClientReference:r.resolveClientReference,signal:i})}function b(e){return e.reason??Error(`Payload request aborted.`)}function x(e){let t=new WeakMap,n=1;function r(e){if(e===null)return null;if(e===void 0)return[`undefined`];if(typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isNaN(e)?[`number`,`NaN`]:e===1/0?[`number`,`Infinity`]:e===-1/0?[`number`,`-Infinity`]:Object.is(e,-0)?[`number`,`-0`]:e;if(typeof e==`bigint`)return[`bigint`,e.toString()];if(typeof e==`symbol`){let t=Symbol.keyFor(e);if(t===void 0)throw Error(`Only global Symbol.for symbols can be serialized.`);return[`symbol`,t]}if(typeof e==`function`)throw Error(`Functions cannot be serialized into the payload.`);if(e instanceof Date){let t=e.toJSON();if(t===null)throw Error(`Invalid Date values cannot be serialized.`);return[`date`,t]}let i=t.get(e);if(i!==void 0)return[`ref`,i];let a=n++;if(t.set(e,a),Array.isArray(e))return[`array`,a,e.map(r)];if(e instanceof Map)return[`map`,a,Array.from(e,([e,t])=>[r(e),r(t)])];if(e instanceof Set)return[`set`,a,Array.from(e,r)];let o=Object.getPrototypeOf(e);if(o!==Object.prototype&&o!==null)throw Error(`Cannot serialize ${o?.constructor?.name??`object`} into the payload.`);let s=e;return[`object`,a,Object.keys(s).sort().map(e=>[e,r(s[e])])]}return r(e)}function S(e){let t=t=>{let n=C(t);return[...e.key,e.cacheKey===void 0?n:e.cacheKey(t)]},n=m({debugArgs:e.cacheKey===void 0?void 0:C,key:t,load:async(n,r)=>{let i=await e.load(n,{key:f(r)?.key??t(n),signal:r.signal});return y(i instanceof Response?i:new Response(i.stream,{headers:{"content-type":i.contentType}}),r,{prepareAssets:e.prepareAssets??e.load.prepareAssets,resolveClientReference:e.resolveClientReference??e.load.resolveClientReference,retainAssets:e.retainAssets??e.load.retainAssets})}}),r=Object.assign(function(e){return w(e),h(r,e)},n);return Object.defineProperty(r,"displayName",{configurable:!0,value:`Payload(${e.key[0]})`}),r}function C(e){return w(e),x(e)}function w(e){if(Object.hasOwn(e,`children`))throw Error(`Payload components do not accept children.`)}function T(e){p(e)}const E=o.flushSync;function D(e,t){let n=o.createRoot(e,t);return i(e,{run:e=>n.data.run(e)}),A(n,e)}function O(e,t,n){let r=o.hydrateRoot(e,t,n);return i(e,{hydrate:(t,n)=>o.hydrateTarget(e,t,n),run:e=>r.data.run(e)}),A(r,e,_(e,n?.identifierPrefix??``,r.data))}function k(e,t,n=null){return l(e,t,n)}function A(e,n,r){return{...e,unmount:()=>{r?.(),e.unmount(),t(n)}}}export{r as composeBind,S as createPayloadComponent,k as createPortal,D as createRoot,E as flushSync,a as hostBinding,O as hydrateRoot,n as insertAssetResources,e as on,T as readBrowser};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/streamed-data.ts","../src/payload-decoder.ts","../src/payload-key.ts","../src/payload-component.ts","../src/index.ts"],"sourcesContent":["import {\n decodePayloadDataEntries,\n type FigDataStore,\n type PayloadDataHydrationEntry,\n STREAMED_DATA_PROPERTY,\n} from \"@bgub/fig/internal\";\nimport type { Container } from \"./events.ts\";\n\ntype StreamedDataRows = PayloadDataHydrationEntry[];\n\n// Rows queued before a root claims the prefix, or that root's receiver.\ninterface StreamedDataQueue {\n push(...batches: StreamedDataRows[]): unknown;\n}\n\ntype StreamedDataCarrier = {\n [STREAMED_DATA_PROPERTY]?: Record<string, StreamedDataQueue>;\n};\n\n// The server's `d` operation pushes rows per identifierPrefix. The first\n// hydrating root with that prefix drains the queued rows and replaces the\n// queue with a receiver that applies later rows directly, owning the prefix\n// until it unmounts. Rows fill only entries the client has no value for, so a\n// late row never overwrites client state.\nexport function adoptStreamedData(\n container: Container,\n identifierPrefix: string,\n store: FigDataStore,\n): (() => void) | undefined {\n const carrier = (container.ownerDocument ?? container) as StreamedDataCarrier;\n const queues = (carrier[STREAMED_DATA_PROPERTY] ??= {});\n const queued = queues[identifierPrefix];\n if (queued !== undefined && !Array.isArray(queued)) return undefined;\n\n const receiver: StreamedDataQueue = {\n push(...batches) {\n for (const rows of batches) {\n store.hydrateMissing(decodePayloadDataEntries(rows));\n }\n },\n };\n queues[identifierPrefix] = receiver;\n if (queued !== undefined) receiver.push(...(queued as StreamedDataRows[]));\n return () => {\n if (queues[identifierPrefix] === receiver) delete queues[identifierPrefix];\n };\n}\n","import type { AwaitedFigNode, DataResourceLoadContext } from \"@bgub/fig\";\nimport {\n assertPayloadCodecMatches,\n jsonPayloadCodec,\n loadContextCapabilities,\n} from \"@bgub/fig/internal\";\nimport {\n decodePayloadStream,\n type PayloadDecodeOptions,\n} from \"@bgub/fig/payload\";\nimport { insertAssetResources } from \"./asset-resources.ts\";\n\ndeclare const __FIG_DEV__: boolean | undefined;\n\nconst __DEV__ = typeof __FIG_DEV__ === \"boolean\" ? __FIG_DEV__ : false;\nconst noop = (): void => undefined;\n\nexport type PayloadDecoderOptions = Pick<\n PayloadDecodeOptions,\n \"prepareAssets\" | \"resolveClientReference\" | \"retainAssets\"\n>;\n\n/**\n * Decodes a validated Payload response within one data-resource generation.\n * The root becomes the entry value, streamed holes keep filling for the\n * generation's lifetime, `data` rows hydrate through its guarded capability,\n * and discovered assets enter the document with dependent reveal gates.\n */\nexport async function decodePayloadResponse(\n response: Response,\n context: DataResourceLoadContext,\n options: PayloadDecoderOptions = {},\n): Promise<AwaitedFigNode> {\n const { signal } = context;\n if (signal.aborted) {\n await response.body?.cancel().catch(noop);\n throw abortReason(signal);\n }\n if (!response.ok) {\n await response.body?.cancel().catch(noop);\n throw new Error(`Payload request failed with status ${response.status}.`);\n }\n const body = response.body;\n if (body === null) {\n throw new Error(\"Payload response did not include a body.\");\n }\n try {\n assertPayloadCodecMatches(\n jsonPayloadCodec,\n response.headers.get(\"content-type\"),\n );\n } catch (error) {\n await body.cancel().catch(noop);\n throw error;\n }\n\n const capabilities = loadContextCapabilities(context);\n return decodePayloadStream(body, {\n // Absent outside a data store: data rows are ignored rather than hydrated.\n hydrate: capabilities?.hydrate,\n onHoleError: capabilities?.attributeError,\n // Post-root failures surface through the rejected holes they strand;\n // observing the stream end keeps a failure that no longer has a pending\n // slot from being silently discarded in development.\n onStreamDone: (result) => {\n if (__DEV__ && result.status === \"failed\") {\n console.error(\n \"Payload decode failed after its root value published:\",\n result.error,\n );\n }\n },\n prepareAssets:\n options.prepareAssets ?? ((assets) => insertAssetResources(assets)),\n retainAssets: options.retainAssets,\n resolveClientReference: options.resolveClientReference,\n signal,\n });\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new Error(\"Payload request aborted.\");\n}\n","import type { DataResourceKeyInput } from \"@bgub/fig\";\n\nexport function encodePayloadKey(value: unknown): DataResourceKeyInput {\n const ids = new WeakMap<object, number>();\n let nextId = 1;\n\n function encode(value: unknown): DataResourceKeyInput {\n if (value === null) return null;\n if (value === undefined) return [\"undefined\"];\n if (typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") {\n if (Number.isNaN(value)) return [\"number\", \"NaN\"];\n if (value === Infinity) return [\"number\", \"Infinity\"];\n if (value === -Infinity) return [\"number\", \"-Infinity\"];\n return Object.is(value, -0) ? [\"number\", \"-0\"] : value;\n }\n if (typeof value === \"bigint\") return [\"bigint\", value.toString()];\n if (typeof value === \"symbol\") {\n const key = Symbol.keyFor(value);\n if (key === undefined) {\n throw new Error(\"Only global Symbol.for symbols can be serialized.\");\n }\n return [\"symbol\", key];\n }\n if (typeof value === \"function\") {\n throw new Error(\"Functions cannot be serialized into the payload.\");\n }\n if (value instanceof Date) {\n const json = value.toJSON();\n if (json === null) {\n throw new Error(\"Invalid Date values cannot be serialized.\");\n }\n return [\"date\", json];\n }\n\n const existing = ids.get(value);\n if (existing !== undefined) return [\"ref\", existing];\n const id = nextId++;\n ids.set(value, id);\n\n if (Array.isArray(value)) {\n return [\"array\", id, value.map(encode)];\n }\n if (value instanceof Map) {\n return [\n \"map\",\n id,\n Array.from(value, ([key, item]) => [encode(key), encode(item)]),\n ];\n }\n if (value instanceof Set) {\n return [\"set\", id, Array.from(value, encode)];\n }\n\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(\n `Cannot serialize ${prototype?.constructor?.name ?? \"object\"} into the payload.`,\n );\n }\n const record = value as Record<string, unknown>;\n return [\n \"object\",\n id,\n Object.keys(record)\n .sort()\n .map((key) => [key, encode(record[key])]),\n ];\n }\n\n return encode(value);\n}\n","import {\n type AwaitedFigNode,\n dataResource,\n type DataResource,\n type DataResourceKey,\n type DataResourceKeyInput,\n type FigNode,\n readData,\n} from \"@bgub/fig\";\nimport { loadContextCapabilities } from \"@bgub/fig/internal\";\nimport {\n decodePayloadResponse,\n type PayloadDecoderOptions,\n} from \"./payload-decoder.ts\";\nimport { encodePayloadKey } from \"./payload-key.ts\";\n\n/** Describes payload source. */\nexport type PayloadSource =\n | Response\n | {\n contentType: string;\n stream: ReadableStream<Uint8Array>;\n };\n\n/** Describes payload component load context. */\nexport interface PayloadComponentLoadContext {\n key: DataResourceKey;\n signal: AbortSignal;\n}\n\n/** Describes payload component loader. */\nexport interface PayloadComponentLoader<\n TProps extends object,\n> extends PayloadDecoderOptions {\n (\n props: TProps,\n context: PayloadComponentLoadContext,\n ): PayloadSource | PromiseLike<PayloadSource>;\n}\n\n/** Describes payload component options. */\nexport interface PayloadComponentOptions<\n TProps extends object,\n> extends PayloadDecoderOptions {\n cacheKey?: (props: TProps) => DataResourceKeyInput;\n key: DataResourceKey;\n load: PayloadComponentLoader<TProps>;\n}\n\n/** Describes payload component. */\nexport interface PayloadComponent<TProps extends object> extends DataResource<\n [TProps],\n AwaitedFigNode\n> {\n (props: TProps & { children?: FigNode }): FigNode;\n}\n\n/**\n * Creates a renderable Payload tree backed by Fig's ordinary data store.\n */\nexport function createPayloadComponent<TProps extends object>(\n options: PayloadComponentOptions<TProps>,\n): PayloadComponent<TProps> {\n const key = (props: TProps): DataResourceKey => {\n const serialized = serializedProps(props);\n return [\n ...options.key,\n options.cacheKey === undefined ? serialized : options.cacheKey(props),\n ];\n };\n const resource = dataResource<[TProps], AwaitedFigNode>({\n debugArgs: options.cacheKey === undefined ? undefined : serializedProps,\n key,\n load: async (props, context) => {\n const source = await options.load(props, {\n key: loadContextCapabilities(context)?.key ?? key(props),\n signal: context.signal,\n });\n const response =\n source instanceof Response\n ? source\n : new Response(source.stream, {\n headers: { \"content-type\": source.contentType },\n });\n return decodePayloadResponse(response, context, {\n prepareAssets: options.prepareAssets ?? options.load.prepareAssets,\n resolveClientReference:\n options.resolveClientReference ?? options.load.resolveClientReference,\n retainAssets: options.retainAssets ?? options.load.retainAssets,\n });\n },\n });\n\n const component: PayloadComponent<TProps> = Object.assign(\n function PayloadComponent(props: TProps & { children?: FigNode }): FigNode {\n rejectChildren(props);\n return readData(component, props);\n },\n resource,\n );\n Object.defineProperty(component, \"displayName\", {\n configurable: true,\n value: `Payload(${options.key[0]})`,\n });\n\n return component;\n}\n\nfunction serializedProps<TProps extends object>(\n props: TProps,\n): DataResourceKeyInput {\n rejectChildren(props);\n return encodePayloadKey(props);\n}\n\nfunction rejectChildren(props: object): void {\n if (Object.hasOwn(props, \"children\")) {\n throw new Error(\"Payload components do not accept children.\");\n }\n}\n","/**\n * Browser DOM rendering APIs for Fig applications.\n *\n * @module\n */\nimport type { FigNode, FigPortal, Key } from \"@bgub/fig\";\nimport {\n createPortalNode,\n type FigDataStore,\n readBrowser as readBrowserDuringRender,\n} from \"@bgub/fig/internal\";\nimport type {\n FigRoot,\n FigRootOptions,\n RecoverableErrorInfo,\n} from \"@bgub/fig-reconciler\";\nimport { composeBind, hostBinding } from \"./bind.ts\";\nimport {\n type EventCallback,\n type EventOptions,\n on,\n} from \"./event-descriptor.ts\";\nimport { type Container, registerRoot, unregisterRoot } from \"./events.ts\";\nimport { domRenderer } from \"./renderer.ts\";\nimport { adoptStreamedData } from \"./streamed-data.ts\";\n\nexport { insertAssetResources } from \"./asset-resources.ts\";\nexport type { Bind, Binding, HostBinding } from \"./bind.ts\";\nexport { composeBind, hostBinding };\nexport { type EventCallback, type EventOptions, on };\nexport type {\n EmptyPropValue,\n HostIntrinsicElements,\n HostProps,\n HostStyle,\n} from \"./jsx.ts\";\nexport {\n createPayloadComponent,\n type PayloadComponent,\n type PayloadComponentLoadContext,\n type PayloadComponentLoader,\n type PayloadComponentOptions,\n type PayloadSource,\n} from \"./payload-component.ts\";\n\nexport type { Container, FigRoot, FigRootOptions, RecoverableErrorInfo };\n\n/** Describes why a component requires browser rendering. */\nexport type BrowserRenderReason = string | (() => unknown);\n\n/**\n * Leaves the closest server-rendered Suspense boundary in its fallback state\n * so this component can render in the browser. This is a no-op during browser\n * rendering. A lazy reason is evaluated only by the server.\n */\nexport function readBrowser(reason?: BrowserRenderReason): void {\n readBrowserDuringRender(reason);\n}\n\n/** The flush sync. */\nexport const flushSync = domRenderer.flushSync;\n\n/** Creates root. */\nexport function createRoot(\n container: Container,\n options?: FigRootOptions,\n): FigRoot {\n const root = domRenderer.createRoot(container, options);\n registerRoot(container, { run: (callback) => root.data.run(callback) });\n return withEventTeardown(root, container);\n}\n\n/** Hydrates root. */\nexport function hydrateRoot(\n container: Container,\n children: FigNode,\n options?: FigRootOptions,\n): FigRoot {\n const root = domRenderer.hydrateRoot(container, children, options);\n registerRoot(container, {\n hydrate: (target, priority) =>\n domRenderer.hydrateTarget(container, target, priority),\n run: (callback) => root.data.run(callback),\n });\n // The root's handle is its renderer store, which accepts streamed rows.\n return withEventTeardown(\n root,\n container,\n adoptStreamedData(\n container,\n options?.identifierPrefix ?? \"\",\n root.data as FigDataStore,\n ),\n );\n}\n\n/** Creates portal. */\nexport function createPortal(\n children: FigNode,\n container: Container,\n key: Key | null = null,\n): FigPortal<Container> {\n return createPortalNode(children, container, key);\n}\n\n// Event routing lives outside the reconciler, so root teardown owns both.\nfunction withEventTeardown(\n root: FigRoot,\n container: Container,\n release?: () => void,\n): FigRoot {\n return {\n ...root,\n unmount: () => {\n release?.();\n root.unmount();\n unregisterRoot(container);\n },\n };\n}\n"],"mappings":"kZAwBA,SAAgB,EACd,EACA,EACA,EAC0B,CAC1B,IAAM,EAAW,EAAU,eAAiB,EACtC,EAAU,EAAQ,KAA4B,CAAC,EAC/C,EAAS,EAAO,GACtB,GAAI,IAAW,IAAA,IAAa,CAAC,MAAM,QAAQ,CAAM,EAAG,OAEpD,IAAM,EAA8B,CAClC,KAAK,GAAG,EAAS,CACf,IAAK,IAAM,KAAQ,EACjB,EAAM,eAAe,EAAyB,CAAI,CAAC,CAEvD,CACF,EAGA,MAFA,GAAO,GAAoB,EACvB,IAAW,IAAA,IAAW,EAAS,KAAK,GAAI,CAA6B,MAC5D,CACP,EAAO,KAAsB,GAAU,OAAO,EAAO,EAC3D,CACF,CC/BA,MAAM,MAAmB,IAAA,GAazB,eAAsB,EACpB,EACA,EACA,EAAiC,CAAC,EACT,CACzB,GAAM,CAAE,UAAW,EACnB,GAAI,EAAO,QAET,MADA,MAAM,EAAS,MAAM,OAAO,CAAC,CAAC,MAAM,CAAI,EAClC,EAAY,CAAM,EAE1B,GAAI,CAAC,EAAS,GAEZ,MADA,MAAM,EAAS,MAAM,OAAO,CAAC,CAAC,MAAM,CAAI,EAC9B,MAAM,sCAAsC,EAAS,OAAO,EAAE,EAE1E,IAAM,EAAO,EAAS,KACtB,GAAI,IAAS,KACX,MAAU,MAAM,0CAA0C,EAE5D,GAAI,CACF,EACE,EACA,EAAS,QAAQ,IAAI,cAAc,CACrC,CACF,OAAS,EAAO,CAEd,MADA,MAAM,EAAK,OAAO,CAAC,CAAC,MAAM,CAAI,EACxB,CACR,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,QAAQ,EACb,EAAe,CAAS,CAC1B,CACF,CACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/streamed-data.ts","../src/payload-decoder.ts","../src/payload-key.ts","../src/payload-component.ts","../src/index.ts"],"sourcesContent":["import type { DataResourceKey } from \"@bgub/fig\";\nimport {\n decodePayloadDataEntries,\n type FigDataStore,\n type PayloadDataHydrationEntry,\n STREAMED_DATA_PROPERTY,\n type StreamedDataMarker,\n} from \"@bgub/fig/internal\";\nimport type { Container } from \"./events.ts\";\n\ntype StreamedDataRows = Array<PayloadDataHydrationEntry | StreamedDataMarker>;\n\n// Rows queued before a root claims the prefix, or that root's receiver.\ninterface StreamedDataQueue {\n push(...batches: StreamedDataRows[]): unknown;\n}\n\ntype StreamedDataCarrier = {\n [STREAMED_DATA_PROPERTY]?: Record<string, StreamedDataQueue>;\n};\n\n// The server's `d` operation pushes rows per identifierPrefix. The first\n// hydrating root with that prefix drains the queued rows and replaces the\n// queue with a receiver that applies later rows directly, owning the prefix\n// until it unmounts. Rows fill only entries the client has no value for, so a\n// late row never overwrites client state.\n//\n// A marker row promises its key's form after a reveal; the store holds that\n// key's load for it. The document finishing parsing means the stream ended,\n// so any form still missing never comes and those loads run without one.\nexport function adoptStreamedData(\n container: Container,\n identifierPrefix: string,\n store: FigDataStore,\n): (() => void) | undefined {\n const doc = (container.ownerDocument ?? container) as Document;\n const carrier = doc as StreamedDataCarrier;\n const queues = (carrier[STREAMED_DATA_PROPERTY] ??= {});\n const queued = queues[identifierPrefix];\n if (queued !== undefined && !Array.isArray(queued)) return undefined;\n\n let streaming = doc.readyState === \"loading\";\n const receiver: StreamedDataQueue = {\n push(...batches) {\n for (const rows of batches) {\n const markers: DataResourceKey[] = [];\n const values: PayloadDataHydrationEntry[] = [];\n for (const row of rows) {\n if (\"pending\" in row) markers.push(row.key);\n else values.push(row);\n }\n if (streaming && markers.length > 0) store.awaitTransferForms(markers);\n if (values.length > 0) {\n store.hydrateMissing(decodePayloadDataEntries(values));\n }\n }\n },\n };\n const release = () => {\n streaming = false;\n store.releaseTransferForms();\n };\n queues[identifierPrefix] = receiver;\n if (queued !== undefined) receiver.push(...(queued as StreamedDataRows[]));\n if (streaming)\n doc.addEventListener(\"DOMContentLoaded\", release, { once: true });\n return () => {\n // Still streaming means the listener is still registered.\n if (streaming) doc.removeEventListener(\"DOMContentLoaded\", release);\n if (queues[identifierPrefix] === receiver) delete queues[identifierPrefix];\n };\n}\n","import type { AwaitedFigNode, DataResourceLoadContext } from \"@bgub/fig\";\nimport {\n assertPayloadCodecMatches,\n jsonPayloadCodec,\n loadContextCapabilities,\n} from \"@bgub/fig/internal\";\nimport {\n decodePayloadStream,\n type PayloadDecodeOptions,\n} from \"@bgub/fig/payload\";\nimport { insertAssetResources } from \"./asset-resources.ts\";\n\ndeclare const __FIG_DEV__: boolean | undefined;\n\nconst __DEV__ = typeof __FIG_DEV__ === \"boolean\" ? __FIG_DEV__ : false;\nconst noop = (): void => undefined;\n\nexport type PayloadDecoderOptions = Pick<\n PayloadDecodeOptions,\n \"prepareAssets\" | \"resolveClientReference\" | \"retainAssets\"\n>;\n\n/**\n * Decodes a validated Payload response within one data-resource generation.\n * The root becomes the entry value, streamed holes keep filling for the\n * generation's lifetime, `data` rows hydrate through its guarded capability,\n * and discovered assets enter the document with dependent reveal gates.\n */\nexport async function decodePayloadResponse(\n response: Response,\n context: DataResourceLoadContext,\n options: PayloadDecoderOptions = {},\n): Promise<AwaitedFigNode> {\n const { signal } = context;\n if (signal.aborted) {\n await response.body?.cancel().catch(noop);\n throw abortReason(signal);\n }\n if (!response.ok) {\n await response.body?.cancel().catch(noop);\n throw new Error(`Payload request failed with status ${response.status}.`);\n }\n const body = response.body;\n if (body === null) {\n throw new Error(\"Payload response did not include a body.\");\n }\n try {\n assertPayloadCodecMatches(\n jsonPayloadCodec,\n response.headers.get(\"content-type\"),\n );\n } catch (error) {\n await body.cancel().catch(noop);\n throw error;\n }\n\n const capabilities = loadContextCapabilities(context);\n return decodePayloadStream(body, {\n // Absent outside a data store: data rows are ignored rather than hydrated.\n hydrate: capabilities?.hydrate,\n onHoleError: capabilities?.attributeError,\n // Post-root failures surface through the rejected holes they strand;\n // observing the stream end keeps a failure that no longer has a pending\n // slot from being silently discarded in development.\n onStreamDone: (result) => {\n if (__DEV__ && result.status === \"failed\") {\n console.error(\n \"Payload decode failed after its root value published:\",\n result.error,\n );\n }\n },\n prepareAssets:\n options.prepareAssets ?? ((assets) => insertAssetResources(assets)),\n retainAssets: options.retainAssets,\n resolveClientReference: options.resolveClientReference,\n signal,\n });\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new Error(\"Payload request aborted.\");\n}\n","import type { DataResourceKeyInput } from \"@bgub/fig\";\n\nexport function encodePayloadKey(value: unknown): DataResourceKeyInput {\n const ids = new WeakMap<object, number>();\n let nextId = 1;\n\n function encode(value: unknown): DataResourceKeyInput {\n if (value === null) return null;\n if (value === undefined) return [\"undefined\"];\n if (typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") {\n if (Number.isNaN(value)) return [\"number\", \"NaN\"];\n if (value === Infinity) return [\"number\", \"Infinity\"];\n if (value === -Infinity) return [\"number\", \"-Infinity\"];\n return Object.is(value, -0) ? [\"number\", \"-0\"] : value;\n }\n if (typeof value === \"bigint\") return [\"bigint\", value.toString()];\n if (typeof value === \"symbol\") {\n const key = Symbol.keyFor(value);\n if (key === undefined) {\n throw new Error(\"Only global Symbol.for symbols can be serialized.\");\n }\n return [\"symbol\", key];\n }\n if (typeof value === \"function\") {\n throw new Error(\"Functions cannot be serialized into the payload.\");\n }\n if (value instanceof Date) {\n const json = value.toJSON();\n if (json === null) {\n throw new Error(\"Invalid Date values cannot be serialized.\");\n }\n return [\"date\", json];\n }\n\n const existing = ids.get(value);\n if (existing !== undefined) return [\"ref\", existing];\n const id = nextId++;\n ids.set(value, id);\n\n if (Array.isArray(value)) {\n return [\"array\", id, value.map(encode)];\n }\n if (value instanceof Map) {\n return [\n \"map\",\n id,\n Array.from(value, ([key, item]) => [encode(key), encode(item)]),\n ];\n }\n if (value instanceof Set) {\n return [\"set\", id, Array.from(value, encode)];\n }\n\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(\n `Cannot serialize ${prototype?.constructor?.name ?? \"object\"} into the payload.`,\n );\n }\n const record = value as Record<string, unknown>;\n return [\n \"object\",\n id,\n Object.keys(record)\n .sort()\n .map((key) => [key, encode(record[key])]),\n ];\n }\n\n return encode(value);\n}\n","import {\n type AwaitedFigNode,\n dataResource,\n type DataResource,\n type DataResourceKey,\n type DataResourceKeyInput,\n type FigNode,\n readData,\n} from \"@bgub/fig\";\nimport { loadContextCapabilities } from \"@bgub/fig/internal\";\nimport {\n decodePayloadResponse,\n type PayloadDecoderOptions,\n} from \"./payload-decoder.ts\";\nimport { encodePayloadKey } from \"./payload-key.ts\";\n\n/** Describes payload source. */\nexport type PayloadSource =\n | Response\n | {\n contentType: string;\n stream: ReadableStream<Uint8Array>;\n };\n\n/** Describes payload component load context. */\nexport interface PayloadComponentLoadContext {\n key: DataResourceKey;\n signal: AbortSignal;\n}\n\n/** Describes payload component loader. */\nexport interface PayloadComponentLoader<\n TProps extends object,\n> extends PayloadDecoderOptions {\n (\n props: TProps,\n context: PayloadComponentLoadContext,\n ): PayloadSource | PromiseLike<PayloadSource>;\n}\n\n/** Describes payload component options. */\nexport interface PayloadComponentOptions<\n TProps extends object,\n> extends PayloadDecoderOptions {\n cacheKey?: (props: TProps) => DataResourceKeyInput;\n key: DataResourceKey;\n load: PayloadComponentLoader<TProps>;\n}\n\n/** Describes payload component. */\nexport interface PayloadComponent<TProps extends object> extends DataResource<\n [TProps],\n AwaitedFigNode\n> {\n (props: TProps & { children?: FigNode }): FigNode;\n}\n\n/**\n * Creates a renderable Payload tree backed by Fig's ordinary data store.\n */\nexport function createPayloadComponent<TProps extends object>(\n options: PayloadComponentOptions<TProps>,\n): PayloadComponent<TProps> {\n const key = (props: TProps): DataResourceKey => {\n const serialized = serializedProps(props);\n return [\n ...options.key,\n options.cacheKey === undefined ? serialized : options.cacheKey(props),\n ];\n };\n const resource = dataResource<[TProps], AwaitedFigNode>({\n debugArgs: options.cacheKey === undefined ? undefined : serializedProps,\n key,\n load: async (props, context) => {\n const source = await options.load(props, {\n key: loadContextCapabilities(context)?.key ?? key(props),\n signal: context.signal,\n });\n const response =\n source instanceof Response\n ? source\n : new Response(source.stream, {\n headers: { \"content-type\": source.contentType },\n });\n return decodePayloadResponse(response, context, {\n prepareAssets: options.prepareAssets ?? options.load.prepareAssets,\n resolveClientReference:\n options.resolveClientReference ?? options.load.resolveClientReference,\n retainAssets: options.retainAssets ?? options.load.retainAssets,\n });\n },\n });\n\n const component: PayloadComponent<TProps> = Object.assign(\n function PayloadComponent(props: TProps & { children?: FigNode }): FigNode {\n rejectChildren(props);\n return readData(component, props);\n },\n resource,\n );\n Object.defineProperty(component, \"displayName\", {\n configurable: true,\n value: `Payload(${options.key[0]})`,\n });\n\n return component;\n}\n\nfunction serializedProps<TProps extends object>(\n props: TProps,\n): DataResourceKeyInput {\n rejectChildren(props);\n return encodePayloadKey(props);\n}\n\nfunction rejectChildren(props: object): void {\n if (Object.hasOwn(props, \"children\")) {\n throw new Error(\"Payload components do not accept children.\");\n }\n}\n","/**\n * Browser DOM rendering APIs for Fig applications.\n *\n * @module\n */\nimport type { FigNode, FigPortal, Key } from \"@bgub/fig\";\nimport {\n createPortalNode,\n type FigDataStore,\n readBrowser as readBrowserDuringRender,\n} from \"@bgub/fig/internal\";\nimport type {\n FigRoot,\n FigRootOptions,\n RecoverableErrorInfo,\n} from \"@bgub/fig-reconciler\";\nimport { composeBind, hostBinding } from \"./bind.ts\";\nimport {\n type EventCallback,\n type EventOptions,\n on,\n} from \"./event-descriptor.ts\";\nimport { type Container, registerRoot, unregisterRoot } from \"./events.ts\";\nimport { domRenderer } from \"./renderer.ts\";\nimport { adoptStreamedData } from \"./streamed-data.ts\";\n\nexport { insertAssetResources } from \"./asset-resources.ts\";\nexport type { Bind, Binding, HostBinding } from \"./bind.ts\";\nexport { composeBind, hostBinding };\nexport { type EventCallback, type EventOptions, on };\nexport type {\n EmptyPropValue,\n HostIntrinsicElements,\n HostProps,\n HostStyle,\n} from \"./jsx.ts\";\nexport {\n createPayloadComponent,\n type PayloadComponent,\n type PayloadComponentLoadContext,\n type PayloadComponentLoader,\n type PayloadComponentOptions,\n type PayloadSource,\n} from \"./payload-component.ts\";\n\nexport type { Container, FigRoot, FigRootOptions, RecoverableErrorInfo };\n\n/** Describes why a component requires browser rendering. */\nexport type BrowserRenderReason = string | (() => unknown);\n\n/**\n * Leaves the closest server-rendered Suspense boundary in its fallback state\n * so this component can render in the browser. This is a no-op during browser\n * rendering. A lazy reason is evaluated only by the server.\n */\nexport function readBrowser(reason?: BrowserRenderReason): void {\n readBrowserDuringRender(reason);\n}\n\n/** The flush sync. */\nexport const flushSync = domRenderer.flushSync;\n\n/** Creates root. */\nexport function createRoot(\n container: Container,\n options?: FigRootOptions,\n): FigRoot {\n const root = domRenderer.createRoot(container, options);\n registerRoot(container, { run: (callback) => root.data.run(callback) });\n return withEventTeardown(root, container);\n}\n\n/** Hydrates root. */\nexport function hydrateRoot(\n container: Container,\n children: FigNode,\n options?: FigRootOptions,\n): FigRoot {\n const root = domRenderer.hydrateRoot(container, children, options);\n registerRoot(container, {\n hydrate: (target, priority) =>\n domRenderer.hydrateTarget(container, target, priority),\n run: (callback) => root.data.run(callback),\n });\n // The root's handle is its renderer store, which accepts streamed rows.\n return withEventTeardown(\n root,\n container,\n adoptStreamedData(\n container,\n options?.identifierPrefix ?? \"\",\n root.data as FigDataStore,\n ),\n );\n}\n\n/** Creates portal. */\nexport function createPortal(\n children: FigNode,\n container: Container,\n key: Key | null = null,\n): FigPortal<Container> {\n return createPortalNode(children, container, key);\n}\n\n// Event routing lives outside the reconciler, so root teardown owns both.\nfunction withEventTeardown(\n root: FigRoot,\n container: Container,\n release?: () => void,\n):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A,EACE,EACA,GAAS,kBAAoB,GAC7B,EAAK,IACP,CACF,CACF,CAGA,SAAgB,EACd,EACA,EACA,EAAkB,KACI,CACtB,OAAO,EAAiB,EAAU,EAAW,CAAG,CAClD,CAGA,SAAS,EACP,EACA,EACA,EACS,CACT,MAAO,CACL,GAAG,EACH,YAAe,CACb,IAAU,EACV,EAAK,QAAQ,EACb,EAAe,CAAS,CAC1B,CACF,CACF"}
@@ -1,2 +1,2 @@
1
- import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./renderer-DRHGq7Wl.js";import{STREAMED_DATA_PROPERTY as s,assertPayloadCodecMatches as c,createPortalNode as l,decodePayloadDataEntries as u,jsonPayloadCodec as d,loadContextCapabilities as f,readBrowser as p}from"@bgub/fig/internal";import{dataResource as m,readData as h}from"@bgub/fig";import{decodePayloadStream as g}from"@bgub/fig/payload";function _(e,t,n){let r=e.ownerDocument??e,i=r[s]??={},a=i[t];if(a!==void 0&&!Array.isArray(a))return;let o={push(...e){for(let t of e)n.hydrateMissing(u(t))}};return i[t]=o,a!==void 0&&o.push(...a),()=>{i[t]===o&&delete i[t]}}const v=()=>void 0;async function y(e,t,r={}){let{signal:i}=t;if(i.aborted)throw await e.body?.cancel().catch(v),b(i);if(!e.ok)throw await e.body?.cancel().catch(v),Error(`Payload request failed with status ${e.status}.`);let a=e.body;if(a===null)throw Error(`Payload response did not include a body.`);try{c(d,e.headers.get(`content-type`))}catch(e){throw await a.cancel().catch(v),e}let o=f(t);return g(a,{hydrate:o?.hydrate,onHoleError:o?.attributeError,onStreamDone:e=>{e.status===`failed`&&console.error(`Payload decode failed after its root value published:`,e.error)},prepareAssets:r.prepareAssets??(e=>n(e)),retainAssets:r.retainAssets,resolveClientReference:r.resolveClientReference,signal:i})}function b(e){return e.reason??Error(`Payload request aborted.`)}function x(e){let t=new WeakMap,n=1;function r(e){if(e===null)return null;if(e===void 0)return[`undefined`];if(typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isNaN(e)?[`number`,`NaN`]:e===1/0?[`number`,`Infinity`]:e===-1/0?[`number`,`-Infinity`]:Object.is(e,-0)?[`number`,`-0`]:e;if(typeof e==`bigint`)return[`bigint`,e.toString()];if(typeof e==`symbol`){let t=Symbol.keyFor(e);if(t===void 0)throw Error(`Only global Symbol.for symbols can be serialized.`);return[`symbol`,t]}if(typeof e==`function`)throw Error(`Functions cannot be serialized into the payload.`);if(e instanceof Date){let t=e.toJSON();if(t===null)throw Error(`Invalid Date values cannot be serialized.`);return[`date`,t]}let i=t.get(e);if(i!==void 0)return[`ref`,i];let a=n++;if(t.set(e,a),Array.isArray(e))return[`array`,a,e.map(r)];if(e instanceof Map)return[`map`,a,Array.from(e,([e,t])=>[r(e),r(t)])];if(e instanceof Set)return[`set`,a,Array.from(e,r)];let o=Object.getPrototypeOf(e);if(o!==Object.prototype&&o!==null)throw Error(`Cannot serialize ${o?.constructor?.name??`object`} into the payload.`);let s=e;return[`object`,a,Object.keys(s).sort().map(e=>[e,r(s[e])])]}return r(e)}function S(e){let t=t=>{let n=C(t);return[...e.key,e.cacheKey===void 0?n:e.cacheKey(t)]},n=m({debugArgs:e.cacheKey===void 0?void 0:C,key:t,load:async(n,r)=>{let i=await e.load(n,{key:f(r)?.key??t(n),signal:r.signal});return y(i instanceof Response?i:new Response(i.stream,{headers:{"content-type":i.contentType}}),r,{prepareAssets:e.prepareAssets??e.load.prepareAssets,resolveClientReference:e.resolveClientReference??e.load.resolveClientReference,retainAssets:e.retainAssets??e.load.retainAssets})}}),r=Object.assign(function(e){return w(e),h(r,e)},n);return Object.defineProperty(r,"displayName",{configurable:!0,value:`Payload(${e.key[0]})`}),r}function C(e){return w(e),x(e)}function w(e){if(Object.hasOwn(e,`children`))throw Error(`Payload components do not accept children.`)}function T(e){p(e)}const E=o.flushSync;function D(e,t){let n=o.createRoot(e,t);return i(e,{run:e=>n.data.run(e)}),A(n,e)}function O(e,t,n){let r=o.hydrateRoot(e,t,n);return i(e,{hydrate:(t,n)=>o.hydrateTarget(e,t,n),run:e=>r.data.run(e)}),A(r,e,_(e,n?.identifierPrefix??``,r.data))}function k(e,t,n=null){return l(e,t,n)}function A(e,n,r){return{...e,unmount:()=>{r?.(),e.unmount(),t(n)}}}export{r as composeBind,S as createPayloadComponent,k as createPortal,D as createRoot,E as flushSync,a as hostBinding,O as hydrateRoot,n as insertAssetResources,e as on,T as readBrowser};
1
+ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./renderer-DRHGq7Wl.js";import{STREAMED_DATA_PROPERTY as s,assertPayloadCodecMatches as c,createPortalNode as l,decodePayloadDataEntries as u,jsonPayloadCodec as d,loadContextCapabilities as f,readBrowser as p}from"@bgub/fig/internal";import{dataResource as m,readData as h}from"@bgub/fig";import{decodePayloadStream as g}from"@bgub/fig/payload";function _(e,t,n){let r=e.ownerDocument??e,i=r,a=i[s]??={},o=a[t];if(o!==void 0&&!Array.isArray(o))return;let c=r.readyState===`loading`,l={push(...e){for(let t of e){let e=[],r=[];for(let n of t)`pending`in n?e.push(n.key):r.push(n);c&&e.length>0&&n.awaitTransferForms(e),r.length>0&&n.hydrateMissing(u(r))}}},d=()=>{c=!1,n.releaseTransferForms()};return a[t]=l,o!==void 0&&l.push(...o),c&&r.addEventListener(`DOMContentLoaded`,d,{once:!0}),()=>{c&&r.removeEventListener(`DOMContentLoaded`,d),a[t]===l&&delete a[t]}}const v=()=>void 0;async function y(e,t,r={}){let{signal:i}=t;if(i.aborted)throw await e.body?.cancel().catch(v),b(i);if(!e.ok)throw await e.body?.cancel().catch(v),Error(`Payload request failed with status ${e.status}.`);let a=e.body;if(a===null)throw Error(`Payload response did not include a body.`);try{c(d,e.headers.get(`content-type`))}catch(e){throw await a.cancel().catch(v),e}let o=f(t);return g(a,{hydrate:o?.hydrate,onHoleError:o?.attributeError,onStreamDone:e=>{e.status===`failed`&&console.error(`Payload decode failed after its root value published:`,e.error)},prepareAssets:r.prepareAssets??(e=>n(e)),retainAssets:r.retainAssets,resolveClientReference:r.resolveClientReference,signal:i})}function b(e){return e.reason??Error(`Payload request aborted.`)}function x(e){let t=new WeakMap,n=1;function r(e){if(e===null)return null;if(e===void 0)return[`undefined`];if(typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isNaN(e)?[`number`,`NaN`]:e===1/0?[`number`,`Infinity`]:e===-1/0?[`number`,`-Infinity`]:Object.is(e,-0)?[`number`,`-0`]:e;if(typeof e==`bigint`)return[`bigint`,e.toString()];if(typeof e==`symbol`){let t=Symbol.keyFor(e);if(t===void 0)throw Error(`Only global Symbol.for symbols can be serialized.`);return[`symbol`,t]}if(typeof e==`function`)throw Error(`Functions cannot be serialized into the payload.`);if(e instanceof Date){let t=e.toJSON();if(t===null)throw Error(`Invalid Date values cannot be serialized.`);return[`date`,t]}let i=t.get(e);if(i!==void 0)return[`ref`,i];let a=n++;if(t.set(e,a),Array.isArray(e))return[`array`,a,e.map(r)];if(e instanceof Map)return[`map`,a,Array.from(e,([e,t])=>[r(e),r(t)])];if(e instanceof Set)return[`set`,a,Array.from(e,r)];let o=Object.getPrototypeOf(e);if(o!==Object.prototype&&o!==null)throw Error(`Cannot serialize ${o?.constructor?.name??`object`} into the payload.`);let s=e;return[`object`,a,Object.keys(s).sort().map(e=>[e,r(s[e])])]}return r(e)}function S(e){let t=t=>{let n=C(t);return[...e.key,e.cacheKey===void 0?n:e.cacheKey(t)]},n=m({debugArgs:e.cacheKey===void 0?void 0:C,key:t,load:async(n,r)=>{let i=await e.load(n,{key:f(r)?.key??t(n),signal:r.signal});return y(i instanceof Response?i:new Response(i.stream,{headers:{"content-type":i.contentType}}),r,{prepareAssets:e.prepareAssets??e.load.prepareAssets,resolveClientReference:e.resolveClientReference??e.load.resolveClientReference,retainAssets:e.retainAssets??e.load.retainAssets})}}),r=Object.assign(function(e){return w(e),h(r,e)},n);return Object.defineProperty(r,"displayName",{configurable:!0,value:`Payload(${e.key[0]})`}),r}function C(e){return w(e),x(e)}function w(e){if(Object.hasOwn(e,`children`))throw Error(`Payload components do not accept children.`)}function T(e){p(e)}const E=o.flushSync;function D(e,t){let n=o.createRoot(e,t);return i(e,{run:e=>n.data.run(e)}),A(n,e)}function O(e,t,n){let r=o.hydrateRoot(e,t,n);return i(e,{hydrate:(t,n)=>o.hydrateTarget(e,t,n),run:e=>r.data.run(e)}),A(r,e,_(e,n?.identifierPrefix??``,r.data))}function k(e,t,n=null){return l(e,t,n)}function A(e,n,r){return{...e,unmount:()=>{r?.(),e.unmount(),t(n)}}}export{r as composeBind,S as createPayloadComponent,k as createPortal,D as createRoot,E as flushSync,a as hostBinding,O as hydrateRoot,n as insertAssetResources,e as on,T as readBrowser};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/streamed-data.ts","../src/payload-decoder.ts","../src/payload-key.ts","../src/payload-component.ts","../src/index.ts"],"sourcesContent":["import {\n decodePayloadDataEntries,\n type FigDataStore,\n type PayloadDataHydrationEntry,\n STREAMED_DATA_PROPERTY,\n} from \"@bgub/fig/internal\";\nimport type { Container } from \"./events.ts\";\n\ntype StreamedDataRows = PayloadDataHydrationEntry[];\n\n// Rows queued before a root claims the prefix, or that root's receiver.\ninterface StreamedDataQueue {\n push(...batches: StreamedDataRows[]): unknown;\n}\n\ntype StreamedDataCarrier = {\n [STREAMED_DATA_PROPERTY]?: Record<string, StreamedDataQueue>;\n};\n\n// The server's `d` operation pushes rows per identifierPrefix. The first\n// hydrating root with that prefix drains the queued rows and replaces the\n// queue with a receiver that applies later rows directly, owning the prefix\n// until it unmounts. Rows fill only entries the client has no value for, so a\n// late row never overwrites client state.\nexport function adoptStreamedData(\n container: Container,\n identifierPrefix: string,\n store: FigDataStore,\n): (() => void) | undefined {\n const carrier = (container.ownerDocument ?? container) as StreamedDataCarrier;\n const queues = (carrier[STREAMED_DATA_PROPERTY] ??= {});\n const queued = queues[identifierPrefix];\n if (queued !== undefined && !Array.isArray(queued)) return undefined;\n\n const receiver: StreamedDataQueue = {\n push(...batches) {\n for (const rows of batches) {\n store.hydrateMissing(decodePayloadDataEntries(rows));\n }\n },\n };\n queues[identifierPrefix] = receiver;\n if (queued !== undefined) receiver.push(...(queued as StreamedDataRows[]));\n return () => {\n if (queues[identifierPrefix] === receiver) delete queues[identifierPrefix];\n };\n}\n","import type { AwaitedFigNode, DataResourceLoadContext } from \"@bgub/fig\";\nimport {\n assertPayloadCodecMatches,\n jsonPayloadCodec,\n loadContextCapabilities,\n} from \"@bgub/fig/internal\";\nimport {\n decodePayloadStream,\n type PayloadDecodeOptions,\n} from \"@bgub/fig/payload\";\nimport { insertAssetResources } from \"./asset-resources.ts\";\n\ndeclare const __FIG_DEV__: boolean | undefined;\n\nconst __DEV__ = typeof __FIG_DEV__ === \"boolean\" ? __FIG_DEV__ : false;\nconst noop = (): void => undefined;\n\nexport type PayloadDecoderOptions = Pick<\n PayloadDecodeOptions,\n \"prepareAssets\" | \"resolveClientReference\" | \"retainAssets\"\n>;\n\n/**\n * Decodes a validated Payload response within one data-resource generation.\n * The root becomes the entry value, streamed holes keep filling for the\n * generation's lifetime, `data` rows hydrate through its guarded capability,\n * and discovered assets enter the document with dependent reveal gates.\n */\nexport async function decodePayloadResponse(\n response: Response,\n context: DataResourceLoadContext,\n options: PayloadDecoderOptions = {},\n): Promise<AwaitedFigNode> {\n const { signal } = context;\n if (signal.aborted) {\n await response.body?.cancel().catch(noop);\n throw abortReason(signal);\n }\n if (!response.ok) {\n await response.body?.cancel().catch(noop);\n throw new Error(`Payload request failed with status ${response.status}.`);\n }\n const body = response.body;\n if (body === null) {\n throw new Error(\"Payload response did not include a body.\");\n }\n try {\n assertPayloadCodecMatches(\n jsonPayloadCodec,\n response.headers.get(\"content-type\"),\n );\n } catch (error) {\n await body.cancel().catch(noop);\n throw error;\n }\n\n const capabilities = loadContextCapabilities(context);\n return decodePayloadStream(body, {\n // Absent outside a data store: data rows are ignored rather than hydrated.\n hydrate: capabilities?.hydrate,\n onHoleError: capabilities?.attributeError,\n // Post-root failures surface through the rejected holes they strand;\n // observing the stream end keeps a failure that no longer has a pending\n // slot from being silently discarded in development.\n onStreamDone: (result) => {\n if (__DEV__ && result.status === \"failed\") {\n console.error(\n \"Payload decode failed after its root value published:\",\n result.error,\n );\n }\n },\n prepareAssets:\n options.prepareAssets ?? ((assets) => insertAssetResources(assets)),\n retainAssets: options.retainAssets,\n resolveClientReference: options.resolveClientReference,\n signal,\n });\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new Error(\"Payload request aborted.\");\n}\n","import type { DataResourceKeyInput } from \"@bgub/fig\";\n\nexport function encodePayloadKey(value: unknown): DataResourceKeyInput {\n const ids = new WeakMap<object, number>();\n let nextId = 1;\n\n function encode(value: unknown): DataResourceKeyInput {\n if (value === null) return null;\n if (value === undefined) return [\"undefined\"];\n if (typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") {\n if (Number.isNaN(value)) return [\"number\", \"NaN\"];\n if (value === Infinity) return [\"number\", \"Infinity\"];\n if (value === -Infinity) return [\"number\", \"-Infinity\"];\n return Object.is(value, -0) ? [\"number\", \"-0\"] : value;\n }\n if (typeof value === \"bigint\") return [\"bigint\", value.toString()];\n if (typeof value === \"symbol\") {\n const key = Symbol.keyFor(value);\n if (key === undefined) {\n throw new Error(\"Only global Symbol.for symbols can be serialized.\");\n }\n return [\"symbol\", key];\n }\n if (typeof value === \"function\") {\n throw new Error(\"Functions cannot be serialized into the payload.\");\n }\n if (value instanceof Date) {\n const json = value.toJSON();\n if (json === null) {\n throw new Error(\"Invalid Date values cannot be serialized.\");\n }\n return [\"date\", json];\n }\n\n const existing = ids.get(value);\n if (existing !== undefined) return [\"ref\", existing];\n const id = nextId++;\n ids.set(value, id);\n\n if (Array.isArray(value)) {\n return [\"array\", id, value.map(encode)];\n }\n if (value instanceof Map) {\n return [\n \"map\",\n id,\n Array.from(value, ([key, item]) => [encode(key), encode(item)]),\n ];\n }\n if (value instanceof Set) {\n return [\"set\", id, Array.from(value, encode)];\n }\n\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(\n `Cannot serialize ${prototype?.constructor?.name ?? \"object\"} into the payload.`,\n );\n }\n const record = value as Record<string, unknown>;\n return [\n \"object\",\n id,\n Object.keys(record)\n .sort()\n .map((key) => [key, encode(record[key])]),\n ];\n }\n\n return encode(value);\n}\n","import {\n type AwaitedFigNode,\n dataResource,\n type DataResource,\n type DataResourceKey,\n type DataResourceKeyInput,\n type FigNode,\n readData,\n} from \"@bgub/fig\";\nimport { loadContextCapabilities } from \"@bgub/fig/internal\";\nimport {\n decodePayloadResponse,\n type PayloadDecoderOptions,\n} from \"./payload-decoder.ts\";\nimport { encodePayloadKey } from \"./payload-key.ts\";\n\n/** Describes payload source. */\nexport type PayloadSource =\n | Response\n | {\n contentType: string;\n stream: ReadableStream<Uint8Array>;\n };\n\n/** Describes payload component load context. */\nexport interface PayloadComponentLoadContext {\n key: DataResourceKey;\n signal: AbortSignal;\n}\n\n/** Describes payload component loader. */\nexport interface PayloadComponentLoader<\n TProps extends object,\n> extends PayloadDecoderOptions {\n (\n props: TProps,\n context: PayloadComponentLoadContext,\n ): PayloadSource | PromiseLike<PayloadSource>;\n}\n\n/** Describes payload component options. */\nexport interface PayloadComponentOptions<\n TProps extends object,\n> extends PayloadDecoderOptions {\n cacheKey?: (props: TProps) => DataResourceKeyInput;\n key: DataResourceKey;\n load: PayloadComponentLoader<TProps>;\n}\n\n/** Describes payload component. */\nexport interface PayloadComponent<TProps extends object> extends DataResource<\n [TProps],\n AwaitedFigNode\n> {\n (props: TProps & { children?: FigNode }): FigNode;\n}\n\n/**\n * Creates a renderable Payload tree backed by Fig's ordinary data store.\n */\nexport function createPayloadComponent<TProps extends object>(\n options: PayloadComponentOptions<TProps>,\n): PayloadComponent<TProps> {\n const key = (props: TProps): DataResourceKey => {\n const serialized = serializedProps(props);\n return [\n ...options.key,\n options.cacheKey === undefined ? serialized : options.cacheKey(props),\n ];\n };\n const resource = dataResource<[TProps], AwaitedFigNode>({\n debugArgs: options.cacheKey === undefined ? undefined : serializedProps,\n key,\n load: async (props, context) => {\n const source = await options.load(props, {\n key: loadContextCapabilities(context)?.key ?? key(props),\n signal: context.signal,\n });\n const response =\n source instanceof Response\n ? source\n : new Response(source.stream, {\n headers: { \"content-type\": source.contentType },\n });\n return decodePayloadResponse(response, context, {\n prepareAssets: options.prepareAssets ?? options.load.prepareAssets,\n resolveClientReference:\n options.resolveClientReference ?? options.load.resolveClientReference,\n retainAssets: options.retainAssets ?? options.load.retainAssets,\n });\n },\n });\n\n const component: PayloadComponent<TProps> = Object.assign(\n function PayloadComponent(props: TProps & { children?: FigNode }): FigNode {\n rejectChildren(props);\n return readData(component, props);\n },\n resource,\n );\n Object.defineProperty(component, \"displayName\", {\n configurable: true,\n value: `Payload(${options.key[0]})`,\n });\n\n return component;\n}\n\nfunction serializedProps<TProps extends object>(\n props: TProps,\n): DataResourceKeyInput {\n rejectChildren(props);\n return encodePayloadKey(props);\n}\n\nfunction rejectChildren(props: object): void {\n if (Object.hasOwn(props, \"children\")) {\n throw new Error(\"Payload components do not accept children.\");\n }\n}\n","/**\n * Browser DOM rendering APIs for Fig applications.\n *\n * @module\n */\nimport type { FigNode, FigPortal, Key } from \"@bgub/fig\";\nimport {\n createPortalNode,\n type FigDataStore,\n readBrowser as readBrowserDuringRender,\n} from \"@bgub/fig/internal\";\nimport type {\n FigRoot,\n FigRootOptions,\n RecoverableErrorInfo,\n} from \"@bgub/fig-reconciler\";\nimport { composeBind, hostBinding } from \"./bind.ts\";\nimport {\n type EventCallback,\n type EventOptions,\n on,\n} from \"./event-descriptor.ts\";\nimport { type Container, registerRoot, unregisterRoot } from \"./events.ts\";\nimport { domRenderer } from \"./renderer.ts\";\nimport { adoptStreamedData } from \"./streamed-data.ts\";\n\nexport { insertAssetResources } from \"./asset-resources.ts\";\nexport type { Bind, Binding, HostBinding } from \"./bind.ts\";\nexport { composeBind, hostBinding };\nexport { type EventCallback, type EventOptions, on };\nexport type {\n EmptyPropValue,\n HostIntrinsicElements,\n HostProps,\n HostStyle,\n} from \"./jsx.ts\";\nexport {\n createPayloadComponent,\n type PayloadComponent,\n type PayloadComponentLoadContext,\n type PayloadComponentLoader,\n type PayloadComponentOptions,\n type PayloadSource,\n} from \"./payload-component.ts\";\n\nexport type { Container, FigRoot, FigRootOptions, RecoverableErrorInfo };\n\n/** Describes why a component requires browser rendering. */\nexport type BrowserRenderReason = string | (() => unknown);\n\n/**\n * Leaves the closest server-rendered Suspense boundary in its fallback state\n * so this component can render in the browser. This is a no-op during browser\n * rendering. A lazy reason is evaluated only by the server.\n */\nexport function readBrowser(reason?: BrowserRenderReason): void {\n readBrowserDuringRender(reason);\n}\n\n/** The flush sync. */\nexport const flushSync = domRenderer.flushSync;\n\n/** Creates root. */\nexport function createRoot(\n container: Container,\n options?: FigRootOptions,\n): FigRoot {\n const root = domRenderer.createRoot(container, options);\n registerRoot(container, { run: (callback) => root.data.run(callback) });\n return withEventTeardown(root, container);\n}\n\n/** Hydrates root. */\nexport function hydrateRoot(\n container: Container,\n children: FigNode,\n options?: FigRootOptions,\n): FigRoot {\n const root = domRenderer.hydrateRoot(container, children, options);\n registerRoot(container, {\n hydrate: (target, priority) =>\n domRenderer.hydrateTarget(container, target, priority),\n run: (callback) => root.data.run(callback),\n });\n // The root's handle is its renderer store, which accepts streamed rows.\n return withEventTeardown(\n root,\n container,\n adoptStreamedData(\n container,\n options?.identifierPrefix ?? \"\",\n root.data as FigDataStore,\n ),\n );\n}\n\n/** Creates portal. */\nexport function createPortal(\n children: FigNode,\n container: Container,\n key: Key | null = null,\n): FigPortal<Container> {\n return createPortalNode(children, container, key);\n}\n\n// Event routing lives outside the reconciler, so root teardown owns both.\nfunction withEventTeardown(\n root: FigRoot,\n container: Container,\n release?: () => void,\n): FigRoot {\n return {\n ...root,\n unmount: () => {\n release?.();\n root.unmount();\n unregisterRoot(container);\n },\n };\n}\n"],"mappings":"kZAw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,EACA,CACF,EAMA,OALA,OAAO,eAAe,EAAW,cAAe,CAC9C,aAAc,GACd,MAAO,WAAW,EAAQ,IAAI,GAAG,EACnC,CAAC,EAEM,CACT,CAEA,SAAS,EACP,EACsB,CAEtB,OADA,EAAe,CAAK,EACb,EAAiB,CAAK,CAC/B,CAEA,SAAS,EAAe,EAAqB,CAC3C,GAAI,OAAO,OAAO,EAAO,UAAU,EACjC,MAAU,MAAM,4CAA4C,CAEhE,CChEA,SAAgB,EAAY,EAAoC,CAC9D,EAAwB,CAAM,CAChC,CAGA,MAAa,EAAY,EAAY,UAGrC,SAAgB,EACd,EACA,EACS,CACT,IAAM,EAAO,EAAY,WAAW,EAAW,CAAO,EAEtD,OADA,EAAa,EAAW,CAAE,IAAM,GAAa,EAAK,KAAK,IAAI,CAAQ,CAAE,CAAC,EAC/D,EAAkB,EAAM,CAAS,CAC1C,CAGA,SAAgB,EACd,EACA,EACA,EACS,CACT,IAAM,EAAO,EAAY,YAAY,EAAW,EAAU,CAAO,EAOjE,OANA,EAAa,EAAW,CACtB,SAAU,EAAQ,IAChB,EAAY,cAAc,EAAW,EAAQ,CAAQ,EACvD,IAAM,GAAa,EAAK,KAAK,IAAI,CAAQ,CAC3C,CAAC,EAEM,EACL,EACA,EACA,EACE,EACA,GAAS,kBAAoB,GAC7B,EAAK,IACP,CACF,CACF,CAGA,SAAgB,EACd,EACA,EACA,EAAkB,KACI,CACtB,OAAO,EAAiB,EAAU,EAAW,CAAG,CAClD,CAGA,SAAS,EACP,EACA,EACA,EACS,CACT,MAAO,CACL,GAAG,EACH,YAAe,CACb,IAAU,EACV,EAAK,QAAQ,EACb,EAAe,CAAS,CAC1B,CACF,CACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/streamed-data.ts","../src/payload-decoder.ts","../src/payload-key.ts","../src/payload-component.ts","../src/index.ts"],"sourcesContent":["import type { DataResourceKey } from \"@bgub/fig\";\nimport {\n decodePayloadDataEntries,\n type FigDataStore,\n type PayloadDataHydrationEntry,\n STREAMED_DATA_PROPERTY,\n type StreamedDataMarker,\n} from \"@bgub/fig/internal\";\nimport type { Container } from \"./events.ts\";\n\ntype StreamedDataRows = Array<PayloadDataHydrationEntry | StreamedDataMarker>;\n\n// Rows queued before a root claims the prefix, or that root's receiver.\ninterface StreamedDataQueue {\n push(...batches: StreamedDataRows[]): unknown;\n}\n\ntype StreamedDataCarrier = {\n [STREAMED_DATA_PROPERTY]?: Record<string, StreamedDataQueue>;\n};\n\n// The server's `d` operation pushes rows per identifierPrefix. The first\n// hydrating root with that prefix drains the queued rows and replaces the\n// queue with a receiver that applies later rows directly, owning the prefix\n// until it unmounts. Rows fill only entries the client has no value for, so a\n// late row never overwrites client state.\n//\n// A marker row promises its key's form after a reveal; the store holds that\n// key's load for it. The document finishing parsing means the stream ended,\n// so any form still missing never comes and those loads run without one.\nexport function adoptStreamedData(\n container: Container,\n identifierPrefix: string,\n store: FigDataStore,\n): (() => void) | undefined {\n const doc = (container.ownerDocument ?? container) as Document;\n const carrier = doc as StreamedDataCarrier;\n const queues = (carrier[STREAMED_DATA_PROPERTY] ??= {});\n const queued = queues[identifierPrefix];\n if (queued !== undefined && !Array.isArray(queued)) return undefined;\n\n let streaming = doc.readyState === \"loading\";\n const receiver: StreamedDataQueue = {\n push(...batches) {\n for (const rows of batches) {\n const markers: DataResourceKey[] = [];\n const values: PayloadDataHydrationEntry[] = [];\n for (const row of rows) {\n if (\"pending\" in row) markers.push(row.key);\n else values.push(row);\n }\n if (streaming && markers.length > 0) store.awaitTransferForms(markers);\n if (values.length > 0) {\n store.hydrateMissing(decodePayloadDataEntries(values));\n }\n }\n },\n };\n const release = () => {\n streaming = false;\n store.releaseTransferForms();\n };\n queues[identifierPrefix] = receiver;\n if (queued !== undefined) receiver.push(...(queued as StreamedDataRows[]));\n if (streaming)\n doc.addEventListener(\"DOMContentLoaded\", release, { once: true });\n return () => {\n // Still streaming means the listener is still registered.\n if (streaming) doc.removeEventListener(\"DOMContentLoaded\", release);\n if (queues[identifierPrefix] === receiver) delete queues[identifierPrefix];\n };\n}\n","import type { AwaitedFigNode, DataResourceLoadContext } from \"@bgub/fig\";\nimport {\n assertPayloadCodecMatches,\n jsonPayloadCodec,\n loadContextCapabilities,\n} from \"@bgub/fig/internal\";\nimport {\n decodePayloadStream,\n type PayloadDecodeOptions,\n} from \"@bgub/fig/payload\";\nimport { insertAssetResources } from \"./asset-resources.ts\";\n\ndeclare const __FIG_DEV__: boolean | undefined;\n\nconst __DEV__ = typeof __FIG_DEV__ === \"boolean\" ? __FIG_DEV__ : false;\nconst noop = (): void => undefined;\n\nexport type PayloadDecoderOptions = Pick<\n PayloadDecodeOptions,\n \"prepareAssets\" | \"resolveClientReference\" | \"retainAssets\"\n>;\n\n/**\n * Decodes a validated Payload response within one data-resource generation.\n * The root becomes the entry value, streamed holes keep filling for the\n * generation's lifetime, `data` rows hydrate through its guarded capability,\n * and discovered assets enter the document with dependent reveal gates.\n */\nexport async function decodePayloadResponse(\n response: Response,\n context: DataResourceLoadContext,\n options: PayloadDecoderOptions = {},\n): Promise<AwaitedFigNode> {\n const { signal } = context;\n if (signal.aborted) {\n await response.body?.cancel().catch(noop);\n throw abortReason(signal);\n }\n if (!response.ok) {\n await response.body?.cancel().catch(noop);\n throw new Error(`Payload request failed with status ${response.status}.`);\n }\n const body = response.body;\n if (body === null) {\n throw new Error(\"Payload response did not include a body.\");\n }\n try {\n assertPayloadCodecMatches(\n jsonPayloadCodec,\n response.headers.get(\"content-type\"),\n );\n } catch (error) {\n await body.cancel().catch(noop);\n throw error;\n }\n\n const capabilities = loadContextCapabilities(context);\n return decodePayloadStream(body, {\n // Absent outside a data store: data rows are ignored rather than hydrated.\n hydrate: capabilities?.hydrate,\n onHoleError: capabilities?.attributeError,\n // Post-root failures surface through the rejected holes they strand;\n // observing the stream end keeps a failure that no longer has a pending\n // slot from being silently discarded in development.\n onStreamDone: (result) => {\n if (__DEV__ && result.status === \"failed\") {\n console.error(\n \"Payload decode failed after its root value published:\",\n result.error,\n );\n }\n },\n prepareAssets:\n options.prepareAssets ?? ((assets) => insertAssetResources(assets)),\n retainAssets: options.retainAssets,\n resolveClientReference: options.resolveClientReference,\n signal,\n });\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new Error(\"Payload request aborted.\");\n}\n","import type { DataResourceKeyInput } from \"@bgub/fig\";\n\nexport function encodePayloadKey(value: unknown): DataResourceKeyInput {\n const ids = new WeakMap<object, number>();\n let nextId = 1;\n\n function encode(value: unknown): DataResourceKeyInput {\n if (value === null) return null;\n if (value === undefined) return [\"undefined\"];\n if (typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") {\n if (Number.isNaN(value)) return [\"number\", \"NaN\"];\n if (value === Infinity) return [\"number\", \"Infinity\"];\n if (value === -Infinity) return [\"number\", \"-Infinity\"];\n return Object.is(value, -0) ? [\"number\", \"-0\"] : value;\n }\n if (typeof value === \"bigint\") return [\"bigint\", value.toString()];\n if (typeof value === \"symbol\") {\n const key = Symbol.keyFor(value);\n if (key === undefined) {\n throw new Error(\"Only global Symbol.for symbols can be serialized.\");\n }\n return [\"symbol\", key];\n }\n if (typeof value === \"function\") {\n throw new Error(\"Functions cannot be serialized into the payload.\");\n }\n if (value instanceof Date) {\n const json = value.toJSON();\n if (json === null) {\n throw new Error(\"Invalid Date values cannot be serialized.\");\n }\n return [\"date\", json];\n }\n\n const existing = ids.get(value);\n if (existing !== undefined) return [\"ref\", existing];\n const id = nextId++;\n ids.set(value, id);\n\n if (Array.isArray(value)) {\n return [\"array\", id, value.map(encode)];\n }\n if (value instanceof Map) {\n return [\n \"map\",\n id,\n Array.from(value, ([key, item]) => [encode(key), encode(item)]),\n ];\n }\n if (value instanceof Set) {\n return [\"set\", id, Array.from(value, encode)];\n }\n\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(\n `Cannot serialize ${prototype?.constructor?.name ?? \"object\"} into the payload.`,\n );\n }\n const record = value as Record<string, unknown>;\n return [\n \"object\",\n id,\n Object.keys(record)\n .sort()\n .map((key) => [key, encode(record[key])]),\n ];\n }\n\n return encode(value);\n}\n","import {\n type AwaitedFigNode,\n dataResource,\n type DataResource,\n type DataResourceKey,\n type DataResourceKeyInput,\n type FigNode,\n readData,\n} from \"@bgub/fig\";\nimport { loadContextCapabilities } from \"@bgub/fig/internal\";\nimport {\n decodePayloadResponse,\n type PayloadDecoderOptions,\n} from \"./payload-decoder.ts\";\nimport { encodePayloadKey } from \"./payload-key.ts\";\n\n/** Describes payload source. */\nexport type PayloadSource =\n | Response\n | {\n contentType: string;\n stream: ReadableStream<Uint8Array>;\n };\n\n/** Describes payload component load context. */\nexport interface PayloadComponentLoadContext {\n key: DataResourceKey;\n signal: AbortSignal;\n}\n\n/** Describes payload component loader. */\nexport interface PayloadComponentLoader<\n TProps extends object,\n> extends PayloadDecoderOptions {\n (\n props: TProps,\n context: PayloadComponentLoadContext,\n ): PayloadSource | PromiseLike<PayloadSource>;\n}\n\n/** Describes payload component options. */\nexport interface PayloadComponentOptions<\n TProps extends object,\n> extends PayloadDecoderOptions {\n cacheKey?: (props: TProps) => DataResourceKeyInput;\n key: DataResourceKey;\n load: PayloadComponentLoader<TProps>;\n}\n\n/** Describes payload component. */\nexport interface PayloadComponent<TProps extends object> extends DataResource<\n [TProps],\n AwaitedFigNode\n> {\n (props: TProps & { children?: FigNode }): FigNode;\n}\n\n/**\n * Creates a renderable Payload tree backed by Fig's ordinary data store.\n */\nexport function createPayloadComponent<TProps extends object>(\n options: PayloadComponentOptions<TProps>,\n): PayloadComponent<TProps> {\n const key = (props: TProps): DataResourceKey => {\n const serialized = serializedProps(props);\n return [\n ...options.key,\n options.cacheKey === undefined ? serialized : options.cacheKey(props),\n ];\n };\n const resource = dataResource<[TProps], AwaitedFigNode>({\n debugArgs: options.cacheKey === undefined ? undefined : serializedProps,\n key,\n load: async (props, context) => {\n const source = await options.load(props, {\n key: loadContextCapabilities(context)?.key ?? key(props),\n signal: context.signal,\n });\n const response =\n source instanceof Response\n ? source\n : new Response(source.stream, {\n headers: { \"content-type\": source.contentType },\n });\n return decodePayloadResponse(response, context, {\n prepareAssets: options.prepareAssets ?? options.load.prepareAssets,\n resolveClientReference:\n options.resolveClientReference ?? options.load.resolveClientReference,\n retainAssets: options.retainAssets ?? options.load.retainAssets,\n });\n },\n });\n\n const component: PayloadComponent<TProps> = Object.assign(\n function PayloadComponent(props: TProps & { children?: FigNode }): FigNode {\n rejectChildren(props);\n return readData(component, props);\n },\n resource,\n );\n Object.defineProperty(component, \"displayName\", {\n configurable: true,\n value: `Payload(${options.key[0]})`,\n });\n\n return component;\n}\n\nfunction serializedProps<TProps extends object>(\n props: TProps,\n): DataResourceKeyInput {\n rejectChildren(props);\n return encodePayloadKey(props);\n}\n\nfunction rejectChildren(props: object): void {\n if (Object.hasOwn(props, \"children\")) {\n throw new Error(\"Payload components do not accept children.\");\n }\n}\n","/**\n * Browser DOM rendering APIs for Fig applications.\n *\n * @module\n */\nimport type { FigNode, FigPortal, Key } from \"@bgub/fig\";\nimport {\n createPortalNode,\n type FigDataStore,\n readBrowser as readBrowserDuringRender,\n} from \"@bgub/fig/internal\";\nimport type {\n FigRoot,\n FigRootOptions,\n RecoverableErrorInfo,\n} from \"@bgub/fig-reconciler\";\nimport { composeBind, hostBinding } from \"./bind.ts\";\nimport {\n type EventCallback,\n type EventOptions,\n on,\n} from \"./event-descriptor.ts\";\nimport { type Container, registerRoot, unregisterRoot } from \"./events.ts\";\nimport { domRenderer } from \"./renderer.ts\";\nimport { adoptStreamedData } from \"./streamed-data.ts\";\n\nexport { insertAssetResources } from \"./asset-resources.ts\";\nexport type { Bind, Binding, HostBinding } from \"./bind.ts\";\nexport { composeBind, hostBinding };\nexport { type EventCallback, type EventOptions, on };\nexport type {\n EmptyPropValue,\n HostIntrinsicElements,\n HostProps,\n HostStyle,\n} from \"./jsx.ts\";\nexport {\n createPayloadComponent,\n type PayloadComponent,\n type PayloadComponentLoadContext,\n type PayloadComponentLoader,\n type PayloadComponentOptions,\n type PayloadSource,\n} from \"./payload-component.ts\";\n\nexport type { Container, FigRoot, FigRootOptions, RecoverableErrorInfo };\n\n/** Describes why a component requires browser rendering. */\nexport type BrowserRenderReason = string | (() => unknown);\n\n/**\n * Leaves the closest server-rendered Suspense boundary in its fallback state\n * so this component can render in the browser. This is a no-op during browser\n * rendering. A lazy reason is evaluated only by the server.\n */\nexport function readBrowser(reason?: BrowserRenderReason): void {\n readBrowserDuringRender(reason);\n}\n\n/** The flush sync. */\nexport const flushSync = domRenderer.flushSync;\n\n/** Creates root. */\nexport function createRoot(\n container: Container,\n options?: FigRootOptions,\n): FigRoot {\n const root = domRenderer.createRoot(container, options);\n registerRoot(container, { run: (callback) => root.data.run(callback) });\n return withEventTeardown(root, container);\n}\n\n/** Hydrates root. */\nexport function hydrateRoot(\n container: Container,\n children: FigNode,\n options?: FigRootOptions,\n): FigRoot {\n const root = domRenderer.hydrateRoot(container, children, options);\n registerRoot(container, {\n hydrate: (target, priority) =>\n domRenderer.hydrateTarget(container, target, priority),\n run: (callback) => root.data.run(callback),\n });\n // The root's handle is its renderer store, which accepts streamed rows.\n return withEventTeardown(\n root,\n container,\n adoptStreamedData(\n container,\n options?.identifierPrefix ?? \"\",\n root.data as FigDataStore,\n ),\n );\n}\n\n/** Creates portal. */\nexport function createPortal(\n children: FigNode,\n container: Container,\n key: Key | null = null,\n): FigPortal<Container> {\n return createPortalNode(children, container, key);\n}\n\n// Event routing lives outside the reconciler, so root teardown owns both.\nfunction withEventTeardown(\n root: FigRoot,\n container: Container,\n release?: () => void,\n): FigRoot {\n return {\n ...root,\n unmount: () => {\n release?.();\n root.unmount();\n unregisterRoot(container);\n },\n };\n}\n"],"mappings":"kZA8BA,SAAgB,EACd,EACA,EACA,EAC0B,CAC1B,IAAM,EAAO,EAAU,eAAiB,EAClC,EAAU,EACV,EAAU,EAAQ,KAA4B,CAAC,EAC/C,EAAS,EAAO,GACtB,GAAI,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AO,CACL,GAAG,EACH,YAAe,CACb,IAAU,EACV,EAAK,QAAQ,EACb,EAAe,CAAS,CAC1B,CACF,CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bgub/fig-dom",
3
- "version": "2.1.0",
3
+ "version": "2.2.1",
4
4
  "description": "Fig DOM renderer",
5
5
  "keywords": [],
6
6
  "homepage": "https://github.com/bgub/fig",
@@ -64,14 +64,14 @@
64
64
  "access": "public"
65
65
  },
66
66
  "dependencies": {
67
- "@bgub/fig-reconciler": "2.1.0"
67
+ "@bgub/fig-reconciler": "2.2.1"
68
68
  },
69
69
  "peerDependencies": {
70
- "@bgub/fig": "2.1.0"
70
+ "@bgub/fig": "2.2.1"
71
71
  },
72
72
  "devDependencies": {
73
- "@bgub/fig-server": "2.1.0",
74
- "@bgub/fig": "2.1.0"
73
+ "@bgub/fig-server": "2.2.1",
74
+ "@bgub/fig": "2.2.1"
75
75
  },
76
76
  "engines": {
77
77
  "node": "^20.19.0 || >=22.12.0"