@forgenex/cli 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/GUIA-IA.md +1350 -0
- package/LICENSE +21 -0
- package/README.md +45 -2
- package/REFERENCIA.md +137 -0
- package/dist/caja.js +49 -0
- package/dist/emscripten-module.wasm +0 -0
- package/dist/forgenex.js +37 -0
- package/dist/locales/ca.js +1 -0
- package/dist/locales/en.js +1 -0
- package/dist/locales/es.js +1 -0
- package/ejemplos/hola-alpine/interfaz/alpine-3.14.9.min.js +5 -0
- package/ejemplos/hola-alpine/interfaz/estilo.css +8 -0
- package/ejemplos/hola-alpine/interfaz/index.html +53 -0
- package/ejemplos/hola-react/interfaz/app.js +9 -0
- package/ejemplos/hola-react/interfaz/estilo.css +8 -0
- package/ejemplos/hola-react/interfaz/index.html +12 -0
- package/ejemplos/hola-react/src/main.jsx +45 -0
- package/extension.schema.json +583 -0
- package/licencias/@jitl__quickjs-ffi-types.txt +21 -0
- package/licencias/@jitl__quickjs-wasmfile-release-sync.txt +47 -0
- package/licencias/hono.txt +21 -0
- package/licencias/kysely.txt +21 -0
- package/licencias/nodemailer.txt +16 -0
- package/licencias/pg-cloudflare.txt +21 -0
- package/licencias/pg-connection-string.txt +21 -0
- package/licencias/pg-int8.txt +13 -0
- package/licencias/pg-pool.txt +21 -0
- package/licencias/pg-protocol.txt +21 -0
- package/licencias/pg.txt +21 -0
- package/licencias/postgres-array.txt +21 -0
- package/licencias/postgres-bytea.txt +21 -0
- package/licencias/postgres-date.txt +21 -0
- package/licencias/postgres-interval.txt +21 -0
- package/licencias/quickjs-emscripten-core.txt +21 -0
- package/licencias/split2.txt +13 -0
- package/licencias/xtend.txt +20 -0
- package/licencias.txt +23 -0
- package/package.json +24 -4
- package/puente-extension.d.ts +12 -0
- package/puente-extension.mjs +46 -0
- package/solucion.schema.json +1188 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ForgeNEX
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,46 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @forgenex/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Crea, prueba, empaqueta e instala apps del CRM ForgeNEX. Valida con el mismo
|
|
4
|
+
código que usa el CRM al instalar: lo que pasa aquí, se instala.
|
|
5
|
+
|
|
6
|
+
Necesitas Node 20 o más nuevo y ser partner con la opción «Desarrollador» en el
|
|
7
|
+
panel de ForgeNEX (Perfil › Desarrollador). Ahí tienes tu espacio de pruebas,
|
|
8
|
+
tu clave de desarrollador y la clave del MCP para tu IA.
|
|
9
|
+
|
|
10
|
+
## Empezar
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npx forgenex crear-app mi-app # o --plantilla react
|
|
14
|
+
cd mi-app
|
|
15
|
+
npx forgenex validar
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Lee `GUIA-IA.md` (se copia al proyecto) antes de escribir la app: ahí está el
|
|
19
|
+
formato entero, con ejemplos. Si trabajas con una IA, dásela junto con
|
|
20
|
+
`extension.schema.json`.
|
|
21
|
+
|
|
22
|
+
## Probar e instalar
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
export FORGENEX_API=https://crm.forgenex.com
|
|
26
|
+
export FORGENEX_CLAVE_DESARROLLADOR=crmdev_… # la del panel; no la pongas en el proyecto
|
|
27
|
+
|
|
28
|
+
npx forgenex claves crear # tu clave de firma (~/.forgenex/desarrollador.pem)
|
|
29
|
+
npx forgenex registrar-clave --espacio <id>
|
|
30
|
+
npx forgenex empaquetar # deja <app>-<versión>.fgx firmado
|
|
31
|
+
npx forgenex instalar --espacio <id> --paquete <app>-<versión>.fgx
|
|
32
|
+
npx forgenex dev --espacio <id> # tus funciones, en tu máquina, contra tu espacio
|
|
33
|
+
npx forgenex publicar --espacio <id> --paquete <app>-<versión>.fgx # a «Mis apps» de tu cuenta
|
|
34
|
+
npx forgenex instalar --espacio <id> --app <id-de-la-app> # desde «Mis apps»
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Al instalar, la app queda en espera hasta que el administrador del espacio
|
|
38
|
+
acepta sus permisos en Ajustes › Apps. Una versión publicada se aplica sola
|
|
39
|
+
donde ya está instalada si no pide más permisos; si pide más, espera a que
|
|
40
|
+
los acepten (detalle en GUIA-IA.md, «Publicar en Mis apps»).
|
|
41
|
+
|
|
42
|
+
## Comandos
|
|
43
|
+
|
|
44
|
+
`crear-app`, `validar`, `dev`, `empaquetar`, `instalar`, `publicar`, `claves crear`,
|
|
45
|
+
`registrar-clave`, `revocar-clave`, `previsualizar`, `esquema`,
|
|
46
|
+
`esquema-extension` y `version`. Sin argumentos, `forgenex` los lista.
|
package/REFERENCIA.md
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# SDK de módulos y soluciones del CRM ForgeNEX
|
|
2
|
+
|
|
3
|
+
Plan: `docs/planes/2026-10-02-sdk-modulos.md`. La guía completa y el kit para
|
|
4
|
+
IA los mantiene hermes; esto es lo mínimo para usar la CLI.
|
|
5
|
+
|
|
6
|
+
- `solucion.schema.json`: la FORMA del formato (`forgenex.solucion`, versión 2),
|
|
7
|
+
generada del código (`cli.ts esquema`). Una prueba (`api/pruebas/sdk.ts`)
|
|
8
|
+
falla si se queda atrás.
|
|
9
|
+
- `cli.ts`: usa EL MISMO validador que el CRM (`validarSolucion`): lo que pasa
|
|
10
|
+
aquí, se instala. Desde `servicios/crm/api`:
|
|
11
|
+
|
|
12
|
+
npx tsx ../sdk/cli.ts validar mi-solucion.json [--json]
|
|
13
|
+
npx tsx ../sdk/cli.ts previsualizar mi-solucion.json
|
|
14
|
+
npx tsx ../sdk/cli.ts esquema > ../sdk/solucion.schema.json
|
|
15
|
+
npx tsx ../sdk/cli.ts version
|
|
16
|
+
|
|
17
|
+
- En el CRM: Módulos › Soluciones › «Importar» (vista previa antes de
|
|
18
|
+
instalar; se instala como copia; las automatizaciones entran APAGADAS; los
|
|
19
|
+
módulos que pasen del plan quedan bloqueados). El equipo interno, además,
|
|
20
|
+
«Proponer a la galería» desde «Exportar solución».
|
|
21
|
+
|
|
22
|
+
- `extension.schema.json`: la forma de `forgenex.extension` (Apps E1,
|
|
23
|
+
`cli.ts esquema-extension`). `validar` reconoce los dos formatos por su
|
|
24
|
+
campo `formato`. Qué hace ya y qué solo se valida: GUIA-IA.md, sección 14.
|
|
25
|
+
|
|
26
|
+
npx tsx ../sdk/cli.ts validar extension.json
|
|
27
|
+
npx tsx ../sdk/cli.ts esquema-extension > ../sdk/extension.schema.json
|
|
28
|
+
|
|
29
|
+
## Para IA
|
|
30
|
+
[GUIA-IA.md](GUIA-IA.md): todo el formato explicado para que una IA escriba soluciones; dásela junto con `solucion.schema.json`.
|
|
31
|
+
|
|
32
|
+
## Cliente experimental de apps
|
|
33
|
+
|
|
34
|
+
El paquete local `@forgenex/crm-sdk` contiene el cliente del puente para
|
|
35
|
+
operaciones v1, integrado en los montajes de E2 (no se publica en npm). Para
|
|
36
|
+
probarlo en un proyecto local se puede instalar esta carpeta como dependencia.
|
|
37
|
+
`pedir` admite GET y POST; en POST se debe indicar `idempotencia`. Los permisos
|
|
38
|
+
los comprueba el servidor. `cerrar()` cancela las peticiones pendientes.
|
|
39
|
+
|
|
40
|
+
## Ejemplos de apps con interfaz (E2)
|
|
41
|
+
|
|
42
|
+
En `ejemplos/`: `hola-alpine` (HTML y Alpine, sin compilar), `hola-react`
|
|
43
|
+
(React, `src/main.jsx` compilado a `interfaz/app.js`) y `hola-falla` (falla a
|
|
44
|
+
propósito: el CRM la aísla, avisa y deja reintentar). Los dos «hola» salen en
|
|
45
|
+
los cuatro montajes: página en el menú, bloque del Inicio, pestaña y acción en
|
|
46
|
+
la ficha de una persona. `node ejemplos/construir.mjs` compila el de React y deja
|
|
47
|
+
los tres en `ejemplos/dist/*.zip`, para «Subir paquete» con el modo
|
|
48
|
+
desarrollador encendido. Mientras se programa, «Probar desde localhost» (menú de
|
|
49
|
+
la app) carga los ficheros de `http://localhost:PUERTO` con los permisos
|
|
50
|
+
de la instalación; el servidor local tiene que responder con
|
|
51
|
+
`Access-Control-Allow-Origin` para el dominio del CRM.
|
|
52
|
+
|
|
53
|
+
Dentro de la caja: `import { crearClienteCRM } from "@forgenex/crm-sdk"` (lo
|
|
54
|
+
resuelve el CRM), `crm.contexto()` (módulo e id de la ficha, o `null`) y
|
|
55
|
+
`crm.pedir(op, parámetros)` con las operaciones de la v1. El tema (variables
|
|
56
|
+
`--background`, `--card`, `--primary`… y la clase `dark`) llega solo. La
|
|
57
|
+
app puede usar fuera los datos a los que el dueño del espacio le da
|
|
58
|
+
permiso; lo que no puede es salir de su espacio, ver la sesión de la persona ni
|
|
59
|
+
navegar la página del CRM a una URL arbitraria.
|
|
60
|
+
|
|
61
|
+
El almacén (`almacen.leer` y `almacen.guardar`, con el permiso `almacen`) es
|
|
62
|
+
de la INSTALACIÓN, como las opciones de un plugin de WordPress: lo leen y lo
|
|
63
|
+
escriben todas las personas que usan la app en ese espacio, y también su
|
|
64
|
+
servidor con la clave. No guardes ahí nada que deba ver solo una persona. Lo
|
|
65
|
+
que cada persona ve de los registros sí se recorta a su papel.
|
|
66
|
+
|
|
67
|
+
## Ejemplo de funciones (E3)
|
|
68
|
+
|
|
69
|
+
`ejemplos/dias-habiles`: calcula los días laborables (sin fines de semana ni
|
|
70
|
+
festivos nacionales, que pide a `date.nager.at`) que faltan hasta una fecha y
|
|
71
|
+
los escribe por la API. Corre al crear y al cambiar un registro, cada noche y
|
|
72
|
+
como paso de automatización. Qué módulo y qué campos lo dice su almacén (clave
|
|
73
|
+
`config`, ver la cabecera de `funciones/dias-habiles.js`). `node
|
|
74
|
+
ejemplos/construir.mjs` lo deja en `ejemplos/dist/dias-habiles.zip`. Las
|
|
75
|
+
reglas de las funciones (disparadores, lo que tienen dentro, topes y registro)
|
|
76
|
+
están en [GUIA-IA.md](GUIA-IA.md), «Funciones (E3)».
|
|
77
|
+
|
|
78
|
+
`hola-alpine/interfaz/alpine-3.14.9.min.js` es Alpine.js 3.14.9 sin tocar (licencia MIT, © Caleb Porzio; `npm pack alpinejs@3.14.9`, publicado el 12-mar-2025).
|
|
79
|
+
|
|
80
|
+
## Recepción del taller y contratos interactivos (E6)
|
|
81
|
+
|
|
82
|
+
Referencia React + Vite + Forja Chispa: [recepcion-taller](ejemplos/recepcion-taller/README.md).
|
|
83
|
+
Su constructor produce un único JS/CSS para el resolver de recursos del CRM.
|
|
84
|
+
También lo construye `node ejemplos/construir.mjs`.
|
|
85
|
+
|
|
86
|
+
- `extensiones.calcular` (POST, `{funcion, entrada}`): solo un pase de interfaz
|
|
87
|
+
de la propia instalación; QuickJS de solo lectura, sin red ni encadenar
|
|
88
|
+
funciones. Hasta 2 funciones simultáneas entre cálculos y cola, y 20 cálculos por minuto e instalación.
|
|
89
|
+
Respeta los topes de tiempo/memoria declarados (máximo interactivo de 8 segundos). Cada llamada se recalcula
|
|
90
|
+
(no se reutiliza una salida tras un cambio de permisos) y deja registro
|
|
91
|
+
sin entrada ni salida del cliente. Respuesta `{correcto, salida?, motivo?}`.
|
|
92
|
+
- `registros.adjuntar` (POST, `{modulo,id,campo?,nombre,contenido_base64}`):
|
|
93
|
+
documentos e imágenes por contenido, hasta 5 MB, con edición de la ficha.
|
|
94
|
+
`campo` añade a archivos o firma, respetando ocultos/solo lectura; sin
|
|
95
|
+
`campo`, queda en Archivos de la ficha. Reintentar con la misma clave no
|
|
96
|
+
duplica. No concede la subida suelta ni la descarga de otros archivos.
|
|
97
|
+
- `mod_<clave>.pdf` (GET): exige ver ese módulo y el registro; usa su plantilla
|
|
98
|
+
y sus máscaras. El servicio PDF lo configura el nodo, nunca la extensión.
|
|
99
|
+
- `registros.historial` (GET, `{modulo,id,antes?}`): el historial real de la
|
|
100
|
+
ficha, filtrado por campo y permiso. Devuelve `{cambios,siguiente}`; pasa
|
|
101
|
+
`siguiente` como `antes` para la página siguiente.
|
|
102
|
+
- `registros.opciones` (GET, `{modulo,campo}`): etiquetas y colores del
|
|
103
|
+
diseñador para un campo de selección visible de un módulo propio.
|
|
104
|
+
- `mensajes.proponer` (POST, `{modulo,id,para,asunto,texto,pdf?}`): requiere
|
|
105
|
+
editar la ficha y un destinatario de sus relaciones visibles. Devuelve
|
|
106
|
+
el enlace de confirmación existente. No manda el correo. La extensión
|
|
107
|
+
nunca puede llamar al envío ni confirmar el enlace.
|
|
108
|
+
- `interfaz.registro` (puente, GET, `{modulo,id,entera?}`): abre la vista rápida
|
|
109
|
+
común, conservando la página; `entera` pide otra pestaña y exige gesto de
|
|
110
|
+
la persona. Solo recursos y números válidos, nunca una URL.
|
|
111
|
+
- `interfaz.confirmar` (puente, GET, `{token,espacio}`): pide al anfitrión abrir
|
|
112
|
+
exclusivamente una confirmación del CRM; no acepta una URL. La persona
|
|
113
|
+
revisa y confirma con su sesión; permisos y destinatario se revalidan.
|
|
114
|
+
- `ficha_bloque`: el mismo aislamiento y contexto que una pestaña, en las
|
|
115
|
+
fichas enteras y rápidas. Las páginas aprovechan la altura de la ventana.
|
|
116
|
+
|
|
117
|
+
Las operaciones genéricas toman `modulo` como recurso (`contacts`, `companies`,
|
|
118
|
+
`deals`, `mod_<clave>`), salvo `registros.opciones`, que consulta módulos propios.
|
|
119
|
+
Además de lo aceptado, siempre se comprueba el papel y la RLS actuales. Los
|
|
120
|
+
adjuntos y propuestas también revalidan antes de devolver una repetición
|
|
121
|
+
idempotente. Los errores del puente conservan su código estable en `message`
|
|
122
|
+
y ofrecen el mensaje legible en `detalle`.
|
|
123
|
+
|
|
124
|
+
La cámara puede no estar disponible en un iframe de origen opaco: proporciona
|
|
125
|
+
siempre subida alternativa. No añadas `allow-same-origin` a la caja en el
|
|
126
|
+
origen del CRM. Desde la 1.9.0, Pix usa las `herramientas_ia`: cada una
|
|
127
|
+
apunta a una función de disparador `herramienta` (ver GUIA-IA.md).
|
|
128
|
+
|
|
129
|
+
## CLI de apps (E4)
|
|
130
|
+
|
|
131
|
+
`./forgenex crear-app nombre --plantilla html|react`, `validar`, `dev`,
|
|
132
|
+
`empaquetar`, `instalar --espacio <id> (--paquete <archivo.fgx> | --app <id>)` y
|
|
133
|
+
`publicar --espacio <id> --paquete <archivo.fgx>` (1.13.0: a «Mis apps» de tu
|
|
134
|
+
cuenta; ver GUIA-IA.md, «Publicar en Mis apps»).
|
|
135
|
+
La CLI se ejecuta desde este checkout o como `@forgenex/cli` (el tarball de
|
|
136
|
+
`paquete/construir.mjs`, Node ≥ 20.19), sin publicar paquetes npm. Alta de credencial, claves, firma, ejemplo completo y
|
|
137
|
+
límites: [GUIA-IA.md, sección 15](GUIA-IA.md#15-crear-una-app-con-tu-ia-cli-forgenex-e4).
|
package/dist/caja.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { createRequire as __fgxRequire } from "node:module"; const require = __fgxRequire(import.meta.url);
|
|
2
|
+
var It=Object.defineProperty;var ee=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(i){throw t=[i],i}};var ae=(e,r)=>{for(var t in r)It(e,t,{get:r[t],enumerable:!0})};var D,be,ue,V,te,le=ee(()=>{D={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},be={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},ue={Pending:0,Fulfilled:1,Rejected:2},V={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},te={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function re(...e){Ee&&console.log("quickjs-emscripten:",...e)}function*ut(e){return yield e}function Dt(e){return ut(Re(e))}function $e(e,r){return(...t)=>{let i=r.call(e,Ae,...t);return Re(i)}}function Vt(e,r){let t=r.call(e,Ae);return Re(t)}function Re(e){function r(t){return t.done?t.value:t.value instanceof Promise?t.value.then(i=>r(e.next(i)),i=>r(e.throw(i))):r(e.next(t.value))}return r(e.next())}function Te(e,r){let t;try{e.dispose()}catch(i){t=i}if(r&&t)throw Object.assign(r,{message:`${r.message}
|
|
3
|
+
Then, failed to dispose scope: ${t.message}`,disposeError:t}),r;if(r||t)throw r||t}function Bt(e){let r=e?Array.from(e):[];function t(){return r.forEach(u=>u.alive?u.dispose():void 0)}function i(){return r.some(u=>u.alive)}return Object.defineProperty(r,Me,{configurable:!0,enumerable:!1,value:t}),Object.defineProperty(r,"dispose",{configurable:!0,enumerable:!1,value:t}),Object.defineProperty(r,"alive",{configurable:!0,enumerable:!1,get:i}),r}function he(e){return!!(e&&(typeof e=="object"||typeof e=="function")&&"alive"in e&&typeof e.alive=="boolean"&&"dispose"in e&&typeof e.dispose=="function")}function Wt(e){if(!e)return 0;let r=0;for(let[t,i]of Object.entries(e)){if(!(t in be))throw new nt(t);i&&(r|=be[t])}return r}function $t(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{type:r,strict:t,strip:i,compileOnly:u,backtraceBarrier:a}=e,m=0;return r==="global"&&(m|=D.JS_EVAL_TYPE_GLOBAL),r==="module"&&(m|=D.JS_EVAL_TYPE_MODULE),t&&(m|=D.JS_EVAL_FLAG_STRICT),i&&(m|=D.JS_EVAL_FLAG_STRIP),u&&(m|=D.JS_EVAL_FLAG_COMPILE_ONLY),a&&(m|=D.JS_EVAL_FLAG_BACKTRACE_BARRIER),m}function qt(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{strings:r,symbols:t,quickjsPrivate:i,onlyEnumerable:u,numbers:a,numbersAsStrings:m}=e,l=0;return r&&(l|=V.JS_GPN_STRING_MASK),t&&(l|=V.JS_GPN_SYMBOL_MASK),i&&(l|=V.JS_GPN_PRIVATE_MASK),u&&(l|=V.JS_GPN_ENUM_ONLY),a&&(l|=V.QTS_GPN_NUMBER_MASK),m&&(l|=V.QTS_STANDARD_COMPLIANT_NUMBER),l}function Kt(...e){let r=[];for(let t of e)t!==void 0&&(r=r.concat(t));return r}function Qe(e){return e>>8}function Le(e,r){r.interruptHandler&&e.setInterruptHandler(r.interruptHandler),r.maxStackSizeBytes!==void 0&&e.setMaxStackSize(r.maxStackSizeBytes),r.memoryLimitBytes!==void 0&&e.setMemoryLimit(r.memoryLimitBytes)}function Ce(e,r){r.moduleLoader&&e.setModuleLoader(r.moduleLoader),r.shouldInterrupt&&e.setInterruptHandler(r.shouldInterrupt),r.memoryLimitBytes!==void 0&&e.setMemoryLimit(r.memoryLimitBytes),r.maxStackSizeBytes!==void 0&&e.setMaxStackSize(r.maxStackSizeBytes)}var Nt,Ft,Ee,Ht,xe,et,Pe,tt,rt,it,Ot,Gt,nt,st,ot,at,F,Ae,C,Me,qe,b,B,Ke,k,ke,jt,Ut,W,zt,ct,yr,Yt,Ye,Xe,ce,Xt,Ze,Zt,er,tr,rr,Je,ht,dt=ee(()=>{le();le();Nt=Object.defineProperty,Ft=(e,r)=>{for(var t in r)Nt(e,t,{get:r[t],enumerable:!0})},Ee=!1;Ht={};Ft(Ht,{QuickJSAsyncifyError:()=>rt,QuickJSAsyncifySuspended:()=>it,QuickJSEmptyGetOwnPropertyNames:()=>ot,QuickJSEmscriptenModuleError:()=>Gt,QuickJSHostRefInvalid:()=>F,QuickJSHostRefRangeExceeded:()=>at,QuickJSMemoryLeakDetected:()=>Ot,QuickJSNotImplemented:()=>tt,QuickJSPromisePending:()=>st,QuickJSUnknownIntrinsic:()=>nt,QuickJSUnwrapError:()=>xe,QuickJSUseAfterFree:()=>Pe,QuickJSWrongOwner:()=>et});xe=class extends Error{constructor(e,r){let t=typeof e=="object"&&e&&"message"in e?String(e.message):String(e);super(t),this.cause=e,this.context=r,this.name="QuickJSUnwrapError"}},et=class extends Error{constructor(){super(...arguments),this.name="QuickJSWrongOwner"}},Pe=class extends Error{constructor(){super(...arguments),this.name="QuickJSUseAfterFree"}},tt=class extends Error{constructor(){super(...arguments),this.name="QuickJSNotImplemented"}},rt=class extends Error{constructor(){super(...arguments),this.name="QuickJSAsyncifyError"}},it=class extends Error{constructor(){super(...arguments),this.name="QuickJSAsyncifySuspended"}},Ot=class extends Error{constructor(){super(...arguments),this.name="QuickJSMemoryLeakDetected"}},Gt=class extends Error{constructor(){super(...arguments),this.name="QuickJSEmscriptenModuleError"}},nt=class extends TypeError{constructor(){super(...arguments),this.name="QuickJSUnknownIntrinsic"}},st=class extends Error{constructor(){super(...arguments),this.name="QuickJSPromisePending"}},ot=class extends Error{constructor(){super(...arguments),this.name="QuickJSEmptyGetOwnPropertyNames"}},at=class extends Error{constructor(){super(...arguments),this.name="QuickJSHostRefRangeExceeded"}},F=class extends Error{constructor(){super(...arguments),this.name="QuickJSHostRefInvalid"}};Ae=ut;Ae.of=Dt;C=class{[Symbol.dispose](){return this.dispose()}},Me=Symbol.dispose??Symbol.for("Symbol.dispose"),qe=C.prototype;qe[Me]||(qe[Me]=function(){return this.dispose()});b=class lt extends C{constructor(r,t,i,u){super(),this._value=r,this.copier=t,this.disposer=i,this._owner=u,this._alive=!0,this._constructorStack=Ee?new Error("Lifetime constructed").stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw new Error("Non-dupable lifetime");return new lt(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(r){this.assertAlive();let t=r(this);return this.dispose(),t}map(r){return this.assertAlive(),r(this)}tap(r){return r(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new Pe(`Lifetime not alive
|
|
4
|
+
${this._constructorStack}
|
|
5
|
+
Lifetime used`):new Pe("Lifetime not alive")}},B=class extends b{constructor(e,r){super(e,void 0,void 0,r)}get dupable(){return!0}dup(){return this}dispose(){}},Ke=class extends b{constructor(e,r,t,i){super(e,r,t,i)}dispose(){this._alive=!1}};k=class me extends C{constructor(){super(...arguments),this._disposables=new b(new Set),this.manage=r=>(this._disposables.value.add(r),r)}static withScope(r){let t=new me,i;try{return r(t)}catch(u){throw i=u,u}finally{Te(t,i)}}static withScopeMaybeAsync(r,t){return Vt(void 0,function*(i){let u=new me,a;try{return yield*i.of(t.call(r,i,u))}catch(m){throw a=m,m}finally{Te(u,a)}})}static async withScopeAsync(r){let t=new me,i;try{return await r(t)}catch(u){throw i=u,u}finally{Te(t,i)}}get alive(){return this._disposables.alive}dispose(){let r=Array.from(this._disposables.value.values()).reverse();for(let t of r)t.alive&&t.dispose();this._disposables.dispose()}};ke=class mt extends C{static success(r){return new jt(r)}static fail(r,t){return new Ut(r,t)}static is(r){return r instanceof mt}},jt=class extends ke{constructor(e){super(),this.value=e}get alive(){return he(this.value)?this.value.alive:!0}dispose(){he(this.value)&&this.value.dispose()}unwrap(){return this.value}unwrapOr(e){return this.value}},Ut=class extends ke{constructor(e,r){super(),this.error=e,this.onUnwrap=r}get alive(){return he(this.error)?this.error.alive:!0}dispose(){he(this.error)&&this.error.dispose()}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(e){return e}},W=ke,zt=class extends C{constructor(e){super(),this.resolve=r=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,r||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.reject=r=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,r||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers()},this.context=e.context,this.owner=e.context.runtime,this.handle=e.promiseHandle,this.settled=new Promise(r=>{this.onSettled=r}),this.resolveHandle=e.resolveHandle,this.rejectHandle=e.rejectHandle}get alive(){return this.handle.alive||this.resolveHandle.alive||this.rejectHandle.alive}disposeResolvers(){this.resolveHandle.alive&&this.resolveHandle.dispose(),this.rejectHandle.alive&&this.rejectHandle.dispose()}},ct=class{constructor(e){this.module=e}toPointerArray(e){let r=new Int32Array(e.map(u=>u.value)),t=r.length*r.BYTES_PER_ELEMENT,i=this.module._malloc(t);return new Uint8Array(this.module.HEAPU8.buffer,i,t).set(new Uint8Array(r.buffer)),new b(i,void 0,u=>this.module._free(u))}newTypedArray(e,r){let t=new e(new Array(r).fill(0)),i=t.length*t.BYTES_PER_ELEMENT,u=this.module._malloc(i),a=new e(this.module.HEAPU8.buffer,u,r);return a.set(t),new b({typedArray:a,ptr:u},void 0,m=>this.module._free(m.ptr))}newMutablePointerArray(e){return this.newTypedArray(Int32Array,e)}newHeapCharPointer(e){let r=this.module.lengthBytesUTF8(e),t=r+1,i=this.module._malloc(t);return this.module.stringToUTF8(e,i,t),new b({ptr:i,strlen:r},void 0,u=>this.module._free(u.ptr))}newHeapBufferPointer(e){let r=e.byteLength,t=this.module._malloc(r);return this.module.HEAPU8.set(e,t),new b({pointer:t,numBytes:r},void 0,i=>this.module._free(i.pointer))}consumeHeapCharPointer(e){let r=this.module.UTF8ToString(e);return this.module._free(e),r}},yr=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});Yt=class extends C{constructor(e,r){super(),this.handle=e,this.context=r,this._isDone=!1,this.owner=r.runtime}[Symbol.iterator](){return this}next(e){if(!this.alive||this._isDone)return{done:!0,value:void 0};let r=this._next??(this._next=this.context.getProp(this.handle,"next"));return this.callIteratorMethod(r,e)}return(e){if(!this.alive)return{done:!0,value:void 0};let r=this.context.getProp(this.handle,"return");if(r===this.context.undefined&&e===void 0)return this.dispose(),{done:!0,value:void 0};let t=this.callIteratorMethod(r,e);return r.dispose(),this.dispose(),t}throw(e){if(!this.alive)return{done:!0,value:void 0};let r=e instanceof b?e:this.context.newError(e),t=this.context.getProp(this.handle,"throw"),i=this.callIteratorMethod(t,e);return r.alive&&r.dispose(),t.dispose(),this.dispose(),i}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(e,r){let t=r?this.context.callFunction(e,this.handle,r):this.context.callFunction(e,this.handle);if(t.error)return this.dispose(),{value:t};let i=this.context.getProp(t.value,"done").consume(a=>this.context.dump(a)),u=this.context.getProp(t.value,"value");return t.value.dispose(),i&&this.dispose(),{value:W.success(u),done:i}}},Ye=-2147483648,Xe=2147483647,ce=0;Xt=class{constructor(){this.nextId=Ye,this.freelist=[],this.groups=new Map}put(e){let r=this.allocateId(),t=Qe(r),i=this.groups.get(t);return i||(i=new Map,this.groups.set(t,i)),i.set(r,e),r}get(e){if(e===ce)throw new F("no host reference id defined");let r=Qe(e),t=this.groups.get(r);if(!t)throw new F(`host reference id ${e} is not defined`);let i=t.get(e);if(!i)throw new F(`host reference id ${e} is not defined`);return i}delete(e){if(e===ce)throw new F("no host reference id defined");let r=Qe(e),t=this.groups.get(r);if(!t)throw new F(`host reference id ${e} is not defined`);t.delete(e),t.size===0&&this.groups.delete(r),this.freelist.push(e)}allocateId(){if(this.freelist.length>0)return this.freelist.shift();if(this.nextId===ce&&this.nextId++,this.nextId>Xe)throw new at(`HostRefMap: too many host refs created without disposing. Max simultaneous host refs: ${Xe-Ye}`);return this.nextId++}},Ze=class extends C{constructor(e,r,t){if(t===ce)throw new F("cannot create HostRef with undefined id");super(),this.runtime=e,this.handle=r,this.id=t}get alive(){return this.handle.alive}dispose(){this.handle.dispose()}get value(){return this.runtime.hostRefs.get(this.id)}},Zt=class extends ct{constructor(e){super(e.module),this.scope=new k,this.copyJSValue=r=>this.ffi.QTS_DupValuePointer(this.ctx.value,r),this.freeJSValue=r=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,r)},e.ownedLifetimes?.forEach(r=>this.scope.manage(r)),this.owner=e.owner,this.module=e.module,this.ffi=e.ffi,this.rt=e.rt,this.ctx=this.scope.manage(e.ctx)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(e){return this.scope.manage(e)}consumeJSCharPointer(e){let r=this.module.UTF8ToString(e);return this.ffi.QTS_FreeCString(this.ctx.value,e),r}heapValueHandle(e,r){let t=r?i=>{r(),this.freeJSValue(i)}:this.freeJSValue;return new b(e,this.copyJSValue,t,this.owner)}staticHeapValueHandle(e){return this.manage(this.heapValueHandle(e)),new B(e,this.owner)}},er=class extends C{constructor(e){super(),this._undefined=void 0,this._null=void 0,this._false=void 0,this._true=void 0,this._global=void 0,this._BigInt=void 0,this._Symbol=void 0,this._SymbolIterator=void 0,this._SymbolAsyncIterator=void 0,this.cToHostCallbacks={callFunction:(r,t,i,u,a)=>{if(r!==this.ctx.value)throw new Error("QuickJSContext instance received C -> JS call with mismatched ctx");let m=this.getFunction(a);return k.withScopeMaybeAsync(this,function*(l,h){let p=h.manage(new Ke(t,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),y=new Array(i);for(let f=0;f<i;f++){let T=this.ffi.QTS_ArgvGetJSValueConstPointer(u,f);y[f]=h.manage(new Ke(T,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let f=yield*l(m.apply(p,y));if(f){if("error"in f&&f.error)throw this.runtime.debugLog("throw error",f.error),f.error;let T=h.manage(f instanceof b?f:f.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,T.value)}return 0}catch(f){return this.errorToHandle(f).consume(T=>this.ffi.QTS_Throw(this.ctx.value,T.value))}})}},this.runtime=e.runtime,this.module=e.module,this.ffi=e.ffi,this.rt=e.rt,this.ctx=e.ctx,this.memory=new Zt({...e,owner:this.runtime}),e.callbacks.setContextCallbacks(this.ctx.value,this.cToHostCallbacks),this.dump=this.dump.bind(this),this.getString=this.getString.bind(this),this.getNumber=this.getNumber.bind(this),this.resolvePromise=this.resolvePromise.bind(this),this.uint32Out=this.memory.manage(this.memory.newTypedArray(Uint32Array,1))}get alive(){return this.memory.alive}dispose(){this.memory.dispose()}get undefined(){if(this._undefined)return this._undefined;let e=this.ffi.QTS_GetUndefined();return this._undefined=new B(e)}get null(){if(this._null)return this._null;let e=this.ffi.QTS_GetNull();return this._null=new B(e)}get true(){if(this._true)return this._true;let e=this.ffi.QTS_GetTrue();return this._true=new B(e)}get false(){if(this._false)return this._false;let e=this.ffi.QTS_GetFalse();return this._false=new B(e)}get global(){if(this._global)return this._global;let e=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(e),this._global}newNumber(e){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,e))}newString(e){let r=this.memory.newHeapCharPointer(e).consume(t=>this.ffi.QTS_NewString(this.ctx.value,t.value.ptr));return this.memory.heapValueHandle(r)}newUniqueSymbol(e){let r=(typeof e=="symbol"?e.description:e)??"",t=this.memory.newHeapCharPointer(r).consume(i=>this.ffi.QTS_NewSymbol(this.ctx.value,i.value.ptr,0));return this.memory.heapValueHandle(t)}newSymbolFor(e){let r=(typeof e=="symbol"?e.description:e)??"",t=this.memory.newHeapCharPointer(r).consume(i=>this.ffi.QTS_NewSymbol(this.ctx.value,i.value.ptr,1));return this.memory.heapValueHandle(t)}getWellKnownSymbol(e){return this._Symbol??(this._Symbol=this.memory.manage(this.getProp(this.global,"Symbol"))),this.getProp(this._Symbol,e)}newBigInt(e){if(!this._BigInt){let i=this.getProp(this.global,"BigInt");this.memory.manage(i),this._BigInt=new B(i.value,this.runtime)}let r=this._BigInt,t=String(e);return this.newString(t).consume(i=>this.unwrapResult(this.callFunction(r,this.undefined,i)))}newObject(e){e&&this.runtime.assertOwned(e);let r=e?this.ffi.QTS_NewObjectProto(this.ctx.value,e.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle(r)}newArray(){let e=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(e)}newArrayBuffer(e){let r=new Uint8Array(e),t=this.memory.newHeapBufferPointer(r),i=this.ffi.QTS_NewArrayBuffer(this.ctx.value,t.value.pointer,r.length);return this.memory.heapValueHandle(i)}newPromise(e){let r=k.withScope(t=>{let i=t.manage(this.memory.newMutablePointerArray(2)),u=this.ffi.QTS_NewPromiseCapability(this.ctx.value,i.value.ptr),a=this.memory.heapValueHandle(u),[m,l]=Array.from(i.value.typedArray).map(h=>this.memory.heapValueHandle(h));return new zt({context:this,promiseHandle:a,resolveHandle:m,rejectHandle:l})});return e&&typeof e=="function"&&(e=new Promise(e)),e&&Promise.resolve(e).then(r.resolve,t=>t instanceof b?r.reject(t):this.newError(t).consume(r.reject)),r}newFunction(e,r){let t=typeof e=="function"?e:r;if(!t)throw new TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:t.length,isConstructor:!1,fn:t})}newConstructorFunction(e,r){let t=typeof e=="function"?e:r;if(!t)throw new TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:t.length,isConstructor:!0,fn:t})}newFunctionWithOptions(e){let{name:r,length:t,isConstructor:i,fn:u}=e,a=this.runtime.hostRefs.put(u);try{return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,r??"",t,i,a))}catch(m){throw this.runtime.hostRefs.delete(a),m}}newError(e){let r=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));return e&&typeof e=="object"?(e.name!==void 0&&this.newString(e.name).consume(t=>this.setProp(r,"name",t)),e.message!==void 0&&this.newString(e.message).consume(t=>this.setProp(r,"message",t))):typeof e=="string"?this.newString(e).consume(t=>this.setProp(r,"message",t)):e!==void 0&&this.newString(String(e)).consume(t=>this.setProp(r,"message",t)),r}newHostRef(e){let r=this.runtime.hostRefs.put(e);try{let t=this.memory.heapValueHandle(this.ffi.QTS_NewHostRef(this.ctx.value,r));return new Ze(this.runtime,t,r)}catch(t){throw this.runtime.hostRefs.delete(r),t}}toHostRef(e){let r=this.ffi.QTS_GetHostRefId(e.value);if(r!==0)return this.runtime.hostRefs.get(r),new Ze(this.runtime,e.dup(),r)}unwrapHostRef(e){let r=this.ffi.QTS_GetHostRefId(e.value);if(r===0)throw new F("handle is not a HostRef");return this.runtime.hostRefs.get(r)}typeof(e){return this.runtime.assertOwned(e),this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value,e.value))}getNumber(e){return this.runtime.assertOwned(e),this.ffi.QTS_GetFloat64(this.ctx.value,e.value)}getString(e){return this.runtime.assertOwned(e),this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value,e.value))}getSymbol(e){this.runtime.assertOwned(e);let r=this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value,e.value));return this.ffi.QTS_IsGlobalSymbol(this.ctx.value,e.value)?Symbol.for(r):Symbol(r)}getBigInt(e){this.runtime.assertOwned(e);let r=this.getString(e);return BigInt(r)}getArrayBuffer(e){this.runtime.assertOwned(e);let r=this.ffi.QTS_GetArrayBufferLength(this.ctx.value,e.value),t=this.ffi.QTS_GetArrayBuffer(this.ctx.value,e.value);if(!t)throw new Error("Couldn't allocate memory to get ArrayBuffer");return new b(this.module.HEAPU8.subarray(t,t+r),void 0,()=>this.module._free(t))}getPromiseState(e){this.runtime.assertOwned(e);let r=this.ffi.QTS_PromiseState(this.ctx.value,e.value);if(r<0)return{type:"fulfilled",value:e,notAPromise:!0};if(r===ue.Pending)return{type:"pending",get error(){return new st("Cannot unwrap a pending promise")}};let t=this.ffi.QTS_PromiseResult(this.ctx.value,e.value),i=this.memory.heapValueHandle(t);if(r===ue.Fulfilled)return{type:"fulfilled",value:i};if(r===ue.Rejected)return{type:"rejected",error:i};throw i.dispose(),new Error(`Unknown JSPromiseStateEnum: ${r}`)}resolvePromise(e){this.runtime.assertOwned(e);let r=k.withScope(t=>{let i=t.manage(this.getProp(this.global,"Promise")),u=t.manage(this.getProp(i,"resolve"));return this.callFunction(u,i,e)});return r.error?Promise.resolve(r):new Promise(t=>{k.withScope(i=>{let u=i.manage(this.newFunction("resolve",h=>{t(this.success(h&&h.dup()))})),a=i.manage(this.newFunction("reject",h=>{t(this.fail(h&&h.dup()))})),m=i.manage(r.value),l=i.manage(this.getProp(m,"then"));this.callFunction(l,m,u,a).unwrap().dispose()})})}isEqual(e,r,t=te.IsStrictlyEqual){if(e===r)return!0;this.runtime.assertOwned(e),this.runtime.assertOwned(r);let i=this.ffi.QTS_IsEqual(this.ctx.value,e.value,r.value,t);if(i===-1)throw new tt("WASM variant does not expose equality");return!!i}eq(e,r){return this.isEqual(e,r,te.IsStrictlyEqual)}sameValue(e,r){return this.isEqual(e,r,te.IsSameValue)}sameValueZero(e,r){return this.isEqual(e,r,te.IsSameValueZero)}getProp(e,r){this.runtime.assertOwned(e);let t;return typeof r=="number"&&r>=0?t=this.ffi.QTS_GetPropNumber(this.ctx.value,e.value,r):t=this.borrowPropertyKey(r).consume(i=>this.ffi.QTS_GetProp(this.ctx.value,e.value,i.value)),this.memory.heapValueHandle(t)}getLength(e){if(this.runtime.assertOwned(e),!(this.ffi.QTS_GetLength(this.ctx.value,this.uint32Out.value.ptr,e.value)<0))return this.uint32Out.value.typedArray[0]}getOwnPropertyNames(e,r={strings:!0,numbersAsStrings:!0}){this.runtime.assertOwned(e),e.value;let t=qt(r);if(t===0)throw new ot("No options set, will return an empty array");return k.withScope(i=>{let u=i.manage(this.memory.newMutablePointerArray(1)),a=this.ffi.QTS_GetOwnPropertyNames(this.ctx.value,u.value.ptr,this.uint32Out.value.ptr,e.value,t);if(a)return this.fail(this.memory.heapValueHandle(a));let m=this.uint32Out.value.typedArray[0],l=u.value.typedArray[0],h=new Uint32Array(this.module.HEAP8.buffer,l,m),p=Array.from(h).map(y=>this.memory.heapValueHandle(y));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,l),this.success(Bt(p))})}getIterator(e){let r=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return k.withScope(t=>{let i=t.manage(this.getProp(e,r)),u=this.callFunction(i,e);return u.error?u:this.success(new Yt(u.value,this))})}setProp(e,r,t){this.runtime.assertOwned(e),this.borrowPropertyKey(r).consume(i=>this.ffi.QTS_SetProp(this.ctx.value,e.value,i.value,t.value))}defineProp(e,r,t){this.runtime.assertOwned(e),k.withScope(i=>{let u=i.manage(this.borrowPropertyKey(r)),a=t.value||this.undefined,m=!!t.configurable,l=!!t.enumerable,h=!!t.value,p=t.get?i.manage(this.newFunction(t.get.name,t.get)):this.undefined,y=t.set?i.manage(this.newFunction(t.set.name,t.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,e.value,u.value,a.value,p.value,y.value,m,l,h)})}callFunction(e,r,...t){this.runtime.assertOwned(e);let i,u=t[0];u===void 0||Array.isArray(u)?i=u??[]:i=t;let a=this.memory.toPointerArray(i).consume(l=>this.ffi.QTS_Call(this.ctx.value,e.value,r.value,i.length,l.value)),m=this.ffi.QTS_ResolveException(this.ctx.value,a);return m?(this.ffi.QTS_FreeValuePointer(this.ctx.value,a),this.fail(this.memory.heapValueHandle(m))):this.success(this.memory.heapValueHandle(a))}callMethod(e,r,t=[]){return this.getProp(e,r).consume(i=>this.callFunction(i,e,t))}evalCode(e,r="eval.js",t){let i=t===void 0?1:0,u=$t(t),a=this.memory.newHeapCharPointer(e).consume(l=>this.ffi.QTS_Eval(this.ctx.value,l.value.ptr,l.value.strlen,r,i,u)),m=this.ffi.QTS_ResolveException(this.ctx.value,a);return m?(this.ffi.QTS_FreeValuePointer(this.ctx.value,a),this.fail(this.memory.heapValueHandle(m))):this.success(this.memory.heapValueHandle(a))}throw(e){return this.errorToHandle(e).consume(r=>this.ffi.QTS_Throw(this.ctx.value,r.value))}borrowPropertyKey(e){return typeof e=="number"?this.newNumber(e):typeof e=="string"?this.newString(e):new B(e.value,this.runtime)}getMemory(e){if(e===this.rt.value)return this.memory;throw new Error("Private API. Cannot get memory from a different runtime")}dump(e){this.runtime.assertOwned(e);let r=this.typeof(e);if(r==="string")return this.getString(e);if(r==="number")return this.getNumber(e);if(r==="bigint")return this.getBigInt(e);if(r==="undefined")return;if(r==="symbol")return this.getSymbol(e);let t=this.getPromiseState(e);if(t.type==="fulfilled"&&!t.notAPromise)return e.dispose(),{type:t.type,value:t.value.consume(this.dump)};if(t.type==="pending")return e.dispose(),{type:t.type};if(t.type==="rejected")return e.dispose(),{type:t.type,error:t.error.consume(this.dump)};let i=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,e.value));try{return JSON.parse(i)}catch{return i}}unwrapResult(e){if(e.error){let r="context"in e.error?e.error.context:this,t=e.error.consume(i=>this.dump(i));if(t&&typeof t=="object"&&typeof t.message=="string"){let{message:i,name:u,stack:a,...m}=t,l=new xe(t,r);typeof u=="string"&&(l.name=t.name),l.message=i;let h=l.stack;throw typeof a=="string"&&(l.stack=`${u}: ${i}
|
|
6
|
+
${t.stack}Host: ${h}`),Object.assign(l,m),l}throw new xe(t)}return e.value}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getFunction(e){let r=this.runtime.hostRefs.get(e);if(typeof r!="function")throw new Error(`Host reference ${e} is not a function`);return r}errorToHandle(e){return e instanceof b?e:this.newError(e)}encodeBinaryJSON(e){let r=this.ffi.QTS_bjson_encode(this.ctx.value,e.value);return this.memory.heapValueHandle(r)}decodeBinaryJSON(e){let r=this.ffi.QTS_bjson_decode(this.ctx.value,e.value);return this.memory.heapValueHandle(r)}success(e){return W.success(e)}fail(e){return W.fail(e,r=>this.unwrapResult(r))}},tr=class extends C{constructor(e){super(),this.scope=new k,this.contextMap=new Map,this.hostRefs=new Xt,this._debugMode=!1,this.cToHostCallbacks={freeHostRef:(r,t)=>{if(r!==this.rt.value)throw new Error("Runtime pointer mismatch");this.hostRefs.delete(t)},shouldInterrupt:r=>{if(r!==this.rt.value)throw new Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let t=this.interruptHandler;if(!t)throw new Error("QuickJSContext had no interrupt handler");return t(this)?1:0},loadModuleSource:$e(this,function*(r,t,i,u){let a=this.moduleLoader;if(!a)throw new Error("Runtime has no module loader");if(t!==this.rt.value)throw new Error("Runtime pointer mismatch");let m=this.contextMap.get(i)??this.newContext({contextPointer:i});try{let l=yield*r(a(u,m));if(typeof l=="object"&&"error"in l&&l.error)throw this.debugLog("cToHostLoadModule: loader returned error",l.error),l.error;let h=typeof l=="string"?l:"value"in l?l.value:l;return this.memory.newHeapCharPointer(h).value.ptr}catch(l){return this.debugLog("cToHostLoadModule: caught error",l),m.throw(l),0}}),normalizeModule:$e(this,function*(r,t,i,u,a){let m=this.moduleNormalizer;if(!m)throw new Error("Runtime has no module normalizer");if(t!==this.rt.value)throw new Error("Runtime pointer mismatch");let l=this.contextMap.get(i)??this.newContext({contextPointer:i});try{let h=yield*r(m(u,a,l));if(typeof h=="object"&&"error"in h&&h.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",h.error),h.error;let p=typeof h=="string"?h:h.value;return l.getMemory(this.rt.value).newHeapCharPointer(p).value.ptr}catch(h){return this.debugLog("normalizeModule: caught error",h),l.throw(h),0}})},e.ownedLifetimes?.forEach(r=>this.scope.manage(r)),this.module=e.module,this.memory=new ct(this.module),this.ffi=e.ffi,this.rt=e.rt,this.callbacks=e.callbacks,this.scope.manage(this.rt),this.callbacks.setRuntimeCallbacks(this.rt.value,this.cToHostCallbacks),this.executePendingJobs=this.executePendingJobs.bind(this),Ee&&this.setDebugMode(!0)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}newContext(e={}){let r=Wt(e.intrinsics),t=new b(e.contextPointer||this.ffi.QTS_NewContext(this.rt.value,r),void 0,u=>{this.contextMap.delete(u),this.callbacks.deleteContext(u),this.ffi.QTS_FreeContext(u)}),i=new er({module:this.module,ctx:t,ffi:this.ffi,rt:this.rt,ownedLifetimes:e.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(t.value,i),i}setModuleLoader(e,r){this.moduleLoader=e,this.moduleNormalizer=r,this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value,this.moduleNormalizer?1:0)}removeModuleLoader(){this.moduleLoader=void 0,this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value)}hasPendingJob(){return!!this.ffi.QTS_IsJobPending(this.rt.value)}setInterruptHandler(e){let r=this.interruptHandler;this.interruptHandler=e,r||this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value)}removeInterruptHandler(){this.interruptHandler&&(this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value),this.interruptHandler=void 0)}executePendingJobs(e=-1){let r=this.memory.newMutablePointerArray(1),t=this.ffi.QTS_ExecutePendingJob(this.rt.value,e??-1,r.value.ptr),i=r.value.typedArray[0];if(r.dispose(),i===0)return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value,t),W.success(0);let u=this.contextMap.get(i)??this.newContext({contextPointer:i}),a=u.getMemory(this.rt.value).heapValueHandle(t);if(u.typeof(a)==="number"){let m=u.getNumber(a);return a.dispose(),W.success(m)}else{let m=Object.assign(a,{context:u});return W.fail(m,l=>u.unwrapResult(l))}}setMemoryLimit(e){if(e<0&&e!==-1)throw new Error("Cannot set memory limit to negative number. To unset, pass -1");this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value,e)}computeMemoryUsage(){let e=this.getSystemContext().getMemory(this.rt.value);return e.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value,e.ctx.value))}dumpMemoryUsage(){return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))}setMaxStackSize(e){if(e<0)throw new Error("Cannot set memory limit to negative number. To unset, pass 0.");this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value,e)}assertOwned(e){if(e.owner&&e.owner.rt!==this.rt)throw new et(`Handle is not owned by this runtime: ${e.owner.rt.value} != ${this.rt.value}`)}setDebugMode(e){this._debugMode=e,this.ffi.DEBUG&&this.rt.alive&&this.ffi.QTS_SetDebugLogEnabled(this.rt.value,e?1:0)}isDebugMode(){return this._debugMode}debugLog(...e){this._debugMode&&console.log("quickjs-emscripten:",...e)}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getSystemContext(){return this.context||(this.context=this.scope.manage(this.newContext())),this.context}},rr=class{constructor(e){this.freeHostRef=e.freeHostRef,this.callFunction=e.callFunction,this.shouldInterrupt=e.shouldInterrupt,this.loadModuleSource=e.loadModuleSource,this.normalizeModule=e.normalizeModule}},Je=class{constructor(e){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new rr({freeHostRef:(r,t,i)=>{let u=this.runtimeCallbacks.get(t);if(!u)throw new Error(`QuickJSRuntime(rt = ${t}) not found when trying to free HostRef(id = ${i})`);u.freeHostRef(t,i)},callFunction:(r,t,i,u,a,m)=>this.handleAsyncify(r,()=>{try{let l=this.contextCallbacks.get(t);if(!l)throw new Error(`QuickJSContext(ctx = ${t}) not found for C function call "${m}"`);return l.callFunction(t,i,u,a,m)}catch(l){return console.error("[C to host error: returning null]",l),0}}),shouldInterrupt:(r,t)=>this.handleAsyncify(r,()=>{try{let i=this.runtimeCallbacks.get(t);if(!i)throw new Error(`QuickJSRuntime(rt = ${t}) not found for C interrupt`);return i.shouldInterrupt(t)}catch(i){return console.error("[C to host interrupt: returning error]",i),1}}),loadModuleSource:(r,t,i,u)=>this.handleAsyncify(r,()=>{try{let a=this.runtimeCallbacks.get(t);if(!a)throw new Error(`QuickJSRuntime(rt = ${t}) not found for C module loader`);let m=a.loadModuleSource;if(!m)throw new Error(`QuickJSRuntime(rt = ${t}) does not support module loading`);return m(t,i,u)}catch(a){return console.error("[C to host module loader error: returning null]",a),0}}),normalizeModule:(r,t,i,u,a)=>this.handleAsyncify(r,()=>{try{let m=this.runtimeCallbacks.get(t);if(!m)throw new Error(`QuickJSRuntime(rt = ${t}) not found for C module loader`);let l=m.normalizeModule;if(!l)throw new Error(`QuickJSRuntime(rt = ${t}) does not support module loading`);return l(t,i,u,a)}catch(m){return console.error("[C to host module loader error: returning null]",m),0}})}),this.module=e,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(e,r){this.runtimeCallbacks.set(e,r)}deleteRuntime(e){this.runtimeCallbacks.delete(e)}setContextCallbacks(e,r){this.contextCallbacks.set(e,r)}deleteContext(e){this.contextCallbacks.delete(e)}handleAsyncify(e,r){if(e)return e.handleSleep(i=>{try{let u=r();if(!(u instanceof Promise)){re("asyncify.handleSleep: not suspending:",u),i(u);return}if(this.suspended)throw new rt(`Already suspended at: ${this.suspended.stack}
|
|
7
|
+
Attempted to suspend at:`);this.suspended=new it(`(${this.suspendedCount++})`),re("asyncify.handleSleep: suspending:",this.suspended),u.then(a=>{this.suspended=void 0,re("asyncify.handleSleep: resolved:",a),i(a)},a=>{re("asyncify.handleSleep: rejected:",a),console.error("QuickJS: cannot handle error in suspended function",a),this.suspended=void 0})}catch(u){throw re("asyncify.handleSleep: error:",u),this.suspended=void 0,u}});let t=r();if(t instanceof Promise)throw new Error("Promise return value not supported in non-asyncify context.");return t}};ht=class{constructor(e,r){this.module=e,this.ffi=r,this.callbacks=new Je(e)}newRuntime(e={}){let r=new b(this.ffi.QTS_NewRuntime(),void 0,i=>{this.ffi.QTS_FreeRuntime(i),this.callbacks.deleteRuntime(i)}),t=new tr({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:r});return Le(t,e),e.moduleLoader&&t.setModuleLoader(e.moduleLoader),t}newContext(e={}){let r=this.newRuntime(),t=r.newContext({...e,ownedLifetimes:Kt(r,e.ownedLifetimes)});return r.context=t,t}evalCode(e,r={}){return k.withScope(t=>{let i=t.manage(this.newContext());Ce(i.runtime,r);let u=i.evalCode(e,"eval.js");if(r.memoryLimitBytes!==void 0&&i.runtime.setMemoryLimit(-1),u.error)throw i.dump(t.manage(u.error));return i.dump(t.manage(u.value))})}getWasmMemory(){let e=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!e)throw new Error("Variant does not support getting WebAssembly.Memory");return e}getFFI(){return this.ffi}}});var ft={};ae(ft,{QuickJSModuleCallbacks:()=>Je,QuickJSWASMModule:()=>ht,applyBaseRuntimeOptions:()=>Le,applyModuleEvalRuntimeOptions:()=>Ce});var pt=ee(()=>{dt()});var wt={};ae(wt,{QuickJSFFI:()=>ir});var ir,yt=ee(()=>{ir=class{constructor(e){this.module=e,this.DEBUG=!1,this.QTS_Throw=this.module.cwrap("QTS_Throw","number",["number","number"]),this.QTS_NewError=this.module.cwrap("QTS_NewError","number",["number"]),this.QTS_RuntimeSetMemoryLimit=this.module.cwrap("QTS_RuntimeSetMemoryLimit",null,["number","number"]),this.QTS_RuntimeComputeMemoryUsage=this.module.cwrap("QTS_RuntimeComputeMemoryUsage","number",["number","number"]),this.QTS_RuntimeDumpMemoryUsage=this.module.cwrap("QTS_RuntimeDumpMemoryUsage","number",["number"]),this.QTS_RecoverableLeakCheck=this.module.cwrap("QTS_RecoverableLeakCheck","number",[]),this.QTS_BuildIsSanitizeLeak=this.module.cwrap("QTS_BuildIsSanitizeLeak","number",[]),this.QTS_RuntimeSetMaxStackSize=this.module.cwrap("QTS_RuntimeSetMaxStackSize",null,["number","number"]),this.QTS_GetUndefined=this.module.cwrap("QTS_GetUndefined","number",[]),this.QTS_GetNull=this.module.cwrap("QTS_GetNull","number",[]),this.QTS_GetFalse=this.module.cwrap("QTS_GetFalse","number",[]),this.QTS_GetTrue=this.module.cwrap("QTS_GetTrue","number",[]),this.QTS_NewHostRef=this.module.cwrap("QTS_NewHostRef","number",["number","number"]),this.QTS_GetHostRefId=this.module.cwrap("QTS_GetHostRefId","number",["number"]),this.QTS_NewRuntime=this.module.cwrap("QTS_NewRuntime","number",[]),this.QTS_FreeRuntime=this.module.cwrap("QTS_FreeRuntime",null,["number"]),this.QTS_NewContext=this.module.cwrap("QTS_NewContext","number",["number","number"]),this.QTS_FreeContext=this.module.cwrap("QTS_FreeContext",null,["number"]),this.QTS_FreeValuePointer=this.module.cwrap("QTS_FreeValuePointer",null,["number","number"]),this.QTS_FreeValuePointerRuntime=this.module.cwrap("QTS_FreeValuePointerRuntime",null,["number","number"]),this.QTS_FreeVoidPointer=this.module.cwrap("QTS_FreeVoidPointer",null,["number","number"]),this.QTS_FreeCString=this.module.cwrap("QTS_FreeCString",null,["number","number"]),this.QTS_DupValuePointer=this.module.cwrap("QTS_DupValuePointer","number",["number","number"]),this.QTS_NewObject=this.module.cwrap("QTS_NewObject","number",["number"]),this.QTS_NewObjectProto=this.module.cwrap("QTS_NewObjectProto","number",["number","number"]),this.QTS_NewArray=this.module.cwrap("QTS_NewArray","number",["number"]),this.QTS_NewArrayBuffer=this.module.cwrap("QTS_NewArrayBuffer","number",["number","number","number"]),this.QTS_NewFloat64=this.module.cwrap("QTS_NewFloat64","number",["number","number"]),this.QTS_GetFloat64=this.module.cwrap("QTS_GetFloat64","number",["number","number"]),this.QTS_NewString=this.module.cwrap("QTS_NewString","number",["number","number"]),this.QTS_GetString=this.module.cwrap("QTS_GetString","number",["number","number"]),this.QTS_GetArrayBuffer=this.module.cwrap("QTS_GetArrayBuffer","number",["number","number"]),this.QTS_GetArrayBufferLength=this.module.cwrap("QTS_GetArrayBufferLength","number",["number","number"]),this.QTS_NewSymbol=this.module.cwrap("QTS_NewSymbol","number",["number","number","number"]),this.QTS_GetSymbolDescriptionOrKey=this.module.cwrap("QTS_GetSymbolDescriptionOrKey","number",["number","number"]),this.QTS_IsGlobalSymbol=this.module.cwrap("QTS_IsGlobalSymbol","number",["number","number"]),this.QTS_IsJobPending=this.module.cwrap("QTS_IsJobPending","number",["number"]),this.QTS_ExecutePendingJob=this.module.cwrap("QTS_ExecutePendingJob","number",["number","number","number"]),this.QTS_GetProp=this.module.cwrap("QTS_GetProp","number",["number","number","number"]),this.QTS_GetPropNumber=this.module.cwrap("QTS_GetPropNumber","number",["number","number","number"]),this.QTS_SetProp=this.module.cwrap("QTS_SetProp",null,["number","number","number","number"]),this.QTS_DefineProp=this.module.cwrap("QTS_DefineProp",null,["number","number","number","number","number","number","boolean","boolean","boolean"]),this.QTS_GetOwnPropertyNames=this.module.cwrap("QTS_GetOwnPropertyNames","number",["number","number","number","number","number"]),this.QTS_Call=this.module.cwrap("QTS_Call","number",["number","number","number","number","number"]),this.QTS_ResolveException=this.module.cwrap("QTS_ResolveException","number",["number","number"]),this.QTS_Dump=this.module.cwrap("QTS_Dump","number",["number","number"]),this.QTS_Eval=this.module.cwrap("QTS_Eval","number",["number","number","number","string","number","number"]),this.QTS_GetModuleNamespace=this.module.cwrap("QTS_GetModuleNamespace","number",["number","number"]),this.QTS_Typeof=this.module.cwrap("QTS_Typeof","number",["number","number"]),this.QTS_GetLength=this.module.cwrap("QTS_GetLength","number",["number","number","number"]),this.QTS_IsEqual=this.module.cwrap("QTS_IsEqual","number",["number","number","number","number"]),this.QTS_GetGlobalObject=this.module.cwrap("QTS_GetGlobalObject","number",["number"]),this.QTS_NewPromiseCapability=this.module.cwrap("QTS_NewPromiseCapability","number",["number","number"]),this.QTS_PromiseState=this.module.cwrap("QTS_PromiseState","number",["number","number"]),this.QTS_PromiseResult=this.module.cwrap("QTS_PromiseResult","number",["number","number"]),this.QTS_TestStringArg=this.module.cwrap("QTS_TestStringArg",null,["string"]),this.QTS_GetDebugLogEnabled=this.module.cwrap("QTS_GetDebugLogEnabled","number",["number"]),this.QTS_SetDebugLogEnabled=this.module.cwrap("QTS_SetDebugLogEnabled",null,["number","number"]),this.QTS_BuildIsDebug=this.module.cwrap("QTS_BuildIsDebug","number",[]),this.QTS_BuildIsAsyncify=this.module.cwrap("QTS_BuildIsAsyncify","number",[]),this.QTS_NewFunction=this.module.cwrap("QTS_NewFunction","number",["number","string","number","boolean","number"]),this.QTS_ArgvGetJSValueConstPointer=this.module.cwrap("QTS_ArgvGetJSValueConstPointer","number",["number","number"]),this.QTS_RuntimeEnableInterruptHandler=this.module.cwrap("QTS_RuntimeEnableInterruptHandler",null,["number"]),this.QTS_RuntimeDisableInterruptHandler=this.module.cwrap("QTS_RuntimeDisableInterruptHandler",null,["number"]),this.QTS_RuntimeEnableModuleLoader=this.module.cwrap("QTS_RuntimeEnableModuleLoader",null,["number","number"]),this.QTS_RuntimeDisableModuleLoader=this.module.cwrap("QTS_RuntimeDisableModuleLoader",null,["number"]),this.QTS_bjson_encode=this.module.cwrap("QTS_bjson_encode","number",["number","number"]),this.QTS_bjson_decode=this.module.cwrap("QTS_bjson_decode","number",["number","number"])}}});var gt={};ae(gt,{default:()=>sr});async function nr(e={}){var r,t=e,i=!!globalThis.window,u=!!globalThis.WorkerGlobalScope,a=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(a){let{createRequire:n}=await import("node:module");var m=n(import.meta.url)}function l(n){n={log:n||function(){}};for(let o of l.Pa)o(n);return t.quickJSEmscriptenExtensions=n}l.Pa=[],t.quickjsEmscriptenInit=l,l.Pa.push(n=>{n.getWasmMemory=function(){return O}});var h="./this.program",p=(n,o)=>{throw o},y=import.meta.url,f="",T,H;if(a){var q=m("node:fs");y.startsWith("file:")&&(f=m("node:path").dirname(m("node:url").fileURLToPath(y))+"/"),H=n=>(n=M(n)?new URL(n):n,q.readFileSync(n)),T=async n=>(n=M(n)?new URL(n):n,q.readFileSync(n,void 0)),1<process.argv.length&&(h=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),p=(n,o)=>{throw process.exitCode=n,o}}else if(i||u){try{f=new URL(".",y).href}catch{}u&&(H=n=>{var o=new XMLHttpRequest;return o.open("GET",n,!1),o.responseType="arraybuffer",o.send(null),new Uint8Array(o.response)}),T=async n=>{if(M(n))return new Promise((s,c)=>{var d=new XMLHttpRequest;d.open("GET",n,!0),d.responseType="arraybuffer",d.onload=()=>{d.status==200||d.status==0&&d.response?s(d.response):c(d.status)},d.onerror=c,d.send(null)});var o=await fetch(n,{credentials:"same-origin"});if(o.ok)return o.arrayBuffer();throw Error(o.status+" : "+o.url)}}var K=console.log.bind(console),x=console.error.bind(console),P,I=!1,j,M=n=>n.startsWith("file://"),Y,ie,U,E,v,A,X=!1;function ne(){var n=O.buffer;t.HEAP8=U=new Int8Array(n),new Int16Array(n),t.HEAPU8=E=new Uint8Array(n),new Uint16Array(n),v=new Int32Array(n),A=new Uint32Array(n),new Float32Array(n),new Float64Array(n),new BigInt64Array(n),new BigUint64Array(n)}function R(n){throw t.onAbort?.(n),n="Aborted("+n+")",x(n),I=!0,n=new WebAssembly.RuntimeError(n+". Build with -sASSERTIONS for more info."),ie?.(n),n}var pe;async function xt(n){if(!P)try{var o=await T(n);return new Uint8Array(o)}catch{}if(n==pe&&P)n=new Uint8Array(P);else if(H)n=H(n);else throw"both async and sync fetching of the wasm failed";return n}async function Pt(n,o){try{var s=await xt(n);return await WebAssembly.instantiate(s,o)}catch(c){x(`failed to asynchronously prepare wasm: ${c}`),R(c)}}async function Mt(n){var o=pe;if(!P&&!M(o)&&!a)try{var s=fetch(o,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(s,n)}catch(c){x(`wasm streaming compile failed: ${c}`),x("falling back to ArrayBuffer instantiation")}return Pt(o,n)}class Se{name="ExitStatus";constructor(o){this.message=`Program terminated with exit(${o})`,this.status=o}}var He=n=>{for(;0<n.length;)n.shift()(t)},Oe=[],Ge=[],Et=()=>{var n=t.preRun.shift();Ge.push(n)},se=!0,O,De=new TextDecoder,Ve=(n,o,s,c)=>{if(s=o+s,c)return s;for(;n[o]&&!(o>=s);)++o;return o},N=(n,o,s)=>n?De.decode(E.subarray(n,Ve(E,n,o,s))):"",we=0,At=[0,31,60,91,121,152,182,213,244,274,305,335],Rt=[0,31,59,90,120,151,181,212,243,273,304,334],Z={},Be=n=>{j=n,se||0<we||(t.onExit?.(n),I=!0),p(n,new Se(n))},kt=n=>{if(!I)try{n()}catch(o){o instanceof Se||o=="unwind"||p(1,o)}finally{if(!(se||0<we))try{j=n=j,Be(n)}catch(o){o instanceof Se||o=="unwind"||p(1,o)}}},G=(n,o,s)=>{var c=E;if(!(0<s))return 0;var d=o;s=o+s-1;for(var S=0;S<n.length;++S){var w=n.codePointAt(S);if(127>=w){if(o>=s)break;c[o++]=w}else if(2047>=w){if(o+1>=s)break;c[o++]=192|w>>6,c[o++]=128|w&63}else if(65535>=w){if(o+2>=s)break;c[o++]=224|w>>12,c[o++]=128|w>>6&63,c[o++]=128|w&63}else{if(o+3>=s)break;c[o++]=240|w>>18,c[o++]=128|w>>12&63,c[o++]=128|w>>6&63,c[o++]=128|w&63,S++}}return c[o]=0,o-d},ye={},je=()=>{if(!ge){var n={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:h||"./this.program"},o;for(o in ye)ye[o]===void 0?delete n[o]:n[o]=ye[o];var s=[];for(o in n)s.push(`${o}=${n[o]}`);ge=s}return ge},ge,_e=n=>{for(var o=0,s=0;s<n.length;++s){var c=n.charCodeAt(s);127>=c?o++:2047>=c?o+=2:55296<=c&&57343>=c?(o+=4,++s):o+=3}return o},Jt=[null,[],[]],Lt=(n,o,s,c)=>{var d={string:g=>{var _=0;if(g!=null&&g!==0){_=_e(g)+1;var L=ve(_);G(g,L,_),_=L}return _},array:g=>{var _=ve(g.length);return U.set(g,_),_}};n=t["_"+n];var S=[],w=0;if(c)for(var Q=0;Q<c.length;Q++){var z=d[s[Q]];z?(w===0&&(w=We()),S[Q]=z(c[Q])):S[Q]=c[Q]}return s=n(...S),s=(function(g){return w!==0&&ze(w),o==="string"?N(g):o==="boolean"?!!g:g})(s)};if(t.wasmMemory?O=t.wasmMemory:O=new WebAssembly.Memory({initial:(t.INITIAL_MEMORY||16777216)/65536,maximum:32768}),ne(),t.noExitRuntime&&(se=t.noExitRuntime),t.print&&(K=t.print),t.printErr&&(x=t.printErr),t.wasmBinary&&(P=t.wasmBinary),t.thisProgram&&(h=t.thisProgram),t.preInit)for(typeof t.preInit=="function"&&(t.preInit=[t.preInit]);0<t.preInit.length;)t.preInit.shift()();t.cwrap=(n,o,s,c)=>{var d=!s||s.every(S=>S==="number"||S==="boolean");return o!=="string"&&d&&!c?t["_"+n]:(...S)=>Lt(n,o,s,S)},t.UTF8ToString=N,t.stringToUTF8=(n,o,s)=>G(n,o,s),t.lengthBytesUTF8=_e;var Ue,ze,ve,We,Ct={b:(n,o,s,c)=>R(`Assertion failed: ${N(n)}, at: `+[o?N(o):"unknown filename",s,c?N(c):"unknown function"]),q:()=>R(""),l:()=>{se=!1,we=0},m:function(n,o){n=-9007199254740992>n||9007199254740992<n?NaN:Number(n),n=new Date(1e3*n),v[o>>2]=n.getSeconds(),v[o+4>>2]=n.getMinutes(),v[o+8>>2]=n.getHours(),v[o+12>>2]=n.getDate(),v[o+16>>2]=n.getMonth(),v[o+20>>2]=n.getFullYear()-1900,v[o+24>>2]=n.getDay();var s=n.getFullYear();v[o+28>>2]=(s%4!==0||s%100===0&&s%400!==0?Rt:At)[n.getMonth()]+n.getDate()-1|0,v[o+36>>2]=-(60*n.getTimezoneOffset()),s=new Date(n.getFullYear(),6,1).getTimezoneOffset();var c=new Date(n.getFullYear(),0,1).getTimezoneOffset();v[o+32>>2]=(s!=c&&n.getTimezoneOffset()==Math.min(c,s))|0},j:(n,o)=>{if(Z[n]&&(clearTimeout(Z[n].id),delete Z[n]),!o)return 0;var s=setTimeout(()=>{delete Z[n],kt(()=>Ue(n,performance.now()))},o);return Z[n]={id:s,Qa:o},0},n:(n,o,s,c)=>{var d=new Date().getFullYear(),S=new Date(d,0,1).getTimezoneOffset();d=new Date(d,6,1).getTimezoneOffset(),A[n>>2]=60*Math.max(S,d),v[o>>2]=+(S!=d),o=w=>{var Q=Math.abs(w);return`UTC${0<=w?"-":"+"}${String(Math.floor(Q/60)).padStart(2,"0")}${String(Q%60).padStart(2,"0")}`},n=o(S),o=o(d),d<S?(G(n,s,17),G(o,c,17)):(G(n,c,17),G(o,s,17))},p:()=>Date.now(),k:n=>{var o=E.length;if(n>>>=0,2147483648<n)return!1;for(var s=1;4>=s;s*=2){var c=o*(1+.2/s);c=Math.min(c,n+100663296);e:{c=(Math.min(2147483648,65536*Math.ceil(Math.max(n,c)/65536))-O.buffer.byteLength+65535)/65536|0;try{O.grow(c),ne();var d=1;break e}catch{}d=void 0}if(d)return!0}return!1},e:(n,o)=>{var s=0,c=0,d;for(d of je()){var S=o+s;A[n+c>>2]=S,s+=G(d,S,1/0)+1,c+=4}return 0},f:(n,o)=>{var s=je();A[n>>2]=s.length,n=0;for(var c of s)n+=_e(c)+1;return A[o>>2]=n,0},d:()=>52,o:function(){return 70},c:(n,o,s,c)=>{for(var d=0,S=0;S<s;S++){var w=A[o>>2],Q=A[o+4>>2];o+=8;for(var z=0;z<Q;z++){var g=n,_=E[w+z],L=Jt[g];_===0||_===10?(g=g===1?K:x,_=Ve(L,0),_=De.decode(L.buffer?L.subarray(0,_):new Uint8Array(L.slice(0,_))),g(_),L.length=0):L.push(_)}d+=Q}return A[c>>2]=d,0},a:O,r:Be,s:function(n,o,s,c,d){return t.callbacks.callFunction(void 0,n,o,s,c,d)},i:function(n){return t.callbacks.shouldInterrupt(void 0,n)},h:function(n,o,s){return s=N(s),t.callbacks.loadModuleSource(void 0,n,o,s)},g:function(n,o,s,c){return s=N(s),c=N(c),t.callbacks.normalizeModule(void 0,n,o,s,c)},t:function(n,o){t.callbacks.freeHostRef(void 0,n,o)}},oe;return oe=await(async function(){function n(s){return s=oe=s.exports,t._malloc=s.v,t._QTS_Throw=s.w,t._QTS_NewError=s.x,t._QTS_RuntimeSetMemoryLimit=s.y,t._QTS_RuntimeComputeMemoryUsage=s.z,t._QTS_RuntimeDumpMemoryUsage=s.A,t._QTS_RecoverableLeakCheck=s.B,t._QTS_BuildIsSanitizeLeak=s.C,t._QTS_RuntimeSetMaxStackSize=s.D,t._QTS_GetUndefined=s.E,t._QTS_GetNull=s.F,t._QTS_GetFalse=s.G,t._QTS_GetTrue=s.H,t._QTS_NewHostRef=s.I,t._QTS_GetHostRefId=s.J,t._QTS_NewRuntime=s.K,t._QTS_FreeRuntime=s.L,t._free=s.M,t._QTS_NewContext=s.N,t._QTS_FreeContext=s.O,t._QTS_FreeValuePointer=s.P,t._QTS_FreeValuePointerRuntime=s.Q,t._QTS_FreeVoidPointer=s.R,t._QTS_FreeCString=s.S,t._QTS_DupValuePointer=s.T,t._QTS_NewObject=s.U,t._QTS_NewObjectProto=s.V,t._QTS_NewArray=s.W,t._QTS_NewArrayBuffer=s.X,t._QTS_NewFloat64=s.Y,t._QTS_GetFloat64=s.Z,t._QTS_NewString=s._,t._QTS_GetString=s.$,t._QTS_GetArrayBuffer=s.aa,t._QTS_GetArrayBufferLength=s.ba,t._QTS_NewSymbol=s.ca,t._QTS_GetSymbolDescriptionOrKey=s.da,t._QTS_IsGlobalSymbol=s.ea,t._QTS_IsJobPending=s.fa,t._QTS_ExecutePendingJob=s.ga,t._QTS_GetProp=s.ha,t._QTS_GetPropNumber=s.ia,t._QTS_SetProp=s.ja,t._QTS_DefineProp=s.ka,t._QTS_GetOwnPropertyNames=s.la,t._QTS_Call=s.ma,t._QTS_ResolveException=s.na,t._QTS_Dump=s.oa,t._QTS_Eval=s.pa,t._QTS_GetModuleNamespace=s.qa,t._QTS_Typeof=s.ra,t._QTS_GetLength=s.sa,t._QTS_IsEqual=s.ta,t._QTS_GetGlobalObject=s.ua,t._QTS_NewPromiseCapability=s.va,t._QTS_PromiseState=s.wa,t._QTS_PromiseResult=s.xa,t._QTS_TestStringArg=s.ya,t._QTS_GetDebugLogEnabled=s.za,t._QTS_SetDebugLogEnabled=s.Aa,t._QTS_BuildIsDebug=s.Ba,t._QTS_BuildIsAsyncify=s.Ca,t._QTS_NewFunction=s.Da,t._QTS_ArgvGetJSValueConstPointer=s.Ea,t._QTS_RuntimeEnableInterruptHandler=s.Fa,t._QTS_RuntimeDisableInterruptHandler=s.Ga,t._QTS_RuntimeEnableModuleLoader=s.Ha,t._QTS_RuntimeDisableModuleLoader=s.Ia,t._QTS_bjson_encode=s.Ja,t._QTS_bjson_decode=s.Ka,Ue=s.La,ze=s.Ma,ve=s.Na,We=s.Oa,oe}var o={a:Ct};return t.instantiateWasm?new Promise(s=>{t.instantiateWasm(o,(c,d)=>{s(n(c,d))})}):(pe??=t.locateFile?t.locateFile?t.locateFile("emscripten-module.wasm",f):f+"emscripten-module.wasm":new URL("emscripten-module.wasm",import.meta.url).href,n((await Mt(o)).instance))})(),(function(){function n(){if(t.calledRun=!0,!I){if(X=!0,oe.u(),Y?.(t),t.onRuntimeInitialized?.(),t.postRun)for(typeof t.postRun=="function"&&(t.postRun=[t.postRun]);t.postRun.length;){var o=t.postRun.shift();Oe.push(o)}He(Oe)}}if(t.preRun)for(typeof t.preRun=="function"&&(t.preRun=[t.preRun]);t.preRun.length;)Et();He(Ge),t.setStatus?(t.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>t.setStatus(""),1),n()},1)):n()})(),X?r=t:r=new Promise((n,o)=>{Y=n,ie=o}),r}var sr,_t=ee(()=>{sr=nr});import{parentPort as ar}from"node:worker_threads";le();async function St(e){let r=Ie(await e),[t,i,{QuickJSWASMModule:u}]=await Promise.all([r.importModuleLoader().then(Ie),r.importFFI(),Promise.resolve().then(()=>(pt(),ft)).then(Ie)]),a=await t();a.type="sync";let m=new i(a);return new u(a,m)}function Ie(e){return e&&"default"in e&&e.default?e.default&&"default"in e.default&&e.default.default?e.default.default:e.default:e}var Fe={};ae(Fe,{default:()=>Ne});var or={type:"sync",importFFI:()=>Promise.resolve().then(()=>(yt(),wt)).then(e=>e.QuickJSFFI),importModuleLoader:()=>Promise.resolve().then(()=>(_t(),gt)).then(e=>e.default)},Ne=or;var ur=Ne??Fe,lr=(e,r)=>String.raw`
|
|
8
|
+
(() => {
|
|
9
|
+
const puerta = globalThis.__puerta;
|
|
10
|
+
delete globalThis.__puerta;
|
|
11
|
+
let vuelo = 0;
|
|
12
|
+
const turno = [];
|
|
13
|
+
const pedir = async (que, datos) => {
|
|
14
|
+
const t = JSON.stringify(datos === undefined ? null : datos);
|
|
15
|
+
if (typeof t === "string" && t.length > ${e}) throw new RangeError("lo que se manda al CRM pasa de ${Math.round(e/1024)} KB");
|
|
16
|
+
while (vuelo >= ${r}) await new Promise((r) => turno.push(r));
|
|
17
|
+
vuelo++;
|
|
18
|
+
try { return JSON.parse(await puerta(que, t)); } finally { vuelo--; const r = turno.shift(); if (r) r(); }
|
|
19
|
+
};
|
|
20
|
+
const modulo = (m) => { if (typeof m !== "string" || !m) throw new TypeError("crm: el módulo es un texto («contactos», «mod_vehiculos»)."); return m; };
|
|
21
|
+
const almacen = Object.freeze({
|
|
22
|
+
leer: (clave) => pedir("crm", { op: "almacen.leer", args: { clave } }),
|
|
23
|
+
listar: (args) => pedir("crm", { op: "almacen.listar", args: args ?? {} }),
|
|
24
|
+
guardar: (clave, valor) => pedir("crm", { op: "almacen.guardar", args: { clave, valor } }),
|
|
25
|
+
borrar: (clave) => pedir("crm", { op: "almacen.borrar", args: { clave } }),
|
|
26
|
+
});
|
|
27
|
+
const crm = Object.freeze({
|
|
28
|
+
llamar: (op, args) => pedir("crm", { op, args: args ?? {} }),
|
|
29
|
+
ver: (m, id) => pedir("crm", { accion: "ver", modulo: modulo(m), args: { id } }),
|
|
30
|
+
buscar: (m, args) => pedir("crm", { accion: "buscar", modulo: modulo(m), args: args ?? {} }),
|
|
31
|
+
crear: (m, valores) => pedir("crm", { accion: "crear", modulo: modulo(m), args: valores ?? {} }),
|
|
32
|
+
actualizar: (m, id, valores) => pedir("crm", { accion: "actualizar", modulo: modulo(m), args: { ...(valores ?? {}), id } }),
|
|
33
|
+
almacen,
|
|
34
|
+
});
|
|
35
|
+
const respuesta = (r) => Object.freeze({
|
|
36
|
+
status: r.status, ok: r.status >= 200 && r.status < 300, headers: Object.freeze({ ...r.headers }),
|
|
37
|
+
text: async () => r.cuerpo, json: async () => JSON.parse(r.cuerpo),
|
|
38
|
+
});
|
|
39
|
+
const fetch = async (url, op) => {
|
|
40
|
+
const o = op ?? {};
|
|
41
|
+
const cuerpo = o.body === undefined || o.body === null ? null : typeof o.body === "string" ? o.body : JSON.stringify(o.body);
|
|
42
|
+
return respuesta(await pedir("red", { url: String(url), metodo: o.method ?? "GET", cabeceras: o.headers ?? {}, cuerpo }));
|
|
43
|
+
};
|
|
44
|
+
Object.defineProperty(globalThis, "crm", { value: crm, enumerable: true });
|
|
45
|
+
Object.defineProperty(globalThis, "fetch", { value: fetch, enumerable: true });
|
|
46
|
+
// Sin salida a ningún sitio: lo que se escribe aquí podría llevar datos del cliente.
|
|
47
|
+
Object.defineProperty(globalThis, "console", { value: Object.freeze({ log() {}, info() {}, warn() {}, error() {} }), enumerable: false });
|
|
48
|
+
})();
|
|
49
|
+
`,bt=ar,mr=0,$=new Map,de=null;bt.on("message",e=>{if(e.tipo==="correr")dr(e);else if(e.tipo==="respuesta"){let r=$.get(e.n);if(!r)return;$.delete(e.n);let t=r.ctx.newString(e.valor);if(e.ok)r.d.resolve(t);else{let i=r.ctx.newError(e.valor);r.d.reject(i),i.dispose()}t.dispose(),r.d.dispose(),de?.()}});var J=e=>bt.postMessage(e),Tt=1024*1024,cr=8*Tt,fe=null,Qt=0,hr=WebAssembly.Memory.prototype.grow;WebAssembly.Memory.prototype.grow=function(e){if(this===fe&&this.buffer.byteLength+e*65536>Qt)throw new RangeError("tope de memoria de la funci\xF3n");return hr.call(this,e)};async function dr(e){let r=Date.now()+e.ms,t=await St(ur);fe=t.getWasmMemory(),Qt=fe.buffer.byteLength+e.memoriaMb*Tt+cr;let i=t.newRuntime();i.setMemoryLimit(e.memoriaMb*1024*1024),i.setMaxStackSize(e.pilaBytes);let u=!1;i.setInterruptHandler(()=>Date.now()>r?u=!0:!1);let a=i.newContext(),m=(l,h)=>{let p=l?a.dump(l):null,y=typeof p?.name=="string"?p.name.slice(0,60):"Error",f=typeof p?.message=="string"?p.message:typeof p=="string"?p:l&&p===null?"out of memory":h;return{tipo:"fin",ok:!1,corte:u||/interrupted/.test(f)?"tiempo":l&&p===null||/out of memory/i.test(f)?"memoria":null,clase:y,mensaje:f.slice(0,500)}};try{let l=a.newFunction("__puerta",(ie,U)=>{let E=a.newPromise(),v=1/0;if(a.typeof(U)==="string"){let R=a.getProp(U,"length");v=a.getNumber(R),R.dispose()}let A=0;for(let R of $.values())R.ctx===a&&A++;if(!(v<=e.llamadaCaracteres)||A>=e.enVuelo){let R=a.newError({name:"RangeError",message:v<=e.llamadaCaracteres?"demasiadas llamadas a la vez":"lo que se manda al CRM es demasiado grande"});return E.reject(R),R.dispose(),E.handle}let X=++mr;$.set(X,{ctx:a,d:E});let ne=a.getString(ie);return J({tipo:"llamar",n:X,que:ne==="red"?"red":"crm",datos:a.getString(U)}),E.handle});a.setProp(a.global,"__puerta",l),l.dispose(),a.unwrapResult(a.evalCode(lr(e.llamadaCaracteres,e.enVuelo),"forgenex-preludio.js")).dispose();let h=a.evalCode(e.codigo,e.fichero,{type:"module"});if(h.error){J(m(h.error,"no se puede cargar")),h.error.dispose();return}let p=h.value,y=await vt(a,i,p,r);if(p.dispose(),"fallo"in y){J(m(y.fallo,"no se puede cargar")),y.fallo?.dispose();return}p=y.valor;let f=a.getProp(p,"default");if(p.dispose(),a.typeof(f)!=="function"){f.dispose(),J({tipo:"fin",ok:!1,corte:null,clase:"TypeError",mensaje:"el fichero no exporta una funci\xF3n por defecto (export default async function \u2026)"});return}let T=a.unwrapResult(a.evalCode(`(${JSON.stringify(JSON.stringify(e.entrada??null))})`)),H=a.unwrapResult(a.evalCode("JSON.parse")),q=a.unwrapResult(a.callFunction(H,a.undefined,T));H.dispose(),T.dispose();let K=a.unwrapResult(a.evalCode(`Object.freeze(${JSON.stringify(e.contexto??{})})`)),x=a.callFunction(f,a.undefined,q,K);if(f.dispose(),q.dispose(),K.dispose(),x.error){J(m(x.error,"error")),x.error.dispose();return}let P=await vt(a,i,x.value,r);if(x.value.dispose(),"fallo"in P){J(m(P.fallo,"error")),P.fallo?.dispose();return}let I=a.getProp(a.global,"JSON"),j=a.getProp(I,"stringify"),M=a.callFunction(j,I,P.valor);if(I.dispose(),j.dispose(),P.valor.dispose(),M.error){J(m(M.error,"la salida no es JSON")),M.error.dispose();return}let Y=a.typeof(M.value)==="string"?a.getString(M.value):"null";if(M.value.dispose(),Buffer.byteLength(Y)>e.salidaBytes){J({tipo:"fin",ok:!1,corte:null,clase:"RangeError",mensaje:`la salida pasa de ${Math.round(e.salidaBytes/1024)} KB`});return}J({tipo:"fin",ok:!0,salida:JSON.parse(Y)})}catch(l){let h=l?.message??String(l);J({tipo:"fin",ok:!1,corte:/out of memory|memory access|tope de memoria/i.test(h)?"memoria":u?"tiempo":null,clase:"Error",mensaje:h.slice(0,500)})}finally{for(let[l,h]of $)if(h.ctx===a){$.delete(l);try{h.d.dispose()}catch{}}try{a.dispose(),i.dispose()}catch{}fe=null}}async function vt(e,r,t,i){for(;;){let u=r.executePendingJobs();if(u.error)return{fallo:u.error};let a=e.getPromiseState(t);if(a.type==="fulfilled")return a.notAPromise?{valor:t.dup()}:{valor:a.value};if(a.type==="rejected")return{fallo:a.error};if(Date.now()>i)return{fallo:e.newError("interrupted")};await new Promise(m=>{let l=setTimeout(()=>{de=null,m()},Math.max(1,i-Date.now()));de=()=>{clearTimeout(l),de=null,m()}})}}
|
|
Binary file
|