@mica-js/editor 0.3.3 → 0.4.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.
@@ -0,0 +1,1618 @@
1
+ import { c as toWireFailure, l as transferBytes, o as mapWireFailure, s as messageOf } from "./wire-BDHL5Aj9.js";
2
+ import { DisposableStore, Emitter, toDisposable } from "@mica-js/core/lifecycle";
3
+ import { packagePathProblem } from "@mica-js/document/fused";
4
+ import { openDevicePackage } from "@mica-js/sdk/fused";
5
+ import { createRpc, defineRpcService } from "@mica-js/core/rpc";
6
+ //#region src/fused/html/protocol.ts
7
+ /**
8
+ * Wire contracts of the device HTML view bridge (RFC 0023).
9
+ *
10
+ * One environment per `(instanceId, viewId)`: a trusted OUTER frame on a deployment directory of its
11
+ * own origin and one INNER sandboxed frame inside it. Both are real documents of that origin
12
+ * (`index.html` and `content.html`), so every origin of both frames is concrete and comparable.
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.
26
+ */
27
+ /** Local contract failure of the HTML view host or of one environment. */
28
+ var HtmlViewError = class extends Error {
29
+ code;
30
+ instanceId;
31
+ viewId;
32
+ constructor(code, message, options = {}) {
33
+ super(message);
34
+ this.name = "HtmlViewError";
35
+ this.code = code;
36
+ this.instanceId = options.instanceId;
37
+ this.viewId = options.viewId;
38
+ }
39
+ };
40
+ function isHtmlViewError(value) {
41
+ return value instanceof HtmlViewError;
42
+ }
43
+ /** Control message the editor posts into a freshly loaded environment. */
44
+ var HTML_VIEW_CONNECT = "mica:view:connect";
45
+ /** Acknowledgement the environment posts back once it owns the transferred port. */
46
+ 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. */
52
+ var HTML_VIEW_ATTACH = "mica:view:attach";
53
+ /** Acknowledgement of {@link HTML_VIEW_ATTACH}; only then may the author document load. */
54
+ var HTML_VIEW_ATTACH_ACK = "mica:view:attach-ack";
55
+ /** Control message the inner frame posts to the environment once its bootstrap runs. */
56
+ var HTML_VIEW_CHILD_HELLO = "mica:view:child-hello";
57
+ /** Control message the environment answers with the bridge port of the inner frame. */
58
+ var HTML_VIEW_CHILD_CONNECT = "mica:view:child-connect";
59
+ /** Control message the inner frame posts once its API and its package grant are in place. */
60
+ var HTML_VIEW_CHILD_PREPARED = "mica:view:child-prepared";
61
+ /**
62
+ * Query parameter that carries the one-time token of one inner frame.
63
+ *
64
+ * The inner document is a real same-origin URL, so both frames derive the environment origin from
65
+ * their own location; only the frame token travels in the URL, and it never grants host access.
66
+ */
67
+ var HTML_VIEW_FRAME_PARAM = "view";
68
+ /** Typed author lane between the editor and one inner frame. */
69
+ var fusedHtmlHostService = defineRpcService("fused-html-host");
70
+ /** Typed control lane between the editor and one trusted environment page. */
71
+ var fusedHtmlHostControlService = defineRpcService("fused-html-host-control");
72
+ /** Typed package lane between the editor and one environment's asset worker. */
73
+ var fusedHtmlAssetService = defineRpcService("fused-html-asset");
74
+ /** Typed view identity lane of one inner frame; it shares the author lane port. */
75
+ var fusedHtmlContentViewService = defineRpcService("fused-html-content-view");
76
+ //#endregion
77
+ //#region src/fused/html/base-url.ts
78
+ /**
79
+ * Validated `viewBaseUrlTemplate` of the HTML view environments (RFC 0023).
80
+ *
81
+ * The template names the deployment directory of the environment resources and carries exactly one
82
+ * `${id}` hostname label. Every environment substitutes a fresh DNS label, so two environments never
83
+ * share an origin and one environment can never read the storage or workers of another.
84
+ */
85
+ /** Placeholder of the environment id inside the template's hostname. */
86
+ var VIEW_ENV_LABEL = "${id}";
87
+ /** Label used to validate the template around the environment id. */
88
+ var PLACEHOLDER_LABEL = "mica-environment";
89
+ var DNS_LABEL = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
90
+ /**
91
+ * Validates one `viewBaseUrlTemplate`.
92
+ *
93
+ * @throws {HtmlViewError} `view/invalid-base-url-template` when the template is not an absolute
94
+ * HTTP(S) directory URL with one standalone `${id}` hostname label on an independent origin.
95
+ */
96
+ function parseHtmlViewBase(template, hostOrigin) {
97
+ function fail(reason) {
98
+ throw new HtmlViewError("view/invalid-base-url-template", `viewBaseUrlTemplate ${reason}: ${JSON.stringify(template)}`);
99
+ }
100
+ if (typeof template !== "string" || template.length === 0) fail("must be a non-empty string");
101
+ if (!template.endsWith("/")) fail("must end with '/'");
102
+ if (template.split("${id}").length !== 2) fail("must contain exactly one ${id} label");
103
+ const parsed = parseUrl(template.replace(VIEW_ENV_LABEL, PLACEHOLDER_LABEL));
104
+ if (parsed === void 0) fail("must be an absolute URL");
105
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") fail("must use HTTP or HTTPS");
106
+ if (parsed.search !== "" || parsed.hash !== "") fail("must not carry a query or a fragment");
107
+ if (parsed.username !== "" || parsed.password !== "") fail("must not carry credentials");
108
+ if (!parsed.hostname.split(".").includes(PLACEHOLDER_LABEL)) fail("must place ${id} as a complete hostname label");
109
+ if (hostOrigin !== void 0) {
110
+ const environment = parseUrl(template.replace(VIEW_ENV_LABEL, PLACEHOLDER_LABEL));
111
+ if (environment !== void 0 && environment.origin === hostOrigin) fail("must use an origin independent of the editor");
112
+ }
113
+ return Object.freeze({
114
+ template,
115
+ deployment: parsed.origin
116
+ });
117
+ }
118
+ /**
119
+ * Environment URL of one validated base and environment id.
120
+ *
121
+ * @throws {TypeError} when `id` is not a DNS label; ids come from {@link newHtmlEnvironmentId}.
122
+ */
123
+ function htmlEnvironmentUrl(base, id) {
124
+ if (!DNS_LABEL.test(id) || id.length > 63) throw new TypeError(`HTML view environment id must be a DNS label, received "${id}"`);
125
+ return new URL(base.template.replace(VIEW_ENV_LABEL, id));
126
+ }
127
+ /** Fresh environment id; distinct ids give every environment its own origin. */
128
+ function newHtmlEnvironmentId() {
129
+ const bytes = /* @__PURE__ */ new Uint8Array(8);
130
+ const webCrypto = globalThis.crypto;
131
+ if (typeof webCrypto?.getRandomValues === "function") webCrypto.getRandomValues(bytes);
132
+ else for (let index = 0; index < bytes.length; index += 1) bytes[index] = Math.random() * 256;
133
+ return `mica-${[...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
134
+ }
135
+ function parseUrl(value) {
136
+ try {
137
+ return new URL(value);
138
+ } catch {
139
+ return;
140
+ }
141
+ }
142
+ //#endregion
143
+ //#region src/fused/html/layout.ts
144
+ /**
145
+ * Insets that clip one slot to the intersection of `bounds`.
146
+ *
147
+ * Every value is expressed against the slot box, so `clip-path: inset(...)` keeps the owner exactly
148
+ * over the slot and only hides the parts outside the scrolling ancestors or the viewport.
149
+ */
150
+ function clipInsets(slot, bounds) {
151
+ if (!hasArea(slot)) return {
152
+ left: 0,
153
+ top: 0,
154
+ right: 0,
155
+ bottom: 0,
156
+ visible: false
157
+ };
158
+ let left = slot.left;
159
+ let top = slot.top;
160
+ let right = slot.right;
161
+ let bottom = slot.bottom;
162
+ for (const bound of bounds) {
163
+ left = Math.max(left, bound.left);
164
+ top = Math.max(top, bound.top);
165
+ right = Math.min(right, bound.right);
166
+ bottom = Math.min(bottom, bound.bottom);
167
+ }
168
+ if (right <= left || bottom <= top) return {
169
+ left: 0,
170
+ top: 0,
171
+ right: 0,
172
+ bottom: 0,
173
+ visible: false
174
+ };
175
+ return {
176
+ left: left - slot.left,
177
+ top: top - slot.top,
178
+ right: slot.right - right,
179
+ bottom: slot.bottom - bottom,
180
+ visible: true
181
+ };
182
+ }
183
+ /** Whether one box has a positive extent. */
184
+ function hasArea(rect) {
185
+ return rect.right > rect.left && rect.bottom > rect.top;
186
+ }
187
+ /** CSS `clip-path` value of one slot clip; `none` when nothing is cut. */
188
+ function clipPathOf(clip) {
189
+ if (!clip.visible) return "inset(100%)";
190
+ if (clip.left === 0 && clip.top === 0 && clip.right === 0 && clip.bottom === 0) return "none";
191
+ return `inset(${clip.top}px ${clip.right}px ${clip.bottom}px ${clip.left}px)`;
192
+ }
193
+ //#endregion
194
+ //#region src/fused/html/paths.ts
195
+ /**
196
+ * Resource mapping of one device HTML environment (RFC 0023).
197
+ *
198
+ * The environment is served from a deployment directory of its own origin, so relative HTML, CSS
199
+ * and ES module references must resolve *inside the package*. Every package file therefore lives
200
+ * under one asset root whose path mirrors the package root; the author document gets a `<base>`
201
+ * pointing at its own package directory. The environment's service worker turns those requests into
202
+ * verified package reads and refuses everything else, including page navigations.
203
+ *
204
+ * The trusted environment document creates one inner sandboxed frame from
205
+ * {@link ENVIRONMENT_CONTENT_DOCUMENT_FILE}; both are real documents of the same per-view origin,
206
+ * which no editor page shares, and the environment writes the author document into the inner
207
+ * document itself.
208
+ */
209
+ /** Directory under the environment base URL that serves the package files. */
210
+ var ASSET_ROOT_DIRECTORY = "__mica_package__/";
211
+ /** Bootstrap document the editor loads in the environment iframe. */
212
+ var ENVIRONMENT_DOCUMENT_FILE = "index.html";
213
+ /** Bundled bootstrap module loaded by {@link ENVIRONMENT_DOCUMENT_FILE}. */
214
+ var ENVIRONMENT_BOOTSTRAP_FILE = "environment.js";
215
+ /** Document the environment loads in the inner sandbox frame; a real same-origin URL. */
216
+ var ENVIRONMENT_CONTENT_DOCUMENT_FILE = "content.html";
217
+ /** Bundled bootstrap module {@link ENVIRONMENT_CONTENT_DOCUMENT_FILE} loads. */
218
+ var ENVIRONMENT_CONTENT_FILE = "content.js";
219
+ /** Bundled service worker that serves the package files of one environment. */
220
+ var ENVIRONMENT_WORKER_FILE = "environment-sw.js";
221
+ /**
222
+ * Content security policy of the author document and of the inner content document.
223
+ *
224
+ * Package scripts, styles, fonts and images are same-origin because the asset worker serves them;
225
+ * opaque `blob:` URLs are the `assets.getUrl` results of the view itself. Nothing else is reachable:
226
+ * the author page has no network, no frames and no form targets. The inner document is served with
227
+ * this policy so an author document can never nest another frame, whatever the trusted environment
228
+ * allows itself.
229
+ */
230
+ var HTML_VIEW_CONTENT_POLICY = [
231
+ "default-src 'none'",
232
+ "script-src 'self' 'unsafe-inline'",
233
+ "style-src 'self' 'unsafe-inline'",
234
+ "img-src 'self' data: blob:",
235
+ "font-src 'self' data: blob:",
236
+ "media-src 'self' data: blob:",
237
+ "connect-src 'self' blob:",
238
+ "frame-src 'none'",
239
+ "object-src 'none'",
240
+ "form-action 'none'",
241
+ "base-uri 'self'"
242
+ ].join("; ");
243
+ /**
244
+ * Policy of the trusted environment document.
245
+ *
246
+ * It only differs from the author policy where the environment itself needs more: exactly one inner
247
+ * frame of its own deployment directory, and the asset worker registration. The inner document is
248
+ * served with {@link HTML_VIEW_CONTENT_POLICY}, so the author document still cannot nest frames,
249
+ * reach another origin or post a form.
250
+ */
251
+ var HTML_VIEW_ENVIRONMENT_POLICY = [
252
+ "default-src 'none'",
253
+ "script-src 'self' 'unsafe-inline'",
254
+ "style-src 'self' 'unsafe-inline'",
255
+ "img-src 'self' data: blob:",
256
+ "font-src 'self' data: blob:",
257
+ "media-src 'self' data: blob:",
258
+ "connect-src 'self' blob:",
259
+ "worker-src 'self'",
260
+ "frame-src 'self'",
261
+ "object-src 'none'",
262
+ "form-action 'none'",
263
+ "base-uri 'self'"
264
+ ].join("; ");
265
+ /** Absolute URL prefix that serves the verified package files of one environment. */
266
+ function assetRootUrl(baseUrl) {
267
+ return new URL(ASSET_ROOT_DIRECTORY, baseUrl);
268
+ }
269
+ /**
270
+ * Base URL the author document resolves relative references against.
271
+ *
272
+ * The asset root mirrors the package root, so the document base is the directory of the view entry
273
+ * and `./main.js` of `views/serial/index.html` resolves to the package file `views/serial/main.js`.
274
+ */
275
+ function authorBaseUrl(assetRoot, entry) {
276
+ const root = assetRoot.href.endsWith("/") ? assetRoot.href : `${assetRoot.href}/`;
277
+ const separator = entry.lastIndexOf("/");
278
+ return separator <= 0 ? root : `${root}${entry.slice(0, separator + 1)}`;
279
+ }
280
+ /**
281
+ * Package path of one asset request, or `undefined` when the request leaves the package.
282
+ *
283
+ * `root` is the pathname of {@link assetRootUrl}; requests outside it, encoded separators and empty
284
+ * segments are rejected, so a view cannot read the environment bootstrap or another package.
285
+ */
286
+ function resolveAssetRequest(pathname, root) {
287
+ const prefix = root.endsWith("/") ? root : `${root}/`;
288
+ if (!pathname.startsWith(prefix)) return void 0;
289
+ const rest = pathname.slice(prefix.length);
290
+ if (rest.length === 0) return void 0;
291
+ const segments = [];
292
+ for (const segment of rest.split("/")) {
293
+ let decoded;
294
+ try {
295
+ decoded = decodeURIComponent(segment);
296
+ } catch {
297
+ return;
298
+ }
299
+ if (decoded.length === 0 || decoded === "." || decoded === "..") return void 0;
300
+ if (decoded.includes("/") || decoded.includes("\\")) return void 0;
301
+ segments.push(decoded);
302
+ }
303
+ const path = segments.join("/");
304
+ return packagePathProblem(path) === void 0 ? path : void 0;
305
+ }
306
+ var MIME_TYPES = Object.freeze({
307
+ html: "text/html; charset=utf-8",
308
+ htm: "text/html; charset=utf-8",
309
+ js: "text/javascript; charset=utf-8",
310
+ mjs: "text/javascript; charset=utf-8",
311
+ css: "text/css; charset=utf-8",
312
+ json: "application/json; charset=utf-8",
313
+ map: "application/json; charset=utf-8",
314
+ svg: "image/svg+xml",
315
+ png: "image/png",
316
+ jpg: "image/jpeg",
317
+ jpeg: "image/jpeg",
318
+ gif: "image/gif",
319
+ webp: "image/webp",
320
+ avif: "image/avif",
321
+ ico: "image/x-icon",
322
+ woff: "font/woff",
323
+ woff2: "font/woff2",
324
+ ttf: "font/ttf",
325
+ otf: "font/otf",
326
+ wasm: "application/wasm",
327
+ txt: "text/plain; charset=utf-8",
328
+ bin: "application/octet-stream"
329
+ });
330
+ /** Response content type of one package file. */
331
+ function mimeTypeOf(path) {
332
+ const separator = path.lastIndexOf(".");
333
+ if (separator <= 0) return "application/octet-stream";
334
+ return MIME_TYPES[path.slice(separator + 1).toLowerCase()] ?? "application/octet-stream";
335
+ }
336
+ /**
337
+ * Injects the document preamble of one view.
338
+ *
339
+ * The `<base>` must be the first base element, the policy travels with the document because it is
340
+ * written into a document of its own, and the theme declarations come before every author script so
341
+ * the author never paints a frame with missing tokens.
342
+ */
343
+ function withHtmlDocumentPreamble(html, preamble) {
344
+ const markup = [
345
+ "<meta charset=\"utf-8\">",
346
+ `<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(preamble.policy)}">`,
347
+ `<base href="${escapeAttribute(preamble.base)}">`,
348
+ `<style>${preamble.style.replace(/<\/style/gi, "<\\/style")}</style>`
349
+ ].join("");
350
+ const head = /<head\b[^>]*>/i.exec(html);
351
+ if (head !== null) {
352
+ const at = head.index + head[0].length;
353
+ return `${html.slice(0, at)}${markup}${html.slice(at)}`;
354
+ }
355
+ const open = /<html\b[^>]*>/i.exec(html);
356
+ if (open !== null) {
357
+ const at = open.index + open[0].length;
358
+ return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
359
+ }
360
+ const doctype = /<!doctype[^>]*>/i.exec(html);
361
+ if (doctype !== null) {
362
+ const at = doctype.index + doctype[0].length;
363
+ return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
364
+ }
365
+ return `<head>${markup}</head>${html}`;
366
+ }
367
+ /**
368
+ * Owns a plain `ArrayBuffer` copy of one byte snapshot.
369
+ *
370
+ * `Blob`, `Response` and the transfer list reject a `SharedArrayBuffer`-backed view, so every byte
371
+ * snapshot that leaves this module is copied first.
372
+ */
373
+ function imageBuffer(bytes) {
374
+ const copy = new Uint8Array(bytes.byteLength);
375
+ copy.set(bytes);
376
+ return copy.buffer;
377
+ }
378
+ /** Decodes package bytes as UTF-8 text, tolerating a byte order mark. */
379
+ function decodeDocument(bytes) {
380
+ return new TextDecoder().decode(bytes).replace(/^\uFEFF/, "");
381
+ }
382
+ /** Escapes one attribute value; policy, base and token never reach the document unescaped. */
383
+ function escapeAttribute(value) {
384
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
385
+ }
386
+ //#endregion
387
+ //#region src/fused/theme.ts
388
+ var WORKBENCH_THEME_CSS_VARIABLES = Object.freeze({
389
+ "workbench.background": "--mica-bg",
390
+ "workbench.foreground": "--mica-text",
391
+ "workbench.mutedForeground": "--mica-muted",
392
+ "panel.background": "--mica-panel",
393
+ border: "--mica-border",
394
+ accent: "--mica-accent",
395
+ "accent.foreground": "--mica-accent-foreground",
396
+ "selection.background": "--mica-active",
397
+ "focus.border": "--mica-focus",
398
+ "canvas.background": "--mica-canvas-background",
399
+ "canvas.grid": "--mica-canvas-grid",
400
+ "canvas.foreground": "--mica-canvas-foreground",
401
+ "canvas.wire": "--mica-canvas-wire",
402
+ "canvas.pin": "--mica-canvas-pin",
403
+ "canvas.selection": "--mica-canvas-selection",
404
+ "error.foreground": "--mica-error",
405
+ shadow: "--mica-shadow"
406
+ });
407
+ var WORKBENCH_DARK_COLORS = Object.freeze({
408
+ "workbench.background": "#1c1c1c",
409
+ "workbench.foreground": "#e5e5e5",
410
+ "workbench.mutedForeground": "#a3a3a3",
411
+ "panel.background": "#242424",
412
+ border: "#383838",
413
+ accent: "#d4d4d4",
414
+ "accent.foreground": "#171717",
415
+ "selection.background": "#353535",
416
+ "focus.border": "#b8b8b8",
417
+ "canvas.background": "#151515",
418
+ "canvas.grid": "#303030",
419
+ "canvas.foreground": "#d4d4d4",
420
+ "canvas.wire": "#a3a3a3",
421
+ "canvas.pin": "#c4c4c4",
422
+ "canvas.selection": "#eeeeee",
423
+ "error.foreground": "#f28b82",
424
+ shadow: "#00000055"
425
+ });
426
+ var WORKBENCH_LIGHT_COLORS = Object.freeze({
427
+ "workbench.background": "#ffffff",
428
+ "workbench.foreground": "#263247",
429
+ "workbench.mutedForeground": "#748098",
430
+ "panel.background": "#fafbfe",
431
+ border: "#e2e6ed",
432
+ accent: "#336df0",
433
+ "accent.foreground": "#ffffff",
434
+ "selection.background": "#e8efff",
435
+ "focus.border": "#336df0",
436
+ "canvas.background": "#f6f7fa",
437
+ "canvas.grid": "#cdd3de",
438
+ "canvas.foreground": "#354058",
439
+ "canvas.wire": "#508d79",
440
+ "canvas.pin": "#4285ff",
441
+ "canvas.selection": "#4285ff",
442
+ "error.foreground": "#b43b35",
443
+ shadow: "#00000022"
444
+ });
445
+ function isToken(value) {
446
+ return Object.hasOwn(WORKBENCH_THEME_CSS_VARIABLES, value);
447
+ }
448
+ function normalizeTheme(theme = "dark") {
449
+ const appearance = typeof theme === "string" ? theme : theme.appearance ?? "dark";
450
+ if (![
451
+ "dark",
452
+ "light",
453
+ "system"
454
+ ].includes(appearance)) throw new Error(`Unknown workbench theme appearance: ${appearance}`);
455
+ const colors = {};
456
+ if (typeof theme !== "string") for (const [token, value] of Object.entries(theme.colors ?? {})) {
457
+ if (!isToken(token)) throw new Error(`Unknown workbench color token: ${token}`);
458
+ if (typeof value !== "string" || value.trim() === "") throw new Error(`Workbench color token ${token} must be a non-empty CSS color`);
459
+ colors[token] = value;
460
+ }
461
+ return Object.freeze({
462
+ appearance,
463
+ colors: Object.freeze(colors)
464
+ });
465
+ }
466
+ function resolveTheme(theme, systemDark) {
467
+ const appearance = theme.appearance === "system" ? systemDark ? "dark" : "light" : theme.appearance ?? "dark";
468
+ return Object.freeze({
469
+ appearance,
470
+ colors: Object.freeze({
471
+ ...appearance === "dark" ? WORKBENCH_DARK_COLORS : WORKBENCH_LIGHT_COLORS,
472
+ ...theme.colors
473
+ })
474
+ });
475
+ }
476
+ function themeStyle(theme) {
477
+ const result = {};
478
+ for (const [token, variable] of Object.entries(WORKBENCH_THEME_CSS_VARIABLES)) if (isToken(token)) result[variable] = theme.colors[token];
479
+ return result;
480
+ }
481
+ function readCanvasTheme(element) {
482
+ const style = getComputedStyle(element);
483
+ const colors = { ...WORKBENCH_DARK_COLORS };
484
+ for (const [token, variable] of Object.entries(WORKBENCH_THEME_CSS_VARIABLES)) {
485
+ if (!isToken(token)) continue;
486
+ const value = style.getPropertyValue(variable).trim();
487
+ if (value === "" || !CSS.supports("color", value)) throw new Error(`Workbench token ${token} did not resolve to a CSS color`);
488
+ colors[token] = value;
489
+ }
490
+ return colors;
491
+ }
492
+ //#endregion
493
+ //#region src/fused/html/theme.ts
494
+ /**
495
+ * Theme mirroring of the device HTML views (RFC 0023).
496
+ *
497
+ * The editor forwards the computed colors of its workbench tokens over the typed host bridge; the
498
+ * environment injects them into the author document before any author script runs and updates the
499
+ * document root in place afterwards, so a theme change never reloads a frame and never loses author
500
+ * input, model session or document history. An environment without an editor theme keeps a complete
501
+ * dark palette, so the author document always resolves every token.
502
+ */
503
+ /** Theme of an environment whose editor forwarded no colors yet. */
504
+ var DEFAULT_HTML_VIEW_THEME = Object.freeze({
505
+ appearance: "dark",
506
+ colors: WORKBENCH_DARK_COLORS
507
+ });
508
+ var TOKENS = Object.keys(WORKBENCH_THEME_CSS_VARIABLES);
509
+ /**
510
+ * Semantic token the generic view background uses.
511
+ *
512
+ * A device view sits inside a workbench panel, so its loading surface is the panel background; the
513
+ * author example paints its own `body` with the same token, which keeps the first paint and the
514
+ * author document seamless.
515
+ */
516
+ var HTML_VIEW_BACKGROUND_TOKEN = "panel.background";
517
+ /** Resolved CSS color of the view background of one theme. */
518
+ function htmlViewBackgroundColor(theme) {
519
+ return theme.colors[HTML_VIEW_BACKGROUND_TOKEN];
520
+ }
521
+ /** Characters that would end the injected declaration or the style element. */
522
+ var UNSAFE_COLOR = /[;{}<>\\]/;
523
+ /**
524
+ * Validates one theme crossing the bridge and completes missing tokens.
525
+ *
526
+ * @throws {TypeError} when the appearance is unknown, a token is undeclared or a color cannot be
527
+ * placed in a style declaration.
528
+ */
529
+ function normalizeHtmlViewTheme(value) {
530
+ if (typeof value !== "object" || value === null) throw new TypeError("An HTML view theme must be an object");
531
+ const record = value;
532
+ const appearance = record.appearance ?? "dark";
533
+ if (appearance !== "dark" && appearance !== "light") throw new TypeError(`Unknown HTML view theme appearance: ${String(appearance)}`);
534
+ const colors = { ...appearance === "dark" ? WORKBENCH_DARK_COLORS : WORKBENCH_LIGHT_COLORS };
535
+ const source = record.colors;
536
+ if (source !== void 0 && source !== null) {
537
+ if (typeof source !== "object") throw new TypeError("HTML view theme colors must be an object");
538
+ for (const [token, color] of Object.entries(source)) {
539
+ if (!Object.hasOwn(WORKBENCH_THEME_CSS_VARIABLES, token)) throw new TypeError(`Unknown HTML view theme token: ${token}`);
540
+ colors[token] = htmlViewColor(token, color);
541
+ }
542
+ }
543
+ for (const token of TOKENS) colors[token] ??= htmlViewColor(token, WORKBENCH_DARK_COLORS[token]);
544
+ return Object.freeze({
545
+ appearance,
546
+ colors: Object.freeze(colors)
547
+ });
548
+ }
549
+ function htmlViewColor(token, value) {
550
+ if (typeof value !== "string" || value.trim() === "") throw new TypeError(`HTML view theme token ${token} must be a non-empty CSS color`);
551
+ if (UNSAFE_COLOR.test(value)) throw new TypeError(`HTML view theme token ${token} must be a plain CSS color`);
552
+ return value.trim();
553
+ }
554
+ /** Whether two themes resolve to the same appearance and colors. */
555
+ function htmlViewThemeEquals(left, right) {
556
+ if (left.appearance !== right.appearance) return false;
557
+ return TOKENS.every((token) => left.colors[token] === right.colors[token]);
558
+ }
559
+ /** Theme declarations injected into the author document head before any author script. */
560
+ function htmlViewThemeCss(theme) {
561
+ const declarations = TOKENS.map((token) => `${WORKBENCH_THEME_CSS_VARIABLES[token]}:${theme.colors[token]}`);
562
+ declarations.push(`color-scheme:${theme.appearance}`);
563
+ return `:root{background-color:${htmlViewBackgroundColor(theme)};${declarations.join(";")}}`;
564
+ }
565
+ /** Mirrors every theme token onto the root element of one document, in place. */
566
+ function applyHtmlViewTheme(root, theme) {
567
+ const style = root.style;
568
+ for (const token of TOKENS) style.setProperty(WORKBENCH_THEME_CSS_VARIABLES[token], theme.colors[token]);
569
+ style.setProperty("color-scheme", theme.appearance);
570
+ style.setProperty("background-color", htmlViewBackgroundColor(theme));
571
+ }
572
+ //#endregion
573
+ //#region src/fused/html/host.ts
574
+ /**
575
+ * Editor-side manager of the device HTML view environments (RFC 0023).
576
+ *
577
+ * One environment per `(instanceId, viewId)`: an iframe on its own origin served from
578
+ * `viewBaseUrlTemplate`, one transferred `MessagePort` for the typed bridge, and one DOM owner that
579
+ * is created once and never moved. The editor UI attaches the owner to a sidebar or floating slot
580
+ * and the manager only positions it, so docking, floating and resizing keep the same page,
581
+ * listeners, local state and model proxy; collapse keeps the environment mounted, and release
582
+ * disposes it. The environment page itself hosts a sandboxed inner frame for the author document,
583
+ * which is why the manager only ever sees one stable owner and one stable outer page.
584
+ *
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.
590
+ */
591
+ var DEFAULT_HANDSHAKE_TIMEOUT_MS = 15e3;
592
+ var MAX_MESSAGE_LENGTH = 500;
593
+ /** Failure codes an environment may report about itself. */
594
+ var REPORTABLE_CODES = /* @__PURE__ */ new Set([
595
+ "view/load-failed",
596
+ "view/bridge-failed",
597
+ "view/execution-failed"
598
+ ]);
599
+ /** Key of one view instance: the same device view in two places is still one environment. */
600
+ function htmlViewKey(instanceId, viewId) {
601
+ return `${instanceId}\u0000${viewId}`;
602
+ }
603
+ /** Creates the HTML view manager of one workbench. */
604
+ function createHtmlViewHost(options) {
605
+ const doc = options.document ?? globalThis.document;
606
+ const win = options.window ?? globalThis.window;
607
+ const origin = options.origin ?? globalThis.location?.origin;
608
+ if (origin === void 0 || origin === "" || origin === "null") throw new HtmlViewError("view/invalid-base-url-template", "The HTML view host needs the editor origin to bind every handshake; pass `origin` outside a browser document.");
609
+ const base = parseHtmlViewBase(options.viewBaseUrlTemplate, origin);
610
+ const handshakeTimeoutMs = options.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS;
611
+ const changes = new Emitter();
612
+ const themeChanges = new Emitter();
613
+ let theme = options.theme === void 0 ? DEFAULT_HTML_VIEW_THEME : normalizeHtmlViewTheme(options.theme);
614
+ const records = /* @__PURE__ */ new Map();
615
+ const pendingOpens = /* @__PURE__ */ new Map();
616
+ const packages = /* @__PURE__ */ new Map();
617
+ const layerListeners = new DisposableStore();
618
+ let layer;
619
+ let observer;
620
+ let slotObserver;
621
+ let pendingFrame;
622
+ let disposed = false;
623
+ return {
624
+ onDidChange: changes.event,
625
+ onDidThemeChange: themeChanges.event,
626
+ get theme() {
627
+ return theme;
628
+ },
629
+ setTheme,
630
+ get views() {
631
+ return [...records.values()].map((record) => handleOf(record));
632
+ },
633
+ get,
634
+ open,
635
+ close,
636
+ closeAll,
637
+ focus,
638
+ refresh,
639
+ dispose
640
+ };
641
+ function assertOpen() {
642
+ if (disposed) throw new HtmlViewError("view/unavailable-mode", "The HTML view host is disposed.");
643
+ }
644
+ function setTheme(next) {
645
+ const resolved = normalizeHtmlViewTheme(next);
646
+ if (disposed) return;
647
+ if (htmlViewThemeEquals(theme, resolved)) return;
648
+ theme = resolved;
649
+ for (const record of records.values()) {
650
+ record.frame.style.background = htmlViewBackgroundColor(theme);
651
+ if (record.state !== "loading") record.owner.style.background = htmlViewBackgroundColor(theme);
652
+ }
653
+ themeChanges.fire(resolved);
654
+ }
655
+ function get(instanceId, viewId) {
656
+ const record = records.get(htmlViewKey(instanceId, viewId));
657
+ return record === void 0 ? void 0 : handleOf(record);
658
+ }
659
+ function open(request) {
660
+ try {
661
+ assertOpen();
662
+ const key = htmlViewKey(request.instanceId, request.viewId);
663
+ const existing = records.get(key);
664
+ if (existing !== void 0) {
665
+ if (existing.state !== "failed") {
666
+ existing.location = request.location;
667
+ focusRecord(existing);
668
+ }
669
+ return Promise.resolve(handleOf(existing));
670
+ }
671
+ const pending = pendingOpens.get(key);
672
+ if (pending !== void 0) return pending.task;
673
+ const entry = createPendingOpen(request);
674
+ pendingOpens.set(key, entry);
675
+ return entry.task;
676
+ } catch (error) {
677
+ return Promise.reject(error instanceof Error ? error : new Error(String(error)));
678
+ }
679
+ }
680
+ /**
681
+ * Starts one open and remembers how to release it before its record exists.
682
+ *
683
+ * The verified package read and the model resolution are asynchronous, so a selection change or an
684
+ * end of the run session may land while the environment is still being prepared. Cancellation
685
+ * rejects the caller's promise and makes the in-flight preparation refuse to create a record.
686
+ */
687
+ function createPendingOpen(request) {
688
+ const key = htmlViewKey(request.instanceId, request.viewId);
689
+ let settle;
690
+ let rejection;
691
+ const gate = new Promise((_resolve, reject) => {
692
+ settle = reject;
693
+ });
694
+ gate.catch(() => void 0);
695
+ const pending = {
696
+ key,
697
+ instanceId: request.instanceId,
698
+ viewId: request.viewId,
699
+ task: gate,
700
+ get cancelled() {
701
+ return rejection !== void 0;
702
+ },
703
+ get rejection() {
704
+ return rejection;
705
+ },
706
+ cancel(reason) {
707
+ if (rejection !== void 0) return;
708
+ rejection = reason;
709
+ pendingOpens.delete(key);
710
+ settle?.(reason);
711
+ }
712
+ };
713
+ const creation = createEnvironment(request, pending);
714
+ creation.catch((error) => {
715
+ if (rejection !== void 0) return;
716
+ settle?.(error instanceof Error ? error : new Error(String(error)));
717
+ });
718
+ pending.task = Promise.race([creation, gate]).finally(() => {
719
+ if (pendingOpens.get(key) === pending) pendingOpens.delete(key);
720
+ });
721
+ pending.task.catch(() => void 0);
722
+ return pending;
723
+ }
724
+ /** Stops one preparation whose release already happened, with an explicit failure. */
725
+ function throwIfReleased(entry) {
726
+ if (entry.cancelled) throw entry.rejection ?? releasedError(entry, "The HTML view was released.");
727
+ assertOpen();
728
+ }
729
+ function releasedError(entry, reason) {
730
+ return new HtmlViewError("view/unavailable-mode", `${reason} No environment was created for ${entry.instanceId}/${entry.viewId}.`, {
731
+ instanceId: entry.instanceId,
732
+ viewId: entry.viewId
733
+ });
734
+ }
735
+ async function createEnvironment(request, entry) {
736
+ const { instanceId, viewId } = request;
737
+ throwIfReleased(entry);
738
+ const instance = describe(instanceId);
739
+ if (instance === void 0) throw new HtmlViewError("view/unavailable-mode", `Instance "${instanceId}" has no mounted device view environment.`, {
740
+ instanceId,
741
+ viewId
742
+ });
743
+ const view = instance.views[viewId];
744
+ if (view === void 0) throw new HtmlViewError("view/unknown-entry", `Device ${instance.device} declares no HTML view "${viewId}".`, {
745
+ instanceId,
746
+ viewId
747
+ });
748
+ if (!view.entry.toLowerCase().endsWith(".html")) throw new HtmlViewError("view/load-failed", `View entry "${view.entry}" of ${instance.device} is not an HTML document.`, {
749
+ instanceId,
750
+ viewId
751
+ });
752
+ let files;
753
+ try {
754
+ files = await packageOf(instance.lock);
755
+ } catch (cause) {
756
+ throw new HtmlViewError("view/load-failed", `Cannot verify ${instance.device}: ${messageOf(cause)}`, {
757
+ instanceId,
758
+ viewId
759
+ });
760
+ }
761
+ if (!Object.hasOwn(files.files, view.entry)) throw new HtmlViewError("view/load-failed", `Package ${instance.device} does not declare the view entry "${view.entry}".`, {
762
+ instanceId,
763
+ viewId
764
+ });
765
+ throwIfReleased(entry);
766
+ const model = resolveModel(instanceId, instance);
767
+ assertOpen();
768
+ const environmentId = (options.createEnvironmentId ?? newHtmlEnvironmentId)();
769
+ const environmentUrl = htmlEnvironmentUrl(base, environmentId);
770
+ const assetRoot = assetRootUrl(environmentUrl).href;
771
+ const documentUrl = new URL(ENVIRONMENT_DOCUMENT_FILE, environmentUrl);
772
+ const record = {
773
+ key: htmlViewKey(instanceId, viewId),
774
+ instanceId,
775
+ viewId,
776
+ title: view.title,
777
+ device: instance.device,
778
+ entry: view.entry,
779
+ lock: instance.lock,
780
+ assetRoot,
781
+ environmentUrl: documentUrl.href,
782
+ props: instance.props,
783
+ methods: new Set(instance.methods),
784
+ events: new Set(instance.events),
785
+ hasModel: instance.hasModel,
786
+ model,
787
+ location: request.location,
788
+ token: createToken(),
789
+ owner: ownerElement(instanceId, viewId, view.title, instance.device),
790
+ frame: frameElement(view.title, instance.device, theme),
791
+ handle: void 0,
792
+ slot: null,
793
+ visible: true,
794
+ state: "loading",
795
+ failure: void 0,
796
+ loadSeen: false,
797
+ endpoint: void 0,
798
+ assetEndpoint: void 0,
799
+ contentEndpoint: void 0,
800
+ subscriptions: /* @__PURE__ */ new Map(),
801
+ eventListeners: /* @__PURE__ */ new Set(),
802
+ closeListeners: /* @__PURE__ */ new Set(),
803
+ timer: void 0
804
+ };
805
+ record.owner.append(record.frame);
806
+ layerElement().append(record.owner);
807
+ records.set(record.key, record);
808
+ record.frame.addEventListener("load", () => onFrameLoad(record));
809
+ if (entry.cancelled) {
810
+ record.owner.remove();
811
+ throwIfReleased(entry);
812
+ }
813
+ record.frame.src = record.environmentUrl;
814
+ if (handshakeTimeoutMs > 0) record.timer = setTimeout(() => {
815
+ record.timer = void 0;
816
+ fault(record, "view/bridge-failed", "The HTML environment did not answer the bridge handshake.");
817
+ }, handshakeTimeoutMs);
818
+ emit("opened", record);
819
+ return handleOf(record);
820
+ }
821
+ function connect(record) {
822
+ const channel = new MessageChannel();
823
+ const endpoint = createRpc(channel.port1);
824
+ record.endpoint = endpoint;
825
+ endpoint.register(fusedHtmlHostControlService, controlService(record), { transfer: (member, value) => member === "readAsset" ? transferBytes(value) : transferPort(value) });
826
+ endpoint.onDidClose(() => {
827
+ if (record.state !== "failed") release(record);
828
+ });
829
+ const frameWindow = record.frame.contentWindow;
830
+ if (frameWindow === null) {
831
+ fault(record, "view/bridge-failed", "The HTML environment frame is not available.");
832
+ return;
833
+ }
834
+ const message = {
835
+ type: HTML_VIEW_CONNECT,
836
+ token: record.token,
837
+ parentOrigin: origin,
838
+ target: viewTarget(record)
839
+ };
840
+ try {
841
+ frameWindow.postMessage(message, new URL(record.environmentUrl).origin, [channel.port2]);
842
+ } catch (cause) {
843
+ fault(record, "view/bridge-failed", `The bridge port was rejected: ${messageOf(cause)}`);
844
+ }
845
+ }
846
+ function viewTarget(record) {
847
+ return {
848
+ instanceId: record.instanceId,
849
+ viewId: record.viewId,
850
+ device: record.device,
851
+ title: record.title,
852
+ entry: record.entry,
853
+ assetRoot: record.assetRoot,
854
+ props: record.props,
855
+ methods: [...record.methods],
856
+ events: [...record.events],
857
+ hasModel: record.hasModel
858
+ };
859
+ }
860
+ /** Lifecycle lane of the trusted environment page. */
861
+ function controlService(record) {
862
+ return {
863
+ readAsset: (path) => readPackageFile(record, path),
864
+ async getTheme() {
865
+ return theme;
866
+ },
867
+ onDidThemeChange(listener) {
868
+ const subscription = themeChanges.event((next) => listener(next));
869
+ return () => subscription.dispose();
870
+ },
871
+ async ready() {
872
+ markReady(record);
873
+ },
874
+ async reportFailure(code, message) {
875
+ reportFailure(record, code, message);
876
+ },
877
+ closed() {
878
+ release(record);
879
+ },
880
+ async assetPort() {
881
+ return requestPort(record, "package");
882
+ },
883
+ async contentPort() {
884
+ return requestPort(record, "author");
885
+ }
886
+ };
887
+ }
888
+ /** Dedicated lane of the inner author frame. */
889
+ function authorService(record) {
890
+ return {
891
+ readAsset: (path) => readPackageFile(record, path),
892
+ async callModel(method, params) {
893
+ try {
894
+ const client = record.model;
895
+ if (client === void 0) throw new HtmlViewError("view/unavailable-mode", `Device ${record.device} declares no model, so the view cannot call "${method}".`, {
896
+ instanceId: record.instanceId,
897
+ viewId: record.viewId
898
+ });
899
+ if (!record.methods.has(method)) throw new HtmlViewError("view/execution-failed", `Method "${method}" is not declared by ${record.device}.`, {
900
+ instanceId: record.instanceId,
901
+ viewId: record.viewId
902
+ });
903
+ const invoke = client.methods[method];
904
+ if (invoke === void 0) throw new HtmlViewError("view/unavailable-mode", `Method "${method}" is not available on the live model.`, {
905
+ instanceId: record.instanceId,
906
+ viewId: record.viewId
907
+ });
908
+ return await invoke(params);
909
+ } catch (cause) {
910
+ throw toWireFailure(cause);
911
+ }
912
+ },
913
+ async subscribe(event) {
914
+ if (record.subscriptions.has(event)) return;
915
+ if (!record.events.has(event)) throw toWireFailure(new HtmlViewError("view/execution-failed", `Event "${event}" is not declared by ${record.device}.`, {
916
+ instanceId: record.instanceId,
917
+ viewId: record.viewId
918
+ }));
919
+ const client = record.model;
920
+ if (client === void 0) throw toWireFailure(new HtmlViewError("view/unavailable-mode", `Device ${record.device} declares no model, so the view cannot observe "${event}".`, {
921
+ instanceId: record.instanceId,
922
+ viewId: record.viewId
923
+ }));
924
+ const outlet = client.events[event];
925
+ if (outlet === void 0) throw toWireFailure(new HtmlViewError("view/execution-failed", `Event "${event}" is declared by ${record.device} but the live model exposes no outlet for it.`, {
926
+ instanceId: record.instanceId,
927
+ viewId: record.viewId
928
+ }));
929
+ const subscription = outlet((payload) => {
930
+ const push = {
931
+ name: event,
932
+ payload
933
+ };
934
+ for (const listener of [...record.eventListeners]) try {
935
+ listener(push);
936
+ } catch {}
937
+ });
938
+ record.subscriptions.set(event, subscription);
939
+ },
940
+ async unsubscribe(event) {
941
+ const subscription = record.subscriptions.get(event);
942
+ if (subscription === void 0) return;
943
+ record.subscriptions.delete(event);
944
+ subscription.dispose();
945
+ },
946
+ onDidModelEvent(listener) {
947
+ record.eventListeners.add(listener);
948
+ return () => record.eventListeners.delete(listener);
949
+ },
950
+ onDidClose(listener) {
951
+ record.closeListeners.add(listener);
952
+ return () => record.closeListeners.delete(listener);
953
+ },
954
+ async reportFailure(code, message) {
955
+ reportFailure(record, code, message);
956
+ }
957
+ };
958
+ }
959
+ function reportFailure(record, code, message) {
960
+ fault(record, REPORTABLE_CODES.has(code) ? code : "view/execution-failed", typeof message === "string" && message.length > 0 ? message : "The HTML view failed without a reason.");
961
+ }
962
+ /**
963
+ * Reads one declared package file of this view.
964
+ *
965
+ * Every lane that reaches package bytes goes through this one verified lookup of the locked
966
+ * package, so neither the author frame nor the worker can read a file the view does not declare.
967
+ */
968
+ async function readPackageFile(record, path) {
969
+ try {
970
+ const problem = typeof path === "string" ? packagePathProblem(path) : "must be a string";
971
+ if (problem !== void 0) throw new HtmlViewError("view/load-failed", `Asset path ${JSON.stringify(path)} ${problem}.`, {
972
+ instanceId: record.instanceId,
973
+ viewId: record.viewId
974
+ });
975
+ const files = await packageOf(record.lock);
976
+ if (!Object.hasOwn(files.files, path)) throw new HtmlViewError("view/load-failed", `Package ${record.device} does not declare "${path}".`, {
977
+ instanceId: record.instanceId,
978
+ viewId: record.viewId
979
+ });
980
+ return await files.read(path);
981
+ } catch (cause) {
982
+ throw toWireFailure(cause);
983
+ }
984
+ }
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.`, {
1002
+ instanceId: record.instanceId,
1003
+ viewId: record.viewId
1004
+ });
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.`, {
1006
+ instanceId: record.instanceId,
1007
+ viewId: record.viewId
1008
+ });
1009
+ const channel = new MessageChannel();
1010
+ 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
+ }
1027
+ endpoint.onDidClose(() => {
1028
+ if (record.state !== "loading" && record.state !== "ready") return;
1029
+ fault(record, "view/bridge-failed", `The dedicated ${lane} port of the view closed.`);
1030
+ });
1031
+ return channel.port2;
1032
+ }
1033
+ function describe(instanceId) {
1034
+ if (disposed) return void 0;
1035
+ return options.describe(instanceId);
1036
+ }
1037
+ /**
1038
+ * Resolves the model proxy of one instance from its declaration.
1039
+ *
1040
+ * A device without a model gets an undefined proxy by design; a device with a model must get one,
1041
+ * so a missing source, a missing proxy or a runtime failure is reported instead of hidden.
1042
+ */
1043
+ function resolveModel(instanceId, instance) {
1044
+ if (!instance.hasModel) return void 0;
1045
+ const source = options.model;
1046
+ if (source === void 0) throw new HtmlViewError("view/unavailable-mode", `Device ${instance.device} declares a model, but the HTML view host has no model source.`, { instanceId });
1047
+ let model;
1048
+ try {
1049
+ model = source(instanceId);
1050
+ } catch (cause) {
1051
+ throw new HtmlViewError("view/unavailable-mode", `The model of ${instance.device} is not available (${failureCodeOf(cause)}): ${messageOf(cause)}`, { instanceId });
1052
+ }
1053
+ if (model === void 0) throw new HtmlViewError("view/unavailable-mode", `Device ${instance.device} declares a model, but the workbench provides no live proxy for it.`, { instanceId });
1054
+ return model;
1055
+ }
1056
+ function packageOf(lock) {
1057
+ const key = `${lock.id}@${lock.version}#${lock.integrity}`;
1058
+ let pending = packages.get(key);
1059
+ if (pending === void 0) {
1060
+ pending = openDevicePackage(options.registry, lock).catch((cause) => {
1061
+ packages.delete(key);
1062
+ throw cause;
1063
+ });
1064
+ packages.set(key, pending);
1065
+ }
1066
+ return pending;
1067
+ }
1068
+ function onFrameLoad(record) {
1069
+ if (record.state === "closed" || record.state === "failed") return;
1070
+ if (!record.loadSeen) {
1071
+ record.loadSeen = true;
1072
+ connect(record);
1073
+ return;
1074
+ }
1075
+ release(record);
1076
+ }
1077
+ function markReady(record) {
1078
+ if (record.state !== "loading") return;
1079
+ clearTimer(record);
1080
+ record.state = "ready";
1081
+ record.owner.style.background = htmlViewBackgroundColor(theme);
1082
+ record.frame.style.visibility = "visible";
1083
+ emit("ready", record);
1084
+ sync(record);
1085
+ }
1086
+ function fault(record, code, message) {
1087
+ if (record.state === "failed" || record.state === "closed") return;
1088
+ record.state = "failed";
1089
+ record.failure = {
1090
+ code,
1091
+ message: bounded(message),
1092
+ instanceId: record.instanceId,
1093
+ viewId: record.viewId,
1094
+ title: record.title,
1095
+ device: record.device
1096
+ };
1097
+ releaseResources(record);
1098
+ emit("failed", record);
1099
+ try {
1100
+ options.onDiagnostic?.(record.failure);
1101
+ } catch {}
1102
+ }
1103
+ /**
1104
+ * Retires the lease of one view, explicitly.
1105
+ *
1106
+ * A failed environment keeps its record and its failure until the workbench releases it, so one
1107
+ * failing view is never replaced by a fresh origin on its own.
1108
+ */
1109
+ function release(record) {
1110
+ if (record.state === "closed") return;
1111
+ record.state = "closed";
1112
+ records.delete(record.key);
1113
+ releaseResources(record);
1114
+ record.owner.remove();
1115
+ emit("closed", record);
1116
+ }
1117
+ function releaseResources(record) {
1118
+ clearTimer(record);
1119
+ if (record.slot !== null) {
1120
+ slotObserver?.unobserve(record.slot);
1121
+ record.slot = null;
1122
+ }
1123
+ for (const subscription of record.subscriptions.values()) try {
1124
+ subscription.dispose();
1125
+ } catch {}
1126
+ record.subscriptions.clear();
1127
+ for (const listener of [...record.closeListeners]) try {
1128
+ listener();
1129
+ } catch {}
1130
+ record.closeListeners.clear();
1131
+ record.eventListeners.clear();
1132
+ const endpoints = [
1133
+ record.endpoint,
1134
+ record.assetEndpoint,
1135
+ record.contentEndpoint
1136
+ ];
1137
+ record.endpoint = void 0;
1138
+ record.assetEndpoint = void 0;
1139
+ record.contentEndpoint = void 0;
1140
+ for (const endpoint of endpoints) try {
1141
+ endpoint?.dispose();
1142
+ } catch {}
1143
+ record.owner.style.display = "none";
1144
+ record.frame.remove();
1145
+ }
1146
+ function clearTimer(record) {
1147
+ if (record.timer === void 0) return;
1148
+ clearTimeout(record.timer);
1149
+ record.timer = void 0;
1150
+ }
1151
+ function close(instanceId, viewId) {
1152
+ const key = htmlViewKey(instanceId, viewId);
1153
+ const pending = pendingOpens.get(key);
1154
+ pending?.cancel(releasedError({
1155
+ instanceId,
1156
+ viewId
1157
+ }, "The HTML view was released while its environment was still being prepared."));
1158
+ const record = records.get(key);
1159
+ if (record !== void 0) release(record);
1160
+ return pending !== void 0 || record !== void 0;
1161
+ }
1162
+ function closeAll() {
1163
+ for (const entry of [...pendingOpens.values()]) entry.cancel(releasedError(entry, "Every HTML view was released while this environment was pending."));
1164
+ pendingOpens.clear();
1165
+ for (const record of [...records.values()]) release(record);
1166
+ records.clear();
1167
+ }
1168
+ function attachSlot(record, slot) {
1169
+ const previous = record.slot;
1170
+ if (previous === slot) {
1171
+ sync(record);
1172
+ return;
1173
+ }
1174
+ record.slot = slot;
1175
+ if (previous !== null) slotObserver?.unobserve(previous);
1176
+ if (slot !== null) slotObserver?.observe(slot);
1177
+ sync(record);
1178
+ }
1179
+ function focus(instanceId, viewId) {
1180
+ const record = records.get(htmlViewKey(instanceId, viewId));
1181
+ if (record === void 0) return false;
1182
+ focusRecord(record);
1183
+ return true;
1184
+ }
1185
+ function focusRecord(record) {
1186
+ record.visible = true;
1187
+ sync(record);
1188
+ try {
1189
+ record.frame.focus({ preventScroll: true });
1190
+ } catch {}
1191
+ }
1192
+ function refresh() {
1193
+ for (const record of records.values()) sync(record);
1194
+ }
1195
+ /** Coalesces scroll and resize churn into one measurement per animation frame. */
1196
+ function scheduleRefresh() {
1197
+ if (pendingFrame !== void 0) return;
1198
+ const schedule = win.requestAnimationFrame?.bind(win);
1199
+ if (schedule === void 0) {
1200
+ refresh();
1201
+ return;
1202
+ }
1203
+ pendingFrame = schedule(() => {
1204
+ pendingFrame = void 0;
1205
+ if (!disposed) refresh();
1206
+ });
1207
+ }
1208
+ function sync(record) {
1209
+ const slot = record.slot;
1210
+ if (slot === null || !record.visible || record.state === "closed" || record.state === "failed") {
1211
+ record.owner.style.display = "none";
1212
+ return;
1213
+ }
1214
+ const rect = slot.getBoundingClientRect();
1215
+ if (rect.width <= 0 || rect.height <= 0) {
1216
+ record.owner.style.display = "none";
1217
+ return;
1218
+ }
1219
+ const clip = clipInsets(boxOf(rect), clipBoundsOf(slot));
1220
+ record.owner.style.display = clip.visible ? "block" : "none";
1221
+ record.owner.style.left = `${rect.left}px`;
1222
+ record.owner.style.top = `${rect.top}px`;
1223
+ record.owner.style.width = `${rect.width}px`;
1224
+ record.owner.style.height = `${rect.height}px`;
1225
+ record.owner.style.clipPath = clipPathOf(clip);
1226
+ }
1227
+ /** Clip boxes of one slot: its scrolling ancestors, the editor container and the viewport. */
1228
+ function clipBoundsOf(slot) {
1229
+ const bounds = [];
1230
+ const viewportWidth = win.innerWidth ?? 0;
1231
+ const viewportHeight = win.innerHeight ?? 0;
1232
+ if (viewportWidth > 0 && viewportHeight > 0) bounds.push({
1233
+ left: 0,
1234
+ top: 0,
1235
+ right: viewportWidth,
1236
+ bottom: viewportHeight
1237
+ });
1238
+ const container = options.container.getBoundingClientRect();
1239
+ if (container.width > 0 && container.height > 0) bounds.push(boxOf(container));
1240
+ for (let node = slot.parentElement; node !== null; node = node.parentElement) {
1241
+ const style = win.getComputedStyle(node);
1242
+ if (!clipsOverflow(style.overflowX, style.overflowY)) continue;
1243
+ const rect = node.getBoundingClientRect();
1244
+ bounds.push({
1245
+ left: rect.left + node.clientLeft,
1246
+ top: rect.top + node.clientTop,
1247
+ right: rect.left + node.clientLeft + node.clientWidth,
1248
+ bottom: rect.top + node.clientTop + node.clientHeight
1249
+ });
1250
+ }
1251
+ return bounds;
1252
+ }
1253
+ function layerElement() {
1254
+ if (layer !== void 0) return layer;
1255
+ const element = doc.createElement("div");
1256
+ element.className = "mica-html-view-layer";
1257
+ element.setAttribute("data-mica-html-views", "");
1258
+ element.style.cssText = "position:fixed;inset:0;overflow:hidden;pointer-events:none;z-index:2147483000;";
1259
+ options.container.append(element);
1260
+ layer = element;
1261
+ layerListeners.add({ dispose: () => {
1262
+ win.removeEventListener("resize", scheduleRefresh);
1263
+ win.removeEventListener("scroll", scheduleRefresh, true);
1264
+ win.removeEventListener("message", onWindowMessage);
1265
+ if (pendingFrame !== void 0) win.cancelAnimationFrame?.(pendingFrame);
1266
+ pendingFrame = void 0;
1267
+ observer?.disconnect();
1268
+ observer = void 0;
1269
+ slotObserver?.disconnect();
1270
+ slotObserver = void 0;
1271
+ } });
1272
+ win.addEventListener("resize", scheduleRefresh);
1273
+ win.addEventListener("scroll", scheduleRefresh, true);
1274
+ win.addEventListener("message", onWindowMessage);
1275
+ if (typeof ResizeObserver !== "undefined") {
1276
+ observer = new ResizeObserver(() => scheduleRefresh());
1277
+ observer.observe(options.container);
1278
+ slotObserver = new ResizeObserver(() => scheduleRefresh());
1279
+ }
1280
+ return element;
1281
+ }
1282
+ function onWindowMessage(event) {
1283
+ const data = event.data;
1284
+ if (data === null || typeof data !== "object" || data.type !== "mica:view:ack") return;
1285
+ if (typeof data.token !== "string") return;
1286
+ const record = [...records.values()].find((entry) => entry.token === data.token);
1287
+ if (record === void 0 || record.state !== "loading") return;
1288
+ if (event.source !== record.frame.contentWindow) return;
1289
+ if (event.origin !== new URL(record.environmentUrl).origin) return;
1290
+ clearTimer(record);
1291
+ }
1292
+ function ownerElement(instanceId, viewId, title, device) {
1293
+ const element = doc.createElement("div");
1294
+ element.className = "mica-html-view-owner";
1295
+ element.setAttribute("role", "group");
1296
+ element.setAttribute("aria-label", `${device} ${title}`);
1297
+ element.dataset["instanceId"] = instanceId;
1298
+ element.dataset["viewId"] = viewId;
1299
+ element.style.position = "absolute";
1300
+ element.style.display = "none";
1301
+ element.style.overflow = "hidden";
1302
+ element.style.pointerEvents = "auto";
1303
+ element.style.background = "transparent";
1304
+ return element;
1305
+ }
1306
+ function frameElement(title, device, current) {
1307
+ const frame = doc.createElement("iframe");
1308
+ frame.className = "mica-html-view-frame";
1309
+ frame.title = `${title} — ${device}`;
1310
+ frame.setAttribute("sandbox", "allow-scripts allow-same-origin");
1311
+ frame.setAttribute("referrerpolicy", "no-referrer");
1312
+ frame.setAttribute("allow", "");
1313
+ frame.style.display = "block";
1314
+ frame.style.width = "100%";
1315
+ frame.style.height = "100%";
1316
+ frame.style.border = "0";
1317
+ frame.style.visibility = "hidden";
1318
+ frame.style.background = htmlViewBackgroundColor(current);
1319
+ return frame;
1320
+ }
1321
+ function handleOf(record) {
1322
+ const existing = record.handle;
1323
+ if (existing !== void 0) return existing;
1324
+ const handle = {
1325
+ key: record.key,
1326
+ instanceId: record.instanceId,
1327
+ viewId: record.viewId,
1328
+ title: record.title,
1329
+ device: record.device,
1330
+ entry: record.entry,
1331
+ get location() {
1332
+ return record.location;
1333
+ },
1334
+ get state() {
1335
+ return record.state;
1336
+ },
1337
+ get failure() {
1338
+ return record.failure;
1339
+ },
1340
+ element: record.owner,
1341
+ attach(slot) {
1342
+ attachSlot(record, slot);
1343
+ },
1344
+ setVisible(visible) {
1345
+ record.visible = visible;
1346
+ sync(record);
1347
+ },
1348
+ setLocation(location) {
1349
+ if (record.location === location) return;
1350
+ record.location = location;
1351
+ emit("moved", record);
1352
+ },
1353
+ focus() {
1354
+ focusRecord(record);
1355
+ },
1356
+ close() {
1357
+ release(record);
1358
+ }
1359
+ };
1360
+ record.handle = handle;
1361
+ return handle;
1362
+ }
1363
+ function emit(type, record) {
1364
+ if (disposed) return;
1365
+ changes.fire({
1366
+ type,
1367
+ handle: handleOf(record)
1368
+ });
1369
+ }
1370
+ async function dispose() {
1371
+ if (disposed) return;
1372
+ disposed = true;
1373
+ for (const entry of [...pendingOpens.values()]) entry.cancel(releasedError(entry, "The HTML view host was disposed while this environment was pending."));
1374
+ pendingOpens.clear();
1375
+ for (const record of [...records.values()]) {
1376
+ record.state = "closed";
1377
+ releaseResources(record);
1378
+ record.owner.remove();
1379
+ }
1380
+ records.clear();
1381
+ for (const pending of packages.values()) pending.catch(() => void 0);
1382
+ packages.clear();
1383
+ layerListeners.dispose();
1384
+ observer?.disconnect();
1385
+ observer = void 0;
1386
+ slotObserver?.disconnect();
1387
+ slotObserver = void 0;
1388
+ layer?.remove();
1389
+ layer = void 0;
1390
+ changes.dispose();
1391
+ themeChanges.dispose();
1392
+ }
1393
+ }
1394
+ function boxOf(rect) {
1395
+ return {
1396
+ left: rect.left,
1397
+ top: rect.top,
1398
+ right: rect.left + rect.width,
1399
+ bottom: rect.top + rect.height
1400
+ };
1401
+ }
1402
+ function clipsOverflow(x, y) {
1403
+ const clips = (value) => value === "auto" || value === "scroll" || value === "hidden" || value === "clip";
1404
+ return clips(x) || clips(y);
1405
+ }
1406
+ function createToken() {
1407
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
1408
+ const webCrypto = globalThis.crypto;
1409
+ if (typeof webCrypto?.getRandomValues === "function") webCrypto.getRandomValues(bytes);
1410
+ else for (let index = 0; index < bytes.length; index += 1) bytes[index] = Math.random() * 256;
1411
+ return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
1412
+ }
1413
+ /** Code of one failure, so a runtime `model/disconnected` stays visible to the workbench. */
1414
+ function failureCodeOf(cause) {
1415
+ if (typeof cause !== "object" || cause === null) return "unknown";
1416
+ const code = cause.code;
1417
+ if (typeof code === "string" && code.length > 0) return code;
1418
+ const name = cause.name;
1419
+ return typeof name === "string" && name.length > 0 ? name : "unknown";
1420
+ }
1421
+ /** Transfer list of one granted direct port. */
1422
+ function transferPort(value) {
1423
+ return typeof MessagePort !== "undefined" && value instanceof MessagePort ? [value] : [];
1424
+ }
1425
+ function bounded(message) {
1426
+ const text = typeof message === "string" ? message : String(message);
1427
+ return text.length > MAX_MESSAGE_LENGTH ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…` : text;
1428
+ }
1429
+ //#endregion
1430
+ //#region src/fused/html/source.ts
1431
+ /** Reads the declaration of one device manifest. */
1432
+ function htmlViewDeviceDeclaration(manifest) {
1433
+ return {
1434
+ views: manifest.view ?? {},
1435
+ hasModel: manifest.model !== void 0
1436
+ };
1437
+ }
1438
+ /** Builds the manager callbacks of one runtime. */
1439
+ function createHtmlViewRuntimeSource(options) {
1440
+ return {
1441
+ describe(instanceId) {
1442
+ const instance = presentationOf(options.runtime, instanceId);
1443
+ if (instance === void 0) return void 0;
1444
+ const declaration = options.device(instance.device);
1445
+ if (declaration === void 0) throw new HtmlViewError("view/unavailable-mode", `The workbench has no declaration for device ${instance.device}; pass its manifest view and model through the source options.`, { instanceId });
1446
+ return {
1447
+ device: instance.device,
1448
+ lock: instance.lock,
1449
+ props: instance.props,
1450
+ methods: instance.methods,
1451
+ events: instance.events,
1452
+ hasModel: declaration.hasModel,
1453
+ views: declaration.views
1454
+ };
1455
+ },
1456
+ model(instanceId) {
1457
+ return options.runtime.getModel(instanceId);
1458
+ }
1459
+ };
1460
+ }
1461
+ function presentationOf(runtime, instanceId) {
1462
+ return runtime.display.instances.find((entry) => entry.instanceId === instanceId);
1463
+ }
1464
+ //#endregion
1465
+ //#region src/fused/html/client.ts
1466
+ /**
1467
+ * Author bridge of one device HTML environment (RFC 0023 `DeviceViewApi`).
1468
+ *
1469
+ * This code runs inside the inner sandbox frame of one environment. It owns the author `Event`
1470
+ * outlets, turns package reads into verified lookups through the host bridge and never touches the
1471
+ * editor DOM, the model implementation or the host file system. It is DOM-free on purpose:
1472
+ * `environment/content.ts` supplies the page around it, and the same bridge runs unchanged in tests.
1473
+ */
1474
+ /** Builds the author-facing bridge over an established host channel. */
1475
+ function createDeviceViewSession(options) {
1476
+ const { host, target } = options;
1477
+ const createObjectUrl = options.createObjectUrl ?? ((blob) => URL.createObjectURL(blob));
1478
+ const revokeObjectUrl = options.revokeObjectUrl ?? ((url) => URL.revokeObjectURL(url));
1479
+ const declared = new Set(target.methods);
1480
+ const channels = /* @__PURE__ */ new Map();
1481
+ const urls = /* @__PURE__ */ new Set();
1482
+ const closeEmitter = new Emitter();
1483
+ let closed = false;
1484
+ let failureReported = false;
1485
+ const fail = (code, message) => {
1486
+ if (failureReported || closed) return;
1487
+ failureReported = true;
1488
+ options.reportFailure(code, message);
1489
+ };
1490
+ const channel = (name) => {
1491
+ return (listener) => {
1492
+ if (closed) return toDisposable(() => void 0);
1493
+ let entry = channels.get(name);
1494
+ if (entry === void 0) {
1495
+ entry = {
1496
+ emitter: new Emitter(),
1497
+ listeners: 0
1498
+ };
1499
+ channels.set(name, entry);
1500
+ }
1501
+ const current = entry;
1502
+ current.listeners += 1;
1503
+ if (current.listeners === 1) subscribe(name);
1504
+ const subscription = current.emitter.event(listener);
1505
+ return toDisposable(() => {
1506
+ subscription.dispose();
1507
+ current.listeners -= 1;
1508
+ if (current.listeners > 0) return;
1509
+ channels.delete(name);
1510
+ current.emitter.dispose();
1511
+ host.unsubscribe(name).catch(() => void 0);
1512
+ });
1513
+ };
1514
+ };
1515
+ async function subscribe(name) {
1516
+ try {
1517
+ await host.subscribe(name);
1518
+ } catch (cause) {
1519
+ fail("view/bridge-failed", `Subscribing to "${name}" failed: ${messageOf(cause)}`);
1520
+ }
1521
+ }
1522
+ const methods = new Proxy(Object.create(null), {
1523
+ get(_target, name) {
1524
+ if (typeof name !== "string" || !declared.has(name)) return void 0;
1525
+ return async (params) => {
1526
+ if (closed) throw new HtmlViewError("view/bridge-failed", "The device view is closed.");
1527
+ return mapWireFailure(() => host.callModel(name, params));
1528
+ };
1529
+ },
1530
+ has(_target, name) {
1531
+ return typeof name === "string" && declared.has(name);
1532
+ }
1533
+ });
1534
+ const events = {};
1535
+ for (const name of target.events) events[name] = channel(name);
1536
+ const assets = {
1537
+ async read(path) {
1538
+ assertAssetPath(path);
1539
+ if (closed) throw new HtmlViewError("view/bridge-failed", "The device view is closed.");
1540
+ const bytes = await mapWireFailure(() => host.readAsset(path));
1541
+ if (!(bytes instanceof Uint8Array)) throw new HtmlViewError("view/load-failed", `The host returned no bytes for ${path}.`);
1542
+ return bytes;
1543
+ },
1544
+ async getUrl(path) {
1545
+ const bytes = await assets.read(path);
1546
+ const url = createObjectUrl(new Blob([imageBuffer(bytes)], { type: mimeTypeOf(path) }));
1547
+ if (closed) {
1548
+ revokeObjectUrl(url);
1549
+ throw new HtmlViewError("view/bridge-failed", "The device view is closed.");
1550
+ }
1551
+ urls.add(url);
1552
+ return url;
1553
+ }
1554
+ };
1555
+ const api = Object.freeze({
1556
+ props: Object.freeze({ ...target.props }),
1557
+ model: target.hasModel ? Object.freeze({
1558
+ methods,
1559
+ events: Object.freeze(events)
1560
+ }) : void 0,
1561
+ assets,
1562
+ onDidClose: (listener) => {
1563
+ if (closed) {
1564
+ listener();
1565
+ return toDisposable(() => void 0);
1566
+ }
1567
+ return closeEmitter.event(listener);
1568
+ }
1569
+ });
1570
+ const release = () => {
1571
+ if (closed) return;
1572
+ closed = true;
1573
+ for (const entry of channels.values()) entry.emitter.dispose();
1574
+ channels.clear();
1575
+ for (const url of urls) try {
1576
+ revokeObjectUrl(url);
1577
+ } catch {}
1578
+ urls.clear();
1579
+ };
1580
+ return {
1581
+ api,
1582
+ get closed() {
1583
+ return closed;
1584
+ },
1585
+ deliver(event) {
1586
+ if (closed) return;
1587
+ const entry = channels.get(event.name);
1588
+ if (entry === void 0) return;
1589
+ try {
1590
+ entry.emitter.fire(event.payload);
1591
+ } catch (cause) {
1592
+ fail("view/execution-failed", `Listener of "${event.name}" failed: ${messageOf(cause)}`);
1593
+ }
1594
+ },
1595
+ close() {
1596
+ if (closed) return;
1597
+ try {
1598
+ closeEmitter.fire(void 0);
1599
+ } finally {
1600
+ closeEmitter.dispose();
1601
+ release();
1602
+ }
1603
+ },
1604
+ dispose() {
1605
+ closeEmitter.dispose();
1606
+ release();
1607
+ }
1608
+ };
1609
+ }
1610
+ /** Rejects a path that is not a normalized package-root relative file path. */
1611
+ function assertAssetPath(path) {
1612
+ const problem = typeof path === "string" ? packagePathProblem(path) : "must be a string";
1613
+ if (problem !== void 0) throw new HtmlViewError("view/load-failed", `Asset path ${JSON.stringify(path)} ${problem}.`);
1614
+ }
1615
+ //#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 };
1617
+
1618
+ //# sourceMappingURL=html-HXwZq1my.js.map