quickjs-emscripten-sync 1.8.3 → 1.9.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.
@@ -1,23 +1,23 @@
1
- (function(m,v){typeof exports=="object"&&typeof module!="undefined"?v(exports):typeof define=="function"&&define.amd?define(["exports"],v):(m=typeof globalThis!="undefined"?globalThis:m||self,v(m.QuickjsEmscriptenSync={}))})(this,(function(m){"use strict";var be=Object.defineProperty;var ve=(m,v,j)=>v in m?be(m,v,{enumerable:!0,configurable:!0,writable:!0,value:j}):m[v]=j;var c=(m,v,j)=>ve(m,typeof v!="symbol"?v+"":v,j);const v=n=>{const e=new j(n);return new Proxy(n,{get(t,r,s){return r in e?e[r]:Reflect.get(t,r,s)}})};class j{constructor(e){c(this,"context");c(this,"fn");c(this,"fnGenerator");c(this,"fnCounter",Number.MIN_SAFE_INTEGER);c(this,"fnMap",new Map);c(this,"newFunction",(e,t)=>{this.fnCounter++;const r=this.fnCounter;return this.fnMap.set(r,t),this.context.unwrapResult(this.context.callFunction(this.fnGenerator,this.context.undefined,this.context.newString(e),this.context.newNumber(t.length),this.context.newNumber(r),this.fn))});this.context=e;const t=this.fnMap;this.fn=this.context.newFunction("",function(r,...s){const o=e.getNumber(r),i=t.get(o);if(!i)throw new Error("function is not registered");return i.call(this,...s)}),this.fnGenerator=e.unwrapResult(e.evalCode(`((name, length, id, f) => {
1
+ (function(m,w){typeof exports=="object"&&typeof module!="undefined"?w(exports):typeof define=="function"&&define.amd?define(["exports"],w):(m=typeof globalThis!="undefined"?globalThis:m||self,w(m.QuickjsEmscriptenSync={}))})(this,(function(m){"use strict";var Fe=Object.defineProperty;var x=Object.getOwnPropertySymbols;var Ie=Object.prototype.hasOwnProperty,Ne=Object.prototype.propertyIsEnumerable;var G=(m,w,g)=>w in m?Fe(m,w,{enumerable:!0,configurable:!0,writable:!0,value:g}):m[w]=g,ee=(m,w)=>{for(var g in w||(w={}))Ie.call(w,g)&&G(m,g,w[g]);if(x)for(var g of x(w))Ne.call(w,g)&&G(m,g,w[g]);return m};var p=(m,w,g)=>G(m,typeof w!="symbol"?w+"":w,g);var te=(m,w,g)=>new Promise((M,k)=>{var I=O=>{try{H(g.next(O))}catch(y){k(y)}},T=O=>{try{H(g.throw(O))}catch(y){k(y)}},H=O=>O.done?M(O.value):Promise.resolve(O.value).then(I,T);H((g=g.apply(m,w)).next())});const w=n=>{const e=new g(n);return new Proxy(n,{get(t,r,s){return r in e?e[r]:Reflect.get(t,r,s)}})};class g{constructor(e){p(this,"context");p(this,"fn");p(this,"fnGenerator");p(this,"fnCounter",Number.MIN_SAFE_INTEGER);p(this,"fnMap",new Map);p(this,"newFunction",(e,t)=>{this.fnCounter++;const r=this.fnCounter;return this.fnMap.set(r,t),this.context.unwrapResult(this.context.callFunction(this.fnGenerator,this.context.undefined,this.context.newString(e),this.context.newNumber(t.length),this.context.newNumber(r),this.fn))});this.context=e;const t=this.fnMap;this.fn=this.context.newFunction("",function(r,...s){const i=e.getNumber(r),o=t.get(i);if(!o)throw new Error("function is not registered");return o.call(this,...s)}),this.fnGenerator=e.unwrapResult(e.evalCode(`((name, length, id, f) => {
2
2
  const fn = function(...args) {
3
3
  return f.call(this, id, ...args);
4
4
  };
5
5
  fn.name = name;
6
6
  fn.length = length;
7
7
  return fn;
8
- })`))}disposeEx(){this.fnGenerator.dispose(),this.fn.dispose()}}const k=[[Symbol,"Symbol"],[Symbol.prototype,"Symbol.prototype"],[Object,"Object"],[Object.prototype,"Object.prototype"],[Function,"Function"],[Function.prototype,"Function.prototype"],[Boolean,"Boolean"],[Boolean.prototype,"Boolean.prototype"],[Array,"Array"],[Array.prototype,"Array.prototype"],[Error,"Error"],[Error.prototype,"Error.prototype"],[EvalError,"EvalError"],[EvalError.prototype,"EvalError.prototype"],[RangeError,"RangeError"],[RangeError.prototype,"RangeError.prototype"],[ReferenceError,"ReferenceError"],[ReferenceError.prototype,"ReferenceError.prototype"],[SyntaxError,"SyntaxError"],[SyntaxError.prototype,"SyntaxError.prototype"],[TypeError,"TypeError"],[TypeError.prototype,"TypeError.prototype"],[URIError,"URIError"],[URIError.prototype,"URIError.prototype"],...Object.getOwnPropertyNames(Symbol).filter(n=>typeof Symbol[n]=="symbol").map(n=>[Symbol[n],`Symbol.${n}`])];function G(n,e){const t=n.unwrapResult(n.evalCode(e)),r=(o,...i)=>n.unwrapResult(n.callFunction(t,o!=null?o:n.undefined,...i)),s=()=>t.dispose();return r.dispose=s,r[Symbol.dispose]=s,r.alive=!0,Object.defineProperty(r,"alive",{get:()=>t.alive}),r}function _(n,e,t,...r){const s=G(n,e);try{return s(t,...r)}finally{s.dispose()}}function J(n,e,t){return n.dump(_(n,"(a, b) => a instanceof b",void 0,e,t))}function C(n,e){return n.dump(_(n,'a => typeof a === "object" && a !== null || typeof a === "function"',void 0,e))}function F(n,e){const t=JSON.stringify(e);return t?_(n,"JSON.parse",void 0,n.newString(t)):n.undefined}function W(n,e){try{return e(n)}finally{for(const t of n)t.alive&&t.dispose()}}function z([n,e],t){try{return t(n)}finally{e&&n.dispose()}}function S(n,e){try{return e(...n.map(t=>t[0]))}finally{for(const[t,r]of n)r&&t.dispose()}}function $(n){return"handle"in n}function V(n){return $(n)?n.handle:n}function L(n,e,t,r){var o;let s;for(const i of r)if(s=i(e,n),s)break;return s?(o=t(e,s))!=null?o:s:void 0}function Q(n,e){return typeof n!="symbol"?void 0:_(e,"d => Symbol(d)",void 0,n.description?e.newString(n.description):e.undefined)}function q(n,e){return n instanceof Date?_(e,"d => new Date(d)",void 0,e.newNumber(n.getTime())):void 0}const X=[Q,q];function H(n){return typeof n=="function"&&/^class\s/.test(Function.prototype.toString.call(n))}function g(n){return typeof n=="function"||typeof n=="object"&&n!==null}function O(n,e){const t=new Set,r=s=>{if(!(!g(s)||t.has(s)||(e==null?void 0:e(s,t))===!1)){if(t.add(s),Array.isArray(s)){for(const o of s)r(o);return}if(typeof s=="object"){const o=Object.getPrototypeOf(s);o&&o!==Object.prototype&&r(o)}for(const o of Object.values(Object.getOwnPropertyDescriptors(s)))"value"in o&&r(o.value),"get"in o&&r(o.get),"set"in o&&r(o.set)}};return r(n),t}function Y(n,e){return O(n,e?(t,r)=>r.size<e:void 0).size}function Z(){let n=()=>{},e=()=>{};return{promise:new Promise((r,s)=>{n=r,e=s}),resolve:n,reject:e}}function N(n,e,t,r){const s=n.newObject(),o=(a,u)=>{const p=r(a),l=typeof u.value=="undefined"?void 0:r(u.value),f=typeof u.get=="undefined"?void 0:r(u.get),d=typeof u.set=="undefined"?void 0:r(u.set);n.newObject().consume(h=>{Object.entries(u).forEach(([y,b])=>{const w=y==="value"?l:y==="get"?f:y==="set"?d:b?n.true:n.false;w&&n.setProp(h,y,w)}),n.setProp(s,p,h)})},i=Object.getOwnPropertyDescriptors(e);Object.entries(i).forEach(([a,u])=>o(a,u)),Object.getOwnPropertySymbols(i).forEach(a=>o(a,i[a])),_(n,"Object.defineProperties",void 0,t,s).dispose(),s.dispose()}function K(n,e,t,r,s,o){var u;if(typeof e!="function")return;const i=n.newFunction(e.name,function(...p){const l=r(this),f=p.map(d=>r(d));if(H(e)&&g(l)){const d=new e(...f);return Object.entries(d).forEach(([h,y])=>{n.setProp(this,h,t(y))}),this}return t(o?o(e,l,f):e.apply(l,f))}).consume(p=>_(n,`Cls => {
8
+ })`))}disposeEx(){this.fnGenerator.dispose(),this.fn.dispose()}}const M=[[Symbol,"Symbol"],[Symbol.prototype,"Symbol.prototype"],[Object,"Object"],[Object.prototype,"Object.prototype"],[Function,"Function"],[Function.prototype,"Function.prototype"],[Boolean,"Boolean"],[Boolean.prototype,"Boolean.prototype"],[Array,"Array"],[Array.prototype,"Array.prototype"],[Error,"Error"],[Error.prototype,"Error.prototype"],[EvalError,"EvalError"],[EvalError.prototype,"EvalError.prototype"],[RangeError,"RangeError"],[RangeError.prototype,"RangeError.prototype"],[ReferenceError,"ReferenceError"],[ReferenceError.prototype,"ReferenceError.prototype"],[SyntaxError,"SyntaxError"],[SyntaxError.prototype,"SyntaxError.prototype"],[TypeError,"TypeError"],[TypeError.prototype,"TypeError.prototype"],[URIError,"URIError"],[URIError.prototype,"URIError.prototype"],...Object.getOwnPropertyNames(Symbol).filter(n=>typeof Symbol[n]=="symbol").map(n=>[Symbol[n],`Symbol.${n}`])];function k(n,e){if("error"in e&&e.error){const{error:t}=e;let r;try{r=n.dump(t)}catch(i){}finally{t.alive&&t.dispose()}const s=new Error(typeof r=="object"&&r&&"message"in r?String(r.message):r!==void 0?String(r):"quickjs-emscripten-sync: VM evaluation failed");throw typeof r=="object"&&r&&("name"in r&&(s.name=String(r.name)),"stack"in r&&(s.stack=String(r.stack))),s}return e.value}function I(n,e){const t=k(n,n.evalCode(e)),r=(i,...o)=>k(n,n.callFunction(t,i!=null?i:n.undefined,...o)),s=()=>t.dispose();return r.dispose=s,r[Symbol.dispose]=s,Object.defineProperty(r,"alive",{get:()=>t.alive}),r}const T=new WeakMap;function H(n){T.has(n)||T.set(n,new Map)}function O(n){const e=T.get(n);if(e){for(const t of e.values())t.alive&&t.dispose();T.delete(n)}}function y(n,e,t,...r){const s=T.get(n);if(!s){const o=I(n,e);try{return o(t,...r)}finally{o.dispose()}}let i=s.get(e);return(!i||!i.alive)&&(i=k(n,n.evalCode(e)),s.set(e,i)),k(n,n.callFunction(i,t!=null?t:n.undefined,...r))}function ne(n,e,t){return n.dump(y(n,"(a, b) => a instanceof b",void 0,e,t))}function J(n,e){const t=n.typeof(e);return t==="function"||t==="object"&&!n.sameValue(e,n.null)}function W(n,e){const t=JSON.stringify(e);return t?y(n,"JSON.parse",void 0,n.newString(t)):n.undefined}function S(n,e){try{return e(n)}finally{n.alive&&n.dispose()}}function z(n,e){try{return e(n)}finally{for(const t of n)t.alive&&t.dispose()}}function re([n,e],t){try{return t(n)}finally{e&&n.dispose()}}function C(n,e){try{return e(...n.map(t=>t[0]))}finally{for(const[t,r]of n)r&&t.dispose()}}function se(n){return"handle"in n}function ie(n){return se(n)?n.handle:n}function oe(n,e,t,r){var i;let s;for(const o of r)if(s=o(e,n),s)break;return s?(i=t(e,s))!=null?i:s:void 0}function ue(n,e){return typeof n!="symbol"?void 0:y(e,"d => Symbol(d)",void 0,n.description?e.newString(n.description):e.undefined)}function ae(n,e){return n instanceof Date?y(e,"d => new Date(d)",void 0,e.newNumber(n.getTime())):void 0}function fe(n,e){if(n instanceof ArrayBuffer)return e.newArrayBuffer(n.slice(0));if(ArrayBuffer.isView(n)){const t=new Uint8Array(n.buffer,n.byteOffset,n.byteLength).slice();return z([e.newArrayBuffer(t.buffer),e.newString(n.constructor.name)],([r,s])=>y(e,"(buf, name) => new globalThis[name](buf)",void 0,r,s))}}const ce=[ue,ae,fe];function $(n){return typeof n=="function"&&/^class\s/.test(Function.prototype.toString.call(n))}function E(n){return typeof n=="function"||typeof n=="object"&&n!==null}function N(n,e){const t=new Set,r=s=>{if(!(!E(s)||t.has(s)||(e==null?void 0:e(s,t))===!1)){if(t.add(s),Array.isArray(s)){for(const i of s)r(i);return}if(typeof s=="object"){const i=Object.getPrototypeOf(s);i&&i!==Object.prototype&&r(i)}for(const i of Object.values(Object.getOwnPropertyDescriptors(s)))"value"in i&&r(i.value),"get"in i&&r(i.get),"set"in i&&r(i.set)}};return r(n),t}function le(n,e){return N(n,e?(t,r)=>r.size<e:void 0).size}function pe(){let n=()=>{},e=()=>{};return{promise:new Promise((r,s)=>{n=r,e=s}),resolve:n,reject:e}}function L(n,e,t,r){const s=n.newObject(),i=(o,u)=>{const a=r(o),f=typeof u.value=="undefined"?void 0:r(u.value),d=typeof u.get=="undefined"?void 0:r(u.get),h=typeof u.set=="undefined"?void 0:r(u.set);n.newObject().consume(_=>{Object.entries(u).forEach(([c,l])=>{const b=c==="value"?f:c==="get"?d:c==="set"?h:l?n.true:n.false;b&&n.setProp(_,c,b)}),n.setProp(s,a,_)})};try{const o=Object.getOwnPropertyDescriptors(e);Object.entries(o).forEach(([u,a])=>i(u,a)),Object.getOwnPropertySymbols(o).forEach(u=>i(u,o[u])),y(n,"Object.defineProperties",void 0,t,s).dispose()}finally{s.dispose()}}function de(n,e,t,r,s,i){var a;if(typeof e!="function")return;const o=n.newFunction(e.name,function(...f){const d=r(this),h=f.map(_=>r(_));if($(e)&&E(d)){const _=new e(...h);return Object.entries(_).forEach(([c,l])=>{n.setProp(this,c,t(l))}),this}return t(i?i(e,d,h):e.apply(d,h))}).consume(f=>y(n,`Cls => {
9
9
  const fn = function(...args) { return Cls.apply(this, args); };
10
10
  fn.name = Cls.name;
11
11
  fn.length = Cls.length;
12
12
  return fn;
13
- }`,void 0,p)),a=(u=s(e,i))!=null?u:i;return N(n,e,i,t),a}function x(n,e,t){var o;const r=F(n,e);return(o=t(e,r))!=null?o:r}function ee(n,e,t,r){var u;if(typeof e!="object"||e===null)return;const s=Array.isArray(e)?n.newArray():n.newObject(),o=(u=r(e,s))!=null?u:s,i=Object.getPrototypeOf(e),a=i&&i!==Object.prototype&&i!==Array.prototype?t(i):void 0;return a&&_(n,"Object.setPrototypeOf",void 0,o,a).dispose(),N(n,e,s,t),o}function te(n,e){switch(typeof e){case"undefined":return n.undefined;case"number":return n.newNumber(e);case"string":return n.newString(e);case"boolean":return e?n.true:n.false;case"object":return e===null?n.null:void 0}}function ne(n,e,t,r){var o;if(!(e instanceof Promise))return;const s=n.newPromise();return e.then(i=>s.resolve(t(i)),i=>s.reject(t(i))),(o=r(e,s))!=null?o:s.handle}function E(n,e){var l,f,d,h,y;const{ctx:t,unmarshal:r,isMarshalable:s,find:o,pre:i}=e;{const b=te(t,n);if(b)return b}{const b=o(n);if(b)return b}const a=s==null?void 0:s(n);if(a===!1)return t.undefined;const u=(b,w)=>i(b,w,a);if(a==="json")return x(t,n,u);const p=b=>E(b,e);return(y=(h=(d=(f=L(t,n,u,[...X,...(l=e.custom)!=null?l:[]]))!=null?f:ne(t,n,p,u))!=null?d:K(t,n,p,r,u,e.preApply))!=null?h:ee(t,n,p,u))!=null?y:t.undefined}function re(n,e,t,r){var o;let s;for(const i of r)if(s=i(e,n),s)break;return s?(o=t(s,e))!=null?o:s:void 0}function se(n,e){if(e.typeof(n)!=="symbol")return;const t=e.getString(e.getProp(n,"description"));return Symbol(t)}function oe(n,e){if(!e.dump(_(e,"a => a instanceof Date",void 0,n)))return;const t=e.getNumber(_(e,"a => a.getTime()",void 0,n));return new Date(t)}const ie=[se,oe];function A(n,e,t,r){n.newFunction("",(s,o)=>{const[i]=r(s);if(typeof i!="string"&&typeof i!="number"&&typeof i!="symbol")return;const a=[["value",!0],["get",!0],["set",!0],["configurable",!1],["enumerable",!1],["writable",!1]].reduce((u,[p,l])=>{const f=n.getProp(o,p),d=n.typeof(f);if(d==="undefined")return u;if(!l&&d==="boolean")return u[p]=n.dump(n.getProp(o,p)),u;const[h,y]=r(f);return y&&f.dispose(),u[p]=h,u},{});Object.defineProperty(t,i,a)}).consume(s=>{_(n,`(o, fn) => {
13
+ }`,void 0,f)),u=(a=s(e,o))!=null?a:o;return L(n,e,o,t),u}function ye(n,e,t){if(!(typeof e!="object"&&typeof e!="function")&&e!==null)return t(e,n.newHostRef(e).handle)}function he(n,e,t){var i;const r=W(n,e);return(i=t(e,r))!=null?i:r}function me(n,e,t,r){var s,i;if(e instanceof Map){const o=y(n,"() => new Map()"),u=(s=r(e,o))!=null?s:o;for(const[a,f]of e)y(n,"(m, k, v) => m.set(k, v)",void 0,o,t(a),t(f)).dispose();return u}if(e instanceof Set){const o=y(n,"() => new Set()"),u=(i=r(e,o))!=null?i:o;for(const a of e)y(n,"(s, v) => s.add(v)",void 0,o,t(a)).dispose();return u}}function _e(n,e,t,r){var a;if(typeof e!="object"||e===null)return;const s=Array.isArray(e)?n.newArray():n.newObject(),i=(a=r(e,s))!=null?a:s,o=Object.getPrototypeOf(e),u=o&&o!==Object.prototype&&o!==Array.prototype?t(o):void 0;return u&&y(n,"Object.setPrototypeOf",void 0,i,u).dispose(),L(n,e,s,t),i}function ve(n,e){switch(typeof e){case"undefined":return n.undefined;case"number":return n.newNumber(e);case"string":return n.newString(e);case"boolean":return e?n.true:n.false;case"bigint":return n.newBigInt(e);case"object":return e===null?n.null:void 0}}function be(n,e,t,r){var i;if(!(e instanceof Promise))return;const s=n.newPromise();return e.then(o=>s.resolve(t(o)),o=>s.reject(t(o))),(i=r(e,s))!=null?i:s.handle}function D(n,e){var d,h,_,c,l,b,j;const{ctx:t,unmarshal:r,isMarshalable:s,find:i,pre:o}=e;{const v=ve(t,n);if(v)return v}{const v=i(n);if(v)return v}if((d=e.marshalByReference)!=null&&d.call(e,n)&&e.registerHostRef){const v=ye(t,n,e.registerHostRef);if(v)return v}const u=s==null?void 0:s(n);if(u===!1)return t.undefined;const a=(v,P)=>o(v,P,u);if(u==="json")return he(t,n,a);const f=v=>D(v,e);return(j=(b=(l=(c=(_=oe(t,n,a,[...ce,...(h=e.custom)!=null?h:[]]))!=null?_:be(t,n,f,a))!=null?c:de(t,n,f,r,a,e.preApply))!=null?l:me(t,n,f,a))!=null?b:_e(t,n,f,a))!=null?j:t.undefined}function we(n,e,t,r){var i;let s;for(const o of r)if(s=o(e,n),s)break;return s?(i=t(s,e))!=null?i:s:void 0}function ge(n,e){if(e.typeof(n)!=="symbol")return;const t=e.getString(e.getProp(n,"description"));return Symbol(t)}function je(n,e){if(!S(y(e,"a => a instanceof Date",void 0,n),r=>e.dump(r)))return;const t=S(y(e,"a => a.getTime()",void 0,n),r=>e.getNumber(r));return new Date(t)}function Se(n,e){if(S(y(e,"a => a instanceof ArrayBuffer",void 0,n),t=>e.dump(t))){const t=e.getArrayBuffer(n),r=t.value.slice();return t.dispose(),r.buffer}if(S(y(e,"a => ArrayBuffer.isView(a)",void 0,n),t=>e.dump(t))){const t=S(y(e,"a => a.constructor.name",void 0,n),u=>e.getString(u)),r=globalThis[t];if(typeof r!="function")return;const s=y(e,"a => a.buffer.slice(a.byteOffset, a.byteOffset + a.byteLength)",void 0,n),i=e.getArrayBuffer(s),o=i.value.slice();return i.dispose(),s.dispose(),new r(o.buffer)}}const Pe=[ge,je,Se];function K(n,e,t,r){S(n.newFunction("",(s,i)=>{const[o]=r(s);if(typeof o!="string"&&typeof o!="number"&&typeof o!="symbol")return;const u=[["value",!0],["get",!0],["set",!0],["configurable",!1],["enumerable",!1],["writable",!1]].reduce((a,[f,d])=>{const h=n.getProp(i,f),_=n.typeof(h);if(_==="undefined")return a;if(!d&&_==="boolean")return a[f]=n.dump(n.getProp(i,f)),a;const[c,l]=r(h);return l&&h.dispose(),a[f]=c,a},{});Object.defineProperty(t,o,u)}),s=>{y(n,`(o, fn) => {
14
14
  const descs = Object.getOwnPropertyDescriptors(o);
15
15
  Object.entries(descs).forEach(([k, v]) => fn(k, v));
16
16
  Object.getOwnPropertySymbols(descs).forEach(k => fn(k, descs[k]));
17
- }`,void 0,e,s).dispose()})}function ue(n,e,t,r,s){var a;if(n.typeof(e)!=="function")return;const o=function(...u){return S([t(this),...u.map(p=>t(p))],(p,...l)=>{if(new.target){const[y]=r(_(n,"(Cls, ...args) => new Cls(...args)",p,e,...l));return Object.defineProperties(this,Object.getOwnPropertyDescriptors(y)),this}const f=n.unwrapResult(n.callFunction(e,p,...l)),[d,h]=r(f);return h&&f.dispose(),d})},i=(a=s(o,e))!=null?a:o;return A(n,e,o,r),i}function ae(n,e,t,r){var a;if(n.typeof(e)!=="object"||n.unwrapResult(n.evalCode("o => o === null")).consume(u=>n.dump(n.unwrapResult(n.callFunction(u,n.undefined,e)))))return;const s=_(n,"Array.isArray",void 0,e).consume(u=>n.dump(u))?[]:{},o=(a=r(s,e))!=null?a:s,i=_(n,`o => {
17
+ }`,void 0,e,s).dispose()})}function ke(n,e,t,r,s){var u;if(n.typeof(e)!=="function")return;const i=function(...a){return C([t(this),...a.map(f=>t(f))],(f,...d)=>{if(new.target){const[l]=r(y(n,"(Cls, ...args) => new Cls(...args)",f,e,...d));return Object.defineProperties(this,Object.getOwnPropertyDescriptors(l)),this}const h=k(n,n.callFunction(e,f,...d)),[_,c]=r(h);return c&&h.dispose(),_})},o=(u=s(i,e))!=null?u:i;return K(n,e,i,r),o}function Q(n,e){const t=n.toHostRef(e);if(t)try{return{value:t.value}}finally{t.dispose()}}function Oe(n,e,t,r){const s=S(y(n,"a => a instanceof Map",void 0,e),a=>n.dump(a)),i=!s&&S(y(n,"a => a instanceof Set",void 0,e),a=>n.dump(a));if(!s&&!i)return;const o=s?new Map:new Set;r(o,e);const u=n.unwrapResult(n.getIterator(e));try{for(const a of u){const f=n.unwrapResult(a);if(s){const d=n.getProp(f,0),h=n.getProp(f,1),[_,c]=t(d),[l,b]=t(h);c&&d.dispose(),b&&h.dispose(),o.set(_,l),f.dispose()}else{const[d,h]=t(f);h&&f.dispose(),o.add(d)}}}finally{u.alive&&u.dispose()}return o}function Ee(n,e,t,r){var u;if(n.typeof(e)!=="object"||n.sameValue(e,n.null))return;const s=S(y(n,"Array.isArray",void 0,e),a=>n.dump(a))?[]:{},i=(u=r(s,e))!=null?u:s,o=S(y(n,`o => {
18
18
  const p = Object.getPrototypeOf(o);
19
19
  return !p || p === Object.prototype || p === Array.prototype ? undefined : p;
20
- }`,void 0,e).consume(u=>{if(n.typeof(u)==="undefined")return;const[p]=t(u);return p});return typeof i=="object"&&Object.setPrototypeOf(o,i),A(n,e,s,t),o}function pe(n,e){const t=n.typeof(e);return t==="undefined"||t==="number"||t==="string"||t==="boolean"?[n.dump(e),!0]:t==="object"&&n.unwrapResult(n.evalCode("a => a === null")).consume(s=>n.dump(n.unwrapResult(n.callFunction(s,n.undefined,e))))?[null,!0]:[void 0,!1]}function fe(n,e,t,r){var p;if(!ce(n,e))return;const s=Z(),[o,i]=t(s.resolve),[a,u]=t(s.reject);return _(n,"(p, res, rej) => { p.then(res, rej); }",void 0,e,o,a),i&&o.dispose(),u&&a.dispose(),(p=r(s.promise,e))!=null?p:s.promise}function ce(n,e){return e.owner?n.unwrapResult(n.evalCode("Promise")).consume(t=>e.owner?J(n,e,t):!1):!1}function D(n,e){const[t]=B(n,e);return t}function B(n,e){var u,p,l,f;const{ctx:t,marshal:r,find:s,pre:o}=e;{const[d,h]=pe(t,n);if(h)return[d,!1]}{const d=s(n);if(d)return[d,!0]}const i=d=>B(d,e);return[(f=(l=(p=re(t,n,o,[...ie,...(u=e.custom)!=null?u:[]]))!=null?p:fe(t,n,r,o))!=null?l:ue(t,n,r,i,o))!=null?f:ae(t,n,i,o),!1]}class M{constructor(e){c(this,"ctx");c(this,"_map1",new Map);c(this,"_map2",new Map);c(this,"_map3",new Map);c(this,"_map4",new Map);c(this,"_counterMap",new Map);c(this,"_disposables",new Set);c(this,"_mapGet");c(this,"_mapSet");c(this,"_mapDelete");c(this,"_mapClear");c(this,"_counter",Number.MIN_SAFE_INTEGER);this.ctx=e;const t=e.unwrapResult(e.evalCode(`() => {
20
+ }`,void 0,e),a=>{if(n.typeof(a)==="undefined")return;const[f]=t(a);return f});return typeof o=="object"&&Object.setPrototypeOf(i,o),K(n,e,s,t),i}function Re(n,e){const t=n.typeof(e);return t==="undefined"||t==="number"||t==="string"||t==="boolean"?[n.dump(e),!0]:t==="bigint"?[n.getBigInt(e),!0]:t==="object"&&n.sameValue(e,n.null)?[null,!0]:[void 0,!1]}function Te(n,e,t,r){var f;if(!He(n,e))return;const s=pe(),[i,o]=t(s.resolve),[u,a]=t(s.reject);return y(n,"(p, res, rej) => { p.then(res, rej); }",void 0,e,i,u),o&&i.dispose(),a&&u.dispose(),(f=r(s.promise,e))!=null?f:s.promise}function He(n,e){return e.owner?n.unwrapResult(n.evalCode("Promise")).consume(t=>e.owner?ne(n,e,t):!1):!1}function q(n,e){const[t]=X(n,e);return t}function X(n,e){var d,h,_;const{ctx:t,marshal:r,find:s,pre:i}=e;{const[c,l]=Re(t,n);if(l)return[c,!1]}{const c=s(n);if(c)return[c,!0]}const o=c=>X(c,e);if(e.hostRef){const c=Q(t,n);if(c)return[c.value,!0]}const u=we(t,n,i,[...Pe,...(d=e.custom)!=null?d:[]]);if(u)return[u,!0];const a=Oe(t,n,o,i);return a?[a,!0]:[(_=(h=Te(t,n,r,i))!=null?h:ke(t,n,r,o,i))!=null?_:Ee(t,n,o,i),!1]}class U{constructor(e){p(this,"ctx");p(this,"_keyToId",new Map);p(this,"_key2ToId",new Map);p(this,"_idToHandle",new Map);p(this,"_idToHandle2",new Map);p(this,"_idToKey",new Map);p(this,"_idToKey2",new Map);p(this,"_disposables",new Set);p(this,"_mapGet");p(this,"_mapSet");p(this,"_mapDelete");p(this,"_mapClear");p(this,"_nextId",Number.MIN_SAFE_INTEGER);this.ctx=e;const t=e.unwrapResult(e.evalCode(`() => {
21
21
  const mapSym = new Map();
22
22
  let map = new WeakMap();
23
23
  let map2 = new WeakMap();
@@ -40,7 +40,7 @@
40
40
  map2 = new WeakMap();
41
41
  }
42
42
  };
43
- }`)).consume(r=>this._call(r,void 0));this._mapGet=e.getProp(t,"get"),this._mapSet=e.getProp(t,"set"),this._mapDelete=e.getProp(t,"delete"),this._mapClear=e.getProp(t,"clear"),t.dispose(),this._disposables.add(this._mapGet),this._disposables.add(this._mapSet),this._disposables.add(this._mapDelete),this._disposables.add(this._mapClear)}set(e,t,r,s){var a;if(!t.alive||s&&!s.alive)return!1;const o=(a=this.get(e))!=null?a:this.get(r);if(o)return o===t||o===s;const i=this._counter++;return this._map1.set(e,i),this._map3.set(i,t),this._counterMap.set(i,e),r&&(this._map2.set(r,i),s&&this._map4.set(i,s)),this.ctx.newNumber(i).consume(u=>{this._call(this._mapSet,void 0,t,u,s!=null?s:this.ctx.undefined)}),!0}merge(e){if(e)for(const t of e)t&&t[1]&&this.set(t[0],t[1],t[2],t[3])}get(e){var s;const t=(s=this._map1.get(e))!=null?s:this._map2.get(e),r=typeof t=="number"?this._map3.get(t):void 0;if(r){if(!r.alive){this.delete(e);return}return r}}getByHandle(e){if(e.alive)return this._counterMap.get(this.ctx.getNumber(this._call(this._mapGet,void 0,e)))}has(e){return!!this.get(e)}hasHandle(e){return typeof this.getByHandle(e)!="undefined"}keys(){return this._map1.keys()}delete(e,t){var i;const r=(i=this._map1.get(e))!=null?i:this._map2.get(e);if(typeof r=="undefined")return;const s=this._map3.get(r),o=this._map4.get(r);this._call(this._mapDelete,void 0,...[s,o].filter(a=>!!(a!=null&&a.alive))),this._map1.delete(e),this._map2.delete(e),this._map3.delete(r),this._map4.delete(r);for(const[a,u]of this._map1)if(u===r){this._map1.delete(a);break}for(const[a,u]of this._map2)if(u===r){this._map2.delete(a);break}for(const[a,u]of this._counterMap)if(u===e){this._counterMap.delete(a);break}t&&(s!=null&&s.alive&&s.dispose(),o!=null&&o.alive&&o.dispose())}deleteByHandle(e,t){const r=this.getByHandle(e);typeof r!="undefined"&&this.delete(r,t)}clear(){this._counter=0,this._map1.clear(),this._map2.clear(),this._map3.clear(),this._map4.clear(),this._counterMap.clear(),this._mapClear.alive&&this._call(this._mapClear,void 0)}dispose(){for(const e of this._disposables.values())e.alive&&e.dispose();for(const e of this._map3.values())e.alive&&e.dispose();for(const e of this._map4.values())e.alive&&e.dispose();this._disposables.clear(),this.clear()}get size(){return this._map1.size}[Symbol.iterator](){const e=this._map1.keys();return{next:()=>{for(;;){const t=e.next();if(t.done)return{value:void 0,done:!0};const r=this._map1.get(t.value);if(typeof r=="undefined")continue;const s=this._map3.get(r),o=this._map4.get(r);if(!s)continue;const i=this._get2(r);return{value:[t.value,s,i,o],done:!1}}}}}_get2(e){for(const[t,r]of this._map2)if(r===e)return t}_call(e,t,...r){return this.ctx.unwrapResult(this.ctx.callFunction(e,typeof t=="undefined"?this.ctx.undefined:t,...r))}}function le(n,e,t,r,s,o,i){if(!g(e)||e instanceof Promise||e instanceof Date||i&&!i(e))return;if(me(e,t))return e;const a=new Proxy(e,{get(u,p){return p===t?u:Reflect.get(u,p)},set(u,p,l,f){var y;const d=P(l,t),h=(y=o==null?void 0:o(f))!=null?y:"host";return h!=="vm"&&!Reflect.set(u,p,d,f)||h==="host"||!n.alive||S([s(f),s(p),s(d)],(b,w,U)=>{const[I,ye]=R(n,b,r);ye?I.consume(_e=>n.setProp(_e,w,U)):n.setProp(I,w,U)}),!0},deleteProperty(u,p){var f;const l=(f=o==null?void 0:o(a))!=null?f:"host";return S([s(a),s(p)],(d,h)=>{const[y,b]=R(n,d,r);if(l==="vm"||Reflect.deleteProperty(u,p)){if(l==="host"||!n.alive)return!0;b?y.consume(w=>_(n,"(a, b) => delete a[b]",void 0,w,h)):_(n,"(a, b) => delete a[b]",void 0,y,h)}return!0})}});return a}function de(n,e,t,r,s,o,i){if(!C(n,e)||i&&!i(e,n))return[void 0,!1];if(T(n,e,r))return[e,!1];const a=l=>{const f=o==null?void 0:o(s(l));return typeof f=="string"?n.newString(f):n.undefined},u=(l,f,d)=>{const h=s(l);if(!h)return;const y=s(f);if(y==="__proto__")return;const b=s(d);P(h,t)[y]=b},p=(l,f)=>{const d=s(l);if(!d)return;const h=s(f);Reflect.deleteProperty(P(d,t),h)};return n.newFunction("proxyFuncs",(l,...f)=>{switch(n.getNumber(l)){case 1:return a(f[0]);case 2:return u(f[0],f[1],f[2]);case 3:return p(f[0],f[1])}return n.undefined}).consume(l=>[_(n,`(target, sym, proxyFuncs) => {
43
+ }`)).consume(r=>this._call(r,void 0));this._mapGet=e.getProp(t,"get"),this._mapSet=e.getProp(t,"set"),this._mapDelete=e.getProp(t,"delete"),this._mapClear=e.getProp(t,"clear"),t.dispose(),this._disposables.add(this._mapGet),this._disposables.add(this._mapSet),this._disposables.add(this._mapDelete),this._disposables.add(this._mapClear)}set(e,t,r,s){var u;if(!t.alive||s&&!s.alive)return!1;const i=(u=this.get(e))!=null?u:this.get(r);if(i)return i===t||i===s;const o=this._nextId++;return this._keyToId.set(e,o),this._idToHandle.set(o,t),this._idToKey.set(o,e),r&&(this._key2ToId.set(r,o),this._idToKey2.set(o,r),s&&this._idToHandle2.set(o,s)),this.ctx.newNumber(o).consume(a=>{this._call(this._mapSet,void 0,t,a,s!=null?s:this.ctx.undefined)}),!0}merge(e){if(e)for(const t of e)t&&t[1]&&this.set(t[0],t[1],t[2],t[3])}get(e){var s;const t=(s=this._keyToId.get(e))!=null?s:this._key2ToId.get(e),r=typeof t=="number"?this._idToHandle.get(t):void 0;if(r){if(!r.alive){this.delete(e);return}return r}}getByHandle(e){if(e.alive)return this._idToKey.get(this.ctx.getNumber(this._call(this._mapGet,void 0,e)))}has(e){return!!this.get(e)}hasHandle(e){return typeof this.getByHandle(e)!="undefined"}keys(){return this._keyToId.keys()}delete(e,t){var a;const r=(a=this._keyToId.get(e))!=null?a:this._key2ToId.get(e);if(typeof r=="undefined")return;const s=this._idToHandle.get(r),i=this._idToHandle2.get(r);this._call(this._mapDelete,void 0,...[s,i].filter(f=>!!(f!=null&&f.alive)));const o=this._idToKey.get(r),u=this._idToKey2.get(r);typeof o!="undefined"&&this._keyToId.delete(o),typeof u!="undefined"&&this._key2ToId.delete(u),this._idToHandle.delete(r),this._idToHandle2.delete(r),this._idToKey.delete(r),this._idToKey2.delete(r),t&&(s!=null&&s.alive&&s.dispose(),i!=null&&i.alive&&i.dispose())}deleteByHandle(e,t){const r=this.getByHandle(e);typeof r!="undefined"&&this.delete(r,t)}clear(){this._nextId=0,this._keyToId.clear(),this._key2ToId.clear(),this._idToHandle.clear(),this._idToHandle2.clear(),this._idToKey.clear(),this._idToKey2.clear(),this._mapClear.alive&&this._call(this._mapClear,void 0)}dispose(){for(const e of this._disposables.values())e.alive&&e.dispose();for(const e of this._idToHandle.values())e.alive&&e.dispose();for(const e of this._idToHandle2.values())e.alive&&e.dispose();this._disposables.clear(),this.clear()}get size(){return this._keyToId.size}[Symbol.iterator](){const e=this._keyToId.keys();return{next:()=>{for(;;){const t=e.next();if(t.done)return{value:void 0,done:!0};const r=this._keyToId.get(t.value);if(typeof r=="undefined")continue;const s=this._idToHandle.get(r),i=this._idToHandle2.get(r);if(!s)continue;const o=this._idToKey2.get(r);return{value:[t.value,s,o,i],done:!1}}}}}_call(e,t,...r){return k(this.ctx,this.ctx.callFunction(e,typeof t=="undefined"?this.ctx.undefined:t,...r))}}function Me(n,e,t,r,s,i,o,u=!0){if(!E(e)||e instanceof Promise||e instanceof Date||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||e instanceof Map||e instanceof Set||o&&!o(e))return;if(Ae(e,t)||!u)return e;const a=new Proxy(e,{get(f,d){return d===t?f:Reflect.get(f,d)},set(f,d,h,_){var b;const c=R(h,t),l=(b=i==null?void 0:i(_))!=null?b:"host";return l!=="vm"&&!Reflect.set(f,d,c)||l==="host"||!n.alive||C([s(_),s(d),s(c)],(j,v,P)=>{const[B,F]=A(n,j,r);F?B.consume(V=>n.setProp(V,v,P)):n.setProp(B,v,P)}),!0},deleteProperty(f,d){var _;const h=(_=i==null?void 0:i(a))!=null?_:"host";return C([s(a),s(d)],(c,l)=>{const[b,j]=A(n,c,r);if(h==="vm"||Reflect.deleteProperty(f,d)){if(h==="host"||!n.alive)return!0;j?b.consume(v=>y(n,"(a, b) => delete a[b]",void 0,v,l)):y(n,"(a, b) => delete a[b]",void 0,b,l)}return!0})},defineProperty(f,d,h){var l;const _=(l=i==null?void 0:i(a))!=null?l:"host",c=ee({},h);return"value"in c&&(c.value=R(c.value,t)),typeof c.get=="function"&&(c.get=R(c.get,t)),typeof c.set=="function"&&(c.set=R(c.set,t)),_!=="vm"&&!Reflect.defineProperty(f,d,c)?!1:(_==="host"||!n.alive||C([s(a),s(d),s(c)],(b,j,v)=>{const[P,B]=A(n,b,r),F=V=>y(n,"(o, k, d) => { Object.defineProperty(o, k, d); }",void 0,V,j,v).dispose();B?P.consume(F):F(P)}),!0)}});return a}function Ce(n,e,t,r,s,i,o,u=!0){if(!J(n,e)||o&&!o(e,n))return[void 0,!1];if(Y(n,e,r))return[e,!1];if(!u)return[e,!1];const a=c=>{const l=i==null?void 0:i(s(c));return typeof l=="string"?n.newString(l):n.undefined},f=(c,l,b)=>{const j=s(c);if(!j)return;const v=s(l);if(v==="__proto__")return;const P=s(b);R(j,t)[v]=P},d=(c,l)=>{const b=s(c);if(!b)return;const j=s(l);Reflect.deleteProperty(R(b,t),j)},h=(c,l,b)=>{const j=s(c);if(!j)return;const v=s(l);if(v==="__proto__")return;const P=s(b);Object.defineProperty(R(j,t),v,P)},_=n.newFunction("proxyFuncs",(c,...l)=>{switch(n.getNumber(c)){case 1:return a(l[0]);case 2:return f(l[0],l[1],l[2]);case 3:return d(l[0],l[1]);case 4:return h(l[0],l[1],l[2])}return n.undefined});return S(_,c=>[y(n,`(target, sym, proxyFuncs) => {
44
44
  const rec = new Proxy(target, {
45
45
  get(obj, key, receiver) {
46
46
  return key === sym ? obj : Reflect.get(obj, key, receiver)
@@ -50,7 +50,7 @@
50
50
  ? value[sym] ?? value
51
51
  : value;
52
52
  const sync = proxyFuncs(1, receiver) ?? "vm";
53
- if (sync === "host" || Reflect.set(obj, key, v, receiver)) {
53
+ if (sync === "host" || Reflect.set(obj, key, v)) {
54
54
  if (sync !== "vm") {
55
55
  proxyFuncs(2, receiver, key, v);
56
56
  }
@@ -66,6 +66,15 @@
66
66
  }
67
67
  return true;
68
68
  },
69
+ defineProperty(obj, key, descriptor) {
70
+ const sync = proxyFuncs(1, rec) ?? "vm";
71
+ if (sync === "host" || Reflect.defineProperty(obj, key, descriptor)) {
72
+ if (sync !== "vm") {
73
+ proxyFuncs(4, rec, key, descriptor);
74
+ }
75
+ }
76
+ return true;
77
+ },
69
78
  });
70
79
  return rec;
71
- }`,void 0,e,r,l),!0])}function P(n,e){var t;return g(n)&&(t=n[e])!=null?t:n}function R(n,e,t){return T(n,e,t)?[n.getProp(e,t),!0]:[e,!1]}function me(n,e){return g(n)&&!!n[e]}function T(n,e,t){return!!n.dump(_(n,'(a, s) => (a instanceof Promise) || (a instanceof Date) || (typeof a === "object" && a !== null || typeof a === "function") && !!a[s]',void 0,e,t))}class he{constructor(e,t){c(this,"context");c(this,"_map");c(this,"_registeredMap");c(this,"_registeredMapDispose",new Set);c(this,"_sync",new Set);c(this,"_temporalSync",new Set);c(this,"_symbol",Symbol());c(this,"_symbolHandle");c(this,"_options");c(this,"_isMarshalable",e=>{var r,s;const t=(r=this._options)==null?void 0:r.isMarshalable;return(s=typeof t=="function"?t(this._unwrap(e)):t)!=null?s:"json"});c(this,"_marshalFind",e=>{var s,o,i;const t=this._unwrap(e);return(i=(o=(s=this._registeredMap.get(e))!=null?s:t!==e?this._registeredMap.get(t):void 0)!=null?o:this._map.get(e))!=null?i:t!==e?this._map.get(t):void 0});c(this,"_marshalPre",(e,t,r)=>{var s;if(r!=="json")return(s=this._register(e,V(t),this._map))==null?void 0:s[1]});c(this,"_marshalPreApply",(e,t,r)=>{const s=g(t)?this._unwrap(t):void 0;s&&this._temporalSync.add(s);try{return e.apply(t,r)}finally{s&&this._temporalSync.delete(s)}});c(this,"_marshal",e=>{var s,o;const t=this._registeredMap.get(e);if(t)return[t,!1];const r=E((s=this._wrap(e))!=null?s:e,{ctx:this.context,unmarshal:this._unmarshal,isMarshalable:this._isMarshalable,find:this._marshalFind,pre:this._marshalPre,preApply:this._marshalPreApply,custom:(o=this._options)==null?void 0:o.customMarshaller});return[r,!this._map.hasHandle(r)]});c(this,"_preUnmarshal",(e,t)=>{var r;return(r=this._register(e,t,void 0,!0))==null?void 0:r[0]});c(this,"_unmarshalFind",e=>{var t;return(t=this._registeredMap.getByHandle(e))!=null?t:this._map.getByHandle(e)});c(this,"_unmarshal",e=>{var s;const t=this._registeredMap.getByHandle(e);if(typeof t!="undefined")return t;const[r]=this._wrapHandle(e);return D(r!=null?r:e,{ctx:this.context,marshal:this._marshal,find:this._unmarshalFind,pre:this._preUnmarshal,custom:(s=this._options)==null?void 0:s.customUnmarshaller})});c(this,"_syncMode",e=>{const t=this._unwrap(e);return this._sync.has(t)||this._temporalSync.has(t)?"both":void 0});c(this,"_unwrapIfNotSynced",e=>{const t=this._unwrap(e);return t instanceof Promise||!this._sync.has(t)?t:e});var r;t!=null&&t.compat&&!("runtime"in e)&&(e.runtime={hasPendingJob:()=>e.hasPendingJob(),executePendingJobs:s=>e.executePendingJobs(s)}),this.context=t!=null&&t.experimentalContextEx?v(e):e,this._options=t,this._symbolHandle=e.unwrapResult(e.evalCode("Symbol()")),this._map=new M(e),this._registeredMap=new M(e),this.registerAll((r=t==null?void 0:t.registeredObjects)!=null?r:k)}dispose(){var e,t;this._map.dispose(),this._registeredMap.dispose(),this._symbolHandle.dispose(),(t=(e=this.context).disposeEx)==null||t.call(e)}evalCode(e){const t=this.context.evalCode(e);return this._unwrapResultAndUnmarshal(t)}evalModule(e,t="module.js"){const r=this.context.evalCode(e,t,{type:"module"});return this._unwrapResultAndUnmarshal(r)}executePendingJobs(e){const t=this.context.runtime.executePendingJobs(e);if("value"in t)return t.value;throw this._unwrapIfNotSynced(t.error.consume(this._unmarshal))}setMemoryLimit(e){this.context.runtime.setMemoryLimit(e)}setMaxStackSize(e){this.context.runtime.setMaxStackSize(e)}getMemoryUsage(){const e=this.context.runtime.computeMemoryUsage();try{return this.context.dump(e)}finally{e.dispose()}}dumpMemoryUsage(){return this.context.runtime.dumpMemoryUsage()}expose(e){for(const[t,r]of Object.entries(e))z(this._marshal(r),s=>{this.context.setProp(this.context.global,t,s)})}sync(e){const t=this._wrap(e);return typeof t=="undefined"?e:(O(t,r=>{const s=this._unwrap(r);this._sync.add(s)}),t)}register(e,t){if(this._registeredMap.has(e))return;const r=typeof t=="string"?this._unwrapResult(this.context.evalCode(t)):t;this.context.sameValue(r,this.context.undefined)||(typeof t=="string"&&this._registeredMapDispose.add(e),this._registeredMap.set(e,r))}registerAll(e){for(const[t,r]of e)this.register(t,r)}unregister(e,t){this._registeredMap.delete(e,this._registeredMapDispose.has(e)||t),this._registeredMapDispose.delete(e)}unregisterAll(e,t){for(const r of e)this.unregister(r,t)}startSync(e){if(!g(e))return;const t=this._unwrap(e);this._sync.add(t)}endSync(e){this._sync.delete(this._unwrap(e))}_unwrapResult(e){if("value"in e)return e.value;throw this._unwrapIfNotSynced(e.error.consume(this._unmarshal))}_unwrapResultAndUnmarshal(e){if(e)return this._unwrapIfNotSynced(this._unwrapResult(e).consume(this._unmarshal))}_register(e,t,r=this._map,s){if(this._registeredMap.has(e)||this._registeredMap.hasHandle(t))return;let o=this._wrap(e);const[i]=this._wrapHandle(t),a=e instanceof Promise;if(!i||!o&&!a)return;a&&(o=e);const u=this._unwrap(e),[p,l]=this._unwrapHandle(t);if(r.set(o,i,u,p))s&&this._sync.add(u);else throw l&&p.dispose(),new Error("already registered");return[o,i]}_wrap(e){var t;return le(this.context,e,this._symbol,this._symbolHandle,this._marshal,this._syncMode,(t=this._options)==null?void 0:t.isWrappable)}_unwrap(e){return P(e,this._symbol)}_wrapHandle(e){var t;return de(this.context,e,this._symbol,this._symbolHandle,this._unmarshal,this._syncMode,(t=this._options)==null?void 0:t.isHandleWrappable)}_unwrapHandle(e){return R(this.context,e,this._symbolHandle)}}m.Arena=he,m.VMMap=M,m.call=_,m.complexity=Y,m.consumeAll=W,m.defaultRegisteredObjects=k,m.isES2015Class=H,m.isHandleObject=C,m.isObject=g,m.json=F,m.marshal=E,m.unmarshal=D,m.walkObject=O,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
80
+ }`,void 0,e,r,c),!0])}function R(n,e){var t;return E(n)&&(t=n[e])!=null?t:n}function A(n,e,t){return Y(n,e,t)?[n.getProp(e,t),!0]:[e,!1]}function Ae(n,e){return E(n)&&!!n[e]}function Y(n,e,t){return!!n.dump(y(n,'(a, s) => (a instanceof Promise) || (a instanceof Date) || (a instanceof ArrayBuffer) || (ArrayBuffer.isView(a)) || (a instanceof Map) || (a instanceof Set) || (typeof a === "object" && a !== null || typeof a === "function") && !!a[s]',void 0,e,t))}class Z{constructor(e,t){p(this,"context");p(this,"_map");p(this,"_registeredMap");p(this,"_registeredMapDispose",new Set);p(this,"_sync",new Set);p(this,"_temporalSync",new Set);p(this,"_symbol",Symbol());p(this,"_symbolHandle");p(this,"_options");p(this,"_isMarshalable",e=>{var r,s;const t=(r=this._options)==null?void 0:r.isMarshalable;return(s=typeof t=="function"?t(this._unwrap(e)):t)!=null?s:"json"});p(this,"_marshalByReference",e=>{var t,r;return!!((r=(t=this._options)==null?void 0:t.marshalByReference)!=null&&r.call(t,this._unwrap(e)))});p(this,"_registerHostRef",(e,t)=>{const r=this._unwrap(e),s=this._map.get(r);return s||(this._map.set(r,t),t)});p(this,"_marshalFind",e=>{var s,i,o;const t=this._unwrap(e);return(o=(i=(s=this._registeredMap.get(e))!=null?s:t!==e?this._registeredMap.get(t):void 0)!=null?i:this._map.get(e))!=null?o:t!==e?this._map.get(t):void 0});p(this,"_marshalPre",(e,t,r)=>{var s;if(r!=="json")return(s=this._register(e,ie(t),this._map))==null?void 0:s[1]});p(this,"_marshalPreApply",(e,t,r)=>{const s=E(t)?this._unwrap(t):void 0;s&&this._temporalSync.add(s);try{return e.apply(t,r)}finally{s&&this._temporalSync.delete(s)}});p(this,"_marshal",e=>{var o,u,a,f;const t=this._registeredMap.get(e);if(t)return[t,!1];const r=this._marshalByReference(e)?this._unwrap(e):(o=this._wrap(e))!=null?o:e,s=D(r,{ctx:this.context,unmarshal:this._unmarshal,isMarshalable:this._isMarshalable,marshalByReference:this._marshalByReference,registerHostRef:this._registerHostRef,find:this._marshalFind,pre:this._marshalPre,preApply:this._marshalPreApply,custom:(u=this._options)==null?void 0:u.customMarshaller}),i=(f=(a=this._options)==null?void 0:a.syncEnabled)!=null?f:!0;return[s,!i||!this._map.hasHandle(s)]});p(this,"_preUnmarshal",(e,t)=>{var r,s,i;return(i=this._register(e,t,void 0,(s=(r=this._options)==null?void 0:r.syncEnabled)!=null?s:!0))==null?void 0:i[0]});p(this,"_unmarshalFind",e=>{var t;return(t=this._registeredMap.getByHandle(e))!=null?t:this._map.getByHandle(e)});p(this,"_unmarshal",e=>{var s,i,o;const t=this._registeredMap.getByHandle(e);if(typeof t!="undefined")return t;if((s=this._options)!=null&&s.marshalByReference){const u=Q(this.context,e);if(u)return u.value}const[r]=this._wrapHandle(e);return q(r!=null?r:e,{ctx:this.context,marshal:this._marshal,find:this._unmarshalFind,pre:this._preUnmarshal,custom:(i=this._options)==null?void 0:i.customUnmarshaller,hostRef:!!((o=this._options)!=null&&o.marshalByReference)})});p(this,"_syncMode",e=>{const t=this._unwrap(e);return this._sync.has(t)||this._temporalSync.has(t)?"both":void 0});p(this,"_unwrapIfNotSynced",e=>{const t=this._unwrap(e);return t instanceof Promise||!this._sync.has(t)?t:e});var r;t!=null&&t.compat&&!("runtime"in e)&&(e.runtime={hasPendingJob:()=>e.hasPendingJob(),executePendingJobs:s=>e.executePendingJobs(s)}),this.context=t!=null&&t.experimentalContextEx?w(e):e,H(this.context),this._options=t,this._symbolHandle=e.unwrapResult(e.evalCode("Symbol()")),this._map=new U(e),this._registeredMap=new U(e),this.registerAll((r=t==null?void 0:t.registeredObjects)!=null?r:M)}dispose(){var e,t;this._map.dispose(),this._registeredMap.dispose(),this._symbolHandle.dispose(),O(this.context),(t=(e=this.context).disposeEx)==null||t.call(e)}[Symbol.dispose](){this.dispose()}evalCode(e){const t=this.context.evalCode(e);return this._unwrapResultAndUnmarshal(t)}evalModule(e,t="module.js"){const r=this.context.evalCode(e,t,{type:"module"});return this._unwrapResultAndUnmarshal(r)}executePendingJobs(e){const t=this.context.runtime.executePendingJobs(e);if("value"in t)return t.value;throw this._unwrapIfNotSynced(S(t.error,this._unmarshal))}setMemoryLimit(e){this.context.runtime.setMemoryLimit(e)}setMaxStackSize(e){this.context.runtime.setMaxStackSize(e)}getMemoryUsage(){const e=this.context.runtime.computeMemoryUsage();try{return this.context.dump(e)}finally{e.dispose()}}dumpMemoryUsage(){return this.context.runtime.dumpMemoryUsage()}expose(e){for(const[t,r]of Object.entries(e))re(this._marshal(r),s=>{this.context.setProp(this.context.global,t,s)})}sync(e){const t=this._wrap(e);return typeof t=="undefined"?e:(N(t,r=>{const s=this._unwrap(r);this._sync.add(s)}),t)}register(e,t){if(this._registeredMap.has(e))return;const r=typeof t=="string"?this._unwrapResult(this.context.evalCode(t)):t;this.context.sameValue(r,this.context.undefined)||(typeof t=="string"&&this._registeredMapDispose.add(e),this._registeredMap.set(e,r))}registerAll(e){for(const[t,r]of e)this.register(t,r)}unregister(e,t){this._registeredMap.delete(e,this._registeredMapDispose.has(e)||t),this._registeredMapDispose.delete(e)}unregisterAll(e,t){for(const r of e)this.unregister(r,t)}startSync(e){if(!E(e))return;const t=this._unwrap(e);this._sync.add(t)}endSync(e){this._sync.delete(this._unwrap(e))}_unwrapResult(e){if("value"in e)return e.value;throw this._unwrapIfNotSynced(S(e.error,this._unmarshal))}_unwrapResultAndUnmarshal(e){if(e)return this._unwrapIfNotSynced(S(this._unwrapResult(e),this._unmarshal))}_register(e,t,r=this._map,s){if(this._registeredMap.has(e)||this._registeredMap.hasHandle(t))return;let i=this._wrap(e);const[o]=this._wrapHandle(t),u=e instanceof Promise;if(!o||!i&&!u)return;u&&(i=e);const a=this._unwrap(e),[f,d]=this._unwrapHandle(t);if(r.set(i,o,a,f))s&&this._sync.add(a);else throw d&&f.dispose(),new Error("already registered");return[i,o]}_wrap(e){var t,r,s;return Me(this.context,e,this._symbol,this._symbolHandle,this._marshal,this._syncMode,(t=this._options)==null?void 0:t.isWrappable,(s=(r=this._options)==null?void 0:r.syncEnabled)!=null?s:!0)}_unwrap(e){return R(e,this._symbol)}_wrapHandle(e){var t,r,s;return Ce(this.context,e,this._symbol,this._symbolHandle,this._unmarshal,this._syncMode,(t=this._options)==null?void 0:t.isHandleWrappable,(s=(r=this._options)==null?void 0:r.syncEnabled)!=null?s:!0)}_unwrapHandle(e){return A(this.context,e,this._symbolHandle)}}class Be extends Z{constructor(t,r){super(t,r);p(this,"asyncContext");this.asyncContext=t}evalCodeAsync(t,r){return te(this,null,function*(){const s=yield this.asyncContext.evalCodeAsync(t,r);return this._unwrapResultAndUnmarshal(s)})}}m.Arena=Z,m.AsyncArena=Be,m.VMMap=U,m.call=y,m.complexity=le,m.consumeAll=z,m.defaultRegisteredObjects=M,m.isES2015Class=$,m.isHandleObject=J,m.isObject=E,m.json=W,m.marshal=D,m.unmarshal=q,m.walkObject=N,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "quickjs-emscripten-sync",
3
3
  "author": "rot1024",
4
- "version": "1.8.3",
4
+ "version": "1.9.0",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -11,16 +11,16 @@
11
11
  "bugs": "https://github.com/reearth/quickjs-emscripten-sync/issues",
12
12
  "type": "module",
13
13
  "source": "./src/index.ts",
14
- "main": "./dist/quickjs-emscripten-sync.umd.js",
15
- "module": "./dist/quickjs-emscripten-sync.mjs",
16
- "unpkg": "./dist/quickjs-emscripten-sync.umd.js",
14
+ "main": "./dist/quickjs-emscripten-sync.umd.cjs",
15
+ "module": "./dist/quickjs-emscripten-sync.js",
16
+ "unpkg": "./dist/quickjs-emscripten-sync.umd.cjs",
17
17
  "types": "./dist/index.d.ts",
18
18
  "sideEffects": false,
19
19
  "exports": {
20
20
  ".": {
21
21
  "types": "./dist/index.d.ts",
22
- "import": "./dist/quickjs-emscripten-sync.mjs",
23
- "require": "./dist/quickjs-emscripten-sync.umd.js"
22
+ "import": "./dist/quickjs-emscripten-sync.js",
23
+ "require": "./dist/quickjs-emscripten-sync.umd.cjs"
24
24
  }
25
25
  },
26
26
  "files": [
@@ -34,6 +34,8 @@
34
34
  "scripts": {
35
35
  "build": "tsc && vite build",
36
36
  "test": "vitest",
37
+ "bench": "vitest bench --run",
38
+ "typecheck": "tsc --noEmit",
37
39
  "lint": "eslint ."
38
40
  },
39
41
  "peerDependencies": {
@@ -44,7 +46,7 @@
44
46
  "eslint": "^9.39.4",
45
47
  "eslint-config-reearth": "^0.3.8",
46
48
  "prettier": "^3.8.3",
47
- "quickjs-emscripten": "^0.31.0",
49
+ "quickjs-emscripten": "^0.32.0",
48
50
  "typescript": "^5.9.3",
49
51
  "vite": "^7.3.3",
50
52
  "vite-plugin-dts": "^4.3.0",
package/src/index.test.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { getQuickJS } from "quickjs-emscripten";
1
+ import { getQuickJS, newAsyncContext } from "quickjs-emscripten";
2
2
  import { describe, expect, test, vi } from "vitest";
3
3
 
4
4
  import { isWrapped } from "./wrapper";
5
5
 
6
- import { Arena } from ".";
6
+ import { Arena, AsyncArena } from ".";
7
7
 
8
8
  describe("readme", () => {
9
9
  test("first", async () => {
@@ -999,11 +999,15 @@ describe("memory management", () => {
999
999
 
1000
1000
  expect(data.items.length).toBe(10);
1001
1001
 
1002
- // But not unlimited data
1002
+ // But not unlimited data. The allocation happens in a local (non-synced)
1003
+ // structure on purpose: a hard out-of-memory hit while mutating a synced
1004
+ // global mid-flight leaves the VM unrecoverable, so it would not be safe to
1005
+ // keep using or cleanly dispose afterwards.
1003
1006
  expect(() => {
1004
1007
  arena.evalCode(`
1005
- for (let i = 0; i < 100000; i++) {
1006
- data.items.push({ id: i, data: "x".repeat(1000) });
1008
+ const huge = [];
1009
+ for (let i = 0; i < 1000000; i++) {
1010
+ huge.push({ id: i, data: "x".repeat(1000) });
1007
1011
  }
1008
1012
  `);
1009
1013
  }).toThrow();
@@ -1032,3 +1036,244 @@ describe("intrinsics configuration", () => {
1032
1036
  runtime.dispose();
1033
1037
  });
1034
1038
  });
1039
+
1040
+ describe("syncEnabled", () => {
1041
+ const objCount = (ctx: any) => {
1042
+ const h = ctx.runtime.computeMemoryUsage();
1043
+ const c = ctx.dump(h).obj_count as number;
1044
+ h.dispose();
1045
+ return c;
1046
+ };
1047
+
1048
+ const growth = async (syncEnabled: boolean) => {
1049
+ const ctx = (await getQuickJS()).newContext();
1050
+ const arena = new Arena(ctx, { isMarshalable: true, registeredObjects: [], syncEnabled });
1051
+
1052
+ arena.expose({ fnFromHost: () => ({ id: "x", data: Math.random() }) });
1053
+ arena.evalCode(`globalThis.run = () => { for (let i = 0; i < 200; i++) fnFromHost(); }`);
1054
+
1055
+ arena.evalCode(`run()`);
1056
+ const before = objCount(ctx);
1057
+ arena.evalCode(`run()`);
1058
+ const after = objCount(ctx);
1059
+
1060
+ arena.dispose();
1061
+ ctx.dispose();
1062
+ return after - before;
1063
+ };
1064
+
1065
+ test("syncEnabled: false does not retain marshalled objects", async () => {
1066
+ // returned objects are not retained, so repeated runs don't grow memory
1067
+ expect(await growth(false)).toBeLessThan(50);
1068
+ });
1069
+
1070
+ test("syncEnabled: true retains marshalled objects (default)", async () => {
1071
+ // with sync on, every returned object is kept for identity, so memory grows
1072
+ expect(await growth(true)).toBeGreaterThan(150);
1073
+ });
1074
+ });
1075
+
1076
+ describe("AsyncArena", () => {
1077
+ test("evalCodeAsync returns values", async () => {
1078
+ const ctx = await newAsyncContext();
1079
+ const arena = new AsyncArena(ctx, { isMarshalable: true });
1080
+
1081
+ expect(await arena.evalCodeAsync(`1 + 2`)).toBe(3);
1082
+ expect(await arena.evalCodeAsync(`({ a: 1, b: [2, 3] })`)).toEqual({ a: 1, b: [2, 3] });
1083
+
1084
+ arena.dispose();
1085
+ ctx.dispose();
1086
+ });
1087
+
1088
+ test("evalCodeAsync re-throws errors", async () => {
1089
+ const ctx = await newAsyncContext();
1090
+ const arena = new AsyncArena(ctx, { isMarshalable: true });
1091
+
1092
+ await expect(arena.evalCodeAsync(`throw new Error("boom")`)).rejects.toThrow("boom");
1093
+
1094
+ arena.dispose();
1095
+ ctx.dispose();
1096
+ });
1097
+ });
1098
+
1099
+ describe("Symbol.dispose", () => {
1100
+ test("using disposes the arena", async () => {
1101
+ const ctx = (await getQuickJS()).newContext();
1102
+ {
1103
+ using arena = new Arena(ctx, { isMarshalable: true });
1104
+ expect(arena.evalCode(`1 + 1`)).toBe(2);
1105
+ }
1106
+ // arena is disposed here; the context can still be disposed cleanly
1107
+ ctx.dispose();
1108
+ });
1109
+ });
1110
+
1111
+ describe("defineProperty sync", () => {
1112
+ test("host -> VM", async () => {
1113
+ const ctx = (await getQuickJS()).newContext();
1114
+ const arena = new Arena(ctx, { isMarshalable: true });
1115
+ const data = arena.sync<any>({});
1116
+ arena.expose({ data });
1117
+
1118
+ Object.defineProperty(data, "x", { value: 42, enumerable: true, configurable: true });
1119
+ expect(arena.evalCode(`data.x`)).toBe(42);
1120
+
1121
+ arena.dispose();
1122
+ ctx.dispose();
1123
+ });
1124
+
1125
+ test("VM -> host", async () => {
1126
+ const ctx = (await getQuickJS()).newContext();
1127
+ const arena = new Arena(ctx, { isMarshalable: true });
1128
+ const data = arena.sync<any>({});
1129
+ arena.expose({ data });
1130
+
1131
+ arena.evalCode(
1132
+ `Object.defineProperty(data, "y", { value: 7, enumerable: true, configurable: true })`,
1133
+ );
1134
+ expect(data.y).toBe(7);
1135
+
1136
+ arena.dispose();
1137
+ ctx.dispose();
1138
+ });
1139
+
1140
+ test("syncs accessor descriptors host -> VM", async () => {
1141
+ const ctx = (await getQuickJS()).newContext();
1142
+ const arena = new Arena(ctx, { isMarshalable: true });
1143
+ const data = arena.sync<any>({});
1144
+ arena.expose({ data });
1145
+
1146
+ Object.defineProperty(data, "g", { get: () => 99, enumerable: true, configurable: true });
1147
+ expect(arena.evalCode(`data.g`)).toBe(99);
1148
+
1149
+ arena.dispose();
1150
+ ctx.dispose();
1151
+ });
1152
+ });
1153
+
1154
+ describe("marshalByReference", () => {
1155
+ test("passes objects through the VM by reference (identity preserved)", async () => {
1156
+ const ctx = (await getQuickJS()).newContext();
1157
+ const secret = {
1158
+ hidden: 42,
1159
+ method() {
1160
+ return this.hidden;
1161
+ },
1162
+ };
1163
+ const arena = new Arena(ctx, {
1164
+ isMarshalable: true,
1165
+ marshalByReference: t => t === secret,
1166
+ });
1167
+
1168
+ arena.expose({
1169
+ getSecret: () => secret,
1170
+ useSecret: (s: typeof secret) => s.method(),
1171
+ });
1172
+
1173
+ // VM receives the opaque ref and passes it back; host resolves the original
1174
+ expect(arena.evalCode(`useSecret(getSecret())`)).toBe(42);
1175
+
1176
+ // host -> VM -> host keeps identity
1177
+ const echo = arena.evalCode<(x: typeof secret) => typeof secret>(`x => x`);
1178
+ expect(echo(secret)).toBe(secret);
1179
+
1180
+ // the guest cannot read into the opaque ref
1181
+ expect(
1182
+ arena.evalCode(`(() => { try { return getSecret().hidden; } catch { return "threw"; } })()`),
1183
+ ).not.toBe(42);
1184
+
1185
+ arena.dispose();
1186
+ ctx.dispose();
1187
+ });
1188
+
1189
+ test("resolves host refs nested in objects", async () => {
1190
+ const ctx = (await getQuickJS()).newContext();
1191
+ const secret = { token: "abc" };
1192
+ const arena = new Arena(ctx, {
1193
+ isMarshalable: true,
1194
+ marshalByReference: t => t === secret,
1195
+ });
1196
+
1197
+ arena.expose({ wrap: () => ({ inner: secret, label: "x" }) });
1198
+ const out = arena.evalCode(`wrap()`);
1199
+ expect(out.label).toBe("x");
1200
+ expect(out.inner).toBe(secret);
1201
+
1202
+ arena.dispose();
1203
+ ctx.dispose();
1204
+ });
1205
+ });
1206
+
1207
+ describe("BigInt", () => {
1208
+ test("roundtrip", async () => {
1209
+ const ctx = (await getQuickJS()).newContext();
1210
+ const arena = new Arena(ctx, { isMarshalable: true });
1211
+
1212
+ expect(arena.evalCode(`123n`)).toBe(123n);
1213
+ expect(arena.evalCode(`2n ** 64n`)).toBe(2n ** 64n);
1214
+
1215
+ const double = arena.evalCode<(x: bigint) => bigint>(`x => x * 2n`);
1216
+ expect(double(21n)).toBe(42n);
1217
+ expect(double(9007199254740993n)).toBe(18014398509481986n);
1218
+
1219
+ arena.dispose();
1220
+ ctx.dispose();
1221
+ });
1222
+ });
1223
+
1224
+ describe("ArrayBuffer and TypedArray", () => {
1225
+ test("roundtrip", async () => {
1226
+ const ctx = (await getQuickJS()).newContext();
1227
+ const arena = new Arena(ctx, { isMarshalable: true });
1228
+
1229
+ const fromVM = arena.evalCode(`new Uint8Array([1, 2, 3, 250])`);
1230
+ expect(fromVM).toBeInstanceOf(Uint8Array);
1231
+ expect(Array.from(fromVM)).toEqual([1, 2, 3, 250]);
1232
+
1233
+ const buf = arena.evalCode(`new ArrayBuffer(4)`);
1234
+ expect(buf).toBeInstanceOf(ArrayBuffer);
1235
+ expect(buf.byteLength).toBe(4);
1236
+
1237
+ const echo = arena.evalCode<(x: Uint8Array) => Uint8Array>(`x => x`);
1238
+ const back = echo(new Uint8Array([9, 8, 7]));
1239
+ expect(back).toBeInstanceOf(Uint8Array);
1240
+ expect(Array.from(back)).toEqual([9, 8, 7]);
1241
+
1242
+ const sum = arena.evalCode<(a: Float64Array) => number>(
1243
+ `a => a.reduce((x, y) => x + y, 0)`,
1244
+ );
1245
+ expect(sum(new Float64Array([1.5, 2.5, 3]))).toBe(7);
1246
+
1247
+ arena.dispose();
1248
+ ctx.dispose();
1249
+ });
1250
+ });
1251
+
1252
+ describe("Map and Set", () => {
1253
+ test("roundtrip", async () => {
1254
+ const ctx = (await getQuickJS()).newContext();
1255
+ const arena = new Arena(ctx, { isMarshalable: true });
1256
+
1257
+ const map = arena.evalCode(`new Map([["a", 1], ["b", { n: 2 }]])`);
1258
+ expect(map).toBeInstanceOf(Map);
1259
+ expect(map.get("a")).toBe(1);
1260
+ expect(map.get("b")).toEqual({ n: 2 });
1261
+
1262
+ const set = arena.evalCode(`new Set([1, 2, 3])`);
1263
+ expect(set).toBeInstanceOf(Set);
1264
+ expect([...set]).toEqual([1, 2, 3]);
1265
+
1266
+ const mapSum = arena.evalCode<(m: Map<string, number>) => number>(
1267
+ `m => { let s = 0; for (const v of m.values()) s += v; return s; }`,
1268
+ );
1269
+ expect(mapSum(new Map([["x", 10], ["y", 20]]))).toBe(30);
1270
+
1271
+ const echo = arena.evalCode<(s: Set<string>) => Set<string>>(`s => s`);
1272
+ const back = echo(new Set(["p", "q"]));
1273
+ expect(back).toBeInstanceOf(Set);
1274
+ expect([...back]).toEqual(["p", "q"]);
1275
+
1276
+ arena.dispose();
1277
+ ctx.dispose();
1278
+ });
1279
+ });