lecodes-web-host 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,MAAM,YAA2G;AAAA,EAC/G,MAAM,0BAAM,OAAO,mCAAgC;AAAA,EACnD,MAAM,0BAAM,OAAO,iCAA8B;AAAA,EACjD,IAAI,0BAAM,OAAO,iCAA8B;AACjD;AAGA,MAAM,UAAyC;AAAA,EAC7C,MAAM,MAAM,kGAA6D;AAAA,EACzE,MAAM,MAAM,gGAA2D;AAAA,EACvE,IAAI,MAAM,gGAA2D;AACvE;AAIO,MAAM,oBAAoB,OAAO,SAAkB,UAA0B,OAA4B;AAC9G,QAAM,WAAW,MAAM,UAAU,OAAO,KAAK;AAC7C,QAAM,MAAM,QAAQ,OAAO;AAC3B,QAAM,OAAgC;AAAA,IACpC,YAAY,CAAC,SAAkB,KAAK,SAAS,OAAO,IAAI,MAAM;AAAA,IAC9D,GAAI,QAAQ,YAAY,EAAE,oBAAoB,QAAQ,WAAW,oBAAoB,QAAQ,aAAa,GAAC,IAAM;AAAA,IACjH,GAAI,QAAQ,cAAc,EAAE,qBAAqB,QAAQ,aAAa,qBAAqB,QAAQ,eAAe,GAAC,IAAM;AAAA,IACzH,GAAG,QAAQ;AAAA;AAEb,QAAM,SAAU,MAAM,QAAQ,IAAI;AAClC,MAAI,OAAO,OAAO,uBAAuB,kBAAkB,IAAI,MAAM,gBAAgB,OAAO,sCAAsC;AAClI,SAAO;AACT;ACnCA,MAAM,gBAAgB,GAAG,WAAW,GAAG,WAAW,GAAG,aAAa,GAAG,eAAe,GAAG,aAAa,GAAG,YAAY,GAAG,YAAY,GAAG,gBAAgB;AACrJ,MAAM,UAAU;AAChB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eAAS,IAAI,IAAI;AACjB,gBAAU,YAAY,SAAS,SAAS;AAAA,IAC1C;AAAA;AAAA,IAEA,cAAc,IAAI;AAAA,IAClB,UAAU;AACR,UAAI,UAAW;AACf,kBAAY;AACZ,UAAI,qBAAqB,GAAG;AAC5B,aAAO;AACP,gBAAU;AACV,YAAM;AAAW,aAAO;AAAW,cAAQ;AAAW,UAAI;AAC1D;AACA,eAAS;AACT,UAAI;AACJ,eAAS;AACT,WAAK;AAAA,IACP;AAAA;AAEJ;ACzQO,MAAMK,UAAQ,OAAO,MAAmB,MAAc,UAAgE,OAAO;AAClI,QAAM,OAAO,MAAMD,aAAW,MAAM,EAAE,GAAG,SAAS,QAAQJ,oBAAkB,IAAI,GAAG;AACnF,MAAI;AACF,SAAK,IAAI,MAAM,EAAE,SAAS,QAAQ,SAAS;AAAA,EAC7C,SAAS,GAAG;AACV,SAAK;AACL,UAAM;AAAA,EACR;AACA,SAAO;AACT;ACnBO,MAAM,aAAyBM;AAC/B,MAAM,QAAeC;AACrB,MAAM,oBAAuCC;AAC7C,MAAM,YAAuBC","names":["map","hex","w","h","scale","rx","ry","apply","seen","PaintKind","join","paint","g","players","onError","parseBundleHeader","preload","profileOf","factories","createHost","mount","host.createHost","host.mount","host.parseBundleHeader","host.profileOf"],"ignoreList":[],"sources":["../../../runtime/web/src/profile.ts","../../../runtime/web/src/jsb.ts","../../../runtime/web/native/dist/creator-full.js.symbols?url","../../../runtime/web/src/wasmCrashSymbolizer.ts","../../../renderers/web-shared/src/utils/fetch.ts","../../../renderers/web-shared/src/ui/viewScale.ts","../../../renderers/web-canvas/src/core/util/svgSrc.ts","../../../renderers/web-canvas/src/host/Host.ts","../../../renderers/web-canvas/src/host/BrowserHost.ts","../../../renderers/web-canvas/src/core/util/colors.ts","../../../renderers/web-canvas/src/core/util/geometry.ts","../../../renderers/web-canvas/src/paint/Canvas2DPainter.ts","../../../renderers/web-shared/src/utils/mediaplayer.ts","../../../sdk/src/ui/tree.ts","../../../renderers/web-canvas/src/core/hitTest.ts","../../../renderers/web-canvas/src/layout/CuiPaint.gen.ts","../../../renderers/web-canvas/src/layout/creatorUi/readGradient.ts","../../../renderers/web-canvas/src/layout/creatorUi/paint-read.ts","../../../renderers/web-canvas/src/core/text.ts","../../../renderers/web-canvas/src/paint/paintTree.ts","../../../renderers/web-canvas/src/serialize/serializeRenderTree.ts","../../../renderers/web-canvas/src/runtime/TreeUI.ts","../../../renderers/web-canvas/src/web/BrowserUI.ts","../../../renderers/web-canvas/src/web/chrome.ts","../../../renderers/web-canvas/src/web/renderer.ts","../../../renderers/web-shared/src/canvas/gen/spec.ts","../../../renderers/web-shared/src/canvas/gen/drawlist.ts","../../../renderers/web-shared/src/canvas/gen/painter.ts","../../../renderers/web-shared/src/canvas/createCanvasHost.ts","../../../renderers/web-shared/src/assets/Roboto-Variable.woff2?url","../../../renderers/web-shared/src/utils/fonts.ts","../../../sdk/src/version.ts","../src/engines/gl.ts","../src/engines/scene2d.ts","../../../renderers/web-shared/src/sourcemapError.ts","../src/errors.ts","../src/header.ts","../src/page.ts","../src/plugins.ts","../src/safeArea.ts","../../../runtime/web/src/gen/materialGroups.gen.ts","../src/materials.ts","../../../runtime/web/src/assets/materials.bin?url","../../../runtime/web/src/assets/materials-world.bin?url","../../../runtime/web/src/assets/neutral_ibl128.ktx?url","../../../runtime/web/src/assets/uberarchive.bin?url","../src/system.ts","../src/tables/app.ts","../src/tables/openFilePicker.ts","../src/tables/device.ts","../src/tables/fetch.ts","../src/tables/inputHost.ts","../src/tables/input.ts","../src/tables/media.ts","../src/tables/serviceSystem.ts","../src/tables/service.ts","../src/tables/socket.ts","../src/tables/storage.ts","../src/world.ts","../src/host.ts","../src/index.ts","../src/package.ts"],"sourcesContent":["/// <reference path=\"./native.d.ts\" />\n// The BROWSER profiles of runtime/web/native/CMakeLists.txt: one Emscripten module per engine set, one\n// heap for every engine in it. A web host loads the profile its bundle needs — the imports below are\n// static strings so a bundler splits each profile into its own chunk and a page that never opens a\n// 3D scene never downloads Filament.\nimport type { WasmModule } from \"./gen/wasm\"\n\n// The other two are not a page's: `headless` is Bun's (runtime/headless loads it itself), `nav` an\n// engine-only twin — named here, a bundler would put both into every browser build.\nexport type Profile = \"full\" | \"2d\" | \"ui\"\n\nexport type ProfileOptions = {\n /** creator-gl's WebGL2 context + the attributes it was created with (init() registers it). */\n glContext?: WebGL2RenderingContext\n glOptions?: WebGLContextAttributes\n /** creator-2d's own WebGL2 context (c2dInit registers it) — a second canvas in dual mode. */\n gl2dContext?: WebGL2RenderingContext\n gl2dOptions?: WebGLContextAttributes\n /** Extra Emscripten module arguments (print, printErr, …). */\n moduleArgs?: Record<string, unknown>\n}\n\nconst factories: Record<Profile, () => Promise<{ default: (args?: Record<string, unknown>) => Promise<any> }>> = {\n full: () => import(\"../native/dist/creator-full.js\"),\n \"2d\": () => import(\"../native/dist/creator-2d.js\"),\n ui: () => import(\"../native/dist/creator-ui.js\"),\n}\n\n// the .wasm beside each module\nconst wasmUrl: Record<Profile, () => string> = {\n full: () => new URL(\"../native/dist/creator-full.wasm\", import.meta.url).href,\n \"2d\": () => new URL(\"../native/dist/creator-2d.wasm\", import.meta.url).href,\n ui: () => new URL(\"../native/dist/creator-ui.wasm\", import.meta.url).href,\n}\n\n/** Instantiate a profile module. The engines' WebGL contexts ride in as module fields (the engines\n * read `Module.filament_glContext` / `Module.creator2d_glContext` when they init). */\nexport const loadProfileModule = async (profile: Profile, options: ProfileOptions = {}): Promise<WasmModule> => {\n const factory = (await factories[profile]()).default\n const url = wasmUrl[profile]()\n const args: Record<string, unknown> = {\n locateFile: (file: string) => (file.endsWith(\".wasm\") ? url : file),\n ...(options.glContext ? { filament_glContext: options.glContext, filament_glOptions: options.glOptions ?? {} } : {}),\n ...(options.gl2dContext ? { creator2d_glContext: options.gl2dContext, creator2d_glOptions: options.gl2dOptions ?? {} } : {}),\n ...options.moduleArgs,\n }\n const module = (await factory(args)) as WasmModule\n if (typeof module._creatorWebVersion !== \"function\") throw new Error(`creator-web: ${profile} is not a creator-web profile module`)\n return module\n}\n","// The JS side of runtime/native's wasm arm (runtime/native/src/js/wasm.cpp): the handle table its\n// `jsb::Value`s index, the imports the arm calls (property access, calls, strings, typed arrays,\n// throws), the wrappers that turn an installed handler table into JS functions, and the\n// FinalizationRegistry behind a class finalizer (the owned `Handle`). One instance per module,\n// installed as `Module.jsb` before `creatorWebInit`. Engine-agnostic: a browser or Bun.\n//\n// Values: a number is its IEEE bits (a NaN written canonical — the engine may canonicalize NaNs,\n// so a tagged word never travels as a JS number); anything else is a NaN with the sign bit set, a\n// TAG in bits 16–19 of the high word and the payload in the low word (wasm-support.h). Handles are\n// refcounted: the arm's `dup` / `free` are `dup` / `release` here; objects and functions are deduped\n// through a WeakMap so the arm's `same` holds; at zero references the slot is dropped and the value\n// is the engine's to collect.\nimport type { WasmModule } from \"./gen/wasm\"\n\nconst TAG_UNDEFINED = 1, TAG_NULL = 2, TAG_BOOL = 3, TAG_OBJECT = 4, TAG_FUNCTION = 5, TAG_STRING = 6, TAG_ARRAY = 7, TAG_OTHER = 8, TAG_EXCEPTION = 15\nconst HI_BASE = 0xFFF00000\nconst hiOf = (tag: number) => (HI_BASE | (tag << 16)) >>> 0\nconst HI_UNDEFINED = hiOf(TAG_UNDEFINED), HI_NULL = hiOf(TAG_NULL), HI_BOOL = hiOf(TAG_BOOL), HI_EXCEPTION = hiOf(TAG_EXCEPTION)\nconst tagOf = (hi: number) => ((hi & 0xFFF00000) >>> 0) === HI_BASE ? (hi >>> 16) & 0xF : 0\n\n/** A world the arm evaluates in: its global object (the bridges are installed on it) + evaluator. */\nexport type JsbWorld = {\n global: object\n evaluate(code: string, filename: string): unknown\n}\n\nexport type JsbOptions = {\n /** The boot world (context 1). */\n world: JsbWorld\n /** A fresh world for `_creatorApp.run` (a vm context headless); absent = the boot world is reused. */\n newWorld?: () => JsbWorld\n /** The host tables the generated forwarders call (`Module.jsb.host.<table>.<slot>`). */\n host: Record<string, unknown>\n}\n\nconst ARG_STACK_BYTES = 64 * 1024\n\n/** A settle group: the heap callbacks of one host slot call, released together after the first settle. */\ntype Group = { ptrs: number[], done: boolean }\n\nexport class Jsb {\n readonly M: WasmModule\n readonly host: Record<string, unknown>\n private out = 0\n // the table: index → value (0 unused); refs[i] = references the arm holds; free = released slots\n private table: unknown[] = [undefined]\n private refs: number[] = [0]\n private freeSlots: number[] = []\n private objIndex = new WeakMap<object, number>()\n private pending: unknown = undefined\n private hasPending = false\n private worlds = new Map<number, JsbWorld>()\n private nextWorld = 2\n private readonly newWorld?: () => JsbWorld\n // the argument stack the wrappers write call arguments into (nested calls bump it)\n private argBase = 0\n private argSp = 0\n private readonly scratch = new DataView(new ArrayBuffer(8))\n private readonly classRegistry: FinalizationRegistry<{ ref: WeakRef<object>, cls: number, opaque: number }>\n // Every live class instance as a WeakRef: `gc()` sweeps them so a finalizer lands SYNCHRONOUSLY\n // inside the arm's runGC (QuickJS semantics: `ownedStats` = collect + drain + count), instead of\n // on the FinalizationRegistry's later task — which still covers the objects a natural collection takes.\n private readonly tracked = new Map<object, { ref: WeakRef<object>, cls: number, opaque: number }>()\n private readonly fnRegistry: FinalizationRegistry<number>\n private readonly opaques = new WeakMap<object, { cls: number, opaque: number }>()\n\n constructor(M: WasmModule, options: JsbOptions) {\n this.M = M\n this.host = options.host\n this.worlds.set(1, options.world)\n this.newWorld = options.newWorld\n this.argBase = M._malloc(ARG_STACK_BYTES)\n this.argSp = this.argBase\n this.classRegistry = new FinalizationRegistry((token) => {\n if (!this.tracked.delete(token)) return // swept already by gc()\n this.M._jsbFinalize(token.cls, token.opaque)\n })\n this.fnRegistry = new FinalizationRegistry((k) => { this.M._jsbFunctionGone(k) })\n }\n\n // ---- the arm's hooks --------------------------------------------------------------------------\n _init(out: number) { this.out = out }\n\n // ---- encoding ---------------------------------------------------------------------------------\n /** Encode `v` at heap address `p` (8 bytes). A handle takes ONE reference (the caller owns it);\n * the result is that handle's index, 0 for an immediate (a boolean's payload is NOT an index —\n * returning it once released slot 1 under an unrelated function). */\n private write(p: number, v: unknown): number {\n const M = this.M\n if (typeof v === \"number\") {\n M.HEAPF64[p >> 3] = v !== v ? NaN : v // the engine writes a canonical NaN for NaN\n return 0\n }\n let lo = 0, hi: number, idx = 0\n if (v === undefined) hi = HI_UNDEFINED\n else if (v === null) hi = HI_NULL\n else if (typeof v === \"boolean\") { hi = HI_BOOL; lo = v ? 1 : 0 }\n else {\n lo = idx = this.alloc(v)\n hi = hiOf(typeof v === \"function\" ? TAG_FUNCTION : typeof v === \"string\" ? TAG_STRING : Array.isArray(v) ? TAG_ARRAY : typeof v === \"object\" ? TAG_OBJECT : TAG_OTHER)\n }\n M.HEAPU32[p >> 2] = lo\n M.HEAPU32[(p >> 2) + 1] = hi\n return idx\n }\n private writeOut(v: unknown) { this.write(this.out, v) }\n private writeOutException() { const M = this.M; M.HEAPU32[this.out >> 2] = 0; M.HEAPU32[(this.out >> 2) + 1] = HI_EXCEPTION }\n /** Decode a (lo, hi) word pair; a handle's value is BORROWED (the reference stays). */\n private decode(lo: number, hi: number): unknown {\n const tag = tagOf(hi)\n switch (tag) {\n case 0: { this.scratch.setUint32(0, lo, true); this.scratch.setUint32(4, hi, true); return this.scratch.getFloat64(0, true) }\n case TAG_UNDEFINED: case TAG_EXCEPTION: return undefined\n case TAG_NULL: return null\n case TAG_BOOL: return lo !== 0\n default: return this.table[lo]\n }\n }\n private readAt(p: number): unknown {\n const M = this.M\n return this.decode(M.HEAPU32[p >> 2], M.HEAPU32[(p >> 2) + 1])\n }\n /** A `value` parameter of a host slot (the generated forwarders): the JS value whose word is at\n * `p` — the app's own value, not a copy; undefined for a null address. */\n valueAt(p: number): unknown { return p ? this.readAt(p) : undefined }\n /** Read the result slot and TAKE the reference the arm handed over (an OWNED result). */\n private takeOut(): { value: unknown, threw: boolean } {\n const M = this.M\n const lo = M.HEAPU32[this.out >> 2], hi = M.HEAPU32[(this.out >> 2) + 1]\n const tag = tagOf(hi)\n if (tag === TAG_EXCEPTION) return { value: undefined, threw: true }\n const value = this.decode(lo, hi)\n if (tag >= TAG_OBJECT && tag <= TAG_OTHER) this.release(lo)\n return { value, threw: false }\n }\n private args(argc: number, argv: number): unknown[] {\n const out: unknown[] = new Array(argc)\n for (let i = 0; i < argc; i++) out[i] = this.readAt(argv + i * 8)\n return out\n }\n\n // ---- the table ----------------------------------------------------------------------------------\n private alloc(v: unknown): number {\n const isObj = typeof v === \"object\" || typeof v === \"function\"\n if (isObj) {\n const hit = this.objIndex.get(v as object)\n if (hit !== undefined) { this.refs[hit]++; return hit }\n }\n let i: number\n if (this.freeSlots.length > 0) { i = this.freeSlots.pop()!; this.table[i] = v; this.refs[i] = 1 }\n else { i = this.table.length; this.table.push(v); this.refs.push(1) }\n if (isObj) this.objIndex.set(v as object, i)\n return i\n }\n dup(idx: number) { if (idx > 0) this.refs[idx]++ }\n release(idx: number) {\n if (idx <= 0) return\n if (this.refs[idx] <= 0) { console.warn(`[jsb] release of a dead handle ${idx} (${typeof this.table[idx]})`, new Error().stack?.split(\"\\n\").slice(2, 6).join(\"\\n\")); return }\n if (--this.refs[idx] > 0) return\n const v = this.table[idx]\n if (typeof v === \"object\" || typeof v === \"function\") this.objIndex.delete(v as object)\n this.table[idx] = undefined\n this.freeSlots.push(idx)\n }\n /** Live handles (for tests). */\n liveHandles(): number { return this.table.length - 1 - this.freeSlots.length }\n\n // ---- worlds -------------------------------------------------------------------------------------\n global(ctx: number) { this.writeOut(this.worlds.get(ctx)?.global ?? this.worlds.get(1)!.global) }\n newContext(): number {\n if (!this.newWorld) return 1\n const id = this.nextWorld++\n this.worlds.set(id, this.newWorld())\n return id\n }\n freeContext(ctx: number) { if (ctx !== 1) this.worlds.delete(ctx) }\n eval(ctx: number, code: string, filename: string) {\n const w = this.worlds.get(ctx) ?? this.worlds.get(1)!\n try { this.writeOut(w.evaluate(code, filename)) }\n catch (e) { this.pending = e; this.hasPending = true; this.writeOutException() }\n }\n\n // ---- objects ----------------------------------------------------------------------------------\n get(lo: number, hi: number, key: string) {\n const o = this.decode(lo, hi) as any\n if (o === undefined || o === null) { this.writeOut(undefined); return }\n try { this.writeOut(o[key]) }\n catch (e) { this.pending = e; this.hasPending = true; this.writeOutException() }\n }\n getIndex(lo: number, hi: number, i: number) {\n const o = this.decode(lo, hi) as any\n if (o === undefined || o === null) { this.writeOut(undefined); return }\n try { this.writeOut(o[i]) }\n catch (e) { this.pending = e; this.hasPending = true; this.writeOutException() }\n }\n has(lo: number, hi: number, key: string): boolean {\n const o = this.decode(lo, hi)\n return (typeof o === \"object\" || typeof o === \"function\") && o !== null && key in (o as object)\n }\n set(obj: number, key: string, lo: number, hi: number) {\n const o = this.table[obj] as any\n if (o === undefined || o === null) return\n o[key] = this.decode(lo, hi)\n }\n setIndex(obj: number, i: number, lo: number, hi: number) {\n const o = this.table[obj] as any\n if (o === undefined || o === null) return\n o[i] = this.decode(lo, hi)\n }\n keys(lo: number, hi: number, countOut: number): number {\n const M = this.M\n const o = this.decode(lo, hi)\n const ks = (typeof o === \"object\" || typeof o === \"function\") && o !== null ? Object.keys(o as object) : []\n let total = 1\n for (const k of ks) total += M.lengthBytesUTF8(k) + 1\n const p = M._malloc(total)\n let off = p\n for (const k of ks) { const n = M.lengthBytesUTF8(k) + 1; M.stringToUTF8(k, off, n); off += n }\n M.HEAPU32[countOut >> 2] = ks.length\n return p\n }\n newObject(classId: number, opaque: number) {\n const o: Record<string, unknown> = {}\n if (classId > 0) {\n this.opaques.set(o, { cls: classId, opaque })\n const token = { ref: new WeakRef(o), cls: classId, opaque }\n this.tracked.set(token, token)\n this.classRegistry.register(o, token, token)\n }\n this.writeOut(o)\n }\n newArray() { this.writeOut([]) }\n opaqueOf(idx: number, classId: number): number {\n const o = this.table[idx]\n if (typeof o !== \"object\" || o === null) return 0\n const e = this.opaques.get(o)\n return e && e.cls === classId ? e.opaque : 0\n }\n json(lo: number, hi: number) {\n let s: unknown\n try { s = JSON.stringify(this.decode(lo, hi)) } catch { s = undefined }\n this.writeOut(s)\n }\n parseJson(text: string) {\n try { this.writeOut(JSON.parse(text)) }\n catch (e) { this.pending = e; this.hasPending = true; this.writeOutException() }\n }\n\n // ---- strings + numbers ---------------------------------------------------------------------------\n newString(s: string) { this.writeOut(s) }\n str(lo: number, hi: number, lenOut: number): number {\n const M = this.M\n const v = this.decode(lo, hi)\n let s: string\n try { s = typeof v === \"string\" ? v : String(v) } catch { return 0 } // a Symbol\n const n = M.lengthBytesUTF8(s)\n const p = M._malloc(n + 1)\n M.stringToUTF8(s, p, n + 1)\n M.HEAPU32[lenOut >> 2] = n\n return p\n }\n logString(lo: number, hi: number): number {\n const M = this.M\n const v = this.decode(lo, hi)\n let s: string\n try { s = String(v) } catch { s = \"\" }\n if (v instanceof Error && typeof v.stack === \"string\" && v.stack.length > 0) {\n const stack = v.stack.startsWith(s) ? v.stack.slice(s.length).replace(/^\\n/, \"\") : v.stack\n if (stack.trim().length > 0) s += \"\\n\" + stack.replace(/[\\r\\n]+$/, \"\")\n }\n const n = M.lengthBytesUTF8(s)\n const p = M._malloc(n + 1)\n M.stringToUTF8(s, p, n + 1)\n return p\n }\n toNumber(idx: number): number { try { return Number(this.table[idx]) } catch { return NaN } }\n truthy(idx: number): boolean { return !!this.table[idx] }\n\n // ---- errors --------------------------------------------------------------------------------------\n newError(message: string) { this.writeOut(new Error(message)) }\n throwNew(kind: number, message: string) {\n this.pending = kind === 1 ? new TypeError(message) : new Error(message)\n this.hasPending = true\n }\n takeException() {\n const e = this.hasPending ? this.pending : undefined\n this.pending = undefined\n this.hasPending = false\n this.writeOut(e)\n }\n private throwPending(): never {\n const e = this.hasPending ? this.pending : new Error(\"native handler failed\")\n this.pending = undefined\n this.hasPending = false\n throw e\n }\n\n // ---- calls ---------------------------------------------------------------------------------------\n call(_ctx: number, fn: number, thisLo: number, thisHi: number, argc: number, argv: number) {\n const f = this.table[fn] as (...a: unknown[]) => unknown\n const thisv = this.decode(thisLo, thisHi)\n const args = this.args(argc, argv)\n try { this.writeOut(f.apply(thisv, args)) }\n catch (e) { this.pending = e; this.hasPending = true; this.writeOutException() }\n }\n construct(ctor: number, argc: number, argv: number) {\n const c = this.table[ctor] as new (...a: unknown[]) => unknown\n const args = this.args(argc, argv)\n try { this.writeOut(Reflect.construct(c, args)) }\n catch (e) { this.pending = e; this.hasPending = true; this.writeOutException() }\n }\n\n // ---- typed arrays ---------------------------------------------------------------------------------\n typedArray(kind: number, data: number, bytes: number) {\n const src = this.M.HEAPU8.slice(data, data + bytes) // a copy: the array owns its buffer\n const buf = src.buffer as ArrayBuffer\n const ctors = [null, Uint8Array, Uint16Array, Uint32Array, Int32Array, Float32Array, Float64Array, Int16Array, Int8Array, Uint8ClampedArray] as const\n if (kind === 0) { this.writeOut(buf); return }\n const C = ctors[kind]\n this.writeOut(C ? new C(buf) : undefined)\n }\n /** mode 0: a typed array of `elem`-byte elements (size = elements); 1: any typed array's bytes;\n * 2: an ArrayBuffer. A malloc'd copy the arm frees (a 1-byte block for an empty array), 0 when\n * the value is not such an array. */\n arrayIn(idx: number, elem: number, mode: number, sizeOut: number): number {\n const M = this.M\n const v = this.table[idx]\n let bytes: Uint8Array | null = null\n let size = 0\n if (mode === 2) {\n if (!(v instanceof ArrayBuffer)) return 0\n bytes = new Uint8Array(v); size = bytes.byteLength\n } else {\n if (!ArrayBuffer.isView(v) || v instanceof DataView) return 0\n const ta = v as Uint8Array\n const bpe = (ta as unknown as { BYTES_PER_ELEMENT: number }).BYTES_PER_ELEMENT\n if (mode === 0 && bpe !== elem) return 0\n bytes = new Uint8Array(ta.buffer, ta.byteOffset, ta.byteLength)\n size = mode === 0 ? ta.length : ta.byteLength\n }\n const p = M._malloc(Math.max(bytes.byteLength, 1))\n if (bytes.byteLength > 0) M.HEAPU8.set(bytes, p)\n M.HEAPU32[sizeOut >> 2] = size\n return p\n }\n arrayOut(idx: number, data: number, bytes: number) {\n const v = this.table[idx]\n let dst: Uint8Array\n if (v instanceof ArrayBuffer) dst = new Uint8Array(v)\n else if (ArrayBuffer.isView(v)) dst = new Uint8Array(v.buffer, v.byteOffset, v.byteLength)\n else return\n const n = Math.min(bytes, dst.byteLength)\n if (n > 0) dst.set(this.M.HEAPU8.subarray(data, data + n))\n }\n\n // ---- handler tables + native functions --------------------------------------------------------\n /** Run an installed handler with `args`: the arguments go onto the arg stack, the result comes\n * back through the slot (an exception re-thrown here). */\n private invoke(call: (argc: number, argv: number) => void, args: unknown[]): unknown {\n const argc = args.length\n const sp = this.argSp\n let argv = sp\n let heapArgv = 0\n if (sp + argc * 8 > this.argBase + ARG_STACK_BYTES) { heapArgv = this.M._malloc(Math.max(argc * 8, 8)); argv = heapArgv }\n else this.argSp = sp + argc * 8\n const owned: number[] = []\n for (let i = 0; i < argc; i++) { const idx = this.write(argv + i * 8, args[i]); if (idx) owned.push(idx) }\n let r: { value: unknown, threw: boolean }\n try {\n call(argc, argv)\n r = this.takeOut()\n } finally {\n for (const idx of owned) this.release(idx)\n this.argSp = sp\n if (heapArgv) this.M._free(heapArgv)\n }\n if (r.threw) this.throwPending()\n return r.value\n }\n defineMethod(ctx: number, obj: number, name: string, fnIndex: number, length: number, getter: number) {\n const o = this.table[obj] as object\n if (getter) {\n Object.defineProperty(o, name, { configurable: true, enumerable: false, get: () => this.invoke(() => this.M._jsbInvokeGetter(fnIndex), []) })\n return\n }\n const M = this.M\n const f = (...args: unknown[]) => this.invoke((argc, argv) => M._jsbInvoke(ctx, fnIndex, argc, argv), args)\n Object.defineProperty(f, \"name\", { value: name })\n Object.defineProperty(f, \"length\", { value: length })\n Object.defineProperty(o, name, { configurable: true, enumerable: false, writable: true, value: f })\n }\n makeFunction(ctx: number, k: number, name: string, length: number) {\n const M = this.M\n const f = (...args: unknown[]) => this.invoke((argc, argv) => M._jsbInvokeData(ctx, k, argc, argv), args)\n if (name) Object.defineProperty(f, \"name\", { value: name })\n Object.defineProperty(f, \"length\", { value: length })\n this.fnRegistry.register(f, k)\n this.writeOut(f)\n }\n\n // ---- host callbacks (the generated forwarders) -----------------------------------------------------\n /** A JS function for a JSCallback heap pointer a host slot received: calling it posts the call\n * through the runtime's dispatch queue (the next tick runs it). `group` = the slot's settle\n * group (released after the first settle; a second settle is ignored); null = a long-lived\n * listener the runtime frees itself. A zero pointer (an optional callback the app left out) is\n * a no-op. */\n callback(ptr: number, group: Group | null): (...args: unknown[]) => void {\n if (!ptr) return () => {}\n return (...args: unknown[]) => {\n if (group) {\n if (group.done) { console.warn(\"[jsb] a settled host callback was called again\"); return }\n group.done = true\n }\n const M = this.M\n const argc = args.length\n const n = group ? group.ptrs.length : 0\n const p = M._malloc(Math.max(argc * 8 + n * 4, 8))\n const owned: number[] = []\n for (let i = 0; i < argc; i++) { const idx = this.write(p + i * 8, args[i]); if (idx) owned.push(idx) }\n const gp = p + argc * 8\n for (let i = 0; i < n; i++) M.HEAPU32[(gp >> 2) + i] = group!.ptrs[i]\n M._jsbHostCall(ptr, argc, p, gp, n)\n for (const idx of owned) this.release(idx)\n M._free(p)\n }\n }\n /** A native view's event, host → app (`channel.emit` of a view a TS host mounted): the payload\n * crosses as the value it is — the runtime retains it until its dispatch queue delivers the\n * event. No payload = the listener gets none. */\n viewEvent(viewId: number, event: string, data?: unknown): void {\n const M = this.M\n const e = M.stringToNewUTF8(event)\n if (data === undefined) { M._jsbViewEvent(viewId, e, 0); M._free(e); return }\n const p = M._malloc(8)\n const idx = this.write(p, data)\n M._jsbViewEvent(viewId, e, p)\n if (idx) this.release(idx)\n M._free(p)\n M._free(e)\n }\n /** A settle group for the callbacks of one slot call. */\n group(...ptrs: number[]): Group { return { ptrs: ptrs.filter((x) => x !== 0), done: false } }\n /** A `const char* const*` + count → strings (the generated forwarders' string[] parameters). */\n strings(ptr: number, count: number): string[] {\n const M = this.M\n const out: string[] = new Array(count)\n for (let i = 0; i < count; i++) { const p = M.HEAPU32[(ptr >> 2) + i]; out[i] = p ? M.UTF8ToString(p) : \"\" }\n return out\n }\n /** A host's byte result → a malloc'd, NUL-terminated copy the runtime frees (0 for none); the\n * byte count goes to `outSize` when the slot has one. */\n bytesOut(r: unknown, outSize: number): number {\n const M = this.M\n let bytes: Uint8Array | null = null\n if (r instanceof Uint8Array) bytes = r\n else if (r instanceof ArrayBuffer) bytes = new Uint8Array(r)\n else if (ArrayBuffer.isView(r)) bytes = new Uint8Array(r.buffer, r.byteOffset, r.byteLength)\n if (!bytes || bytes.byteLength === 0) { if (outSize) M.HEAPU32[outSize >> 2] = 0; return 0 }\n const p = M._malloc(bytes.byteLength + 1)\n M.HEAPU8.set(bytes, p)\n M.HEAPU8[p + bytes.byteLength] = 0\n if (outSize) M.HEAPU32[outSize >> 2] = bytes.byteLength\n return p\n }\n\n gc() {\n const g = (globalThis as { gc?: () => void }).gc\n const bun = (globalThis as { Bun?: { gc?: (force: boolean) => void } }).Bun\n // twice: the first full collection leaves what only became unreachable during it (the weak\n // processing of the sweep below is one such source); the second takes it\n for (let i = 0; i < 2; i++) {\n if (bun?.gc) bun.gc(true)\n else if (typeof g === \"function\") g()\n else return\n this.sweep()\n }\n }\n /** Collected class instances finalize now, not on the registry's later task. */\n private sweep() {\n for (const token of [...this.tracked.keys()] as { ref: WeakRef<object>, cls: number, opaque: number }[]) {\n if (token.ref.deref() !== undefined) continue\n this.tracked.delete(token)\n this.classRegistry.unregister(token)\n this.M._jsbFinalize(token.cls, token.opaque)\n }\n }\n}\n\n/** Create the glue for a loaded runtime module and install it as `Module.jsb`. */\nexport const installJsb = (M: WasmModule, options: JsbOptions): Jsb => {\n const jsb = new Jsb(M, options)\n ;(M as unknown as { jsb: Jsb }).jsb = jsb\n return jsb\n}\n","export default \"__VITE_ASSET__BwIUPEiH__\"","// Lazy crash symbolizer for the creator-gl wasm. The shipped wasm has no name section\n// (see creator-gl/CMakeLists.txt: --emit-symbol-map), so a runtime trap surfaces as\n// \"RuntimeError: unreachable at wasm-function[1234]\" with anonymous frames. The build deploys\n// creator-gl.js.symbols (function index -> C++ name) next to the wasm; this module fetches that\n// map ONLY after a crash has already happened and prints a decoded trace to the console. Happy\n// path cost: zero — nothing is fetched or parsed until the first wasm frame appears in an error.\n//\n// The map is only valid for creator-gl.wasm. Frames from another wasm module (creator-ui,\n// creator-2d) carry their own URL in the stack line and are left untouched; frames with no URL\n// at all (Safari's \"[wasm code]\") are decoded anyway, since a creator-gl trap is by far the\n// likeliest source, and marked with \"?\" so a misattributed name isn't taken as gospel.\n\nimport symbolsUrl from '../native/dist/creator-full.js.symbols?url'\n\nconst WASM_FRAME = /wasm-function\\[(\\d+)\\]/g\n\n// index -> raw (still escaped) name. Parsed once, kept raw — escape decoding runs only on the\n// handful of frames actually printed, not on all ~40k entries.\nlet mapPromise: Promise<Map<number, string> | null> | null = null\n\nconst loadSymbolMap = (): Promise<Map<number, string> | null> => {\n if (!mapPromise) {\n mapPromise = fetch(symbolsUrl)\n .then(resp => {\n if (!resp.ok) throw new Error(`${resp.status} ${resp.statusText}`)\n return resp.text()\n })\n .then(text => {\n const map = new Map<number, string>()\n for (const line of text.split('\\n')) {\n const sep = line.indexOf(':')\n if (sep > 0) map.set(Number(line.slice(0, sep)), line.slice(sep + 1))\n }\n return map\n })\n .catch(e => {\n console.warn('[creator-gl] creator-gl.js.symbols unavailable, wasm frames stay anonymous:', e)\n return null\n })\n }\n return mapPromise\n}\n\n// The symbol map escapes non-identifier chars as \\XX hex (emscripten format): \\20 = space,\n// \\2c = comma, \\28\\29 = parens.\nconst decodeName = (raw: string): string =>\n raw.replace(/\\\\([0-9a-fA-F]{2})/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)))\n\n// Which wasm module does this stack line reference? Matches \"creator-ui.wasm:\",\n// \"creator-gl-B3xYz9.wasm)\" etc., but not the \".wasm-function[N]\" token itself (the lookahead\n// rejects the \"-f\"). The name is matched loosely (\"creator-gl\" prefix) because Vite hashes prod\n// asset filenames. null = no module URL in the line (Safari's \"[wasm code]\").\nconst MODULE_REF = /([\\w.-]+)\\.wasm(?=[^\\w-]|$)/g\nconst lineModule = (line: string): 'ours' | 'other' | null => {\n const refs = [...line.matchAll(MODULE_REF)].map(m => m[1]!)\n if (refs.length === 0) return null\n return refs.some(r => r.includes('creator-gl')) ? 'ours' : 'other'\n}\n\n/**\n * Decode every creator-gl `wasm-function[N]` frame in a stack trace. Resolves to null when the\n * stack has no wasm frames (or the symbol map can't be fetched) — callers use that to stay\n * silent for ordinary JS errors.\n */\nexport const symbolizeWasmStack = async (stack: string): Promise<string | null> => {\n WASM_FRAME.lastIndex = 0\n if (!WASM_FRAME.test(stack)) return null\n const map = await loadSymbolMap()\n if (!map) return null\n\n let decodedAny = false\n const lines = stack.split('\\n').map(line => {\n WASM_FRAME.lastIndex = 0\n if (!WASM_FRAME.test(line)) return line\n const mod = lineModule(line)\n // A frame naming a different wasm module belongs to that module's map, not ours. URL-less\n // frames are decoded anyway (a creator-gl trap is by far the likeliest source) but marked \"?\".\n if (mod === 'other') return line\n return line.replace(WASM_FRAME, (frame, index) => {\n const raw = map.get(Number(index))\n if (raw === undefined) return frame\n decodedAny = true\n return `${mod === null ? '?' : ''}${decodeName(raw)} (${frame})`\n })\n })\n return decodedAny ? lines.join('\\n') : null\n}\n\n/**\n * The display-friendly cut of symbolizeWasmStack for UI overlays: just the decoded C++ names of\n * the creator-gl frames, top-first — no URLs, no JS glue frames. Empty when the stack has no\n * decodable creator-gl frames (or the map can't be fetched).\n */\nexport const symbolizeWasmFrames = async (stack: string): Promise<string[]> => {\n WASM_FRAME.lastIndex = 0\n if (!WASM_FRAME.test(stack)) return []\n const map = await loadSymbolMap()\n if (!map) return []\n const names: string[] = []\n for (const line of stack.split('\\n')) {\n if (lineModule(line) === 'other') continue\n for (const m of line.matchAll(WASM_FRAME)) {\n const raw = map.get(Number(m[1]))\n // libc++'s internal namespace is pure noise in a UI overlay.\n if (raw !== undefined) names.push(decodeName(raw).replaceAll('std::__2::', 'std::'))\n }\n }\n return names\n}\n\n/** Fire-and-forget: print a decoded trace for `err` if it contains creator-gl wasm frames. */\nexport const symbolizeWasmError = (err: unknown): void => {\n const stack = (err as { stack?: unknown } | null)?.stack\n if (typeof stack !== 'string') return\n symbolizeWasmStack(stack).then(decoded => {\n if (decoded) console.error('[creator-gl] decoded wasm stack (via creator-gl.js.symbols):\\n' + decoded)\n })\n}\n\nlet installed = false\n\n/**\n * Catch wasm traps that escape to the top (the render rAF loop has no try/catch — an engine\n * crash lands on the global 'error' event) and follow the browser's own report with a decoded\n * trace. Errors swallowed by app-level try/catch never get here — those paths call\n * symbolizeWasmError directly (see createGlb/loadGlb).\n */\nexport const installWasmCrashSymbolizer = (): void => {\n if (installed) return\n installed = true\n addEventListener('error', e => symbolizeWasmError((e as ErrorEvent).error))\n addEventListener('unhandledrejection', e => symbolizeWasmError((e as PromiseRejectionEvent).reason))\n}\n","// Slot 0 is reserved: 0 means \"no buffer\" in the host contract (HostFetch.putBuffer, a form's bufferId > 0).\nconst arrayBuffers: ArrayBuffer[] = [null as unknown as ArrayBuffer]\n\nconst decoder = new TextDecoder('utf-8');\n\nexport const _fetch = async (url: string, fetchOptions: any, onComplete: (systemId: number, statusCode: number) => void, onReject: (err: Error) => void) => {\n \n let body: any = undefined\n if (fetchOptions.body) {\n if (typeof fetchOptions.body === \"object\" && Array.isArray(fetchOptions.body._entries)) {\n const formData = new FormData()\n for (let [key,value,filename] of fetchOptions.body._entries) {\n if (typeof value === \"object\") {\n formData.append(key, new Blob([ getBuffer(value._id) ]), filename)\n } else {\n formData.append(key, value)\n }\n }\n body = formData\n } else if (typeof fetchOptions.body === \"string\") {\n body = fetchOptions.body\n } else {\n onReject(new Error(\"Invalid body\"))\n }\n }\n \n const resp = await fetch(url, {\n method: fetchOptions.method,\n body,\n headers: fetchOptions.headers,\n mode: \"cors\",\n credentials: \"omit\"\n })\n\n const onProgress =\n typeof fetchOptions.onProgress === 'function'\n ? fetchOptions.onProgress\n : null\n\n // FAST PATH (без стрима)\n if (!onProgress) {\n const buffer = await resp.arrayBuffer()\n arrayBuffers.push(buffer)\n onComplete(arrayBuffers.length - 1, resp.status)\n return\n }\n\n // STREAMING PATH\n const reader = resp.body?.getReader()\n\n // fallback если стрима нет\n if (!reader) {\n const buffer = await resp.arrayBuffer()\n arrayBuffers.push(buffer)\n onComplete(arrayBuffers.length - 1, resp.status)\n return\n }\n\n const contentLength = Number(resp.headers.get(\"content-length\")) || undefined\n\n let loaded = 0\n const chunks: Uint8Array[] = []\n\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n\n if (value) {\n chunks.push(value)\n loaded += value.length\n\n onProgress({ loaded, total: contentLength })\n }\n }\n\n // сборка\n const result = new Uint8Array(loaded)\n let offset = 0\n for (const chunk of chunks) {\n result.set(chunk, offset)\n offset += chunk.length\n }\n\n arrayBuffers.push(result.buffer)\n onComplete(arrayBuffers.length - 1, resp.status)\n}\n\nexport const _fetchToJson = (systemId: number) => { \n return JSON.parse(decoder.decode(getBuffer(systemId)))\n}\n\nexport const _fetchToText = (systemId: number) => {\n return decoder.decode(getBuffer(systemId))\n}\n\n/** The fetched bytes as a Uint8Array copy (Terrain.load and other SDK-parsed binaries). */\nexport const _fetchToBytes = (systemId: number): Uint8Array => {\n return new Uint8Array(getBuffer(systemId)).slice()\n}\n\nexport const _fetchSlice = (systemId: number, start: number, end: number) => {\n return decoder.decode(getBuffer(systemId).slice(start, end))\n}\n\nexport const getUrl = (systemId: number) => {\n const blob = new Blob([ arrayBuffers[systemId] ])\n return URL.createObjectURL(blob)\n}\n\nexport const getBlob = (systemId: number) => {\n return new Blob([ arrayBuffers[systemId] ])\n}\n\nexport const getBuffer = (systemId: number) => {\n return arrayBuffers[systemId]\n}\n\nexport const _disposeFetch = (id: number) => {\n arrayBuffers[id] = null as any\n}\n\nexport const putBuffer = (buffer: ArrayBuffer) => {\n arrayBuffers.push(buffer)\n return arrayBuffers.length - 1\n}\n\nconst map = new Map<string, ArrayBuffer>()\nexport const putLocalBuffer = (str: string, buf: ArrayBuffer) => {\n map.set(str, buf)\n // A name may already be materialized as a systemId (localResources caches forever). Refresh the\n // buffer behind it, or a later engine sees the stale payload — e.g. the lite engine's empty\n // built-in registrations must not shadow the real filamat the Filament engine loads on a\n // lite → filament host switch.\n const systemId = localResources.get(str)\n if (systemId !== undefined) arrayBuffers[systemId] = buf\n}\n\nexport const hasLocalBuffer = (str: string) => map.has(str)\n\nconst localResources = new Map<string, number>()\n\n/** Reverse lookup: the local-resource name a systemId was materialized from (viewer-lite resolves\n * material shaders — \"lit.filamat\" etc — by name instead of compiling the filamat package). */\nexport const getLocalName = (systemId: number): string | undefined => {\n for (const [name, id] of localResources) if (id === systemId) return name\n return undefined\n}\n\nexport const _fetchLocal = (path: string): number => {\n const existsSystemId = localResources.get(path)\n if (existsSystemId !== undefined) {\n return existsSystemId\n }\n const buf = map.get(path)\n if (!buf) return -1\n \n arrayBuffers.push(buf)\n const systemId = arrayBuffers.length-1\n\n localResources.set(path, systemId)\n return systemId\n}\n","// The effective on-screen scale of a host root, recovered from the DOM.\n//\n// The simulator displays the app at a fixed CSS `zoom` (default 0.75) so the preview matches a real\n// device while the app keeps its true logical viewport. Under `zoom` — and under a legacy\n// `transform: scale()` — an element's getBoundingClientRect() reports VISUAL px (post-scale) while\n// clientWidth/clientHeight stay LAYOUT px (the element's own coordinate space). Their ratio is the\n// effective scale a visual coordinate (e.g. a pointer's `clientX - rect.left`) must be divided by to\n// reach the app's logical space.\n//\n// This is the same computation createUI's getBoundingClientRect bridge already does\n// (appRect.width / displayWidth); factored out so every pointer path shares one definition.\n\n/** Visual-to-layout scale of `el` (guards a zero layout size → 1). */\nexport const viewScale = (el: HTMLElement): number => {\n const layout = el.clientWidth\n if (!layout) return 1\n const visual = el.getBoundingClientRect().width\n return visual > 0 ? visual / layout : 1\n}\n","// Image-source resolution, shared by every Host. The authoring layer (worker) hands an image `src`\n// (or `backgroundImage`) as one of: a string url, an inline `SvgSource` ({ svg }), or a host buffer\n// handle ({ _id } — an SDK `FetchResponse`/`File`, both carrying the buffer id under `_id`). A raw\n// DOM `File` is a separate, browser-embed-only case. Only the string case is platform-free; the rest\n// need a host-provided URL (asset bytes / object URL), so each Host wires those callbacks in.\n\n/** An inline SVG source (`SvgSource(...)` in the worker). */\nexport function isSvgSource(src: unknown): src is { svg: string } {\n return typeof src === \"object\" && src !== null && \"svg\" in (src as Record<string, unknown>)\n}\n\n/** A host buffer handle: an SDK `FetchResponse` / `File` / uploaded asset, keyed by its buffer id.\n * Checked BEFORE isFileLike — an SDK `File` is a plain object with `_id`, not a DOM File. */\nfunction hasId(src: unknown): src is { _id: number } {\n return typeof src === \"object\" && src !== null && \"_id\" in (src as Record<string, unknown>)\n}\n\n/** A baked `_creatorCanvas` surface (UIImage(canvas)) — resolved to a texture via a CanvasSurfaceProvider. */\nfunction hasCanvasSurface(src: unknown): src is { canvasSurface: number } {\n return typeof src === \"object\" && src !== null && \"canvasSurface\" in (src as Record<string, unknown>)\n}\n\n/** Synthetic url a `{ canvasSurface }` src resolves to; the host turns it back into a baked surface. */\nexport const CANVAS_SRC_PREFIX = \"lecodes-canvas://\"\n/** Parse a `lecodes-canvas://N` url back to its surface id, or undefined. */\nexport function canvasSurfaceId(src: string): number | undefined {\n return src.startsWith(CANVAS_SRC_PREFIX) ? Number(src.slice(CANVAS_SRC_PREFIX.length)) : undefined\n}\n\n/** A raw DOM `File` — only ever reaches here from a browser embed handing one in directly. The SDK's\n * `File` is NOT one of these: it's a `{ _id, name, size }` buffer handle caught by hasId above. */\nfunction isFileLike(src: unknown): boolean {\n return typeof File !== \"undefined\" && src instanceof File\n}\n\n/** Inline SVG → a `data:image/svg+xml` URI an `<img>` / decoder can load (mirrors the DOM viewer). */\nexport function svgToDataUri(svg: string): string {\n let s = svg.trim()\n // A data: URI is parsed as a standalone XML document — xmlns is mandatory there (inline DOM <svg>\n // tolerates its absence; a data-uri image without it renders broken).\n if (!/\\sxmlns\\s*=/.test(s)) s = s.replace(/<svg\\b/, '<svg xmlns=\"http://www.w3.org/2000/svg\"')\n const bytes = new TextEncoder().encode(s)\n let binary = \"\"\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return `data:image/svg+xml;base64,${btoa(binary)}`\n}\n\n/** True if a *resolved* src is an SVG (data-uri or `.svg` url) — i.e. a mask-capable, tintable image.\n * Used to gate `tintColor`: SVG recolors (mask), an opaque raster does not (the DOM no-ops it). */\nexport function isSvgLikeSrc(src: string | undefined): boolean {\n return !!src && (src.startsWith(\"data:image/svg+xml\") || /\\.svg(\\?|#|$)/i.test(src))\n}\n\n/**\n * Intrinsic size of an inline SVG, taken from its `viewBox` (\"min-x min-y width height\"), or its\n * `<svg>` width/height attributes, or null. SVG is a vector, so this is the size to lay out at (and\n * it may upscale). Matches the DOM, which reads the viewBox into `data-viewbox` for measuring.\n */\nexport function extractSvgViewBox(svg: string): { width: number; height: number } | null {\n // Only read the opening <svg> tag, so child element width/height never leak in.\n const tag = svg.match(/<svg\\b[^>]*>/i)?.[0] ?? \"\"\n const vb = tag.match(/viewBox\\s*=\\s*[\"']\\s*[\\d.+-]+\\s+[\\d.+-]+\\s+([\\d.+-]+)\\s+([\\d.+-]+)\\s*[\"']/i)\n if (vb) {\n const w = parseFloat(vb[1]), h = parseFloat(vb[2])\n if (w > 0 && h > 0) return { width: w, height: h }\n }\n const w = parseFloat(tag.match(/\\bwidth\\s*=\\s*[\"']?([\\d.]+)/i)?.[1] ?? \"\")\n const h = parseFloat(tag.match(/\\bheight\\s*=\\s*[\"']?([\\d.]+)/i)?.[1] ?? \"\")\n if (w > 0 && h > 0) return { width: w, height: h }\n return null\n}\n\n/** Decode an `data:image/svg+xml` URI (base64 or text/url-encoded) back to its markup, or null. */\nexport function decodeSvgDataUri(src: string): string | null {\n const m = /^data:image\\/svg\\+xml(;[^,]*)?,([\\s\\S]*)$/.exec(src)\n if (!m) return null\n const data = m[2]\n try {\n if (/;base64/i.test(m[1] ?? \"\")) {\n const bin = atob(data)\n const bytes = new Uint8Array(bin.length)\n for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)\n return new TextDecoder().decode(bytes)\n }\n return decodeURIComponent(data)\n } catch {\n return null\n }\n}\n\n/**\n * The intrinsic (viewBox) size of an SVG from its resolved src. SVGs without explicit width/height\n * have NO intrinsic size, so a browser `<img>` reports the CSS default 300×150 — wrong for layout +\n * object-fit. Reading the viewBox instead makes canvas/native size SVGs to their box like the DOM\n * does. Inline data-uris are decoded synchronously; a remote/blob `.svg` url needs `fetchText`.\n */\nexport async function svgIntrinsicSize(\n src: string,\n fetchText?: (url: string) => Promise<string | null>,\n): Promise<{ width: number; height: number } | null> {\n if (!isSvgLikeSrc(src)) return null\n const inline = decodeSvgDataUri(src)\n if (inline) return extractSvgViewBox(inline)\n if (!fetchText) return null\n const text = await fetchText(src).catch(() => null)\n return text ? extractSvgViewBox(text) : null\n}\n\nexport interface SrcResolverOptions {\n /** Resolve a host buffer handle ({ _id } — SDK `FetchResponse` / `File`) to a url (e.g. a blob url\n * for the fetched bytes). */\n assetUrl?: (id: number) => string | undefined\n /** Resolve a raw DOM `File` to a url (browser: `URL.createObjectURL`). Not the SDK `File` — that\n * one is a buffer handle and goes through `assetUrl`. */\n fileUrl?: (file: unknown) => string | undefined\n}\n\n/**\n * Build a memoized `resolveSrc(rawSrc) → string | undefined`. Strings pass through; `SvgSource` →\n * data-uri; `{ _id }` (SDK `FetchResponse`/`File`) and a raw DOM `File` go through the injected\n * callbacks (undefined when not wired, e.g. headless). Memoized by object identity so SVG\n * data-uris / blob urls are created once per source.\n */\nexport function createSrcResolver(opts: SrcResolverOptions = {}): (src: unknown) => string | undefined {\n const cache = new WeakMap<object, string>()\n return (src: unknown): string | undefined => {\n if (src == null) return undefined\n if (typeof src === \"string\") return src\n if (typeof src !== \"object\") return undefined\n const obj = src as object\n const cached = cache.get(obj)\n if (cached !== undefined) return cached\n let out: string | undefined\n if (isSvgSource(obj)) out = svgToDataUri(obj.svg)\n else if (hasCanvasSurface(obj)) out = CANVAS_SRC_PREFIX + obj.canvasSurface\n else if (hasId(obj)) out = opts.assetUrl?.(obj._id)\n else if (isFileLike(obj)) out = opts.fileUrl?.(obj)\n if (out !== undefined) cache.set(obj, out)\n return out\n }\n}\n","import type { ImageInfo } from \"../types\"\nimport { canvasSurfaceId } from \"../core/util/svgSrc\"\n\n/**\n * Access to baked `_creatorCanvas` surfaces, so a `UIImage(canvas)` resolves to a texture. `canvas` is\n * a drawable the painter can `drawImage` (an OffscreenCanvas on web, a napi canvas headless); width/\n * height are the surface's device pixels. Injected into a Host so it can turn a `lecodes-canvas://N`\n * src into an ImageInfo.\n */\nexport interface CanvasSurfaceProvider {\n getSurface(surfaceId: number): { canvas: unknown, width: number, height: number } | null\n}\n\n/** If `src` is a `lecodes-canvas://N` url, resolve it to an ImageInfo via the provider (the baked\n * surface is already rasterized → synchronous). Returns undefined for any other src. */\nexport function resolveCanvasImage(src: string, provider: CanvasSurfaceProvider | undefined): ImageInfo | undefined {\n if (!provider) return undefined\n const id = canvasSurfaceId(src)\n if (id === undefined) return undefined\n const surf = provider.getSurface(id)\n if (!surf) return undefined\n return { src, naturalWidth: surf.width, naturalHeight: surf.height, handle: surf.canvas }\n}\n\n/** A fully-resolved font, as the core asks the host to measure it. */\nexport interface FontSpec {\n family: string\n size: number\n weight: number\n italic: boolean\n letterSpacing: number\n}\n\n/**\n * Platform capabilities the portable core can't implement itself. Injected so the core runs\n * headless under Bun (HeadlessHost) and in the browser (BrowserHost) unchanged.\n */\nexport interface Host {\n /** Advance width of a single line of text, in CSS pixels. */\n measureText(text: string, font: FontSpec): number\n\n /** Vertical metrics for a font (used for line-height fallback and the text baseline). */\n fontMetrics(font: FontSpec): { ascent: number; descent: number }\n\n /**\n * Synchronous cache lookup for an image's intrinsic size. Returns undefined until the image is\n * decoded — the core then measures it as 0×0 (collapsed), exactly like the DOM renderer before\n * `naturalWidth` is known.\n */\n getImage(src: string): ImageInfo | undefined\n\n /**\n * Begin (or reuse) an async decode. Resolves with the intrinsic size; the caller marks the\n * owning screen dirty so the next render picks up the now-known size. May resolve synchronously\n * via the cache in HeadlessHost.\n */\n loadImage(src: string): Promise<ImageInfo>\n\n /**\n * Load a custom font so subsequent `measureText`/painting use it. Web: `FontFace`; headless:\n * disk/network bytes into the canvas backend (NodeCanvasHost) or a no-op (synthetic metrics);\n * desktop: a tgfx typeface load. Resolves once the font is usable (or has fallen back).\n */\n loadFont(family: string, url: string, options: { weight?: number; style?: string }): Promise<void>\n\n /** Preferred CDN face container (`_creatorUI.fontFormat`): browser hosts \"woff2\"; absent = ttf. */\n fontFormat?: \"woff2\" | \"ttf\"\n\n /**\n * Map a style-level fontFamily to what this host's text stack can actually resolve — the CSS\n * generic families, mostly: browser hosts alias the SDK's \"monospaced\" to the CSS keyword\n * \"monospace\"; headless pins every generic to a vendored concrete face (genericFamilies.ts),\n * because Skia has no generic resolution. Applied by paintTree when building a FontSpec; hosts\n * also apply it inside their own measureText/fontMetrics so layout and paint always agree.\n */\n resolveFontFamily?(family: string): string\n\n /**\n * Resolve an authoring image source to a loadable url string, or undefined if it can't be. The\n * source is a string url, an inline `SvgSource` ({ svg }), an uploaded asset ({ _id }), or a\n * `File`. String + SVG are platform-free; `{ _id }`/`File` need platform url resolution, which only\n * some hosts wire (e.g. the browser host with the app's asset resolver). Memoized per source.\n */\n resolveSrc(src: unknown): string | undefined\n}\n","import type { ImageInfo } from \"../types\"\nimport { resolveCanvasImage, type CanvasSurfaceProvider, type FontSpec, type Host } from \"./Host\"\nimport { createSrcResolver, isSvgLikeSrc, svgIntrinsicSize } from \"../core/util/svgSrc\"\n\n// The SDK spells the fixed-width system family \"monospaced\" (the iOS name); CSS spells it\n// \"monospace\". Other generics (\"serif\", \"sans-serif\") are real CSS keywords and resolve natively.\nconst cssFamily = (family: string) => (family === \"monospaced\" ? \"monospace\" : family)\n\nfunction fontCss(font: FontSpec): string {\n return `${font.italic ? \"italic \" : \"\"}${font.weight} ${font.size}px ${cssFamily(font.family)}`\n}\n\nexport interface BrowserHostOptions {\n /** Resolve an uploaded asset ({ _id }) to a url — the app injects this (e.g. the viewer's\n * `getUrl(id)` blob-url resolver). Without it, `{ _id }` image sources don't render. */\n resolveAssetUrl?: (id: number) => string | undefined\n /** Resolve `UIImage(canvas)` sources (baked `_creatorCanvas` surfaces) to textures. */\n canvasSurfaces?: CanvasSurfaceProvider\n}\n\n/** Browser host: text metrics via a measuring 2D context, image decode via HTMLImageElement. */\nexport class BrowserHost implements Host {\n private ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D\n private images = new Map<string, ImageInfo>()\n private pending = new Map<string, Promise<ImageInfo>>()\n private resolver: (src: unknown) => string | undefined\n private canvasSurfaces?: CanvasSurfaceProvider\n\n constructor(opts: BrowserHostOptions = {}) {\n // Measure on a DOM canvas whenever a document exists: a main-thread OffscreenCanvas context\n // does not reliably resolve document.fonts faces in every browser (Safari), which would keep\n // measuring custom faces with the fallback while the visible canvas paints the real one.\n // OffscreenCanvas stays for workers, where there is no document.\n const canvas =\n typeof document !== \"undefined\"\n ? (document.createElement(\"canvas\") as HTMLCanvasElement)\n : new OffscreenCanvas(8, 8)\n this.ctx = (canvas as any).getContext(\"2d\")\n this.canvasSurfaces = opts.canvasSurfaces\n // Inline SVG → data-uri; uploaded assets via the app's resolver; File → object url.\n this.resolver = createSrcResolver({\n assetUrl: opts.resolveAssetUrl,\n fileUrl: (file) => URL.createObjectURL(file as File),\n })\n }\n\n resolveSrc(src: unknown): string | undefined {\n return this.resolver(src)\n }\n\n /** Image decodes still in flight — lets a host idle its paint loop until they land (the\n * headless NodeCanvasHost exposes the same probe). */\n pendingImages(): number {\n return this.pending.size\n }\n\n resolveFontFamily(family: string): string {\n return cssFamily(family)\n }\n\n measureText(text: string, font: FontSpec): number {\n this.ctx.font = fontCss(font)\n ;(this.ctx as any).letterSpacing = `${font.letterSpacing}px`\n return this.ctx.measureText(text).width\n }\n\n fontMetrics(font: FontSpec) {\n this.ctx.font = fontCss(font)\n const m = this.ctx.measureText(\"Mg\")\n // The FONT's ascent/descent — the metrics CSS line-box layout centers inside line-height.\n // The ink extent (actualBoundingBox of the sample glyphs) is smaller, which would place the\n // baseline ~1px higher than the DOM/native render of the same text.\n const ascent = m.fontBoundingBoxAscent || m.actualBoundingBoxAscent || font.size * 0.8\n const descent = m.fontBoundingBoxDescent || m.actualBoundingBoxDescent || font.size * 0.2\n return { ascent, descent }\n }\n\n getImage(src: string): ImageInfo | undefined {\n return resolveCanvasImage(src, this.canvasSurfaces) ?? this.images.get(src)\n }\n\n loadImage(src: string): Promise<ImageInfo> {\n const canvasImg = resolveCanvasImage(src, this.canvasSurfaces)\n if (canvasImg) return Promise.resolve(canvasImg) // baked surface — already rasterized, no decode\n const cached = this.images.get(src)\n if (cached) return Promise.resolve(cached)\n const inFlight = this.pending.get(src)\n if (inFlight) return inFlight\n\n const promise = (async (): Promise<ImageInfo> => {\n const img = await this.decode(src)\n let naturalWidth = img.naturalWidth\n let naturalHeight = img.naturalHeight\n // A browser gives a viewBox-only SVG the CSS default 300×150 intrinsic size, which breaks layout\n // + object-fit (the icon won't size to its box). Use the real viewBox instead — matching the DOM\n // (which reads the viewBox) and the native renderers.\n if (isSvgLikeSrc(src)) {\n const vb = await svgIntrinsicSize(src, (url) => fetch(url).then((r) => (r.ok ? r.text() : null)))\n if (vb) { naturalWidth = vb.width; naturalHeight = vb.height }\n }\n const info: ImageInfo = { src, naturalWidth, naturalHeight, handle: img }\n this.images.set(src, info)\n this.pending.delete(src)\n return info\n })()\n this.pending.set(src, promise)\n promise.catch(() => this.pending.delete(src)) // a decode failure must clear the in-flight slot\n return promise\n }\n\n /** Decode an image url into an HTMLImageElement (resolves on load, rejects on error). */\n private decode(src: string): Promise<HTMLImageElement> {\n return new Promise((resolve, reject) => {\n const img = new Image()\n img.onload = () => resolve(img)\n img.onerror = (e) => reject(e)\n img.src = src\n })\n }\n\n // Browser host: CDN faces should come as woff2 (the font() macro's generated code reads this).\n fontFormat = \"woff2\" as const\n\n async loadFont(family: string, url: string, options: { weight?: number; style?: string }): Promise<void> {\n if (typeof (globalThis as any).FontFace === \"undefined\") return\n const face = new FontFace(family, `url(${url})`, options as FontFaceDescriptors)\n // Added before load resolves: text swaps in the moment the bytes land, whether or not\n // anything awaits the legacy completion callback (Renderer purges wrap caches on resolve).\n ;(document as any).fonts.add(face)\n await face.load()\n }\n}\n","import type { RGBA } from \"../../types\"\n\nexport interface RGBAChannels {\n r: number\n g: number\n b: number\n a: number\n}\n\n/** Unpack a 0xRRGGBBAA color into channels (a in 0..255). */\nexport function unpackRGBA(v: RGBA): RGBAChannels {\n const u = v >>> 0\n return { r: (u >>> 24) & 0xff, g: (u >>> 16) & 0xff, b: (u >>> 8) & 0xff, a: u & 0xff }\n}\n\n/** 0xRRGGBBAA → \"#rrggbbaa\" (lowercase), the readable form used in the JSON output. */\nexport function rgbaToHex(v: RGBA): string {\n return \"#\" + (v >>> 0).toString(16).padStart(8, \"0\")\n}\n\n/** 0xRRGGBBAA → a CSS/canvas \"rgba(r, g, b, a)\" string. */\nexport function rgbaToCss(v: RGBA): string {\n const { r, g, b, a } = unpackRGBA(v)\n return `rgba(${r}, ${g}, ${b}, ${(a / 255).toFixed(4)})`\n}\n\n/** True if the color is fully transparent (skip painting). */\nexport function isTransparent(v: RGBA | undefined): boolean {\n return v === undefined || (v >>> 0 & 0xff) === 0\n}\n","import type { BorderRadius, RadialGradient, Rect } from \"../../types\"\n\n/** Clamp the corner radii so opposite corners never overlap (CSS behavior). */\nexport function clampRadius(radius: BorderRadius | undefined, rect: Rect): BorderRadius | undefined {\n if (!radius) return undefined\n const max = Math.min(rect.width, rect.height) / 2\n return {\n tl: Math.min(radius.tl, max),\n tr: Math.min(radius.tr, max),\n br: Math.min(radius.br, max),\n bl: Math.min(radius.bl, max),\n }\n}\n\nexport function hasRadius(radius: BorderRadius | undefined): boolean {\n return !!radius && (radius.tl > 0 || radius.tr > 0 || radius.br > 0 || radius.bl > 0)\n}\n\n/**\n * Resolve object-fit into source (image px) + destination (screen px) rects, ready for a canvas\n * drawImage(src.x, src.y, src.w, src.h, dst.x, dst.y, dst.w, dst.h).\n */\nexport function computeObjectFit(\n naturalWidth: number,\n naturalHeight: number,\n box: Rect,\n fit: \"cover\" | \"contain\" | \"fill\",\n): { src: Rect; dst: Rect } {\n const full: Rect = { x: 0, y: 0, width: naturalWidth, height: naturalHeight }\n if (fit === \"fill\" || naturalWidth === 0 || naturalHeight === 0) {\n return { src: full, dst: box }\n }\n\n if (fit === \"cover\") {\n // Crop the image so it fills the box without distortion.\n const scale = Math.max(box.width / naturalWidth, box.height / naturalHeight)\n const sw = box.width / scale\n const sh = box.height / scale\n return {\n src: { x: (naturalWidth - sw) / 2, y: (naturalHeight - sh) / 2, width: sw, height: sh },\n dst: box,\n }\n }\n\n // contain: scale to fit inside, centered.\n const scale = Math.min(box.width / naturalWidth, box.height / naturalHeight)\n const dw = naturalWidth * scale\n const dh = naturalHeight * scale\n return {\n src: full,\n dst: { x: box.x + (box.width - dw) / 2, y: box.y + (box.height - dh) / 2, width: dw, height: dh },\n }\n}\n\n/**\n * Resolve a CSS gradient angle (0 = to top, 90 = to right, clockwise) into a gradient line through a\n * rect (start = 0%, end = 100%), using the standard CSS endpoint projection.\n */\nexport function gradientLine(angle: number, rect: Rect) {\n const rad = (angle * Math.PI) / 180\n const dx = Math.sin(rad)\n const dy = -Math.cos(rad)\n const cx = rect.x + rect.width / 2\n const cy = rect.y + rect.height / 2\n const halfLen = (Math.abs(rect.width * dx) + Math.abs(rect.height * dy)) / 2\n return {\n x0: cx - dx * halfLen,\n y0: cy - dy * halfLen,\n x1: cx + dx * halfLen,\n y1: cy + dy * halfLen,\n }\n}\n\n/**\n * Resolve a radial gradient's CSS geometry against a rect: the center (absolute px) and the two\n * semi-axes `rx`/`ry` (px) of the ending ellipse. Implements the CSS extent keywords; a `circle`\n * uses a single radius (equal axes). For the corner extents an ellipse keeps the matching side\n * ellipse's aspect ratio and passes through that corner (the √2 factor for an axis-aligned box).\n */\nexport function radialGeometry(g: RadialGradient, rect: Rect) {\n const cx = rect.x + g.cx * rect.width\n const cy = rect.y + g.cy * rect.height\n\n // Explicit radii: px used directly, a \"fraction\" (from a % radius) resolves against the box axis.\n if (g.extent === \"explicit\") {\n const rx = g.rxUnit === \"fraction\" ? (g.rx ?? 0) * rect.width : (g.rx ?? 0)\n const ry = g.ryUnit === \"fraction\" ? (g.ry ?? 0) * rect.height : (g.ry ?? 0)\n return { cx, cy, rx, ry }\n }\n\n // distances from the center to each side\n const left = g.cx * rect.width\n const right = (1 - g.cx) * rect.width\n const top = g.cy * rect.height\n const bottom = (1 - g.cy) * rect.height\n const nearX = Math.min(left, right)\n const farX = Math.max(left, right)\n const nearY = Math.min(top, bottom)\n const farY = Math.max(top, bottom)\n\n let rx: number\n let ry: number\n if (g.shape === \"circle\") {\n let r: number\n switch (g.extent) {\n case \"closest-side\": r = Math.min(nearX, nearY); break\n case \"farthest-side\": r = Math.max(farX, farY); break\n case \"closest-corner\": r = Math.hypot(nearX, nearY); break\n default: r = Math.hypot(farX, farY); break // farthest-corner\n }\n rx = ry = r\n } else {\n switch (g.extent) {\n case \"closest-side\": rx = nearX; ry = nearY; break\n case \"farthest-side\": rx = farX; ry = farY; break\n case \"closest-corner\": rx = nearX * Math.SQRT2; ry = nearY * Math.SQRT2; break\n default: rx = farX * Math.SQRT2; ry = farY * Math.SQRT2; break // farthest-corner\n }\n }\n return { cx, cy, rx, ry }\n}\n","import type { BorderRadius, Gradient, ImageInfo, RadialGradient, Rect, RGBA } from \"../types\"\nimport type { FontSpec } from \"../host/Host\"\nimport type { Borders, DrawImageOpts, Painter } from \"./Painter\"\nimport { rgbaToCss } from \"../core/util/colors\"\nimport { clampRadius, computeObjectFit, gradientLine, radialGeometry } from \"../core/util/geometry\"\n\n/** Painter backend over a CanvasRenderingContext2D (browser). */\ntype AnyCtx = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D\n\nexport class Canvas2DPainter implements Painter {\n private ctx: AnyCtx\n private dpr: number\n // Stack of in-progress opacity groups: each captures the parent ctx + an offscreen layer + alpha.\n private groups: { parent: AnyCtx; layer: HTMLCanvasElement | OffscreenCanvas; alpha: number }[] = []\n\n constructor(ctx: CanvasRenderingContext2D, dpr = 1) {\n this.ctx = ctx\n this.dpr = dpr\n }\n\n beginGroup(alpha: number) {\n const cur = this.ctx\n const w = (cur.canvas as HTMLCanvasElement | OffscreenCanvas).width\n const h = (cur.canvas as HTMLCanvasElement | OffscreenCanvas).height\n let layer: HTMLCanvasElement | OffscreenCanvas\n if (typeof OffscreenCanvas !== \"undefined\") {\n layer = new OffscreenCanvas(w, h)\n } else {\n layer = document.createElement(\"canvas\")\n layer.width = w\n layer.height = h\n }\n const lctx = (layer as any).getContext(\"2d\") as AnyCtx\n lctx.setTransform(cur.getTransform()) // paint the subtree in the same coordinate space\n this.groups.push({ parent: cur, layer, alpha })\n this.ctx = lctx\n }\n\n endGroup() {\n const g = this.groups.pop()\n if (!g) return\n this.ctx = g.parent\n this.ctx.save()\n this.ctx.setTransform(1, 0, 0, 1, 0, 0) // composite the layer in device pixels\n this.ctx.globalAlpha *= g.alpha\n this.ctx.drawImage(g.layer as CanvasImageSource, 0, 0)\n this.ctx.restore()\n }\n\n beginFrame(width: number, height: number) {\n const { ctx, dpr } = this\n ctx.setTransform(dpr, 0, 0, dpr, 0, 0)\n ctx.clearRect(0, 0, width, height)\n ctx.globalAlpha = 1\n }\n endFrame() {}\n\n save() {\n this.ctx.save()\n }\n restore() {\n this.ctx.restore()\n }\n setAlpha(multiplier: number) {\n this.ctx.globalAlpha *= multiplier\n }\n translate(x: number, y: number) {\n this.ctx.translate(x, y)\n }\n scale(sx: number, sy: number) {\n this.ctx.scale(sx, sy)\n }\n transform(a: number, b: number, c: number, d: number, e: number, f: number) {\n this.ctx.transform(a, b, c, d, e, f)\n }\n\n /** Append a (rounded) rect sub-path to the current path — no beginPath, so callers can build\n * multi-subpath paths (e.g. an even-odd ring). */\n private addRectPath(rect: Rect, radius?: BorderRadius) {\n const ctx = this.ctx\n if (radius && (radius.tl || radius.tr || radius.br || radius.bl)) {\n ctx.roundRect(rect.x, rect.y, rect.width, rect.height, [radius.tl, radius.tr, radius.br, radius.bl])\n } else {\n ctx.rect(rect.x, rect.y, rect.width, rect.height)\n }\n }\n\n private path(rect: Rect, radius?: BorderRadius) {\n this.ctx.beginPath()\n this.addRectPath(rect, radius)\n }\n\n clipRoundRect(rect: Rect, radius?: BorderRadius) {\n this.path(rect, radius)\n this.ctx.clip()\n }\n\n fillRoundRect(rect: Rect, radius: BorderRadius | undefined, color: RGBA) {\n this.path(rect, radius)\n this.ctx.fillStyle = rgbaToCss(color)\n this.ctx.fill()\n }\n\n clearRoundRect(rect: Rect, radius: BorderRadius | undefined) {\n const ctx = this.ctx\n ctx.save()\n ctx.globalCompositeOperation = \"destination-out\"\n ctx.globalAlpha = 1\n this.path(rect, radius)\n ctx.fillStyle = \"#000\"\n ctx.fill()\n ctx.restore()\n }\n\n fillGradient(rect: Rect, radius: BorderRadius | undefined, gradient: Gradient) {\n if (gradient.type === \"radial\") {\n this.fillRadial(rect, radius, gradient)\n return\n }\n const { x0, y0, x1, y1 } = gradientLine(gradient.angle, rect)\n const grad = this.ctx.createLinearGradient(x0, y0, x1, y1)\n for (const stop of gradient.stops) grad.addColorStop(Math.max(0, Math.min(1, stop.position)), rgbaToCss(stop.color))\n this.path(rect, radius)\n this.ctx.fillStyle = grad\n this.ctx.fill()\n }\n\n private fillRadial(rect: Rect, radius: BorderRadius | undefined, gradient: RadialGradient) {\n const { cx, cy, rx, ry } = radialGeometry(gradient, rect)\n const ctx = this.ctx\n // createRadialGradient only makes circles; scale the context anisotropically so a unit-radius\n // circle becomes the rx×ry ellipse. Clip to the (rounded) rect first — the clip is captured in\n // the pre-scale space, so it stays put while we paint the ellipse in the scaled space.\n const sx = rx || 1e-6\n const sy = ry || 1e-6\n ctx.save()\n this.path(rect, radius)\n ctx.clip()\n ctx.translate(cx, cy)\n ctx.scale(sx, sy)\n const grad = ctx.createRadialGradient(0, 0, 0, 0, 0, 1)\n for (const stop of gradient.stops) grad.addColorStop(Math.max(0, Math.min(1, stop.position)), rgbaToCss(stop.color))\n ctx.fillStyle = grad\n // Cover the whole clipped rect in the scaled coordinate space (canvas extends the last stop\n // outward, so pixels past the ellipse edge get the final color, matching CSS).\n const u0 = (rect.x - cx) / sx\n const u1 = (rect.x + rect.width - cx) / sx\n const v0 = (rect.y - cy) / sy\n const v1 = (rect.y + rect.height - cy) / sy\n ctx.fillRect(u0, v0, u1 - u0, v1 - v0)\n ctx.restore()\n }\n\n strokeBorder(rect: Rect, radius: BorderRadius | undefined, sides: Borders) {\n const ctx = this.ctx\n const present = ([\"top\", \"right\", \"bottom\", \"left\"] as const).filter((s) => sides[s])\n const uniform =\n present.length === 4 &&\n present.every((s) => sides[s]!.width === sides.top!.width && sides[s]!.color === sides.top!.color)\n\n if (uniform) {\n const w = sides.top!.width\n // Border-box: the border lies fully INSIDE rect. Fill the ring between the outer rounded-rect\n // and an inner rounded-rect inset by the border width (inner corner radius = outer − w), as an\n // even-odd fill. We do NOT use a centred ctx.stroke(): a stroke straddles the path (half would\n // sit outside the box), and the inset-path trick relied on roundRect clamping its radius — which\n // @napi-rs/canvas (skia) does differently than browsers, so the border leaked outside the box.\n const outer = clampRadius(radius, rect)\n ctx.beginPath()\n this.addRectPath(rect, outer)\n const inner: Rect = { x: rect.x + w, y: rect.y + w, width: rect.width - 2 * w, height: rect.height - 2 * w }\n if (inner.width > 0 && inner.height > 0) {\n const innerRadius = outer && clampRadius(\n {\n tl: Math.max(0, outer.tl - w), tr: Math.max(0, outer.tr - w),\n br: Math.max(0, outer.br - w), bl: Math.max(0, outer.bl - w),\n },\n inner,\n )\n this.addRectPath(inner, innerRadius || undefined)\n }\n ctx.fillStyle = rgbaToCss(sides.top!.color)\n ctx.fill(\"evenodd\")\n return\n }\n\n // Per-side fallback: straight edges (radius ignored for mismatched borders).\n for (const s of present) {\n const { width, color } = sides[s]!\n ctx.fillStyle = rgbaToCss(color)\n if (s === \"top\") ctx.fillRect(rect.x, rect.y, rect.width, width)\n else if (s === \"bottom\") ctx.fillRect(rect.x, rect.y + rect.height - width, rect.width, width)\n else if (s === \"left\") ctx.fillRect(rect.x, rect.y, width, rect.height)\n else ctx.fillRect(rect.x + rect.width - width, rect.y, width, rect.height)\n }\n }\n\n private scratch?: OffscreenCanvas | HTMLCanvasElement\n private scratchCtx?: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D\n private getScratch(w: number, h: number) {\n if (!this.scratch) {\n this.scratch = typeof OffscreenCanvas !== \"undefined\" ? new OffscreenCanvas(w, h) : document.createElement(\"canvas\")\n this.scratchCtx = (this.scratch as any).getContext(\"2d\")\n }\n if (this.scratch.width < w || this.scratch.height < h) {\n this.scratch.width = Math.max(this.scratch.width, w)\n this.scratch.height = Math.max(this.scratch.height, h)\n }\n return this.scratchCtx!\n }\n\n drawImage(image: ImageInfo, srcRect: Rect | null, dst: Rect, opts: DrawImageOpts) {\n if (!image.handle) return\n // An explicit crop fills the box; otherwise resolve object-fit.\n const { src, dst: d } = srcRect\n ? { src: srcRect, dst }\n : computeObjectFit(image.naturalWidth, image.naturalHeight, dst, opts.fit)\n // The destination in DEVICE pixels: what a vector source rasterizes at, and the tint scratch's\n // size — the frame is painted under the dpr transform, so a CSS-px scratch would be upscaled.\n const dw = Math.max(1, Math.ceil(d.width * this.dpr))\n const dh = Math.max(1, Math.ceil(d.height * this.dpr))\n const handle = (image.rasterize ? image.rasterize(dw, dh) : image.handle) as CanvasImageSource\n\n // When we're drawing the WHOLE image (no atlas crop, not a cover-crop) draw it WITHOUT a source\n // rect. A viewBox-only SVG `<img>` has the browser's default 300×150 raster, so a source crop\n // (computed from the viewBox size) samples the wrong region and the icon vanishes — drawing the\n // whole image straight into the box lets the backend re-rasterize the SVG to fit (matches the DOM,\n // and keeps the working tinted/scratch path consistent with the direct path).\n const whole = !srcRect && opts.fit !== \"cover\"\n\n if (opts.tint === undefined) {\n if (whole) this.ctx.drawImage(handle, d.x, d.y, d.width, d.height)\n else this.ctx.drawImage(handle, src.x, src.y, src.width, src.height, d.x, d.y, d.width, d.height)\n return\n }\n // Tint on an offscreen so `source-in` only recolors the image pixels.\n const sc = this.getScratch(dw, dh)\n sc.clearRect(0, 0, dw, dh)\n sc.globalCompositeOperation = \"source-over\"\n if (whole) sc.drawImage(handle, 0, 0, dw, dh)\n else sc.drawImage(handle, src.x, src.y, src.width, src.height, 0, 0, dw, dh)\n sc.globalCompositeOperation = \"source-in\"\n sc.fillStyle = rgbaToCss(opts.tint)\n sc.fillRect(0, 0, dw, dh)\n sc.globalCompositeOperation = \"source-over\"\n this.ctx.drawImage(sc.canvas as CanvasImageSource, 0, 0, dw, dh, d.x, d.y, d.width, d.height)\n }\n\n fillText(text: string, x: number, baselineY: number, font: FontSpec, color: RGBA) {\n const ctx = this.ctx\n ctx.font = `${font.italic ? \"italic \" : \"\"}${font.weight} ${font.size}px ${font.family}`\n ctx.textBaseline = \"alphabetic\"\n ctx.textAlign = \"left\"\n if (\"letterSpacing\" in ctx) (ctx as any).letterSpacing = `${font.letterSpacing}px`\n ctx.fillStyle = rgbaToCss(color)\n ctx.fillText(text, x, baselineY)\n }\n}\n","\n// Slots are addressed by id (their original index) and are never spliced — disposing a single\n// player nulls its slot so every other id stays valid. `releasePlayer` does the actual teardown.\n// Slot 0 stays empty: id 0 is the SDK's dead handle (sdk/src/core/pins.ts DEAD_HANDLE), and a\n// player with that id would never get its end-of-playback report.\nconst players: (HTMLVideoElement | HTMLAudioElement | null)[] = [null]\n\n// Looping is driven manually rather than through the element's native `loop` flag: a natively\n// looping element never fires \"ended\", so we could not signal each loop boundary. Instead we keep\n// the desired loop state per player, listen for \"ended\", invoke the SDK's finished callback, and —\n// when looping — rewind and replay ourselves. `onFinished` lets the SDK decide loopReached vs\n// completed based on its own loop flag.\nconst loopFlags: boolean[] = [false]\n\nconst attachFinished = (\n player: HTMLVideoElement | HTMLAudioElement,\n id: number,\n onFinished: () => void\n) => {\n player.addEventListener(\"ended\", () => {\n onFinished()\n if (loopFlags[id]) {\n player.currentTime = 0\n player.play()\n }\n })\n}\n\nexport const createVideoPlayer = (src: string, onFinished: () => void) => {\n const player = document.createElement(\"video\")\n document.body.appendChild(player)\n player.crossOrigin = \"anonymous\"\n player.style = \"opacity: 0; position: absolute; top: 0; left: 0; width: 1px; height: 1px\"\n player.src = src\n player.playsInline = true\n player.controls = false\n const id = players.length\n players.push(player)\n loopFlags.push(false)\n attachFinished(player, id, onFinished)\n return id\n}\n\nexport const createAudioPlayer = (src: string, onFinished: () => void) => {\n const player = document.createElement(\"audio\")\n document.body.appendChild(player)\n player.style = \"opacity: 0; position: absolute; top: 0; left: 0; width: 1px; height: 1px\"\n player.src = src\n const id = players.length\n players.push(player)\n loopFlags.push(false)\n attachFinished(player, id, onFinished)\n return id\n}\n\nexport const updateMediaPlayerVolume = (id: number, volume: number) => {\n const player = players[id]\n if (!player) return\n if (volume === 0) {\n player.muted = true\n } else {\n if (player.muted) {\n player.muted = false\n }\n player.volume = volume\n }\n}\n\nexport const updateMediaPlayerPlaying = (id: number, play: boolean) => {\n const player = players[id]\n if (!player) return\n if (play){\n player.play()\n } else {\n player.pause()\n }\n}\n\nexport const updateMediaPlayerLoop = (id: number, loop: boolean) => {\n // Tracked for the \"ended\" handler; the native loop flag stays off so \"ended\" keeps firing.\n loopFlags[id] = loop\n}\n\nexport const getMediaPlayerTime = (id: number) => {\n return players[id]?.currentTime ?? 0\n}\n\nexport const setMediaPlayerTime = (id: number, time: number) => {\n const player = players[id]\n if (player) player.currentTime = time\n}\n\nexport const getMediaPlayerDuration = (id: number) => {\n // NaN before metadata loads — normalise to 0 so callers get a clean number.\n const duration = players[id]?.duration ?? 0\n return isNaN(duration) ? 0 : duration\n}\n\nexport const getPlayer = (id: number) => {\n return players[id]\n}\n\n// Tear down one element's media pipeline (decoder, buffering, network) and detach it from the DOM.\nconst releasePlayer = (player: HTMLVideoElement | HTMLAudioElement) => {\n // Removing the element from the DOM alone keeps the media pipeline alive. Pause, drop the source\n // and load() to release it before detaching.\n player.pause()\n player.removeAttribute(\"src\")\n player.load()\n player.remove()\n}\n\nexport const removeMediaPlayer = (id: number) => {\n const player = players[id]\n if (!player) return\n releasePlayer(player)\n // Null the slot rather than splice, so all other ids keep pointing at the right element.\n players[id] = null\n loopFlags[id] = false\n}\n\nexport const removePlayers = () => {\n for (let player of players) {\n if (player) releasePlayer(player)\n }\n players.length = 1 // keep the reserved slot 0\n loopFlags.length = 1\n}\n","// The SDK's side of the tree of truth (docs/plans/hosts-unification-plan.md, phase 9): the numbers shared\n// with runtime/native (creator-pkg/tree-events.h — mirrored VERBATIM, `bun run check:tree-consts`),\n// the pin table that keeps the element of every attached node alive and findable by id, the\n// destination registry, and the ONE emitter every event of `_creatorTree` comes through.\n//\n// Ownership (tree.h): an attached node belongs to the runtime's tree and its element is PINNED here\n// (so `children` returns the same objects and listeners survive the app dropping its reference); a\n// detached root belongs to its element — when that is collected, the handle's finalizer frees the\n// node. The runtime tells us when it detaches a root (TREE_EVENT_DETACHED) or frees nodes underneath\n// their handles (TREE_EVENT_FREED); everything else we pin / unpin ourselves.\n\n// ---- emit kinds (id = the node, 0 for world-level events) ----------------------------------------\nexport const TREE_EVENT_LAYOUT = 1\nexport const TREE_EVENT_TOUCH_START = 2\nexport const TREE_EVENT_CLICK = 3\nexport const TREE_EVENT_LONG_PRESS = 4\nexport const TREE_EVENT_TOUCH_MOVE = 5\nexport const TREE_EVENT_TOUCH_END = 6\nexport const TREE_EVENT_TOUCH_CANCEL = 7\nexport const TREE_EVENT_SCROLL = 8\nexport const TREE_EVENT_OVERSCROLL = 9\nexport const TREE_EVENT_SCROLL_RELEASE = 10\nexport const TREE_EVENT_REFRESH = 11\nexport const TREE_EVENT_CHANGE = 12\nexport const TREE_EVENT_FOCUS = 13\nexport const TREE_EVENT_BLUR = 14\nexport const TREE_EVENT_SUBMIT = 15\nexport const TREE_EVENT_OVERLAY_TAP = 16\nexport const TREE_EVENT_DETENT = 17\nexport const TREE_EVENT_OPEN = 18\nexport const TREE_EVENT_CLOSE = 19\nexport const TREE_EVENT_BACK = 20\nexport const TREE_EVENT_PAGER_SELECT = 21\nexport const TREE_EVENT_PAGER_POP = 22\nexport const TREE_EVENT_VLIST_SYNC = 23\nexport const TREE_EVENT_VLIST_EDGE = 24\nexport const TREE_EVENT_VIEW_EVENT = 25\nexport const TREE_EVENT_RESIZE = 26\nexport const TREE_EVENT_ROUTER_CHANGE = 27\nexport const TREE_EVENT_SCENE_TOUCH_START = 28\nexport const TREE_EVENT_SCENE_CLICK = 29\nexport const TREE_EVENT_DETACHED = 30\nexport const TREE_EVENT_FREED = 31\nexport const TREE_EVENT_HOVER_ENTER = 32\nexport const TREE_EVENT_HOVER_MOVE = 33\nexport const TREE_EVENT_HOVER_END = 34\nexport const TREE_EVENT_HOVER_CANCEL = 35\n\n// ---- setFlags(id, mask) ---------------------------------------------------------------------------\nexport const TREE_FLAG_INTERACTIVE = 1 << 0\nexport const TREE_FLAG_CLICK = 1 << 1\nexport const TREE_FLAG_LONG_PRESS = 1 << 2\nexport const TREE_FLAG_LAYOUT = 1 << 3\nexport const TREE_FLAG_SCROLL = 1 << 4\nexport const TREE_FLAG_OVERSCROLL = 1 << 5\nexport const TREE_FLAG_SCROLL_RELEASE = 1 << 6\nexport const TREE_FLAG_REFRESH = 1 << 7\nexport const TREE_FLAG_CHANGE = 1 << 8\nexport const TREE_FLAG_FOCUS = 1 << 9\nexport const TREE_FLAG_BLUR = 1 << 10\nexport const TREE_FLAG_SUBMIT = 1 << 11\nexport const TREE_FLAG_OVERLAY_TAP = 1 << 12\nexport const TREE_FLAG_DETENT = 1 << 13\nexport const TREE_FLAG_KEEP_ALIVE = 1 << 14\nexport const TREE_FLAG_BACK = 1 << 15\nexport const TREE_FLAG_VLIST_END = 1 << 16\nexport const TREE_FLAG_VLIST_START = 1 << 17\nexport const TREE_FLAG_HOVER = 1 << 18\n\n// ---- the touchStart / longPress answer -------------------------------------------------------------\nexport const TREE_TRACK_CLAIM_MASK = 0xFF\nexport const TREE_TRACK_TRACKED = 1 << 8\nexport const TREE_TRACK_MOVE = 1 << 9\nexport const TREE_TRACK_HANDLED = 1 << 10\n\n// ---- destination kinds -------------------------------------------------------------------------------\nexport const TREE_DEST_SCREEN = 0\nexport const TREE_DEST_SCENE3D = 1\nexport const TREE_DEST_SCENE2D = 2\nexport const TREE_DEST_NATIVE = 3\nexport const TREE_DEST_VIDEO = 4\nexport const TREE_DEST_NONE = 0xFF\n\n// Owned-handle kinds (owned.h OwnedKind) — the `_creatorApp.setFreedEmitter` channel names the kind\n// whose resources the runtime freed underneath their wrappers (core/pins.ts).\nexport const OWNED_KIND_TREE = 0\nexport const OWNED_KIND_FETCH = 1\nexport const OWNED_KIND_GL_MATERIAL = 2\nexport const OWNED_KIND_GL_TEXTURE = 3\nexport const OWNED_KIND_GL_ENTITY = 4\nexport const OWNED_KIND_ENTITY_2D = 5\nexport const OWNED_KIND_MEDIA = 6\nexport const OWNED_KIND_TWEEN = 7\nexport const OWNED_KIND_CANVAS = 8\n\n// PanDirection (creator-pkg.h) — the low byte of a track answer.\nimport { DEAD_HANDLE } from \"../core/pins\"\n\nconst PAN: Record<string, number> = { \"pan-up\": 1, \"pan-right\": 2, \"pan-down\": 4, \"pan-left\": 8, \"pan-x\": 10, \"pan-y\": 5 }\n\n// ---- the bridge ---------------------------------------------------------------------------------------\n/** @internal The tree bridge. Every host that runs bundles installs it before the bundle evaluates. */\nexport const tree = (): typeof _creatorTree => _creatorTree\n\n// ---- what an element / presentable must offer the emitter (duck-typed, all `_`-prefixed so chisel keeps them)\n/** @internal */\nexport interface TreeElement {\n /** The owned handle (`_h.id` = the node id; DEAD_HANDLE once the node is gone). */\n _h: Handle\n _emitLayout?(box: { left: number, top: number, width: number, height: number }): void\n _emitTouchStart?(pointerId: number, x: number, y: number): TrackLike | null\n _emitClick?(pointerId: number, x: number, y: number): void\n _emitLongPress?(pointerId: number, x: number, y: number): { track: TrackLike | null } | null\n _emitMouseEnter?(x: number, y: number): HoverTrackLike | null\n _emitScroll?(position: number): void\n _emitOverscroll?(delta: number): void\n _emitScrollRelease?(): void\n _emitRefresh?(): unknown\n _emitChange?(value: string): void\n _emitFocus?(): void\n _emitBlur?(): void\n _emitSubmit?(value: string): void\n _emitOverlayTap?(): void\n _emitDetent?(index: number): void\n _hostDidSelect?(index: number): void\n _hostDidPop?(depth: number): void\n _syncWindow?(unmountKeys: string[], mountKeys: string[]): void\n _emitEdge?(end: boolean): void\n _detached?(): void\n _freed?(): void\n /** The element's node got a native owner (it was inserted under a parent) / lost it. */\n _pinned?(): void\n _unpinned?(): void\n _emitBack?(): boolean\n}\n\n/** @internal A track handler (runtime/touch.ts TrackHandler), as the emitter reads it. */\nexport interface TrackLike {\n onMove?(pos: { clientX: number, clientY: number, deltaX: number, deltaY: number }): void\n onEnd?(pos: { clientX: number, clientY: number, deltaX: number, deltaY: number }): void\n onCancel?(): void\n claim?: boolean | string\n}\n/** @internal A hover track handler (runtime/touch.ts HoverTrackHandler): TrackLike without a claim. */\nexport type HoverTrackLike = Omit<TrackLike, \"claim\">\n\n/** @internal What a destination offers: the presentation lifecycle + the back handler. */\nexport interface TreeDest {\n _emitOpen?(): void\n _emitClose?(): void\n _emitBack?(): boolean\n}\n\nexport { DEAD_HANDLE }\n\n// ---- pins -------------------------------------------------------------------------------------------------\nconst pins = new Map<number, TreeElement>()\n\n/** @internal Keep `el` alive and findable while its node is attached / presented / shown. */\nexport const pin = (el: TreeElement | null | undefined): void => {\n if (!el || el._h.id === 0) return\n pins.set(el._h.id, el)\n el._pinned?.()\n}\n/** @internal */\nexport const unpin = (id: number): void => {\n const el = pins.get(id)\n if (!el) return\n pins.delete(id)\n el._unpinned?.()\n}\n/** @internal The pinned element of a node id (an attached node's element), or undefined. */\nexport const byId = (id: number): TreeElement | undefined => pins.get(id)\n/** @internal The elements of a list of ids (attached nodes only). */\nexport const elementsOf = (ids: number[]): any[] => {\n const out: any[] = []\n for (const id of ids) { const el = pins.get(id); if (el) out.push(el) }\n return out\n}\n\n// ---- destinations ------------------------------------------------------------------------------------------\n// Non-screen presentables (scenes, native views) register here under their engine id; screens and\n// video nodes resolve through the pins (their destination id IS the node id).\nconst dests = new Map<string, TreeDest>()\nconst destKey = (kind: number, id: number): string => `${kind}:${id}`\n\n/** @internal */\nexport const registerDest = (kind: number, id: number, p: TreeDest): void => { dests.set(destKey(kind, id), p) }\n/** @internal */\nexport const unregisterDest = (kind: number, id: number): void => { dests.delete(destKey(kind, id)) }\n/** @internal The presentable a (kind, id) pair names. */\nexport const resolveDest = (kind: number, id: number): (TreeDest & Partial<TreeElement>) | undefined => {\n if (kind === TREE_DEST_SCREEN || kind === TREE_DEST_VIDEO) return pins.get(id) as any\n return dests.get(destKey(kind, id)) as any\n}\n\n// ---- world-level hooks (set by the modules that own them) --------------------------------------------------\ntype SceneTouchStart = (pointerId: number, x: number, y: number, entityId: number) => TrackLike | null\ntype SceneClick = (pointerId: number, x: number, y: number, entityId: number) => void\nlet sceneTouchStart: SceneTouchStart | null = null\nlet sceneClick: SceneClick | null = null\n/** @internal gl/touch.ts: the scene-level pointer dispatch. */\nexport const setSceneTouchHandlers = (start: SceneTouchStart | null, click: SceneClick | null): void => {\n sceneTouchStart = start\n sceneClick = click\n}\n\nconst resizeListeners: ((width: number, height: number) => void)[] = []\n/** @internal runtime/device.ts */\nexport const onTreeResize = (cb: (width: number, height: number) => void): (() => void) => {\n resizeListeners.push(cb)\n return () => { const i = resizeListeners.indexOf(cb); if (i >= 0) resizeListeners.splice(i, 1) }\n}\n\nlet routerChange: ((kind: number, id: number) => void) | null = null\n/** @internal ui/router.ts */\nexport const setRouterChangeHandler = (cb: ((kind: number, id: number) => void) | null): void => { routerChange = cb }\n\nlet appBack: (() => void) | null = null\n/** @internal runtime/app.ts — the app-level back handler (the end of the runtime's back chain). */\nexport const setAppBackHandler = (cb: (() => void) | null): void => { appBack = cb }\n\nconst nativeViews = new Map<number, { _emitViewEvent(event: string, data?: unknown): void }>()\n/** @internal ui/NativeView.ts: the instance a viewId names (host → view events). */\nexport const registerNativeView = (viewId: number, v: { _emitViewEvent(event: string, data?: unknown): void }): void => { nativeViews.set(viewId, v) }\n/** @internal */\nexport const unregisterNativeView = (viewId: number): void => { nativeViews.delete(viewId) }\n\n// ---- gestures -----------------------------------------------------------------------------------------------\n// The track handler of every pointer a listener claimed (`ev.track(...)`): the runtime feeds the\n// pointer's moves / end / cancel here by pointer id — nothing of it is retained natively.\nconst trackers = new Map<number, TrackLike>()\n\n// The hover's own slot — the cursor is one, and it is NOT a gesture: a mouse drag keeps its touch\n// tracker under pointer 0 while the hover under the same cursor runs here, independently.\nlet hoverTracker: HoverTrackLike | null = null\n\nconst hoverAnswer = (handler: HoverTrackLike | null | undefined): number => {\n hoverTracker = handler ?? null\n if (!handler) return 0\n return TREE_TRACK_TRACKED | (handler.onMove ? TREE_TRACK_MOVE : 0)\n}\n\nconst trackAnswer = (pointerId: number, handler: TrackLike | null | undefined): number => {\n if (!handler) return 0\n trackers.set(pointerId, handler)\n let r = TREE_TRACK_TRACKED\n if (handler.onMove) r |= TREE_TRACK_MOVE\n const claim = handler.claim\n if (claim === true || claim === \"all\") r |= 15\n else if (typeof claim === \"string\") r |= PAN[claim] ?? 0\n return r\n}\n\n// ---- the emitter --------------------------------------------------------------------------------------------\nlet installed = false\nconst emit = (id: number, kind: number, a?: any, b?: any, c?: any, d?: any, e?: any): any => {\n switch (kind) {\n case TREE_EVENT_LAYOUT: pins.get(id)?._emitLayout?.({ left: a, top: b, width: c, height: d }); return\n case TREE_EVENT_TOUCH_START: return trackAnswer(a, pins.get(id)?._emitTouchStart?.(a, b, c))\n case TREE_EVENT_CLICK: pins.get(id)?._emitClick?.(a, b, c); return\n case TREE_EVENT_LONG_PRESS: {\n const r = pins.get(id)?._emitLongPress?.(a, b, c)\n if (!r) return 0\n return TREE_TRACK_HANDLED | trackAnswer(a, r.track)\n }\n case TREE_EVENT_TOUCH_MOVE: trackers.get(a)?.onMove?.({ clientX: b, clientY: c, deltaX: d, deltaY: e }); return\n case TREE_EVENT_TOUCH_END: {\n const t = trackers.get(a)\n trackers.delete(a)\n t?.onEnd?.({ clientX: b, clientY: c, deltaX: d, deltaY: e })\n return\n }\n case TREE_EVENT_TOUCH_CANCEL: {\n const t = trackers.get(a)\n trackers.delete(a)\n t?.onCancel?.()\n return\n }\n case TREE_EVENT_HOVER_ENTER: return hoverAnswer(pins.get(id)?._emitMouseEnter?.(a, b))\n case TREE_EVENT_HOVER_MOVE: hoverTracker?.onMove?.({ clientX: a, clientY: b, deltaX: c, deltaY: d }); return\n case TREE_EVENT_HOVER_END: {\n const t = hoverTracker\n hoverTracker = null\n t?.onEnd?.({ clientX: a, clientY: b, deltaX: c, deltaY: d })\n return\n }\n case TREE_EVENT_HOVER_CANCEL: {\n const t = hoverTracker\n hoverTracker = null\n t?.onCancel?.()\n return\n }\n case TREE_EVENT_SCROLL: pins.get(id)?._emitScroll?.(a); return\n case TREE_EVENT_OVERSCROLL: pins.get(id)?._emitOverscroll?.(a); return\n case TREE_EVENT_SCROLL_RELEASE: pins.get(id)?._emitScrollRelease?.(); return\n case TREE_EVENT_REFRESH: return pins.get(id)?._emitRefresh?.()\n case TREE_EVENT_CHANGE: pins.get(id)?._emitChange?.(a); return\n case TREE_EVENT_FOCUS: pins.get(id)?._emitFocus?.(); return\n case TREE_EVENT_BLUR: pins.get(id)?._emitBlur?.(); return\n case TREE_EVENT_SUBMIT: pins.get(id)?._emitSubmit?.(a); return\n case TREE_EVENT_OVERLAY_TAP: pins.get(id)?._emitOverlayTap?.(); return\n case TREE_EVENT_DETENT: pins.get(id)?._emitDetent?.(a); return\n case TREE_EVENT_OPEN: resolveDest(a, b)?._emitOpen?.(); return\n case TREE_EVENT_CLOSE: resolveDest(a, b)?._emitClose?.(); return\n case TREE_EVENT_BACK: {\n if (a === TREE_DEST_NONE) {\n if (id !== 0) return pins.get(id)?._emitBack?.() === true // a widget\n if (!appBack) return false\n appBack()\n return true\n }\n return resolveDest(a, b)?._emitBack?.() === true\n }\n case TREE_EVENT_PAGER_SELECT: pins.get(id)?._hostDidSelect?.(a); return\n case TREE_EVENT_PAGER_POP: pins.get(id)?._hostDidPop?.(a); return\n case TREE_EVENT_VLIST_SYNC: pins.get(id)?._syncWindow?.(a, b); return\n case TREE_EVENT_VLIST_EDGE: pins.get(id)?._emitEdge?.(!!a); return\n case TREE_EVENT_VIEW_EVENT: nativeViews.get(a)?._emitViewEvent(b, c); return\n case TREE_EVENT_RESIZE: for (const cb of resizeListeners.slice()) cb(a, b); return\n case TREE_EVENT_ROUTER_CHANGE: routerChange?.(a, b); return\n case TREE_EVENT_SCENE_TOUCH_START: return trackAnswer(a, sceneTouchStart?.(a, b, c, d))\n case TREE_EVENT_SCENE_CLICK: sceneClick?.(a, b, c, d); return\n case TREE_EVENT_DETACHED: {\n const el = pins.get(id)\n pins.delete(id)\n el?._detached?.()\n return\n }\n case TREE_EVENT_FREED: {\n for (const fid of a as number[]) {\n const el = pins.get(fid)\n pins.delete(fid)\n el?._freed?.()\n }\n return\n }\n }\n}\n\n/** @internal Install the emitter once per world (the first element / presentable calls it). */\nexport const ensureEmitter = (): void => {\n if (installed) return\n installed = true\n _creatorTree.setEmitter(emit)\n}\n","import type { RenderNode } from \"../types\"\n\nfunction contains(node: RenderNode, x: number, y: number): boolean {\n const r = node.rect\n return x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height\n}\n\n/**\n * Find the topmost node satisfying `accept` (e.g. interactive) under a point. Walks in paint order\n * and returns the last match — later siblings and deeper children paint on top, so they win, which\n * matches the DOM event-bubbling target the worker buttons expect.\n */\nexport function hitTest(\n root: RenderNode,\n x: number,\n y: number,\n accept: (node: RenderNode) => boolean,\n): RenderNode | null {\n let found: RenderNode | null = null\n const walk = (node: RenderNode) => {\n const inside = contains(node, x, y)\n if (inside && accept(node)) found = node\n // A clipping node (scrollable / overflow:hidden) hides children outside its rect — so a child\n // scrolled out of view isn't hittable, matching the DOM's overflow clipping.\n if (node.clip && !inside) return\n for (const child of node.children) walk(child)\n }\n walk(root)\n return found\n}\n","// AUTO-GENERATED from engines/ui/properties.mjs — DO NOT EDIT. Regenerate: bun run gen:ui-props\n//\n// The CUIPaint record layout (engines/ui/include/creator-ui/paint.gen.h) for a reader over the wasm\n// heap: `HEAPU32[(ptr >> 2) + word]` / `HEAPF32[...]`. Bits index the present / dirty masks\n// (two u32 words each: lo at word 0 / 2, hi at word 1 / 3).\n\nexport const CUI_PAINT_WORDS = 78\nexport const CUI_PRESENT_LO = 0, CUI_PRESENT_HI = 1, CUI_DIRTY_LO = 2, CUI_DIRTY_HI = 3\nexport const CUI_INHERIT_MASK_LO = 4096, CUI_INHERIT_MASK_HI = 4080\nexport const CUI_MEASURE_MASK_LO = 0, CUI_MEASURE_MASK_HI = 5104 // a dirty measure field re-measures a text leaf\n\nexport type CuiKind = \"float\" | \"color\" | \"enum\" | \"str\" | \"matrix\" | \"origin\" | \"gradient\"\n\nexport const CUI_FIELDS = {\n display: { bit: 0, word: 4, kind: \"enum\" },\n overflow: { bit: 1, word: 5, kind: \"enum\" },\n scrollDirection: { bit: 2, word: 6, kind: \"enum\" },\n borderWidth: { bit: 3, word: 7, kind: \"float\" },\n borderTopWidth: { bit: 4, word: 8, kind: \"float\" },\n borderRightWidth: { bit: 5, word: 9, kind: \"float\" },\n borderBottomWidth: { bit: 6, word: 10, kind: \"float\" },\n borderLeftWidth: { bit: 7, word: 11, kind: \"float\" },\n borderHorizontalWidth: { bit: 8, word: 12, kind: \"float\" },\n borderVerticalWidth: { bit: 9, word: 13, kind: \"float\" },\n borderStartWidth: { bit: 10, word: 14, kind: \"float\" },\n borderEndWidth: { bit: 11, word: 15, kind: \"float\" },\n color: { bit: 12, word: 16, kind: \"color\" },\n backgroundColor: { bit: 13, word: 17, kind: \"color\" },\n borderColor: { bit: 14, word: 18, kind: \"color\" },\n borderTopColor: { bit: 15, word: 19, kind: \"color\" },\n borderRightColor: { bit: 16, word: 20, kind: \"color\" },\n borderBottomColor: { bit: 17, word: 21, kind: \"color\" },\n borderLeftColor: { bit: 18, word: 22, kind: \"color\" },\n placeholderColor: { bit: 19, word: 23, kind: \"color\" },\n refreshControlColor: { bit: 20, word: 24, kind: \"color\" },\n tintColor: { bit: 21, word: 25, kind: \"color\" },\n rippleColor: { bit: 22, word: 26, kind: \"color\" },\n overlayColor: { bit: 23, word: 27, kind: \"color\" },\n backgroundImage: { bit: 24, word: 28, kind: \"str\" },\n backgroundSize: { bit: 25, word: 29, kind: \"enum\" },\n backgroundGradient: { bit: 26, word: 30, kind: \"gradient\" },\n borderRadius: { bit: 27, word: 31, kind: \"float\" },\n borderTopLeftRadius: { bit: 28, word: 32, kind: \"float\" },\n borderTopRightRadius: { bit: 29, word: 33, kind: \"float\" },\n borderBottomRightRadius: { bit: 30, word: 34, kind: \"float\" },\n borderBottomLeftRadius: { bit: 31, word: 35, kind: \"float\" },\n opacity: { bit: 32, word: 36, kind: \"float\" },\n transform: { bit: 33, word: 37, kind: \"matrix\" },\n transformOrigin: { bit: 34, word: 46, kind: \"origin\" },\n pointerEvents: { bit: 35, word: 50, kind: \"enum\" },\n fontSize: { bit: 36, word: 51, kind: \"float\" },\n fontWeight: { bit: 37, word: 52, kind: \"float\" },\n fontStyle: { bit: 38, word: 53, kind: \"enum\" },\n fontFamily: { bit: 39, word: 54, kind: \"str\" },\n lineHeight: { bit: 40, word: 55, kind: \"float\" },\n letterSpacing: { bit: 41, word: 56, kind: \"float\" },\n textAlign: { bit: 42, word: 57, kind: \"enum\" },\n textDecoration: { bit: 43, word: 58, kind: \"enum\" },\n lineClamp: { bit: 44, word: 59, kind: \"float\" },\n textOverflow: { bit: 45, word: 60, kind: \"enum\" },\n objectFit: { bit: 46, word: 61, kind: \"enum\" },\n placeholder: { bit: 47, word: 62, kind: \"str\" },\n type: { bit: 48, word: 63, kind: \"enum\" },\n enterKey: { bit: 49, word: 64, kind: \"enum\" },\n autocapitalize: { bit: 50, word: 65, kind: \"enum\" },\n autocorrect: { bit: 51, word: 66, kind: \"float\" },\n maxLength: { bit: 52, word: 67, kind: \"float\" },\n keyboardShrink: { bit: 53, word: 68, kind: \"float\" },\n keyboardDismiss: { bit: 54, word: 69, kind: \"float\" },\n showScrollbar: { bit: 55, word: 70, kind: \"float\" },\n overscrollMode: { bit: 56, word: 71, kind: \"enum\" },\n keyboardDismissMode: { bit: 57, word: 72, kind: \"enum\" },\n snap: { bit: 58, word: 73, kind: \"enum\" },\n sheetDetents: { bit: 59, word: 74, kind: \"str\" },\n sheetDetent: { bit: 60, word: 75, kind: \"float\" },\n sheetDismissible: { bit: 61, word: 76, kind: \"float\" },\n dim: { bit: 62, word: 77, kind: \"float\" },\n} as const satisfies Record<string, { bit: number, word: number, kind: CuiKind }>\n\nexport type CuiFieldKey = keyof typeof CUI_FIELDS\n\nexport const CuiDisplay = { \"flex\": 0, \"none\": 1 } as const\nexport const CuiOverflow = { \"visible\": 0, \"hidden\": 1, \"scroll\": 2 } as const\nexport const CuiScrollDirection = { \"vertical\": 0, \"horizontal\": 1, \"all\": 2 } as const\nexport const CuiBackgroundSize = { \"cover\": 0, \"contain\": 1, \"fill\": 2, \"tile\": 3 } as const\nexport const CuiPointerEvents = { \"all\": 0, \"none\": 1 } as const\nexport const CuiFontStyle = { \"normal\": 0, \"italic\": 1 } as const\nexport const CuiTextAlign = { \"start\": 0, \"center\": 1, \"end\": 2, \"left\": 3, \"right\": 4 } as const\nexport const CuiTextDecoration = { \"underline\": 0, \"line-through\": 1, \"none\": 2 } as const\nexport const CuiTextOverflow = { \"ellipsis\": 0, \"clip\": 1 } as const\nexport const CuiObjectFit = { \"cover\": 0, \"contain\": 1, \"fill\": 2 } as const\nexport const CuiType = { \"text\": 0, \"password\": 1, \"tel\": 2, \"email\": 3, \"number\": 4, \"decimal\": 5, \"url\": 6, \"search\": 7, \"date\": 8, \"time\": 9 } as const\nexport const CuiEnterKey = { \"done\": 0, \"go\": 1, \"next\": 2, \"search\": 3, \"send\": 4 } as const\nexport const CuiAutocapitalize = { \"none\": 0, \"sentences\": 1, \"words\": 2, \"characters\": 3 } as const\nexport const CuiOverscrollMode = { \"default\": 0, \"none\": 1, \"absorb\": 2 } as const\nexport const CuiKeyboardDismissMode = { \"interactive\": 0, \"scroll\": 1, \"none\": 2 } as const\nexport const CuiSnap = { \"none\": 0, \"start\": 1, \"center\": 2, \"end\": 3 } as const\n\n/** The registry spelling of each enum code, by field. */\nexport const CUI_NAMES = {\n display: [\"flex\", \"none\"],\n overflow: [\"visible\", \"hidden\", \"scroll\"],\n scrollDirection: [\"vertical\", \"horizontal\", \"all\"],\n backgroundSize: [\"cover\", \"contain\", \"fill\", \"tile\"],\n pointerEvents: [\"all\", \"none\"],\n fontStyle: [\"normal\", \"italic\"],\n textAlign: [\"start\", \"center\", \"end\", \"left\", \"right\"],\n textDecoration: [\"underline\", \"line-through\", \"none\"],\n textOverflow: [\"ellipsis\", \"clip\"],\n objectFit: [\"cover\", \"contain\", \"fill\"],\n type: [\"text\", \"password\", \"tel\", \"email\", \"number\", \"decimal\", \"url\", \"search\", \"date\", \"time\"],\n enterKey: [\"done\", \"go\", \"next\", \"search\", \"send\"],\n autocapitalize: [\"none\", \"sentences\", \"words\", \"characters\"],\n overscrollMode: [\"default\", \"none\", \"absorb\"],\n keyboardDismissMode: [\"interactive\", \"scroll\", \"none\"],\n snap: [\"none\", \"start\", \"center\", \"end\"],\n} as const\n\n/** present / dirty bit test on the (lo, hi) word pair. */\nexport const cuiBit = (lo: number, hi: number, bit: number): boolean =>\n bit < 32 ? ((lo >>> bit) & 1) === 1 : ((hi >>> (bit - 32)) & 1) === 1\n","import type { Gradient, GradientStop, RadialExtent } from \"../../types\"\n\n// Decodes the creator-ui CUIGradient struct (creator-ui/include/creator-ui/creator-ui.h) out of the\n// wasm heap. wasm32 layout, all fields 4-byte aligned:\n// CUIGradient { float angle@0; u32 type@4; u32 stopCount@8; u32 _pad@12; CUIGradientStop* stops@16;\n// u32 shape@20; u32 extent@24; float cx@28; float cy@32;\n// float rx@36; float ry@40; u32 rUnitX@44; u32 rUnitY@48 }\n// CUIGradientStop { u32 color@0; float position@4 } (8 bytes, tightly packed)\n// The radial fields are appended AFTER the 4-byte `stops` pointer, so the linear prefix\n// (angle/type/stopCount/stops) is byte-identical to before. `color` is COLOR_FORMAT = 0xRRGGBBAA on\n// web (== our RGBA), so no conversion is needed. extent == 4 means explicit rx/ry (rUnit 0 = px, 1 =\n// box-axis fraction). Pure (takes heap views) so it can be unit-tested with a synthetic buffer.\n\nconst EXTENTS: RadialExtent[] = [\"farthest-corner\", \"closest-side\", \"closest-corner\", \"farthest-side\"]\n\n// sizeof(CUIGradient) on wasm32 (13 × 4-byte fields), pinned by a static_assert in gradient.h. The\n// multi-layer handler hands us a pointer to `count` of these laid out back-to-back.\nconst CUI_GRADIENT_STRIDE = 52\n\n/** Decode a `count`-long CUIGradient array (the background-image layer stack, [0] = topmost). */\nexport function readGradientStructs(f32: Float32Array, u32: Uint32Array, ptr: number, count: number): Gradient[] {\n const out: Gradient[] = []\n for (let k = 0; k < count; k++) out.push(readGradientStruct(f32, u32, ptr + k * CUI_GRADIENT_STRIDE))\n return out\n}\n\nexport function readGradientStruct(f32: Float32Array, u32: Uint32Array, ptr: number): Gradient {\n const i = ptr >> 2\n const angle = f32[i]\n const type = u32[i + 1]\n const stopCount = u32[i + 2]\n const stopsPtr = u32[i + 4]\n\n const stops: GradientStop[] = []\n for (let s = 0; s < stopCount; s++) {\n const b = (stopsPtr + s * 8) >> 2\n stops.push({ color: u32[b] >>> 0, position: f32[b + 1] })\n }\n\n if (type === 1) {\n const extentCode = u32[i + 6]\n const base = {\n type: \"radial\" as const,\n shape: (u32[i + 5] === 1 ? \"circle\" : \"ellipse\") as \"circle\" | \"ellipse\",\n cx: f32[i + 7],\n cy: f32[i + 8],\n stops,\n }\n if (extentCode === 4) {\n return {\n ...base,\n extent: \"explicit\",\n rx: f32[i + 9],\n ry: f32[i + 10],\n rxUnit: u32[i + 11] === 1 ? \"fraction\" : \"px\",\n ryUnit: u32[i + 12] === 1 ? \"fraction\" : \"px\",\n }\n }\n return { ...base, extent: EXTENTS[extentCode] ?? \"farthest-corner\" }\n }\n return { type: \"linear\", angle, stops }\n}\n","// The paint state reader (creator-ui/paint.gen.h, CuiPaint.gen.ts): the runtime keeps one resolved\n// paint record per node; this renderer READS it — the dirty records `_paintCollect` hands out once\n// per frame, or a node's record in place (`_cuiPaintOf`) whenever it measures. The per-prop style\n// handlers this file replaced (2026-09-24) wrote the same ResolvedStyle field by field; here one\n// record write fills it, and the text style arrives EFFECTIVE (the core inherits), so no ancestor\n// walk remains anywhere in the renderer.\nimport type { ResolvedStyle } from \"../../types\"\nimport { CUI_FIELDS, CUI_NAMES, CUI_PAINT_WORDS, CuiFontStyle, CuiOverflow, CuiScrollDirection, cuiBit } from \"../CuiPaint.gen\"\nimport { readGradientStructs } from \"./readGradient\"\n\n/** The wasm module surface the reader needs (a subset of CreatorUiModule). */\nexport interface PaintModule {\n HEAPF32: Float32Array\n HEAPU32: Uint32Array\n UTF8ToString(ptr: number): string\n _malloc(size: number): number\n _paintCollect(): number\n _paintNodes(): number\n _paintRecords(): number\n _cuiPaintOf(nodePtr: number): number\n _cuiStringOf(id: number): number\n _cuiGradientOf(id: number, outCountPtr: number): number\n}\n\nconst F = CUI_FIELDS\nconst ALIGN: ResolvedStyle[\"textAlign\"][] = [\"start\", \"center\", \"end\", \"start\", \"end\"] // start center end left right\n\nlet countPtr = 0\n\n/** Read the record at `ptr` (a word-aligned CUIPaint) into `style`. */\nexport function readPaintRecord(M: PaintModule, ptr: number, style: ResolvedStyle): void {\n const u32 = M.HEAPU32, f32 = M.HEAPF32\n const w = ptr >>> 2\n const presentLo = u32[w], presentHi = u32[w + 1]\n const has = (bit: number) => cuiBit(presentLo, presentHi, bit)\n const str = (word: number): string | undefined => {\n const id = u32[w + word]\n return id === 0 ? undefined : M.UTF8ToString(M._cuiStringOf(id))\n }\n\n // box\n style.backgroundColor = u32[w + F.backgroundColor.word] >>> 0\n style.opacity = f32[w + F.opacity.word]\n style.dim = f32[w + F.dim.word]\n style.display = CUI_NAMES.display[u32[w + F.display.word]]\n style.overflow = u32[w + F.overflow.word] === CuiOverflow.hidden ? \"hidden\" : \"visible\"\n style.scrollAxis = u32[w + F.scrollDirection.word] === CuiScrollDirection.horizontal ? \"x\" : \"y\"\n // borders: the core fans borderWidth / borderColor out into the four sides (paint.cpp)\n style.border = {\n top: { width: f32[w + F.borderTopWidth.word], color: u32[w + F.borderTopColor.word] >>> 0 },\n right: { width: f32[w + F.borderRightWidth.word], color: u32[w + F.borderRightColor.word] >>> 0 },\n bottom: { width: f32[w + F.borderBottomWidth.word], color: u32[w + F.borderBottomColor.word] >>> 0 },\n left: { width: f32[w + F.borderLeftWidth.word], color: u32[w + F.borderLeftColor.word] >>> 0 },\n }\n style.borderRadius = {\n tl: f32[w + F.borderTopLeftRadius.word], tr: f32[w + F.borderTopRightRadius.word],\n br: f32[w + F.borderBottomRightRadius.word], bl: f32[w + F.borderBottomLeftRadius.word],\n }\n // background layers\n style.backgroundImage = str(F.backgroundImage.word)\n style.backgroundSize = CUI_NAMES.backgroundSize[u32[w + F.backgroundSize.word]] as ResolvedStyle[\"backgroundSize\"]\n const gradientId = u32[w + F.backgroundGradient.word]\n if (gradientId === 0) style.backgroundGradients = undefined\n else {\n if (countPtr === 0) countPtr = M._malloc(4)\n const gp = M._cuiGradientOf(gradientId, countPtr)\n const count = M.HEAPU32[countPtr >>> 2]\n style.backgroundGradients = gp !== 0 && count > 0 ? readGradientStructs(M.HEAPF32, M.HEAPU32, gp, count) : undefined\n }\n // transform: the 2D affine [a,b,c,d,e,f] of the 3x3 (column-major m0 m1 m3 m4 m6 m7); identity = absent\n const t = w + F.transform.word\n const a = f32[t], b = f32[t + 1], c = f32[t + 3], d = f32[t + 4], e = f32[t + 6], f = f32[t + 7]\n style.transform = a === 1 && b === 0 && c === 0 && d === 1 && e === 0 && f === 0 ? undefined : [a, b, c, d, e, f]\n const o = w + F.transformOrigin.word\n style.transformOrigin = { x: f32[o], y: f32[o + 1], xPercent: u32[o + 2] !== 0, yPercent: u32[o + 3] !== 0 }\n\n // text (effective; absent = the renderer default — core/text.ts DEFAULTS)\n style.color = has(F.color.bit) ? u32[w + F.color.word] >>> 0 : undefined\n style.fontFamily = has(F.fontFamily.bit) ? str(F.fontFamily.word) : undefined\n style.fontSize = f32[w + F.fontSize.word]\n style.fontWeight = f32[w + F.fontWeight.word]\n style.fontStyle = u32[w + F.fontStyle.word] === CuiFontStyle.italic ? \"italic\" : \"normal\"\n style.lineHeight = f32[w + F.lineHeight.word]\n style.letterSpacing = f32[w + F.letterSpacing.word]\n style.textAlign = ALIGN[u32[w + F.textAlign.word]] ?? \"start\"\n style.textDecoration = CUI_NAMES.textDecoration[u32[w + F.textDecoration.word]] as ResolvedStyle[\"textDecoration\"]\n style.lineClamp = f32[w + F.lineClamp.word]\n style.textOverflow = CUI_NAMES.textOverflow[u32[w + F.textOverflow.word]] as ResolvedStyle[\"textOverflow\"]\n\n // image / input / widget (presence props: absent = the renderer default)\n style.objectFit = CUI_NAMES.objectFit[u32[w + F.objectFit.word]] as ResolvedStyle[\"objectFit\"]\n style.tintColor = has(F.tintColor.bit) ? u32[w + F.tintColor.word] >>> 0 : undefined\n style.placeholder = str(F.placeholder.word)\n style.placeholderColor = has(F.placeholderColor.bit) ? u32[w + F.placeholderColor.word] >>> 0 : undefined\n style.inputType = CUI_NAMES.type[u32[w + F.type.word]]\n style.overlayColor = has(F.overlayColor.bit) ? u32[w + F.overlayColor.word] >>> 0 : undefined\n}\n\n/** The node's record has changes the frame's sync has not taken yet. */\nexport function paintPending(M: PaintModule, nodePtr: number): boolean {\n const p = M._cuiPaintOf(nodePtr)\n if (p === 0) return false\n const w = p >>> 2\n return M.HEAPU32[w + 2] !== 0 || M.HEAPU32[w + 3] !== 0\n}\n\n/** Read a live node's current record in place (a measure that runs before this frame's sync). */\nexport function readPaintOf(M: PaintModule, nodePtr: number, style: ResolvedStyle): boolean {\n const p = M._cuiPaintOf(nodePtr)\n if (p === 0) return false\n readPaintRecord(M, p, style)\n return true\n}\n\n/**\n * Once per frame, before layout: every record that changed since the last call, into its node's\n * style via `apply`. Returns the number of records taken.\n */\nexport function syncPaint(M: PaintModule, apply: (nodePtr: number, read: (style: ResolvedStyle) => void) => void): number {\n const n = M._paintCollect()\n if (n === 0) return 0\n const nodes = M._paintNodes() >>> 2\n const records = M._paintRecords()\n for (let i = 0; i < n; i++) {\n const ptr = M.HEAPU32[nodes + i]\n const rec = records + i * CUI_PAINT_WORDS * 4\n apply(ptr, (style) => readPaintRecord(M, rec, style))\n }\n return n\n}\n\n","import type { ResolvedStyle, RGBA } from \"../types\"\nimport type { FontSpec, Host } from \"../host/Host\"\nimport type { SceneNode } from \"./SceneNode\"\nimport { extractSvgViewBox, isSvgSource } from \"./util/svgSrc\"\n\n/** Effective, fully-defaulted text style for a node (after walking inheritance). */\nexport interface EffectiveText {\n color: RGBA\n fontSize: number\n fontFamily: string\n fontWeight: number\n fontStyle: \"normal\" | \"italic\"\n lineHeight: number\n letterSpacing: number\n textAlign: \"start\" | \"center\" | \"end\"\n textDecoration: \"underline\" | \"line-through\" | \"none\"\n}\n\n// The last-resort values for a node whose record carries no color / font (the runtime inherits\n// text style and the theme's defaults core-side; these only fill what is absent there).\nconst DEFAULTS = {\n color: 0x000000ff as RGBA,\n fontSize: 14,\n fontFamily: \"Roboto\",\n fontWeight: 400,\n fontStyle: \"normal\" as const,\n letterSpacing: 0,\n textAlign: \"start\" as const,\n textDecoration: \"none\" as const,\n}\n\n/**\n * A node's text style: its ResolvedStyle already holds the EFFECTIVE values (the runtime's paint\n * record inherits text style core-side), so this only fills the defaults for absent fields. The\n * measure callback and the render-tree build both call this, so layout and paint never disagree.\n */\nexport function resolveTextStyle(node: SceneNode): EffectiveText {\n const s = node.style\n const { color, fontSize, fontFamily, fontWeight, fontStyle, lineHeight, letterSpacing, textAlign, textDecoration } = s\n\n const size = fontSize ?? DEFAULTS.fontSize\n return {\n color: color ?? DEFAULTS.color,\n fontSize: size,\n fontFamily: fontFamily ?? DEFAULTS.fontFamily,\n fontWeight: fontWeight ?? DEFAULTS.fontWeight,\n fontStyle: fontStyle ?? DEFAULTS.fontStyle,\n lineHeight,\n letterSpacing: letterSpacing ?? DEFAULTS.letterSpacing,\n textAlign: textAlign ?? DEFAULTS.textAlign,\n textDecoration: textDecoration ?? DEFAULTS.textDecoration,\n }\n}\n\nexport function toFontSpec(t: EffectiveText): FontSpec {\n return {\n family: t.fontFamily,\n size: t.fontSize,\n weight: t.fontWeight,\n italic: t.fontStyle === \"italic\",\n letterSpacing: t.letterSpacing,\n }\n}\n\n/**\n * Greedy word-wrap to `maxWidth` (honoring explicit \\n, and breaking over-long words). Returns the\n * lines and the widest line. Ported from the DOM measure system, but measuring via the host so it\n * works headless. `maxWidth = Infinity` yields intrinsic (no-wrap) sizing.\n */\nexport function wrapText(\n text: string,\n maxWidth: number,\n measure: (s: string) => number,\n): { lines: string[]; maxWidth: number } {\n const result: string[] = []\n let widest = 0\n\n for (const rawLine of text.split(\"\\n\")) {\n if (rawLine.length === 0) {\n result.push(\"\")\n continue\n }\n let current = rawLine\n while (current) {\n if (measure(current) <= maxWidth) {\n result.push(current)\n widest = Math.max(widest, measure(current))\n break\n }\n\n let splitPos = 0\n let lastSpace = -1\n let spaceIdx = 0\n while ((spaceIdx = current.indexOf(\" \", spaceIdx + 1)) !== -1) {\n if (measure(current.substring(0, spaceIdx)) > maxWidth) break\n lastSpace = spaceIdx\n }\n\n if (lastSpace > 0) {\n splitPos = lastSpace\n } else {\n let wordEnd = current.indexOf(\" \")\n if (wordEnd === -1) wordEnd = current.length\n const firstWord = current.substring(0, wordEnd)\n if (measure(firstWord) > maxWidth) {\n for (let i = 1; i <= firstWord.length; i++) {\n if (measure(firstWord.substring(0, i)) > maxWidth) {\n splitPos = i - 1\n break\n }\n }\n } else {\n for (let i = wordEnd + 1; i <= current.length; i++) {\n if (measure(current.substring(0, i)) > maxWidth) {\n splitPos = i - 1\n break\n }\n }\n }\n }\n\n if (splitPos <= 0) splitPos = 1\n const line = current.substring(0, splitPos)\n result.push(line)\n widest = Math.max(widest, measure(line))\n current = current.substring(splitPos + (lastSpace > 0 ? 1 : 0))\n }\n }\n\n return { lines: result, maxWidth: widest }\n}\n\n/** Appended to the last surviving line when a clamp cut the text and textOverflow is \"ellipsis\". */\nconst ELLIPSIS = \"…\"\n\n/**\n * Apply `lineClamp` / `textOverflow` to a wrapped line list. Returns the surviving lines — with the\n * last one shortened so `…` fits the content width, unless `textOverflow: \"clip\"` asks for a hard\n * cut. creator-ui touches neither prop (it changes no Yoga style), so clamping — including\n * reporting the clamped box — is entirely the host's job: measure and the render tree both call\n * this, so the measured height and the painted lines can't disagree.\n *\n * Returns the input array itself when nothing is clamped, so callers can skip the re-measure.\n */\nexport function clampLines(\n lines: string[],\n style: ResolvedStyle,\n maxWidth: number,\n measure: (s: string) => number,\n): string[] {\n const clamp = style.lineClamp ?? 0\n if (clamp <= 0 || lines.length <= clamp) return lines\n const kept = lines.slice(0, clamp)\n if (style.textOverflow === \"clip\") return kept\n kept[clamp - 1] = ellipsize(kept[clamp - 1], maxWidth, measure)\n return kept\n}\n\n/** Trim `line` (from the end, on whole characters) until `line…` fits `maxWidth`. */\nfunction ellipsize(line: string, maxWidth: number, measure: (s: string) => number): string {\n // Unconstrained (intrinsic) measure: nothing to fit into, so the ellipsis just widens the box.\n if (!isFinite(maxWidth)) return line + ELLIPSIS\n const chars = [...line] // by code point — never cut a surrogate pair in half\n let end = chars.length\n while (end > 0 && measure(chars.slice(0, end).join(\"\") + ELLIPSIS) > maxWidth) end--\n return chars.slice(0, end).join(\"\").trimEnd() + ELLIPSIS\n}\n\n/** Measure a text node for creator-ui (returns intrinsic/wrapped size for the given constraints). */\nexport function measureTextNode(node: SceneNode, host: Host, width: number): { width: number; height: number } {\n const t = resolveTextStyle(node)\n const font = toFontSpec(t)\n const measureWidth = isNaN(width) ? Infinity : width\n const measure = (s: string) => host.measureText(s, font)\n const wrapped = wrapText(node.text ?? \"\", measureWidth, measure)\n const lines = clampLines(wrapped.lines, node.style, measureWidth, measure)\n // A clamp reports the CLAMPED box, otherwise the layout would reflow around the full string and\n // leave dead space under the last line. The width has to be recomputed over the surviving lines\n // only — the widest line is often one of the ones that got cut.\n let widest = wrapped.maxWidth\n if (lines !== wrapped.lines) {\n widest = 0\n for (const line of lines) widest = Math.max(widest, measure(line))\n }\n return { width: Math.ceil(widest), height: Math.ceil(lines.length * t.lineHeight) }\n}\n\n/** Measure an editable field (input / textarea) for creator-ui. An input is one text line; a\n * textarea wraps its value at the given width (empty → one line), so a field with no explicit\n * height grows with its content — Yoga clamps via the node's minHeight/maxHeight styles. Font\n * fallbacks mirror paintInput: measure and paint must agree on the line grid. */\nexport function measureEditableNode(node: SceneNode, host: Host, width: number): { width: number; height: number } {\n const s = node.style\n const font: FontSpec = {\n family: s.fontFamily ?? \"Roboto\",\n size: s.fontSize ?? 14,\n weight: s.fontWeight ?? 400,\n italic: s.fontStyle === \"italic\",\n letterSpacing: s.letterSpacing ?? 0,\n }\n const lineHeight = s.lineHeight\n const value = node.value ?? \"\"\n if (node.type === \"input\") {\n return { width: Math.ceil(host.measureText(value, font)), height: Math.ceil(lineHeight) }\n }\n const measureWidth = isNaN(width) ? Infinity : width\n const wrapped = wrapText(value, measureWidth, (t) => host.measureText(t, font))\n return { width: Math.ceil(wrapped.maxWidth), height: Math.ceil(Math.max(1, wrapped.lines.length) * lineHeight) }\n}\n\n/** Measure an image node for creator-ui (intrinsic size). A source crop (atlas frame) uses the crop's\n * w/h. An SVG is a vector → its size comes from the viewBox and it may upscale; a raster is clamped\n * to not upscale. */\nexport function measureImageNode(\n node: SceneNode,\n host: Host,\n width: number,\n height: number,\n): { width: number; height: number } {\n const raw = node.imageSrcRaw\n let iw = 0\n let ih = 0\n\n if (node.sourceRect) {\n iw = node.sourceRect[2]\n ih = node.sourceRect[3]\n } else if (isSvgSource(raw)) {\n // Inline SVG: size from the viewBox (no decode needed — works on the headless/JSON path too).\n const vb = extractSvgViewBox(raw.svg)\n if (vb) {\n iw = vb.width\n ih = vb.height\n } else {\n const info = host.getImage(host.resolveSrc(raw) ?? \"\")\n iw = info?.naturalWidth ?? 0\n ih = info?.naturalHeight ?? 0\n }\n } else {\n const src = host.resolveSrc(raw)\n const info = src ? host.getImage(src) : undefined\n iw = info?.naturalWidth ?? 0\n ih = info?.naturalHeight ?? 0\n }\n if (iw === 0 || ih === 0) return { width: 0, height: 0 }\n\n // Never past the intrinsic size under a constraint (the CSS rule, iOS's and the desktop's measure):\n // an SVG scales without quality loss, but an unsized icon still lays out at its own size — a box\n // that names a dimension is exact for yoga, which sizes past this answer anyway.\n const fit = Math.min(width / iw, height / ih)\n const k =\n isNaN(width) && isNaN(height)\n ? 1\n : isNaN(width)\n ? height / ih\n : isNaN(height)\n ? width / iw\n : Math.min(fit, 1)\n return { width: iw * k, height: ih * k }\n}\n","import type { BorderRadius, Layer, RenderNode, UITransform } from \"../types\"\nimport type { Host, FontSpec } from \"../host/Host\"\nimport type { Borders, Painter } from \"./Painter\"\nimport { clampRadius, hasRadius } from \"../core/util/geometry\"\nimport { isTransparent } from \"../core/util/colors\"\nimport { isSvgLikeSrc } from \"../core/util/svgSrc\"\nimport { wrapText } from \"../core/text\"\n\n/** What the host shows ITSELF, so the painter leaves it out. */\nexport type PaintOptions = {\n /** A native view and a video are surfaces UNDER the picture: their box is a window onto them\n * (absent: a video is a placeholder, a native view nothing). */\n surfaces?: boolean\n /** The field being edited, by node id: a live <input> stands over it, with the text and the caret. */\n editing?: number\n}\n\n/**\n * Walk the render tree and replay it into a Painter. All paint *logic* (clip-on-radius, border\n * stacking, text alignment + baseline) lives here, so every backend shares it and only the leaf\n * primitives differ. `host` is used for text metrics (deterministic across backends).\n */\nexport function paintTree(tree: RenderNode | null, painter: Painter, host: Host, options: PaintOptions = {}) {\n if (!tree) return\n painter.beginFrame(tree.rect.width, tree.rect.height)\n paintNode(tree, painter, host, options)\n painter.endFrame()\n}\n\n/**\n * Paint a full frame of compositing layers (main screen + widget overlays) in one begin/end. A\n * widget's `backdrop` is a full-viewport fill painted behind it.\n */\nexport function paintFrame(\n layers: Layer[],\n painter: Painter,\n host: Host,\n width: number,\n height: number,\n transform?: UITransform,\n options: PaintOptions = {},\n) {\n painter.beginFrame(width, height)\n // The simulated keyboard rescales the whole UI into the band above it (the keyboard itself is the\n // host's — DOM on web). The bottom band is left empty for the host to draw over.\n if (transform) {\n painter.save()\n painter.translate(transform.tx, transform.ty)\n painter.scale(transform.scale, transform.scale)\n }\n // z-order (matches the DOM): the base screen(s) first, then ALL widget backdrops, then ALL widget\n // bodies — so with ≥2 overlays a later widget's backdrop never covers an earlier widget.\n const widgets = layers.filter((l) => l.widget)\n for (const l of layers) if (!l.widget) paintNode(l.tree, painter, host, options)\n for (const l of widgets) if (l.backdrop) painter.fillRoundRect({ x: 0, y: 0, width, height }, undefined, l.backdrop.color)\n for (const l of widgets) paintNode(l.tree, painter, host, options)\n if (transform) painter.restore()\n painter.endFrame()\n}\n\nfunction paintNode(node: RenderNode, painter: Painter, host: Host, options: PaintOptions) {\n const { style, rect } = node\n painter.save()\n // A translucent container fades as a GROUP (composited offscreen, then faded once) so overlapping\n // children blend like the DOM's CSS opacity; a leaf uses cheap per-primitive alpha (identical for a\n // single fill, no offscreen needed).\n const opacity = style.opacity !== undefined && style.opacity < 1 ? style.opacity : undefined\n const grouped = opacity !== undefined && node.children.length > 0\n if (grouped) painter.beginGroup(opacity!)\n else if (opacity !== undefined) painter.setAlpha(opacity)\n\n // 2D transform about `transformOrigin` (the node centre by default), affecting the node + its subtree.\n if (style.transform) {\n const [a, b, c, d, e, f] = style.transform\n const o = style.transformOrigin\n const cx = rect.x + (o ? (o.xPercent ? rect.width * o.x / 100 : o.x) : rect.width / 2)\n const cy = rect.y + (o ? (o.yPercent ? rect.height * o.y / 100 : o.y) : rect.height / 2)\n painter.translate(cx, cy)\n painter.transform(a, b, c, d, e, f)\n painter.translate(-cx, -cy)\n }\n\n const radius = clampRadius(style.borderRadius, rect)\n\n // background color\n if (!isTransparent(style.backgroundColor)) {\n painter.fillRoundRect(rect, radius, style.backgroundColor!)\n }\n\n // background image (string url, painted behind content)\n if (style.backgroundImage) {\n const bg = host.getImage(style.backgroundImage)\n if (bg && bg.naturalWidth > 0 && bg.naturalHeight > 0) {\n painter.save()\n if (hasRadius(radius)) painter.clipRoundRect(rect, radius)\n painter.drawImage(bg, null, rect, { fit: bgSizeToFit(style.backgroundSize) })\n painter.restore()\n }\n }\n\n // background gradient layers (painted over the background image, like the DOM layer order).\n // CSS paints the first-listed layer on top, so paint the stack back-to-front (last → first).\n if (style.backgroundGradients) {\n for (let i = style.backgroundGradients.length - 1; i >= 0; i--) {\n const g = style.backgroundGradients[i]\n if (g.stops.length > 0) painter.fillGradient(rect, radius, g)\n }\n }\n\n // image (clipped to the radius if any). A source crop overrides object-fit (the frame fills the box).\n if (node.image && node.image.naturalWidth > 0 && node.image.naturalHeight > 0) {\n const crop = node.sourceRect\n painter.save()\n if (hasRadius(radius)) painter.clipRoundRect(rect, radius)\n painter.drawImage(node.image, crop ? { x: crop[0], y: crop[1], width: crop[2], height: crop[3] } : null, rect, {\n // DOM default: `img { object-fit: contain }`. A sourceRect crop always fills its box.\n fit: crop ? \"fill\" : (style.objectFit ?? \"contain\"),\n // tintColor recolors a mask-capable (SVG) image; on an opaque raster the DOM no-ops it, so\n // only tint SVG sources — otherwise a photo would become a flat silhouette.\n tint: isSvgLikeSrc(node.image.src) ? style.tintColor : undefined,\n radius,\n })\n painter.restore()\n }\n\n // text\n if (node.type === \"text\" && node.lines && node.lines.length > 0) {\n paintText(node, painter, host)\n }\n\n // input / textarea: the value (or placeholder), single line, clipped, with a caret when focused\n if ((node.type === \"input\" || node.type === \"textarea\") && node.id !== options.editing) {\n paintInput(node, painter, host, radius)\n }\n\n // a surface under the picture: its box is a window onto it. Without one, a video is a sized\n // placeholder\n if (node.type === \"video\" || node.type === \"native\") {\n if (options.surfaces) painter.clearRoundRect(rect, radius)\n else if (node.type === \"video\") paintVideoPlaceholder(node, painter, host, radius)\n }\n\n // clip children to the viewport (scrollable / overflow:hidden)\n if (node.clip) painter.clipRoundRect(rect, radius)\n\n // children\n for (const child of node.children) paintNode(child, painter, host, options)\n\n // a screen's dim: black over its content and children (a transition's pose)\n if (style.dim !== undefined && style.dim > 0) {\n painter.fillRoundRect(rect, radius, Math.round(Math.min(1, style.dim) * 255) >>> 0)\n }\n\n // border on top\n const sides = visibleBorders(style.border)\n if (sides) painter.strokeBorder(rect, radius, sides)\n\n if (grouped) painter.endGroup()\n painter.restore()\n}\n\nfunction bgSizeToFit(size: \"cover\" | \"contain\" | \"tile\" | undefined): \"cover\" | \"contain\" | \"fill\" {\n // tile isn't supported yet — fall back to cover.\n return size === \"contain\" ? \"contain\" : \"cover\"\n}\n\nfunction visibleBorders(border: RenderNode[\"style\"][\"border\"]): Borders | null {\n if (!border) return null\n const out: Borders = {}\n let any = false\n for (const side of [\"top\", \"right\", \"bottom\", \"left\"] as const) {\n const sd = border[side]\n if (sd && sd.width > 0 && (sd.color >>> 0) % 256 !== 0) {\n out[side] = sd\n any = true\n }\n }\n return any ? out : null\n}\n\n// The painter gets a raw ctx (no host), so the host's family mapping (CSS-generic aliases,\n// headless concrete faces) is applied here, when the FontSpec is built.\nconst familyOf = (host: Host, family: string | undefined) => {\n const fam = family ?? \"Roboto\"\n return host.resolveFontFamily?.(fam) ?? fam\n}\n\nfunction paintText(node: RenderNode, painter: Painter, host: Host) {\n const s = node.style\n const font: FontSpec = {\n family: familyOf(host, s.fontFamily),\n size: s.fontSize ?? 14,\n weight: s.fontWeight ?? 400,\n italic: s.fontStyle === \"italic\",\n letterSpacing: s.letterSpacing ?? 0,\n }\n const color = s.color ?? 0x000000ff\n const lineHeight = s.lineHeight\n const align = s.textAlign ?? \"start\"\n const metrics = host.fontMetrics(font)\n const { rect, lines } = node\n // The rect is the border box; inset by the node's own padding (the lines were already wrapped to\n // this content width in renderTree). Matches the DOM, which applies padding via box-sizing.\n const pl = node.padding?.[0] ?? 0\n const pt = node.padding?.[1] ?? 0\n const pr = node.padding?.[2] ?? 0\n const contentX = rect.x + pl\n const contentW = rect.width - pl - pr\n\n for (let i = 0; i < lines!.length; i++) {\n const line = lines![i]\n const lineTop = rect.y + pt + i * lineHeight\n const baselineY = lineTop + (lineHeight - (metrics.ascent + metrics.descent)) / 2 + metrics.ascent\n\n const lineWidth = host.measureText(line, font)\n const x =\n align === \"center\"\n ? contentX + (contentW - lineWidth) / 2\n : align === \"end\"\n ? contentX + contentW - lineWidth\n : contentX\n\n painter.fillText(line, x, baselineY, font, color)\n\n if (s.textDecoration === \"underline\" || s.textDecoration === \"line-through\") {\n const thickness = Math.max(1, font.size / 14)\n const y = s.textDecoration === \"underline\" ? baselineY + thickness : baselineY - font.size * 0.3\n painter.fillRoundRect({ x, y, width: lineWidth, height: thickness }, undefined, color)\n }\n }\n}\n\nfunction paintVideoPlaceholder(node: RenderNode, painter: Painter, host: Host, radius: BorderRadius | undefined) {\n const { rect } = node\n // Dark placeholder fill (unless the author set a background), so the video reads as a sized box.\n if (isTransparent(node.style.backgroundColor)) painter.fillRoundRect(rect, radius, 0x111317ff)\n // Centred play glyph.\n const size = Math.min(rect.width, rect.height) * 0.3\n if (size >= 6) {\n const font: FontSpec = { family: \"Roboto\", size, weight: 400, italic: false, letterSpacing: 0 }\n const metrics = host.fontMetrics(font)\n const w = host.measureText(\"▶\", font)\n const x = rect.x + (rect.width - w) / 2\n const baselineY = rect.y + (rect.height - (metrics.ascent + metrics.descent)) / 2 + metrics.ascent\n painter.fillText(\"▶\", x, baselineY, font, 0xffffffcc)\n }\n}\n\nfunction paintInput(node: RenderNode, painter: Painter, host: Host, radius: BorderRadius | undefined) {\n const s = node.style\n const font: FontSpec = {\n family: familyOf(host, s.fontFamily),\n size: s.fontSize ?? 14,\n weight: s.fontWeight ?? 400,\n italic: s.fontStyle === \"italic\",\n letterSpacing: s.letterSpacing ?? 0,\n }\n const value = node.value ?? \"\"\n const empty = value.length === 0\n const masked = s.inputType === \"password\" && !empty\n const display = empty ? (s.placeholder ?? \"\") : masked ? \"•\".repeat(value.length) : value\n const color = empty ? (s.placeholderColor ?? 0x999999ff) : (s.color ?? 0x000000ff)\n const { rect } = node\n // Inset the value/placeholder/caret by the field's own padding (rect is the border box).\n const pl = node.padding?.[0] ?? 0\n const pt = node.padding?.[1] ?? 0\n const pr = node.padding?.[2] ?? 0\n const pb = node.padding?.[3] ?? 0\n const contentX = rect.x + pl\n const contentW = rect.width - pl - pr\n const contentY = rect.y + pt\n const contentH = rect.height - pt - pb\n const metrics = host.fontMetrics(font)\n const lineHeight = s.lineHeight\n const align = s.textAlign ?? \"start\"\n\n // A textarea wraps to the content width and top-aligns its lines; an input is a single line,\n // vertically centred in the field.\n const multiline = node.type === \"textarea\"\n const lines = multiline ? wrapText(display, contentW, (t) => host.measureText(t, font)).lines : [display]\n const lineX = (w: number) =>\n align === \"center\" ? contentX + (contentW - w) / 2 : align === \"end\" ? contentX + contentW - w : contentX\n const lineBaseline = (i: number) =>\n multiline\n ? contentY + i * lineHeight + (lineHeight - (metrics.ascent + metrics.descent)) / 2 + metrics.ascent\n : contentY + (contentH - (metrics.ascent + metrics.descent)) / 2 + metrics.ascent\n\n painter.save()\n painter.clipRoundRect(rect, radius) // keep content inside the field\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]\n if (line.length > 0) painter.fillText(line, lineX(host.measureText(line, font)), lineBaseline(i), font, color)\n }\n\n // Caret at the end of the real value (or the start when empty) while focused. Static (no blink).\n if (node.state?.focused) {\n const valueLines = empty\n ? [\"\"]\n : multiline\n ? wrapText(masked ? \"•\".repeat(value.length) : value, contentW, (t) => host.measureText(t, font)).lines\n : [display]\n const i = valueLines.length - 1\n const lineW = host.measureText(valueLines[i], font)\n const caretX = empty ? lineX(0) : lineX(lineW) + lineW\n const baselineY = lineBaseline(i)\n const caretW = Math.max(1, font.size / 14)\n painter.fillRoundRect(\n { x: caretX, y: baselineY - metrics.ascent, width: caretW, height: metrics.ascent + metrics.descent },\n undefined,\n s.color ?? 0x000000ff,\n )\n }\n painter.restore()\n}\n","import type { BorderRadius, RenderNode, ResolvedStyle } from \"../types\"\nimport { rgbaToHex } from \"../core/util/colors\"\n\nexport interface SerializeOptions {\n /** Decimal places for rects (default 2). */\n precision?: number\n /** Include the `id` (creator-ui node id) — off by default; ids are unstable across runs. */\n includeIds?: boolean\n}\n\n/**\n * Serialize a render tree into a plain, JSON-friendly object — the primary text output. Colors\n * become \"#rrggbbaa\", rects are rounded, and only meaningful fields appear, so the result is\n * readable for AI feedback and stable for snapshot assertions.\n */\nexport function serializeRenderTree(tree: RenderNode | null, opts: SerializeOptions = {}): unknown {\n if (!tree) return null\n return serializeNode(tree, opts.precision ?? 2, opts.includeIds ?? false)\n}\n\n/** Convenience: the serialized tree as pretty JSON text. */\nexport function renderTreeToText(tree: RenderNode | null, opts?: SerializeOptions): string {\n return JSON.stringify(serializeRenderTree(tree, opts), null, 2)\n}\n\n/**\n * Serialize a whole frame — the main screen plus any widget overlays — so the JSON describes\n * everything painted (PNG/JSON parity). Widget trees are attached as an `overlays` array on the main\n * root (they composite above it). With no widgets this returns the bare main tree, unchanged; with no\n * main screen but live widgets it returns `{ type: \"frame\", overlays }`.\n */\nexport function serializeFrame(main: RenderNode | null, widgets: RenderNode[] = [], opts: SerializeOptions = {}): unknown {\n const precision = opts.precision ?? 2\n const includeIds = opts.includeIds ?? false\n const root = main ? serializeNode(main, precision, includeIds) : null\n if (widgets.length === 0) return root\n const overlays = widgets.map((w) => serializeNode(w, precision, includeIds))\n if (root) {\n root.overlays = overlays\n return root\n }\n return { type: \"frame\", overlays }\n}\n\n/** Convenience: the serialized frame (screen + overlays) as pretty JSON text. */\nexport function frameToText(main: RenderNode | null, widgets: RenderNode[] = [], opts?: SerializeOptions): string {\n return JSON.stringify(serializeFrame(main, widgets, opts), null, 2)\n}\n\nfunction round(n: number, p: number): number {\n const f = 10 ** p\n return Math.round(n * f) / f\n}\n\nfunction serializeNode(node: RenderNode, precision: number, includeIds: boolean): any {\n const r = node.rect\n const out: any = { type: node.type }\n if (node.name) out.name = node.name\n out.rect = [round(r.x, precision), round(r.y, precision), round(r.width, precision), round(r.height, precision)]\n if (includeIds) out.id = node.id\n\n const style = serializeStyle(node.style)\n if (style) out.style = style\n\n if (node.text !== undefined) out.text = node.text\n if (node.lines && (node.lines.length !== 1 || node.lines[0] !== node.text)) out.lines = node.lines\n // Editables: show what the field says — its typed value, or the placeholder an empty field\n // renders (also the AI-facing selector for label-less inputs).\n if (node.value !== undefined && node.value !== \"\") out.value = node.value\n if (node.style.placeholder !== undefined) out.placeholder = node.style.placeholder\n if (node.image) {\n out.image = { src: node.image.src, natural: [node.image.naturalWidth, node.image.naturalHeight] }\n }\n if (node.sourceRect) out.sourceRect = node.sourceRect\n if (node.state && (node.state.pressed || node.state.classes?.length)) {\n out.state = {\n ...(node.state.pressed ? { pressed: true } : {}),\n ...(node.state.classes?.length ? { classes: node.state.classes } : {}),\n }\n }\n if (node.scroll) {\n out.scroll = { offset: round(node.scroll.offset, precision), content: round(node.scroll.content, precision) }\n }\n\n if (node.children.length > 0) {\n out.children = node.children.map((c) => serializeNode(c, precision, includeIds))\n }\n return out\n}\n\nfunction radiusObj(radius: BorderRadius) {\n if (radius.tl === radius.tr && radius.tr === radius.br && radius.br === radius.bl) return radius.tl\n return [radius.tl, radius.tr, radius.br, radius.bl]\n}\n\nfunction serializeStyle(s: ResolvedStyle): Record<string, unknown> | undefined {\n const out: Record<string, unknown> = {}\n if (s.backgroundColor !== undefined) out.backgroundColor = rgbaToHex(s.backgroundColor)\n if (s.opacity !== undefined) out.opacity = s.opacity\n if (s.color !== undefined) out.color = rgbaToHex(s.color)\n if (s.fontSize !== undefined) out.fontSize = s.fontSize\n if (s.fontFamily !== undefined) out.fontFamily = s.fontFamily\n if (s.fontWeight !== undefined) out.fontWeight = s.fontWeight\n if (s.fontStyle !== undefined && s.fontStyle !== \"normal\") out.fontStyle = s.fontStyle\n if (s.lineHeight !== undefined) out.lineHeight = s.lineHeight\n if (s.letterSpacing) out.letterSpacing = s.letterSpacing\n if (s.textAlign !== undefined && s.textAlign !== \"start\") out.textAlign = s.textAlign\n if (s.textDecoration !== undefined && s.textDecoration !== \"none\") out.textDecoration = s.textDecoration\n // Only an ACTIVE clamp is worth showing: `lines` already carries the visible result (with its \"…\"),\n // and `textOverflow` means nothing without a clamp.\n if (s.lineClamp) {\n out.lineClamp = s.lineClamp\n if (s.textOverflow === \"clip\") out.textOverflow = s.textOverflow\n }\n if (s.objectFit !== undefined) out.objectFit = s.objectFit\n if (s.tintColor !== undefined) out.tintColor = rgbaToHex(s.tintColor)\n if (s.overlayColor !== undefined) out.overlayColor = rgbaToHex(s.overlayColor)\n if (s.backgroundImage !== undefined) out.backgroundImage = s.backgroundImage\n if (s.backgroundSize !== undefined) out.backgroundSize = s.backgroundSize\n if (s.backgroundGradients !== undefined && s.backgroundGradients.length > 0) {\n out.backgroundGradients = s.backgroundGradients.map((g) => {\n const stops = g.stops.map((st) => ({ color: rgbaToHex(st.color), position: st.position }))\n if (g.type === \"radial\") {\n const rad: Record<string, unknown> = { type: \"radial\", shape: g.shape, extent: g.extent, cx: g.cx, cy: g.cy, stops }\n if (g.extent === \"explicit\") {\n rad.rx = g.rx\n rad.ry = g.ry\n rad.rxUnit = g.rxUnit\n rad.ryUnit = g.ryUnit\n }\n return rad\n }\n return { angle: g.angle, stops } // linear stays shape-compatible with the pre-radial output\n })\n }\n\n if (s.borderRadius && (s.borderRadius.tl || s.borderRadius.tr || s.borderRadius.br || s.borderRadius.bl)) {\n out.borderRadius = radiusObj(s.borderRadius)\n }\n if (s.border) {\n const b: Record<string, unknown> = {}\n for (const side of [\"top\", \"right\", \"bottom\", \"left\"] as const) {\n const sd = s.border[side]\n if (sd && sd.width > 0) b[side] = { width: sd.width, color: rgbaToHex(sd.color) }\n }\n if (Object.keys(b).length > 0) out.border = b\n }\n\n return Object.keys(out).length > 0 ? out : undefined\n}\n","/// <reference path=\"../contract.d.ts\" />\n// The tree UI: the HostUI table of the runtime (sdk/src/bridges/tree.d.ts `HostUI`) implemented\n// in TypeScript over the wasm runtime module — the shared core of the web renderers (the canvas\n// mount in the browser, the DOM renderer, the headless host). The runtime OWNS the tree (creator-ui\n// Yoga, the screens / destinations / widgets / pager / vlist); this class keeps one HNode per node\n// id (the yoga pointer), the paint-ready style creator-ui's handlers write into it, the content\n// properties, and the boxes of the last layout pass — and turns them into the render tree (the\n// RenderNode: the semantic JSON AND the paint source), hit-tests pointers over it and reports what\n// happened back to the runtime through the creatorWeb* entry points (node events, touches, scroll,\n// focus / change). Nothing of JavaScript reaches it: the SDK's element objects live behind the\n// runtime's emitter.\nimport type { WasmModule } from \"lecodes-web-runtime/src/gen/wasm\"\nimport type { WasmHostUI } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport { paintPending, readPaintOf, syncPaint, type PaintModule } from \"../layout/creatorUi/paint-read\"\nimport type { CreatorUiModule } from \"../layout/creatorUi/loadCreatorUi\"\nimport type { Host } from \"../host/Host\"\nimport type { Layer, Rect, RenderNode, ResolvedStyle, WorkerNode } from \"../types\"\nimport type { SceneNode } from \"../core/SceneNode\"\nimport type { Painter } from \"../paint/Painter\"\nimport { clampLines, measureEditableNode, measureImageNode, measureTextNode, resolveTextStyle, toFontSpec, wrapText } from \"../core/text\"\nimport { paintFrame, type PaintOptions } from \"../paint/paintTree\"\nimport { frameToText, serializeFrame } from \"../serialize/serializeRenderTree\"\nimport { hitTest } from \"../core/hitTest\"\nimport { svgToDataUri } from \"../core/util/svgSrc\"\nimport {\n TREE_DEST_SCREEN, TREE_EVENT_BLUR, TREE_EVENT_CHANGE, TREE_EVENT_FOCUS, TREE_EVENT_OVERLAY_TAP, TREE_EVENT_OVERSCROLL,\n TREE_EVENT_SCROLL_RELEASE, TREE_EVENT_SUBMIT, TREE_FLAG_BLUR, TREE_FLAG_CHANGE, TREE_FLAG_CLICK, TREE_FLAG_FOCUS,\n TREE_FLAG_INTERACTIVE, TREE_FLAG_LAYOUT, TREE_FLAG_LONG_PRESS, TREE_FLAG_OVERLAY_TAP, TREE_FLAG_OVERSCROLL, TREE_FLAG_SCROLL,\n TREE_FLAG_SCROLL_RELEASE, TREE_FLAG_SUBMIT,\n} from \"lecodes-sdk/ui/tree\"\n\n/** Fraction of the viewport the simulated keyboard occupies while an input is focused (the number\n * every simulator host uses); the focused root re-flows above it (runtime pkgSetShrunkRoot). */\nconst KEYBOARD_FRACTION = 0.32\n/** Drag distance (px) before a press commits to scrolling. */\nconst SCROLL_THRESHOLD = 4\n\n/** One node of the runtime's tree as this renderer sees it. Structurally a web-canvas SceneNode for\n * the shared text / measure helpers (they read `style`, `parent`, `text`, `value`, `sourceRect`). */\n/**\n * The image src as the SDK puts it on the wire (sdk/src/ui/UIImage.ts): a url, `id:<buffer>` (the\n * fetch host serves it), `canvas:<id>` (a baked _creatorCanvas surface → the web-canvas host's\n * `lecodes-canvas://` scheme), `svg:<markup>` (an inline SvgSource → the data-uri the image decoder\n * loads, encoded once per distinct markup). A `scene2d:` source has no image: the box is the render.\n */\nconst svgUris = new Map<string, string>()\nfunction wireSrc(s: string | undefined): string | undefined {\n if (!s) return s\n if (s.startsWith(\"canvas:\")) return `lecodes-canvas://${s.slice(7)}`\n if (s.startsWith(\"svg:\")) {\n let uri = svgUris.get(s)\n if (uri === undefined) { uri = svgToDataUri(s.slice(4)); svgUris.set(s, uri) }\n return uri\n }\n return s\n}\n\nexport class HNode {\n parent: HNode | null = null\n children: HNode[] = []\n style: ResolvedStyle = { lineHeight: 14 * 1.2 } // the core's fresh-node record; the first paint sync replaces it\n name?: string\n text = \"\"\n src: string | undefined\n value = \"\"\n sourceRect?: [number, number, number, number]\n viewName?: string\n viewParams?: string\n /** \"playerId\" of a video node / \"viewId\" of a native node (setPropertyInt). */\n playerId = 0\n viewId = 0\n flags = 0\n /** The box of the last layout pass (parent-relative; a root's is its own frame). */\n layoutRect: Rect | null = null\n scrollOffset = 0\n wrapCache?: { key: string, lines: string[] }\n /** The minimal WorkerNode the shared helpers expect (unused fields). */\n readonly jsNode: Record<string, unknown>\n constructor(readonly id: number, readonly type: string) { this.jsNode = { type, _id: id } }\n get measured(): boolean { return this.type === \"text\" || this.type === \"image\" || this.editable }\n get editable(): boolean { return this.type === \"input\" || this.type === \"textarea\" }\n get scrollable(): boolean { return this.type === \"scrollable\" || this.type === \"scrollableScreen\" || this.type === \"vlist\" }\n get scrollAxis(): \"x\" | \"y\" { return this.style.scrollAxis === \"x\" ? \"x\" : \"y\" }\n get interactive(): boolean { return (this.flags & TREE_FLAG_INTERACTIVE) !== 0 }\n get imageSrcRaw(): unknown { return this.type === \"image\" ? wireSrc(this.src) : undefined }\n has(flag: number): boolean { return (this.flags & flag) !== 0 }\n}\n\ntype Gesture = {\n node: HNode | null // the pressed interactive node\n scroll: HNode | null // the overflowing scrollable this gesture may drive\n backdrop: HNode | null // a modal widget whose backdrop was tapped\n edit: HNode | null // the editable the press landed in\n global: boolean // fell through to the scene\n dismiss: boolean // a clean release blurs the focused input\n lastX: number\n lastY: number\n acc: number\n scrolling: boolean\n swallowClick: boolean // a long-press listener took the gesture\n}\n\nexport type TreeUIOptions = {\n /** The app-facing keyboard listener state: the host reports the band height through the runtime. */\n onKeyboard?: (height: number) => void\n /** The band the on-screen keyboard takes while an input is focused, in logical px. Absent = a\n * simulated one (a fixed fraction of the height: the headless host, where nothing else tells);\n * a browser page answers with what its window really loses. */\n keyboardHeight?: () => number\n /** A toast to show (the headless host records it, a browser mount paints one). */\n onToast?: (message: string, duration: number) => void\n}\n\nexport class TreeUI implements WasmHostUI {\n readonly nodes = new Map<number, HNode>()\n /** The presented screen root (TREE_DEST_SCREEN), null while a scene / nothing is presented. */\n root: HNode | null = null\n /** The screen that LEFT and is still shown: the runtime moves it and the incoming one through\n * their own transform / opacity / dim (a transition is tween tracks on the roots — a host plays\n * none of its own) and drops it when the transition lands (dropView). Painted only. */\n leaving: HNode | null = null\n /** …over the current screen, else under it. */\n leavingAbove = false\n /** Per pager: the page its current tab shows, and the one that left that place and is still\n * shown — the runtime moves both through their own transform / opacity / dim and says when the\n * one that left goes (HostUI.pagerShowPage / pagerDropPage). `above` = over the page shown. */\n private pagerShown = new Map<number, HNode>()\n private pagerLeaving = new Map<number, { page: HNode, above: boolean }>()\n /** TREE_DEST_* of the current destination, -1 when none. */\n destKind = -1\n readonly widgetRoots: HNode[] = []\n width = 0\n height = 0\n private focused: HNode | null = null\n private readonly pressed = new Set<number>()\n private readonly gestures = new Map<number, Gesture>()\n private readonly vlists = new Set<HNode>()\n private frameCache: Layer[] | null = null\n private painted: Layer[] | null = null\n private fontsPending = 0\n private lastToast: string | null = null\n /** Bumped by every mutation; the render tree is rebuilt when it changed. */\n private dirty = true\n /** The host's hook on the destination change (TREE_DEST_*; -1 = none) — `id` is the sceneId of a\n * scene destination: it shows / hides its scene canvases. */\n onDestination: ((kind: number, id: number) => void) | null = null\n /** The destination that left was dropped (HostUI.dropView): the host takes a surface away here,\n * not when the next destination opens — a screen may still be coming in over it. */\n onDropped: ((kind: number, id: number) => void) | null = null\n\n constructor(readonly M: WasmModule, readonly host: Host, private readonly options: TreeUIOptions = {}) {}\n\n // ---- setup ------------------------------------------------------------------------------------\n /** Register the measure function with creator-ui (once, before any node). Style needs no\n * registration: the runtime keeps every node's paint record, this renderer reads it (paint-read.ts). */\n install(): void {\n const view = new DataView(new ArrayBuffer(8))\n const measure = (_screenId: number, nodePtr: number, width: number, _wType: number, height: number, _hType: number): bigint => {\n const r = this.measure(nodePtr, width, height)\n view.setFloat32(4, r.width, true)\n view.setFloat32(0, r.height, true)\n return view.getBigUint64(0, true)\n }\n this.M._setMeasureFunc(this.M.addFunction(measure, \"jiififi\"))\n }\n\n private measure(nodeId: number, width: number, height: number): { width: number, height: number } {\n const n = this.nodes.get(nodeId)\n if (!n) return { width: 0, height: 0 }\n // A layout the runtime runs before this frame's sync (it lays a screen out when it presents\n // it) must still measure with the font the record holds NOW.\n const P = this.M as unknown as PaintModule\n if (paintPending(P, nodeId)) readPaintOf(P, nodeId, n.style)\n const sn = n as unknown as SceneNode\n if (n.type === \"text\") return measureTextNode(sn, this.host, width)\n if (n.type === \"image\") return measureImageNode(sn, this.host, width, height)\n if (n.editable) return measureEditableNode(sn, this.host, width)\n return { width: 0, height: 0 }\n }\n\n /** The viewport in logical px; safe-area insets in CSS order + the system-bar edges. */\n resize(width: number, height: number): void {\n this.width = width\n this.height = height\n this.M._creatorWebResize(width, height)\n this.M._setConditionValue(width, height)\n this.dirty = true\n }\n setSafeArea(area: [number, number, number, number] | null, bars: readonly (\"top\" | \"right\" | \"bottom\" | \"left\")[] = []): void {\n const [t, r, b, l] = area ?? (this.width > this.height ? [0, 8, 0, 20] : [20, 0, 8, 0])\n const BIT = { top: 1, right: 2, bottom: 4, left: 8 }\n this.M._setSafeAreaBars(bars.reduce((m, e) => m | BIT[e], 0))\n this.M._setSafePaddings(t, r, b, l, 0)\n this.dirty = true\n }\n\n // ---- the frame ---------------------------------------------------------------------------------\n /** After a runtime tick: lay every live root out (the runtime's pass), read the boxes, settle the\n * virtualized lists, report onLayout to the nodes that listen. */\n layoutFrame(): void {\n const M = this.M\n // Every style write since the last frame sits in the core's dirty paint records: take them\n // BEFORE layout (measure reads the font) — a non-empty batch is a mutation of the render tree.\n const changed = syncPaint(M as unknown as PaintModule, (ptr, read) => {\n const node = this.nodes.get(ptr)\n if (node) read(node.style)\n })\n if (changed > 0) this.dirty = true\n const n = M._creatorWebLayoutFrame(this.width, this.height)\n if (n > 0) this.readLayoutBatch(n)\n for (const v of this.vlists) {\n if (!M._vlistExists(v.id)) continue\n M._vlistUpdateLayout(v.id)\n // the mounted items are detached core roots the batch never visits: read their boxes here\n for (const item of v.children) this.deliverSubtree(item)\n }\n }\n /** Whether the render tree changed since the last `frame()` (a mount paints only then). */\n /** Whether the picture is behind the tree: something changed since the frame that was PAINTED.\n * Not since the frame that was last built — a hit test or a hover builds one between a change\n * and the paint, and the change is still owed its picture. */\n needsPaint(): boolean { return this.dirty || this.frameCache === null || this.frameCache !== this.painted }\n /** Consume a subtree's new layouts (getLayoutPointer: one-shot per node) into the cached boxes. */\n private deliverSubtree(node: HNode): void {\n const M = this.M\n if (!this.layoutPtr) this.layoutPtr = M._malloc(16)\n if (M._getLayoutPointer(node.id, this.layoutPtr)) {\n const i = this.layoutPtr >> 2\n const rect = { x: M.HEAPF32[i], y: M.HEAPF32[i + 1], width: M.HEAPF32[i + 2], height: M.HEAPF32[i + 3] }\n const old = node.layoutRect\n const changed = !old || old.x !== rect.x || old.y !== rect.y || old.width !== rect.width || old.height !== rect.height\n node.layoutRect = rect\n if (changed) this.dirty = true\n if (changed && node.has(TREE_FLAG_LAYOUT)) M._creatorWebNodeLayout(node.id, rect.x, rect.y, rect.width, rect.height)\n }\n for (const c of node.children) this.deliverSubtree(c)\n }\n private layoutPtr = 0\n private readLayoutBatch(n: number): void {\n const M = this.M\n const nodesPtr = M._collectNodes() >>> 2\n const rectsPtr = M._collectRects() >>> 2\n const u32 = M.HEAPU32, f32 = M.HEAPF32\n for (let i = 0; i < n; i++) {\n const ptr = u32[nodesPtr + i]\n const node = this.nodes.get(ptr)\n if (!node) continue\n const l = f32[rectsPtr + i * 4], t = f32[rectsPtr + i * 4 + 1], r = f32[rectsPtr + i * 4 + 2], b = f32[rectsPtr + i * 4 + 3]\n const rect = { x: l, y: t, width: r - l, height: b - t }\n const old = node.layoutRect\n const changed = !old || old.x !== rect.x || old.y !== rect.y || old.width !== rect.width || old.height !== rect.height\n node.layoutRect = rect\n if (changed) this.dirty = true\n if (changed && node.has(TREE_FLAG_LAYOUT)) M._creatorWebNodeLayout(ptr, l, t, rect.width, rect.height)\n }\n }\n\n /** Every compositing layer, bottom-to-top: the screen — and the one that left, under or over it\n * — then the widgets in show order. */\n frame(): Layer[] {\n if (this.frameCache && !this.dirty) return this.frameCache\n const layers: Layer[] = []\n const viewport = { x: 0, y: 0, width: this.width, height: this.height }\n const left = this.leaving ? this.build(this.leaving, viewport) : null\n if (left && !this.leavingAbove) layers.push({ tree: left, leaving: true })\n if (this.root) {\n const tree = this.build(this.root, viewport)\n if (tree) layers.push({ tree })\n }\n if (left && this.leavingAbove) layers.push({ tree: left, leaving: true })\n for (const w of this.widgetRoots) {\n const box = w.layoutRect ?? { x: 0, y: 0, width: this.width, height: this.height }\n const tree = this.build(w, box)\n if (!tree) continue\n const color = tree.style.overlayColor\n layers.push({ tree, widget: true, backdrop: color !== undefined ? { color, jsNode: w.jsNode as WorkerNode } : undefined })\n }\n this.frameCache = layers\n this.dirty = false\n return layers\n }\n renderTree(): RenderNode | null { return this.frame().find((l) => !l.widget && !l.leaving)?.tree ?? null }\n widgetTrees(): RenderNode[] { return this.frame().filter((l) => l.widget).map((l) => l.tree) }\n /** The widget overlay trees, in show order (the scenario engine reads them). */\n widgets(): RenderNode[] { return this.widgetTrees() }\n serialize(): unknown { return serializeFrame(this.renderTree(), this.widgetTrees()) }\n toText(): string { return frameToText(this.renderTree(), this.widgetTrees()) }\n paint(painter: Painter, options?: PaintOptions): void {\n const frame = this.frame()\n paintFrame(frame, painter, this.host, this.width, this.height, undefined, options)\n this.painted = frame\n }\n\n /** The absolute, fully-resolved render tree of a root (the web-canvas builder, over the runtime's\n * boxes: a pager shows its selected page, a vlist places its mounted items at the core's offsets). */\n private build(root: HNode, rootRect: Rect): RenderNode | null {\n const M = this.M\n const walk = (node: HNode, px: number, py: number, isRoot: boolean): RenderNode | null => {\n if (node.style.display === \"none\") return null\n let x: number, y: number, width: number, height: number\n if (isRoot) { x = rootRect.x; y = rootRect.y; width = rootRect.width; height = rootRect.height }\n else {\n const rel = node.layoutRect\n if (!rel) return null\n x = px + rel.x; y = py + rel.y; width = rel.width; height = rel.height\n }\n const out: RenderNode = { id: node.id, type: node.type, rect: { x, y, width, height }, style: node.style, children: [] }\n if (node.name) out.name = node.name\n const sn = node as unknown as SceneNode\n if (node.type === \"text\") {\n const t = resolveTextStyle(sn)\n const font = toFontSpec(t)\n out.text = node.text\n const pad = this.padding(node.id)\n if (pad[0] || pad[1] || pad[2] || pad[3]) out.padding = pad\n const contentW = width - pad[0] - pad[2]\n const key = `${contentW}|${font.size}|${font.weight}|${font.italic ? 1 : 0}|${font.letterSpacing}|${font.family}|${node.style.lineClamp ?? 0}|${node.style.textOverflow ?? \"\"}|${node.text}`\n if (node.wrapCache?.key === key) out.lines = node.wrapCache.lines\n else {\n const measure = (s: string) => this.host.measureText(s, font)\n const lines = clampLines(wrapText(node.text, contentW, measure).lines, node.style, contentW, measure)\n node.wrapCache = { key, lines }\n out.lines = lines\n }\n out.style = { ...node.style, color: t.color, fontSize: t.fontSize, fontFamily: t.fontFamily, fontWeight: t.fontWeight, fontStyle: t.fontStyle, lineHeight: t.lineHeight, letterSpacing: t.letterSpacing, textAlign: t.textAlign, textDecoration: t.textDecoration }\n } else if (node.type === \"image\") {\n const src = this.host.resolveSrc(node.imageSrcRaw)\n const info = src ? this.host.getImage(src) : undefined\n out.image = info ?? (src ? { src, naturalWidth: 0, naturalHeight: 0 } : undefined)\n if (node.sourceRect) out.sourceRect = node.sourceRect\n } else if (node.editable) {\n out.value = node.value\n const pad = this.padding(node.id)\n if (pad[0] || pad[1] || pad[2] || pad[3]) out.padding = pad\n const t = resolveTextStyle(sn)\n out.style = { ...node.style, color: t.color, fontSize: t.fontSize, fontFamily: t.fontFamily, fontWeight: t.fontWeight, fontStyle: t.fontStyle, lineHeight: t.lineHeight, letterSpacing: t.letterSpacing, textAlign: t.textAlign, textDecoration: t.textDecoration }\n }\n if (node.interactive) out.state = { pressed: this.pressed.has(node.id) }\n if (node.editable && this.focused === node) out.state = { ...out.state, focused: true }\n if (node.style.overflow === \"hidden\") out.clip = true\n let childX = x, childY = y\n if (node.scrollable) {\n const axis = node.scrollAxis\n const content = axis === \"x\" ? M._getContentWidth(node.id) : M._getContentHeight(node.id)\n out.clip = true\n out.scroll = { offset: node.scrollOffset, content, axis }\n if (axis === \"x\") childX = x - node.scrollOffset\n else childY = y - node.scrollOffset\n }\n if (node.type === \"pager\") {\n // the selected tab's top page: an independent root laid out at the pager's box\n const tab = M._creatorWebPagerSelectedIndex(node.id)\n const len = M._creatorWebPagerStackLen(node.id, tab)\n const pageId = len > 0 ? M._creatorWebPagerPageNode(node.id, tab, len - 1) : 0\n const page = pageId ? this.nodes.get(pageId) : undefined\n if (page) this.pagerShown.set(node.id, page); else this.pagerShown.delete(node.id)\n const left = this.pagerLeaving.get(node.id)\n for (const p of left && left.page !== page ? (left.above ? [page, left.page] : [left.page, page]) : [page]) {\n const r = p ? walk(p, x, y, false) : null\n if (r) out.children.push(r)\n }\n return out\n }\n if (node.type === \"vlist\") {\n // mounted items: each a detached core root at the offset the window math gave it\n for (const child of node.children) {\n const itemRoot = M._getParentNode(child.id)\n if (!itemRoot) continue\n const off = M._vlistItemOffsetOf(node.id, itemRoot)\n if (Number.isNaN(off)) continue\n const rel = child.layoutRect ?? { x: 0, y: 0, width: 0, height: 0 }\n const r = walk(child, x - rel.x, y + off - node.scrollOffset - rel.y, false)\n if (r) out.children.push(r)\n }\n return out\n }\n for (const child of node.children) { const r = walk(child, childX, childY, false); if (r) out.children.push(r) }\n return out\n }\n return walk(root, 0, 0, true)\n }\n /** A node's resolved padding, [left, top, right, bottom] (an inspector's). */\n paddingOf(nodeId: number): [number, number, number, number] { return this.padding(nodeId) }\n private padding(nodeId: number): [number, number, number, number] {\n const M = this.M\n if (!this.padPtr) this.padPtr = M._malloc(16)\n M._getPaddingPointer(nodeId, this.padPtr)\n const i = this.padPtr >> 2\n return [M.HEAPF32[i], M.HEAPF32[i + 1], M.HEAPF32[i + 2], M.HEAPF32[i + 3]]\n }\n private padPtr = 0\n /** Call an export that takes a C string. */\n private withStr<T>(s: string, fn: (ptr: number) => T): T {\n const p = this.M.stringToNewUTF8(s)\n try { return fn(p) } finally { this.M._free(p) }\n }\n\n // ---- lookups ---------------------------------------------------------------------------------------\n get(id: number): HNode | undefined { return this.nodes.get(id) }\n /** Rendered nodes by their author-given `name`, the screen first, then the widgets. */\n findAll(name: string): RenderNode[] {\n const out: RenderNode[] = []\n const walk = (n: RenderNode) => { if (n.name === name) out.push(n); for (const c of n.children) walk(c) }\n for (const l of this.frame()) walk(l.tree)\n return out\n }\n /** The absolute rect of a rendered node, null when it is not on screen. */\n findRect(id: number): Rect | null {\n const walk = (n: RenderNode): Rect | null => {\n if (n.id === id) return n.rect\n for (const c of n.children) { const r = walk(c); if (r) return r }\n return null\n }\n for (const l of this.frame()) { const r = walk(l.tree); if (r) return r }\n return null\n }\n /** The last toast shown (the host paints none). */\n toast(): string | null { return this.lastToast }\n pendingFonts(): number { return this.fontsPending }\n keyboardHeight(): number {\n if (!this.focused) return 0\n return this.options.keyboardHeight ? this.options.keyboardHeight() : Math.round(this.height * KEYBOARD_FRACTION)\n }\n focusedId(): number { return this.focused?.id ?? 0 }\n\n // ---- HostUI: the tree ---------------------------------------------------------------------------\n /** The node the runtime made last (an inspector ties the element the SDK is making to it). */\n lastCreated = 0\n nodeFactory(id: number, type: string, parent: number, index: number): void {\n this.lastCreated = id\n const n = new HNode(id, type)\n this.nodes.set(id, n)\n if (type === \"vlist\") this.vlists.add(n)\n const p = this.nodes.get(parent)\n if (p) this.link(p, n, Math.max(0, index))\n this.dirty = true\n }\n private link(p: HNode, c: HNode, index: number): void {\n if (c.parent) c.parent.children = c.parent.children.filter((x) => x !== c)\n c.parent = p\n p.children.splice(Math.min(index, p.children.length), 0, c)\n }\n insertNode(parent: number, child: number, index: number): void {\n const p = this.nodes.get(parent), c = this.nodes.get(child)\n if (p && c) this.link(p, c, index)\n this.dirty = true\n }\n removeNode(parent: number, child: number): void {\n const p = this.nodes.get(parent), c = this.nodes.get(child)\n if (!p || !c) return\n this.forget(c)\n p.children = p.children.filter((x) => x !== c)\n if (c.parent === p) c.parent = null\n if (this.pagerLeaving.get(parent)?.page === c) this.pagerLeaving.delete(parent)\n if (this.pagerShown.get(parent) === c) this.pagerShown.delete(parent)\n this.dirty = true\n }\n releaseNode(id: number): void {\n const n = this.nodes.get(id)\n if (!n) return\n this.nodes.delete(id)\n this.forget(n)\n if (n.parent) n.parent.children = n.parent.children.filter((x) => x !== n)\n if (this.root === n) this.root = null\n if (this.leaving === n) this.leaving = null\n this.pagerShown.delete(id)\n this.pagerLeaving.delete(id)\n for (const [pager, left] of this.pagerLeaving) if (left.page === n) this.pagerLeaving.delete(pager)\n if (this.focused === n) { this.focused = null; this.M._creatorWebSetShrunkRoot(0, 0); this.emitKeyboard() }\n const wi = this.widgetRoots.indexOf(n)\n if (wi >= 0) this.widgetRoots.splice(wi, 1)\n this.vlists.delete(n)\n this.pressed.delete(id)\n this.dirty = true\n }\n /** A node leaving the tree must leave every in-flight gesture too. */\n private forget(n: HNode): void {\n for (const g of this.gestures.values()) {\n if (g.node === n) g.node = null\n if (g.scroll === n) g.scroll = null\n if (g.backdrop === n) g.backdrop = null\n if (g.edit === n) g.edit = null\n }\n for (const c of n.children) this.forget(c)\n }\n\n // ---- HostUI: content -----------------------------------------------------------------------------\n setPropertyString(id: number, prop: string, value: string | null): void {\n const n = this.nodes.get(id)\n if (!n) return\n const v = value ?? \"\"\n switch (prop) {\n case \"text\": n.text = v; n.wrapCache = undefined; break\n case \"value\": n.value = v; break\n case \"name\": n.name = v || undefined; break\n case \"src\": {\n n.src = v || undefined\n const src = this.host.resolveSrc(this.srcOf(n))\n if (src && !this.host.getImage(src)) {\n this.host.loadImage(src).then(() => { if (this.nodes.get(id) === n && this.M._nodeHasMeasure(id)) this.M._markNodeDirty(id); this.dirty = true }).catch(() => {})\n }\n break\n }\n case \"sourceRect\": {\n const p = v.split(\" \").map(Number)\n n.sourceRect = p.length === 4 ? [p[0], p[1], p[2], p[3]] : undefined\n break\n }\n case \"focus\": if (v === \"1\" || v === \"true\") this.focusInput(id); else if (this.focused === n) this.blurInput(); break\n case \"viewName\": n.viewName = v; break\n case \"viewParams\": n.viewParams = v; break\n default: break // viewParams, placeholder-like props reach the style through creator-ui\n }\n this.dirty = true\n }\n private srcOf(n: HNode): unknown { return wireSrc(n.src) }\n setPropertyInt(id: number, prop: string, value: number): void {\n const n = this.nodes.get(id)\n if (n) { if (prop === \"playerId\") n.playerId = value; else if (prop === \"viewId\") n.viewId = value }\n this.dirty = true\n }\n setFlags(id: number, mask: number): void { const n = this.nodes.get(id); if (n) n.flags = mask >>> 0 }\n\n // ---- HostUI: presentation -------------------------------------------------------------------------\n /** The screen that was shown stays painted until the runtime drops it — one at a time: the\n * runtime lands a transition before it starts the next one. */\n private leave(above: boolean): void {\n if (!this.root) return\n this.leaving = this.root\n this.leavingAbove = above\n this.root = null\n }\n openView(kind: number, node: number, id: number, _viewName: string, _paramsJson: string, above: boolean): void {\n this.destKind = kind\n const next = kind === TREE_DEST_SCREEN ? this.nodes.get(node) ?? null : null\n if (next !== this.root) this.leave(!above || next === null) // a screen next to a surface is above it\n if (this.leaving === next) this.leaving = null\n this.root = next\n if (this.focused) this.blurInput() // a navigation dismisses the keyboard\n this.dirty = true\n this.onDestination?.(kind, id)\n }\n dropView(kind: number, node: number, id: number): void {\n if (kind === TREE_DEST_SCREEN) {\n const n = this.nodes.get(node) ?? null\n if (n !== null && this.leaving === n) this.leaving = null\n if (n !== null && this.root === n) this.root = null\n }\n this.dirty = true\n this.onDropped?.(kind, id)\n }\n closeView(): void { this.destKind = -1; this.leave(true); this.dirty = true; this.onDestination?.(-1, 0) }\n widgetOpen(node: number, _ownerKind: number, _ownerId: number, _ownerNode: number): void {\n const w = this.nodes.get(node)\n if (w && !this.widgetRoots.includes(w)) this.widgetRoots.push(w)\n this.dirty = true\n }\n widgetClose(node: number): void {\n const w = this.nodes.get(node)\n for (const g of this.gestures.values()) if (g.backdrop === w) g.backdrop = null\n const i = w ? this.widgetRoots.indexOf(w) : -1\n if (i >= 0) this.widgetRoots.splice(i, 1)\n this.dirty = true\n }\n registerFont(url: string, fontFamily: string, weight: number, style: number, onComplete: () => void, onReject: (err: string) => void): void {\n this.fontsPending++\n this.host.loadFont(fontFamily, url, { weight, style: style === 2 ? \"italic\" : \"normal\" })\n .then(() => { this.invalidateText(); onComplete() }, (e) => onReject(String(e)))\n .finally(() => { this.fontsPending-- })\n }\n /** A late face changes metrics without touching any style: re-measure every text leaf. */\n private invalidateText(): void {\n for (const n of this.nodes.values()) {\n n.wrapCache = undefined\n if (n.measured && n.type !== \"image\" && this.M._nodeHasMeasure(n.id)) this.M._markNodeDirty(n.id)\n }\n this.dirty = true\n }\n showToast(message: string, duration: number): void { this.lastToast = message; this.options.onToast?.(message, duration) }\n getButtonPressed(node: number): boolean { return this.pressed.has(node) }\n getTextValue(node: number): string { return this.nodes.get(node)?.value ?? \"\" }\n getBoundingRect(node: number): ArrayLike<number> | null {\n const r = this.findRect(node)\n return r ? [r.x, r.y, r.width, r.height] : null\n }\n longPressHandler(pointerId: number, _node: number): void {\n const g = this.gestures.get(pointerId)\n if (g) g.swallowClick = true\n }\n vlistScroll(node: number, scrollY: number, _animated: boolean): void {\n const n = this.nodes.get(node)\n if (n) n.scrollOffset = scrollY\n this.dirty = true\n }\n /** \"select\" / \"content\": the pages are re-read from the runtime's pulls when the frame is built;\n * nothing is in flight then (the runtime lands a pager's transition before either). */\n pagerCommand(node: number, _cmd: string, _animated: boolean): void {\n this.pagerLeaving.delete(node)\n this.dirty = true\n }\n /** `page` is the top of the current tab now: the page shown there stays shown, under it or over\n * it, until the runtime drops it. */\n pagerShowPage(node: number, page: number, above: boolean): void {\n const next = this.nodes.get(page), shown = this.pagerShown.get(node)\n if (next) this.pagerShown.set(node, next)\n if (shown && shown !== next) this.pagerLeaving.set(node, { page: shown, above: !above })\n this.dirty = true\n }\n pagerDropPage(node: number, page: number): void {\n if (this.pagerLeaving.get(node)?.page.id === page) this.pagerLeaving.delete(node)\n this.dirty = true\n }\n pagerPageMounted(_page: number, _mounted: boolean): void { this.dirty = true }\n refreshDone(_node: number): void {}\n\n // ---- input: focus + values --------------------------------------------------------------------------\n private rootOf(n: HNode): HNode { let r = n; while (r.parent) r = r.parent; return r }\n private emitKeyboard(): void {\n const h = this.keyboardHeight()\n this.options.onKeyboard?.(h)\n this.M._creatorWebKeyboardEvent(h, 0)\n }\n focusInput(id: number): void {\n const n = this.nodes.get(id)\n if (!n || !n.editable || this.focused === n) return\n if (this.focused) this.blurInput()\n this.focused = n\n this.M._setNodeFocused(id, 1)\n if (n.has(TREE_FLAG_FOCUS)) this.M._creatorWebNodeEvent(id, TREE_EVENT_FOCUS)\n // the focused-root rule: only the root that owns the input re-flows above the keyboard band\n this.M._creatorWebSetShrunkRoot(this.rootOf(n).id, this.keyboardHeight())\n this.emitKeyboard()\n this.dirty = true\n }\n blurInput(): void {\n const n = this.focused\n if (!n) return\n this.focused = null\n this.M._setNodeFocused(n.id, 0)\n if (n.has(TREE_FLAG_BLUR)) this.M._creatorWebNodeEvent(n.id, TREE_EVENT_BLUR)\n this.M._creatorWebSetShrunkRoot(0, 0)\n this.emitKeyboard()\n this.dirty = true\n }\n /** A value typed by the user: onChange fires (a code-set value comes through setPropertyString). */\n setInputValue(id: number, value: string): void {\n const n = this.nodes.get(id)\n if (!n) return\n n.value = value\n if (n.has(TREE_FLAG_CHANGE)) this.withStr(value, (p) => this.M._creatorWebNodeEventStr(id, TREE_EVENT_CHANGE, p))\n if (this.M._nodeHasMeasure(id)) this.M._markNodeDirty(id)\n this.dirty = true\n }\n /** The return key on the focused input: onSubmit with its value, then the keyboard goes. */\n submitInput(): boolean {\n const n = this.focused\n if (!n) return false\n if (n.has(TREE_FLAG_SUBMIT)) this.withStr(n.value, (p) => this.M._creatorWebNodeEventStr(n.id, TREE_EVENT_SUBMIT, p))\n if (this.focused === n) this.blurInput()\n return true\n }\n\n // ---- input: scrolling ---------------------------------------------------------------------------------\n private scrollMax(n: HNode): number {\n const rect = this.findRect(n.id) ?? n.layoutRect ?? { width: 0, height: 0 }\n const viewport = n.scrollAxis === \"x\" ? rect.width : rect.height\n const content = n.scrollAxis === \"x\" ? this.M._getContentWidth(n.id) : this.M._getContentHeight(n.id)\n return Math.max(0, content - viewport)\n }\n /** Scroll a scrollable by `delta` px along its axis (clamped); onScroll / onOverscroll fire. */\n scrollBy(id: number, delta: number): boolean {\n const n = this.nodes.get(id)\n if (!n || !n.scrollable) return false\n const max = this.scrollMax(n)\n const desired = n.scrollOffset + delta\n const next = Math.min(max, Math.max(0, desired))\n const over = desired < 0 ? desired : desired > max ? desired - max : 0\n if (over !== 0 && n.has(TREE_FLAG_OVERSCROLL)) this.M._creatorWebNodeEventNum(id, TREE_EVENT_OVERSCROLL, over)\n if (next === n.scrollOffset) return false\n n.scrollOffset = next\n if (n.type === \"vlist\" && this.M._vlistExists(id)) this.M._vlistOnScroll(id, next)\n if (n.has(TREE_FLAG_SCROLL)) this.M._creatorWebNodeScroll(id, next)\n this.dirty = true\n return true\n }\n\n // ---- input: pointers (the tgfx renderer's routing, over the render tree) -----------------------------------\n private topInteractive(x: number, y: number): HNode | null {\n const layers = this.frame()\n for (let i = layers.length - 1; i >= 0; i--) {\n const hit = hitTest(layers[i].tree, x, y, (n) => this.nodes.get(n.id)?.interactive ?? false)\n if (hit) return this.nodes.get(hit.id) ?? null\n if (layers[i].backdrop) return null\n }\n return null\n }\n private setPressed(n: HNode, pressed: boolean): void {\n if (pressed) this.pressed.add(n.id); else this.pressed.delete(n.id)\n if (this.nodes.get(n.id) === n) this.M._setNodePressed(n.id, pressed ? 1 : 0)\n this.dirty = true\n }\n // ---- input: the mouse cursor (hover) — the tgfx renderer's tickHover over the render tree ----------------\n private hoverX = 0\n private hoverY = 0\n private hoverInside = false\n private hoverMoved = false\n /** The cursor's position (logical px), button or not. Only stored: `tickHover` resolves the node\n * under it once per frame and hands it to the runtime (emitHover → `$hovered`, onMouseEnter). */\n pointerHover(x: number, y: number): void { this.hoverX = x; this.hoverY = y; this.hoverInside = true; this.hoverMoved = true }\n /** The cursor left the surface: nothing is hovered. */\n pointerLeave(): void { if (!this.hoverInside) return; this.hoverInside = false; this.hoverMoved = true }\n /** Whether this runtime module routes hover (the export landed with the 2026-09-27 rebuild). */\n get hasHover(): boolean { return typeof this.M._creatorWebHover === \"function\" }\n /** Once per frame, after layout: the topmost interactive node under the cursor → the runtime.\n * Resolved when the cursor moved or the frame changed under a still cursor, never otherwise. */\n tickHover(): void {\n if (!this.hasHover) return\n if (!this.hoverMoved && !this.dirty) return\n this.hoverMoved = false\n const node = this.hoverInside ? this.topInteractive(this.hoverX, this.hoverY) : null\n this.M._creatorWebHover(node?.id ?? 0, this.hoverX, this.hoverY)\n }\n pointerDown(fingerId: number, x: number, y: number): void {\n const M = this.M\n if (M._creatorWeb2dSceneOpen()) M._creatorWeb2dEmitPointer(0, fingerId, x, y)\n const g: Gesture = { node: null, scroll: null, backdrop: null, edit: null, global: false, dismiss: true, lastX: x, lastY: y, acc: 0, scrolling: false, swallowClick: false }\n this.gestures.set(fingerId, g)\n const layers = this.frame()\n // an editable takes the press (focus), a modal backdrop blocks below\n for (let i = layers.length - 1; i >= 0; i--) {\n const e = hitTest(layers[i].tree, x, y, (n) => this.nodes.get(n.id)?.editable ?? false)\n if (e) { const n = this.nodes.get(e.id)!; this.focusInput(n.id); g.edit = n; g.dismiss = false; return }\n if (layers[i].backdrop) break\n }\n for (let i = layers.length - 1; i >= 0; i--) {\n const layer = layers[i]\n const inter = hitTest(layer.tree, x, y, (n) => this.nodes.get(n.id)?.interactive ?? false)\n const scrollHit = hitTest(layer.tree, x, y, (n) => !!n.scroll && n.scroll.content > (n.scroll.axis === \"x\" ? n.rect.width : n.rect.height) + 0.5)\n const scroll = scrollHit ? this.nodes.get(scrollHit.id) ?? null : null\n if (inter) {\n const n = this.nodes.get(inter.id)!\n g.node = n\n g.scroll = scroll\n g.dismiss = n.type !== \"button\" // a control keeps the keyboard up\n this.setPressed(n, true)\n M._creatorWebNodeTouchStart(n.id, fingerId, x, y)\n return\n }\n if (scroll) { g.scroll = scroll; return }\n if (layer.backdrop) {\n const r = layer.tree.rect\n const insideBody = x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height\n g.backdrop = insideBody ? null : this.nodes.get(layer.tree.id) ?? null\n return\n }\n }\n g.global = true\n M._creatorWebSceneTouchStart(fingerId, x, y)\n }\n pointerMove(fingerId: number, x: number, y: number): void {\n const g = this.gestures.get(fingerId)\n if (!g) return\n const M = this.M\n if (M._creatorWeb2dSceneOpen()) M._creatorWeb2dEmitPointer(1, fingerId, x, y)\n const dx = x - g.lastX, dy = y - g.lastY\n g.lastX = x; g.lastY = y\n g.acc += Math.abs(dx) + Math.abs(dy)\n if (g.edit) return\n if (!g.scrolling && g.scroll && g.acc > SCROLL_THRESHOLD) {\n g.scrolling = true\n if (g.node) this.setPressed(g.node, false)\n }\n if (g.scrolling && g.scroll) { this.scrollBy(g.scroll.id, g.scroll.scrollAxis === \"x\" ? -dx : -dy); return }\n M._creatorWebTouchMove(fingerId, x, y, dx, dy)\n }\n pointerUp(fingerId: number, x: number, y: number): void {\n const g = this.gestures.get(fingerId)\n if (!g) return\n this.gestures.delete(fingerId)\n const M = this.M\n if (M._creatorWeb2dSceneOpen()) M._creatorWeb2dEmitPointer(2, fingerId, x, y)\n const dx = x - g.lastX, dy = y - g.lastY\n M._creatorWebTouchEnd(fingerId, x, y, dx, dy)\n if (g.edit) return\n if (g.scrolling && g.scroll && g.scroll.has(TREE_FLAG_SCROLL_RELEASE)) M._creatorWebNodeEvent(g.scroll.id, TREE_EVENT_SCROLL_RELEASE)\n if (g.dismiss && !g.scrolling && this.focused) this.blurInput()\n if (g.node) {\n this.setPressed(g.node, false)\n if (!g.scrolling && !g.swallowClick && this.topInteractive(x, y) === g.node && g.node.has(TREE_FLAG_CLICK)) M._creatorWebNodeClick(g.node.id, fingerId, x, y)\n } else if (g.backdrop) {\n if (!g.scrolling && g.backdrop.has(TREE_FLAG_OVERLAY_TAP)) M._creatorWebNodeEvent(g.backdrop.id, TREE_EVENT_OVERLAY_TAP)\n } else if (g.global) {\n if (!g.scrolling) M._creatorWebSceneTouchClick(fingerId, x, y)\n }\n }\n /** The pointer left without a release (the browser's pointercancel): every gesture state goes. */\n pointerCancel(fingerId: number): void {\n const g = this.gestures.get(fingerId)\n if (!g) return\n this.gestures.delete(fingerId)\n const M = this.M\n if (M._creatorWeb2dSceneOpen()) M._creatorWeb2dEmitPointer(3, fingerId, g.lastX, g.lastY)\n if (g.node) this.setPressed(g.node, false)\n M._creatorWebTouchCancel(fingerId)\n }\n /** A wheel notch over (x, y): scrolls the overflowing scrollable under it (a mouse host). */\n wheel(x: number, y: number, dx: number, dy: number): boolean {\n const layers = this.frame()\n for (let i = layers.length - 1; i >= 0; i--) {\n const hit = hitTest(layers[i].tree, x, y, (n) => !!n.scroll && n.scroll.content > (n.scroll.axis === \"x\" ? n.rect.width : n.rect.height) + 0.5)\n if (hit) { const n = this.nodes.get(hit.id); return n ? this.scrollBy(n.id, n.scrollAxis === \"x\" ? dx : dy) : false }\n if (layers[i].backdrop) return false\n }\n return false\n }\n /** A long press: the runtime asks the node's listener; a handled one swallows the release's click. */\n longPress(fingerId: number, x: number, y: number): void {\n const g = this.gestures.get(fingerId)\n if (g?.node && g.node.has(TREE_FLAG_LONG_PRESS)) this.M._creatorWebNodeLongPress(g.node.id, fingerId, x, y)\n }\n isVlist(n: HNode): boolean { return this.vlists.has(n) }\n}\n","// The TreeUI of a browser page: the painted picture, and the few things a browser shows better than\n// a painter — the way a native host keeps a platform view for them:\n//\n// under the picture a native view (a plugin's web half: a map, a camera) and a video. The\n// painter leaves a window where the node is (`clearRoundRect`), so what the\n// app paints AFTER the node — a button over the map — is over it.\n// over the picture the field being edited: a live <input> / <textarea> in the place of its\n// node, for as long as it has the focus — the caret, the selection, the\n// clipboard and the input method are the browser's. The painter leaves the\n// field's text out meanwhile.\n//\n// Both are placed from the render tree every time it changes: the box of the node, moved by the\n// transforms above it (a screen in a transition carries its field along), cut by the clips above it.\nimport type { WasmModule } from \"lecodes-web-runtime/src/gen/wasm\"\nimport type { WebViewFactory, WebViewInstanceHandle } from \"lecodes-web-shared/src/ui/nativeView\"\nimport { getPlayer } from \"lecodes-web-shared/src/utils/mediaplayer\"\nimport { TREE_DEST_NATIVE } from \"lecodes-sdk/ui/tree\"\nimport { hitTest } from \"../core/hitTest\"\nimport type { Host } from \"../host/Host\"\nimport type { PaintOptions } from \"../paint/paintTree\"\nimport { TreeUI, type TreeUIOptions } from \"../runtime/TreeUI\"\nimport type { Rect, RenderNode } from \"../types\"\n\nconst FIELD_STYLE = `\n.lc-field { position: absolute; left: 0; top: 0; margin: 0; border: none; outline: none; background: none; resize: none; box-sizing: border-box; transform-origin: 0 0; pointer-events: auto; overflow: hidden; -webkit-appearance: none; appearance: none; }\n.lc-field::placeholder { color: var(--lc-placeholder, #999); opacity: 1; }\n`\n\nconst hex = (v: number | undefined, fallback: string) => (v === undefined ? fallback : \"#\" + (v >>> 0).toString(16).padStart(8, \"0\"))\nconst isSurface = (n: { type: string }) => n.type === \"native\" || n.type === \"video\"\n\ntype Matrix = [number, number, number, number, number, number]\nconst IDENTITY: Matrix = [1, 0, 0, 1, 0, 0]\n/** `m` then `n` in the coordinate system `m` made (the painter's `transform`). */\nconst multiply = (m: Matrix, n: Matrix): Matrix => [\n m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1],\n m[0] * n[2] + m[2] * n[3], m[1] * n[2] + m[3] * n[3],\n m[0] * n[4] + m[2] * n[5] + m[4], m[1] * n[4] + m[3] * n[5] + m[5],\n]\nconst intersect = (a: Rect | null, b: Rect): Rect => {\n if (!a) return b\n const x = Math.max(a.x, b.x), y = Math.max(a.y, b.y)\n return { x, y, width: Math.max(0, Math.min(a.x + a.width, b.x + b.width) - x), height: Math.max(0, Math.min(a.y + a.height, b.y + b.height) - y) }\n}\n\n/** Where a node is: its box, the transform of everything above it, the clip of everything above it. */\ntype Place = { node: RenderNode, matrix: Matrix, clip: Rect | null }\n\nexport class BrowserUI extends TreeUI {\n private readonly doc: Document\n private readonly factories = new Map<string, WebViewFactory>()\n private readonly versions = new Map<string, number>()\n private readonly views = new Map<number, { name: string, params: string, handle: WebViewInstanceHandle }>()\n /** The wrapper of a native node's view, by node id. */\n private readonly wrappers = new Map<number, HTMLElement>()\n /** What is under the picture now, by node id (a wrapper, or a video's own element). */\n private readonly shown = new Map<number, HTMLElement>()\n /** The fullscreen native destination (openView kind 3), null when none. */\n private destination: { viewId: number, el: HTMLElement } | null = null\n private field: { id: number, el: HTMLInputElement | HTMLTextAreaElement } | null = null\n private placedFor: unknown = null\n\n /** `under` and `over` are the host's layers below and above the painted canvas. */\n constructor(M: WasmModule, host: Host, private readonly under: HTMLElement, private readonly over: HTMLElement, options: TreeUIOptions = {}) {\n super(M, host, options)\n this.doc = under.ownerDocument\n const style = this.doc.createElement(\"style\")\n style.textContent = FIELD_STYLE\n over.appendChild(style)\n }\n\n /** What the page shows itself: the painter leaves it out. */\n paintOptions(): PaintOptions { return { surfaces: true, editing: this.field?.id } }\n\n // ---- native views: the plugins' web halves -----------------------------------------------------------\n /** `version` = the contract version the half was generated from (1 for one written by hand). */\n registerView(name: string, factory: WebViewFactory, version = 1): void { this.factories.set(name, factory); this.versions.set(name, version) }\n /** A view the next bundle does not have (its plugin is not among the app's): unsupported again. */\n unregisterView(name: string): void { this.factories.delete(name); this.versions.delete(name) }\n isViewSupported(name: string): boolean { return this.factories.has(name) }\n viewVersion(name: string): number { return this.versions.get(name) ?? 0 }\n\n private ensureView(viewId: number, name: string, params: string): WebViewInstanceHandle | null {\n const live = this.views.get(viewId)\n // A new project world restarts the SDK's view ids from 1: another name or other params under a\n // live id is an instance of the world that left.\n if (live && (live.name !== name || live.params !== params)) this.destroyView(viewId)\n else if (live) return live.handle\n const factory = this.factories.get(name)\n if (!factory) return null\n let parsed: unknown = {}\n try { parsed = params ? JSON.parse(params) : {} } catch { /* the runtime's JSON */ }\n // An event's payload crosses as the value it is: the app and this host are the same JavaScript.\n const handle = factory(parsed, { emit: (event, data) => this.M.jsb.viewEvent(viewId, event, data) }, this.doc)\n handle.el.style.cssText += \";position:absolute;inset:0;width:100%;height:100%;\"\n this.views.set(viewId, { name, params, handle })\n return handle\n }\n private destroyView(viewId: number): void {\n const live = this.views.get(viewId)\n if (!live) return\n this.views.delete(viewId)\n live.handle.destroy?.()\n live.handle.el.remove()\n }\n /** `args` is the app's own array: a half reads it, never keeps or changes it. */\n viewCall(viewId: number, method: string, args: unknown, onComplete: (result?: unknown) => void, onReject: (message: string) => void): void {\n const live = this.views.get(viewId)\n if (!live?.handle.call) { onReject(`NativeView call \"${method}\": no live instance or no call handler (viewId ${viewId})`); return }\n try {\n Promise.resolve(live.handle.call(method, Array.isArray(args) ? args : [])).then(\n (result) => { if (result === undefined) onComplete(); else onComplete(result) },\n (e) => onReject(e instanceof Error ? e.message : String(e)),\n )\n } catch (e) { onReject(e instanceof Error ? e.message : String(e)) }\n }\n\n // A native destination is a surface: it stays where it is until the runtime drops it (a screen\n // may still be coming in over it), under every screen.\n override openView(kind: number, node: number, id: number, viewName: string, paramsJson: string, above: boolean): void {\n super.openView(kind, node, id, viewName, paramsJson, above)\n if (kind !== TREE_DEST_NATIVE) return\n this.dropDestination()\n const handle = this.ensureView(id, viewName, paramsJson)\n if (!handle) return\n const el = this.doc.createElement(\"div\")\n el.style.cssText = \"position:absolute;inset:0;pointer-events:auto;\"\n el.appendChild(handle.el)\n this.under.prepend(el)\n this.destination = { viewId: id, el }\n }\n override dropView(kind: number, node: number, id: number): void {\n super.dropView(kind, node, id)\n // …unless the one on screen now is that very view, presented again\n if (kind === TREE_DEST_NATIVE && this.destination?.viewId === id && this.destKind !== TREE_DEST_NATIVE) this.dropDestination()\n }\n private dropDestination(): void {\n this.destination?.el.remove()\n this.destination = null\n }\n\n override releaseNode(id: number): void {\n const n = this.get(id)\n if (this.field?.id === id) this.unmountField()\n super.releaseNode(id)\n this.shown.get(id)?.remove()\n this.shown.delete(id)\n this.wrappers.delete(id)\n if (n?.type === \"native\" && n.viewId) this.destroyView(n.viewId)\n }\n\n // ---- the field being edited ---------------------------------------------------------------------------\n override focusInput(id: number): void {\n super.focusInput(id)\n if (this.focusedId() !== id || this.field?.id === id) return\n this.unmountField()\n const node = this.get(id)\n if (!node) return\n const el = this.doc.createElement(node.type === \"textarea\" ? \"textarea\" : \"input\")\n el.className = \"lc-field\"\n el.setAttribute(\"autocomplete\", \"off\")\n el.value = node.value\n el.addEventListener(\"input\", () => { if (this.focusedId() === id) this.setInputValue(id, el.value) })\n el.addEventListener(\"keydown\", (e) => { if ((e as KeyboardEvent).key === \"Enter\" && el.tagName === \"INPUT\") { e.preventDefault(); this.submitInput() } })\n // the browser took the focus away (another window, a tab key): the app's field lost it too\n el.addEventListener(\"blur\", () => { if (this.field?.el === el && this.focusedId() === id) this.blurInput() })\n this.over.appendChild(el)\n this.field = { id, el }\n this.placedFor = null // placed with the next frame; focused now, inside the gesture that asked\n this.place()\n el.focus({ preventScroll: true })\n }\n override blurInput(): void {\n super.blurInput()\n this.unmountField()\n }\n private unmountField(): void {\n const field = this.field\n if (!field) return\n this.field = null\n field.el.remove()\n this.placedFor = null\n }\n override setPropertyString(id: number, prop: string, value: string | null): void {\n super.setPropertyString(id, prop, value)\n // a value the CODE set while the field is edited\n if (prop === \"value\" && this.field?.id === id) { const v = this.get(id)?.value ?? \"\"; if (this.field.el.value !== v) this.field.el.value = v }\n }\n\n // ---- placing ------------------------------------------------------------------------------------------\n /** The nodes the page shows itself, where the frame has them. */\n private find(): Place[] {\n const found: Place[] = []\n const editing = this.field?.id\n const walk = (node: RenderNode, above: Matrix, clip: Rect | null) => {\n let matrix = above\n const t = node.style.transform\n if (t) {\n // the painter's: the node's matrix about its transform origin (its centre by default)\n const o = node.style.transformOrigin\n const cx = node.rect.x + (o ? (o.xPercent ? node.rect.width * o.x / 100 : o.x) : node.rect.width / 2)\n const cy = node.rect.y + (o ? (o.yPercent ? node.rect.height * o.y / 100 : o.y) : node.rect.height / 2)\n matrix = multiply(multiply(multiply(above, [1, 0, 0, 1, cx, cy]), t as unknown as Matrix), [1, 0, 0, 1, -cx, -cy])\n }\n if (isSurface(node) || node.id === editing) found.push({ node, matrix, clip })\n const inner = node.clip ? intersect(clip, node.rect) : clip\n for (const child of node.children) walk(child, matrix, inner)\n }\n for (const layer of this.frame()) walk(layer.tree, IDENTITY, null)\n return found\n }\n private static put(el: HTMLElement, place: Place): void {\n const { rect } = place.node\n const s = el.style\n s.position = \"absolute\"\n s.left = \"0\"\n s.top = \"0\"\n s.width = rect.width + \"px\"\n s.height = rect.height + \"px\"\n s.transformOrigin = \"0 0\"\n s.transform = `matrix(${place.matrix.join(\",\")}) translate(${rect.x}px,${rect.y}px)`\n const c = place.clip\n // the clip is in the frame's coordinates, the element's clip-path in its own box\n s.clipPath = c ? `inset(${Math.max(0, c.y - rect.y)}px ${Math.max(0, rect.x + rect.width - (c.x + c.width))}px ${Math.max(0, rect.y + rect.height - (c.y + c.height))}px ${Math.max(0, c.x - rect.x)}px)` : \"\"\n }\n private surfaceElement(node: RenderNode): HTMLElement | null {\n const n = this.get(node.id)\n if (!n) return null\n if (n.type === \"video\") {\n const player = getPlayer(n.playerId)\n return player instanceof HTMLVideoElement ? player : null\n }\n if (!n.viewId) return null\n const handle = this.ensureView(n.viewId, n.viewName ?? \"\", n.viewParams ?? \"\")\n if (!handle) return null\n let wrapper = this.wrappers.get(n.id)\n if (!wrapper) { wrapper = this.doc.createElement(\"div\"); this.wrappers.set(n.id, wrapper) }\n if (handle.el.parentElement !== wrapper) wrapper.replaceChildren(handle.el)\n return wrapper\n }\n private styleField(el: HTMLInputElement | HTMLTextAreaElement, node: RenderNode): void {\n const s = node.style\n const st = el.style\n const [pl, pt, pr, pb] = node.padding ?? [0, 0, 0, 0]\n st.padding = `${pt}px ${pr}px ${pb}px ${pl}px`\n st.color = hex(s.color, \"#000000ff\")\n st.caretColor = st.color\n const family = s.fontFamily ?? \"Roboto\"\n st.fontFamily = this.host.resolveFontFamily?.(family) ?? family\n st.fontSize = (s.fontSize ?? 14) + \"px\"\n st.fontWeight = String(s.fontWeight ?? 400)\n st.fontStyle = s.fontStyle ?? \"normal\"\n st.letterSpacing = (s.letterSpacing ?? 0) + \"px\"\n // a textarea's lines are the node's; an input is one line, centred in the field by the browser\n st.lineHeight = el.tagName === \"TEXTAREA\" && s.lineHeight !== undefined ? s.lineHeight + \"px\" : \"normal\"\n st.textAlign = s.textAlign === \"center\" ? \"center\" : s.textAlign === \"end\" ? \"right\" : \"left\"\n st.borderRadius = \"0\"\n el.placeholder = s.placeholder ?? \"\"\n st.setProperty(\"--lc-placeholder\", hex(s.placeholderColor, \"#999999ff\"))\n if (el instanceof HTMLInputElement) { const type = s.inputType ?? \"text\"; if (el.type !== type) el.type = type }\n }\n /** After the paint: what the page shows itself goes where the frame has it. */\n place(): void {\n const frame = this.frame()\n if (frame === this.placedFor) return\n this.placedFor = frame\n const seen = new Set<number>()\n for (const place of this.find()) {\n const { node } = place\n if (node.id === this.field?.id) {\n this.styleField(this.field.el, node)\n BrowserUI.put(this.field.el, place)\n continue\n }\n const el = this.surfaceElement(node)\n if (!el) continue\n seen.add(node.id)\n if (el.parentElement !== this.under) this.under.appendChild(el)\n el.style.display = \"block\"\n el.style.opacity = \"\"\n el.style.pointerEvents = \"auto\" // where the picture has a window onto it\n if (el instanceof HTMLVideoElement) el.style.objectFit = node.style.objectFit ?? \"contain\"\n BrowserUI.put(el, place)\n this.shown.set(node.id, el)\n }\n // what the frame no longer shows (a page that left, a node taken out): kept, not seen\n for (const [id, el] of this.shown) if (!seen.has(id)) { el.style.display = \"none\"; this.shown.delete(id) }\n }\n\n // ---- whose the pointer is --------------------------------------------------------------------------------\n /** Whether the point is a surface's: the topmost thing there that takes input is a native view\n * (or the native destination, with nothing of the UI over it) — the event is that view's. */\n surfaceAt(x: number, y: number): boolean {\n const layers = this.frame()\n for (let i = layers.length - 1; i >= 0; i--) {\n const layer = layers[i]!\n if (layer.leaving) continue\n const hit = hitTest(layer.tree, x, y, (n) => n.type === \"native\" || (this.get(n.id)?.interactive ?? false) || (this.get(n.id)?.editable ?? false) || !!n.scroll)\n if (hit) return hit.type === \"native\"\n if (layer.backdrop) return false\n }\n return this.destination !== null\n }\n\n dispose(): void {\n this.unmountField()\n for (const id of [...this.views.keys()]) this.destroyView(id)\n this.dropDestination()\n for (const el of this.shown.values()) if (!(el instanceof HTMLVideoElement)) el.remove()\n this.shown.clear()\n }\n}\n","// What the browser renderer shows of the host's own: the toast strip.\n\n/** A transient toast strip at the bottom of the root (duration in ms; ≤ 0 = 2 s). */\nexport function showToast(doc: Document, root: HTMLElement, message: string, duration: number) {\n const el = doc.createElement(\"div\")\n el.textContent = message\n el.style.cssText =\n \"position:absolute;left:50%;bottom:48px;transform:translateX(-50%);max-width:80%;padding:10px 16px;border-radius:8px;\" +\n \"background:rgba(30,30,30,0.92);color:#fff;font:13px/1.4 system-ui,sans-serif;z-index:30;pointer-events:none;\"\n root.appendChild(el)\n setTimeout(() => el.remove(), duration > 0 ? duration : 2000)\n}\n","// The canvas renderer in the browser: the TreeUI (the runtime's HostUI table) painted to a 2D canvas\n// that lies over the scene canvases, with a layer under it for the native views and the videos and\n// a layer over it for the field being edited (./BrowserUI.ts). The host calls `render()` after each\n// layout pass.\n//\n// The canvas is the host's: it sizes the backing store (device px, the host's page), the renderer\n// only paints. Nothing here draws a keyboard or a device — the page is the app's window.\n//\n// POINTERS. The painted canvas takes no pointer itself (`pointer-events: none`): an event lands on\n// what is under the pointer in the page — a native view, a scene canvas, the container — and the\n// renderer meets it on its way down, at the container, in the capture phase. There the render tree\n// says whose the point is. The UI's: the event goes to the TreeUI's routing (logical px), and\n// stops before a view under the picture hears of it. A native view's: it goes on to the view.\nimport type { WasmModule } from \"lecodes-web-runtime/src/gen/wasm\"\nimport type { CanvasHost } from \"lecodes-web-shared/src/canvas/createCanvasHost\"\nimport { getUrl } from \"lecodes-web-shared/src/utils/fetch\"\nimport { viewScale } from \"lecodes-web-shared/src/ui/viewScale\"\nimport { BrowserHost } from \"../host/BrowserHost\"\nimport { Canvas2DPainter } from \"../paint/Canvas2DPainter\"\nimport { BrowserUI } from \"./BrowserUI\"\nimport { showToast } from \"./chrome\"\n\n/** Hold this long before a press counts as a long press (the runtime asks the node's listener). */\nconst LONG_PRESS_MS = 500\n\nexport type SafeAreaEdge = \"top\" | \"right\" | \"bottom\" | \"left\"\n/** Insets in logical px; `bars` = the edges that are exact-height system bars (`comfort-*` adds its\n * knob past a bar instead of flooring against it). */\nexport type SafeArea = { top: number, right: number, bottom: number, left: number, bars?: readonly SafeAreaEdge[] }\n\nexport type CanvasRendererOptions = {\n M: WasmModule\n /** The canvas to paint on, over the scene canvases. */\n canvas: HTMLCanvasElement\n canvasHost?: CanvasHost\n /** What the window loses to the on-screen keyboard, in logical px. */\n keyboardHeight?: () => number\n}\n\n/** What a page fires for one press besides its pointer events: stopped with them on the way to a\n * view under the picture. */\nconst FOLLOWERS = [\"mousedown\", \"mouseup\", \"click\", \"dblclick\", \"contextmenu\", \"touchstart\", \"touchmove\", \"touchend\"] as const\n\nexport const createCanvasRenderer = (root: HTMLElement, options: CanvasRendererOptions) => {\n const doc = root.ownerDocument\n const { canvas } = options\n canvas.style.display = \"block\"\n canvas.style.pointerEvents = \"none\"\n root.style.touchAction = \"none\"\n const context = canvas.getContext(\"2d\")!\n\n const layer = () => {\n const el = doc.createElement(\"div\")\n el.style.cssText = \"position:absolute;inset:0;overflow:hidden;pointer-events:none;\"\n return el\n }\n const under = layer()\n const over = layer()\n root.insertBefore(under, canvas)\n canvas.after(over)\n\n // Uploaded-asset image srcs ({ _id }) resolve to blob urls through the fetch store; UIImage(canvas)\n // surfaces through the canvas host.\n const host = new BrowserHost({ resolveAssetUrl: (id) => getUrl(id), canvasSurfaces: options.canvasHost })\n const ui = new BrowserUI(options.M, host, under, over, {\n keyboardHeight: options.keyboardHeight ?? (() => 0),\n onToast: (message, duration) => showToast(doc, root, message, duration),\n })\n\n // The painter bakes the resolution factor into its transform: a new one when the factor moves.\n let factor = 1\n let painter = new Canvas2DPainter(context, factor)\n // A canvas that took a new size was WIPED: paint once even if nothing changed.\n let wiped = true\n const render = () => {\n if (wiped || ui.needsPaint()) {\n wiped = false\n ui.paint(painter, ui.paintOptions())\n }\n ui.place()\n }\n\n /** The viewport in logical px and the device px per logical px; the canvas already has the size. */\n const resize = (width: number, height: number, nextFactor: number) => {\n if (width <= 0 || height <= 0) return\n if (nextFactor !== factor) { factor = nextFactor; painter = new Canvas2DPainter(context, factor) }\n wiped = true\n ui.resize(width, height)\n }\n const setSafeArea = (area: SafeArea) => {\n ui.setSafeArea([area.top, area.right, area.bottom, area.left], area.bars ?? [])\n }\n\n // ---- pointers (logical px: clientX and the rect are VISUAL px under a CSS zoom) ----\n const local = (e: { clientX: number, clientY: number }): [number, number] => {\n const rect = root.getBoundingClientRect()\n const scale = viewScale(root)\n return [(e.clientX - rect.left) / scale, (e.clientY - rect.top) / scale]\n }\n const inField = (e: Event) => e.target instanceof Node && over.contains(e.target)\n const toView = (e: Event) => e.target instanceof Node && under.contains(e.target)\n /** The event is the UI's: a view under the picture does not hear of it. */\n const keep = (e: Event) => { if (toView(e)) e.stopPropagation() }\n\n /** The pointers the UI has (down on it, until they are up): theirs is every event that follows. */\n const held = new Set<number>()\n const longPress = new Map<number, number>()\n const clearLongPress = (id: number) => { const t = longPress.get(id); if (t !== undefined) { clearTimeout(t); longPress.delete(id) } }\n\n const onDown = (e: PointerEvent) => {\n if (inField(e)) return // the field being edited: the browser's own caret and selection\n const [x, y] = local(e)\n if (ui.surfaceAt(x, y)) return\n keep(e)\n held.add(e.pointerId)\n try { root.setPointerCapture(e.pointerId) } catch { /* detached */ }\n ui.pointerDown(e.pointerId, x, y)\n clearLongPress(e.pointerId)\n longPress.set(e.pointerId, window.setTimeout(() => { longPress.delete(e.pointerId); ui.longPress(e.pointerId, x, y) }, LONG_PRESS_MS))\n }\n // A mouse move is also the cursor's hover (button or not): stored here, resolved once per frame\n // (TreeUI.tickHover). A finger hovers nothing.\n const onMove = (e: PointerEvent) => {\n const [x, y] = local(e)\n if (held.has(e.pointerId)) { keep(e); ui.pointerMove(e.pointerId, x, y) }\n if (e.pointerType !== \"mouse\") return\n if (inField(e) || (!held.has(e.pointerId) && ui.surfaceAt(x, y))) ui.pointerLeave()\n else ui.pointerHover(x, y)\n }\n const onLeave = (e: PointerEvent) => { if (e.pointerType === \"mouse\") ui.pointerLeave() }\n const onUp = (e: PointerEvent) => {\n if (!held.delete(e.pointerId)) return\n keep(e)\n clearLongPress(e.pointerId)\n const [x, y] = local(e)\n ui.pointerUp(e.pointerId, x, y)\n }\n const onCancel = (e: PointerEvent) => {\n if (!held.delete(e.pointerId)) return\n clearLongPress(e.pointerId)\n ui.pointerCancel(e.pointerId)\n }\n const onWheel = (e: WheelEvent) => {\n if (inField(e)) return\n const [x, y] = local(e)\n if (ui.surfaceAt(x, y)) return\n keep(e)\n const k = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? ui.height : 1\n if (ui.wheel(x, y, e.deltaX * k, e.deltaY * k)) e.preventDefault()\n }\n // What follows a press the UI took: not the view's either. A mouse press on the UI moves no\n // focus and selects nothing (the field being edited keeps its caret while a button is pressed).\n const onFollower = (e: Event) => {\n if (inField(e)) return\n const point = \"clientX\" in e ? (e as MouseEvent) : (e as TouchEvent).changedTouches?.[0]\n if (!point) return\n const [x, y] = local(point)\n if (ui.surfaceAt(x, y)) return\n keep(e)\n if (e.type === \"mousedown\") e.preventDefault()\n }\n\n root.addEventListener(\"pointerdown\", onDown, true)\n root.addEventListener(\"pointermove\", onMove, true)\n root.addEventListener(\"pointerleave\", onLeave)\n root.addEventListener(\"pointerup\", onUp, true)\n root.addEventListener(\"pointercancel\", onCancel, true)\n root.addEventListener(\"wheel\", onWheel, { passive: false, capture: true })\n for (const type of FOLLOWERS) root.addEventListener(type, onFollower, true)\n\n return {\n ui,\n render,\n resize,\n setSafeArea,\n destroy() {\n for (const id of longPress.keys()) clearLongPress(id)\n root.removeEventListener(\"pointerdown\", onDown, true)\n root.removeEventListener(\"pointermove\", onMove, true)\n root.removeEventListener(\"pointerleave\", onLeave)\n root.removeEventListener(\"pointerup\", onUp, true)\n root.removeEventListener(\"pointercancel\", onCancel, true)\n root.removeEventListener(\"wheel\", onWheel, true)\n for (const type of FOLLOWERS) root.removeEventListener(type, onFollower, true)\n ui.dispose()\n under.remove()\n over.remove()\n },\n }\n}\n\nexport type CanvasRenderer = ReturnType<typeof createCanvasRenderer>\n","// GENERATED by scripts/vendor-canvas.ts from engines/canvas/spec/gen/spec.ts @ ae6bc30b952b — do not edit here.\n// Bump the submodule and run `bun run vendor:canvas`; `bun run check:canvas-ops` fails when this copy is stale.\n// GENERATED by spec/generate.ts from spec/*.h — do not edit.\n\nexport const SPEC_VERSION = 1\n\nexport const LineJoin = {\n MITER: 0,\n ROUND: 1,\n BEVEL: 2,\n} as const\nexport type LineJoin = (typeof LineJoin)[keyof typeof LineJoin]\nexport const LineJoinName: readonly string[] = [\"miter\", \"round\", \"bevel\"]\n\nexport const LineCap = {\n BUTT: 0,\n ROUND: 1,\n SQUARE: 2,\n} as const\nexport type LineCap = (typeof LineCap)[keyof typeof LineCap]\nexport const LineCapName: readonly string[] = [\"butt\", \"round\", \"square\"]\n\nexport const TextAlign = {\n LEFT: 0,\n CENTER: 1,\n RIGHT: 2,\n START: 3,\n END: 4,\n} as const\nexport type TextAlign = (typeof TextAlign)[keyof typeof TextAlign]\nexport const TextAlignName: readonly string[] = [\"left\", \"center\", \"right\", \"start\", \"end\"]\n\nexport const TextBaseline = {\n ALPHABETIC: 0,\n TOP: 1,\n MIDDLE: 2,\n BOTTOM: 3,\n HANGING: 4,\n IDEOGRAPHIC: 5,\n} as const\nexport type TextBaseline = (typeof TextBaseline)[keyof typeof TextBaseline]\nexport const TextBaselineName: readonly string[] = [\"alphabetic\", \"top\", \"middle\", \"bottom\", \"hanging\", \"ideographic\"]\n\nexport const FillRule = {\n NONZERO: 0,\n EVENODD: 1,\n} as const\nexport type FillRule = (typeof FillRule)[keyof typeof FillRule]\nexport const FillRuleName: readonly string[] = [\"nonzero\", \"evenodd\"]\n\nexport const Spread = {\n PAD: 0,\n REFLECT: 1,\n REPEAT: 2,\n} as const\nexport type Spread = (typeof Spread)[keyof typeof Spread]\nexport const SpreadName: readonly string[] = [\"pad\", \"reflect\", \"repeat\"]\n\nexport const Gradient = {\n LINEAR: 0,\n RADIAL: 1,\n} as const\nexport type Gradient = (typeof Gradient)[keyof typeof Gradient]\nexport const GradientName: readonly string[] = [\"linear\", \"radial\"]\n\nexport const Paint = {\n COLOR: 0,\n LINEAR: 1,\n RADIAL: 2,\n} as const\nexport type Paint = (typeof Paint)[keyof typeof Paint]\nexport const PaintName: readonly string[] = [\"color\", \"linear\", \"radial\"]\n\nexport const PathVerb = {\n MOVE: 0,\n LINE: 1,\n QUAD: 2,\n CUBIC: 3,\n CLOSE: 4,\n} as const\nexport type PathVerb = (typeof PathVerb)[keyof typeof PathVerb]\nexport const PathVerbName: readonly string[] = [\"move\", \"line\", \"quad\", \"cubic\", \"close\"]\n\nexport const ImageFormat = {\n PNG: 0,\n JPEG: 1,\n} as const\nexport type ImageFormat = (typeof ImageFormat)[keyof typeof ImageFormat]\nexport const ImageFormatName: readonly string[] = [\"png\", \"jpeg\"]\n\n/** The opcode stream: op id → the word after it. */\nexport const OP = {\n SAVE: 0,\n RESTORE: 1,\n TRANSLATE: 2,\n SCALE: 3,\n ROTATE: 4,\n TRANSFORM: 5,\n SET_TRANSFORM: 6,\n RESET_TRANSFORM: 7,\n GLOBAL_ALPHA: 8,\n FILL_STYLE: 9,\n STROKE_STYLE: 10,\n FILL_GRADIENT: 11,\n STROKE_GRADIENT: 12,\n LINE_WIDTH: 13,\n LINE_JOIN: 14,\n LINE_CAP: 15,\n MITER_LIMIT: 16,\n LINE_DASH: 17,\n LINE_DASH_OFFSET: 18,\n FONT: 19,\n TEXT_ALIGN: 20,\n TEXT_BASELINE: 21,\n LETTER_SPACING: 22,\n PATH_BEGIN: 23,\n PATH_CLOSE: 24,\n MOVE_TO: 25,\n LINE_TO: 26,\n QUADRATIC_TO: 27,\n BEZIER_TO: 28,\n ARC: 29,\n ARC_TO: 30,\n ELLIPSE: 31,\n RECT: 32,\n ROUND_RECT: 33,\n FILL: 34,\n STROKE: 35,\n CLIP: 36,\n FILL_RECT: 37,\n STROKE_RECT: 38,\n CLEAR_RECT: 39,\n FILL_TEXT: 40,\n STROKE_TEXT: 41,\n DRAW_IMAGE: 42,\n} as const\nexport type OP = (typeof OP)[keyof typeof OP]\n/** Operand layout per op: `args` is one letter per fixed word (f float, i int, r string ref);\n * `repeat` is the group that follows the trailing count. */\nexport const OP_ARGS: Record<number, { args: string, repeat: string }> = {\n 0: { args: \"\", repeat: \"\" },\n 1: { args: \"\", repeat: \"\" },\n 2: { args: \"ff\", repeat: \"\" },\n 3: { args: \"ff\", repeat: \"\" },\n 4: { args: \"f\", repeat: \"\" },\n 5: { args: \"ffffff\", repeat: \"\" },\n 6: { args: \"ffffff\", repeat: \"\" },\n 7: { args: \"\", repeat: \"\" },\n 8: { args: \"f\", repeat: \"\" },\n 9: { args: \"r\", repeat: \"\" },\n 10: { args: \"r\", repeat: \"\" },\n 11: { args: \"iffffffi\", repeat: \"fr\" },\n 12: { args: \"iffffffi\", repeat: \"fr\" },\n 13: { args: \"f\", repeat: \"\" },\n 14: { args: \"i\", repeat: \"\" },\n 15: { args: \"i\", repeat: \"\" },\n 16: { args: \"f\", repeat: \"\" },\n 17: { args: \"i\", repeat: \"f\" },\n 18: { args: \"f\", repeat: \"\" },\n 19: { args: \"r\", repeat: \"\" },\n 20: { args: \"i\", repeat: \"\" },\n 21: { args: \"i\", repeat: \"\" },\n 22: { args: \"f\", repeat: \"\" },\n 23: { args: \"\", repeat: \"\" },\n 24: { args: \"\", repeat: \"\" },\n 25: { args: \"ff\", repeat: \"\" },\n 26: { args: \"ff\", repeat: \"\" },\n 27: { args: \"ffff\", repeat: \"\" },\n 28: { args: \"ffffff\", repeat: \"\" },\n 29: { args: \"fffffi\", repeat: \"\" },\n 30: { args: \"fffff\", repeat: \"\" },\n 31: { args: \"fffffffi\", repeat: \"\" },\n 32: { args: \"ffff\", repeat: \"\" },\n 33: { args: \"fffff\", repeat: \"\" },\n 34: { args: \"i\", repeat: \"\" },\n 35: { args: \"\", repeat: \"\" },\n 36: { args: \"i\", repeat: \"\" },\n 37: { args: \"ffff\", repeat: \"\" },\n 38: { args: \"ffff\", repeat: \"\" },\n 39: { args: \"ffff\", repeat: \"\" },\n 40: { args: \"rfff\", repeat: \"\" },\n 41: { args: \"rfff\", repeat: \"\" },\n 42: { args: \"iffffffff\", repeat: \"\" },\n}\nexport const OP_NAME: readonly string[] = [\"save\", \"restore\", \"translate\", \"scale\", \"rotate\", \"transform\", \"setTransform\", \"resetTransform\", \"globalAlpha\", \"fillStyle\", \"strokeStyle\", \"fillGradient\", \"strokeGradient\", \"lineWidth\", \"lineJoin\", \"lineCap\", \"miterLimit\", \"lineDash\", \"lineDashOffset\", \"font\", \"textAlign\", \"textBaseline\", \"letterSpacing\", \"pathBegin\", \"pathClose\", \"moveTo\", \"lineTo\", \"quadraticTo\", \"bezierTo\", \"arc\", \"arcTo\", \"ellipse\", \"rect\", \"roundRect\", \"fill\", \"stroke\", \"clip\", \"fillRect\", \"strokeRect\", \"clearRect\", \"fillText\", \"strokeText\", \"drawImage\"]\n\n/** The draw list: command id → the word after it. */\nexport const DRAW = {\n SET_TRANSFORM: 0,\n SAVE: 1,\n RESTORE: 2,\n CLIP: 3,\n FILL_PATH: 4,\n STROKE_PATH: 5,\n FILL_TEXT: 6,\n STROKE_TEXT: 7,\n DRAW_IMAGE: 8,\n CLEAR_RECT: 9,\n} as const\nexport type DRAW = (typeof DRAW)[keyof typeof DRAW]\nexport const DRAW_NAME: readonly string[] = [\"setTransform\", \"save\", \"restore\", \"clip\", \"fillPath\", \"strokePath\", \"fillText\", \"strokeText\", \"drawImage\", \"clearRect\"]\n","// GENERATED by scripts/vendor-canvas.ts from engines/canvas/painters/web/src/drawlist.ts @ ae6bc30b952b — do not edit here.\n// Bump the submodule and run `bun run vendor:canvas`; `bun run check:canvas-ops` fails when this copy is stale.\n// The draw list in TypeScript: the typed commands, the reader of the word buffer (spec/draw.h) and\n// the reader of the core's JSON dump. Both produce the same DrawCommand objects — the tests hold the\n// two readers against each other on every golden.\nimport {\n DRAW, Paint as PaintKind, PathVerb, LineJoinName, LineCapName, TextAlignName, TextBaselineName, FillRuleName, SpreadName,\n} from \"./spec\"\n\nexport type Color = [number, number, number, number]\nexport type Matrix6 = [number, number, number, number, number, number]\nexport interface Stop { offset: number, color: Color }\nexport interface ColorPaint { kind: \"color\", alpha: number, color: Color }\nexport interface LinearPaint { kind: \"linear\", alpha: number, matrix: Matrix6, spread: string, stops: Stop[] }\nexport interface RadialPaint { kind: \"radial\", alpha: number, matrix: Matrix6, fx: number, fy: number, r0: number, spread: string, stops: Stop[] }\nexport type Paint = ColorPaint | LinearPaint | RadialPaint\nexport interface Stroke { width: number, join: string, cap: string, miterLimit: number, dashOffset: number, dash: number[] }\nexport interface Font { family: string, size: number, weight: number, italic: boolean }\nexport type PathSeg = [\"M\", number, number] | [\"L\", number, number] | [\"Q\", number, number, number, number] | [\"C\", number, number, number, number, number, number] | [\"Z\"]\n\nexport type DrawCommand =\n | { cmd: \"setTransform\", matrix: Matrix6 }\n | { cmd: \"save\" }\n | { cmd: \"restore\" }\n | { cmd: \"clip\", rule: string, path: PathSeg[] }\n | { cmd: \"fillPath\", rule: string, paint: Paint, path: PathSeg[] }\n | { cmd: \"strokePath\", stroke: Stroke, paint: Paint, path: PathSeg[] }\n | { cmd: \"fillText\", text: string, x: number, y: number, maxWidth: number, font: Font, align: string, baseline: string, letterSpacing: number, paint: Paint }\n | { cmd: \"strokeText\", text: string, x: number, y: number, maxWidth: number, font: Font, align: string, baseline: string, letterSpacing: number, stroke: Stroke, paint: Paint }\n | { cmd: \"drawImage\", surface: number, src: [number, number, number, number], dst: [number, number, number, number], alpha: number }\n | { cmd: \"clearRect\", rect: [number, number, number, number] }\n\nclass Reader {\n pos = 0\n constructor(readonly w: Float32Array, readonly strings: readonly string[]) {}\n f(): number { if (this.pos >= this.w.length) throw new Error(\"draw list: truncated\"); return this.w[this.pos++] }\n i(): number { return this.f() | 0 }\n str(): string { const i = this.i(); if (i < 0 || i >= this.strings.length) throw new Error(`draw list: bad string index ${i}`); return this.strings[i] }\n color(): Color { return [this.f(), this.f(), this.f(), this.f()] }\n matrix(): Matrix6 { return [this.f(), this.f(), this.f(), this.f(), this.f(), this.f()] }\n paint(): Paint {\n const kind = this.i(), alpha = this.f()\n if (kind === PaintKind.COLOR) return { kind: \"color\", alpha, color: this.color() }\n const matrix = this.matrix()\n let fx = 0, fy = 0, r0 = 0\n if (kind === PaintKind.RADIAL) { fx = this.f(); fy = this.f(); r0 = this.f() }\n const spread = SpreadName[this.i()] ?? \"pad\"\n const n = this.i()\n const stops: Stop[] = []\n for (let k = 0; k < n; k++) stops.push({ offset: this.f(), color: this.color() })\n return kind === PaintKind.RADIAL ? { kind: \"radial\", alpha, matrix, fx, fy, r0, spread, stops } : { kind: \"linear\", alpha, matrix, spread, stops }\n }\n stroke(): Stroke {\n const width = this.f(), join = LineJoinName[this.i()] ?? \"miter\", cap = LineCapName[this.i()] ?? \"butt\"\n const miterLimit = this.f(), dashOffset = this.f(), n = this.i()\n const dash: number[] = []\n for (let k = 0; k < n; k++) dash.push(this.f())\n return { width, join, cap, miterLimit, dashOffset, dash }\n }\n font(): Font { return { family: this.str(), size: this.f(), weight: this.i(), italic: this.i() !== 0 } }\n path(): PathSeg[] {\n const n = this.i()\n const end = this.pos + n\n if (end > this.w.length) throw new Error(\"draw list: truncated path\")\n const segs: PathSeg[] = []\n while (this.pos < end) {\n switch (this.i()) {\n case PathVerb.MOVE: segs.push([\"M\", this.f(), this.f()]); break\n case PathVerb.LINE: segs.push([\"L\", this.f(), this.f()]); break\n case PathVerb.QUAD: segs.push([\"Q\", this.f(), this.f(), this.f(), this.f()]); break\n case PathVerb.CUBIC: segs.push([\"C\", this.f(), this.f(), this.f(), this.f(), this.f(), this.f()]); break\n case PathVerb.CLOSE: segs.push([\"Z\"]); break\n default: throw new Error(\"draw list: bad path verb\")\n }\n }\n return segs\n }\n rect4(): [number, number, number, number] { return [this.f(), this.f(), this.f(), this.f()] }\n}\n\n/** Decode a word buffer + string table into commands. A command this build does not know is skipped. */\nexport const readDrawList = (words: Float32Array, strings: readonly string[]): DrawCommand[] => {\n const r = new Reader(words, strings)\n const out: DrawCommand[] = []\n while (r.pos + 2 <= words.length) {\n const cmd = r.i(), len = r.i()\n const end = r.pos + len\n if (len < 0 || end > words.length) throw new Error(\"draw list: truncated command\")\n switch (cmd) {\n case DRAW.SET_TRANSFORM: out.push({ cmd: \"setTransform\", matrix: r.matrix() }); break\n case DRAW.SAVE: out.push({ cmd: \"save\" }); break\n case DRAW.RESTORE: out.push({ cmd: \"restore\" }); break\n case DRAW.CLIP: { const rule = FillRuleName[r.i()] ?? \"nonzero\"; out.push({ cmd: \"clip\", rule, path: r.path() }); break }\n case DRAW.FILL_PATH: { const rule = FillRuleName[r.i()] ?? \"nonzero\"; const paint = r.paint(); out.push({ cmd: \"fillPath\", rule, paint, path: r.path() }); break }\n case DRAW.STROKE_PATH: { const stroke = r.stroke(); const paint = r.paint(); out.push({ cmd: \"strokePath\", stroke, paint, path: r.path() }); break }\n case DRAW.FILL_TEXT: case DRAW.STROKE_TEXT: {\n const text = r.str(), x = r.f(), y = r.f(), maxWidth = r.f(), font = r.font()\n const align = TextAlignName[r.i()] ?? \"start\", baseline = TextBaselineName[r.i()] ?? \"alphabetic\", letterSpacing = r.f()\n if (cmd === DRAW.STROKE_TEXT) { const stroke = r.stroke(); out.push({ cmd: \"strokeText\", text, x, y, maxWidth, font, align, baseline, letterSpacing, stroke, paint: r.paint() }) }\n else out.push({ cmd: \"fillText\", text, x, y, maxWidth, font, align, baseline, letterSpacing, paint: r.paint() })\n break\n }\n case DRAW.DRAW_IMAGE: { const surface = r.i(); const src = r.rect4(); const dst = r.rect4(); out.push({ cmd: \"drawImage\", surface, src, dst, alpha: r.f() }); break }\n case DRAW.CLEAR_RECT: out.push({ cmd: \"clearRect\", rect: r.rect4() }); break\n default: break // unknown: skipped by len\n }\n if (r.pos !== end) {\n if (r.pos > end) throw new Error(`draw list: command ${cmd} overran its length`)\n r.pos = end\n }\n }\n return out\n}\n\n/** The core's JSON dump (ac_drawlist_json / acdump) → commands. */\nexport const parseDrawListJson = (text: string): DrawCommand[] => {\n const v = JSON.parse(text)\n if (!Array.isArray(v)) throw new Error(\"draw list JSON: expected an array\")\n for (const c of v) if (typeof c !== \"object\" || typeof c.cmd !== \"string\") throw new Error(\"draw list JSON: bad command\")\n return v as DrawCommand[]\n}\n\n/** The binary file acdump / the golden test write: u32 wordCount, f32 words, u32 stringCount, (u32 len, utf8)*. */\nexport const readDrawListBinary = (bytes: Uint8Array): { words: Float32Array, strings: string[] } => {\n const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n let pos = 0\n const wordCount = dv.getUint32(pos, true); pos += 4\n const words = new Float32Array(wordCount)\n for (let i = 0; i < wordCount; i++) { words[i] = dv.getFloat32(pos, true); pos += 4 }\n const stringCount = dv.getUint32(pos, true); pos += 4\n const strings: string[] = []\n const dec = new TextDecoder()\n for (let i = 0; i < stringCount; i++) {\n const len = dv.getUint32(pos, true); pos += 4\n strings.push(dec.decode(bytes.subarray(pos, pos + len))); pos += len\n }\n return { words, strings }\n}\n","// GENERATED by scripts/vendor-canvas.ts from engines/canvas/painters/web/src/painter.ts @ ae6bc30b952b — do not edit here.\n// Bump the submodule and run `bun run vendor:canvas`; `bun run check:canvas-ops` fails when this copy is stale.\n// The web painter: replays a draw list on anything shaped like a CanvasRenderingContext2D — the\n// browser, an OffscreenCanvas, node-canvas / @napi-rs/canvas. A loop with one case per command, no\n// state of its own: the list carries absolute transforms and resolved paints.\n//\n// Platform limits, stated: Canvas2D gradients only PAD (reflect / repeat draw as pad); a gradient\n// under a non-similarity transform (skew, non-uniform scale — SVG objectBoundingBox on a non-square\n// shape) is drawn by transforming the context, which also distorts a STROKE's pen; letterSpacing\n// applies where the context supports it (Chrome 99+, Safari 17+; not node-canvas).\nimport type { DrawCommand, Paint, Stroke, Font, PathSeg, Matrix6, Color } from \"./drawlist\"\n\n/** The subset of CanvasRenderingContext2D the painter uses. */\nexport interface Canvas2DLike {\n save(): void\n restore(): void\n setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void\n transform(a: number, b: number, c: number, d: number, e: number, f: number): void\n beginPath(): void\n moveTo(x: number, y: number): void\n lineTo(x: number, y: number): void\n quadraticCurveTo(cx: number, cy: number, x: number, y: number): void\n bezierCurveTo(c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number): void\n closePath(): void\n fill(rule?: \"nonzero\" | \"evenodd\"): void\n stroke(): void\n clip(rule?: \"nonzero\" | \"evenodd\"): void\n fillStyle: any\n strokeStyle: any\n lineWidth: number\n lineJoin: any\n lineCap: any\n miterLimit: number\n setLineDash(segments: number[]): void\n lineDashOffset: number\n globalAlpha: number\n font: string\n textAlign: any\n textBaseline: any\n letterSpacing?: string\n fillText(text: string, x: number, y: number, maxWidth?: number): void\n strokeText(text: string, x: number, y: number, maxWidth?: number): void\n drawImage(image: any, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void\n clearRect(x: number, y: number, w: number, h: number): void\n createLinearGradient(x0: number, y0: number, x1: number, y1: number): any\n createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): any\n}\n\nexport interface PainterHooks {\n /** The drawable for a surface id (a canvas, an ImageBitmap, an Image); null skips the blit. */\n image?(surface: number): any\n /** Map a font family to what this context can render (a registered font's real name, a fallback). */\n fontFamily?(family: string): string\n}\n\nconst GENERIC_FAMILIES = new Set([\"serif\", \"sans-serif\", \"monospace\", \"cursive\", \"fantasy\", \"system-ui\", \"ui-serif\", \"ui-sans-serif\", \"ui-monospace\", \"ui-rounded\", \"emoji\", \"math\", \"fangsong\"])\n\n/** A draw-list color as CSS. */\nexport const cssColor = (c: Color): string => `rgba(${Math.round(c[0] * 255)}, ${Math.round(c[1] * 255)}, ${Math.round(c[2] * 255)}, ${c[3]})`\n\n/** A draw-list font as a CSS font shorthand. */\nexport const cssFont = (f: Font, family = f.family): string => {\n const fam = GENERIC_FAMILIES.has(family) ? family : `\"${family.replace(/\"/g, \"'\")}\"`\n return `${f.italic ? \"italic \" : \"\"}${f.weight} ${f.size}px ${fam}`\n}\n\nconst apply = (m: Matrix6, x: number, y: number): [number, number] => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]]\n\n// A similarity transform (uniform scale + rotation + translation) keeps circles circles, so the\n// gradient can be expressed in user space without transforming the context.\nconst isSimilarity = (m: Matrix6): boolean => Math.abs(m[0] - m[3]) < 1e-6 && Math.abs(m[1] + m[2]) < 1e-6\n\nconst buildPath = (ctx: Canvas2DLike, path: PathSeg[]): void => {\n ctx.beginPath()\n for (const s of path) {\n switch (s[0]) {\n case \"M\": ctx.moveTo(s[1], s[2]); break\n case \"L\": ctx.lineTo(s[1], s[2]); break\n case \"Q\": ctx.quadraticCurveTo(s[1], s[2], s[3], s[4]); break\n case \"C\": ctx.bezierCurveTo(s[1], s[2], s[3], s[4], s[5], s[6]); break\n case \"Z\": ctx.closePath(); break\n }\n }\n}\n\nconst gradientStops = (g: any, paint: Paint & { stops: { offset: number, color: Color }[] }): void => {\n for (const s of paint.stops) g.addColorStop(s.offset, cssColor(s.color))\n}\n\n// Sets fillStyle / strokeStyle + globalAlpha, then runs `draw`. A gradient with a general matrix is\n// drawn inside a context transform (the path, already built, is not affected — Canvas2D keeps paths\n// in device space).\nconst withPaint = (ctx: Canvas2DLike, paint: Paint, which: \"fill\" | \"stroke\", draw: () => void): void => {\n ctx.globalAlpha = paint.alpha\n if (paint.kind === \"color\") {\n ctx[which === \"fill\" ? \"fillStyle\" : \"strokeStyle\"] = cssColor(paint.color)\n draw()\n return\n }\n const m = paint.matrix\n if (isSimilarity(m)) {\n let g: any\n if (paint.kind === \"linear\") {\n const [x0, y0] = apply(m, 0, 0), [x1, y1] = apply(m, 1, 0)\n g = ctx.createLinearGradient(x0, y0, x1, y1)\n } else {\n const s = Math.hypot(m[0], m[1])\n const [cx, cy] = apply(m, 0, 0), [fx, fy] = apply(m, paint.fx, paint.fy)\n g = ctx.createRadialGradient(fx, fy, paint.r0 * s, cx, cy, s)\n }\n gradientStops(g, paint)\n ctx[which === \"fill\" ? \"fillStyle\" : \"strokeStyle\"] = g\n draw()\n return\n }\n ctx.save()\n ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5])\n const g = paint.kind === \"linear\" ? ctx.createLinearGradient(0, 0, 1, 0) : ctx.createRadialGradient(paint.fx, paint.fy, paint.r0, 0, 0, 1)\n gradientStops(g, paint)\n ctx[which === \"fill\" ? \"fillStyle\" : \"strokeStyle\"] = g\n draw()\n ctx.restore()\n}\n\nconst applyStroke = (ctx: Canvas2DLike, s: Stroke): void => {\n ctx.lineWidth = s.width\n ctx.lineJoin = s.join\n ctx.lineCap = s.cap\n ctx.miterLimit = s.miterLimit\n ctx.setLineDash(s.dash)\n ctx.lineDashOffset = s.dashOffset\n}\n\nconst applyText = (ctx: Canvas2DLike, c: { font: Font, align: string, baseline: string, letterSpacing: number }, hooks: PainterHooks): void => {\n ctx.font = cssFont(c.font, hooks.fontFamily ? hooks.fontFamily(c.font.family) : c.font.family)\n ctx.textAlign = c.align\n ctx.textBaseline = c.baseline\n if (\"letterSpacing\" in ctx) ctx.letterSpacing = `${c.letterSpacing}px`\n}\n\n/** Replay `commands` on `ctx`. The context should start with the identity transform and an empty\n * save stack (the painter sets the identity itself); clearing the surface is the caller's decision.\n * The replay runs inside one save, so no clip, transform or style it sets outlives it (Canvas2D\n * keeps a clip set outside any save, and the next paint's clearRect would clear only that clip). */\nexport const paint = (ctx: Canvas2DLike, commands: DrawCommand[], hooks: PainterHooks = {}): void => {\n ctx.save()\n let saves = 0 // a list restore never pops the wrapper save\n try {\n ctx.setTransform(1, 0, 0, 1, 0, 0)\n ctx.globalAlpha = 1\n for (const c of commands) {\n switch (c.cmd) {\n case \"setTransform\": ctx.setTransform(c.matrix[0], c.matrix[1], c.matrix[2], c.matrix[3], c.matrix[4], c.matrix[5]); break\n case \"save\": ctx.save(); saves++; break\n case \"restore\": if (saves > 0) { ctx.restore(); saves-- } break\n case \"clip\": buildPath(ctx, c.path); ctx.clip(c.rule as \"nonzero\" | \"evenodd\"); break\n case \"fillPath\": buildPath(ctx, c.path); withPaint(ctx, c.paint, \"fill\", () => ctx.fill(c.rule as \"nonzero\" | \"evenodd\")); break\n case \"strokePath\": buildPath(ctx, c.path); applyStroke(ctx, c.stroke); withPaint(ctx, c.paint, \"stroke\", () => ctx.stroke()); break\n case \"fillText\": applyText(ctx, c, hooks); withPaint(ctx, c.paint, \"fill\", () => c.maxWidth > 0 ? ctx.fillText(c.text, c.x, c.y, c.maxWidth) : ctx.fillText(c.text, c.x, c.y)); break\n case \"strokeText\": applyText(ctx, c, hooks); applyStroke(ctx, c.stroke); withPaint(ctx, c.paint, \"stroke\", () => c.maxWidth > 0 ? ctx.strokeText(c.text, c.x, c.y, c.maxWidth) : ctx.strokeText(c.text, c.x, c.y)); break\n case \"drawImage\": {\n const img = hooks.image?.(c.surface)\n if (!img) break\n ctx.globalAlpha = c.alpha\n ctx.drawImage(img, c.src[0], c.src[1], c.src[2], c.src[3], c.dst[0], c.dst[1], c.dst[2], c.dst[3])\n break\n }\n case \"clearRect\": ctx.clearRect(c.rect[0], c.rect[1], c.rect[2], c.rect[3]); break\n default: { const never: never = c; throw new Error(`unhandled draw command ${(never as DrawCommand).cmd}`) }\n }\n }\n } finally {\n for (; saves > 0; saves--) ctx.restore()\n ctx.restore()\n }\n}\n","// The web PAINTER host for `_creatorCanvas`: the HostCanvas table of the wasm runtime (host.gen.ts\n// `WasmHostCanvas`) over OffscreenCanvas. The runtime's AnyCanvas core interprets the SDK's opcode\n// stream and SVG into a draw list; this host keeps one OffscreenCanvas per surface id and replays the\n// list with the vendored AnyCanvas web painter (./gen, `bun run vendor:canvas`). The browser gives text\n// shaping, emoji, font fallback and image decoding for free.\n//\n// `readSurface` / `getSurface` / `surfaceToDataUrl` are how the baked pixels reach the engines (a GPU\n// texture), the canvas UI renderer (`UIImage(canvas)` draws the live OffscreenCanvas) and the DOM\n// renderer (a data URL).\n\nimport { readDrawList } from \"./gen/drawlist\"\nimport { paint, cssFont } from \"./gen/painter\"\n\nexport interface CanvasHost {\n /** The HostCanvas table the wasm runtime calls (a web host's canvas table). */\n table: {\n paint(surfaceId: number, pw: number, ph: number, scale: number, words: Float32Array, strings: string[]): void\n measureText(text: string, family: string, size: number, weight: number, italic: boolean, out: Float32Array): void\n decodeImage(bufferId: number, surfaceId: number, size: Int32Array): boolean\n readPixels(surfaceId: number, size: Int32Array): Uint8Array | null\n releaseSurface(surfaceId: number): void\n }\n /** Straight (non-premultiplied) RGBA8 pixels of a baked surface, for engine texture upload. */\n readSurface(surfaceId: number): { data: Uint8ClampedArray, width: number, height: number } | null\n /** The baked surface as a drawable canvas (device px) — a `CanvasSurfaceProvider` for canvas-ui's\n * `UIImage(canvas)` (lecodes-headless BrowserHost). */\n getSurface(surfaceId: number): { canvas: OffscreenCanvas, width: number, height: number } | null\n /** The baked surface as a data-uri, for the DOM renderer's `<img>` (`UIImage(canvas)`). */\n surfaceToDataUrl(surfaceId: number): string | null\n}\n\n/** `fontFamily` maps a draw-list family to what the page can render (a registered font's real name);\n * the default keeps the family as is. Image decoding is asynchronous in the browser while the table is\n * synchronous, so `decodeImage` answers false: `Canvas.loadImage(fetchResponse)` rejects on the web\n * (SVG goes through the core and works). */\nexport const createCanvasHost = (fontFamily?: (family: string) => string): CanvasHost => {\n const supported = typeof OffscreenCanvas !== \"undefined\"\n const surfaces = new Map<number, OffscreenCanvas>()\n let measureCtx: OffscreenCanvasRenderingContext2D | null = null\n\n const ensure = (surfaceId: number, pw: number, ph: number): OffscreenCanvas | null => {\n if (!supported) return null\n let cv = surfaces.get(surfaceId)\n if (!cv) { cv = new OffscreenCanvas(pw, ph); surfaces.set(surfaceId, cv) }\n else if (cv.width !== pw || cv.height !== ph) { cv.width = pw; cv.height = ph }\n return cv\n }\n\n const table: CanvasHost[\"table\"] = {\n paint: (surfaceId, pw, ph, _scale, words, strings) => {\n const cv = ensure(surfaceId, Math.max(1, pw), Math.max(1, ph))\n const ctx = cv?.getContext(\"2d\")\n if (!cv || !ctx) return\n ctx.setTransform(1, 0, 0, 1, 0, 0)\n ctx.clearRect(0, 0, cv.width, cv.height)\n // `words` is a view into wasm memory, valid for this call only: decode before returning.\n paint(ctx, readDrawList(words, strings), { image: id => surfaces.get(id) ?? null, fontFamily })\n },\n measureText: (text, family, size, weight, italic, out) => {\n out[0] = 0; out[1] = 0; out[2] = 0\n if (!supported) return\n if (!measureCtx) measureCtx = new OffscreenCanvas(1, 1).getContext(\"2d\")\n if (!measureCtx) return\n measureCtx.font = cssFont({ family, size, weight, italic }, fontFamily ? fontFamily(family) : family)\n const m = measureCtx.measureText(text)\n out[0] = m.width\n out[1] = m.fontBoundingBoxAscent ?? m.actualBoundingBoxAscent\n out[2] = m.fontBoundingBoxDescent ?? m.actualBoundingBoxDescent\n },\n decodeImage: () => false,\n readPixels: (surfaceId, size) => {\n const s = readSurface(surfaceId)\n if (!s) return null\n size[0] = s.width; size[1] = s.height\n return new Uint8Array(s.data.buffer, s.data.byteOffset, s.data.byteLength)\n },\n releaseSurface: (surfaceId) => { surfaces.delete(surfaceId) },\n }\n\n const readSurface = (surfaceId: number) => {\n const cv = surfaces.get(surfaceId)\n const ctx = cv?.getContext(\"2d\")\n if (!cv || !ctx) return null\n const img = ctx.getImageData(0, 0, cv.width, cv.height) // straight RGBA8 per the Canvas2D spec\n return { data: img.data, width: cv.width, height: cv.height }\n }\n\n const getSurface = (surfaceId: number) => {\n const cv = surfaces.get(surfaceId)\n return cv ? { canvas: cv, width: cv.width, height: cv.height } : null\n }\n\n const surfaceToDataUrl = (surfaceId: number): string | null => {\n const cv = surfaces.get(surfaceId)\n if (!cv || typeof document === \"undefined\") return null\n const el = document.createElement(\"canvas\")\n el.width = cv.width; el.height = cv.height\n el.getContext(\"2d\")?.drawImage(cv, 0, 0)\n return el.toDataURL()\n }\n\n return { table, readSurface, getSurface, surfaceToDataUrl }\n}\n","export default \"__VITE_ASSET__lw8T$mh5__\"","// The viewer measures text with a real canvas 2D context (the DOM measure system's OffscreenCanvas\n// and the canvas-ui BrowserHost), which only sees fonts the document has actually loaded — so the\n// measurement font must be fully loaded before the first layout, or text lays out against a\n// fallback and never recovers (Yoga caches the measure).\n//\n// The font is the vendored variable Roboto (weights 100–900, latin + cyrillic + greek + vietnamese\n// in ONE file), self-hosted and same-origin. The previous Google-Fonts Inter pipeline was broken on\n// a cold cache: css2 serves each family split into unicode-range subsets, and\n// `fonts.load(\"400 14px Inter\")` (default text = a space) only awaited the *latin* subset — the\n// first measure of Cyrillic text ran against a fallback and produced a wrong layout that later\n// cache-warm loads never reproduced. One complete file makes the await cover every glyph, every\n// weight, with no CDN round trip.\nimport robotoUrl from \"../assets/Roboto-Variable.woff2?url\"\n\n// The default measurement/paint family (createMeasureSystem / paintTree / the lite CSS renderer).\nexport const DEFAULT_FONT_FAMILY = \"Roboto\"\n\n// One variable face serves every weight — a single load covers 400..800.\nconst DEFAULT_FONTS = [`400 14px ${DEFAULT_FONT_FAMILY}`]\n\nconst FONT_STYLE_MARKER = \"data-lecodes-fonts\"\n\n/** Register the vendored @font-face in `doc` (idempotent) and resolve once the bytes are in. */\nexport const ensureFontsLoaded = async (fonts: string[] = DEFAULT_FONTS, doc?: Document) => {\n // Fonts are per-document: the lite host renders inside its own iframe and passes that\n // document; the default serves the classic full-viewer path.\n const target = doc ?? (typeof document === \"undefined\" ? undefined : document)\n if (!target || !target.fonts) return\n\n if (!target.head.querySelector(`style[${FONT_STYLE_MARKER}]`)) {\n // Resolve against the embedder document: the lite host's iframe is a base-less about:blank,\n // and Vite emits a root-relative asset path.\n const absUrl = new URL(robotoUrl, document.baseURI).href\n const style = target.createElement(\"style\")\n style.setAttribute(FONT_STYLE_MARKER, \"\")\n style.textContent =\n `@font-face{font-family:\"${DEFAULT_FONT_FAMILY}\";src:url(\"${absUrl}\") format(\"woff2\");` +\n `font-weight:100 900;font-display:swap}`\n target.head.appendChild(style)\n }\n\n try {\n // load() resolves once each matched face's bytes are in, and resolves (not rejects) with an\n // empty array when nothing matches — so a missing face is a no-op, not a failure.\n await Promise.all(fonts.map(font => target.fonts.load(font)))\n } catch {\n // Best-effort: a font that fails to fetch must never block the simulator from starting.\n }\n}\n\n// ---- app-declared boot fonts (the bundle's `// fonts:` header) ----------------------------------\n\nexport type BootFont = { family: string, weight: number, italic: boolean, url: string }\n\n/** Parse the bundle's `// fonts:` header value (`Family@<weight>[i]=<url>;…`) from the header\n * region of a compiled bundle. A `{fmt}` placeholder in a URL is the container-format choice —\n * replaced with this host's preference (browsers: woff2). */\nexport const parseFontsHeader = (header: string, format = \"woff2\"): BootFont[] => {\n const m = /^\\/\\/ fonts: (.+)$/m.exec(header)\n if (!m) return []\n const out: BootFont[] = []\n for (const entry of m[1].split(\";\")) {\n const eq = entry.indexOf(\"=\")\n if (eq === -1) continue\n const tag = /^(.+)@(\\d+)(i?)$/.exec(entry.slice(0, eq))\n if (!tag) continue\n out.push({ family: tag[1], weight: parseInt(tag[2], 10), italic: tag[3] === \"i\", url: entry.slice(eq + 1).replace(\"{fmt}\", format) })\n }\n return out\n}\n\n/** Boot hold: start loading the app's declared faces, resolving when they settle or the budget\n * expires (~2s, like font-display's block period but shorter) — the host delays first paint on\n * this so text appears in the right font from the start. Faces are added to the document FIRST,\n * so one that loses the race still swaps in when it lands (the degraded-network fallback). */\nexport const loadBootFonts = async (fonts: BootFont[], doc?: Document, budgetMs = 2000): Promise<void> => {\n const target = doc ?? (typeof document === \"undefined\" ? undefined : document)\n if (!target?.fonts || fonts.length === 0) return\n const loads: Promise<unknown>[] = []\n for (const f of fonts) {\n try {\n const face = new FontFace(f.family, `url(\"${f.url}\")`, { weight: String(f.weight), style: f.italic ? \"italic\" : \"normal\" } as FontFaceDescriptors)\n target.fonts.add(face)\n loads.push(face.load().catch(() => { /* missing face → fallback, never a boot failure */ }))\n } catch { /* malformed entry — skip */ }\n }\n await Promise.race([ Promise.all(loads), new Promise((res) => setTimeout(res, budgetMs)) ])\n}\n","// GENERATED by scripts/release/set-version.ts from sdk/package.json — do not edit by hand.\n// The ONE version of the SDK + the runtime (the npm runtime set ships as one version; the C++\n// twin is CREATOR_PKG_SDK_VERSION in creator-pkg/host.gen.h, emitted by gen:bridges from the\n// same manifest). Its MAJOR is the bundle ↔ runtime contract: a bundle's `// sdk:` header line\n// and a host's embedded version must agree on the major for the host to run the bundle; minor\n// and patch never gate anything (features are detected, never versioned).\nexport const SDK_VERSION = \"2.0.0\"\n\n/** The major of a semver string, or null when it is not one. */\nexport const sdkMajor = (version: string | null | undefined): number | null => {\n const m = version?.match(/^(\\d+)\\.\\d+\\.\\d+/)\n return m ? Number(m[1]) : null\n}\n\n/** The `// sdk: <version>` line of a compiled bundle's header (sdk/src/compile/header.ts), read from\n * its first bytes; null for a bundle compiled before the line existed (SDK 0.x / 1.x — the\n * pre-tree contract, which no 2.x host runs). */\nexport const bundleSdkVersion = (head: string): string | null =>\n head.slice(0, 2000).match(/^\\/\\/ sdk: (\\d+\\.\\d+\\.\\d+\\S*)/m)?.[1] ?? null\n\n/** Whether a host embedding `hostVersion` can run a bundle whose header carries `bundleVersion`\n * (null = no line = pre-2.0 contract): the majors must match. */\nexport const bundleRunsOn = (bundleVersion: string | null, hostVersion: string): boolean =>\n sdkMajor(bundleVersion) !== null && sdkMajor(bundleVersion) === sdkMajor(hostVersion)\n","// The 3D host slots (HostGL): the canvas Filament presents on, the textures the browser decodes,\n// media textures.\nimport type { WasmModule } from \"lecodes-web-runtime/src/gen/wasm\"\nimport type { WasmHostGL } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport { getBlob, getBuffer } from \"lecodes-web-shared/src/utils/fetch\"\nimport { getPlayer } from \"lecodes-web-shared/src/utils/mediaplayer\"\nimport type { Page } from \"../page\"\n\n// 12-byte KTX2 magic («KTX 20» CR LF 0x1A LF) — createTexture routes these to the wasm transcoder\nconst KTX2_MAGIC = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a]\nconst isKtx2 = (b: Uint8Array) => b.length >= 12 && KTX2_MAGIC.every((v, i) => b[i] === v)\n\nexport type GLSurface = ReturnType<typeof createGLSurface>\n\n/** `preserve` = the drawing buffer survives the frame (a bundle that captures the scene). */\nexport const createGLSurface = (page: Page, preserve: boolean) => {\n // The attributes creator-gl's context is created with (init.cpp registers it).\n const options: WebGLContextAttributes = {\n antialias: false, depth: true, alpha: false, stencil: false, desynchronized: false,\n failIfMajorPerformanceCaveat: false, powerPreference: \"high-performance\", premultipliedAlpha: true,\n preserveDrawingBuffer: preserve,\n }\n const canvas = page.newCanvas()\n const gl = canvas.getContext(\"webgl2\", options)\n if (!gl) throw new Error(\"WebGL2 is not available\")\n\n let M: WasmModule | null = null\n let ready = false\n const players: { player: HTMLVideoElement, texture: WebGLTexture, lastTime: number }[] = []\n\n const newTexture = (): WebGLTexture => {\n const texture = gl.createTexture()!\n gl.bindTexture(gl.TEXTURE_2D, texture)\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false)\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false)\n gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE)\n return texture\n }\n const importTexture = (module: WasmModule, texture: WebGLTexture, width: number, height: number): number => {\n const id = module.GL.getNewId(module.GL.textures)\n module.GL.textures[id] = texture\n return module._importTexture(id, width, height) >>> 0\n }\n\n return {\n canvas,\n context: gl,\n options,\n /** The table, once the module is up (the context rode in as a module field). */\n table(module: WasmModule): WasmHostGL {\n M = module\n return {\n engineCreated() {\n // the engine just came up (or was rebuilt): its surface is this canvas\n module._createSwapChainHeadless(canvas.width, canvas.height)\n module._creatorWebSetViewport(canvas.width, canvas.height)\n ready = true\n },\n createGLView() { canvas.style.display = \"block\" },\n closeScene() { canvas.style.display = \"none\" },\n createTexture(systemId, flags, onComplete, onReject) {\n const buffer = getBuffer(systemId)\n if (!buffer) { onReject(`createTexture: no buffer behind id ${systemId}`); return }\n const bytes = new Uint8Array(buffer)\n if (isKtx2(bytes)) {\n // KTX2 (Basis Universal): the wasm core transcodes it and keeps the file's mip chain\n const ptr = module._malloc(bytes.length)\n module.HEAPU8.set(bytes, ptr)\n const id = module._createTextureFromKtx2(ptr, bytes.length) >>> 0\n module._free(ptr)\n if (id === 0xffffffff) { onReject(\"KTX2 transcode failed\"); return }\n onComplete(id, module._getTextureWidth(id), module._getTextureHeight(id))\n return\n }\n // PNG / JPG / WebP through the browser's decoder → a GL texture imported into Filament\n // (sRGB unless the flags say linear data)\n createImageBitmap(getBlob(systemId)).then((bitmap) => {\n const texture = newTexture()\n gl.texStorage2D(gl.TEXTURE_2D, 1, (flags & 1) ? gl.RGBA8 : gl.SRGB8_ALPHA8, bitmap.width, bitmap.height)\n gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, bitmap.width, bitmap.height, gl.RGBA, gl.UNSIGNED_BYTE, bitmap)\n onComplete(importTexture(module, texture, bitmap.width, bitmap.height), bitmap.width, bitmap.height)\n }, (e) => onReject(e instanceof Error ? e.message : String(e)))\n },\n createMediaPlayerTexture(playerId) {\n const player = getPlayer(playerId) as HTMLVideoElement | undefined\n if (!player) return 0\n const texture = newTexture()\n players.push({ player, texture, lastTime: 0 })\n return importTexture(module, texture, 0, 0)\n },\n }\n },\n show() { canvas.style.display = \"block\" },\n hide() { canvas.style.display = \"none\" },\n /** The canvas took a new size (page.ts): the engine's viewport follows. */\n resize() { if (M && ready) M._creatorWebSetViewport(canvas.width, canvas.height) },\n /** Before the runtime's tick: the video frames that moved. */\n frame() {\n for (const p of players) {\n if (p.player.readyState < 2 || p.player.currentTime === p.lastTime) continue\n p.lastTime = p.player.currentTime\n gl.bindTexture(gl.TEXTURE_2D, p.texture)\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, p.player)\n }\n },\n destroy() {\n players.length = 0\n gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n },\n }\n}\n","// The 2D host slots (HostScene2d): the canvas creator-2d draws on.\nimport type { WasmModule } from \"lecodes-web-runtime/src/gen/wasm\"\nimport type { WasmHostScene2d } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport type { Page } from \"../page\"\n\nexport type Scene2dSurface = ReturnType<typeof createScene2dSurface>\n\nexport const createScene2dSurface = (page: Page) => {\n // creator-2d's WebGL2 attributes (c2dInit registers the context).\n const options: WebGLContextAttributes = {\n alpha: false, depth: true, stencil: true, antialias: false, premultipliedAlpha: false, desynchronized: false,\n powerPreference: \"high-performance\", failIfMajorPerformanceCaveat: false,\n }\n const canvas = page.newCanvas()\n const gl = canvas.getContext(\"webgl2\", options)\n if (!gl) throw new Error(\"WebGL2 is not available\")\n\n let M: WasmModule | null = null\n let inited = false\n const pushViewport = () => {\n if (!M || !inited) return\n M._c2dSetViewport(canvas.width, canvas.height)\n M._c2dSetDensity(page.size().factor)\n }\n\n // The engine comes up with the first scene (c2dInit on this canvas's context), not before.\n const show = () => {\n if (!M) return\n M._creatorWeb2dEnsureInited()\n inited = true\n pushViewport()\n canvas.style.display = \"block\"\n }\n const hide = () => { canvas.style.display = \"none\" }\n\n return {\n canvas,\n context: gl,\n options,\n table(module: WasmModule): WasmHostScene2d {\n M = module\n return { open2DScene: show, close2DScene: hide }\n },\n /** A 2D scene presents: through the table (`_creator2d.openScene`) or as a destination — which\n * the runtime opens WITHOUT the table's slot, the view being the host's to mount. */\n show,\n hide,\n resize: pushViewport,\n /** After the runtime's tick: the 2D frame, when a 2D scene is open. */\n frame(now: number) { if (M && M._creatorWeb2dSceneOpen()) M._creatorWeb2dRenderFrame(now) },\n destroy() { gl.getExtension(\"WEBGL_lose_context\")?.loseContext() },\n }\n}\n","// Map runtime errors from a compiled bundle back to original source locations.\n//\n// The preview runs the bundle via `new Function(code)`, so the browser won't apply the bundle's\n// inline source map to stack frames automatically — we do it here. Two offsets are involved and both\n// are handled: the bundle carries an inline source map whose generated positions already include the\n// compile header (the backend shifts it), and `new Function` adds a constant wrapper offset that we\n// calibrate at runtime. Self-contained (a tiny VLQ decoder), so there's no extra dependency.\n\ntype RawSourceMap = { version: number, sources: string[], mappings: string, sourcesContent?: (string | null)[] }\ntype OrigPos = { source: string, line: number, column: number }\nexport type MappedFrame = { fn: string | null, source: string, line: number, column: number }\n/** A runtime error from the preview. `native` errors come from the WASM engine (no JS source to map).\n * `nativeFrames` are the crash's decoded engine (C++) function names, top-first — filled in by a\n * follow-up emit once the wasm host has fetched its symbol map (see viewer's wasmCrashSymbolizer). */\nexport type PreviewError = { message: string, frames: MappedFrame[], stack?: string, native?: boolean, detail?: string, nativeFrames?: string[] }\n\n/**\n * Is this a native (WASM engine) error rather than a JS error from the user's bundle? Emscripten\n * surfaces C++ exceptions/aborts as a bare number (a pointer), and WebAssembly traps as\n * `WebAssembly.RuntimeError`; either way there's no JS source position to map. We deliberately do\n * *not* treat an arbitrary frameless JS `Error` as native (that would hijack unrelated editor errors).\n */\nexport const isNativeError = (e: unknown): boolean => {\n if (typeof e === \"number\" || typeof e === \"bigint\") return true\n if (typeof WebAssembly !== \"undefined\" && e instanceof WebAssembly.RuntimeError) return true\n const stack = e instanceof Error ? (e.stack ?? \"\") : \"\"\n return /\\bwasm\\b|wasm-function|\\.wasm/i.test(stack)\n}\n\nconst B64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"\nconst B64_INDEX: Record<string, number> = {}\nfor (let i = 0; i < B64.length; i++) B64_INDEX[B64[i]!] = i\n\n/** Decode one comma-segment of base64-VLQ into signed ints. */\nconst decodeVlq = (segment: string): number[] => {\n const out: number[] = []\n let shift = 0, value = 0\n for (const ch of segment) {\n const digit = B64_INDEX[ch]\n if (digit === undefined) break\n const more = digit & 32\n value += (digit & 31) << shift\n if (more) {\n shift += 5\n } else {\n const negative = value & 1\n value >>= 1\n out.push(negative ? -value : value)\n value = 0\n shift = 0\n }\n }\n return out\n}\n\n/** A minimal source-map consumer: original position for a generated (1-based line, 0-based column). */\nexport class SourceMap {\n private sources: string[]\n // Per generated line: sorted segments [genCol, srcIdx, srcLine, srcCol].\n private lines: number[][][]\n\n constructor(raw: RawSourceMap) {\n this.sources = raw.sources\n this.lines = []\n let srcIdx = 0, srcLine = 0, srcCol = 0\n for (const lineStr of raw.mappings.split(\";\")) {\n const segs: number[][] = []\n let genCol = 0\n if (lineStr) {\n for (const segStr of lineStr.split(\",\")) {\n const v = decodeVlq(segStr)\n if (v.length === 0) continue\n genCol += v[0]!\n if (v.length >= 4) {\n srcIdx += v[1]!\n srcLine += v[2]!\n srcCol += v[3]!\n segs.push([ genCol, srcIdx, srcLine, srcCol ])\n }\n }\n }\n this.lines.push(segs)\n }\n }\n\n originalPositionFor(line: number, column: number): OrigPos | null {\n const segs = this.lines[line - 1]\n if (!segs || segs.length === 0) return null\n // Largest segment whose generated column is <= the queried column.\n let best: number[] | null = null\n for (const seg of segs) {\n if (seg[0]! <= column) best = seg\n else break\n }\n best ??= segs[0]!\n const source = this.sources[best[1]!]\n if (source === undefined) return null\n return { source, line: best[2]! + 1, column: best[3]! }\n }\n}\n\n/** Pull the inline `//# lecodesMap=data:...base64,…` map out of a bundle string (a non-standard\n * directive the browser ignores — see inlineSourceMapComment in the SDK for why). */\nexport const extractInlineSourceMap = (code: string): SourceMap | null => {\n const m = code.match(/\\/\\/# lecodesMap=data:application\\/json;(?:charset=[^;]+;)?base64,([A-Za-z0-9+/=]+)\\s*$/)\n if (!m) return null\n try {\n const json = typeof atob === \"function\" ? atob(m[1]!) : Buffer.from(m[1]!, \"base64\").toString(\"utf8\")\n return new SourceMap(JSON.parse(json) as RawSourceMap)\n } catch {\n return null\n }\n}\n\n// `new Function(body)` wraps the body in `function anonymous(args\\n) {\\n<body>\\n}`, so the body starts\n// a constant number of lines down. Calibrate once per engine by throwing from a one-line body.\nlet functionOffset: number | null = null\nconst newFunctionLineOffset = (): number => {\n if (functionOffset !== null) return functionOffset\n try {\n new Function(\"throw new Error('chisel-calibrate')\")()\n } catch (e) {\n const stack = (e as Error).stack ?? \"\"\n // The body coordinate is the `<anonymous>:line:col` one (V8/Chrome). A one-line body throws at\n // body line 1, so its reported line minus 1 is the wrapper offset.\n const m = stack.match(/<anonymous>:(\\d+):\\d+/)\n functionOffset = m ? parseInt(m[1]!, 10) - 1 : 2\n return functionOffset\n }\n functionOffset = 2\n return functionOffset\n}\n\n/** Parse `error.stack`, mapping each `new Function` frame back to original source via `map`. */\nexport const mapErrorStack = (error: unknown, map: SourceMap): MappedFrame[] => {\n const stack = (error instanceof Error ? error.stack : \"\") ?? \"\"\n const offset = newFunctionLineOffset()\n const frames: MappedFrame[] = []\n for (const raw of stack.split(\"\\n\")) {\n // The user-bundle position is the `<anonymous>:line:col` coordinate (V8 gives body-relative\n // lines here; an `eval at … (file:line)` prefix, if present, is the call site — not it).\n const m = raw.match(/<anonymous>:(\\d+):(\\d+)/)\n if (!m) continue\n const genLine = parseInt(m[1]!, 10) - offset\n const genCol = parseInt(m[2]!, 10) - 1\n if (genLine < 1) continue\n const orig = map.originalPositionFor(genLine, genCol < 0 ? 0 : genCol)\n if (!orig) continue\n const fnMatch = raw.match(/at\\s+([^\\s(]+)\\s*\\(/)\n frames.push({ fn: fnMatch ? fnMatch[1]! : null, source: orig.source, line: orig.line, column: orig.column })\n }\n return frames\n}\n\n/** Rewrite every `<filename>:line:col` frame in a block of text to its original position.\n * This is the shape a host that EVALUATES the bundle as one named file produces — quickjs on the\n * native hosts (`module.js:5:51631`, see creatorUtilsHandler) and `vm.runInContext` in the headless\n * renderer (`project.js:…`) — as opposed to the preview's `new Function` frames above. Both report\n * 1-based columns. Frames naming other files (a host's own launcher, `native`) pass through. */\nexport const mapNamedFileStack = (text: string, map: SourceMap, filename: string): string => {\n const escaped = filename.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n return text.replace(new RegExp(`\\\\b${escaped}:(\\\\d+):(\\\\d+)`, \"g\"), (whole, l: string, c: string) => {\n const orig = map.originalPositionFor(parseInt(l, 10), Math.max(0, parseInt(c, 10) - 1))\n return orig ? `${orig.source.replace(/^(\\.\\/|\\/)/, \"\")}:${orig.line}:${orig.column}` : whole\n })\n}\n\n/** A one-line, human-readable original location for an error, or null if it can't be mapped. */\nexport const formatErrorLocation = (error: unknown, code: string): { message: string, frames: MappedFrame[] } | null => {\n const map = extractInlineSourceMap(code)\n if (!map) return null\n const frames = mapErrorStack(error, map)\n if (frames.length === 0) return null\n const top = frames[0]!\n const msg = error instanceof Error ? error.message : String(error)\n const where = `${top.source}:${top.line}:${top.column}${top.fn ? ` (${top.fn})` : \"\"}`\n return { message: `${msg}\\n at ${where}`, frames }\n}\n","// What a bundle threw, mapped back to the app's source. A bundle is evaluated through `new Function`\n// (./world.ts), whose frames the browser cannot map itself: the bundle's inline source map is applied\n// here. Errors arrive two ways — the runtime's own lines (`[ERROR] run …`: a throw it caught around\n// a callback) and the window's error events (everything else, a native trap of the engine included).\nimport { symbolizeWasmFrames } from \"lecodes-web-runtime/src/wasmCrashSymbolizer\"\nimport { extractInlineSourceMap, isNativeError, mapErrorStack, type MappedFrame, type PreviewError, type SourceMap } from \"lecodes-web-shared/src/sourcemapError\"\n\nexport type { MappedFrame, PreviewError }\n\n/** The runtime's error lines: what a bundle threw, and where the runtime caught it. */\nconst RUNTIME_ERROR = /^\\[ERROR\\] (run|host callback|JsDispatch|timer|setLoop|animate|tween)\\b:? ?([\\s\\S]*)$/\n\ntype RunRecord = { sourceMap: SourceMap | null, onError?: (error: PreviewError) => void }\n\nexport type ErrorReporter = ReturnType<typeof createErrorReporter>\n\n/** `native` = the profile carries an engine whose traps can be symbolized (the `full` one). */\nexport const createErrorReporter = (win: Window, native: boolean) => {\n const runs: RunRecord[] = []\n\n const emit = (record: RunRecord, e: unknown, frames: MappedFrame[], eventMessage?: string) => {\n if (frames.length === 0 && isNativeError(e)) {\n // The engine (Emscripten) prints the real message to the console; the value that reaches JS\n // is a pointer / an abort code. Surface it as an engine error with what description there is.\n const raw = typeof e === \"number\" || typeof e === \"bigint\" ? `code ${e}` : e instanceof Error ? (e.message || e.name) : String(e)\n const detail = [eventMessage, raw].filter((v): v is string => !!v).filter((v, i, a) => a.indexOf(v) === i).join(\"\\n\")\n console.error(`[lecodes] native engine error — ${detail || raw} (see the console for the engine's message)`)\n const error: PreviewError = { message: \"Native engine error\", detail, frames: [], native: true, stack: e instanceof Error ? e.stack : undefined }\n record.onError?.(error)\n // Late enrichment: the trap's engine frames through the lazy symbol map, emitted again.\n if (error.stack && native) {\n void symbolizeWasmFrames(error.stack).then((nativeFrames) => { if (nativeFrames.length > 0) record.onError?.({ ...error, nativeFrames }) })\n }\n return\n }\n const message = e instanceof Error ? e.message : String(e)\n const top = frames[0]\n console.error(top ? `[lecodes] ${message}\\n at ${top.source}:${top.line}:${top.column}${top.fn ? ` (${top.fn})` : \"\"}` : `[lecodes] ${message}`)\n record.onError?.({ message, frames, stack: e instanceof Error ? e.stack : undefined })\n }\n\n // An error whose stack maps into one of the runs' source maps (the newest first), or a native one.\n const report = (e: unknown, eventMessage?: string) => {\n for (let i = runs.length - 1; i >= 0; i--) {\n const record = runs[i]!\n if (!record.sourceMap) continue\n const frames = mapErrorStack(e, record.sourceMap)\n if (frames.length > 0) return emit(record, e, frames, eventMessage)\n }\n const last = runs[runs.length - 1]\n if (last && isNativeError(e)) emit(last, e, [], eventMessage)\n }\n\n let pending: { message: string, stack: string[] } | null = null\n const flush = () => {\n const record = runs[runs.length - 1]\n const held = pending\n pending = null\n if (!held || !record) return\n const error = new Error(held.message.replace(/^Error: /, \"\"))\n error.stack = held.stack.join(\"\\n\")\n emit(record, error, record.sourceMap ? mapErrorStack(error, record.sourceMap) : [])\n }\n\n const onError = (ev: ErrorEvent) => report(ev.error ?? ev.message, ev.message)\n const onRejection = (ev: PromiseRejectionEvent) => report(ev.reason)\n win.addEventListener(\"error\", onError)\n win.addEventListener(\"unhandledrejection\", onRejection)\n\n return {\n /** A bundle about to run: errors that map into it go to `onError` until the run is dropped. */\n track(code: string, onError?: (error: PreviewError) => void) {\n const record: RunRecord = { sourceMap: extractInlineSourceMap(code), onError }\n runs.push(record)\n return { drop() { const i = runs.indexOf(record); if (i >= 0) runs.splice(i, 1) } }\n },\n /** Where a stack leads in the source of the bundle that runs now (a creation site an inspector\n * was handed): its frames, the innermost first. */\n locate(error: unknown): MappedFrame[] {\n const map = runs[runs.length - 1]?.sourceMap\n return map ? mapErrorStack(error, map) : []\n },\n /** A line the module printed. The runtime logs what a bundle threw as `[ERROR] <where> <message>`\n * and its stack — in the same line, or a line per frame after it: the lines of one error come in\n * a row, and the error is reported when the row is through. True = the line was the error's. */\n runtimeLine(line: string): boolean {\n if (pending && /^\\s+at /.test(line)) { pending.stack.push(line); return true }\n const m = RUNTIME_ERROR.exec(line)\n if (!m || runs.length === 0) return false\n flush()\n const [message, ...stack] = m[2]!.split(\"\\n\")\n pending = { message: (message ?? \"\").replace(/^JsTask /, \"\"), stack }\n win.setTimeout(flush, 0)\n return true\n },\n dispose() {\n win.removeEventListener(\"error\", onError)\n win.removeEventListener(\"unhandledrejection\", onRejection)\n runs.length = 0\n },\n }\n}\n","// The compiler's bundle header (`lecodes compile` / the builder write it at the top of app.js):\n// // sdk: 2.0.0 the SDK the bundle was compiled with\n// // preload: material:lit;uberarchive;hero.glb what the engine fetches before the first run\n// (`material:<name>` = a built-in material the\n// bundle asks for — ./system.ts picks the archives)\n// // gl: disable | defer no 3D engine up front (the bundle calls\n// `createEngine()` when it needs one — or never)\n// // 2d: enable the project uses Scene2D (creator-2d)\n// // plugins: camera;map the app's plugins, by id (app.json)\n// // fonts: … boot faces (parseFontsHeader)\n// What it MEANS for the engines is `profileOf`: the one place a header becomes a runtime profile.\nimport { parseFontsHeader, type BootFont } from \"lecodes-web-shared/src/utils/fonts\"\nimport type { Profile } from \"lecodes-web-runtime/src/profile\"\n\n/** The browser profiles of the runtime module (runtime/web/native/CMakeLists.txt). */\nexport type HostProfile = Extract<Profile, \"full\" | \"2d\" | \"ui\">\n\nexport type BundleHeader = {\n /** `// sdk: <version>` — the SDK the bundle was compiled with; null = compiled before 2.0 (the\n * pre-tree contract, which this runtime cannot run). Its major must be the host's. */\n sdk: string | null\n /** `// name:` — the project's name as the compiler wrote it. */\n name: string | null\n preloads: Set<string>\n /** `on` = the 3D engine up front, `defer` = the bundle calls `createEngine()` itself, `off` = the\n * bundle names no 3D call at all. */\n gl: \"on\" | \"defer\" | \"off\"\n is2d: boolean\n /** `// plugins:` — the ids of the app's plugins: the ones a host registers for this bundle. A\n * bundle without the line has none. */\n plugins: Set<string>\n bootFonts: BootFont[]\n}\n\nexport const parseBundleHeader = (code: string): BundleHeader => {\n // Wide enough for a `// fonts:` line with several faces (URLs make it the longest header line).\n const header = code.slice(0, 2000)\n const preloads = new Set<string>()\n const preload = header.match(/\\/\\/ preload: (.+)/)\n if (preload) for (const item of preload[1]!.split(\";\")) preloads.add(item)\n const gl = header.includes(\"// gl: disable\") ? \"off\" : header.includes(\"// gl: defer\") ? \"defer\" : \"on\"\n const sdk = header.match(/^\\/\\/ sdk: (\\d+\\.\\d+\\.\\d+\\S*)/m)?.[1] ?? null\n const name = header.match(/^\\/\\/ name: (.+)$/m)?.[1]?.trim() ?? null\n const plugins = new Set((header.match(/^\\/\\/ plugins: (.+)$/m)?.[1] ?? \"\").split(\";\").map((id) => id.trim()).filter(Boolean))\n return { sdk, name, preloads, gl, is2d: header.includes(\"// 2d: enable\"), plugins, bootFonts: parseFontsHeader(header) }\n}\n\n/** The profile a bundle runs on: Filament only for a bundle that names a 3D call (`gl` on / defer),\n * creator-2d for a 2D one, the UI core alone for the rest — a UI app never downloads an engine. */\nexport const profileOf = (header: BundleHeader): HostProfile =>\n header.gl !== \"off\" ? \"full\" : header.is2d ? \"2d\" : \"ui\"\n","// The page: the container the host fills, its size, and the canvases in it.\n//\n// A canvas is sharp when its backing store has exactly the device pixels of its box. That count is\n// the browser's to give (`devicePixelContentBox`): at a fractional pixel ratio (Windows at 125 % /\n// 150 %, a browser zoom) `round(css × ratio)` is off by one now and then, and a canvas one pixel\n// short is resampled — soft text. The observer also fires when the ratio alone changes (the window\n// moved to another display), where the CSS size stays what it was.\nimport { viewScale } from \"lecodes-web-shared/src/ui/viewScale\"\n\nexport type PageSize = {\n /** The container in CSS px — the app's logical viewport. */\n width: number\n height: number\n /** The container in device px — every canvas's backing store. */\n pixelWidth: number\n pixelHeight: number\n /** Device px per CSS px (devicePixelRatio × a CSS zoom above the container). */\n factor: number\n}\n\nexport type Page = ReturnType<typeof createPage>\n\nexport const createPage = (root: HTMLElement) => {\n const doc = root.ownerDocument\n const win = doc.defaultView ?? window\n\n // Until the observer has answered (and where it cannot give device px: Safari), the ratio times\n // the zoom recovered from the DOM.\n const estimate = (width: number, height: number): PageSize => {\n const factor = (win.devicePixelRatio || 1) * viewScale(root)\n return { width, height, factor, pixelWidth: Math.max(1, Math.round(width * factor)), pixelHeight: Math.max(1, Math.round(height * factor)) }\n }\n let size = estimate(Math.max(1, root.clientWidth), Math.max(1, root.clientHeight))\n\n const canvases: HTMLCanvasElement[] = []\n const fit = (canvas: HTMLCanvasElement) => {\n if (canvas.width !== size.pixelWidth) canvas.width = size.pixelWidth\n if (canvas.height !== size.pixelHeight) canvas.height = size.pixelHeight\n }\n /** A canvas over the whole container, hidden until something presents on it. Its box is the\n * container's, so the container's device px are its own. */\n const newCanvas = (): HTMLCanvasElement => {\n const canvas = doc.createElement(\"canvas\")\n canvas.style.cssText = \"position:absolute;inset:0;width:100%;height:100%;display:none;\"\n root.appendChild(canvas)\n fit(canvas)\n canvases.push(canvas)\n return canvas\n }\n\n const listeners = new Set<(size: PageSize) => void>()\n const apply = (next: PageSize) => {\n if (next.width <= 0 || next.height <= 0) return\n size = next\n for (const canvas of canvases) fit(canvas)\n for (const listener of listeners) listener(size)\n }\n const observer = new ResizeObserver(([entry]) => {\n if (!entry) return\n const { width, height } = entry.contentRect\n const device = entry.devicePixelContentBoxSize?.[0]\n const estimated = estimate(width, height)\n // Under an EMULATED pixel ratio (the responsive mode of the browser's tools) the box is\n // reported in the real display's px while the page is drawn at the emulated ratio: the box\n // is believed only where it agrees with the ratio to the pixel it is there to settle.\n const agrees = device && Math.abs(device.inlineSize - width * estimated.factor) <= 1 && Math.abs(device.blockSize - height * estimated.factor) <= 1\n if (!device || !agrees) { apply(estimated); return }\n apply({ width, height, pixelWidth: Math.max(1, device.inlineSize), pixelHeight: Math.max(1, device.blockSize), factor: estimated.factor })\n })\n try { observer.observe(root, { box: \"device-pixel-content-box\" }) } catch { observer.observe(root) }\n\n return {\n root, doc, win,\n size: () => size,\n newCanvas,\n /** Called with every new size, after the canvases took it. */\n onResize(listener: (size: PageSize) => void) { listeners.add(listener); return () => { listeners.delete(listener) } },\n destroy() {\n observer.disconnect()\n listeners.clear()\n for (const canvas of canvases) canvas.remove()\n canvases.length = 0\n },\n }\n}\n","// The doors of the plugins' web halves. A half is the `web/` folder of a plugin: generated glue\n// over its contract and the implementation behind it; it imports nothing of the host — it declares\n// the SHAPE of the host it needs, and `HalfHost` is the object that fits them all.\n//\n// The host names no plugin and ships none. Whoever builds the page hands the halves over\n// (`host.registerPlugin(id, register)`), and WHICH of them a bundle has is the app's list\n// (`\"plugins\"` of app.json → the `// plugins:` line of the bundle's header): what a shell built\n// from the project installs is what the browser registers, so an app cannot work here and fail in\n// its shell. Inside that a half registers itself only where the browser can serve it (a camera\n// needs getUserMedia), so `CameraView.isSupported` answers honestly.\nimport { getBuffer, putBuffer } from \"lecodes-web-shared/src/utils/fetch\"\nimport type { WebViewFactory } from \"lecodes-web-shared/src/ui/nativeView\"\nimport type { ServiceFactory } from \"./tables/serviceSystem\"\n\nexport type HalfHost = {\n /** `version` = the contract version the half was generated from. */\n registerView(name: string, factory: WebViewFactory, version?: number): void\n registerService(name: string, factory: ServiceFactory, version?: number): void\n /** Store bytes in the host's buffer table: the handle a File crosses as. */\n putBuffer(bytes: ArrayBuffer): number\n /** The bytes of a buffer of that table — what the handle of a File the app sent names. */\n getBuffer(systemId: number): ArrayBuffer | Uint8Array | null | undefined\n}\n\n/** What a half exports: it registers its views and services with the host it is handed. */\nexport type PluginHalf = (host: HalfHost) => void\n\n/** Where a registration lands. A renderer that mounts no native view has no `registerView`: views\n * stay unsupported there, services register all the same. */\nexport type PluginDoors = {\n registerView?: (name: string, factory: WebViewFactory, version?: number) => void\n unregisterView?: (name: string) => void\n registerService: (name: string, factory: ServiceFactory, version?: number) => void\n unregisterService: (name: string) => void\n}\n\ntype Registration = { id: string, version: number } & ({ kind: \"view\", name: string, factory: WebViewFactory } | { kind: \"service\", name: string, factory: ServiceFactory })\n\nexport const createPlugins = (doors: PluginDoors) => {\n // What each half registered, by the id of its plugin: a half knows its channel's name, the app's\n // list knows ids.\n const registrations: Registration[] = []\n const known = new Set<string>()\n\n return {\n has: (id: string) => known.has(id),\n register(id: string, half: PluginHalf) {\n if (known.has(id)) return\n known.add(id)\n half({\n registerView: (name, factory, version = 1) => { registrations.push({ id, version, kind: \"view\", name, factory }) },\n registerService: (name, factory, version = 1) => { registrations.push({ id, version, kind: \"service\", name, factory }) },\n putBuffer,\n getBuffer,\n })\n },\n /** The plugins of the bundle about to run: theirs are behind the doors, the others are not. */\n allow(ids: Iterable<string>) {\n const allowed = new Set(ids)\n for (const r of registrations) {\n const on = allowed.has(r.id)\n if (r.kind === \"view\") { if (on) doors.registerView?.(r.name, r.factory, r.version); else doors.unregisterView?.(r.name) }\n else if (on) doors.registerService(r.name, r.factory, r.version)\n else doors.unregisterService(r.name)\n }\n },\n }\n}\n","// The safe area of the page: what the browser reports (`env(safe-area-inset-*)` — zero on a desktop,\n// the notch and the home indicator on a phone) unless the embedder sets its own. The host knows no\n// device: an embedder that draws one over the app says how much of each edge it took.\nimport type { SafeArea } from \"lecodes-web-canvas/src/web/renderer\"\n\nexport type { SafeArea }\n\nexport const createSafeArea = (root: HTMLElement) => {\n // env() is only readable through a computed style.\n const probe = root.ownerDocument.createElement(\"div\")\n probe.style.cssText =\n \"position:absolute;visibility:hidden;pointer-events:none;width:0;height:0;\" +\n \"padding:env(safe-area-inset-top,0px) env(safe-area-inset-right,0px) env(safe-area-inset-bottom,0px) env(safe-area-inset-left,0px);\"\n root.appendChild(probe)\n const px = (value: string) => Math.round(parseFloat(value) || 0)\n const fromPage = (): SafeArea => {\n const style = getComputedStyle(probe)\n return { top: px(style.paddingTop), right: px(style.paddingRight), bottom: px(style.paddingBottom), left: px(style.paddingLeft) }\n }\n\n let set: SafeArea | null = null\n return {\n /** The embedder's insets, or null for the page's own. */\n set(area: SafeArea | null) { set = area },\n current: (): SafeArea => set ?? fromPage(),\n destroy() { probe.remove() },\n }\n}\n","// GENERATED by engines/gl/materials/build.mjs from materials.json `groups` — do not edit.\n// The archive a built-in material rides: a name that is not here rides the base one.\nexport const MATERIAL_GROUP: Record<string, string> = {\n \"lightmap\": \"world\",\n \"lightmap-masked\": \"world\",\n \"lightmap-lite\": \"world\",\n \"lightmap-masked-lite\": \"world\",\n \"terrain\": \"world\",\n \"terrain-lightmap\": \"world\",\n \"foliage\": \"world\",\n \"foliage-masked\": \"world\",\n}\n","// Which materials archives a bundle needs (./system.ts fetches them). The bundle's `// preload:`\n// header names the built-in MATERIALS it asks for (`material:lit`), never the archives: how the\n// shared set is split into files (materials.json `groups`, the generated table beside the\n// archives) may change under a bundle compiled long ago, and that bundle must still get the archive\n// its material rides today.\nimport { MATERIAL_GROUP } from \"lecodes-web-runtime/src/gen/materialGroups.gen\"\n\nconst PREFIX = \"material:\"\n\n/** The groups whose archives hold the materials `preloads` names — \"base\" first, each once. A\n * material no group names rides the base archive. */\nexport const materialGroupsOf = (preloads: Iterable<string>): string[] => {\n const groups = new Set<string>()\n for (const item of preloads) {\n if (item.startsWith(PREFIX)) groups.add(MATERIAL_GROUP[item.slice(PREFIX.length)] ?? \"base\")\n }\n return [...groups].sort((a, b) => (a === \"base\" ? -1 : b === \"base\" ? 1 : a.localeCompare(b)))\n}\n","export default \"__VITE_ASSET__g0Ta5n91__\"","export default \"__VITE_ASSET__D83o3gZr__\"","export default \"__VITE_ASSET__CQj_jpxr__\"","export default \"__VITE_ASSET__D7kfxuDz__\"","// The engine's built-in blobs, which the runtime asks for by system id (globals.h): 1 = the default\n// IBL, 2 = the ubershader archive, 3 = the archives of the materials a bundle asked for\n// (./materials.ts), back to back. Only the `full` profile reads them.\nimport { materialGroupsOf } from \"./materials\"\nimport materialsBase from \"lecodes-web-runtime/src/assets/materials.bin?url\"\nimport materialsWorld from \"lecodes-web-runtime/src/assets/materials-world.bin?url\"\nimport iblTexture from \"lecodes-web-runtime/src/assets/neutral_ibl128.ktx?url\"\nimport uberarchive from \"lecodes-web-runtime/src/assets/uberarchive.bin?url\"\n\nexport type SystemBuffers = Partial<Record<1 | 2 | 3, ArrayBuffer>>\n\nconst ARCHIVES: Record<string, string> = { base: materialsBase, world: materialsWorld }\n\nconst join = (parts: ArrayBuffer[]): ArrayBuffer => {\n const out = new Uint8Array(parts.reduce((n, p) => n + p.byteLength, 0))\n let at = 0\n for (const p of parts) { out.set(new Uint8Array(p), at); at += p.byteLength }\n return out.buffer\n}\n\nexport const loadSystemBuffers = async (preloads: Iterable<string>): Promise<SystemBuffers> => {\n const bytes = async (url: string) => {\n const response = await fetch(url)\n if (!response.ok) throw new Error(`${url} → HTTP ${response.status}`)\n return response.arrayBuffer()\n }\n const wanted = materialGroupsOf(preloads).map((group) => ARCHIVES[group]).filter((url): url is string => !!url)\n const [ibl, uber, ...materials] = await Promise.all([bytes(iblTexture), bytes(uberarchive), ...wanted.map(bytes)])\n return { 1: ibl, 2: uber, ...(materials.length > 0 ? { 3: join(materials) } : {}) }\n}\n","// HostApp: the app's lifecycle and environment — the document's visibility, the network state, the\n// url the app was opened with, the orientation it asks for.\nimport type { WasmHostApp } from \"lecodes-web-runtime/src/gen/host.gen\"\n\nexport type AppTableOptions = {\n /** app.setOrientation sink (an embedder that draws a device turns it); absent = a best-effort\n * screen.orientation.lock on the page (browsers honor it only in fullscreen). */\n onOrientation?: (mode: \"landscape\" | \"portrait\" | \"auto\") => void\n /** Push an app event into the runtime (`creatorWebAppEvent`). */\n push: (event: string, data?: string) => void\n}\n\nexport const createAppTable = (options: AppTableOptions) => {\n const onVisibility = () => options.push(document.hidden ? \"pause\" : \"resume\")\n const onOnline = () => options.push(\"online\")\n const onOffline = () => options.push(\"offline\")\n document.addEventListener(\"visibilitychange\", onVisibility)\n window.addEventListener(\"online\", onOnline)\n window.addEventListener(\"offline\", onOffline)\n\n const table: WasmHostApp = {\n state: () => (document.hidden ? \"background\" : \"active\"),\n isOnline: () => navigator.onLine,\n openUrl(url) { window.open(url, \"_blank\", \"noopener\") },\n setOrientation(mode) {\n const m = mode === \"landscape\" || mode === \"portrait\" ? mode : \"auto\"\n if (options.onOrientation) { options.onOrientation(m); return }\n const so = typeof screen !== \"undefined\" ? (screen.orientation as unknown as { lock?: (m: string) => Promise<void>, unlock?: () => void }) : undefined\n if (!so) return\n try {\n if (m === \"auto\") so.unlock?.()\n else so.lock?.(m)?.catch?.(() => {})\n } catch { /* not fullscreen / unsupported */ }\n },\n }\n return {\n table,\n /** The embedder delivers a warm link (\"url\") or a synthetic lifecycle event. */\n emit: (event: string, data?: string) => options.push(event, data),\n dispose() {\n document.removeEventListener(\"visibilitychange\", onVisibility)\n window.removeEventListener(\"online\", onOnline)\n window.removeEventListener(\"offline\", onOffline)\n },\n }\n}\n","import { putBuffer } from \"lecodes-web-shared/src/utils/fetch\";\n\nexport const openFilePicker = (\n onComplete: (files: any) => void,\n onReject: (error: any) => void,\n multiple: boolean,\n accept?: string\n) => {\n try {\n const input = document.createElement(\"input\");\n input.type = \"file\";\n input.multiple = multiple;\n\n if (accept) {\n input.accept = accept;\n }\n\n input.onchange = async () => {\n const { files } = input;\n if (multiple) {\n const arr: any[] = []\n if (!files) return onComplete([])\n for (let file of files) {\n arr.push([\n putBuffer(await file.arrayBuffer()),\n file.name,\n file.size\n ])\n }\n onComplete(arr);\n } else {\n if (!files || files.length === 0) return onComplete(null)\n onComplete([ [ putBuffer(await files[0].arrayBuffer()), files[0].name, files[0].size ] ]);\n }\n };\n\n // Срабатывает когда диалог закрывается без выбора файла\n window.addEventListener(\n \"focus\",\n () => {\n setTimeout(() => {\n if (!input.files || input.files.length === 0) {\n onComplete(multiple ? [] : null);\n }\n }, 300);\n },\n { once: true }\n );\n\n input.click();\n } catch (error) {\n onReject(error);\n }\n};","// HostDevice. The data fields are read at every resize (the runtime's hostWasmSync): live getters\n// keep the pixel ratio honest when the window moves between displays.\nimport type { WasmHostDevice } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport { getBlob } from \"lecodes-web-shared/src/utils/fetch\"\nimport { openFilePicker } from \"./openFilePicker\"\n\nexport const createDeviceTable = (language: () => string): WasmHostDevice => ({\n get platform() { return \"web\" },\n get language() { return language() },\n get pixelRatio() { return window.devicePixelRatio || 1 },\n vibrate() { try { navigator.vibrate?.(30) } catch { /* unsupported */ } },\n clipboardWrite(text) { navigator.clipboard?.writeText(text).catch(() => {}) },\n clipboardRead(onComplete, onReject) {\n const c = navigator.clipboard\n if (!c?.readText) { onReject(\"Clipboard is not available\"); return }\n c.readText().then(onComplete, (e: unknown) => onReject(e instanceof Error ? e.message : \"Clipboard read failed\"))\n },\n // No web share sheet — save (download) the buffer. `text` is ignored on web.\n share(systemId) {\n const url = URL.createObjectURL(getBlob(systemId))\n const a = document.createElement(\"a\")\n a.href = url\n a.download = \"image.png\"\n document.body.appendChild(a)\n a.click()\n a.remove()\n URL.revokeObjectURL(url)\n },\n openFilePicker: (onComplete, onReject, multiple, accept) => openFilePicker(onComplete, onReject, multiple, accept ?? undefined),\n // The browser has no standalone camera-permission prompt: getUserMedia asks at capture time.\n requestCamera(onComplete) { onComplete() },\n})\n","// HostFetch: the network and the buffer store. The store is web-shared's — the one every web\n// package reads (a texture is resolved by its system id there, a plugin's File is a buffer of it).\nimport type { WasmHostFetch } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport { _disposeFetch, _fetchLocal, getBlob, getBuffer, putBuffer } from \"lecodes-web-shared/src/utils/fetch\"\nimport type { SystemBuffers } from \"../system\"\n\nexport const createFetchTable = (system: SystemBuffers = {}): WasmHostFetch => ({\n local: (path) => _fetchLocal(path),\n dispose: (id) => _disposeFetch(id),\n request(url, method, headers, body, form, onComplete, onReject, onProgress) {\n // an asset the store already holds (`id:<n>`)\n if (url.startsWith(\"id:\")) { const id = Number(url.slice(3)); onComplete(id, getBuffer(id) ? 200 : 404); return }\n const h: Record<string, string> = {}\n for (let i = 0; i + 1 < headers.length; i += 2) h[headers[i]] = headers[i + 1]\n let payload: BodyInit | undefined\n if (form.length > 0) {\n const fd = new FormData()\n for (const e of form) {\n if (e.key === null) continue\n if (e.bufferId > 0) fd.append(e.key, getBlob(e.bufferId), e.filename ?? undefined)\n else fd.append(e.key, e.value ?? \"\")\n }\n payload = fd\n } else if (body !== null) payload = body\n ;(async () => {\n try {\n const resp = await fetch(url, { method, headers: h, body: payload, mode: \"cors\", credentials: \"omit\" })\n const reader = onProgress ? resp.body?.getReader() : undefined\n if (!reader) {\n onComplete(putBuffer(await resp.arrayBuffer()), resp.status)\n return\n }\n const total = Number(resp.headers.get(\"content-length\")) || undefined\n const chunks: Uint8Array[] = []\n let loaded = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (value) { chunks.push(value); loaded += value.length; onProgress!({ loaded, total }) }\n }\n const out = new Uint8Array(loaded)\n let off = 0\n for (const c of chunks) { out.set(c, off); off += c.length }\n onComplete(putBuffer(out.buffer), resp.status)\n } catch (e) {\n onReject(e instanceof Error ? e.message : String(e))\n }\n })()\n },\n buffer: (id) => { const b = getBuffer(id); return b ? new Uint8Array(b) : null },\n putBuffer: (bytes) => putBuffer(bytes.slice().buffer), // an encoded canvas (Canvas.toFile) → a File\n bufferSlice(id, start, end) {\n const b = getBuffer(id)\n if (!b) return null\n const s = Math.max(0, Math.min(start, b.byteLength)), e = Math.max(s, Math.min(end, b.byteLength))\n return new Uint8Array(b, s, e - s)\n },\n systemBuffer: (id) => { const b = system[id as 1 | 2 | 3]; return b ? new Uint8Array(b) : null },\n})\n","// Browser input host behind `_creatorInput.key / read / setPointerLock / registerEvent`\n// (sdk/src/bridges/input.d.ts).\n//\n// Buttons: keyboard keys, mouse buttons and gamepad buttons live in ONE held set keyed by the shared\n// code vocabulary (\"KeyW\" / \"MouseLeft\" / \"GamepadSouth\"); gamepad buttons are additionally keyed\n// per pad (\"GamepadSouth@1\") so `inputKey(code, pad)` can scope. Continuous channels (mouse motion /\n// wheel / sticks) are sampled on a requestAnimationFrame boundary: the accumulator that fills during\n// a frame becomes the value every `inputRead` sees during the next one — \"motion during the previous\n// frame\", the same contract the native hosts implement on their event pump.\n\nconst MOUSE_BUTTON_CODES = [\"MouseLeft\", \"MouseMiddle\", \"MouseRight\", \"MouseBack\", \"MouseForward\"]\n// W3C \"standard\" gamepad mapping button index → code.\nconst GAMEPAD_BUTTON_CODES = [\n \"GamepadSouth\", \"GamepadEast\", \"GamepadWest\", \"GamepadNorth\", \"GamepadL1\", \"GamepadR1\", \"GamepadL2\", \"GamepadR2\",\n \"GamepadSelect\", \"GamepadStart\", \"GamepadL3\", \"GamepadR3\", \"GamepadUp\", \"GamepadDown\", \"GamepadLeft\", \"GamepadRight\",\n]\nconst MAX_PADS = 4\nconst PAD_BASE = 16, PAD_STRIDE = 16\nconst TRIGGER_AS_BUTTON = 0.5 // analog L2/R2 count as held past this\n\nexport type InputEventSink = (kind: number, code: string, gamepad: number, repeat: number) => void\n\nexport interface InputHostOptions {\n /** Windows to listen on for keys (the app's own window plus the embedder's, which keeps focus\n * until the user clicks the preview). */\n windows: Window[]\n /** The viewport element: mouse position is relative to it, pointer lock is requested on it. */\n root: HTMLElement\n /** Listen for keyboard keys (default true). Mouse/gamepad are always wired. */\n keyboard?: boolean\n}\n\nexport const createInputHost = (options: InputHostOptions) => {\n const held = new Set<string>()\n let sink: InputEventSink | null = null\n const emit = (kind: number, code: string, gamepad = -1, repeat = 0) => { sink?.(kind, code, gamepad, repeat) }\n\n // ---- keyboard ----------------------------------------------------------------------------------\n const onKeyDown = (e: KeyboardEvent) => {\n if (!e.code) return\n const wasHeld = held.has(e.code)\n held.add(e.code)\n emit(0, e.code, -1, wasHeld || e.repeat ? 1 : 0)\n }\n const onKeyUp = (e: KeyboardEvent) => { if (e.code && held.delete(e.code)) emit(1, e.code) }\n // Focus loss: the window never sees the release of a key held through it → clear + emit keyups.\n const onBlur = () => {\n for (const code of [...held]) {\n if (!code.startsWith(\"Gamepad\")) { held.delete(code); emit(1, code) }\n }\n }\n\n // ---- mouse -------------------------------------------------------------------------------------\n const { root } = options\n let mouseX = 0, mouseY = 0\n let accDX = 0, accDY = 0, accWX = 0, accWY = 0 // filling during the current frame\n let frameDX = 0, frameDY = 0, frameWX = 0, frameWY = 0 // what inputRead reports (previous frame)\n const onPointerMove = (e: PointerEvent | MouseEvent) => {\n if ((e as PointerEvent).pointerType && (e as PointerEvent).pointerType !== \"mouse\") return\n const r = root.getBoundingClientRect()\n mouseX = e.clientX - r.left; mouseY = e.clientY - r.top\n accDX += e.movementX || 0; accDY += e.movementY || 0\n }\n const onMouseDown = (e: MouseEvent) => {\n const code = MOUSE_BUTTON_CODES[e.button]\n if (!code) return\n held.add(code); emit(0, code)\n }\n const onMouseUp = (e: MouseEvent) => {\n const code = MOUSE_BUTTON_CODES[e.button]\n if (code && held.delete(code)) emit(1, code)\n }\n const onWheel = (e: WheelEvent) => {\n // Notches: deltaMode 0 (pixels) ≈ 100 px per notch on most browsers.\n const k = e.deltaMode === 0 ? 1 / 100 : 1\n accWX += e.deltaX * k; accWY += e.deltaY * k\n }\n const onContextMenu = (e: Event) => { if (document.pointerLockElement === root) e.preventDefault() }\n\n // ---- gamepads ----------------------------------------------------------------------------------\n // The Gamepad API is poll-only: sample on the frame boundary, diff buttons into events.\n const padConnected: boolean[] = []\n const padAxes: number[][] = [] // [lx, ly, rx, ry, lt, rt] per pad\n const padButtons: boolean[][] = []\n const pollGamepads = () => {\n const pads: (Gamepad | null)[] = typeof navigator !== \"undefined\" && navigator.getGamepads ? Array.from(navigator.getGamepads()) : []\n for (let i = 0; i < MAX_PADS; i++) {\n const p = pads[i] ?? null\n const connected = !!p && p.connected\n if (connected !== !!padConnected[i]) {\n padConnected[i] = connected\n if (!connected) { // release everything the pad held\n for (const code of GAMEPAD_BUTTON_CODES) {\n if (held.delete(code + \"@\" + i)) { emit(1, code, i); refreshAnyPad(code) }\n }\n padButtons[i] = []; padAxes[i] = [0, 0, 0, 0, 0, 0]\n }\n emit(connected ? 2 : 3, \"\", i)\n }\n if (!p || !connected) continue\n const a = p.axes, b = p.buttons\n const lt = b[6]?.value ?? 0, rt = b[7]?.value ?? 0\n padAxes[i] = [a[0] ?? 0, a[1] ?? 0, a[2] ?? 0, a[3] ?? 0, lt, rt]\n const prev = padButtons[i] ?? (padButtons[i] = [])\n for (let k = 0; k < GAMEPAD_BUTTON_CODES.length; k++) {\n const btn = b[k]\n const down = !!btn && (btn.pressed || btn.value > TRIGGER_AS_BUTTON)\n if (down === !!prev[k]) continue\n prev[k] = down\n const code = GAMEPAD_BUTTON_CODES[k]\n if (down) held.add(code + \"@\" + i); else held.delete(code + \"@\" + i)\n refreshAnyPad(code)\n emit(down ? 0 : 1, code, i)\n }\n }\n }\n // The unscoped code (\"GamepadSouth\") is held while ANY pad holds it.\n const refreshAnyPad = (code: string) => {\n let any = false\n for (let i = 0; i < MAX_PADS && !any; i++) if (held.has(code + \"@\" + i)) any = true\n if (any) held.add(code); else held.delete(code)\n }\n\n // ---- frame boundary ----------------------------------------------------------------------------\n let raf = 0\n const onFrame = () => {\n frameDX = accDX; frameDY = accDY; frameWX = accWX; frameWY = accWY\n accDX = accDY = accWX = accWY = 0\n pollGamepads()\n raf = requestAnimationFrame(onFrame)\n }\n\n // ---- wiring ------------------------------------------------------------------------------------\n const windows = options.windows.filter((w, i, arr) => w && arr.indexOf(w) === i)\n for (const w of windows) {\n if (options.keyboard !== false) {\n w.addEventListener(\"keydown\", onKeyDown)\n w.addEventListener(\"keyup\", onKeyUp)\n }\n w.addEventListener(\"blur\", onBlur)\n }\n // In the CAPTURE phase: the UI renderer stops an event it took on its way to a view under the\n // picture, and what the mouse did is the app's to read either way.\n root.addEventListener(\"pointermove\", onPointerMove, true)\n root.addEventListener(\"mousedown\", onMouseDown, true)\n // Up on the window: a drag that ends outside the viewport must still release the button.\n window.addEventListener(\"mouseup\", onMouseUp, true)\n root.addEventListener(\"wheel\", onWheel, { passive: true, capture: true })\n root.addEventListener(\"contextmenu\", onContextMenu, true)\n if (typeof requestAnimationFrame === \"function\") raf = requestAnimationFrame(onFrame)\n\n const inputKey = (code: string, gamepad: number) =>\n gamepad >= 0 && code.startsWith(\"Gamepad\") ? held.has(code + \"@\" + gamepad) : held.has(code)\n\n const inputRead = (channel: number): number => {\n switch (channel) {\n case 0: return mouseX\n case 1: return mouseY\n case 2: return frameDX\n case 3: return frameDY\n case 4: return frameWX\n case 5: return frameWY\n case 6: return document.pointerLockElement === root ? 1 : 0\n case 7: { let n = 0; for (let i = 0; i < MAX_PADS; i++) if (padConnected[i]) n++; return n }\n }\n if (channel >= PAD_BASE) {\n const pad = Math.floor((channel - PAD_BASE) / PAD_STRIDE), k = (channel - PAD_BASE) % PAD_STRIDE\n if (pad >= MAX_PADS || !padConnected[pad]) return 0\n if (k === 0) return 1\n return padAxes[pad]?.[k - 1] ?? 0\n }\n return 0\n }\n\n const inputSetPointerLock = (on: boolean): boolean => {\n if (!on) { if (document.pointerLockElement === root) document.exitPointerLock(); return true }\n if (document.pointerLockElement === root) return true\n if (typeof root.requestPointerLock !== \"function\") return false\n try {\n const r: any = root.requestPointerLock({ unadjustedMovement: true } as any)\n if (r && typeof r.catch === \"function\") r.catch(() => { try { root.requestPointerLock() } catch {} })\n return true\n } catch { return false }\n }\n\n const registerInputEvent = (cb: InputEventSink) => { sink = cb }\n\n const dispose = () => {\n for (const w of windows) {\n w.removeEventListener(\"keydown\", onKeyDown)\n w.removeEventListener(\"keyup\", onKeyUp)\n w.removeEventListener(\"blur\", onBlur)\n }\n root.removeEventListener(\"pointermove\", onPointerMove, true)\n root.removeEventListener(\"mousedown\", onMouseDown, true)\n window.removeEventListener(\"mouseup\", onMouseUp, true)\n root.removeEventListener(\"wheel\", onWheel, true)\n root.removeEventListener(\"contextmenu\", onContextMenu, true)\n if (raf) cancelAnimationFrame(raf)\n if (document.pointerLockElement === root) document.exitPointerLock()\n held.clear(); sink = null\n }\n\n return { inputKey, inputRead, inputSetPointerLock, registerInputEvent, dispose }\n}\n","// HostInput: keys, mouse and gamepads (./inputHost.ts), and the height of the on-screen keyboard.\nimport type { WasmHostInput } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport { createInputHost, type InputHostOptions } from \"./inputHost\"\n\nexport type InputTableOptions = InputHostOptions & {\n push: (kind: number, code: string, gamepad: number, repeat: number) => void\n keyboardHeight: () => number\n}\n\nexport const createInputTable = (options: InputTableOptions) => {\n const input = createInputHost(options)\n input.registerInputEvent(options.push)\n const table: WasmHostInput = {\n key: input.inputKey,\n read: input.inputRead,\n setPointerLock: input.inputSetPointerLock,\n keyboardHeight: options.keyboardHeight,\n }\n return { table, dispose: input.dispose }\n}\n","// HostMedia: the video / audio players of web-shared.\nimport type { WasmHostMedia } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport { createAudioPlayer, createVideoPlayer, getMediaPlayerDuration, getMediaPlayerTime, removeMediaPlayer, setMediaPlayerTime, updateMediaPlayerLoop, updateMediaPlayerPlaying, updateMediaPlayerVolume } from \"lecodes-web-shared/src/utils/mediaplayer\"\n\nexport const mediaTable: WasmHostMedia = {\n createVideo: createVideoPlayer,\n createAudio: createAudioPlayer,\n setVolume: updateMediaPlayerVolume,\n setPlaying: updateMediaPlayerPlaying,\n setLoop: updateMediaPlayerLoop,\n time: getMediaPlayerTime,\n setTime: setMediaPlayerTime,\n duration: getMediaPlayerDuration,\n remove: removeMediaPlayer,\n}\n","// The headless services of a web host — the UI-less sibling of a native view. A plugin's web half\n// registers a factory:\n//\n// host.registerService(\"geolocation\", (params, channel) => ({\n// call: (method, args) => {...},\n// close: () => {...},\n// }))\n//\n// One `serviceOpen` = one live session (host-allocated id, websocket-style); `channel.emit`\n// delivers events to the session's SDK-side listeners. There is no placeholder concept —\n// an unregistered name makes serviceOpen return -1 and the SDK wrapper rejects cleanly.\n\nexport type ServiceChannel = { emit(event: string, data?: any): void }\nexport type ServiceHandle = {\n call?(method: string, args: any[]): any | Promise<any>\n close?(): void\n}\nexport type ServiceFactory = (params: any, channel: ServiceChannel) => ServiceHandle\n\nexport const createServiceSystem = () => {\n const factories = new Map<string, ServiceFactory>()\n const versions = new Map<string, number>()\n const sessions = new Map<number, ServiceHandle>()\n let nextSessionId = 1\n\n /** `version` = the contract version the half was generated from (1 for one written by hand). */\n const registerService = (name: string, factory: ServiceFactory, version = 1) => { factories.set(name, factory); versions.set(name, version) }\n /** A service the next bundle does not have (its plugin is not among the app's). */\n const unregisterService = (name: string) => { factories.delete(name); versions.delete(name) }\n const isServiceSupported = (name: string) => factories.has(name)\n const serviceVersion = (name: string) => versions.get(name) ?? 0\n\n /** The `_creatorService.open` bridge. Must stay cheap: factories create the session\n * object only — permission prompts and I/O belong in the first call that needs them. */\n const serviceOpen = (name: string, params: string, onEvent: (event: string, data?: unknown) => void): number => {\n const factory = factories.get(name)\n if (!factory) return -1\n const id = nextSessionId++\n // A payload crosses as the value it is: the app and this host are the same JavaScript.\n const handle = factory(params ? JSON.parse(params) : {}, {\n emit: (event, data) => { if (data === undefined) onEvent(event); else onEvent(event, data) },\n })\n sessions.set(id, handle)\n return id\n }\n\n /** The `_creatorService.call` bridge — values in and out, promise-friendly (same as viewCall).\n * `args` is the app's own array: a half reads, never keeps or changes it. */\n const serviceCall = (serviceId: number, method: string, args: unknown, onComplete: (result?: unknown) => void, onError: (err: string) => void) => {\n const session = sessions.get(serviceId)\n if (!session?.call) {\n onError(`Service call \"${method}\": no live session or no call handler (serviceId ${serviceId})`)\n return\n }\n try {\n Promise.resolve(session.call(method, Array.isArray(args) ? args : [])).then(\n (result) => { if (result === undefined) onComplete(); else onComplete(result) },\n (e) => onError(e instanceof Error ? e.message : String(e)),\n )\n } catch (e) {\n onError(e instanceof Error ? e.message : String(e))\n }\n }\n\n const serviceClose = (serviceId: number) => {\n sessions.get(serviceId)?.close?.()\n sessions.delete(serviceId)\n }\n\n /** Host teardown: release every live session (a GPS watch must actually stop). */\n const destroy = () => {\n for (const s of sessions.values()) s.close?.()\n sessions.clear()\n }\n\n return { registerService, unregisterService, isServiceSupported, serviceVersion, serviceOpen, serviceCall, serviceClose, destroy }\n}\n\nexport type ServiceSystem = ReturnType<typeof createServiceSystem>\n","// HostService: the headless services of the plugins' web halves (a session per `open`).\nimport type { WasmHostService } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport { createServiceSystem } from \"./serviceSystem\"\n\nexport const createServiceTable = () => {\n const services = createServiceSystem()\n const table: WasmHostService = { supported: services.isServiceSupported, version: services.serviceVersion, open: services.serviceOpen, call: services.serviceCall, close: services.serviceClose }\n return { table, registerService: services.registerService, unregisterService: services.unregisterService, dispose: services.destroy }\n}\n","// HostSocket: the websockets of one host — tearing a host down closes its own, no other's.\nimport type { WasmHostSocket } from \"lecodes-web-runtime/src/gen/host.gen\"\n\nexport const createSocketTable = () => {\n const sockets: WebSocket[] = []\n const table: WasmHostSocket = {\n open(url, onMessage) {\n const socket = new WebSocket(url)\n socket.addEventListener(\"open\", () => onMessage(\"open\"))\n socket.addEventListener(\"message\", (ev) => onMessage(\"message\", ev.data as string))\n socket.addEventListener(\"close\", (ev) => onMessage(\"close\", ev.code))\n socket.addEventListener(\"error\", () => onMessage(\"error\"))\n sockets.push(socket)\n return sockets.length - 1\n },\n send(id, data) { sockets[id]?.send(data) },\n close(id) { sockets[id]?.close() },\n }\n return {\n table,\n dispose() {\n for (const socket of sockets) if (socket.readyState === WebSocket.OPEN) socket.close()\n sockets.length = 0\n },\n }\n}\n","// HostStorage: one JSON blob per storage name, in localStorage under the project's key — what an app\n// saved is there the next time it is opened, and two projects served from one origin (a dev server,\n// a page of demos) do not read each other's.\nimport type { WasmHostStorage } from \"lecodes-web-runtime/src/gen/host.gen\"\n\nexport const createStorageTable = (project: string): WasmHostStorage => {\n const key = (name: string) => `lecodes:${project}:${name}`\n return {\n load(name) { try { return window.localStorage.getItem(key(name)) } catch { return null } },\n save(name, json) { try { window.localStorage.setItem(key(name), json) } catch { /* quota / private mode */ } },\n }\n}\n","// A world: the global object a bundle runs against. The runtime installs its bridges on it\n// (non-enumerable: getOwnPropertyNames), and the bundle's globals reach the bundle as the\n// PARAMETERS of a Function. Not a sandbox — the page's `window` and `document` are in reach of the\n// bundle; an embedder that runs code it does not trust puts the page on another origin.\n// No sourceURL: the source map applies to `<anonymous>` frames (./errors.ts).\nimport type { JsbWorld } from \"lecodes-web-runtime/src/jsb\"\n\nexport const makeWorld = (): JsbWorld => {\n const global: Record<string, unknown> = {}\n const evaluate = (code: string) => {\n const names = Object.getOwnPropertyNames(global)\n return new Function(...names, code)(...names.map((name) => global[name]))\n }\n return { global, evaluate }\n}\n","// The web host: a compiled bundle in the browser on the RUNTIME MODULE — runtime/native compiled to\n// wasm (runtime/web: `full` = Filament + 2d + ui + nav, `2d`, `ui`), over the page's own JS engine.\n// The runtime owns the UI tree, the timers / loops / tweens, the worlds and every bridge object\n// (`_creator`, `_creatorTree`, `_creatorFetch`, …); the host is what it calls a page for — and this\n// file only puts the parts together, each of which is a file of its own:\n//\n// page.ts the container, its size in device px, the canvases\n// engines/ the 3D and the 2D surface (HostGL, HostScene2d)\n// tables/ fetch, storage, device, app, socket, service, input, media — a file per table\n// the renderer lecodes-web-canvas: the TreeUI (HostUI) painted on a canvas over the scenes\n// plugins.ts the doors of the plugins' web halves\n// errors.ts what a bundle threw, mapped to its source\n//\n// The host FILLS the container it is given and knows nothing around it: no device, no frame, no\n// zoom, no url, no message. `createHost(root, options)` brings it up once; `host.run(code)`\n// evaluates a bundle, repeatably.\n/// <reference path=\"./contract.d.ts\" />\n\nimport { loadProfileModule } from \"lecodes-web-runtime/src/profile\"\nimport type { WasmHostTables } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport { installJsb } from \"lecodes-web-runtime/src/jsb\"\nimport { installWasmCrashSymbolizer } from \"lecodes-web-runtime/src/wasmCrashSymbolizer\"\nimport { createCanvasRenderer, type CanvasRenderer } from \"lecodes-web-canvas/src/web/renderer\"\nimport { createCanvasHost } from \"lecodes-web-shared/src/canvas/createCanvasHost\"\nimport { removePlayers } from \"lecodes-web-shared/src/utils/mediaplayer\"\nimport { ensureFontsLoaded, loadBootFonts } from \"lecodes-web-shared/src/utils/fonts\"\nimport { viewScale } from \"lecodes-web-shared/src/ui/viewScale\"\nimport { SDK_VERSION, bundleRunsOn } from \"lecodes-sdk/version\"\nimport { TREE_DEST_SCENE2D, TREE_DEST_SCENE3D } from \"lecodes-sdk/ui/tree\"\nimport { createGLSurface } from \"./engines/gl\"\nimport { createScene2dSurface } from \"./engines/scene2d\"\nimport { createErrorReporter, type PreviewError } from \"./errors\"\nimport { parseBundleHeader, profileOf, type BundleHeader, type HostProfile } from \"./header\"\nimport { createPage, type PageSize } from \"./page\"\nimport { createPlugins, type PluginHalf } from \"./plugins\"\nimport { createSafeArea, type SafeArea } from \"./safeArea\"\nimport { loadSystemBuffers, type SystemBuffers } from \"./system\"\nimport { createAppTable } from \"./tables/app\"\nimport { createDeviceTable } from \"./tables/device\"\nimport { createFetchTable } from \"./tables/fetch\"\nimport { createInputTable } from \"./tables/input\"\nimport { mediaTable } from \"./tables/media\"\nimport { createServiceTable } from \"./tables/service\"\nimport { createSocketTable } from \"./tables/socket\"\nimport { createStorageTable } from \"./tables/storage\"\nimport { makeWorld } from \"./world\"\n\nexport type HostOptions = {\n /** The header of the bundle the host is for (`parseBundleHeader`): its engines decide the profile,\n * its materials the archives, its fonts the boot faces. */\n header?: BundleHeader\n /** The runtime profile, in place of the header's (a host with no bundle yet: an editor). */\n profile?: HostProfile\n /** false = an engine-only host: no UI renderer, no fonts. Default true. */\n ui?: boolean\n /** The project, as the key its storage is kept under. Default: the header's name. */\n project?: string\n /** Insets the embedder took of the container; absent = the page's own (`env(safe-area-inset-*)`). */\n safeArea?: SafeArea\n /** device.language. Default: the browser's. */\n language?: () => string\n /** The url the app was opened with (app.launchUrl). A warm link goes through `host.emitAppEvent(\"url\", url)`. */\n launchUrl?: string\n /** app.setOrientation sink; absent = a best-effort screen.orientation.lock on the page. */\n onOrientation?: (mode: \"landscape\" | \"portrait\" | \"auto\") => void\n /** Listen for keyboard keys (Input.key). Default true. */\n keyboard?: boolean\n /** Windows to listen on for keys besides the host's own (an embedder that keeps the focus). */\n keyboardTargets?: Window[]\n}\n\nexport type RunOptions = {\n /** Called when this bundle throws, with the error mapped back to its source. */\n onError?: (error: PreviewError) => void\n /** The bundle's header, in place of the one read from its first lines (a bundle compiled with\n * none: its SDK version and its plugins are what is said here). */\n header?: Pick<BundleHeader, \"sdk\" | \"plugins\">\n}\n\nexport type Run = {\n /** Stop attributing errors to this run. What the bundle created is the world's: it goes with the\n * host, or when the app swaps worlds. */\n dispose(): void\n}\n\n/** An engine-only host still owes the runtime its HostUI table: nothing is rendered but the\n * destination change (the scene canvases). */\nconst nullHostUI = (onDestination: (kind: number, id: number) => void, onDropped: (kind: number, id: number) => void): WasmHostTables[\"ui\"] => ({\n nodeFactory() {}, setPropertyString() {}, setPropertyInt() {}, setFlags() {}, insertNode() {}, removeNode() {}, releaseNode() {},\n openView(kind, _node, id) { onDestination(kind, id) }, dropView(kind, _node, id) { onDropped(kind, id) }, closeView() { onDestination(-1, 0) }, widgetOpen() {}, widgetClose() {},\n registerFont(_url, _family, _weight, _style, onComplete) { onComplete() },\n showToast() {}, getButtonPressed: () => false, getTextValue: () => \"\", vlistScroll() {},\n})\n\nexport type Host = Awaited<ReturnType<typeof createHost>>\n\nexport const createHost = async (root: HTMLElement, options: HostOptions = {}) => {\n const header = options.header\n const profile = options.profile ?? (header ? profileOf(header) : \"full\")\n const preloads = header?.preloads ?? new Set<string>()\n const withUI = options.ui !== false\n const has3d = profile === \"full\"\n const has2d = profile === \"2d\" || (profile === \"full\" && !!header?.is2d)\n\n const page = createPage(root)\n const { doc, win } = page\n\n // The measurement font + the app's boot faces load beside the module; awaited before the host\n // returns, so the first layout measures text against the real font.\n const fonts = withUI ? Promise.all([ensureFontsLoaded(undefined, doc), loadBootFonts(header?.bootFonts ?? [], doc)]) : null\n\n // Bottom to top: the 3D scene, the 2D scene, the UI.\n const gl = has3d ? createGLSurface(page, preloads.has(\"capture\")) : null\n const scene2d = has2d ? createScene2dSurface(page) : null\n const uiCanvas = withUI ? page.newCanvas() : null\n\n const errors = createErrorReporter(win, has3d)\n if (has3d) installWasmCrashSymbolizer()\n\n const [M, system] = await Promise.all([\n loadProfileModule(profile, {\n glContext: gl?.context, glOptions: gl?.options,\n gl2dContext: scene2d?.context, gl2dOptions: scene2d?.options,\n moduleArgs: {\n // what a bundle threw is reported once, mapped to its source (errors.ts): its raw lines are\n // for whoever reads the browser's console at its most verbose\n print: (line: string) => { if (errors.runtimeLine(line)) console.debug(line); else console.log(line) },\n printErr: (line: string) => { console.error(line) },\n },\n }),\n has3d ? loadSystemBuffers(preloads) : Promise.resolve<SystemBuffers>({}),\n ])\n const withStr = <T>(s: string, fn: (ptr: number) => T): T => {\n const p = M.stringToNewUTF8(s)\n try { return fn(p) } finally { M._free(p) }\n }\n\n // ---- a destination change: a scene presents on its canvas ---------------------------------------\n // The canvas of the destination that LEFT goes when the runtime drops it (HostUI.dropView), not\n // when the next one opens: a screen may still be coming in over it — a surface never moves, it\n // stands under the screen until the transition lands. Unless a destination of the same kind is on\n // screen by then: the canvas is that one's.\n let destination = -1\n const onDestination = (kind: number) => {\n destination = kind\n if (kind === TREE_DEST_SCENE3D) gl?.show()\n if (kind === TREE_DEST_SCENE2D) scene2d?.show()\n }\n const onDropped = (kind: number) => {\n if (kind === destination) return\n if (kind === TREE_DEST_SCENE3D) gl?.hide()\n if (kind === TREE_DEST_SCENE2D) scene2d?.hide()\n }\n\n // ---- the tables ---------------------------------------------------------------------------------\n const canvasHost = createCanvasHost() // the painter behind `_creatorCanvas`; the runtime's core makes the draw lists\n // What the window loses to the on-screen keyboard (a phone; a desktop loses nothing).\n const keyboardHeight = () => {\n const viewport = win.visualViewport\n return viewport ? Math.max(0, Math.round((win.innerHeight - viewport.height - viewport.offsetTop) / viewScale(root))) : 0\n }\n const renderer: CanvasRenderer | null = uiCanvas ? createCanvasRenderer(root, { M, canvas: uiCanvas, canvasHost, keyboardHeight }) : null\n if (renderer) {\n renderer.ui.onDestination = onDestination\n renderer.ui.onDropped = onDropped\n }\n const app = createAppTable({\n onOrientation: options.onOrientation,\n push: (event, data) => {\n // A \"url\" event sets the pull value first, so app.launchUrl agrees with the event.\n if (event === \"url\" && data !== undefined) withStr(data, (p) => M._creatorWebSetLaunchUrl(p))\n withStr(event, (e) => { if (data === undefined) M._creatorWebAppEvent(e, 0); else withStr(data, (d) => M._creatorWebAppEvent(e, d)) })\n },\n })\n const socket = createSocketTable()\n const service = createServiceTable()\n const input = createInputTable({\n windows: [...new Set([win as Window, ...(options.keyboardTargets ?? [])])],\n root, keyboard: options.keyboard !== false,\n push: (kind, code, gamepad, repeat) => withStr(code, (c) => M._creatorWebInputEvent(kind, c, gamepad, repeat)),\n keyboardHeight: () => renderer?.ui.keyboardHeight() ?? 0,\n })\n const tables: WasmHostTables = {\n ui: renderer?.ui ?? nullHostUI(onDestination, onDropped),\n app: app.table,\n device: createDeviceTable(options.language ?? (() => (win.navigator.language || \"en\").slice(0, 2))),\n fetch: createFetchTable(system),\n storage: createStorageTable(options.project ?? header?.name ?? \"app\"),\n socket: socket.table, service: service.table, input: input.table, media: mediaTable, canvas: canvasHost.table,\n ...(gl ? { gl: gl.table(M) } : {}),\n ...(scene2d ? { scene2d: scene2d.table(M) } : {}),\n }\n const world = makeWorld()\n const globals = world.global as Record<string, unknown>\n installJsb(M, { host: tables as unknown as Record<string, unknown>, world, newWorld: makeWorld })\n\n const plugins = createPlugins({\n // a native view is the renderer's to mount: an engine-only host has none\n ...(renderer ? { registerView: (name, factory, version) => renderer.ui.registerView(name, factory, version), unregisterView: (name) => renderer.ui.unregisterView(name) } : {}),\n registerService: service.registerService, unregisterService: service.unregisterService,\n })\n\n M._creatorWebInit()\n if (options.launchUrl) withStr(options.launchUrl, (p) => M._creatorWebSetLaunchUrl(p))\n renderer?.ui.install()\n // The engine up front (the desktop host's initial.js does the same): every `_creator` call needs\n // it. A `// gl: defer` bundle calls createEngine() itself.\n if (has3d && header?.gl !== \"defer\") (globals._creator as typeof _creator | undefined)?.createEngine()\n\n // ---- the size -----------------------------------------------------------------------------------\n const safeArea = createSafeArea(root)\n if (options.safeArea) safeArea.set(options.safeArea)\n const resize = (size: PageSize) => {\n gl?.resize()\n scene2d?.resize()\n if (renderer) {\n renderer.resize(size.width, size.height, size.factor)\n renderer.setSafeArea(safeArea.current()) // after: it re-flows against the new size\n } else M._creatorWebResize(size.width, size.height)\n }\n page.onResize(resize)\n resize(page.size())\n\n // ---- the frame ----------------------------------------------------------------------------------\n let raf = 0\n const frame = (now: number) => {\n raf = win.requestAnimationFrame(frame)\n gl?.frame()\n M._creatorWebTick(now) // timers, loops, tweens, the dispatch queue, the 3D frame\n scene2d?.frame(now)\n if (renderer) { renderer.ui.layoutFrame(); renderer.ui.tickHover(); renderer.render() }\n }\n raf = win.requestAnimationFrame(frame)\n\n await fonts\n\n let destroyed = false\n return {\n profile,\n /** The runtime module (an embedder that reads the engine directly: an editor). */\n M,\n /** The runtime's world: the bundle's globals (`_creator`, `_creatorTree`, `_creatorApp`, …). */\n world: globals,\n /** The UI as the renderer holds it (the render tree, the pointer routing); null on an engine-only host. */\n ui: renderer?.ui ?? null,\n /** Evaluate a bundle. Throws when the bundle is of another SDK major than this host. */\n run(code: string, runOptions: RunOptions = {}): Run {\n const bundle = runOptions.header ?? parseBundleHeader(code)\n if (!bundleRunsOn(bundle.sdk, SDK_VERSION)) {\n throw new Error(`This app was built with LeCodes SDK ${bundle.sdk ?? \"older than 2.0\"}; this host runs SDK ${SDK_VERSION}. It needs a new build.`)\n }\n const run = errors.track(code, runOptions.onError)\n // BEFORE the bundle runs: `isSupported` is a synchronous truth.\n plugins.allow(bundle.plugins)\n withStr(code, (p) => M._creatorWebRun(p)) // a throw is logged by the runtime (`[ERROR] run …`) → errors.runtimeLine\n return { dispose: run.drop }\n },\n /** A plugin's web half, by the id an app lists it under. Registered once; a bundle gets the ones\n * its header names. */\n registerPlugin: (id: string, half: PluginHalf) => plugins.register(id, half),\n hasPlugin: plugins.has,\n /** Where a stack of the running bundle leads in its source (an inspector's creation sites). */\n locate: errors.locate,\n /** The insets the app is told now: the embedder's, or the page's own. */\n safeArea: () => safeArea.current(),\n /** The embedder's insets (it drew over the container), or null for the page's own. */\n setSafeArea(area: SafeArea | null) {\n safeArea.set(area)\n renderer?.setSafeArea(safeArea.current())\n },\n /** A warm link (\"url\") or a synthetic lifecycle event (\"pause\", \"resume\"). */\n emitAppEvent: app.emit,\n destroy() {\n if (destroyed) return\n destroyed = true\n win.cancelAnimationFrame(raf)\n errors.dispose()\n renderer?.destroy()\n input.dispose(); socket.dispose(); service.dispose(); app.dispose()\n removePlayers()\n safeArea.destroy()\n gl?.destroy()\n scene2d?.destroy()\n page.destroy()\n },\n }\n}\n","// lecodes-web-host: a compiled LeCodes bundle in the browser, in the container it is given.\n//\n// const host = await mount(root, code) // the header's profile, the bundle run\n// host.destroy()\n//\n// const host = await createHost(root, { header: parseBundleHeader(code) })\n// host.run(code, { onError }) // repeatably\n//\n// The page around the container is the embedder's — lecodes-web-player is the one this repo ships.\nimport { createHost, type HostOptions, type RunOptions } from \"./host\"\nimport { parseBundleHeader } from \"./header\"\n\nexport { createHost } from \"./host\"\nexport type { Host, HostOptions, Run, RunOptions } from \"./host\"\nexport { parseBundleHeader, profileOf } from \"./header\"\nexport type { BundleHeader, HostProfile } from \"./header\"\nexport type { HalfHost, PluginHalf } from \"./plugins\"\nexport type { SafeArea } from \"./safeArea\"\nexport type { MappedFrame, PreviewError } from \"./errors\"\n\n/** A host for this bundle, and the bundle run on it. */\nexport const mount = async (root: HTMLElement, code: string, options: Omit<HostOptions, \"header\" | \"profile\"> & RunOptions = {}) => {\n const host = await createHost(root, { ...options, header: parseBundleHeader(code) })\n try {\n host.run(code, { onError: options.onError })\n } catch (e) {\n host.destroy()\n throw e\n }\n return host\n}\n","// The entry of the PUBLISHED package (dist/index.js): the host, typed by its public contract\n// (./api.ts) and by nothing else. Here the implementation is held to the contract — an assignment\n// that stops compiling is a contract that was broken.\n//\n// Inside this repo a package is a folder: the player takes the host from ./index.ts, with the\n// types the sources have.\nimport * as host from \"./index\"\nimport type { CreateHost, Mount, ParseBundleHeader, ProfileOf } from \"./api\"\n\nexport type * from \"./api\"\n\nexport const createHost: CreateHost = host.createHost\nexport const mount: Mount = host.mount\nexport const parseBundleHeader: ParseBundleHeader = host.parseBundleHeader\nexport const profileOf: ProfileOf = host.profileOf\n"],"file":"index.js"}
1
+ {"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,MAAM,YAA2G;AAAA,EAC/G,MAAM,0BAAM,OAAO,mCAAgC;AAAA,EACnD,MAAM,0BAAM,OAAO,iCAA8B;AAAA,EACjD,IAAI,0BAAM,OAAO,iCAA8B;AACjD;AAGA,MAAM,UAAyC;AAAA,EAC7C,MAAM,MAAM,kGAA6D;AAAA,EACzE,MAAM,MAAM,gGAA2D;AAAA,EACvE,IAAI,MAAM,gGAA2D;AACvE;AAIO,MAAM,oBAAoB,OAAO,SAAkB,UAA0B,OAA4B;AAC9G,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nBO,MAAM,aAAyBM;AAC/B,MAAM,QAAeC;AACrB,MAAM,oBAAuCC;AAC7C,MAAM,YAAuBC","names":["map","hex","w","h","scale","rx","ry","apply","seen","PaintKind","join","paint","g","players","onError","parseBundleHeader","preload","profileOf","factories","createHost","mount","host.createHost","host.mount","host.parseBundleHeader","host.profileOf"],"ignoreList":[],"sources":["../../../runtime/web/src/profile.ts","../../../runtime/web/src/jsb.ts","../../../runtime/web/native/dist/creator-full.js.symbols?url","../../../runtime/web/src/wasmCrashSymbolizer.ts","../../../renderers/web-shared/src/utils/fetch.ts","../../../renderers/web-shared/src/ui/viewScale.ts","../../../renderers/web-canvas/src/core/util/svgSrc.ts","../../../renderers/web-canvas/src/host/Host.ts","../../../renderers/web-canvas/src/host/BrowserHost.ts","../../../renderers/web-canvas/src/core/util/colors.ts","../../../renderers/web-canvas/src/core/util/geometry.ts","../../../renderers/web-canvas/src/paint/Canvas2DPainter.ts","../../../renderers/web-shared/src/utils/mediaplayer.ts","../../../sdk/src/ui/tree.ts","../../../renderers/web-canvas/src/core/hitTest.ts","../../../renderers/web-canvas/src/layout/CuiPaint.gen.ts","../../../renderers/web-canvas/src/layout/creatorUi/readGradient.ts","../../../renderers/web-canvas/src/layout/creatorUi/paint-read.ts","../../../renderers/web-canvas/src/core/text.ts","../../../renderers/web-canvas/src/paint/paintTree.ts","../../../renderers/web-canvas/src/serialize/serializeRenderTree.ts","../../../renderers/web-canvas/src/runtime/TreeUI.ts","../../../renderers/web-canvas/src/web/BrowserUI.ts","../../../renderers/web-canvas/src/web/chrome.ts","../../../renderers/web-canvas/src/web/renderer.ts","../../../renderers/web-shared/src/canvas/gen/spec.ts","../../../renderers/web-shared/src/canvas/gen/drawlist.ts","../../../renderers/web-shared/src/canvas/gen/painter.ts","../../../renderers/web-shared/src/canvas/createCanvasHost.ts","../../../renderers/web-shared/src/assets/Roboto-Variable.woff2?url","../../../renderers/web-shared/src/utils/fonts.ts","../../../sdk/src/version.ts","../src/engines/gl.ts","../src/engines/scene2d.ts","../../../renderers/web-shared/src/sourcemapError.ts","../src/errors.ts","../src/header.ts","../src/page.ts","../src/plugins.ts","../src/safeArea.ts","../../../runtime/web/src/gen/materialGroups.gen.ts","../src/materials.ts","../../../runtime/web/src/assets/materials.bin?url","../../../runtime/web/src/assets/materials-world.bin?url","../../../runtime/web/src/assets/neutral_ibl128.ktx?url","../../../runtime/web/src/assets/uberarchive.bin?url","../src/system.ts","../src/tables/app.ts","../src/tables/openFilePicker.ts","../src/tables/device.ts","../src/tables/fetch.ts","../src/tables/inputHost.ts","../src/tables/input.ts","../src/tables/media.ts","../src/tables/serviceSystem.ts","../src/tables/service.ts","../src/tables/socket.ts","../src/tables/storage.ts","../src/world.ts","../src/host.ts","../src/index.ts","../src/package.ts"],"sourcesContent":["/// <reference path=\"./native.d.ts\" />\n// The BROWSER profiles of runtime/web/native/CMakeLists.txt: one Emscripten module per engine set, one\n// heap for every engine in it. A web host loads the profile its bundle needs — the imports below are\n// static strings so a bundler splits each profile into its own chunk and a page that never opens a\n// 3D scene never downloads Filament.\nimport type { WasmModule } from \"./gen/wasm\"\n\n// The other two are not a page's: `headless` is Bun's (runtime/headless loads it itself), `nav` an\n// engine-only twin — named here, a bundler would put both into every browser build.\nexport type Profile = \"full\" | \"2d\" | \"ui\"\n\nexport type ProfileOptions = {\n /** creator-gl's WebGL2 context + the attributes it was created with (init() registers it). */\n glContext?: WebGL2RenderingContext\n glOptions?: WebGLContextAttributes\n /** creator-2d's own WebGL2 context (c2dInit registers it) — a second canvas in dual mode. */\n gl2dContext?: WebGL2RenderingContext\n gl2dOptions?: WebGLContextAttributes\n /** Extra Emscripten module arguments (print, printErr, …). */\n moduleArgs?: Record<string, unknown>\n}\n\nconst factories: Record<Profile, () => Promise<{ default: (args?: Record<string, unknown>) => Promise<any> }>> = {\n full: () => import(\"../native/dist/creator-full.js\"),\n \"2d\": () => import(\"../native/dist/creator-2d.js\"),\n ui: () => import(\"../native/dist/creator-ui.js\"),\n}\n\n// the .wasm beside each module\nconst wasmUrl: Record<Profile, () => string> = {\n full: () => new URL(\"../native/dist/creator-full.wasm\", import.meta.url).href,\n \"2d\": () => new URL(\"../native/dist/creator-2d.wasm\", import.meta.url).href,\n ui: () => new URL(\"../native/dist/creator-ui.wasm\", import.meta.url).href,\n}\n\n/** Instantiate a profile module. The engines' WebGL contexts ride in as module fields (the engines\n * read `Module.filament_glContext` / `Module.creator2d_glContext` when they init). */\nexport const loadProfileModule = async (profile: Profile, options: ProfileOptions = {}): Promise<WasmModule> => {\n const factory = (await factories[profile]()).default\n const url = wasmUrl[profile]()\n const args: Record<string, unknown> = {\n locateFile: (file: string) => (file.endsWith(\".wasm\") ? url : file),\n ...(options.glContext ? { filament_glContext: options.glContext, filament_glOptions: options.glOptions ?? {} } : {}),\n ...(options.gl2dContext ? { creator2d_glContext: options.gl2dContext, creator2d_glOptions: options.gl2dOptions ?? {} } : {}),\n ...options.moduleArgs,\n }\n const module = (await factory(args)) as WasmModule\n if (typeof module._creatorWebVersion !== \"function\") throw new Error(`creator-web: ${profile} is not a creator-web profile module`)\n return module\n}\n","// The JS side of runtime/native's wasm arm (runtime/native/src/js/wasm.cpp): the handle table its\n// `jsb::Value`s index, the imports the arm calls (property access, calls, strings, typed arrays,\n// throws), the wrappers that turn an installed handler table into JS functions, and the\n// FinalizationRegistry behind a class finalizer (the owned `Handle`). One instance per module,\n// installed as `Module.jsb` before `creatorWebInit`. Engine-agnostic: a browser or Bun.\n//\n// Values: a number is its IEEE bits (a NaN written canonical — the engine may canonicalize NaNs,\n// so a tagged word never travels as a JS number); anything else is a NaN with the sign bit set, a\n// TAG in bits 16–19 of the high word and the payload in the low word (wasm-support.h). Handles are\n// refcounted: the arm's `dup` / `free` are `dup` / `release` here; objects and functions are deduped\n// through a WeakMap so the arm's `same` holds; at zero references the slot is dropped and the value\n// is the engine's to collect.\nimport type { WasmModule } from \"./gen/wasm\"\n\nconst TAG_UNDEFINED = 1, TAG_NULL = 2, TAG_BOOL = 3, TAG_OBJECT = 4, TAG_FUNCTION = 5, TAG_STRING = 6, TAG_ARRAY = 7, TAG_OTHER = 8, TAG_EXCEPTION = 15\nconst HI_BASE = 0xFFF00000\nconst hiOf = (tag: number) => (HI_BASE | (tag << 16)) >>> 0\nconst HI_UNDEFINED = hiOf(TAG_UNDEFINED), HI_NULL = hiOf(TAG_NULL), HI_BOOL = hiOf(TAG_BOOL), HI_EXCEPTION = hiOf(TAG_EXCEPTION)\nconst tagOf = (hi: number) => ((hi & 0xFFF00000) >>> 0) === HI_BASE ? (hi >>> 16) & 0xF : 0\n\n/** A world the arm evaluates in: its global object (the bridges are installed on it) + evaluator. */\nexport type JsbWorld = {\n global: object\n evaluate(code: string, filename: string): unknown\n}\n\nexport type JsbOptions = {\n /** The boot world (context 1). */\n world: JsbWorld\n /** A fresh world for `_creatorApp.run` (a vm context headless); absent = the boot world is reused. */\n newWorld?: () => JsbWorld\n /** The host tables the generated forwarders call (`Module.jsb.host.<table>.<slot>`). */\n host: Record<string, unknown>\n}\n\nconst ARG_STACK_BYTES = 64 * 1024\n\n/** A settle group: the heap callbacks of one host slot call, released together after the first settle. */\ntype Group = { ptrs: number[], done: boolean }\n\nexport class Jsb {\n readonly M: WasmModule\n readonly host: Record<string, unknown>\n private out = 0\n // the table: index → value (0 unused); refs[i] = references the arm holds; free = released slots\n private table: unknown[] = [undefined]\n private refs: number[] = [0]\n private freeSlots: number[] = []\n private objIndex = new WeakMap<object, number>()\n private pending: unknown = undefined\n private hasPending = false\n private worlds = new Map<number, JsbWorld>()\n private nextWorld = 2\n private readonly newWorld?: () => JsbWorld\n // the argument stack the wrappers write call arguments into (nested calls bump it)\n private argBase = 0\n private argSp = 0\n private readonly scratch = new DataView(new ArrayBuffer(8))\n private readonly classRegistry: FinalizationRegistry<{ ref: WeakRef<object>, cls: number, opaque: number }>\n // Every live class instance as a WeakRef: `gc()` sweeps them so a finalizer lands SYNCHRONOUSLY\n // inside the arm's runGC (QuickJS semantics: `ownedStats` = collect + drain + count), instead of\n // on the FinalizationRegistry's later task — which still covers the objects a natural collection takes.\n private readonly tracked = new Map<object, { ref: WeakRef<object>, cls: number, opaque: number }>()\n private readonly fnRegistry: FinalizationRegistry<number>\n private readonly opaques = new WeakMap<object, { cls: number, opaque: number }>()\n\n constructor(M: WasmModule, options: JsbOptions) {\n this.M = M\n this.host = options.host\n this.worlds.set(1, options.world)\n this.newWorld = options.newWorld\n this.argBase = M._malloc(ARG_STACK_BYTES)\n this.argSp = this.argBase\n this.classRegistry = new FinalizationRegistry((token) => {\n if (!this.tracked.delete(token)) return // swept already by gc()\n this.M._jsbFinalize(token.cls, token.opaque)\n })\n this.fnRegistry = new FinalizationRegistry((k) => { this.M._jsbFunctionGone(k) })\n }\n\n // ---- the arm's hooks --------------------------------------------------------------------------\n _init(out: number) { this.out = out }\n\n // ---- encoding ---------------------------------------------------------------------------------\n /** Encode `v` at heap address `p` (8 bytes). A handle takes ONE reference (the caller owns it);\n * the result is that handle's index, 0 for an immediate (a boolean's payload is NOT an index —\n * returning it once released slot 1 under an unrelated function). */\n private write(p: number, v: unknown): number {\n const M = this.M\n if (typeof v === \"number\") {\n M.HEAPF64[p >> 3] = v !== v ? NaN : v // the engine writes a canonical NaN for NaN\n return 0\n }\n let lo = 0, hi: number, idx = 0\n if (v === undefined) hi = HI_UNDEFINED\n else if (v === null) hi = HI_NULL\n else if (typeof v === \"boolean\") { hi = HI_BOOL; lo = v ? 1 : 0 }\n else {\n lo = idx = this.alloc(v)\n hi = hiOf(typeof v === \"function\" ? TAG_FUNCTION : typeof v === \"string\" ? TAG_STRING : Array.isArray(v) ? TAG_ARRAY : typeof v === \"object\" ? TAG_OBJECT : TAG_OTHER)\n }\n M.HEAPU32[p >> 2] = lo\n M.HEAPU32[(p >> 2) + 1] = hi\n return idx\n }\n private writeOut(v: unknown) { this.write(this.out, v) }\n private writeOutException() { const M = this.M; M.HEAPU32[this.out >> 2] = 0; M.HEAPU32[(this.out >> 2) + 1] = HI_EXCEPTION }\n /** Decode a (lo, hi) word pair; a handle's value is BORROWED (the reference stays). */\n private decode(lo: number, hi: number): unknown {\n const tag = tagOf(hi)\n switch (tag) {\n case 0: { this.scratch.setUint32(0, lo, true); this.scratch.setUint32(4, hi, true); return this.scratch.getFloat64(0, true) }\n case TAG_UNDEFINED: case TAG_EXCEPTION: return undefined\n case TAG_NULL: return null\n case TAG_BOOL: return lo !== 0\n default: return this.table[lo]\n }\n }\n private readAt(p: number): unknown {\n const M = this.M\n return this.decode(M.HEAPU32[p >> 2], M.HEAPU32[(p >> 2) + 1])\n }\n /** A `value` parameter of a host slot (the generated forwarders): the JS value whose word is at\n * `p` — the app's own value, not a copy; undefined for a null address. */\n valueAt(p: number): unknown { return p ? this.readAt(p) : undefined }\n /** Read the result slot and TAKE the reference the arm handed over (an OWNED result). */\n private takeOut(): { value: unknown, threw: boolean } {\n const M = this.M\n const lo = M.HEAPU32[this.out >> 2], hi = M.HEAPU32[(this.out >> 2) + 1]\n const tag = tagOf(hi)\n if (tag === TAG_EXCEPTION) return { value: undefined, threw: true }\n const value = this.decode(lo, hi)\n if (tag >= TAG_OBJECT && tag <= TAG_OTHER) this.release(lo)\n return { value, threw: false }\n }\n private args(argc: number, argv: number): unknown[] {\n const out: unknown[] = new Array(argc)\n for (let i = 0; i < argc; i++) out[i] = this.readAt(argv + i * 8)\n return out\n }\n\n // ---- the table ----------------------------------------------------------------------------------\n private alloc(v: unknown): number {\n const isObj = typeof v === \"object\" || typeof v === \"function\"\n if (isObj) {\n const hit = this.objIndex.get(v as object)\n if (hit !== undefined) { this.refs[hit]++; return hit }\n }\n let i: number\n if (this.freeSlots.length > 0) { i = this.freeSlots.pop()!; this.table[i] = v; this.refs[i] = 1 }\n else { i = this.table.length; this.table.push(v); this.refs.push(1) }\n if (isObj) this.objIndex.set(v as object, i)\n return i\n }\n dup(idx: number) { if (idx > 0) this.refs[idx]++ }\n release(idx: number) {\n if (idx <= 0) return\n if (this.refs[idx] <= 0) { console.warn(`[jsb] release of a dead handle ${idx} (${typeof this.table[idx]})`, new Error().stack?.split(\"\\n\").slice(2, 6).join(\"\\n\")); return }\n if (--this.refs[idx] > 0) return\n const v = this.table[idx]\n if (typeof v === \"object\" || typeof v === \"function\") this.objIndex.delete(v as object)\n this.table[idx] = undefined\n this.freeSlots.push(idx)\n }\n /** Live handles (for tests). */\n liveHandles(): number { return this.table.length - 1 - this.freeSlots.length }\n\n // ---- worlds -------------------------------------------------------------------------------------\n global(ctx: number) { this.writeOut(this.worlds.get(ctx)?.global ?? this.worlds.get(1)!.global) }\n newContext(): number {\n if (!this.newWorld) return 1\n const id = this.nextWorld++\n this.worlds.set(id, this.newWorld())\n return id\n }\n freeContext(ctx: number) { if (ctx !== 1) this.worlds.delete(ctx) }\n eval(ctx: number, code: string, filename: string) {\n const w = this.worlds.get(ctx) ?? this.worlds.get(1)!\n try { this.writeOut(w.evaluate(code, filename)) }\n catch (e) { this.pending = e; this.hasPending = true; this.writeOutException() }\n }\n\n // ---- objects ----------------------------------------------------------------------------------\n get(lo: number, hi: number, key: string) {\n const o = this.decode(lo, hi) as any\n if (o === undefined || o === null) { this.writeOut(undefined); return }\n try { this.writeOut(o[key]) }\n catch (e) { this.pending = e; this.hasPending = true; this.writeOutException() }\n }\n getIndex(lo: number, hi: number, i: number) {\n const o = this.decode(lo, hi) as any\n if (o === undefined || o === null) { this.writeOut(undefined); return }\n try { this.writeOut(o[i]) }\n catch (e) { this.pending = e; this.hasPending = true; this.writeOutException() }\n }\n has(lo: number, hi: number, key: string): boolean {\n const o = this.decode(lo, hi)\n return (typeof o === \"object\" || typeof o === \"function\") && o !== null && key in (o as object)\n }\n set(obj: number, key: string, lo: number, hi: number) {\n const o = this.table[obj] as any\n if (o === undefined || o === null) return\n o[key] = this.decode(lo, hi)\n }\n setIndex(obj: number, i: number, lo: number, hi: number) {\n const o = this.table[obj] as any\n if (o === undefined || o === null) return\n o[i] = this.decode(lo, hi)\n }\n keys(lo: number, hi: number, countOut: number): number {\n const M = this.M\n const o = this.decode(lo, hi)\n const ks = (typeof o === \"object\" || typeof o === \"function\") && o !== null ? Object.keys(o as object) : []\n let total = 1\n for (const k of ks) total += M.lengthBytesUTF8(k) + 1\n const p = M._malloc(total)\n let off = p\n for (const k of ks) { const n = M.lengthBytesUTF8(k) + 1; M.stringToUTF8(k, off, n); off += n }\n M.HEAPU32[countOut >> 2] = ks.length\n return p\n }\n newObject(classId: number, opaque: number) {\n const o: Record<string, unknown> = {}\n if (classId > 0) {\n this.opaques.set(o, { cls: classId, opaque })\n const token = { ref: new WeakRef(o), cls: classId, opaque }\n this.tracked.set(token, token)\n this.classRegistry.register(o, token, token)\n }\n this.writeOut(o)\n }\n newArray() { this.writeOut([]) }\n opaqueOf(idx: number, classId: number): number {\n const o = this.table[idx]\n if (typeof o !== \"object\" || o === null) return 0\n const e = this.opaques.get(o)\n return e && e.cls === classId ? e.opaque : 0\n }\n json(lo: number, hi: number) {\n let s: unknown\n try { s = JSON.stringify(this.decode(lo, hi)) } catch { s = undefined }\n this.writeOut(s)\n }\n parseJson(text: string) {\n try { this.writeOut(JSON.parse(text)) }\n catch (e) { this.pending = e; this.hasPending = true; this.writeOutException() }\n }\n\n // ---- strings + numbers ---------------------------------------------------------------------------\n newString(s: string) { this.writeOut(s) }\n str(lo: number, hi: number, lenOut: number): number {\n const M = this.M\n const v = this.decode(lo, hi)\n let s: string\n try { s = typeof v === \"string\" ? v : String(v) } catch { return 0 } // a Symbol\n const n = M.lengthBytesUTF8(s)\n const p = M._malloc(n + 1)\n M.stringToUTF8(s, p, n + 1)\n M.HEAPU32[lenOut >> 2] = n\n return p\n }\n logString(lo: number, hi: number): number {\n const M = this.M\n const v = this.decode(lo, hi)\n let s: string\n try { s = String(v) } catch { s = \"\" }\n if (v instanceof Error && typeof v.stack === \"string\" && v.stack.length > 0) {\n const stack = v.stack.startsWith(s) ? v.stack.slice(s.length).replace(/^\\n/, \"\") : v.stack\n if (stack.trim().length > 0) s += \"\\n\" + stack.replace(/[\\r\\n]+$/, \"\")\n }\n const n = M.lengthBytesUTF8(s)\n const p = M._malloc(n + 1)\n M.stringToUTF8(s, p, n + 1)\n return p\n }\n toNumber(idx: number): number { try { return Number(this.table[idx]) } catch { return NaN } }\n truthy(idx: number): boolean { return !!this.table[idx] }\n\n // ---- errors --------------------------------------------------------------------------------------\n newError(message: string) { this.writeOut(new Error(message)) }\n throwNew(kind: number, message: string) {\n this.pending = kind === 1 ? new TypeError(message) : new Error(message)\n this.hasPending = true\n }\n takeException() {\n const e = this.hasPending ? this.pending : undefined\n this.pending = undefined\n this.hasPending = false\n this.writeOut(e)\n }\n private throwPending(): never {\n const e = this.hasPending ? this.pending : new Error(\"native handler failed\")\n this.pending = undefined\n this.hasPending = false\n throw e\n }\n\n // ---- calls ---------------------------------------------------------------------------------------\n call(_ctx: number, fn: number, thisLo: number, thisHi: number, argc: number, argv: number) {\n const f = this.table[fn] as (...a: unknown[]) => unknown\n const thisv = this.decode(thisLo, thisHi)\n const args = this.args(argc, argv)\n try { this.writeOut(f.apply(thisv, args)) }\n catch (e) { this.pending = e; this.hasPending = true; this.writeOutException() }\n }\n construct(ctor: number, argc: number, argv: number) {\n const c = this.table[ctor] as new (...a: unknown[]) => unknown\n const args = this.args(argc, argv)\n try { this.writeOut(Reflect.construct(c, args)) }\n catch (e) { this.pending = e; this.hasPending = true; this.writeOutException() }\n }\n\n // ---- typed arrays ---------------------------------------------------------------------------------\n typedArray(kind: number, data: number, bytes: number) {\n const src = this.M.HEAPU8.slice(data, data + bytes) // a copy: the array owns its buffer\n const buf = src.buffer as ArrayBuffer\n const ctors = [null, Uint8Array, Uint16Array, Uint32Array, Int32Array, Float32Array, Float64Array, Int16Array, Int8Array, Uint8ClampedArray] as const\n if (kind === 0) { this.writeOut(buf); return }\n const C = ctors[kind]\n this.writeOut(C ? new C(buf) : undefined)\n }\n /** mode 0: a typed array of `elem`-byte elements (size = elements); 1: any typed array's bytes;\n * 2: an ArrayBuffer. A malloc'd copy the arm frees (a 1-byte block for an empty array), 0 when\n * the value is not such an array. */\n arrayIn(idx: number, elem: number, mode: number, sizeOut: number): number {\n const M = this.M\n const v = this.table[idx]\n let bytes: Uint8Array | null = null\n let size = 0\n if (mode === 2) {\n if (!(v instanceof ArrayBuffer)) return 0\n bytes = new Uint8Array(v); size = bytes.byteLength\n } else {\n if (!ArrayBuffer.isView(v) || v instanceof DataView) return 0\n const ta = v as Uint8Array\n const bpe = (ta as unknown as { BYTES_PER_ELEMENT: number }).BYTES_PER_ELEMENT\n if (mode === 0 && bpe !== elem) return 0\n bytes = new Uint8Array(ta.buffer, ta.byteOffset, ta.byteLength)\n size = mode === 0 ? ta.length : ta.byteLength\n }\n const p = M._malloc(Math.max(bytes.byteLength, 1))\n if (bytes.byteLength > 0) M.HEAPU8.set(bytes, p)\n M.HEAPU32[sizeOut >> 2] = size\n return p\n }\n arrayOut(idx: number, data: number, bytes: number) {\n const v = this.table[idx]\n let dst: Uint8Array\n if (v instanceof ArrayBuffer) dst = new Uint8Array(v)\n else if (ArrayBuffer.isView(v)) dst = new Uint8Array(v.buffer, v.byteOffset, v.byteLength)\n else return\n const n = Math.min(bytes, dst.byteLength)\n if (n > 0) dst.set(this.M.HEAPU8.subarray(data, data + n))\n }\n\n // ---- handler tables + native functions --------------------------------------------------------\n /** Run an installed handler with `args`: the arguments go onto the arg stack, the result comes\n * back through the slot (an exception re-thrown here). */\n private invoke(call: (argc: number, argv: number) => void, args: unknown[]): unknown {\n const argc = args.length\n const sp = this.argSp\n let argv = sp\n let heapArgv = 0\n if (sp + argc * 8 > this.argBase + ARG_STACK_BYTES) { heapArgv = this.M._malloc(Math.max(argc * 8, 8)); argv = heapArgv }\n else this.argSp = sp + argc * 8\n const owned: number[] = []\n for (let i = 0; i < argc; i++) { const idx = this.write(argv + i * 8, args[i]); if (idx) owned.push(idx) }\n let r: { value: unknown, threw: boolean }\n try {\n call(argc, argv)\n r = this.takeOut()\n } finally {\n for (const idx of owned) this.release(idx)\n this.argSp = sp\n if (heapArgv) this.M._free(heapArgv)\n }\n if (r.threw) this.throwPending()\n return r.value\n }\n defineMethod(ctx: number, obj: number, name: string, fnIndex: number, length: number, getter: number) {\n const o = this.table[obj] as object\n if (getter) {\n Object.defineProperty(o, name, { configurable: true, enumerable: false, get: () => this.invoke(() => this.M._jsbInvokeGetter(fnIndex), []) })\n return\n }\n const M = this.M\n const f = (...args: unknown[]) => this.invoke((argc, argv) => M._jsbInvoke(ctx, fnIndex, argc, argv), args)\n Object.defineProperty(f, \"name\", { value: name })\n Object.defineProperty(f, \"length\", { value: length })\n Object.defineProperty(o, name, { configurable: true, enumerable: false, writable: true, value: f })\n }\n makeFunction(ctx: number, k: number, name: string, length: number) {\n const M = this.M\n const f = (...args: unknown[]) => this.invoke((argc, argv) => M._jsbInvokeData(ctx, k, argc, argv), args)\n if (name) Object.defineProperty(f, \"name\", { value: name })\n Object.defineProperty(f, \"length\", { value: length })\n this.fnRegistry.register(f, k)\n this.writeOut(f)\n }\n\n // ---- host callbacks (the generated forwarders) -----------------------------------------------------\n /** A JS function for a JSCallback heap pointer a host slot received: calling it posts the call\n * through the runtime's dispatch queue (the next tick runs it). `group` = the slot's settle\n * group (released after the first settle; a second settle is ignored); null = a long-lived\n * listener the runtime frees itself. A zero pointer (an optional callback the app left out) is\n * a no-op. */\n callback(ptr: number, group: Group | null): (...args: unknown[]) => void {\n if (!ptr) return () => {}\n return (...args: unknown[]) => {\n if (group) {\n if (group.done) { console.warn(\"[jsb] a settled host callback was called again\"); return }\n group.done = true\n }\n const M = this.M\n const argc = args.length\n const n = group ? group.ptrs.length : 0\n const p = M._malloc(Math.max(argc * 8 + n * 4, 8))\n const owned: number[] = []\n for (let i = 0; i < argc; i++) { const idx = this.write(p + i * 8, args[i]); if (idx) owned.push(idx) }\n const gp = p + argc * 8\n for (let i = 0; i < n; i++) M.HEAPU32[(gp >> 2) + i] = group!.ptrs[i]\n M._jsbHostCall(ptr, argc, p, gp, n)\n for (const idx of owned) this.release(idx)\n M._free(p)\n }\n }\n /** A native view's event, host → app (`channel.emit` of a view a TS host mounted): the payload\n * crosses as the value it is — the runtime retains it until its dispatch queue delivers the\n * event. No payload = the listener gets none. */\n viewEvent(viewId: number, event: string, data?: unknown): void {\n const M = this.M\n const e = M.stringToNewUTF8(event)\n if (data === undefined) { M._jsbViewEvent(viewId, e, 0); M._free(e); return }\n const p = M._malloc(8)\n const idx = this.write(p, data)\n M._jsbViewEvent(viewId, e, p)\n if (idx) this.release(idx)\n M._free(p)\n M._free(e)\n }\n /** A settle group for the callbacks of one slot call. */\n group(...ptrs: number[]): Group { return { ptrs: ptrs.filter((x) => x !== 0), done: false } }\n /** A `const char* const*` + count → strings (the generated forwarders' string[] parameters). */\n strings(ptr: number, count: number): string[] {\n const M = this.M\n const out: string[] = new Array(count)\n for (let i = 0; i < count; i++) { const p = M.HEAPU32[(ptr >> 2) + i]; out[i] = p ? M.UTF8ToString(p) : \"\" }\n return out\n }\n /** A host's byte result → a malloc'd, NUL-terminated copy the runtime frees (0 for none); the\n * byte count goes to `outSize` when the slot has one. */\n bytesOut(r: unknown, outSize: number): number {\n const M = this.M\n let bytes: Uint8Array | null = null\n if (r instanceof Uint8Array) bytes = r\n else if (r instanceof ArrayBuffer) bytes = new Uint8Array(r)\n else if (ArrayBuffer.isView(r)) bytes = new Uint8Array(r.buffer, r.byteOffset, r.byteLength)\n if (!bytes || bytes.byteLength === 0) { if (outSize) M.HEAPU32[outSize >> 2] = 0; return 0 }\n const p = M._malloc(bytes.byteLength + 1)\n M.HEAPU8.set(bytes, p)\n M.HEAPU8[p + bytes.byteLength] = 0\n if (outSize) M.HEAPU32[outSize >> 2] = bytes.byteLength\n return p\n }\n\n gc() {\n const g = (globalThis as { gc?: () => void }).gc\n const bun = (globalThis as { Bun?: { gc?: (force: boolean) => void } }).Bun\n // twice: the first full collection leaves what only became unreachable during it (the weak\n // processing of the sweep below is one such source); the second takes it\n for (let i = 0; i < 2; i++) {\n if (bun?.gc) bun.gc(true)\n else if (typeof g === \"function\") g()\n else return\n this.sweep()\n }\n }\n /** Collected class instances finalize now, not on the registry's later task. */\n private sweep() {\n for (const token of [...this.tracked.keys()] as { ref: WeakRef<object>, cls: number, opaque: number }[]) {\n if (token.ref.deref() !== undefined) continue\n this.tracked.delete(token)\n this.classRegistry.unregister(token)\n this.M._jsbFinalize(token.cls, token.opaque)\n }\n }\n}\n\n/** Create the glue for a loaded runtime module and install it as `Module.jsb`. */\nexport const installJsb = (M: WasmModule, options: JsbOptions): Jsb => {\n const jsb = new Jsb(M, options)\n ;(M as unknown as { jsb: Jsb }).jsb = jsb\n return jsb\n}\n","export default \"__VITE_ASSET__BwIUPEiH__\"","// Lazy crash symbolizer for the creator-gl wasm. The shipped wasm has no name section\n// (see creator-gl/CMakeLists.txt: --emit-symbol-map), so a runtime trap surfaces as\n// \"RuntimeError: unreachable at wasm-function[1234]\" with anonymous frames. The build deploys\n// creator-gl.js.symbols (function index -> C++ name) next to the wasm; this module fetches that\n// map ONLY after a crash has already happened and prints a decoded trace to the console. Happy\n// path cost: zero — nothing is fetched or parsed until the first wasm frame appears in an error.\n//\n// The map is only valid for creator-gl.wasm. Frames from another wasm module (creator-ui,\n// creator-2d) carry their own URL in the stack line and are left untouched; frames with no URL\n// at all (Safari's \"[wasm code]\") are decoded anyway, since a creator-gl trap is by far the\n// likeliest source, and marked with \"?\" so a misattributed name isn't taken as gospel.\n\nimport symbolsUrl from '../native/dist/creator-full.js.symbols?url'\n\nconst WASM_FRAME = /wasm-function\\[(\\d+)\\]/g\n\n// index -> raw (still escaped) name. Parsed once, kept raw — escape decoding runs only on the\n// handful of frames actually printed, not on all ~40k entries.\nlet mapPromise: Promise<Map<number, string> | null> | null = null\n\nconst loadSymbolMap = (): Promise<Map<number, string> | null> => {\n if (!mapPromise) {\n mapPromise = fetch(symbolsUrl)\n .then(resp => {\n if (!resp.ok) throw new Error(`${resp.status} ${resp.statusText}`)\n return resp.text()\n })\n .then(text => {\n const map = new Map<number, string>()\n for (const line of text.split('\\n')) {\n const sep = line.indexOf(':')\n if (sep > 0) map.set(Number(line.slice(0, sep)), line.slice(sep + 1))\n }\n return map\n })\n .catch(e => {\n console.warn('[creator-gl] creator-gl.js.symbols unavailable, wasm frames stay anonymous:', e)\n return null\n })\n }\n return mapPromise\n}\n\n// The symbol map escapes non-identifier chars as \\XX hex (emscripten format): \\20 = space,\n// \\2c = comma, \\28\\29 = parens.\nconst decodeName = (raw: string): string =>\n raw.replace(/\\\\([0-9a-fA-F]{2})/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)))\n\n// Which wasm module does this stack line reference? Matches \"creator-ui.wasm:\",\n// \"creator-gl-B3xYz9.wasm)\" etc., but not the \".wasm-function[N]\" token itself (the lookahead\n// rejects the \"-f\"). The name is matched loosely (\"creator-gl\" prefix) because Vite hashes prod\n// asset filenames. null = no module URL in the line (Safari's \"[wasm code]\").\nconst MODULE_REF = /([\\w.-]+)\\.wasm(?=[^\\w-]|$)/g\nconst lineModule = (line: string): 'ours' | 'other' | null => {\n const refs = [...line.matchAll(MODULE_REF)].map(m => m[1]!)\n if (refs.length === 0) return null\n return refs.some(r => r.includes('creator-gl')) ? 'ours' : 'other'\n}\n\n/**\n * Decode every creator-gl `wasm-function[N]` frame in a stack trace. Resolves to null when the\n * stack has no wasm frames (or the symbol map can't be fetched) — callers use that to stay\n * silent for ordinary JS errors.\n */\nexport const symbolizeWasmStack = async (stack: string): Promise<string | null> => {\n WASM_FRAME.lastIndex = 0\n if (!WASM_FRAME.test(stack)) return null\n const map = await loadSymbolMap()\n if (!map) return null\n\n let decodedAny = false\n const lines = stack.split('\\n').map(line => {\n WASM_FRAME.lastIndex = 0\n if (!WASM_FRAME.test(line)) return line\n const mod = lineModule(line)\n // A frame naming a different wasm module belongs to that module's map, not ours. URL-less\n // frames are decoded anyway (a creator-gl trap is by far the likeliest source) but marked \"?\".\n if (mod === 'other') return line\n return line.replace(WASM_FRAME, (frame, index) => {\n const raw = map.get(Number(index))\n if (raw === undefined) return frame\n decodedAny = true\n return `${mod === null ? '?' : ''}${decodeName(raw)} (${frame})`\n })\n })\n return decodedAny ? lines.join('\\n') : null\n}\n\n/**\n * The display-friendly cut of symbolizeWasmStack for UI overlays: just the decoded C++ names of\n * the creator-gl frames, top-first — no URLs, no JS glue frames. Empty when the stack has no\n * decodable creator-gl frames (or the map can't be fetched).\n */\nexport const symbolizeWasmFrames = async (stack: string): Promise<string[]> => {\n WASM_FRAME.lastIndex = 0\n if (!WASM_FRAME.test(stack)) return []\n const map = await loadSymbolMap()\n if (!map) return []\n const names: string[] = []\n for (const line of stack.split('\\n')) {\n if (lineModule(line) === 'other') continue\n for (const m of line.matchAll(WASM_FRAME)) {\n const raw = map.get(Number(m[1]))\n // libc++'s internal namespace is pure noise in a UI overlay.\n if (raw !== undefined) names.push(decodeName(raw).replaceAll('std::__2::', 'std::'))\n }\n }\n return names\n}\n\n/** Fire-and-forget: print a decoded trace for `err` if it contains creator-gl wasm frames. */\nexport const symbolizeWasmError = (err: unknown): void => {\n const stack = (err as { stack?: unknown } | null)?.stack\n if (typeof stack !== 'string') return\n symbolizeWasmStack(stack).then(decoded => {\n if (decoded) console.error('[creator-gl] decoded wasm stack (via creator-gl.js.symbols):\\n' + decoded)\n })\n}\n\nlet installed = false\n\n/**\n * Catch wasm traps that escape to the top (the render rAF loop has no try/catch — an engine\n * crash lands on the global 'error' event) and follow the browser's own report with a decoded\n * trace. Errors swallowed by app-level try/catch never get here — those paths call\n * symbolizeWasmError directly (see createGlb/loadGlb).\n */\nexport const installWasmCrashSymbolizer = (): void => {\n if (installed) return\n installed = true\n addEventListener('error', e => symbolizeWasmError((e as ErrorEvent).error))\n addEventListener('unhandledrejection', e => symbolizeWasmError((e as PromiseRejectionEvent).reason))\n}\n","// Slot 0 is reserved: 0 means \"no buffer\" in the host contract (HostFetch.putBuffer, a form's bufferId > 0).\nconst arrayBuffers: ArrayBuffer[] = [null as unknown as ArrayBuffer]\n\nconst decoder = new TextDecoder('utf-8');\n\nexport const _fetch = async (url: string, fetchOptions: any, onComplete: (systemId: number, statusCode: number) => void, onReject: (err: Error) => void) => {\n \n let body: any = undefined\n if (fetchOptions.body) {\n if (typeof fetchOptions.body === \"object\" && Array.isArray(fetchOptions.body._entries)) {\n const formData = new FormData()\n for (let [key,value,filename] of fetchOptions.body._entries) {\n if (typeof value === \"object\") {\n formData.append(key, new Blob([ getBuffer(value._id) ]), filename)\n } else {\n formData.append(key, value)\n }\n }\n body = formData\n } else if (typeof fetchOptions.body === \"string\") {\n body = fetchOptions.body\n } else {\n onReject(new Error(\"Invalid body\"))\n }\n }\n \n const resp = await fetch(url, {\n method: fetchOptions.method,\n body,\n headers: fetchOptions.headers,\n mode: \"cors\",\n credentials: \"omit\"\n })\n\n const onProgress =\n typeof fetchOptions.onProgress === 'function'\n ? fetchOptions.onProgress\n : null\n\n // FAST PATH (без стрима)\n if (!onProgress) {\n const buffer = await resp.arrayBuffer()\n arrayBuffers.push(buffer)\n onComplete(arrayBuffers.length - 1, resp.status)\n return\n }\n\n // STREAMING PATH\n const reader = resp.body?.getReader()\n\n // fallback если стрима нет\n if (!reader) {\n const buffer = await resp.arrayBuffer()\n arrayBuffers.push(buffer)\n onComplete(arrayBuffers.length - 1, resp.status)\n return\n }\n\n const contentLength = Number(resp.headers.get(\"content-length\")) || undefined\n\n let loaded = 0\n const chunks: Uint8Array[] = []\n\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n\n if (value) {\n chunks.push(value)\n loaded += value.length\n\n onProgress({ loaded, total: contentLength })\n }\n }\n\n // сборка\n const result = new Uint8Array(loaded)\n let offset = 0\n for (const chunk of chunks) {\n result.set(chunk, offset)\n offset += chunk.length\n }\n\n arrayBuffers.push(result.buffer)\n onComplete(arrayBuffers.length - 1, resp.status)\n}\n\nexport const _fetchToJson = (systemId: number) => { \n return JSON.parse(decoder.decode(getBuffer(systemId)))\n}\n\nexport const _fetchToText = (systemId: number) => {\n return decoder.decode(getBuffer(systemId))\n}\n\n/** The fetched bytes as a Uint8Array copy (Terrain.load and other SDK-parsed binaries). */\nexport const _fetchToBytes = (systemId: number): Uint8Array => {\n return new Uint8Array(getBuffer(systemId)).slice()\n}\n\nexport const _fetchSlice = (systemId: number, start: number, end: number) => {\n return decoder.decode(getBuffer(systemId).slice(start, end))\n}\n\nexport const getUrl = (systemId: number) => {\n const blob = new Blob([ arrayBuffers[systemId] ])\n return URL.createObjectURL(blob)\n}\n\nexport const getBlob = (systemId: number) => {\n return new Blob([ arrayBuffers[systemId] ])\n}\n\nexport const getBuffer = (systemId: number) => {\n return arrayBuffers[systemId]\n}\n\nexport const _disposeFetch = (id: number) => {\n arrayBuffers[id] = null as any\n}\n\nexport const putBuffer = (buffer: ArrayBuffer) => {\n arrayBuffers.push(buffer)\n return arrayBuffers.length - 1\n}\n\nconst map = new Map<string, ArrayBuffer>()\nexport const putLocalBuffer = (str: string, buf: ArrayBuffer) => {\n map.set(str, buf)\n // A name may already be materialized as a systemId (localResources caches forever). Refresh the\n // buffer behind it, or a later engine sees the stale payload — e.g. the lite engine's empty\n // built-in registrations must not shadow the real filamat the Filament engine loads on a\n // lite → filament host switch.\n const systemId = localResources.get(str)\n if (systemId !== undefined) arrayBuffers[systemId] = buf\n}\n\nexport const hasLocalBuffer = (str: string) => map.has(str)\n\nconst localResources = new Map<string, number>()\n\n/** Reverse lookup: the local-resource name a systemId was materialized from (viewer-lite resolves\n * material shaders — \"lit.filamat\" etc — by name instead of compiling the filamat package). */\nexport const getLocalName = (systemId: number): string | undefined => {\n for (const [name, id] of localResources) if (id === systemId) return name\n return undefined\n}\n\nexport const _fetchLocal = (path: string): number => {\n const existsSystemId = localResources.get(path)\n if (existsSystemId !== undefined) {\n return existsSystemId\n }\n const buf = map.get(path)\n if (!buf) return -1\n \n arrayBuffers.push(buf)\n const systemId = arrayBuffers.length-1\n\n localResources.set(path, systemId)\n return systemId\n}\n","// The effective on-screen scale of a host root, recovered from the DOM.\n//\n// The simulator displays the app at a fixed CSS `zoom` (default 0.75) so the preview matches a real\n// device while the app keeps its true logical viewport. Under `zoom` — and under a legacy\n// `transform: scale()` — an element's getBoundingClientRect() reports VISUAL px (post-scale) while\n// clientWidth/clientHeight stay LAYOUT px (the element's own coordinate space). Their ratio is the\n// effective scale a visual coordinate (e.g. a pointer's `clientX - rect.left`) must be divided by to\n// reach the app's logical space.\n//\n// This is the same computation createUI's getBoundingClientRect bridge already does\n// (appRect.width / displayWidth); factored out so every pointer path shares one definition.\n\n/** Visual-to-layout scale of `el` (guards a zero layout size → 1). */\nexport const viewScale = (el: HTMLElement): number => {\n const layout = el.clientWidth\n if (!layout) return 1\n const visual = el.getBoundingClientRect().width\n return visual > 0 ? visual / layout : 1\n}\n","// Image-source resolution, shared by every Host. The authoring layer (worker) hands an image `src`\n// (or `backgroundImage`) as one of: a string url, an inline `SvgSource` ({ svg }), or a host buffer\n// handle ({ _id } — an SDK `FetchResponse`/`File`, both carrying the buffer id under `_id`). A raw\n// DOM `File` is a separate, browser-embed-only case. Only the string case is platform-free; the rest\n// need a host-provided URL (asset bytes / object URL), so each Host wires those callbacks in.\n\n/** An inline SVG source (`SvgSource(...)` in the worker). */\nexport function isSvgSource(src: unknown): src is { svg: string } {\n return typeof src === \"object\" && src !== null && \"svg\" in (src as Record<string, unknown>)\n}\n\n/** A host buffer handle: an SDK `FetchResponse` / `File` / uploaded asset, keyed by its buffer id.\n * Checked BEFORE isFileLike — an SDK `File` is a plain object with `_id`, not a DOM File. */\nfunction hasId(src: unknown): src is { _id: number } {\n return typeof src === \"object\" && src !== null && \"_id\" in (src as Record<string, unknown>)\n}\n\n/** A baked `_creatorCanvas` surface (UIImage(canvas)) — resolved to a texture via a CanvasSurfaceProvider. */\nfunction hasCanvasSurface(src: unknown): src is { canvasSurface: number } {\n return typeof src === \"object\" && src !== null && \"canvasSurface\" in (src as Record<string, unknown>)\n}\n\n/** Synthetic url a `{ canvasSurface }` src resolves to; the host turns it back into a baked surface. */\nexport const CANVAS_SRC_PREFIX = \"lecodes-canvas://\"\n/** Parse a `lecodes-canvas://N` url back to its surface id, or undefined. */\nexport function canvasSurfaceId(src: string): number | undefined {\n return src.startsWith(CANVAS_SRC_PREFIX) ? Number(src.slice(CANVAS_SRC_PREFIX.length)) : undefined\n}\n\n/** A raw DOM `File` — only ever reaches here from a browser embed handing one in directly. The SDK's\n * `File` is NOT one of these: it's a `{ _id, name, size }` buffer handle caught by hasId above. */\nfunction isFileLike(src: unknown): boolean {\n return typeof File !== \"undefined\" && src instanceof File\n}\n\n/** Inline SVG → a `data:image/svg+xml` URI an `<img>` / decoder can load (mirrors the DOM viewer). */\nexport function svgToDataUri(svg: string): string {\n let s = svg.trim()\n // A data: URI is parsed as a standalone XML document — xmlns is mandatory there (inline DOM <svg>\n // tolerates its absence; a data-uri image without it renders broken).\n if (!/\\sxmlns\\s*=/.test(s)) s = s.replace(/<svg\\b/, '<svg xmlns=\"http://www.w3.org/2000/svg\"')\n const bytes = new TextEncoder().encode(s)\n let binary = \"\"\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return `data:image/svg+xml;base64,${btoa(binary)}`\n}\n\n/** True if a *resolved* src is an SVG (data-uri or `.svg` url) — i.e. a mask-capable, tintable image.\n * Used to gate `tintColor`: SVG recolors (mask), an opaque raster does not (the DOM no-ops it). */\nexport function isSvgLikeSrc(src: string | undefined): boolean {\n return !!src && (src.startsWith(\"data:image/svg+xml\") || /\\.svg(\\?|#|$)/i.test(src))\n}\n\n/**\n * Intrinsic size of an inline SVG, taken from its `viewBox` (\"min-x min-y width height\"), or its\n * `<svg>` width/height attributes, or null. SVG is a vector, so this is the size to lay out at (and\n * it may upscale). Matches the DOM, which reads the viewBox into `data-viewbox` for measuring.\n */\nexport function extractSvgViewBox(svg: string): { width: number; height: number } | null {\n // Only read the opening <svg> tag, so child element width/height never leak in.\n const tag = svg.match(/<svg\\b[^>]*>/i)?.[0] ?? \"\"\n const vb = tag.match(/viewBox\\s*=\\s*[\"']\\s*[\\d.+-]+\\s+[\\d.+-]+\\s+([\\d.+-]+)\\s+([\\d.+-]+)\\s*[\"']/i)\n if (vb) {\n const w = parseFloat(vb[1]), h = parseFloat(vb[2])\n if (w > 0 && h > 0) return { width: w, height: h }\n }\n const w = parseFloat(tag.match(/\\bwidth\\s*=\\s*[\"']?([\\d.]+)/i)?.[1] ?? \"\")\n const h = parseFloat(tag.match(/\\bheight\\s*=\\s*[\"']?([\\d.]+)/i)?.[1] ?? \"\")\n if (w > 0 && h > 0) return { width: w, height: h }\n return null\n}\n\n/** Decode an `data:image/svg+xml` URI (base64 or text/url-encoded) back to its markup, or null. */\nexport function decodeSvgDataUri(src: string): string | null {\n const m = /^data:image\\/svg\\+xml(;[^,]*)?,([\\s\\S]*)$/.exec(src)\n if (!m) return null\n const data = m[2]\n try {\n if (/;base64/i.test(m[1] ?? \"\")) {\n const bin = atob(data)\n const bytes = new Uint8Array(bin.length)\n for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)\n return new TextDecoder().decode(bytes)\n }\n return decodeURIComponent(data)\n } catch {\n return null\n }\n}\n\n/**\n * The intrinsic (viewBox) size of an SVG from its resolved src. SVGs without explicit width/height\n * have NO intrinsic size, so a browser `<img>` reports the CSS default 300×150 — wrong for layout +\n * object-fit. Reading the viewBox instead makes canvas/native size SVGs to their box like the DOM\n * does. Inline data-uris are decoded synchronously; a remote/blob `.svg` url needs `fetchText`.\n */\nexport async function svgIntrinsicSize(\n src: string,\n fetchText?: (url: string) => Promise<string | null>,\n): Promise<{ width: number; height: number } | null> {\n if (!isSvgLikeSrc(src)) return null\n const inline = decodeSvgDataUri(src)\n if (inline) return extractSvgViewBox(inline)\n if (!fetchText) return null\n const text = await fetchText(src).catch(() => null)\n return text ? extractSvgViewBox(text) : null\n}\n\nexport interface SrcResolverOptions {\n /** Resolve a host buffer handle ({ _id } — SDK `FetchResponse` / `File`) to a url (e.g. a blob url\n * for the fetched bytes). */\n assetUrl?: (id: number) => string | undefined\n /** Resolve a raw DOM `File` to a url (browser: `URL.createObjectURL`). Not the SDK `File` — that\n * one is a buffer handle and goes through `assetUrl`. */\n fileUrl?: (file: unknown) => string | undefined\n}\n\n/**\n * Build a memoized `resolveSrc(rawSrc) → string | undefined`. Strings pass through; `SvgSource` →\n * data-uri; `{ _id }` (SDK `FetchResponse`/`File`) and a raw DOM `File` go through the injected\n * callbacks (undefined when not wired, e.g. headless). Memoized by object identity so SVG\n * data-uris / blob urls are created once per source.\n */\nexport function createSrcResolver(opts: SrcResolverOptions = {}): (src: unknown) => string | undefined {\n const cache = new WeakMap<object, string>()\n return (src: unknown): string | undefined => {\n if (src == null) return undefined\n if (typeof src === \"string\") return src\n if (typeof src !== \"object\") return undefined\n const obj = src as object\n const cached = cache.get(obj)\n if (cached !== undefined) return cached\n let out: string | undefined\n if (isSvgSource(obj)) out = svgToDataUri(obj.svg)\n else if (hasCanvasSurface(obj)) out = CANVAS_SRC_PREFIX + obj.canvasSurface\n else if (hasId(obj)) out = opts.assetUrl?.(obj._id)\n else if (isFileLike(obj)) out = opts.fileUrl?.(obj)\n if (out !== undefined) cache.set(obj, out)\n return out\n }\n}\n","import type { ImageInfo } from \"../types\"\nimport { canvasSurfaceId } from \"../core/util/svgSrc\"\n\n/**\n * Access to baked `_creatorCanvas` surfaces, so a `UIImage(canvas)` resolves to a texture. `canvas` is\n * a drawable the painter can `drawImage` (an OffscreenCanvas on web, a napi canvas headless); width/\n * height are the surface's device pixels. Injected into a Host so it can turn a `lecodes-canvas://N`\n * src into an ImageInfo.\n */\nexport interface CanvasSurfaceProvider {\n getSurface(surfaceId: number): { canvas: unknown, width: number, height: number } | null\n}\n\n/** If `src` is a `lecodes-canvas://N` url, resolve it to an ImageInfo via the provider (the baked\n * surface is already rasterized → synchronous). Returns undefined for any other src. */\nexport function resolveCanvasImage(src: string, provider: CanvasSurfaceProvider | undefined): ImageInfo | undefined {\n if (!provider) return undefined\n const id = canvasSurfaceId(src)\n if (id === undefined) return undefined\n const surf = provider.getSurface(id)\n if (!surf) return undefined\n return { src, naturalWidth: surf.width, naturalHeight: surf.height, handle: surf.canvas }\n}\n\n/** A fully-resolved font, as the core asks the host to measure it. */\nexport interface FontSpec {\n family: string\n size: number\n weight: number\n italic: boolean\n letterSpacing: number\n}\n\n/**\n * Platform capabilities the portable core can't implement itself. Injected so the core runs\n * headless under Bun (HeadlessHost) and in the browser (BrowserHost) unchanged.\n */\nexport interface Host {\n /** Advance width of a single line of text, in CSS pixels. */\n measureText(text: string, font: FontSpec): number\n\n /** Vertical metrics for a font (used for line-height fallback and the text baseline). */\n fontMetrics(font: FontSpec): { ascent: number; descent: number }\n\n /**\n * Synchronous cache lookup for an image's intrinsic size. Returns undefined until the image is\n * decoded — the core then measures it as 0×0 (collapsed), exactly like the DOM renderer before\n * `naturalWidth` is known.\n */\n getImage(src: string): ImageInfo | undefined\n\n /**\n * Begin (or reuse) an async decode. Resolves with the intrinsic size; the caller marks the\n * owning screen dirty so the next render picks up the now-known size. May resolve synchronously\n * via the cache in HeadlessHost.\n */\n loadImage(src: string): Promise<ImageInfo>\n\n /**\n * Load a custom font so subsequent `measureText`/painting use it. Web: `FontFace`; headless:\n * disk/network bytes into the canvas backend (NodeCanvasHost) or a no-op (synthetic metrics);\n * desktop: a tgfx typeface load. Resolves once the font is usable (or has fallen back).\n */\n loadFont(family: string, url: string, options: { weight?: number; style?: string }): Promise<void>\n\n /** Preferred CDN face container (`_creatorUI.fontFormat`): browser hosts \"woff2\"; absent = ttf. */\n fontFormat?: \"woff2\" | \"ttf\"\n\n /**\n * Map a style-level fontFamily to what this host's text stack can actually resolve — the CSS\n * generic families, mostly: browser hosts alias the SDK's \"monospaced\" to the CSS keyword\n * \"monospace\"; headless pins every generic to a vendored concrete face (genericFamilies.ts),\n * because Skia has no generic resolution. Applied by paintTree when building a FontSpec; hosts\n * also apply it inside their own measureText/fontMetrics so layout and paint always agree.\n */\n resolveFontFamily?(family: string): string\n\n /**\n * Resolve an authoring image source to a loadable url string, or undefined if it can't be. The\n * source is a string url, an inline `SvgSource` ({ svg }), an uploaded asset ({ _id }), or a\n * `File`. String + SVG are platform-free; `{ _id }`/`File` need platform url resolution, which only\n * some hosts wire (e.g. the browser host with the app's asset resolver). Memoized per source.\n */\n resolveSrc(src: unknown): string | undefined\n}\n","import type { ImageInfo } from \"../types\"\nimport { resolveCanvasImage, type CanvasSurfaceProvider, type FontSpec, type Host } from \"./Host\"\nimport { createSrcResolver, isSvgLikeSrc, svgIntrinsicSize } from \"../core/util/svgSrc\"\n\n// The SDK spells the fixed-width system family \"monospaced\" (the iOS name); CSS spells it\n// \"monospace\". Other generics (\"serif\", \"sans-serif\") are real CSS keywords and resolve natively.\nconst cssFamily = (family: string) => (family === \"monospaced\" ? \"monospace\" : family)\n\nfunction fontCss(font: FontSpec): string {\n return `${font.italic ? \"italic \" : \"\"}${font.weight} ${font.size}px ${cssFamily(font.family)}`\n}\n\nexport interface BrowserHostOptions {\n /** Resolve an uploaded asset ({ _id }) to a url — the app injects this (e.g. the viewer's\n * `getUrl(id)` blob-url resolver). Without it, `{ _id }` image sources don't render. */\n resolveAssetUrl?: (id: number) => string | undefined\n /** Resolve `UIImage(canvas)` sources (baked `_creatorCanvas` surfaces) to textures. */\n canvasSurfaces?: CanvasSurfaceProvider\n}\n\n/** Browser host: text metrics via a measuring 2D context, image decode via HTMLImageElement. */\nexport class BrowserHost implements Host {\n private ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D\n private images = new Map<string, ImageInfo>()\n private pending = new Map<string, Promise<ImageInfo>>()\n private resolver: (src: unknown) => string | undefined\n private canvasSurfaces?: CanvasSurfaceProvider\n\n constructor(opts: BrowserHostOptions = {}) {\n // Measure on a DOM canvas whenever a document exists: a main-thread OffscreenCanvas context\n // does not reliably resolve document.fonts faces in every browser (Safari), which would keep\n // measuring custom faces with the fallback while the visible canvas paints the real one.\n // OffscreenCanvas stays for workers, where there is no document.\n const canvas =\n typeof document !== \"undefined\"\n ? (document.createElement(\"canvas\") as HTMLCanvasElement)\n : new OffscreenCanvas(8, 8)\n this.ctx = (canvas as any).getContext(\"2d\")\n this.canvasSurfaces = opts.canvasSurfaces\n // Inline SVG → data-uri; uploaded assets via the app's resolver; File → object url.\n this.resolver = createSrcResolver({\n assetUrl: opts.resolveAssetUrl,\n fileUrl: (file) => URL.createObjectURL(file as File),\n })\n }\n\n resolveSrc(src: unknown): string | undefined {\n return this.resolver(src)\n }\n\n /** Image decodes still in flight — lets a host idle its paint loop until they land (the\n * headless NodeCanvasHost exposes the same probe). */\n pendingImages(): number {\n return this.pending.size\n }\n\n resolveFontFamily(family: string): string {\n return cssFamily(family)\n }\n\n measureText(text: string, font: FontSpec): number {\n this.ctx.font = fontCss(font)\n ;(this.ctx as any).letterSpacing = `${font.letterSpacing}px`\n return this.ctx.measureText(text).width\n }\n\n fontMetrics(font: FontSpec) {\n this.ctx.font = fontCss(font)\n const m = this.ctx.measureText(\"Mg\")\n // The FONT's ascent/descent — the metrics CSS line-box layout centers inside line-height.\n // The ink extent (actualBoundingBox of the sample glyphs) is smaller, which would place the\n // baseline ~1px higher than the DOM/native render of the same text.\n const ascent = m.fontBoundingBoxAscent || m.actualBoundingBoxAscent || font.size * 0.8\n const descent = m.fontBoundingBoxDescent || m.actualBoundingBoxDescent || font.size * 0.2\n return { ascent, descent }\n }\n\n getImage(src: string): ImageInfo | undefined {\n return resolveCanvasImage(src, this.canvasSurfaces) ?? this.images.get(src)\n }\n\n loadImage(src: string): Promise<ImageInfo> {\n const canvasImg = resolveCanvasImage(src, this.canvasSurfaces)\n if (canvasImg) return Promise.resolve(canvasImg) // baked surface — already rasterized, no decode\n const cached = this.images.get(src)\n if (cached) return Promise.resolve(cached)\n const inFlight = this.pending.get(src)\n if (inFlight) return inFlight\n\n const promise = (async (): Promise<ImageInfo> => {\n const img = await this.decode(src)\n let naturalWidth = img.naturalWidth\n let naturalHeight = img.naturalHeight\n // A browser gives a viewBox-only SVG the CSS default 300×150 intrinsic size, which breaks layout\n // + object-fit (the icon won't size to its box). Use the real viewBox instead — matching the DOM\n // (which reads the viewBox) and the native renderers.\n if (isSvgLikeSrc(src)) {\n const vb = await svgIntrinsicSize(src, (url) => fetch(url).then((r) => (r.ok ? r.text() : null)))\n if (vb) { naturalWidth = vb.width; naturalHeight = vb.height }\n }\n const info: ImageInfo = { src, naturalWidth, naturalHeight, handle: img }\n this.images.set(src, info)\n this.pending.delete(src)\n return info\n })()\n this.pending.set(src, promise)\n promise.catch(() => this.pending.delete(src)) // a decode failure must clear the in-flight slot\n return promise\n }\n\n /** Decode an image url into an HTMLImageElement (resolves on load, rejects on error). */\n private decode(src: string): Promise<HTMLImageElement> {\n return new Promise((resolve, reject) => {\n const img = new Image()\n img.onload = () => resolve(img)\n img.onerror = (e) => reject(e)\n img.src = src\n })\n }\n\n // Browser host: CDN faces should come as woff2 (the font() macro's generated code reads this).\n fontFormat = \"woff2\" as const\n\n async loadFont(family: string, url: string, options: { weight?: number; style?: string }): Promise<void> {\n if (typeof (globalThis as any).FontFace === \"undefined\") return\n const face = new FontFace(family, `url(${url})`, options as FontFaceDescriptors)\n // Added before load resolves: text swaps in the moment the bytes land, whether or not\n // anything awaits the legacy completion callback (Renderer purges wrap caches on resolve).\n ;(document as any).fonts.add(face)\n await face.load()\n }\n}\n","import type { RGBA } from \"../../types\"\n\nexport interface RGBAChannels {\n r: number\n g: number\n b: number\n a: number\n}\n\n/** Unpack a 0xRRGGBBAA color into channels (a in 0..255). */\nexport function unpackRGBA(v: RGBA): RGBAChannels {\n const u = v >>> 0\n return { r: (u >>> 24) & 0xff, g: (u >>> 16) & 0xff, b: (u >>> 8) & 0xff, a: u & 0xff }\n}\n\n/** 0xRRGGBBAA → \"#rrggbbaa\" (lowercase), the readable form used in the JSON output. */\nexport function rgbaToHex(v: RGBA): string {\n return \"#\" + (v >>> 0).toString(16).padStart(8, \"0\")\n}\n\n/** 0xRRGGBBAA → a CSS/canvas \"rgba(r, g, b, a)\" string. */\nexport function rgbaToCss(v: RGBA): string {\n const { r, g, b, a } = unpackRGBA(v)\n return `rgba(${r}, ${g}, ${b}, ${(a / 255).toFixed(4)})`\n}\n\n/** True if the color is fully transparent (skip painting). */\nexport function isTransparent(v: RGBA | undefined): boolean {\n return v === undefined || (v >>> 0 & 0xff) === 0\n}\n","import type { BorderRadius, RadialGradient, Rect } from \"../../types\"\n\n/** Clamp the corner radii so opposite corners never overlap (CSS behavior). */\nexport function clampRadius(radius: BorderRadius | undefined, rect: Rect): BorderRadius | undefined {\n if (!radius) return undefined\n const max = Math.min(rect.width, rect.height) / 2\n return {\n tl: Math.min(radius.tl, max),\n tr: Math.min(radius.tr, max),\n br: Math.min(radius.br, max),\n bl: Math.min(radius.bl, max),\n }\n}\n\nexport function hasRadius(radius: BorderRadius | undefined): boolean {\n return !!radius && (radius.tl > 0 || radius.tr > 0 || radius.br > 0 || radius.bl > 0)\n}\n\n/**\n * Resolve object-fit into source (image px) + destination (screen px) rects, ready for a canvas\n * drawImage(src.x, src.y, src.w, src.h, dst.x, dst.y, dst.w, dst.h).\n */\nexport function computeObjectFit(\n naturalWidth: number,\n naturalHeight: number,\n box: Rect,\n fit: \"cover\" | \"contain\" | \"fill\",\n): { src: Rect; dst: Rect } {\n const full: Rect = { x: 0, y: 0, width: naturalWidth, height: naturalHeight }\n if (fit === \"fill\" || naturalWidth === 0 || naturalHeight === 0) {\n return { src: full, dst: box }\n }\n\n if (fit === \"cover\") {\n // Crop the image so it fills the box without distortion.\n const scale = Math.max(box.width / naturalWidth, box.height / naturalHeight)\n const sw = box.width / scale\n const sh = box.height / scale\n return {\n src: { x: (naturalWidth - sw) / 2, y: (naturalHeight - sh) / 2, width: sw, height: sh },\n dst: box,\n }\n }\n\n // contain: scale to fit inside, centered.\n const scale = Math.min(box.width / naturalWidth, box.height / naturalHeight)\n const dw = naturalWidth * scale\n const dh = naturalHeight * scale\n return {\n src: full,\n dst: { x: box.x + (box.width - dw) / 2, y: box.y + (box.height - dh) / 2, width: dw, height: dh },\n }\n}\n\n/**\n * Resolve a CSS gradient angle (0 = to top, 90 = to right, clockwise) into a gradient line through a\n * rect (start = 0%, end = 100%), using the standard CSS endpoint projection.\n */\nexport function gradientLine(angle: number, rect: Rect) {\n const rad = (angle * Math.PI) / 180\n const dx = Math.sin(rad)\n const dy = -Math.cos(rad)\n const cx = rect.x + rect.width / 2\n const cy = rect.y + rect.height / 2\n const halfLen = (Math.abs(rect.width * dx) + Math.abs(rect.height * dy)) / 2\n return {\n x0: cx - dx * halfLen,\n y0: cy - dy * halfLen,\n x1: cx + dx * halfLen,\n y1: cy + dy * halfLen,\n }\n}\n\n/**\n * Resolve a radial gradient's CSS geometry against a rect: the center (absolute px) and the two\n * semi-axes `rx`/`ry` (px) of the ending ellipse. Implements the CSS extent keywords; a `circle`\n * uses a single radius (equal axes). For the corner extents an ellipse keeps the matching side\n * ellipse's aspect ratio and passes through that corner (the √2 factor for an axis-aligned box).\n */\nexport function radialGeometry(g: RadialGradient, rect: Rect) {\n const cx = rect.x + g.cx * rect.width\n const cy = rect.y + g.cy * rect.height\n\n // Explicit radii: px used directly, a \"fraction\" (from a % radius) resolves against the box axis.\n if (g.extent === \"explicit\") {\n const rx = g.rxUnit === \"fraction\" ? (g.rx ?? 0) * rect.width : (g.rx ?? 0)\n const ry = g.ryUnit === \"fraction\" ? (g.ry ?? 0) * rect.height : (g.ry ?? 0)\n return { cx, cy, rx, ry }\n }\n\n // distances from the center to each side\n const left = g.cx * rect.width\n const right = (1 - g.cx) * rect.width\n const top = g.cy * rect.height\n const bottom = (1 - g.cy) * rect.height\n const nearX = Math.min(left, right)\n const farX = Math.max(left, right)\n const nearY = Math.min(top, bottom)\n const farY = Math.max(top, bottom)\n\n let rx: number\n let ry: number\n if (g.shape === \"circle\") {\n let r: number\n switch (g.extent) {\n case \"closest-side\": r = Math.min(nearX, nearY); break\n case \"farthest-side\": r = Math.max(farX, farY); break\n case \"closest-corner\": r = Math.hypot(nearX, nearY); break\n default: r = Math.hypot(farX, farY); break // farthest-corner\n }\n rx = ry = r\n } else {\n switch (g.extent) {\n case \"closest-side\": rx = nearX; ry = nearY; break\n case \"farthest-side\": rx = farX; ry = farY; break\n case \"closest-corner\": rx = nearX * Math.SQRT2; ry = nearY * Math.SQRT2; break\n default: rx = farX * Math.SQRT2; ry = farY * Math.SQRT2; break // farthest-corner\n }\n }\n return { cx, cy, rx, ry }\n}\n","import type { BorderRadius, Gradient, ImageInfo, RadialGradient, Rect, RGBA } from \"../types\"\nimport type { FontSpec } from \"../host/Host\"\nimport type { Borders, DrawImageOpts, Painter } from \"./Painter\"\nimport { rgbaToCss } from \"../core/util/colors\"\nimport { clampRadius, computeObjectFit, gradientLine, radialGeometry } from \"../core/util/geometry\"\n\n/** Painter backend over a CanvasRenderingContext2D (browser). */\ntype AnyCtx = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D\n\nexport class Canvas2DPainter implements Painter {\n private ctx: AnyCtx\n private dpr: number\n // Stack of in-progress opacity groups: each captures the parent ctx + an offscreen layer + alpha.\n private groups: { parent: AnyCtx; layer: HTMLCanvasElement | OffscreenCanvas; alpha: number }[] = []\n\n constructor(ctx: CanvasRenderingContext2D, dpr = 1) {\n this.ctx = ctx\n this.dpr = dpr\n }\n\n beginGroup(alpha: number) {\n const cur = this.ctx\n const w = (cur.canvas as HTMLCanvasElement | OffscreenCanvas).width\n const h = (cur.canvas as HTMLCanvasElement | OffscreenCanvas).height\n let layer: HTMLCanvasElement | OffscreenCanvas\n if (typeof OffscreenCanvas !== \"undefined\") {\n layer = new OffscreenCanvas(w, h)\n } else {\n layer = document.createElement(\"canvas\")\n layer.width = w\n layer.height = h\n }\n const lctx = (layer as any).getContext(\"2d\") as AnyCtx\n lctx.setTransform(cur.getTransform()) // paint the subtree in the same coordinate space\n this.groups.push({ parent: cur, layer, alpha })\n this.ctx = lctx\n }\n\n endGroup() {\n const g = this.groups.pop()\n if (!g) return\n this.ctx = g.parent\n this.ctx.save()\n this.ctx.setTransform(1, 0, 0, 1, 0, 0) // composite the layer in device pixels\n this.ctx.globalAlpha *= g.alpha\n this.ctx.drawImage(g.layer as CanvasImageSource, 0, 0)\n this.ctx.restore()\n }\n\n beginFrame(width: number, height: number) {\n const { ctx, dpr } = this\n ctx.setTransform(dpr, 0, 0, dpr, 0, 0)\n ctx.clearRect(0, 0, width, height)\n ctx.globalAlpha = 1\n }\n endFrame() {}\n\n save() {\n this.ctx.save()\n }\n restore() {\n this.ctx.restore()\n }\n setAlpha(multiplier: number) {\n this.ctx.globalAlpha *= multiplier\n }\n translate(x: number, y: number) {\n this.ctx.translate(x, y)\n }\n scale(sx: number, sy: number) {\n this.ctx.scale(sx, sy)\n }\n transform(a: number, b: number, c: number, d: number, e: number, f: number) {\n this.ctx.transform(a, b, c, d, e, f)\n }\n\n /** Append a (rounded) rect sub-path to the current path — no beginPath, so callers can build\n * multi-subpath paths (e.g. an even-odd ring). */\n private addRectPath(rect: Rect, radius?: BorderRadius) {\n const ctx = this.ctx\n if (radius && (radius.tl || radius.tr || radius.br || radius.bl)) {\n ctx.roundRect(rect.x, rect.y, rect.width, rect.height, [radius.tl, radius.tr, radius.br, radius.bl])\n } else {\n ctx.rect(rect.x, rect.y, rect.width, rect.height)\n }\n }\n\n private path(rect: Rect, radius?: BorderRadius) {\n this.ctx.beginPath()\n this.addRectPath(rect, radius)\n }\n\n clipRoundRect(rect: Rect, radius?: BorderRadius) {\n this.path(rect, radius)\n this.ctx.clip()\n }\n\n fillRoundRect(rect: Rect, radius: BorderRadius | undefined, color: RGBA) {\n this.path(rect, radius)\n this.ctx.fillStyle = rgbaToCss(color)\n this.ctx.fill()\n }\n\n clearRoundRect(rect: Rect, radius: BorderRadius | undefined) {\n const ctx = this.ctx\n ctx.save()\n ctx.globalCompositeOperation = \"destination-out\"\n ctx.globalAlpha = 1\n this.path(rect, radius)\n ctx.fillStyle = \"#000\"\n ctx.fill()\n ctx.restore()\n }\n\n fillGradient(rect: Rect, radius: BorderRadius | undefined, gradient: Gradient) {\n if (gradient.type === \"radial\") {\n this.fillRadial(rect, radius, gradient)\n return\n }\n const { x0, y0, x1, y1 } = gradientLine(gradient.angle, rect)\n const grad = this.ctx.createLinearGradient(x0, y0, x1, y1)\n for (const stop of gradient.stops) grad.addColorStop(Math.max(0, Math.min(1, stop.position)), rgbaToCss(stop.color))\n this.path(rect, radius)\n this.ctx.fillStyle = grad\n this.ctx.fill()\n }\n\n private fillRadial(rect: Rect, radius: BorderRadius | undefined, gradient: RadialGradient) {\n const { cx, cy, rx, ry } = radialGeometry(gradient, rect)\n const ctx = this.ctx\n // createRadialGradient only makes circles; scale the context anisotropically so a unit-radius\n // circle becomes the rx×ry ellipse. Clip to the (rounded) rect first — the clip is captured in\n // the pre-scale space, so it stays put while we paint the ellipse in the scaled space.\n const sx = rx || 1e-6\n const sy = ry || 1e-6\n ctx.save()\n this.path(rect, radius)\n ctx.clip()\n ctx.translate(cx, cy)\n ctx.scale(sx, sy)\n const grad = ctx.createRadialGradient(0, 0, 0, 0, 0, 1)\n for (const stop of gradient.stops) grad.addColorStop(Math.max(0, Math.min(1, stop.position)), rgbaToCss(stop.color))\n ctx.fillStyle = grad\n // Cover the whole clipped rect in the scaled coordinate space (canvas extends the last stop\n // outward, so pixels past the ellipse edge get the final color, matching CSS).\n const u0 = (rect.x - cx) / sx\n const u1 = (rect.x + rect.width - cx) / sx\n const v0 = (rect.y - cy) / sy\n const v1 = (rect.y + rect.height - cy) / sy\n ctx.fillRect(u0, v0, u1 - u0, v1 - v0)\n ctx.restore()\n }\n\n strokeBorder(rect: Rect, radius: BorderRadius | undefined, sides: Borders) {\n const ctx = this.ctx\n const present = ([\"top\", \"right\", \"bottom\", \"left\"] as const).filter((s) => sides[s])\n const uniform =\n present.length === 4 &&\n present.every((s) => sides[s]!.width === sides.top!.width && sides[s]!.color === sides.top!.color)\n\n if (uniform) {\n const w = sides.top!.width\n // Border-box: the border lies fully INSIDE rect. Fill the ring between the outer rounded-rect\n // and an inner rounded-rect inset by the border width (inner corner radius = outer − w), as an\n // even-odd fill. We do NOT use a centred ctx.stroke(): a stroke straddles the path (half would\n // sit outside the box), and the inset-path trick relied on roundRect clamping its radius — which\n // @napi-rs/canvas (skia) does differently than browsers, so the border leaked outside the box.\n const outer = clampRadius(radius, rect)\n ctx.beginPath()\n this.addRectPath(rect, outer)\n const inner: Rect = { x: rect.x + w, y: rect.y + w, width: rect.width - 2 * w, height: rect.height - 2 * w }\n if (inner.width > 0 && inner.height > 0) {\n const innerRadius = outer && clampRadius(\n {\n tl: Math.max(0, outer.tl - w), tr: Math.max(0, outer.tr - w),\n br: Math.max(0, outer.br - w), bl: Math.max(0, outer.bl - w),\n },\n inner,\n )\n this.addRectPath(inner, innerRadius || undefined)\n }\n ctx.fillStyle = rgbaToCss(sides.top!.color)\n ctx.fill(\"evenodd\")\n return\n }\n\n // Per-side fallback: straight edges (radius ignored for mismatched borders).\n for (const s of present) {\n const { width, color } = sides[s]!\n ctx.fillStyle = rgbaToCss(color)\n if (s === \"top\") ctx.fillRect(rect.x, rect.y, rect.width, width)\n else if (s === \"bottom\") ctx.fillRect(rect.x, rect.y + rect.height - width, rect.width, width)\n else if (s === \"left\") ctx.fillRect(rect.x, rect.y, width, rect.height)\n else ctx.fillRect(rect.x + rect.width - width, rect.y, width, rect.height)\n }\n }\n\n private scratch?: OffscreenCanvas | HTMLCanvasElement\n private scratchCtx?: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D\n private getScratch(w: number, h: number) {\n if (!this.scratch) {\n this.scratch = typeof OffscreenCanvas !== \"undefined\" ? new OffscreenCanvas(w, h) : document.createElement(\"canvas\")\n this.scratchCtx = (this.scratch as any).getContext(\"2d\")\n }\n if (this.scratch.width < w || this.scratch.height < h) {\n this.scratch.width = Math.max(this.scratch.width, w)\n this.scratch.height = Math.max(this.scratch.height, h)\n }\n return this.scratchCtx!\n }\n\n drawImage(image: ImageInfo, srcRect: Rect | null, dst: Rect, opts: DrawImageOpts) {\n if (!image.handle) return\n // An explicit crop fills the box; otherwise resolve object-fit.\n const { src, dst: d } = srcRect\n ? { src: srcRect, dst }\n : computeObjectFit(image.naturalWidth, image.naturalHeight, dst, opts.fit)\n // The destination in DEVICE pixels: what a vector source rasterizes at, and the tint scratch's\n // size — the frame is painted under the dpr transform, so a CSS-px scratch would be upscaled.\n const dw = Math.max(1, Math.ceil(d.width * this.dpr))\n const dh = Math.max(1, Math.ceil(d.height * this.dpr))\n const handle = (image.rasterize ? image.rasterize(dw, dh) : image.handle) as CanvasImageSource\n\n // When we're drawing the WHOLE image (no atlas crop, not a cover-crop) draw it WITHOUT a source\n // rect. A viewBox-only SVG `<img>` has the browser's default 300×150 raster, so a source crop\n // (computed from the viewBox size) samples the wrong region and the icon vanishes — drawing the\n // whole image straight into the box lets the backend re-rasterize the SVG to fit (matches the DOM,\n // and keeps the working tinted/scratch path consistent with the direct path).\n const whole = !srcRect && opts.fit !== \"cover\"\n\n if (opts.tint === undefined) {\n if (whole) this.ctx.drawImage(handle, d.x, d.y, d.width, d.height)\n else this.ctx.drawImage(handle, src.x, src.y, src.width, src.height, d.x, d.y, d.width, d.height)\n return\n }\n // Tint on an offscreen so `source-in` only recolors the image pixels.\n const sc = this.getScratch(dw, dh)\n sc.clearRect(0, 0, dw, dh)\n sc.globalCompositeOperation = \"source-over\"\n if (whole) sc.drawImage(handle, 0, 0, dw, dh)\n else sc.drawImage(handle, src.x, src.y, src.width, src.height, 0, 0, dw, dh)\n sc.globalCompositeOperation = \"source-in\"\n sc.fillStyle = rgbaToCss(opts.tint)\n sc.fillRect(0, 0, dw, dh)\n sc.globalCompositeOperation = \"source-over\"\n this.ctx.drawImage(sc.canvas as CanvasImageSource, 0, 0, dw, dh, d.x, d.y, d.width, d.height)\n }\n\n fillText(text: string, x: number, baselineY: number, font: FontSpec, color: RGBA) {\n const ctx = this.ctx\n ctx.font = `${font.italic ? \"italic \" : \"\"}${font.weight} ${font.size}px ${font.family}`\n ctx.textBaseline = \"alphabetic\"\n ctx.textAlign = \"left\"\n if (\"letterSpacing\" in ctx) (ctx as any).letterSpacing = `${font.letterSpacing}px`\n ctx.fillStyle = rgbaToCss(color)\n ctx.fillText(text, x, baselineY)\n }\n}\n","\n// Slots are addressed by id (their original index) and are never spliced — disposing a single\n// player nulls its slot so every other id stays valid. `releasePlayer` does the actual teardown.\n// Slot 0 stays empty: id 0 is the SDK's dead handle (sdk/src/core/pins.ts DEAD_HANDLE), and a\n// player with that id would never get its end-of-playback report.\nconst players: (HTMLVideoElement | HTMLAudioElement | null)[] = [null]\n\n// Looping is driven manually rather than through the element's native `loop` flag: a natively\n// looping element never fires \"ended\", so we could not signal each loop boundary. Instead we keep\n// the desired loop state per player, listen for \"ended\", invoke the SDK's finished callback, and —\n// when looping — rewind and replay ourselves. `onFinished` lets the SDK decide loopReached vs\n// completed based on its own loop flag.\nconst loopFlags: boolean[] = [false]\n\nconst attachFinished = (\n player: HTMLVideoElement | HTMLAudioElement,\n id: number,\n onFinished: () => void\n) => {\n player.addEventListener(\"ended\", () => {\n onFinished()\n if (loopFlags[id]) {\n player.currentTime = 0\n player.play()\n }\n })\n}\n\nexport const createVideoPlayer = (src: string, onFinished: () => void) => {\n const player = document.createElement(\"video\")\n document.body.appendChild(player)\n player.crossOrigin = \"anonymous\"\n player.style = \"opacity: 0; position: absolute; top: 0; left: 0; width: 1px; height: 1px\"\n player.src = src\n player.playsInline = true\n player.controls = false\n const id = players.length\n players.push(player)\n loopFlags.push(false)\n attachFinished(player, id, onFinished)\n return id\n}\n\nexport const createAudioPlayer = (src: string, onFinished: () => void) => {\n const player = document.createElement(\"audio\")\n document.body.appendChild(player)\n player.style = \"opacity: 0; position: absolute; top: 0; left: 0; width: 1px; height: 1px\"\n player.src = src\n const id = players.length\n players.push(player)\n loopFlags.push(false)\n attachFinished(player, id, onFinished)\n return id\n}\n\nexport const updateMediaPlayerVolume = (id: number, volume: number) => {\n const player = players[id]\n if (!player) return\n if (volume === 0) {\n player.muted = true\n } else {\n if (player.muted) {\n player.muted = false\n }\n player.volume = volume\n }\n}\n\nexport const updateMediaPlayerPlaying = (id: number, play: boolean) => {\n const player = players[id]\n if (!player) return\n if (play){\n player.play()\n } else {\n player.pause()\n }\n}\n\nexport const updateMediaPlayerLoop = (id: number, loop: boolean) => {\n // Tracked for the \"ended\" handler; the native loop flag stays off so \"ended\" keeps firing.\n loopFlags[id] = loop\n}\n\nexport const getMediaPlayerTime = (id: number) => {\n return players[id]?.currentTime ?? 0\n}\n\nexport const setMediaPlayerTime = (id: number, time: number) => {\n const player = players[id]\n if (player) player.currentTime = time\n}\n\nexport const getMediaPlayerDuration = (id: number) => {\n // NaN before metadata loads — normalise to 0 so callers get a clean number.\n const duration = players[id]?.duration ?? 0\n return isNaN(duration) ? 0 : duration\n}\n\nexport const getPlayer = (id: number) => {\n return players[id]\n}\n\n// Tear down one element's media pipeline (decoder, buffering, network) and detach it from the DOM.\nconst releasePlayer = (player: HTMLVideoElement | HTMLAudioElement) => {\n // Removing the element from the DOM alone keeps the media pipeline alive. Pause, drop the source\n // and load() to release it before detaching.\n player.pause()\n player.removeAttribute(\"src\")\n player.load()\n player.remove()\n}\n\nexport const removeMediaPlayer = (id: number) => {\n const player = players[id]\n if (!player) return\n releasePlayer(player)\n // Null the slot rather than splice, so all other ids keep pointing at the right element.\n players[id] = null\n loopFlags[id] = false\n}\n\nexport const removePlayers = () => {\n for (let player of players) {\n if (player) releasePlayer(player)\n }\n players.length = 1 // keep the reserved slot 0\n loopFlags.length = 1\n}\n","// The SDK's side of the tree of truth (docs/plans/hosts-unification-plan.md, phase 9): the numbers shared\n// with runtime/native (creator-pkg/tree-events.h — mirrored VERBATIM, `bun run check:tree-consts`),\n// the pin table that keeps the element of every attached node alive and findable by id, the\n// destination registry, and the ONE emitter every event of `_creatorTree` comes through.\n//\n// Ownership (tree.h): an attached node belongs to the runtime's tree and its element is PINNED here\n// (so `children` returns the same objects and listeners survive the app dropping its reference); a\n// detached root belongs to its element — when that is collected, the handle's finalizer frees the\n// node. The runtime tells us when it detaches a root (TREE_EVENT_DETACHED) or frees nodes underneath\n// their handles (TREE_EVENT_FREED); everything else we pin / unpin ourselves.\n\n// ---- emit kinds (id = the node, 0 for world-level events) ----------------------------------------\nexport const TREE_EVENT_LAYOUT = 1\nexport const TREE_EVENT_TOUCH_START = 2\nexport const TREE_EVENT_CLICK = 3\nexport const TREE_EVENT_LONG_PRESS = 4\nexport const TREE_EVENT_TOUCH_MOVE = 5\nexport const TREE_EVENT_TOUCH_END = 6\nexport const TREE_EVENT_TOUCH_CANCEL = 7\nexport const TREE_EVENT_SCROLL = 8\nexport const TREE_EVENT_OVERSCROLL = 9\nexport const TREE_EVENT_SCROLL_RELEASE = 10\nexport const TREE_EVENT_REFRESH = 11\nexport const TREE_EVENT_CHANGE = 12\nexport const TREE_EVENT_FOCUS = 13\nexport const TREE_EVENT_BLUR = 14\nexport const TREE_EVENT_SUBMIT = 15\nexport const TREE_EVENT_OVERLAY_TAP = 16\nexport const TREE_EVENT_DETENT = 17\nexport const TREE_EVENT_OPEN = 18\nexport const TREE_EVENT_CLOSE = 19\nexport const TREE_EVENT_BACK = 20\nexport const TREE_EVENT_PAGER_SELECT = 21\nexport const TREE_EVENT_PAGER_POP = 22\nexport const TREE_EVENT_VLIST_SYNC = 23\nexport const TREE_EVENT_VLIST_EDGE = 24\nexport const TREE_EVENT_VIEW_EVENT = 25\nexport const TREE_EVENT_RESIZE = 26\nexport const TREE_EVENT_ROUTER_CHANGE = 27\nexport const TREE_EVENT_SCENE_TOUCH_START = 28\nexport const TREE_EVENT_SCENE_CLICK = 29\nexport const TREE_EVENT_DETACHED = 30\nexport const TREE_EVENT_FREED = 31\nexport const TREE_EVENT_HOVER_ENTER = 32\nexport const TREE_EVENT_HOVER_MOVE = 33\nexport const TREE_EVENT_HOVER_END = 34\nexport const TREE_EVENT_HOVER_CANCEL = 35\n\n// ---- setFlags(id, mask) ---------------------------------------------------------------------------\nexport const TREE_FLAG_INTERACTIVE = 1 << 0\nexport const TREE_FLAG_CLICK = 1 << 1\nexport const TREE_FLAG_LONG_PRESS = 1 << 2\nexport const TREE_FLAG_LAYOUT = 1 << 3\nexport const TREE_FLAG_SCROLL = 1 << 4\nexport const TREE_FLAG_OVERSCROLL = 1 << 5\nexport const TREE_FLAG_SCROLL_RELEASE = 1 << 6\nexport const TREE_FLAG_REFRESH = 1 << 7\nexport const TREE_FLAG_CHANGE = 1 << 8\nexport const TREE_FLAG_FOCUS = 1 << 9\nexport const TREE_FLAG_BLUR = 1 << 10\nexport const TREE_FLAG_SUBMIT = 1 << 11\nexport const TREE_FLAG_OVERLAY_TAP = 1 << 12\nexport const TREE_FLAG_DETENT = 1 << 13\nexport const TREE_FLAG_KEEP_ALIVE = 1 << 14\nexport const TREE_FLAG_BACK = 1 << 15\nexport const TREE_FLAG_VLIST_END = 1 << 16\nexport const TREE_FLAG_VLIST_START = 1 << 17\nexport const TREE_FLAG_HOVER = 1 << 18\n\n// ---- the touchStart / longPress answer -------------------------------------------------------------\nexport const TREE_TRACK_CLAIM_MASK = 0xFF\nexport const TREE_TRACK_TRACKED = 1 << 8\nexport const TREE_TRACK_MOVE = 1 << 9\nexport const TREE_TRACK_HANDLED = 1 << 10\n\n// ---- destination kinds -------------------------------------------------------------------------------\nexport const TREE_DEST_SCREEN = 0\nexport const TREE_DEST_SCENE3D = 1\nexport const TREE_DEST_SCENE2D = 2\nexport const TREE_DEST_NATIVE = 3\nexport const TREE_DEST_VIDEO = 4\nexport const TREE_DEST_NONE = 0xFF\n\n// Owned-handle kinds (owned.h OwnedKind) — the `_creatorApp.setFreedEmitter` channel names the kind\n// whose resources the runtime freed underneath their wrappers (core/pins.ts).\nexport const OWNED_KIND_TREE = 0\nexport const OWNED_KIND_FETCH = 1\nexport const OWNED_KIND_GL_MATERIAL = 2\nexport const OWNED_KIND_GL_TEXTURE = 3\nexport const OWNED_KIND_GL_ENTITY = 4\nexport const OWNED_KIND_ENTITY_2D = 5\nexport const OWNED_KIND_MEDIA = 6\nexport const OWNED_KIND_TWEEN = 7\nexport const OWNED_KIND_CANVAS = 8\n\n// PanDirection (creator-pkg.h) — the low byte of a track answer.\nimport { DEAD_HANDLE } from \"../core/pins\"\n\nconst PAN: Record<string, number> = { \"pan-up\": 1, \"pan-right\": 2, \"pan-down\": 4, \"pan-left\": 8, \"pan-x\": 10, \"pan-y\": 5 }\n\n// ---- the bridge ---------------------------------------------------------------------------------------\n/** @internal The tree bridge. Every host that runs bundles installs it before the bundle evaluates. */\nexport const tree = (): typeof _creatorTree => _creatorTree\n\n// ---- what an element / presentable must offer the emitter (duck-typed, all `_`-prefixed so chisel keeps them)\n/** @internal */\nexport interface TreeElement {\n /** The owned handle (`_h.id` = the node id; DEAD_HANDLE once the node is gone). */\n _h: Handle\n _emitLayout?(box: { left: number, top: number, width: number, height: number }): void\n _emitTouchStart?(pointerId: number, x: number, y: number): TrackLike | null\n _emitClick?(pointerId: number, x: number, y: number): void\n _emitLongPress?(pointerId: number, x: number, y: number): { track: TrackLike | null } | null\n _emitMouseEnter?(x: number, y: number): HoverTrackLike | null\n _emitScroll?(position: number): void\n _emitOverscroll?(delta: number): void\n _emitScrollRelease?(): void\n _emitRefresh?(): unknown\n _emitChange?(value: string): void\n _emitFocus?(): void\n _emitBlur?(): void\n _emitSubmit?(value: string): void\n _emitOverlayTap?(): void\n _emitDetent?(index: number): void\n _hostDidSelect?(index: number): void\n _hostDidPop?(depth: number): void\n _syncWindow?(unmountKeys: string[], mountKeys: string[]): void\n _emitEdge?(end: boolean): void\n _detached?(): void\n _freed?(): void\n /** The element's node got a native owner (it was inserted under a parent) / lost it. */\n _pinned?(): void\n _unpinned?(): void\n _emitBack?(): boolean\n}\n\n/** @internal A track handler (runtime/touch.ts TrackHandler), as the emitter reads it. */\nexport interface TrackLike {\n onMove?(pos: { clientX: number, clientY: number, deltaX: number, deltaY: number }): void\n onEnd?(pos: { clientX: number, clientY: number, deltaX: number, deltaY: number }): void\n onCancel?(): void\n claim?: boolean | string\n}\n/** @internal A hover track handler (runtime/touch.ts HoverTrackHandler): TrackLike without a claim. */\nexport type HoverTrackLike = Omit<TrackLike, \"claim\">\n\n/** @internal What a destination offers: the presentation lifecycle + the back handler. */\nexport interface TreeDest {\n _emitOpen?(): void\n _emitClose?(): void\n _emitBack?(): boolean\n}\n\nexport { DEAD_HANDLE }\n\n// ---- pins -------------------------------------------------------------------------------------------------\nconst pins = new Map<number, TreeElement>()\n\n/** @internal Keep `el` alive and findable while its node is attached / presented / shown. */\nexport const pin = (el: TreeElement | null | undefined): void => {\n if (!el || el._h.id === 0) return\n pins.set(el._h.id, el)\n el._pinned?.()\n}\n/** @internal */\nexport const unpin = (id: number): void => {\n const el = pins.get(id)\n if (!el) return\n pins.delete(id)\n el._unpinned?.()\n}\n/** @internal The pinned element of a node id (an attached node's element), or undefined. */\nexport const byId = (id: number): TreeElement | undefined => pins.get(id)\n/** @internal The elements of a list of ids (attached nodes only). */\nexport const elementsOf = (ids: number[]): any[] => {\n const out: any[] = []\n for (const id of ids) { const el = pins.get(id); if (el) out.push(el) }\n return out\n}\n\n// ---- destinations ------------------------------------------------------------------------------------------\n// Non-screen presentables (scenes, native views) register here under their engine id; screens and\n// video nodes resolve through the pins (their destination id IS the node id).\nconst dests = new Map<string, TreeDest>()\nconst destKey = (kind: number, id: number): string => `${kind}:${id}`\n\n/** @internal */\nexport const registerDest = (kind: number, id: number, p: TreeDest): void => { dests.set(destKey(kind, id), p) }\n/** @internal */\nexport const unregisterDest = (kind: number, id: number): void => { dests.delete(destKey(kind, id)) }\n/** @internal The presentable a (kind, id) pair names. */\nexport const resolveDest = (kind: number, id: number): (TreeDest & Partial<TreeElement>) | undefined => {\n if (kind === TREE_DEST_SCREEN || kind === TREE_DEST_VIDEO) return pins.get(id) as any\n return dests.get(destKey(kind, id)) as any\n}\n\n// ---- world-level hooks (set by the modules that own them) --------------------------------------------------\ntype SceneTouchStart = (pointerId: number, x: number, y: number, entityId: number) => TrackLike | null\ntype SceneClick = (pointerId: number, x: number, y: number, entityId: number) => void\nlet sceneTouchStart: SceneTouchStart | null = null\nlet sceneClick: SceneClick | null = null\n/** @internal gl/touch.ts: the scene-level pointer dispatch. */\nexport const setSceneTouchHandlers = (start: SceneTouchStart | null, click: SceneClick | null): void => {\n sceneTouchStart = start\n sceneClick = click\n}\n\nconst resizeListeners: ((width: number, height: number) => void)[] = []\n/** @internal runtime/device.ts */\nexport const onTreeResize = (cb: (width: number, height: number) => void): (() => void) => {\n resizeListeners.push(cb)\n return () => { const i = resizeListeners.indexOf(cb); if (i >= 0) resizeListeners.splice(i, 1) }\n}\n\nlet routerChange: ((kind: number, id: number) => void) | null = null\n/** @internal ui/router.ts */\nexport const setRouterChangeHandler = (cb: ((kind: number, id: number) => void) | null): void => { routerChange = cb }\n\nlet appBack: (() => void) | null = null\n/** @internal runtime/app.ts — the app-level back handler (the end of the runtime's back chain). */\nexport const setAppBackHandler = (cb: (() => void) | null): void => { appBack = cb }\n\nconst nativeViews = new Map<number, { _emitViewEvent(event: string, data?: unknown): void }>()\n/** @internal ui/NativeView.ts: the instance a viewId names (host → view events). */\nexport const registerNativeView = (viewId: number, v: { _emitViewEvent(event: string, data?: unknown): void }): void => { nativeViews.set(viewId, v) }\n/** @internal */\nexport const unregisterNativeView = (viewId: number): void => { nativeViews.delete(viewId) }\n\n// ---- gestures -----------------------------------------------------------------------------------------------\n// The track handler of every pointer a listener claimed (`ev.track(...)`): the runtime feeds the\n// pointer's moves / end / cancel here by pointer id — nothing of it is retained natively.\nconst trackers = new Map<number, TrackLike>()\n\n// The hover's own slot — the cursor is one, and it is NOT a gesture: a mouse drag keeps its touch\n// tracker under pointer 0 while the hover under the same cursor runs here, independently.\nlet hoverTracker: HoverTrackLike | null = null\n\nconst hoverAnswer = (handler: HoverTrackLike | null | undefined): number => {\n hoverTracker = handler ?? null\n if (!handler) return 0\n return TREE_TRACK_TRACKED | (handler.onMove ? TREE_TRACK_MOVE : 0)\n}\n\nconst trackAnswer = (pointerId: number, handler: TrackLike | null | undefined): number => {\n if (!handler) return 0\n trackers.set(pointerId, handler)\n let r = TREE_TRACK_TRACKED\n if (handler.onMove) r |= TREE_TRACK_MOVE\n const claim = handler.claim\n if (claim === true || claim === \"all\") r |= 15\n else if (typeof claim === \"string\") r |= PAN[claim] ?? 0\n return r\n}\n\n// ---- the emitter --------------------------------------------------------------------------------------------\nlet installed = false\nconst emit = (id: number, kind: number, a?: any, b?: any, c?: any, d?: any, e?: any): any => {\n switch (kind) {\n case TREE_EVENT_LAYOUT: pins.get(id)?._emitLayout?.({ left: a, top: b, width: c, height: d }); return\n case TREE_EVENT_TOUCH_START: return trackAnswer(a, pins.get(id)?._emitTouchStart?.(a, b, c))\n case TREE_EVENT_CLICK: pins.get(id)?._emitClick?.(a, b, c); return\n case TREE_EVENT_LONG_PRESS: {\n const r = pins.get(id)?._emitLongPress?.(a, b, c)\n if (!r) return 0\n return TREE_TRACK_HANDLED | trackAnswer(a, r.track)\n }\n case TREE_EVENT_TOUCH_MOVE: trackers.get(a)?.onMove?.({ clientX: b, clientY: c, deltaX: d, deltaY: e }); return\n case TREE_EVENT_TOUCH_END: {\n const t = trackers.get(a)\n trackers.delete(a)\n t?.onEnd?.({ clientX: b, clientY: c, deltaX: d, deltaY: e })\n return\n }\n case TREE_EVENT_TOUCH_CANCEL: {\n const t = trackers.get(a)\n trackers.delete(a)\n t?.onCancel?.()\n return\n }\n case TREE_EVENT_HOVER_ENTER: return hoverAnswer(pins.get(id)?._emitMouseEnter?.(a, b))\n case TREE_EVENT_HOVER_MOVE: hoverTracker?.onMove?.({ clientX: a, clientY: b, deltaX: c, deltaY: d }); return\n case TREE_EVENT_HOVER_END: {\n const t = hoverTracker\n hoverTracker = null\n t?.onEnd?.({ clientX: a, clientY: b, deltaX: c, deltaY: d })\n return\n }\n case TREE_EVENT_HOVER_CANCEL: {\n const t = hoverTracker\n hoverTracker = null\n t?.onCancel?.()\n return\n }\n case TREE_EVENT_SCROLL: pins.get(id)?._emitScroll?.(a); return\n case TREE_EVENT_OVERSCROLL: pins.get(id)?._emitOverscroll?.(a); return\n case TREE_EVENT_SCROLL_RELEASE: pins.get(id)?._emitScrollRelease?.(); return\n case TREE_EVENT_REFRESH: return pins.get(id)?._emitRefresh?.()\n case TREE_EVENT_CHANGE: pins.get(id)?._emitChange?.(a); return\n case TREE_EVENT_FOCUS: pins.get(id)?._emitFocus?.(); return\n case TREE_EVENT_BLUR: pins.get(id)?._emitBlur?.(); return\n case TREE_EVENT_SUBMIT: pins.get(id)?._emitSubmit?.(a); return\n case TREE_EVENT_OVERLAY_TAP: pins.get(id)?._emitOverlayTap?.(); return\n case TREE_EVENT_DETENT: pins.get(id)?._emitDetent?.(a); return\n case TREE_EVENT_OPEN: resolveDest(a, b)?._emitOpen?.(); return\n case TREE_EVENT_CLOSE: resolveDest(a, b)?._emitClose?.(); return\n case TREE_EVENT_BACK: {\n if (a === TREE_DEST_NONE) {\n if (id !== 0) return pins.get(id)?._emitBack?.() === true // a widget\n if (!appBack) return false\n appBack()\n return true\n }\n return resolveDest(a, b)?._emitBack?.() === true\n }\n case TREE_EVENT_PAGER_SELECT: pins.get(id)?._hostDidSelect?.(a); return\n case TREE_EVENT_PAGER_POP: pins.get(id)?._hostDidPop?.(a); return\n case TREE_EVENT_VLIST_SYNC: pins.get(id)?._syncWindow?.(a, b); return\n case TREE_EVENT_VLIST_EDGE: pins.get(id)?._emitEdge?.(!!a); return\n case TREE_EVENT_VIEW_EVENT: nativeViews.get(a)?._emitViewEvent(b, c); return\n case TREE_EVENT_RESIZE: for (const cb of resizeListeners.slice()) cb(a, b); return\n case TREE_EVENT_ROUTER_CHANGE: routerChange?.(a, b); return\n case TREE_EVENT_SCENE_TOUCH_START: return trackAnswer(a, sceneTouchStart?.(a, b, c, d))\n case TREE_EVENT_SCENE_CLICK: sceneClick?.(a, b, c, d); return\n case TREE_EVENT_DETACHED: {\n const el = pins.get(id)\n pins.delete(id)\n el?._detached?.()\n return\n }\n case TREE_EVENT_FREED: {\n for (const fid of a as number[]) {\n const el = pins.get(fid)\n pins.delete(fid)\n el?._freed?.()\n }\n return\n }\n }\n}\n\n/** @internal Install the emitter once per world (the first element / presentable calls it). */\nexport const ensureEmitter = (): void => {\n if (installed) return\n installed = true\n _creatorTree.setEmitter(emit)\n}\n","import type { RenderNode } from \"../types\"\n\nfunction contains(node: RenderNode, x: number, y: number): boolean {\n const r = node.rect\n return x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height\n}\n\n/**\n * Find the topmost node satisfying `accept` (e.g. interactive) under a point. Walks in paint order\n * and returns the last match — later siblings and deeper children paint on top, so they win, which\n * matches the DOM event-bubbling target the worker buttons expect.\n */\nexport function hitTest(\n root: RenderNode,\n x: number,\n y: number,\n accept: (node: RenderNode) => boolean,\n): RenderNode | null {\n let found: RenderNode | null = null\n const walk = (node: RenderNode) => {\n const inside = contains(node, x, y)\n if (inside && accept(node)) found = node\n // A clipping node (scrollable / overflow:hidden) hides children outside its rect — so a child\n // scrolled out of view isn't hittable, matching the DOM's overflow clipping.\n if (node.clip && !inside) return\n for (const child of node.children) walk(child)\n }\n walk(root)\n return found\n}\n","// AUTO-GENERATED from engines/ui/properties.mjs — DO NOT EDIT. Regenerate: bun run gen:ui-props\n//\n// The CUIPaint record layout (engines/ui/include/creator-ui/paint.gen.h) for a reader over the wasm\n// heap: `HEAPU32[(ptr >> 2) + word]` / `HEAPF32[...]`. Bits index the present / dirty masks\n// (two u32 words each: lo at word 0 / 2, hi at word 1 / 3).\n\nexport const CUI_PAINT_WORDS = 78\nexport const CUI_PRESENT_LO = 0, CUI_PRESENT_HI = 1, CUI_DIRTY_LO = 2, CUI_DIRTY_HI = 3\nexport const CUI_INHERIT_MASK_LO = 4096, CUI_INHERIT_MASK_HI = 4080\nexport const CUI_MEASURE_MASK_LO = 0, CUI_MEASURE_MASK_HI = 5104 // a dirty measure field re-measures a text leaf\n\nexport type CuiKind = \"float\" | \"color\" | \"enum\" | \"str\" | \"matrix\" | \"origin\" | \"gradient\"\n\nexport const CUI_FIELDS = {\n display: { bit: 0, word: 4, kind: \"enum\" },\n overflow: { bit: 1, word: 5, kind: \"enum\" },\n scrollDirection: { bit: 2, word: 6, kind: \"enum\" },\n borderWidth: { bit: 3, word: 7, kind: \"float\" },\n borderTopWidth: { bit: 4, word: 8, kind: \"float\" },\n borderRightWidth: { bit: 5, word: 9, kind: \"float\" },\n borderBottomWidth: { bit: 6, word: 10, kind: \"float\" },\n borderLeftWidth: { bit: 7, word: 11, kind: \"float\" },\n borderHorizontalWidth: { bit: 8, word: 12, kind: \"float\" },\n borderVerticalWidth: { bit: 9, word: 13, kind: \"float\" },\n borderStartWidth: { bit: 10, word: 14, kind: \"float\" },\n borderEndWidth: { bit: 11, word: 15, kind: \"float\" },\n color: { bit: 12, word: 16, kind: \"color\" },\n backgroundColor: { bit: 13, word: 17, kind: \"color\" },\n borderColor: { bit: 14, word: 18, kind: \"color\" },\n borderTopColor: { bit: 15, word: 19, kind: \"color\" },\n borderRightColor: { bit: 16, word: 20, kind: \"color\" },\n borderBottomColor: { bit: 17, word: 21, kind: \"color\" },\n borderLeftColor: { bit: 18, word: 22, kind: \"color\" },\n placeholderColor: { bit: 19, word: 23, kind: \"color\" },\n refreshControlColor: { bit: 20, word: 24, kind: \"color\" },\n tintColor: { bit: 21, word: 25, kind: \"color\" },\n rippleColor: { bit: 22, word: 26, kind: \"color\" },\n overlayColor: { bit: 23, word: 27, kind: \"color\" },\n backgroundImage: { bit: 24, word: 28, kind: \"str\" },\n backgroundSize: { bit: 25, word: 29, kind: \"enum\" },\n backgroundGradient: { bit: 26, word: 30, kind: \"gradient\" },\n borderRadius: { bit: 27, word: 31, kind: \"float\" },\n borderTopLeftRadius: { bit: 28, word: 32, kind: \"float\" },\n borderTopRightRadius: { bit: 29, word: 33, kind: \"float\" },\n borderBottomRightRadius: { bit: 30, word: 34, kind: \"float\" },\n borderBottomLeftRadius: { bit: 31, word: 35, kind: \"float\" },\n opacity: { bit: 32, word: 36, kind: \"float\" },\n transform: { bit: 33, word: 37, kind: \"matrix\" },\n transformOrigin: { bit: 34, word: 46, kind: \"origin\" },\n pointerEvents: { bit: 35, word: 50, kind: \"enum\" },\n fontSize: { bit: 36, word: 51, kind: \"float\" },\n fontWeight: { bit: 37, word: 52, kind: \"float\" },\n fontStyle: { bit: 38, word: 53, kind: \"enum\" },\n fontFamily: { bit: 39, word: 54, kind: \"str\" },\n lineHeight: { bit: 40, word: 55, kind: \"float\" },\n letterSpacing: { bit: 41, word: 56, kind: \"float\" },\n textAlign: { bit: 42, word: 57, kind: \"enum\" },\n textDecoration: { bit: 43, word: 58, kind: \"enum\" },\n lineClamp: { bit: 44, word: 59, kind: \"float\" },\n textOverflow: { bit: 45, word: 60, kind: \"enum\" },\n objectFit: { bit: 46, word: 61, kind: \"enum\" },\n placeholder: { bit: 47, word: 62, kind: \"str\" },\n type: { bit: 48, word: 63, kind: \"enum\" },\n enterKey: { bit: 49, word: 64, kind: \"enum\" },\n autocapitalize: { bit: 50, word: 65, kind: \"enum\" },\n autocorrect: { bit: 51, word: 66, kind: \"float\" },\n maxLength: { bit: 52, word: 67, kind: \"float\" },\n keyboardShrink: { bit: 53, word: 68, kind: \"float\" },\n keyboardDismiss: { bit: 54, word: 69, kind: \"float\" },\n showScrollbar: { bit: 55, word: 70, kind: \"float\" },\n overscrollMode: { bit: 56, word: 71, kind: \"enum\" },\n keyboardDismissMode: { bit: 57, word: 72, kind: \"enum\" },\n snap: { bit: 58, word: 73, kind: \"enum\" },\n sheetDetents: { bit: 59, word: 74, kind: \"str\" },\n sheetDetent: { bit: 60, word: 75, kind: \"float\" },\n sheetDismissible: { bit: 61, word: 76, kind: \"float\" },\n dim: { bit: 62, word: 77, kind: \"float\" },\n} as const satisfies Record<string, { bit: number, word: number, kind: CuiKind }>\n\nexport type CuiFieldKey = keyof typeof CUI_FIELDS\n\nexport const CuiDisplay = { \"flex\": 0, \"none\": 1 } as const\nexport const CuiOverflow = { \"visible\": 0, \"hidden\": 1, \"scroll\": 2 } as const\nexport const CuiScrollDirection = { \"vertical\": 0, \"horizontal\": 1, \"all\": 2 } as const\nexport const CuiBackgroundSize = { \"cover\": 0, \"contain\": 1, \"fill\": 2, \"tile\": 3 } as const\nexport const CuiPointerEvents = { \"all\": 0, \"none\": 1 } as const\nexport const CuiFontStyle = { \"normal\": 0, \"italic\": 1 } as const\nexport const CuiTextAlign = { \"start\": 0, \"center\": 1, \"end\": 2, \"left\": 3, \"right\": 4 } as const\nexport const CuiTextDecoration = { \"underline\": 0, \"line-through\": 1, \"none\": 2 } as const\nexport const CuiTextOverflow = { \"ellipsis\": 0, \"clip\": 1 } as const\nexport const CuiObjectFit = { \"cover\": 0, \"contain\": 1, \"fill\": 2 } as const\nexport const CuiType = { \"text\": 0, \"password\": 1, \"tel\": 2, \"email\": 3, \"number\": 4, \"decimal\": 5, \"url\": 6, \"search\": 7, \"date\": 8, \"time\": 9 } as const\nexport const CuiEnterKey = { \"done\": 0, \"go\": 1, \"next\": 2, \"search\": 3, \"send\": 4 } as const\nexport const CuiAutocapitalize = { \"none\": 0, \"sentences\": 1, \"words\": 2, \"characters\": 3 } as const\nexport const CuiOverscrollMode = { \"default\": 0, \"none\": 1, \"absorb\": 2 } as const\nexport const CuiKeyboardDismissMode = { \"interactive\": 0, \"scroll\": 1, \"none\": 2 } as const\nexport const CuiSnap = { \"none\": 0, \"start\": 1, \"center\": 2, \"end\": 3 } as const\n\n/** The registry spelling of each enum code, by field. */\nexport const CUI_NAMES = {\n display: [\"flex\", \"none\"],\n overflow: [\"visible\", \"hidden\", \"scroll\"],\n scrollDirection: [\"vertical\", \"horizontal\", \"all\"],\n backgroundSize: [\"cover\", \"contain\", \"fill\", \"tile\"],\n pointerEvents: [\"all\", \"none\"],\n fontStyle: [\"normal\", \"italic\"],\n textAlign: [\"start\", \"center\", \"end\", \"left\", \"right\"],\n textDecoration: [\"underline\", \"line-through\", \"none\"],\n textOverflow: [\"ellipsis\", \"clip\"],\n objectFit: [\"cover\", \"contain\", \"fill\"],\n type: [\"text\", \"password\", \"tel\", \"email\", \"number\", \"decimal\", \"url\", \"search\", \"date\", \"time\"],\n enterKey: [\"done\", \"go\", \"next\", \"search\", \"send\"],\n autocapitalize: [\"none\", \"sentences\", \"words\", \"characters\"],\n overscrollMode: [\"default\", \"none\", \"absorb\"],\n keyboardDismissMode: [\"interactive\", \"scroll\", \"none\"],\n snap: [\"none\", \"start\", \"center\", \"end\"],\n} as const\n\n/** present / dirty bit test on the (lo, hi) word pair. */\nexport const cuiBit = (lo: number, hi: number, bit: number): boolean =>\n bit < 32 ? ((lo >>> bit) & 1) === 1 : ((hi >>> (bit - 32)) & 1) === 1\n","import type { Gradient, GradientStop, RadialExtent } from \"../../types\"\n\n// Decodes the creator-ui CUIGradient struct (creator-ui/include/creator-ui/creator-ui.h) out of the\n// wasm heap. wasm32 layout, all fields 4-byte aligned:\n// CUIGradient { float angle@0; u32 type@4; u32 stopCount@8; u32 _pad@12; CUIGradientStop* stops@16;\n// u32 shape@20; u32 extent@24; float cx@28; float cy@32;\n// float rx@36; float ry@40; u32 rUnitX@44; u32 rUnitY@48 }\n// CUIGradientStop { u32 color@0; float position@4 } (8 bytes, tightly packed)\n// The radial fields are appended AFTER the 4-byte `stops` pointer, so the linear prefix\n// (angle/type/stopCount/stops) is byte-identical to before. `color` is COLOR_FORMAT = 0xRRGGBBAA on\n// web (== our RGBA), so no conversion is needed. extent == 4 means explicit rx/ry (rUnit 0 = px, 1 =\n// box-axis fraction). Pure (takes heap views) so it can be unit-tested with a synthetic buffer.\n\nconst EXTENTS: RadialExtent[] = [\"farthest-corner\", \"closest-side\", \"closest-corner\", \"farthest-side\"]\n\n// sizeof(CUIGradient) on wasm32 (13 × 4-byte fields), pinned by a static_assert in gradient.h. The\n// multi-layer handler hands us a pointer to `count` of these laid out back-to-back.\nconst CUI_GRADIENT_STRIDE = 52\n\n/** Decode a `count`-long CUIGradient array (the background-image layer stack, [0] = topmost). */\nexport function readGradientStructs(f32: Float32Array, u32: Uint32Array, ptr: number, count: number): Gradient[] {\n const out: Gradient[] = []\n for (let k = 0; k < count; k++) out.push(readGradientStruct(f32, u32, ptr + k * CUI_GRADIENT_STRIDE))\n return out\n}\n\nexport function readGradientStruct(f32: Float32Array, u32: Uint32Array, ptr: number): Gradient {\n const i = ptr >> 2\n const angle = f32[i]\n const type = u32[i + 1]\n const stopCount = u32[i + 2]\n const stopsPtr = u32[i + 4]\n\n const stops: GradientStop[] = []\n for (let s = 0; s < stopCount; s++) {\n const b = (stopsPtr + s * 8) >> 2\n stops.push({ color: u32[b] >>> 0, position: f32[b + 1] })\n }\n\n if (type === 1) {\n const extentCode = u32[i + 6]\n const base = {\n type: \"radial\" as const,\n shape: (u32[i + 5] === 1 ? \"circle\" : \"ellipse\") as \"circle\" | \"ellipse\",\n cx: f32[i + 7],\n cy: f32[i + 8],\n stops,\n }\n if (extentCode === 4) {\n return {\n ...base,\n extent: \"explicit\",\n rx: f32[i + 9],\n ry: f32[i + 10],\n rxUnit: u32[i + 11] === 1 ? \"fraction\" : \"px\",\n ryUnit: u32[i + 12] === 1 ? \"fraction\" : \"px\",\n }\n }\n return { ...base, extent: EXTENTS[extentCode] ?? \"farthest-corner\" }\n }\n return { type: \"linear\", angle, stops }\n}\n","// The paint state reader (creator-ui/paint.gen.h, CuiPaint.gen.ts): the runtime keeps one resolved\n// paint record per node; this renderer READS it — the dirty records `_paintCollect` hands out once\n// per frame, or a node's record in place (`_cuiPaintOf`) whenever it measures. The per-prop style\n// handlers this file replaced (2026-09-24) wrote the same ResolvedStyle field by field; here one\n// record write fills it, and the text style arrives EFFECTIVE (the core inherits), so no ancestor\n// walk remains anywhere in the renderer.\nimport type { ResolvedStyle } from \"../../types\"\nimport { CUI_FIELDS, CUI_NAMES, CUI_PAINT_WORDS, CuiFontStyle, CuiOverflow, CuiScrollDirection, cuiBit } from \"../CuiPaint.gen\"\nimport { readGradientStructs } from \"./readGradient\"\n\n/** The wasm module surface the reader needs (a subset of CreatorUiModule). */\nexport interface PaintModule {\n HEAPF32: Float32Array\n HEAPU32: Uint32Array\n UTF8ToString(ptr: number): string\n _malloc(size: number): number\n _paintCollect(): number\n _paintNodes(): number\n _paintRecords(): number\n _cuiPaintOf(nodePtr: number): number\n _cuiStringOf(id: number): number\n _cuiGradientOf(id: number, outCountPtr: number): number\n}\n\nconst F = CUI_FIELDS\nconst ALIGN: ResolvedStyle[\"textAlign\"][] = [\"start\", \"center\", \"end\", \"start\", \"end\"] // start center end left right\n\nlet countPtr = 0\n\n/** Read the record at `ptr` (a word-aligned CUIPaint) into `style`. */\nexport function readPaintRecord(M: PaintModule, ptr: number, style: ResolvedStyle): void {\n const u32 = M.HEAPU32, f32 = M.HEAPF32\n const w = ptr >>> 2\n const presentLo = u32[w], presentHi = u32[w + 1]\n const has = (bit: number) => cuiBit(presentLo, presentHi, bit)\n const str = (word: number): string | undefined => {\n const id = u32[w + word]\n return id === 0 ? undefined : M.UTF8ToString(M._cuiStringOf(id))\n }\n\n // box\n style.backgroundColor = u32[w + F.backgroundColor.word] >>> 0\n style.opacity = f32[w + F.opacity.word]\n style.dim = f32[w + F.dim.word]\n style.display = CUI_NAMES.display[u32[w + F.display.word]]\n style.overflow = u32[w + F.overflow.word] === CuiOverflow.hidden ? \"hidden\" : \"visible\"\n style.scrollAxis = u32[w + F.scrollDirection.word] === CuiScrollDirection.horizontal ? \"x\" : \"y\"\n // borders: the core fans borderWidth / borderColor out into the four sides (paint.cpp)\n style.border = {\n top: { width: f32[w + F.borderTopWidth.word], color: u32[w + F.borderTopColor.word] >>> 0 },\n right: { width: f32[w + F.borderRightWidth.word], color: u32[w + F.borderRightColor.word] >>> 0 },\n bottom: { width: f32[w + F.borderBottomWidth.word], color: u32[w + F.borderBottomColor.word] >>> 0 },\n left: { width: f32[w + F.borderLeftWidth.word], color: u32[w + F.borderLeftColor.word] >>> 0 },\n }\n style.borderRadius = {\n tl: f32[w + F.borderTopLeftRadius.word], tr: f32[w + F.borderTopRightRadius.word],\n br: f32[w + F.borderBottomRightRadius.word], bl: f32[w + F.borderBottomLeftRadius.word],\n }\n // background layers\n style.backgroundImage = str(F.backgroundImage.word)\n style.backgroundSize = CUI_NAMES.backgroundSize[u32[w + F.backgroundSize.word]] as ResolvedStyle[\"backgroundSize\"]\n const gradientId = u32[w + F.backgroundGradient.word]\n if (gradientId === 0) style.backgroundGradients = undefined\n else {\n if (countPtr === 0) countPtr = M._malloc(4)\n const gp = M._cuiGradientOf(gradientId, countPtr)\n const count = M.HEAPU32[countPtr >>> 2]\n style.backgroundGradients = gp !== 0 && count > 0 ? readGradientStructs(M.HEAPF32, M.HEAPU32, gp, count) : undefined\n }\n // transform: the 2D affine [a,b,c,d,e,f] of the 3x3 (column-major m0 m1 m3 m4 m6 m7); identity = absent\n const t = w + F.transform.word\n const a = f32[t], b = f32[t + 1], c = f32[t + 3], d = f32[t + 4], e = f32[t + 6], f = f32[t + 7]\n style.transform = a === 1 && b === 0 && c === 0 && d === 1 && e === 0 && f === 0 ? undefined : [a, b, c, d, e, f]\n const o = w + F.transformOrigin.word\n style.transformOrigin = { x: f32[o], y: f32[o + 1], xPercent: u32[o + 2] !== 0, yPercent: u32[o + 3] !== 0 }\n\n // text (effective; absent = the renderer default — core/text.ts DEFAULTS)\n style.color = has(F.color.bit) ? u32[w + F.color.word] >>> 0 : undefined\n style.fontFamily = has(F.fontFamily.bit) ? str(F.fontFamily.word) : undefined\n style.fontSize = f32[w + F.fontSize.word]\n style.fontWeight = f32[w + F.fontWeight.word]\n style.fontStyle = u32[w + F.fontStyle.word] === CuiFontStyle.italic ? \"italic\" : \"normal\"\n style.lineHeight = f32[w + F.lineHeight.word]\n style.letterSpacing = f32[w + F.letterSpacing.word]\n style.textAlign = ALIGN[u32[w + F.textAlign.word]] ?? \"start\"\n style.textDecoration = CUI_NAMES.textDecoration[u32[w + F.textDecoration.word]] as ResolvedStyle[\"textDecoration\"]\n style.lineClamp = f32[w + F.lineClamp.word]\n style.textOverflow = CUI_NAMES.textOverflow[u32[w + F.textOverflow.word]] as ResolvedStyle[\"textOverflow\"]\n\n // image / input / widget (presence props: absent = the renderer default)\n style.objectFit = CUI_NAMES.objectFit[u32[w + F.objectFit.word]] as ResolvedStyle[\"objectFit\"]\n style.tintColor = has(F.tintColor.bit) ? u32[w + F.tintColor.word] >>> 0 : undefined\n style.placeholder = str(F.placeholder.word)\n style.placeholderColor = has(F.placeholderColor.bit) ? u32[w + F.placeholderColor.word] >>> 0 : undefined\n style.inputType = CUI_NAMES.type[u32[w + F.type.word]]\n style.overlayColor = has(F.overlayColor.bit) ? u32[w + F.overlayColor.word] >>> 0 : undefined\n}\n\n/** The node's record has changes the frame's sync has not taken yet. */\nexport function paintPending(M: PaintModule, nodePtr: number): boolean {\n const p = M._cuiPaintOf(nodePtr)\n if (p === 0) return false\n const w = p >>> 2\n return M.HEAPU32[w + 2] !== 0 || M.HEAPU32[w + 3] !== 0\n}\n\n/** Read a live node's current record in place (a measure that runs before this frame's sync). */\nexport function readPaintOf(M: PaintModule, nodePtr: number, style: ResolvedStyle): boolean {\n const p = M._cuiPaintOf(nodePtr)\n if (p === 0) return false\n readPaintRecord(M, p, style)\n return true\n}\n\n/**\n * Once per frame, before layout: every record that changed since the last call, into its node's\n * style via `apply`. Returns the number of records taken.\n */\nexport function syncPaint(M: PaintModule, apply: (nodePtr: number, read: (style: ResolvedStyle) => void) => void): number {\n const n = M._paintCollect()\n if (n === 0) return 0\n const nodes = M._paintNodes() >>> 2\n const records = M._paintRecords()\n for (let i = 0; i < n; i++) {\n const ptr = M.HEAPU32[nodes + i]\n const rec = records + i * CUI_PAINT_WORDS * 4\n apply(ptr, (style) => readPaintRecord(M, rec, style))\n }\n return n\n}\n\n","import type { ResolvedStyle, RGBA } from \"../types\"\nimport type { FontSpec, Host } from \"../host/Host\"\nimport type { SceneNode } from \"./SceneNode\"\nimport { extractSvgViewBox, isSvgSource } from \"./util/svgSrc\"\n\n/** Effective, fully-defaulted text style for a node (after walking inheritance). */\nexport interface EffectiveText {\n color: RGBA\n fontSize: number\n fontFamily: string\n fontWeight: number\n fontStyle: \"normal\" | \"italic\"\n lineHeight: number\n letterSpacing: number\n textAlign: \"start\" | \"center\" | \"end\"\n textDecoration: \"underline\" | \"line-through\" | \"none\"\n}\n\n// The last-resort values for a node whose record carries no color / font (the runtime inherits\n// text style and the theme's defaults core-side; these only fill what is absent there).\nconst DEFAULTS = {\n color: 0x000000ff as RGBA,\n fontSize: 14,\n fontFamily: \"Roboto\",\n fontWeight: 400,\n fontStyle: \"normal\" as const,\n letterSpacing: 0,\n textAlign: \"start\" as const,\n textDecoration: \"none\" as const,\n}\n\n/**\n * A node's text style: its ResolvedStyle already holds the EFFECTIVE values (the runtime's paint\n * record inherits text style core-side), so this only fills the defaults for absent fields. The\n * measure callback and the render-tree build both call this, so layout and paint never disagree.\n */\nexport function resolveTextStyle(node: SceneNode): EffectiveText {\n const s = node.style\n const { color, fontSize, fontFamily, fontWeight, fontStyle, lineHeight, letterSpacing, textAlign, textDecoration } = s\n\n const size = fontSize ?? DEFAULTS.fontSize\n return {\n color: color ?? DEFAULTS.color,\n fontSize: size,\n fontFamily: fontFamily ?? DEFAULTS.fontFamily,\n fontWeight: fontWeight ?? DEFAULTS.fontWeight,\n fontStyle: fontStyle ?? DEFAULTS.fontStyle,\n lineHeight,\n letterSpacing: letterSpacing ?? DEFAULTS.letterSpacing,\n textAlign: textAlign ?? DEFAULTS.textAlign,\n textDecoration: textDecoration ?? DEFAULTS.textDecoration,\n }\n}\n\nexport function toFontSpec(t: EffectiveText): FontSpec {\n return {\n family: t.fontFamily,\n size: t.fontSize,\n weight: t.fontWeight,\n italic: t.fontStyle === \"italic\",\n letterSpacing: t.letterSpacing,\n }\n}\n\n/**\n * Greedy word-wrap to `maxWidth` (honoring explicit \\n, and breaking over-long words). Returns the\n * lines and the widest line. Ported from the DOM measure system, but measuring via the host so it\n * works headless. `maxWidth = Infinity` yields intrinsic (no-wrap) sizing.\n */\nexport function wrapText(\n text: string,\n maxWidth: number,\n measure: (s: string) => number,\n): { lines: string[]; maxWidth: number } {\n const result: string[] = []\n let widest = 0\n\n for (const rawLine of text.split(\"\\n\")) {\n if (rawLine.length === 0) {\n result.push(\"\")\n continue\n }\n let current = rawLine\n while (current) {\n if (measure(current) <= maxWidth) {\n result.push(current)\n widest = Math.max(widest, measure(current))\n break\n }\n\n let splitPos = 0\n let lastSpace = -1\n let spaceIdx = 0\n while ((spaceIdx = current.indexOf(\" \", spaceIdx + 1)) !== -1) {\n if (measure(current.substring(0, spaceIdx)) > maxWidth) break\n lastSpace = spaceIdx\n }\n\n if (lastSpace > 0) {\n splitPos = lastSpace\n } else {\n let wordEnd = current.indexOf(\" \")\n if (wordEnd === -1) wordEnd = current.length\n const firstWord = current.substring(0, wordEnd)\n if (measure(firstWord) > maxWidth) {\n for (let i = 1; i <= firstWord.length; i++) {\n if (measure(firstWord.substring(0, i)) > maxWidth) {\n splitPos = i - 1\n break\n }\n }\n } else {\n for (let i = wordEnd + 1; i <= current.length; i++) {\n if (measure(current.substring(0, i)) > maxWidth) {\n splitPos = i - 1\n break\n }\n }\n }\n }\n\n if (splitPos <= 0) splitPos = 1\n const line = current.substring(0, splitPos)\n result.push(line)\n widest = Math.max(widest, measure(line))\n current = current.substring(splitPos + (lastSpace > 0 ? 1 : 0))\n }\n }\n\n return { lines: result, maxWidth: widest }\n}\n\n/** Appended to the last surviving line when a clamp cut the text and textOverflow is \"ellipsis\". */\nconst ELLIPSIS = \"…\"\n\n/**\n * Apply `lineClamp` / `textOverflow` to a wrapped line list. Returns the surviving lines — with the\n * last one shortened so `…` fits the content width, unless `textOverflow: \"clip\"` asks for a hard\n * cut. creator-ui touches neither prop (it changes no Yoga style), so clamping — including\n * reporting the clamped box — is entirely the host's job: measure and the render tree both call\n * this, so the measured height and the painted lines can't disagree.\n *\n * Returns the input array itself when nothing is clamped, so callers can skip the re-measure.\n */\nexport function clampLines(\n lines: string[],\n style: ResolvedStyle,\n maxWidth: number,\n measure: (s: string) => number,\n): string[] {\n const clamp = style.lineClamp ?? 0\n if (clamp <= 0 || lines.length <= clamp) return lines\n const kept = lines.slice(0, clamp)\n if (style.textOverflow === \"clip\") return kept\n kept[clamp - 1] = ellipsize(kept[clamp - 1], maxWidth, measure)\n return kept\n}\n\n/** Trim `line` (from the end, on whole characters) until `line…` fits `maxWidth`. */\nfunction ellipsize(line: string, maxWidth: number, measure: (s: string) => number): string {\n // Unconstrained (intrinsic) measure: nothing to fit into, so the ellipsis just widens the box.\n if (!isFinite(maxWidth)) return line + ELLIPSIS\n const chars = [...line] // by code point — never cut a surrogate pair in half\n let end = chars.length\n while (end > 0 && measure(chars.slice(0, end).join(\"\") + ELLIPSIS) > maxWidth) end--\n return chars.slice(0, end).join(\"\").trimEnd() + ELLIPSIS\n}\n\n/** Measure a text node for creator-ui (returns intrinsic/wrapped size for the given constraints). */\nexport function measureTextNode(node: SceneNode, host: Host, width: number): { width: number; height: number } {\n const t = resolveTextStyle(node)\n const font = toFontSpec(t)\n const measureWidth = isNaN(width) ? Infinity : width\n const measure = (s: string) => host.measureText(s, font)\n const wrapped = wrapText(node.text ?? \"\", measureWidth, measure)\n const lines = clampLines(wrapped.lines, node.style, measureWidth, measure)\n // A clamp reports the CLAMPED box, otherwise the layout would reflow around the full string and\n // leave dead space under the last line. The width has to be recomputed over the surviving lines\n // only — the widest line is often one of the ones that got cut.\n let widest = wrapped.maxWidth\n if (lines !== wrapped.lines) {\n widest = 0\n for (const line of lines) widest = Math.max(widest, measure(line))\n }\n return { width: Math.ceil(widest), height: Math.ceil(lines.length * t.lineHeight) }\n}\n\n/** Measure an editable field (input / textarea) for creator-ui. An input is one text line; a\n * textarea wraps its value at the given width (empty → one line), so a field with no explicit\n * height grows with its content — Yoga clamps via the node's minHeight/maxHeight styles. Font\n * fallbacks mirror paintInput: measure and paint must agree on the line grid. */\nexport function measureEditableNode(node: SceneNode, host: Host, width: number): { width: number; height: number } {\n const s = node.style\n const font: FontSpec = {\n family: s.fontFamily ?? \"Roboto\",\n size: s.fontSize ?? 14,\n weight: s.fontWeight ?? 400,\n italic: s.fontStyle === \"italic\",\n letterSpacing: s.letterSpacing ?? 0,\n }\n const lineHeight = s.lineHeight\n const value = node.value ?? \"\"\n if (node.type === \"input\") {\n return { width: Math.ceil(host.measureText(value, font)), height: Math.ceil(lineHeight) }\n }\n const measureWidth = isNaN(width) ? Infinity : width\n const wrapped = wrapText(value, measureWidth, (t) => host.measureText(t, font))\n return { width: Math.ceil(wrapped.maxWidth), height: Math.ceil(Math.max(1, wrapped.lines.length) * lineHeight) }\n}\n\n/** Measure an image node for creator-ui (intrinsic size). A source crop (atlas frame) uses the crop's\n * w/h. An SVG is a vector → its size comes from the viewBox and it may upscale; a raster is clamped\n * to not upscale. */\nexport function measureImageNode(\n node: SceneNode,\n host: Host,\n width: number,\n height: number,\n): { width: number; height: number } {\n const raw = node.imageSrcRaw\n let iw = 0\n let ih = 0\n\n if (node.sourceRect) {\n iw = node.sourceRect[2]\n ih = node.sourceRect[3]\n } else if (isSvgSource(raw)) {\n // Inline SVG: size from the viewBox (no decode needed — works on the headless/JSON path too).\n const vb = extractSvgViewBox(raw.svg)\n if (vb) {\n iw = vb.width\n ih = vb.height\n } else {\n const info = host.getImage(host.resolveSrc(raw) ?? \"\")\n iw = info?.naturalWidth ?? 0\n ih = info?.naturalHeight ?? 0\n }\n } else {\n const src = host.resolveSrc(raw)\n const info = src ? host.getImage(src) : undefined\n iw = info?.naturalWidth ?? 0\n ih = info?.naturalHeight ?? 0\n }\n if (iw === 0 || ih === 0) return { width: 0, height: 0 }\n\n // Never past the intrinsic size under a constraint (the CSS rule, iOS's and the desktop's measure):\n // an SVG scales without quality loss, but an unsized icon still lays out at its own size — a box\n // that names a dimension is exact for yoga, which sizes past this answer anyway.\n const fit = Math.min(width / iw, height / ih)\n const k =\n isNaN(width) && isNaN(height)\n ? 1\n : isNaN(width)\n ? height / ih\n : isNaN(height)\n ? width / iw\n : Math.min(fit, 1)\n return { width: iw * k, height: ih * k }\n}\n","import type { BorderRadius, Layer, RenderNode, UITransform } from \"../types\"\nimport type { Host, FontSpec } from \"../host/Host\"\nimport type { Borders, Painter } from \"./Painter\"\nimport { clampRadius, hasRadius } from \"../core/util/geometry\"\nimport { isTransparent } from \"../core/util/colors\"\nimport { isSvgLikeSrc } from \"../core/util/svgSrc\"\nimport { wrapText } from \"../core/text\"\n\n/** What the host shows ITSELF, so the painter leaves it out. */\nexport type PaintOptions = {\n /** A native view and a video are surfaces UNDER the picture: their box is a window onto them\n * (absent: a video is a placeholder, a native view nothing). */\n surfaces?: boolean\n /** The field being edited, by node id: a live <input> stands over it, with the text and the caret. */\n editing?: number\n}\n\n/**\n * Walk the render tree and replay it into a Painter. All paint *logic* (clip-on-radius, border\n * stacking, text alignment + baseline) lives here, so every backend shares it and only the leaf\n * primitives differ. `host` is used for text metrics (deterministic across backends).\n */\nexport function paintTree(tree: RenderNode | null, painter: Painter, host: Host, options: PaintOptions = {}) {\n if (!tree) return\n painter.beginFrame(tree.rect.width, tree.rect.height)\n paintNode(tree, painter, host, options)\n painter.endFrame()\n}\n\n/**\n * Paint a full frame of compositing layers (main screen + widget overlays) in one begin/end. A\n * widget's `backdrop` is a full-viewport fill painted behind it.\n */\nexport function paintFrame(\n layers: Layer[],\n painter: Painter,\n host: Host,\n width: number,\n height: number,\n transform?: UITransform,\n options: PaintOptions = {},\n) {\n painter.beginFrame(width, height)\n // The simulated keyboard rescales the whole UI into the band above it (the keyboard itself is the\n // host's — DOM on web). The bottom band is left empty for the host to draw over.\n if (transform) {\n painter.save()\n painter.translate(transform.tx, transform.ty)\n painter.scale(transform.scale, transform.scale)\n }\n // z-order (matches the DOM): the base screen(s) first, then ALL widget backdrops, then ALL widget\n // bodies — so with ≥2 overlays a later widget's backdrop never covers an earlier widget.\n const widgets = layers.filter((l) => l.widget)\n for (const l of layers) if (!l.widget) paintNode(l.tree, painter, host, options)\n for (const l of widgets) if (l.backdrop) painter.fillRoundRect({ x: 0, y: 0, width, height }, undefined, l.backdrop.color)\n for (const l of widgets) paintNode(l.tree, painter, host, options)\n if (transform) painter.restore()\n painter.endFrame()\n}\n\nfunction paintNode(node: RenderNode, painter: Painter, host: Host, options: PaintOptions) {\n const { style, rect } = node\n painter.save()\n // A translucent container fades as a GROUP (composited offscreen, then faded once) so overlapping\n // children blend like the DOM's CSS opacity; a leaf uses cheap per-primitive alpha (identical for a\n // single fill, no offscreen needed).\n const opacity = style.opacity !== undefined && style.opacity < 1 ? style.opacity : undefined\n const grouped = opacity !== undefined && node.children.length > 0\n if (grouped) painter.beginGroup(opacity!)\n else if (opacity !== undefined) painter.setAlpha(opacity)\n\n // 2D transform about `transformOrigin` (the node centre by default), affecting the node + its subtree.\n if (style.transform) {\n const [a, b, c, d, e, f] = style.transform\n const o = style.transformOrigin\n const cx = rect.x + (o ? (o.xPercent ? rect.width * o.x / 100 : o.x) : rect.width / 2)\n const cy = rect.y + (o ? (o.yPercent ? rect.height * o.y / 100 : o.y) : rect.height / 2)\n painter.translate(cx, cy)\n painter.transform(a, b, c, d, e, f)\n painter.translate(-cx, -cy)\n }\n\n const radius = clampRadius(style.borderRadius, rect)\n\n // background color\n if (!isTransparent(style.backgroundColor)) {\n painter.fillRoundRect(rect, radius, style.backgroundColor!)\n }\n\n // background image (string url, painted behind content)\n if (style.backgroundImage) {\n const bg = host.getImage(style.backgroundImage)\n if (bg && bg.naturalWidth > 0 && bg.naturalHeight > 0) {\n painter.save()\n if (hasRadius(radius)) painter.clipRoundRect(rect, radius)\n painter.drawImage(bg, null, rect, { fit: bgSizeToFit(style.backgroundSize) })\n painter.restore()\n }\n }\n\n // background gradient layers (painted over the background image, like the DOM layer order).\n // CSS paints the first-listed layer on top, so paint the stack back-to-front (last → first).\n if (style.backgroundGradients) {\n for (let i = style.backgroundGradients.length - 1; i >= 0; i--) {\n const g = style.backgroundGradients[i]\n if (g.stops.length > 0) painter.fillGradient(rect, radius, g)\n }\n }\n\n // image (clipped to the radius if any). A source crop overrides object-fit (the frame fills the box).\n if (node.image && node.image.naturalWidth > 0 && node.image.naturalHeight > 0) {\n const crop = node.sourceRect\n painter.save()\n if (hasRadius(radius)) painter.clipRoundRect(rect, radius)\n painter.drawImage(node.image, crop ? { x: crop[0], y: crop[1], width: crop[2], height: crop[3] } : null, rect, {\n // DOM default: `img { object-fit: contain }`. A sourceRect crop always fills its box.\n fit: crop ? \"fill\" : (style.objectFit ?? \"contain\"),\n // tintColor recolors a mask-capable (SVG) image; on an opaque raster the DOM no-ops it, so\n // only tint SVG sources — otherwise a photo would become a flat silhouette.\n tint: isSvgLikeSrc(node.image.src) ? style.tintColor : undefined,\n radius,\n })\n painter.restore()\n }\n\n // text\n if (node.type === \"text\" && node.lines && node.lines.length > 0) {\n paintText(node, painter, host)\n }\n\n // input / textarea: the value (or placeholder), single line, clipped, with a caret when focused\n if ((node.type === \"input\" || node.type === \"textarea\") && node.id !== options.editing) {\n paintInput(node, painter, host, radius)\n }\n\n // a surface under the picture: its box is a window onto it. Without one, a video is a sized\n // placeholder\n if (node.type === \"video\" || node.type === \"native\") {\n if (options.surfaces) painter.clearRoundRect(rect, radius)\n else if (node.type === \"video\") paintVideoPlaceholder(node, painter, host, radius)\n }\n\n // clip children to the viewport (scrollable / overflow:hidden)\n if (node.clip) painter.clipRoundRect(rect, radius)\n\n // children\n for (const child of node.children) paintNode(child, painter, host, options)\n\n // a screen's dim: black over its content and children (a transition's pose)\n if (style.dim !== undefined && style.dim > 0) {\n painter.fillRoundRect(rect, radius, Math.round(Math.min(1, style.dim) * 255) >>> 0)\n }\n\n // border on top\n const sides = visibleBorders(style.border)\n if (sides) painter.strokeBorder(rect, radius, sides)\n\n if (grouped) painter.endGroup()\n painter.restore()\n}\n\nfunction bgSizeToFit(size: \"cover\" | \"contain\" | \"tile\" | undefined): \"cover\" | \"contain\" | \"fill\" {\n // tile isn't supported yet — fall back to cover.\n return size === \"contain\" ? \"contain\" : \"cover\"\n}\n\nfunction visibleBorders(border: RenderNode[\"style\"][\"border\"]): Borders | null {\n if (!border) return null\n const out: Borders = {}\n let any = false\n for (const side of [\"top\", \"right\", \"bottom\", \"left\"] as const) {\n const sd = border[side]\n if (sd && sd.width > 0 && (sd.color >>> 0) % 256 !== 0) {\n out[side] = sd\n any = true\n }\n }\n return any ? out : null\n}\n\n// The painter gets a raw ctx (no host), so the host's family mapping (CSS-generic aliases,\n// headless concrete faces) is applied here, when the FontSpec is built.\nconst familyOf = (host: Host, family: string | undefined) => {\n const fam = family ?? \"Roboto\"\n return host.resolveFontFamily?.(fam) ?? fam\n}\n\nfunction paintText(node: RenderNode, painter: Painter, host: Host) {\n const s = node.style\n const font: FontSpec = {\n family: familyOf(host, s.fontFamily),\n size: s.fontSize ?? 14,\n weight: s.fontWeight ?? 400,\n italic: s.fontStyle === \"italic\",\n letterSpacing: s.letterSpacing ?? 0,\n }\n const color = s.color ?? 0x000000ff\n const lineHeight = s.lineHeight\n const align = s.textAlign ?? \"start\"\n const metrics = host.fontMetrics(font)\n const { rect, lines } = node\n // The rect is the border box; inset by the node's own padding (the lines were already wrapped to\n // this content width in renderTree). Matches the DOM, which applies padding via box-sizing.\n const pl = node.padding?.[0] ?? 0\n const pt = node.padding?.[1] ?? 0\n const pr = node.padding?.[2] ?? 0\n const contentX = rect.x + pl\n const contentW = rect.width - pl - pr\n\n for (let i = 0; i < lines!.length; i++) {\n const line = lines![i]\n const lineTop = rect.y + pt + i * lineHeight\n const baselineY = lineTop + (lineHeight - (metrics.ascent + metrics.descent)) / 2 + metrics.ascent\n\n const lineWidth = host.measureText(line, font)\n const x =\n align === \"center\"\n ? contentX + (contentW - lineWidth) / 2\n : align === \"end\"\n ? contentX + contentW - lineWidth\n : contentX\n\n painter.fillText(line, x, baselineY, font, color)\n\n if (s.textDecoration === \"underline\" || s.textDecoration === \"line-through\") {\n const thickness = Math.max(1, font.size / 14)\n const y = s.textDecoration === \"underline\" ? baselineY + thickness : baselineY - font.size * 0.3\n painter.fillRoundRect({ x, y, width: lineWidth, height: thickness }, undefined, color)\n }\n }\n}\n\nfunction paintVideoPlaceholder(node: RenderNode, painter: Painter, host: Host, radius: BorderRadius | undefined) {\n const { rect } = node\n // Dark placeholder fill (unless the author set a background), so the video reads as a sized box.\n if (isTransparent(node.style.backgroundColor)) painter.fillRoundRect(rect, radius, 0x111317ff)\n // Centred play glyph.\n const size = Math.min(rect.width, rect.height) * 0.3\n if (size >= 6) {\n const font: FontSpec = { family: \"Roboto\", size, weight: 400, italic: false, letterSpacing: 0 }\n const metrics = host.fontMetrics(font)\n const w = host.measureText(\"▶\", font)\n const x = rect.x + (rect.width - w) / 2\n const baselineY = rect.y + (rect.height - (metrics.ascent + metrics.descent)) / 2 + metrics.ascent\n painter.fillText(\"▶\", x, baselineY, font, 0xffffffcc)\n }\n}\n\nfunction paintInput(node: RenderNode, painter: Painter, host: Host, radius: BorderRadius | undefined) {\n const s = node.style\n const font: FontSpec = {\n family: familyOf(host, s.fontFamily),\n size: s.fontSize ?? 14,\n weight: s.fontWeight ?? 400,\n italic: s.fontStyle === \"italic\",\n letterSpacing: s.letterSpacing ?? 0,\n }\n const value = node.value ?? \"\"\n const empty = value.length === 0\n const masked = s.inputType === \"password\" && !empty\n const display = empty ? (s.placeholder ?? \"\") : masked ? \"•\".repeat(value.length) : value\n const color = empty ? (s.placeholderColor ?? 0x999999ff) : (s.color ?? 0x000000ff)\n const { rect } = node\n // Inset the value/placeholder/caret by the field's own padding (rect is the border box).\n const pl = node.padding?.[0] ?? 0\n const pt = node.padding?.[1] ?? 0\n const pr = node.padding?.[2] ?? 0\n const pb = node.padding?.[3] ?? 0\n const contentX = rect.x + pl\n const contentW = rect.width - pl - pr\n const contentY = rect.y + pt\n const contentH = rect.height - pt - pb\n const metrics = host.fontMetrics(font)\n const lineHeight = s.lineHeight\n const align = s.textAlign ?? \"start\"\n\n // A textarea wraps to the content width and top-aligns its lines; an input is a single line,\n // vertically centred in the field.\n const multiline = node.type === \"textarea\"\n const lines = multiline ? wrapText(display, contentW, (t) => host.measureText(t, font)).lines : [display]\n const lineX = (w: number) =>\n align === \"center\" ? contentX + (contentW - w) / 2 : align === \"end\" ? contentX + contentW - w : contentX\n const lineBaseline = (i: number) =>\n multiline\n ? contentY + i * lineHeight + (lineHeight - (metrics.ascent + metrics.descent)) / 2 + metrics.ascent\n : contentY + (contentH - (metrics.ascent + metrics.descent)) / 2 + metrics.ascent\n\n painter.save()\n painter.clipRoundRect(rect, radius) // keep content inside the field\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]\n if (line.length > 0) painter.fillText(line, lineX(host.measureText(line, font)), lineBaseline(i), font, color)\n }\n\n // Caret at the end of the real value (or the start when empty) while focused. Static (no blink).\n if (node.state?.focused) {\n const valueLines = empty\n ? [\"\"]\n : multiline\n ? wrapText(masked ? \"•\".repeat(value.length) : value, contentW, (t) => host.measureText(t, font)).lines\n : [display]\n const i = valueLines.length - 1\n const lineW = host.measureText(valueLines[i], font)\n const caretX = empty ? lineX(0) : lineX(lineW) + lineW\n const baselineY = lineBaseline(i)\n const caretW = Math.max(1, font.size / 14)\n painter.fillRoundRect(\n { x: caretX, y: baselineY - metrics.ascent, width: caretW, height: metrics.ascent + metrics.descent },\n undefined,\n s.color ?? 0x000000ff,\n )\n }\n painter.restore()\n}\n","import type { BorderRadius, RenderNode, ResolvedStyle } from \"../types\"\nimport { rgbaToHex } from \"../core/util/colors\"\n\nexport interface SerializeOptions {\n /** Decimal places for rects (default 2). */\n precision?: number\n /** Include the `id` (creator-ui node id) — off by default; ids are unstable across runs. */\n includeIds?: boolean\n}\n\n/**\n * Serialize a render tree into a plain, JSON-friendly object — the primary text output. Colors\n * become \"#rrggbbaa\", rects are rounded, and only meaningful fields appear, so the result is\n * readable for AI feedback and stable for snapshot assertions.\n */\nexport function serializeRenderTree(tree: RenderNode | null, opts: SerializeOptions = {}): unknown {\n if (!tree) return null\n return serializeNode(tree, opts.precision ?? 2, opts.includeIds ?? false)\n}\n\n/** Convenience: the serialized tree as pretty JSON text. */\nexport function renderTreeToText(tree: RenderNode | null, opts?: SerializeOptions): string {\n return JSON.stringify(serializeRenderTree(tree, opts), null, 2)\n}\n\n/**\n * Serialize a whole frame — the main screen plus any widget overlays — so the JSON describes\n * everything painted (PNG/JSON parity). Widget trees are attached as an `overlays` array on the main\n * root (they composite above it). With no widgets this returns the bare main tree, unchanged; with no\n * main screen but live widgets it returns `{ type: \"frame\", overlays }`.\n */\nexport function serializeFrame(main: RenderNode | null, widgets: RenderNode[] = [], opts: SerializeOptions = {}): unknown {\n const precision = opts.precision ?? 2\n const includeIds = opts.includeIds ?? false\n const root = main ? serializeNode(main, precision, includeIds) : null\n if (widgets.length === 0) return root\n const overlays = widgets.map((w) => serializeNode(w, precision, includeIds))\n if (root) {\n root.overlays = overlays\n return root\n }\n return { type: \"frame\", overlays }\n}\n\n/** Convenience: the serialized frame (screen + overlays) as pretty JSON text. */\nexport function frameToText(main: RenderNode | null, widgets: RenderNode[] = [], opts?: SerializeOptions): string {\n return JSON.stringify(serializeFrame(main, widgets, opts), null, 2)\n}\n\nfunction round(n: number, p: number): number {\n const f = 10 ** p\n return Math.round(n * f) / f\n}\n\nfunction serializeNode(node: RenderNode, precision: number, includeIds: boolean): any {\n const r = node.rect\n const out: any = { type: node.type }\n if (node.name) out.name = node.name\n out.rect = [round(r.x, precision), round(r.y, precision), round(r.width, precision), round(r.height, precision)]\n if (includeIds) out.id = node.id\n\n const style = serializeStyle(node.style)\n if (style) out.style = style\n\n if (node.text !== undefined) out.text = node.text\n if (node.lines && (node.lines.length !== 1 || node.lines[0] !== node.text)) out.lines = node.lines\n // Editables: show what the field says — its typed value, or the placeholder an empty field\n // renders (also the AI-facing selector for label-less inputs).\n if (node.value !== undefined && node.value !== \"\") out.value = node.value\n if (node.style.placeholder !== undefined) out.placeholder = node.style.placeholder\n if (node.image) {\n out.image = { src: node.image.src, natural: [node.image.naturalWidth, node.image.naturalHeight] }\n }\n if (node.sourceRect) out.sourceRect = node.sourceRect\n if (node.state && (node.state.pressed || node.state.classes?.length)) {\n out.state = {\n ...(node.state.pressed ? { pressed: true } : {}),\n ...(node.state.classes?.length ? { classes: node.state.classes } : {}),\n }\n }\n if (node.scroll) {\n out.scroll = { offset: round(node.scroll.offset, precision), content: round(node.scroll.content, precision) }\n }\n\n if (node.children.length > 0) {\n out.children = node.children.map((c) => serializeNode(c, precision, includeIds))\n }\n return out\n}\n\nfunction radiusObj(radius: BorderRadius) {\n if (radius.tl === radius.tr && radius.tr === radius.br && radius.br === radius.bl) return radius.tl\n return [radius.tl, radius.tr, radius.br, radius.bl]\n}\n\nfunction serializeStyle(s: ResolvedStyle): Record<string, unknown> | undefined {\n const out: Record<string, unknown> = {}\n if (s.backgroundColor !== undefined) out.backgroundColor = rgbaToHex(s.backgroundColor)\n if (s.opacity !== undefined) out.opacity = s.opacity\n if (s.color !== undefined) out.color = rgbaToHex(s.color)\n if (s.fontSize !== undefined) out.fontSize = s.fontSize\n if (s.fontFamily !== undefined) out.fontFamily = s.fontFamily\n if (s.fontWeight !== undefined) out.fontWeight = s.fontWeight\n if (s.fontStyle !== undefined && s.fontStyle !== \"normal\") out.fontStyle = s.fontStyle\n if (s.lineHeight !== undefined) out.lineHeight = s.lineHeight\n if (s.letterSpacing) out.letterSpacing = s.letterSpacing\n if (s.textAlign !== undefined && s.textAlign !== \"start\") out.textAlign = s.textAlign\n if (s.textDecoration !== undefined && s.textDecoration !== \"none\") out.textDecoration = s.textDecoration\n // Only an ACTIVE clamp is worth showing: `lines` already carries the visible result (with its \"…\"),\n // and `textOverflow` means nothing without a clamp.\n if (s.lineClamp) {\n out.lineClamp = s.lineClamp\n if (s.textOverflow === \"clip\") out.textOverflow = s.textOverflow\n }\n if (s.objectFit !== undefined) out.objectFit = s.objectFit\n if (s.tintColor !== undefined) out.tintColor = rgbaToHex(s.tintColor)\n if (s.overlayColor !== undefined) out.overlayColor = rgbaToHex(s.overlayColor)\n if (s.backgroundImage !== undefined) out.backgroundImage = s.backgroundImage\n if (s.backgroundSize !== undefined) out.backgroundSize = s.backgroundSize\n if (s.backgroundGradients !== undefined && s.backgroundGradients.length > 0) {\n out.backgroundGradients = s.backgroundGradients.map((g) => {\n const stops = g.stops.map((st) => ({ color: rgbaToHex(st.color), position: st.position }))\n if (g.type === \"radial\") {\n const rad: Record<string, unknown> = { type: \"radial\", shape: g.shape, extent: g.extent, cx: g.cx, cy: g.cy, stops }\n if (g.extent === \"explicit\") {\n rad.rx = g.rx\n rad.ry = g.ry\n rad.rxUnit = g.rxUnit\n rad.ryUnit = g.ryUnit\n }\n return rad\n }\n return { angle: g.angle, stops } // linear stays shape-compatible with the pre-radial output\n })\n }\n\n if (s.borderRadius && (s.borderRadius.tl || s.borderRadius.tr || s.borderRadius.br || s.borderRadius.bl)) {\n out.borderRadius = radiusObj(s.borderRadius)\n }\n if (s.border) {\n const b: Record<string, unknown> = {}\n for (const side of [\"top\", \"right\", \"bottom\", \"left\"] as const) {\n const sd = s.border[side]\n if (sd && sd.width > 0) b[side] = { width: sd.width, color: rgbaToHex(sd.color) }\n }\n if (Object.keys(b).length > 0) out.border = b\n }\n\n return Object.keys(out).length > 0 ? out : undefined\n}\n","/// <reference path=\"../contract.d.ts\" />\n// The tree UI: the HostUI table of the runtime (sdk/src/bridges/tree.d.ts `HostUI`) implemented\n// in TypeScript over the wasm runtime module — the shared core of the web renderers (the canvas\n// mount in the browser, the DOM renderer, the headless host). The runtime OWNS the tree (creator-ui\n// Yoga, the screens / destinations / widgets / pager / vlist); this class keeps one HNode per node\n// id (the yoga pointer), the paint-ready style creator-ui's handlers write into it, the content\n// properties, and the boxes of the last layout pass — and turns them into the render tree (the\n// RenderNode: the semantic JSON AND the paint source), hit-tests pointers over it and reports what\n// happened back to the runtime through the creatorWeb* entry points (node events, touches, scroll,\n// focus / change). Nothing of JavaScript reaches it: the SDK's element objects live behind the\n// runtime's emitter.\nimport type { WasmModule } from \"lecodes-web-runtime/src/gen/wasm\"\nimport type { WasmHostUI } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport { paintPending, readPaintOf, syncPaint, type PaintModule } from \"../layout/creatorUi/paint-read\"\nimport type { CreatorUiModule } from \"../layout/creatorUi/loadCreatorUi\"\nimport type { Host } from \"../host/Host\"\nimport type { Layer, Rect, RenderNode, ResolvedStyle, WorkerNode } from \"../types\"\nimport type { SceneNode } from \"../core/SceneNode\"\nimport type { Painter } from \"../paint/Painter\"\nimport { clampLines, measureEditableNode, measureImageNode, measureTextNode, resolveTextStyle, toFontSpec, wrapText } from \"../core/text\"\nimport { paintFrame, type PaintOptions } from \"../paint/paintTree\"\nimport { frameToText, serializeFrame } from \"../serialize/serializeRenderTree\"\nimport { hitTest } from \"../core/hitTest\"\nimport { svgToDataUri } from \"../core/util/svgSrc\"\nimport {\n TREE_DEST_SCREEN, TREE_EVENT_BLUR, TREE_EVENT_CHANGE, TREE_EVENT_FOCUS, TREE_EVENT_OVERLAY_TAP, TREE_EVENT_OVERSCROLL,\n TREE_EVENT_SCROLL_RELEASE, TREE_EVENT_SUBMIT, TREE_FLAG_BLUR, TREE_FLAG_CHANGE, TREE_FLAG_CLICK, TREE_FLAG_FOCUS,\n TREE_FLAG_INTERACTIVE, TREE_FLAG_LAYOUT, TREE_FLAG_LONG_PRESS, TREE_FLAG_OVERLAY_TAP, TREE_FLAG_OVERSCROLL, TREE_FLAG_SCROLL,\n TREE_FLAG_SCROLL_RELEASE, TREE_FLAG_SUBMIT,\n} from \"lecodes-sdk/ui/tree\"\n\n/** Fraction of the viewport the simulated keyboard occupies while an input is focused (the number\n * every simulator host uses); the focused root re-flows above it (runtime pkgSetShrunkRoot). */\nconst KEYBOARD_FRACTION = 0.32\n/** Drag distance (px) before a press commits to scrolling. */\nconst SCROLL_THRESHOLD = 4\n\n/** One node of the runtime's tree as this renderer sees it. Structurally a web-canvas SceneNode for\n * the shared text / measure helpers (they read `style`, `parent`, `text`, `value`, `sourceRect`). */\n/**\n * The image src as the SDK puts it on the wire (sdk/src/ui/UIImage.ts): a url, `id:<buffer>` (the\n * fetch host serves it), `canvas:<id>` (a baked _creatorCanvas surface → the web-canvas host's\n * `lecodes-canvas://` scheme), `svg:<markup>` (an inline SvgSource → the data-uri the image decoder\n * loads, encoded once per distinct markup). A `scene2d:` source has no image: the box is the render.\n */\nconst svgUris = new Map<string, string>()\nfunction wireSrc(s: string | undefined): string | undefined {\n if (!s) return s\n if (s.startsWith(\"canvas:\")) return `lecodes-canvas://${s.slice(7)}`\n if (s.startsWith(\"svg:\")) {\n let uri = svgUris.get(s)\n if (uri === undefined) { uri = svgToDataUri(s.slice(4)); svgUris.set(s, uri) }\n return uri\n }\n return s\n}\n\nexport class HNode {\n parent: HNode | null = null\n children: HNode[] = []\n style: ResolvedStyle = { lineHeight: 14 * 1.2 } // the core's fresh-node record; the first paint sync replaces it\n name?: string\n text = \"\"\n src: string | undefined\n value = \"\"\n sourceRect?: [number, number, number, number]\n viewName?: string\n viewParams?: string\n /** \"playerId\" of a video node / \"viewId\" of a native node (setPropertyInt). */\n playerId = 0\n viewId = 0\n flags = 0\n /** The box of the last layout pass (parent-relative; a root's is its own frame). */\n layoutRect: Rect | null = null\n scrollOffset = 0\n wrapCache?: { key: string, lines: string[] }\n /** The minimal WorkerNode the shared helpers expect (unused fields). */\n readonly jsNode: Record<string, unknown>\n constructor(readonly id: number, readonly type: string) { this.jsNode = { type, _id: id } }\n get measured(): boolean { return this.type === \"text\" || this.type === \"image\" || this.editable }\n get editable(): boolean { return this.type === \"input\" || this.type === \"textarea\" }\n get scrollable(): boolean { return this.type === \"scrollable\" || this.type === \"scrollableScreen\" || this.type === \"vlist\" }\n get scrollAxis(): \"x\" | \"y\" { return this.style.scrollAxis === \"x\" ? \"x\" : \"y\" }\n get interactive(): boolean { return (this.flags & TREE_FLAG_INTERACTIVE) !== 0 }\n get imageSrcRaw(): unknown { return this.type === \"image\" ? wireSrc(this.src) : undefined }\n has(flag: number): boolean { return (this.flags & flag) !== 0 }\n}\n\ntype Gesture = {\n node: HNode | null // the pressed interactive node\n scroll: HNode | null // the overflowing scrollable this gesture may drive\n backdrop: HNode | null // a modal widget whose backdrop was tapped\n edit: HNode | null // the editable the press landed in\n global: boolean // fell through to the scene\n dismiss: boolean // a clean release blurs the focused input\n lastX: number\n lastY: number\n acc: number\n scrolling: boolean\n swallowClick: boolean // a long-press listener took the gesture\n}\n\nexport type TreeUIOptions = {\n /** The app-facing keyboard listener state: the host reports the band height through the runtime. */\n onKeyboard?: (height: number) => void\n /** The band the on-screen keyboard takes while an input is focused, in logical px. Absent = a\n * simulated one (a fixed fraction of the height: the headless host, where nothing else tells);\n * a browser page answers with what its window really loses. */\n keyboardHeight?: () => number\n /** A toast to show (the headless host records it, a browser mount paints one). */\n onToast?: (message: string, duration: number) => void\n}\n\nexport class TreeUI implements WasmHostUI {\n readonly nodes = new Map<number, HNode>()\n /** The presented screen root (TREE_DEST_SCREEN), null while a scene / nothing is presented. */\n root: HNode | null = null\n /** The screen that LEFT and is still shown: the runtime moves it and the incoming one through\n * their own transform / opacity / dim (a transition is tween tracks on the roots — a host plays\n * none of its own) and drops it when the transition lands (dropView). Painted only. */\n leaving: HNode | null = null\n /** …over the current screen, else under it. */\n leavingAbove = false\n /** Per pager: the page its current tab shows, and the one that left that place and is still\n * shown — the runtime moves both through their own transform / opacity / dim and says when the\n * one that left goes (HostUI.pagerShowPage / pagerDropPage). `above` = over the page shown. */\n private pagerShown = new Map<number, HNode>()\n private pagerLeaving = new Map<number, { page: HNode, above: boolean }>()\n /** TREE_DEST_* of the current destination, -1 when none. */\n destKind = -1\n readonly widgetRoots: HNode[] = []\n width = 0\n height = 0\n private focused: HNode | null = null\n private readonly pressed = new Set<number>()\n private readonly gestures = new Map<number, Gesture>()\n private readonly vlists = new Set<HNode>()\n private frameCache: Layer[] | null = null\n private painted: Layer[] | null = null\n private fontsPending = 0\n private lastToast: string | null = null\n /** Bumped by every mutation; the render tree is rebuilt when it changed. */\n private dirty = true\n /** The host's hook on the destination change (TREE_DEST_*; -1 = none) — `id` is the sceneId of a\n * scene destination: it shows / hides its scene canvases. */\n onDestination: ((kind: number, id: number) => void) | null = null\n /** The destination that left was dropped (HostUI.dropView): the host takes a surface away here,\n * not when the next destination opens — a screen may still be coming in over it. */\n onDropped: ((kind: number, id: number) => void) | null = null\n\n constructor(readonly M: WasmModule, readonly host: Host, private readonly options: TreeUIOptions = {}) {}\n\n // ---- setup ------------------------------------------------------------------------------------\n /** Register the measure function with creator-ui (once, before any node). Style needs no\n * registration: the runtime keeps every node's paint record, this renderer reads it (paint-read.ts). */\n install(): void {\n const view = new DataView(new ArrayBuffer(8))\n const measure = (_screenId: number, nodePtr: number, width: number, _wType: number, height: number, _hType: number): bigint => {\n const r = this.measure(nodePtr, width, height)\n view.setFloat32(4, r.width, true)\n view.setFloat32(0, r.height, true)\n return view.getBigUint64(0, true)\n }\n this.M._setMeasureFunc(this.M.addFunction(measure, \"jiififi\"))\n }\n\n private measure(nodeId: number, width: number, height: number): { width: number, height: number } {\n const n = this.nodes.get(nodeId)\n if (!n) return { width: 0, height: 0 }\n // A layout the runtime runs before this frame's sync (it lays a screen out when it presents\n // it) must still measure with the font the record holds NOW.\n const P = this.M as unknown as PaintModule\n if (paintPending(P, nodeId)) readPaintOf(P, nodeId, n.style)\n const sn = n as unknown as SceneNode\n if (n.type === \"text\") return measureTextNode(sn, this.host, width)\n if (n.type === \"image\") return measureImageNode(sn, this.host, width, height)\n if (n.editable) return measureEditableNode(sn, this.host, width)\n return { width: 0, height: 0 }\n }\n\n /** The viewport in logical px; safe-area insets in CSS order + the system-bar edges. */\n resize(width: number, height: number): void {\n this.width = width\n this.height = height\n this.M._creatorWebResize(width, height)\n this.M._setConditionValue(width, height)\n this.dirty = true\n }\n setSafeArea(area: [number, number, number, number] | null, bars: readonly (\"top\" | \"right\" | \"bottom\" | \"left\")[] = []): void {\n const [t, r, b, l] = area ?? (this.width > this.height ? [0, 8, 0, 20] : [20, 0, 8, 0])\n const BIT = { top: 1, right: 2, bottom: 4, left: 8 }\n this.M._setSafeAreaBars(bars.reduce((m, e) => m | BIT[e], 0))\n this.M._setSafePaddings(t, r, b, l, 0)\n this.dirty = true\n }\n\n // ---- the frame ---------------------------------------------------------------------------------\n /** After a runtime tick: lay every live root out (the runtime's pass), read the boxes, settle the\n * virtualized lists, report onLayout to the nodes that listen. */\n layoutFrame(): void {\n const M = this.M\n // Every style write since the last frame sits in the core's dirty paint records: take them\n // BEFORE layout (measure reads the font) — a non-empty batch is a mutation of the render tree.\n const changed = syncPaint(M as unknown as PaintModule, (ptr, read) => {\n const node = this.nodes.get(ptr)\n if (node) read(node.style)\n })\n if (changed > 0) this.dirty = true\n const n = M._creatorWebLayoutFrame(this.width, this.height)\n if (n > 0) this.readLayoutBatch(n)\n for (const v of this.vlists) {\n if (!M._vlistExists(v.id)) continue\n M._vlistUpdateLayout(v.id)\n // the mounted items are detached core roots the batch never visits: read their boxes here\n for (const item of v.children) this.deliverSubtree(item)\n }\n }\n /** Whether the render tree changed since the last `frame()` (a mount paints only then). */\n /** Whether the picture is behind the tree: something changed since the frame that was PAINTED.\n * Not since the frame that was last built — a hit test or a hover builds one between a change\n * and the paint, and the change is still owed its picture. */\n needsPaint(): boolean { return this.dirty || this.frameCache === null || this.frameCache !== this.painted }\n /** Consume a subtree's new layouts (getLayoutPointer: one-shot per node) into the cached boxes. */\n private deliverSubtree(node: HNode): void {\n const M = this.M\n if (!this.layoutPtr) this.layoutPtr = M._malloc(16)\n if (M._getLayoutPointer(node.id, this.layoutPtr)) {\n const i = this.layoutPtr >> 2\n const rect = { x: M.HEAPF32[i], y: M.HEAPF32[i + 1], width: M.HEAPF32[i + 2], height: M.HEAPF32[i + 3] }\n const old = node.layoutRect\n const changed = !old || old.x !== rect.x || old.y !== rect.y || old.width !== rect.width || old.height !== rect.height\n node.layoutRect = rect\n if (changed) this.dirty = true\n if (changed && node.has(TREE_FLAG_LAYOUT)) M._creatorWebNodeLayout(node.id, rect.x, rect.y, rect.width, rect.height)\n }\n for (const c of node.children) this.deliverSubtree(c)\n }\n private layoutPtr = 0\n private readLayoutBatch(n: number): void {\n const M = this.M\n const nodesPtr = M._collectNodes() >>> 2\n const rectsPtr = M._collectRects() >>> 2\n const u32 = M.HEAPU32, f32 = M.HEAPF32\n for (let i = 0; i < n; i++) {\n const ptr = u32[nodesPtr + i]\n const node = this.nodes.get(ptr)\n if (!node) continue\n const l = f32[rectsPtr + i * 4], t = f32[rectsPtr + i * 4 + 1], r = f32[rectsPtr + i * 4 + 2], b = f32[rectsPtr + i * 4 + 3]\n const rect = { x: l, y: t, width: r - l, height: b - t }\n const old = node.layoutRect\n const changed = !old || old.x !== rect.x || old.y !== rect.y || old.width !== rect.width || old.height !== rect.height\n node.layoutRect = rect\n if (changed) this.dirty = true\n if (changed && node.has(TREE_FLAG_LAYOUT)) M._creatorWebNodeLayout(ptr, l, t, rect.width, rect.height)\n }\n }\n\n /** Every compositing layer, bottom-to-top: the screen — and the one that left, under or over it\n * — then the widgets in show order. */\n frame(): Layer[] {\n if (this.frameCache && !this.dirty) return this.frameCache\n const layers: Layer[] = []\n const viewport = { x: 0, y: 0, width: this.width, height: this.height }\n const left = this.leaving ? this.build(this.leaving, viewport) : null\n if (left && !this.leavingAbove) layers.push({ tree: left, leaving: true })\n if (this.root) {\n const tree = this.build(this.root, viewport)\n if (tree) layers.push({ tree })\n }\n if (left && this.leavingAbove) layers.push({ tree: left, leaving: true })\n for (const w of this.widgetRoots) {\n const box = w.layoutRect ?? { x: 0, y: 0, width: this.width, height: this.height }\n const tree = this.build(w, box)\n if (!tree) continue\n const color = tree.style.overlayColor\n layers.push({ tree, widget: true, backdrop: color !== undefined ? { color, jsNode: w.jsNode as WorkerNode } : undefined })\n }\n this.frameCache = layers\n this.dirty = false\n return layers\n }\n renderTree(): RenderNode | null { return this.frame().find((l) => !l.widget && !l.leaving)?.tree ?? null }\n widgetTrees(): RenderNode[] { return this.frame().filter((l) => l.widget).map((l) => l.tree) }\n /** The widget overlay trees, in show order (the scenario engine reads them). */\n widgets(): RenderNode[] { return this.widgetTrees() }\n serialize(): unknown { return serializeFrame(this.renderTree(), this.widgetTrees()) }\n toText(): string { return frameToText(this.renderTree(), this.widgetTrees()) }\n paint(painter: Painter, options?: PaintOptions): void {\n const frame = this.frame()\n paintFrame(frame, painter, this.host, this.width, this.height, undefined, options)\n this.painted = frame\n }\n\n /** The absolute, fully-resolved render tree of a root (the web-canvas builder, over the runtime's\n * boxes: a pager shows its selected page, a vlist places its mounted items at the core's offsets). */\n private build(root: HNode, rootRect: Rect): RenderNode | null {\n const M = this.M\n const walk = (node: HNode, px: number, py: number, isRoot: boolean): RenderNode | null => {\n if (node.style.display === \"none\") return null\n let x: number, y: number, width: number, height: number\n if (isRoot) { x = rootRect.x; y = rootRect.y; width = rootRect.width; height = rootRect.height }\n else {\n const rel = node.layoutRect\n if (!rel) return null\n x = px + rel.x; y = py + rel.y; width = rel.width; height = rel.height\n }\n const out: RenderNode = { id: node.id, type: node.type, rect: { x, y, width, height }, style: node.style, children: [] }\n if (node.name) out.name = node.name\n const sn = node as unknown as SceneNode\n if (node.type === \"text\") {\n const t = resolveTextStyle(sn)\n const font = toFontSpec(t)\n out.text = node.text\n const pad = this.padding(node.id)\n if (pad[0] || pad[1] || pad[2] || pad[3]) out.padding = pad\n const contentW = width - pad[0] - pad[2]\n const key = `${contentW}|${font.size}|${font.weight}|${font.italic ? 1 : 0}|${font.letterSpacing}|${font.family}|${node.style.lineClamp ?? 0}|${node.style.textOverflow ?? \"\"}|${node.text}`\n if (node.wrapCache?.key === key) out.lines = node.wrapCache.lines\n else {\n const measure = (s: string) => this.host.measureText(s, font)\n const lines = clampLines(wrapText(node.text, contentW, measure).lines, node.style, contentW, measure)\n node.wrapCache = { key, lines }\n out.lines = lines\n }\n out.style = { ...node.style, color: t.color, fontSize: t.fontSize, fontFamily: t.fontFamily, fontWeight: t.fontWeight, fontStyle: t.fontStyle, lineHeight: t.lineHeight, letterSpacing: t.letterSpacing, textAlign: t.textAlign, textDecoration: t.textDecoration }\n } else if (node.type === \"image\") {\n const src = this.host.resolveSrc(node.imageSrcRaw)\n const info = src ? this.host.getImage(src) : undefined\n out.image = info ?? (src ? { src, naturalWidth: 0, naturalHeight: 0 } : undefined)\n if (node.sourceRect) out.sourceRect = node.sourceRect\n } else if (node.editable) {\n out.value = node.value\n const pad = this.padding(node.id)\n if (pad[0] || pad[1] || pad[2] || pad[3]) out.padding = pad\n const t = resolveTextStyle(sn)\n out.style = { ...node.style, color: t.color, fontSize: t.fontSize, fontFamily: t.fontFamily, fontWeight: t.fontWeight, fontStyle: t.fontStyle, lineHeight: t.lineHeight, letterSpacing: t.letterSpacing, textAlign: t.textAlign, textDecoration: t.textDecoration }\n }\n if (node.interactive) out.state = { pressed: this.pressed.has(node.id) }\n if (node.editable && this.focused === node) out.state = { ...out.state, focused: true }\n if (node.style.overflow === \"hidden\") out.clip = true\n let childX = x, childY = y\n if (node.scrollable) {\n const axis = node.scrollAxis\n const content = axis === \"x\" ? M._getContentWidth(node.id) : M._getContentHeight(node.id)\n out.clip = true\n out.scroll = { offset: node.scrollOffset, content, axis }\n if (axis === \"x\") childX = x - node.scrollOffset\n else childY = y - node.scrollOffset\n }\n if (node.type === \"pager\") {\n // the selected tab's top page: an independent root laid out at the pager's box\n const tab = M._creatorWebPagerSelectedIndex(node.id)\n const len = M._creatorWebPagerStackLen(node.id, tab)\n const pageId = len > 0 ? M._creatorWebPagerPageNode(node.id, tab, len - 1) : 0\n const page = pageId ? this.nodes.get(pageId) : undefined\n if (page) this.pagerShown.set(node.id, page); else this.pagerShown.delete(node.id)\n const left = this.pagerLeaving.get(node.id)\n for (const p of left && left.page !== page ? (left.above ? [page, left.page] : [left.page, page]) : [page]) {\n const r = p ? walk(p, x, y, false) : null\n if (r) out.children.push(r)\n }\n return out\n }\n if (node.type === \"vlist\") {\n // mounted items: each a detached core root at the offset the window math gave it\n for (const child of node.children) {\n const itemRoot = M._getParentNode(child.id)\n if (!itemRoot) continue\n const off = M._vlistItemOffsetOf(node.id, itemRoot)\n if (Number.isNaN(off)) continue\n const rel = child.layoutRect ?? { x: 0, y: 0, width: 0, height: 0 }\n const r = walk(child, x - rel.x, y + off - node.scrollOffset - rel.y, false)\n if (r) out.children.push(r)\n }\n return out\n }\n for (const child of node.children) { const r = walk(child, childX, childY, false); if (r) out.children.push(r) }\n return out\n }\n return walk(root, 0, 0, true)\n }\n /** A node's resolved padding, [left, top, right, bottom] (an inspector's). */\n paddingOf(nodeId: number): [number, number, number, number] { return this.padding(nodeId) }\n private padding(nodeId: number): [number, number, number, number] {\n const M = this.M\n if (!this.padPtr) this.padPtr = M._malloc(16)\n M._getPaddingPointer(nodeId, this.padPtr)\n const i = this.padPtr >> 2\n return [M.HEAPF32[i], M.HEAPF32[i + 1], M.HEAPF32[i + 2], M.HEAPF32[i + 3]]\n }\n private padPtr = 0\n /** Call an export that takes a C string. */\n private withStr<T>(s: string, fn: (ptr: number) => T): T {\n const p = this.M.stringToNewUTF8(s)\n try { return fn(p) } finally { this.M._free(p) }\n }\n\n // ---- lookups ---------------------------------------------------------------------------------------\n get(id: number): HNode | undefined { return this.nodes.get(id) }\n /** Rendered nodes by their author-given `name`, the screen first, then the widgets. */\n findAll(name: string): RenderNode[] {\n const out: RenderNode[] = []\n const walk = (n: RenderNode) => { if (n.name === name) out.push(n); for (const c of n.children) walk(c) }\n for (const l of this.frame()) walk(l.tree)\n return out\n }\n /** The absolute rect of a rendered node, null when it is not on screen. */\n findRect(id: number): Rect | null {\n const walk = (n: RenderNode): Rect | null => {\n if (n.id === id) return n.rect\n for (const c of n.children) { const r = walk(c); if (r) return r }\n return null\n }\n for (const l of this.frame()) { const r = walk(l.tree); if (r) return r }\n return null\n }\n /** The last toast shown (the host paints none). */\n toast(): string | null { return this.lastToast }\n pendingFonts(): number { return this.fontsPending }\n keyboardHeight(): number {\n if (!this.focused) return 0\n return this.options.keyboardHeight ? this.options.keyboardHeight() : Math.round(this.height * KEYBOARD_FRACTION)\n }\n focusedId(): number { return this.focused?.id ?? 0 }\n\n // ---- HostUI: the tree ---------------------------------------------------------------------------\n /** The node the runtime made last (an inspector ties the element the SDK is making to it). */\n lastCreated = 0\n nodeFactory(id: number, type: string, parent: number, index: number): void {\n this.lastCreated = id\n const n = new HNode(id, type)\n this.nodes.set(id, n)\n if (type === \"vlist\") this.vlists.add(n)\n const p = this.nodes.get(parent)\n if (p) this.link(p, n, Math.max(0, index))\n this.dirty = true\n }\n private link(p: HNode, c: HNode, index: number): void {\n if (c.parent) c.parent.children = c.parent.children.filter((x) => x !== c)\n c.parent = p\n p.children.splice(Math.min(index, p.children.length), 0, c)\n }\n insertNode(parent: number, child: number, index: number): void {\n const p = this.nodes.get(parent), c = this.nodes.get(child)\n if (p && c) this.link(p, c, index)\n this.dirty = true\n }\n removeNode(parent: number, child: number): void {\n const p = this.nodes.get(parent), c = this.nodes.get(child)\n if (!p || !c) return\n this.forget(c)\n p.children = p.children.filter((x) => x !== c)\n if (c.parent === p) c.parent = null\n if (this.pagerLeaving.get(parent)?.page === c) this.pagerLeaving.delete(parent)\n if (this.pagerShown.get(parent) === c) this.pagerShown.delete(parent)\n this.dirty = true\n }\n releaseNode(id: number): void {\n const n = this.nodes.get(id)\n if (!n) return\n this.nodes.delete(id)\n this.forget(n)\n if (n.parent) n.parent.children = n.parent.children.filter((x) => x !== n)\n if (this.root === n) this.root = null\n if (this.leaving === n) this.leaving = null\n this.pagerShown.delete(id)\n this.pagerLeaving.delete(id)\n for (const [pager, left] of this.pagerLeaving) if (left.page === n) this.pagerLeaving.delete(pager)\n if (this.focused === n) { this.focused = null; this.M._creatorWebSetShrunkRoot(0, 0); this.emitKeyboard() }\n const wi = this.widgetRoots.indexOf(n)\n if (wi >= 0) this.widgetRoots.splice(wi, 1)\n this.vlists.delete(n)\n this.pressed.delete(id)\n this.dirty = true\n }\n /** A node leaving the tree must leave every in-flight gesture too. */\n private forget(n: HNode): void {\n for (const g of this.gestures.values()) {\n if (g.node === n) g.node = null\n if (g.scroll === n) g.scroll = null\n if (g.backdrop === n) g.backdrop = null\n if (g.edit === n) g.edit = null\n }\n for (const c of n.children) this.forget(c)\n }\n\n // ---- HostUI: content -----------------------------------------------------------------------------\n setPropertyString(id: number, prop: string, value: string | null): void {\n const n = this.nodes.get(id)\n if (!n) return\n const v = value ?? \"\"\n switch (prop) {\n case \"text\": n.text = v; n.wrapCache = undefined; break\n case \"value\": n.value = v; break\n case \"name\": n.name = v || undefined; break\n case \"src\": {\n n.src = v || undefined\n const src = this.host.resolveSrc(this.srcOf(n))\n if (src && !this.host.getImage(src)) {\n this.host.loadImage(src).then(() => { if (this.nodes.get(id) === n && this.M._nodeHasMeasure(id)) this.M._markNodeDirty(id); this.dirty = true }).catch(() => {})\n }\n break\n }\n case \"sourceRect\": {\n const p = v.split(\" \").map(Number)\n n.sourceRect = p.length === 4 ? [p[0], p[1], p[2], p[3]] : undefined\n break\n }\n case \"focus\": if (v === \"1\" || v === \"true\") this.focusInput(id); else if (this.focused === n) this.blurInput(); break\n case \"viewName\": n.viewName = v; break\n case \"viewParams\": n.viewParams = v; break\n default: break // viewParams, placeholder-like props reach the style through creator-ui\n }\n this.dirty = true\n }\n private srcOf(n: HNode): unknown { return wireSrc(n.src) }\n setPropertyInt(id: number, prop: string, value: number): void {\n const n = this.nodes.get(id)\n if (n) { if (prop === \"playerId\") n.playerId = value; else if (prop === \"viewId\") n.viewId = value }\n this.dirty = true\n }\n setFlags(id: number, mask: number): void { const n = this.nodes.get(id); if (n) n.flags = mask >>> 0 }\n\n // ---- HostUI: presentation -------------------------------------------------------------------------\n /** The screen that was shown stays painted until the runtime drops it — one at a time: the\n * runtime lands a transition before it starts the next one. */\n private leave(above: boolean): void {\n if (!this.root) return\n this.leaving = this.root\n this.leavingAbove = above\n this.root = null\n }\n openView(kind: number, node: number, id: number, _viewName: string, _paramsJson: string, above: boolean): void {\n this.destKind = kind\n const next = kind === TREE_DEST_SCREEN ? this.nodes.get(node) ?? null : null\n if (next !== this.root) this.leave(!above || next === null) // a screen next to a surface is above it\n if (this.leaving === next) this.leaving = null\n this.root = next\n if (this.focused) this.blurInput() // a navigation dismisses the keyboard\n this.dirty = true\n this.onDestination?.(kind, id)\n }\n dropView(kind: number, node: number, id: number): void {\n if (kind === TREE_DEST_SCREEN) {\n const n = this.nodes.get(node) ?? null\n if (n !== null && this.leaving === n) this.leaving = null\n if (n !== null && this.root === n) this.root = null\n }\n this.dirty = true\n this.onDropped?.(kind, id)\n }\n closeView(): void { this.destKind = -1; this.leave(true); this.dirty = true; this.onDestination?.(-1, 0) }\n widgetOpen(node: number, _ownerKind: number, _ownerId: number, _ownerNode: number): void {\n const w = this.nodes.get(node)\n if (w && !this.widgetRoots.includes(w)) this.widgetRoots.push(w)\n this.dirty = true\n }\n widgetClose(node: number): void {\n const w = this.nodes.get(node)\n for (const g of this.gestures.values()) if (g.backdrop === w) g.backdrop = null\n const i = w ? this.widgetRoots.indexOf(w) : -1\n if (i >= 0) this.widgetRoots.splice(i, 1)\n this.dirty = true\n }\n registerFont(url: string, fontFamily: string, weight: number, style: number, onComplete: () => void, onReject: (err: string) => void): void {\n this.fontsPending++\n this.host.loadFont(fontFamily, url, { weight, style: style === 2 ? \"italic\" : \"normal\" })\n .then(() => { this.invalidateText(); onComplete() }, (e) => onReject(String(e)))\n .finally(() => { this.fontsPending-- })\n }\n /** A late face changes metrics without touching any style: re-measure every text leaf. */\n private invalidateText(): void {\n for (const n of this.nodes.values()) {\n n.wrapCache = undefined\n if (n.measured && n.type !== \"image\" && this.M._nodeHasMeasure(n.id)) this.M._markNodeDirty(n.id)\n }\n this.dirty = true\n }\n showToast(message: string, duration: number): void { this.lastToast = message; this.options.onToast?.(message, duration) }\n getButtonPressed(node: number): boolean { return this.pressed.has(node) }\n getTextValue(node: number): string { return this.nodes.get(node)?.value ?? \"\" }\n getBoundingRect(node: number): ArrayLike<number> | null {\n const r = this.findRect(node)\n return r ? [r.x, r.y, r.width, r.height] : null\n }\n longPressHandler(pointerId: number, _node: number): void {\n const g = this.gestures.get(pointerId)\n if (g) g.swallowClick = true\n }\n vlistScroll(node: number, scrollY: number, _animated: boolean): void {\n const n = this.nodes.get(node)\n if (n) n.scrollOffset = scrollY\n this.dirty = true\n }\n /** \"select\" / \"content\": the pages are re-read from the runtime's pulls when the frame is built;\n * nothing is in flight then (the runtime lands a pager's transition before either). */\n pagerCommand(node: number, _cmd: string, _animated: boolean): void {\n this.pagerLeaving.delete(node)\n this.dirty = true\n }\n /** `page` is the top of the current tab now: the page shown there stays shown, under it or over\n * it, until the runtime drops it. */\n pagerShowPage(node: number, page: number, above: boolean): void {\n const next = this.nodes.get(page), shown = this.pagerShown.get(node)\n if (next) this.pagerShown.set(node, next)\n if (shown && shown !== next) this.pagerLeaving.set(node, { page: shown, above: !above })\n this.dirty = true\n }\n pagerDropPage(node: number, page: number): void {\n if (this.pagerLeaving.get(node)?.page.id === page) this.pagerLeaving.delete(node)\n this.dirty = true\n }\n pagerPageMounted(_page: number, _mounted: boolean): void { this.dirty = true }\n refreshDone(_node: number): void {}\n\n // ---- input: focus + values --------------------------------------------------------------------------\n private rootOf(n: HNode): HNode { let r = n; while (r.parent) r = r.parent; return r }\n private emitKeyboard(): void {\n const h = this.keyboardHeight()\n this.options.onKeyboard?.(h)\n this.M._creatorWebKeyboardEvent(h, 0)\n }\n focusInput(id: number): void {\n const n = this.nodes.get(id)\n if (!n || !n.editable || this.focused === n) return\n if (this.focused) this.blurInput()\n this.focused = n\n this.M._setNodeFocused(id, 1)\n if (n.has(TREE_FLAG_FOCUS)) this.M._creatorWebNodeEvent(id, TREE_EVENT_FOCUS)\n // the focused-root rule: only the root that owns the input re-flows above the keyboard band\n this.M._creatorWebSetShrunkRoot(this.rootOf(n).id, this.keyboardHeight())\n this.emitKeyboard()\n this.dirty = true\n }\n blurInput(): void {\n const n = this.focused\n if (!n) return\n this.focused = null\n this.M._setNodeFocused(n.id, 0)\n if (n.has(TREE_FLAG_BLUR)) this.M._creatorWebNodeEvent(n.id, TREE_EVENT_BLUR)\n this.M._creatorWebSetShrunkRoot(0, 0)\n this.emitKeyboard()\n this.dirty = true\n }\n /** A value typed by the user: onChange fires (a code-set value comes through setPropertyString). */\n setInputValue(id: number, value: string): void {\n const n = this.nodes.get(id)\n if (!n) return\n n.value = value\n if (n.has(TREE_FLAG_CHANGE)) this.withStr(value, (p) => this.M._creatorWebNodeEventStr(id, TREE_EVENT_CHANGE, p))\n if (this.M._nodeHasMeasure(id)) this.M._markNodeDirty(id)\n this.dirty = true\n }\n /** The return key on the focused input: onSubmit with its value, then the keyboard goes. */\n submitInput(): boolean {\n const n = this.focused\n if (!n) return false\n if (n.has(TREE_FLAG_SUBMIT)) this.withStr(n.value, (p) => this.M._creatorWebNodeEventStr(n.id, TREE_EVENT_SUBMIT, p))\n if (this.focused === n) this.blurInput()\n return true\n }\n\n // ---- input: scrolling ---------------------------------------------------------------------------------\n private scrollMax(n: HNode): number {\n const rect = this.findRect(n.id) ?? n.layoutRect ?? { width: 0, height: 0 }\n const viewport = n.scrollAxis === \"x\" ? rect.width : rect.height\n const content = n.scrollAxis === \"x\" ? this.M._getContentWidth(n.id) : this.M._getContentHeight(n.id)\n return Math.max(0, content - viewport)\n }\n /** Scroll a scrollable by `delta` px along its axis (clamped); onScroll / onOverscroll fire. */\n scrollBy(id: number, delta: number): boolean {\n const n = this.nodes.get(id)\n if (!n || !n.scrollable) return false\n const max = this.scrollMax(n)\n const desired = n.scrollOffset + delta\n const next = Math.min(max, Math.max(0, desired))\n const over = desired < 0 ? desired : desired > max ? desired - max : 0\n if (over !== 0 && n.has(TREE_FLAG_OVERSCROLL)) this.M._creatorWebNodeEventNum(id, TREE_EVENT_OVERSCROLL, over)\n if (next === n.scrollOffset) return false\n n.scrollOffset = next\n if (n.type === \"vlist\" && this.M._vlistExists(id)) this.M._vlistOnScroll(id, next)\n if (n.has(TREE_FLAG_SCROLL)) this.M._creatorWebNodeScroll(id, next)\n this.dirty = true\n return true\n }\n\n // ---- input: pointers (the tgfx renderer's routing, over the render tree) -----------------------------------\n private topInteractive(x: number, y: number): HNode | null {\n const layers = this.frame()\n for (let i = layers.length - 1; i >= 0; i--) {\n const hit = hitTest(layers[i].tree, x, y, (n) => this.nodes.get(n.id)?.interactive ?? false)\n if (hit) return this.nodes.get(hit.id) ?? null\n if (layers[i].backdrop) return null\n }\n return null\n }\n private setPressed(n: HNode, pressed: boolean): void {\n if (pressed) this.pressed.add(n.id); else this.pressed.delete(n.id)\n if (this.nodes.get(n.id) === n) this.M._setNodePressed(n.id, pressed ? 1 : 0)\n this.dirty = true\n }\n // ---- input: the mouse cursor (hover) — the tgfx renderer's tickHover over the render tree ----------------\n private hoverX = 0\n private hoverY = 0\n private hoverInside = false\n private hoverMoved = false\n /** The cursor's position (logical px), button or not. Only stored: `tickHover` resolves the node\n * under it once per frame and hands it to the runtime (emitHover → `$hovered`, onMouseEnter). */\n pointerHover(x: number, y: number): void { this.hoverX = x; this.hoverY = y; this.hoverInside = true; this.hoverMoved = true }\n /** The cursor left the surface: nothing is hovered. */\n pointerLeave(): void { if (!this.hoverInside) return; this.hoverInside = false; this.hoverMoved = true }\n /** Whether this runtime module routes hover (the export landed with the 2026-09-27 rebuild). */\n get hasHover(): boolean { return typeof this.M._creatorWebHover === \"function\" }\n /** Once per frame, after layout: the topmost interactive node under the cursor → the runtime.\n * Resolved when the cursor moved or the frame changed under a still cursor, never otherwise. */\n tickHover(): void {\n if (!this.hasHover) return\n if (!this.hoverMoved && !this.dirty) return\n this.hoverMoved = false\n const node = this.hoverInside ? this.topInteractive(this.hoverX, this.hoverY) : null\n this.M._creatorWebHover(node?.id ?? 0, this.hoverX, this.hoverY)\n }\n pointerDown(fingerId: number, x: number, y: number): void {\n const M = this.M\n if (M._creatorWeb2dSceneOpen()) M._creatorWeb2dEmitPointer(0, fingerId, x, y)\n const g: Gesture = { node: null, scroll: null, backdrop: null, edit: null, global: false, dismiss: true, lastX: x, lastY: y, acc: 0, scrolling: false, swallowClick: false }\n this.gestures.set(fingerId, g)\n const layers = this.frame()\n // an editable takes the press (focus), a modal backdrop blocks below\n for (let i = layers.length - 1; i >= 0; i--) {\n const e = hitTest(layers[i].tree, x, y, (n) => this.nodes.get(n.id)?.editable ?? false)\n if (e) { const n = this.nodes.get(e.id)!; this.focusInput(n.id); g.edit = n; g.dismiss = false; return }\n if (layers[i].backdrop) break\n }\n for (let i = layers.length - 1; i >= 0; i--) {\n const layer = layers[i]\n const inter = hitTest(layer.tree, x, y, (n) => this.nodes.get(n.id)?.interactive ?? false)\n const scrollHit = hitTest(layer.tree, x, y, (n) => !!n.scroll && n.scroll.content > (n.scroll.axis === \"x\" ? n.rect.width : n.rect.height) + 0.5)\n const scroll = scrollHit ? this.nodes.get(scrollHit.id) ?? null : null\n if (inter) {\n const n = this.nodes.get(inter.id)!\n g.node = n\n g.scroll = scroll\n g.dismiss = n.type !== \"button\" // a control keeps the keyboard up\n this.setPressed(n, true)\n M._creatorWebNodeTouchStart(n.id, fingerId, x, y)\n return\n }\n if (scroll) { g.scroll = scroll; return }\n if (layer.backdrop) {\n const r = layer.tree.rect\n const insideBody = x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height\n g.backdrop = insideBody ? null : this.nodes.get(layer.tree.id) ?? null\n return\n }\n }\n g.global = true\n M._creatorWebSceneTouchStart(fingerId, x, y)\n }\n pointerMove(fingerId: number, x: number, y: number): void {\n const g = this.gestures.get(fingerId)\n if (!g) return\n const M = this.M\n if (M._creatorWeb2dSceneOpen()) M._creatorWeb2dEmitPointer(1, fingerId, x, y)\n const dx = x - g.lastX, dy = y - g.lastY\n g.lastX = x; g.lastY = y\n g.acc += Math.abs(dx) + Math.abs(dy)\n if (g.edit) return\n if (!g.scrolling && g.scroll && g.acc > SCROLL_THRESHOLD) {\n g.scrolling = true\n if (g.node) this.setPressed(g.node, false)\n }\n if (g.scrolling && g.scroll) { this.scrollBy(g.scroll.id, g.scroll.scrollAxis === \"x\" ? -dx : -dy); return }\n M._creatorWebTouchMove(fingerId, x, y, dx, dy)\n }\n pointerUp(fingerId: number, x: number, y: number): void {\n const g = this.gestures.get(fingerId)\n if (!g) return\n this.gestures.delete(fingerId)\n const M = this.M\n if (M._creatorWeb2dSceneOpen()) M._creatorWeb2dEmitPointer(2, fingerId, x, y)\n const dx = x - g.lastX, dy = y - g.lastY\n M._creatorWebTouchEnd(fingerId, x, y, dx, dy)\n if (g.edit) return\n if (g.scrolling && g.scroll && g.scroll.has(TREE_FLAG_SCROLL_RELEASE)) M._creatorWebNodeEvent(g.scroll.id, TREE_EVENT_SCROLL_RELEASE)\n if (g.dismiss && !g.scrolling && this.focused) this.blurInput()\n if (g.node) {\n this.setPressed(g.node, false)\n if (!g.scrolling && !g.swallowClick && this.topInteractive(x, y) === g.node && g.node.has(TREE_FLAG_CLICK)) M._creatorWebNodeClick(g.node.id, fingerId, x, y)\n } else if (g.backdrop) {\n if (!g.scrolling && g.backdrop.has(TREE_FLAG_OVERLAY_TAP)) M._creatorWebNodeEvent(g.backdrop.id, TREE_EVENT_OVERLAY_TAP)\n } else if (g.global) {\n if (!g.scrolling) M._creatorWebSceneTouchClick(fingerId, x, y)\n }\n }\n /** The pointer left without a release (the browser's pointercancel): every gesture state goes. */\n pointerCancel(fingerId: number): void {\n const g = this.gestures.get(fingerId)\n if (!g) return\n this.gestures.delete(fingerId)\n const M = this.M\n if (M._creatorWeb2dSceneOpen()) M._creatorWeb2dEmitPointer(3, fingerId, g.lastX, g.lastY)\n if (g.node) this.setPressed(g.node, false)\n M._creatorWebTouchCancel(fingerId)\n }\n /** A wheel notch over (x, y): scrolls the overflowing scrollable under it (a mouse host). */\n wheel(x: number, y: number, dx: number, dy: number): boolean {\n const layers = this.frame()\n for (let i = layers.length - 1; i >= 0; i--) {\n const hit = hitTest(layers[i].tree, x, y, (n) => !!n.scroll && n.scroll.content > (n.scroll.axis === \"x\" ? n.rect.width : n.rect.height) + 0.5)\n if (hit) { const n = this.nodes.get(hit.id); return n ? this.scrollBy(n.id, n.scrollAxis === \"x\" ? dx : dy) : false }\n if (layers[i].backdrop) return false\n }\n return false\n }\n /** A long press: the runtime asks the node's listener; a handled one swallows the release's click. */\n longPress(fingerId: number, x: number, y: number): void {\n const g = this.gestures.get(fingerId)\n if (g?.node && g.node.has(TREE_FLAG_LONG_PRESS)) this.M._creatorWebNodeLongPress(g.node.id, fingerId, x, y)\n }\n isVlist(n: HNode): boolean { return this.vlists.has(n) }\n}\n","// The TreeUI of a browser page: the painted picture, and the few things a browser shows better than\n// a painter — the way a native host keeps a platform view for them:\n//\n// under the picture a native view (a plugin's web half: a map, a camera) and a video. The\n// painter leaves a window where the node is (`clearRoundRect`), so what the\n// app paints AFTER the node — a button over the map — is over it.\n// over the picture the field being edited: a live <input> / <textarea> in the place of its\n// node, for as long as it has the focus — the caret, the selection, the\n// clipboard and the input method are the browser's. The painter leaves the\n// field's text out meanwhile.\n//\n// Both are placed from the render tree every time it changes: the box of the node, moved by the\n// transforms above it (a screen in a transition carries its field along), cut by the clips above it.\nimport type { WasmModule } from \"lecodes-web-runtime/src/gen/wasm\"\nimport type { WebViewFactory, WebViewInstanceHandle } from \"lecodes-web-shared/src/ui/nativeView\"\nimport { getPlayer } from \"lecodes-web-shared/src/utils/mediaplayer\"\nimport { TREE_DEST_NATIVE } from \"lecodes-sdk/ui/tree\"\nimport { hitTest } from \"../core/hitTest\"\nimport type { Host } from \"../host/Host\"\nimport type { PaintOptions } from \"../paint/paintTree\"\nimport { TreeUI, type TreeUIOptions } from \"../runtime/TreeUI\"\nimport type { Rect, RenderNode } from \"../types\"\n\nconst FIELD_STYLE = `\n.lc-field { position: absolute; left: 0; top: 0; margin: 0; border: none; outline: none; background: none; resize: none; box-sizing: border-box; transform-origin: 0 0; pointer-events: auto; overflow: hidden; -webkit-appearance: none; appearance: none; }\n.lc-field::placeholder { color: var(--lc-placeholder, #999); opacity: 1; }\n`\n\nconst hex = (v: number | undefined, fallback: string) => (v === undefined ? fallback : \"#\" + (v >>> 0).toString(16).padStart(8, \"0\"))\nconst isSurface = (n: { type: string }) => n.type === \"native\" || n.type === \"video\"\n\ntype Matrix = [number, number, number, number, number, number]\nconst IDENTITY: Matrix = [1, 0, 0, 1, 0, 0]\n/** `m` then `n` in the coordinate system `m` made (the painter's `transform`). */\nconst multiply = (m: Matrix, n: Matrix): Matrix => [\n m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1],\n m[0] * n[2] + m[2] * n[3], m[1] * n[2] + m[3] * n[3],\n m[0] * n[4] + m[2] * n[5] + m[4], m[1] * n[4] + m[3] * n[5] + m[5],\n]\nconst intersect = (a: Rect | null, b: Rect): Rect => {\n if (!a) return b\n const x = Math.max(a.x, b.x), y = Math.max(a.y, b.y)\n return { x, y, width: Math.max(0, Math.min(a.x + a.width, b.x + b.width) - x), height: Math.max(0, Math.min(a.y + a.height, b.y + b.height) - y) }\n}\n\n/** Where a node is: its box, the transform of everything above it, the clip of everything above it. */\ntype Place = { node: RenderNode, matrix: Matrix, clip: Rect | null }\n\nexport class BrowserUI extends TreeUI {\n private readonly doc: Document\n private readonly factories = new Map<string, WebViewFactory>()\n private readonly versions = new Map<string, number>()\n private readonly views = new Map<number, { name: string, params: string, handle: WebViewInstanceHandle }>()\n /** The wrapper of a native node's view, by node id. */\n private readonly wrappers = new Map<number, HTMLElement>()\n /** What is under the picture now, by node id (a wrapper, or a video's own element). */\n private readonly shown = new Map<number, HTMLElement>()\n /** The fullscreen native destination (openView kind 3), null when none. */\n private destination: { viewId: number, el: HTMLElement } | null = null\n private field: { id: number, el: HTMLInputElement | HTMLTextAreaElement } | null = null\n private placedFor: unknown = null\n\n /** `under` and `over` are the host's layers below and above the painted canvas. */\n constructor(M: WasmModule, host: Host, private readonly under: HTMLElement, private readonly over: HTMLElement, options: TreeUIOptions = {}) {\n super(M, host, options)\n this.doc = under.ownerDocument\n const style = this.doc.createElement(\"style\")\n style.textContent = FIELD_STYLE\n over.appendChild(style)\n }\n\n /** What the page shows itself: the painter leaves it out. */\n paintOptions(): PaintOptions { return { surfaces: true, editing: this.field?.id } }\n\n // ---- native views: the plugins' web halves -----------------------------------------------------------\n /** `version` = the contract version the half was generated from (1 for one written by hand). */\n registerView(name: string, factory: WebViewFactory, version = 1): void { this.factories.set(name, factory); this.versions.set(name, version) }\n /** A view the next bundle does not have (its plugin is not among the app's): unsupported again. */\n unregisterView(name: string): void { this.factories.delete(name); this.versions.delete(name) }\n isViewSupported(name: string): boolean { return this.factories.has(name) }\n viewVersion(name: string): number { return this.versions.get(name) ?? 0 }\n\n private ensureView(viewId: number, name: string, params: string): WebViewInstanceHandle | null {\n const live = this.views.get(viewId)\n // A new project world restarts the SDK's view ids from 1: another name or other params under a\n // live id is an instance of the world that left.\n if (live && (live.name !== name || live.params !== params)) this.destroyView(viewId)\n else if (live) return live.handle\n const factory = this.factories.get(name)\n if (!factory) return null\n let parsed: unknown = {}\n try { parsed = params ? JSON.parse(params) : {} } catch { /* the runtime's JSON */ }\n // An event's payload crosses as the value it is: the app and this host are the same JavaScript.\n const handle = factory(parsed, { emit: (event, data) => this.M.jsb.viewEvent(viewId, event, data) }, this.doc)\n handle.el.style.cssText += \";position:absolute;inset:0;width:100%;height:100%;\"\n this.views.set(viewId, { name, params, handle })\n return handle\n }\n private destroyView(viewId: number): void {\n const live = this.views.get(viewId)\n if (!live) return\n this.views.delete(viewId)\n live.handle.destroy?.()\n live.handle.el.remove()\n }\n /** `args` is the app's own array: a half reads it, never keeps or changes it. */\n viewCall(viewId: number, method: string, args: unknown, onComplete: (result?: unknown) => void, onReject: (message: string) => void): void {\n const live = this.views.get(viewId)\n if (!live?.handle.call) { onReject(`NativeView call \"${method}\": no live instance or no call handler (viewId ${viewId})`); return }\n try {\n Promise.resolve(live.handle.call(method, Array.isArray(args) ? args : [])).then(\n (result) => { if (result === undefined) onComplete(); else onComplete(result) },\n (e) => onReject(e instanceof Error ? e.message : String(e)),\n )\n } catch (e) { onReject(e instanceof Error ? e.message : String(e)) }\n }\n\n // A native destination is a surface: it stays where it is until the runtime drops it (a screen\n // may still be coming in over it), under every screen.\n override openView(kind: number, node: number, id: number, viewName: string, paramsJson: string, above: boolean): void {\n super.openView(kind, node, id, viewName, paramsJson, above)\n if (kind !== TREE_DEST_NATIVE) return\n this.dropDestination()\n const handle = this.ensureView(id, viewName, paramsJson)\n if (!handle) return\n const el = this.doc.createElement(\"div\")\n el.style.cssText = \"position:absolute;inset:0;pointer-events:auto;\"\n el.appendChild(handle.el)\n this.under.prepend(el)\n this.destination = { viewId: id, el }\n }\n override dropView(kind: number, node: number, id: number): void {\n super.dropView(kind, node, id)\n // …unless the one on screen now is that very view, presented again\n if (kind === TREE_DEST_NATIVE && this.destination?.viewId === id && this.destKind !== TREE_DEST_NATIVE) this.dropDestination()\n }\n private dropDestination(): void {\n this.destination?.el.remove()\n this.destination = null\n }\n\n override releaseNode(id: number): void {\n const n = this.get(id)\n if (this.field?.id === id) this.unmountField()\n super.releaseNode(id)\n this.shown.get(id)?.remove()\n this.shown.delete(id)\n this.wrappers.delete(id)\n if (n?.type === \"native\" && n.viewId) this.destroyView(n.viewId)\n }\n\n // ---- the field being edited ---------------------------------------------------------------------------\n override focusInput(id: number): void {\n super.focusInput(id)\n if (this.focusedId() !== id || this.field?.id === id) return\n this.unmountField()\n const node = this.get(id)\n if (!node) return\n const el = this.doc.createElement(node.type === \"textarea\" ? \"textarea\" : \"input\")\n el.className = \"lc-field\"\n el.setAttribute(\"autocomplete\", \"off\")\n el.value = node.value\n el.addEventListener(\"input\", () => { if (this.focusedId() === id) this.setInputValue(id, el.value) })\n el.addEventListener(\"keydown\", (e) => { if ((e as KeyboardEvent).key === \"Enter\" && el.tagName === \"INPUT\") { e.preventDefault(); this.submitInput() } })\n // the browser took the focus away (another window, a tab key): the app's field lost it too\n el.addEventListener(\"blur\", () => { if (this.field?.el === el && this.focusedId() === id) this.blurInput() })\n this.over.appendChild(el)\n this.field = { id, el }\n this.placedFor = null // placed with the next frame; focused now, inside the gesture that asked\n this.place()\n el.focus({ preventScroll: true })\n }\n override blurInput(): void {\n super.blurInput()\n this.unmountField()\n }\n private unmountField(): void {\n const field = this.field\n if (!field) return\n this.field = null\n field.el.remove()\n this.placedFor = null\n }\n override setPropertyString(id: number, prop: string, value: string | null): void {\n super.setPropertyString(id, prop, value)\n // a value the CODE set while the field is edited\n if (prop === \"value\" && this.field?.id === id) { const v = this.get(id)?.value ?? \"\"; if (this.field.el.value !== v) this.field.el.value = v }\n }\n\n // ---- placing ------------------------------------------------------------------------------------------\n /** The nodes the page shows itself, where the frame has them. */\n private find(): Place[] {\n const found: Place[] = []\n const editing = this.field?.id\n const walk = (node: RenderNode, above: Matrix, clip: Rect | null) => {\n let matrix = above\n const t = node.style.transform\n if (t) {\n // the painter's: the node's matrix about its transform origin (its centre by default)\n const o = node.style.transformOrigin\n const cx = node.rect.x + (o ? (o.xPercent ? node.rect.width * o.x / 100 : o.x) : node.rect.width / 2)\n const cy = node.rect.y + (o ? (o.yPercent ? node.rect.height * o.y / 100 : o.y) : node.rect.height / 2)\n matrix = multiply(multiply(multiply(above, [1, 0, 0, 1, cx, cy]), t as unknown as Matrix), [1, 0, 0, 1, -cx, -cy])\n }\n if (isSurface(node) || node.id === editing) found.push({ node, matrix, clip })\n const inner = node.clip ? intersect(clip, node.rect) : clip\n for (const child of node.children) walk(child, matrix, inner)\n }\n for (const layer of this.frame()) walk(layer.tree, IDENTITY, null)\n return found\n }\n private static put(el: HTMLElement, place: Place): void {\n const { rect } = place.node\n const s = el.style\n s.position = \"absolute\"\n s.left = \"0\"\n s.top = \"0\"\n s.width = rect.width + \"px\"\n s.height = rect.height + \"px\"\n s.transformOrigin = \"0 0\"\n s.transform = `matrix(${place.matrix.join(\",\")}) translate(${rect.x}px,${rect.y}px)`\n const c = place.clip\n // the clip is in the frame's coordinates, the element's clip-path in its own box\n s.clipPath = c ? `inset(${Math.max(0, c.y - rect.y)}px ${Math.max(0, rect.x + rect.width - (c.x + c.width))}px ${Math.max(0, rect.y + rect.height - (c.y + c.height))}px ${Math.max(0, c.x - rect.x)}px)` : \"\"\n }\n private surfaceElement(node: RenderNode): HTMLElement | null {\n const n = this.get(node.id)\n if (!n) return null\n if (n.type === \"video\") {\n const player = getPlayer(n.playerId)\n return player instanceof HTMLVideoElement ? player : null\n }\n if (!n.viewId) return null\n const handle = this.ensureView(n.viewId, n.viewName ?? \"\", n.viewParams ?? \"\")\n if (!handle) return null\n let wrapper = this.wrappers.get(n.id)\n if (!wrapper) { wrapper = this.doc.createElement(\"div\"); this.wrappers.set(n.id, wrapper) }\n if (handle.el.parentElement !== wrapper) wrapper.replaceChildren(handle.el)\n return wrapper\n }\n private styleField(el: HTMLInputElement | HTMLTextAreaElement, node: RenderNode): void {\n const s = node.style\n const st = el.style\n const [pl, pt, pr, pb] = node.padding ?? [0, 0, 0, 0]\n st.padding = `${pt}px ${pr}px ${pb}px ${pl}px`\n st.color = hex(s.color, \"#000000ff\")\n st.caretColor = st.color\n const family = s.fontFamily ?? \"Roboto\"\n st.fontFamily = this.host.resolveFontFamily?.(family) ?? family\n st.fontSize = (s.fontSize ?? 14) + \"px\"\n st.fontWeight = String(s.fontWeight ?? 400)\n st.fontStyle = s.fontStyle ?? \"normal\"\n st.letterSpacing = (s.letterSpacing ?? 0) + \"px\"\n // a textarea's lines are the node's; an input is one line, centred in the field by the browser\n st.lineHeight = el.tagName === \"TEXTAREA\" && s.lineHeight !== undefined ? s.lineHeight + \"px\" : \"normal\"\n st.textAlign = s.textAlign === \"center\" ? \"center\" : s.textAlign === \"end\" ? \"right\" : \"left\"\n st.borderRadius = \"0\"\n el.placeholder = s.placeholder ?? \"\"\n st.setProperty(\"--lc-placeholder\", hex(s.placeholderColor, \"#999999ff\"))\n if (el instanceof HTMLInputElement) { const type = s.inputType ?? \"text\"; if (el.type !== type) el.type = type }\n }\n /** After the paint: what the page shows itself goes where the frame has it. */\n place(): void {\n const frame = this.frame()\n if (frame === this.placedFor) return\n this.placedFor = frame\n const seen = new Set<number>()\n for (const place of this.find()) {\n const { node } = place\n if (node.id === this.field?.id) {\n this.styleField(this.field.el, node)\n BrowserUI.put(this.field.el, place)\n continue\n }\n const el = this.surfaceElement(node)\n if (!el) continue\n seen.add(node.id)\n if (el.parentElement !== this.under) this.under.appendChild(el)\n el.style.display = \"block\"\n el.style.opacity = \"\"\n el.style.pointerEvents = \"auto\" // where the picture has a window onto it\n if (el instanceof HTMLVideoElement) el.style.objectFit = node.style.objectFit ?? \"contain\"\n BrowserUI.put(el, place)\n this.shown.set(node.id, el)\n }\n // what the frame no longer shows (a page that left, a node taken out): kept, not seen\n for (const [id, el] of this.shown) if (!seen.has(id)) { el.style.display = \"none\"; this.shown.delete(id) }\n }\n\n // ---- whose the pointer is --------------------------------------------------------------------------------\n /** Whether the point is a surface's: the topmost thing there that takes input is a native view\n * (or the native destination, with nothing of the UI over it) — the event is that view's. */\n surfaceAt(x: number, y: number): boolean {\n const layers = this.frame()\n for (let i = layers.length - 1; i >= 0; i--) {\n const layer = layers[i]!\n if (layer.leaving) continue\n const hit = hitTest(layer.tree, x, y, (n) => n.type === \"native\" || (this.get(n.id)?.interactive ?? false) || (this.get(n.id)?.editable ?? false) || !!n.scroll)\n if (hit) return hit.type === \"native\"\n if (layer.backdrop) return false\n }\n return this.destination !== null\n }\n\n dispose(): void {\n this.unmountField()\n for (const id of [...this.views.keys()]) this.destroyView(id)\n this.dropDestination()\n for (const el of this.shown.values()) if (!(el instanceof HTMLVideoElement)) el.remove()\n this.shown.clear()\n }\n}\n","// What the browser renderer shows of the host's own: the toast strip.\n\n/** A transient toast strip at the bottom of the root (duration in ms; ≤ 0 = 2 s). */\nexport function showToast(doc: Document, root: HTMLElement, message: string, duration: number) {\n const el = doc.createElement(\"div\")\n el.textContent = message\n el.style.cssText =\n \"position:absolute;left:50%;bottom:48px;transform:translateX(-50%);max-width:80%;padding:10px 16px;border-radius:8px;\" +\n \"background:rgba(30,30,30,0.92);color:#fff;font:13px/1.4 system-ui,sans-serif;z-index:30;pointer-events:none;\"\n root.appendChild(el)\n setTimeout(() => el.remove(), duration > 0 ? duration : 2000)\n}\n","// The canvas renderer in the browser: the TreeUI (the runtime's HostUI table) painted to a 2D canvas\n// that lies over the scene canvases, with a layer under it for the native views and the videos and\n// a layer over it for the field being edited (./BrowserUI.ts). The host calls `render()` after each\n// layout pass.\n//\n// The canvas is the host's: it sizes the backing store (device px, the host's page), the renderer\n// only paints. Nothing here draws a keyboard or a device — the page is the app's window.\n//\n// POINTERS. The painted canvas takes no pointer itself (`pointer-events: none`): an event lands on\n// what is under the pointer in the page — a native view, a scene canvas, the container — and the\n// renderer meets it on its way down, at the container, in the capture phase. There the render tree\n// says whose the point is. The UI's: the event goes to the TreeUI's routing (logical px), and\n// stops before a view under the picture hears of it. A native view's: it goes on to the view.\nimport type { WasmModule } from \"lecodes-web-runtime/src/gen/wasm\"\nimport type { CanvasHost } from \"lecodes-web-shared/src/canvas/createCanvasHost\"\nimport { getUrl } from \"lecodes-web-shared/src/utils/fetch\"\nimport { viewScale } from \"lecodes-web-shared/src/ui/viewScale\"\nimport { BrowserHost } from \"../host/BrowserHost\"\nimport { Canvas2DPainter } from \"../paint/Canvas2DPainter\"\nimport { BrowserUI } from \"./BrowserUI\"\nimport { showToast } from \"./chrome\"\n\n/** Hold this long before a press counts as a long press (the runtime asks the node's listener). */\nconst LONG_PRESS_MS = 500\n\nexport type SafeAreaEdge = \"top\" | \"right\" | \"bottom\" | \"left\"\n/** Insets in logical px; `bars` = the edges that are exact-height system bars (`comfort-*` adds its\n * knob past a bar instead of flooring against it). */\nexport type SafeArea = { top: number, right: number, bottom: number, left: number, bars?: readonly SafeAreaEdge[] }\n\nexport type CanvasRendererOptions = {\n M: WasmModule\n /** The canvas to paint on, over the scene canvases. */\n canvas: HTMLCanvasElement\n canvasHost?: CanvasHost\n /** What the window loses to the on-screen keyboard, in logical px. */\n keyboardHeight?: () => number\n}\n\n/** What a page fires for one press besides its pointer events: stopped with them on the way to a\n * view under the picture. */\nconst FOLLOWERS = [\"mousedown\", \"mouseup\", \"click\", \"dblclick\", \"contextmenu\", \"touchstart\", \"touchmove\", \"touchend\"] as const\n\nexport const createCanvasRenderer = (root: HTMLElement, options: CanvasRendererOptions) => {\n const doc = root.ownerDocument\n const { canvas } = options\n canvas.style.display = \"block\"\n canvas.style.pointerEvents = \"none\"\n root.style.touchAction = \"none\"\n const context = canvas.getContext(\"2d\")!\n\n const layer = () => {\n const el = doc.createElement(\"div\")\n el.style.cssText = \"position:absolute;inset:0;overflow:hidden;pointer-events:none;\"\n return el\n }\n const under = layer()\n const over = layer()\n root.insertBefore(under, canvas)\n canvas.after(over)\n\n // Uploaded-asset image srcs ({ _id }) resolve to blob urls through the fetch store; UIImage(canvas)\n // surfaces through the canvas host.\n const host = new BrowserHost({ resolveAssetUrl: (id) => getUrl(id), canvasSurfaces: options.canvasHost })\n const ui = new BrowserUI(options.M, host, under, over, {\n keyboardHeight: options.keyboardHeight ?? (() => 0),\n onToast: (message, duration) => showToast(doc, root, message, duration),\n })\n\n // The painter bakes the resolution factor into its transform: a new one when the factor moves.\n let factor = 1\n let painter = new Canvas2DPainter(context, factor)\n // A canvas that took a new size was WIPED: paint once even if nothing changed.\n let wiped = true\n const render = () => {\n if (wiped || ui.needsPaint()) {\n wiped = false\n ui.paint(painter, ui.paintOptions())\n }\n ui.place()\n }\n\n /** The viewport in logical px and the device px per logical px; the canvas already has the size. */\n const resize = (width: number, height: number, nextFactor: number) => {\n if (width <= 0 || height <= 0) return\n if (nextFactor !== factor) { factor = nextFactor; painter = new Canvas2DPainter(context, factor) }\n wiped = true\n ui.resize(width, height)\n }\n const setSafeArea = (area: SafeArea) => {\n ui.setSafeArea([area.top, area.right, area.bottom, area.left], area.bars ?? [])\n }\n\n // ---- pointers (logical px: clientX and the rect are VISUAL px under a CSS zoom) ----\n const local = (e: { clientX: number, clientY: number }): [number, number] => {\n const rect = root.getBoundingClientRect()\n const scale = viewScale(root)\n return [(e.clientX - rect.left) / scale, (e.clientY - rect.top) / scale]\n }\n const inField = (e: Event) => e.target instanceof Node && over.contains(e.target)\n const toView = (e: Event) => e.target instanceof Node && under.contains(e.target)\n /** The event is the UI's: a view under the picture does not hear of it. */\n const keep = (e: Event) => { if (toView(e)) e.stopPropagation() }\n\n /** The pointers the UI has (down on it, until they are up): theirs is every event that follows. */\n const held = new Set<number>()\n const longPress = new Map<number, number>()\n const clearLongPress = (id: number) => { const t = longPress.get(id); if (t !== undefined) { clearTimeout(t); longPress.delete(id) } }\n\n const onDown = (e: PointerEvent) => {\n if (inField(e)) return // the field being edited: the browser's own caret and selection\n const [x, y] = local(e)\n if (ui.surfaceAt(x, y)) return\n keep(e)\n held.add(e.pointerId)\n try { root.setPointerCapture(e.pointerId) } catch { /* detached */ }\n ui.pointerDown(e.pointerId, x, y)\n clearLongPress(e.pointerId)\n longPress.set(e.pointerId, window.setTimeout(() => { longPress.delete(e.pointerId); ui.longPress(e.pointerId, x, y) }, LONG_PRESS_MS))\n }\n // A mouse move is also the cursor's hover (button or not): stored here, resolved once per frame\n // (TreeUI.tickHover). A finger hovers nothing.\n const onMove = (e: PointerEvent) => {\n const [x, y] = local(e)\n if (held.has(e.pointerId)) { keep(e); ui.pointerMove(e.pointerId, x, y) }\n if (e.pointerType !== \"mouse\") return\n if (inField(e) || (!held.has(e.pointerId) && ui.surfaceAt(x, y))) ui.pointerLeave()\n else ui.pointerHover(x, y)\n }\n const onLeave = (e: PointerEvent) => { if (e.pointerType === \"mouse\") ui.pointerLeave() }\n const onUp = (e: PointerEvent) => {\n if (!held.delete(e.pointerId)) return\n keep(e)\n clearLongPress(e.pointerId)\n const [x, y] = local(e)\n ui.pointerUp(e.pointerId, x, y)\n }\n const onCancel = (e: PointerEvent) => {\n if (!held.delete(e.pointerId)) return\n clearLongPress(e.pointerId)\n ui.pointerCancel(e.pointerId)\n }\n const onWheel = (e: WheelEvent) => {\n if (inField(e)) return\n const [x, y] = local(e)\n if (ui.surfaceAt(x, y)) return\n keep(e)\n const k = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? ui.height : 1\n if (ui.wheel(x, y, e.deltaX * k, e.deltaY * k)) e.preventDefault()\n }\n // What follows a press the UI took: not the view's either. A mouse press on the UI moves no\n // focus and selects nothing (the field being edited keeps its caret while a button is pressed).\n const onFollower = (e: Event) => {\n if (inField(e)) return\n const point = \"clientX\" in e ? (e as MouseEvent) : (e as TouchEvent).changedTouches?.[0]\n if (!point) return\n const [x, y] = local(point)\n if (ui.surfaceAt(x, y)) return\n keep(e)\n if (e.type === \"mousedown\") e.preventDefault()\n }\n\n root.addEventListener(\"pointerdown\", onDown, true)\n root.addEventListener(\"pointermove\", onMove, true)\n root.addEventListener(\"pointerleave\", onLeave)\n root.addEventListener(\"pointerup\", onUp, true)\n root.addEventListener(\"pointercancel\", onCancel, true)\n root.addEventListener(\"wheel\", onWheel, { passive: false, capture: true })\n for (const type of FOLLOWERS) root.addEventListener(type, onFollower, true)\n\n return {\n ui,\n render,\n resize,\n setSafeArea,\n destroy() {\n for (const id of longPress.keys()) clearLongPress(id)\n root.removeEventListener(\"pointerdown\", onDown, true)\n root.removeEventListener(\"pointermove\", onMove, true)\n root.removeEventListener(\"pointerleave\", onLeave)\n root.removeEventListener(\"pointerup\", onUp, true)\n root.removeEventListener(\"pointercancel\", onCancel, true)\n root.removeEventListener(\"wheel\", onWheel, true)\n for (const type of FOLLOWERS) root.removeEventListener(type, onFollower, true)\n ui.dispose()\n under.remove()\n over.remove()\n },\n }\n}\n\nexport type CanvasRenderer = ReturnType<typeof createCanvasRenderer>\n","// GENERATED by scripts/vendor-canvas.ts from engines/canvas/spec/gen/spec.ts @ ae6bc30b952b — do not edit here.\n// Bump the submodule and run `bun run vendor:canvas`; `bun run check:canvas-ops` fails when this copy is stale.\n// GENERATED by spec/generate.ts from spec/*.h — do not edit.\n\nexport const SPEC_VERSION = 1\n\nexport const LineJoin = {\n MITER: 0,\n ROUND: 1,\n BEVEL: 2,\n} as const\nexport type LineJoin = (typeof LineJoin)[keyof typeof LineJoin]\nexport const LineJoinName: readonly string[] = [\"miter\", \"round\", \"bevel\"]\n\nexport const LineCap = {\n BUTT: 0,\n ROUND: 1,\n SQUARE: 2,\n} as const\nexport type LineCap = (typeof LineCap)[keyof typeof LineCap]\nexport const LineCapName: readonly string[] = [\"butt\", \"round\", \"square\"]\n\nexport const TextAlign = {\n LEFT: 0,\n CENTER: 1,\n RIGHT: 2,\n START: 3,\n END: 4,\n} as const\nexport type TextAlign = (typeof TextAlign)[keyof typeof TextAlign]\nexport const TextAlignName: readonly string[] = [\"left\", \"center\", \"right\", \"start\", \"end\"]\n\nexport const TextBaseline = {\n ALPHABETIC: 0,\n TOP: 1,\n MIDDLE: 2,\n BOTTOM: 3,\n HANGING: 4,\n IDEOGRAPHIC: 5,\n} as const\nexport type TextBaseline = (typeof TextBaseline)[keyof typeof TextBaseline]\nexport const TextBaselineName: readonly string[] = [\"alphabetic\", \"top\", \"middle\", \"bottom\", \"hanging\", \"ideographic\"]\n\nexport const FillRule = {\n NONZERO: 0,\n EVENODD: 1,\n} as const\nexport type FillRule = (typeof FillRule)[keyof typeof FillRule]\nexport const FillRuleName: readonly string[] = [\"nonzero\", \"evenodd\"]\n\nexport const Spread = {\n PAD: 0,\n REFLECT: 1,\n REPEAT: 2,\n} as const\nexport type Spread = (typeof Spread)[keyof typeof Spread]\nexport const SpreadName: readonly string[] = [\"pad\", \"reflect\", \"repeat\"]\n\nexport const Gradient = {\n LINEAR: 0,\n RADIAL: 1,\n} as const\nexport type Gradient = (typeof Gradient)[keyof typeof Gradient]\nexport const GradientName: readonly string[] = [\"linear\", \"radial\"]\n\nexport const Paint = {\n COLOR: 0,\n LINEAR: 1,\n RADIAL: 2,\n} as const\nexport type Paint = (typeof Paint)[keyof typeof Paint]\nexport const PaintName: readonly string[] = [\"color\", \"linear\", \"radial\"]\n\nexport const PathVerb = {\n MOVE: 0,\n LINE: 1,\n QUAD: 2,\n CUBIC: 3,\n CLOSE: 4,\n} as const\nexport type PathVerb = (typeof PathVerb)[keyof typeof PathVerb]\nexport const PathVerbName: readonly string[] = [\"move\", \"line\", \"quad\", \"cubic\", \"close\"]\n\nexport const ImageFormat = {\n PNG: 0,\n JPEG: 1,\n} as const\nexport type ImageFormat = (typeof ImageFormat)[keyof typeof ImageFormat]\nexport const ImageFormatName: readonly string[] = [\"png\", \"jpeg\"]\n\n/** The opcode stream: op id → the word after it. */\nexport const OP = {\n SAVE: 0,\n RESTORE: 1,\n TRANSLATE: 2,\n SCALE: 3,\n ROTATE: 4,\n TRANSFORM: 5,\n SET_TRANSFORM: 6,\n RESET_TRANSFORM: 7,\n GLOBAL_ALPHA: 8,\n FILL_STYLE: 9,\n STROKE_STYLE: 10,\n FILL_GRADIENT: 11,\n STROKE_GRADIENT: 12,\n LINE_WIDTH: 13,\n LINE_JOIN: 14,\n LINE_CAP: 15,\n MITER_LIMIT: 16,\n LINE_DASH: 17,\n LINE_DASH_OFFSET: 18,\n FONT: 19,\n TEXT_ALIGN: 20,\n TEXT_BASELINE: 21,\n LETTER_SPACING: 22,\n PATH_BEGIN: 23,\n PATH_CLOSE: 24,\n MOVE_TO: 25,\n LINE_TO: 26,\n QUADRATIC_TO: 27,\n BEZIER_TO: 28,\n ARC: 29,\n ARC_TO: 30,\n ELLIPSE: 31,\n RECT: 32,\n ROUND_RECT: 33,\n FILL: 34,\n STROKE: 35,\n CLIP: 36,\n FILL_RECT: 37,\n STROKE_RECT: 38,\n CLEAR_RECT: 39,\n FILL_TEXT: 40,\n STROKE_TEXT: 41,\n DRAW_IMAGE: 42,\n} as const\nexport type OP = (typeof OP)[keyof typeof OP]\n/** Operand layout per op: `args` is one letter per fixed word (f float, i int, r string ref);\n * `repeat` is the group that follows the trailing count. */\nexport const OP_ARGS: Record<number, { args: string, repeat: string }> = {\n 0: { args: \"\", repeat: \"\" },\n 1: { args: \"\", repeat: \"\" },\n 2: { args: \"ff\", repeat: \"\" },\n 3: { args: \"ff\", repeat: \"\" },\n 4: { args: \"f\", repeat: \"\" },\n 5: { args: \"ffffff\", repeat: \"\" },\n 6: { args: \"ffffff\", repeat: \"\" },\n 7: { args: \"\", repeat: \"\" },\n 8: { args: \"f\", repeat: \"\" },\n 9: { args: \"r\", repeat: \"\" },\n 10: { args: \"r\", repeat: \"\" },\n 11: { args: \"iffffffi\", repeat: \"fr\" },\n 12: { args: \"iffffffi\", repeat: \"fr\" },\n 13: { args: \"f\", repeat: \"\" },\n 14: { args: \"i\", repeat: \"\" },\n 15: { args: \"i\", repeat: \"\" },\n 16: { args: \"f\", repeat: \"\" },\n 17: { args: \"i\", repeat: \"f\" },\n 18: { args: \"f\", repeat: \"\" },\n 19: { args: \"r\", repeat: \"\" },\n 20: { args: \"i\", repeat: \"\" },\n 21: { args: \"i\", repeat: \"\" },\n 22: { args: \"f\", repeat: \"\" },\n 23: { args: \"\", repeat: \"\" },\n 24: { args: \"\", repeat: \"\" },\n 25: { args: \"ff\", repeat: \"\" },\n 26: { args: \"ff\", repeat: \"\" },\n 27: { args: \"ffff\", repeat: \"\" },\n 28: { args: \"ffffff\", repeat: \"\" },\n 29: { args: \"fffffi\", repeat: \"\" },\n 30: { args: \"fffff\", repeat: \"\" },\n 31: { args: \"fffffffi\", repeat: \"\" },\n 32: { args: \"ffff\", repeat: \"\" },\n 33: { args: \"fffff\", repeat: \"\" },\n 34: { args: \"i\", repeat: \"\" },\n 35: { args: \"\", repeat: \"\" },\n 36: { args: \"i\", repeat: \"\" },\n 37: { args: \"ffff\", repeat: \"\" },\n 38: { args: \"ffff\", repeat: \"\" },\n 39: { args: \"ffff\", repeat: \"\" },\n 40: { args: \"rfff\", repeat: \"\" },\n 41: { args: \"rfff\", repeat: \"\" },\n 42: { args: \"iffffffff\", repeat: \"\" },\n}\nexport const OP_NAME: readonly string[] = [\"save\", \"restore\", \"translate\", \"scale\", \"rotate\", \"transform\", \"setTransform\", \"resetTransform\", \"globalAlpha\", \"fillStyle\", \"strokeStyle\", \"fillGradient\", \"strokeGradient\", \"lineWidth\", \"lineJoin\", \"lineCap\", \"miterLimit\", \"lineDash\", \"lineDashOffset\", \"font\", \"textAlign\", \"textBaseline\", \"letterSpacing\", \"pathBegin\", \"pathClose\", \"moveTo\", \"lineTo\", \"quadraticTo\", \"bezierTo\", \"arc\", \"arcTo\", \"ellipse\", \"rect\", \"roundRect\", \"fill\", \"stroke\", \"clip\", \"fillRect\", \"strokeRect\", \"clearRect\", \"fillText\", \"strokeText\", \"drawImage\"]\n\n/** The draw list: command id → the word after it. */\nexport const DRAW = {\n SET_TRANSFORM: 0,\n SAVE: 1,\n RESTORE: 2,\n CLIP: 3,\n FILL_PATH: 4,\n STROKE_PATH: 5,\n FILL_TEXT: 6,\n STROKE_TEXT: 7,\n DRAW_IMAGE: 8,\n CLEAR_RECT: 9,\n} as const\nexport type DRAW = (typeof DRAW)[keyof typeof DRAW]\nexport const DRAW_NAME: readonly string[] = [\"setTransform\", \"save\", \"restore\", \"clip\", \"fillPath\", \"strokePath\", \"fillText\", \"strokeText\", \"drawImage\", \"clearRect\"]\n","// GENERATED by scripts/vendor-canvas.ts from engines/canvas/painters/web/src/drawlist.ts @ ae6bc30b952b — do not edit here.\n// Bump the submodule and run `bun run vendor:canvas`; `bun run check:canvas-ops` fails when this copy is stale.\n// The draw list in TypeScript: the typed commands, the reader of the word buffer (spec/draw.h) and\n// the reader of the core's JSON dump. Both produce the same DrawCommand objects — the tests hold the\n// two readers against each other on every golden.\nimport {\n DRAW, Paint as PaintKind, PathVerb, LineJoinName, LineCapName, TextAlignName, TextBaselineName, FillRuleName, SpreadName,\n} from \"./spec\"\n\nexport type Color = [number, number, number, number]\nexport type Matrix6 = [number, number, number, number, number, number]\nexport interface Stop { offset: number, color: Color }\nexport interface ColorPaint { kind: \"color\", alpha: number, color: Color }\nexport interface LinearPaint { kind: \"linear\", alpha: number, matrix: Matrix6, spread: string, stops: Stop[] }\nexport interface RadialPaint { kind: \"radial\", alpha: number, matrix: Matrix6, fx: number, fy: number, r0: number, spread: string, stops: Stop[] }\nexport type Paint = ColorPaint | LinearPaint | RadialPaint\nexport interface Stroke { width: number, join: string, cap: string, miterLimit: number, dashOffset: number, dash: number[] }\nexport interface Font { family: string, size: number, weight: number, italic: boolean }\nexport type PathSeg = [\"M\", number, number] | [\"L\", number, number] | [\"Q\", number, number, number, number] | [\"C\", number, number, number, number, number, number] | [\"Z\"]\n\nexport type DrawCommand =\n | { cmd: \"setTransform\", matrix: Matrix6 }\n | { cmd: \"save\" }\n | { cmd: \"restore\" }\n | { cmd: \"clip\", rule: string, path: PathSeg[] }\n | { cmd: \"fillPath\", rule: string, paint: Paint, path: PathSeg[] }\n | { cmd: \"strokePath\", stroke: Stroke, paint: Paint, path: PathSeg[] }\n | { cmd: \"fillText\", text: string, x: number, y: number, maxWidth: number, font: Font, align: string, baseline: string, letterSpacing: number, paint: Paint }\n | { cmd: \"strokeText\", text: string, x: number, y: number, maxWidth: number, font: Font, align: string, baseline: string, letterSpacing: number, stroke: Stroke, paint: Paint }\n | { cmd: \"drawImage\", surface: number, src: [number, number, number, number], dst: [number, number, number, number], alpha: number }\n | { cmd: \"clearRect\", rect: [number, number, number, number] }\n\nclass Reader {\n pos = 0\n constructor(readonly w: Float32Array, readonly strings: readonly string[]) {}\n f(): number { if (this.pos >= this.w.length) throw new Error(\"draw list: truncated\"); return this.w[this.pos++] }\n i(): number { return this.f() | 0 }\n str(): string { const i = this.i(); if (i < 0 || i >= this.strings.length) throw new Error(`draw list: bad string index ${i}`); return this.strings[i] }\n color(): Color { return [this.f(), this.f(), this.f(), this.f()] }\n matrix(): Matrix6 { return [this.f(), this.f(), this.f(), this.f(), this.f(), this.f()] }\n paint(): Paint {\n const kind = this.i(), alpha = this.f()\n if (kind === PaintKind.COLOR) return { kind: \"color\", alpha, color: this.color() }\n const matrix = this.matrix()\n let fx = 0, fy = 0, r0 = 0\n if (kind === PaintKind.RADIAL) { fx = this.f(); fy = this.f(); r0 = this.f() }\n const spread = SpreadName[this.i()] ?? \"pad\"\n const n = this.i()\n const stops: Stop[] = []\n for (let k = 0; k < n; k++) stops.push({ offset: this.f(), color: this.color() })\n return kind === PaintKind.RADIAL ? { kind: \"radial\", alpha, matrix, fx, fy, r0, spread, stops } : { kind: \"linear\", alpha, matrix, spread, stops }\n }\n stroke(): Stroke {\n const width = this.f(), join = LineJoinName[this.i()] ?? \"miter\", cap = LineCapName[this.i()] ?? \"butt\"\n const miterLimit = this.f(), dashOffset = this.f(), n = this.i()\n const dash: number[] = []\n for (let k = 0; k < n; k++) dash.push(this.f())\n return { width, join, cap, miterLimit, dashOffset, dash }\n }\n font(): Font { return { family: this.str(), size: this.f(), weight: this.i(), italic: this.i() !== 0 } }\n path(): PathSeg[] {\n const n = this.i()\n const end = this.pos + n\n if (end > this.w.length) throw new Error(\"draw list: truncated path\")\n const segs: PathSeg[] = []\n while (this.pos < end) {\n switch (this.i()) {\n case PathVerb.MOVE: segs.push([\"M\", this.f(), this.f()]); break\n case PathVerb.LINE: segs.push([\"L\", this.f(), this.f()]); break\n case PathVerb.QUAD: segs.push([\"Q\", this.f(), this.f(), this.f(), this.f()]); break\n case PathVerb.CUBIC: segs.push([\"C\", this.f(), this.f(), this.f(), this.f(), this.f(), this.f()]); break\n case PathVerb.CLOSE: segs.push([\"Z\"]); break\n default: throw new Error(\"draw list: bad path verb\")\n }\n }\n return segs\n }\n rect4(): [number, number, number, number] { return [this.f(), this.f(), this.f(), this.f()] }\n}\n\n/** Decode a word buffer + string table into commands. A command this build does not know is skipped. */\nexport const readDrawList = (words: Float32Array, strings: readonly string[]): DrawCommand[] => {\n const r = new Reader(words, strings)\n const out: DrawCommand[] = []\n while (r.pos + 2 <= words.length) {\n const cmd = r.i(), len = r.i()\n const end = r.pos + len\n if (len < 0 || end > words.length) throw new Error(\"draw list: truncated command\")\n switch (cmd) {\n case DRAW.SET_TRANSFORM: out.push({ cmd: \"setTransform\", matrix: r.matrix() }); break\n case DRAW.SAVE: out.push({ cmd: \"save\" }); break\n case DRAW.RESTORE: out.push({ cmd: \"restore\" }); break\n case DRAW.CLIP: { const rule = FillRuleName[r.i()] ?? \"nonzero\"; out.push({ cmd: \"clip\", rule, path: r.path() }); break }\n case DRAW.FILL_PATH: { const rule = FillRuleName[r.i()] ?? \"nonzero\"; const paint = r.paint(); out.push({ cmd: \"fillPath\", rule, paint, path: r.path() }); break }\n case DRAW.STROKE_PATH: { const stroke = r.stroke(); const paint = r.paint(); out.push({ cmd: \"strokePath\", stroke, paint, path: r.path() }); break }\n case DRAW.FILL_TEXT: case DRAW.STROKE_TEXT: {\n const text = r.str(), x = r.f(), y = r.f(), maxWidth = r.f(), font = r.font()\n const align = TextAlignName[r.i()] ?? \"start\", baseline = TextBaselineName[r.i()] ?? \"alphabetic\", letterSpacing = r.f()\n if (cmd === DRAW.STROKE_TEXT) { const stroke = r.stroke(); out.push({ cmd: \"strokeText\", text, x, y, maxWidth, font, align, baseline, letterSpacing, stroke, paint: r.paint() }) }\n else out.push({ cmd: \"fillText\", text, x, y, maxWidth, font, align, baseline, letterSpacing, paint: r.paint() })\n break\n }\n case DRAW.DRAW_IMAGE: { const surface = r.i(); const src = r.rect4(); const dst = r.rect4(); out.push({ cmd: \"drawImage\", surface, src, dst, alpha: r.f() }); break }\n case DRAW.CLEAR_RECT: out.push({ cmd: \"clearRect\", rect: r.rect4() }); break\n default: break // unknown: skipped by len\n }\n if (r.pos !== end) {\n if (r.pos > end) throw new Error(`draw list: command ${cmd} overran its length`)\n r.pos = end\n }\n }\n return out\n}\n\n/** The core's JSON dump (ac_drawlist_json / acdump) → commands. */\nexport const parseDrawListJson = (text: string): DrawCommand[] => {\n const v = JSON.parse(text)\n if (!Array.isArray(v)) throw new Error(\"draw list JSON: expected an array\")\n for (const c of v) if (typeof c !== \"object\" || typeof c.cmd !== \"string\") throw new Error(\"draw list JSON: bad command\")\n return v as DrawCommand[]\n}\n\n/** The binary file acdump / the golden test write: u32 wordCount, f32 words, u32 stringCount, (u32 len, utf8)*. */\nexport const readDrawListBinary = (bytes: Uint8Array): { words: Float32Array, strings: string[] } => {\n const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n let pos = 0\n const wordCount = dv.getUint32(pos, true); pos += 4\n const words = new Float32Array(wordCount)\n for (let i = 0; i < wordCount; i++) { words[i] = dv.getFloat32(pos, true); pos += 4 }\n const stringCount = dv.getUint32(pos, true); pos += 4\n const strings: string[] = []\n const dec = new TextDecoder()\n for (let i = 0; i < stringCount; i++) {\n const len = dv.getUint32(pos, true); pos += 4\n strings.push(dec.decode(bytes.subarray(pos, pos + len))); pos += len\n }\n return { words, strings }\n}\n","// GENERATED by scripts/vendor-canvas.ts from engines/canvas/painters/web/src/painter.ts @ ae6bc30b952b — do not edit here.\n// Bump the submodule and run `bun run vendor:canvas`; `bun run check:canvas-ops` fails when this copy is stale.\n// The web painter: replays a draw list on anything shaped like a CanvasRenderingContext2D — the\n// browser, an OffscreenCanvas, node-canvas / @napi-rs/canvas. A loop with one case per command, no\n// state of its own: the list carries absolute transforms and resolved paints.\n//\n// Platform limits, stated: Canvas2D gradients only PAD (reflect / repeat draw as pad); a gradient\n// under a non-similarity transform (skew, non-uniform scale — SVG objectBoundingBox on a non-square\n// shape) is drawn by transforming the context, which also distorts a STROKE's pen; letterSpacing\n// applies where the context supports it (Chrome 99+, Safari 17+; not node-canvas).\nimport type { DrawCommand, Paint, Stroke, Font, PathSeg, Matrix6, Color } from \"./drawlist\"\n\n/** The subset of CanvasRenderingContext2D the painter uses. */\nexport interface Canvas2DLike {\n save(): void\n restore(): void\n setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void\n transform(a: number, b: number, c: number, d: number, e: number, f: number): void\n beginPath(): void\n moveTo(x: number, y: number): void\n lineTo(x: number, y: number): void\n quadraticCurveTo(cx: number, cy: number, x: number, y: number): void\n bezierCurveTo(c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number): void\n closePath(): void\n fill(rule?: \"nonzero\" | \"evenodd\"): void\n stroke(): void\n clip(rule?: \"nonzero\" | \"evenodd\"): void\n fillStyle: any\n strokeStyle: any\n lineWidth: number\n lineJoin: any\n lineCap: any\n miterLimit: number\n setLineDash(segments: number[]): void\n lineDashOffset: number\n globalAlpha: number\n font: string\n textAlign: any\n textBaseline: any\n letterSpacing?: string\n fillText(text: string, x: number, y: number, maxWidth?: number): void\n strokeText(text: string, x: number, y: number, maxWidth?: number): void\n drawImage(image: any, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void\n clearRect(x: number, y: number, w: number, h: number): void\n createLinearGradient(x0: number, y0: number, x1: number, y1: number): any\n createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): any\n}\n\nexport interface PainterHooks {\n /** The drawable for a surface id (a canvas, an ImageBitmap, an Image); null skips the blit. */\n image?(surface: number): any\n /** Map a font family to what this context can render (a registered font's real name, a fallback). */\n fontFamily?(family: string): string\n}\n\nconst GENERIC_FAMILIES = new Set([\"serif\", \"sans-serif\", \"monospace\", \"cursive\", \"fantasy\", \"system-ui\", \"ui-serif\", \"ui-sans-serif\", \"ui-monospace\", \"ui-rounded\", \"emoji\", \"math\", \"fangsong\"])\n\n/** A draw-list color as CSS. */\nexport const cssColor = (c: Color): string => `rgba(${Math.round(c[0] * 255)}, ${Math.round(c[1] * 255)}, ${Math.round(c[2] * 255)}, ${c[3]})`\n\n/** A draw-list font as a CSS font shorthand. */\nexport const cssFont = (f: Font, family = f.family): string => {\n const fam = GENERIC_FAMILIES.has(family) ? family : `\"${family.replace(/\"/g, \"'\")}\"`\n return `${f.italic ? \"italic \" : \"\"}${f.weight} ${f.size}px ${fam}`\n}\n\nconst apply = (m: Matrix6, x: number, y: number): [number, number] => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]]\n\n// A similarity transform (uniform scale + rotation + translation) keeps circles circles, so the\n// gradient can be expressed in user space without transforming the context.\nconst isSimilarity = (m: Matrix6): boolean => Math.abs(m[0] - m[3]) < 1e-6 && Math.abs(m[1] + m[2]) < 1e-6\n\nconst buildPath = (ctx: Canvas2DLike, path: PathSeg[]): void => {\n ctx.beginPath()\n for (const s of path) {\n switch (s[0]) {\n case \"M\": ctx.moveTo(s[1], s[2]); break\n case \"L\": ctx.lineTo(s[1], s[2]); break\n case \"Q\": ctx.quadraticCurveTo(s[1], s[2], s[3], s[4]); break\n case \"C\": ctx.bezierCurveTo(s[1], s[2], s[3], s[4], s[5], s[6]); break\n case \"Z\": ctx.closePath(); break\n }\n }\n}\n\nconst gradientStops = (g: any, paint: Paint & { stops: { offset: number, color: Color }[] }): void => {\n for (const s of paint.stops) g.addColorStop(s.offset, cssColor(s.color))\n}\n\n// Sets fillStyle / strokeStyle + globalAlpha, then runs `draw`. A gradient with a general matrix is\n// drawn inside a context transform (the path, already built, is not affected — Canvas2D keeps paths\n// in device space).\nconst withPaint = (ctx: Canvas2DLike, paint: Paint, which: \"fill\" | \"stroke\", draw: () => void): void => {\n ctx.globalAlpha = paint.alpha\n if (paint.kind === \"color\") {\n ctx[which === \"fill\" ? \"fillStyle\" : \"strokeStyle\"] = cssColor(paint.color)\n draw()\n return\n }\n const m = paint.matrix\n if (isSimilarity(m)) {\n let g: any\n if (paint.kind === \"linear\") {\n const [x0, y0] = apply(m, 0, 0), [x1, y1] = apply(m, 1, 0)\n g = ctx.createLinearGradient(x0, y0, x1, y1)\n } else {\n const s = Math.hypot(m[0], m[1])\n const [cx, cy] = apply(m, 0, 0), [fx, fy] = apply(m, paint.fx, paint.fy)\n g = ctx.createRadialGradient(fx, fy, paint.r0 * s, cx, cy, s)\n }\n gradientStops(g, paint)\n ctx[which === \"fill\" ? \"fillStyle\" : \"strokeStyle\"] = g\n draw()\n return\n }\n ctx.save()\n ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5])\n const g = paint.kind === \"linear\" ? ctx.createLinearGradient(0, 0, 1, 0) : ctx.createRadialGradient(paint.fx, paint.fy, paint.r0, 0, 0, 1)\n gradientStops(g, paint)\n ctx[which === \"fill\" ? \"fillStyle\" : \"strokeStyle\"] = g\n draw()\n ctx.restore()\n}\n\nconst applyStroke = (ctx: Canvas2DLike, s: Stroke): void => {\n ctx.lineWidth = s.width\n ctx.lineJoin = s.join\n ctx.lineCap = s.cap\n ctx.miterLimit = s.miterLimit\n ctx.setLineDash(s.dash)\n ctx.lineDashOffset = s.dashOffset\n}\n\nconst applyText = (ctx: Canvas2DLike, c: { font: Font, align: string, baseline: string, letterSpacing: number }, hooks: PainterHooks): void => {\n ctx.font = cssFont(c.font, hooks.fontFamily ? hooks.fontFamily(c.font.family) : c.font.family)\n ctx.textAlign = c.align\n ctx.textBaseline = c.baseline\n if (\"letterSpacing\" in ctx) ctx.letterSpacing = `${c.letterSpacing}px`\n}\n\n/** Replay `commands` on `ctx`. The context should start with the identity transform and an empty\n * save stack (the painter sets the identity itself); clearing the surface is the caller's decision.\n * The replay runs inside one save, so no clip, transform or style it sets outlives it (Canvas2D\n * keeps a clip set outside any save, and the next paint's clearRect would clear only that clip). */\nexport const paint = (ctx: Canvas2DLike, commands: DrawCommand[], hooks: PainterHooks = {}): void => {\n ctx.save()\n let saves = 0 // a list restore never pops the wrapper save\n try {\n ctx.setTransform(1, 0, 0, 1, 0, 0)\n ctx.globalAlpha = 1\n for (const c of commands) {\n switch (c.cmd) {\n case \"setTransform\": ctx.setTransform(c.matrix[0], c.matrix[1], c.matrix[2], c.matrix[3], c.matrix[4], c.matrix[5]); break\n case \"save\": ctx.save(); saves++; break\n case \"restore\": if (saves > 0) { ctx.restore(); saves-- } break\n case \"clip\": buildPath(ctx, c.path); ctx.clip(c.rule as \"nonzero\" | \"evenodd\"); break\n case \"fillPath\": buildPath(ctx, c.path); withPaint(ctx, c.paint, \"fill\", () => ctx.fill(c.rule as \"nonzero\" | \"evenodd\")); break\n case \"strokePath\": buildPath(ctx, c.path); applyStroke(ctx, c.stroke); withPaint(ctx, c.paint, \"stroke\", () => ctx.stroke()); break\n case \"fillText\": applyText(ctx, c, hooks); withPaint(ctx, c.paint, \"fill\", () => c.maxWidth > 0 ? ctx.fillText(c.text, c.x, c.y, c.maxWidth) : ctx.fillText(c.text, c.x, c.y)); break\n case \"strokeText\": applyText(ctx, c, hooks); applyStroke(ctx, c.stroke); withPaint(ctx, c.paint, \"stroke\", () => c.maxWidth > 0 ? ctx.strokeText(c.text, c.x, c.y, c.maxWidth) : ctx.strokeText(c.text, c.x, c.y)); break\n case \"drawImage\": {\n const img = hooks.image?.(c.surface)\n if (!img) break\n ctx.globalAlpha = c.alpha\n ctx.drawImage(img, c.src[0], c.src[1], c.src[2], c.src[3], c.dst[0], c.dst[1], c.dst[2], c.dst[3])\n break\n }\n case \"clearRect\": ctx.clearRect(c.rect[0], c.rect[1], c.rect[2], c.rect[3]); break\n default: { const never: never = c; throw new Error(`unhandled draw command ${(never as DrawCommand).cmd}`) }\n }\n }\n } finally {\n for (; saves > 0; saves--) ctx.restore()\n ctx.restore()\n }\n}\n","// The web PAINTER host for `_creatorCanvas`: the HostCanvas table of the wasm runtime (host.gen.ts\n// `WasmHostCanvas`) over OffscreenCanvas. The runtime's AnyCanvas core interprets the SDK's opcode\n// stream and SVG into a draw list; this host keeps one OffscreenCanvas per surface id and replays the\n// list with the vendored AnyCanvas web painter (./gen, `bun run vendor:canvas`). The browser gives text\n// shaping, emoji, font fallback and image decoding for free.\n//\n// `readSurface` / `getSurface` / `surfaceToDataUrl` are how the baked pixels reach the engines (a GPU\n// texture), the canvas UI renderer (`UIImage(canvas)` draws the live OffscreenCanvas) and the DOM\n// renderer (a data URL).\n\nimport { readDrawList } from \"./gen/drawlist\"\nimport { paint, cssFont } from \"./gen/painter\"\n\nexport interface CanvasHost {\n /** The HostCanvas table the wasm runtime calls (a web host's canvas table). */\n table: {\n paint(surfaceId: number, pw: number, ph: number, scale: number, words: Float32Array, strings: string[]): void\n measureText(text: string, family: string, size: number, weight: number, italic: boolean, out: Float32Array): void\n decodeImage(bufferId: number, surfaceId: number, size: Int32Array): boolean\n readPixels(surfaceId: number, size: Int32Array): Uint8Array | null\n releaseSurface(surfaceId: number): void\n }\n /** Straight (non-premultiplied) RGBA8 pixels of a baked surface, for engine texture upload. */\n readSurface(surfaceId: number): { data: Uint8ClampedArray, width: number, height: number } | null\n /** The baked surface as a drawable canvas (device px) — a `CanvasSurfaceProvider` for canvas-ui's\n * `UIImage(canvas)` (lecodes-headless BrowserHost). */\n getSurface(surfaceId: number): { canvas: OffscreenCanvas, width: number, height: number } | null\n /** The baked surface as a data-uri, for the DOM renderer's `<img>` (`UIImage(canvas)`). */\n surfaceToDataUrl(surfaceId: number): string | null\n}\n\n/** `fontFamily` maps a draw-list family to what the page can render (a registered font's real name);\n * the default keeps the family as is. Image decoding is asynchronous in the browser while the table is\n * synchronous, so `decodeImage` answers false: `Canvas.loadImage(fetchResponse)` rejects on the web\n * (SVG goes through the core and works). */\nexport const createCanvasHost = (fontFamily?: (family: string) => string): CanvasHost => {\n const supported = typeof OffscreenCanvas !== \"undefined\"\n const surfaces = new Map<number, OffscreenCanvas>()\n let measureCtx: OffscreenCanvasRenderingContext2D | null = null\n\n const ensure = (surfaceId: number, pw: number, ph: number): OffscreenCanvas | null => {\n if (!supported) return null\n let cv = surfaces.get(surfaceId)\n if (!cv) { cv = new OffscreenCanvas(pw, ph); surfaces.set(surfaceId, cv) }\n else if (cv.width !== pw || cv.height !== ph) { cv.width = pw; cv.height = ph }\n return cv\n }\n\n const table: CanvasHost[\"table\"] = {\n paint: (surfaceId, pw, ph, _scale, words, strings) => {\n const cv = ensure(surfaceId, Math.max(1, pw), Math.max(1, ph))\n const ctx = cv?.getContext(\"2d\")\n if (!cv || !ctx) return\n ctx.setTransform(1, 0, 0, 1, 0, 0)\n ctx.clearRect(0, 0, cv.width, cv.height)\n // `words` is a view into wasm memory, valid for this call only: decode before returning.\n paint(ctx, readDrawList(words, strings), { image: id => surfaces.get(id) ?? null, fontFamily })\n },\n measureText: (text, family, size, weight, italic, out) => {\n out[0] = 0; out[1] = 0; out[2] = 0\n if (!supported) return\n if (!measureCtx) measureCtx = new OffscreenCanvas(1, 1).getContext(\"2d\")\n if (!measureCtx) return\n measureCtx.font = cssFont({ family, size, weight, italic }, fontFamily ? fontFamily(family) : family)\n const m = measureCtx.measureText(text)\n out[0] = m.width\n out[1] = m.fontBoundingBoxAscent ?? m.actualBoundingBoxAscent\n out[2] = m.fontBoundingBoxDescent ?? m.actualBoundingBoxDescent\n },\n decodeImage: () => false,\n readPixels: (surfaceId, size) => {\n const s = readSurface(surfaceId)\n if (!s) return null\n size[0] = s.width; size[1] = s.height\n return new Uint8Array(s.data.buffer, s.data.byteOffset, s.data.byteLength)\n },\n releaseSurface: (surfaceId) => { surfaces.delete(surfaceId) },\n }\n\n const readSurface = (surfaceId: number) => {\n const cv = surfaces.get(surfaceId)\n const ctx = cv?.getContext(\"2d\")\n if (!cv || !ctx) return null\n const img = ctx.getImageData(0, 0, cv.width, cv.height) // straight RGBA8 per the Canvas2D spec\n return { data: img.data, width: cv.width, height: cv.height }\n }\n\n const getSurface = (surfaceId: number) => {\n const cv = surfaces.get(surfaceId)\n return cv ? { canvas: cv, width: cv.width, height: cv.height } : null\n }\n\n const surfaceToDataUrl = (surfaceId: number): string | null => {\n const cv = surfaces.get(surfaceId)\n if (!cv || typeof document === \"undefined\") return null\n const el = document.createElement(\"canvas\")\n el.width = cv.width; el.height = cv.height\n el.getContext(\"2d\")?.drawImage(cv, 0, 0)\n return el.toDataURL()\n }\n\n return { table, readSurface, getSurface, surfaceToDataUrl }\n}\n","export default \"__VITE_ASSET__lw8T$mh5__\"","// The viewer measures text with a real canvas 2D context (the DOM measure system's OffscreenCanvas\n// and the canvas-ui BrowserHost), which only sees fonts the document has actually loaded — so the\n// measurement font must be fully loaded before the first layout, or text lays out against a\n// fallback and never recovers (Yoga caches the measure).\n//\n// The font is the vendored variable Roboto (weights 100–900, latin + cyrillic + greek + vietnamese\n// in ONE file), self-hosted and same-origin. The previous Google-Fonts Inter pipeline was broken on\n// a cold cache: css2 serves each family split into unicode-range subsets, and\n// `fonts.load(\"400 14px Inter\")` (default text = a space) only awaited the *latin* subset — the\n// first measure of Cyrillic text ran against a fallback and produced a wrong layout that later\n// cache-warm loads never reproduced. One complete file makes the await cover every glyph, every\n// weight, with no CDN round trip.\nimport robotoUrl from \"../assets/Roboto-Variable.woff2?url\"\n\n// The default measurement/paint family (createMeasureSystem / paintTree / the lite CSS renderer).\nexport const DEFAULT_FONT_FAMILY = \"Roboto\"\n\n// One variable face serves every weight — a single load covers 400..800.\nconst DEFAULT_FONTS = [`400 14px ${DEFAULT_FONT_FAMILY}`]\n\nconst FONT_STYLE_MARKER = \"data-lecodes-fonts\"\n\n/** Register the vendored @font-face in `doc` (idempotent) and resolve once the bytes are in. */\nexport const ensureFontsLoaded = async (fonts: string[] = DEFAULT_FONTS, doc?: Document) => {\n // Fonts are per-document: the lite host renders inside its own iframe and passes that\n // document; the default serves the classic full-viewer path.\n const target = doc ?? (typeof document === \"undefined\" ? undefined : document)\n if (!target || !target.fonts) return\n\n if (!target.head.querySelector(`style[${FONT_STYLE_MARKER}]`)) {\n // Resolve against the embedder document: the lite host's iframe is a base-less about:blank,\n // and Vite emits a root-relative asset path.\n const absUrl = new URL(robotoUrl, document.baseURI).href\n const style = target.createElement(\"style\")\n style.setAttribute(FONT_STYLE_MARKER, \"\")\n style.textContent =\n `@font-face{font-family:\"${DEFAULT_FONT_FAMILY}\";src:url(\"${absUrl}\") format(\"woff2\");` +\n `font-weight:100 900;font-display:swap}`\n target.head.appendChild(style)\n }\n\n try {\n // load() resolves once each matched face's bytes are in, and resolves (not rejects) with an\n // empty array when nothing matches — so a missing face is a no-op, not a failure.\n await Promise.all(fonts.map(font => target.fonts.load(font)))\n } catch {\n // Best-effort: a font that fails to fetch must never block the simulator from starting.\n }\n}\n\n// ---- app-declared boot fonts (the bundle's `// fonts:` header) ----------------------------------\n\nexport type BootFont = { family: string, weight: number, italic: boolean, url: string }\n\n/** Parse the bundle's `// fonts:` header value (`Family@<weight>[i]=<url>;…`) from the header\n * region of a compiled bundle. A `{fmt}` placeholder in a URL is the container-format choice —\n * replaced with this host's preference (browsers: woff2). */\nexport const parseFontsHeader = (header: string, format = \"woff2\"): BootFont[] => {\n const m = /^\\/\\/ fonts: (.+)$/m.exec(header)\n if (!m) return []\n const out: BootFont[] = []\n for (const entry of m[1].split(\";\")) {\n const eq = entry.indexOf(\"=\")\n if (eq === -1) continue\n const tag = /^(.+)@(\\d+)(i?)$/.exec(entry.slice(0, eq))\n if (!tag) continue\n out.push({ family: tag[1], weight: parseInt(tag[2], 10), italic: tag[3] === \"i\", url: entry.slice(eq + 1).replace(\"{fmt}\", format) })\n }\n return out\n}\n\n/** Boot hold: start loading the app's declared faces, resolving when they settle or the budget\n * expires (~2s, like font-display's block period but shorter) — the host delays first paint on\n * this so text appears in the right font from the start. Faces are added to the document FIRST,\n * so one that loses the race still swaps in when it lands (the degraded-network fallback). */\nexport const loadBootFonts = async (fonts: BootFont[], doc?: Document, budgetMs = 2000): Promise<void> => {\n const target = doc ?? (typeof document === \"undefined\" ? undefined : document)\n if (!target?.fonts || fonts.length === 0) return\n const loads: Promise<unknown>[] = []\n for (const f of fonts) {\n try {\n const face = new FontFace(f.family, `url(\"${f.url}\")`, { weight: String(f.weight), style: f.italic ? \"italic\" : \"normal\" } as FontFaceDescriptors)\n target.fonts.add(face)\n loads.push(face.load().catch(() => { /* missing face → fallback, never a boot failure */ }))\n } catch { /* malformed entry — skip */ }\n }\n await Promise.race([ Promise.all(loads), new Promise((res) => setTimeout(res, budgetMs)) ])\n}\n","// GENERATED by scripts/release/set-version.ts from sdk/package.json — do not edit by hand.\n// The ONE version of the SDK + the runtime (the npm runtime set ships as one version; the C++\n// twin is CREATOR_PKG_SDK_VERSION in creator-pkg/host.gen.h, emitted by gen:bridges from the\n// same manifest). Its MAJOR is the bundle ↔ runtime contract: a bundle's `// sdk:` header line\n// and a host's embedded version must agree on the major for the host to run the bundle; minor\n// and patch never gate anything (features are detected, never versioned).\nexport const SDK_VERSION = \"2.0.1\"\n\n/** The major of a semver string, or null when it is not one. */\nexport const sdkMajor = (version: string | null | undefined): number | null => {\n const m = version?.match(/^(\\d+)\\.\\d+\\.\\d+/)\n return m ? Number(m[1]) : null\n}\n\n/** The `// sdk: <version>` line of a compiled bundle's header (sdk/src/compile/header.ts), read from\n * its first bytes; null for a bundle compiled before the line existed (SDK 0.x / 1.x — the\n * pre-tree contract, which no 2.x host runs). */\nexport const bundleSdkVersion = (head: string): string | null =>\n head.slice(0, 2000).match(/^\\/\\/ sdk: (\\d+\\.\\d+\\.\\d+\\S*)/m)?.[1] ?? null\n\n/** Whether a host embedding `hostVersion` can run a bundle whose header carries `bundleVersion`\n * (null = no line = pre-2.0 contract): the majors must match. */\nexport const bundleRunsOn = (bundleVersion: string | null, hostVersion: string): boolean =>\n sdkMajor(bundleVersion) !== null && sdkMajor(bundleVersion) === sdkMajor(hostVersion)\n","// The 3D host slots (HostGL): the canvas Filament presents on, the textures the browser decodes,\n// media textures.\nimport type { WasmModule } from \"lecodes-web-runtime/src/gen/wasm\"\nimport type { WasmHostGL } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport { getBlob, getBuffer } from \"lecodes-web-shared/src/utils/fetch\"\nimport { getPlayer } from \"lecodes-web-shared/src/utils/mediaplayer\"\nimport type { Page } from \"../page\"\n\n// 12-byte KTX2 magic («KTX 20» CR LF 0x1A LF) — createTexture routes these to the wasm transcoder\nconst KTX2_MAGIC = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a]\nconst isKtx2 = (b: Uint8Array) => b.length >= 12 && KTX2_MAGIC.every((v, i) => b[i] === v)\n\nexport type GLSurface = ReturnType<typeof createGLSurface>\n\n/** `preserve` = the drawing buffer survives the frame (a bundle that captures the scene). */\nexport const createGLSurface = (page: Page, preserve: boolean) => {\n // The attributes creator-gl's context is created with (init.cpp registers it).\n const options: WebGLContextAttributes = {\n antialias: false, depth: true, alpha: false, stencil: false, desynchronized: false,\n failIfMajorPerformanceCaveat: false, powerPreference: \"high-performance\", premultipliedAlpha: true,\n preserveDrawingBuffer: preserve,\n }\n const canvas = page.newCanvas()\n const gl = canvas.getContext(\"webgl2\", options)\n if (!gl) throw new Error(\"WebGL2 is not available\")\n\n let M: WasmModule | null = null\n let ready = false\n const players: { player: HTMLVideoElement, texture: WebGLTexture, lastTime: number }[] = []\n\n const newTexture = (): WebGLTexture => {\n const texture = gl.createTexture()!\n gl.bindTexture(gl.TEXTURE_2D, texture)\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false)\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false)\n gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE)\n return texture\n }\n const importTexture = (module: WasmModule, texture: WebGLTexture, width: number, height: number): number => {\n const id = module.GL.getNewId(module.GL.textures)\n module.GL.textures[id] = texture\n return module._importTexture(id, width, height) >>> 0\n }\n\n return {\n canvas,\n context: gl,\n options,\n /** The table, once the module is up (the context rode in as a module field). */\n table(module: WasmModule): WasmHostGL {\n M = module\n return {\n engineCreated() {\n // the engine just came up (or was rebuilt): its surface is this canvas\n module._createSwapChainHeadless(canvas.width, canvas.height)\n module._creatorWebSetViewport(canvas.width, canvas.height)\n ready = true\n },\n createGLView() { canvas.style.display = \"block\" },\n closeScene() { canvas.style.display = \"none\" },\n createTexture(systemId, flags, onComplete, onReject) {\n const buffer = getBuffer(systemId)\n if (!buffer) { onReject(`createTexture: no buffer behind id ${systemId}`); return }\n const bytes = new Uint8Array(buffer)\n if (isKtx2(bytes)) {\n // KTX2 (Basis Universal): the wasm core transcodes it and keeps the file's mip chain\n const ptr = module._malloc(bytes.length)\n module.HEAPU8.set(bytes, ptr)\n const id = module._createTextureFromKtx2(ptr, bytes.length) >>> 0\n module._free(ptr)\n if (id === 0xffffffff) { onReject(\"KTX2 transcode failed\"); return }\n onComplete(id, module._getTextureWidth(id), module._getTextureHeight(id))\n return\n }\n // PNG / JPG / WebP through the browser's decoder → a GL texture imported into Filament\n // (sRGB unless the flags say linear data)\n createImageBitmap(getBlob(systemId)).then((bitmap) => {\n const texture = newTexture()\n gl.texStorage2D(gl.TEXTURE_2D, 1, (flags & 1) ? gl.RGBA8 : gl.SRGB8_ALPHA8, bitmap.width, bitmap.height)\n gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, bitmap.width, bitmap.height, gl.RGBA, gl.UNSIGNED_BYTE, bitmap)\n onComplete(importTexture(module, texture, bitmap.width, bitmap.height), bitmap.width, bitmap.height)\n }, (e) => onReject(e instanceof Error ? e.message : String(e)))\n },\n createMediaPlayerTexture(playerId) {\n const player = getPlayer(playerId) as HTMLVideoElement | undefined\n if (!player) return 0\n const texture = newTexture()\n players.push({ player, texture, lastTime: 0 })\n return importTexture(module, texture, 0, 0)\n },\n }\n },\n show() { canvas.style.display = \"block\" },\n hide() { canvas.style.display = \"none\" },\n /** The canvas took a new size (page.ts): the engine's viewport follows. */\n resize() { if (M && ready) M._creatorWebSetViewport(canvas.width, canvas.height) },\n /** Before the runtime's tick: the video frames that moved. */\n frame() {\n for (const p of players) {\n if (p.player.readyState < 2 || p.player.currentTime === p.lastTime) continue\n p.lastTime = p.player.currentTime\n gl.bindTexture(gl.TEXTURE_2D, p.texture)\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, p.player)\n }\n },\n destroy() {\n players.length = 0\n gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n },\n }\n}\n","// The 2D host slots (HostScene2d): the canvas creator-2d draws on.\nimport type { WasmModule } from \"lecodes-web-runtime/src/gen/wasm\"\nimport type { WasmHostScene2d } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport type { Page } from \"../page\"\n\nexport type Scene2dSurface = ReturnType<typeof createScene2dSurface>\n\nexport const createScene2dSurface = (page: Page) => {\n // creator-2d's WebGL2 attributes (c2dInit registers the context).\n const options: WebGLContextAttributes = {\n alpha: false, depth: true, stencil: true, antialias: false, premultipliedAlpha: false, desynchronized: false,\n powerPreference: \"high-performance\", failIfMajorPerformanceCaveat: false,\n }\n const canvas = page.newCanvas()\n const gl = canvas.getContext(\"webgl2\", options)\n if (!gl) throw new Error(\"WebGL2 is not available\")\n\n let M: WasmModule | null = null\n let inited = false\n const pushViewport = () => {\n if (!M || !inited) return\n M._c2dSetViewport(canvas.width, canvas.height)\n M._c2dSetDensity(page.size().factor)\n }\n\n // The engine comes up with the first scene (c2dInit on this canvas's context), not before.\n const show = () => {\n if (!M) return\n M._creatorWeb2dEnsureInited()\n inited = true\n pushViewport()\n canvas.style.display = \"block\"\n }\n const hide = () => { canvas.style.display = \"none\" }\n\n return {\n canvas,\n context: gl,\n options,\n table(module: WasmModule): WasmHostScene2d {\n M = module\n return { open2DScene: show, close2DScene: hide }\n },\n /** A 2D scene presents: through the table (`_creator2d.openScene`) or as a destination — which\n * the runtime opens WITHOUT the table's slot, the view being the host's to mount. */\n show,\n hide,\n resize: pushViewport,\n /** After the runtime's tick: the 2D frame, when a 2D scene is open. */\n frame(now: number) { if (M && M._creatorWeb2dSceneOpen()) M._creatorWeb2dRenderFrame(now) },\n destroy() { gl.getExtension(\"WEBGL_lose_context\")?.loseContext() },\n }\n}\n","// Map runtime errors from a compiled bundle back to original source locations.\n//\n// The preview runs the bundle via `new Function(code)`, so the browser won't apply the bundle's\n// inline source map to stack frames automatically — we do it here. Two offsets are involved and both\n// are handled: the bundle carries an inline source map whose generated positions already include the\n// compile header (the backend shifts it), and `new Function` adds a constant wrapper offset that we\n// calibrate at runtime. Self-contained (a tiny VLQ decoder), so there's no extra dependency.\n\ntype RawSourceMap = { version: number, sources: string[], mappings: string, sourcesContent?: (string | null)[] }\ntype OrigPos = { source: string, line: number, column: number }\nexport type MappedFrame = { fn: string | null, source: string, line: number, column: number }\n/** A runtime error from the preview. `native` errors come from the WASM engine (no JS source to map).\n * `nativeFrames` are the crash's decoded engine (C++) function names, top-first — filled in by a\n * follow-up emit once the wasm host has fetched its symbol map (see viewer's wasmCrashSymbolizer). */\nexport type PreviewError = { message: string, frames: MappedFrame[], stack?: string, native?: boolean, detail?: string, nativeFrames?: string[] }\n\n/**\n * Is this a native (WASM engine) error rather than a JS error from the user's bundle? Emscripten\n * surfaces C++ exceptions/aborts as a bare number (a pointer), and WebAssembly traps as\n * `WebAssembly.RuntimeError`; either way there's no JS source position to map. We deliberately do\n * *not* treat an arbitrary frameless JS `Error` as native (that would hijack unrelated editor errors).\n */\nexport const isNativeError = (e: unknown): boolean => {\n if (typeof e === \"number\" || typeof e === \"bigint\") return true\n if (typeof WebAssembly !== \"undefined\" && e instanceof WebAssembly.RuntimeError) return true\n const stack = e instanceof Error ? (e.stack ?? \"\") : \"\"\n return /\\bwasm\\b|wasm-function|\\.wasm/i.test(stack)\n}\n\nconst B64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"\nconst B64_INDEX: Record<string, number> = {}\nfor (let i = 0; i < B64.length; i++) B64_INDEX[B64[i]!] = i\n\n/** Decode one comma-segment of base64-VLQ into signed ints. */\nconst decodeVlq = (segment: string): number[] => {\n const out: number[] = []\n let shift = 0, value = 0\n for (const ch of segment) {\n const digit = B64_INDEX[ch]\n if (digit === undefined) break\n const more = digit & 32\n value += (digit & 31) << shift\n if (more) {\n shift += 5\n } else {\n const negative = value & 1\n value >>= 1\n out.push(negative ? -value : value)\n value = 0\n shift = 0\n }\n }\n return out\n}\n\n/** A minimal source-map consumer: original position for a generated (1-based line, 0-based column). */\nexport class SourceMap {\n private sources: string[]\n // Per generated line: sorted segments [genCol, srcIdx, srcLine, srcCol].\n private lines: number[][][]\n\n constructor(raw: RawSourceMap) {\n this.sources = raw.sources\n this.lines = []\n let srcIdx = 0, srcLine = 0, srcCol = 0\n for (const lineStr of raw.mappings.split(\";\")) {\n const segs: number[][] = []\n let genCol = 0\n if (lineStr) {\n for (const segStr of lineStr.split(\",\")) {\n const v = decodeVlq(segStr)\n if (v.length === 0) continue\n genCol += v[0]!\n if (v.length >= 4) {\n srcIdx += v[1]!\n srcLine += v[2]!\n srcCol += v[3]!\n segs.push([ genCol, srcIdx, srcLine, srcCol ])\n }\n }\n }\n this.lines.push(segs)\n }\n }\n\n originalPositionFor(line: number, column: number): OrigPos | null {\n const segs = this.lines[line - 1]\n if (!segs || segs.length === 0) return null\n // Largest segment whose generated column is <= the queried column.\n let best: number[] | null = null\n for (const seg of segs) {\n if (seg[0]! <= column) best = seg\n else break\n }\n best ??= segs[0]!\n const source = this.sources[best[1]!]\n if (source === undefined) return null\n return { source, line: best[2]! + 1, column: best[3]! }\n }\n}\n\n/** Pull the inline `//# lecodesMap=data:...base64,…` map out of a bundle string (a non-standard\n * directive the browser ignores — see inlineSourceMapComment in the SDK for why). */\nexport const extractInlineSourceMap = (code: string): SourceMap | null => {\n const m = code.match(/\\/\\/# lecodesMap=data:application\\/json;(?:charset=[^;]+;)?base64,([A-Za-z0-9+/=]+)\\s*$/)\n if (!m) return null\n try {\n const json = typeof atob === \"function\" ? atob(m[1]!) : Buffer.from(m[1]!, \"base64\").toString(\"utf8\")\n return new SourceMap(JSON.parse(json) as RawSourceMap)\n } catch {\n return null\n }\n}\n\n// `new Function(body)` wraps the body in `function anonymous(args\\n) {\\n<body>\\n}`, so the body starts\n// a constant number of lines down. Calibrate once per engine by throwing from a one-line body.\nlet functionOffset: number | null = null\nconst newFunctionLineOffset = (): number => {\n if (functionOffset !== null) return functionOffset\n try {\n new Function(\"throw new Error('chisel-calibrate')\")()\n } catch (e) {\n const stack = (e as Error).stack ?? \"\"\n // The body coordinate is the `<anonymous>:line:col` one (V8/Chrome). A one-line body throws at\n // body line 1, so its reported line minus 1 is the wrapper offset.\n const m = stack.match(/<anonymous>:(\\d+):\\d+/)\n functionOffset = m ? parseInt(m[1]!, 10) - 1 : 2\n return functionOffset\n }\n functionOffset = 2\n return functionOffset\n}\n\n/** Parse `error.stack`, mapping each `new Function` frame back to original source via `map`. */\nexport const mapErrorStack = (error: unknown, map: SourceMap): MappedFrame[] => {\n const stack = (error instanceof Error ? error.stack : \"\") ?? \"\"\n const offset = newFunctionLineOffset()\n const frames: MappedFrame[] = []\n for (const raw of stack.split(\"\\n\")) {\n // The user-bundle position is the `<anonymous>:line:col` coordinate (V8 gives body-relative\n // lines here; an `eval at … (file:line)` prefix, if present, is the call site — not it).\n const m = raw.match(/<anonymous>:(\\d+):(\\d+)/)\n if (!m) continue\n const genLine = parseInt(m[1]!, 10) - offset\n const genCol = parseInt(m[2]!, 10) - 1\n if (genLine < 1) continue\n const orig = map.originalPositionFor(genLine, genCol < 0 ? 0 : genCol)\n if (!orig) continue\n const fnMatch = raw.match(/at\\s+([^\\s(]+)\\s*\\(/)\n frames.push({ fn: fnMatch ? fnMatch[1]! : null, source: orig.source, line: orig.line, column: orig.column })\n }\n return frames\n}\n\n/** Rewrite every `<filename>:line:col` frame in a block of text to its original position.\n * This is the shape a host that EVALUATES the bundle as one named file produces — quickjs on the\n * native hosts (`module.js:5:51631`, see creatorUtilsHandler) and `vm.runInContext` in the headless\n * renderer (`project.js:…`) — as opposed to the preview's `new Function` frames above. Both report\n * 1-based columns. Frames naming other files (a host's own launcher, `native`) pass through. */\nexport const mapNamedFileStack = (text: string, map: SourceMap, filename: string): string => {\n const escaped = filename.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n return text.replace(new RegExp(`\\\\b${escaped}:(\\\\d+):(\\\\d+)`, \"g\"), (whole, l: string, c: string) => {\n const orig = map.originalPositionFor(parseInt(l, 10), Math.max(0, parseInt(c, 10) - 1))\n return orig ? `${orig.source.replace(/^(\\.\\/|\\/)/, \"\")}:${orig.line}:${orig.column}` : whole\n })\n}\n\n/** A one-line, human-readable original location for an error, or null if it can't be mapped. */\nexport const formatErrorLocation = (error: unknown, code: string): { message: string, frames: MappedFrame[] } | null => {\n const map = extractInlineSourceMap(code)\n if (!map) return null\n const frames = mapErrorStack(error, map)\n if (frames.length === 0) return null\n const top = frames[0]!\n const msg = error instanceof Error ? error.message : String(error)\n const where = `${top.source}:${top.line}:${top.column}${top.fn ? ` (${top.fn})` : \"\"}`\n return { message: `${msg}\\n at ${where}`, frames }\n}\n","// What a bundle threw, mapped back to the app's source. A bundle is evaluated through `new Function`\n// (./world.ts), whose frames the browser cannot map itself: the bundle's inline source map is applied\n// here. Errors arrive two ways — the runtime's own lines (`[ERROR] run …`: a throw it caught around\n// a callback) and the window's error events (everything else, a native trap of the engine included).\nimport { symbolizeWasmFrames } from \"lecodes-web-runtime/src/wasmCrashSymbolizer\"\nimport { extractInlineSourceMap, isNativeError, mapErrorStack, type MappedFrame, type PreviewError, type SourceMap } from \"lecodes-web-shared/src/sourcemapError\"\n\nexport type { MappedFrame, PreviewError }\n\n/** The runtime's error lines: what a bundle threw, and where the runtime caught it. */\nconst RUNTIME_ERROR = /^\\[ERROR\\] (run|host callback|JsDispatch|timer|setLoop|animate|tween)\\b:? ?([\\s\\S]*)$/\n\ntype RunRecord = { sourceMap: SourceMap | null, onError?: (error: PreviewError) => void }\n\nexport type ErrorReporter = ReturnType<typeof createErrorReporter>\n\n/** `native` = the profile carries an engine whose traps can be symbolized (the `full` one). */\nexport const createErrorReporter = (win: Window, native: boolean) => {\n const runs: RunRecord[] = []\n\n const emit = (record: RunRecord, e: unknown, frames: MappedFrame[], eventMessage?: string) => {\n if (frames.length === 0 && isNativeError(e)) {\n // The engine (Emscripten) prints the real message to the console; the value that reaches JS\n // is a pointer / an abort code. Surface it as an engine error with what description there is.\n const raw = typeof e === \"number\" || typeof e === \"bigint\" ? `code ${e}` : e instanceof Error ? (e.message || e.name) : String(e)\n const detail = [eventMessage, raw].filter((v): v is string => !!v).filter((v, i, a) => a.indexOf(v) === i).join(\"\\n\")\n console.error(`[lecodes] native engine error — ${detail || raw} (see the console for the engine's message)`)\n const error: PreviewError = { message: \"Native engine error\", detail, frames: [], native: true, stack: e instanceof Error ? e.stack : undefined }\n record.onError?.(error)\n // Late enrichment: the trap's engine frames through the lazy symbol map, emitted again.\n if (error.stack && native) {\n void symbolizeWasmFrames(error.stack).then((nativeFrames) => { if (nativeFrames.length > 0) record.onError?.({ ...error, nativeFrames }) })\n }\n return\n }\n const message = e instanceof Error ? e.message : String(e)\n const top = frames[0]\n console.error(top ? `[lecodes] ${message}\\n at ${top.source}:${top.line}:${top.column}${top.fn ? ` (${top.fn})` : \"\"}` : `[lecodes] ${message}`)\n record.onError?.({ message, frames, stack: e instanceof Error ? e.stack : undefined })\n }\n\n // An error whose stack maps into one of the runs' source maps (the newest first), or a native one.\n const report = (e: unknown, eventMessage?: string) => {\n for (let i = runs.length - 1; i >= 0; i--) {\n const record = runs[i]!\n if (!record.sourceMap) continue\n const frames = mapErrorStack(e, record.sourceMap)\n if (frames.length > 0) return emit(record, e, frames, eventMessage)\n }\n const last = runs[runs.length - 1]\n if (last && isNativeError(e)) emit(last, e, [], eventMessage)\n }\n\n let pending: { message: string, stack: string[] } | null = null\n const flush = () => {\n const record = runs[runs.length - 1]\n const held = pending\n pending = null\n if (!held || !record) return\n const error = new Error(held.message.replace(/^Error: /, \"\"))\n error.stack = held.stack.join(\"\\n\")\n emit(record, error, record.sourceMap ? mapErrorStack(error, record.sourceMap) : [])\n }\n\n const onError = (ev: ErrorEvent) => report(ev.error ?? ev.message, ev.message)\n const onRejection = (ev: PromiseRejectionEvent) => report(ev.reason)\n win.addEventListener(\"error\", onError)\n win.addEventListener(\"unhandledrejection\", onRejection)\n\n return {\n /** A bundle about to run: errors that map into it go to `onError` until the run is dropped. */\n track(code: string, onError?: (error: PreviewError) => void) {\n const record: RunRecord = { sourceMap: extractInlineSourceMap(code), onError }\n runs.push(record)\n return { drop() { const i = runs.indexOf(record); if (i >= 0) runs.splice(i, 1) } }\n },\n /** Where a stack leads in the source of the bundle that runs now (a creation site an inspector\n * was handed): its frames, the innermost first. */\n locate(error: unknown): MappedFrame[] {\n const map = runs[runs.length - 1]?.sourceMap\n return map ? mapErrorStack(error, map) : []\n },\n /** A line the module printed. The runtime logs what a bundle threw as `[ERROR] <where> <message>`\n * and its stack — in the same line, or a line per frame after it: the lines of one error come in\n * a row, and the error is reported when the row is through. True = the line was the error's. */\n runtimeLine(line: string): boolean {\n if (pending && /^\\s+at /.test(line)) { pending.stack.push(line); return true }\n const m = RUNTIME_ERROR.exec(line)\n if (!m || runs.length === 0) return false\n flush()\n const [message, ...stack] = m[2]!.split(\"\\n\")\n pending = { message: (message ?? \"\").replace(/^JsTask /, \"\"), stack }\n win.setTimeout(flush, 0)\n return true\n },\n dispose() {\n win.removeEventListener(\"error\", onError)\n win.removeEventListener(\"unhandledrejection\", onRejection)\n runs.length = 0\n },\n }\n}\n","// The compiler's bundle header (`lecodes compile` / the builder write it at the top of app.js):\n// // sdk: 2.0.0 the SDK the bundle was compiled with\n// // preload: material:lit;uberarchive;hero.glb what the engine fetches before the first run\n// (`material:<name>` = a built-in material the\n// bundle asks for — ./system.ts picks the archives)\n// // gl: disable | defer no 3D engine up front (the bundle calls\n// `createEngine()` when it needs one — or never)\n// // 2d: enable the project uses Scene2D (creator-2d)\n// // plugins: camera;map the app's plugins, by id (app.json)\n// // fonts: … boot faces (parseFontsHeader)\n// What it MEANS for the engines is `profileOf`: the one place a header becomes a runtime profile.\nimport { parseFontsHeader, type BootFont } from \"lecodes-web-shared/src/utils/fonts\"\nimport type { Profile } from \"lecodes-web-runtime/src/profile\"\n\n/** The browser profiles of the runtime module (runtime/web/native/CMakeLists.txt). */\nexport type HostProfile = Extract<Profile, \"full\" | \"2d\" | \"ui\">\n\nexport type BundleHeader = {\n /** `// sdk: <version>` — the SDK the bundle was compiled with; null = compiled before 2.0 (the\n * pre-tree contract, which this runtime cannot run). Its major must be the host's. */\n sdk: string | null\n /** `// name:` — the project's name as the compiler wrote it. */\n name: string | null\n preloads: Set<string>\n /** `on` = the 3D engine up front, `defer` = the bundle calls `createEngine()` itself, `off` = the\n * bundle names no 3D call at all. */\n gl: \"on\" | \"defer\" | \"off\"\n is2d: boolean\n /** `// plugins:` — the ids of the app's plugins: the ones a host registers for this bundle. A\n * bundle without the line has none. */\n plugins: Set<string>\n bootFonts: BootFont[]\n}\n\nexport const parseBundleHeader = (code: string): BundleHeader => {\n // Wide enough for a `// fonts:` line with several faces (URLs make it the longest header line).\n const header = code.slice(0, 2000)\n const preloads = new Set<string>()\n const preload = header.match(/\\/\\/ preload: (.+)/)\n if (preload) for (const item of preload[1]!.split(\";\")) preloads.add(item)\n const gl = header.includes(\"// gl: disable\") ? \"off\" : header.includes(\"// gl: defer\") ? \"defer\" : \"on\"\n const sdk = header.match(/^\\/\\/ sdk: (\\d+\\.\\d+\\.\\d+\\S*)/m)?.[1] ?? null\n const name = header.match(/^\\/\\/ name: (.+)$/m)?.[1]?.trim() ?? null\n const plugins = new Set((header.match(/^\\/\\/ plugins: (.+)$/m)?.[1] ?? \"\").split(\";\").map((id) => id.trim()).filter(Boolean))\n return { sdk, name, preloads, gl, is2d: header.includes(\"// 2d: enable\"), plugins, bootFonts: parseFontsHeader(header) }\n}\n\n/** The profile a bundle runs on: Filament only for a bundle that names a 3D call (`gl` on / defer),\n * creator-2d for a 2D one, the UI core alone for the rest — a UI app never downloads an engine. */\nexport const profileOf = (header: BundleHeader): HostProfile =>\n header.gl !== \"off\" ? \"full\" : header.is2d ? \"2d\" : \"ui\"\n","// The page: the container the host fills, its size, and the canvases in it.\n//\n// A canvas is sharp when its backing store has exactly the device pixels of its box. That count is\n// the browser's to give (`devicePixelContentBox`): at a fractional pixel ratio (Windows at 125 % /\n// 150 %, a browser zoom) `round(css × ratio)` is off by one now and then, and a canvas one pixel\n// short is resampled — soft text. The observer also fires when the ratio alone changes (the window\n// moved to another display), where the CSS size stays what it was.\nimport { viewScale } from \"lecodes-web-shared/src/ui/viewScale\"\n\nexport type PageSize = {\n /** The container in CSS px — the app's logical viewport. */\n width: number\n height: number\n /** The container in device px — every canvas's backing store. */\n pixelWidth: number\n pixelHeight: number\n /** Device px per CSS px (devicePixelRatio × a CSS zoom above the container). */\n factor: number\n}\n\nexport type Page = ReturnType<typeof createPage>\n\nexport const createPage = (root: HTMLElement) => {\n const doc = root.ownerDocument\n const win = doc.defaultView ?? window\n\n // Until the observer has answered (and where it cannot give device px: Safari), the ratio times\n // the zoom recovered from the DOM.\n const estimate = (width: number, height: number): PageSize => {\n const factor = (win.devicePixelRatio || 1) * viewScale(root)\n return { width, height, factor, pixelWidth: Math.max(1, Math.round(width * factor)), pixelHeight: Math.max(1, Math.round(height * factor)) }\n }\n let size = estimate(Math.max(1, root.clientWidth), Math.max(1, root.clientHeight))\n\n const canvases: HTMLCanvasElement[] = []\n const fit = (canvas: HTMLCanvasElement) => {\n if (canvas.width !== size.pixelWidth) canvas.width = size.pixelWidth\n if (canvas.height !== size.pixelHeight) canvas.height = size.pixelHeight\n }\n /** A canvas over the whole container, hidden until something presents on it. Its box is the\n * container's, so the container's device px are its own. */\n const newCanvas = (): HTMLCanvasElement => {\n const canvas = doc.createElement(\"canvas\")\n canvas.style.cssText = \"position:absolute;inset:0;width:100%;height:100%;display:none;\"\n root.appendChild(canvas)\n fit(canvas)\n canvases.push(canvas)\n return canvas\n }\n\n const listeners = new Set<(size: PageSize) => void>()\n const apply = (next: PageSize) => {\n if (next.width <= 0 || next.height <= 0) return\n size = next\n for (const canvas of canvases) fit(canvas)\n for (const listener of listeners) listener(size)\n }\n const observer = new ResizeObserver(([entry]) => {\n if (!entry) return\n const { width, height } = entry.contentRect\n const device = entry.devicePixelContentBoxSize?.[0]\n const estimated = estimate(width, height)\n // Under an EMULATED pixel ratio (the responsive mode of the browser's tools) the box is\n // reported in the real display's px while the page is drawn at the emulated ratio: the box\n // is believed only where it agrees with the ratio to the pixel it is there to settle.\n const agrees = device && Math.abs(device.inlineSize - width * estimated.factor) <= 1 && Math.abs(device.blockSize - height * estimated.factor) <= 1\n if (!device || !agrees) { apply(estimated); return }\n apply({ width, height, pixelWidth: Math.max(1, device.inlineSize), pixelHeight: Math.max(1, device.blockSize), factor: estimated.factor })\n })\n try { observer.observe(root, { box: \"device-pixel-content-box\" }) } catch { observer.observe(root) }\n\n return {\n root, doc, win,\n size: () => size,\n newCanvas,\n /** Called with every new size, after the canvases took it. */\n onResize(listener: (size: PageSize) => void) { listeners.add(listener); return () => { listeners.delete(listener) } },\n destroy() {\n observer.disconnect()\n listeners.clear()\n for (const canvas of canvases) canvas.remove()\n canvases.length = 0\n },\n }\n}\n","// The doors of the plugins' web halves. A half is the `web/` folder of a plugin: generated glue\n// over its contract and the implementation behind it; it imports nothing of the host — it declares\n// the SHAPE of the host it needs, and `HalfHost` is the object that fits them all.\n//\n// The host names no plugin and ships none. Whoever builds the page hands the halves over\n// (`host.registerPlugin(id, register)`), and WHICH of them a bundle has is the app's list\n// (`\"plugins\"` of app.json → the `// plugins:` line of the bundle's header): what a shell built\n// from the project installs is what the browser registers, so an app cannot work here and fail in\n// its shell. Inside that a half registers itself only where the browser can serve it (a camera\n// needs getUserMedia), so `CameraView.isSupported` answers honestly.\nimport { getBuffer, putBuffer } from \"lecodes-web-shared/src/utils/fetch\"\nimport type { WebViewFactory } from \"lecodes-web-shared/src/ui/nativeView\"\nimport type { ServiceFactory } from \"./tables/serviceSystem\"\n\nexport type HalfHost = {\n /** `version` = the contract version the half was generated from. */\n registerView(name: string, factory: WebViewFactory, version?: number): void\n registerService(name: string, factory: ServiceFactory, version?: number): void\n /** Store bytes in the host's buffer table: the handle a File crosses as. */\n putBuffer(bytes: ArrayBuffer): number\n /** The bytes of a buffer of that table — what the handle of a File the app sent names. */\n getBuffer(systemId: number): ArrayBuffer | Uint8Array | null | undefined\n}\n\n/** What a half exports: it registers its views and services with the host it is handed. */\nexport type PluginHalf = (host: HalfHost) => void\n\n/** Where a registration lands. A renderer that mounts no native view has no `registerView`: views\n * stay unsupported there, services register all the same. */\nexport type PluginDoors = {\n registerView?: (name: string, factory: WebViewFactory, version?: number) => void\n unregisterView?: (name: string) => void\n registerService: (name: string, factory: ServiceFactory, version?: number) => void\n unregisterService: (name: string) => void\n}\n\ntype Registration = { id: string, version: number } & ({ kind: \"view\", name: string, factory: WebViewFactory } | { kind: \"service\", name: string, factory: ServiceFactory })\n\nexport const createPlugins = (doors: PluginDoors) => {\n // What each half registered, by the id of its plugin: a half knows its channel's name, the app's\n // list knows ids.\n const registrations: Registration[] = []\n const known = new Set<string>()\n\n return {\n has: (id: string) => known.has(id),\n register(id: string, half: PluginHalf) {\n if (known.has(id)) return\n known.add(id)\n half({\n registerView: (name, factory, version = 1) => { registrations.push({ id, version, kind: \"view\", name, factory }) },\n registerService: (name, factory, version = 1) => { registrations.push({ id, version, kind: \"service\", name, factory }) },\n putBuffer,\n getBuffer,\n })\n },\n /** The plugins of the bundle about to run: theirs are behind the doors, the others are not. */\n allow(ids: Iterable<string>) {\n const allowed = new Set(ids)\n for (const r of registrations) {\n const on = allowed.has(r.id)\n if (r.kind === \"view\") { if (on) doors.registerView?.(r.name, r.factory, r.version); else doors.unregisterView?.(r.name) }\n else if (on) doors.registerService(r.name, r.factory, r.version)\n else doors.unregisterService(r.name)\n }\n },\n }\n}\n","// The safe area of the page: what the browser reports (`env(safe-area-inset-*)` — zero on a desktop,\n// the notch and the home indicator on a phone) unless the embedder sets its own. The host knows no\n// device: an embedder that draws one over the app says how much of each edge it took.\nimport type { SafeArea } from \"lecodes-web-canvas/src/web/renderer\"\n\nexport type { SafeArea }\n\nexport const createSafeArea = (root: HTMLElement) => {\n // env() is only readable through a computed style.\n const probe = root.ownerDocument.createElement(\"div\")\n probe.style.cssText =\n \"position:absolute;visibility:hidden;pointer-events:none;width:0;height:0;\" +\n \"padding:env(safe-area-inset-top,0px) env(safe-area-inset-right,0px) env(safe-area-inset-bottom,0px) env(safe-area-inset-left,0px);\"\n root.appendChild(probe)\n const px = (value: string) => Math.round(parseFloat(value) || 0)\n const fromPage = (): SafeArea => {\n const style = getComputedStyle(probe)\n return { top: px(style.paddingTop), right: px(style.paddingRight), bottom: px(style.paddingBottom), left: px(style.paddingLeft) }\n }\n\n let set: SafeArea | null = null\n return {\n /** The embedder's insets, or null for the page's own. */\n set(area: SafeArea | null) { set = area },\n current: (): SafeArea => set ?? fromPage(),\n destroy() { probe.remove() },\n }\n}\n","// GENERATED by engines/gl/materials/build.mjs from materials.json `groups` — do not edit.\n// The archive a built-in material rides: a name that is not here rides the base one.\nexport const MATERIAL_GROUP: Record<string, string> = {\n \"lightmap\": \"world\",\n \"lightmap-masked\": \"world\",\n \"lightmap-lite\": \"world\",\n \"lightmap-masked-lite\": \"world\",\n \"terrain\": \"world\",\n \"terrain-lightmap\": \"world\",\n \"foliage\": \"world\",\n \"foliage-masked\": \"world\",\n}\n","// Which materials archives a bundle needs (./system.ts fetches them). The bundle's `// preload:`\n// header names the built-in MATERIALS it asks for (`material:lit`), never the archives: how the\n// shared set is split into files (materials.json `groups`, the generated table beside the\n// archives) may change under a bundle compiled long ago, and that bundle must still get the archive\n// its material rides today.\nimport { MATERIAL_GROUP } from \"lecodes-web-runtime/src/gen/materialGroups.gen\"\n\nconst PREFIX = \"material:\"\n\n/** The groups whose archives hold the materials `preloads` names — \"base\" first, each once. A\n * material no group names rides the base archive. */\nexport const materialGroupsOf = (preloads: Iterable<string>): string[] => {\n const groups = new Set<string>()\n for (const item of preloads) {\n if (item.startsWith(PREFIX)) groups.add(MATERIAL_GROUP[item.slice(PREFIX.length)] ?? \"base\")\n }\n return [...groups].sort((a, b) => (a === \"base\" ? -1 : b === \"base\" ? 1 : a.localeCompare(b)))\n}\n","export default \"__VITE_ASSET__g0Ta5n91__\"","export default \"__VITE_ASSET__D83o3gZr__\"","export default \"__VITE_ASSET__CQj_jpxr__\"","export default \"__VITE_ASSET__D7kfxuDz__\"","// The engine's built-in blobs, which the runtime asks for by system id (globals.h): 1 = the default\n// IBL, 2 = the ubershader archive, 3 = the archives of the materials a bundle asked for\n// (./materials.ts), back to back. Only the `full` profile reads them.\nimport { materialGroupsOf } from \"./materials\"\nimport materialsBase from \"lecodes-web-runtime/src/assets/materials.bin?url\"\nimport materialsWorld from \"lecodes-web-runtime/src/assets/materials-world.bin?url\"\nimport iblTexture from \"lecodes-web-runtime/src/assets/neutral_ibl128.ktx?url\"\nimport uberarchive from \"lecodes-web-runtime/src/assets/uberarchive.bin?url\"\n\nexport type SystemBuffers = Partial<Record<1 | 2 | 3, ArrayBuffer>>\n\nconst ARCHIVES: Record<string, string> = { base: materialsBase, world: materialsWorld }\n\nconst join = (parts: ArrayBuffer[]): ArrayBuffer => {\n const out = new Uint8Array(parts.reduce((n, p) => n + p.byteLength, 0))\n let at = 0\n for (const p of parts) { out.set(new Uint8Array(p), at); at += p.byteLength }\n return out.buffer\n}\n\nexport const loadSystemBuffers = async (preloads: Iterable<string>): Promise<SystemBuffers> => {\n const bytes = async (url: string) => {\n const response = await fetch(url)\n if (!response.ok) throw new Error(`${url} → HTTP ${response.status}`)\n return response.arrayBuffer()\n }\n const wanted = materialGroupsOf(preloads).map((group) => ARCHIVES[group]).filter((url): url is string => !!url)\n const [ibl, uber, ...materials] = await Promise.all([bytes(iblTexture), bytes(uberarchive), ...wanted.map(bytes)])\n return { 1: ibl, 2: uber, ...(materials.length > 0 ? { 3: join(materials) } : {}) }\n}\n","// HostApp: the app's lifecycle and environment — the document's visibility, the network state, the\n// url the app was opened with, the orientation it asks for.\nimport type { WasmHostApp } from \"lecodes-web-runtime/src/gen/host.gen\"\n\nexport type AppTableOptions = {\n /** app.setOrientation sink (an embedder that draws a device turns it); absent = a best-effort\n * screen.orientation.lock on the page (browsers honor it only in fullscreen). */\n onOrientation?: (mode: \"landscape\" | \"portrait\" | \"auto\") => void\n /** Push an app event into the runtime (`creatorWebAppEvent`). */\n push: (event: string, data?: string) => void\n}\n\nexport const createAppTable = (options: AppTableOptions) => {\n const onVisibility = () => options.push(document.hidden ? \"pause\" : \"resume\")\n const onOnline = () => options.push(\"online\")\n const onOffline = () => options.push(\"offline\")\n document.addEventListener(\"visibilitychange\", onVisibility)\n window.addEventListener(\"online\", onOnline)\n window.addEventListener(\"offline\", onOffline)\n\n const table: WasmHostApp = {\n state: () => (document.hidden ? \"background\" : \"active\"),\n isOnline: () => navigator.onLine,\n openUrl(url) { window.open(url, \"_blank\", \"noopener\") },\n setOrientation(mode) {\n const m = mode === \"landscape\" || mode === \"portrait\" ? mode : \"auto\"\n if (options.onOrientation) { options.onOrientation(m); return }\n const so = typeof screen !== \"undefined\" ? (screen.orientation as unknown as { lock?: (m: string) => Promise<void>, unlock?: () => void }) : undefined\n if (!so) return\n try {\n if (m === \"auto\") so.unlock?.()\n else so.lock?.(m)?.catch?.(() => {})\n } catch { /* not fullscreen / unsupported */ }\n },\n }\n return {\n table,\n /** The embedder delivers a warm link (\"url\") or a synthetic lifecycle event. */\n emit: (event: string, data?: string) => options.push(event, data),\n dispose() {\n document.removeEventListener(\"visibilitychange\", onVisibility)\n window.removeEventListener(\"online\", onOnline)\n window.removeEventListener(\"offline\", onOffline)\n },\n }\n}\n","import { putBuffer } from \"lecodes-web-shared/src/utils/fetch\";\n\nexport const openFilePicker = (\n onComplete: (files: any) => void,\n onReject: (error: any) => void,\n multiple: boolean,\n accept?: string\n) => {\n try {\n const input = document.createElement(\"input\");\n input.type = \"file\";\n input.multiple = multiple;\n\n if (accept) {\n input.accept = accept;\n }\n\n input.onchange = async () => {\n const { files } = input;\n if (multiple) {\n const arr: any[] = []\n if (!files) return onComplete([])\n for (let file of files) {\n arr.push([\n putBuffer(await file.arrayBuffer()),\n file.name,\n file.size\n ])\n }\n onComplete(arr);\n } else {\n if (!files || files.length === 0) return onComplete(null)\n onComplete([ [ putBuffer(await files[0].arrayBuffer()), files[0].name, files[0].size ] ]);\n }\n };\n\n // Срабатывает когда диалог закрывается без выбора файла\n window.addEventListener(\n \"focus\",\n () => {\n setTimeout(() => {\n if (!input.files || input.files.length === 0) {\n onComplete(multiple ? [] : null);\n }\n }, 300);\n },\n { once: true }\n );\n\n input.click();\n } catch (error) {\n onReject(error);\n }\n};","// HostDevice. The data fields are read at every resize (the runtime's hostWasmSync): live getters\n// keep the pixel ratio honest when the window moves between displays.\nimport type { WasmHostDevice } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport { getBlob } from \"lecodes-web-shared/src/utils/fetch\"\nimport { openFilePicker } from \"./openFilePicker\"\n\nexport const createDeviceTable = (language: () => string): WasmHostDevice => ({\n get platform() { return \"web\" },\n get language() { return language() },\n get pixelRatio() { return window.devicePixelRatio || 1 },\n vibrate() { try { navigator.vibrate?.(30) } catch { /* unsupported */ } },\n clipboardWrite(text) { navigator.clipboard?.writeText(text).catch(() => {}) },\n clipboardRead(onComplete, onReject) {\n const c = navigator.clipboard\n if (!c?.readText) { onReject(\"Clipboard is not available\"); return }\n c.readText().then(onComplete, (e: unknown) => onReject(e instanceof Error ? e.message : \"Clipboard read failed\"))\n },\n // No web share sheet — save (download) the buffer. `text` is ignored on web.\n share(systemId) {\n const url = URL.createObjectURL(getBlob(systemId))\n const a = document.createElement(\"a\")\n a.href = url\n a.download = \"image.png\"\n document.body.appendChild(a)\n a.click()\n a.remove()\n URL.revokeObjectURL(url)\n },\n openFilePicker: (onComplete, onReject, multiple, accept) => openFilePicker(onComplete, onReject, multiple, accept ?? undefined),\n // The browser has no standalone camera-permission prompt: getUserMedia asks at capture time.\n requestCamera(onComplete) { onComplete() },\n})\n","// HostFetch: the network and the buffer store. The store is web-shared's — the one every web\n// package reads (a texture is resolved by its system id there, a plugin's File is a buffer of it).\nimport type { WasmHostFetch } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport { _disposeFetch, _fetchLocal, getBlob, getBuffer, putBuffer } from \"lecodes-web-shared/src/utils/fetch\"\nimport type { SystemBuffers } from \"../system\"\n\nexport const createFetchTable = (system: SystemBuffers = {}): WasmHostFetch => ({\n local: (path) => _fetchLocal(path),\n dispose: (id) => _disposeFetch(id),\n request(url, method, headers, body, form, onComplete, onReject, onProgress) {\n // an asset the store already holds (`id:<n>`)\n if (url.startsWith(\"id:\")) { const id = Number(url.slice(3)); onComplete(id, getBuffer(id) ? 200 : 404); return }\n const h: Record<string, string> = {}\n for (let i = 0; i + 1 < headers.length; i += 2) h[headers[i]] = headers[i + 1]\n let payload: BodyInit | undefined\n if (form.length > 0) {\n const fd = new FormData()\n for (const e of form) {\n if (e.key === null) continue\n if (e.bufferId > 0) fd.append(e.key, getBlob(e.bufferId), e.filename ?? undefined)\n else fd.append(e.key, e.value ?? \"\")\n }\n payload = fd\n } else if (body !== null) payload = body\n ;(async () => {\n try {\n const resp = await fetch(url, { method, headers: h, body: payload, mode: \"cors\", credentials: \"omit\" })\n const reader = onProgress ? resp.body?.getReader() : undefined\n if (!reader) {\n onComplete(putBuffer(await resp.arrayBuffer()), resp.status)\n return\n }\n const total = Number(resp.headers.get(\"content-length\")) || undefined\n const chunks: Uint8Array[] = []\n let loaded = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (value) { chunks.push(value); loaded += value.length; onProgress!({ loaded, total }) }\n }\n const out = new Uint8Array(loaded)\n let off = 0\n for (const c of chunks) { out.set(c, off); off += c.length }\n onComplete(putBuffer(out.buffer), resp.status)\n } catch (e) {\n onReject(e instanceof Error ? e.message : String(e))\n }\n })()\n },\n buffer: (id) => { const b = getBuffer(id); return b ? new Uint8Array(b) : null },\n putBuffer: (bytes) => putBuffer(bytes.slice().buffer), // an encoded canvas (Canvas.toFile) → a File\n bufferSlice(id, start, end) {\n const b = getBuffer(id)\n if (!b) return null\n const s = Math.max(0, Math.min(start, b.byteLength)), e = Math.max(s, Math.min(end, b.byteLength))\n return new Uint8Array(b, s, e - s)\n },\n systemBuffer: (id) => { const b = system[id as 1 | 2 | 3]; return b ? new Uint8Array(b) : null },\n})\n","// Browser input host behind `_creatorInput.key / read / setPointerLock / registerEvent`\n// (sdk/src/bridges/input.d.ts).\n//\n// Buttons: keyboard keys, mouse buttons and gamepad buttons live in ONE held set keyed by the shared\n// code vocabulary (\"KeyW\" / \"MouseLeft\" / \"GamepadSouth\"); gamepad buttons are additionally keyed\n// per pad (\"GamepadSouth@1\") so `inputKey(code, pad)` can scope. Continuous channels (mouse motion /\n// wheel / sticks) are sampled on a requestAnimationFrame boundary: the accumulator that fills during\n// a frame becomes the value every `inputRead` sees during the next one — \"motion during the previous\n// frame\", the same contract the native hosts implement on their event pump.\n\nconst MOUSE_BUTTON_CODES = [\"MouseLeft\", \"MouseMiddle\", \"MouseRight\", \"MouseBack\", \"MouseForward\"]\n// W3C \"standard\" gamepad mapping button index → code.\nconst GAMEPAD_BUTTON_CODES = [\n \"GamepadSouth\", \"GamepadEast\", \"GamepadWest\", \"GamepadNorth\", \"GamepadL1\", \"GamepadR1\", \"GamepadL2\", \"GamepadR2\",\n \"GamepadSelect\", \"GamepadStart\", \"GamepadL3\", \"GamepadR3\", \"GamepadUp\", \"GamepadDown\", \"GamepadLeft\", \"GamepadRight\",\n]\nconst MAX_PADS = 4\nconst PAD_BASE = 16, PAD_STRIDE = 16\nconst TRIGGER_AS_BUTTON = 0.5 // analog L2/R2 count as held past this\n\nexport type InputEventSink = (kind: number, code: string, gamepad: number, repeat: number) => void\n\nexport interface InputHostOptions {\n /** Windows to listen on for keys (the app's own window plus the embedder's, which keeps focus\n * until the user clicks the preview). */\n windows: Window[]\n /** The viewport element: mouse position is relative to it, pointer lock is requested on it. */\n root: HTMLElement\n /** Listen for keyboard keys (default true). Mouse/gamepad are always wired. */\n keyboard?: boolean\n}\n\nexport const createInputHost = (options: InputHostOptions) => {\n const held = new Set<string>()\n let sink: InputEventSink | null = null\n const emit = (kind: number, code: string, gamepad = -1, repeat = 0) => { sink?.(kind, code, gamepad, repeat) }\n\n // ---- keyboard ----------------------------------------------------------------------------------\n const onKeyDown = (e: KeyboardEvent) => {\n if (!e.code) return\n const wasHeld = held.has(e.code)\n held.add(e.code)\n emit(0, e.code, -1, wasHeld || e.repeat ? 1 : 0)\n }\n const onKeyUp = (e: KeyboardEvent) => { if (e.code && held.delete(e.code)) emit(1, e.code) }\n // Focus loss: the window never sees the release of a key held through it → clear + emit keyups.\n const onBlur = () => {\n for (const code of [...held]) {\n if (!code.startsWith(\"Gamepad\")) { held.delete(code); emit(1, code) }\n }\n }\n\n // ---- mouse -------------------------------------------------------------------------------------\n const { root } = options\n let mouseX = 0, mouseY = 0\n let accDX = 0, accDY = 0, accWX = 0, accWY = 0 // filling during the current frame\n let frameDX = 0, frameDY = 0, frameWX = 0, frameWY = 0 // what inputRead reports (previous frame)\n const onPointerMove = (e: PointerEvent | MouseEvent) => {\n if ((e as PointerEvent).pointerType && (e as PointerEvent).pointerType !== \"mouse\") return\n const r = root.getBoundingClientRect()\n mouseX = e.clientX - r.left; mouseY = e.clientY - r.top\n accDX += e.movementX || 0; accDY += e.movementY || 0\n }\n const onMouseDown = (e: MouseEvent) => {\n const code = MOUSE_BUTTON_CODES[e.button]\n if (!code) return\n held.add(code); emit(0, code)\n }\n const onMouseUp = (e: MouseEvent) => {\n const code = MOUSE_BUTTON_CODES[e.button]\n if (code && held.delete(code)) emit(1, code)\n }\n const onWheel = (e: WheelEvent) => {\n // Notches: deltaMode 0 (pixels) ≈ 100 px per notch on most browsers.\n const k = e.deltaMode === 0 ? 1 / 100 : 1\n accWX += e.deltaX * k; accWY += e.deltaY * k\n }\n const onContextMenu = (e: Event) => { if (document.pointerLockElement === root) e.preventDefault() }\n\n // ---- gamepads ----------------------------------------------------------------------------------\n // The Gamepad API is poll-only: sample on the frame boundary, diff buttons into events.\n const padConnected: boolean[] = []\n const padAxes: number[][] = [] // [lx, ly, rx, ry, lt, rt] per pad\n const padButtons: boolean[][] = []\n const pollGamepads = () => {\n const pads: (Gamepad | null)[] = typeof navigator !== \"undefined\" && navigator.getGamepads ? Array.from(navigator.getGamepads()) : []\n for (let i = 0; i < MAX_PADS; i++) {\n const p = pads[i] ?? null\n const connected = !!p && p.connected\n if (connected !== !!padConnected[i]) {\n padConnected[i] = connected\n if (!connected) { // release everything the pad held\n for (const code of GAMEPAD_BUTTON_CODES) {\n if (held.delete(code + \"@\" + i)) { emit(1, code, i); refreshAnyPad(code) }\n }\n padButtons[i] = []; padAxes[i] = [0, 0, 0, 0, 0, 0]\n }\n emit(connected ? 2 : 3, \"\", i)\n }\n if (!p || !connected) continue\n const a = p.axes, b = p.buttons\n const lt = b[6]?.value ?? 0, rt = b[7]?.value ?? 0\n padAxes[i] = [a[0] ?? 0, a[1] ?? 0, a[2] ?? 0, a[3] ?? 0, lt, rt]\n const prev = padButtons[i] ?? (padButtons[i] = [])\n for (let k = 0; k < GAMEPAD_BUTTON_CODES.length; k++) {\n const btn = b[k]\n const down = !!btn && (btn.pressed || btn.value > TRIGGER_AS_BUTTON)\n if (down === !!prev[k]) continue\n prev[k] = down\n const code = GAMEPAD_BUTTON_CODES[k]\n if (down) held.add(code + \"@\" + i); else held.delete(code + \"@\" + i)\n refreshAnyPad(code)\n emit(down ? 0 : 1, code, i)\n }\n }\n }\n // The unscoped code (\"GamepadSouth\") is held while ANY pad holds it.\n const refreshAnyPad = (code: string) => {\n let any = false\n for (let i = 0; i < MAX_PADS && !any; i++) if (held.has(code + \"@\" + i)) any = true\n if (any) held.add(code); else held.delete(code)\n }\n\n // ---- frame boundary ----------------------------------------------------------------------------\n let raf = 0\n const onFrame = () => {\n frameDX = accDX; frameDY = accDY; frameWX = accWX; frameWY = accWY\n accDX = accDY = accWX = accWY = 0\n pollGamepads()\n raf = requestAnimationFrame(onFrame)\n }\n\n // ---- wiring ------------------------------------------------------------------------------------\n const windows = options.windows.filter((w, i, arr) => w && arr.indexOf(w) === i)\n for (const w of windows) {\n if (options.keyboard !== false) {\n w.addEventListener(\"keydown\", onKeyDown)\n w.addEventListener(\"keyup\", onKeyUp)\n }\n w.addEventListener(\"blur\", onBlur)\n }\n // In the CAPTURE phase: the UI renderer stops an event it took on its way to a view under the\n // picture, and what the mouse did is the app's to read either way.\n root.addEventListener(\"pointermove\", onPointerMove, true)\n root.addEventListener(\"mousedown\", onMouseDown, true)\n // Up on the window: a drag that ends outside the viewport must still release the button.\n window.addEventListener(\"mouseup\", onMouseUp, true)\n root.addEventListener(\"wheel\", onWheel, { passive: true, capture: true })\n root.addEventListener(\"contextmenu\", onContextMenu, true)\n if (typeof requestAnimationFrame === \"function\") raf = requestAnimationFrame(onFrame)\n\n const inputKey = (code: string, gamepad: number) =>\n gamepad >= 0 && code.startsWith(\"Gamepad\") ? held.has(code + \"@\" + gamepad) : held.has(code)\n\n const inputRead = (channel: number): number => {\n switch (channel) {\n case 0: return mouseX\n case 1: return mouseY\n case 2: return frameDX\n case 3: return frameDY\n case 4: return frameWX\n case 5: return frameWY\n case 6: return document.pointerLockElement === root ? 1 : 0\n case 7: { let n = 0; for (let i = 0; i < MAX_PADS; i++) if (padConnected[i]) n++; return n }\n }\n if (channel >= PAD_BASE) {\n const pad = Math.floor((channel - PAD_BASE) / PAD_STRIDE), k = (channel - PAD_BASE) % PAD_STRIDE\n if (pad >= MAX_PADS || !padConnected[pad]) return 0\n if (k === 0) return 1\n return padAxes[pad]?.[k - 1] ?? 0\n }\n return 0\n }\n\n const inputSetPointerLock = (on: boolean): boolean => {\n if (!on) { if (document.pointerLockElement === root) document.exitPointerLock(); return true }\n if (document.pointerLockElement === root) return true\n if (typeof root.requestPointerLock !== \"function\") return false\n try {\n const r: any = root.requestPointerLock({ unadjustedMovement: true } as any)\n if (r && typeof r.catch === \"function\") r.catch(() => { try { root.requestPointerLock() } catch {} })\n return true\n } catch { return false }\n }\n\n const registerInputEvent = (cb: InputEventSink) => { sink = cb }\n\n const dispose = () => {\n for (const w of windows) {\n w.removeEventListener(\"keydown\", onKeyDown)\n w.removeEventListener(\"keyup\", onKeyUp)\n w.removeEventListener(\"blur\", onBlur)\n }\n root.removeEventListener(\"pointermove\", onPointerMove, true)\n root.removeEventListener(\"mousedown\", onMouseDown, true)\n window.removeEventListener(\"mouseup\", onMouseUp, true)\n root.removeEventListener(\"wheel\", onWheel, true)\n root.removeEventListener(\"contextmenu\", onContextMenu, true)\n if (raf) cancelAnimationFrame(raf)\n if (document.pointerLockElement === root) document.exitPointerLock()\n held.clear(); sink = null\n }\n\n return { inputKey, inputRead, inputSetPointerLock, registerInputEvent, dispose }\n}\n","// HostInput: keys, mouse and gamepads (./inputHost.ts), and the height of the on-screen keyboard.\nimport type { WasmHostInput } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport { createInputHost, type InputHostOptions } from \"./inputHost\"\n\nexport type InputTableOptions = InputHostOptions & {\n push: (kind: number, code: string, gamepad: number, repeat: number) => void\n keyboardHeight: () => number\n}\n\nexport const createInputTable = (options: InputTableOptions) => {\n const input = createInputHost(options)\n input.registerInputEvent(options.push)\n const table: WasmHostInput = {\n key: input.inputKey,\n read: input.inputRead,\n setPointerLock: input.inputSetPointerLock,\n keyboardHeight: options.keyboardHeight,\n }\n return { table, dispose: input.dispose }\n}\n","// HostMedia: the video / audio players of web-shared.\nimport type { WasmHostMedia } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport { createAudioPlayer, createVideoPlayer, getMediaPlayerDuration, getMediaPlayerTime, removeMediaPlayer, setMediaPlayerTime, updateMediaPlayerLoop, updateMediaPlayerPlaying, updateMediaPlayerVolume } from \"lecodes-web-shared/src/utils/mediaplayer\"\n\nexport const mediaTable: WasmHostMedia = {\n createVideo: createVideoPlayer,\n createAudio: createAudioPlayer,\n setVolume: updateMediaPlayerVolume,\n setPlaying: updateMediaPlayerPlaying,\n setLoop: updateMediaPlayerLoop,\n time: getMediaPlayerTime,\n setTime: setMediaPlayerTime,\n duration: getMediaPlayerDuration,\n remove: removeMediaPlayer,\n}\n","// The headless services of a web host — the UI-less sibling of a native view. A plugin's web half\n// registers a factory:\n//\n// host.registerService(\"geolocation\", (params, channel) => ({\n// call: (method, args) => {...},\n// close: () => {...},\n// }))\n//\n// One `serviceOpen` = one live session (host-allocated id, websocket-style); `channel.emit`\n// delivers events to the session's SDK-side listeners. There is no placeholder concept —\n// an unregistered name makes serviceOpen return -1 and the SDK wrapper rejects cleanly.\n\nexport type ServiceChannel = { emit(event: string, data?: any): void }\nexport type ServiceHandle = {\n call?(method: string, args: any[]): any | Promise<any>\n close?(): void\n}\nexport type ServiceFactory = (params: any, channel: ServiceChannel) => ServiceHandle\n\nexport const createServiceSystem = () => {\n const factories = new Map<string, ServiceFactory>()\n const versions = new Map<string, number>()\n const sessions = new Map<number, ServiceHandle>()\n let nextSessionId = 1\n\n /** `version` = the contract version the half was generated from (1 for one written by hand). */\n const registerService = (name: string, factory: ServiceFactory, version = 1) => { factories.set(name, factory); versions.set(name, version) }\n /** A service the next bundle does not have (its plugin is not among the app's). */\n const unregisterService = (name: string) => { factories.delete(name); versions.delete(name) }\n const isServiceSupported = (name: string) => factories.has(name)\n const serviceVersion = (name: string) => versions.get(name) ?? 0\n\n /** The `_creatorService.open` bridge. Must stay cheap: factories create the session\n * object only — permission prompts and I/O belong in the first call that needs them. */\n const serviceOpen = (name: string, params: string, onEvent: (event: string, data?: unknown) => void): number => {\n const factory = factories.get(name)\n if (!factory) return -1\n const id = nextSessionId++\n // A payload crosses as the value it is: the app and this host are the same JavaScript.\n const handle = factory(params ? JSON.parse(params) : {}, {\n emit: (event, data) => { if (data === undefined) onEvent(event); else onEvent(event, data) },\n })\n sessions.set(id, handle)\n return id\n }\n\n /** The `_creatorService.call` bridge — values in and out, promise-friendly (same as viewCall).\n * `args` is the app's own array: a half reads, never keeps or changes it. */\n const serviceCall = (serviceId: number, method: string, args: unknown, onComplete: (result?: unknown) => void, onError: (err: string) => void) => {\n const session = sessions.get(serviceId)\n if (!session?.call) {\n onError(`Service call \"${method}\": no live session or no call handler (serviceId ${serviceId})`)\n return\n }\n try {\n Promise.resolve(session.call(method, Array.isArray(args) ? args : [])).then(\n (result) => { if (result === undefined) onComplete(); else onComplete(result) },\n (e) => onError(e instanceof Error ? e.message : String(e)),\n )\n } catch (e) {\n onError(e instanceof Error ? e.message : String(e))\n }\n }\n\n const serviceClose = (serviceId: number) => {\n sessions.get(serviceId)?.close?.()\n sessions.delete(serviceId)\n }\n\n /** Host teardown: release every live session (a GPS watch must actually stop). */\n const destroy = () => {\n for (const s of sessions.values()) s.close?.()\n sessions.clear()\n }\n\n return { registerService, unregisterService, isServiceSupported, serviceVersion, serviceOpen, serviceCall, serviceClose, destroy }\n}\n\nexport type ServiceSystem = ReturnType<typeof createServiceSystem>\n","// HostService: the headless services of the plugins' web halves (a session per `open`).\nimport type { WasmHostService } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport { createServiceSystem } from \"./serviceSystem\"\n\nexport const createServiceTable = () => {\n const services = createServiceSystem()\n const table: WasmHostService = { supported: services.isServiceSupported, version: services.serviceVersion, open: services.serviceOpen, call: services.serviceCall, close: services.serviceClose }\n return { table, registerService: services.registerService, unregisterService: services.unregisterService, dispose: services.destroy }\n}\n","// HostSocket: the websockets of one host — tearing a host down closes its own, no other's.\nimport type { WasmHostSocket } from \"lecodes-web-runtime/src/gen/host.gen\"\n\nexport const createSocketTable = () => {\n const sockets: WebSocket[] = []\n const table: WasmHostSocket = {\n open(url, onMessage) {\n const socket = new WebSocket(url)\n socket.addEventListener(\"open\", () => onMessage(\"open\"))\n socket.addEventListener(\"message\", (ev) => onMessage(\"message\", ev.data as string))\n socket.addEventListener(\"close\", (ev) => onMessage(\"close\", ev.code))\n socket.addEventListener(\"error\", () => onMessage(\"error\"))\n sockets.push(socket)\n return sockets.length - 1\n },\n send(id, data) { sockets[id]?.send(data) },\n close(id) { sockets[id]?.close() },\n }\n return {\n table,\n dispose() {\n for (const socket of sockets) if (socket.readyState === WebSocket.OPEN) socket.close()\n sockets.length = 0\n },\n }\n}\n","// HostStorage: one JSON blob per storage name, in localStorage under the project's key — what an app\n// saved is there the next time it is opened, and two projects served from one origin (a dev server,\n// a page of demos) do not read each other's.\nimport type { WasmHostStorage } from \"lecodes-web-runtime/src/gen/host.gen\"\n\nexport const createStorageTable = (project: string): WasmHostStorage => {\n const key = (name: string) => `lecodes:${project}:${name}`\n return {\n load(name) { try { return window.localStorage.getItem(key(name)) } catch { return null } },\n save(name, json) { try { window.localStorage.setItem(key(name), json) } catch { /* quota / private mode */ } },\n }\n}\n","// A world: the global object a bundle runs against. The runtime installs its bridges on it\n// (non-enumerable: getOwnPropertyNames), and the bundle's globals reach the bundle as the\n// PARAMETERS of a Function. Not a sandbox — the page's `window` and `document` are in reach of the\n// bundle; an embedder that runs code it does not trust puts the page on another origin.\n// No sourceURL: the source map applies to `<anonymous>` frames (./errors.ts).\nimport type { JsbWorld } from \"lecodes-web-runtime/src/jsb\"\n\nexport const makeWorld = (): JsbWorld => {\n const global: Record<string, unknown> = {}\n const evaluate = (code: string) => {\n const names = Object.getOwnPropertyNames(global)\n return new Function(...names, code)(...names.map((name) => global[name]))\n }\n return { global, evaluate }\n}\n","// The web host: a compiled bundle in the browser on the RUNTIME MODULE — runtime/native compiled to\n// wasm (runtime/web: `full` = Filament + 2d + ui + nav, `2d`, `ui`), over the page's own JS engine.\n// The runtime owns the UI tree, the timers / loops / tweens, the worlds and every bridge object\n// (`_creator`, `_creatorTree`, `_creatorFetch`, …); the host is what it calls a page for — and this\n// file only puts the parts together, each of which is a file of its own:\n//\n// page.ts the container, its size in device px, the canvases\n// engines/ the 3D and the 2D surface (HostGL, HostScene2d)\n// tables/ fetch, storage, device, app, socket, service, input, media — a file per table\n// the renderer lecodes-web-canvas: the TreeUI (HostUI) painted on a canvas over the scenes\n// plugins.ts the doors of the plugins' web halves\n// errors.ts what a bundle threw, mapped to its source\n//\n// The host FILLS the container it is given and knows nothing around it: no device, no frame, no\n// zoom, no url, no message. `createHost(root, options)` brings it up once; `host.run(code)`\n// evaluates a bundle, repeatably.\n/// <reference path=\"./contract.d.ts\" />\n\nimport { loadProfileModule } from \"lecodes-web-runtime/src/profile\"\nimport type { WasmHostTables } from \"lecodes-web-runtime/src/gen/host.gen\"\nimport { installJsb } from \"lecodes-web-runtime/src/jsb\"\nimport { installWasmCrashSymbolizer } from \"lecodes-web-runtime/src/wasmCrashSymbolizer\"\nimport { createCanvasRenderer, type CanvasRenderer } from \"lecodes-web-canvas/src/web/renderer\"\nimport { createCanvasHost } from \"lecodes-web-shared/src/canvas/createCanvasHost\"\nimport { removePlayers } from \"lecodes-web-shared/src/utils/mediaplayer\"\nimport { ensureFontsLoaded, loadBootFonts } from \"lecodes-web-shared/src/utils/fonts\"\nimport { viewScale } from \"lecodes-web-shared/src/ui/viewScale\"\nimport { SDK_VERSION, bundleRunsOn } from \"lecodes-sdk/version\"\nimport { TREE_DEST_SCENE2D, TREE_DEST_SCENE3D } from \"lecodes-sdk/ui/tree\"\nimport { createGLSurface } from \"./engines/gl\"\nimport { createScene2dSurface } from \"./engines/scene2d\"\nimport { createErrorReporter, type PreviewError } from \"./errors\"\nimport { parseBundleHeader, profileOf, type BundleHeader, type HostProfile } from \"./header\"\nimport { createPage, type PageSize } from \"./page\"\nimport { createPlugins, type PluginHalf } from \"./plugins\"\nimport { createSafeArea, type SafeArea } from \"./safeArea\"\nimport { loadSystemBuffers, type SystemBuffers } from \"./system\"\nimport { createAppTable } from \"./tables/app\"\nimport { createDeviceTable } from \"./tables/device\"\nimport { createFetchTable } from \"./tables/fetch\"\nimport { createInputTable } from \"./tables/input\"\nimport { mediaTable } from \"./tables/media\"\nimport { createServiceTable } from \"./tables/service\"\nimport { createSocketTable } from \"./tables/socket\"\nimport { createStorageTable } from \"./tables/storage\"\nimport { makeWorld } from \"./world\"\n\nexport type HostOptions = {\n /** The header of the bundle the host is for (`parseBundleHeader`): its engines decide the profile,\n * its materials the archives, its fonts the boot faces. */\n header?: BundleHeader\n /** The runtime profile, in place of the header's (a host with no bundle yet: an editor). */\n profile?: HostProfile\n /** false = an engine-only host: no UI renderer, no fonts. Default true. */\n ui?: boolean\n /** The project, as the key its storage is kept under. Default: the header's name. */\n project?: string\n /** Insets the embedder took of the container; absent = the page's own (`env(safe-area-inset-*)`). */\n safeArea?: SafeArea\n /** device.language. Default: the browser's. */\n language?: () => string\n /** The url the app was opened with (app.launchUrl). A warm link goes through `host.emitAppEvent(\"url\", url)`. */\n launchUrl?: string\n /** app.setOrientation sink; absent = a best-effort screen.orientation.lock on the page. */\n onOrientation?: (mode: \"landscape\" | \"portrait\" | \"auto\") => void\n /** Listen for keyboard keys (Input.key). Default true. */\n keyboard?: boolean\n /** Windows to listen on for keys besides the host's own (an embedder that keeps the focus). */\n keyboardTargets?: Window[]\n}\n\nexport type RunOptions = {\n /** Called when this bundle throws, with the error mapped back to its source. */\n onError?: (error: PreviewError) => void\n /** The bundle's header, in place of the one read from its first lines (a bundle compiled with\n * none: its SDK version and its plugins are what is said here). */\n header?: Pick<BundleHeader, \"sdk\" | \"plugins\">\n}\n\nexport type Run = {\n /** Stop attributing errors to this run. What the bundle created is the world's: it goes with the\n * host, or when the app swaps worlds. */\n dispose(): void\n}\n\n/** An engine-only host still owes the runtime its HostUI table: nothing is rendered but the\n * destination change (the scene canvases). */\nconst nullHostUI = (onDestination: (kind: number, id: number) => void, onDropped: (kind: number, id: number) => void): WasmHostTables[\"ui\"] => ({\n nodeFactory() {}, setPropertyString() {}, setPropertyInt() {}, setFlags() {}, insertNode() {}, removeNode() {}, releaseNode() {},\n openView(kind, _node, id) { onDestination(kind, id) }, dropView(kind, _node, id) { onDropped(kind, id) }, closeView() { onDestination(-1, 0) }, widgetOpen() {}, widgetClose() {},\n registerFont(_url, _family, _weight, _style, onComplete) { onComplete() },\n showToast() {}, getButtonPressed: () => false, getTextValue: () => \"\", vlistScroll() {},\n})\n\nexport type Host = Awaited<ReturnType<typeof createHost>>\n\nexport const createHost = async (root: HTMLElement, options: HostOptions = {}) => {\n const header = options.header\n const profile = options.profile ?? (header ? profileOf(header) : \"full\")\n const preloads = header?.preloads ?? new Set<string>()\n const withUI = options.ui !== false\n const has3d = profile === \"full\"\n const has2d = profile === \"2d\" || (profile === \"full\" && !!header?.is2d)\n\n const page = createPage(root)\n const { doc, win } = page\n\n // The measurement font + the app's boot faces load beside the module; awaited before the host\n // returns, so the first layout measures text against the real font.\n const fonts = withUI ? Promise.all([ensureFontsLoaded(undefined, doc), loadBootFonts(header?.bootFonts ?? [], doc)]) : null\n\n // Bottom to top: the 3D scene, the 2D scene, the UI.\n const gl = has3d ? createGLSurface(page, preloads.has(\"capture\")) : null\n const scene2d = has2d ? createScene2dSurface(page) : null\n const uiCanvas = withUI ? page.newCanvas() : null\n\n const errors = createErrorReporter(win, has3d)\n if (has3d) installWasmCrashSymbolizer()\n\n const [M, system] = await Promise.all([\n loadProfileModule(profile, {\n glContext: gl?.context, glOptions: gl?.options,\n gl2dContext: scene2d?.context, gl2dOptions: scene2d?.options,\n moduleArgs: {\n // what a bundle threw is reported once, mapped to its source (errors.ts): its raw lines are\n // for whoever reads the browser's console at its most verbose\n print: (line: string) => { if (errors.runtimeLine(line)) console.debug(line); else console.log(line) },\n printErr: (line: string) => { console.error(line) },\n },\n }),\n has3d ? loadSystemBuffers(preloads) : Promise.resolve<SystemBuffers>({}),\n ])\n const withStr = <T>(s: string, fn: (ptr: number) => T): T => {\n const p = M.stringToNewUTF8(s)\n try { return fn(p) } finally { M._free(p) }\n }\n\n // ---- a destination change: a scene presents on its canvas ---------------------------------------\n // The canvas of the destination that LEFT goes when the runtime drops it (HostUI.dropView), not\n // when the next one opens: a screen may still be coming in over it — a surface never moves, it\n // stands under the screen until the transition lands. Unless a destination of the same kind is on\n // screen by then: the canvas is that one's.\n let destination = -1\n const onDestination = (kind: number) => {\n destination = kind\n if (kind === TREE_DEST_SCENE3D) gl?.show()\n if (kind === TREE_DEST_SCENE2D) scene2d?.show()\n }\n const onDropped = (kind: number) => {\n if (kind === destination) return\n if (kind === TREE_DEST_SCENE3D) gl?.hide()\n if (kind === TREE_DEST_SCENE2D) scene2d?.hide()\n }\n\n // ---- the tables ---------------------------------------------------------------------------------\n const canvasHost = createCanvasHost() // the painter behind `_creatorCanvas`; the runtime's core makes the draw lists\n // What the window loses to the on-screen keyboard (a phone; a desktop loses nothing).\n const keyboardHeight = () => {\n const viewport = win.visualViewport\n return viewport ? Math.max(0, Math.round((win.innerHeight - viewport.height - viewport.offsetTop) / viewScale(root))) : 0\n }\n const renderer: CanvasRenderer | null = uiCanvas ? createCanvasRenderer(root, { M, canvas: uiCanvas, canvasHost, keyboardHeight }) : null\n if (renderer) {\n renderer.ui.onDestination = onDestination\n renderer.ui.onDropped = onDropped\n }\n const app = createAppTable({\n onOrientation: options.onOrientation,\n push: (event, data) => {\n // A \"url\" event sets the pull value first, so app.launchUrl agrees with the event.\n if (event === \"url\" && data !== undefined) withStr(data, (p) => M._creatorWebSetLaunchUrl(p))\n withStr(event, (e) => { if (data === undefined) M._creatorWebAppEvent(e, 0); else withStr(data, (d) => M._creatorWebAppEvent(e, d)) })\n },\n })\n const socket = createSocketTable()\n const service = createServiceTable()\n const input = createInputTable({\n windows: [...new Set([win as Window, ...(options.keyboardTargets ?? [])])],\n root, keyboard: options.keyboard !== false,\n push: (kind, code, gamepad, repeat) => withStr(code, (c) => M._creatorWebInputEvent(kind, c, gamepad, repeat)),\n keyboardHeight: () => renderer?.ui.keyboardHeight() ?? 0,\n })\n const tables: WasmHostTables = {\n ui: renderer?.ui ?? nullHostUI(onDestination, onDropped),\n app: app.table,\n device: createDeviceTable(options.language ?? (() => (win.navigator.language || \"en\").slice(0, 2))),\n fetch: createFetchTable(system),\n storage: createStorageTable(options.project ?? header?.name ?? \"app\"),\n socket: socket.table, service: service.table, input: input.table, media: mediaTable, canvas: canvasHost.table,\n ...(gl ? { gl: gl.table(M) } : {}),\n ...(scene2d ? { scene2d: scene2d.table(M) } : {}),\n }\n const world = makeWorld()\n const globals = world.global as Record<string, unknown>\n installJsb(M, { host: tables as unknown as Record<string, unknown>, world, newWorld: makeWorld })\n\n const plugins = createPlugins({\n // a native view is the renderer's to mount: an engine-only host has none\n ...(renderer ? { registerView: (name, factory, version) => renderer.ui.registerView(name, factory, version), unregisterView: (name) => renderer.ui.unregisterView(name) } : {}),\n registerService: service.registerService, unregisterService: service.unregisterService,\n })\n\n M._creatorWebInit()\n if (options.launchUrl) withStr(options.launchUrl, (p) => M._creatorWebSetLaunchUrl(p))\n renderer?.ui.install()\n // The engine up front (the desktop host's initial.js does the same): every `_creator` call needs\n // it. A `// gl: defer` bundle calls createEngine() itself.\n if (has3d && header?.gl !== \"defer\") (globals._creator as typeof _creator | undefined)?.createEngine()\n\n // ---- the size -----------------------------------------------------------------------------------\n const safeArea = createSafeArea(root)\n if (options.safeArea) safeArea.set(options.safeArea)\n const resize = (size: PageSize) => {\n gl?.resize()\n scene2d?.resize()\n if (renderer) {\n renderer.resize(size.width, size.height, size.factor)\n renderer.setSafeArea(safeArea.current()) // after: it re-flows against the new size\n } else M._creatorWebResize(size.width, size.height)\n }\n page.onResize(resize)\n resize(page.size())\n\n // ---- the frame ----------------------------------------------------------------------------------\n let raf = 0\n const frame = (now: number) => {\n raf = win.requestAnimationFrame(frame)\n gl?.frame()\n M._creatorWebTick(now) // timers, loops, tweens, the dispatch queue, the 3D frame\n scene2d?.frame(now)\n if (renderer) { renderer.ui.layoutFrame(); renderer.ui.tickHover(); renderer.render() }\n }\n raf = win.requestAnimationFrame(frame)\n\n await fonts\n\n let destroyed = false\n return {\n profile,\n /** The runtime module (an embedder that reads the engine directly: an editor). */\n M,\n /** The runtime's world: the bundle's globals (`_creator`, `_creatorTree`, `_creatorApp`, …). */\n world: globals,\n /** The UI as the renderer holds it (the render tree, the pointer routing); null on an engine-only host. */\n ui: renderer?.ui ?? null,\n /** Evaluate a bundle. Throws when the bundle is of another SDK major than this host. */\n run(code: string, runOptions: RunOptions = {}): Run {\n const bundle = runOptions.header ?? parseBundleHeader(code)\n if (!bundleRunsOn(bundle.sdk, SDK_VERSION)) {\n throw new Error(`This app was built with LeCodes SDK ${bundle.sdk ?? \"older than 2.0\"}; this host runs SDK ${SDK_VERSION}. It needs a new build.`)\n }\n const run = errors.track(code, runOptions.onError)\n // BEFORE the bundle runs: `isSupported` is a synchronous truth.\n plugins.allow(bundle.plugins)\n withStr(code, (p) => M._creatorWebRun(p)) // a throw is logged by the runtime (`[ERROR] run …`) → errors.runtimeLine\n return { dispose: run.drop }\n },\n /** A plugin's web half, by the id an app lists it under. Registered once; a bundle gets the ones\n * its header names. */\n registerPlugin: (id: string, half: PluginHalf) => plugins.register(id, half),\n hasPlugin: plugins.has,\n /** Where a stack of the running bundle leads in its source (an inspector's creation sites). */\n locate: errors.locate,\n /** The insets the app is told now: the embedder's, or the page's own. */\n safeArea: () => safeArea.current(),\n /** The embedder's insets (it drew over the container), or null for the page's own. */\n setSafeArea(area: SafeArea | null) {\n safeArea.set(area)\n renderer?.setSafeArea(safeArea.current())\n },\n /** A warm link (\"url\") or a synthetic lifecycle event (\"pause\", \"resume\"). */\n emitAppEvent: app.emit,\n destroy() {\n if (destroyed) return\n destroyed = true\n win.cancelAnimationFrame(raf)\n errors.dispose()\n renderer?.destroy()\n input.dispose(); socket.dispose(); service.dispose(); app.dispose()\n removePlayers()\n safeArea.destroy()\n gl?.destroy()\n scene2d?.destroy()\n page.destroy()\n },\n }\n}\n","// lecodes-web-host: a compiled LeCodes bundle in the browser, in the container it is given.\n//\n// const host = await mount(root, code) // the header's profile, the bundle run\n// host.destroy()\n//\n// const host = await createHost(root, { header: parseBundleHeader(code) })\n// host.run(code, { onError }) // repeatably\n//\n// The page around the container is the embedder's — lecodes-web-player is the one this repo ships.\nimport { createHost, type HostOptions, type RunOptions } from \"./host\"\nimport { parseBundleHeader } from \"./header\"\n\nexport { createHost } from \"./host\"\nexport type { Host, HostOptions, Run, RunOptions } from \"./host\"\nexport { parseBundleHeader, profileOf } from \"./header\"\nexport type { BundleHeader, HostProfile } from \"./header\"\nexport type { HalfHost, PluginHalf } from \"./plugins\"\nexport type { SafeArea } from \"./safeArea\"\nexport type { MappedFrame, PreviewError } from \"./errors\"\n\n/** A host for this bundle, and the bundle run on it. */\nexport const mount = async (root: HTMLElement, code: string, options: Omit<HostOptions, \"header\" | \"profile\"> & RunOptions = {}) => {\n const host = await createHost(root, { ...options, header: parseBundleHeader(code) })\n try {\n host.run(code, { onError: options.onError })\n } catch (e) {\n host.destroy()\n throw e\n }\n return host\n}\n","// The entry of the PUBLISHED package (dist/index.js): the host, typed by its public contract\n// (./api.ts) and by nothing else. Here the implementation is held to the contract — an assignment\n// that stops compiling is a contract that was broken.\n//\n// Inside this repo a package is a folder: the player takes the host from ./index.ts, with the\n// types the sources have.\nimport * as host from \"./index\"\nimport type { CreateHost, Mount, ParseBundleHeader, ProfileOf } from \"./api\"\n\nexport type * from \"./api\"\n\nexport const createHost: CreateHost = host.createHost\nexport const mount: Mount = host.mount\nexport const parseBundleHeader: ParseBundleHeader = host.parseBundleHeader\nexport const profileOf: ProfileOf = host.profileOf\n"],"file":"index.js"}