@fluid-app/widget-runtime 0.1.281 → 0.1.283

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.
Files changed (74) hide show
  1. package/dist/index.cjs +2 -2
  2. package/dist/index.d.cts +3 -3
  3. package/dist/index.d.mts +3 -3
  4. package/dist/index.mjs +2 -2
  5. package/dist/{remote-dom-renderer-BGIZ0FRi.d.mts → remote-dom-renderer-BnqVsw6k.d.mts} +4 -8
  6. package/dist/remote-dom-renderer-BnqVsw6k.d.mts.map +1 -0
  7. package/dist/remote-dom-renderer-CMpuJrkw.cjs +471 -0
  8. package/dist/remote-dom-renderer-CMpuJrkw.cjs.map +1 -0
  9. package/dist/remote-dom-renderer-D2FspToS.mjs +466 -0
  10. package/dist/remote-dom-renderer-D2FspToS.mjs.map +1 -0
  11. package/dist/{remote-dom-renderer-BoB9jd3B.d.cts → remote-dom-renderer-D3Jz1sOH.d.cts} +4 -8
  12. package/dist/remote-dom-renderer-D3Jz1sOH.d.cts.map +1 -0
  13. package/dist/{remote-dom-renderer-m5bn0hcE.mjs → remote-dom-styles-CmHfrrKz.mjs} +261 -702
  14. package/dist/remote-dom-styles-CmHfrrKz.mjs.map +1 -0
  15. package/dist/{remote-dom-renderer-VA5axIKk.cjs → remote-dom-styles-RV40tYyt.cjs} +328 -698
  16. package/dist/remote-dom-styles-RV40tYyt.cjs.map +1 -0
  17. package/dist/{remote-dom-ui-contract-B140dMly.d.mts → remote-dom-ui-contract-Dr0q3O4E.d.cts} +75 -77
  18. package/dist/remote-dom-ui-contract-Dr0q3O4E.d.cts.map +1 -0
  19. package/dist/{remote-dom-ui-contract-BLOyWbT2.d.cts → remote-dom-ui-contract-Dr0q3O4E.d.mts} +75 -77
  20. package/dist/remote-dom-ui-contract-Dr0q3O4E.d.mts.map +1 -0
  21. package/dist/remote-dom-values-BBN5u_Mj.mjs +1358 -0
  22. package/dist/remote-dom-values-BBN5u_Mj.mjs.map +1 -0
  23. package/dist/{remote-dom-values-D4AgBNWr.d.cts → remote-dom-values-BR8Qnhg9.d.cts} +1 -3
  24. package/dist/remote-dom-values-BR8Qnhg9.d.cts.map +1 -0
  25. package/dist/remote-dom-values-D1Fi2ibn.cjs +1441 -0
  26. package/dist/remote-dom-values-D1Fi2ibn.cjs.map +1 -0
  27. package/dist/{remote-dom-values-EwoLXnSn.d.mts → remote-dom-values-D8qikv8I.d.mts} +2 -3
  28. package/dist/remote-dom-values-D8qikv8I.d.mts.map +1 -0
  29. package/dist/remote-dom.cjs +2 -2
  30. package/dist/remote-dom.d.cts +2 -2
  31. package/dist/remote-dom.d.mts +2 -2
  32. package/dist/remote-dom.mjs +2 -2
  33. package/dist/site-host.cjs +372 -0
  34. package/dist/site-host.cjs.map +1 -0
  35. package/dist/site-host.d.cts +61 -0
  36. package/dist/site-host.d.cts.map +1 -0
  37. package/dist/site-host.d.mts +61 -0
  38. package/dist/site-host.d.mts.map +1 -0
  39. package/dist/site-host.mjs +369 -0
  40. package/dist/site-host.mjs.map +1 -0
  41. package/dist/{worker-react-bootstrap-C7tCMYGA.mjs → worker-react-bootstrap-CwlNMpMT.mjs} +2 -3
  42. package/dist/{worker-react-bootstrap-C7tCMYGA.mjs.map → worker-react-bootstrap-CwlNMpMT.mjs.map} +1 -1
  43. package/dist/{worker-react-bootstrap-N8jcWZ3L.cjs → worker-react-bootstrap-Dbq9hU1k.cjs} +2 -3
  44. package/dist/{worker-react-bootstrap-N8jcWZ3L.cjs.map → worker-react-bootstrap-Dbq9hU1k.cjs.map} +1 -1
  45. package/dist/{worker-react-renderer-ByjjgyrY.cjs → worker-react-renderer-CsI-dsP5.cjs} +5 -6
  46. package/dist/worker-react-renderer-CsI-dsP5.cjs.map +1 -0
  47. package/dist/{worker-react-renderer-ggcPIDLl.mjs → worker-react-renderer-LC2Dr-gj.mjs} +5 -5
  48. package/dist/{worker-react-renderer-ggcPIDLl.mjs.map → worker-react-renderer-LC2Dr-gj.mjs.map} +1 -1
  49. package/dist/worker.cjs +12 -17
  50. package/dist/worker.cjs.map +1 -1
  51. package/dist/worker.d.cts +15 -13
  52. package/dist/worker.d.cts.map +1 -1
  53. package/dist/worker.d.mts +16 -14
  54. package/dist/worker.d.mts.map +1 -1
  55. package/dist/worker.mjs +9 -13
  56. package/dist/worker.mjs.map +1 -1
  57. package/package.json +11 -6
  58. package/dist/Thread-0eUyc0Hw.cjs +0 -591
  59. package/dist/Thread-0eUyc0Hw.cjs.map +0 -1
  60. package/dist/Thread-BiW7rXts.mjs +0 -574
  61. package/dist/Thread-BiW7rXts.mjs.map +0 -1
  62. package/dist/remote-dom-renderer-BGIZ0FRi.d.mts.map +0 -1
  63. package/dist/remote-dom-renderer-BoB9jd3B.d.cts.map +0 -1
  64. package/dist/remote-dom-renderer-VA5axIKk.cjs.map +0 -1
  65. package/dist/remote-dom-renderer-m5bn0hcE.mjs.map +0 -1
  66. package/dist/remote-dom-ui-contract-B140dMly.d.mts.map +0 -1
  67. package/dist/remote-dom-ui-contract-BLOyWbT2.d.cts.map +0 -1
  68. package/dist/remote-dom-values-B5UZPDRy.cjs +0 -849
  69. package/dist/remote-dom-values-B5UZPDRy.cjs.map +0 -1
  70. package/dist/remote-dom-values-D4AgBNWr.d.cts.map +0 -1
  71. package/dist/remote-dom-values-EwoLXnSn.d.mts.map +0 -1
  72. package/dist/remote-dom-values-wEbrw5iW.mjs +0 -790
  73. package/dist/remote-dom-values-wEbrw5iW.mjs.map +0 -1
  74. package/dist/worker-react-renderer-ByjjgyrY.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-host.cjs","names":["REMOTE_DOM_SITE_UI_CONTRACT_VERSION","isRemoteDomSerializableValue","normalizeNavigationOrigin","createRemoteDomUrlOriginPolicy","attachRemoteDomStyles","reportHostError","reportCleanupErrors","collectCleanupErrors","Thread","createSubmitPreventionListener","handleRemoteDomNavigationIntent","createSanitizingRemoteConnection","enforceAllowedAnchorSafety","callRemoteDomCapability","ROOT_ID","createRemoteConnection","UPDATE_PROPERTY_TYPE_PROPERTY","NODE_TYPE_TEXT","NODE_TYPE_COMMENT","NODE_TYPE_ELEMENT","REMOTE_DOM_NODE_ID_ATTRIBUTE","UPDATE_PROPERTY_TYPE_ATTRIBUTE","UPDATE_PROPERTY_TYPE_EVENT_LISTENER","retain","release","hasCloserRemoteEventListener","deliverRemoteDomEvent"],"sources":["../src/site-host.ts"],"sourcesContent":["// The host for member sites: draws a sandboxed widget into the page's own DOM\n// with no React (widgets plan, step 2.1; L-W.4, L-W.22). Every mutation the\n// worker sends passes the same sanitizer as the React host before it is\n// applied here, and nothing in this module may import React\n// (`scripts/verify-site-host-no-react.mjs`).\nimport { release, retain, Thread } from \"@quilted/threads\";\nimport {\n createRemoteConnection,\n NODE_TYPE_COMMENT,\n NODE_TYPE_ELEMENT,\n NODE_TYPE_TEXT,\n ROOT_ID,\n UPDATE_PROPERTY_TYPE_ATTRIBUTE,\n UPDATE_PROPERTY_TYPE_EVENT_LISTENER,\n UPDATE_PROPERTY_TYPE_PROPERTY,\n type RemoteConnection,\n type RemoteNodeSerialization,\n} from \"@remote-dom/core\";\nimport {\n callRemoteDomCapability,\n collectCleanupErrors,\n createSubmitPreventionListener,\n deliverRemoteDomEvent,\n enforceAllowedAnchorSafety,\n handleRemoteDomNavigationIntent,\n hasCloserRemoteEventListener,\n normalizeNavigationOrigin,\n REMOTE_DOM_NODE_ID_ATTRIBUTE,\n reportCleanupErrors,\n reportHostError,\n type RemoteDomCapabilityHandler,\n} from \"./remote-dom-host-shared\";\nimport { createSanitizingRemoteConnection } from \"./remote-dom-sanitizing-connection\";\nimport {\n attachRemoteDomStyles,\n REMOTE_DOM_WIDGET_STYLE_ATTRIBUTE,\n type RemoteDomCssFetcher,\n type RemoteDomStyleAttachment,\n type RemoteDomThemeBridgeOptions,\n} from \"./remote-dom-styles\";\nimport { REMOTE_DOM_SITE_UI_CONTRACT_VERSION } from \"./remote-dom-ui-contract\";\nimport {\n createRemoteDomUrlOriginPolicy,\n isRemoteDomSerializableValue,\n type RemoteDomNavigationIntent,\n type RemoteDomSerializableValue,\n} from \"./remote-dom-values\";\nimport type {\n RemoteDomWidgetArtifact,\n RemoteDomWorkerFactory,\n RemoteDomWorkerLike,\n} from \"./remote-dom-renderer\";\nimport type {\n RemoteDomWidgetWorkerApi,\n RemoteDomWidgetWorkerHostApi,\n} from \"./worker-runtime\";\n\n/**\n * The site host offers only the site contract. Workers built today require\n * contract 2 and carry React, so they refuse this host; a build for sites\n * names the site contract (`uiContractVersions`) and mounts.\n */\nexport const SITE_HOST_UI_CONTRACT_VERSIONS: readonly string[] = [\n REMOTE_DOM_SITE_UI_CONTRACT_VERSION,\n];\n\nexport interface MountSiteWidgetOptions {\n readonly host: HTMLElement;\n readonly artifact: RemoteDomWidgetArtifact;\n readonly props?: RemoteDomSerializableValue | undefined;\n /** Answers the widget's capability calls. Fluid data goes through the site. */\n readonly callCapability?: RemoteDomCapabilityHandler | undefined;\n readonly onNavigate?:\n | ((intent: RemoteDomNavigationIntent) => void | Promise<void>)\n | undefined;\n readonly onError?: ((error: Error) => void) | undefined;\n readonly workerFactory?: RemoteDomWorkerFactory | undefined;\n /**\n * The site's origin. The worker must be served from it, under the policy\n * the gateway sends for widget code (O-W.13). Defaults to `location.origin`.\n */\n readonly siteOrigin?: string | undefined;\n /**\n * Origins drawn images and media may load from besides the package's own\n * files. Empty by default: unlike other hosts, no shared media host is\n * allowed unless the caller names it (O-W.13).\n */\n readonly mediaOrigins?: readonly string[] | undefined;\n readonly allowedAnchorUrls?: ReadonlySet<string> | undefined;\n readonly maxMutationBatchSize?: number | undefined;\n readonly maxDomNodeCount?: number | undefined;\n readonly cssText?: string | undefined;\n readonly widgetCssText?: string | undefined;\n readonly themeBridgeCssText?: string | undefined;\n readonly themeBridge?:\n | Omit<RemoteDomThemeBridgeOptions, \"root\">\n | false\n | undefined;\n readonly fetchCss?: RemoteDomCssFetcher | undefined;\n}\n\nexport interface SiteWidgetHandle {\n readonly shadowRoot: ShadowRoot;\n readonly styles: RemoteDomStyleAttachment;\n readonly ready: Promise<void>;\n updateProps(props: RemoteDomSerializableValue): void;\n dispose(): void;\n}\n\nconst DEFAULT_MAX_MUTATION_BATCH_SIZE = 1_000;\nconst DEFAULT_MAX_DOM_NODE_COUNT = 1_000;\n\ntype RemoteListener = (...args: readonly unknown[]) => unknown;\n\ninterface DrawnElement {\n readonly element: Element;\n readonly tagName: string;\n readonly listeners: Map<string, RemoteListener>;\n readonly handlers: Map<string, EventListener>;\n}\n\ninterface SiteHostState {\n readonly options: MountSiteWidgetOptions;\n readonly shadowRoot: ShadowRoot;\n readonly renderContainer: HTMLElement;\n readonly worker: RemoteDomWorkerLike;\n readonly thread: Thread<RemoteDomWidgetWorkerApi>;\n readonly styles: RemoteDomStyleAttachment;\n readonly drawn: DomTree;\n readonly submitListener: EventListener;\n readonly navigationListener: EventListener;\n disposed: boolean;\n}\n\n/**\n * Mounts one widget on a member site.\n *\n * Refuses a worker served from another origin, and a widget granted network\n * access: on a site the sandbox's limit comes from the policy on the worker's\n * own response, which a cross-origin or blob worker would not carry.\n *\n * Raises TypeError when the props aren't serializable, the artifact asks for\n * network access, or the worker isn't on the site's origin.\n */\nexport function mountSiteWidget(\n options: MountSiteWidgetOptions,\n): SiteWidgetHandle {\n const initialProps = options.props ?? null;\n if (!isRemoteDomSerializableValue(initialProps)) {\n throw new TypeError(\"Initial widget props must be serializable\");\n }\n if (options.artifact.networkAccessGranted === true) {\n throw new TypeError(\n \"Widgets on member sites can't be granted network access\",\n );\n }\n const siteOrigin = normalizeNavigationOrigin(\n options.siteOrigin ??\n (typeof location === \"undefined\" ? undefined : location.origin),\n );\n if (!siteOrigin) {\n throw new TypeError(\"A site widget needs the site's http(s) origin\");\n }\n if (!isOnOrigin(options.artifact.workerEntryUrl, siteOrigin)) {\n throw new TypeError(\"A site widget's worker must be served from the site\");\n }\n\n const shadowRoot =\n options.host.shadowRoot ?? options.host.attachShadow({ mode: \"open\" });\n shadowRoot.replaceChildren();\n const urlOriginPolicy = createRemoteDomUrlOriginPolicy({\n artifactUrls: [\n options.artifact.workerEntryUrl,\n ...options.artifact.cssUrls,\n ...options.artifact.assetUrls,\n ],\n mediaOrigins: options.mediaOrigins ?? [],\n navigationOrigin: siteOrigin,\n });\n const styles = attachRemoteDomStyles({\n artifact: options.artifact,\n root: shadowRoot,\n urlOriginPolicy,\n onFailure: (count) => {\n reportHostError(options, `${count} site widget styles failed to load`);\n },\n ...(options.cssText === undefined ? {} : { cssText: options.cssText }),\n ...(options.widgetCssText === undefined\n ? {}\n : { widgetCssText: options.widgetCssText }),\n ...(options.themeBridgeCssText === undefined\n ? {}\n : { themeBridgeCssText: options.themeBridgeCssText }),\n ...(options.themeBridge === undefined\n ? {}\n : { themeBridge: options.themeBridge }),\n ...(options.fetchCss === undefined ? {} : { fetchCss: options.fetchCss }),\n });\n\n let worker: RemoteDomWorkerLike;\n try {\n worker = (options.workerFactory ?? createSiteWorker)(\n options.artifact.workerEntryUrl,\n { type: \"module\" },\n );\n } catch (error) {\n reportCleanupErrors(\n options,\n \"Site widget setup cleanup failed\",\n collectCleanupErrors([\n () => styles.dispose(),\n () => clearDrawnNodes(shadowRoot),\n ]),\n );\n throw error;\n }\n\n const thread = new Thread<RemoteDomWidgetWorkerApi>({\n send(message, transferables) {\n worker.postMessage(message, transferables ?? []);\n },\n listen(listener, { signal }) {\n const onMessage = (event: MessageEvent<unknown>): void => {\n listener(event.data);\n };\n if (worker.addEventListener) {\n worker.addEventListener(\"message\", onMessage, { signal });\n return;\n }\n worker.onmessage = onMessage;\n signal?.addEventListener(\n \"abort\",\n () => {\n worker.onmessage = null;\n },\n { once: true },\n );\n },\n });\n\n const renderContainer = document.createElement(\"div\");\n renderContainer.setAttribute(\"data-fluid-remote-dom-render-root\", \"\");\n shadowRoot.append(renderContainer);\n\n let state: SiteHostState;\n const isDisposed = (): boolean => state.disposed;\n const drawn = new DomTree(renderContainer, options, isDisposed);\n state = {\n options,\n shadowRoot,\n renderContainer,\n worker,\n thread,\n styles,\n drawn,\n submitListener: createSubmitPreventionListener(),\n navigationListener: (event) => {\n handleRemoteDomNavigationIntent(\n {\n shadowRoot,\n urlOriginPolicy,\n navigationOrigin: siteOrigin,\n allowedAnchorUrls: options.allowedAnchorUrls,\n onNavigate: options.onNavigate,\n onError: options.onError,\n isDisposed,\n },\n event,\n );\n },\n disposed: false,\n };\n\n const connection = createSanitizingRemoteConnection({\n connection: drawn.connection,\n ...(options.allowedAnchorUrls\n ? { allowedAnchorUrls: options.allowedAnchorUrls }\n : {}),\n urlOriginPolicy,\n maxMutationBatchSize:\n options.maxMutationBatchSize ?? DEFAULT_MAX_MUTATION_BATCH_SIZE,\n maxDomNodeCount: options.maxDomNodeCount ?? DEFAULT_MAX_DOM_NODE_COUNT,\n onNodeLimitExceeded: () => {\n reportHostError(options, \"Site widget exceeded its DOM node limit\");\n },\n onInvalidRecord: (message) => reportHostError(options, message),\n onMutateError: (error) =>\n reportHostError(\n options,\n \"Site widget mutation could not be applied\",\n error,\n ),\n });\n\n shadowRoot.addEventListener(\"submit\", state.submitListener, {\n capture: true,\n });\n shadowRoot.addEventListener(\"click\", state.navigationListener, {\n capture: true,\n });\n worker.onerror = (event) => {\n // An uncaught throw in the worker is re-reported on the page unless the\n // event is cancelled; a widget's fault must not reach the site's handlers.\n event.preventDefault?.();\n if (state.disposed) return;\n reportHostError(\n options,\n event.message || \"Site widget worker failed\",\n event.error,\n );\n disposeQuietly(state, false);\n };\n\n const hostApi: RemoteDomWidgetWorkerHostApi = {\n mutate(records) {\n if (state.disposed) return;\n connection.mutate(records);\n enforceAllowedAnchorSafety(shadowRoot, options.allowedAnchorUrls);\n },\n callCapability(capability, method, payload) {\n return callRemoteDomCapability(\n {\n declared: options.artifact.capabilities,\n host: options.host,\n shadowRoot,\n callCapability: options.callCapability,\n onError: options.onError,\n isDisposed,\n },\n capability,\n method,\n payload,\n );\n },\n reportError(error) {\n reportHostError(options, error.message);\n },\n };\n\n const ready = Promise.all([\n styles.ready,\n thread.imports.mount(\n {\n widgetType: options.artifact.widgetType,\n props: initialProps,\n supportedUiContractVersions: SITE_HOST_UI_CONTRACT_VERSIONS,\n },\n hostApi,\n ),\n ]).then(() => undefined);\n void ready.catch((error: unknown) => {\n if (state.disposed) return;\n reportHostError(options, \"Site widget failed to mount\", error);\n disposeQuietly(state);\n });\n\n return {\n shadowRoot,\n styles,\n ready,\n updateProps(props) {\n if (state.disposed) return;\n if (!isRemoteDomSerializableValue(props)) {\n throw new TypeError(\"Widget props must be serializable\");\n }\n void state.thread.imports.updateProps(props).catch((error: unknown) => {\n if (!state.disposed) {\n reportHostError(options, \"Site widget props update failed\", error);\n }\n });\n },\n dispose() {\n disposeSiteWidget(state);\n },\n };\n}\n\n/**\n * Starts the worker straight from its URL. No blob wrapper: a blob worker\n * takes the page's policy instead of the one on the worker's response.\n */\nexport function createSiteWorker(\n workerEntryUrl: string,\n options: WorkerOptions,\n): RemoteDomWorkerLike {\n if (typeof Worker === \"undefined\") {\n throw new Error(\"Workers are not available in this environment\");\n }\n return new Worker(workerEntryUrl, options);\n}\n\n// Only an http(s) URL on the site counts: a same-origin `blob:` or `data:`\n// worker would take the page's policy, not the one on the worker's response.\nfunction isOnOrigin(url: string, origin: string): boolean {\n try {\n const parsed = new URL(url, origin);\n return (\n (parsed.protocol === \"https:\" || parsed.protocol === \"http:\") &&\n parsed.origin === origin\n );\n } catch {\n return false;\n }\n}\n\n/** Applies sanitized Remote DOM records to real DOM nodes. */\nclass DomTree {\n readonly connection: RemoteConnection;\n private readonly nodes = new Map<string, Node>();\n private readonly ids = new WeakMap<Node, string>();\n private readonly elements = new Map<string, DrawnElement>();\n\n constructor(\n private readonly container: HTMLElement,\n private readonly reporter: MountSiteWidgetOptions,\n private readonly isDisposed: () => boolean,\n ) {\n this.elements.set(ROOT_ID, {\n element: container,\n tagName: \"\",\n listeners: new Map(),\n handlers: new Map(),\n });\n this.connection = createRemoteConnection({\n call: (_id, method) => {\n throw new Error(`Site widget method \"${method}\" is not allowed`);\n },\n insertChild: (parentId, child, index) => {\n const parent = this.parentNode(parentId);\n const node = this.build(child);\n parent.insertBefore(node, parent.childNodes[index] ?? null);\n },\n removeChild: (parentId, index) => {\n const parent = this.parentNode(parentId);\n const node = parent.childNodes[index];\n if (!node) throw new Error(`No child at ${index} of \"${parentId}\"`);\n this.forget(node);\n node.remove();\n },\n // A late update for a node an earlier record removed is dropped, as\n // Remote DOM's own receivers do.\n updateText: (id, text) => {\n const node = this.nodes.get(id);\n if (node instanceof CharacterData) node.data = text;\n },\n updateProperty: (id, name, value, type) => {\n const drawn = this.elements.get(id);\n if (drawn) {\n this.apply(drawn, name, value, type ?? UPDATE_PROPERTY_TYPE_PROPERTY);\n }\n },\n });\n }\n\n clear(): void {\n for (const child of Array.from(this.container.childNodes)) {\n this.forget(child);\n child.remove();\n }\n const root = this.elements.get(ROOT_ID);\n if (root) {\n for (const eventName of Array.from(root.listeners.keys())) {\n this.listen(root, eventName, null);\n }\n }\n }\n\n private parentNode(id: string): Node {\n const parent = id === ROOT_ID ? this.container : this.nodes.get(id);\n if (!parent) throw new Error(`Parent \"${id}\" is missing`);\n return parent;\n }\n\n private build(child: RemoteNodeSerialization): Node {\n let node: Node;\n if (child.type === NODE_TYPE_TEXT) {\n node = document.createTextNode(child.data);\n } else if (child.type === NODE_TYPE_COMMENT) {\n node = document.createComment(child.data);\n } else if (child.type === NODE_TYPE_ELEMENT) {\n const element = document.createElement(child.element);\n element.setAttribute(REMOTE_DOM_NODE_ID_ATTRIBUTE, child.id);\n const drawn: DrawnElement = {\n element,\n tagName: child.element,\n listeners: new Map(),\n handlers: new Map(),\n };\n this.elements.set(child.id, drawn);\n for (const grandchild of child.children ?? []) {\n element.append(this.build(grandchild));\n }\n for (const [name, value] of Object.entries(child.attributes ?? {})) {\n this.apply(drawn, name, value, UPDATE_PROPERTY_TYPE_ATTRIBUTE);\n }\n for (const [name, value] of Object.entries(child.properties ?? {})) {\n this.apply(drawn, name, value, UPDATE_PROPERTY_TYPE_PROPERTY);\n }\n for (const [name, value] of Object.entries(child.eventListeners ?? {})) {\n this.apply(drawn, name, value, UPDATE_PROPERTY_TYPE_EVENT_LISTENER);\n }\n node = element;\n } else {\n throw new Error(\"Unknown Remote DOM node type\");\n }\n this.nodes.set(child.id, node);\n this.ids.set(node, child.id);\n return node;\n }\n\n private apply(\n drawn: DrawnElement,\n name: string,\n value: unknown,\n type: number,\n ): void {\n if (type === UPDATE_PROPERTY_TYPE_EVENT_LISTENER) {\n this.listen(\n drawn,\n name,\n typeof value === \"function\" ? (value as RemoteListener) : null,\n );\n return;\n }\n const { element } = drawn;\n // Form values are live state, as the React host treats them: an input's\n // value and checked come only from properties, and a textarea's value\n // sets what the field shows, not its default.\n if (\n element instanceof HTMLInputElement &&\n (name === \"value\" || name === \"checked\")\n ) {\n if (type !== UPDATE_PROPERTY_TYPE_PROPERTY) return;\n if (name === \"value\" && typeof value === \"string\") element.value = value;\n if (name === \"checked\" && typeof value === \"boolean\")\n element.checked = value;\n return;\n }\n if (element instanceof HTMLTextAreaElement && name === \"value\") {\n element.value = typeof value === \"string\" ? value : \"\";\n return;\n }\n if (value === undefined || value === null || value === false) {\n element.removeAttribute(name);\n } else if (value === true) {\n element.setAttribute(name, \"\");\n } else if (typeof value === \"string\" || typeof value === \"number\") {\n element.setAttribute(name, String(value));\n } else {\n // A structured property of a contract 1 Fluid element: the element\n // reads it as a property, as the React host passes it.\n (element as unknown as Record<string, unknown>)[name] = value;\n }\n }\n\n private listen(\n drawn: DrawnElement,\n eventName: string,\n listener: RemoteListener | null,\n ): void {\n const previous = drawn.listeners.get(eventName);\n if (previous === listener) return;\n // The worker's listener is a proxy across the thread: hold it while it is\n // drawn and let it go when it is replaced or removed.\n if (listener) retain(listener);\n if (previous) release(previous);\n if (!listener) {\n drawn.listeners.delete(eventName);\n const handler = drawn.handlers.get(eventName);\n if (handler) {\n drawn.element.removeEventListener(eventName, handler, {\n capture: drawn.element === this.container,\n });\n drawn.handlers.delete(eventName);\n }\n return;\n }\n drawn.listeners.set(eventName, listener);\n if (drawn.handlers.has(eventName)) return;\n const currentTargetId =\n drawn.element === this.container\n ? ROOT_ID\n : (drawn.element.getAttribute(REMOTE_DOM_NODE_ID_ATTRIBUTE) ?? ROOT_ID);\n const handler: EventListener = (event) => {\n const current = drawn.listeners.get(eventName);\n if (!current) return;\n if (\n hasCloserRemoteEventListener(event, currentTargetId, (id) =>\n Boolean(this.elements.get(id)?.listeners.has(eventName)),\n )\n ) {\n return;\n }\n deliverRemoteDomEvent({\n event,\n eventName,\n currentTargetId,\n ...(drawn.tagName ? { currentTargetTagName: drawn.tagName } : {}),\n listener: current,\n reporter: this.reporter,\n isDisposed: this.isDisposed,\n });\n };\n drawn.handlers.set(eventName, handler);\n drawn.element.addEventListener(eventName, handler, {\n capture: drawn.element === this.container,\n });\n }\n\n private forget(node: Node): void {\n const id = this.ids.get(node);\n if (id !== undefined) {\n const drawn = this.elements.get(id);\n if (drawn) {\n for (const listener of drawn.listeners.values()) release(listener);\n drawn.listeners.clear();\n }\n this.nodes.delete(id);\n this.elements.delete(id);\n }\n for (const child of Array.from(node.childNodes)) this.forget(child);\n }\n}\n\nfunction disposeSiteWidget(state: SiteHostState, notifyWorker = true): void {\n if (state.disposed) return;\n state.disposed = true;\n const errors = collectCleanupErrors([\n () => {\n state.worker.onerror = null;\n },\n () =>\n state.shadowRoot.removeEventListener(\"submit\", state.submitListener, {\n capture: true,\n }),\n () =>\n state.shadowRoot.removeEventListener(\"click\", state.navigationListener, {\n capture: true,\n }),\n () => state.drawn.clear(),\n () => state.styles.dispose(),\n () => clearDrawnNodes(state.shadowRoot),\n ]);\n if (notifyWorker) {\n void Promise.resolve(state.thread.imports.dispose()).catch(() => undefined);\n }\n queueMicrotask(() => {\n reportCleanupErrors(\n state.options,\n \"Site widget asynchronous cleanup failed\",\n collectCleanupErrors([\n () => state.thread.close(),\n () => state.worker.terminate(),\n ]),\n );\n });\n if (errors.length > 0) {\n throw new AggregateError(errors, \"Site widget cleanup failed\");\n }\n}\n\nfunction disposeQuietly(state: SiteHostState, notifyWorker = true): void {\n try {\n disposeSiteWidget(state, notifyWorker);\n } catch (error) {\n reportHostError(\n state.options,\n \"Site widget cleanup failed after an earlier error\",\n error,\n );\n }\n}\n\nfunction clearDrawnNodes(shadowRoot: ShadowRoot): void {\n for (const child of Array.from(shadowRoot.childNodes)) {\n if (\n !(\n child instanceof HTMLStyleElement &&\n child.hasAttribute(REMOTE_DOM_WIDGET_STYLE_ATTRIBUTE)\n )\n ) {\n child.remove();\n }\n }\n}\n"],"mappings":";;;;;;;;;;AA8DA,MAAa,iCAAoD,CAC/DA,0BAAAA,mCACF;AA6CA,MAAM,kCAAkC;AACxC,MAAM,6BAA6B;;;;;;;;;;;AAkCnC,SAAgB,gBACd,SACkB;CAClB,MAAM,eAAe,QAAQ,SAAS;CACtC,IAAI,CAACC,0BAAAA,6BAA6B,YAAY,GAC5C,MAAM,IAAI,UAAU,2CAA2C;CAEjE,IAAI,QAAQ,SAAS,yBAAyB,MAC5C,MAAM,IAAI,UACR,yDACF;CAEF,MAAM,aAAaC,0BAAAA,0BACjB,QAAQ,eACL,OAAO,aAAa,cAAc,KAAA,IAAY,SAAS,OAC5D;CACA,IAAI,CAAC,YACH,MAAM,IAAI,UAAU,+CAA+C;CAErE,IAAI,CAAC,WAAW,QAAQ,SAAS,gBAAgB,UAAU,GACzD,MAAM,IAAI,UAAU,qDAAqD;CAG3E,MAAM,aACJ,QAAQ,KAAK,cAAc,QAAQ,KAAK,aAAa,EAAE,MAAM,OAAO,CAAC;CACvE,WAAW,gBAAgB;CAC3B,MAAM,kBAAkBC,0BAAAA,+BAA+B;EACrD,cAAc;GACZ,QAAQ,SAAS;GACjB,GAAG,QAAQ,SAAS;GACpB,GAAG,QAAQ,SAAS;EACtB;EACA,cAAc,QAAQ,gBAAgB,CAAC;EACvC,kBAAkB;CACpB,CAAC;CACD,MAAM,SAASC,0BAAAA,sBAAsB;EACnC,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QAED,MAAM,WAAW,oBAAoB,SAAS,MAAM,oBAAoB,EACtE,SAAS,KACX,CAAC;QACG,MAAM,MAAM,MAAM;QAClB,MAAM,OAAO,QAAQ;QACrB,gBAAgB,MAAM,UAAU;CACxC,CAAC;CACD,IAAI,cACG,QAAQ,QAAQ,MAAM,OAAO,QAAQ,QAAQ,CAAC,CAAC,CAAC,YAAY,KAAA,CAAS;CAE5E,qBAAqB;EACnBD,0BAAAA,oBACE,MAAM,SACN,2CACAC,0BAAAA,qBAAqB,OACb,MAAM,OAAO,MAAM,SACnB,MAAM,OAAO,UAAU,CAC/B,CAAC,CACH;CACF,CAAC;CACD,IAAI,OAAO,SAAS,GAClB,MAAM,IAAI,eAAe,QAAQ,4BAA4B;AAEjE;AAEA,SAAS,eAAe,OAAsB,eAAe,MAAY;CACvE,IAAI;EACF,kBAAkB,OAAO,YAAY;CACvC,SAAS,OAAO;EACdF,0BAAAA,gBACE,MAAM,SACN,qDACA,KACF;CACF;AACF;AAEA,SAAS,gBAAgB,YAA8B;CACrD,KAAK,MAAM,SAAS,MAAM,KAAK,WAAW,UAAU,GAClD,IACE,EACE,iBAAiB,oBACjB,MAAM,aAAA,yBAA8C,IAGtD,MAAM,OAAO;AAGnB"}
@@ -0,0 +1,61 @@
1
+ import { f as RemoteDomStyleAttachment, i as RemoteDomWidgetArtifact, l as RemoteDomCapabilityHandler, o as RemoteDomWorkerFactory, p as RemoteDomThemeBridgeOptions, s as RemoteDomWorkerLike, u as RemoteDomCssFetcher } from "./remote-dom-renderer-D3Jz1sOH.cjs";
2
+ import { n as RemoteDomSerializableValue, t as RemoteDomNavigationIntent } from "./remote-dom-values-BR8Qnhg9.cjs";
3
+ /**
4
+ * The site host offers only the site contract. Workers built today require
5
+ * contract 2 and carry React, so they refuse this host; a build for sites
6
+ * names the site contract (`uiContractVersions`) and mounts.
7
+ */
8
+ export declare const SITE_HOST_UI_CONTRACT_VERSIONS: readonly string[];
9
+ export interface MountSiteWidgetOptions {
10
+ readonly host: HTMLElement;
11
+ readonly artifact: RemoteDomWidgetArtifact;
12
+ readonly props?: RemoteDomSerializableValue | undefined;
13
+ /** Answers the widget's capability calls. Fluid data goes through the site. */
14
+ readonly callCapability?: RemoteDomCapabilityHandler | undefined;
15
+ readonly onNavigate?: ((intent: RemoteDomNavigationIntent) => void | Promise<void>) | undefined;
16
+ readonly onError?: ((error: Error) => void) | undefined;
17
+ readonly workerFactory?: RemoteDomWorkerFactory | undefined;
18
+ /**
19
+ * The site's origin. The worker must be served from it, under the policy
20
+ * the gateway sends for widget code (O-W.13). Defaults to `location.origin`.
21
+ */
22
+ readonly siteOrigin?: string | undefined;
23
+ /**
24
+ * Origins drawn images and media may load from besides the package's own
25
+ * files. Empty by default: unlike other hosts, no shared media host is
26
+ * allowed unless the caller names it (O-W.13).
27
+ */
28
+ readonly mediaOrigins?: readonly string[] | undefined;
29
+ readonly allowedAnchorUrls?: ReadonlySet<string> | undefined;
30
+ readonly maxMutationBatchSize?: number | undefined;
31
+ readonly maxDomNodeCount?: number | undefined;
32
+ readonly cssText?: string | undefined;
33
+ readonly widgetCssText?: string | undefined;
34
+ readonly themeBridgeCssText?: string | undefined;
35
+ readonly themeBridge?: Omit<RemoteDomThemeBridgeOptions, "root"> | false | undefined;
36
+ readonly fetchCss?: RemoteDomCssFetcher | undefined;
37
+ }
38
+ export interface SiteWidgetHandle {
39
+ readonly shadowRoot: ShadowRoot;
40
+ readonly styles: RemoteDomStyleAttachment;
41
+ readonly ready: Promise<void>;
42
+ updateProps(props: RemoteDomSerializableValue): void;
43
+ dispose(): void;
44
+ }
45
+ /**
46
+ * Mounts one widget on a member site.
47
+ *
48
+ * Refuses a worker served from another origin, and a widget granted network
49
+ * access: on a site the sandbox's limit comes from the policy on the worker's
50
+ * own response, which a cross-origin or blob worker would not carry.
51
+ *
52
+ * Raises TypeError when the props aren't serializable, the artifact asks for
53
+ * network access, or the worker isn't on the site's origin.
54
+ */
55
+ export declare function mountSiteWidget(options: MountSiteWidgetOptions): SiteWidgetHandle;
56
+ /**
57
+ * Starts the worker straight from its URL. No blob wrapper: a blob worker
58
+ * takes the page's policy instead of the one on the worker's response.
59
+ */
60
+ export declare function createSiteWorker(workerEntryUrl: string, options: WorkerOptions): RemoteDomWorkerLike;
61
+ //# sourceMappingURL=site-host.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-host.d.cts","names":[],"sources":["../src/site-host.ts"],"mappings":";;;;;;;qBA8Da;iBAII;WACN,MAAM;WACN,UAAU;WACV,QAAQ;;WAER,iBAAiB;WACjB,eACH,QAAQ,qCAAqC;WAE1C,YAAY,OAAO;WACnB,gBAAgB;;;;;WAKhB;;;;;;WAMA;WACA,oBAAoB;WACpB;WACA;WACA;WACA;WACA;WACA,cACL,KAAK;WAGA,WAAW;;iBAGL;WACN,YAAY;WACZ,QAAQ;WACR,OAAO;EAChB,YAAY,OAAO;EACnB;;;;;;;;;;;;wBAsCc,gBACd,SAAS,yBACR;;;;;wBA2Oa,iBACd,wBACA,SAAS,gBACR"}
@@ -0,0 +1,61 @@
1
+ import { f as RemoteDomStyleAttachment, i as RemoteDomWidgetArtifact, l as RemoteDomCapabilityHandler, o as RemoteDomWorkerFactory, p as RemoteDomThemeBridgeOptions, s as RemoteDomWorkerLike, u as RemoteDomCssFetcher } from "./remote-dom-renderer-BnqVsw6k.mjs";
2
+ import { n as RemoteDomSerializableValue, t as RemoteDomNavigationIntent } from "./remote-dom-values-D8qikv8I.mjs";
3
+ /**
4
+ * The site host offers only the site contract. Workers built today require
5
+ * contract 2 and carry React, so they refuse this host; a build for sites
6
+ * names the site contract (`uiContractVersions`) and mounts.
7
+ */
8
+ export declare const SITE_HOST_UI_CONTRACT_VERSIONS: readonly string[];
9
+ export interface MountSiteWidgetOptions {
10
+ readonly host: HTMLElement;
11
+ readonly artifact: RemoteDomWidgetArtifact;
12
+ readonly props?: RemoteDomSerializableValue | undefined;
13
+ /** Answers the widget's capability calls. Fluid data goes through the site. */
14
+ readonly callCapability?: RemoteDomCapabilityHandler | undefined;
15
+ readonly onNavigate?: ((intent: RemoteDomNavigationIntent) => void | Promise<void>) | undefined;
16
+ readonly onError?: ((error: Error) => void) | undefined;
17
+ readonly workerFactory?: RemoteDomWorkerFactory | undefined;
18
+ /**
19
+ * The site's origin. The worker must be served from it, under the policy
20
+ * the gateway sends for widget code (O-W.13). Defaults to `location.origin`.
21
+ */
22
+ readonly siteOrigin?: string | undefined;
23
+ /**
24
+ * Origins drawn images and media may load from besides the package's own
25
+ * files. Empty by default: unlike other hosts, no shared media host is
26
+ * allowed unless the caller names it (O-W.13).
27
+ */
28
+ readonly mediaOrigins?: readonly string[] | undefined;
29
+ readonly allowedAnchorUrls?: ReadonlySet<string> | undefined;
30
+ readonly maxMutationBatchSize?: number | undefined;
31
+ readonly maxDomNodeCount?: number | undefined;
32
+ readonly cssText?: string | undefined;
33
+ readonly widgetCssText?: string | undefined;
34
+ readonly themeBridgeCssText?: string | undefined;
35
+ readonly themeBridge?: Omit<RemoteDomThemeBridgeOptions, "root"> | false | undefined;
36
+ readonly fetchCss?: RemoteDomCssFetcher | undefined;
37
+ }
38
+ export interface SiteWidgetHandle {
39
+ readonly shadowRoot: ShadowRoot;
40
+ readonly styles: RemoteDomStyleAttachment;
41
+ readonly ready: Promise<void>;
42
+ updateProps(props: RemoteDomSerializableValue): void;
43
+ dispose(): void;
44
+ }
45
+ /**
46
+ * Mounts one widget on a member site.
47
+ *
48
+ * Refuses a worker served from another origin, and a widget granted network
49
+ * access: on a site the sandbox's limit comes from the policy on the worker's
50
+ * own response, which a cross-origin or blob worker would not carry.
51
+ *
52
+ * Raises TypeError when the props aren't serializable, the artifact asks for
53
+ * network access, or the worker isn't on the site's origin.
54
+ */
55
+ export declare function mountSiteWidget(options: MountSiteWidgetOptions): SiteWidgetHandle;
56
+ /**
57
+ * Starts the worker straight from its URL. No blob wrapper: a blob worker
58
+ * takes the page's policy instead of the one on the worker's response.
59
+ */
60
+ export declare function createSiteWorker(workerEntryUrl: string, options: WorkerOptions): RemoteDomWorkerLike;
61
+ //# sourceMappingURL=site-host.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-host.d.mts","names":[],"sources":["../src/site-host.ts"],"mappings":";;;;;;;qBA8Da;iBAII;WACN,MAAM;WACN,UAAU;WACV,QAAQ;;WAER,iBAAiB;WACjB,eACH,QAAQ,qCAAqC;WAE1C,YAAY,OAAO;WACnB,gBAAgB;;;;;WAKhB;;;;;;WAMA;WACA,oBAAoB;WACpB;WACA;WACA;WACA;WACA;WACA,cACL,KAAK;WAGA,WAAW;;iBAGL;WACN,YAAY;WACZ,QAAQ;WACR,OAAO;EAChB,YAAY,OAAO;EACnB;;;;;;;;;;;;wBAsCc,gBACd,SAAS,yBACR;;;;;wBA2Oa,iBACd,wBACA,SAAS,gBACR"}
@@ -0,0 +1,369 @@
1
+ import { a as isRemoteDomSerializableValue, c as REMOTE_DOM_SITE_UI_CONTRACT_VERSION, f as Thread, i as createRemoteDomUrlOriginPolicy, m as retain, p as release } from "./remote-dom-values-BBN5u_Mj.mjs";
2
+ import { a as collectCleanupErrors, c as enforceAllowedAnchorSafety, d as normalizeNavigationOrigin, f as reportCleanupErrors, i as callRemoteDomCapability, l as handleRemoteDomNavigationIntent, m as createSanitizingRemoteConnection, n as attachRemoteDomStyles, o as createSubmitPreventionListener, p as reportHostError, r as REMOTE_DOM_NODE_ID_ATTRIBUTE, s as deliverRemoteDomEvent, u as hasCloserRemoteEventListener } from "./remote-dom-styles-CmHfrrKz.mjs";
3
+ import { NODE_TYPE_COMMENT, NODE_TYPE_ELEMENT, NODE_TYPE_TEXT, ROOT_ID, UPDATE_PROPERTY_TYPE_ATTRIBUTE, UPDATE_PROPERTY_TYPE_EVENT_LISTENER, UPDATE_PROPERTY_TYPE_PROPERTY, createRemoteConnection } from "@remote-dom/core";
4
+ // src/site-host.ts
5
+ /**
6
+ * The site host offers only the site contract. Workers built today require
7
+ * contract 2 and carry React, so they refuse this host; a build for sites
8
+ * names the site contract (`uiContractVersions`) and mounts.
9
+ */
10
+ const SITE_HOST_UI_CONTRACT_VERSIONS = [REMOTE_DOM_SITE_UI_CONTRACT_VERSION];
11
+ const DEFAULT_MAX_MUTATION_BATCH_SIZE = 1e3;
12
+ const DEFAULT_MAX_DOM_NODE_COUNT = 1e3;
13
+ /**
14
+ * Mounts one widget on a member site.
15
+ *
16
+ * Refuses a worker served from another origin, and a widget granted network
17
+ * access: on a site the sandbox's limit comes from the policy on the worker's
18
+ * own response, which a cross-origin or blob worker would not carry.
19
+ *
20
+ * Raises TypeError when the props aren't serializable, the artifact asks for
21
+ * network access, or the worker isn't on the site's origin.
22
+ */
23
+ function mountSiteWidget(options) {
24
+ const initialProps = options.props ?? null;
25
+ if (!isRemoteDomSerializableValue(initialProps)) throw new TypeError("Initial widget props must be serializable");
26
+ if (options.artifact.networkAccessGranted === true) throw new TypeError("Widgets on member sites can't be granted network access");
27
+ const siteOrigin = normalizeNavigationOrigin(options.siteOrigin ?? (typeof location === "undefined" ? void 0 : location.origin));
28
+ if (!siteOrigin) throw new TypeError("A site widget needs the site's http(s) origin");
29
+ if (!isOnOrigin(options.artifact.workerEntryUrl, siteOrigin)) throw new TypeError("A site widget's worker must be served from the site");
30
+ const shadowRoot = options.host.shadowRoot ?? options.host.attachShadow({ mode: "open" });
31
+ shadowRoot.replaceChildren();
32
+ const urlOriginPolicy = createRemoteDomUrlOriginPolicy({
33
+ artifactUrls: [
34
+ options.artifact.workerEntryUrl,
35
+ ...options.artifact.cssUrls,
36
+ ...options.artifact.assetUrls
37
+ ],
38
+ mediaOrigins: options.mediaOrigins ?? [],
39
+ navigationOrigin: siteOrigin
40
+ });
41
+ const styles = attachRemoteDomStyles({
42
+ artifact: options.artifact,
43
+ root: shadowRoot,
44
+ urlOriginPolicy,
45
+ onFailure: (count) => {
46
+ reportHostError(options, `${count} site widget styles failed to load`);
47
+ },
48
+ ...options.cssText === void 0 ? {} : { cssText: options.cssText },
49
+ ...options.widgetCssText === void 0 ? {} : { widgetCssText: options.widgetCssText },
50
+ ...options.themeBridgeCssText === void 0 ? {} : { themeBridgeCssText: options.themeBridgeCssText },
51
+ ...options.themeBridge === void 0 ? {} : { themeBridge: options.themeBridge },
52
+ ...options.fetchCss === void 0 ? {} : { fetchCss: options.fetchCss }
53
+ });
54
+ let worker;
55
+ try {
56
+ worker = (options.workerFactory ?? createSiteWorker)(options.artifact.workerEntryUrl, { type: "module" });
57
+ } catch (error) {
58
+ reportCleanupErrors(options, "Site widget setup cleanup failed", collectCleanupErrors([() => styles.dispose(), () => clearDrawnNodes(shadowRoot)]));
59
+ throw error;
60
+ }
61
+ const thread = new Thread({
62
+ send(message, transferables) {
63
+ worker.postMessage(message, transferables ?? []);
64
+ },
65
+ listen(listener, { signal }) {
66
+ const onMessage = (event) => {
67
+ listener(event.data);
68
+ };
69
+ if (worker.addEventListener) {
70
+ worker.addEventListener("message", onMessage, { signal });
71
+ return;
72
+ }
73
+ worker.onmessage = onMessage;
74
+ signal?.addEventListener("abort", () => {
75
+ worker.onmessage = null;
76
+ }, { once: true });
77
+ }
78
+ });
79
+ const renderContainer = document.createElement("div");
80
+ renderContainer.setAttribute("data-fluid-remote-dom-render-root", "");
81
+ shadowRoot.append(renderContainer);
82
+ let state;
83
+ const isDisposed = () => state.disposed;
84
+ const drawn = new DomTree(renderContainer, options, isDisposed);
85
+ state = {
86
+ options,
87
+ shadowRoot,
88
+ renderContainer,
89
+ worker,
90
+ thread,
91
+ styles,
92
+ drawn,
93
+ submitListener: createSubmitPreventionListener(),
94
+ navigationListener: (event) => {
95
+ handleRemoteDomNavigationIntent({
96
+ shadowRoot,
97
+ urlOriginPolicy,
98
+ navigationOrigin: siteOrigin,
99
+ allowedAnchorUrls: options.allowedAnchorUrls,
100
+ onNavigate: options.onNavigate,
101
+ onError: options.onError,
102
+ isDisposed
103
+ }, event);
104
+ },
105
+ disposed: false
106
+ };
107
+ const connection = createSanitizingRemoteConnection({
108
+ connection: drawn.connection,
109
+ ...options.allowedAnchorUrls ? { allowedAnchorUrls: options.allowedAnchorUrls } : {},
110
+ urlOriginPolicy,
111
+ maxMutationBatchSize: options.maxMutationBatchSize ?? DEFAULT_MAX_MUTATION_BATCH_SIZE,
112
+ maxDomNodeCount: options.maxDomNodeCount ?? DEFAULT_MAX_DOM_NODE_COUNT,
113
+ onNodeLimitExceeded: () => {
114
+ reportHostError(options, "Site widget exceeded its DOM node limit");
115
+ },
116
+ onInvalidRecord: (message) => reportHostError(options, message),
117
+ onMutateError: (error) => reportHostError(options, "Site widget mutation could not be applied", error)
118
+ });
119
+ shadowRoot.addEventListener("submit", state.submitListener, { capture: true });
120
+ shadowRoot.addEventListener("click", state.navigationListener, { capture: true });
121
+ worker.onerror = (event) => {
122
+ event.preventDefault?.();
123
+ if (state.disposed) return;
124
+ reportHostError(options, event.message || "Site widget worker failed", event.error);
125
+ disposeQuietly(state, false);
126
+ };
127
+ const ready = Promise.all([styles.ready, thread.imports.mount({
128
+ widgetType: options.artifact.widgetType,
129
+ props: initialProps,
130
+ supportedUiContractVersions: SITE_HOST_UI_CONTRACT_VERSIONS
131
+ }, {
132
+ mutate(records) {
133
+ if (state.disposed) return;
134
+ connection.mutate(records);
135
+ enforceAllowedAnchorSafety(shadowRoot, options.allowedAnchorUrls);
136
+ },
137
+ callCapability(capability, method, payload) {
138
+ return callRemoteDomCapability({
139
+ declared: options.artifact.capabilities,
140
+ host: options.host,
141
+ shadowRoot,
142
+ callCapability: options.callCapability,
143
+ onError: options.onError,
144
+ isDisposed
145
+ }, capability, method, payload);
146
+ },
147
+ reportError(error) {
148
+ reportHostError(options, error.message);
149
+ }
150
+ })]).then(() => void 0);
151
+ ready.catch((error) => {
152
+ if (state.disposed) return;
153
+ reportHostError(options, "Site widget failed to mount", error);
154
+ disposeQuietly(state);
155
+ });
156
+ return {
157
+ shadowRoot,
158
+ styles,
159
+ ready,
160
+ updateProps(props) {
161
+ if (state.disposed) return;
162
+ if (!isRemoteDomSerializableValue(props)) throw new TypeError("Widget props must be serializable");
163
+ state.thread.imports.updateProps(props).catch((error) => {
164
+ if (!state.disposed) reportHostError(options, "Site widget props update failed", error);
165
+ });
166
+ },
167
+ dispose() {
168
+ disposeSiteWidget(state);
169
+ }
170
+ };
171
+ }
172
+ /**
173
+ * Starts the worker straight from its URL. No blob wrapper: a blob worker
174
+ * takes the page's policy instead of the one on the worker's response.
175
+ */
176
+ function createSiteWorker(workerEntryUrl, options) {
177
+ if (typeof Worker === "undefined") throw new Error("Workers are not available in this environment");
178
+ return new Worker(workerEntryUrl, options);
179
+ }
180
+ function isOnOrigin(url, origin) {
181
+ try {
182
+ const parsed = new URL(url, origin);
183
+ return (parsed.protocol === "https:" || parsed.protocol === "http:") && parsed.origin === origin;
184
+ } catch {
185
+ return false;
186
+ }
187
+ }
188
+ /** Applies sanitized Remote DOM records to real DOM nodes. */
189
+ var DomTree = class {
190
+ container;
191
+ reporter;
192
+ isDisposed;
193
+ connection;
194
+ nodes = /* @__PURE__ */ new Map();
195
+ ids = /* @__PURE__ */ new WeakMap();
196
+ elements = /* @__PURE__ */ new Map();
197
+ constructor(container, reporter, isDisposed) {
198
+ this.container = container;
199
+ this.reporter = reporter;
200
+ this.isDisposed = isDisposed;
201
+ this.elements.set(ROOT_ID, {
202
+ element: container,
203
+ tagName: "",
204
+ listeners: /* @__PURE__ */ new Map(),
205
+ handlers: /* @__PURE__ */ new Map()
206
+ });
207
+ this.connection = createRemoteConnection({
208
+ call: (_id, method) => {
209
+ throw new Error(`Site widget method "${method}" is not allowed`);
210
+ },
211
+ insertChild: (parentId, child, index) => {
212
+ const parent = this.parentNode(parentId);
213
+ const node = this.build(child);
214
+ parent.insertBefore(node, parent.childNodes[index] ?? null);
215
+ },
216
+ removeChild: (parentId, index) => {
217
+ const node = this.parentNode(parentId).childNodes[index];
218
+ if (!node) throw new Error(`No child at ${index} of "${parentId}"`);
219
+ this.forget(node);
220
+ node.remove();
221
+ },
222
+ updateText: (id, text) => {
223
+ const node = this.nodes.get(id);
224
+ if (node instanceof CharacterData) node.data = text;
225
+ },
226
+ updateProperty: (id, name, value, type) => {
227
+ const drawn = this.elements.get(id);
228
+ if (drawn) this.apply(drawn, name, value, type ?? UPDATE_PROPERTY_TYPE_PROPERTY);
229
+ }
230
+ });
231
+ }
232
+ clear() {
233
+ for (const child of Array.from(this.container.childNodes)) {
234
+ this.forget(child);
235
+ child.remove();
236
+ }
237
+ const root = this.elements.get(ROOT_ID);
238
+ if (root) for (const eventName of Array.from(root.listeners.keys())) this.listen(root, eventName, null);
239
+ }
240
+ parentNode(id) {
241
+ const parent = id === ROOT_ID ? this.container : this.nodes.get(id);
242
+ if (!parent) throw new Error(`Parent "${id}" is missing`);
243
+ return parent;
244
+ }
245
+ build(child) {
246
+ let node;
247
+ if (child.type === NODE_TYPE_TEXT) node = document.createTextNode(child.data);
248
+ else if (child.type === NODE_TYPE_COMMENT) node = document.createComment(child.data);
249
+ else if (child.type === NODE_TYPE_ELEMENT) {
250
+ const element = document.createElement(child.element);
251
+ element.setAttribute(REMOTE_DOM_NODE_ID_ATTRIBUTE, child.id);
252
+ const drawn = {
253
+ element,
254
+ tagName: child.element,
255
+ listeners: /* @__PURE__ */ new Map(),
256
+ handlers: /* @__PURE__ */ new Map()
257
+ };
258
+ this.elements.set(child.id, drawn);
259
+ for (const grandchild of child.children ?? []) element.append(this.build(grandchild));
260
+ for (const [name, value] of Object.entries(child.attributes ?? {})) this.apply(drawn, name, value, UPDATE_PROPERTY_TYPE_ATTRIBUTE);
261
+ for (const [name, value] of Object.entries(child.properties ?? {})) this.apply(drawn, name, value, UPDATE_PROPERTY_TYPE_PROPERTY);
262
+ for (const [name, value] of Object.entries(child.eventListeners ?? {})) this.apply(drawn, name, value, UPDATE_PROPERTY_TYPE_EVENT_LISTENER);
263
+ node = element;
264
+ } else throw new Error("Unknown Remote DOM node type");
265
+ this.nodes.set(child.id, node);
266
+ this.ids.set(node, child.id);
267
+ return node;
268
+ }
269
+ apply(drawn, name, value, type) {
270
+ if (type === UPDATE_PROPERTY_TYPE_EVENT_LISTENER) {
271
+ this.listen(drawn, name, typeof value === "function" ? value : null);
272
+ return;
273
+ }
274
+ const { element } = drawn;
275
+ if (element instanceof HTMLInputElement && (name === "value" || name === "checked")) {
276
+ if (type !== UPDATE_PROPERTY_TYPE_PROPERTY) return;
277
+ if (name === "value" && typeof value === "string") element.value = value;
278
+ if (name === "checked" && typeof value === "boolean") element.checked = value;
279
+ return;
280
+ }
281
+ if (element instanceof HTMLTextAreaElement && name === "value") {
282
+ element.value = typeof value === "string" ? value : "";
283
+ return;
284
+ }
285
+ if (value === void 0 || value === null || value === false) element.removeAttribute(name);
286
+ else if (value === true) element.setAttribute(name, "");
287
+ else if (typeof value === "string" || typeof value === "number") element.setAttribute(name, String(value));
288
+ else element[name] = value;
289
+ }
290
+ listen(drawn, eventName, listener) {
291
+ const previous = drawn.listeners.get(eventName);
292
+ if (previous === listener) return;
293
+ if (listener) retain(listener);
294
+ if (previous) release(previous);
295
+ if (!listener) {
296
+ drawn.listeners.delete(eventName);
297
+ const handler = drawn.handlers.get(eventName);
298
+ if (handler) {
299
+ drawn.element.removeEventListener(eventName, handler, { capture: drawn.element === this.container });
300
+ drawn.handlers.delete(eventName);
301
+ }
302
+ return;
303
+ }
304
+ drawn.listeners.set(eventName, listener);
305
+ if (drawn.handlers.has(eventName)) return;
306
+ const currentTargetId = drawn.element === this.container ? ROOT_ID : drawn.element.getAttribute("data-fluid-remote-dom-node-id") ?? ROOT_ID;
307
+ const handler = (event) => {
308
+ const current = drawn.listeners.get(eventName);
309
+ if (!current) return;
310
+ if (hasCloserRemoteEventListener(event, currentTargetId, (id) => Boolean(this.elements.get(id)?.listeners.has(eventName)))) return;
311
+ deliverRemoteDomEvent({
312
+ event,
313
+ eventName,
314
+ currentTargetId,
315
+ ...drawn.tagName ? { currentTargetTagName: drawn.tagName } : {},
316
+ listener: current,
317
+ reporter: this.reporter,
318
+ isDisposed: this.isDisposed
319
+ });
320
+ };
321
+ drawn.handlers.set(eventName, handler);
322
+ drawn.element.addEventListener(eventName, handler, { capture: drawn.element === this.container });
323
+ }
324
+ forget(node) {
325
+ const id = this.ids.get(node);
326
+ if (id !== void 0) {
327
+ const drawn = this.elements.get(id);
328
+ if (drawn) {
329
+ for (const listener of drawn.listeners.values()) release(listener);
330
+ drawn.listeners.clear();
331
+ }
332
+ this.nodes.delete(id);
333
+ this.elements.delete(id);
334
+ }
335
+ for (const child of Array.from(node.childNodes)) this.forget(child);
336
+ }
337
+ };
338
+ function disposeSiteWidget(state, notifyWorker = true) {
339
+ if (state.disposed) return;
340
+ state.disposed = true;
341
+ const errors = collectCleanupErrors([
342
+ () => {
343
+ state.worker.onerror = null;
344
+ },
345
+ () => state.shadowRoot.removeEventListener("submit", state.submitListener, { capture: true }),
346
+ () => state.shadowRoot.removeEventListener("click", state.navigationListener, { capture: true }),
347
+ () => state.drawn.clear(),
348
+ () => state.styles.dispose(),
349
+ () => clearDrawnNodes(state.shadowRoot)
350
+ ]);
351
+ if (notifyWorker) Promise.resolve(state.thread.imports.dispose()).catch(() => void 0);
352
+ queueMicrotask(() => {
353
+ reportCleanupErrors(state.options, "Site widget asynchronous cleanup failed", collectCleanupErrors([() => state.thread.close(), () => state.worker.terminate()]));
354
+ });
355
+ if (errors.length > 0) throw new AggregateError(errors, "Site widget cleanup failed");
356
+ }
357
+ function disposeQuietly(state, notifyWorker = true) {
358
+ try {
359
+ disposeSiteWidget(state, notifyWorker);
360
+ } catch (error) {
361
+ reportHostError(state.options, "Site widget cleanup failed after an earlier error", error);
362
+ }
363
+ }
364
+ function clearDrawnNodes(shadowRoot) {
365
+ for (const child of Array.from(shadowRoot.childNodes)) if (!(child instanceof HTMLStyleElement && child.hasAttribute("data-fluid-widget-style"))) child.remove();
366
+ }
367
+ export { SITE_HOST_UI_CONTRACT_VERSIONS, createSiteWorker, mountSiteWidget };
368
+
369
+ //# sourceMappingURL=site-host.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-host.mjs","names":[],"sources":["../src/site-host.ts"],"sourcesContent":["// The host for member sites: draws a sandboxed widget into the page's own DOM\n// with no React (widgets plan, step 2.1; L-W.4, L-W.22). Every mutation the\n// worker sends passes the same sanitizer as the React host before it is\n// applied here, and nothing in this module may import React\n// (`scripts/verify-site-host-no-react.mjs`).\nimport { release, retain, Thread } from \"@quilted/threads\";\nimport {\n createRemoteConnection,\n NODE_TYPE_COMMENT,\n NODE_TYPE_ELEMENT,\n NODE_TYPE_TEXT,\n ROOT_ID,\n UPDATE_PROPERTY_TYPE_ATTRIBUTE,\n UPDATE_PROPERTY_TYPE_EVENT_LISTENER,\n UPDATE_PROPERTY_TYPE_PROPERTY,\n type RemoteConnection,\n type RemoteNodeSerialization,\n} from \"@remote-dom/core\";\nimport {\n callRemoteDomCapability,\n collectCleanupErrors,\n createSubmitPreventionListener,\n deliverRemoteDomEvent,\n enforceAllowedAnchorSafety,\n handleRemoteDomNavigationIntent,\n hasCloserRemoteEventListener,\n normalizeNavigationOrigin,\n REMOTE_DOM_NODE_ID_ATTRIBUTE,\n reportCleanupErrors,\n reportHostError,\n type RemoteDomCapabilityHandler,\n} from \"./remote-dom-host-shared\";\nimport { createSanitizingRemoteConnection } from \"./remote-dom-sanitizing-connection\";\nimport {\n attachRemoteDomStyles,\n REMOTE_DOM_WIDGET_STYLE_ATTRIBUTE,\n type RemoteDomCssFetcher,\n type RemoteDomStyleAttachment,\n type RemoteDomThemeBridgeOptions,\n} from \"./remote-dom-styles\";\nimport { REMOTE_DOM_SITE_UI_CONTRACT_VERSION } from \"./remote-dom-ui-contract\";\nimport {\n createRemoteDomUrlOriginPolicy,\n isRemoteDomSerializableValue,\n type RemoteDomNavigationIntent,\n type RemoteDomSerializableValue,\n} from \"./remote-dom-values\";\nimport type {\n RemoteDomWidgetArtifact,\n RemoteDomWorkerFactory,\n RemoteDomWorkerLike,\n} from \"./remote-dom-renderer\";\nimport type {\n RemoteDomWidgetWorkerApi,\n RemoteDomWidgetWorkerHostApi,\n} from \"./worker-runtime\";\n\n/**\n * The site host offers only the site contract. Workers built today require\n * contract 2 and carry React, so they refuse this host; a build for sites\n * names the site contract (`uiContractVersions`) and mounts.\n */\nexport const SITE_HOST_UI_CONTRACT_VERSIONS: readonly string[] = [\n REMOTE_DOM_SITE_UI_CONTRACT_VERSION,\n];\n\nexport interface MountSiteWidgetOptions {\n readonly host: HTMLElement;\n readonly artifact: RemoteDomWidgetArtifact;\n readonly props?: RemoteDomSerializableValue | undefined;\n /** Answers the widget's capability calls. Fluid data goes through the site. */\n readonly callCapability?: RemoteDomCapabilityHandler | undefined;\n readonly onNavigate?:\n | ((intent: RemoteDomNavigationIntent) => void | Promise<void>)\n | undefined;\n readonly onError?: ((error: Error) => void) | undefined;\n readonly workerFactory?: RemoteDomWorkerFactory | undefined;\n /**\n * The site's origin. The worker must be served from it, under the policy\n * the gateway sends for widget code (O-W.13). Defaults to `location.origin`.\n */\n readonly siteOrigin?: string | undefined;\n /**\n * Origins drawn images and media may load from besides the package's own\n * files. Empty by default: unlike other hosts, no shared media host is\n * allowed unless the caller names it (O-W.13).\n */\n readonly mediaOrigins?: readonly string[] | undefined;\n readonly allowedAnchorUrls?: ReadonlySet<string> | undefined;\n readonly maxMutationBatchSize?: number | undefined;\n readonly maxDomNodeCount?: number | undefined;\n readonly cssText?: string | undefined;\n readonly widgetCssText?: string | undefined;\n readonly themeBridgeCssText?: string | undefined;\n readonly themeBridge?:\n | Omit<RemoteDomThemeBridgeOptions, \"root\">\n | false\n | undefined;\n readonly fetchCss?: RemoteDomCssFetcher | undefined;\n}\n\nexport interface SiteWidgetHandle {\n readonly shadowRoot: ShadowRoot;\n readonly styles: RemoteDomStyleAttachment;\n readonly ready: Promise<void>;\n updateProps(props: RemoteDomSerializableValue): void;\n dispose(): void;\n}\n\nconst DEFAULT_MAX_MUTATION_BATCH_SIZE = 1_000;\nconst DEFAULT_MAX_DOM_NODE_COUNT = 1_000;\n\ntype RemoteListener = (...args: readonly unknown[]) => unknown;\n\ninterface DrawnElement {\n readonly element: Element;\n readonly tagName: string;\n readonly listeners: Map<string, RemoteListener>;\n readonly handlers: Map<string, EventListener>;\n}\n\ninterface SiteHostState {\n readonly options: MountSiteWidgetOptions;\n readonly shadowRoot: ShadowRoot;\n readonly renderContainer: HTMLElement;\n readonly worker: RemoteDomWorkerLike;\n readonly thread: Thread<RemoteDomWidgetWorkerApi>;\n readonly styles: RemoteDomStyleAttachment;\n readonly drawn: DomTree;\n readonly submitListener: EventListener;\n readonly navigationListener: EventListener;\n disposed: boolean;\n}\n\n/**\n * Mounts one widget on a member site.\n *\n * Refuses a worker served from another origin, and a widget granted network\n * access: on a site the sandbox's limit comes from the policy on the worker's\n * own response, which a cross-origin or blob worker would not carry.\n *\n * Raises TypeError when the props aren't serializable, the artifact asks for\n * network access, or the worker isn't on the site's origin.\n */\nexport function mountSiteWidget(\n options: MountSiteWidgetOptions,\n): SiteWidgetHandle {\n const initialProps = options.props ?? null;\n if (!isRemoteDomSerializableValue(initialProps)) {\n throw new TypeError(\"Initial widget props must be serializable\");\n }\n if (options.artifact.networkAccessGranted === true) {\n throw new TypeError(\n \"Widgets on member sites can't be granted network access\",\n );\n }\n const siteOrigin = normalizeNavigationOrigin(\n options.siteOrigin ??\n (typeof location === \"undefined\" ? undefined : location.origin),\n );\n if (!siteOrigin) {\n throw new TypeError(\"A site widget needs the site's http(s) origin\");\n }\n if (!isOnOrigin(options.artifact.workerEntryUrl, siteOrigin)) {\n throw new TypeError(\"A site widget's worker must be served from the site\");\n }\n\n const shadowRoot =\n options.host.shadowRoot ?? options.host.attachShadow({ mode: \"open\" });\n shadowRoot.replaceChildren();\n const urlOriginPolicy = createRemoteDomUrlOriginPolicy({\n artifactUrls: [\n options.artifact.workerEntryUrl,\n ...options.artifact.cssUrls,\n ...options.artifact.assetUrls,\n ],\n mediaOrigins: options.mediaOrigins ?? [],\n navigationOrigin: siteOrigin,\n });\n const styles = attachRemoteDomStyles({\n artifact: options.artifact,\n root: shadowRoot,\n urlOriginPolicy,\n onFailure: (count) => {\n reportHostError(options, `${count} site widget styles failed to load`);\n },\n ...(options.cssText === undefined ? {} : { cssText: options.cssText }),\n ...(options.widgetCssText === undefined\n ? {}\n : { widgetCssText: options.widgetCssText }),\n ...(options.themeBridgeCssText === undefined\n ? {}\n : { themeBridgeCssText: options.themeBridgeCssText }),\n ...(options.themeBridge === undefined\n ? {}\n : { themeBridge: options.themeBridge }),\n ...(options.fetchCss === undefined ? {} : { fetchCss: options.fetchCss }),\n });\n\n let worker: RemoteDomWorkerLike;\n try {\n worker = (options.workerFactory ?? createSiteWorker)(\n options.artifact.workerEntryUrl,\n { type: \"module\" },\n );\n } catch (error) {\n reportCleanupErrors(\n options,\n \"Site widget setup cleanup failed\",\n collectCleanupErrors([\n () => styles.dispose(),\n () => clearDrawnNodes(shadowRoot),\n ]),\n );\n throw error;\n }\n\n const thread = new Thread<RemoteDomWidgetWorkerApi>({\n send(message, transferables) {\n worker.postMessage(message, transferables ?? []);\n },\n listen(listener, { signal }) {\n const onMessage = (event: MessageEvent<unknown>): void => {\n listener(event.data);\n };\n if (worker.addEventListener) {\n worker.addEventListener(\"message\", onMessage, { signal });\n return;\n }\n worker.onmessage = onMessage;\n signal?.addEventListener(\n \"abort\",\n () => {\n worker.onmessage = null;\n },\n { once: true },\n );\n },\n });\n\n const renderContainer = document.createElement(\"div\");\n renderContainer.setAttribute(\"data-fluid-remote-dom-render-root\", \"\");\n shadowRoot.append(renderContainer);\n\n let state: SiteHostState;\n const isDisposed = (): boolean => state.disposed;\n const drawn = new DomTree(renderContainer, options, isDisposed);\n state = {\n options,\n shadowRoot,\n renderContainer,\n worker,\n thread,\n styles,\n drawn,\n submitListener: createSubmitPreventionListener(),\n navigationListener: (event) => {\n handleRemoteDomNavigationIntent(\n {\n shadowRoot,\n urlOriginPolicy,\n navigationOrigin: siteOrigin,\n allowedAnchorUrls: options.allowedAnchorUrls,\n onNavigate: options.onNavigate,\n onError: options.onError,\n isDisposed,\n },\n event,\n );\n },\n disposed: false,\n };\n\n const connection = createSanitizingRemoteConnection({\n connection: drawn.connection,\n ...(options.allowedAnchorUrls\n ? { allowedAnchorUrls: options.allowedAnchorUrls }\n : {}),\n urlOriginPolicy,\n maxMutationBatchSize:\n options.maxMutationBatchSize ?? DEFAULT_MAX_MUTATION_BATCH_SIZE,\n maxDomNodeCount: options.maxDomNodeCount ?? DEFAULT_MAX_DOM_NODE_COUNT,\n onNodeLimitExceeded: () => {\n reportHostError(options, \"Site widget exceeded its DOM node limit\");\n },\n onInvalidRecord: (message) => reportHostError(options, message),\n onMutateError: (error) =>\n reportHostError(\n options,\n \"Site widget mutation could not be applied\",\n error,\n ),\n });\n\n shadowRoot.addEventListener(\"submit\", state.submitListener, {\n capture: true,\n });\n shadowRoot.addEventListener(\"click\", state.navigationListener, {\n capture: true,\n });\n worker.onerror = (event) => {\n // An uncaught throw in the worker is re-reported on the page unless the\n // event is cancelled; a widget's fault must not reach the site's handlers.\n event.preventDefault?.();\n if (state.disposed) return;\n reportHostError(\n options,\n event.message || \"Site widget worker failed\",\n event.error,\n );\n disposeQuietly(state, false);\n };\n\n const hostApi: RemoteDomWidgetWorkerHostApi = {\n mutate(records) {\n if (state.disposed) return;\n connection.mutate(records);\n enforceAllowedAnchorSafety(shadowRoot, options.allowedAnchorUrls);\n },\n callCapability(capability, method, payload) {\n return callRemoteDomCapability(\n {\n declared: options.artifact.capabilities,\n host: options.host,\n shadowRoot,\n callCapability: options.callCapability,\n onError: options.onError,\n isDisposed,\n },\n capability,\n method,\n payload,\n );\n },\n reportError(error) {\n reportHostError(options, error.message);\n },\n };\n\n const ready = Promise.all([\n styles.ready,\n thread.imports.mount(\n {\n widgetType: options.artifact.widgetType,\n props: initialProps,\n supportedUiContractVersions: SITE_HOST_UI_CONTRACT_VERSIONS,\n },\n hostApi,\n ),\n ]).then(() => undefined);\n void ready.catch((error: unknown) => {\n if (state.disposed) return;\n reportHostError(options, \"Site widget failed to mount\", error);\n disposeQuietly(state);\n });\n\n return {\n shadowRoot,\n styles,\n ready,\n updateProps(props) {\n if (state.disposed) return;\n if (!isRemoteDomSerializableValue(props)) {\n throw new TypeError(\"Widget props must be serializable\");\n }\n void state.thread.imports.updateProps(props).catch((error: unknown) => {\n if (!state.disposed) {\n reportHostError(options, \"Site widget props update failed\", error);\n }\n });\n },\n dispose() {\n disposeSiteWidget(state);\n },\n };\n}\n\n/**\n * Starts the worker straight from its URL. No blob wrapper: a blob worker\n * takes the page's policy instead of the one on the worker's response.\n */\nexport function createSiteWorker(\n workerEntryUrl: string,\n options: WorkerOptions,\n): RemoteDomWorkerLike {\n if (typeof Worker === \"undefined\") {\n throw new Error(\"Workers are not available in this environment\");\n }\n return new Worker(workerEntryUrl, options);\n}\n\n// Only an http(s) URL on the site counts: a same-origin `blob:` or `data:`\n// worker would take the page's policy, not the one on the worker's response.\nfunction isOnOrigin(url: string, origin: string): boolean {\n try {\n const parsed = new URL(url, origin);\n return (\n (parsed.protocol === \"https:\" || parsed.protocol === \"http:\") &&\n parsed.origin === origin\n );\n } catch {\n return false;\n }\n}\n\n/** Applies sanitized Remote DOM records to real DOM nodes. */\nclass DomTree {\n readonly connection: RemoteConnection;\n private readonly nodes = new Map<string, Node>();\n private readonly ids = new WeakMap<Node, string>();\n private readonly elements = new Map<string, DrawnElement>();\n\n constructor(\n private readonly container: HTMLElement,\n private readonly reporter: MountSiteWidgetOptions,\n private readonly isDisposed: () => boolean,\n ) {\n this.elements.set(ROOT_ID, {\n element: container,\n tagName: \"\",\n listeners: new Map(),\n handlers: new Map(),\n });\n this.connection = createRemoteConnection({\n call: (_id, method) => {\n throw new Error(`Site widget method \"${method}\" is not allowed`);\n },\n insertChild: (parentId, child, index) => {\n const parent = this.parentNode(parentId);\n const node = this.build(child);\n parent.insertBefore(node, parent.childNodes[index] ?? null);\n },\n removeChild: (parentId, index) => {\n const parent = this.parentNode(parentId);\n const node = parent.childNodes[index];\n if (!node) throw new Error(`No child at ${index} of \"${parentId}\"`);\n this.forget(node);\n node.remove();\n },\n // A late update for a node an earlier record removed is dropped, as\n // Remote DOM's own receivers do.\n updateText: (id, text) => {\n const node = this.nodes.get(id);\n if (node instanceof CharacterData) node.data = text;\n },\n updateProperty: (id, name, value, type) => {\n const drawn = this.elements.get(id);\n if (drawn) {\n this.apply(drawn, name, value, type ?? UPDATE_PROPERTY_TYPE_PROPERTY);\n }\n },\n });\n }\n\n clear(): void {\n for (const child of Array.from(this.container.childNodes)) {\n this.forget(child);\n child.remove();\n }\n const root = this.elements.get(ROOT_ID);\n if (root) {\n for (const eventName of Array.from(root.listeners.keys())) {\n this.listen(root, eventName, null);\n }\n }\n }\n\n private parentNode(id: string): Node {\n const parent = id === ROOT_ID ? this.container : this.nodes.get(id);\n if (!parent) throw new Error(`Parent \"${id}\" is missing`);\n return parent;\n }\n\n private build(child: RemoteNodeSerialization): Node {\n let node: Node;\n if (child.type === NODE_TYPE_TEXT) {\n node = document.createTextNode(child.data);\n } else if (child.type === NODE_TYPE_COMMENT) {\n node = document.createComment(child.data);\n } else if (child.type === NODE_TYPE_ELEMENT) {\n const element = document.createElement(child.element);\n element.setAttribute(REMOTE_DOM_NODE_ID_ATTRIBUTE, child.id);\n const drawn: DrawnElement = {\n element,\n tagName: child.element,\n listeners: new Map(),\n handlers: new Map(),\n };\n this.elements.set(child.id, drawn);\n for (const grandchild of child.children ?? []) {\n element.append(this.build(grandchild));\n }\n for (const [name, value] of Object.entries(child.attributes ?? {})) {\n this.apply(drawn, name, value, UPDATE_PROPERTY_TYPE_ATTRIBUTE);\n }\n for (const [name, value] of Object.entries(child.properties ?? {})) {\n this.apply(drawn, name, value, UPDATE_PROPERTY_TYPE_PROPERTY);\n }\n for (const [name, value] of Object.entries(child.eventListeners ?? {})) {\n this.apply(drawn, name, value, UPDATE_PROPERTY_TYPE_EVENT_LISTENER);\n }\n node = element;\n } else {\n throw new Error(\"Unknown Remote DOM node type\");\n }\n this.nodes.set(child.id, node);\n this.ids.set(node, child.id);\n return node;\n }\n\n private apply(\n drawn: DrawnElement,\n name: string,\n value: unknown,\n type: number,\n ): void {\n if (type === UPDATE_PROPERTY_TYPE_EVENT_LISTENER) {\n this.listen(\n drawn,\n name,\n typeof value === \"function\" ? (value as RemoteListener) : null,\n );\n return;\n }\n const { element } = drawn;\n // Form values are live state, as the React host treats them: an input's\n // value and checked come only from properties, and a textarea's value\n // sets what the field shows, not its default.\n if (\n element instanceof HTMLInputElement &&\n (name === \"value\" || name === \"checked\")\n ) {\n if (type !== UPDATE_PROPERTY_TYPE_PROPERTY) return;\n if (name === \"value\" && typeof value === \"string\") element.value = value;\n if (name === \"checked\" && typeof value === \"boolean\")\n element.checked = value;\n return;\n }\n if (element instanceof HTMLTextAreaElement && name === \"value\") {\n element.value = typeof value === \"string\" ? value : \"\";\n return;\n }\n if (value === undefined || value === null || value === false) {\n element.removeAttribute(name);\n } else if (value === true) {\n element.setAttribute(name, \"\");\n } else if (typeof value === \"string\" || typeof value === \"number\") {\n element.setAttribute(name, String(value));\n } else {\n // A structured property of a contract 1 Fluid element: the element\n // reads it as a property, as the React host passes it.\n (element as unknown as Record<string, unknown>)[name] = value;\n }\n }\n\n private listen(\n drawn: DrawnElement,\n eventName: string,\n listener: RemoteListener | null,\n ): void {\n const previous = drawn.listeners.get(eventName);\n if (previous === listener) return;\n // The worker's listener is a proxy across the thread: hold it while it is\n // drawn and let it go when it is replaced or removed.\n if (listener) retain(listener);\n if (previous) release(previous);\n if (!listener) {\n drawn.listeners.delete(eventName);\n const handler = drawn.handlers.get(eventName);\n if (handler) {\n drawn.element.removeEventListener(eventName, handler, {\n capture: drawn.element === this.container,\n });\n drawn.handlers.delete(eventName);\n }\n return;\n }\n drawn.listeners.set(eventName, listener);\n if (drawn.handlers.has(eventName)) return;\n const currentTargetId =\n drawn.element === this.container\n ? ROOT_ID\n : (drawn.element.getAttribute(REMOTE_DOM_NODE_ID_ATTRIBUTE) ?? ROOT_ID);\n const handler: EventListener = (event) => {\n const current = drawn.listeners.get(eventName);\n if (!current) return;\n if (\n hasCloserRemoteEventListener(event, currentTargetId, (id) =>\n Boolean(this.elements.get(id)?.listeners.has(eventName)),\n )\n ) {\n return;\n }\n deliverRemoteDomEvent({\n event,\n eventName,\n currentTargetId,\n ...(drawn.tagName ? { currentTargetTagName: drawn.tagName } : {}),\n listener: current,\n reporter: this.reporter,\n isDisposed: this.isDisposed,\n });\n };\n drawn.handlers.set(eventName, handler);\n drawn.element.addEventListener(eventName, handler, {\n capture: drawn.element === this.container,\n });\n }\n\n private forget(node: Node): void {\n const id = this.ids.get(node);\n if (id !== undefined) {\n const drawn = this.elements.get(id);\n if (drawn) {\n for (const listener of drawn.listeners.values()) release(listener);\n drawn.listeners.clear();\n }\n this.nodes.delete(id);\n this.elements.delete(id);\n }\n for (const child of Array.from(node.childNodes)) this.forget(child);\n }\n}\n\nfunction disposeSiteWidget(state: SiteHostState, notifyWorker = true): void {\n if (state.disposed) return;\n state.disposed = true;\n const errors = collectCleanupErrors([\n () => {\n state.worker.onerror = null;\n },\n () =>\n state.shadowRoot.removeEventListener(\"submit\", state.submitListener, {\n capture: true,\n }),\n () =>\n state.shadowRoot.removeEventListener(\"click\", state.navigationListener, {\n capture: true,\n }),\n () => state.drawn.clear(),\n () => state.styles.dispose(),\n () => clearDrawnNodes(state.shadowRoot),\n ]);\n if (notifyWorker) {\n void Promise.resolve(state.thread.imports.dispose()).catch(() => undefined);\n }\n queueMicrotask(() => {\n reportCleanupErrors(\n state.options,\n \"Site widget asynchronous cleanup failed\",\n collectCleanupErrors([\n () => state.thread.close(),\n () => state.worker.terminate(),\n ]),\n );\n });\n if (errors.length > 0) {\n throw new AggregateError(errors, \"Site widget cleanup failed\");\n }\n}\n\nfunction disposeQuietly(state: SiteHostState, notifyWorker = true): void {\n try {\n disposeSiteWidget(state, notifyWorker);\n } catch (error) {\n reportHostError(\n state.options,\n \"Site widget cleanup failed after an earlier error\",\n error,\n );\n }\n}\n\nfunction clearDrawnNodes(shadowRoot: ShadowRoot): void {\n for (const child of Array.from(shadowRoot.childNodes)) {\n if (\n !(\n child instanceof HTMLStyleElement &&\n child.hasAttribute(REMOTE_DOM_WIDGET_STYLE_ATTRIBUTE)\n )\n ) {\n child.remove();\n }\n }\n}\n"],"mappings":";;;;;;;;;AA8DA,MAAa,iCAAoD,CAC/D,mCACF;AA6CA,MAAM,kCAAkC;AACxC,MAAM,6BAA6B;;;;;;;;;;;AAkCnC,SAAgB,gBACd,SACkB;CAClB,MAAM,eAAe,QAAQ,SAAS;CACtC,IAAI,CAAC,6BAA6B,YAAY,GAC5C,MAAM,IAAI,UAAU,2CAA2C;CAEjE,IAAI,QAAQ,SAAS,yBAAyB,MAC5C,MAAM,IAAI,UACR,yDACF;CAEF,MAAM,aAAa,0BACjB,QAAQ,eACL,OAAO,aAAa,cAAc,KAAA,IAAY,SAAS,OAC5D;CACA,IAAI,CAAC,YACH,MAAM,IAAI,UAAU,+CAA+C;CAErE,IAAI,CAAC,WAAW,QAAQ,SAAS,gBAAgB,UAAU,GACzD,MAAM,IAAI,UAAU,qDAAqD;CAG3E,MAAM,aACJ,QAAQ,KAAK,cAAc,QAAQ,KAAK,aAAa,EAAE,MAAM,OAAO,CAAC;CACvE,WAAW,gBAAgB;CAC3B,MAAM,kBAAkB,+BAA+B;EACrD,cAAc;GACZ,QAAQ,SAAS;GACjB,GAAG,QAAQ,SAAS;GACpB,GAAG,QAAQ,SAAS;EACtB;EACA,cAAc,QAAQ,gBAAgB,CAAC;EACvC,kBAAkB;CACpB,CAAC;CACD,MAAM,SAAS,sBAAsB;EACnC,UAAU,QAAQ;EAClB,MAAM;EACN;EACA,YAAY,UAAU;GACpB,gBAAgB,SAAS,GAAG,MAAM,mCAAmC;EACvE;EACA,GAAI,QAAQ,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,QAAQ,QAAQ;EACpE,GAAI,QAAQ,kBAAkB,KAAA,IAC1B,CAAC,IACD,EAAE,eAAe,QAAQ,cAAc;EAC3C,GAAI,QAAQ,uB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