@mica-js/editor 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { c as toWireFailure, l as transferBytes, o as mapWireFailure, s as messageOf } from "./wire-BDHL5Aj9.js";
1
+ import { c as toWireFailure, l as transferBytes, o as mapWireFailure, s as messageOf } from "./wire-Di4FVpnu.js";
2
2
  import { DisposableStore, Emitter, toDisposable } from "@mica-js/core/lifecycle";
3
3
  import { packagePathProblem } from "@mica-js/document/fused";
4
4
  import { openDevicePackage } from "@mica-js/sdk/fused";
@@ -11,18 +11,9 @@ import { createRpc, defineRpcService } from "@mica-js/core/rpc";
11
11
  * own origin and one INNER sandboxed frame inside it. Both are real documents of that origin
12
12
  * (`index.html` and `content.html`), so every origin of both frames is concrete and comparable.
13
13
  * The outer owns the author document: it writes it into the inner document once the inner bootstrap
14
- * announced that the API and the package grant are in place. Three `MessagePort` lanes cross that
15
- * boundary, and only the control lane ever reaches the outer frame:
16
- *
17
- * | Lane | Peers | Carries |
18
- * | ------- | ----------- | ---------------------------------------------------------------- |
19
- * | control | host, outer | loading, theme, errors, and the two port grants |
20
- * | author | host, inner | model methods and events, props, assets, close, view identity |
21
- * | package | host, SW | verified package bytes of one asset request |
22
- *
23
- * The outer never proxies a package read or a model call: it receives the two dedicated ports over
24
- * the control lane and hands them straight to the worker and to the sandboxed frame. Author code
25
- * never receives a model implementation, the editor DOM, a `MessagePort` or any host proxy.
14
+ * announced that the API and the package grant are in place. The editor keeps a control lane to
15
+ * the outer frame and an author lane directly to the inner frame. The asset worker requests package
16
+ * reads from the outer frame on a port scoped to each fetch, so it can restart independently.
26
17
  */
27
18
  /** Local contract failure of the HTML view host or of one environment. */
28
19
  var HtmlViewError = class extends Error {
@@ -44,11 +35,9 @@ function isHtmlViewError(value) {
44
35
  var HTML_VIEW_CONNECT = "mica:view:connect";
45
36
  /** Acknowledgement the environment posts back once it owns the transferred port. */
46
37
  var HTML_VIEW_ACK = "mica:view:ack";
47
- /** Control message that grants the environment's asset worker its package channel. */
48
- var HTML_VIEW_ASSETS = "mica:view:assets";
49
- /** Acknowledgement of {@link HTML_VIEW_ASSETS}: the worker owns the package port. */
50
- var HTML_VIEW_ASSETS_ACK = "mica:view:assets-ack";
51
- /** Control message the inner frame posts into the asset worker to authorize its own requests. */
38
+ /** The asset worker requests a port for one package fetch. */
39
+ var HTML_VIEW_ASSET_READ = "mica:view:asset-read";
40
+ /** Control message the inner frame sends through the asset worker to authorize its requests. */
52
41
  var HTML_VIEW_ATTACH = "mica:view:attach";
53
42
  /** Acknowledgement of {@link HTML_VIEW_ATTACH}; only then may the author document load. */
54
43
  var HTML_VIEW_ATTACH_ACK = "mica:view:attach-ack";
@@ -582,11 +571,9 @@ function applyHtmlViewTheme(root, theme) {
582
571
  * disposes it. The environment page itself hosts a sandboxed inner frame for the author document,
583
572
  * which is why the manager only ever sees one stable owner and one stable outer page.
584
573
  *
585
- * Three lanes belong to one view lease. The environment page keeps the control lane (loading,
586
- * theme, failures, the two port grants), while the author lane and the package lane are dedicated
587
- * ports this manager creates on request and the environment only hands on: model methods, model
588
- * events, props, assets and the package reads of the asset worker reach this manager directly, so
589
- * no intermediate frame relays them.
574
+ * Two lanes belong to one view lease. The outer frame manages loading, theme, diagnostics and
575
+ * verified package reads. The inner frame has a separate direct port for the author's API and
576
+ * model events.
590
577
  */
591
578
  var DEFAULT_HANDSHAKE_TIMEOUT_MS = 15e3;
592
579
  var MAX_MESSAGE_LENGTH = 500;
@@ -795,7 +782,6 @@ function createHtmlViewHost(options) {
795
782
  failure: void 0,
796
783
  loadSeen: false,
797
784
  endpoint: void 0,
798
- assetEndpoint: void 0,
799
785
  contentEndpoint: void 0,
800
786
  subscriptions: /* @__PURE__ */ new Map(),
801
787
  eventListeners: /* @__PURE__ */ new Set(),
@@ -877,11 +863,12 @@ function createHtmlViewHost(options) {
877
863
  closed() {
878
864
  release(record);
879
865
  },
880
- async assetPort() {
881
- return requestPort(record, "package");
882
- },
883
866
  async contentPort() {
884
- return requestPort(record, "author");
867
+ try {
868
+ return grantAuthorPort(record);
869
+ } catch (cause) {
870
+ throw toWireFailure(cause);
871
+ }
885
872
  }
886
873
  };
887
874
  }
@@ -982,51 +969,29 @@ function createHtmlViewHost(options) {
982
969
  throw toWireFailure(cause);
983
970
  }
984
971
  }
985
- /**
986
- * Creates the one dedicated port of one lane of this view.
987
- *
988
- * Both ends of a direct port belong to this lease: the peer reads only the declared files of the
989
- * locked package, only the declared methods and events of this instance and only the props of this
990
- * view. A second request is an explicit failure, because a silently replaced channel would leave
991
- * the first consumer reading a closed port.
992
- */
993
- function requestPort(record, lane) {
994
- try {
995
- return grantPort(record, lane);
996
- } catch (cause) {
997
- throw toWireFailure(cause);
998
- }
999
- }
1000
- function grantPort(record, lane) {
1001
- if (record.state !== "loading" && record.state !== "ready") throw new HtmlViewError("view/unavailable-mode", `The HTML view ${record.instanceId}/${record.viewId} is ${record.state} and grants no ${lane} port.`, {
972
+ /** Grants the author's direct port once for the lifetime of the content document. */
973
+ function grantAuthorPort(record) {
974
+ if (record.state !== "loading" && record.state !== "ready") throw new HtmlViewError("view/unavailable-mode", `The HTML view ${record.instanceId}/${record.viewId} is ${record.state} and grants no author port.`, {
1002
975
  instanceId: record.instanceId,
1003
976
  viewId: record.viewId
1004
977
  });
1005
- if ((lane === "package" ? record.assetEndpoint : record.contentEndpoint) !== void 0) throw new HtmlViewError("view/bridge-failed", `The ${lane} port of ${record.instanceId}/${record.viewId} was already granted.`, {
978
+ if (record.contentEndpoint !== void 0) throw new HtmlViewError("view/bridge-failed", `The author port of ${record.instanceId}/${record.viewId} was already granted.`, {
1006
979
  instanceId: record.instanceId,
1007
980
  viewId: record.viewId
1008
981
  });
1009
982
  const channel = new MessageChannel();
1010
983
  const endpoint = createRpc(channel.port1);
1011
- const transfer = (_member, value) => transferBytes(value);
1012
- if (lane === "package") {
1013
- record.assetEndpoint = endpoint;
1014
- endpoint.register(fusedHtmlAssetService, { async read(path) {
1015
- return readPackageFile(record, path);
1016
- } }, { transfer });
1017
- } else {
1018
- record.contentEndpoint = endpoint;
1019
- endpoint.register(fusedHtmlHostService, authorService(record), { transfer });
1020
- endpoint.register(fusedHtmlContentViewService, { async view() {
1021
- return {
1022
- token: record.token,
1023
- target: viewTarget(record)
1024
- };
1025
- } });
1026
- }
984
+ record.contentEndpoint = endpoint;
985
+ endpoint.register(fusedHtmlHostService, authorService(record), { transfer: (_member, value) => transferBytes(value) });
986
+ endpoint.register(fusedHtmlContentViewService, { async view() {
987
+ return {
988
+ token: record.token,
989
+ target: viewTarget(record)
990
+ };
991
+ } });
1027
992
  endpoint.onDidClose(() => {
1028
993
  if (record.state !== "loading" && record.state !== "ready") return;
1029
- fault(record, "view/bridge-failed", `The dedicated ${lane} port of the view closed.`);
994
+ fault(record, "view/bridge-failed", "The dedicated author port of the view closed.");
1030
995
  });
1031
996
  return channel.port2;
1032
997
  }
@@ -1129,13 +1094,8 @@ function createHtmlViewHost(options) {
1129
1094
  } catch {}
1130
1095
  record.closeListeners.clear();
1131
1096
  record.eventListeners.clear();
1132
- const endpoints = [
1133
- record.endpoint,
1134
- record.assetEndpoint,
1135
- record.contentEndpoint
1136
- ];
1097
+ const endpoints = [record.endpoint, record.contentEndpoint];
1137
1098
  record.endpoint = void 0;
1138
- record.assetEndpoint = void 0;
1139
1099
  record.contentEndpoint = void 0;
1140
1100
  for (const endpoint of endpoints) try {
1141
1101
  endpoint?.dispose();
@@ -1613,6 +1573,6 @@ function assertAssetPath(path) {
1613
1573
  if (problem !== void 0) throw new HtmlViewError("view/load-failed", `Asset path ${JSON.stringify(path)} ${problem}.`);
1614
1574
  }
1615
1575
  //#endregion
1616
- export { mimeTypeOf as A, HTML_VIEW_ATTACH as B, ENVIRONMENT_DOCUMENT_FILE as C, assetRootUrl as D, HTML_VIEW_ENVIRONMENT_POLICY as E, newHtmlEnvironmentId as F, HTML_VIEW_CONNECT as G, HTML_VIEW_CHILD_CONNECT as H, parseHtmlViewBase as I, fusedHtmlAssetService as J, HTML_VIEW_FRAME_PARAM as K, HTML_VIEW_ACK as L, withHtmlDocumentPreamble as M, VIEW_ENV_LABEL as N, authorBaseUrl as O, htmlEnvironmentUrl as P, isHtmlViewError as Q, HTML_VIEW_ASSETS as R, ENVIRONMENT_CONTENT_FILE as S, HTML_VIEW_CONTENT_POLICY as T, HTML_VIEW_CHILD_HELLO as U, HTML_VIEW_ATTACH_ACK as V, HTML_VIEW_CHILD_PREPARED as W, fusedHtmlHostControlService as X, fusedHtmlContentViewService as Y, fusedHtmlHostService as Z, resolveTheme as _, createHtmlViewHost as a, ENVIRONMENT_BOOTSTRAP_FILE as b, applyHtmlViewTheme as c, normalizeHtmlViewTheme as d, WORKBENCH_DARK_COLORS as f, readCanvasTheme as g, normalizeTheme as h, htmlViewDeviceDeclaration as i, resolveAssetRequest as j, decodeDocument as k, htmlViewThemeCss as l, WORKBENCH_THEME_CSS_VARIABLES as m, createDeviceViewSession as n, htmlViewKey as o, WORKBENCH_LIGHT_COLORS as p, HtmlViewError as q, createHtmlViewRuntimeSource as r, DEFAULT_HTML_VIEW_THEME as s, assertAssetPath as t, htmlViewThemeEquals as u, themeStyle as v, ENVIRONMENT_WORKER_FILE as w, ENVIRONMENT_CONTENT_DOCUMENT_FILE as x, ASSET_ROOT_DIRECTORY as y, HTML_VIEW_ASSETS_ACK as z };
1576
+ export { mimeTypeOf as A, HTML_VIEW_ATTACH_ACK as B, ENVIRONMENT_DOCUMENT_FILE as C, assetRootUrl as D, HTML_VIEW_ENVIRONMENT_POLICY as E, newHtmlEnvironmentId as F, HTML_VIEW_FRAME_PARAM as G, HTML_VIEW_CHILD_HELLO as H, parseHtmlViewBase as I, fusedHtmlContentViewService as J, HtmlViewError as K, HTML_VIEW_ACK as L, withHtmlDocumentPreamble as M, VIEW_ENV_LABEL as N, authorBaseUrl as O, htmlEnvironmentUrl as P, HTML_VIEW_ASSET_READ as R, ENVIRONMENT_CONTENT_FILE as S, HTML_VIEW_CONTENT_POLICY as T, HTML_VIEW_CHILD_PREPARED as U, HTML_VIEW_CHILD_CONNECT as V, HTML_VIEW_CONNECT as W, fusedHtmlHostService as X, fusedHtmlHostControlService as Y, isHtmlViewError as Z, resolveTheme as _, createHtmlViewHost as a, ENVIRONMENT_BOOTSTRAP_FILE as b, applyHtmlViewTheme as c, normalizeHtmlViewTheme as d, WORKBENCH_DARK_COLORS as f, readCanvasTheme as g, normalizeTheme as h, htmlViewDeviceDeclaration as i, resolveAssetRequest as j, decodeDocument as k, htmlViewThemeCss as l, WORKBENCH_THEME_CSS_VARIABLES as m, createDeviceViewSession as n, htmlViewKey as o, WORKBENCH_LIGHT_COLORS as p, fusedHtmlAssetService as q, createHtmlViewRuntimeSource as r, DEFAULT_HTML_VIEW_THEME as s, assertAssetPath as t, htmlViewThemeEquals as u, themeStyle as v, ENVIRONMENT_WORKER_FILE as w, ENVIRONMENT_CONTENT_DOCUMENT_FILE as x, ASSET_ROOT_DIRECTORY as y, HTML_VIEW_ATTACH as z };
1617
1577
 
1618
- //# sourceMappingURL=html-HXwZq1my.js.map
1578
+ //# sourceMappingURL=html-B0pN-5Mx.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"html-B0pN-5Mx.js","names":[],"sources":["../src/fused/html/protocol.ts","../src/fused/html/base-url.ts","../src/fused/html/layout.ts","../src/fused/html/paths.ts","../src/fused/theme.ts","../src/fused/html/theme.ts","../src/fused/html/host.ts","../src/fused/html/source.ts","../src/fused/html/client.ts"],"sourcesContent":["/**\n * Wire contracts of the device HTML view bridge (RFC 0023).\n *\n * One environment per `(instanceId, viewId)`: a trusted OUTER frame on a deployment directory of its\n * own origin and one INNER sandboxed frame inside it. Both are real documents of that origin\n * (`index.html` and `content.html`), so every origin of both frames is concrete and comparable.\n * The outer owns the author document: it writes it into the inner document once the inner bootstrap\n * announced that the API and the package grant are in place. The editor keeps a control lane to\n * the outer frame and an author lane directly to the inner frame. The asset worker requests package\n * reads from the outer frame on a port scoped to each fetch, so it can restart independently.\n */\nimport { defineRpcService } from '@mica-js/core/rpc';\nimport type { Value } from '@mica-js/document/fused';\nimport type { ModelEvent } from '@mica-js/sdk/fused';\nimport type { WorkbenchThemeColors } from '../theme';\nimport type { FusedPresentationProps } from '../runtime/protocol';\n\n/** Diagnostic codes the HTML view contract reports (RFC 0023 \"校验\"). */\nexport type HtmlViewDiagnosticCode =\n | 'view/invalid-base-url-template'\n | 'view/unknown-entry'\n | 'view/unavailable-mode'\n | 'view/load-failed'\n | 'view/bridge-failed'\n | 'view/execution-failed';\n\n/** Failure of one HTML view; the container shows device, title and reason. */\nexport interface IHtmlViewFailure {\n readonly code: HtmlViewDiagnosticCode;\n readonly message: string;\n readonly instanceId: string;\n readonly viewId: string;\n readonly title: string;\n readonly device: string;\n}\n\n/** Local contract failure of the HTML view host or of one environment. */\nexport class HtmlViewError extends Error {\n readonly code: HtmlViewDiagnosticCode;\n readonly instanceId: string | undefined;\n readonly viewId: string | undefined;\n\n constructor(\n code: HtmlViewDiagnosticCode,\n message: string,\n options: { readonly instanceId?: string; readonly viewId?: string } = {},\n ) {\n super(message);\n this.name = 'HtmlViewError';\n this.code = code;\n this.instanceId = options.instanceId;\n this.viewId = options.viewId;\n }\n}\n\nexport function isHtmlViewError(value: unknown): value is HtmlViewError {\n return value instanceof HtmlViewError;\n}\n\n/** Control message the editor posts into a freshly loaded environment. */\nexport const HTML_VIEW_CONNECT = 'mica:view:connect';\n\n/** Acknowledgement the environment posts back once it owns the transferred port. */\nexport const HTML_VIEW_ACK = 'mica:view:ack';\n\n/** The asset worker requests a port for one package fetch. */\nexport const HTML_VIEW_ASSET_READ = 'mica:view:asset-read';\n\n/** Control message the inner frame sends through the asset worker to authorize its requests. */\nexport const HTML_VIEW_ATTACH = 'mica:view:attach';\n\n/** Acknowledgement of {@link HTML_VIEW_ATTACH}; only then may the author document load. */\nexport const HTML_VIEW_ATTACH_ACK = 'mica:view:attach-ack';\n\n/** Control message the inner frame posts to the environment once its bootstrap runs. */\nexport const HTML_VIEW_CHILD_HELLO = 'mica:view:child-hello';\n\n/** Control message the environment answers with the bridge port of the inner frame. */\nexport const HTML_VIEW_CHILD_CONNECT = 'mica:view:child-connect';\n\n/** Control message the inner frame posts once its API and its package grant are in place. */\nexport const HTML_VIEW_CHILD_PREPARED = 'mica:view:child-prepared';\n\n/**\n * Query parameter that carries the one-time token of one inner frame.\n *\n * The inner document is a real same-origin URL, so both frames derive the environment origin from\n * their own location; only the frame token travels in the URL, and it never grants host access.\n */\nexport const HTML_VIEW_FRAME_PARAM = 'view';\n\n/** Resolved workbench theme one environment mirrors into its author document. */\nexport interface IHtmlViewTheme {\n readonly appearance: 'dark' | 'light';\n /** Computed CSS colors of the workbench tokens; every token is present. */\n readonly colors: WorkbenchThemeColors;\n}\n\n/** Everything one environment needs before the author document exists. */\nexport interface IHtmlViewTarget {\n readonly instanceId: string;\n readonly viewId: string;\n readonly device: string;\n readonly title: string;\n /** Package-root relative `.html` entry of the view. */\n readonly entry: string;\n /** Absolute URL prefix that serves the verified package files of this view. */\n readonly assetRoot: string;\n /** Resolved property snapshot, identical to the one the model received. */\n readonly props: FusedPresentationProps;\n /** Declared model methods; empty for a device without a model. */\n readonly methods: readonly string[];\n /** Declared model events; empty for a device without a model. */\n readonly events: readonly string[];\n /** Whether the device declares a model; an absent model leaves `api.model` undefined. */\n readonly hasModel: boolean;\n}\n\nexport interface IHtmlViewConnectMessage {\n readonly type: typeof HTML_VIEW_CONNECT;\n /** One-time value of this environment; messages of stale pages never match it. */\n readonly token: string;\n /** Origin the environment must use for every message back to the editor. */\n readonly parentOrigin: string;\n readonly target: IHtmlViewTarget;\n}\n\nexport interface IHtmlViewAckMessage {\n readonly type: typeof HTML_VIEW_ACK;\n readonly token: string;\n}\n\n/** Authorization of one inner frame in the package asset worker. */\nexport interface IHtmlViewAttachMessage {\n readonly type: typeof HTML_VIEW_ATTACH;\n /** Grant token the frame read from its own view identity, never from the author document. */\n readonly token: string;\n}\n\nexport interface IHtmlViewAttachAckMessage {\n readonly type: typeof HTML_VIEW_ATTACH_ACK;\n readonly token: string;\n}\n\n/** Handshake of the inner bootstrap, posted before any author script exists. */\nexport interface IHtmlViewChildHelloMessage {\n readonly type: typeof HTML_VIEW_CHILD_HELLO;\n readonly token: string;\n}\n\n/** Answer of the environment, carrying the one author port of the inner frame. */\nexport interface IHtmlViewChildConnectMessage {\n readonly type: typeof HTML_VIEW_CHILD_CONNECT;\n readonly token: string;\n}\n\n/** Announcement of the inner frame that its API and its package grant are in place. */\nexport interface IHtmlViewChildPreparedMessage {\n readonly type: typeof HTML_VIEW_CHILD_PREPARED;\n readonly token: string;\n}\n\n/** One model event pushed into an environment, for an event it subscribed to. */\nexport interface IFusedHtmlModelEventWire {\n readonly name: string;\n readonly payload: ModelEvent<Value>;\n}\n\n/**\n * Author-facing capabilities of one inner frame, served directly by the editor.\n *\n * Every member is bound to the lease of one view: the declared methods and events of that instance,\n * the verified package of that lock and the live proxy of that model.\n */\nexport interface IFusedHtmlHostService {\n /** Reads one declared package file; `path` is package-root relative and verified. */\n readAsset(path: string): Promise<Uint8Array>;\n /** Invokes one declared model method through the live model proxy of the instance. */\n callModel(method: string, params: Value): Promise<Value>;\n /** Starts receiving one declared model event. */\n subscribe(event: string): Promise<void>;\n /** Stops receiving one declared model event. */\n unsubscribe(event: string): Promise<void>;\n /** Every subscribed model event of this environment, in production order. */\n onDidModelEvent(listener: (event: IFusedHtmlModelEventWire) => void): () => void;\n /** Announces that the editor released this environment. */\n onDidClose(listener: () => void): () => void;\n /** Reports an author failure; the editor faults the view (RFC 0023). */\n reportFailure(code: string, message: string): Promise<void>;\n}\n\n/** Lifecycle and verified package reads of the trusted outer frame. */\nexport interface IFusedHtmlHostControlService {\n /** Reads one declared package file of this view, including the entry document. */\n readAsset(path: string): Promise<Uint8Array>;\n /** Computed theme of the workbench at this moment. */\n getTheme(): Promise<IHtmlViewTheme>;\n /** Announces every later theme of the workbench, including appearance changes. */\n onDidThemeChange(listener: (theme: IHtmlViewTheme) => void): () => void;\n /** Announces that the author document is written; the view leaves the loading state. */\n ready(): Promise<void>;\n /** Reports an author failure; the editor faults the view (RFC 0023). */\n reportFailure(code: string, message: string): Promise<void>;\n /** Announces that the environment goes away without an editor request. */\n closed(): void;\n /**\n * Grants the dedicated author lane of this view's inner frame, once.\n *\n * The port is transferred into the sandboxed frame straight from the outer frame, after that\n * frame announced its own hello with the token of this environment.\n */\n contentPort(): Promise<MessagePort>;\n}\n\n/** Package bytes the trusted outer frame answers one asset request with. */\nexport interface IFusedHtmlAssetService {\n /** Reads a verified package file for this fetch, or returns undefined for an unauthorized client. */\n read(path: string): Promise<Uint8Array | undefined>;\n}\n\n/** Identity of one view, as the inner frame receives it before the author document exists. */\nexport interface IHtmlViewContent {\n /**\n * Package grant token of this environment.\n *\n * It never appears in the author document; the inner frame presents it to the asset worker so\n * only this frame may read the package files of the view.\n */\n readonly token: string;\n readonly target: IHtmlViewTarget;\n}\n\n/**\n * View identity the inner frame reads from the editor before the author document exists.\n *\n * It shares the author lane port with {@link IFusedHtmlHostService}, so props, declared methods and\n * events arrive from the same lease and never travel through the outer frame.\n */\nexport interface IFusedHtmlContentViewService {\n /** Reads the identity of the view; the inner frame calls this exactly once. */\n view(): Promise<IHtmlViewContent>;\n}\n\n/** Typed author lane between the editor and one inner frame. */\nexport const fusedHtmlHostService = defineRpcService<IFusedHtmlHostService>('fused-html-host');\n\n/** Typed control lane between the editor and one trusted environment page. */\nexport const fusedHtmlHostControlService =\n defineRpcService<IFusedHtmlHostControlService>('fused-html-host-control');\n\n/** Typed package lane between the editor and one environment's asset worker. */\nexport const fusedHtmlAssetService = defineRpcService<IFusedHtmlAssetService>('fused-html-asset');\n\n/** Typed view identity lane of one inner frame; it shares the author lane port. */\nexport const fusedHtmlContentViewService =\n defineRpcService<IFusedHtmlContentViewService>('fused-html-content-view');\n","/**\n * Validated `viewBaseUrlTemplate` of the HTML view environments (RFC 0023).\n *\n * The template names the deployment directory of the environment resources and carries exactly one\n * `${id}` hostname label. Every environment substitutes a fresh DNS label, so two environments never\n * share an origin and one environment can never read the storage or workers of another.\n */\nimport { HtmlViewError } from './protocol';\n\n/** Placeholder of the environment id inside the template's hostname. */\nexport const VIEW_ENV_LABEL = '${id}';\n\n/** Label used to validate the template around the environment id. */\nconst PLACEHOLDER_LABEL = 'mica-environment';\n\nconst DNS_LABEL = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\n\n/** Validated base URL of the HTML environment deployment. */\nexport interface IHtmlViewBase {\n /** Configured template, with its single `${id}` label retained. */\n readonly template: string;\n /** Minimum suffix shared by every environment URL, used for diagnostics only. */\n readonly deployment: string;\n}\n\n/**\n * Validates one `viewBaseUrlTemplate`.\n *\n * @throws {HtmlViewError} `view/invalid-base-url-template` when the template is not an absolute\n * HTTP(S) directory URL with one standalone `${id}` hostname label on an independent origin.\n */\nexport function parseHtmlViewBase(template: string, hostOrigin?: string): IHtmlViewBase {\n function fail(reason: string): never {\n throw new HtmlViewError(\n 'view/invalid-base-url-template',\n `viewBaseUrlTemplate ${reason}: ${JSON.stringify(template)}`,\n );\n }\n if (typeof template !== 'string' || template.length === 0) fail('must be a non-empty string');\n if (!template.endsWith('/')) fail(\"must end with '/'\");\n if (template.split(VIEW_ENV_LABEL).length !== 2) fail('must contain exactly one ${id} label');\n\n const parsed = parseUrl(template.replace(VIEW_ENV_LABEL, PLACEHOLDER_LABEL));\n if (parsed === undefined) fail('must be an absolute URL');\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') fail('must use HTTP or HTTPS');\n if (parsed.search !== '' || parsed.hash !== '') fail('must not carry a query or a fragment');\n if (parsed.username !== '' || parsed.password !== '') fail('must not carry credentials');\n if (!parsed.hostname.split('.').includes(PLACEHOLDER_LABEL))\n fail('must place ${id} as a complete hostname label');\n\n if (hostOrigin !== undefined) {\n const environment = parseUrl(template.replace(VIEW_ENV_LABEL, PLACEHOLDER_LABEL));\n if (environment !== undefined && environment.origin === hostOrigin)\n fail('must use an origin independent of the editor');\n }\n return Object.freeze({ template, deployment: parsed.origin });\n}\n\n/**\n * Environment URL of one validated base and environment id.\n *\n * @throws {TypeError} when `id` is not a DNS label; ids come from {@link newHtmlEnvironmentId}.\n */\nexport function htmlEnvironmentUrl(base: IHtmlViewBase, id: string): URL {\n if (!DNS_LABEL.test(id) || id.length > 63)\n throw new TypeError(`HTML view environment id must be a DNS label, received \"${id}\"`);\n return new URL(base.template.replace(VIEW_ENV_LABEL, id));\n}\n\n/** Fresh environment id; distinct ids give every environment its own origin. */\nexport function newHtmlEnvironmentId(): string {\n const bytes = new Uint8Array(8);\n const webCrypto = globalThis.crypto;\n if (typeof webCrypto?.getRandomValues === 'function') webCrypto.getRandomValues(bytes);\n else for (let index = 0; index < bytes.length; index += 1) bytes[index] = Math.random() * 256;\n const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, '0'));\n return `mica-${hex.join('')}`;\n}\n\nfunction parseUrl(value: string): URL | undefined {\n try {\n return new URL(value);\n } catch {\n return undefined;\n }\n}\n","/**\n * Visible bounds of one environment slot (RFC 0023 container behaviour).\n *\n * The environment owner lives in a fixed layer, so nothing clips it for free: a slot that is\n * partially scrolled out of `.mica-wb-sidebar-content` would otherwise paint over the editor. The\n * manager clips the owner with `clip-path` instead of resizing it, so the page never reflows while\n * the surrounding UI scrolls.\n */\n\n/** One viewport-aligned box, in CSS pixels. */\nexport interface IClipRect {\n readonly left: number;\n readonly top: number;\n readonly right: number;\n readonly bottom: number;\n}\n\n/** Insets of the visible part of a slot, relative to the slot box. */\nexport interface ISlotClip {\n readonly left: number;\n readonly top: number;\n readonly right: number;\n readonly bottom: number;\n /** `false` when the slot lies completely outside every clipping box. */\n readonly visible: boolean;\n}\n\n/**\n * Insets that clip one slot to the intersection of `bounds`.\n *\n * Every value is expressed against the slot box, so `clip-path: inset(...)` keeps the owner exactly\n * over the slot and only hides the parts outside the scrolling ancestors or the viewport.\n */\nexport function clipInsets(slot: IClipRect, bounds: readonly IClipRect[]): ISlotClip {\n if (!hasArea(slot)) {\n return { left: 0, top: 0, right: 0, bottom: 0, visible: false };\n }\n let left = slot.left;\n let top = slot.top;\n let right = slot.right;\n let bottom = slot.bottom;\n for (const bound of bounds) {\n left = Math.max(left, bound.left);\n top = Math.max(top, bound.top);\n right = Math.min(right, bound.right);\n bottom = Math.min(bottom, bound.bottom);\n }\n if (right <= left || bottom <= top) {\n return { left: 0, top: 0, right: 0, bottom: 0, visible: false };\n }\n return {\n left: left - slot.left,\n top: top - slot.top,\n right: slot.right - right,\n bottom: slot.bottom - bottom,\n visible: true,\n };\n}\n\n/** Whether one box has a positive extent. */\nexport function hasArea(rect: IClipRect): boolean {\n return rect.right > rect.left && rect.bottom > rect.top;\n}\n\n/** CSS `clip-path` value of one slot clip; `none` when nothing is cut. */\nexport function clipPathOf(clip: ISlotClip): string {\n if (!clip.visible) return 'inset(100%)';\n if (clip.left === 0 && clip.top === 0 && clip.right === 0 && clip.bottom === 0) return 'none';\n return `inset(${clip.top}px ${clip.right}px ${clip.bottom}px ${clip.left}px)`;\n}\n","/**\n * Resource mapping of one device HTML environment (RFC 0023).\n *\n * The environment is served from a deployment directory of its own origin, so relative HTML, CSS\n * and ES module references must resolve *inside the package*. Every package file therefore lives\n * under one asset root whose path mirrors the package root; the author document gets a `<base>`\n * pointing at its own package directory. The environment's service worker turns those requests into\n * verified package reads and refuses everything else, including page navigations.\n *\n * The trusted environment document creates one inner sandboxed frame from\n * {@link ENVIRONMENT_CONTENT_DOCUMENT_FILE}; both are real documents of the same per-view origin,\n * which no editor page shares, and the environment writes the author document into the inner\n * document itself.\n */\nimport { packagePathProblem } from '@mica-js/document/fused';\n\n/** Directory under the environment base URL that serves the package files. */\nexport const ASSET_ROOT_DIRECTORY = '__mica_package__/';\n\n/** Bootstrap document the editor loads in the environment iframe. */\nexport const ENVIRONMENT_DOCUMENT_FILE = 'index.html';\n\n/** Bundled bootstrap module loaded by {@link ENVIRONMENT_DOCUMENT_FILE}. */\nexport const ENVIRONMENT_BOOTSTRAP_FILE = 'environment.js';\n\n/** Document the environment loads in the inner sandbox frame; a real same-origin URL. */\nexport const ENVIRONMENT_CONTENT_DOCUMENT_FILE = 'content.html';\n\n/** Bundled bootstrap module {@link ENVIRONMENT_CONTENT_DOCUMENT_FILE} loads. */\nexport const ENVIRONMENT_CONTENT_FILE = 'content.js';\n\n/** Bundled service worker that serves the package files of one environment. */\nexport const ENVIRONMENT_WORKER_FILE = 'environment-sw.js';\n\n/**\n * Content security policy of the author document and of the inner content document.\n *\n * Package scripts, styles, fonts and images are same-origin because the asset worker serves them;\n * opaque `blob:` URLs are the `assets.getUrl` results of the view itself. Nothing else is reachable:\n * the author page has no network, no frames and no form targets. The inner document is served with\n * this policy so an author document can never nest another frame, whatever the trusted environment\n * allows itself.\n */\nexport const HTML_VIEW_CONTENT_POLICY = [\n \"default-src 'none'\",\n \"script-src 'self' 'unsafe-inline'\",\n \"style-src 'self' 'unsafe-inline'\",\n \"img-src 'self' data: blob:\",\n \"font-src 'self' data: blob:\",\n \"media-src 'self' data: blob:\",\n \"connect-src 'self' blob:\",\n \"frame-src 'none'\",\n \"object-src 'none'\",\n \"form-action 'none'\",\n \"base-uri 'self'\",\n].join('; ');\n\n/**\n * Policy of the trusted environment document.\n *\n * It only differs from the author policy where the environment itself needs more: exactly one inner\n * frame of its own deployment directory, and the asset worker registration. The inner document is\n * served with {@link HTML_VIEW_CONTENT_POLICY}, so the author document still cannot nest frames,\n * reach another origin or post a form.\n */\nexport const HTML_VIEW_ENVIRONMENT_POLICY = [\n \"default-src 'none'\",\n \"script-src 'self' 'unsafe-inline'\",\n \"style-src 'self' 'unsafe-inline'\",\n \"img-src 'self' data: blob:\",\n \"font-src 'self' data: blob:\",\n \"media-src 'self' data: blob:\",\n \"connect-src 'self' blob:\",\n \"worker-src 'self'\",\n \"frame-src 'self'\",\n \"object-src 'none'\",\n \"form-action 'none'\",\n \"base-uri 'self'\",\n].join('; ');\n\n/** Absolute URL prefix that serves the verified package files of one environment. */\nexport function assetRootUrl(baseUrl: URL): URL {\n return new URL(ASSET_ROOT_DIRECTORY, baseUrl);\n}\n\n/**\n * Base URL the author document resolves relative references against.\n *\n * The asset root mirrors the package root, so the document base is the directory of the view entry\n * and `./main.js` of `views/serial/index.html` resolves to the package file `views/serial/main.js`.\n */\nexport function authorBaseUrl(assetRoot: URL, entry: string): string {\n const root = assetRoot.href.endsWith('/') ? assetRoot.href : `${assetRoot.href}/`;\n const separator = entry.lastIndexOf('/');\n return separator <= 0 ? root : `${root}${entry.slice(0, separator + 1)}`;\n}\n\n/**\n * Package path of one asset request, or `undefined` when the request leaves the package.\n *\n * `root` is the pathname of {@link assetRootUrl}; requests outside it, encoded separators and empty\n * segments are rejected, so a view cannot read the environment bootstrap or another package.\n */\nexport function resolveAssetRequest(pathname: string, root: string): string | undefined {\n const prefix = root.endsWith('/') ? root : `${root}/`;\n if (!pathname.startsWith(prefix)) return undefined;\n const rest = pathname.slice(prefix.length);\n if (rest.length === 0) return undefined;\n const segments: string[] = [];\n for (const segment of rest.split('/')) {\n let decoded: string;\n try {\n decoded = decodeURIComponent(segment);\n } catch {\n return undefined;\n }\n if (decoded.length === 0 || decoded === '.' || decoded === '..') return undefined;\n if (decoded.includes('/') || decoded.includes('\\\\')) return undefined;\n segments.push(decoded);\n }\n const path = segments.join('/');\n return packagePathProblem(path) === undefined ? path : undefined;\n}\n\nconst MIME_TYPES: Readonly<Record<string, string>> = Object.freeze({\n html: 'text/html; charset=utf-8',\n htm: 'text/html; charset=utf-8',\n js: 'text/javascript; charset=utf-8',\n mjs: 'text/javascript; charset=utf-8',\n css: 'text/css; charset=utf-8',\n json: 'application/json; charset=utf-8',\n map: 'application/json; charset=utf-8',\n svg: 'image/svg+xml',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n avif: 'image/avif',\n ico: 'image/x-icon',\n woff: 'font/woff',\n woff2: 'font/woff2',\n ttf: 'font/ttf',\n otf: 'font/otf',\n wasm: 'application/wasm',\n txt: 'text/plain; charset=utf-8',\n bin: 'application/octet-stream',\n});\n\n/** Response content type of one package file. */\nexport function mimeTypeOf(path: string): string {\n const separator = path.lastIndexOf('.');\n if (separator <= 0) return 'application/octet-stream';\n return MIME_TYPES[path.slice(separator + 1).toLowerCase()] ?? 'application/octet-stream';\n}\n\n/** Preamble injected into the author document before any of its own markup. */\nexport interface IHtmlDocumentPreamble {\n /** Absolute base URL the author document resolves relative references against. */\n readonly base: string;\n /** Content security policy of the author document. */\n readonly policy: string;\n /** Theme declarations of the environment, applied before any author script runs. */\n readonly style: string;\n}\n\n/**\n * Injects the document preamble of one view.\n *\n * The `<base>` must be the first base element, the policy travels with the document because it is\n * written into a document of its own, and the theme declarations come before every author script so\n * the author never paints a frame with missing tokens.\n */\nexport function withHtmlDocumentPreamble(html: string, preamble: IHtmlDocumentPreamble): string {\n const markup = [\n '<meta charset=\"utf-8\">',\n `<meta http-equiv=\"Content-Security-Policy\" content=\"${escapeAttribute(preamble.policy)}\">`,\n `<base href=\"${escapeAttribute(preamble.base)}\">`,\n `<style>${preamble.style.replace(/<\\/style/gi, '<\\\\/style')}</style>`,\n ].join('');\n const head = /<head\\b[^>]*>/i.exec(html);\n if (head !== null) {\n const at = head.index + head[0].length;\n return `${html.slice(0, at)}${markup}${html.slice(at)}`;\n }\n const open = /<html\\b[^>]*>/i.exec(html);\n if (open !== null) {\n const at = open.index + open[0].length;\n return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;\n }\n const doctype = /<!doctype[^>]*>/i.exec(html);\n if (doctype !== null) {\n const at = doctype.index + doctype[0].length;\n return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;\n }\n return `<head>${markup}</head>${html}`;\n}\n\n/** Concrete HTTP(S) origin; used to reject an opaque or malformed frame location. */\nconst FRAME_ORIGIN = /^https?:\\/\\/[^/]+$/;\n\n/**\n * Concrete HTTP(S) origin of a URL, or `undefined` when the document has no comparable origin.\n *\n * Both frames of an environment are real documents of the deployment directory, so their origins\n * are concrete; this guard keeps a stray `about:`, `blob:` or `data:` location from ever being\n * compared as if it were the environment.\n */\nexport function concreteOriginOf(url: string | undefined): string | undefined {\n if (url === undefined || url === '') return undefined;\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return undefined;\n return FRAME_ORIGIN.test(parsed.origin) ? parsed.origin : undefined;\n } catch {\n return undefined;\n }\n}\n/**\n * Owns a plain `ArrayBuffer` copy of one byte snapshot.\n *\n * `Blob`, `Response` and the transfer list reject a `SharedArrayBuffer`-backed view, so every byte\n * snapshot that leaves this module is copied first.\n */\nexport function imageBuffer(bytes: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return copy.buffer;\n}\n\n/** Decodes package bytes as UTF-8 text, tolerating a byte order mark. */\nexport function decodeDocument(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes).replace(/^\\uFEFF/, '');\n}\n\n/** Escapes one attribute value; policy, base and token never reach the document unescaped. */\nexport function escapeAttribute(value: string): string {\n return value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;');\n}\n","export const WORKBENCH_THEME_CSS_VARIABLES = Object.freeze({\n 'workbench.background': '--mica-bg',\n 'workbench.foreground': '--mica-text',\n 'workbench.mutedForeground': '--mica-muted',\n 'panel.background': '--mica-panel',\n border: '--mica-border',\n accent: '--mica-accent',\n 'accent.foreground': '--mica-accent-foreground',\n 'selection.background': '--mica-active',\n 'focus.border': '--mica-focus',\n 'canvas.background': '--mica-canvas-background',\n 'canvas.grid': '--mica-canvas-grid',\n 'canvas.foreground': '--mica-canvas-foreground',\n 'canvas.wire': '--mica-canvas-wire',\n 'canvas.pin': '--mica-canvas-pin',\n 'canvas.selection': '--mica-canvas-selection',\n 'error.foreground': '--mica-error',\n shadow: '--mica-shadow',\n} as const);\n\nexport type WorkbenchColorToken = keyof typeof WORKBENCH_THEME_CSS_VARIABLES;\nexport type WorkbenchThemeColors = Readonly<Record<WorkbenchColorToken, string>>;\nexport type WorkbenchThemeAppearance = 'dark' | 'light' | 'system';\nexport type WorkbenchTheme = WorkbenchThemeAppearance | IWorkbenchTheme;\n\nexport interface IWorkbenchTheme {\n readonly appearance?: WorkbenchThemeAppearance;\n readonly colors?: Partial<WorkbenchThemeColors>;\n}\n\nexport interface IResolvedWorkbenchTheme {\n readonly appearance: 'dark' | 'light';\n readonly colors: WorkbenchThemeColors;\n}\n\nexport const WORKBENCH_DARK_COLORS: WorkbenchThemeColors = Object.freeze({\n 'workbench.background': '#1c1c1c',\n 'workbench.foreground': '#e5e5e5',\n 'workbench.mutedForeground': '#a3a3a3',\n 'panel.background': '#242424',\n border: '#383838',\n accent: '#d4d4d4',\n 'accent.foreground': '#171717',\n 'selection.background': '#353535',\n 'focus.border': '#b8b8b8',\n 'canvas.background': '#151515',\n 'canvas.grid': '#303030',\n 'canvas.foreground': '#d4d4d4',\n 'canvas.wire': '#a3a3a3',\n 'canvas.pin': '#c4c4c4',\n 'canvas.selection': '#eeeeee',\n 'error.foreground': '#f28b82',\n shadow: '#00000055',\n});\n\nexport const WORKBENCH_LIGHT_COLORS: WorkbenchThemeColors = Object.freeze({\n 'workbench.background': '#ffffff',\n 'workbench.foreground': '#263247',\n 'workbench.mutedForeground': '#748098',\n 'panel.background': '#fafbfe',\n border: '#e2e6ed',\n accent: '#336df0',\n 'accent.foreground': '#ffffff',\n 'selection.background': '#e8efff',\n 'focus.border': '#336df0',\n 'canvas.background': '#f6f7fa',\n 'canvas.grid': '#cdd3de',\n 'canvas.foreground': '#354058',\n 'canvas.wire': '#508d79',\n 'canvas.pin': '#4285ff',\n 'canvas.selection': '#4285ff',\n 'error.foreground': '#b43b35',\n shadow: '#00000022',\n});\n\nfunction isToken(value: string): value is WorkbenchColorToken {\n return Object.hasOwn(WORKBENCH_THEME_CSS_VARIABLES, value);\n}\n\nexport function normalizeTheme(theme: WorkbenchTheme = 'dark'): IWorkbenchTheme {\n const appearance = typeof theme === 'string' ? theme : (theme.appearance ?? 'dark');\n if (!['dark', 'light', 'system'].includes(appearance))\n throw new Error(`Unknown workbench theme appearance: ${appearance}`);\n const colors: Partial<Record<WorkbenchColorToken, string>> = {};\n if (typeof theme !== 'string') {\n for (const [token, value] of Object.entries(theme.colors ?? {})) {\n if (!isToken(token)) throw new Error(`Unknown workbench color token: ${token}`);\n if (typeof value !== 'string' || value.trim() === '')\n throw new Error(`Workbench color token ${token} must be a non-empty CSS color`);\n colors[token] = value;\n }\n }\n return Object.freeze({ appearance, colors: Object.freeze(colors) });\n}\n\nexport function resolveTheme(theme: IWorkbenchTheme, systemDark: boolean): IResolvedWorkbenchTheme {\n const appearance =\n theme.appearance === 'system' ? (systemDark ? 'dark' : 'light') : (theme.appearance ?? 'dark');\n return Object.freeze({\n appearance,\n colors: Object.freeze({\n ...(appearance === 'dark' ? WORKBENCH_DARK_COLORS : WORKBENCH_LIGHT_COLORS),\n ...theme.colors,\n }),\n });\n}\n\nexport function themeStyle(theme: IResolvedWorkbenchTheme): Record<`--mica-${string}`, string> {\n const result: Record<`--mica-${string}`, string> = {};\n for (const [token, variable] of Object.entries(WORKBENCH_THEME_CSS_VARIABLES))\n if (isToken(token)) result[variable] = theme.colors[token];\n return result;\n}\n\nexport function readCanvasTheme(element: HTMLElement): WorkbenchThemeColors {\n const style = getComputedStyle(element);\n const colors = { ...WORKBENCH_DARK_COLORS };\n for (const [token, variable] of Object.entries(WORKBENCH_THEME_CSS_VARIABLES)) {\n if (!isToken(token)) continue;\n const value = style.getPropertyValue(variable).trim();\n if (value === '' || !CSS.supports('color', value))\n throw new Error(`Workbench token ${token} did not resolve to a CSS color`);\n colors[token] = value;\n }\n return colors;\n}\n","/**\n * Theme mirroring of the device HTML views (RFC 0023).\n *\n * The editor forwards the computed colors of its workbench tokens over the typed host bridge; the\n * environment injects them into the author document before any author script runs and updates the\n * document root in place afterwards, so a theme change never reloads a frame and never loses author\n * input, model session or document history. An environment without an editor theme keeps a complete\n * dark palette, so the author document always resolves every token.\n */\nimport {\n WORKBENCH_DARK_COLORS,\n WORKBENCH_LIGHT_COLORS,\n WORKBENCH_THEME_CSS_VARIABLES,\n} from '../theme';\nimport type { WorkbenchColorToken, WorkbenchThemeColors } from '../theme';\nimport type { IHtmlViewTheme } from './protocol';\n\n/** Theme of an environment whose editor forwarded no colors yet. */\nexport const DEFAULT_HTML_VIEW_THEME: IHtmlViewTheme = Object.freeze({\n appearance: 'dark',\n colors: WORKBENCH_DARK_COLORS,\n});\n\nconst TOKENS = Object.keys(WORKBENCH_THEME_CSS_VARIABLES) as readonly WorkbenchColorToken[];\n\n/**\n * Semantic token the generic view background uses.\n *\n * A device view sits inside a workbench panel, so its loading surface is the panel background; the\n * author example paints its own `body` with the same token, which keeps the first paint and the\n * author document seamless.\n */\nexport const HTML_VIEW_BACKGROUND_TOKEN: WorkbenchColorToken = 'panel.background';\n\n/** Resolved CSS color of the view background of one theme. */\nexport function htmlViewBackgroundColor(theme: IHtmlViewTheme): string {\n return theme.colors[HTML_VIEW_BACKGROUND_TOKEN];\n}\n\n/** Characters that would end the injected declaration or the style element. */\nconst UNSAFE_COLOR = /[;{}<>\\\\]/;\n\n/**\n * Validates one theme crossing the bridge and completes missing tokens.\n *\n * @throws {TypeError} when the appearance is unknown, a token is undeclared or a color cannot be\n * placed in a style declaration.\n */\nexport function normalizeHtmlViewTheme(value: unknown): IHtmlViewTheme {\n if (typeof value !== 'object' || value === null)\n throw new TypeError('An HTML view theme must be an object');\n const record = value as { readonly appearance?: unknown; readonly colors?: unknown };\n const appearance = record.appearance ?? 'dark';\n if (appearance !== 'dark' && appearance !== 'light')\n throw new TypeError(`Unknown HTML view theme appearance: ${String(appearance)}`);\n const colors: Partial<Record<WorkbenchColorToken, string>> = {\n ...(appearance === 'dark' ? WORKBENCH_DARK_COLORS : WORKBENCH_LIGHT_COLORS),\n };\n const source = record.colors;\n if (source !== undefined && source !== null) {\n if (typeof source !== 'object') throw new TypeError('HTML view theme colors must be an object');\n for (const [token, color] of Object.entries(source)) {\n if (!Object.hasOwn(WORKBENCH_THEME_CSS_VARIABLES, token))\n throw new TypeError(`Unknown HTML view theme token: ${token}`);\n colors[token as WorkbenchColorToken] = htmlViewColor(token, color);\n }\n }\n for (const token of TOKENS) colors[token] ??= htmlViewColor(token, WORKBENCH_DARK_COLORS[token]);\n return Object.freeze({\n appearance,\n colors: Object.freeze(colors as WorkbenchThemeColors),\n });\n}\n\nfunction htmlViewColor(token: string, value: unknown): string {\n if (typeof value !== 'string' || value.trim() === '')\n throw new TypeError(`HTML view theme token ${token} must be a non-empty CSS color`);\n if (UNSAFE_COLOR.test(value))\n throw new TypeError(`HTML view theme token ${token} must be a plain CSS color`);\n return value.trim();\n}\n\n/** Whether two themes resolve to the same appearance and colors. */\nexport function htmlViewThemeEquals(left: IHtmlViewTheme, right: IHtmlViewTheme): boolean {\n if (left.appearance !== right.appearance) return false;\n return TOKENS.every((token) => left.colors[token] === right.colors[token]);\n}\n\n/** Theme declarations injected into the author document head before any author script. */\nexport function htmlViewThemeCss(theme: IHtmlViewTheme): string {\n const declarations = TOKENS.map(\n (token) => `${WORKBENCH_THEME_CSS_VARIABLES[token]}:${theme.colors[token]}`,\n );\n declarations.push(`color-scheme:${theme.appearance}`);\n // The canvas behind the author page starts as the view background, so no white frame is ever\n // painted between the document write and the first author stylesheet.\n return `:root{background-color:${htmlViewBackgroundColor(theme)};${declarations.join(';')}}`;\n}\n\n/** Mirrors every theme token onto the root element of one document, in place. */\nexport function applyHtmlViewTheme(root: HTMLElement, theme: IHtmlViewTheme): void {\n const style = root.style;\n for (const token of TOKENS)\n style.setProperty(WORKBENCH_THEME_CSS_VARIABLES[token], theme.colors[token]);\n style.setProperty('color-scheme', theme.appearance);\n style.setProperty('background-color', htmlViewBackgroundColor(theme));\n}\n","/**\n * Editor-side manager of the device HTML view environments (RFC 0023).\n *\n * One environment per `(instanceId, viewId)`: an iframe on its own origin served from\n * `viewBaseUrlTemplate`, one transferred `MessagePort` for the typed bridge, and one DOM owner that\n * is created once and never moved. The editor UI attaches the owner to a sidebar or floating slot\n * and the manager only positions it, so docking, floating and resizing keep the same page,\n * listeners, local state and model proxy; collapse keeps the environment mounted, and release\n * disposes it. The environment page itself hosts a sandboxed inner frame for the author document,\n * which is why the manager only ever sees one stable owner and one stable outer page.\n *\n * Two lanes belong to one view lease. The outer frame manages loading, theme, diagnostics and\n * verified package reads. The inner frame has a separate direct port for the author's API and\n * model events.\n */\nimport { DisposableStore, Emitter } from '@mica-js/core/lifecycle';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type {\n DeviceLock,\n DeviceRegistry,\n HtmlViewDefinition,\n Value,\n} from '@mica-js/document/fused';\nimport { packagePathProblem } from '@mica-js/document/fused';\nimport { openDevicePackage } from '@mica-js/sdk/fused';\nimport type { VerifiedPackage } from '@mica-js/sdk/fused';\nimport type { FusedPresentationProps, IFusedModelClient } from '../runtime/protocol';\nimport { messageOf, toWireFailure, transferBytes } from '../runtime/wire';\nimport { htmlEnvironmentUrl, newHtmlEnvironmentId, parseHtmlViewBase } from './base-url';\nimport type { IHtmlViewBase } from './base-url';\nimport { clipInsets, clipPathOf } from './layout';\nimport type { IClipRect } from './layout';\nimport { ENVIRONMENT_DOCUMENT_FILE, assetRootUrl } from './paths';\nimport {\n HTML_VIEW_ACK,\n HTML_VIEW_CONNECT,\n HtmlViewError,\n fusedHtmlContentViewService,\n fusedHtmlHostControlService,\n fusedHtmlHostService,\n} from './protocol';\nimport type {\n HtmlViewDiagnosticCode,\n IFusedHtmlHostControlService,\n IFusedHtmlHostService,\n IFusedHtmlModelEventWire,\n IHtmlViewAckMessage,\n IHtmlViewConnectMessage,\n IHtmlViewContent,\n IHtmlViewFailure,\n IHtmlViewTarget,\n IHtmlViewTheme,\n} from './protocol';\nimport {\n DEFAULT_HTML_VIEW_THEME,\n htmlViewBackgroundColor,\n htmlViewThemeEquals,\n normalizeHtmlViewTheme,\n} from './theme';\n\n/** One live instance an HTML view may attach to. */\nexport interface IHtmlViewInstance {\n readonly device: string;\n readonly lock: DeviceLock;\n readonly props: FusedPresentationProps;\n readonly methods: readonly string[];\n readonly events: readonly string[];\n /**\n * Whether the instance device declares a model (RFC 0021).\n *\n * Authoritative: a model with an empty public surface still counts as present, and a device\n * without a model keeps `api.model` undefined whatever its declared methods and events say.\n */\n readonly hasModel: boolean;\n /** Declared HTML views of the instance device, normally `manifest.view`. */\n readonly views: Readonly<Record<string, HtmlViewDefinition>>;\n}\n\n/** Container an environment occupies; switching never reloads its page. */\nexport type HtmlViewLocation = 'sidebar' | 'floating';\n\n/** Lifecycle of one environment. */\nexport type HtmlViewState = 'loading' | 'ready' | 'failed' | 'closed';\n\nexport interface IHtmlViewOpenRequest {\n readonly instanceId: string;\n readonly viewId: string;\n readonly location: HtmlViewLocation;\n}\n\n/** One stable environment of one view. */\nexport interface IHtmlViewHandle {\n /** Stable key of `(instanceId, viewId)`. */\n readonly key: string;\n readonly instanceId: string;\n readonly viewId: string;\n readonly title: string;\n readonly device: string;\n /** Package-root relative `.html` entry the environment loaded. */\n readonly entry: string;\n readonly location: HtmlViewLocation;\n readonly state: HtmlViewState;\n readonly failure: IHtmlViewFailure | undefined;\n /** Owner of the iframe; it stays in the environment layer for the life of the environment. */\n readonly element: HTMLElement;\n /**\n * Positions the owner over `slot`; `null` keeps the page alive but hides it.\n *\n * The owner keeps the slot box and is clipped to the visible part of every scrolling ancestor,\n * the editor container and the viewport, so a partially scrolled sidebar never lets the frame\n * paint over the rest of the editor. A slot that scrolled out completely stops painting.\n */\n attach(slot: HTMLElement | null): void;\n /** Hides the page without unloading it; used when the container collapses. */\n setVisible(visible: boolean): void;\n setLocation(location: HtmlViewLocation): void;\n focus(): void;\n close(): void;\n}\n\nexport type HtmlViewChangeType = 'opened' | 'ready' | 'failed' | 'closed' | 'moved';\n\nexport interface IHtmlViewChange {\n readonly type: HtmlViewChangeType;\n readonly handle: IHtmlViewHandle;\n}\n\n/** Manager of every device HTML environment of one workbench. */\nexport interface IHtmlViewHost {\n readonly onDidChange: Event<IHtmlViewChange>;\n /** Announces every resolved theme the environments must mirror. */\n readonly onDidThemeChange: Event<IHtmlViewTheme>;\n /** Theme the environments mirror at this moment; dark unless the workbench sets one. */\n readonly theme: IHtmlViewTheme;\n /**\n * Sets the theme every environment mirrors, in place.\n *\n * The workbench forwards its *computed* colors, so a `var(...)` of the host page is already\n * resolved. An equal theme is ignored and a change never reloads a frame, so author input, model\n * session and document history survive it.\n */\n setTheme(theme: IHtmlViewTheme): void;\n readonly views: readonly IHtmlViewHandle[];\n get(instanceId: string, viewId: string): IHtmlViewHandle | undefined;\n /**\n * Opens or focuses the single environment of one view; it never creates a second one.\n *\n * Rejects with `view/unavailable-mode` when {@link close}, {@link closeAll} or\n * {@link dispose} release the view while its verified package read is still in flight, so a\n * cancelled open can never create a stale environment later.\n */\n open(request: IHtmlViewOpenRequest): Promise<IHtmlViewHandle>;\n /** Releases the environment or cancels its pending open; `true` when either existed. */\n close(instanceId: string, viewId: string): boolean;\n /**\n * Releases every environment and cancels every pending open, keeping the manager usable.\n *\n * The manager caches the model proxy of each environment for its lifetime, so a runtime reset\n * must call this before the replacement runtime is prepared and then reopen the views: they bind\n * the new model on their next {@link open}.\n */\n closeAll(): void;\n focus(instanceId: string, viewId: string): boolean;\n /** Re-measures every attached environment; call after a layout-only change. */\n refresh(): void;\n /** Releases every environment and cancels every pending open. */\n dispose(): Promise<void>;\n}\n\nexport interface IHtmlViewHostOptions {\n /** Absolute HTTP(S) deployment directory with one `${id}` hostname label (RFC 0023). */\n readonly viewBaseUrlTemplate: string;\n /**\n * Element the fixed environment layer is appended to.\n *\n * It is the editor host element, so its box also bounds every environment: an attached slot is\n * clipped to it as well as to its own scrolling ancestors and the viewport.\n */\n readonly container: HTMLElement;\n /** Resolves one live instance; `undefined` when it is not mounted (edit mode, no selection). */\n readonly describe: (instanceId: string) => IHtmlViewInstance | undefined;\n /** Registry that owns the locked packages every view resource is read from. */\n readonly registry: DeviceRegistry;\n /**\n * Proxy of the mounted model of one instance.\n *\n * Called only for instances whose declaration has a model; it must resolve one, and a throw (for\n * example `model/disconnected` outside a run session) fails the open with `view/unavailable-mode`\n * instead of handing the author an API without a model.\n */\n readonly model?: (instanceId: string) => IFusedModelClient | undefined;\n readonly onDiagnostic?: (failure: IHtmlViewFailure) => void;\n /** Theme the environments mirror before the workbench forwards its own; defaults to dark. */\n readonly theme?: IHtmlViewTheme;\n /** Budget of one bridge handshake; defaults to 15 s, `0` disables it. */\n readonly handshakeTimeoutMs?: number;\n /**\n * Origin of the editor page; a template resolving to it is rejected.\n *\n * Defaults to `globalThis.location.origin`; hosts without a browser location must pass it. The\n * environment refuses a non-HTTP(S) answer origin, so there is no wildcard fallback.\n */\n readonly origin?: string;\n /** DOM seams; default to the globals of the editor realm. */\n readonly document?: Document;\n readonly window?: Window;\n readonly createEnvironmentId?: () => string;\n}\n\nconst DEFAULT_HANDSHAKE_TIMEOUT_MS = 15_000;\nconst MAX_MESSAGE_LENGTH = 500;\n\n/** Failure codes an environment may report about itself. */\nconst REPORTABLE_CODES: ReadonlySet<string> = new Set<HtmlViewDiagnosticCode>([\n 'view/load-failed',\n 'view/bridge-failed',\n 'view/execution-failed',\n]);\n\n/** One `open` whose environment does not exist yet; it can be released before the record exists. */\ninterface IPendingOpen {\n readonly key: string;\n readonly instanceId: string;\n readonly viewId: string;\n /** The caller's promise; it rejects when the open is released before its record exists. */\n task: Promise<IHtmlViewHandle>;\n readonly cancelled: boolean;\n /** Set exactly when {@link task} was rejected by a release. */\n readonly rejection: HtmlViewError | undefined;\n /** Rejects {@link task} and marks the open stale; later creation is refused. */\n cancel(reason: HtmlViewError): void;\n}\n\ninterface IHtmlViewRecord {\n readonly key: string;\n readonly instanceId: string;\n readonly viewId: string;\n readonly title: string;\n readonly device: string;\n readonly entry: string;\n readonly lock: DeviceLock;\n readonly assetRoot: string;\n readonly environmentUrl: string;\n readonly props: FusedPresentationProps;\n readonly methods: ReadonlySet<string>;\n readonly events: ReadonlySet<string>;\n readonly hasModel: boolean;\n readonly model: IFusedModelClient | undefined;\n location: HtmlViewLocation;\n token: string;\n owner: HTMLElement;\n frame: HTMLIFrameElement;\n handle: IHtmlViewHandle | undefined;\n slot: HTMLElement | null;\n visible: boolean;\n state: HtmlViewState;\n failure: IHtmlViewFailure | undefined;\n loadSeen: boolean;\n endpoint: RpcEndpoint | undefined;\n /** Dedicated author lane of the inner frame; created at most once per view. */\n contentEndpoint: RpcEndpoint | undefined;\n subscriptions: Map<string, { dispose(): void }>;\n eventListeners: Set<(event: IFusedHtmlModelEventWire) => void>;\n closeListeners: Set<() => void>;\n timer: ReturnType<typeof setTimeout> | undefined;\n}\n\n/** Key of one view instance: the same device view in two places is still one environment. */\nexport function htmlViewKey(instanceId: string, viewId: string): string {\n return `${instanceId}\\u0000${viewId}`;\n}\n\n/** Creates the HTML view manager of one workbench. */\nexport function createHtmlViewHost(options: IHtmlViewHostOptions): IHtmlViewHost {\n const doc = options.document ?? globalThis.document;\n const win = options.window ?? globalThis.window;\n const origin = options.origin ?? globalThis.location?.origin;\n if (origin === undefined || origin === '' || origin === 'null') {\n throw new HtmlViewError(\n 'view/invalid-base-url-template',\n 'The HTML view host needs the editor origin to bind every handshake; pass `origin` outside a browser document.',\n );\n }\n const base: IHtmlViewBase = parseHtmlViewBase(options.viewBaseUrlTemplate, origin);\n const handshakeTimeoutMs = options.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS;\n const changes = new Emitter<IHtmlViewChange>();\n const themeChanges = new Emitter<IHtmlViewTheme>();\n let theme =\n options.theme === undefined ? DEFAULT_HTML_VIEW_THEME : normalizeHtmlViewTheme(options.theme);\n const records = new Map<string, IHtmlViewRecord>();\n const pendingOpens = new Map<string, IPendingOpen>();\n const packages = new Map<string, Promise<VerifiedPackage>>();\n const layerListeners = new DisposableStore();\n let layer: HTMLElement | undefined;\n let observer: ResizeObserver | undefined;\n let slotObserver: ResizeObserver | undefined;\n let pendingFrame: number | undefined;\n let disposed = false;\n\n return {\n onDidChange: changes.event,\n onDidThemeChange: themeChanges.event,\n get theme() {\n return theme;\n },\n setTheme,\n get views() {\n return [...records.values()].map((record) => handleOf(record));\n },\n get,\n open,\n close,\n closeAll,\n focus,\n refresh,\n dispose,\n };\n\n function assertOpen(): void {\n if (disposed)\n throw new HtmlViewError('view/unavailable-mode', 'The HTML view host is disposed.');\n }\n\n function setTheme(next: IHtmlViewTheme): void {\n const resolved = normalizeHtmlViewTheme(next);\n // A disposed host has no environment left to mirror; the workbench may still re-render once.\n if (disposed) return;\n if (htmlViewThemeEquals(theme, resolved)) return;\n theme = resolved;\n // The environment element follows a theme change before the environment answers the bridge; the\n // owner keeps painting the container surface while the view loads, so the loading status stays\n // readable, and it takes the theme only once the view is ready.\n for (const record of records.values()) {\n record.frame.style.background = htmlViewBackgroundColor(theme);\n if (record.state !== 'loading')\n record.owner.style.background = htmlViewBackgroundColor(theme);\n }\n themeChanges.fire(resolved);\n }\n\n function get(instanceId: string, viewId: string): IHtmlViewHandle | undefined {\n const record = records.get(htmlViewKey(instanceId, viewId));\n return record === undefined ? undefined : handleOf(record);\n }\n\n function open(request: IHtmlViewOpenRequest): Promise<IHtmlViewHandle> {\n // Deliberately not `async`: the returned promise is the pending task itself, so one release\n // rejects the exact promise the caller holds instead of an adopted copy of it.\n try {\n assertOpen();\n const key = htmlViewKey(request.instanceId, request.viewId);\n const existing = records.get(key);\n if (existing !== undefined) {\n // A failed environment is the one and only environment of this view until it is released.\n // Opening a fresh origin behind the failure would hide it behind a load loop, so the\n // retained handle is returned and only an explicit close starts a new environment.\n if (existing.state !== 'failed') {\n existing.location = request.location;\n focusRecord(existing);\n }\n return Promise.resolve(handleOf(existing));\n }\n const pending = pendingOpens.get(key);\n if (pending !== undefined) return pending.task;\n const entry = createPendingOpen(request);\n pendingOpens.set(key, entry);\n return entry.task;\n } catch (error) {\n return Promise.reject(error instanceof Error ? error : new Error(String(error)));\n }\n }\n\n /**\n * Starts one open and remembers how to release it before its record exists.\n *\n * The verified package read and the model resolution are asynchronous, so a selection change or an\n * end of the run session may land while the environment is still being prepared. Cancellation\n * rejects the caller's promise and makes the in-flight preparation refuse to create a record.\n */\n function createPendingOpen(request: IHtmlViewOpenRequest): IPendingOpen {\n const key = htmlViewKey(request.instanceId, request.viewId);\n let settle: ((error: Error) => void) | undefined;\n let rejection: HtmlViewError | undefined;\n const gate = new Promise<never>((_resolve, reject) => {\n settle = reject;\n });\n // The caller receives the rejection through the race below; this keeps a late `await` of a\n // released open from surfacing as an unhandled rejection of the gate itself.\n void gate.catch(() => undefined);\n const pending: IPendingOpen = {\n key,\n instanceId: request.instanceId,\n viewId: request.viewId,\n task: gate,\n get cancelled() {\n return rejection !== undefined;\n },\n get rejection() {\n return rejection;\n },\n cancel(reason) {\n if (rejection !== undefined) return;\n rejection = reason;\n pendingOpens.delete(key);\n settle?.(reason);\n },\n };\n const creation = createEnvironment(request, pending);\n // A preparation may fail on its own (missing package, released model, failing declaration);\n // forward that failure unless a release already settled the caller's promise.\n void creation.catch((error: unknown) => {\n if (rejection !== undefined) return;\n settle?.(error instanceof Error ? error : new Error(String(error)));\n });\n pending.task = Promise.race([creation, gate]).finally(() => {\n if (pendingOpens.get(key) === pending) pendingOpens.delete(key);\n });\n // A release rejects the caller's promise on purpose; this keeps a caller that dropped the\n // handle from producing an unhandled rejection while the failure is still observable.\n void pending.task.catch(() => undefined);\n return pending;\n }\n\n /** Stops one preparation whose release already happened, with an explicit failure. */\n function throwIfReleased(entry: IPendingOpen): void {\n if (entry.cancelled) {\n throw entry.rejection ?? releasedError(entry, 'The HTML view was released.');\n }\n assertOpen();\n }\n\n function releasedError(\n entry: { instanceId: string; viewId: string },\n reason: string,\n ): HtmlViewError {\n return new HtmlViewError(\n 'view/unavailable-mode',\n `${reason} No environment was created for ${entry.instanceId}/${entry.viewId}.`,\n { instanceId: entry.instanceId, viewId: entry.viewId },\n );\n }\n async function createEnvironment(\n request: IHtmlViewOpenRequest,\n entry: IPendingOpen,\n ): Promise<IHtmlViewHandle> {\n const { instanceId, viewId } = request;\n throwIfReleased(entry);\n const instance = describe(instanceId);\n if (instance === undefined) {\n throw new HtmlViewError(\n 'view/unavailable-mode',\n `Instance \"${instanceId}\" has no mounted device view environment.`,\n { instanceId, viewId },\n );\n }\n const view = instance.views[viewId];\n if (view === undefined) {\n throw new HtmlViewError(\n 'view/unknown-entry',\n `Device ${instance.device} declares no HTML view \"${viewId}\".`,\n { instanceId, viewId },\n );\n }\n if (!view.entry.toLowerCase().endsWith('.html')) {\n throw new HtmlViewError(\n 'view/load-failed',\n `View entry \"${view.entry}\" of ${instance.device} is not an HTML document.`,\n { instanceId, viewId },\n );\n }\n let files: VerifiedPackage;\n try {\n files = await packageOf(instance.lock);\n } catch (cause) {\n throw new HtmlViewError(\n 'view/load-failed',\n `Cannot verify ${instance.device}: ${messageOf(cause)}`,\n { instanceId, viewId },\n );\n }\n if (!Object.hasOwn(files.files, view.entry)) {\n throw new HtmlViewError(\n 'view/load-failed',\n `Package ${instance.device} does not declare the view entry \"${view.entry}\".`,\n { instanceId, viewId },\n );\n }\n // The package read is the long await: a selection change or an ended run session may have\n // released this view while it was pending, and no record may be created then.\n throwIfReleased(entry);\n const model = resolveModel(instanceId, instance);\n assertOpen();\n\n const environmentId = (options.createEnvironmentId ?? newHtmlEnvironmentId)();\n const environmentUrl = htmlEnvironmentUrl(base, environmentId);\n const assetRoot = assetRootUrl(environmentUrl).href;\n const documentUrl = new URL(ENVIRONMENT_DOCUMENT_FILE, environmentUrl);\n const record: IHtmlViewRecord = {\n key: htmlViewKey(instanceId, viewId),\n instanceId,\n viewId,\n title: view.title,\n device: instance.device,\n entry: view.entry,\n lock: instance.lock,\n assetRoot,\n environmentUrl: documentUrl.href,\n props: instance.props,\n methods: new Set(instance.methods),\n events: new Set(instance.events),\n hasModel: instance.hasModel,\n model,\n location: request.location,\n token: createToken(),\n owner: ownerElement(instanceId, viewId, view.title, instance.device),\n frame: frameElement(view.title, instance.device, theme),\n handle: undefined,\n slot: null,\n visible: true,\n state: 'loading',\n failure: undefined,\n loadSeen: false,\n endpoint: undefined,\n contentEndpoint: undefined,\n subscriptions: new Map(),\n eventListeners: new Set(),\n closeListeners: new Set(),\n timer: undefined,\n };\n record.owner.append(record.frame);\n layerElement().append(record.owner);\n records.set(record.key, record);\n record.frame.addEventListener('load', () => onFrameLoad(record));\n if (entry.cancelled) {\n // Defensive: a cancelled preparation must never leave a frame behind.\n record.owner.remove();\n throwIfReleased(entry);\n }\n record.frame.src = record.environmentUrl;\n if (handshakeTimeoutMs > 0) {\n record.timer = setTimeout(() => {\n record.timer = undefined;\n fault(\n record,\n 'view/bridge-failed',\n 'The HTML environment did not answer the bridge handshake.',\n );\n }, handshakeTimeoutMs);\n }\n emit('opened', record);\n return handleOf(record);\n }\n\n function connect(record: IHtmlViewRecord): void {\n const channel = new MessageChannel();\n const endpoint = createRpc(channel.port1);\n record.endpoint = endpoint;\n endpoint.register(fusedHtmlHostControlService, controlService(record), {\n transfer: (member, value) =>\n member === 'readAsset' ? transferBytes(value) : transferPort(value),\n });\n // The bridge closing is a teardown signal, never a way to drop a retained failure: the failed\n // record stays listed until the workbench releases it explicitly.\n endpoint.onDidClose(() => {\n if (record.state !== 'failed') release(record);\n });\n const frameWindow = record.frame.contentWindow;\n if (frameWindow === null) {\n fault(record, 'view/bridge-failed', 'The HTML environment frame is not available.');\n return;\n }\n // The target is structured-cloned, never transferred: the runtime keeps its own props.\n const message: IHtmlViewConnectMessage = {\n type: HTML_VIEW_CONNECT,\n token: record.token,\n parentOrigin: origin,\n target: viewTarget(record),\n };\n try {\n frameWindow.postMessage(message, new URL(record.environmentUrl).origin, [channel.port2]);\n } catch (cause) {\n fault(record, 'view/bridge-failed', `The bridge port was rejected: ${messageOf(cause)}`);\n }\n }\n\n function viewTarget(record: IHtmlViewRecord): IHtmlViewTarget {\n return {\n instanceId: record.instanceId,\n viewId: record.viewId,\n device: record.device,\n title: record.title,\n entry: record.entry,\n assetRoot: record.assetRoot,\n props: record.props,\n methods: [...record.methods],\n events: [...record.events],\n hasModel: record.hasModel,\n };\n }\n\n /** Lifecycle lane of the trusted environment page. */\n function controlService(record: IHtmlViewRecord): IFusedHtmlHostControlService {\n return {\n readAsset: (path) => readPackageFile(record, path),\n async getTheme() {\n return theme;\n },\n onDidThemeChange(listener) {\n const subscription = themeChanges.event((next) => listener(next));\n return () => subscription.dispose();\n },\n async ready() {\n markReady(record);\n },\n async reportFailure(code, message) {\n reportFailure(record, code, message);\n },\n closed() {\n release(record);\n },\n async contentPort() {\n try {\n return grantAuthorPort(record);\n } catch (cause) {\n throw toWireFailure(cause);\n }\n },\n };\n }\n\n /** Dedicated lane of the inner author frame. */\n function authorService(record: IHtmlViewRecord): IFusedHtmlHostService {\n return {\n readAsset: (path) => readPackageFile(record, path),\n async callModel(method, params: Value) {\n try {\n const client = record.model;\n if (client === undefined) {\n throw new HtmlViewError(\n 'view/unavailable-mode',\n `Device ${record.device} declares no model, so the view cannot call \"${method}\".`,\n { instanceId: record.instanceId, viewId: record.viewId },\n );\n }\n if (!record.methods.has(method)) {\n throw new HtmlViewError(\n 'view/execution-failed',\n `Method \"${method}\" is not declared by ${record.device}.`,\n { instanceId: record.instanceId, viewId: record.viewId },\n );\n }\n const invoke = client.methods[method];\n if (invoke === undefined) {\n throw new HtmlViewError(\n 'view/unavailable-mode',\n `Method \"${method}\" is not available on the live model.`,\n { instanceId: record.instanceId, viewId: record.viewId },\n );\n }\n return await invoke(params);\n } catch (cause) {\n throw toWireFailure(cause);\n }\n },\n async subscribe(event) {\n if (record.subscriptions.has(event)) return;\n if (!record.events.has(event)) {\n throw toWireFailure(\n new HtmlViewError(\n 'view/execution-failed',\n `Event \"${event}\" is not declared by ${record.device}.`,\n { instanceId: record.instanceId, viewId: record.viewId },\n ),\n );\n }\n const client = record.model;\n if (client === undefined) {\n throw toWireFailure(\n new HtmlViewError(\n 'view/unavailable-mode',\n `Device ${record.device} declares no model, so the view cannot observe \"${event}\".`,\n { instanceId: record.instanceId, viewId: record.viewId },\n ),\n );\n }\n const outlet = client.events[event];\n if (outlet === undefined) {\n throw toWireFailure(\n new HtmlViewError(\n 'view/execution-failed',\n `Event \"${event}\" is declared by ${record.device} but the live model exposes no outlet for it.`,\n { instanceId: record.instanceId, viewId: record.viewId },\n ),\n );\n }\n const subscription = outlet((payload) => {\n const push: IFusedHtmlModelEventWire = { name: event, payload };\n for (const listener of [...record.eventListeners]) {\n try {\n listener(push);\n } catch {\n // One broken environment listener must not stop the other views.\n }\n }\n });\n record.subscriptions.set(event, subscription);\n },\n async unsubscribe(event) {\n const subscription = record.subscriptions.get(event);\n if (subscription === undefined) return;\n record.subscriptions.delete(event);\n subscription.dispose();\n },\n onDidModelEvent(listener) {\n record.eventListeners.add(listener);\n return () => record.eventListeners.delete(listener);\n },\n onDidClose(listener) {\n record.closeListeners.add(listener);\n return () => record.closeListeners.delete(listener);\n },\n async reportFailure(code, message) {\n reportFailure(record, code, message);\n },\n };\n }\n\n function reportFailure(record: IHtmlViewRecord, code: string, message: string): void {\n fault(\n record,\n REPORTABLE_CODES.has(code) ? (code as HtmlViewDiagnosticCode) : 'view/execution-failed',\n typeof message === 'string' && message.length > 0\n ? message\n : 'The HTML view failed without a reason.',\n );\n }\n\n /**\n * Reads one declared package file of this view.\n *\n * Every lane that reaches package bytes goes through this one verified lookup of the locked\n * package, so neither the author frame nor the worker can read a file the view does not declare.\n */\n async function readPackageFile(record: IHtmlViewRecord, path: string): Promise<Uint8Array> {\n try {\n const problem = typeof path === 'string' ? packagePathProblem(path) : 'must be a string';\n if (problem !== undefined) {\n throw new HtmlViewError(\n 'view/load-failed',\n `Asset path ${JSON.stringify(path)} ${problem}.`,\n { instanceId: record.instanceId, viewId: record.viewId },\n );\n }\n const files = await packageOf(record.lock);\n if (!Object.hasOwn(files.files, path)) {\n throw new HtmlViewError(\n 'view/load-failed',\n `Package ${record.device} does not declare \"${path}\".`,\n { instanceId: record.instanceId, viewId: record.viewId },\n );\n }\n return await files.read(path);\n } catch (cause) {\n throw toWireFailure(cause);\n }\n }\n\n /** Grants the author's direct port once for the lifetime of the content document. */\n function grantAuthorPort(record: IHtmlViewRecord): MessagePort {\n if (record.state !== 'loading' && record.state !== 'ready') {\n throw new HtmlViewError(\n 'view/unavailable-mode',\n `The HTML view ${record.instanceId}/${record.viewId} is ${record.state} and grants no author port.`,\n { instanceId: record.instanceId, viewId: record.viewId },\n );\n }\n if (record.contentEndpoint !== undefined) {\n throw new HtmlViewError(\n 'view/bridge-failed',\n `The author port of ${record.instanceId}/${record.viewId} was already granted.`,\n { instanceId: record.instanceId, viewId: record.viewId },\n );\n }\n const channel = new MessageChannel();\n const endpoint = createRpc(channel.port1);\n record.contentEndpoint = endpoint;\n endpoint.register(fusedHtmlHostService, authorService(record), {\n transfer: (_member, value) => transferBytes(value),\n });\n endpoint.register(fusedHtmlContentViewService, {\n async view(): Promise<IHtmlViewContent> {\n return { token: record.token, target: viewTarget(record) };\n },\n });\n endpoint.onDidClose(() => {\n if (record.state !== 'loading' && record.state !== 'ready') return;\n fault(record, 'view/bridge-failed', 'The dedicated author port of the view closed.');\n });\n return channel.port2;\n }\n\n function describe(instanceId: string): IHtmlViewInstance | undefined {\n if (disposed) return undefined;\n // A failing declaration callback is a host wiring error; it must not look like \"not mounted\".\n return options.describe(instanceId);\n }\n\n /**\n * Resolves the model proxy of one instance from its declaration.\n *\n * A device without a model gets an undefined proxy by design; a device with a model must get one,\n * so a missing source, a missing proxy or a runtime failure is reported instead of hidden.\n */\n function resolveModel(\n instanceId: string,\n instance: IHtmlViewInstance,\n ): IFusedModelClient | undefined {\n if (!instance.hasModel) return undefined;\n const source = options.model;\n if (source === undefined) {\n throw new HtmlViewError(\n 'view/unavailable-mode',\n `Device ${instance.device} declares a model, but the HTML view host has no model source.`,\n { instanceId },\n );\n }\n let model: IFusedModelClient | undefined;\n try {\n model = source(instanceId);\n } catch (cause) {\n throw new HtmlViewError(\n 'view/unavailable-mode',\n `The model of ${instance.device} is not available (${failureCodeOf(cause)}): ${messageOf(cause)}`,\n { instanceId },\n );\n }\n if (model === undefined) {\n throw new HtmlViewError(\n 'view/unavailable-mode',\n `Device ${instance.device} declares a model, but the workbench provides no live proxy for it.`,\n { instanceId },\n );\n }\n return model;\n }\n\n function packageOf(lock: DeviceLock): Promise<VerifiedPackage> {\n const key = `${lock.id}@${lock.version}#${lock.integrity}`;\n let pending = packages.get(key);\n if (pending === undefined) {\n pending = openDevicePackage(options.registry, lock).catch((cause: unknown) => {\n packages.delete(key);\n throw cause;\n });\n packages.set(key, pending);\n }\n return pending;\n }\n\n function onFrameLoad(record: IHtmlViewRecord): void {\n if (record.state === 'closed' || record.state === 'failed') return;\n if (!record.loadSeen) {\n // The environment document is in place; only now can the bridge port be granted.\n record.loadSeen = true;\n connect(record);\n return;\n }\n // The environment left the document it was granted: the view is gone (RFC 0023). The author\n // document lives in the inner frame, so only a navigation of the trusted page reaches here.\n release(record);\n }\n\n function markReady(record: IHtmlViewRecord): void {\n if (record.state !== 'loading') return;\n clearTimer(record);\n record.state = 'ready';\n // Only now can the frame paint: the environment wrote the author document with its base, its\n // policy and the resolved theme, so the first visible frame is the themed document instead of\n // the white canvas of an unthemed one. The owner takes over the surface with the current theme\n // before the frame appears, so nothing of the container shows through the reveal.\n record.owner.style.background = htmlViewBackgroundColor(theme);\n record.frame.style.visibility = 'visible';\n emit('ready', record);\n sync(record);\n }\n\n function fault(record: IHtmlViewRecord, code: HtmlViewDiagnosticCode, message: string): void {\n if (record.state === 'failed' || record.state === 'closed') return;\n record.state = 'failed';\n record.failure = {\n code,\n message: bounded(message),\n instanceId: record.instanceId,\n viewId: record.viewId,\n title: record.title,\n device: record.device,\n };\n releaseResources(record);\n emit('failed', record);\n try {\n options.onDiagnostic?.(record.failure);\n } catch {\n // Diagnostics must not break the manager.\n }\n }\n\n /**\n * Retires the lease of one view, explicitly.\n *\n * A failed environment keeps its record and its failure until the workbench releases it, so one\n * failing view is never replaced by a fresh origin on its own.\n */\n function release(record: IHtmlViewRecord): void {\n if (record.state === 'closed') return;\n record.state = 'closed';\n records.delete(record.key);\n releaseResources(record);\n record.owner.remove();\n emit('closed', record);\n }\n\n function releaseResources(record: IHtmlViewRecord): void {\n clearTimer(record);\n if (record.slot !== null) {\n slotObserver?.unobserve(record.slot);\n record.slot = null;\n }\n for (const subscription of record.subscriptions.values()) {\n try {\n subscription.dispose();\n } catch {\n // A released model outlet may already be gone.\n }\n }\n record.subscriptions.clear();\n for (const listener of [...record.closeListeners]) {\n try {\n listener();\n } catch {\n // The environment may already be detached.\n }\n }\n record.closeListeners.clear();\n record.eventListeners.clear();\n const endpoints = [record.endpoint, record.contentEndpoint];\n record.endpoint = undefined;\n record.contentEndpoint = undefined;\n for (const endpoint of endpoints) {\n try {\n endpoint?.dispose();\n } catch {\n // The port may already be closed.\n }\n }\n record.owner.style.display = 'none';\n record.frame.remove();\n }\n\n function clearTimer(record: IHtmlViewRecord): void {\n if (record.timer === undefined) return;\n clearTimeout(record.timer);\n record.timer = undefined;\n }\n\n function close(instanceId: string, viewId: string): boolean {\n const key = htmlViewKey(instanceId, viewId);\n const pending = pendingOpens.get(key);\n // A release must also stop a preparation that has no record yet, e.g. the sidebar view of the\n // instance the user just deselected.\n pending?.cancel(\n releasedError(\n { instanceId, viewId },\n 'The HTML view was released while its environment was still being prepared.',\n ),\n );\n const record = records.get(key);\n if (record !== undefined) release(record);\n return pending !== undefined || record !== undefined;\n }\n\n function closeAll(): void {\n for (const entry of [...pendingOpens.values()]) {\n entry.cancel(\n releasedError(entry, 'Every HTML view was released while this environment was pending.'),\n );\n }\n pendingOpens.clear();\n for (const record of [...records.values()]) release(record);\n records.clear();\n }\n\n function attachSlot(record: IHtmlViewRecord, slot: HTMLElement | null): void {\n const previous = record.slot;\n if (previous === slot) {\n sync(record);\n return;\n }\n record.slot = slot;\n if (previous !== null) slotObserver?.unobserve(previous);\n // A resizing sidebar or floating panel changes the slot box without a window resize.\n if (slot !== null) slotObserver?.observe(slot);\n sync(record);\n }\n\n function focus(instanceId: string, viewId: string): boolean {\n const record = records.get(htmlViewKey(instanceId, viewId));\n if (record === undefined) return false;\n focusRecord(record);\n return true;\n }\n\n function focusRecord(record: IHtmlViewRecord): void {\n record.visible = true;\n sync(record);\n try {\n record.frame.focus({ preventScroll: true });\n } catch {\n // A cross-origin frame may refuse focus; the UI still marks the view active.\n }\n }\n\n function refresh(): void {\n for (const record of records.values()) sync(record);\n }\n\n /** Coalesces scroll and resize churn into one measurement per animation frame. */\n function scheduleRefresh(): void {\n if (pendingFrame !== undefined) return;\n const schedule = win.requestAnimationFrame?.bind(win);\n if (schedule === undefined) {\n refresh();\n return;\n }\n pendingFrame = schedule(() => {\n pendingFrame = undefined;\n if (!disposed) refresh();\n });\n }\n\n function sync(record: IHtmlViewRecord): void {\n const slot = record.slot;\n // A failed view paints no frame any more; the container shows the failure in the slot itself.\n if (\n slot === null ||\n !record.visible ||\n record.state === 'closed' ||\n record.state === 'failed'\n ) {\n record.owner.style.display = 'none';\n return;\n }\n const rect = slot.getBoundingClientRect();\n if (rect.width <= 0 || rect.height <= 0) {\n record.owner.style.display = 'none';\n return;\n }\n // The owner always covers the whole slot; only the parts outside a scrolling ancestor, the\n // editor container or the viewport are clipped, so scrolling never reflows the author page.\n const clip = clipInsets(boxOf(rect), clipBoundsOf(slot));\n record.owner.style.display = clip.visible ? 'block' : 'none';\n record.owner.style.left = `${rect.left}px`;\n record.owner.style.top = `${rect.top}px`;\n record.owner.style.width = `${rect.width}px`;\n record.owner.style.height = `${rect.height}px`;\n record.owner.style.clipPath = clipPathOf(clip);\n }\n\n /** Clip boxes of one slot: its scrolling ancestors, the editor container and the viewport. */\n function clipBoundsOf(slot: HTMLElement): readonly IClipRect[] {\n const bounds: IClipRect[] = [];\n const viewportWidth = win.innerWidth ?? 0;\n const viewportHeight = win.innerHeight ?? 0;\n if (viewportWidth > 0 && viewportHeight > 0) {\n bounds.push({ left: 0, top: 0, right: viewportWidth, bottom: viewportHeight });\n }\n const container = options.container.getBoundingClientRect();\n if (container.width > 0 && container.height > 0) bounds.push(boxOf(container));\n for (let node = slot.parentElement; node !== null; node = node.parentElement) {\n const style = win.getComputedStyle(node);\n if (!clipsOverflow(style.overflowX, style.overflowY)) continue;\n const rect = node.getBoundingClientRect();\n // The client box excludes borders and scrollbars: that is exactly the visible area.\n bounds.push({\n left: rect.left + node.clientLeft,\n top: rect.top + node.clientTop,\n right: rect.left + node.clientLeft + node.clientWidth,\n bottom: rect.top + node.clientTop + node.clientHeight,\n });\n }\n return bounds;\n }\n\n function layerElement(): HTMLElement {\n if (layer !== undefined) return layer;\n const element = doc.createElement('div');\n element.className = 'mica-html-view-layer';\n element.setAttribute('data-mica-html-views', '');\n element.style.cssText =\n 'position:fixed;inset:0;overflow:hidden;pointer-events:none;z-index:2147483000;';\n options.container.append(element);\n layer = element;\n layerListeners.add({\n dispose: () => {\n win.removeEventListener('resize', scheduleRefresh);\n win.removeEventListener('scroll', scheduleRefresh, true);\n win.removeEventListener('message', onWindowMessage);\n if (pendingFrame !== undefined) win.cancelAnimationFrame?.(pendingFrame);\n pendingFrame = undefined;\n observer?.disconnect();\n observer = undefined;\n slotObserver?.disconnect();\n slotObserver = undefined;\n },\n });\n win.addEventListener('resize', scheduleRefresh);\n win.addEventListener('scroll', scheduleRefresh, true);\n win.addEventListener('message', onWindowMessage);\n if (typeof ResizeObserver !== 'undefined') {\n observer = new ResizeObserver(() => scheduleRefresh());\n observer.observe(options.container);\n slotObserver = new ResizeObserver(() => scheduleRefresh());\n }\n return element;\n }\n\n function onWindowMessage(event: MessageEvent): void {\n const data = event.data as Partial<IHtmlViewAckMessage> | null;\n if (data === null || typeof data !== 'object' || data.type !== HTML_VIEW_ACK) return;\n if (typeof data.token !== 'string') return;\n const record = [...records.values()].find((entry) => entry.token === data.token);\n if (record === undefined || record.state !== 'loading') return;\n // A stale page keeps its old token and a foreign window keeps its own source: both are ignored.\n if (event.source !== record.frame.contentWindow) return;\n if (event.origin !== new URL(record.environmentUrl).origin) return;\n clearTimer(record);\n }\n\n function ownerElement(\n instanceId: string,\n viewId: string,\n title: string,\n device: string,\n ): HTMLElement {\n const element = doc.createElement('div');\n element.className = 'mica-html-view-owner';\n element.setAttribute('role', 'group');\n element.setAttribute('aria-label', `${device} ${title}`);\n element.dataset['instanceId'] = instanceId;\n element.dataset['viewId'] = viewId;\n element.style.position = 'absolute';\n element.style.display = 'none';\n element.style.overflow = 'hidden';\n element.style.pointerEvents = 'auto';\n // While the view loads, the container paints the surface and keeps its status text visible; the\n // owner stays transparent until `markReady` hands it the resolved theme.\n element.style.background = 'transparent';\n return element;\n }\n\n function frameElement(title: string, device: string, current: IHtmlViewTheme): HTMLIFrameElement {\n const frame = doc.createElement('iframe');\n frame.className = 'mica-html-view-frame';\n frame.title = `${title} — ${device}`;\n frame.setAttribute('sandbox', 'allow-scripts allow-same-origin');\n frame.setAttribute('referrerpolicy', 'no-referrer');\n frame.setAttribute('allow', '');\n frame.style.display = 'block';\n frame.style.width = '100%';\n frame.style.height = '100%';\n frame.style.border = '0';\n // The loading surface of this slot is the owner below, not the frame: a browser paints a white\n // canvas for a document that has not been themed yet, and that canvas would cover every\n // background of the element and of the embedding page. The frame therefore stays invisible but\n // fully alive (it loads, runs its bootstrap and keeps its driver identity) until the themed\n // author document is ready.\n frame.style.visibility = 'hidden';\n frame.style.background = htmlViewBackgroundColor(current);\n return frame;\n }\n\n function handleOf(record: IHtmlViewRecord): IHtmlViewHandle {\n const existing = record.handle;\n if (existing !== undefined) return existing;\n const handle: IHtmlViewHandle = {\n key: record.key,\n instanceId: record.instanceId,\n viewId: record.viewId,\n title: record.title,\n device: record.device,\n entry: record.entry,\n get location() {\n return record.location;\n },\n get state() {\n return record.state;\n },\n get failure() {\n return record.failure;\n },\n element: record.owner,\n attach(slot) {\n attachSlot(record, slot);\n },\n setVisible(visible) {\n record.visible = visible;\n sync(record);\n },\n setLocation(location) {\n if (record.location === location) return;\n record.location = location;\n emit('moved', record);\n },\n focus() {\n focusRecord(record);\n },\n close() {\n release(record);\n },\n };\n record.handle = handle;\n return handle;\n }\n\n function emit(type: HtmlViewChangeType, record: IHtmlViewRecord): void {\n if (disposed) return;\n changes.fire({ type, handle: handleOf(record) });\n }\n\n async function dispose(): Promise<void> {\n if (disposed) return;\n disposed = true;\n for (const entry of [...pendingOpens.values()]) {\n entry.cancel(\n releasedError(entry, 'The HTML view host was disposed while this environment was pending.'),\n );\n }\n pendingOpens.clear();\n for (const record of [...records.values()]) {\n record.state = 'closed';\n releaseResources(record);\n record.owner.remove();\n }\n records.clear();\n for (const pending of packages.values()) void pending.catch(() => undefined);\n packages.clear();\n layerListeners.dispose();\n observer?.disconnect();\n observer = undefined;\n slotObserver?.disconnect();\n slotObserver = undefined;\n layer?.remove();\n layer = undefined;\n changes.dispose();\n themeChanges.dispose();\n }\n}\n\nfunction boxOf(rect: {\n readonly left: number;\n readonly top: number;\n readonly width: number;\n readonly height: number;\n}): IClipRect {\n return {\n left: rect.left,\n top: rect.top,\n right: rect.left + rect.width,\n bottom: rect.top + rect.height,\n };\n}\n\nfunction clipsOverflow(x: string, y: string): boolean {\n const clips = (value: string): boolean =>\n value === 'auto' || value === 'scroll' || value === 'hidden' || value === 'clip';\n return clips(x) || clips(y);\n}\n\nfunction createToken(): string {\n const bytes = new Uint8Array(16);\n const webCrypto = globalThis.crypto;\n if (typeof webCrypto?.getRandomValues === 'function') webCrypto.getRandomValues(bytes);\n else for (let index = 0; index < bytes.length; index += 1) bytes[index] = Math.random() * 256;\n return [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\n/** Code of one failure, so a runtime `model/disconnected` stays visible to the workbench. */\nfunction failureCodeOf(cause: unknown): string {\n if (typeof cause !== 'object' || cause === null) return 'unknown';\n const code = (cause as { readonly code?: unknown }).code;\n if (typeof code === 'string' && code.length > 0) return code;\n const name = (cause as { readonly name?: unknown }).name;\n return typeof name === 'string' && name.length > 0 ? name : 'unknown';\n}\n\n/** Transfer list of one granted direct port. */\nfunction transferPort(value: unknown): readonly Transferable[] {\n return typeof MessagePort !== 'undefined' && value instanceof MessagePort ? [value] : [];\n}\n\nfunction bounded(message: string): string {\n const text = typeof message === 'string' ? message : String(message);\n return text.length > MAX_MESSAGE_LENGTH ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…` : text;\n}\n","/**\n * Adapter from the fused runtime to the HTML view manager inputs (RFC 0023 / 0025).\n *\n * Model presence is never inferred here: the declaration of the instance device says so. A device\n * whose manifest has no `model` entry has no model even when it exposes no methods or events, and a\n * device with a model keeps its proxy even when that model declares an empty public surface. Every\n * failure of the runtime is propagated, so the workbench sees \"not in a run session\" or \"model\n * faulted\" instead of a silent `api.model === undefined`.\n */\nimport type { HtmlViewDefinition, UnifiedDeviceManifest } from '@mica-js/document/fused';\nimport type { IFusedInstancePresentation, IFusedModelClient } from '../runtime/protocol';\nimport type { IFusedRuntime } from '../runtime/host/types';\nimport { HtmlViewError } from './protocol';\nimport type { IHtmlViewInstance } from './host';\n\n/** Declared HTML views and model presence of one device, normally read from its manifest. */\nexport interface IHtmlViewDeviceDeclaration {\n /** Declared HTML views of the device; `manifest.view ?? {}`. */\n readonly views: Readonly<Record<string, HtmlViewDefinition>>;\n /** Whether the device declares a model (`manifest.model !== undefined`; RFC 0021). */\n readonly hasModel: boolean;\n}\n\nexport interface IHtmlViewSourceOptions {\n readonly runtime: IFusedRuntime;\n /**\n * Declaration of one device id.\n *\n * Return `undefined` only when the workbench does not know the device at all; an instance whose\n * declaration is missing is reported as `view/unavailable-mode` instead of a view without views.\n */\n readonly device: (deviceId: string) => IHtmlViewDeviceDeclaration | undefined;\n}\n\n/** Inputs of {@link createHtmlViewHost} backed by one runtime. */\nexport interface IHtmlViewRuntimeSource {\n /** Describes one prepared instance; `undefined` when it is not mounted. */\n describe(instanceId: string): IHtmlViewInstance | undefined;\n /** Proxy of the mounted model; runtime failures propagate. */\n model(instanceId: string): IFusedModelClient;\n}\n\n/** Reads the declaration of one device manifest. */\nexport function htmlViewDeviceDeclaration(\n manifest: Pick<UnifiedDeviceManifest, 'view' | 'model'>,\n): IHtmlViewDeviceDeclaration {\n return { views: manifest.view ?? {}, hasModel: manifest.model !== undefined };\n}\n\n/** Builds the manager callbacks of one runtime. */\nexport function createHtmlViewRuntimeSource(\n options: IHtmlViewSourceOptions,\n): IHtmlViewRuntimeSource {\n return {\n describe(instanceId) {\n const instance = presentationOf(options.runtime, instanceId);\n // No prepared presentation means the run session does not hold this instance: edit mode,\n // a cleared selection or a released session. That is a deliberate \"not mounted\" answer.\n if (instance === undefined) return undefined;\n const declaration = options.device(instance.device);\n if (declaration === undefined) {\n throw new HtmlViewError(\n 'view/unavailable-mode',\n `The workbench has no declaration for device ${instance.device}; pass its manifest view and model through the source options.`,\n { instanceId },\n );\n }\n return {\n device: instance.device,\n lock: instance.lock,\n props: instance.props,\n methods: instance.methods,\n events: instance.events,\n hasModel: declaration.hasModel,\n views: declaration.views,\n };\n },\n model(instanceId) {\n // `model/disconnected`, `model/unknown-instance` and model faults propagate to the caller.\n return options.runtime.getModel(instanceId);\n },\n };\n}\n\nfunction presentationOf(\n runtime: IFusedRuntime,\n instanceId: string,\n): IFusedInstancePresentation | undefined {\n return runtime.display.instances.find((entry) => entry.instanceId === instanceId);\n}\n","/**\n * Author bridge of one device HTML environment (RFC 0023 `DeviceViewApi`).\n *\n * This code runs inside the inner sandbox frame of one environment. It owns the author `Event`\n * outlets, turns package reads into verified lookups through the host bridge and never touches the\n * editor DOM, the model implementation or the host file system. It is DOM-free on purpose:\n * `environment/content.ts` supplies the page around it, and the same bridge runs unchanged in tests.\n */\nimport { Emitter, toDisposable } from '@mica-js/core/lifecycle';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type { RpcProxy } from '@mica-js/core/rpc';\nimport { packagePathProblem } from '@mica-js/document/fused';\nimport type { Value } from '@mica-js/document/fused';\nimport type { ModelEvent } from '@mica-js/sdk/fused';\nimport type { FusedPresentationProps } from '../runtime/protocol';\nimport { mapWireFailure, messageOf } from '../runtime/wire';\nimport { imageBuffer, mimeTypeOf } from './paths';\nimport { HtmlViewError } from './protocol';\nimport type { IFusedHtmlHostService, IFusedHtmlModelEventWire, IHtmlViewTarget } from './protocol';\n\n/** RFC 0023 `HtmlAssets`: verified package reads and view-scoped resource URLs. */\nexport interface IHtmlAssets {\n /** Reads one declared package file; `path` is package-root relative. */\n read(path: string): Promise<Uint8Array>;\n /** Resolves one package file to an opaque URL that dies with this view. */\n getUrl(path: string): Promise<string>;\n}\n\n/** RFC 0023 `DeviceViewApi.model`: the declared surface of the owning model. */\nexport interface IDeviceViewModel {\n /** Declared methods; only declared names resolve. */\n readonly methods: Readonly<Record<string, (params: Value) => Promise<Value>>>;\n /** Declared event outlets; a subscription is created on the wire when it is first observed. */\n readonly events: Readonly<Record<string, Event<ModelEvent<Value>>>>;\n}\n\n/** RFC 0023 `DeviceViewApi`. */\nexport interface IDeviceViewApi {\n readonly props: FusedPresentationProps;\n readonly model: IDeviceViewModel | undefined;\n readonly assets: IHtmlAssets;\n readonly onDidClose: Event<void>;\n}\n\n/** Live bridge of one environment. */\nexport interface IDeviceViewSession {\n readonly api: IDeviceViewApi;\n readonly closed: boolean;\n /** Delivers one model event the host pushed into this environment. */\n deliver(event: IFusedHtmlModelEventWire): void;\n /** Announces the host released this view; fires `onDidClose` once. */\n close(): void;\n dispose(): void;\n}\n\nexport interface IDeviceViewSessionOptions {\n readonly host: RpcProxy<IFusedHtmlHostService>;\n readonly target: IHtmlViewTarget;\n /** Reports an author failure once; the editor faults the view afterwards (RFC 0023). */\n readonly reportFailure: (code: string, message: string) => void;\n /** Object URL seam; defaults to the environment realm `URL`. */\n readonly createObjectUrl?: (blob: Blob) => string;\n readonly revokeObjectUrl?: (url: string) => void;\n}\n\ninterface IEventChannel {\n readonly emitter: Emitter<ModelEvent<Value>>;\n listeners: number;\n}\n\n/** Builds the author-facing bridge over an established host channel. */\nexport function createDeviceViewSession(options: IDeviceViewSessionOptions): IDeviceViewSession {\n const { host, target } = options;\n const createObjectUrl = options.createObjectUrl ?? ((blob: Blob) => URL.createObjectURL(blob));\n const revokeObjectUrl = options.revokeObjectUrl ?? ((url: string) => URL.revokeObjectURL(url));\n const declared = new Set(target.methods);\n const channels = new Map<string, IEventChannel>();\n const urls = new Set<string>();\n const closeEmitter = new Emitter<void>();\n let closed = false;\n let failureReported = false;\n\n const fail = (code: string, message: string): void => {\n if (failureReported || closed) return;\n failureReported = true;\n options.reportFailure(code, message);\n };\n\n const channel = (name: string): Event<ModelEvent<Value>> => {\n return (listener) => {\n if (closed) return toDisposable(() => undefined);\n let entry = channels.get(name);\n if (entry === undefined) {\n entry = { emitter: new Emitter<ModelEvent<Value>>(), listeners: 0 };\n channels.set(name, entry);\n }\n const current = entry;\n current.listeners += 1;\n if (current.listeners === 1) void subscribe(name);\n const subscription = current.emitter.event(listener);\n return toDisposable(() => {\n subscription.dispose();\n current.listeners -= 1;\n if (current.listeners > 0) return;\n channels.delete(name);\n current.emitter.dispose();\n void host.unsubscribe(name).catch(() => undefined);\n });\n };\n };\n\n async function subscribe(name: string): Promise<void> {\n try {\n await host.subscribe(name);\n } catch (cause) {\n fail('view/bridge-failed', `Subscribing to \"${name}\" failed: ${messageOf(cause)}`);\n }\n }\n\n const methods = new Proxy(Object.create(null) as Record<string, unknown>, {\n get(_target, name) {\n if (typeof name !== 'string' || !declared.has(name)) return undefined;\n return async (params: Value) => {\n if (closed) throw new HtmlViewError('view/bridge-failed', 'The device view is closed.');\n return mapWireFailure(() => host.callModel(name, params));\n };\n },\n has(_target, name) {\n return typeof name === 'string' && declared.has(name);\n },\n }) as IDeviceViewModel['methods'];\n\n const events: Record<string, Event<ModelEvent<Value>>> = {};\n for (const name of target.events) events[name] = channel(name);\n\n const assets: IHtmlAssets = {\n async read(path) {\n assertAssetPath(path);\n if (closed) throw new HtmlViewError('view/bridge-failed', 'The device view is closed.');\n const bytes = await mapWireFailure(() => host.readAsset(path));\n if (!(bytes instanceof Uint8Array)) {\n throw new HtmlViewError('view/load-failed', `The host returned no bytes for ${path}.`);\n }\n return bytes;\n },\n async getUrl(path) {\n const bytes = await assets.read(path);\n const url = createObjectUrl(new Blob([imageBuffer(bytes)], { type: mimeTypeOf(path) }));\n if (closed) {\n revokeObjectUrl(url);\n throw new HtmlViewError('view/bridge-failed', 'The device view is closed.');\n }\n urls.add(url);\n return url;\n },\n };\n\n const api: IDeviceViewApi = Object.freeze({\n props: Object.freeze({ ...target.props }),\n model: target.hasModel ? Object.freeze({ methods, events: Object.freeze(events) }) : undefined,\n assets,\n onDidClose: (listener: () => unknown) => {\n if (closed) {\n listener();\n return toDisposable(() => undefined);\n }\n return closeEmitter.event(listener);\n },\n });\n\n const release = (): void => {\n if (closed) return;\n closed = true;\n for (const entry of channels.values()) entry.emitter.dispose();\n channels.clear();\n for (const url of urls) {\n try {\n revokeObjectUrl(url);\n } catch {\n // The environment may already be gone.\n }\n }\n urls.clear();\n };\n\n return {\n api,\n get closed() {\n return closed;\n },\n deliver(event) {\n if (closed) return;\n const entry = channels.get(event.name);\n if (entry === undefined) return;\n try {\n entry.emitter.fire(event.payload);\n } catch (cause) {\n fail('view/execution-failed', `Listener of \"${event.name}\" failed: ${messageOf(cause)}`);\n }\n },\n close() {\n if (closed) return;\n try {\n closeEmitter.fire(undefined);\n } finally {\n closeEmitter.dispose();\n release();\n }\n },\n dispose() {\n closeEmitter.dispose();\n release();\n },\n };\n}\n\n/** Rejects a path that is not a normalized package-root relative file path. */\nexport function assertAssetPath(path: string): void {\n const problem = typeof path === 'string' ? packagePathProblem(path) : 'must be a string';\n if (problem !== undefined) {\n throw new HtmlViewError('view/load-failed', `Asset path ${JSON.stringify(path)} ${problem}.`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqCA,IAAa,gB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