@elurjs/universal 0.0.0-stage → 0.1.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.
Files changed (758) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +24 -0
  3. package/README.md +102 -2
  4. package/THIRD_PARTY_NOTICES.md +153 -0
  5. package/cli/.gitkeep +0 -0
  6. package/cli/build-spec.mjs +46 -0
  7. package/cli/build-ssg.mjs +145 -0
  8. package/cli/build-ssr.mjs +276 -0
  9. package/cli/check-divergences.mjs +135 -0
  10. package/cli/check-doc-sync.mjs +282 -0
  11. package/cli/commands.d.mts +8 -0
  12. package/cli/commands.mjs +124 -0
  13. package/cli/commit-present.py +157 -0
  14. package/cli/create-app.mjs +768 -0
  15. package/cli/debug.mjs +45 -0
  16. package/cli/dev.mjs +488 -0
  17. package/cli/doctor.mjs +197 -0
  18. package/cli/elur.mjs +394 -0
  19. package/cli/font-license.mjs +24 -0
  20. package/cli/gen-bundle.mjs +195 -0
  21. package/cli/gen-doc-data.mjs +274 -0
  22. package/cli/gen-es5.mjs +60 -0
  23. package/cli/gen-hbc.mjs +87 -0
  24. package/cli/gen-host-integration.mjs +386 -0
  25. package/cli/gen-i18n-corpus.mjs +47 -0
  26. package/cli/gen-manifest.mjs +95 -0
  27. package/cli/gen-qjsc.mjs +77 -0
  28. package/cli/gen-route-types.mjs +65 -0
  29. package/cli/gen-routes.mjs +129 -0
  30. package/cli/gen-signals.mjs +151 -0
  31. package/cli/gen-ssr-client.mjs +119 -0
  32. package/cli/gen-wire-codec.mjs +214 -0
  33. package/cli/gen-wire-corpus.mjs +318 -0
  34. package/cli/gen-worklet-src.mjs +200 -0
  35. package/cli/gen-zones.mjs +197 -0
  36. package/cli/hermes-pair.mjs +61 -0
  37. package/cli/inspect.mjs +55 -0
  38. package/cli/layout-oracle-web.mjs +213 -0
  39. package/cli/layout-oracle.mjs +80 -0
  40. package/cli/lib-vlq.mjs +84 -0
  41. package/cli/measure-engines.mjs +206 -0
  42. package/cli/measure-shared.mjs +143 -0
  43. package/cli/package-linux.mjs +440 -0
  44. package/cli/parity-align.mjs +66 -0
  45. package/cli/platform-plugin.ts +97 -0
  46. package/cli/plugin-manifest.mjs +573 -0
  47. package/cli/run-bench.mjs +291 -0
  48. package/cli/run-commit-present.sh +91 -0
  49. package/cli/run-device-ab-surface.sh +94 -0
  50. package/cli/run-device-ab.sh +107 -0
  51. package/cli/run-energy.sh +44 -0
  52. package/cli/run-parity.mjs +164 -0
  53. package/cli/run-semantics.mjs +111 -0
  54. package/cli/run-tck.mjs +243 -0
  55. package/cli/sdui.mjs +1211 -0
  56. package/cli/symbolicate.mjs +90 -0
  57. package/cli/tck-android.sh +21 -0
  58. package/cli/tck-events-android.mjs +101 -0
  59. package/cli/tck-linux-atspi.py +389 -0
  60. package/cli/tck-platform-linux.mjs +638 -0
  61. package/cli/tck-platform.mjs +510 -0
  62. package/cli/visual-parity.mjs +691 -0
  63. package/docs/AUDITORIA-STATE-OF-THE-ART-2026-11.md +981 -0
  64. package/docs/ESTADO.md +679 -0
  65. package/docs/IMPLEMENTACION-NATIVA-v5.md +507 -0
  66. package/docs/PENDIENTES.md +1306 -0
  67. package/docs/adr/0013-transiciones-navegacion.md +169 -0
  68. package/docs/adr/0014-list-renderitem-factory.md +41 -0
  69. package/docs/adr/0015-dl-header-versionado.md +57 -0
  70. package/docs/adr/0016-hermes-v1-runtime.md +78 -0
  71. package/docs/adr/0017-encoder-nativo-dl.md +62 -0
  72. package/docs/adr/0018-yoga-tree-nativo.md +78 -0
  73. package/docs/adr/0019-ssr-universal-hidratacion.md +245 -0
  74. package/docs/adr/0020-canvas-draw-list.md +65 -0
  75. package/docs/adr/0021-text-input-props.md +55 -0
  76. package/docs/adr/0022-deep-links.md +49 -0
  77. package/docs/adr/0023-animacion-declarativa.md +130 -0
  78. package/docs/adr/0024-estilos-reactivos-vocabulario.md +100 -0
  79. package/docs/adr/0025-worklets-contrato-runner.md +181 -0
  80. package/docs/adr/0026-threading-js-dedicado.md +94 -0
  81. package/docs/adr/0027-ui-array-children-y-scope-por-fila.md +58 -0
  82. package/docs/adr/0028-commit-por-frame-en-host-embebido.md +93 -0
  83. package/docs/adr/0029-render-commit-latest-wins-screenhost.md +62 -0
  84. package/docs/adr/0030-destruccion-recursiva-ids-monotonicos.md +79 -0
  85. package/docs/adr/0031-scopes-formales-pool-filas.md +76 -0
  86. package/docs/adr/0032-nav-commit-autoritativo.md +64 -0
  87. package/docs/adr/0033-lista-virtual-ventana.md +80 -0
  88. package/docs/adr/0034-attach-event-class-strict-styles.md +89 -0
  89. package/docs/adr/0035-pipeline-imagenes-acotado.md +133 -0
  90. package/docs/adr/0036-data-por-entry-spa.md +91 -0
  91. package/docs/adr/0037-ir-serializable-factories-por-id.md +73 -0
  92. package/docs/adr/0038-transform-keys-compositor.md +79 -0
  93. package/docs/adr/0039-destroy-postorder-scope-ownership.md +86 -0
  94. package/docs/adr/0040-outbound-barriers-overflow-ack.md +60 -0
  95. package/docs/adr/0041-diff-treap-ir-version-strict.md +65 -0
  96. package/docs/adr/0042-data-endpoint-seguridad-hasloader.md +67 -0
  97. package/docs/adr/0043-aplicador-dom-unico.md +70 -0
  98. package/docs/adr/0044-descriptor-runtime-explicito.md +80 -0
  99. package/docs/adr/0045-navstate-versionado-scroll-settle.md +72 -0
  100. package/docs/adr/0046-harness-build-fail-closed.md +99 -0
  101. package/docs/adr/0047-envelope-evento-normalizado.md +110 -0
  102. package/docs/adr/0048-sesion-embebida-estados.md +91 -0
  103. package/docs/adr/0049-strict-styles-valores-portables.md +78 -0
  104. package/docs/adr/0050-update-style-tipado-abi-v5.md +66 -0
  105. package/docs/adr/0051-plugin-sdk-comandos.md +65 -0
  106. package/docs/adr/0052-benchmarks-reproducibles.md +50 -0
  107. package/docs/adr/0053-fling-target-pool-estructural.md +105 -0
  108. package/docs/adr/0054-lista-nativa-render-policy.md +130 -0
  109. package/docs/adr/0055-cesm-core.md +143 -0
  110. package/docs/adr/0056-dos-ejes-superficie-vs-propietario-de-ventana.md +112 -0
  111. package/docs/adr/0057-reset-node-y-firma-de-reciclaje.md +95 -0
  112. package/docs/adr/0058-rollback-de-montaje.md +83 -0
  113. package/docs/adr/0059-traza-on-device-u01-y-scroll-unico-productor.md +89 -0
  114. package/docs/adr/0060-list-update-patch-por-campo.md +73 -0
  115. package/docs/adr/0061-elegibilidad-de-plantilla-nativa.md +70 -0
  116. package/docs/adr/0062-invalidacion-adapter-lista-nativa.md +77 -0
  117. package/docs/adr/0063-autoridad-eventos-y-scroll.md +66 -0
  118. package/docs/adr/0064-admision-unica-de-commits.md +66 -0
  119. package/docs/adr/0065-runtime-de-sesion-u11.md +97 -0
  120. package/docs/adr/0066-perfil-layout-y-safe-area.md +78 -0
  121. package/docs/adr/0067-sesion-robusta-y-procedencia-de-build.md +121 -0
  122. package/docs/adr/0068-metodologia-de-benchmark-y-carril-verificable.md +94 -0
  123. package/docs/adr/0069-schema-de-wire-y-corpus-comun-de-codecs.md +126 -0
  124. package/docs/adr/0070-modelo-publico-de-aplicacion-y-mount.md +91 -0
  125. package/docs/adr/0071-image-service-y-tck-de-plataforma.md +133 -0
  126. package/docs/adr/0072-par-compilador-runtime-hermes.md +62 -0
  127. package/docs/adr/0073-corpus-de-semantica-y-lowering-por-motor.md +67 -0
  128. package/docs/adr/0074-perfil-i18n-formateo-dom-free.md +85 -0
  129. package/docs/adr/0075-back-predictivo-restore-y-layout-adaptativo.md +126 -0
  130. package/docs/adr/0076-contrato-de-modulos-capa-1.md +159 -0
  131. package/docs/adr/0077-manifest-de-plugin-y-plugin-sync.md +109 -0
  132. package/docs/adr/0078-extraccion-de-i18n-a-paquete-propio.md +114 -0
  133. package/docs/adr/0079-handles-de-host-objects-por-epoch.md +96 -0
  134. package/docs/adr/0080-platform-views-por-contrato.md +93 -0
  135. package/docs/adr/0081-codegen-del-dsl-de-modulos.md +118 -0
  136. package/docs/adr/0082-variante-web-de-modulos-nativos.md +126 -0
  137. package/docs/adr/0083-perfiles-dev-release.md +92 -0
  138. package/docs/adr/0084-instrumentacion-acotada-exportable.md +126 -0
  139. package/docs/adr/0085-medicion-agrupada-en-main.md +125 -0
  140. package/docs/adr/0086-matriz-capacidades-props-eventos.md +75 -0
  141. package/docs/adr/0087-uithread-runner-android.md +271 -0
  142. package/docs/adr/0088-worklet-src-estatico.md +82 -0
  143. package/docs/adr/0089-composicion-animaciones-settle-drag.md +122 -0
  144. package/docs/adr/0090-linter-capturas-build.md +94 -0
  145. package/docs/adr/0091-router-core-vs-universal.md +74 -0
  146. package/docs/adr/0092-sharedregion-type-strings.md +59 -0
  147. package/docs/adr/0093-permission-request-estandar.md +52 -0
  148. package/docs/adr/0094-dispatch-worker-timeoutms.md +51 -0
  149. package/docs/adr/0095-tck-modulos.md +65 -0
  150. package/docs/adr/0096-cesm-ring-deferral.md +47 -0
  151. package/docs/adr/0097-tooling-diferido.md +51 -0
  152. package/docs/adr/0098-handshake-moduleabi.md +46 -0
  153. package/docs/adr/0099-modulos-ambient.md +58 -0
  154. package/docs/adr/0100-auto-declaracion-modulos.md +43 -0
  155. package/docs/adr/0101-plataforma-build.md +49 -0
  156. package/docs/adr/0102-permisos-manifest-build.md +38 -0
  157. package/docs/adr/0103-registrant-ownership.md +45 -0
  158. package/docs/adr/0104-toolchain-release.md +125 -0
  159. package/docs/adr/0105-cesm-ring-mode.md +71 -0
  160. package/docs/adr/0106-module-observabilidad.md +100 -0
  161. package/docs/adr/0107-layout-l1-oraculo.md +67 -0
  162. package/docs/adr/0108-semantica-como-ops.md +69 -0
  163. package/docs/adr/0109-text-input-composition.md +64 -0
  164. package/docs/adr/0110-yoga-3-2.md +63 -0
  165. package/docs/adr/0111-hot-reload-con-estado.md +92 -0
  166. package/docs/adr/0112-metricas-nativas-reales.md +65 -0
  167. package/docs/adr/0113-cesm-proyeccion-ampliada.md +80 -0
  168. package/docs/adr/0114-androidx-deps.md +72 -0
  169. package/docs/adr/0115-coil-imagenes.md +57 -0
  170. package/docs/adr/0116-precomputed-text-off-ui.md +49 -0
  171. package/docs/adr/0117-a11y-state-hint-foco.md +54 -0
  172. package/docs/adr/0118-yoga-3-2-vocabulario.md +98 -0
  173. package/docs/adr/0119-codecs-wire-desde-esquema.md +86 -0
  174. package/docs/adr/0120-unidades-logicas-pointscalefactor.md +73 -0
  175. package/docs/adr/0121-yoga-filas-lista.md +100 -0
  176. package/docs/adr/0122-delegado-layout-subarbol.md +140 -0
  177. package/docs/adr/0123-canvas-sobre-skia-raster.md +101 -0
  178. package/docs/adr/0124-evaluacion-taffy-css-grid.md +52 -0
  179. package/docs/adr/0125-paridad-visual-android.md +89 -0
  180. package/docs/adr/0126-documento-web-metadata-enlaces.md +52 -0
  181. package/docs/adr/0127-perfil-l1-shorthand-flex-herencia-texto.md +70 -0
  182. package/docs/adr/0128-pantalla-llena-fragmentos-transparentes.md +56 -0
  183. package/docs/adr/0129-content-visibility-canvas-unidades-logicas.md +37 -0
  184. package/docs/adr/0130-expresiones-reactivas-ui.md +55 -0
  185. package/docs/adr/0131-state-style.md +59 -0
  186. package/docs/adr/0132-create-theme-system-color-scheme.md +58 -0
  187. package/docs/adr/0133-navegacion-rutas-href-chrome.md +59 -0
  188. package/docs/adr/0134-servicios-ambient-modulos-timers.md +63 -0
  189. package/docs/adr/0135-registro-fuentes.md +67 -0
  190. package/docs/adr/0136-i18n-zonas-dst-locale-reactivo.md +70 -0
  191. package/docs/adr/0137-ssg-universal.md +78 -0
  192. package/docs/adr/0138-plantillas-fila-ui-rowref.md +54 -0
  193. package/docs/adr/0139-paridad-geometrica-e-inspector.md +63 -0
  194. package/docs/adr/0140-medida-line-height-css.md +78 -0
  195. package/docs/adr/0141-build-ssr-autocontenido.md +37 -0
  196. package/docs/adr/0142-tema-ssr-cookie-client-hint.md +42 -0
  197. package/docs/adr/0143-paridad-visual-ci.md +51 -0
  198. package/docs/adr/0144-oraculo-layout-chromium.md +45 -0
  199. package/docs/adr/0145-admision-opcodes-wire.md +89 -0
  200. package/docs/adr/0146-presupuesto-divergencias.md +82 -0
  201. package/docs/adr/0147-spans-texto-enriquecido.md +113 -0
  202. package/docs/adr/0148-scroll-restore.md +92 -0
  203. package/docs/adr/0149-gestion-foco.md +94 -0
  204. package/docs/adr/0150-sticky.md +89 -0
  205. package/docs/adr/0151-politica-migracion-snapshots.md +83 -0
  206. package/docs/adr/0152-vocabulario-semantico-v3.md +112 -0
  207. package/docs/adr/0153-puerta-doc-codigo.md +59 -0
  208. package/docs/adr/0154-matriz-paridad.md +79 -0
  209. package/docs/adr/0155-rtl-ambiente.md +73 -0
  210. package/docs/adr/0156-quickjs-ng-0170.md +55 -0
  211. package/docs/adr/0157-qjsc-bytecode-android.md +73 -0
  212. package/docs/adr/0158-abi-host-explicita.md +62 -0
  213. package/docs/adr/0159-entrada-desktop.md +59 -0
  214. package/docs/adr/0160-port-linux-hallazgos-plataforma.md +91 -0
  215. package/docs/adr/0161-paridad-deeplink-alineacion-estructural.md +76 -0
  216. package/docs/adr/0162-fontscale-linux-fuentes.md +63 -0
  217. package/docs/adr/0163-overflow-hidden-linux-clip.md +67 -0
  218. package/docs/adr/0164-nav-transitions-linux.md +126 -0
  219. package/docs/adr/0165-transiciones-declarativas.md +147 -0
  220. package/docs/adr/0166-ime-composition-linux.md +68 -0
  221. package/docs/adr/0167-spans-pango-linux.md +80 -0
  222. package/docs/adr/0168-statestyle-linux.md +65 -0
  223. package/docs/adr/0169-animate-linux.md +114 -0
  224. package/docs/adr/0170-image-service-linux.md +54 -0
  225. package/docs/adr/0171-semantics-atspi-linux.md +80 -0
  226. package/docs/adr/0172-conformidad-de-host-por-terceros.md +159 -0
  227. package/docs/adr/0173-licencias-espec-y-codigo.md +95 -0
  228. package/docs/adr/0174-tabla-estilo-yoga-compartida.md +67 -0
  229. package/docs/adr/0175-easings-normativos-cubic-bezier.md +68 -0
  230. package/docs/adr/0176-harness-plataforma-linux-y-locale-decimal.md +80 -0
  231. package/docs/adr/0177-gaps-linux-dir-as-navstate.md +84 -0
  232. package/docs/adr/0178-matriz-linux-y-tablas-normativas-generadas.md +104 -0
  233. package/docs/adr/0179-eventos-gesto-y-teclado.md +132 -0
  234. package/docs/adr/0180-desktop-nativo-linux-windows-macos-chromeos.md +58 -0
  235. package/docs/adr/0181-linux-platform-views-uiworklet-y-gaps-certificados.md +101 -0
  236. package/docs/adr/0182-sdui-envelope-dialecto-rico-y-lowering.md +452 -0
  237. package/docs/adr/0183-hermes-es6-block-scoping-en-source-eval.md +99 -0
  238. package/docs/adr/0184-sdui-consumidor-de-referencia-y-modulo-http.md +72 -0
  239. package/docs/adr/0185-sdui-modelo-de-seguridad-del-envelope.md +160 -0
  240. package/docs/adr/0186-linux-packaging-deb-rpm-flatpak.md +61 -0
  241. package/docs/adr/0187-modelo-de-hilos-ejecutores-logicos.md +163 -0
  242. package/docs/adr/0188-sdui-seguridad-hardening.md +214 -0
  243. package/docs/adr/0189-worklets-web-worker-y-egreso-pinning.md +235 -0
  244. package/docs/adr/0190-semantics-actions-linux-via-gaction-muxer.md +102 -0
  245. package/docs/adr/0191-reporte-de-errores-en-produccion.md +126 -0
  246. package/docs/adr/0192-source-maps-y-simbolizacion-de-stacks.md +107 -0
  247. package/docs/adr/0193-renderer-skia-opt-in-en-linux.md +143 -0
  248. package/docs/adr/0194-superficie-declarada-y-carril-skia-tree.md +96 -0
  249. package/docs/adr/0195-bundles-embebidos-subpaths-core.md +66 -0
  250. package/docs/adr/0196-matriz-capacidades-verdad.md +84 -0
  251. package/docs/adr/0197-entorno-reactivo-cableado.md +67 -0
  252. package/docs/adr/0198-csprng-host-wintertc.md +57 -0
  253. package/docs/adr/0199-testing-harness-dom-free.md +59 -0
  254. package/docs/adr/0200-overlays-back-foco.md +84 -0
  255. package/docs/adr/0201-paridad-nativa-props-texto-fase1.md +79 -0
  256. package/docs/adr/0202-node-ref-measure-web.md +61 -0
  257. package/docs/adr/0203-primitivas-headless.md +54 -0
  258. package/docs/adr/0204-imagen-load-error-fallback.md +123 -0
  259. package/docs/adr/0205-primitivas-controls-fase2.md +79 -0
  260. package/docs/adr/0206-a2ui-catalogo-tabs-modal-choicepicker-icon.md +110 -0
  261. package/docs/adr/0207-a2ui-superficie-viva.md +104 -0
  262. package/docs/adr/0208-a2ui-checks-validacion.md +94 -0
  263. package/docs/adr/0209-loaddata-nativo-default.md +56 -0
  264. package/docs/adr/0210-primitivas-navegacion-fase3.md +69 -0
  265. package/docs/adr/0211-a2ui-formato-localizado.md +113 -0
  266. package/docs/adr/0212-red-fuera-del-core.md +67 -0
  267. package/docs/adr/0213-dev-fast-y-rutas-automaticas.md +68 -0
  268. package/docs/adr/0214-dev-web-server-reload.md +55 -0
  269. package/docs/adr/0215-ui-host-noderef-back-http-linux.md +77 -0
  270. package/docs/adr/0216-paridad-nativa-switch-scroll-lista.md +53 -0
  271. package/docs/adr/0217-overlays-drag-y-popover-anclado.md +64 -0
  272. package/docs/adr/0218-sdui-gateway-live-mcp-y-scaffold.md +31 -0
  273. package/docs/adr/0219-event-ref-envelope-y-oracle-scroll-aware.md +82 -0
  274. package/docs/adr/README.md +229 -0
  275. package/docs/deuda/i18n-libreria-separada.md +50 -0
  276. package/docs/doc-data.json +2788 -0
  277. package/docs/propuestas/demo-google-devfest-a2ui-sdui.md +374 -0
  278. package/docs/propuestas/dx-y-paridad.md +684 -0
  279. package/docs/propuestas/investigacion-apps-completas/PENDIENTES-CORE-APPS-COMPLETAS.md +226 -0
  280. package/docs/propuestas/investigacion-apps-completas/arquitectura-motor-videojuegos-elur.md +254 -0
  281. package/docs/propuestas/investigacion-apps-completas/auditoria-paridad-frameworks-y-sdui.md +295 -0
  282. package/docs/propuestas/investigacion-apps-completas/ciclo-de-vida-dx-y-apps-completas.md +394 -0
  283. package/docs/propuestas/investigacion-apps-completas/crear-proyecto-desde-npm-y-agentes.md +477 -0
  284. package/docs/propuestas/investigacion-apps-completas/especificacion-arquitectura-capacidades-faltantes.md +407 -0
  285. package/docs/propuestas/investigacion-apps-completas/identidad-y-nombre-elur-universal.md +133 -0
  286. package/docs/propuestas/investigacion-apps-completas/migracion-elur-core-4.md +266 -0
  287. package/docs/propuestas/investigacion-apps-completas/sdui-a2ui-aplicaciones-completas.md +255 -0
  288. package/docs/propuestas/investigacion-apps-completas/verificacion-mejoras-y-brechas-nuevas.md +228 -0
  289. package/docs/propuestas/modelo-de-consumo.md +287 -0
  290. package/docs/propuestas/modulos-nativos.md +1062 -0
  291. package/docs/propuestas/palabras-clave-normativas.md +69 -0
  292. package/docs/propuestas/sdui-seguridad-hardening.md +322 -0
  293. package/docs/propuestas/skia-graphite.md +167 -0
  294. package/docs/propuestas/skia-renderer-arbol.md +603 -0
  295. package/docs/propuestas/targets-nativos-nuevos.md +359 -0
  296. package/docs/propuestas/toolchain-y-distribucion.md +311 -0
  297. package/docs/propuestas/ui-worklet-capacidades-exclusivas.md +114 -0
  298. package/examples/a11ylive/elur.app.json +8 -0
  299. package/examples/a11ylive/entry.ts +22 -0
  300. package/examples/a11ysem/elur.app.json +8 -0
  301. package/examples/a11ysem/entry.ts +24 -0
  302. package/examples/anim/elur.app.json +8 -0
  303. package/examples/anim/entry.ts +50 -0
  304. package/examples/app.ts +10 -0
  305. package/examples/cliprad/elur.app.json +8 -0
  306. package/examples/cliprad/entry.ts +16 -0
  307. package/examples/controls/app.ts +32 -0
  308. package/examples/controls/elur.app.json +8 -0
  309. package/examples/counter/app.ts +21 -0
  310. package/examples/counter/elur.app.json +8 -0
  311. package/examples/counter/entry.ts +7 -0
  312. package/examples/entry.ts +11 -0
  313. package/examples/feedstress/app.ts +334 -0
  314. package/examples/feedstress/elur.app.json +8 -0
  315. package/examples/feedstress/entry.ts +7 -0
  316. package/examples/i18n/app.ts +86 -0
  317. package/examples/i18n/elur.app.json +8 -0
  318. package/examples/i18n/entry.ts +22 -0
  319. package/examples/imecomp/elur.app.json +8 -0
  320. package/examples/imecomp/entry.ts +41 -0
  321. package/examples/imgtest/elur.app.json +8 -0
  322. package/examples/imgtest/entry.ts +18 -0
  323. package/examples/mareas/app/ajustes/page.ts +54 -0
  324. package/examples/mareas/app/page.ts +91 -0
  325. package/examples/mareas/app/puerto/[id]/page.ts +106 -0
  326. package/examples/mareas/app.ts +12 -0
  327. package/examples/mareas/elur.app.json +35 -0
  328. package/examples/mareas/entry.ts +11 -0
  329. package/examples/mareas/fonts/DejaVuSansMono-Bold.ttf +0 -0
  330. package/examples/mareas/fonts/DejaVuSansMono.ttf +0 -0
  331. package/examples/mareas/fonts/DejaVuSerif-Bold.ttf +0 -0
  332. package/examples/mareas/fonts/DejaVuSerif-Italic.ttf +0 -0
  333. package/examples/mareas/fonts/DejaVuSerif.ttf +0 -0
  334. package/examples/mareas/fonts/LICENSE-DejaVu.txt +187 -0
  335. package/examples/mareas/fonts.ts +6 -0
  336. package/examples/mareas/head.ts +12 -0
  337. package/examples/mareas/i18n.ts +163 -0
  338. package/examples/mareas/ports.ts +131 -0
  339. package/examples/mareas/routes.gen.ts +44 -0
  340. package/examples/mareas/serve.ts +70 -0
  341. package/examples/mareas/services.ts +5 -0
  342. package/examples/mareas/services.web.ts +6 -0
  343. package/examples/mareas/state.ts +64 -0
  344. package/examples/mareas/theme.ts +56 -0
  345. package/examples/mareas/ui/controls.ts +42 -0
  346. package/examples/mareas/ui/frame.ts +63 -0
  347. package/examples/mareas/ui/marigram.ts +52 -0
  348. package/examples/masonry/app.ts +32 -0
  349. package/examples/masonry/elur.app.json +8 -0
  350. package/examples/masonry/entry.ts +4 -0
  351. package/examples/natprobe/elur.app.json +8 -0
  352. package/examples/natprobe/entry.ts +196 -0
  353. package/examples/navdemo/app.ts +109 -0
  354. package/examples/navdemo/elur.app.json +8 -0
  355. package/examples/navdemo/entry.ts +7 -0
  356. package/examples/navtrans/elur.app.json +8 -0
  357. package/examples/navtrans/entry.ts +53 -0
  358. package/examples/platformview/app.ts +26 -0
  359. package/examples/platformview/elur.app.json +8 -0
  360. package/examples/sdui-demo/docs/home.envelope.json +588 -0
  361. package/examples/sdui-demo/docs/home.iife.json +582 -0
  362. package/examples/sdui-demo/elur.app.json +8 -0
  363. package/examples/sdui-demo/entry.ts +346 -0
  364. package/examples/select/elur.app.json +8 -0
  365. package/examples/select/entry.ts +20 -0
  366. package/examples/skiacanvas/app.ts +34 -0
  367. package/examples/skiacanvas/elur.app.json +8 -0
  368. package/examples/skiacanvas/entry.ts +4 -0
  369. package/examples/spans/elur.app.json +8 -0
  370. package/examples/spans/entry.ts +28 -0
  371. package/examples/ssr/app/about/page.ts +18 -0
  372. package/examples/ssr/app/items/[id]/page.ts +16 -0
  373. package/examples/ssr/app/layout.ts +21 -0
  374. package/examples/ssr/app/page.action.ts +10 -0
  375. package/examples/ssr/app/page.data.ts +5 -0
  376. package/examples/ssr/app/page.ts +95 -0
  377. package/examples/ssr/app/slow/loading.ts +10 -0
  378. package/examples/ssr/app/slow/page.data.ts +4 -0
  379. package/examples/ssr/app/slow/page.ts +16 -0
  380. package/examples/ssr/app/store.ts +3 -0
  381. package/examples/ssr/serve.ts +53 -0
  382. package/examples/statestyle/elur.app.json +8 -0
  383. package/examples/statestyle/entry.ts +25 -0
  384. package/examples/swipe/elur.app.json +8 -0
  385. package/examples/swipe/entry.ts +39 -0
  386. package/examples/tasks/app.ts +145 -0
  387. package/examples/tasks/elur.app.json +8 -0
  388. package/examples/uiwk/app.ts +288 -0
  389. package/examples/uiwk/elur.app.json +8 -0
  390. package/examples/uiwk/entry.ts +7 -0
  391. package/examples/vertical/app.ts +275 -0
  392. package/examples/vertical/elur.app.json +8 -0
  393. package/examples/vertical/entry.ts +31 -0
  394. package/examples/yogafeatures/app.ts +55 -0
  395. package/examples/yogafeatures/elur.app.json +8 -0
  396. package/examples/yogafeatures/entry.ts +4 -0
  397. package/native/cesm/README.md +94 -0
  398. package/native/cesm/adapters/hermes/HermesAdapter.h +432 -0
  399. package/native/cesm/adapters/quickjs/QuickJsAdapter.h +562 -0
  400. package/native/cesm/core/Bytes.h +236 -0
  401. package/native/cesm/core/Core.h +157 -0
  402. package/native/cesm/core/EngineAdapter.h +20 -0
  403. package/native/cesm/core/Region.h +77 -0
  404. package/native/cesm/core/Ring.h +99 -0
  405. package/native/cesm/core/Slots.h +132 -0
  406. package/native/cesm/core/Types.h +67 -0
  407. package/native/cesm/tests/CMakeLists.txt +50 -0
  408. package/native/cesm/tests/README.md +89 -0
  409. package/native/cesm/tests/compile_check_hermes.cpp +23 -0
  410. package/native/cesm/tests/test_core.cpp +101 -0
  411. package/native/cesm/tests/test_main.cpp +13 -0
  412. package/native/cesm/tests/test_quickjs_adapter.cpp +252 -0
  413. package/native/cesm/tests/test_ring.cpp +131 -0
  414. package/native/cesm/tests/test_slots.cpp +81 -0
  415. package/native/cesm/tests/test_sync.cpp +157 -0
  416. package/native/cesm/tests/test_util.h +24 -0
  417. package/native/layout/elur_layout_style.cpp +297 -0
  418. package/native/layout/elur_layout_style.h +36 -0
  419. package/native/layout-oracle/CMakeLists.txt +22 -0
  420. package/native/layout-oracle/oracle.cpp +140 -0
  421. package/native/rand/elur_random.h +43 -0
  422. package/native/skia-tree/elur_skia_tree.cpp +1293 -0
  423. package/native/skia-tree/elur_skia_tree.h +231 -0
  424. package/native/yoga/LICENSE +21 -0
  425. package/native/yoga/YGConfig.cpp +92 -0
  426. package/native/yoga/YGConfig.h +158 -0
  427. package/native/yoga/YGEnums.cpp +262 -0
  428. package/native/yoga/YGEnums.h +142 -0
  429. package/native/yoga/YGMacros.h +99 -0
  430. package/native/yoga/YGNode.cpp +366 -0
  431. package/native/yoga/YGNode.h +304 -0
  432. package/native/yoga/YGNodeLayout.cpp +92 -0
  433. package/native/yoga/YGNodeLayout.h +35 -0
  434. package/native/yoga/YGNodeStyle.cpp +405 -0
  435. package/native/yoga/YGNodeStyle.h +130 -0
  436. package/native/yoga/YGPixelGrid.cpp +22 -0
  437. package/native/yoga/YGPixelGrid.h +29 -0
  438. package/native/yoga/YGValue.cpp +20 -0
  439. package/native/yoga/YGValue.h +84 -0
  440. package/native/yoga/Yoga.h +21 -0
  441. package/native/yoga/algorithm/AbsoluteLayout.cpp +563 -0
  442. package/native/yoga/algorithm/AbsoluteLayout.h +41 -0
  443. package/native/yoga/algorithm/Align.h +72 -0
  444. package/native/yoga/algorithm/Baseline.cpp +78 -0
  445. package/native/yoga/algorithm/Baseline.h +21 -0
  446. package/native/yoga/algorithm/BoundAxis.h +79 -0
  447. package/native/yoga/algorithm/Cache.cpp +121 -0
  448. package/native/yoga/algorithm/Cache.h +30 -0
  449. package/native/yoga/algorithm/CalculateLayout.cpp +2428 -0
  450. package/native/yoga/algorithm/CalculateLayout.h +38 -0
  451. package/native/yoga/algorithm/FlexDirection.h +120 -0
  452. package/native/yoga/algorithm/FlexLine.cpp +124 -0
  453. package/native/yoga/algorithm/FlexLine.h +75 -0
  454. package/native/yoga/algorithm/PixelGrid.cpp +132 -0
  455. package/native/yoga/algorithm/PixelGrid.h +29 -0
  456. package/native/yoga/algorithm/SizingMode.h +73 -0
  457. package/native/yoga/algorithm/TrailingPosition.h +44 -0
  458. package/native/yoga/config/Config.cpp +135 -0
  459. package/native/yoga/config/Config.h +92 -0
  460. package/native/yoga/debug/AssertFatal.cpp +53 -0
  461. package/native/yoga/debug/AssertFatal.h +29 -0
  462. package/native/yoga/debug/Log.cpp +107 -0
  463. package/native/yoga/debug/Log.h +34 -0
  464. package/native/yoga/enums/Align.h +47 -0
  465. package/native/yoga/enums/BoxSizing.h +40 -0
  466. package/native/yoga/enums/Dimension.h +40 -0
  467. package/native/yoga/enums/Direction.h +41 -0
  468. package/native/yoga/enums/Display.h +41 -0
  469. package/native/yoga/enums/Edge.h +47 -0
  470. package/native/yoga/enums/Errata.h +41 -0
  471. package/native/yoga/enums/ExperimentalFeature.h +39 -0
  472. package/native/yoga/enums/FlexDirection.h +42 -0
  473. package/native/yoga/enums/Gutter.h +41 -0
  474. package/native/yoga/enums/Justify.h +44 -0
  475. package/native/yoga/enums/LogLevel.h +44 -0
  476. package/native/yoga/enums/MeasureMode.h +41 -0
  477. package/native/yoga/enums/NodeType.h +40 -0
  478. package/native/yoga/enums/Overflow.h +41 -0
  479. package/native/yoga/enums/PhysicalEdge.h +21 -0
  480. package/native/yoga/enums/PositionType.h +41 -0
  481. package/native/yoga/enums/Unit.h +42 -0
  482. package/native/yoga/enums/Wrap.h +41 -0
  483. package/native/yoga/enums/YogaEnums.h +85 -0
  484. package/native/yoga/event/event.cpp +87 -0
  485. package/native/yoga/event/event.h +130 -0
  486. package/native/yoga/node/CachedMeasurement.h +53 -0
  487. package/native/yoga/node/LayoutResults.cpp +48 -0
  488. package/native/yoga/node/LayoutResults.h +122 -0
  489. package/native/yoga/node/LayoutableChildren.h +148 -0
  490. package/native/yoga/node/Node.cpp +443 -0
  491. package/native/yoga/node/Node.h +337 -0
  492. package/native/yoga/numeric/Comparison.h +81 -0
  493. package/native/yoga/numeric/FloatOptional.h +93 -0
  494. package/native/yoga/style/SmallValueBuffer.h +133 -0
  495. package/native/yoga/style/Style.h +757 -0
  496. package/native/yoga/style/StyleLength.h +107 -0
  497. package/native/yoga/style/StyleValueHandle.h +98 -0
  498. package/native/yoga/style/StyleValuePool.h +127 -0
  499. package/package.json +112 -3
  500. package/src/adapters/kit-bridge.ts +72 -0
  501. package/src/adapters/kit-ssg.ts +219 -0
  502. package/src/adapters/kit-ssr.ts +577 -0
  503. package/src/adapters/kit-types.ts +28 -0
  504. package/src/adapters/request-adapter.ts +41 -0
  505. package/src/adapters/ssr-resolver.ts +177 -0
  506. package/src/adapters/web-history.ts +218 -0
  507. package/src/adapters/web-nav-executor.ts +72 -0
  508. package/src/animations/.gitkeep +0 -0
  509. package/src/animations/bindWorklets.ts +49 -0
  510. package/src/animations/captureCheck.ts +75 -0
  511. package/src/animations/compose.ts +127 -0
  512. package/src/animations/easing.ts +75 -0
  513. package/src/animations/gestureWorklets.ts +129 -0
  514. package/src/animations/index.ts +23 -0
  515. package/src/animations/runner.ts +404 -0
  516. package/src/animations/scrollWorklets.ts +48 -0
  517. package/src/animations/uiBindings.ts +83 -0
  518. package/src/animations/uiRunner.ts +449 -0
  519. package/src/animations/worklet.ts +157 -0
  520. package/src/animations/workletForm.ts +197 -0
  521. package/src/app/clock.ts +69 -0
  522. package/src/app/embedded.ts +232 -0
  523. package/src/app/index.ts +24 -0
  524. package/src/app/load-data.ts +36 -0
  525. package/src/app/mount.native.ts +18 -0
  526. package/src/app/mount.ts +26 -0
  527. package/src/app/mount.web.ts +21 -0
  528. package/src/app/state.ts +256 -0
  529. package/src/app/types.ts +146 -0
  530. package/src/app/web.ts +291 -0
  531. package/src/backends/native/hostAbi.ts +304 -0
  532. package/src/backends/native/index.ts +1132 -0
  533. package/src/backends/textInputProtocol.ts +111 -0
  534. package/src/backends/web/.gitkeep +0 -0
  535. package/src/backends/web/base-css.ts +148 -0
  536. package/src/backends/web/batcher.ts +162 -0
  537. package/src/backends/web/hydrate.ts +227 -0
  538. package/src/backends/web/index.ts +2231 -0
  539. package/src/backends/web/inspect.ts +80 -0
  540. package/src/backends/web/workerRunner.ts +513 -0
  541. package/src/context/index.ts +19 -0
  542. package/src/events.ts +139 -0
  543. package/src/forms/index.ts +264 -0
  544. package/src/hydration/.gitkeep +0 -0
  545. package/src/index.ts +169 -0
  546. package/src/ir/.gitkeep +0 -0
  547. package/src/ir/catalog.ts +166 -0
  548. package/src/ir/events.ts +54 -0
  549. package/src/ir/schema.ts +1103 -0
  550. package/src/ir/semantics.ts +189 -0
  551. package/src/ir/shortcut.ts +104 -0
  552. package/src/ir/signal-names.ts +27 -0
  553. package/src/ir/ui.ts +709 -0
  554. package/src/layout/.gitkeep +0 -0
  555. package/src/native/.gitkeep +0 -0
  556. package/src/native/binaryCodec.ts +230 -0
  557. package/src/native/codegen.ts +635 -0
  558. package/src/native/hostArtifacts.ts +386 -0
  559. package/src/native/http.ts +558 -0
  560. package/src/native/index.ts +54 -0
  561. package/src/native/manifest.ts +227 -0
  562. package/src/native/module.ts +1108 -0
  563. package/src/native/platformView.ts +107 -0
  564. package/src/native/pluginManifest.ts +269 -0
  565. package/src/native/sharedMemory.ts +168 -0
  566. package/src/native/specType.ts +164 -0
  567. package/src/native/tck.ts +436 -0
  568. package/src/native/trace.ts +97 -0
  569. package/src/native/webModule.ts +281 -0
  570. package/src/overlays/index.ts +579 -0
  571. package/src/platform.ts +89 -0
  572. package/src/primitives/controls.ts +725 -0
  573. package/src/primitives/index.ts +400 -0
  574. package/src/primitives/navigation.ts +407 -0
  575. package/src/reconciler/reconciler.ts +2857 -0
  576. package/src/router/guards.ts +129 -0
  577. package/src/router/index.ts +41 -0
  578. package/src/router/lifecycle.ts +133 -0
  579. package/src/router/match.ts +184 -0
  580. package/src/router/router.ts +508 -0
  581. package/src/router/screen-host.ts +918 -0
  582. package/src/router/state.ts +76 -0
  583. package/src/router/table.ts +55 -0
  584. package/src/router/transitions.ts +87 -0
  585. package/src/router/types.ts +161 -0
  586. package/src/runtime/environment.ts +332 -0
  587. package/src/runtime/wintertc-globals.ts +1067 -0
  588. package/src/sdui/a2ui.ts +1480 -0
  589. package/src/sdui/a2uiSurface.ts +214 -0
  590. package/src/sdui/client.ts +370 -0
  591. package/src/sdui/cryptoModule.ts +107 -0
  592. package/src/sdui/diagnostics.ts +39 -0
  593. package/src/sdui/downlevel.ts +375 -0
  594. package/src/sdui/envelope.ts +729 -0
  595. package/src/sdui/expr.ts +658 -0
  596. package/src/sdui/gateway.ts +223 -0
  597. package/src/sdui/httpModule.ts +29 -0
  598. package/src/sdui/index.ts +74 -0
  599. package/src/sdui/intents.ts +217 -0
  600. package/src/sdui/lower.ts +576 -0
  601. package/src/sdui/machines.ts +141 -0
  602. package/src/sdui/manifest.ts +167 -0
  603. package/src/sdui/oracle.ts +400 -0
  604. package/src/sdui/profile.ts +72 -0
  605. package/src/sdui/seqStore.ts +89 -0
  606. package/src/sdui/sign.ts +155 -0
  607. package/src/sdui/worklets.ts +164 -0
  608. package/src/ssr/html-applicator.ts +515 -0
  609. package/src/ssr/render-page.ts +264 -0
  610. package/src/store/index.ts +28 -0
  611. package/src/style/textInherit.ts +29 -0
  612. package/src/style/theme.ts +178 -0
  613. package/src/testing/index.ts +276 -0
  614. package/src/transport/.gitkeep +0 -0
  615. package/src/transport/format.ts +477 -0
  616. package/src/transport/wireSchema.ts +189 -0
  617. package/src/web.ts +31 -0
  618. package/targets/android/app/build.gradle.kts +192 -0
  619. package/targets/android/app/proguard-rules-elur.pro +12 -0
  620. package/targets/android/app/proguard-rules.pro +3 -0
  621. package/targets/android/app/src/main/AndroidManifest.xml +81 -0
  622. package/targets/android/app/src/main/cpp/CMakeLists.txt +117 -0
  623. package/targets/android/app/src/main/cpp/dlEncoder.h +117 -0
  624. package/targets/android/app/src/main/cpp/dlEncoderJsi.cpp +315 -0
  625. package/targets/android/app/src/main/cpp/dlEncoderQjs.cpp +394 -0
  626. package/targets/android/app/src/main/cpp/dlOps.inc +145 -0
  627. package/targets/android/app/src/main/cpp/elurBridge.cpp +1350 -0
  628. package/targets/android/app/src/main/cpp/elurBridgeHermes.cpp +1294 -0
  629. package/targets/android/app/src/main/cpp/elurSkia.cpp +287 -0
  630. package/targets/android/app/src/main/cpp/elurSkiaTree.cpp +448 -0
  631. package/targets/android/app/src/main/cpp/elurUiWorklet.cpp +1233 -0
  632. package/targets/android/app/src/main/cpp/elurYoga.cpp +1060 -0
  633. package/targets/android/app/src/main/cpp/elurYoga.h +82 -0
  634. package/targets/android/app/src/main/cpp/hermes-libs/LICENSE +21 -0
  635. package/targets/android/app/src/main/cpp/hermes-libs/arm64-v8a/libhermesvm.so +0 -0
  636. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/AsyncDebuggerAPI.h +276 -0
  637. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/CompileJS.h +97 -0
  638. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/DebuggerAPI.h +502 -0
  639. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/CrashManager.h +107 -0
  640. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/CtorConfig.h +145 -0
  641. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/DebuggerTypes.h +193 -0
  642. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/GCConfig.h +211 -0
  643. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/GCTripwireContext.h +40 -0
  644. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/HermesExport.h +14 -0
  645. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/JSOutOfMemoryError.h +27 -0
  646. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/RuntimeConfig.h +141 -0
  647. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/Public/SamplingProfiler.h +270 -0
  648. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/RuntimeTaskRunner.h +64 -0
  649. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/SynthTrace.h +1566 -0
  650. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/SynthTraceParser.h +37 -0
  651. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/ThreadSafetyAnalysis.h +75 -0
  652. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/TimerStats.h +23 -0
  653. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/TraceInterpreter.h +334 -0
  654. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/TracingRuntime.h +328 -0
  655. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/CDPAgent.h +131 -0
  656. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/CDPDebugAPI.h +73 -0
  657. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/CallbackOStream.h +89 -0
  658. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/ConsoleMessage.h +135 -0
  659. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/DebuggerDomainAgent.h +280 -0
  660. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/DebuggerDomainCoordinator.h +137 -0
  661. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/DomainAgent.h +107 -0
  662. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/DomainState.h +140 -0
  663. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/HeapProfilerDomainAgent.h +71 -0
  664. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/JSONValueInterfaces.h +40 -0
  665. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageConverters.h +82 -0
  666. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageInterfaces.h +72 -0
  667. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageTypes.h +1279 -0
  668. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageTypesInlines.h +313 -0
  669. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/ProfilerDomainAgent.h +38 -0
  670. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/RemoteObjectConverters.h +77 -0
  671. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/RemoteObjectsTable.h +127 -0
  672. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/cdp/RuntimeDomainAgent.h +138 -0
  673. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/Dummy.h +24 -0
  674. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/Extensions.h +20 -0
  675. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/ExtensionsBytecode.h +23 -0
  676. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/Intrinsics.h +44 -0
  677. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/JSIUtils.h +123 -0
  678. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/TextEncoder.h +29 -0
  679. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/ContribDummy.h +24 -0
  680. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/ContribExtensions.h +23 -0
  681. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/TextDecoder.h +30 -0
  682. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/TextDecoderUtils.h +113 -0
  683. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/hermes.h +242 -0
  684. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes/hermes_tracing.h +52 -0
  685. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_abi/HermesABIHelpers.h +295 -0
  686. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_abi/HermesABIRuntimeWrapper.h +25 -0
  687. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_abi/hermes_abi.h +642 -0
  688. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_abi/hermes_vtable.h +29 -0
  689. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/HermesSandboxRuntime.h +41 -0
  690. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_compiled.h +12 -0
  691. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_dbg_compiled-impl.h +8516 -0
  692. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_dbg_compiled.h +137 -0
  693. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_opt_compiled-impl.h +3945 -0
  694. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_opt_compiled.h +119 -0
  695. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/wasm-rt-fb.h +124 -0
  696. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/wasm-rt-impl.h +66 -0
  697. package/targets/android/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/wasm-rt.h +456 -0
  698. package/targets/android/app/src/main/cpp/hermes-libs/include/jsi/JSIDynamic.h +26 -0
  699. package/targets/android/app/src/main/cpp/hermes-libs/include/jsi/decorator.h +1157 -0
  700. package/targets/android/app/src/main/cpp/hermes-libs/include/jsi/hermes-interfaces.h +242 -0
  701. package/targets/android/app/src/main/cpp/hermes-libs/include/jsi/instrumentation.h +132 -0
  702. package/targets/android/app/src/main/cpp/hermes-libs/include/jsi/jsi-inl.h +434 -0
  703. package/targets/android/app/src/main/cpp/hermes-libs/include/jsi/jsi.h +2266 -0
  704. package/targets/android/app/src/main/cpp/hermes-libs/include/jsi/jsilib.h +59 -0
  705. package/targets/android/app/src/main/cpp/hermes-libs/include/jsi/threadsafe.h +79 -0
  706. package/targets/android/app/src/main/cpp/hermes-libs/jsi-impl/jsi.cpp +1111 -0
  707. package/targets/android/app/src/main/cpp/hermes-libs/x86_64/libhermesvm.so +0 -0
  708. package/targets/android/app/src/main/java/com/elur/universal/BinaryCodec.kt +121 -0
  709. package/targets/android/app/src/main/java/com/elur/universal/DlDecoder.kt +260 -0
  710. package/targets/android/app/src/main/java/com/elur/universal/DlOpsDecode.kt +158 -0
  711. package/targets/android/app/src/main/java/com/elur/universal/ElurBoxDrawable.kt +161 -0
  712. package/targets/android/app/src/main/java/com/elur/universal/ElurBridge.kt +238 -0
  713. package/targets/android/app/src/main/java/com/elur/universal/ElurBridgeHermes.kt +223 -0
  714. package/targets/android/app/src/main/java/com/elur/universal/ElurCanvasView.kt +202 -0
  715. package/targets/android/app/src/main/java/com/elur/universal/ElurCryptoModule.kt +206 -0
  716. package/targets/android/app/src/main/java/com/elur/universal/ElurCustomLayout.kt +185 -0
  717. package/targets/android/app/src/main/java/com/elur/universal/ElurEditText.kt +17 -0
  718. package/targets/android/app/src/main/java/com/elur/universal/ElurFontRegistry.kt +190 -0
  719. package/targets/android/app/src/main/java/com/elur/universal/ElurHttpModule.kt +306 -0
  720. package/targets/android/app/src/main/java/com/elur/universal/ElurImageService.kt +348 -0
  721. package/targets/android/app/src/main/java/com/elur/universal/ElurLicensesActivity.kt +84 -0
  722. package/targets/android/app/src/main/java/com/elur/universal/ElurListView.kt +954 -0
  723. package/targets/android/app/src/main/java/com/elur/universal/ElurManifest.kt +117 -0
  724. package/targets/android/app/src/main/java/com/elur/universal/ElurMetrics.kt +325 -0
  725. package/targets/android/app/src/main/java/com/elur/universal/ElurModuleRegistrar.kt +14 -0
  726. package/targets/android/app/src/main/java/com/elur/universal/ElurPermissionGate.kt +36 -0
  727. package/targets/android/app/src/main/java/com/elur/universal/ElurRenderer.kt +6112 -0
  728. package/targets/android/app/src/main/java/com/elur/universal/ElurRowYoga.kt +130 -0
  729. package/targets/android/app/src/main/java/com/elur/universal/ElurScrollView.kt +240 -0
  730. package/targets/android/app/src/main/java/com/elur/universal/ElurShellView.kt +117 -0
  731. package/targets/android/app/src/main/java/com/elur/universal/ElurSkiaCanvasView.kt +162 -0
  732. package/targets/android/app/src/main/java/com/elur/universal/ElurSkiaTreeRenderer.kt +968 -0
  733. package/targets/android/app/src/main/java/com/elur/universal/ElurStateModule.kt +69 -0
  734. package/targets/android/app/src/main/java/com/elur/universal/ElurSwipeDriver.kt +34 -0
  735. package/targets/android/app/src/main/java/com/elur/universal/ElurTckModule.kt +99 -0
  736. package/targets/android/app/src/main/java/com/elur/universal/ElurTextMeasure.kt +16 -0
  737. package/targets/android/app/src/main/java/com/elur/universal/ElurTrace.kt +24 -0
  738. package/targets/android/app/src/main/java/com/elur/universal/ElurUiModule.kt +48 -0
  739. package/targets/android/app/src/main/java/com/elur/universal/ElurUiWorklet.kt +305 -0
  740. package/targets/android/app/src/main/java/com/elur/universal/JsBridge.kt +67 -0
  741. package/targets/android/app/src/main/java/com/elur/universal/JsThread.kt +189 -0
  742. package/targets/android/app/src/main/java/com/elur/universal/MainActivity.kt +844 -0
  743. package/targets/android/app/src/main/java/com/elur/universal/ModuleRegistry.kt +701 -0
  744. package/targets/android/app/src/main/java/com/elur/universal/YogaRowScope.kt +97 -0
  745. package/targets/android/app/src/main/res/values/ids.xml +10 -0
  746. package/targets/android/app/src/main/res/values/strings.xml +8 -0
  747. package/targets/android/app/src/main/res/values-es/strings.xml +5 -0
  748. package/targets/android/app/src/main/res/xml/network_security_config.xml +10 -0
  749. package/targets/android/build.gradle.kts +5 -0
  750. package/targets/android/gradle/libs.versions.toml +12 -0
  751. package/targets/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  752. package/targets/android/gradle/wrapper/gradle-wrapper.properties +8 -0
  753. package/targets/android/gradle.properties +23 -0
  754. package/targets/android/gradlew +251 -0
  755. package/targets/android/gradlew.bat +94 -0
  756. package/targets/android/settings.gradle.kts +32 -0
  757. package/targets/web/.gitkeep +0 -0
  758. package/targets/web/index.html +13 -0
@@ -0,0 +1,2857 @@
1
+ // src/reconciler/reconciler.ts
2
+ // ADR-0003: El Reconciler vive en la Capa 3. Módulo JS DOM-free que recorre
3
+ // el IR, suscribe los bindings a los signals y emite ops del Display List.
4
+ // Los backends son aplicadores puros de ops.
5
+ //
6
+ // ADR-0002: Transaction model — render pass (emit separado de flush) +
7
+ // update pass (batch para agrupar escrituras).
8
+ //
9
+ // Este módulo NO conoce el DOM ni Android. Solo emite ops via `emit()`.
10
+ // El backend decide qué hacer con cada op.
11
+
12
+ import {
13
+ Owner,
14
+ effect,
15
+ runWithOwner,
16
+ signal,
17
+ untrack,
18
+ type Signal,
19
+ } from "@elurjs/core/signals";
20
+ import { EVENT_DEFAULT_CLASS } from "../ir/events";
21
+ import { makeEnvelope } from "../events";
22
+ import {
23
+ IR_VERSION,
24
+ STATE_STYLE_KEYS,
25
+ STRICT_FLEXBOX_KEYS,
26
+ isPortableEvent,
27
+ isPortableProp,
28
+ isSignal,
29
+ validateStyleValue,
30
+ validateTextSpans,
31
+ type Binding, type IRDocument, type IRNode, type ListItemFactory,
32
+ type Style,
33
+ } from "../ir/schema";
34
+ import { isSemanticProp } from "../ir/semantics";
35
+ import { isApplePlatform, normalizeCombo } from "../ir/shortcut";
36
+ import { Platform } from "../platform";
37
+ import { isNodeRef, windowInsets } from "../runtime/environment";
38
+
39
+ /** ADR-0179: combo canónico de la prop `shortcut` (null si inválido). */
40
+ function shortcutComboOf(v: unknown): string | null {
41
+ return typeof v === "string" ? normalizeCombo(v, isApplePlatform(Platform.OS)) : null;
42
+ }
43
+
44
+ /** Mezcla `extra` en un payload JSON-objeto de attach-event. */
45
+ function mergePayload(payload: string | undefined, extra: Record<string, unknown>): string {
46
+ const base = payload !== undefined ? JSON.parse(payload) as Record<string, unknown> : {};
47
+ return JSON.stringify({ ...base, ...extra });
48
+ }
49
+ import {
50
+ type DisplayOp, type IdMap, type NativeListItem,
51
+ allocId, createIdMap, toId,
52
+ } from "../transport/format";
53
+ import { isUiStyleKey, uiBindAdd, uiBindDrop } from "../animations/uiBindings";
54
+ import { uiScrollAdd, uiScrollDrop } from "../animations/scrollWorklets";
55
+ import { uiGestureAdd, uiGestureDrop } from "../animations/gestureWorklets";
56
+ import { uiBindWkAdd, uiBindWkDrop } from "../animations/bindWorklets";
57
+
58
+ // Tipos públicos
59
+
60
+ export interface ReconcilerOptions {
61
+ ir: IRDocument;
62
+ signals: Record<string, Signal<unknown>>;
63
+ emit: (op: DisplayOp) => void;
64
+ /** Funciones extractoras de keys para listas keyed */
65
+ keyFns?: Record<string, (item: any) => string>;
66
+ /** ADR-0037 — factories de `repeat()` por id: `list.renderItem`
67
+ * es `"f<N>"` en el IR serializable; aquí vive el closure. */
68
+ factories?: Record<string, ListItemFactory>;
69
+ /** Registry compartido de handlers — las listas con renderItem-factory
70
+ * (ADR-0014) mergean los handlers de cada fila aquí. */
71
+ handlers?: Record<string, (e?: unknown) => void>;
72
+ /** IdMap compartido (multi-pantalla: ScreenHost). Default: uno nuevo. */
73
+ idMap?: IdMap;
74
+ /** Prefijo de las claves string en el idMap — evita colisiones de ids
75
+ * user-authored entre pantallas que comparten el map. */
76
+ idPrefix?: string;
77
+ /** ADR-0034/R4.6 — modo estricto de vocabulario de estilos: las
78
+ * claves fuera de STRICT_FLEXBOX_KEYS se eliminan del update-style
79
+ * con warn (default false = pasan — contrato best-effort visual). */
80
+ strictStyles?: boolean;
81
+ /** ADR-0128 — el documento es la raíz de una pantalla: su nodo raíz
82
+ * recibe los defaults de llenado (`SCREEN_ROOT_DEFAULTS`) en las
83
+ * claves que el autor no fijó. ScreenHost y el SSR universal lo
84
+ * activan; fragmentos (loading de streaming) no. */
85
+ screenRoot?: boolean;
86
+ /** ADR-0086/R4.6 — modo estricto de props: una clave fuera de
87
+ * PROPS_CAPABILITY o marcada `no` en algún backend se elimina del
88
+ * update-props con warn. Props de platform-view exentas — su
89
+ * vocabulario lo define el módulo (ADR-0080). */
90
+ strictProps?: boolean;
91
+ /** ADR-0086/R4.6 — modo estricto de eventos: un attach-event fuera
92
+ * de EVENTS_CAPABILITY o marcado `no` en algún backend se descarta
93
+ * con warn — no se emite un handler que nunca disparará.
94
+ * Eventos de platform-view exentos (vocabulario del módulo). */
95
+ strictEvents?: boolean;
96
+ /** ADR-0054 — el host declara la cap "native-list": una `list` con
97
+ * filas template emite plantilla + datos a nivel item
98
+ * (set-list-template / set-list-items / list-splice / list-update /
99
+ * list-move) y el host posee ventana, recycle y bind. Sin la cap,
100
+ * o con filas factory, se usa el path JS (ventana + pool). */
101
+ nativeList?: boolean;
102
+ /** ADR-0123 — cap "skia": `canvas` con renderPolicy:"custom" pinta
103
+ * por el backend raster Skia. Sin ella degrada a views con warn. */
104
+ skia?: boolean;
105
+ /** ADR-0148 — mapa vivo del entry: id de autoría del scrolleable →
106
+ * `y` lógica. ScreenHost lo provee (RouteEntry.scrollPositions);
107
+ * presente, los scroll-view/list con `id` propio se auto-cablean a
108
+ * un tracker interno que persiste su posición, y al montar reciben
109
+ * la posición restaurada por update-props `scrollTop`. */
110
+ scrollPositions?: Record<string, number>;
111
+ /** ADR-0149 — caja del foco del entry: al crear, el `nodeId`
112
+ * sembrado es el restore (el reconciler emite `focused` en ese
113
+ * nodo y lo consume); en vida es el sink del tracker. */
114
+ focusState?: { nodeId?: string };
115
+ }
116
+
117
+ export interface ReconcilerHandle {
118
+ /** IdMap string → number, compartido con el backend */
119
+ idMap: IdMap;
120
+ /** Id numérico del nodo raíz renderizado (-1 si no hay root). */
121
+ rootId: number;
122
+ /** Detach un nodo de su padre (emit remove-child). No destruye. */
123
+ detachFromParent: (nodeId: string) => void;
124
+ /** Re-adjuntar un nodo a un padre en un índice (emit insert-child). */
125
+ attachToParent: (nodeId: string, parentId: string, index: number) => void;
126
+ /** Destruir un nodo (emit delete-node). Libera recursos del backend. */
127
+ destroyNode: (nodeId: string) => void;
128
+ /** Mover un nodo dentro de su padre a un nuevo índice (emit move-child). */
129
+ moveNode: (nodeId: string, parentId: string, index: number) => void;
130
+ /** Dispose de todos los effects (al destruir la pantalla/subárbol). */
131
+ dispose: () => void;
132
+ /**
133
+ * Destroy CON emisión: delete-node postorder por cada nodo vivo del
134
+ * subárbol + dispose completo de scopes. El backend libera el
135
+ * elemento real de cada descendiente, no solo el root (V02).
136
+ * Idempotente; usar cuando el modelo muere (no para detach).
137
+ */
138
+ destroy: () => void;
139
+ /** Registra un cleanup en el scope raíz — muere con esta instancia
140
+ * (ScreenCtx.onCleanup lo cablea para effects/recursos de factory). */
141
+ onDispose: (fn: () => void) => void;
142
+ /** ADR-0149 — re-aplica `focused` al último nodo enfocado recordado
143
+ * en sesión (ScreenHost lo llama tras re-attach en pop-back — la
144
+ * vista conservada pierde el foco al desmontarse). No-op sin foco. */
145
+ restoreFocus: () => void;
146
+ /** Contadores de recursos vivos (R1.6) — nodos, listas, worklets,
147
+ * entradas de idMap, handlers con listeners adjuntos y effects
148
+ * aproximados activos. */
149
+ metrics: () => {
150
+ nodes: number;
151
+ lists: number;
152
+ worklets: number;
153
+ idMapEntries: number;
154
+ handlers: number;
155
+ effects: number;
156
+ };
157
+ }
158
+
159
+ // Contexto interno del reconciler
160
+
161
+ /**
162
+ * CONTRATO R1.1 — Scope: unidad de propiedad de recursos.
163
+ * Jerarquía app → pantalla → nodo/fila (el reconciler crea un scope por
164
+ * nodo bajo el scope del padre; `rootScope` es el scope de la instancia).
165
+ * Todo effect, handler, worklet, entrada de idMap y estado de lista se
166
+ * registra en el scope del nodo que lo creó y muere con él.
167
+ * `dispose()`: recursivo postorder, idempotente, se desliga del padre.
168
+ * Un disposer que lanza NO aborta el resto — el cleanup es completo y
169
+ * el primer error se relanza al final (aislamiento de errores, V03).
170
+ * `addDispose` sobre un scope ya dispuesto ejecuta el dispose al
171
+ * instante — un recurso no puede quedar registrado en un scope muerto.
172
+ */
173
+ export class Scope {
174
+ /** id del nodo dueño de este scope (undefined en rootScope virtual). */
175
+ nodeId?: number;
176
+ readonly owner: Owner;
177
+ private parent?: Scope;
178
+ private children: Set<Scope>;
179
+ private disposes: Array<() => void>;
180
+ private disposed: boolean;
181
+
182
+ // Sin class fields — prohibidos en código embebido (AGENTS.md/Hermes).
183
+ constructor(parent?: Scope, nodeId?: number) {
184
+ this.nodeId = nodeId;
185
+ this.parent = parent;
186
+ this.owner = parent
187
+ ? runWithOwner(parent.owner, () => new Owner())
188
+ : new Owner();
189
+ this.children = new Set();
190
+ this.disposes = [];
191
+ this.disposed = false;
192
+ parent?.children.add(this);
193
+ }
194
+
195
+ run<T>(fn: () => T): T {
196
+ return runWithOwner(this.owner, fn);
197
+ }
198
+
199
+ addDispose(fn: () => void): void {
200
+ if (this.disposed) { fn(); return; }
201
+ this.disposes.push(fn);
202
+ }
203
+
204
+ dispose(): void {
205
+ if (this.disposed) return;
206
+ this.disposed = true;
207
+ let firstError: unknown;
208
+ let hasError = false;
209
+ const capture = (fn: () => void) => {
210
+ try {
211
+ fn();
212
+ } catch (e) {
213
+ if (!hasError) { hasError = true; firstError = e; }
214
+ }
215
+ };
216
+ for (const c of [...this.children]) capture(() => c.dispose());
217
+ this.children.clear();
218
+ for (const d of this.disposes) capture(d);
219
+ this.disposes.length = 0;
220
+ capture(() => this.owner.dispose());
221
+ this.parent?.children.delete(this);
222
+ this.parent = undefined;
223
+ if (hasError) throw firstError;
224
+ }
225
+
226
+ /** Recursos vivos registrados en el subárbol (métricas R1.6). */
227
+ get liveDisposes(): number {
228
+ let n = this.disposes.length;
229
+ for (const c of this.children) n += c.liveDisposes;
230
+ return n;
231
+ }
232
+
233
+ get childScopes(): ReadonlySet<Scope> { return this.children; }
234
+ }
235
+
236
+ interface ReconcilerContext {
237
+ signals: Record<string, Signal<unknown>>;
238
+ emit: (op: DisplayOp) => void;
239
+ idMap: IdMap;
240
+ /** scope virtual de la instancia — padre del scope del nodo raíz */
241
+ rootScope: Scope;
242
+ /** nodeId → scope del nodo (propiedad de recursos, R1.1) */
243
+ nodeScope: Map<number, Scope>;
244
+ /** childId → parentId, para detach sin pasar el parent */
245
+ nodeParents: Map<number, number>;
246
+ /** handler names que aportó un nodo al registry (filas factory) */
247
+ nodeHandlers: Map<number, string[]>;
248
+ /** id numérico → clave del idMap, para liberarla al destruir */
249
+ nodeIrIds: Map<number, string>;
250
+ /** keyFn handlers: extraen key de un item */
251
+ keyFns: Record<string, (item: any) => string>;
252
+ /** factories de repeat() por id (ADR-0037) */
253
+ factories: Record<string, ListItemFactory>;
254
+ /** registry compartido de handlers (list-factory mergea por fila) */
255
+ handlers?: Record<string, (e?: unknown) => void>;
256
+ /** prefijo de claves en idMap (ScreenHost: entryId) */
257
+ idPrefix: string;
258
+ /** Estado de listas: listId → keys actuales en orden */
259
+ listState: Map<number, { keys: string[]; keyToId: Map<string, number> }>;
260
+ /** Contador de IDs para items de listas */
261
+ listItemCounter: number;
262
+ /** Animaciones worklet vivas por nodo — cancelan en destroy/dispose. */
263
+ workletAnims: Map<number, { cancel(): void }>;
264
+ /** Pila de scroll-view ancestros durante el render (ADR-0033): una
265
+ * lista virtual sin binding `scroll` auto-cablea su feed al
266
+ * scroll-view más cercano. */
267
+ scrollerStack: number[];
268
+ /** ADR-0034 — modo estricto de estilos (ver ReconcilerOptions). */
269
+ strictStyles: boolean;
270
+ /** ADR-0128 (ver ReconcilerOptions.screenRoot). */
271
+ screenRoot: boolean;
272
+ /** ADR-0127 — estilo de texto heredable efectivo por nodo (valores o
273
+ * bindings). Mapa por id y no pila de recursión: las filas de lista
274
+ * se renderizan después y parten del estilo del nodo lista. */
275
+ inheritedText: Map<number, Record<string, unknown>>;
276
+ /** ADR-0086 — modo estricto de props y eventos (ver ReconcilerOptions). */
277
+ strictProps: boolean;
278
+ strictEvents: boolean;
279
+ /** Disposers de los effects de binding por nodo (ADR-0033 pool
280
+ * estructural): reciclar una fila re-renderiza el IR del item nuevo
281
+ * sobre los ids vivos — antes hay que matar SOLO las suscripciones
282
+ * (las views y scopes sobreviven). Wrappers idempotentes: el teardown
283
+ * real del scope no los dispara dos veces. */
284
+ bindDisposes: Map<number, Array<() => void>>;
285
+ /** Remap activo durante un render reciclado: ids del subárbol
286
+ * aparcado en orden DFS — renderNode toma el id de la cola y omite
287
+ * create-node/insert-child/trackChild/scope (la estructura nativa
288
+ * ya existe; solo se re-emiten bindings y eventos). */
289
+ remapIds: number[] | undefined;
290
+ remapPos: number;
291
+ /** ADR-0054 — cap "native-list" negociada por el host. */
292
+ nativeList: boolean;
293
+ /** ADR-0123 — cap "skia" negociada por el host. */
294
+ skia: boolean;
295
+ /** ADR-0054 — payload de entrega (JSON) que se estampa en cada
296
+ * attach-event emitido durante el render de una fila template:
297
+ * `{"key": "<itemKey>"}` — el host lo mergea en `data` del envelope
298
+ * para que el handler compartido identifique el item bindeado. */
299
+ rowEventPayload: string | undefined;
300
+ /** ADR-0148 — sink vivo de posiciones (ver ReconcilerOptions). */
301
+ scrollPositions: Record<string, number> | undefined;
302
+ /** ADR-0148 — tracker por scroller: feeds de listas virtuales
303
+ * descendientes + handler `scroll` de la app a reenviar. El host
304
+ * guarda UN handler por (id, evento) — el tracker es ese attach y
305
+ * todos los consumidores cuelgan del bucket. */
306
+ scrollTrack: Map<number, {
307
+ nodeId?: string;
308
+ feeds: Array<Signal<{ y: number; vh: number; ty?: number }>>;
309
+ listeners: Array<(p: {
310
+ y: number; x: number; vh: number; vw: number; ch: number; cw: number; ty?: number;
311
+ }) => void>;
312
+ appFn: ((e?: unknown) => void) | undefined;
313
+ }>;
314
+ /** ADR-0149 — caja del foco recordado (ver ReconcilerOptions). */
315
+ focusState: { nodeId?: string } | undefined;
316
+ /** ADR-0149 — tracker por nodo enfocable nombrado: reenvío al
317
+ * handler `focus` de la app. Mismo motivo que scrollTrack. */
318
+ focusTrack: Map<number, {
319
+ nodeId: string;
320
+ appFn: ((e?: unknown) => void) | undefined;
321
+ }>;
322
+ /** ADR-0149 — id numérico del último nodo enfocado (solo sesión). */
323
+ focusedNum: number | undefined;
324
+ }
325
+
326
+ // Driver de worklets inyectado por animations/ (ADR-0025) — reconciler
327
+ // no puede importar Capa 6. El prop `animate={{worklet, timing}}` no
328
+ // cruza el wire: un Worklet no es JSON-serializable; el reconciler lo
329
+ // conduce localmente y lo ata al ciclo de vida del nodo.
330
+ export type WorkletDriverFn = (
331
+ wk: unknown, timing?: unknown,
332
+ ) => { cancel(): void; finished?: Promise<void> } | undefined;
333
+ let workletDriver: WorkletDriverFn | undefined;
334
+ export function setWorkletDriver(d: WorkletDriverFn | undefined): void {
335
+ workletDriver = d;
336
+ }
337
+
338
+ const isWorkletAnimate = (v: unknown): v is { worklet: unknown; timing?: unknown } =>
339
+ typeof v === "object" && v !== null &&
340
+ typeof (v as { worklet?: unknown }).worklet === "object" &&
341
+ (v as { worklet: { __isWorklet?: boolean } }).worklet.__isWorklet === true;
342
+
343
+ /** Scope del nodo — existe siempre tras renderNode (R1.1). */
344
+ function scopeOf(ctx: ReconcilerContext, nodeId: number): Scope {
345
+ return ctx.nodeScope.get(nodeId) ?? ctx.rootScope;
346
+ }
347
+
348
+ /**
349
+ * ADR-0148 — tracker de scroll por scroller nombrado: persiste la `y`
350
+ * lógica en ctx.scrollPositions[nodeId] (snapshot la serializa por
351
+ * entry), alimenta las señales `feed` de listas virtuales que cuelgan
352
+ * de él y reenvía el envelope al handler `scroll` de la app. Un solo
353
+ * attach por (id,"scroll") — el host retiene un único handler.
354
+ */
355
+ function ensureScrollHub(
356
+ ctx: ReconcilerContext,
357
+ id: number,
358
+ nodeId?: string,
359
+ appScroll?: { handler: string },
360
+ ) {
361
+ let bucket = ctx.scrollTrack.get(id);
362
+ const handlers = ctx.handlers;
363
+ if (bucket) {
364
+ if (nodeId !== undefined && bucket.nodeId === undefined) bucket.nodeId = nodeId;
365
+ if (appScroll && handlers && !bucket.appFn) {
366
+ bucket.appFn = handlers[appScroll.handler];
367
+ }
368
+ return bucket;
369
+ }
370
+ if (!handlers) return undefined;
371
+ bucket = {
372
+ nodeId,
373
+ feeds: [],
374
+ listeners: [],
375
+ appFn: appScroll ? handlers[appScroll.handler] : undefined,
376
+ };
377
+ const hname = `__elur_sct:${id}`;
378
+ handlers[hname] = (e?: unknown) => {
379
+ const env = (typeof e === "string" ? JSON.parse(e) : e) as {
380
+ data?: {
381
+ y?: number; x?: number; vh?: number; vw?: number;
382
+ ch?: number; cw?: number; ty?: number;
383
+ };
384
+ } | undefined;
385
+ const p = (env && env.data) ?? (env as {
386
+ y?: number; x?: number; vh?: number; vw?: number;
387
+ ch?: number; cw?: number; ty?: number;
388
+ } | undefined);
389
+ const y = p?.y ?? 0;
390
+ const x = p?.x ?? 0;
391
+ const vh = p?.vh ?? 0;
392
+ const vw = p?.vw ?? 0;
393
+ const ch = p?.ch ?? 0;
394
+ const cw = p?.cw ?? 0;
395
+ if (bucket!.nodeId !== undefined && ctx.scrollPositions) {
396
+ ctx.scrollPositions[bucket!.nodeId] = y;
397
+ }
398
+ for (const f of bucket!.feeds) {
399
+ f.value = { y, vh, ty: p?.ty };
400
+ }
401
+ for (const l of bucket!.listeners) {
402
+ l({ y, x, vh, vw, ch, cw, ty: p?.ty });
403
+ }
404
+ bucket!.appFn?.(env);
405
+ };
406
+ ctx.emit({
407
+ op: "attach-event", id, event: "scroll",
408
+ handler: hname, class: "continuous",
409
+ });
410
+ ctx.scrollTrack.set(id, bucket);
411
+ addDispose(ctx, id, () => {
412
+ ctx.emit({ op: "detach-event", id, event: "scroll" });
413
+ delete handlers[hname];
414
+ ctx.scrollTrack.delete(id);
415
+ });
416
+ return bucket;
417
+ }
418
+
419
+ function installScrollTracker(
420
+ ctx: ReconcilerContext,
421
+ id: number,
422
+ nodeId: string,
423
+ appScroll: { handler: string } | undefined,
424
+ ): void {
425
+ if (!ctx.scrollPositions) return;
426
+ ensureScrollHub(ctx, id, nodeId, appScroll);
427
+ }
428
+
429
+ /**
430
+ * ADR-0148 — restore: si el mapa vivo del entry guarda posición para
431
+ * este scroller se emite `scrollTop` por update-props y la clave se
432
+ * consume — un recreate posterior parte de 0 hasta el próximo scroll
433
+ * real (el tracker la reescribirá desde el primer evento).
434
+ */
435
+ function emitScrollRestore(
436
+ ctx: ReconcilerContext, id: number, nodeId: string | undefined,
437
+ ): void {
438
+ const positions = ctx.scrollPositions;
439
+ if (!positions || nodeId === undefined) return;
440
+ const y = positions[nodeId];
441
+ if (y === undefined) return;
442
+ delete positions[nodeId];
443
+ if (y !== 0) {
444
+ ctx.emit({ op: "update-props", id, changedProps: { scrollTop: y } });
445
+ }
446
+ }
447
+
448
+ /** ADR-0149 — tipos enfocables por defecto en ambas plataformas: el
449
+ * tracker solo se instala donde un `focus` real puede dispararse. */
450
+ const FOCUSABLE_TYPES = new Set(["button", "text-input", "switch", "slider"]);
451
+
452
+ /**
453
+ * ADR-0149 — memoria del foco por entry: tracker interno sobre el
454
+ * evento `focus` de nodos con `id` de autoría que pueden recibirlo.
455
+ * El host retiene un solo handler por (id,"focus") — slot `first` del
456
+ * par focus/blur de Android — así que el tracker posee el attach y
457
+ * reenvía el envelope al handler de la app, igual que el de scroll.
458
+ * El `id` de autoría viaja al snapshot; `focusedNum` guarda el id
459
+ * numérico para re-enfocar tras detach/attach (pop-back, ADR-0075).
460
+ */
461
+ function installFocusTracker(
462
+ ctx: ReconcilerContext,
463
+ id: number,
464
+ nodeId: string,
465
+ appFocus: { handler: string } | undefined,
466
+ ): void {
467
+ const handlers = ctx.handlers;
468
+ const state = ctx.focusState;
469
+ if (!handlers || !state) return;
470
+ const bucket = {
471
+ nodeId,
472
+ appFn: appFocus ? handlers[appFocus.handler] : undefined,
473
+ };
474
+ const hname = `__elur_foc:${id}`;
475
+ handlers[hname] = (e?: unknown) => {
476
+ const env = typeof e === "string" ? JSON.parse(e) : e;
477
+ state.nodeId = bucket.nodeId;
478
+ ctx.focusedNum = id;
479
+ bucket.appFn?.(env);
480
+ };
481
+ ctx.emit({ op: "attach-event", id, event: "focus", handler: hname });
482
+ ctx.focusTrack.set(id, bucket);
483
+ addDispose(ctx, id, () => {
484
+ ctx.emit({ op: "detach-event", id, event: "focus" });
485
+ delete handlers[hname];
486
+ ctx.focusTrack.delete(id);
487
+ if (ctx.focusedNum === id) ctx.focusedNum = undefined;
488
+ });
489
+ }
490
+
491
+ /**
492
+ * ADR-0149 — restore del foco persistido: si el slot del entry guarda
493
+ * este `id` de autoría se emite `focused:true` por update-semantics
494
+ * (el host mueve foco de entrada + foco a11y) y la clave se consume.
495
+ */
496
+ function emitFocusRestore(
497
+ ctx: ReconcilerContext, id: number, nodeId: string | undefined,
498
+ ): void {
499
+ const state = ctx.focusState;
500
+ if (!state || nodeId === undefined || state.nodeId !== nodeId) return;
501
+ state.nodeId = undefined;
502
+ ctx.focusedNum = id;
503
+ ctx.emit({ op: "update-semantics", id, semantics: { focused: true } });
504
+ }
505
+
506
+ /** Registra un dispose en el scope del nodo que lo creó (R1.1). */
507
+ function addDispose(ctx: ReconcilerContext, nodeId: number, d: () => void): void {
508
+ scopeOf(ctx, nodeId).addDispose(d);
509
+ }
510
+
511
+ /** Registra el dispose de un effect de binding: va al scope del nodo
512
+ * (teardown normal) y además a `bindDisposes` — el pool estructural
513
+ * (ADR-0033) mata solo las suscripciones al reciclar la fila, sin
514
+ * destruir views. El wrapper es idempotente para el teardown posterior. */
515
+ function trackBinding(ctx: ReconcilerContext, nodeId: number, d: () => void): void {
516
+ let done = false;
517
+ const wrapped = () => { if (!done) { done = true; d(); } };
518
+ addDispose(ctx, nodeId, wrapped);
519
+ let arr = ctx.bindDisposes.get(nodeId);
520
+ if (!arr) ctx.bindDisposes.set(nodeId, (arr = []));
521
+ arr.push(wrapped);
522
+ }
523
+
524
+ /** Punto único de emisión de update-style (ADR-0034): en modo estricto
525
+ * las claves fuera de STRICT_FLEXBOX_KEYS se eliminan con warn — una
526
+ * por clave por instancia (el set actúa de dedupe). */
527
+ function emitStyle(
528
+ ctx: ReconcilerContext, id: number, style: Record<string, unknown>,
529
+ ): void {
530
+ if (ctx.strictStyles) {
531
+ for (const key of Object.keys(style)) {
532
+ const badKey = !STRICT_FLEXBOX_KEYS.has(key);
533
+ // V14: también el VALOR — una dimensión "12em" o un enum
534
+ // fuera del set portátil renderizaría en web y se ignoraría
535
+ // en Android silenciosamente.
536
+ const badValue = !badKey && !validateStyleValue(key, style[key]);
537
+ if (badKey || badValue) {
538
+ if (typeof console !== "undefined" && console.warn) {
539
+ console.warn(
540
+ `[elur] strictStyles: ${badKey
541
+ ? `clave '${key}' fuera del vocabulario`
542
+ : `valor '${style[key]}' no portable para '${key}'`
543
+ } — eliminada (nodo ${id})`,
544
+ );
545
+ }
546
+ delete style[key];
547
+ }
548
+ }
549
+ if (Object.keys(style).length === 0) return;
550
+ }
551
+ ctx.emit({ op: "update-style", id, style: style as Style });
552
+ }
553
+
554
+ /** ADR-0127 — claves tipográficas que heredan los descendientes con
555
+ * texto. Los backends no implementan cascada (ADR-0003): el reconciler
556
+ * las emite en cada nodo de `TEXT_BEARING` que no las fija. La fuente
557
+ * única vive en src/style/textInherit.ts — la comparte el downleveler
558
+ * 10→9 de sdui, que hornea esta misma semántica. */
559
+ export { TEXT_INHERITED_KEYS, TEXT_BEARING, expandFlex }
560
+ from "../style/textInherit";
561
+ import { TEXT_INHERITED_KEYS, TEXT_BEARING, expandFlex }
562
+ from "../style/textInherit";
563
+
564
+ /** ADR-0128 — defaults de rol (el estilo del autor gana por clave). La
565
+ * raíz de pantalla llena el shell; un scroll-view encoge bajo su
566
+ * contenido (CSS resuelve `min-height:auto` a 0 en contenedores de
567
+ * scroll, Yoga no). */
568
+ const SCREEN_ROOT_DEFAULTS: Record<string, unknown> = {
569
+ flexGrow: 1, flexShrink: 1, flexBasis: 0, minHeight: 0,
570
+ };
571
+ const SCROLL_VIEW_DEFAULTS: Record<string, unknown> = { flexShrink: 1, minHeight: 0 };
572
+
573
+ /** Estilo efectivo del nodo: defaults de rol < herencia de texto <
574
+ * estilo propio (con `flex` expandido). Registra además el estilo
575
+ * heredable que verán sus descendientes. */
576
+ function resolveStyle(
577
+ node: IRNode, parentId: number | undefined, id: number, ctx: ReconcilerContext,
578
+ ): Record<string, unknown> | undefined {
579
+ const own = node.style ? expandFlex(node.style as Record<string, unknown>) : undefined;
580
+ let defaults: Record<string, unknown> | undefined;
581
+ if (parentId === undefined && ctx.screenRoot) {
582
+ // Con tamaño propio explícito solo queda el clamp (shrink +
583
+ // min 0 — lo que permite que el scroll interno encoja como en
584
+ // CSS); sin él la raíz llena el shell.
585
+ defaults = own && ("height" in own || "flexGrow" in own || "flexBasis" in own)
586
+ ? SCROLL_VIEW_DEFAULTS
587
+ : SCREEN_ROOT_DEFAULTS;
588
+ } else if (node.type === "scroll-view") {
589
+ defaults = SCROLL_VIEW_DEFAULTS;
590
+ }
591
+ const parentInh = parentId !== undefined ? ctx.inheritedText.get(parentId) : undefined;
592
+ let inh = parentInh;
593
+ if (own) {
594
+ for (const k of TEXT_INHERITED_KEYS) {
595
+ if (k in own) {
596
+ if (inh === parentInh) inh = { ...parentInh };
597
+ inh![k] = own[k];
598
+ }
599
+ }
600
+ }
601
+ if (inh) ctx.inheritedText.set(id, inh);
602
+ const fromParent = TEXT_BEARING.has(node.type) ? parentInh : undefined;
603
+ if (!own && !defaults && !fromParent) return undefined;
604
+ return { ...defaults, ...fromParent, ...own };
605
+ }
606
+
607
+ /** Avisos strict de layout (docs §3.1/§3.16): patrones que en L1
608
+ * (flexShrink:0 por defecto) desbordan donde CSS encogía — el autor los
609
+ * ve en web antes de descubrirlos en el dispositivo. */
610
+ function warnLayoutSmells(
611
+ parent: IRNode, child: IRNode, parentStyle: Record<string, unknown> | undefined,
612
+ ): void {
613
+ if (typeof console === "undefined" || typeof console.warn !== "function") return;
614
+ // `row` como tipo ya implica flex-direction:row en los backends —
615
+ // un style que lo contradiga (`flexDirection:"column"`) gana.
616
+ const isRow = parentStyle?.flexDirection
617
+ ? parentStyle.flexDirection === "row"
618
+ : parent.type === "row";
619
+ if (!isRow) return;
620
+ const cs = child.style
621
+ ? expandFlex(child.style as Record<string, unknown>)
622
+ : undefined;
623
+ if (parentStyle?.flexWrap === "wrap" && cs && "flexBasis" in cs && !("flexShrink" in cs)) {
624
+ console.warn(
625
+ `[elur] strict: hijo de row+wrap con flexBasis=${cs.flexBasis} ` +
626
+ "sin flexShrink — con L1 no encoge; en Android desborda " +
627
+ "(declare flexShrink o use `flex`)"
628
+ );
629
+ }
630
+ const txt = typeof child.text === "string" ? child.text : "";
631
+ if (child.type === "text" && txt.length > 32 &&
632
+ (!cs || !("flexShrink" in cs))) {
633
+ console.warn(
634
+ `[elur] strict: texto largo (${txt.length} chars) dentro de row ` +
635
+ "sin flexShrink — con L1 desborda en vez de encoger"
636
+ );
637
+ }
638
+ }
639
+
640
+ /** Registra id como hijo de parentId (parent-link para detach). */
641
+ function trackChild(ctx: ReconcilerContext, parentId: number, id: number): void {
642
+ ctx.nodeParents.set(id, parentId);
643
+ }
644
+
645
+ /**
646
+ * Teardown por nodo, registrado en su propio scope: cancela worklets,
647
+ * suelta handlers del registry, limpia bookkeeping y libera la clave
648
+ * del idMap. El emit de delete-node NO va aquí — es decisión de
649
+ * destroySubtree (dispose() del handle no emite ops).
650
+ */
651
+ function teardownNode(id: number, ctx: ReconcilerContext): void {
652
+ ctx.workletAnims.get(id)?.cancel();
653
+ ctx.workletAnims.delete(id);
654
+ ctx.inheritedText.delete(id);
655
+ const hs = ctx.nodeHandlers.get(id);
656
+ if (hs) {
657
+ if (ctx.handlers) for (const h of hs) delete ctx.handlers[h];
658
+ ctx.nodeHandlers.delete(id);
659
+ }
660
+ ctx.nodeParents.delete(id);
661
+ ctx.listState.delete(id);
662
+ ctx.bindDisposes.delete(id);
663
+ const irKey = ctx.nodeIrIds.get(id);
664
+ if (irKey !== undefined) {
665
+ ctx.idMap.delete(irKey);
666
+ ctx.nodeIrIds.delete(id);
667
+ }
668
+ ctx.nodeScope.delete(id);
669
+ }
670
+
671
+ /**
672
+ * Destruye un subárbol en post-order: emit delete-node por cada nodo
673
+ * (hijos primero) y dispone sus scopes — effects, handlers, worklets e
674
+ * ids mueren con el nodo. El estado del modelo ya no existe para estos
675
+ * nodos: esto es destroy, no detach (F01/ADR-0030).
676
+ */
677
+ function destroySubtree(id: number, ctx: ReconcilerContext): void {
678
+ const scope = ctx.nodeScope.get(id);
679
+ if (!scope) return;
680
+ for (const child of [...scope.childScopes]) {
681
+ if (child.nodeId !== undefined) destroySubtree(child.nodeId, ctx);
682
+ }
683
+ ctx.emit({ op: "delete-node", id });
684
+ scope.dispose();
685
+ }
686
+
687
+ // Funciones compartidas (antes duplicadas en web.ts y elurApp.js)
688
+
689
+ /** Extrae todos los nombres de signals que aparecen en un Binding. */
690
+ export function collectReferencedSignals(binding: Binding): string[] {
691
+ if (binding.kind === "signal" || binding.kind === "computed") {
692
+ return binding.signal ? [binding.signal] : [];
693
+ }
694
+ if (binding.kind === "template") {
695
+ return (binding.expressions ?? [])
696
+ .map((e: any) => e?.signal)
697
+ .filter(Boolean) as string[];
698
+ }
699
+ return [];
700
+ }
701
+
702
+ /** Resuelve un Binding a string usando el valor actual de los signals. */
703
+ export function resolveText(
704
+ text: string | { binding: Binding; initial: string } | undefined,
705
+ signals: Record<string, Signal<unknown>>,
706
+ ): string {
707
+ if (typeof text === "string") return text;
708
+ if (text && typeof text === "object") {
709
+ const binding = text.binding;
710
+ if (binding.kind === "signal" || binding.kind === "computed") {
711
+ const sig = binding.signal ? signals[binding.signal] : undefined;
712
+ return String(sig?.value ?? "");
713
+ }
714
+ if (binding.kind === "template") {
715
+ let result = "";
716
+ const parts = binding.parts ?? [];
717
+ const exprs = binding.expressions ?? [];
718
+ for (let i = 0; i < parts.length; i++) {
719
+ result += parts[i];
720
+ if (i < exprs.length) {
721
+ const name = (exprs[i] as any)?.signal;
722
+ const sig = name ? signals[name] : undefined;
723
+ result += String(sig?.value ?? "");
724
+ }
725
+ }
726
+ return result;
727
+ }
728
+ return text.initial ?? "";
729
+ }
730
+ return "";
731
+ }
732
+
733
+ // Keyed list diff — A.6.4
734
+
735
+ interface ListDiffOp {
736
+ type: "create" | "move" | "remove" | "noop";
737
+ key: string;
738
+ item?: any;
739
+ newIndex: number;
740
+ /** Posición viva en el array del host al momento de aplicar la op
741
+ * (ADR-0054: list-splice/list-move la necesitan — recomputarla con
742
+ * indexOf por op sería O(n²) en reversas). -1 en create. */
743
+ oldIndex: number;
744
+ oldId?: number;
745
+ }
746
+
747
+ /**
748
+ * Diff de keys minimal — LIS + colocación por ancla (F04).
749
+ *
750
+ * Las keys que NO necesitan moverse son las de la subsecuencia creciente
751
+ * más larga (LIS) de posiciones antiguas en el orden nuevo — su orden
752
+ * relativo ya es el final. El resto se coloca explícitamente antes de su
753
+ * ancla (la key ya procesada a la derecha), procesando newKeys de
754
+ * derecha a izquierda. Rotación de N items → 1 move; el algoritmo
755
+ * anterior movía cada posición desalineada (rotación → N-1 moves).
756
+ *
757
+ * Las posiciones se simulan sobre `cur` para que cada índice emitido sea
758
+ * válido en el momento en que el host aplique la op (las ops se aplican
759
+ * en orden de emisión). Keys duplicadas = identidad ambigua → error.
760
+ */
761
+ // Treap implícito para la simulación del array del host (V06): rank,
762
+ // insert y remove por posición en O(log n). El array + rebuildPos por op
763
+ // anterior era O(n) por movimiento — O(n²) en reversas/rotaciones. El
764
+ // recorrido in-order del treap = orden actual de los hijos en el host.
765
+ // Prioridades deterministas por contador — Math.random no forma parte de
766
+ // la superficie de APIs declarada para el runtime embebido (R3.4).
767
+
768
+ interface TreapNode {
769
+ key: string;
770
+ pri: number;
771
+ size: number;
772
+ l: TreapNode | undefined;
773
+ r: TreapNode | undefined;
774
+ p: TreapNode | undefined;
775
+ }
776
+
777
+ function treapSize(n: TreapNode | undefined): number { return n?.size ?? 0; }
778
+ function treapPull(n: TreapNode): void {
779
+ n.size = 1 + treapSize(n.l) + treapSize(n.r);
780
+ }
781
+ function treapSetL(n: TreapNode, c: TreapNode | undefined): void {
782
+ n.l = c; if (c) c.p = n;
783
+ }
784
+ function treapSetR(n: TreapNode, c: TreapNode | undefined): void {
785
+ n.r = c; if (c) c.p = n;
786
+ }
787
+
788
+ /** Prioridad pseudoaleatoria determinista (SplitMix sobre contador). */
789
+ function makePriGen(): () => number {
790
+ let s = 0;
791
+ return () => {
792
+ let x = (s += 0x9e3779b9) >>> 0;
793
+ x = Math.imul(x ^ (x >>> 16), 0x21f0aaad) >>> 0;
794
+ x = Math.imul(x ^ (x >>> 15), 0x735a2d97) >>> 0;
795
+ return (x ^ (x >>> 15)) >>> 0;
796
+ };
797
+ }
798
+
799
+ /** Merge por prioridad; todo-a precede a todo-b en in-order. El root
800
+ * devuelto sale con p=undefined (los callers fijan el padre real). */
801
+ function treapMerge(a: TreapNode | undefined, b: TreapNode | undefined): TreapNode | undefined {
802
+ let r: TreapNode | undefined;
803
+ if (!a) r = b;
804
+ else if (!b) r = a;
805
+ else if (a.pri <= b.pri) {
806
+ treapSetR(a, treapMerge(a.r, b));
807
+ treapPull(a);
808
+ r = a;
809
+ } else {
810
+ treapSetL(b, treapMerge(a, b.l));
811
+ treapPull(b);
812
+ r = b;
813
+ }
814
+ if (r) r.p = undefined;
815
+ return r;
816
+ }
817
+
818
+ /** Split por tamaño: [primeros k en in-order, resto]. */
819
+ function treapSplit(
820
+ n: TreapNode | undefined, k: number,
821
+ ): [TreapNode | undefined, TreapNode | undefined] {
822
+ if (!n) return [undefined, undefined];
823
+ if (treapSize(n.l) >= k) {
824
+ const [a, b] = treapSplit(n.l, k);
825
+ treapSetL(n, b);
826
+ treapPull(n);
827
+ n.p = undefined;
828
+ if (a) a.p = undefined;
829
+ return [a, n];
830
+ }
831
+ const [a, b] = treapSplit(n.r, k - treapSize(n.l) - 1);
832
+ treapSetR(n, a);
833
+ treapPull(n);
834
+ n.p = undefined;
835
+ if (b) b.p = undefined;
836
+ return [n, b];
837
+ }
838
+
839
+ /** Posición in-order del nodo (0-based) — O(log n) por punteros a padre. */
840
+ function treapRank(n: TreapNode): number {
841
+ let r = treapSize(n.l);
842
+ while (n.p) {
843
+ if (n.p.r === n) r += treapSize(n.p.l) + 1;
844
+ n = n.p;
845
+ }
846
+ return r;
847
+ }
848
+
849
+ /** Inserta el nodo en la posición in-order `idx`; devuelve la raíz. */
850
+ function treapInsert(
851
+ root: TreapNode | undefined, n: TreapNode, idx: number,
852
+ ): TreapNode | undefined {
853
+ const [a, b] = treapSplit(root, idx);
854
+ return treapMerge(treapMerge(a, n), b);
855
+ }
856
+
857
+ /** Quita el nodo del árbol (merge de sus hijos en su lugar); devuelve raíz.
858
+ * El nodo sale como hoja detachada: `size=1` es obligatorio — conservar el
859
+ * tamaño del subárbol viejo inflaba los pull de los ancestros al reinsertar
860
+ * y `treapRank` dejaba de representar el array real (U02). */
861
+ function treapRemove(n: TreapNode): TreapNode | undefined {
862
+ const m = treapMerge(n.l, n.r);
863
+ const p = n.p;
864
+ n.l = n.r = n.p = undefined;
865
+ n.size = 1;
866
+ if (m) m.p = p;
867
+ if (!p) return m;
868
+ if (p.l === n) p.l = m; else p.r = m;
869
+ let a: TreapNode = p;
870
+ while (a.p) { treapPull(a); a = a.p; }
871
+ treapPull(a);
872
+ return a;
873
+ }
874
+
875
+ function diffKeyed(
876
+ oldKeys: string[],
877
+ newKeys: string[],
878
+ items: any[],
879
+ ): ListDiffOp[] {
880
+ const ops: ListDiffOp[] = [];
881
+
882
+ const newSet = new Set<string>();
883
+ for (const k of newKeys) {
884
+ if (!newSet.add(k)) {
885
+ throw new Error(`[elur] duplicate key "${k}" in keyed list`);
886
+ }
887
+ }
888
+ const oldPos = new Map<string, number>();
889
+ oldKeys.forEach((k, i) => oldPos.set(k, i));
890
+
891
+ // Removes primero: se resuelven por id, sin índice. El treap simula el
892
+ // array del host = keys viejas que sobreviven, en su orden actual.
893
+ let root: TreapNode | undefined;
894
+ let size = 0;
895
+ const nodeOf = new Map<string, TreapNode>();
896
+ const nextPri = makePriGen();
897
+ let removed = 0;
898
+ for (const k of oldKeys) {
899
+ if (newSet.has(k)) {
900
+ const n: TreapNode = {
901
+ key: k, pri: nextPri(), size: 1,
902
+ l: undefined, r: undefined, p: undefined,
903
+ };
904
+ nodeOf.set(k, n);
905
+ root = treapMerge(root, n);
906
+ size++;
907
+ } else {
908
+ // Se emiten en orden ascendente de posición: el índice vivo
909
+ // del k-ésimo remove es su posición vieja menos los removes
910
+ // ya aplicados.
911
+ ops.push({
912
+ type: "remove", key: k, newIndex: -1,
913
+ oldIndex: (oldPos.get(k) ?? 0) - removed++
914
+ });
915
+ }
916
+ }
917
+
918
+ // LIS sobre las posiciones antiguas de las keys nuevas presentes
919
+ // (los creates tienen -1 y nunca son estables).
920
+ const stable = new Set(lisIndices(newKeys.map((k) => oldPos.get(k) ?? -1)));
921
+
922
+ for (let i = newKeys.length - 1; i >= 0; i--) {
923
+ const key = newKeys[i];
924
+ // Ancla = key ya colocada a la derecha (i+1). Su posición actual
925
+ // es donde va el elemento procesado.
926
+ const anchor = i + 1 < newKeys.length
927
+ ? nodeOf.get(newKeys[i + 1])
928
+ : undefined;
929
+ const anchorRank = anchor ? treapRank(anchor) : size;
930
+ const node = nodeOf.get(key);
931
+
932
+ if (!node) {
933
+ // Item nuevo — create + insert antes del ancla.
934
+ const n: TreapNode = {
935
+ key, pri: nextPri(), size: 1,
936
+ l: undefined, r: undefined, p: undefined,
937
+ };
938
+ nodeOf.set(key, n);
939
+ root = treapInsert(root, n, anchorRank);
940
+ size++;
941
+ ops.push({
942
+ type: "create", key, item: items[i], newIndex: anchorRank,
943
+ oldIndex: -1
944
+ });
945
+ continue;
946
+ }
947
+
948
+ // Ya justo antes del ancla (o último sin ancla) → posición
949
+ // relativa correcta, ninguna op necesaria.
950
+ if (treapRank(node) === anchorRank - 1) continue;
951
+ // Estable (LIS): su orden relativo ya es el final — confiar.
952
+ if (stable.has(i)) continue;
953
+
954
+ // Move: extraer y reinsertar antes del ancla. El índice emitido
955
+ // es el rank del ancla tras la extracción.
956
+ const from = treapRank(node);
957
+ root = treapRemove(node);
958
+ size--;
959
+ const target = anchor ? treapRank(anchor) : size;
960
+ root = treapInsert(root, node, target);
961
+ size++;
962
+ ops.push({ type: "move", key, newIndex: target, oldIndex: from });
963
+ }
964
+
965
+ return ops;
966
+ }
967
+
968
+ /**
969
+ * Índices de la subsecuencia estrictamente creciente más larga de
970
+ * `seq` (las entradas -1 — items nuevos — se ignoran). Patience sort
971
+ * con reconstrucción de padres. O(n log n).
972
+ */
973
+ function lisIndices(seq: number[]): number[] {
974
+ const tails: number[] = []; // tails[l] = índice en seq del final del mejor LIS de largo l+1
975
+ const prev = new Int32Array(seq.length).fill(-1);
976
+ for (let i = 0; i < seq.length; i++) {
977
+ const v = seq[i];
978
+ if (v < 0) continue;
979
+ // binary search: primer l con seq[tails[l]] >= v
980
+ let lo = 0, hi = tails.length;
981
+ while (lo < hi) {
982
+ const mid = (lo + hi) >> 1;
983
+ if (seq[tails[mid]] < v) lo = mid + 1; else hi = mid;
984
+ }
985
+ if (lo > 0) prev[i] = tails[lo - 1];
986
+ tails[lo] = i;
987
+ }
988
+ const out: number[] = [];
989
+ for (let i = tails.length - 1, cur = tails[tails.length - 1]; i >= 0; i--, cur = prev[cur]) {
990
+ out[i] = cur;
991
+ }
992
+ return out;
993
+ }
994
+
995
+ /** Igualdad superficial de items para decidir refresh vs recreate en
996
+ * factory-mode (V05): campos por `===`; un campo Signal se compara por
997
+ * valor desenvuelto (el item nuevo puede traer un signal equivalente).
998
+ * ADR-0060: las lecturas son `peek()` — esta función corre dentro del
999
+ * effect estructural y un `.value` suscribiría el diff del array a cada
1000
+ * signal de campo (un like re-diferenciaría la lista entera). */
1001
+ /** Lectura sin suscripción compatible con `Computed` perezoso de core v4:
1002
+ * `untrack(() => s.value)` evalúa/refresca el computed frío sin crear arista. */
1003
+ function peekSignal<T>(s: Signal<T>): T {
1004
+ return untrack(() => s.value);
1005
+ }
1006
+
1007
+ function sameShallowItem(a: unknown, b: unknown): boolean {
1008
+ if (a === b) return true;
1009
+ if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
1010
+ const ka = Object.keys(a as object);
1011
+ const kb = Object.keys(b as object);
1012
+ if (ka.length !== kb.length) return false;
1013
+ for (const k of ka) {
1014
+ const va = (a as Record<string, unknown>)[k];
1015
+ const vb = (b as Record<string, unknown>)[k];
1016
+ if (va === vb) continue;
1017
+ const ua = isSignal(va) ? peekSignal(va as Signal<unknown>) : va;
1018
+ const ub = isSignal(vb) ? peekSignal(vb as Signal<unknown>) : vb;
1019
+ if (ua !== ub) return false;
1020
+ }
1021
+ return true;
1022
+ }
1023
+
1024
+ /** Copia los campos de un item nuevo a los signals de la fila (F04).
1025
+ * Un signal en el item aporta su valor actual; la fila conserva SU
1026
+ * signal — la suscripción viva del binding no se reemplaza. */
1027
+ function refreshRowFields(
1028
+ fields: Record<string, Signal<unknown>> | undefined,
1029
+ newItem: unknown,
1030
+ ): void {
1031
+ if (!fields || !newItem || typeof newItem !== "object") return;
1032
+ for (const [field, sig] of Object.entries(fields)) {
1033
+ const v = (newItem as Record<string, unknown>)[field];
1034
+ sig.value = isSignal(v) ? v.value : v;
1035
+ }
1036
+ }
1037
+
1038
+ /**
1039
+ * CONTRATO F04/R5.2 — keys duplicadas son error de programación: la
1040
+ * identidad keyed exige unicidad. Política determinista: gana la
1041
+ * PRIMERA ocurrencia, las siguientes se descartan del render y se
1042
+ * reportan vía `console.warn` una vez por pasada de diff (guarded —
1043
+ * en motores sin console no-op). Se valida en render inicial y en cada
1044
+ * update, sobre el array completo (no incremental) para que una key
1045
+ * reinsertada tras ser removida no cuente como duplicada.
1046
+ */
1047
+ function dedupeKeys(items: any[], keys: string[]): { items: any[]; keys: string[] } {
1048
+ const seen = new Set<string>();
1049
+ const dups: string[] = [];
1050
+ const outItems: any[] = [];
1051
+ const outKeys: string[] = [];
1052
+ for (let i = 0; i < keys.length; i++) {
1053
+ const k = keys[i];
1054
+ if (seen.has(k)) {
1055
+ if (dups.indexOf(k) === -1) dups.push(k);
1056
+ continue;
1057
+ }
1058
+ seen.add(k);
1059
+ outItems.push(items[i]);
1060
+ outKeys.push(k);
1061
+ }
1062
+ if (dups.length && typeof console !== "undefined" && typeof console.warn === "function") {
1063
+ console.warn(`[elur] keys duplicadas en lista keyed (primera ocurrencia gana): ${dups.join(", ")}`);
1064
+ }
1065
+ return { items: outItems, keys: outKeys };
1066
+ }
1067
+
1068
+ /** Renderiza una lista keyed: render inicial + suscripción reactiva con diff. */
1069
+ /**
1070
+ * Ventana virtual (ADR-0033): rango [start, end) de filas a materializar
1071
+ * dado el feed {y, vh} en unidades lógicas. Pura y DOM-free — cubierta
1072
+ * por unit + parity tests. Con vh=0 (viewport aún no reportado) la
1073
+ * ventana inicial es [0, overscan) — el primer reporte la expande.
1074
+ */
1075
+ export function virtualWindow(
1076
+ count: number, y: number, vh: number, rowH: number, overscan: number,
1077
+ ): { start: number; end: number } {
1078
+ const start = Math.min(count, Math.max(0, Math.floor(y / rowH) - overscan));
1079
+ const end = Math.min(count, Math.max(start, Math.ceil((y + vh) / rowH) + overscan));
1080
+ return { start, end };
1081
+ }
1082
+
1083
+ function renderList(node: IRNode, listId: number, ctx: ReconcilerContext) {
1084
+ const listDef = node.list!;
1085
+ const itemsBinding = listDef.items;
1086
+ const keyFnName = listDef.keyFn;
1087
+ // ADR-0037: renderItem puede ser id de factory — el closure vive en
1088
+ // options.factories (el IR solo lleva el id → serializable).
1089
+ const rt = listDef.renderItem;
1090
+ const renderItemTemplate =
1091
+ typeof rt === "string" ? ctx.factories[rt] : rt;
1092
+ if (!renderItemTemplate) {
1093
+ // Factory id sin closure registrado = bug de composición (el IR
1094
+ // llegó sin su registry). Fallar temprano — una lista vacía
1095
+ // silenciosa es más difícil de diagnosticar que el throw (V05).
1096
+ throw new Error(
1097
+ `[elur] list.renderItem '${String(rt)}' sin factory ` +
1098
+ `registrada (options.factories)`);
1099
+ }
1100
+
1101
+ // Obtener el signal de items
1102
+ let itemsSignal: Signal<any[]> | undefined;
1103
+ if (itemsBinding.kind === "signal" || itemsBinding.kind === "computed") {
1104
+ itemsSignal = ctx.signals[itemsBinding.signal!] as Signal<any[]> | undefined;
1105
+ }
1106
+ if (!itemsSignal) return;
1107
+
1108
+ const keyFn = ctx.keyFns[keyFnName] ?? ((item: any) => String(item.id ?? item.key ?? item));
1109
+
1110
+ // ADR-0056 — dos ejes ortogonales. `renderPolicy` elige la superficie
1111
+ // (views del SO vs Skia); `list.materialization` elige el propietario
1112
+ // de la ventana (widget host vs ventana+pool JS). El widget host solo
1113
+ // existe sobre views con filas template: la variante Skia sería la cap
1114
+ // "canvas-list", aún inexistente — `custom`+`host` degrada igual que
1115
+ // `custom` solo. `materialization:"js"` sobre superficie `native` es
1116
+ // válido: vistas nativas materializadas por la ventana JS.
1117
+ const policy = node.renderPolicy ?? "auto";
1118
+ const materialization = listDef.materialization ?? "auto";
1119
+ const templateRows = typeof renderItemTemplate !== "function";
1120
+ // U06 (ADR-0061): la plantilla debe ser elegible para el perfil de
1121
+ // fila del host — bindings de entorno, tipos, eventos y layout que
1122
+ // el inflador nativo no expresa causan pérdida silenciosa de
1123
+ // features en JS→nativo. `ineligible` lleva el motivo.
1124
+ const ineligible = templateRows
1125
+ ? nativeListEligibility(renderItemTemplate, ctx.signals)
1126
+ : null;
1127
+ const hostOk = policy !== "custom" && templateRows
1128
+ && !ineligible && ctx.nativeList;
1129
+ if (materialization !== "js" && hostOk) {
1130
+ renderListNative(
1131
+ node, listId, renderItemTemplate, itemsSignal, keyFn,
1132
+ listDef.virtual, ctx,
1133
+ );
1134
+ return;
1135
+ }
1136
+ if (typeof console !== "undefined" && console.warn) {
1137
+ const reason = !ctx.nativeList
1138
+ ? "cap 'native-list' en el host"
1139
+ : !templateRows
1140
+ ? "filas template (factory no es serializable como datos)"
1141
+ : ineligible
1142
+ ? `plantilla inelegible (${ineligible})`
1143
+ : "cap 'canvas-list' (lista Skia inexistente en este host)";
1144
+ if (materialization === "host") {
1145
+ console.warn(
1146
+ `[elur] list.materialization='host' sin ${reason}` +
1147
+ " — fallback al path JS",
1148
+ );
1149
+ } else if (materialization === "auto" && ineligible
1150
+ && policy !== "custom") {
1151
+ // En 'auto' la ausencia de cap es rutinaria (silenciosa);
1152
+ // una plantilla inelegible es pérdida real de feature —
1153
+ // siempre con motivo (U06).
1154
+ console.warn(
1155
+ `[elur] lista nativa no usada: ${reason} — fallback al path JS`,
1156
+ );
1157
+ }
1158
+ }
1159
+ if (policy === "custom" && typeof console !== "undefined" && console.warn) {
1160
+ console.warn(
1161
+ "[elur] renderPolicy='custom' exige el renderer Skia (100 %), ausente" +
1162
+ " en este host — degradando al path JS (no es un modo equivalente)",
1163
+ );
1164
+ }
1165
+
1166
+ // Pool LRU de filas removidas (ADR-0031/R1.5): solo en template-mode.
1167
+ // Una fila aparcada conserva scope (effects, handlers, estado local)
1168
+ // y su elemento backend — reaparecer la key la re-adjunta intacta.
1169
+ // Al desbordar poolSize se destruye la menos reciente (postorder).
1170
+ const poolSize = Math.max(0, listDef.poolSize ?? 0);
1171
+ const pool = new Map<string, {
1172
+ id: number;
1173
+ item: unknown;
1174
+ fields?: Record<string, Signal<unknown>>;
1175
+ struct?: RowStruct;
1176
+ }>();
1177
+
1178
+ // Ventana virtual (ADR-0033): solo se materializan las filas del
1179
+ // rango [start, end) derivado del feed de scroll {y, vh} en unidades
1180
+ // lógicas. El reconciler emite la geometría de cada fila (absolute +
1181
+ // top = index*rowHeight) y el height total del contenedor lista.
1182
+ const virt = listDef.virtual;
1183
+ // ADR-0128: la lista no virtual no genera caja — sus filas participan
1184
+ // del flex del padre (gap, wrap, align) como si fueran hijas directas.
1185
+ // Excepción: una lista con props/eventos de eje propio (horizontal,
1186
+ // inverted, columns, paging, refreshing, offsets, scroll/refresh/
1187
+ // endReached) ES una caja/scroller — `contents` le quitaría el rect
1188
+ // y el host no tendría viewport propio (Linux swappea el fixed a
1189
+ // GtkScrolledWindow; el div web con overflow ya es caja).
1190
+ const listProps = node.props ?? {};
1191
+ const listEvents = node.events ?? {};
1192
+ const needsBox = listProps.horizontal !== undefined ||
1193
+ listProps.inverted !== undefined || listProps.columns !== undefined ||
1194
+ listProps.paging !== undefined || listProps.refreshing !== undefined ||
1195
+ listProps.scrollTop !== undefined || listProps.scrollLeft !== undefined ||
1196
+ listEvents.scroll !== undefined || listEvents.refresh !== undefined ||
1197
+ listEvents.endReached !== undefined;
1198
+ if (!virt && !needsBox && !(node.style && "display" in node.style)) {
1199
+ emitStyle(ctx, listId, { display: "contents" });
1200
+ }
1201
+ const rowH = virt ? Math.max(1, virt.rowHeight) : 0;
1202
+ const overscan = virt ? Math.max(0, virt.overscan ?? 4) : 0;
1203
+ let feedSig: Signal<{ y: number; vh: number; ty?: number }> | undefined;
1204
+ if (virt) {
1205
+ const sb = virt.scroll;
1206
+ if (sb && (sb.kind === "signal" || sb.kind === "computed")) {
1207
+ feedSig = ctx.signals[sb.signal] as
1208
+ Signal<{ y: number; vh: number; ty?: number }> | undefined;
1209
+ if (!feedSig && typeof console !== "undefined" && console.warn) {
1210
+ console.warn(
1211
+ `[elur] list.virtual.scroll: signal '${sb.signal}' no resuelta — auto-wire`,
1212
+ );
1213
+ }
1214
+ }
1215
+ if (!feedSig) {
1216
+ // Auto-wire: feed interno alimentado por el evento "scroll"
1217
+ // del scroll-view ancestro (payload {y, vh} normalizado por
1218
+ // el backend; string JSON en el carril nativo).
1219
+ feedSig = signal({ y: 0, vh: 0 });
1220
+ const scrollerId = ctx.scrollerStack[ctx.scrollerStack.length - 1];
1221
+ if (scrollerId !== undefined && ctx.handlers) {
1222
+ const bucket = ensureScrollHub(ctx, scrollerId);
1223
+ if (bucket) {
1224
+ const feed = feedSig;
1225
+ bucket.feeds.push(feed);
1226
+ addDispose(ctx, listId, () => {
1227
+ const i = bucket.feeds.indexOf(feed);
1228
+ if (i >= 0) bucket.feeds.splice(i, 1);
1229
+ });
1230
+ }
1231
+ }
1232
+ }
1233
+ }
1234
+ // key → último top emitido; lista → último height emitido (evita
1235
+ // update-style redundantes en cada pasada del diff).
1236
+ const keyTop = new Map<string, number>();
1237
+ let lastHeight = -1;
1238
+ const emitWindowGeometry = (keys: string[], wStart: number, total: number) => {
1239
+ for (let i = 0; i < keys.length; i++) {
1240
+ const key = keys[i];
1241
+ const top = (wStart + i) * rowH;
1242
+ if (keyTop.get(key) === top) continue;
1243
+ keyTop.set(key, top);
1244
+ const rid = keyToId.get(key);
1245
+ if (rid !== undefined) {
1246
+ emitStyle(ctx, rid, {
1247
+ position: "absolute", top, left: 0,
1248
+ right: 0, height: rowH,
1249
+ });
1250
+ }
1251
+ }
1252
+ const h = total * rowH;
1253
+ if (h !== lastHeight) {
1254
+ lastHeight = h;
1255
+ emitStyle(ctx, listId, { height: h });
1256
+ }
1257
+ };
1258
+
1259
+ // Estado inicial de la lista (keys validadas — F04/R5.2). En modo
1260
+ // virtual el estado es la VISTA (slice de la ventana), no el array.
1261
+ const initialRaw = (itemsSignal.value as any[]) ?? [];
1262
+ let winStart0 = 0;
1263
+ let initialView = initialRaw;
1264
+ if (virt) {
1265
+ const f = feedSig!.value;
1266
+ const w = virtualWindow(initialRaw.length, f.y, f.vh, rowH, overscan);
1267
+ winStart0 = w.start;
1268
+ initialView = initialRaw.slice(w.start, w.end);
1269
+ }
1270
+ const initial = dedupeKeys(initialView, initialView.map(keyFn));
1271
+ const initialItems = initial.items;
1272
+ const initialKeys = initial.keys;
1273
+ const keyToId = new Map<string, number>();
1274
+ // key → {item, signals por campo} — para refrescar datos cuando la
1275
+ // key sobrevive con otro objeto (F04). Solo template-mode; las filas
1276
+ // factory cierran sobre su item en closures — misma key no refresca.
1277
+ const keyToItem = new Map<string, {
1278
+ item: unknown;
1279
+ fields?: Record<string, Signal<unknown>>;
1280
+ struct?: RowStruct;
1281
+ }>();
1282
+
1283
+ const state = { keys: initialKeys, keyToId };
1284
+ ctx.listState.set(listId, state);
1285
+
1286
+ // Render inicial: crear un nodo por cada item
1287
+ for (let i = 0; i < initialItems.length; i++) {
1288
+ const item = initialItems[i];
1289
+ const key = initialKeys[i];
1290
+ const itemTempId = ++ctx.listItemCounter;
1291
+ // renderListItem retorna el ID real asignado por toId()
1292
+ const rendered = renderListItem(renderItemTemplate, itemTempId, listId, i, item, ctx, undefined, key);
1293
+ keyToId.set(key, rendered.id);
1294
+ keyToItem.set(key, { item, fields: rendered.fields, struct: rendered.struct });
1295
+ trackChild(ctx, listId, rendered.id);
1296
+ }
1297
+ if (virt) emitWindowGeometry(initialKeys, winStart0, initialRaw.length);
1298
+
1299
+ // Fling-prefetch (ADR-0033): en una ráfaga de scroll rápido, un
1300
+ // re-window por evento es trabajo garantizado-obsoleto — para cuando
1301
+ // las ops aplican, el viewport ya pasó de largo, y el backlog deja
1302
+ // la lista en blanco segundos. En su lugar se aplica UNA ventana cada
1303
+ // ~150ms hacia la posición PREDICHA (y + velocidad·lookahead) — las
1304
+ // filas se materializan delante del scroll físico, mismo truco que el
1305
+ // prefetch de RecyclerView por velocidad. Aplica al instante en el
1306
+ // primer evento con delta pequeño (settle), tras un hueco temporal
1307
+ // (salto aislado/programático) o al tocar un borde. El host re-reporta
1308
+ // la y final ~120ms tras el último movimiento (scroll-settle watchdog)
1309
+ // → el estado no puede quedar stale aunque el stream muera de golpe.
1310
+ // `lastMoveAt` solo cuenta eventos con movimiento — el run inicial
1311
+ // del effect (dy=0) no debe marcar "stream" al primer write real.
1312
+ // DOM-free: sin timers — el guard usa solo deltas y Date.now.
1313
+ let lastFeedY = feedSig?.value.y ?? 0;
1314
+ let lastMoveAt = 0;
1315
+ let lastApplyAt = 0;
1316
+ let velocity = 0;
1317
+
1318
+ // Suscripción reactiva: cuando el signal cambia, hacer diff
1319
+ const dispose = effect(() => {
1320
+ const rawItems = (itemsSignal!.value as any[]) ?? [];
1321
+ let wStart = 0;
1322
+ let view = rawItems;
1323
+ if (virt) {
1324
+ const f = feedSig!.value;
1325
+ const nowMs = Date.now();
1326
+ const dy = f.y - lastFeedY;
1327
+ const ady = Math.abs(dy);
1328
+ const streaming = lastMoveAt !== 0 && nowMs - lastMoveAt < 120;
1329
+ if (ady > 1) {
1330
+ velocity = dy / Math.max(1, nowMs - lastMoveAt);
1331
+ lastMoveAt = nowMs;
1332
+ }
1333
+ lastFeedY = f.y;
1334
+ const maxY = Math.max(0, rawItems.length * rowH - f.vh);
1335
+ const atEdge = f.y <= 0 || f.y >= maxY - rowH;
1336
+ const jump = Math.max(f.vh * 0.4, rowH * 4);
1337
+ let targetY = f.y;
1338
+ let targetVh = f.vh;
1339
+ // Overscan adaptativo (R5.4): solo en ráfaga (fling con ty
1340
+ // o drag rápido continuo) — un salto aislado aplica la
1341
+ // ventana exacta con el overscan base. El extra cubre el
1342
+ // borde trasero y una reversa del gesto sin commit
1343
+ // intermedio: la mitad de las filas/100ms, acotado a +6.
1344
+ let ovBoost = 0;
1345
+ const ty = f.ty;
1346
+ if (
1347
+ ty !== undefined && ty >= 0 && !atEdge &&
1348
+ Math.abs(ty - f.y) > jump && nowMs - lastApplyAt >= 60
1349
+ ) {
1350
+ // Fling con destino EXACTO (ElurScrollView replica el
1351
+ // OverScroller del gesto): cubrir el path [y → ty+vh].
1352
+ // Si excede el presupuesto (4×vh) la ventana es una
1353
+ // alfombra rodante ANCLADA EN LA POSICIÓN ACTUAL — el
1354
+ // tramo sin materializar queda por delante del dedo pero
1355
+ // el borde visible nunca queda desnudo (anclar al destino
1356
+ // desmontaba la región que el usuario estaba viendo).
1357
+ const lo = Math.min(f.y, ty);
1358
+ const hi = Math.max(f.y + f.vh, ty + f.vh);
1359
+ // Presupuesto 2.5×vh (~29 filas/commit): un salto mayor
1360
+ // concentra tanto diff en un solo commit que el hilo JS se
1361
+ // bloquea más que lo que dura el propio fling.
1362
+ const maxSpan = f.vh * 2.5;
1363
+ if (hi - lo <= maxSpan) {
1364
+ targetY = lo;
1365
+ targetVh = hi - lo;
1366
+ } else if (ty > f.y) {
1367
+ targetY = f.y;
1368
+ targetVh = maxSpan;
1369
+ } else {
1370
+ targetY = f.y + f.vh - maxSpan;
1371
+ targetVh = maxSpan;
1372
+ }
1373
+ ovBoost = Math.min(
1374
+ 6, Math.round(Math.abs(velocity) * 50 / rowH));
1375
+ } else if (streaming && !atEdge && ady > jump) {
1376
+ // Drag rápido (sin fling → sin ty): aplicar como mucho una
1377
+ // ventana cada 100ms cubriendo el rango CONTINUO
1378
+ // viewport→predicho (lead por velocidad, cap 2.5×vh).
1379
+ if (nowMs - lastApplyAt < 100) return;
1380
+ const cap = f.vh * 2.5;
1381
+ const lead = Math.max(-cap, Math.min(cap, velocity * 120));
1382
+ targetY = Math.min(f.y, f.y + lead);
1383
+ targetVh = Math.abs(lead) + f.vh;
1384
+ ovBoost = Math.min(
1385
+ 6, Math.round(Math.abs(velocity) * 50 / rowH));
1386
+ }
1387
+ lastApplyAt = nowMs;
1388
+ const w = virtualWindow(
1389
+ rawItems.length, targetY, targetVh, rowH,
1390
+ overscan + ovBoost);
1391
+ wStart = w.start;
1392
+ view = rawItems.slice(w.start, w.end);
1393
+ }
1394
+ const deduped = dedupeKeys(view, view.map(keyFn));
1395
+ const newItems = deduped.items;
1396
+ const newKeys = deduped.keys;
1397
+ const oldKeys = state.keys;
1398
+ const oldSet = new Set(oldKeys);
1399
+
1400
+ const diffOps = diffKeyed(oldKeys, newKeys, newItems);
1401
+
1402
+ for (const op of diffOps) {
1403
+ if (op.type === "create") {
1404
+ const parked = pool.get(op.key);
1405
+ if (parked) {
1406
+ // Reattach (R1.5): la key reaparece — re-adjuntar la
1407
+ // instancia viva (scope, handlers y estado conservados)
1408
+ // y refrescar sus campos desde el nuevo item.
1409
+ pool.delete(op.key);
1410
+ state.keyToId.set(op.key, parked.id);
1411
+ keyToItem.set(op.key, { item: op.item, fields: parked.fields, struct: parked.struct });
1412
+ ctx.emit({ op: "insert-child", parentId: listId, childId: parked.id, index: op.newIndex });
1413
+ refreshRowFields(parked.fields, op.item);
1414
+ } else {
1415
+ // Pool estructural (ADR-0033): la key no reaparece —
1416
+ // se vende la fila aparcada más reciente con struct
1417
+ // capturada y el item nuevo se renderiza SOBRE sus
1418
+ // views (rebind: update-ops + nuevas suscripciones,
1419
+ // cero inflación nativa). Es el mecanismo de FlashList
1420
+ // adaptado al diff keyed: en un salto de ventana el
1421
+ // costo por fila cae de ~8 creates+inflation a ~rebind.
1422
+ let candKey: string | undefined;
1423
+ let cand: { id: number; item: unknown; struct?: RowStruct } | undefined;
1424
+ if (pool.size) {
1425
+ const pk = Array.from(pool.keys());
1426
+ for (let i = pk.length - 1; i >= 0; i--) {
1427
+ const e = pool.get(pk[i])!;
1428
+ if (e.struct) { candKey = pk[i]; cand = e; break; }
1429
+ }
1430
+ }
1431
+ const itemTempId = ++ctx.listItemCounter;
1432
+ const rendered = renderListItem(
1433
+ renderItemTemplate, itemTempId, listId, op.newIndex,
1434
+ op.item, ctx, cand?.struct, op.key);
1435
+ if (cand && rendered.recycled) {
1436
+ pool.delete(candKey!);
1437
+ state.keyToId.set(op.key, cand.id);
1438
+ keyToItem.set(op.key, {
1439
+ item: op.item, fields: rendered.fields,
1440
+ struct: cand.struct,
1441
+ });
1442
+ } else {
1443
+ if (cand) {
1444
+ // Estructura incompatible — la aparcada no sirve.
1445
+ pool.delete(candKey!);
1446
+ destroySubtree(cand.id, ctx);
1447
+ }
1448
+ state.keyToId.set(op.key, rendered.id);
1449
+ keyToItem.set(op.key, {
1450
+ item: op.item, fields: rendered.fields,
1451
+ struct: rendered.struct,
1452
+ });
1453
+ trackChild(ctx, listId, rendered.id);
1454
+ }
1455
+ }
1456
+ } else if (op.type === "remove") {
1457
+ const itemId = state.keyToId.get(op.key);
1458
+ if (itemId !== undefined) {
1459
+ ctx.emit({ op: "remove-child", parentId: listId, childId: itemId });
1460
+ keyTop.delete(op.key);
1461
+ const rec = keyToItem.get(op.key);
1462
+ // Aparcar: template-mode conserva fields (rebind por
1463
+ // nombre); cualquier fila con struct capturada es
1464
+ // reutilizable estructuralmente para OTRO item (V05
1465
+ // resuelto por el rebind: handlers y signals se
1466
+ // re-renderizan contra el item nuevo, no queda
1467
+ // closure vieja).
1468
+ if (poolSize > 0 && rec && (rec.fields || rec.struct)) {
1469
+ // Aparcar (detach ya emitido arriba). Reinsertar en
1470
+ // el Map mantiene el orden LRU = último uso.
1471
+ pool.set(op.key, { id: itemId, item: rec.item, fields: rec.fields, struct: rec.struct });
1472
+ keyToItem.delete(op.key);
1473
+ state.keyToId.delete(op.key);
1474
+ if (pool.size > poolSize) {
1475
+ const evictKey = pool.keys().next().value as string;
1476
+ const evicted = pool.get(evictKey)!;
1477
+ pool.delete(evictKey);
1478
+ // Expulsada del pool → destroy completo (F01).
1479
+ destroySubtree(evicted.id, ctx);
1480
+ }
1481
+ } else {
1482
+ state.keyToId.delete(op.key);
1483
+ keyToItem.delete(op.key);
1484
+ // El item salió del modelo: destruir su subárbol —
1485
+ // effects, handlers, worklets e ids (F01).
1486
+ destroySubtree(itemId, ctx);
1487
+ }
1488
+ }
1489
+ } else if (op.type === "move") {
1490
+ const itemId = state.keyToId.get(op.key);
1491
+ if (itemId !== undefined) {
1492
+ ctx.emit({ op: "move-child", parentId: listId, childId: itemId, index: op.newIndex });
1493
+ }
1494
+ }
1495
+ // noop: no hacer nada
1496
+ }
1497
+
1498
+ // Refresh por key (F04): misma key + objeto distinto → copiar los
1499
+ // valores nuevos a los signals de la fila — conserva identidad,
1500
+ // handlers y estado local (foco) sin recrear el subárbol.
1501
+ for (let i = 0; i < newKeys.length; i++) {
1502
+ const key = newKeys[i];
1503
+ if (!oldSet.has(key)) continue; // recién creado/reattach
1504
+ const rec = keyToItem.get(key);
1505
+ const newItem = newItems[i];
1506
+ if (!rec || rec.item === newItem) continue;
1507
+ const prevItem = rec.item;
1508
+ rec.item = newItem;
1509
+ if (rec.fields) {
1510
+ refreshRowFields(rec.fields, newItem);
1511
+ } else if (!sameShallowItem(prevItem, newItem)) {
1512
+ // Factory-mode (V05): la fila cerró sobre el item viejo
1513
+ // en sus closures — no hay signals por campo que
1514
+ // refrescar. Objeto con contenido distinto = dominio
1515
+ // distinto: recrear la fila en su posición (delete
1516
+ // postorder + create + insert en i, ya colocada por el
1517
+ // diff). Contenido igual → conservar la fila intacta.
1518
+ const oldId = state.keyToId.get(key);
1519
+ if (oldId !== undefined) {
1520
+ ctx.emit({ op: "remove-child", parentId: listId, childId: oldId });
1521
+ destroySubtree(oldId, ctx);
1522
+ }
1523
+ const itemTempId = ++ctx.listItemCounter;
1524
+ const rendered = renderListItem(
1525
+ renderItemTemplate, itemTempId, listId, i, newItem, ctx,
1526
+ undefined, key);
1527
+ state.keyToId.set(key, rendered.id);
1528
+ keyToItem.set(key, { item: newItem, fields: rendered.fields, struct: rendered.struct });
1529
+ trackChild(ctx, listId, rendered.id);
1530
+ keyTop.delete(key); // geometría virtual → reemitir
1531
+ }
1532
+ }
1533
+
1534
+ if (virt) emitWindowGeometry(newKeys, wStart, rawItems.length);
1535
+ state.keys = newKeys;
1536
+ });
1537
+ addDispose(ctx, listId, dispose);
1538
+ }
1539
+
1540
+ /** ADR-0060 (U05) — campos del item que la plantilla puede leer: signals
1541
+ * referenciados por bindings de style/props/text (`{kind:"signal"|
1542
+ * "computed", signal:F}` y expresiones de `kind:"template"`). Solo estos
1543
+ * campos se serializan al host y solo sus signals se observan — un campo
1544
+ * no ligado (p.ej. `id` usado por keyFn) nunca viaja ni suscribe. */
1545
+ function collectTemplateFields(t: IRNode, out?: Set<string>): Set<string> {
1546
+ const acc = out ?? new Set<string>();
1547
+ const take = (v: unknown) => {
1548
+ if (v && typeof v === "object") {
1549
+ const k = (v as { kind?: string }).kind;
1550
+ const s = (v as { signal?: unknown }).signal;
1551
+ if ((k === "signal" || k === "computed") && typeof s === "string") {
1552
+ acc.add(s);
1553
+ }
1554
+ }
1555
+ };
1556
+ if (t.style) for (const v of Object.values(t.style)) take(v);
1557
+ if (t.props) for (const v of Object.values(t.props)) take(v);
1558
+ const tx = t.text;
1559
+ if (tx && typeof tx === "object" && "binding" in tx) {
1560
+ const b = (tx as { binding: Binding }).binding;
1561
+ if (b.kind === "template") {
1562
+ // Las expresiones son {signal} sin `kind` — siempre dinámicas.
1563
+ for (const e of b.expressions) acc.add(e.signal);
1564
+ } else {
1565
+ take(b);
1566
+ }
1567
+ }
1568
+ for (const c of t.children ?? []) collectTemplateFields(c, acc);
1569
+ return acc;
1570
+ }
1571
+
1572
+ /** ADR-0060 — diff de campos requeridos entre dos versiones de un item:
1573
+ * `fields` = valores nuevos/cambiados (signals desenvueltos por peek —
1574
+ * lectura no rastreada), `removed` = campos requeridos presentes antes
1575
+ * y ausentes ahora. `undefined` si nada relevante cambió. */
1576
+ function diffTemplateFields(
1577
+ prev: unknown,
1578
+ next: unknown,
1579
+ required: Set<string>,
1580
+ ): { fields: Record<string, unknown>; removed: string[] } | undefined {
1581
+ const p = (prev && typeof prev === "object" ? prev : {}) as Record<string, unknown>;
1582
+ const n = (next && typeof next === "object" ? next : {}) as Record<string, unknown>;
1583
+ const fields: Record<string, unknown> = {};
1584
+ const removed: string[] = [];
1585
+ for (const f of required) {
1586
+ const hasN = f in n;
1587
+ const nv = hasN ? n[f] : undefined;
1588
+ const pv = p[f];
1589
+ const uv = isSignal(nv) ? peekSignal(nv as Signal<unknown>) : nv;
1590
+ const up = isSignal(pv) ? peekSignal(pv as Signal<unknown>) : pv;
1591
+ if (!hasN) {
1592
+ if (f in p) removed.push(f);
1593
+ } else if (uv !== up) {
1594
+ fields[f] = uv;
1595
+ }
1596
+ }
1597
+ return removed.length || Object.keys(fields).length ? { fields, removed } : undefined;
1598
+ }
1599
+
1600
+ /** ADR-0061 (U06) — perfil de fila nativa: tipos que el inflador del
1601
+ * host puede construir (los demás — list anidada, scroll-view, canvas,
1602
+ * text-input, platform-view, desconocidos — perderían función o
1603
+ * listeners en silencio). */
1604
+ const NATIVE_ROW_TYPES: ReadonlySet<string> = new Set([
1605
+ "column", "row", "text", "image", "button", "switch", "slider",
1606
+ ]);
1607
+
1608
+ /** Keys estructurales de STRICT_FLEXBOX que el mini-flex NO expresa:
1609
+ * min/max, direction/wrap, shrink/basis, gaps por eje, posición y
1610
+ * zIndex — pasarían a ignorarse en silencio. El resto del vocabulario
1611
+ * (color, fondo, fuente, bordes, opacity, transforms, display,
1612
+ * overflow…) es visual: viaja por `applyRowStyles`, el mismo aplicador
1613
+ * que update-style del path JS — igual resultado, no es inelegibilidad.
1614
+ * (U14: la regla original rechazaba cualquier key fuera del mini-flex,
1615
+ * lo que hacía inelegible toda fila realista con estilo visual — el
1616
+ * carril "nativo" del A/B caía a JS sin que el intent lo delatara.) */
1617
+ const NATIVE_ROW_UNSUPPORTED_KEYS: ReadonlySet<string> = new Set([
1618
+ "minWidth", "maxWidth", "minHeight", "maxHeight",
1619
+ "flexDirection", "flexWrap", "flexShrink", "flexBasis",
1620
+ "rowGap", "columnGap",
1621
+ "position", "top", "right", "bottom", "left", "zIndex",
1622
+ ]);
1623
+
1624
+ /** Keys de dimensión que el mini-flex expresa (LinearLayout + params):
1625
+ * width/height, flexGrow→weight, gap, margins y paddings con override
1626
+ * longhand (ADR-0066) — justify/align además por gravity/spacers.
1627
+ * Solo números (px lógicos) o bindings son expresables; "%"/"auto"
1628
+ * declarados inelegibles (U12). justify/align no entran aquí: sus
1629
+ * valores son keywords válidas, no dimensiones. */
1630
+ const NATIVE_ROW_DIM_KEYS: ReadonlySet<string> = new Set([
1631
+ "width", "height", "flexGrow", "gap",
1632
+ "margin", "marginTop", "marginRight", "marginBottom", "marginLeft",
1633
+ "padding", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft",
1634
+ ]);
1635
+
1636
+ /** ADR-0061 (U06) — elegibilidad de la plantilla para el path nativo.
1637
+ * Devuelve el primer motivo de inelegibilidad, o `null`. Reglas:
1638
+ * - tipo de nodo dentro del perfil de fila del host;
1639
+ * - eventos cableables en fila: `press` universal, `change`→switch,
1640
+ * `input`→slider (cualquier otro moriría en silencio);
1641
+ * - bindings a signals de entorno (`ctx.signals`): el host solo
1642
+ * recibe campos del item — un `theme` global funcionaría en JS y
1643
+ * quedaría congelado en nativo;
1644
+ * - keys de layout STRICT_FLEXBOX que el mini-flex no expresa. */
1645
+ function nativeListEligibility(
1646
+ t: IRNode,
1647
+ env: Record<string, Signal<unknown>> | undefined,
1648
+ ): string | null {
1649
+ if (!NATIVE_ROW_TYPES.has(t.type)) {
1650
+ return `tipo '${t.type}' no soportado en fila nativa`;
1651
+ }
1652
+ if (t.events) {
1653
+ for (const name of Object.keys(t.events)) {
1654
+ const ok = name === "press"
1655
+ || (name === "change" && t.type === "switch")
1656
+ || (name === "input" && t.type === "slider");
1657
+ if (!ok) {
1658
+ return `evento '${name}' sobre '${t.type}' sin listener en fila nativa`;
1659
+ }
1660
+ }
1661
+ }
1662
+ const envBind = (v: unknown): string | null => {
1663
+ if (v && typeof v === "object") {
1664
+ const k = (v as { kind?: string }).kind;
1665
+ const s = (v as { signal?: unknown }).signal;
1666
+ if ((k === "signal" || k === "computed")
1667
+ && typeof s === "string" && env && s in env) {
1668
+ return `binding '${s}' es de entorno — el host solo ve campos del item`;
1669
+ }
1670
+ }
1671
+ return null;
1672
+ };
1673
+ if (t.style) {
1674
+ for (const [k, v] of Object.entries(t.style)) {
1675
+ if (NATIVE_ROW_UNSUPPORTED_KEYS.has(k)) {
1676
+ return `style '${k}' no expresable en el mini-flex de fila nativa`;
1677
+ }
1678
+ // U12: el mini-flex solo expresa dimensiones numéricas —
1679
+ // "50%"/"auto" en una dimensión llegarían como string y
1680
+ // caerían a un default silencioso. Se declara inelegible →
1681
+ // fallback JS con Yoga. justify/align SÍ son strings
1682
+ // legítimos (keywords), no dimensiones.
1683
+ if (NATIVE_ROW_DIM_KEYS.has(k)
1684
+ && v !== null && typeof v !== "number"
1685
+ && !(v && typeof v === "object"
1686
+ && "kind" in (v as Record<string, unknown>))) {
1687
+ return `style '${k}' con valor no numérico — el mini-flex no expresa %/auto`;
1688
+ }
1689
+ const r = envBind(v);
1690
+ if (r) return r;
1691
+ }
1692
+ }
1693
+ if (t.props) {
1694
+ for (const v of Object.values(t.props)) {
1695
+ const r = envBind(v);
1696
+ if (r) return r;
1697
+ }
1698
+ }
1699
+ const tx = t.text;
1700
+ if (tx && typeof tx === "object" && "binding" in tx) {
1701
+ const b = (tx as { binding: Binding }).binding;
1702
+ if (b.kind === "template") {
1703
+ for (const e of b.expressions) {
1704
+ if (env && e.signal in env) {
1705
+ return `binding '${e.signal}' es de entorno — el host solo ve campos del item`;
1706
+ }
1707
+ }
1708
+ } else {
1709
+ const r = envBind(b);
1710
+ if (r) return r;
1711
+ }
1712
+ }
1713
+ for (const c of t.children ?? []) {
1714
+ const r = nativeListEligibility(c, env);
1715
+ if (r) return r;
1716
+ }
1717
+ return null;
1718
+ }
1719
+
1720
+ /** ADR-0054 — path nativo de `list`: el host (cap "native-list") posee
1721
+ * ventana, recycle y bind; el reconciler emite la plantilla de fila una
1722
+ * vez y luego solo datos a nivel item. Las mutaciones del array viajan
1723
+ * como splice/move calculados por el MISMO diffKeyed que el path JS —
1724
+ * semántica keyed idéntica en ambos backends.
1725
+ * ADR-0060 (U05): los updates son PATCHES por key — un `effect` por item
1726
+ * lee solo los campos que la plantilla bindea; el runtime deduplica por
1727
+ * batch (N campos en una transacción → un solo `list-update` con todos
1728
+ * los cambiados) y el patch nunca serializa campos intactos.
1729
+ * `curKeys` es el estado espejo del array del adapter del host; las
1730
+ * posiciones llegan en `op.oldIndex`/`newIndex` desde el treap de
1731
+ * diffKeyed (válidas en el orden de emisión — sin indexOf por op). */
1732
+ function renderListNative(
1733
+ node: IRNode,
1734
+ listId: number,
1735
+ template: IRNode,
1736
+ itemsSignal: Signal<any[]>,
1737
+ keyFn: (item: any) => string,
1738
+ virt: { rowHeight: number; overscan?: number; scroll?: Binding } | undefined,
1739
+ ctx: ReconcilerContext,
1740
+ ) {
1741
+ const rowH = virt ? Math.max(1, virt.rowHeight) : 0;
1742
+ ctx.emit({ op: "set-list-template", id: listId, template, rowHeight: rowH });
1743
+ // ADR-0148: el widget nativo ES el scroller — la posición persistida
1744
+ // llega tras la plantilla (el host resuelve posición+offset por
1745
+ // rowHeight; un restore sin template no tiene geometría).
1746
+ emitScrollRestore(ctx, listId, node.id);
1747
+
1748
+ // El widget nativo ES el contenedor scrolleable — reporta el mismo
1749
+ // payload {y, vh, ty?} que el scroll-view del path JS. `data` llega
1750
+ // en el envelope (ADR-0047); se tolera también el objeto crudo.
1751
+ // ADR-0087 §scroll — scroll-worklet declarativo: el reconciler solo
1752
+ // registra el par (listId, worklet); el UIThreadRunner lo consume
1753
+ // como spec kind:"scroll" si el host tiene la cap. El dispose del
1754
+ // binding cubre el destroy del nodo (las lists no se reciclan).
1755
+ const fx = node.list?.scrollFx;
1756
+ if (fx) {
1757
+ uiScrollAdd(listId, fx as never);
1758
+ addDispose(ctx, listId, () => uiScrollDrop(listId));
1759
+ }
1760
+ // ADR-0087 §bind — row-worklet evaluado en el onBindViewHolder
1761
+ // nativo: mismo canal de registro que scrollFx; el runner lo emite
1762
+ // como spec kind:"bind".
1763
+ const rfx = node.list?.rowFx;
1764
+ if (rfx) {
1765
+ uiBindWkAdd(listId, rfx as never);
1766
+ addDispose(ctx, listId, () => uiBindWkDrop(listId));
1767
+ }
1768
+
1769
+ const sb = virt?.scroll;
1770
+ if (sb && (sb.kind === "signal" || sb.kind === "computed") && ctx.handlers) {
1771
+ const target = ctx.signals[sb.signal] as
1772
+ Signal<{ y: number; vh: number; ty?: number }> | undefined;
1773
+ if (target) {
1774
+ const bucket = ctx.scrollTrack.get(listId);
1775
+ if (bucket) {
1776
+ // ADR-0148: el tracker del nodo lista ya posee el attach
1777
+ // — la signal se alimenta desde el bucket compartido.
1778
+ bucket.feeds.push(target);
1779
+ addDispose(ctx, listId, () => {
1780
+ const i = bucket.feeds.indexOf(target);
1781
+ if (i >= 0) bucket.feeds.splice(i, 1);
1782
+ });
1783
+ } else {
1784
+ // El nodo lista ES la scroller en modo nativo: si la app
1785
+ // también ligó `events.scroll` al nodo, el attach interno lo
1786
+ // sobrescribe en el host (un solo handler por id+evento) —
1787
+ // el handler interno reenvía el mismo envelope a la app.
1788
+ const appScroll = node.events?.["scroll"];
1789
+ const appFn = appScroll ? ctx.handlers[appScroll.handler] : undefined;
1790
+ const hname = `__elur_vscroll:${listId}`;
1791
+ ctx.handlers[hname] = (e?: unknown) => {
1792
+ const env = (typeof e === "string" ? JSON.parse(e) : e) as
1793
+ { data?: { y?: number; vh?: number; ty?: number } } | undefined;
1794
+ const d = (env && env.data) ??
1795
+ (env as { y?: number; vh?: number; ty?: number } | undefined);
1796
+ target.value = { y: d?.y ?? 0, vh: d?.vh ?? 0, ty: d?.ty };
1797
+ appFn?.(env);
1798
+ };
1799
+ ctx.emit({
1800
+ op: "attach-event", id: listId, event: "scroll",
1801
+ handler: hname, class: "continuous",
1802
+ });
1803
+ addDispose(ctx, listId, () => {
1804
+ ctx.emit({ op: "detach-event", id: listId, event: "scroll" });
1805
+ if (ctx.handlers) delete ctx.handlers[hname];
1806
+ });
1807
+ }
1808
+ }
1809
+ }
1810
+
1811
+ // Solo los campos que la plantilla puede leer viajan al host y se
1812
+ // observan — un campo no ligado no se serializa ni suscribe (U05).
1813
+ const required = collectTemplateFields(template);
1814
+ const toItem = (item: any, key: string): NativeListItem => {
1815
+ const fields: Record<string, unknown> = {};
1816
+ if (item && typeof item === "object") {
1817
+ for (const fk of required) {
1818
+ const fv = (item as Record<string, unknown>)[fk];
1819
+ // peek, no .value: toItem corre dentro del effect de items
1820
+ // — un .value suscribiría el diff completo a cada signal
1821
+ // de campo (un like re-diferenciaría el array entero).
1822
+ if (fv !== undefined) {
1823
+ fields[fk] = isSignal(fv) ? peekSignal(fv as Signal<unknown>) : fv;
1824
+ }
1825
+ }
1826
+ }
1827
+ return { key, fields };
1828
+ };
1829
+
1830
+ const itemsByKey = new Map<string, any>();
1831
+ const fieldSubs = new Map<string, Array<() => void>>();
1832
+ // ADR-0060: UN effect por key sobre los signals requeridos. El
1833
+ // runtime deduplica suscripciones por batch — N campos escritos en
1834
+ // una transacción producen UN `list-update` con el patch exacto.
1835
+ // `last` recuerda lo enviado: el patch lleva solo lo que cambió.
1836
+ const subFields = (key: string, item: any) => {
1837
+ const deps: Array<[string, Signal<unknown>]> = [];
1838
+ if (item && typeof item === "object") {
1839
+ for (const f of required) {
1840
+ const v = (item as Record<string, unknown>)[f];
1841
+ if (isSignal(v)) deps.push([f, v as Signal<unknown>]);
1842
+ }
1843
+ }
1844
+ if (!deps.length) return;
1845
+ const last = new Map<string, unknown>();
1846
+ for (const [f, s] of deps) last.set(f, peekSignal(s));
1847
+ let first = true;
1848
+ const dispose = effect(() => {
1849
+ const patch: Record<string, unknown> = {};
1850
+ for (const [f, s] of deps) {
1851
+ const v = s.value; // lectura rastreada — suscribe
1852
+ if (!Object.is(v, last.get(f))) {
1853
+ patch[f] = v;
1854
+ last.set(f, v);
1855
+ }
1856
+ }
1857
+ if (first) { first = false; return; }
1858
+ if (Object.keys(patch).length) {
1859
+ ctx.emit({ op: "list-update", id: listId, key, fields: patch });
1860
+ }
1861
+ });
1862
+ fieldSubs.set(key, [dispose]);
1863
+ };
1864
+ const unsubFields = (key: string) => {
1865
+ const ds = fieldSubs.get(key);
1866
+ if (ds) { for (const d of ds) d(); fieldSubs.delete(key); }
1867
+ };
1868
+
1869
+ const initRaw = (itemsSignal.value as any[]) ?? [];
1870
+ const init = dedupeKeys(initRaw, initRaw.map(keyFn));
1871
+ // Espejo del array del host para el diff — solo keys; las posiciones
1872
+ // de cada op llegan en oldIndex/newIndex (calculadas por el treap de
1873
+ // diffKeyed), así no hay indexOf lineal por mutación.
1874
+ let curKeys: string[] = [];
1875
+ for (let i = 0; i < init.keys.length; i++) {
1876
+ curKeys.push(init.keys[i]);
1877
+ itemsByKey.set(init.keys[i], init.items[i]);
1878
+ subFields(init.keys[i], init.items[i]);
1879
+ }
1880
+ ctx.emit({
1881
+ op: "set-list-items", id: listId,
1882
+ items: init.items.map((it, i) => toItem(it, init.keys[i])),
1883
+ });
1884
+
1885
+ const dispose = effect(() => {
1886
+ const rawItems = (itemsSignal.value as any[]) ?? [];
1887
+ const deduped = dedupeKeys(rawItems, rawItems.map(keyFn));
1888
+ const prevItems = new Map(itemsByKey);
1889
+ const diffOps = diffKeyed(curKeys, deduped.keys, deduped.items);
1890
+ for (const op of diffOps) {
1891
+ if (op.type === "remove") {
1892
+ ctx.emit({
1893
+ op: "list-splice", id: listId,
1894
+ index: op.oldIndex, removeCount: 1,
1895
+ });
1896
+ itemsByKey.delete(op.key);
1897
+ unsubFields(op.key);
1898
+ } else if (op.type === "create") {
1899
+ itemsByKey.set(op.key, op.item);
1900
+ subFields(op.key, op.item);
1901
+ ctx.emit({
1902
+ op: "list-splice", id: listId,
1903
+ index: op.newIndex, removeCount: 0,
1904
+ items: [toItem(op.item, op.key)],
1905
+ });
1906
+ } else if (op.type === "move") {
1907
+ ctx.emit({
1908
+ op: "list-move", id: listId, from: op.oldIndex, to: op.newIndex,
1909
+ });
1910
+ }
1911
+ }
1912
+ // El array del host ya quedó transformado por las ops — el espejo
1913
+ // del próximo diff es deduped.keys (sin splice por op = O(n²)).
1914
+ curKeys = deduped.keys;
1915
+ // Refresh por key (F04): misma key con objeto distinto → patch
1916
+ // list-update de sus fields (ADR-0060: solo cambiados + removed
1917
+ // explícito); los subs se rearman por si el item nuevo trae
1918
+ // otros signals.
1919
+ for (let i = 0; i < deduped.keys.length; i++) {
1920
+ const key = deduped.keys[i];
1921
+ const prev = prevItems.get(key);
1922
+ const next = deduped.items[i];
1923
+ if (prev === undefined || prev === next) continue;
1924
+ itemsByKey.set(key, next);
1925
+ unsubFields(key);
1926
+ subFields(key, next);
1927
+ const patch = diffTemplateFields(prev, next, required);
1928
+ if (patch) {
1929
+ ctx.emit({
1930
+ op: "list-update", id: listId, key,
1931
+ fields: patch.fields, removed: patch.removed,
1932
+ });
1933
+ }
1934
+ }
1935
+ });
1936
+ addDispose(ctx, listId, dispose);
1937
+ addDispose(ctx, listId, () => {
1938
+ for (const key of [...fieldSubs.keys()]) unsubFields(key);
1939
+ });
1940
+ }
1941
+
1942
+ /** Estructura capturada de una fila: ids nativos + firma por nodo en
1943
+ * orden DFS. El pool estructural (ADR-0033) la usa para reciclar el
1944
+ * subárbol de views de una fila detachada sobre un item distinto — el
1945
+ * patrón de reciclaje por tipo de FlashList/RecyclerView adaptado al
1946
+ * modelo keyed: las views no se recrean, solo se re-bindean signals y
1947
+ * handlers.
1948
+ * ADR-0057 (U03): la firma incluye TODAS las claves que el render aplica
1949
+ * sobre la view — style, props, eventos y presencia de text. Reciclar
1950
+ * exige firmas idénticas por posición: todo estado declarado se
1951
+ * re-emite en el rebind y nada declarado puede quedar stale. Filas con
1952
+ * la misma forma de tipos pero keys aplicadas distintas (A con
1953
+ * `press`/`bg`, B sin ellos) no son compatibles: se destruyen, no se
1954
+ * reciclan. El estado efímero (foco, selección, checked, scroll,
1955
+ * animaciones) lo limpia la op `reset-node` emitida por nodo. */
1956
+ type RowStruct = { ids: number[]; sigs: string[] };
1957
+
1958
+ /** Firma de un nodo para compatibilidad de reciclaje: tipo + keys que el
1959
+ * render APLICA realmente. Un binding `{kind:"signal"}` cuyo signal no
1960
+ * resuelve en `signals` no emite nada — no cuenta como aplicada (dos
1961
+ * items con campos distintos producen firmas distintas aunque el IR
1962
+ * del template sea el mismo). */
1963
+ function rowNodeSig(node: IRNode, signals: Record<string, unknown>): string {
1964
+ const pick = (obj: Record<string, unknown> | undefined): string => {
1965
+ if (!obj) return "";
1966
+ const keys: string[] = [];
1967
+ for (const k of Object.keys(obj)) {
1968
+ const v = obj[k] as { kind?: string; signal?: string } | null;
1969
+ if (v && typeof v === "object" && v.kind === "signal") {
1970
+ if (v.signal && signals[v.signal] !== undefined) keys.push(k);
1971
+ } else {
1972
+ keys.push(k);
1973
+ }
1974
+ }
1975
+ return keys.sort().join(",");
1976
+ };
1977
+ return node.type +
1978
+ "|s:" + pick(node.style as Record<string, unknown> | undefined) +
1979
+ "|p:" + pick(node.props) +
1980
+ "|e:" + (node.events ? Object.keys(node.events).sort().join(",") : "") +
1981
+ (node.text !== undefined ? "|t" : "");
1982
+ }
1983
+
1984
+ /** Firmas del subárbol IR en orden DFS preorder — mismo orden que los
1985
+ * create-node emitidos por renderNode. Una `list` o `platform-view`
1986
+ * dentro de la fila la hace no reciclable (devuelve false): la primera
1987
+ * posee su propio estado de ventana y la segunda es un widget opaco. */
1988
+ function collectRowSigs(
1989
+ node: IRNode, signals: Record<string, unknown>, out: string[],
1990
+ ): boolean {
1991
+ if (node.type === "list" || node.type === "platform-view") return false;
1992
+ out.push(rowNodeSig(node, signals));
1993
+ if (node.children) {
1994
+ for (const c of node.children) {
1995
+ if (!collectRowSigs(c, signals, out)) return false;
1996
+ }
1997
+ }
1998
+ return true;
1999
+ }
2000
+
2001
+ /** Renderiza un item de lista. Dos modos (ADR-0014):
2002
+ * - IRNode template: merge de itemSignals (campos → signals por nombre).
2003
+ * - factory(item) → UIResult: cada fila renderiza su propio ui`` — sus
2004
+ * signals se mergean al scope y sus handlers al registry compartido,
2005
+ * así un @press de la fila cierra sobre el item real.
2006
+ * Retorna el ID real del nodo raíz del item y, en template-mode, los
2007
+ * signals por campo — el diff los usa para refrescar datos cuando la
2008
+ * key sobrevive con otro objeto (F04).
2009
+ * Con `recycle` (ADR-0033): si el IR del item nuevo tiene exactamente
2010
+ * la misma estructura de tipos que la fila aparcada, el render se hace
2011
+ * sobre sus ids vivos (remap — sin create-node/insert ni scopes nuevos)
2012
+ * tras disponer sus effects de binding viejos; el resultado es un
2013
+ * rebind, no una recreación. Estructura distinta → render normal y
2014
+ * `recycled=false` para que el llamador destruya la aparcada. */
2015
+ function renderListItem(
2016
+ template: IRNode | ListItemFactory,
2017
+ itemTempId: number,
2018
+ parentId: number,
2019
+ index: number,
2020
+ item: any,
2021
+ ctx: ReconcilerContext,
2022
+ recycle?: RowStruct,
2023
+ itemKey?: string,
2024
+ ): {
2025
+ id: number;
2026
+ fields?: Record<string, Signal<unknown>>;
2027
+ struct?: RowStruct;
2028
+ recycled: boolean;
2029
+ } {
2030
+ const savedSignals = ctx.signals;
2031
+ const savedKeyFns = ctx.keyFns;
2032
+ const savedFactories = ctx.factories;
2033
+
2034
+ let root: IRNode;
2035
+ let factoryHandlers: string[] | undefined;
2036
+ let itemFields: Record<string, Signal<unknown>> | undefined;
2037
+ let rowOwner: Owner | undefined;
2038
+ if (typeof template === "function") {
2039
+ rowOwner = new Owner();
2040
+ const result = runWithOwner(rowOwner, () => template(item));
2041
+ ctx.signals = { ...ctx.signals, ...result.signals };
2042
+ // Registries por fila con save/restore (como ctx.signals): un
2043
+ // repeat() anidado dentro de la fila resuelve SUS factories y
2044
+ // keyFns aquí, sin contaminar el scope de las demás filas (V05).
2045
+ if (result.keyFns) ctx.keyFns = { ...ctx.keyFns, ...result.keyFns };
2046
+ if (result.factories) ctx.factories = { ...ctx.factories, ...result.factories };
2047
+ if (ctx.handlers) {
2048
+ factoryHandlers = Object.keys(result.handlers);
2049
+ Object.assign(ctx.handlers, result.handlers);
2050
+ }
2051
+ root = result.document.root;
2052
+ } else {
2053
+ // itemSignals: campos del item → signals REALES por nombre (F04 —
2054
+ // antes eran {value} falsos: no eran reactivos y no se podían
2055
+ // refrescar). Un signal del propio item pasa directo — sus
2056
+ // updates por campo fluyen a la fila.
2057
+ itemFields = {};
2058
+ if (item && typeof item === "object") {
2059
+ for (const [key, value] of Object.entries(item)) {
2060
+ itemFields[key] = isSignal(value)
2061
+ ? (value as Signal<unknown>)
2062
+ : signal(value);
2063
+ }
2064
+ }
2065
+ ctx.signals = { ...ctx.signals, ...itemFields };
2066
+ root = template;
2067
+ }
2068
+
2069
+ // Decisión de reciclaje (ADR-0057): la fila aparcada sirve solo si
2070
+ // la firma por nodo — tipo + keys que el render aplica — coincide
2071
+ // EXACTAMENTE. Todo lo declarado se re-emite en el rebind, así nada
2072
+ // puede quedar stale. Misma forma de tipos con keys distintas (A con
2073
+ // press/bg → B sin ellos) no es compatible: destroy, no recycle.
2074
+ // Una list/platform-view dentro de la fila la hace no reciclable.
2075
+ const newSigs: string[] = [];
2076
+ const shapeOk = collectRowSigs(root, ctx.signals, newSigs);
2077
+ let remapIds: number[] | undefined;
2078
+ if (recycle && shapeOk && newSigs.length === recycle.sigs.length) {
2079
+ let same = true;
2080
+ for (let i = 0; i < newSigs.length; i++) {
2081
+ if (newSigs[i] !== recycle.sigs[i]) { same = false; break; }
2082
+ }
2083
+ if (same) remapIds = recycle.ids;
2084
+ }
2085
+
2086
+ let struct: RowStruct | undefined;
2087
+ let actualId: number;
2088
+ const rootWithId: IRNode = { ...root, id: root.id ?? `item-${itemTempId}` };
2089
+ // ADR-0054: en template-mode los attach-event de la fila llevan la key
2090
+ // del item — el handler compartido la recibe en `data` del envelope.
2091
+ // Las filas factory cierran sobre el item en sus closures — sin stamp.
2092
+ const prevPayload = ctx.rowEventPayload;
2093
+ if (typeof template !== "function") {
2094
+ ctx.rowEventPayload = JSON.stringify({ key: itemKey ?? "" });
2095
+ }
2096
+ try {
2097
+ if (remapIds) {
2098
+ // Rebind: matar las suscripciones viejas (las views sobreviven),
2099
+ // luego re-renderizar sobre los mismos ids.
2100
+ for (const nid of remapIds) {
2101
+ const ds = ctx.bindDisposes.get(nid);
2102
+ if (ds) {
2103
+ for (const d of ds) d();
2104
+ ctx.bindDisposes.delete(nid);
2105
+ }
2106
+ const wa = ctx.workletAnims.get(nid);
2107
+ if (wa) { wa.cancel(); ctx.workletAnims.delete(nid); }
2108
+ }
2109
+ // ADR-0057 (U03): el estado efímero es por item, no por
2110
+ // holder — reset-node limpia foco/selección/checked/scroll/
2111
+ // animaciones antes de re-emitir los bindings del item nuevo.
2112
+ for (const nid of remapIds) ctx.emit({ op: "reset-node", id: nid });
2113
+ ctx.remapIds = remapIds;
2114
+ ctx.remapPos = 0;
2115
+ try {
2116
+ actualId = renderNode(rootWithId, parentId, index, ctx);
2117
+ } finally {
2118
+ ctx.remapIds = undefined;
2119
+ ctx.remapPos = 0;
2120
+ }
2121
+ // El único attach estructural: la raíz de la fila vuelve a la lista.
2122
+ ctx.emit({ op: "insert-child", parentId, childId: actualId, index });
2123
+ // Los handler names viejos del registry mueren — apuntaban a
2124
+ // closures del item anterior.
2125
+ const old = ctx.nodeHandlers.get(actualId);
2126
+ if (old && ctx.handlers) for (const n of old) delete ctx.handlers[n];
2127
+ struct = recycle;
2128
+ } else {
2129
+ // Captura de estructura para el pool: ids nativos en orden
2130
+ // DFS de create + firmas del IR (mismo orden preorder).
2131
+ const ids: number[] = [];
2132
+ const origEmit = ctx.emit;
2133
+ ctx.emit = (op) => {
2134
+ if (op.op === "create-node") ids.push(op.id);
2135
+ origEmit(op);
2136
+ };
2137
+ try {
2138
+ actualId = renderNode(rootWithId, parentId, index, ctx);
2139
+ } finally {
2140
+ ctx.emit = origEmit;
2141
+ }
2142
+ if (shapeOk && ids.length === newSigs.length && ids.length > 0) {
2143
+ struct = { ids, sigs: newSigs };
2144
+ }
2145
+ }
2146
+ } finally {
2147
+ ctx.rowEventPayload = prevPayload;
2148
+ }
2149
+ if (factoryHandlers?.length) ctx.nodeHandlers.set(actualId, factoryHandlers);
2150
+ if (rowOwner) {
2151
+ const ro = rowOwner;
2152
+ trackBinding(ctx, actualId, () => ro.dispose());
2153
+ }
2154
+ ctx.signals = savedSignals;
2155
+ ctx.keyFns = savedKeyFns;
2156
+ ctx.factories = savedFactories;
2157
+ return { id: actualId, fields: itemFields, struct, recycled: remapIds !== undefined };
2158
+ }
2159
+
2160
+
2161
+
2162
+ // Render — walk del IR → emite ops del Display List
2163
+
2164
+ function renderNode(
2165
+ node: IRNode,
2166
+ parentId: number | undefined,
2167
+ index: number,
2168
+ ctx: ReconcilerContext,
2169
+ ): number {
2170
+ // Nodos sin id de autor: la key se deriva de un id reservado del
2171
+ // contador monotónico del mapa — nunca del size (R1.4, tras un
2172
+ // destroy el size decrece y la key colisionaría con una viva).
2173
+ // Con remap activo (pool estructural, ADR-0033) el id sale de la
2174
+ // cola del subárbol aparcado: ni create, ni scope, ni trackChild —
2175
+ // la view nativa ya existe; solo se re-emiten bindings y eventos.
2176
+ const remap = ctx.remapIds;
2177
+ let id: number;
2178
+ let irKey: string;
2179
+ if (remap) {
2180
+ id = remap[ctx.remapPos++];
2181
+ irKey = ctx.nodeIrIds.get(id) ?? `auto-${id}`;
2182
+ } else if (node.id) {
2183
+ irKey = ctx.idPrefix + node.id;
2184
+ id = toId(ctx.idMap, irKey);
2185
+ } else {
2186
+ id = allocId(ctx.idMap);
2187
+ irKey = `auto-${id}`;
2188
+ ctx.idMap.set(irKey, id);
2189
+ }
2190
+ if (!remap) ctx.nodeIrIds.set(id, irKey);
2191
+
2192
+ // Scope del nodo (R1.1): hijo del scope del padre — el padre ya tiene
2193
+ // scope porque los hijos se renderizan tras esta línea en el padre.
2194
+ // Su teardown libera recursos por nodo al disponer (postorder).
2195
+ // En remap el scope ya vive (la fila aparcada conserva su ciclo).
2196
+ if (!remap) {
2197
+ const nodeScope = new Scope(
2198
+ parentId !== undefined ? scopeOf(ctx, parentId) : ctx.rootScope,
2199
+ id,
2200
+ );
2201
+ ctx.nodeScope.set(id, nodeScope);
2202
+ nodeScope.addDispose(() => teardownNode(id, ctx));
2203
+ }
2204
+
2205
+ // platform-view resuelve módulo nativo por factory — op dedicada (ABI 14).
2206
+ // Selectores: los campos canónicos del schema son node.module/node.view
2207
+ // (F12 — un IR manual con ellos producía selectores vacíos porque solo
2208
+ // se leían de props). props.module/view queda como fallback: es donde
2209
+ // los deposita la interpolación de atributos de ui``.
2210
+ const isPlatformView = node.type === "platform-view";
2211
+ if (isPlatformView) {
2212
+ const { module: propModule, view: propView, ...rest } =
2213
+ (node.props ?? {}) as Record<string, unknown>;
2214
+ const module = node.module ?? propModule;
2215
+ const view = node.view ?? propView;
2216
+ // solo estáticos no-binding al create; el resto llega por update-*-props
2217
+ const statics = Object.fromEntries(
2218
+ Object.entries(rest).filter(([, v]) => !(v && typeof v === "object" && "kind" in v)),
2219
+ );
2220
+ if (!remap) ctx.emit({
2221
+ op: "create-platform-view", id,
2222
+ module: String(module ?? ""),
2223
+ view: String(view ?? ""),
2224
+ props: statics,
2225
+ });
2226
+ } else if (!remap) {
2227
+ // ADR-0129: un nodo con `list` se reporta como type "list" — sus
2228
+ // hijas las gestiona el diff keyed (display:contents si no es
2229
+ // virtual, absolutas si lo es), así que el tipo propio de layout
2230
+ // no se usa y el marcador es lo que distingue filas de lista
2231
+ // (content-visibility en web/SSR, contenedor sin clip en host).
2232
+ ctx.emit({ op: "create-node", id, type: node.list ? "list" : node.type });
2233
+ }
2234
+
2235
+ // Track parent para detach e hijos para destroy en cascada
2236
+ if (parentId !== undefined && !remap) {
2237
+ trackChild(ctx, parentId, id);
2238
+ }
2239
+
2240
+ // Estilo — valores con binding {kind:"signal"} → update-style
2241
+ // reactivo parcial por clave (mismo mecanismo que props, §ADR-0023
2242
+ // extiende la semántica: cualquier StyleKey puede ser reactiva).
2243
+ const nodeStyle = resolveStyle(node, parentId, id, ctx);
2244
+ if (nodeStyle) {
2245
+ const staticStyle: Record<string, unknown> = {};
2246
+ for (const [key, value] of Object.entries(nodeStyle)) {
2247
+ const b = value as { kind?: string; signal?: string } | null;
2248
+ if (b && typeof b === "object" && b.kind === "signal" && b.signal) {
2249
+ const sig = ctx.signals[b.signal];
2250
+ if (sig) {
2251
+ staticStyle[key] = sig.value;
2252
+ const styleKey = key;
2253
+ const nodeId = id;
2254
+ // `ctx.signals` se restaura al scope padre al terminar el
2255
+ // item de lista — el effect usa `sig` capturado, no el mapa.
2256
+ const dispose = effect(() => {
2257
+ sig.value; // suscribirse
2258
+ emitStyle(ctx, nodeId, { [styleKey]: sig.value });
2259
+ });
2260
+ trackBinding(ctx, id, dispose);
2261
+ // ADR-0087: clave compositor ligada a signal → elegible
2262
+ // para writes del UIThreadRunner (directo a la View).
2263
+ if (isUiStyleKey(key)) {
2264
+ uiBindAdd(b.signal, nodeId, key);
2265
+ const sigName = b.signal;
2266
+ trackBinding(ctx, nodeId, () => {
2267
+ uiBindDrop(sigName, nodeId, styleKey);
2268
+ });
2269
+ }
2270
+ }
2271
+ } else {
2272
+ staticStyle[key] = value;
2273
+ }
2274
+ }
2275
+ if (Object.keys(staticStyle).length > 0) {
2276
+ emitStyle(ctx, id, staticStyle);
2277
+ }
2278
+ }
2279
+
2280
+ // ADR-0087 §gestures — drag-worklet declarativo sobre este nodo:
2281
+ // el reconciler solo registra el par (nodeId, worklet); el
2282
+ // UIThreadRunner lo consume como spec kind:"drag" si el host
2283
+ // tiene la cap uiWorklet. El dispose del scope cubre el destroy.
2284
+ // Va DESPUÉS del bloque de estilo: emitFeed recolecta los binds
2285
+ // compositor de las signals del worklet en el momento del registro
2286
+ // (emit síncrono vía uiGestureOnChange) — las del propio nodo solo
2287
+ // existen una vez procesado node.style.
2288
+ if (node.dragFx) {
2289
+ const dfx = node.dragFx;
2290
+ uiGestureAdd(id, dfx as never);
2291
+ addDispose(ctx, id, () => uiGestureDrop(id));
2292
+ }
2293
+
2294
+ // Props (placeholder, value, etc.) — soporte para text-input y otros
2295
+ if (node.props) {
2296
+ const staticProps: Record<string, unknown> = {};
2297
+ // ADR-0108: claves del vocabulario semántico (src/ir/semantics.ts)
2298
+ // viajan por update-semantics, no por update-props — el backend
2299
+ // materializa a11y sin cribar el saco de props arbitrarias.
2300
+ const staticSemantics: Record<string, unknown> = {};
2301
+ for (const [key, value] of Object.entries(node.props)) {
2302
+ // module/view son selectores de factory, no props del view
2303
+ if (isPlatformView && (key === "module" || key === "view")) continue;
2304
+ // ADR-0179: `shortcut` viaja normalizado en el payload del
2305
+ // attach-event `shortcut` — no es estado del view.
2306
+ if (key === "shortcut") continue;
2307
+ if (key === "ref" && isNodeRef(value)) {
2308
+ const refObj = value;
2309
+ const nodeId = id;
2310
+ refObj._bind({ numericId: nodeId, emit: ctx.emit });
2311
+ addDispose(ctx, nodeId, () => refObj._bind(null));
2312
+ continue;
2313
+ }
2314
+ if (key === "safeArea" && value) {
2315
+ const edges = Array.isArray(value)
2316
+ ? new Set(value.map(String))
2317
+ : new Set(["top", "right", "bottom", "left"]);
2318
+ const nodeId = id;
2319
+ const disposeSafe = effect(() => {
2320
+ const ins = windowInsets.value;
2321
+ const patch: Record<string, unknown> = {};
2322
+ if (edges.has("top")) patch.paddingTop = ins.top;
2323
+ if (edges.has("right")) patch.paddingRight = ins.right;
2324
+ if (edges.has("bottom")) patch.paddingBottom = ins.bottom;
2325
+ if (edges.has("left")) patch.paddingLeft = ins.left;
2326
+ emitStyle(ctx, nodeId, patch);
2327
+ });
2328
+ trackBinding(ctx, id, disposeSafe);
2329
+ continue;
2330
+ }
2331
+ if (key === "keyboardAvoiding" && value) {
2332
+ const nodeId = id;
2333
+ const disposeKb = effect(() => {
2334
+ const ime = windowInsets.value.imeBottom;
2335
+ emitStyle(ctx, nodeId, { paddingBottom: ime });
2336
+ });
2337
+ trackBinding(ctx, id, disposeKb);
2338
+ continue;
2339
+ }
2340
+ const semantic = !isPlatformView && isSemanticProp(key);
2341
+ const bucket = semantic ? staticSemantics : staticProps;
2342
+ // ADR-0086/R4.6: una prop fuera del vocabulario portátil o
2343
+ // no soportada en algún backend se elimina con warn — web la
2344
+ // aplicaría por passthrough DOM y Android la ignoraría en
2345
+ // silencio. Platform-views exentas: su vocabulario lo define
2346
+ // el módulo (ADR-0080), no la matriz portátil.
2347
+ if (ctx.strictProps && !isPlatformView && !isPortableProp(key) && !semantic) {
2348
+ if (typeof console !== "undefined" && console.warn) {
2349
+ console.warn(
2350
+ `[elur] strictProps: prop '${key}' no portable — eliminada (nodo ${id})`,
2351
+ );
2352
+ }
2353
+ continue;
2354
+ }
2355
+ // ADR-0131: stateStyle admite solo claves visuales — en
2356
+ // strictStyles las de layout se eliminan con warn (un estado
2357
+ // nunca puede provocar re-layout, ni siquiera por bug).
2358
+ if (key === "stateStyle" && value && typeof value === "object" &&
2359
+ ctx.strictStyles) {
2360
+ const spec = value as Record<string, Record<string, unknown>>;
2361
+ for (const st of Object.keys(spec)) {
2362
+ const sub = spec[st];
2363
+ if (!sub || typeof sub !== "object") continue;
2364
+ for (const sk of Object.keys(sub)) {
2365
+ if (!STATE_STYLE_KEYS.has(sk)) {
2366
+ if (typeof console !== "undefined" && console.warn) {
2367
+ console.warn(
2368
+ `[elur] strictStyles: stateStyle.${st}.${sk} ` +
2369
+ `no es clave visual — eliminada (nodo ${id})`,
2370
+ );
2371
+ }
2372
+ delete sub[sk];
2373
+ }
2374
+ }
2375
+ }
2376
+ }
2377
+ // Si es un binding, resolver al valor actual
2378
+ if (value && typeof value === "object" && "kind" in value) {
2379
+ const binding = value as any;
2380
+ if (binding.kind === "signal") {
2381
+ const sig = ctx.signals[binding.signal];
2382
+ if (sig) {
2383
+ bucket[key] = sig.value;
2384
+ // Suscripción reactiva — `sig` capturado (no el mapa:
2385
+ // tras renderListItem el scope vuelve al padre).
2386
+ const propKey = key;
2387
+ const nodeId = id;
2388
+ const dispose = effect(() => {
2389
+ sig.value; // suscribirse
2390
+ ctx.emit(isPlatformView
2391
+ ? { op: "update-platform-view-props", id: nodeId, changedProps: { [propKey]: sig.value } }
2392
+ : semantic
2393
+ ? { op: "update-semantics", id: nodeId, semantics: { [propKey]: sig.value } }
2394
+ : { op: "update-props", id: nodeId, changedProps: { [propKey]: sig.value } });
2395
+ });
2396
+ trackBinding(ctx, id, dispose);
2397
+ }
2398
+ }
2399
+ } else if (key === "animate" && isWorkletAnimate(value)) {
2400
+ // ADR-0025: {worklet, timing} se conduce local con el
2401
+ // runner instalado; nunca se emite por update-props.
2402
+ const handle = workletDriver?.(value.worklet, value.timing);
2403
+ if (handle) {
2404
+ // finished rechaza en cancel — el reconciler posee el
2405
+ // handle, nadie más observa la promesa.
2406
+ handle.finished?.catch(() => { });
2407
+ ctx.workletAnims.set(id, handle);
2408
+ }
2409
+ } else if (key === "spans") {
2410
+ // ADR-0147: estructura de rangos validada aquí (orden,
2411
+ // anidación, claves de estilo). Los backends clampean al
2412
+ // texto vigente — puede ser binding más corto que los
2413
+ // rangos. null/[] = retirada explícita de la prop.
2414
+ const clean = validateTextSpans(value);
2415
+ if (clean) {
2416
+ bucket[key] = clean;
2417
+ } else if (value == null ||
2418
+ (Array.isArray(value) && value.length === 0)) {
2419
+ bucket[key] = null;
2420
+ } else if (typeof console !== "undefined" && console.warn) {
2421
+ console.warn(
2422
+ `[elur] spans inválidos — prop descartada (nodo ${id})`,
2423
+ );
2424
+ }
2425
+ } else {
2426
+ bucket[key] = value;
2427
+ }
2428
+ }
2429
+ if (Object.keys(staticProps).length > 0) {
2430
+ ctx.emit(isPlatformView
2431
+ ? { op: "update-platform-view-props", id, changedProps: staticProps }
2432
+ : { op: "update-props", id, changedProps: staticProps });
2433
+ }
2434
+ if (Object.keys(staticSemantics).length > 0) {
2435
+ ctx.emit({ op: "update-semantics", id, semantics: staticSemantics });
2436
+ }
2437
+ if (
2438
+ !isPlatformView &&
2439
+ (node.type === "scroll-view" || (node.type === "list" && !ctx.nativeList)) &&
2440
+ node.style?.flexDirection === undefined &&
2441
+ (node.props?.horizontal !== undefined || node.props?.inverted !== undefined)
2442
+ ) {
2443
+ const valOf = (raw: unknown): boolean => {
2444
+ if (raw && typeof raw === "object" && "kind" in raw) {
2445
+ const b = raw as { kind: string; signal?: string };
2446
+ if (b.kind === "signal" && b.signal) {
2447
+ return Boolean(ctx.signals[b.signal]?.value);
2448
+ }
2449
+ }
2450
+ return Boolean(raw);
2451
+ };
2452
+ const nodeId = id;
2453
+ const disposeAxis = effect(() => {
2454
+ const h = valOf(node.props?.horizontal);
2455
+ const inv = valOf(node.props?.inverted);
2456
+ emitStyle(ctx, nodeId, {
2457
+ flexDirection: h
2458
+ ? (inv ? "row-reverse" : "row")
2459
+ : (inv ? "column-reverse" : "column"),
2460
+ });
2461
+ });
2462
+ trackBinding(ctx, id, disposeAxis);
2463
+ }
2464
+ }
2465
+
2466
+ // ADR-0123 — `renderPolicy` declarado en un `canvas` viaja como prop
2467
+ // para que el host elija superficie (views | Skia raster). "custom"
2468
+ // sin cap `skia` degrada con warn — el prop no viaja y el host queda
2469
+ // en su impl views por defecto.
2470
+ if (!isPlatformView && node.type === "canvas" && node.renderPolicy !== undefined) {
2471
+ if (node.renderPolicy === "custom" && !ctx.skia) {
2472
+ if (typeof console !== "undefined" && console.warn) {
2473
+ console.warn(
2474
+ "[elur] canvas renderPolicy='custom' sin cap skia — " +
2475
+ "degrada a Platform Views",
2476
+ );
2477
+ }
2478
+ } else {
2479
+ ctx.emit({ op: "update-props", id, changedProps: { renderPolicy: node.renderPolicy } });
2480
+ }
2481
+ }
2482
+
2483
+ // Texto: estático o reactivo
2484
+ if (typeof node.text === "string") {
2485
+ ctx.emit({ op: "update-text", id, value: node.text });
2486
+ } else if (node.text && typeof node.text === "object") {
2487
+ // Valor inicial (render pass)
2488
+ const initial = resolveText(node.text, ctx.signals);
2489
+ ctx.emit({ op: "update-text", id, value: initial });
2490
+
2491
+ // Suscripción reactiva (update pass)
2492
+ // ADR-0002: el effect ejecuta síncrono y emite, pero NO flushea.
2493
+ // El flush es responsabilidad del llamador al final del walk.
2494
+ // `scope` captura el mapa activo al renderizar — en items de lista
2495
+ // `ctx.signals` vuelve al scope padre al terminar renderListItem y
2496
+ // el effect no encontraría las signals del item.
2497
+ //
2498
+ // UN solo effect por nodo de texto (F04): con M bindings se
2499
+ // creaban M effects y cada uno re-emitía el texto COMPLETO — un
2500
+ // batch() que cambiaba 2 signals producía 2 update-text idénticas.
2501
+ // El effect se suscribe a todas las signals referenciadas (batch
2502
+ // lo corre una vez por flush) y solo emite si el valor resuelto
2503
+ // cambió respecto al último emitido.
2504
+ const scope = ctx.signals;
2505
+ const referenced = collectReferencedSignals(node.text.binding);
2506
+ if (referenced.length > 0) {
2507
+ let last = initial;
2508
+ const dispose = effect(() => {
2509
+ for (const name of referenced) scope[name]?.value; // suscribirse
2510
+ const v = resolveText(node.text, scope);
2511
+ if (v !== last) {
2512
+ last = v;
2513
+ ctx.emit({ op: "update-text", id, value: v });
2514
+ }
2515
+ });
2516
+ trackBinding(ctx, id, dispose);
2517
+ }
2518
+ }
2519
+
2520
+ // ADR-0148 — restore/tracking de scroll: scrolleable nombrado con
2521
+ // sink de posiciones → tracker interno (posee el attach "scroll";
2522
+ // el host guarda un solo handler por evento — el loop de abajo lo
2523
+ // salta y el tracker reenvía el envelope al handler de la app).
2524
+ // En remap (pool de filas) no hay scope nuevo — se omite.
2525
+ const isScrollable = node.type === "scroll-view" || node.type === "list";
2526
+ const trackedScroll = !remap && isScrollable && !!node.id &&
2527
+ !!ctx.scrollPositions && !!ctx.handlers;
2528
+ if (trackedScroll) {
2529
+ installScrollTracker(ctx, id, node.id!, node.events?.["scroll"]);
2530
+ }
2531
+ const endReachedBinding = !remap && isScrollable ? node.events?.["endReached"] : undefined;
2532
+ if (endReachedBinding && ctx.handlers) {
2533
+ const endFn = ctx.handlers[endReachedBinding.handler];
2534
+ if (typeof endFn === "function") {
2535
+ const readProp = (raw: unknown): unknown => {
2536
+ if (raw && typeof raw === "object" && "kind" in raw) {
2537
+ const b = raw as { kind: string; signal?: string };
2538
+ if (b.kind === "signal" && b.signal) {
2539
+ return ctx.signals[b.signal]?.peek();
2540
+ }
2541
+ }
2542
+ return raw;
2543
+ };
2544
+ const targetScrollerId =
2545
+ node.type === "list" && !ctx.nativeList && ctx.scrollerStack.length > 0
2546
+ ? ctx.scrollerStack[ctx.scrollerStack.length - 1]
2547
+ : id;
2548
+ const hub = ensureScrollHub(
2549
+ ctx,
2550
+ targetScrollerId,
2551
+ targetScrollerId === id ? node.id : undefined,
2552
+ targetScrollerId === id ? node.events?.["scroll"] : undefined,
2553
+ );
2554
+ if (hub) {
2555
+ let lastFiredContent = -1;
2556
+ const onScrollMetric = (p: {
2557
+ y: number; x: number; vh: number; vw: number; ch: number; cw: number;
2558
+ }) => {
2559
+ const horiz = Boolean(readProp(node.props?.["horizontal"]));
2560
+ const rawThr = Number(readProp(node.props?.["endReachedThreshold"]) ?? 0.8);
2561
+ const thr = Number.isFinite(rawThr) && rawThr > 0 ? Math.min(1, rawThr) : 0.8;
2562
+ const pos = horiz ? p.x : p.y;
2563
+ const view = horiz ? p.vw : p.vh;
2564
+ const content = horiz ? p.cw : p.ch;
2565
+ if (content <= 0 || view <= 0) return;
2566
+ const reached = pos + view >= content * thr;
2567
+ if (reached) {
2568
+ if (lastFiredContent !== content) {
2569
+ lastFiredContent = content;
2570
+ const dist = Math.max(0, content - (pos + view));
2571
+ endFn(makeEnvelope("endReached", "user", {
2572
+ y: pos, ch: content, distanceFromEnd: dist,
2573
+ }, Date.now()));
2574
+ }
2575
+ } else {
2576
+ lastFiredContent = -1;
2577
+ }
2578
+ };
2579
+ hub.listeners.push(onScrollMetric);
2580
+ addDispose(ctx, id, () => {
2581
+ const idx = hub.listeners.indexOf(onScrollMetric);
2582
+ if (idx >= 0) hub.listeners.splice(idx, 1);
2583
+ });
2584
+ }
2585
+ }
2586
+ }
2587
+
2588
+ // ADR-0149 — memoria del foco: solo nodos nombrados que pueden
2589
+ // recibirlo (interactivos, focusable/focused declarado, o handler
2590
+ // de la app). El tracker posee el attach "focus" — el loop de
2591
+ // abajo lo salta y el bucket reenvía el envelope.
2592
+ const trackedFocus = !remap && !!node.id && !!ctx.focusState &&
2593
+ !!ctx.handlers && (
2594
+ FOCUSABLE_TYPES.has(node.type) ||
2595
+ node.props?.["focusable"] !== undefined ||
2596
+ node.props?.["focused"] !== undefined ||
2597
+ node.events?.["focus"] !== undefined ||
2598
+ node.events?.["blur"] !== undefined
2599
+ );
2600
+ if (trackedFocus) {
2601
+ installFocusTracker(ctx, id, node.id!, node.events?.["focus"]);
2602
+ }
2603
+
2604
+ // ADR-0149: restore del foco persistido — el nodo ya existe;
2605
+ // update-semantics post-create lo re-enfoca en el host.
2606
+ if (!remap) emitFocusRestore(ctx, id, node.id);
2607
+
2608
+ // Eventos — ADR-0034: `class` viaja en la op (discrete/continuous) —
2609
+ // el host decide coalescing por clase, no por nombre de evento.
2610
+ if (node.events) {
2611
+ for (const [eventName, binding] of Object.entries(node.events)) {
2612
+ // ADR-0148: el tracker posee el attach "scroll" del nodo —
2613
+ // emitir también el de la app lo pisaría en el host.
2614
+ if (eventName === "scroll" && ctx.scrollTrack.has(id)) continue;
2615
+ // ADR-0149: mismo motivo para "focus" — el tracker lo posee.
2616
+ if (eventName === "focus" && ctx.focusTrack.has(id)) continue;
2617
+ // ADR-0086/R4.6: un attach-event fuera del vocabulario o no
2618
+ // soportado en algún backend se descarta con warn — emitirlo
2619
+ // registraría un handler que nunca dispara. Platform-views
2620
+ // exentas (eventos definidos por el módulo, ADR-0080 §13).
2621
+ if (ctx.strictEvents && !isPlatformView && !isPortableEvent(eventName)) {
2622
+ if (typeof console !== "undefined" && console.warn) {
2623
+ console.warn(
2624
+ `[elur] strictEvents: evento '${eventName}' no portable — attach descartado (nodo ${id})`,
2625
+ );
2626
+ }
2627
+ continue;
2628
+ }
2629
+ // ADR-0054: dentro de una fila template, el attach lleva el
2630
+ // contexto del item — el host lo mergea en data del envelope
2631
+ // al despachar (la misma key viaja al handler).
2632
+ let payload = ctx.rowEventPayload;
2633
+ // ADR-0179: el combo de `shortcut` viaja canónico en el
2634
+ // payload — el host compara strings, no parsea combos. Solo
2635
+ // valor estático: un combo reactivo re-registraría atajos
2636
+ // globales por frame.
2637
+ if (eventName === "shortcut") {
2638
+ const combo = shortcutComboOf(node.props?.shortcut);
2639
+ if (combo === null) {
2640
+ if (typeof console !== "undefined" && console.warn) {
2641
+ console.warn(
2642
+ `[elur] @shortcut sin prop shortcut válida — attach descartado (nodo ${id})`,
2643
+ );
2644
+ }
2645
+ continue;
2646
+ }
2647
+ payload = mergePayload(payload, { combo });
2648
+ }
2649
+ ctx.emit({
2650
+ op: "attach-event", id, event: eventName,
2651
+ handler: binding.handler,
2652
+ class: binding.class ??
2653
+ (EVENT_DEFAULT_CLASS as Record<string, "discrete" | "continuous">)[eventName] ??
2654
+ "discrete",
2655
+ ...(payload !== undefined ? { payload } : {}),
2656
+ });
2657
+ }
2658
+ }
2659
+
2660
+ // scroll-view entra a la pila de scrolleables (ADR-0033) mientras se
2661
+ // renderizan sus descendientes — una lista virtual lo consume para
2662
+ // auto-cablear su feed de scroll.
2663
+ const isScroller = node.type === "scroll-view";
2664
+ // ADR-0148: restore de la posición persistida (scrollTop post-create
2665
+ // — el backend la aplica tras el primer layout).
2666
+ if (isScroller && !remap) emitScrollRestore(ctx, id, node.id);
2667
+ if (isScroller) ctx.scrollerStack.push(id);
2668
+
2669
+ // Lista keyed (A.6.4) — diff por key, no re-render de todo.
2670
+ // Una fila con lista anidada no es reciclable estructuralmente
2671
+ // (la suscripción interna pertenece al item viejo): el flag del
2672
+ // pool la excluye antes de llegar aquí — el guard es defensa.
2673
+ if (node.list && !remap) {
2674
+ renderList(node, id, ctx);
2675
+ }
2676
+
2677
+ // Hijos (solo si no es lista — las listas manejan sus hijos via diff)
2678
+ if (node.children && !node.list) {
2679
+ for (let i = 0; i < node.children.length; i++) {
2680
+ warnLayoutSmells(node, node.children[i], nodeStyle);
2681
+ renderNode(node.children[i], id, i, ctx);
2682
+ }
2683
+ }
2684
+
2685
+ if (isScroller) ctx.scrollerStack.pop();
2686
+
2687
+ // insert-child al final (como en elurApp.js). En remap la jerarquía
2688
+ // interna ya está montada — el único insert lo emite el llamador
2689
+ // para la raíz de la fila.
2690
+ if (parentId !== undefined && !remap) {
2691
+ ctx.emit({ op: "insert-child", parentId, childId: id, index });
2692
+ }
2693
+
2694
+ return id;
2695
+ }
2696
+
2697
+ // Entry point
2698
+
2699
+ export function createReconciler(options: ReconcilerOptions): ReconcilerHandle {
2700
+ // Contrato A.4: irVersion siempre presente e == IR_VERSION. Un IR de
2701
+ // otra versión es ininterpretable — rechazo explícito, no best-effort.
2702
+ if (options.ir?.irVersion !== IR_VERSION) {
2703
+ throw new Error(
2704
+ `[elur] irVersion=${String(options.ir?.irVersion)} no soportada ` +
2705
+ `(runtime IR_VERSION=${IR_VERSION})`,
2706
+ );
2707
+ }
2708
+ const ctx: ReconcilerContext = {
2709
+ signals: options.signals,
2710
+ emit: options.emit,
2711
+ idMap: options.idMap ?? createIdMap(),
2712
+ rootScope: new Scope(),
2713
+ nodeScope: new Map(),
2714
+ nodeParents: new Map(),
2715
+ nodeHandlers: new Map(),
2716
+ nodeIrIds: new Map(),
2717
+ keyFns: options.keyFns ?? {},
2718
+ factories: options.factories ?? {},
2719
+ handlers: options.handlers,
2720
+ idPrefix: options.idPrefix ?? "",
2721
+ listState: new Map(),
2722
+ listItemCounter: 1000, // IDs de items empiezan en 1000 para no chocar con IDs del IR
2723
+ workletAnims: new Map(),
2724
+ scrollerStack: [],
2725
+ strictStyles: options.strictStyles ?? false,
2726
+ screenRoot: options.screenRoot === true,
2727
+ inheritedText: new Map(),
2728
+ strictProps: options.strictProps ?? false,
2729
+ strictEvents: options.strictEvents ?? false,
2730
+ bindDisposes: new Map(),
2731
+ remapIds: undefined,
2732
+ remapPos: 0,
2733
+ nativeList: options.nativeList === true,
2734
+ skia: options.skia === true,
2735
+ rowEventPayload: undefined,
2736
+ scrollPositions: options.scrollPositions,
2737
+ scrollTrack: new Map(),
2738
+ focusState: options.focusState,
2739
+ focusTrack: new Map(),
2740
+ focusedNum: undefined,
2741
+ };
2742
+
2743
+ // Render pass: walk del IR. Los effects se registran y emiten,
2744
+ // pero NO flushean. El llamador llama flush() al final.
2745
+ // U10 — rollback si el walk lanza: un render parcial dejaba
2746
+ // suscripciones vivas (emitiendo ops tras el fallo), handlers de
2747
+ // filas factory en el registry y views huérfanas en el backend.
2748
+ // Se emite delete-node postorder por lo creado y se dispone el
2749
+ // scope raíz — el estado vuelve al baseline de antes de la llamada.
2750
+ let rootId = -1;
2751
+ try {
2752
+ rootId = options.ir.root
2753
+ ? renderNode(options.ir.root, undefined, 0, ctx)
2754
+ : -1;
2755
+ } catch (e) {
2756
+ for (const child of [...ctx.rootScope.childScopes]) {
2757
+ if (child.nodeId !== undefined) destroySubtree(child.nodeId, ctx);
2758
+ }
2759
+ ctx.rootScope.dispose();
2760
+ ctx.nodeScope.clear();
2761
+ ctx.nodeParents.clear();
2762
+ ctx.nodeHandlers.clear();
2763
+ ctx.nodeIrIds.clear();
2764
+ ctx.listState.clear();
2765
+ ctx.bindDisposes.clear();
2766
+ ctx.workletAnims.clear();
2767
+ throw e;
2768
+ }
2769
+
2770
+ return {
2771
+ idMap: ctx.idMap,
2772
+ rootId,
2773
+
2774
+ dispose: () => {
2775
+ // Dispose del scope raíz — cascada por el árbol de scopes
2776
+ // (R1.1): cada nodo libera effects, worklets, handlers e ids.
2777
+ // No emite ops: es teardown del reconciler, no del modelo.
2778
+ ctx.rootScope.dispose();
2779
+ ctx.nodeScope.clear();
2780
+ ctx.nodeParents.clear();
2781
+ ctx.nodeHandlers.clear();
2782
+ ctx.nodeIrIds.clear();
2783
+ ctx.listState.clear();
2784
+ },
2785
+
2786
+ destroy: () => {
2787
+ // Teardown con emisión (V02): delete-node postorder por cada
2788
+ // nodo vivo — el aplicador suelta el elemento real de cada
2789
+ // descendiente. destroySubtree disposes los scopes por nodo;
2790
+ // rootScope (onDispose/cleanups fuera de nodo) se disposes
2791
+ // después — no cuelga del árbol de nodos.
2792
+ if (rootId >= 0) destroySubtree(rootId, ctx);
2793
+ ctx.rootScope.dispose();
2794
+ ctx.nodeScope.clear();
2795
+ ctx.nodeParents.clear();
2796
+ ctx.nodeHandlers.clear();
2797
+ ctx.nodeIrIds.clear();
2798
+ ctx.listState.clear();
2799
+ },
2800
+
2801
+ onDispose: (fn) => ctx.rootScope.addDispose(fn),
2802
+
2803
+ /** ADR-0149 — re-enfoque tras detach/attach (pop-back): la
2804
+ * vista conservada pierde el foco al desmontarse; se re-aplica
2805
+ * `focused` sobre el último nodo enfocado recordado en sesión.
2806
+ * No-op si nunca hubo foco trackeado. */
2807
+ restoreFocus: () => {
2808
+ const n = ctx.focusedNum;
2809
+ if (n !== undefined) {
2810
+ ctx.emit({ op: "update-semantics", id: n, semantics: { focused: true } });
2811
+ }
2812
+ },
2813
+
2814
+ /** Métricas vivas del reconciler (R1.6) — para tests e invariantes. */
2815
+ metrics: () => ({
2816
+ nodes: ctx.nodeScope.size,
2817
+ lists: ctx.listState.size,
2818
+ worklets: ctx.workletAnims.size,
2819
+ idMapEntries: ctx.idMap.size,
2820
+ handlers: ctx.nodeHandlers.size,
2821
+ // Disposes vivos menos los teardowns por nodo ≈ effects activos.
2822
+ effects: Math.max(0, ctx.rootScope.liveDisposes - ctx.nodeScope.size),
2823
+ }),
2824
+
2825
+ detachFromParent: (nodeId: string) => {
2826
+ const id = ctx.idMap.get(ctx.idPrefix + nodeId);
2827
+ if (id === undefined) return;
2828
+ const parentId = ctx.nodeParents.get(id);
2829
+ if (parentId !== undefined) {
2830
+ ctx.emit({ op: "remove-child", parentId, childId: id });
2831
+ }
2832
+ },
2833
+
2834
+ attachToParent: (nodeId: string, parentId: string, index: number) => {
2835
+ const id = ctx.idMap.get(ctx.idPrefix + nodeId);
2836
+ const pid = ctx.idMap.get(ctx.idPrefix + parentId);
2837
+ if (id !== undefined && pid !== undefined) {
2838
+ ctx.emit({ op: "insert-child", parentId: pid, childId: id, index });
2839
+ }
2840
+ },
2841
+
2842
+ destroyNode: (nodeId: string) => {
2843
+ const id = ctx.idMap.get(ctx.idPrefix + nodeId);
2844
+ if (id !== undefined) {
2845
+ destroySubtree(id, ctx);
2846
+ }
2847
+ },
2848
+
2849
+ moveNode: (nodeId: string, parentId: string, index: number) => {
2850
+ const id = ctx.idMap.get(ctx.idPrefix + nodeId);
2851
+ const pid = ctx.idMap.get(ctx.idPrefix + parentId);
2852
+ if (id !== undefined && pid !== undefined) {
2853
+ ctx.emit({ op: "move-child", parentId: pid, childId: id, index });
2854
+ }
2855
+ },
2856
+ };
2857
+ }