@innovatorved/code-lab 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/ARCHITECTURE.md +2 -2
  2. package/CHANGELOG.md +30 -0
  3. package/README.md +6 -6
  4. package/dist/code-lab-sql.esm.js +19 -19
  5. package/dist/code-lab-sql.umd.js +20 -20
  6. package/dist/code-lab.css +1 -1
  7. package/dist/code-lab.d.ts +47 -38
  8. package/dist/code-lab.esm.js +1183 -1909
  9. package/dist/code-lab.js +1182 -1906
  10. package/dist/extensions/cpp.esm.js +132 -8760
  11. package/dist/extensions/cpp.js +124 -8770
  12. package/dist/extensions/guided-lab.esm.js +33 -6836
  13. package/dist/extensions/guided-lab.js +33 -6854
  14. package/dist/extensions/javascript.esm.js +1 -36
  15. package/dist/extensions/javascript.js +1 -58
  16. package/dist/extensions/python.esm.js +113 -8122
  17. package/dist/extensions/python.js +113 -8140
  18. package/dist/extensions/typescript.esm.js +1 -55
  19. package/dist/extensions/typescript.js +1 -77
  20. package/dist/index.d.ts +1 -1
  21. package/dist/logger.d.ts +4 -20
  22. package/dist/modular-kernel.d.ts +0 -5
  23. package/dist/packages/core/src/errors.d.ts +5 -1
  24. package/dist/packages/fs/src/backends.d.ts +0 -27
  25. package/dist/packages/fs/src/index.d.ts +1 -1
  26. package/dist/packages/ui/src/html.d.ts +1 -0
  27. package/dist/packages/ui/src/index.d.ts +1 -0
  28. package/dist/{apps/web/src/index.d.ts → packages/ui/src/kernel.d.ts} +3 -11
  29. package/dist/packages/ui/src/observability.d.ts +1 -1
  30. package/dist/packages/ui/src/settings-dialog.d.ts +0 -1
  31. package/dist/preview-sw.js +1 -1
  32. package/dist/runtime.d.ts +3 -0
  33. package/dist/runtime.esm.js +78 -78
  34. package/dist/runtime.js +78 -78
  35. package/dist/schemas.d.ts +10 -1
  36. package/dist/schemas.esm.js +33 -6815
  37. package/dist/schemas.js +33 -6831
  38. package/dist/shell.esm.js +277 -285
  39. package/dist/shell.js +277 -285
  40. package/dist/terminal.esm.js +9 -7
  41. package/dist/terminal.js +7 -7
  42. package/dist/workbench/command-palette.d.ts +0 -4
  43. package/dist/workbench/editor.d.ts +0 -4
  44. package/dist/workbench/index.d.ts +0 -22
  45. package/dist/workbench/intellisense.d.ts +1 -8
  46. package/dist/workbench/xterm-adapter.d.ts +0 -1
  47. package/package.json +4 -13
  48. package/dist/code-lab.umd.js +0 -6117
  49. package/dist/packages/editor/src/index.d.ts +0 -118
  50. package/dist/packages/preview/src/index.d.ts +0 -34
  51. package/dist/packages/runtime/src/index.d.ts +0 -47
  52. package/dist/packages/terminal/src/index.d.ts +0 -54
  53. package/dist/workbench/drawer.d.ts +0 -18
  54. package/dist/workbench/file-tree.d.ts +0 -11
  55. package/dist/workbench/guided-pane.d.ts +0 -11
  56. package/dist/workbench/styles.d.ts +0 -4
  57. package/dist/workbench/toolbar.d.ts +0 -17
  58. package/packages/commands/README.md +0 -7
  59. package/packages/commands/package.json +0 -16
  60. package/packages/commands/src/index.ts +0 -467
  61. package/packages/commands/tsconfig.json +0 -22
  62. package/packages/core/README.md +0 -12
  63. package/packages/core/package.json +0 -13
  64. package/packages/core/src/di.ts +0 -147
  65. package/packages/core/src/disposable.ts +0 -112
  66. package/packages/core/src/errors.ts +0 -205
  67. package/packages/core/src/events.ts +0 -157
  68. package/packages/core/src/index.ts +0 -49
  69. package/packages/core/src/path.ts +0 -118
  70. package/packages/core/src/registry.ts +0 -61
  71. package/packages/core/tsconfig.json +0 -19
  72. package/packages/editor/README.md +0 -9
  73. package/packages/editor/package.json +0 -18
  74. package/packages/editor/src/index.ts +0 -344
  75. package/packages/editor/tsconfig.json +0 -24
  76. package/packages/fs/README.md +0 -7
  77. package/packages/fs/package.json +0 -16
  78. package/packages/fs/src/backends.ts +0 -301
  79. package/packages/fs/src/index.ts +0 -18
  80. package/packages/fs/src/types.ts +0 -44
  81. package/packages/fs/src/vfs-service.ts +0 -257
  82. package/packages/fs/tsconfig.json +0 -22
  83. package/packages/preview/README.md +0 -3
  84. package/packages/preview/package.json +0 -16
  85. package/packages/preview/src/index.ts +0 -125
  86. package/packages/preview/tsconfig.json +0 -22
  87. package/packages/runtime/README.md +0 -3
  88. package/packages/runtime/package.json +0 -17
  89. package/packages/runtime/src/index.ts +0 -134
  90. package/packages/runtime/tsconfig.json +0 -23
  91. package/packages/settings/README.md +0 -7
  92. package/packages/settings/package.json +0 -16
  93. package/packages/settings/src/builtin-schemas.ts +0 -262
  94. package/packages/settings/src/configuration-service.ts +0 -609
  95. package/packages/settings/src/index.ts +0 -38
  96. package/packages/settings/src/jsonc.ts +0 -189
  97. package/packages/settings/src/schema.ts +0 -164
  98. package/packages/settings/tsconfig.json +0 -22
  99. package/packages/sql/README.md +0 -12
  100. package/packages/sql/package.json +0 -13
  101. package/packages/sql/src/completions.ts +0 -359
  102. package/packages/sql/src/diagnostics.ts +0 -200
  103. package/packages/sql/src/formatter.ts +0 -271
  104. package/packages/sql/src/index.ts +0 -54
  105. package/packages/sql/src/sql-editor.ts +0 -802
  106. package/packages/sql/src/styles.ts +0 -524
  107. package/packages/sql/src/tokenizer.ts +0 -457
  108. package/packages/sql/src/types.ts +0 -148
  109. package/packages/sql/tsconfig.json +0 -19
  110. package/packages/terminal/README.md +0 -3
  111. package/packages/terminal/package.json +0 -16
  112. package/packages/terminal/src/index.ts +0 -183
  113. package/packages/terminal/tsconfig.json +0 -22
  114. package/packages/ui/README.md +0 -8
  115. package/packages/ui/package.json +0 -18
  116. package/packages/ui/src/index.ts +0 -40
  117. package/packages/ui/src/observability.ts +0 -173
  118. package/packages/ui/src/plugin-registry.ts +0 -289
  119. package/packages/ui/src/settings-dialog.ts +0 -939
  120. package/packages/ui/src/themes.ts +0 -333
  121. package/packages/ui/tsconfig.json +0 -24
  122. package/src/code-lab.css +0 -8584
  123. package/src/csp.ts +0 -590
  124. package/src/diagnostics.ts +0 -287
  125. package/src/extensions/cpp.ts +0 -2389
  126. package/src/extensions/guided-lab.ts +0 -64
  127. package/src/extensions/javascript.ts +0 -54
  128. package/src/extensions/python.ts +0 -1737
  129. package/src/extensions/typescript.ts +0 -85
  130. package/src/extensions/umbrella.ts +0 -5
  131. package/src/html.ts +0 -88
  132. package/src/index.ts +0 -129
  133. package/src/logger.ts +0 -139
  134. package/src/modular-kernel.ts +0 -11
  135. package/src/preview-sw.js +0 -296
  136. package/src/runtime/test-harness.ts +0 -57
  137. package/src/runtime.ts +0 -10480
  138. package/src/sample.html +0 -304
  139. package/src/schemas.ts +0 -366
  140. package/src/scm.ts +0 -2453
  141. package/src/search.ts +0 -433
  142. package/src/shell.ts +0 -10987
  143. package/src/storage.ts +0 -773
  144. package/src/terminal.ts +0 -1400
  145. package/src/workbench/command-palette.ts +0 -381
  146. package/src/workbench/diff-editor.ts +0 -470
  147. package/src/workbench/drawer.ts +0 -157
  148. package/src/workbench/editor.ts +0 -49
  149. package/src/workbench/file-tree.ts +0 -51
  150. package/src/workbench/guided-pane.ts +0 -43
  151. package/src/workbench/icons.ts +0 -255
  152. package/src/workbench/index.ts +0 -44
  153. package/src/workbench/intellisense.ts +0 -1871
  154. package/src/workbench/share.ts +0 -128
  155. package/src/workbench/styles.ts +0 -211
  156. package/src/workbench/toolbar.ts +0 -182
  157. package/src/workbench/xterm-adapter.ts +0 -1571
  158. package/src/workbench.ts +0 -22132
  159. package/src/zip.ts +0 -348
package/dist/runtime.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.7.0 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.7.2 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
@@ -16,36 +16,36 @@
16
16
  */
17
17
  (function (root) {
18
18
  'use strict';
19
- var CodeLabLogger=(()=>{var s=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var y=(o,n)=>{for(var a in n)s(o,a,{get:n[a],enumerable:!0})},v=(o,n,a,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let e of C(n))!x.call(o,e)&&e!==a&&s(o,e,{get:()=>n[e],enumerable:!(t=p(n,e))||t.enumerable});return o};var O=o=>v(s({},"__esModule",{value:!0}),o);var h={};y(h,{CodeLabError:()=>d,DEFAULT_LOGGER:()=>w,LOG_PREFIX:()=>c,createLogger:()=>g,default:()=>_,isCodeLabError:()=>f});var c="[code-lab]",d=class extends Error{code;options;cause;recoverable;details;context;constructor(n,a,t={}){super(a),this.name="CodeLabError",this.code=n,this.options=t,this.cause=t.cause,this.recoverable=t.recoverable!==!1;let e=t.details??t.context;e!==void 0&&(this.details=e,this.context=e),Object.setPrototypeOf(this,new.target.prototype)}};function f(o){return!!(o&&typeof o=="object"&&(o instanceof d||o.name==="CodeLabError"&&typeof o.code=="string"))}function g(o={}){let n=o.logger??null,a=o.debug===!0,t=o.prefix||c,e=(r,b)=>{if(r==="debug"&&!a)return;if(n&&typeof n[r]=="function"){let L=null;try{n[r](...b);return}catch(k){L=k}}let i=typeof console<"u"?console:null,l=i?i[r]:null;typeof l=="function"&&l.call(i,t,...b)};return{debug:(...r)=>e("debug",r),info:(...r)=>e("info",r),warn:(...r)=>e("warn",r),error:(...r)=>e("error",r)}}var w=g(),E={LOG_PREFIX:c,CodeLabError:d,isCodeLabError:f,createLogger:g,DEFAULT_LOGGER:w},u=typeof globalThis<"u"?globalThis:null;u&&!u.CodeLabLogger&&(u.CodeLabLogger=E);var _=E;return O(h);})();
19
+ var CodeLabLogger=(()=>{var d=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var w=Object.prototype.hasOwnProperty;var k=(e,n)=>{for(var i in n)d(e,i,{get:n[i],enumerable:!0})},m=(e,n,i,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of R(n))!w.call(e,o)&&o!==i&&d(e,o,{get:()=>n[o],enumerable:!(r=y(n,o))||r.enumerable});return e};var _=e=>m(d({},"__esModule",{value:!0}),e);var h={};k(h,{CodeLabError:()=>s,DEFAULT_LOGGER:()=>f,LOG_PREFIX:()=>a,createLogger:()=>c,default:()=>C,isCodeLabError:()=>g});var s=class extends Error{code;options;cause;context;details;recoverable;constructor(n,i,r={}){super(i,r.cause!==void 0?{cause:r.cause}:void 0),this.name="CodeLabError",this.code=n,this.options=r,this.cause=r.cause,this.recoverable=r.recoverable!==!1;let o=r.details??r.context;this.context=Object.freeze({...o??{}}),o!==void 0&&(this.details=this.context),Object.setPrototypeOf(this,new.target.prototype)}};function g(e){return e instanceof s||typeof e=="object"&&e!==null&&e.name==="CodeLabError"&&typeof e.code=="string"}var a="[code-lab]";function c(e={}){let n=e.logger??null,i=e.debug===!0,r=e.prefix||a,o=(t,L)=>{if(t==="debug"&&!i)return;if(n&&typeof n[t]=="function"){let b=null;try{n[t](...L);return}catch(v){b=v}}let l=typeof console<"u"?console:null,E=l?l[t]:null;typeof E=="function"&&E.call(l,r,...L)};return{debug:(...t)=>o("debug",t),info:(...t)=>o("info",t),warn:(...t)=>o("warn",t),error:(...t)=>o("error",t)}}var f=c(),p={LOG_PREFIX:a,CodeLabError:s,isCodeLabError:g,createLogger:c,DEFAULT_LOGGER:f},u=typeof globalThis<"u"?globalThis:null;u&&!u.CodeLabLogger&&(u.CodeLabLogger=p);var C=p;return _(h);})();
20
20
 
21
21
  (function () {
22
- "use strict";typeof globalThis<"u"&&typeof globalThis.Bun>"u"&&(globalThis.Bun={version:"1.1.20"});function __initVirtualRuntime(X){const j=X&&X.CodeLabLogger&&typeof X.CodeLabLogger.createLogger=="function"?X.CodeLabLogger.createLogger():{debug(){},info(){},warn(t,e){typeof console<"u"&&console.warn&&console.warn("[CodeLab]",t,e||"")},error(t,e){typeof console<"u"&&console.error&&console.error("[CodeLab]",t,e||"")}},de=typeof TextEncoder<"u"?new TextEncoder:null,ce=typeof TextDecoder<"u"?new TextDecoder("utf-8",{fatal:!1}):null;function ne(t){if(t=String(t),de)return de.encode(t);const e=[];for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);if(s<128)e.push(s);else if(s<2048)e.push(192|s>>6,128|s&63);else if(s>=55296&&s<=56319&&r+1<t.length){const n=t.charCodeAt(r+1);n>=56320&&n<=57343?(s=65536+((s&1023)<<10|n&1023),e.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|s&63),r++):e.push(224|s>>12,128|s>>6&63,128|s&63)}else e.push(224|s>>12,128|s>>6&63,128|s&63)}return new Uint8Array(e)}function Q(t){if(ce)return ce.decode(t);let e="",r=0;for(;r<t.length;){const s=t[r++];if(s<128)e+=String.fromCharCode(s);else if((s&224)===192){const n=t[r++]&63;e+=String.fromCharCode((s&31)<<6|n)}else if((s&240)===224){const n=t[r++]&63,i=t[r++]&63;e+=String.fromCharCode((s&15)<<12|n<<6|i)}else{const n=t[r++]&63,i=t[r++]&63,a=t[r++]&63,f=((s&7)<<18|n<<12|i<<6|a)-65536;e+=String.fromCharCode(55296+(f>>10),56320+(f&1023))}}return e}const ee="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",le=new Int16Array(256).fill(-1);for(let t=0;t<ee.length;t++)le[ee.charCodeAt(t)]=t;le[45]=62,le[95]=63;function ye(t,e=!1){let r="";const s=t.length;for(let n=0;n<s;n+=3){const i=t[n],a=n+1<s?t[n+1]:0,f=n+2<s?t[n+2]:0,m=i<<16|a<<8|f;r+=ee[m>>18&63],r+=ee[m>>12&63],r+=n+1<s?ee[m>>6&63]:e?"":"=",r+=n+2<s?ee[m&63]:e?"":"="}return e&&(r=r.replace(/\+/g,"-").replace(/\//g,"_")),r}function Se(t){const e=[];for(let i=0;i<t.length;i++){const a=t.charCodeAt(i);if(a===61)break;const f=a<256?le[a]:-1;f>=0&&e.push(f)}const r=Math.floor(e.length*3/4),s=new Uint8Array(r);let n=0;for(let i=0;i<e.length;i+=4){const a=e[i],f=i+1<e.length?e[i+1]:0,m=i+2<e.length?e[i+2]:0,b=i+3<e.length?e[i+3]:0,x=a<<18|f<<12|m<<6|b;n<r&&(s[n++]=x>>16&255),n<r&&(s[n++]=x>>8&255),n<r&&(s[n++]=x&255)}return s}function Ne(t){let e="";for(let r=0;r<t.length;r++){const s=t[r];e+=(s<16?"0":"")+s.toString(16)}return e}function ke(t){t=String(t);const e=[];for(let r=0;r+1<t.length;r+=2){const s=parseInt(t.slice(r,r+2),16);if(Number.isNaN(s))break;e.push(s)}return new Uint8Array(e)}class P extends Uint8Array{constructor(e,r,s){typeof e=="number"?super(e):e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer?super(e,r,s):e!==void 0?super(e):super(0),this._isVirtualBuffer=!0}static get[Symbol.species](){return P}static isBuffer(e){return!!(e&&(e instanceof P||e._isVirtualBuffer===!0))}static isEncoding(e){return typeof e!="string"?!1:["utf8","utf-8","hex","base64","base64url","ascii","latin1","binary","ucs2","ucs-2","utf16le","utf-16le"].includes(e.toLowerCase())}static from(e,r,s){if(typeof e=="string"){const n=(typeof r=="string"?r:"utf8").toLowerCase();let i;if(n==="utf8"||n==="utf-8")i=ne(e);else if(n==="hex")i=ke(e);else if(n==="base64"||n==="base64url")i=Se(e);else if(n==="ascii"||n==="latin1"||n==="binary"){i=new Uint8Array(e.length);for(let f=0;f<e.length;f++)i[f]=e.charCodeAt(f)&255}else if(n==="utf16le"||n==="utf-16le"||n==="ucs2"||n==="ucs-2"){i=new Uint8Array(e.length*2);for(let f=0;f<e.length;f++){const m=e.charCodeAt(f);i[f*2]=m&255,i[f*2+1]=m>>>8&255}}else i=ne(e);const a=new P(i.length);return a.set(i),a}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){const n=new Uint8Array(e,r||0,s!==void 0?s:e.byteLength-(r||0));return Object.setPrototypeOf(n,P.prototype),n._isVirtualBuffer=!0,n}if(ArrayBuffer.isView(e)){const n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),i=new P(n.length);return i.set(n),i}if(Array.isArray(e)||e&&typeof e.length=="number"){const n=new P(e.length);for(let i=0;i<e.length;i++)n[i]=e[i]&255;return n}if(e&&typeof e.valueOf=="function"&&e.valueOf()!==e)return P.from(e.valueOf(),r,s);throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object")}static alloc(e,r,s){if(typeof e!="number"||e<0||!Number.isFinite(e))throw new RangeError("Invalid buffer size");const n=new P(e);return r!==void 0&&e>0&&n.fill(r,0,e,s),n}static allocUnsafe(e){return P.alloc(e)}static allocUnsafeSlow(e){return P.alloc(e)}static concat(e,r){if(!Array.isArray(e))throw new TypeError("list argument must be an Array");if(e.length===0)return P.alloc(0);let s=r;if(s===void 0){s=0;for(let a=0;a<e.length;a++)s+=e[a].length}const n=P.alloc(s);let i=0;for(let a=0;a<e.length;a++){const f=e[a];if(i+f.length>s){n.set(f.subarray(0,s-i),i);break}n.set(f,i),i+=f.length}return n}static byteLength(e,r="utf8"){if(typeof e!="string"){if(e&&typeof e.byteLength=="number")return e.byteLength;if(e&&typeof e.length=="number")return e.length;throw new TypeError('The "string" argument must be of type string or an instance of Buffer or ArrayBuffer')}const s=(r||"utf8").toLowerCase();return s==="utf8"||s==="utf-8"?ne(e).length:s==="ascii"||s==="latin1"||s==="binary"?e.length:s==="utf16le"||s==="utf-16le"||s==="ucs2"||s==="ucs-2"?e.length*2:s==="hex"?e.length>>>1:s==="base64"||s==="base64url"?Se(e).length:ne(e).length}static compare(e,r){if(!(e instanceof Uint8Array)||!(r instanceof Uint8Array))throw new TypeError("Arguments must be Buffers or Uint8Arrays");const s=Math.min(e.length,r.length);for(let n=0;n<s;n++)if(e[n]!==r[n])return e[n]<r[n]?-1:1;return e.length===r.length?0:e.length<r.length?-1:1}fill(e,r=0,s=this.length,n="utf8"){if(typeof r=="string"?(n=r,r=0,s=this.length):typeof s=="string"&&(n=s,s=this.length),typeof e=="number")return super.fill(e&255,r,s),this;const i=typeof e=="string"?P.from(e,n):e;if(!i||i.length===0)return super.fill(0,r,s),this;for(let a=r;a<s;a++)this[a]=i[(a-r)%i.length];return this}subarray(e=0,r=this.length){const s=Uint8Array.prototype.subarray.call(this,e,r);return Object.setPrototypeOf(s,P.prototype),s._isVirtualBuffer=!0,s}slice(e=0,r=this.length){return this.subarray(e,r)}compare(e,r=0,s=e.length,n=0,i=this.length){const a=this.subarray(n,i),f=e.subarray(r,s);return P.compare(a,f)}equals(e){return!(e instanceof Uint8Array)||this.length!==e.length?!1:P.compare(this,e)===0}copy(e,r=0,s=0,n=this.length){if(s>=n||r>=e.length)return 0;const i=this.subarray(s,n),a=Math.min(i.length,e.length-r);return e.set(i.subarray(0,a),r),a}write(e,r=0,s=this.length-r,n="utf8"){typeof r=="string"?(n=r,r=0,s=this.length):typeof s=="string"&&(n=s,s=this.length-r);const i=P.from(String(e),n),a=Math.min(i.length,s,this.length-r);return a<=0?0:(this.set(i.subarray(0,a),r),a)}toString(e="utf8",r=0,s=this.length){if(r<0&&(r=0),s>this.length&&(s=this.length),r>=s)return"";const n=Uint8Array.prototype.subarray.call(this,r,s),i=String(e||"utf8").toLowerCase();if(i==="utf8"||i==="utf-8")return Q(n);if(i==="hex")return Ne(n);if(i==="base64")return ye(n,!1);if(i==="base64url")return ye(n,!0);if(i==="ascii"||i==="latin1"||i==="binary"){let a="";for(let f=0;f<n.length;f++)a+=String.fromCharCode(n[f]);return a}if(i==="utf16le"||i==="utf-16le"||i==="ucs2"||i==="ucs-2"){let a="";for(let f=0;f+1<n.length;f+=2)a+=String.fromCharCode(n[f]|n[f+1]<<8);return a}return Q(n)}toJSON(){return{type:"Buffer",data:Array.from(this)}}_dv(){return new DataView(this.buffer,this.byteOffset,this.byteLength)}readUInt8(e=0){return this._dv().getUint8(e)}readUint8(e=0){return this._dv().getUint8(e)}readInt8(e=0){return this._dv().getInt8(e)}readUInt16BE(e=0){return this._dv().getUint16(e,!1)}readUint16BE(e=0){return this._dv().getUint16(e,!1)}readUInt16LE(e=0){return this._dv().getUint16(e,!0)}readUint16LE(e=0){return this._dv().getUint16(e,!0)}readInt16BE(e=0){return this._dv().getInt16(e,!1)}readInt16LE(e=0){return this._dv().getInt16(e,!0)}readUInt32BE(e=0){return this._dv().getUint32(e,!1)}readUint32BE(e=0){return this._dv().getUint32(e,!1)}readUInt32LE(e=0){return this._dv().getUint32(e,!0)}readUint32LE(e=0){return this._dv().getUint32(e,!0)}readInt32BE(e=0){return this._dv().getInt32(e,!1)}readInt32LE(e=0){return this._dv().getInt32(e,!0)}readBigUInt64BE(e=0){return this._dv().getBigUint64(e,!1)}readBigUint64BE(e=0){return this._dv().getBigUint64(e,!1)}readBigUInt64LE(e=0){return this._dv().getBigUint64(e,!0)}readBigUint64LE(e=0){return this._dv().getBigUint64(e,!0)}readBigInt64BE(e=0){return this._dv().getBigInt64(e,!1)}readBigInt64LE(e=0){return this._dv().getBigInt64(e,!0)}readFloatBE(e=0){return this._dv().getFloat32(e,!1)}readFloatLE(e=0){return this._dv().getFloat32(e,!0)}readDoubleBE(e=0){return this._dv().getFloat64(e,!1)}readDoubleLE(e=0){return this._dv().getFloat64(e,!0)}writeUInt8(e,r=0){return this._dv().setUint8(r,Number(e)),r+1}writeUint8(e,r=0){return this.writeUInt8(e,r)}writeInt8(e,r=0){return this._dv().setInt8(r,Number(e)),r+1}writeUInt16BE(e,r=0){return this._dv().setUint16(r,Number(e),!1),r+2}writeUint16BE(e,r=0){return this.writeUInt16BE(e,r)}writeUInt16LE(e,r=0){return this._dv().setUint16(r,Number(e),!0),r+2}writeUint16LE(e,r=0){return this.writeUInt16LE(e,r)}writeInt16BE(e,r=0){return this._dv().setInt16(r,Number(e),!1),r+2}writeInt16LE(e,r=0){return this._dv().setInt16(r,Number(e),!0),r+2}writeUInt32BE(e,r=0){return this._dv().setUint32(r,Number(e)>>>0,!1),r+4}writeUint32BE(e,r=0){return this.writeUInt32BE(e,r)}writeUInt32LE(e,r=0){return this._dv().setUint32(r,Number(e)>>>0,!0),r+4}writeUint32LE(e,r=0){return this.writeUInt32LE(e,r)}writeInt32BE(e,r=0){return this._dv().setInt32(r,Number(e)|0,!1),r+4}writeInt32LE(e,r=0){return this._dv().setInt32(r,Number(e)|0,!0),r+4}writeBigUInt64BE(e,r=0){return this._dv().setBigUint64(r,BigInt(e),!1),r+8}writeBigUint64BE(e,r=0){return this.writeBigUInt64BE(e,r)}writeBigUInt64LE(e,r=0){return this._dv().setBigUint64(r,BigInt(e),!0),r+8}writeBigUint64LE(e,r=0){return this.writeBigUInt64LE(e,r)}writeBigInt64BE(e,r=0){return this._dv().setBigInt64(r,BigInt(e),!1),r+8}writeBigInt64LE(e,r=0){return this._dv().setBigInt64(r,BigInt(e),!0),r+8}writeFloatBE(e,r=0){return this._dv().setFloat32(r,Number(e),!1),r+4}writeFloatLE(e,r=0){return this._dv().setFloat32(r,Number(e),!0),r+4}writeDoubleBE(e,r=0){return this._dv().setFloat64(r,Number(e),!1),r+8}writeDoubleLE(e,r=0){return this._dv().setFloat64(r,Number(e),!0),r+8}}const tt=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],Ve=new Uint32Array(64);for(let t=0;t<64;t++)Ve[t]=Math.floor(Math.abs(Math.sin(t+1))*4294967296)>>>0;function nt(t){const e=t.length,r=e<<3>>>0,s=e>>>29>>>0,n=(e+8&-64)+64,i=new Uint8Array(n);i.set(t),i[e]=128;const a=new DataView(i.buffer);a.setUint32(n-8,r,!0),a.setUint32(n-4,s,!0);let f=1732584193,m=4023233417,b=2562383102,x=271733878;const u=new Uint32Array(16);for(let y=0;y<n;y+=64){for(let l=0;l<16;l++)u[l]=a.getUint32(y+l*4,!0);let A=f,M=m,k=b,$=x;for(let l=0;l<64;l++){let F,U;l<16?(F=M&k|~M&$,U=l):l<32?(F=$&M|~$&k,U=(5*l+1)%16):l<48?(F=M^k^$,U=(3*l+5)%16):(F=k^(M|~$),U=7*l%16),F=F+A+Ve[l]+u[U]|0,A=$,$=k,k=M;const C=tt[l];M=M+(F<<C|F>>>32-C)|0}f=f+A|0,m=m+M|0,b=b+k|0,x=x+$|0}const d=P.alloc(16);return d.writeInt32LE(f,0),d.writeInt32LE(m,4),d.writeInt32LE(b,8),d.writeInt32LE(x,12),d}const Oe=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function Ie(t,e){return t>>>e|t<<32-e}function rt(t){const e=t.length,r=Math.floor(e/536870912),s=e<<3>>>0,n=(e+8&-64)+64,i=new Uint8Array(n);i.set(t),i[e]=128;const a=new DataView(i.buffer);a.setUint32(n-8,r,!1),a.setUint32(n-4,s,!1);let f=1779033703,m=3144134277,b=1013904242,x=2773480762,u=1359893119,d=2600822924,y=528734635,A=1541459225;const M=new Uint32Array(64);for(let $=0;$<n;$+=64){for(let T=0;T<16;T++)M[T]=a.getUint32($+T*4,!1);for(let T=16;T<64;T++){const R=Ie(M[T-15],7)^Ie(M[T-15],18)^M[T-15]>>>3,N=Ie(M[T-2],17)^Ie(M[T-2],19)^M[T-2]>>>10;M[T]=M[T-16]+R+M[T-7]+N>>>0}let l=f,F=m,U=b,C=x,w=u,g=d,p=y,_=A;for(let T=0;T<64;T++){const R=Ie(w,6)^Ie(w,11)^Ie(w,25),N=w&g^~w&p,L=_+R+N+Oe[T]+M[T]>>>0,O=Ie(l,2)^Ie(l,13)^Ie(l,22),B=l&F^l&U^F&U,Z=O+B>>>0;_=p,p=g,g=w,w=C+L>>>0,C=U,U=F,F=l,l=L+Z>>>0}f=f+l>>>0,m=m+F>>>0,b=b+U>>>0,x=x+C>>>0,u=u+w>>>0,d=d+g>>>0,y=y+p>>>0,A=A+_>>>0}const k=P.alloc(32);return k.writeUInt32BE(f,0),k.writeUInt32BE(m,4),k.writeUInt32BE(b,8),k.writeUInt32BE(x,12),k.writeUInt32BE(u,16),k.writeUInt32BE(d,20),k.writeUInt32BE(y,24),k.writeUInt32BE(A,28),k}function je(t){const e=t.length,r=Math.floor(e/536870912),s=e<<3>>>0,n=(e+8&-64)+64,i=new Uint8Array(n);i.set(t),i[e]=128;const a=new DataView(i.buffer);a.setUint32(n-8,r,!1),a.setUint32(n-4,s,!1);let f=1732584193,m=4023233417,b=2562383102,x=271733878,u=3285377520;const d=new Uint32Array(80);for(let A=0;A<n;A+=64){for(let U=0;U<16;U++)d[U]=a.getUint32(A+U*4,!1);for(let U=16;U<80;U++){const C=d[U-3]^d[U-8]^d[U-14]^d[U-16];d[U]=(C<<1|C>>>31)>>>0}let M=f,k=m,$=b,l=x,F=u;for(let U=0;U<80;U++){let C,w;U<20?(C=k&$|~k&l,w=1518500249):U<40?(C=k^$^l,w=1859775393):U<60?(C=k&$|k&l|$&l,w=2400959708):(C=k^$^l,w=3395469782);const g=((M<<5|M>>>27)>>>0)+(C>>>0)+F+w+d[U]>>>0;F=l,l=$,$=(k<<30|k>>>2)>>>0,k=M,M=g}f=f+M>>>0,m=m+k>>>0,b=b+$>>>0,x=x+l>>>0,u=u+F>>>0}const y=P.alloc(20);return y.writeUInt32BE(f,0),y.writeUInt32BE(m,4),y.writeUInt32BE(b,8),y.writeUInt32BE(x,12),y.writeUInt32BE(u,16),y}function st(t,e){const r=String(t).toLowerCase().replace("-","");if(r==="md5")return nt(e);if(r==="sha1")return je(e);if(r==="sha256")return rt(e);throw new Error(`Unsupported hash algorithm: ${t}`)}class he{constructor(e){this.algorithm=e,this.chunks=[],this.digested=!1}update(e,r){if(this.digested)throw new Error("Digest already called");const s=typeof e=="string"?P.from(e,r||"utf8"):P.from(e);return this.chunks.push(s),this}digest(e){if(this.digested)throw new Error("Digest already called");this.digested=!0;const r=P.concat(this.chunks),s=st(this.algorithm,r);return!e||e==="buffer"?s:s.toString(e)}}class te{constructor(e,r){this.algorithm=e;let s=typeof r=="string"?P.from(r,"utf8"):P.from(r);const n=64;s.length>n&&(s=st(e,s)),this.ipad=P.alloc(n,54),this.opad=P.alloc(n,92);for(let i=0;i<s.length;i++)this.ipad[i]^=s[i],this.opad[i]^=s[i];this.inner=new he(e),this.inner.update(this.ipad),this.digested=!1}update(e,r){return this.inner.update(e,r),this}digest(e){if(this.digested)throw new Error("Digest already called");this.digested=!0;const r=this.inner.digest(),s=new he(this.algorithm);return s.update(this.opad),s.update(r),s.digest(e)}}const Fe={createHash(t){return new he(t)},createHmac(t,e){return new te(t,e)},timingSafeEqual(t,e){if(!ArrayBuffer.isView(t)||!ArrayBuffer.isView(e))throw new TypeError("Input must be Buffer or TypedArray");if(t.byteLength!==e.byteLength)throw new RangeError("Input buffers must have the same byte length");const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);let n=0;for(let i=0;i<r.length;i++)n|=r[i]^s[i];return n===0},randomBytes(t,e){const r=P.alloc(t);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(r);else for(let s=0;s<t;s++)r[s]=Math.floor(Math.random()*256);return typeof e=="function"&&queueMicrotask(()=>e(null,r)),r},randomUUID(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();const t=Fe.randomBytes(16);t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=t.toString("hex");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20,32)}`}},fn=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})(),xe={crc32(t,e=0){const r=typeof t=="string"?ne(t):t instanceof Uint8Array?t:P.from(t);let s=e>>>0^4294967295;for(let n=0;n<r.length;n++)s=fn[(s^r[n])&255]^s>>>8;return(s^4294967295)>>>0},constants:{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,ZLIB_VERNUM:4880,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1}};(()=>{let t=null;try{t=typeof require=="function"?require("zlib"):null}catch{t=null}const e=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","unzip","gzipSync","gunzipSync","deflateSync","inflateSync","deflateRawSync","inflateRawSync","unzipSync","createGzip","createGunzip","createDeflate","createInflate","createDeflateRaw","createInflateRaw"];if(t){for(const n of e)typeof t[n]=="function"&&(xe[n]=t[n].bind(t));return}const r=(n,i)=>(a,f,m)=>{const b=typeof f=="function"?f:typeof m=="function"?m:null,x=(async()=>{if(typeof CompressionStream>"u"||typeof DecompressionStream>"u"||typeof Response>"u")throw new Error("zlib."+i+" is not supported in this environment");const d=/^(gunzip|unzip|inflate)/.test(i)?new DecompressionStream(n):new CompressionStream(n),y=d.writable.getWriter(),A=a instanceof Uint8Array?a:P.from(a);y.write(A),y.close();const M=await new Response(d.readable).arrayBuffer();return P.from(M)})();if(b){x.then(u=>b(null,u),u=>b(u));return}return x};xe.gzip=r("gzip","gzip"),xe.gunzip=r("gzip","gunzip"),xe.unzip=r("gzip","unzip"),xe.deflate=r("deflate","deflate"),xe.inflate=r("deflate","inflate"),xe.deflateRaw=r("deflate-raw","deflateRaw"),xe.inflateRaw=r("deflate-raw","inflateRaw");const s=n=>()=>{throw new Error("zlib."+n+" is not supported in a browser worker (use the async API)")};xe.gzipSync=s("gzipSync"),xe.gunzipSync=s("gunzipSync"),xe.deflateSync=s("deflateSync"),xe.inflateSync=s("inflateSync"),xe.deflateRawSync=s("deflateRawSync"),xe.inflateRawSync=s("inflateRawSync"),xe.unzipSync=s("unzipSync")})();let it=()=>"/workspace";const J={sep:"/",delimiter:":",normalize(t){if(typeof t!="string")throw new TypeError("Path must be a string");if(t.length===0)return".";const e=t.startsWith("/"),r=t.endsWith("/")&&t.length>1,s=t.split("/"),n=[];for(let a=0;a<s.length;a++){const f=s[a];!f||f==="."||(f===".."?n.length>0&&n[n.length-1]!==".."?n.pop():e||n.push(".."):n.push(f))}let i=(e?"/":"")+n.join("/");return i||(i=e?"/":"."),r&&i!=="/"&&(i+="/"),i},join(...t){if(t.length===0)return".";const e=t.filter(r=>r!=="").join("/");return e?J.normalize(e):"."},resolve(...t){let e="";for(let s=t.length-1;s>=0&&!e.startsWith("/");s--){const n=t[s];n&&(e=e?`${n}/${e}`:n)}e.startsWith("/")||(e=`${typeof it=="function"?it():"/workspace"}/${e}`);const r=J.normalize(e);return r.length>1&&r.endsWith("/")?r.slice(0,-1):r},relative(t,e){const r=J.resolve(t),s=J.resolve(e);if(r===s)return"";const n=r.split("/").filter(Boolean),i=s.split("/").filter(Boolean);let a=0;for(;a<n.length&&a<i.length&&n[a]===i[a];)a++;return[...new Array(n.length-a).fill(".."),...i.slice(a)].join("/")},dirname(t){if(typeof t!="string")throw new TypeError("Path must be a string");if(t.length===0)return".";const e=t.length>1&&t.endsWith("/")?t.slice(0,-1):t,r=e.lastIndexOf("/");return r===-1?".":r===0?"/":e.slice(0,r)},basename(t,e){if(typeof t!="string")throw new TypeError("Path must be a string");const r=t.length>1&&t.endsWith("/")?t.slice(0,-1):t,s=r.lastIndexOf("/");let n=s===-1?r:r.slice(s+1);return e&&n.endsWith(e)&&(n=n.slice(0,n.length-e.length)),n},extname(t){const e=J.basename(t),r=e.lastIndexOf(".");return r<=0?"":e.slice(r)},parse(t){if(typeof t!="string")throw new TypeError("Path must be a string");const e=t.startsWith("/")?"/":"",r=t?J.dirname(t):"",s=t?J.basename(t):"",n=t?J.extname(t):"",i=n?s.slice(0,s.length-n.length):s;return{root:e,dir:r==="."&&!t.startsWith("./")?"":r,base:s,ext:n,name:i}},format(t){if(!t||typeof t!="object")throw new TypeError("pathObject must be an object");const e=t.dir||t.root||"",r=t.base||`${t.name||""}${t.ext||""}`;return e?e===t.root?`${e}${r}`:`${e}/${r}`:r},isAbsolute(t){return typeof t=="string"&&t.startsWith("/")}};J.posix=J;let xt=null;const ln={tmpdir:()=>"/tmp",EOL:`
23
- `,platform:()=>"linux",arch:()=>"x64",homedir:()=>typeof xt=="function"?xt():"/home/codelab",hostname:()=>"code-lab-vm",cpus:()=>[{model:"Virtual Code-Lab CPU",speed:3200}]},jt=new Map;function or(t,e){if(!e||typeof e!="object")return t;const r=new Set;let s=t.replace(/(^|\n)\s*const\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=/g,(u,d,y)=>(r.add(y),`${d}let ${y} =`));const n=/(?:^|\n)\s*(?:let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\b/g;let i;for(;(i=n.exec(s))!==null;)r.add(i[1]);const a=/(?:^|\n)\s*(?:async\s+)?(?:function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)\b/g;for(;(i=a.exec(s))!==null;)r.add(i[1]);const f=Object.keys(e).filter(u=>/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(u)&&!r.has(u)),m=f.map(u=>`let ${u} = __replCtx[${JSON.stringify(u)}];`).join(`
24
- `),x=Array.from(new Set([...f,...Array.from(r)])).map(u=>`try { if (typeof ${u} !== 'undefined') __replCtx[${JSON.stringify(u)}] = ${u}; } catch (_e) { void _e; }`).join(`
25
- `);return`${m}
22
+ "use strict";typeof globalThis<"u"&&typeof globalThis.Bun>"u"&&(globalThis.Bun={version:"1.1.20"});function __initVirtualRuntime(X){const D=X&&X.CodeLabLogger&&typeof X.CodeLabLogger.createLogger=="function"?X.CodeLabLogger.createLogger():{debug(){},info(){},warn(t,e){typeof console<"u"&&console.warn&&console.warn("[CodeLab]",t,e||"")},error(t,e){typeof console<"u"&&console.error&&console.error("[CodeLab]",t,e||"")}},he=typeof TextEncoder<"u"?new TextEncoder:null,ce=typeof TextDecoder<"u"?new TextDecoder("utf-8",{fatal:!1}):null;function se(t){if(t=String(t),he)return he.encode(t);const e=[];for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);if(s<128)e.push(s);else if(s<2048)e.push(192|s>>6,128|s&63);else if(s>=55296&&s<=56319&&r+1<t.length){const n=t.charCodeAt(r+1);n>=56320&&n<=57343?(s=65536+((s&1023)<<10|n&1023),e.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|s&63),r++):e.push(224|s>>12,128|s>>6&63,128|s&63)}else e.push(224|s>>12,128|s>>6&63,128|s&63)}return new Uint8Array(e)}function te(t){if(ce)return ce.decode(t);let e="",r=0;for(;r<t.length;){const s=t[r++];if(s<128)e+=String.fromCharCode(s);else if((s&224)===192){const n=t[r++]&63;e+=String.fromCharCode((s&31)<<6|n)}else if((s&240)===224){const n=t[r++]&63,i=t[r++]&63;e+=String.fromCharCode((s&15)<<12|n<<6|i)}else{const n=t[r++]&63,i=t[r++]&63,a=t[r++]&63,f=((s&7)<<18|n<<12|i<<6|a)-65536;e+=String.fromCharCode(55296+(f>>10),56320+(f&1023))}}return e}const ne="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ue=new Int16Array(256).fill(-1);for(let t=0;t<ne.length;t++)ue[ne.charCodeAt(t)]=t;ue[45]=62,ue[95]=63;function ge(t,e=!1){let r="";const s=t.length;for(let n=0;n<s;n+=3){const i=t[n],a=n+1<s?t[n+1]:0,f=n+2<s?t[n+2]:0,p=i<<16|a<<8|f;r+=ne[p>>18&63],r+=ne[p>>12&63],r+=n+1<s?ne[p>>6&63]:e?"":"=",r+=n+2<s?ne[p&63]:e?"":"="}return e&&(r=r.replace(/\+/g,"-").replace(/\//g,"_")),r}function xe(t){const e=[];for(let i=0;i<t.length;i++){const a=t.charCodeAt(i);if(a===61)break;const f=a<256?ue[a]:-1;f>=0&&e.push(f)}const r=Math.floor(e.length*3/4),s=new Uint8Array(r);let n=0;for(let i=0;i<e.length;i+=4){const a=e[i],f=i+1<e.length?e[i+1]:0,p=i+2<e.length?e[i+2]:0,y=i+3<e.length?e[i+3]:0,S=a<<18|f<<12|p<<6|y;n<r&&(s[n++]=S>>16&255),n<r&&(s[n++]=S>>8&255),n<r&&(s[n++]=S&255)}return s}function $e(t){let e="";for(let r=0;r<t.length;r++){const s=t[r];e+=(s<16?"0":"")+s.toString(16)}return e}function Ie(t){t=String(t);const e=[];for(let r=0;r+1<t.length;r+=2){const s=parseInt(t.slice(r,r+2),16);if(Number.isNaN(s))break;e.push(s)}return new Uint8Array(e)}class O extends Uint8Array{constructor(e,r,s){typeof e=="number"?super(e):e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer?super(e,r,s):e!==void 0?super(e):super(0),this._isVirtualBuffer=!0}static get[Symbol.species](){return O}static isBuffer(e){return!!(e&&(e instanceof O||e._isVirtualBuffer===!0))}static isEncoding(e){return typeof e!="string"?!1:["utf8","utf-8","hex","base64","base64url","ascii","latin1","binary","ucs2","ucs-2","utf16le","utf-16le"].includes(e.toLowerCase())}static from(e,r,s){if(typeof e=="string"){const n=(typeof r=="string"?r:"utf8").toLowerCase();let i;if(n==="utf8"||n==="utf-8")i=se(e);else if(n==="hex")i=Ie(e);else if(n==="base64"||n==="base64url")i=xe(e);else if(n==="ascii"||n==="latin1"||n==="binary"){i=new Uint8Array(e.length);for(let f=0;f<e.length;f++)i[f]=e.charCodeAt(f)&255}else if(n==="utf16le"||n==="utf-16le"||n==="ucs2"||n==="ucs-2"){i=new Uint8Array(e.length*2);for(let f=0;f<e.length;f++){const p=e.charCodeAt(f);i[f*2]=p&255,i[f*2+1]=p>>>8&255}}else i=se(e);const a=new O(i.length);return a.set(i),a}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){const n=new Uint8Array(e,r||0,s!==void 0?s:e.byteLength-(r||0));return Object.setPrototypeOf(n,O.prototype),n._isVirtualBuffer=!0,n}if(ArrayBuffer.isView(e)){const n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),i=new O(n.length);return i.set(n),i}if(Array.isArray(e)||e&&typeof e.length=="number"){const n=new O(e.length);for(let i=0;i<e.length;i++)n[i]=e[i]&255;return n}if(e&&typeof e.valueOf=="function"&&e.valueOf()!==e)return O.from(e.valueOf(),r,s);throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object")}static alloc(e,r,s){if(typeof e!="number"||e<0||!Number.isFinite(e))throw new RangeError("Invalid buffer size");const n=new O(e);return r!==void 0&&e>0&&n.fill(r,0,e,s),n}static allocUnsafe(e){return O.alloc(e)}static allocUnsafeSlow(e){return O.alloc(e)}static concat(e,r){if(!Array.isArray(e))throw new TypeError("list argument must be an Array");if(e.length===0)return O.alloc(0);let s=r;if(s===void 0){s=0;for(let a=0;a<e.length;a++)s+=e[a].length}const n=O.alloc(s);let i=0;for(let a=0;a<e.length;a++){const f=e[a];if(i+f.length>s){n.set(f.subarray(0,s-i),i);break}n.set(f,i),i+=f.length}return n}static byteLength(e,r="utf8"){if(typeof e!="string"){if(e&&typeof e.byteLength=="number")return e.byteLength;if(e&&typeof e.length=="number")return e.length;throw new TypeError('The "string" argument must be of type string or an instance of Buffer or ArrayBuffer')}const s=(r||"utf8").toLowerCase();return s==="utf8"||s==="utf-8"?se(e).length:s==="ascii"||s==="latin1"||s==="binary"?e.length:s==="utf16le"||s==="utf-16le"||s==="ucs2"||s==="ucs-2"?e.length*2:s==="hex"?e.length>>>1:s==="base64"||s==="base64url"?xe(e).length:se(e).length}static compare(e,r){if(!(e instanceof Uint8Array)||!(r instanceof Uint8Array))throw new TypeError("Arguments must be Buffers or Uint8Arrays");const s=Math.min(e.length,r.length);for(let n=0;n<s;n++)if(e[n]!==r[n])return e[n]<r[n]?-1:1;return e.length===r.length?0:e.length<r.length?-1:1}fill(e,r=0,s=this.length,n="utf8"){if(typeof r=="string"?(n=r,r=0,s=this.length):typeof s=="string"&&(n=s,s=this.length),typeof e=="number")return super.fill(e&255,r,s),this;const i=typeof e=="string"?O.from(e,n):e;if(!i||i.length===0)return super.fill(0,r,s),this;for(let a=r;a<s;a++)this[a]=i[(a-r)%i.length];return this}subarray(e=0,r=this.length){const s=Uint8Array.prototype.subarray.call(this,e,r);return Object.setPrototypeOf(s,O.prototype),s._isVirtualBuffer=!0,s}slice(e=0,r=this.length){return this.subarray(e,r)}compare(e,r=0,s=e.length,n=0,i=this.length){const a=this.subarray(n,i),f=e.subarray(r,s);return O.compare(a,f)}equals(e){return!(e instanceof Uint8Array)||this.length!==e.length?!1:O.compare(this,e)===0}copy(e,r=0,s=0,n=this.length){if(s>=n||r>=e.length)return 0;const i=this.subarray(s,n),a=Math.min(i.length,e.length-r);return e.set(i.subarray(0,a),r),a}write(e,r=0,s=this.length-r,n="utf8"){typeof r=="string"?(n=r,r=0,s=this.length):typeof s=="string"&&(n=s,s=this.length-r);const i=O.from(String(e),n),a=Math.min(i.length,s,this.length-r);return a<=0?0:(this.set(i.subarray(0,a),r),a)}toString(e="utf8",r=0,s=this.length){if(r<0&&(r=0),s>this.length&&(s=this.length),r>=s)return"";const n=Uint8Array.prototype.subarray.call(this,r,s),i=String(e||"utf8").toLowerCase();if(i==="utf8"||i==="utf-8")return te(n);if(i==="hex")return $e(n);if(i==="base64")return ge(n,!1);if(i==="base64url")return ge(n,!0);if(i==="ascii"||i==="latin1"||i==="binary"){let a="";for(let f=0;f<n.length;f++)a+=String.fromCharCode(n[f]);return a}if(i==="utf16le"||i==="utf-16le"||i==="ucs2"||i==="ucs-2"){let a="";for(let f=0;f+1<n.length;f+=2)a+=String.fromCharCode(n[f]|n[f+1]<<8);return a}return te(n)}toJSON(){return{type:"Buffer",data:Array.from(this)}}_dv(){return new DataView(this.buffer,this.byteOffset,this.byteLength)}readUInt8(e=0){return this._dv().getUint8(e)}readUint8(e=0){return this._dv().getUint8(e)}readInt8(e=0){return this._dv().getInt8(e)}readUInt16BE(e=0){return this._dv().getUint16(e,!1)}readUint16BE(e=0){return this._dv().getUint16(e,!1)}readUInt16LE(e=0){return this._dv().getUint16(e,!0)}readUint16LE(e=0){return this._dv().getUint16(e,!0)}readInt16BE(e=0){return this._dv().getInt16(e,!1)}readInt16LE(e=0){return this._dv().getInt16(e,!0)}readUInt32BE(e=0){return this._dv().getUint32(e,!1)}readUint32BE(e=0){return this._dv().getUint32(e,!1)}readUInt32LE(e=0){return this._dv().getUint32(e,!0)}readUint32LE(e=0){return this._dv().getUint32(e,!0)}readInt32BE(e=0){return this._dv().getInt32(e,!1)}readInt32LE(e=0){return this._dv().getInt32(e,!0)}readBigUInt64BE(e=0){return this._dv().getBigUint64(e,!1)}readBigUint64BE(e=0){return this._dv().getBigUint64(e,!1)}readBigUInt64LE(e=0){return this._dv().getBigUint64(e,!0)}readBigUint64LE(e=0){return this._dv().getBigUint64(e,!0)}readBigInt64BE(e=0){return this._dv().getBigInt64(e,!1)}readBigInt64LE(e=0){return this._dv().getBigInt64(e,!0)}readFloatBE(e=0){return this._dv().getFloat32(e,!1)}readFloatLE(e=0){return this._dv().getFloat32(e,!0)}readDoubleBE(e=0){return this._dv().getFloat64(e,!1)}readDoubleLE(e=0){return this._dv().getFloat64(e,!0)}writeUInt8(e,r=0){return this._dv().setUint8(r,Number(e)),r+1}writeUint8(e,r=0){return this.writeUInt8(e,r)}writeInt8(e,r=0){return this._dv().setInt8(r,Number(e)),r+1}writeUInt16BE(e,r=0){return this._dv().setUint16(r,Number(e),!1),r+2}writeUint16BE(e,r=0){return this.writeUInt16BE(e,r)}writeUInt16LE(e,r=0){return this._dv().setUint16(r,Number(e),!0),r+2}writeUint16LE(e,r=0){return this.writeUInt16LE(e,r)}writeInt16BE(e,r=0){return this._dv().setInt16(r,Number(e),!1),r+2}writeInt16LE(e,r=0){return this._dv().setInt16(r,Number(e),!0),r+2}writeUInt32BE(e,r=0){return this._dv().setUint32(r,Number(e)>>>0,!1),r+4}writeUint32BE(e,r=0){return this.writeUInt32BE(e,r)}writeUInt32LE(e,r=0){return this._dv().setUint32(r,Number(e)>>>0,!0),r+4}writeUint32LE(e,r=0){return this.writeUInt32LE(e,r)}writeInt32BE(e,r=0){return this._dv().setInt32(r,Number(e)|0,!1),r+4}writeInt32LE(e,r=0){return this._dv().setInt32(r,Number(e)|0,!0),r+4}writeBigUInt64BE(e,r=0){return this._dv().setBigUint64(r,BigInt(e),!1),r+8}writeBigUint64BE(e,r=0){return this.writeBigUInt64BE(e,r)}writeBigUInt64LE(e,r=0){return this._dv().setBigUint64(r,BigInt(e),!0),r+8}writeBigUint64LE(e,r=0){return this.writeBigUInt64LE(e,r)}writeBigInt64BE(e,r=0){return this._dv().setBigInt64(r,BigInt(e),!1),r+8}writeBigInt64LE(e,r=0){return this._dv().setBigInt64(r,BigInt(e),!0),r+8}writeFloatBE(e,r=0){return this._dv().setFloat32(r,Number(e),!1),r+4}writeFloatLE(e,r=0){return this._dv().setFloat32(r,Number(e),!0),r+4}writeDoubleBE(e,r=0){return this._dv().setFloat64(r,Number(e),!1),r+8}writeDoubleLE(e,r=0){return this._dv().setFloat64(r,Number(e),!0),r+8}}const tt=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],Ve=new Uint32Array(64);for(let t=0;t<64;t++)Ve[t]=Math.floor(Math.abs(Math.sin(t+1))*4294967296)>>>0;function nt(t){const e=t.length,r=e<<3>>>0,s=e>>>29>>>0,n=(e+8&-64)+64,i=new Uint8Array(n);i.set(t),i[e]=128;const a=new DataView(i.buffer);a.setUint32(n-8,r,!0),a.setUint32(n-4,s,!0);let f=1732584193,p=4023233417,y=2562383102,S=271733878;const l=new Uint32Array(16);for(let m=0;m<n;m+=64){for(let u=0;u<16;u++)l[u]=a.getUint32(m+u*4,!0);let A=f,N=p,k=y,L=S;for(let u=0;u<64;u++){let B,F;u<16?(B=N&k|~N&L,F=u):u<32?(B=L&N|~L&k,F=(5*u+1)%16):u<48?(B=N^k^L,F=(3*u+5)%16):(B=k^(N|~L),F=7*u%16),B=B+A+Ve[u]+l[F]|0,A=L,L=k,k=N;const U=tt[u];N=N+(B<<U|B>>>32-U)|0}f=f+A|0,p=p+N|0,y=y+k|0,S=S+L|0}const d=O.alloc(16);return d.writeInt32LE(f,0),d.writeInt32LE(p,4),d.writeInt32LE(y,8),d.writeInt32LE(S,12),d}const We=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function ke(t,e){return t>>>e|t<<32-e}function rt(t){const e=t.length,r=Math.floor(e/536870912),s=e<<3>>>0,n=(e+8&-64)+64,i=new Uint8Array(n);i.set(t),i[e]=128;const a=new DataView(i.buffer);a.setUint32(n-8,r,!1),a.setUint32(n-4,s,!1);let f=1779033703,p=3144134277,y=1013904242,S=2773480762,l=1359893119,d=2600822924,m=528734635,A=1541459225;const N=new Uint32Array(64);for(let L=0;L<n;L+=64){for(let R=0;R<16;R++)N[R]=a.getUint32(L+R*4,!1);for(let R=16;R<64;R++){const T=ke(N[R-15],7)^ke(N[R-15],18)^N[R-15]>>>3,v=ke(N[R-2],17)^ke(N[R-2],19)^N[R-2]>>>10;N[R]=N[R-16]+T+N[R-7]+v>>>0}let u=f,B=p,F=y,U=S,b=l,w=d,g=m,x=A;for(let R=0;R<64;R++){const T=ke(b,6)^ke(b,11)^ke(b,25),v=b&w^~b&g,$=x+T+v+We[R]+N[R]>>>0,j=ke(u,2)^ke(u,13)^ke(u,22),C=u&B^u&F^B&F,z=j+C>>>0;x=g,g=w,w=b,b=U+$>>>0,U=F,F=B,B=u,u=$+z>>>0}f=f+u>>>0,p=p+B>>>0,y=y+F>>>0,S=S+U>>>0,l=l+b>>>0,d=d+w>>>0,m=m+g>>>0,A=A+x>>>0}const k=O.alloc(32);return k.writeUInt32BE(f,0),k.writeUInt32BE(p,4),k.writeUInt32BE(y,8),k.writeUInt32BE(S,12),k.writeUInt32BE(l,16),k.writeUInt32BE(d,20),k.writeUInt32BE(m,24),k.writeUInt32BE(A,28),k}function Pe(t){const e=t.length,r=Math.floor(e/536870912),s=e<<3>>>0,n=(e+8&-64)+64,i=new Uint8Array(n);i.set(t),i[e]=128;const a=new DataView(i.buffer);a.setUint32(n-8,r,!1),a.setUint32(n-4,s,!1);let f=1732584193,p=4023233417,y=2562383102,S=271733878,l=3285377520;const d=new Uint32Array(80);for(let A=0;A<n;A+=64){for(let F=0;F<16;F++)d[F]=a.getUint32(A+F*4,!1);for(let F=16;F<80;F++){const U=d[F-3]^d[F-8]^d[F-14]^d[F-16];d[F]=(U<<1|U>>>31)>>>0}let N=f,k=p,L=y,u=S,B=l;for(let F=0;F<80;F++){let U,b;F<20?(U=k&L|~k&u,b=1518500249):F<40?(U=k^L^u,b=1859775393):F<60?(U=k&L|k&u|L&u,b=2400959708):(U=k^L^u,b=3395469782);const w=((N<<5|N>>>27)>>>0)+(U>>>0)+B+b+d[F]>>>0;B=u,u=L,L=(k<<30|k>>>2)>>>0,k=N,N=w}f=f+N>>>0,p=p+k>>>0,y=y+L>>>0,S=S+u>>>0,l=l+B>>>0}const m=O.alloc(20);return m.writeUInt32BE(f,0),m.writeUInt32BE(p,4),m.writeUInt32BE(y,8),m.writeUInt32BE(S,12),m.writeUInt32BE(l,16),m}function st(t,e){const r=String(t).toLowerCase().replace("-","");if(r==="md5")return nt(e);if(r==="sha1")return Pe(e);if(r==="sha256")return rt(e);throw new Error(`Unsupported hash algorithm: ${t}`)}class pe{constructor(e){this.algorithm=e,this.chunks=[],this.digested=!1}update(e,r){if(this.digested)throw new Error("Digest already called");const s=typeof e=="string"?O.from(e,r||"utf8"):O.from(e);return this.chunks.push(s),this}digest(e){if(this.digested)throw new Error("Digest already called");this.digested=!0;const r=O.concat(this.chunks),s=st(this.algorithm,r);return!e||e==="buffer"?s:s.toString(e)}}class re{constructor(e,r){this.algorithm=e;let s=typeof r=="string"?O.from(r,"utf8"):O.from(r);const n=64;s.length>n&&(s=st(e,s)),this.ipad=O.alloc(n,54),this.opad=O.alloc(n,92);for(let i=0;i<s.length;i++)this.ipad[i]^=s[i],this.opad[i]^=s[i];this.inner=new pe(e),this.inner.update(this.ipad),this.digested=!1}update(e,r){return this.inner.update(e,r),this}digest(e){if(this.digested)throw new Error("Digest already called");this.digested=!0;const r=this.inner.digest(),s=new pe(this.algorithm);return s.update(this.opad),s.update(r),s.digest(e)}}const je={createHash(t){return new pe(t)},createHmac(t,e){return new re(t,e)},timingSafeEqual(t,e){if(!ArrayBuffer.isView(t)||!ArrayBuffer.isView(e))throw new TypeError("Input must be Buffer or TypedArray");if(t.byteLength!==e.byteLength)throw new RangeError("Input buffers must have the same byte length");const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);let n=0;for(let i=0;i<r.length;i++)n|=r[i]^s[i];return n===0},randomBytes(t,e){const r=O.alloc(t);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(r);else for(let s=0;s<t;s++)r[s]=Math.floor(Math.random()*256);return typeof e=="function"&&queueMicrotask(()=>e(null,r)),r},randomUUID(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();const t=je.randomBytes(16);t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=t.toString("hex");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20,32)}`}},fn=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})(),Ee={crc32(t,e=0){const r=typeof t=="string"?se(t):t instanceof Uint8Array?t:O.from(t);let s=e>>>0^4294967295;for(let n=0;n<r.length;n++)s=fn[(s^r[n])&255]^s>>>8;return(s^4294967295)>>>0},constants:{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,ZLIB_VERNUM:4880,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1}};(()=>{let t=null;try{t=typeof require=="function"?require("zlib"):null}catch{t=null}const e=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","unzip","gzipSync","gunzipSync","deflateSync","inflateSync","deflateRawSync","inflateRawSync","unzipSync","createGzip","createGunzip","createDeflate","createInflate","createDeflateRaw","createInflateRaw"];if(t){for(const n of e)typeof t[n]=="function"&&(Ee[n]=t[n].bind(t));return}const r=(n,i)=>(a,f,p)=>{const y=typeof f=="function"?f:typeof p=="function"?p:null,S=(async()=>{if(typeof CompressionStream>"u"||typeof DecompressionStream>"u"||typeof Response>"u")throw new Error("zlib."+i+" is not supported in this environment");const d=/^(gunzip|unzip|inflate)/.test(i)?new DecompressionStream(n):new CompressionStream(n),m=d.writable.getWriter(),A=a instanceof Uint8Array?a:O.from(a);m.write(A),m.close();const N=await new Response(d.readable).arrayBuffer();return O.from(N)})();if(y){S.then(l=>y(null,l),l=>y(l));return}return S};Ee.gzip=r("gzip","gzip"),Ee.gunzip=r("gzip","gunzip"),Ee.unzip=r("gzip","unzip"),Ee.deflate=r("deflate","deflate"),Ee.inflate=r("deflate","inflate"),Ee.deflateRaw=r("deflate-raw","deflateRaw"),Ee.inflateRaw=r("deflate-raw","inflateRaw");const s=n=>()=>{throw new Error("zlib."+n+" is not supported in a browser worker (use the async API)")};Ee.gzipSync=s("gzipSync"),Ee.gunzipSync=s("gunzipSync"),Ee.deflateSync=s("deflateSync"),Ee.inflateSync=s("inflateSync"),Ee.deflateRawSync=s("deflateRawSync"),Ee.inflateRawSync=s("inflateRawSync"),Ee.unzipSync=s("unzipSync")})();let it=()=>"/workspace";const J={sep:"/",delimiter:":",normalize(t){if(typeof t!="string")throw new TypeError("Path must be a string");if(t.length===0)return".";const e=t.startsWith("/"),r=t.endsWith("/")&&t.length>1,s=t.split("/"),n=[];for(let a=0;a<s.length;a++){const f=s[a];!f||f==="."||(f===".."?n.length>0&&n[n.length-1]!==".."?n.pop():e||n.push(".."):n.push(f))}let i=(e?"/":"")+n.join("/");return i||(i=e?"/":"."),r&&i!=="/"&&(i+="/"),i},join(...t){if(t.length===0)return".";const e=t.filter(r=>r!=="").join("/");return e?J.normalize(e):"."},resolve(...t){let e="";for(let s=t.length-1;s>=0&&!e.startsWith("/");s--){const n=t[s];n&&(e=e?`${n}/${e}`:n)}e.startsWith("/")||(e=`${typeof it=="function"?it():"/workspace"}/${e}`);const r=J.normalize(e);return r.length>1&&r.endsWith("/")?r.slice(0,-1):r},relative(t,e){const r=J.resolve(t),s=J.resolve(e);if(r===s)return"";const n=r.split("/").filter(Boolean),i=s.split("/").filter(Boolean);let a=0;for(;a<n.length&&a<i.length&&n[a]===i[a];)a++;return[...new Array(n.length-a).fill(".."),...i.slice(a)].join("/")},dirname(t){if(typeof t!="string")throw new TypeError("Path must be a string");if(t.length===0)return".";const e=t.length>1&&t.endsWith("/")?t.slice(0,-1):t,r=e.lastIndexOf("/");return r===-1?".":r===0?"/":e.slice(0,r)},basename(t,e){if(typeof t!="string")throw new TypeError("Path must be a string");const r=t.length>1&&t.endsWith("/")?t.slice(0,-1):t,s=r.lastIndexOf("/");let n=s===-1?r:r.slice(s+1);return e&&n.endsWith(e)&&(n=n.slice(0,n.length-e.length)),n},extname(t){const e=J.basename(t),r=e.lastIndexOf(".");return r<=0?"":e.slice(r)},parse(t){if(typeof t!="string")throw new TypeError("Path must be a string");const e=t.startsWith("/")?"/":"",r=t?J.dirname(t):"",s=t?J.basename(t):"",n=t?J.extname(t):"",i=n?s.slice(0,s.length-n.length):s;return{root:e,dir:r==="."&&!t.startsWith("./")?"":r,base:s,ext:n,name:i}},format(t){if(!t||typeof t!="object")throw new TypeError("pathObject must be an object");const e=t.dir||t.root||"",r=t.base||`${t.name||""}${t.ext||""}`;return e?e===t.root?`${e}${r}`:`${e}/${r}`:r},isAbsolute(t){return typeof t=="string"&&t.startsWith("/")}};J.posix=J;let xt=null;const ln={tmpdir:()=>"/tmp",EOL:`
23
+ `,platform:()=>"linux",arch:()=>"x64",homedir:()=>typeof xt=="function"?xt():"/home/codelab",hostname:()=>"code-lab-vm",cpus:()=>[{model:"Virtual Code-Lab CPU",speed:3200}]},jt=new Map;function or(t,e){if(!e||typeof e!="object")return t;const r=new Set;let s=t.replace(/(^|\n)\s*const\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=/g,(l,d,m)=>(r.add(m),`${d}let ${m} =`));const n=/(?:^|\n)\s*(?:let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\b/g;let i;for(;(i=n.exec(s))!==null;)r.add(i[1]);const a=/(?:^|\n)\s*(?:async\s+)?(?:function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)\b/g;for(;(i=a.exec(s))!==null;)r.add(i[1]);const f=Object.keys(e).filter(l=>/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(l)&&!r.has(l)),p=f.map(l=>`let ${l} = __replCtx[${JSON.stringify(l)}];`).join(`
24
+ `),S=Array.from(new Set([...f,...Array.from(r)])).map(l=>`try { if (typeof ${l} !== 'undefined') __replCtx[${JSON.stringify(l)}] = ${l}; } catch (_e) { void _e; }`).join(`
25
+ `);return`${p}
26
26
  try {
27
27
  ${s}
28
28
  } finally {
29
- ${x}
30
- }`}function Dt(t={},e={}){const r=new Set(["/","/tmp","/workspace","/etc","/home","/home/user","/home/codelab"]),s=new Map,n=new Map,i=50,a=65536,f=typeof e=="function"?e:e&&typeof e.cwdGetter=="function"?e.cwdGetter:null,m=new Map;let b=10,x=100,u=1;function d(w,g,p){if(!(!g||g.byteLength<=0||g.byteLength>a)){if(n.has(w))n.delete(w);else if(n.size>=i){const _=n.keys().next().value;_!==void 0&&n.delete(_)}n.set(w,{data:g.slice(),mtimeMs:p,deletedAtMs:Date.now()})}}function y(w){if(typeof w!="string"||!w){const _=new TypeError("path must be a non-empty string");throw _.code="ERR_INVALID_ARG_TYPE",_}const g=typeof f=="function"?f():typeof it=="function"?it():"/workspace",p=w.startsWith("/")?J.normalize(w):J.resolve(g,w);return p.length>1&&p.endsWith("/")?p.slice(0,-1):p}function A(w,g,p,_){const T=new Error(`${w}: ${_||w}, ${g} '${p}'`);return T.code=w,T.syscall=g,T.path=p,T}function M(w){const g=w.split("/").filter(Boolean);let p="";for(let _=0;_<g.length-1;_++)p+="/"+g[_],r.add(p)}function k(w,g,p,_=1,T=null){const R=new Date(g);return{size:w,ino:_,mode:T??(p?16877:33188),mtimeMs:g,ctimeMs:g,atimeMs:g,birthtimeMs:g,mtime:R,ctime:R,atime:R,birthtime:R,isFile:()=>!p,isDirectory:()=>p,isSymbolicLink:()=>!1,isBlockDevice:()=>!1,isCharacterDevice:()=>!1,isFIFO:()=>!1,isSocket:()=>!1}}for(const[w,g]of Object.entries(t)){const p=w.startsWith("/")?w.slice(1):w,_=/^\/(workspace|usr|tmp|lib|include|etc|bin|dev|home)(\/|$)/.test(w);let T=y(_?w:`/workspace/${p}`);if(!_&&T!=="/workspace"&&!T.startsWith("/workspace/")){const N=p.split("/").filter(L=>L&&L!=="."&&L!=="..").join("/");T=y(`/workspace/${N||"file"}`)}M(T);const R=typeof g=="string"?ne(g):new Uint8Array(g);s.set(T,{data:R,mtimeMs:Date.now(),ctimeMs:Date.now(),ino:x++,mode:33188,isInitialProjectFile:!/^\/(usr|tmp|lib|include|etc|bin|dev|home)(\/|$)/.test(T)})}let $="";const l={_setActiveStdin(w){$=w!=null?String(w):""},existsSync(w){try{const g=y(w);return r.has(g)||s.has(g)}catch{return!1}},mkdirSync(w,g){const p=y(w),_=typeof g=="object"&&g!==null?!!g.recursive:!!g;if(s.has(p))throw A("EEXIST","mkdir",w,"file already exists");if(r.has(p)){if(_)return;throw A("EEXIST","mkdir",w,"directory already exists")}const T=J.dirname(p);if(!r.has(T)){if(!_)throw A("ENOENT","mkdir",w,"no such file or directory");M(p+"/placeholder")}return r.add(p),p},mkdtempSync(w){if(typeof w!="string")throw new TypeError("filename prefix is required");const g=String(u++).padStart(4,"0")+Math.random().toString(36).slice(2,4),p=y(`${w}${g}`);return M(p+"/placeholder"),r.add(p),p},readdirSync(w,g){const p=y(w);if(!r.has(p))throw s.has(p)?A("ENOTDIR","scandir",w,"not a directory"):A("ENOENT","scandir",w,"no such file or directory");const _=p==="/"?"/":p+"/",T=new Map;for(const N of r)if(N!==p&&N.startsWith(_)){const O=N.slice(_.length).split("/")[0];O&&T.set(O,!0)}for(const N of s.keys())if(N.startsWith(_)){const L=N.slice(_.length);L.includes("/")||T.set(L,!1)}const R=Array.from(T.keys()).sort();return g&&typeof g=="object"&&g.withFileTypes?R.map(N=>{const L=T.get(N);return{name:N,isFile:()=>!L,isDirectory:()=>L,isSymbolicLink:()=>!1}}):R},statSync(w){const g=y(w);if(r.has(g))return k(0,Date.now(),!0,1,16877);const p=s.get(g);if(p)return k(p.data.byteLength,p.mtimeMs,!1,p.ino,p.mode!==void 0?p.mode:33188);throw A("ENOENT","stat",w,"no such file or directory")},lstatSync(w){return l.statSync(w)},fstatSync(w){const g=m.get(w);if(!g)throw A("EBADF","fstat",String(w),"bad file descriptor");return g.isDirectory?k(0,Date.now(),!0,1,16877):k(g.inode.data.byteLength,g.inode.mtimeMs,!1,g.inode.ino,g.inode.mode!==void 0?g.inode.mode:33188)},openSync(w,g="r",p=438){const _=y(w),T=String(g||"r");if(r.has(_)){if(T==="r"){const L=b++;return m.set(L,{inode:null,path:_,flags:T,pos:0,isDirectory:!0}),L}throw A("EISDIR","open",w,"illegal operation on a directory")}let R=s.get(_);if(T.includes("x")&&R)throw A("EEXIST","open",w,"file already exists");if(T.startsWith("r")&&!T.includes("c")){if(!R)throw A("ENOENT","open",w,"no such file or directory")}else if(T.startsWith("w")){const L=J.dirname(_);if(!r.has(L))throw A("ENOENT","open",w,"no such file or directory");R?(R.data=new Uint8Array(0),R.mtimeMs=Date.now()):(R={data:new Uint8Array(0),mtimeMs:Date.now(),ctimeMs:Date.now(),ino:x++,mode:32768|Number(p)&511},s.set(_,R))}else if(T.startsWith("a")||T.includes("c")){const L=J.dirname(_);if(!r.has(L))throw A("ENOENT","open",w,"no such file or directory");R||(R={data:new Uint8Array(0),mtimeMs:Date.now(),ctimeMs:Date.now(),ino:x++,mode:32768|Number(p)&511},s.set(_,R))}const N=b++;return m.set(N,{inode:R,path:_,flags:T,pos:T.startsWith("a")?R.data.byteLength:0,isDirectory:!1}),N},lseekSync(w,g,p=0){const _=m.get(w);if(!_||_.isDirectory)throw A("EBADF","lseek",String(w),"bad file descriptor");const T=Number(g)||0;let R=_.pos;if(p===0)R=T;else if(p===1)R=_.pos+T;else if(p===2)R=(_.inode?_.inode.data.byteLength:0)+T;else throw A("EINVAL","lseek",String(w),"invalid whence");if(R<0)throw A("EINVAL","lseek",String(w),"negative seek offset");return _.pos=R,_.pos},tellSync(w){const g=m.get(w);if(!g||g.isDirectory)throw A("EBADF","tell",String(w),"bad file descriptor");return g.pos},closeSync(w){if(!m.has(w))throw A("EBADF","close",String(w),"bad file descriptor");m.delete(w)},fsyncSync(w){if(!m.get(w))throw A("EBADF","fsync",String(w),"bad file descriptor")},fdatasyncSync(w){return l.fsyncSync(w)},writeSync(w,g,p,_,T){const R=m.get(w);if(!R||R.isDirectory)throw A("EBADF","write",String(w),"bad file descriptor");let N,L=null;if(typeof g=="string"){const V=typeof _=="string"?_:"utf8";N=P.from(g,V),typeof p=="number"&&(L=p)}else{const V=g instanceof Uint8Array?g:P.from(g),re=typeof p=="number"?p:0,ue=typeof _=="number"?_:V.byteLength-re;typeof T=="number"&&(L=T),N=V.subarray(re,re+ue)}const O=R.inode,B=R.flags.startsWith("a")?O.data.byteLength:L!==null?L:R.pos,Z=B+N.byteLength;if(Z>O.data.byteLength){const V=new Uint8Array(Z);V.set(O.data,0),O.data=V}return O.data.set(N,B),O.mtimeMs=Date.now(),R.pos=B+N.byteLength,N.byteLength},readSync(w,g,p=0,_=g.byteLength-p,T=null){const R=m.get(w);if(!R||R.isDirectory)throw A("EBADF","read",String(w),"bad file descriptor");const N=R.inode,L=T??R.pos;if(L>=N.data.byteLength||_<=0)return 0;const O=Math.min(_,N.data.byteLength-L);return g.set(N.data.subarray(L,L+O),p),T==null&&(R.pos=L+O),O},readFileSync(w,g){if(w===0||w==="/dev/stdin"){const N=P.from(String($||""),"utf8"),L=typeof g=="string"?g:g&&g.encoding;return L?N.toString(L):N}const p=y(w);if(r.has(p))throw A("EISDIR","read",w,"illegal operation on a directory");const _=s.get(p);if(!_)throw A("ENOENT","open",w,"no such file or directory");const T=P.alloc(_.data.byteLength);T.set(_.data);const R=typeof g=="string"?g:g&&g.encoding;return R?T.toString(R):T},writeFileSync(w,g,p){const _=y(w);if(r.has(_))throw A("EISDIR","open",w,"illegal operation on a directory");const T=J.dirname(_);if(!r.has(T))throw A("ENOENT","open",w,"no such file or directory");const R=typeof p=="string"?p:p&&p.encoding||"utf8",N=typeof g=="string"?ne(g):g instanceof Uint8Array?g.slice():new Uint8Array(P.from(String(g),R));let L=s.get(_);if(L)L.data=N,L.mtimeMs=Date.now(),p&&typeof p=="object"&&p.mode!==void 0&&(L.mode=32768|Number(p.mode)&511);else{const O=p&&typeof p=="object"&&p.mode!==void 0?32768|Number(p.mode)&511:33188;L={data:N,mtimeMs:Date.now(),ctimeMs:Date.now(),ino:x++,mode:O},s.set(_,L)}n.delete(_)},chmodSync(w,g){const p=y(w),_=typeof g=="string"?parseInt(g,8):Number(g);if(r.has(p))return;const T=s.get(p);if(!T)throw A("ENOENT","chmod",w,"no such file or directory");const R=(T.mode!==void 0?T.mode:33188)&-512;T.mode=R|_&511},appendFileSync(w,g,p){const _=y(w),T=typeof p=="string"?p:p&&p.encoding||"utf8",R=typeof g=="string"?ne(g):g instanceof Uint8Array?g:new Uint8Array(P.from(String(g),T));let N=s.get(_);if(!N){l.writeFileSync(_,R,p);return}const L=new Uint8Array(N.data.byteLength+R.byteLength);L.set(N.data,0),L.set(R,N.data.byteLength),N.data=L,N.mtimeMs=Date.now(),n.delete(_)},truncateSync(w,g=0){const p=y(w),_=s.get(p);if(!_)throw A("ENOENT","truncate",w,"no such file or directory");const T=Math.max(0,Number(g)||0);if(T<=_.data.byteLength)_.data=_.data.slice(0,T);else{const R=new Uint8Array(T);R.set(_.data,0),_.data=R}_.mtimeMs=Date.now()},renameSync(w,g){const p=y(w),_=y(g);if(r.has(p)){if(p===_)return;if(_.startsWith(p+"/"))throw A("EINVAL","rename",w,"cannot move an ancestor to child");if(s.has(_))throw A("ENOTDIR","rename",g,"not a directory");if(r.has(_)){if(Array.from(r).some(Z=>Z!==_&&Z.startsWith(_+"/"))||Array.from(s.keys()).some(Z=>Z.startsWith(_+"/")))throw A("ENOTEMPTY","rename",g,"directory not empty");r.delete(_)}M(_),r.delete(p),r.add(_);const R=p+"/",N=_+"/",L=[];for(const B of r)B.startsWith(R)&&L.push(B);for(const B of L)r.delete(B),r.add(N+B.slice(R.length));const O=[];for(const[B,Z]of s.entries())B.startsWith(R)&&O.push([B,Z]);for(const[B,Z]of O){s.delete(B);const V=N+B.slice(R.length);s.set(V,Z);for(const re of m.values())re.path===B&&(re.path=V)}return}const T=s.get(p);if(!T)throw A("ENOENT","rename",w,"no such file or directory");M(_),s.set(_,T),s.delete(p);for(const R of m.values())R.path===p&&(R.path=_);n.delete(p),n.delete(_)},unlinkSync(w){const g=y(w),p=s.get(g);if(!p)throw A("ENOENT","unlink",w,"no such file or directory");d(g,p.data,p.mtimeMs),s.delete(g)},rmSync(w,g={}){const p=y(w),_=!!(g&&g.recursive),T=!!(g&&g.force);if(s.has(p)){l.unlinkSync(p);return}if(r.has(p)){const R=p==="/"?"/":p+"/";for(const[N,L]of Array.from(s.entries()))if(N.startsWith(R)){if(!_)throw A("ENOTEMPTY","rm",w,"directory not empty");d(N,L.data,L.mtimeMs),s.delete(N)}for(const N of Array.from(r))(N===p||N.startsWith(R))&&N!=="/"&&N!=="/tmp"&&N!=="/workspace"&&r.delete(N);return}if(!T)throw A("ENOENT","rm",w,"no such file or directory")},rmdirSync(w,g={}){return l.rmSync(w,{...g,recursive:!!(g&&g.recursive)})},accessSync(w){const g=y(w);if(!r.has(g)&&!s.has(g))throw A("ENOENT","access",w,"no such file or directory")},realpathSync(w){const g=y(w);if(!r.has(g)&&!s.has(g))throw A("ENOENT","realpath",w,"no such file or directory");return g},copyFileSync(w,g,p=0){const _=y(w),T=y(g);if(r.has(_))throw A("EISDIR","copyfile",w,"illegal operation on a directory");const R=s.get(_);if(!R)throw A("ENOENT","copyfile",w,"no such file or directory");if(r.has(T))throw A("EISDIR","copyfile",g,"illegal operation on a directory");if(p&1&&s.has(T))throw A("EEXIST","copyfile",g,"file already exists");l.writeFileSync(T,R.data.slice())},createReadStream(w,g={}){typeof g=="string"&&(g={encoding:g});const p=y(w),_=typeof g.start=="number"?g.start:0,T=typeof g.end=="number"?g.end:1/0,R=g.highWaterMark||16384,N=new Tt({encoding:g.encoding||null});return N.path=p,N.bytesRead=0,queueMicrotask(()=>{if(N.destroyed)return;if(r.has(p)){N.destroy(A("EISDIR","read",w,"illegal operation on a directory"));return}const L=s.get(p);if(!L){N.destroy(A("ENOENT","open",w,"no such file or directory"));return}N.emit("open",100),N.emit("ready");const O=Math.min(L.data.byteLength,Number.isFinite(T)?T+1:L.data.byteLength),B=L.data.subarray(Math.max(0,_),Math.max(0,O));for(let Z=0;Z<B.byteLength;Z+=R){if(N.destroyed)return;const V=P.from(B.subarray(Z,Math.min(B.byteLength,Z+R)));N.bytesRead+=V.byteLength,N.push(V)}N.destroyed||N.push(null)}),N},createWriteStream(w,g={}){typeof g=="string"&&(g={encoding:g});const p=y(w),_=g&&g.flags||"w";let T=null,R=null;try{T=l.openSync(p,_)}catch(L){R=L}const N=new Pt({write(L,O,B){if(R)return B(R);try{const Z=typeof L=="string"?P.from(L,O||g&&g.encoding||"utf8"):P.from(L),V=l.writeSync(T,Z,0,Z.byteLength);N.bytesWritten+=V,B(null)}catch(Z){B(Z)}},final(L){if(T!==null){try{l.closeSync(T)}catch(O){j.debug("vfs writeStream closeSync failed",O)}T=null}L(null)}});return N.path=p,N.bytesWritten=0,queueMicrotask(()=>{R?N.destroy(R):(N.emit("open",T),N.emit("ready"))}),N},constants:{F_OK:0,R_OK:4,W_OK:2,X_OK:1,COPYFILE_EXCL:1,COPYFILE_FICLONE:2,COPYFILE_FICLONE_FORCE:4},getSnapshot(){const w=[],g=p=>{const _=p.subarray(0,256);let T=0;for(let B=0;B<_.length;B++){const Z=_[B];(Z>=32&&Z<=126||Z===9||Z===10||Z===13)&&T++}const R=_.length===0||T/_.length>=.75,N=R?Q(p.subarray(0,512)):null,L=[],O=Math.min(p.length,64);for(let B=0;B<O;B++)L.push(p[B].toString(16).padStart(2,"0"));return{isBinary:!R,preview:N,hexPreview:L.join(" ")+(p.length>64?" \u2026":"")}};for(const[p,_]of s.entries()){const{isBinary:T,preview:R,hexPreview:N}=g(_.data);w.push({path:p,size:_.data.byteLength,mtimeMs:_.mtimeMs,isDirectory:!1,deleted:!1,isInitialProjectFile:!!_.isInitialProjectFile,isBinary:T,preview:R,hexPreview:N})}for(const[p,_]of n.entries())if(!s.has(p)&&!p.endsWith(".tmp")&&_.data.byteLength>0){const{isBinary:T,preview:R,hexPreview:N}=g(_.data);w.push({path:p,size:_.data.byteLength,mtimeMs:_.mtimeMs,isDirectory:!1,deleted:!0,isInitialProjectFile:!1,isBinary:T,preview:R,hexPreview:N})}return w.sort((p,_)=>p.path.localeCompare(_.path)),w},_listOpenFds(){return Array.from(m.keys())}};l.realpathSync.native=l.realpathSync;const F=w=>(...g)=>{const p=typeof g[g.length-1]=="function"?g.pop():()=>{};queueMicrotask(()=>{try{const _=w(...g);p(null,_)}catch(_){p(_)}})};l.exists=(w,g)=>queueMicrotask(()=>typeof g=="function"?g(l.existsSync(w)):void 0),l.readFile=F(l.readFileSync),l.writeFile=F(l.writeFileSync),l.appendFile=F(l.appendFileSync),l.mkdir=F(l.mkdirSync),l.mkdtemp=F(l.mkdtempSync),l.readdir=F(l.readdirSync),l.stat=F(l.statSync),l.lstat=F(l.lstatSync),l.fstat=F(l.fstatSync),l.unlink=F(l.unlinkSync),l.rm=F(l.rmSync),l.rmdir=F(l.rmdirSync),l.rename=F(l.renameSync),l.truncate=F(l.truncateSync),l.access=F(l.accessSync),l.copyFile=F(l.copyFileSync),l.realpath=F(l.realpathSync),l.chmod=F(l.chmodSync),l.open=F(l.openSync),l.close=F(l.closeSync),l.fsync=F(l.fsyncSync),l.fdatasync=F(l.fdatasyncSync),l.read=(w,g,p,_,T,R)=>{typeof T=="function"&&(R=T,T=null),queueMicrotask(()=>{try{const N=l.readSync(w,g,p,_,T);typeof R=="function"&&R(null,N,g)}catch(N){typeof R=="function"&&R(N)}})},l.write=(w,g,p,_,T,R)=>{typeof p=="function"?(R=p,p=void 0):typeof _=="function"?(R=_,_=void 0):typeof T=="function"&&(R=T,T=void 0),queueMicrotask(()=>{try{const N=l.writeSync(w,g,p,_,T);typeof R=="function"&&R(null,N,g)}catch(N){typeof R=="function"&&R(N)}})};class U{constructor(g,p){this.fd=g,this.path=p,this._closed=!1}async read(g,p,_,T){let R=g;return g&&typeof g=="object"&&!ArrayBuffer.isView(g)?(R=g.buffer||P.alloc(g.length||16384),p=g.offset??0,_=g.length??R.byteLength-p,T=g.position??null):R||(R=P.alloc(16384),p=0,_=R.byteLength,T=null),p===void 0&&(p=0),_===void 0&&(_=R.byteLength-p),{bytesRead:l.readSync(this.fd,R,p,_,T),buffer:R}}async write(g,p,_,T){return{bytesWritten:l.writeSync(this.fd,g,p,_,T),buffer:g}}async readFile(g){return l.readFileSync(this.path,g)}async writeFile(g,p){return l.writeFileSync(this.path,g,p)}async stat(){return l.fstatSync(this.fd)}async truncate(g=0){return l.truncateSync(this.path,g)}async sync(){return l.fsyncSync(this.fd)}async datasync(){return l.fdatasyncSync(this.fd)}async close(){this._closed||(this._closed=!0,l.closeSync(this.fd))}}const C={constants:l.constants,FileHandle:U,access:async(w,g)=>l.accessSync(w,g),chmod:async(w,g)=>l.chmodSync(w,g),copyFile:async(w,g,p)=>l.copyFileSync(w,g,p),open:async(w,g="r")=>{const p=y(w),_=l.openSync(p,g);return new U(_,p)},readFile:async(w,g)=>w instanceof U?w.readFile(g):l.readFileSync(w,g),writeFile:async(w,g,p)=>w instanceof U?w.writeFile(g,p):l.writeFileSync(w,g,p),appendFile:async(w,g,p)=>l.appendFileSync(w,g,p),mkdir:async(w,g)=>l.mkdirSync(w,g),mkdtemp:async w=>l.mkdtempSync(w),readdir:async(w,g)=>l.readdirSync(w,g),stat:async w=>l.statSync(w),lstat:async w=>l.lstatSync(w),unlink:async w=>l.unlinkSync(w),rm:async(w,g)=>l.rmSync(w,g),rmdir:async(w,g)=>l.rmdirSync(w,g),rename:async(w,g)=>l.renameSync(w,g),truncate:async(w,g)=>l.truncateSync(w,g),realpath:async w=>l.realpathSync(w)};return l.promises=C,l._exportRawState=()=>{const w=new Map;for(const[g,p]of s.entries())w.set(g,p.data instanceof Uint8Array?p.data.slice():new Uint8Array(p.data||0));return{files:w,dirs:new Set(r)}},l}class fe{constructor(){this._events=new Map,this._maxListeners=fe.defaultMaxListeners}_ensureMap(){return this._events||(this._events=new Map),this._events}setMaxListeners(e){return this._maxListeners=Number(e),this}getMaxListeners(){return this._maxListeners!==void 0?this._maxListeners:fe.defaultMaxListeners}on(e,r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function');const s=this._ensureMap();return s.has(e)||s.set(e,[]),s.get(e).push({fn:r,once:!1}),e!=="newListener"&&s.has("newListener")&&this.emit("newListener",e,r),this}addListener(e,r){return this.on(e,r)}prependListener(e,r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function');const s=this._ensureMap();return s.has(e)||s.set(e,[]),s.get(e).unshift({fn:r,once:!1}),this}once(e,r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function');const s=this._ensureMap();return s.has(e)||s.set(e,[]),s.get(e).push({fn:r,once:!0}),this}prependOnceListener(e,r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function');const s=this._ensureMap();return s.has(e)||s.set(e,[]),s.get(e).unshift({fn:r,once:!0}),this}off(e,r){const s=this._ensureMap(),n=s.get(e);if(!n)return this;const i=n.findIndex(a=>a.fn===r||a.fn.listener===r);return i!==-1&&(n.splice(i,1),n.length===0&&s.delete(e),e!=="removeListener"&&s.has("removeListener")&&this.emit("removeListener",e,r)),this}removeListener(e,r){return this.off(e,r)}removeAllListeners(e){const r=this._ensureMap();return e!==void 0?r.delete(e):r.clear(),this}listeners(e){const r=this._ensureMap().get(e);return r?r.map(s=>s.fn):[]}rawListeners(e){return this.listeners(e)}listenerCount(e){const r=this._ensureMap().get(e);return r?r.length:0}eventNames(){return Array.from(this._ensureMap().keys())}emit(e,...r){const s=this._ensureMap(),n=s.get(e);if(!n||n.length===0){if(e==="error")throw r[0]instanceof Error?r[0]:new Error(String(r[0]||"Unhandled error event"));return!1}const i=n.slice(),a=n.filter(f=>!f.once);a.length>0?s.set(e,a):s.delete(e);for(let f=0;f<i.length;f++)i[f].fn.apply(this,r);return!0}}fe.defaultMaxListeners=10,fe.EventEmitter=fe,fe.listenerCount=(t,e)=>t.listenerCount(e),fe.once=(t,e)=>new Promise((r,s)=>{const n=(...a)=>{t.off("error",i),r(a)},i=a=>{t.off(e,n),s(a)};t.once(e,n),e!=="error"&&t.once("error",i)});const Et=fe,$e={escape(t){return encodeURIComponent(String(t))},unescape(t){try{return decodeURIComponent(String(t).replace(/\+/g," "))}catch{return String(t)}},parse(t,e="&",r="="){const s=Object.create(null);if(typeof t!="string"||t.length===0)return s;const i=(t.startsWith("?")?t.slice(1):t).split(e||"&");for(let a=0;a<i.length;a++){const f=i[a];if(!f)continue;const m=f.indexOf(r||"="),b=m===-1?f:f.slice(0,m),x=m===-1?"":f.slice(m+(r||"=").length),u=$e.unescape(b),d=$e.unescape(x);Object.prototype.hasOwnProperty.call(s,u)?Array.isArray(s[u])?s[u].push(d):s[u]=[s[u],d]:s[u]=d}return s},stringify(t,e="&",r="="){if(!t||typeof t!="object")return"";const s=[];for(const[n,i]of Object.entries(t)){const a=$e.escape(n);if(Array.isArray(i))for(let f=0;f<i.length;f++)s.push(`${a}${r}${$e.escape(i[f]??"")}`);else i!==void 0&&s.push(`${a}${r}${$e.escape(i??"")}`)}return s.join(e)}};$e.decode=$e.parse,$e.encode=$e.stringify;const At={URL:typeof URL<"u"?URL:null,URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:null,parse(t,e=!1){t=String(t||"");let r=null;const s=t.indexOf("#");s!==-1&&(r=t.slice(s),t=t.slice(0,s));let n=null,i=e?Object.create(null):null;const a=t.indexOf("?");if(a!==-1){n=t.slice(a);const l=n.slice(1);i=e?$e.parse(l):l,t=t.slice(0,a)}const f=/^([a-zA-Z][a-zA-Z0-9+.-]*:)?(\/\/)?([^/?#]*)?(\/.*)?$/.exec(t),m=f&&f[1]?f[1].toLowerCase():null,b=!!(f&&f[2]);let x=f&&f[2]?f[3]||"":null,u=f&&f[2]?f[4]||"/":t||"/",d=null,y=null,A=null,M=null;if(x!==null){const l=x.indexOf("@");l!==-1&&(d=x.slice(0,l),x=x.slice(l+1)),y=x;const F=x.lastIndexOf(":");F!==-1&&!x.endsWith("]")?(A=x.slice(0,F),M=x.slice(F+1)):A=x}const k=u+(n||""),$=(m||"")+(b?"//":"")+(d?d+"@":"")+(y||"")+k+(r||"");return{protocol:m,slashes:b,auth:d,host:y,port:M,hostname:A,hash:r,search:n,query:i,pathname:u,path:k,href:$}},format(t){if(typeof t=="string")return t;if(typeof URL<"u"&&t instanceof URL)return t.toString();if(!t||typeof t!="object")return"";if(t.href)return t.href;const e=t.protocol?t.protocol.endsWith(":")?t.protocol:t.protocol+":":"",r=t.slashes||e==="http:"||e==="https:"||e==="file:"?"//":"",s=t.auth?t.auth+"@":"",n=t.host||(t.hostname?t.hostname+(t.port?":"+t.port:""):""),i=t.pathname||"/";let a=t.search||"";if(!a&&t.query){const m=typeof t.query=="object"?$e.stringify(t.query):String(t.query);m&&(a="?"+m)}const f=t.hash?t.hash.startsWith("#")?t.hash:"#"+t.hash:"";return`${e}${r}${s}${n}${i}${a}${f}`},resolve(t,e){const r=String(t||""),s=String(e||"");if(!s)return r;if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(s))return s;if(typeof URL<"u")try{const i=new URL(s,new URL(r,"resolve://"));if(i.protocol==="resolve:"){const{pathname:a,search:f,hash:m}=i;return a+f+m}return i.href}catch(i){j.debug("url.resolve fallback used",i)}if(s.startsWith("/")){const i=/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]+)/.exec(r);return i?i[1]+s:s}return(r.endsWith("/")?r:r.replace(/[^/]*$/,""))+s},fileURLToPath(t){return(typeof t=="string"?t:t.href||String(t)).replace(/^file:\/\//i,"")||"/"},pathToFileURL(t){const e=J.resolve(String(t));return typeof URL<"u"?new URL(`file://${e}`):{href:`file://${e}`,pathname:e}}};class Be extends fe{pipe(e,r={}){const s=n=>{!e.destroyed&&!e.writableFinished&&e.write(n)};return this.on("data",s),r.end!==!1&&this.once("end",()=>{!e.destroyed&&!e.writableFinished&&e.end()}),this.once("error",n=>{e.emit("error",n)}),e.emit("pipe",this),e}}class Tt extends Be{constructor(e={}){super(),this.readable=!0,this.readableEnded=!1,this.destroyed=!1,this._objectMode=!!e.objectMode,this._encoding=e.encoding||null,this._readableBuffer=[],this._flowing=!1,this._reading=!1,typeof e.read=="function"&&(this._read=e.read),typeof e.destroy=="function"&&(this._destroy=e.destroy)}_read(){}setEncoding(e){return this._encoding=e,this}push(e,r){if(this.destroyed||this.readableEnded)return!1;if(e===null)return this.readableEnded=!0,this._flushReadable(),!1;let s=e;if(!this._objectMode){const n=typeof e=="string"?P.from(e,r||this._encoding||"utf8"):P.isBuffer(e)?e:P.from(e);s=this._encoding?n.toString(this._encoding):n}return this._readableBuffer.push(s),this._flushReadable(),!0}read(){if(this._readableBuffer.length===0&&!this.readableEnded&&!this._reading){this._reading=!0;try{this._read(16384)}finally{this._reading=!1}}return this._readableBuffer.length===0?null:this._readableBuffer.shift()}on(e,r){return super.on(e,r),e==="data"?(this._flowing=!0,queueMicrotask(()=>this._drainReadable())):e==="end"&&this.readableEnded&&this._readableBuffer.length===0&&queueMicrotask(()=>this.emit("end")),this}resume(){return this._flowing=!0,queueMicrotask(()=>this._drainReadable()),this}pause(){return this._flowing=!1,this}unpipe(){return this.removeAllListeners("data"),this}_drainReadable(){if(!this.destroyed){if(!this.readableEnded&&this._readableBuffer.length===0&&!this._reading){this._reading=!0;try{this._read(16384)}finally{this._reading=!1}}this._flushReadable()}}_flushReadable(){if(!this.destroyed){if(this._flowing&&this.listenerCount("data")>0)for(;this._readableBuffer.length>0&&this._flowing;){const e=this._readableBuffer.shift();this.emit("data",e)}this.readableEnded&&this._readableBuffer.length===0&&!this._endEmitted&&(this._endEmitted=!0,queueMicrotask(()=>{this.destroyed||(this.emit("end"),this.emit("close"))}))}}destroy(e){return this.destroyed?this:(this.destroyed=!0,e&&queueMicrotask(()=>this.emit("error",e)),queueMicrotask(()=>this.emit("close")),this)}async*[Symbol.asyncIterator](){const e=[];let r=!1,s=null,n=null;for(this.on("data",i=>{if(e.push(i),n){const a=n;n=null,a()}}),this.once("end",()=>{if(r=!0,n){const i=n;n=null,i()}}),this.once("error",i=>{if(s=i,r=!0,n){const a=n;n=null,a()}});!r||e.length>0;){if(s)throw s;e.length>0?yield e.shift():r||await new Promise(i=>{n=i})}if(s)throw s}static from(e,r={}){const s=new Tt({objectMode:!0,...r});return queueMicrotask(async()=>{try{for await(const n of e)s.push(n);s.push(null)}catch(n){s.destroy(n)}}),s}}class Pt extends Be{constructor(e={}){super(),this.writable=!0,this.writableFinished=!1,this.destroyed=!1,this._objectMode=!!e.objectMode,typeof e.write=="function"&&(this._write=e.write),typeof e.final=="function"&&(this._final=e.final)}_write(e,r,s){typeof s=="function"&&s()}write(e,r,s){if(typeof r=="function"&&(s=r,r="utf8"),this.destroyed||this.writableFinished)return!1;const n=!this._objectMode&&typeof e=="string"?P.from(e,r||"utf8"):e;return this._write(n,r||"utf8",i=>{i&&this.emit("error",i),typeof s=="function"&&s(i)}),!0}cork(){}uncork(){}end(e,r,s){if(typeof e=="function"?(s=e,e=void 0,r=void 0):typeof r=="function"&&(s=r,r=void 0),this.destroyed||this.writableFinished)return this;e!=null&&this.write(e,r);const n=()=>{this.writableFinished=!0,queueMicrotask(()=>{this.emit("finish"),this.emit("close"),typeof s=="function"&&s()})};return typeof this._final=="function"?this._final(i=>{i&&this.emit("error",i),n()}):n(),this}destroy(e){return this.destroyed?this:(this.destroyed=!0,e&&queueMicrotask(()=>this.emit("error",e)),queueMicrotask(()=>this.emit("close")),this)}}class un extends Tt{constructor(e={}){super(e),this.writable=!0,this.writableFinished=!1,typeof e.write=="function"&&(this._write=e.write),typeof e.final=="function"&&(this._final=e.final)}_write(e,r,s){typeof s=="function"&&s()}write(e,r,s){return Pt.prototype.write.call(this,e,r,s)}end(e,r,s){return Pt.prototype.end.call(this,e,r,s)}}class Cn extends un{constructor(e={}){super(e),typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)}_transform(e,r,s){s(null,e)}_write(e,r,s){this._transform(e,r,(n,i)=>{if(n){typeof s=="function"?s(n):this.emit("error",n);return}i!=null&&this.push(i),typeof s=="function"&&s()})}end(e,r,s){typeof e=="function"?(s=e,e=void 0,r=void 0):typeof r=="function"&&(s=r,r=void 0),e!=null&&this.write(e,r);const n=(i,a)=>{i&&this.emit("error",i),a!=null&&this.push(a),this.push(null),this.writableFinished=!0,queueMicrotask(()=>{this.emit("finish"),typeof s=="function"&&s(i)})};return typeof this._flush=="function"?this._flush(n):n(),this}}class He extends Cn{}function dn(t,e,r){const s=typeof e=="function"?e:r;let n=!1;const i=a=>{n||(n=!0,typeof s=="function"&&s(a||null))};return t.once("end",()=>i(null)),t.once("finish",()=>i(null)),t.once("error",a=>i(a)),t.once("close",()=>i(null)),()=>{n=!0}}function Un(...t){const r=typeof t[t.length-1]=="function"?t.pop():null,s=t.flat(),n=new Promise((i,a)=>{if(s.length<2){i();return}let f=!1;const m=x=>{if(!f){f=!0;for(const u of s)typeof u.destroy=="function"&&u.destroy();a(x)}};for(let x=0;x<s.length-1;x++)s[x].on("error",m),s[x].pipe(s[x+1]);const b=s[s.length-1];b.on("error",m),dn(b,x=>{f||(f=!0,x?a(x):i())})});return r?(n.then(()=>r(null),i=>r(i)),s[s.length-1]):n}const Wt={pipeline:(...t)=>new Promise((e,r)=>Un(...t,s=>s?r(s):e())),finished:(t,e)=>new Promise((r,s)=>dn(t,e,n=>n?s(n):r()))};Be.Stream=Be,Be.Readable=Tt,Be.Writable=Pt,Be.Duplex=un,Be.Transform=Cn,Be.PassThrough=He,Be.pipeline=Un,Be.finished=dn,Be.promises=Wt;const hn=Be;function Fn(){const t=new Map,e=new Map,r=new Map;function s(a,...f){const m=e.get(a);if(m)for(const b of Array.from(m))try{b(...f)}catch(x){typeof console<"u"&&typeof console.error=="function"&&console.error(`[portTable] listener for "${a}" threw:`,x)}}function n(a,f={},m=null){const b=Number(a),u=Object.assign({},m||{port:b,latencyMs:0,jitterMs:0,dropRate:0,errorRate:0,statusCode:503,partitionFromPorts:[],crashed:!1},f,{port:b});return u.latencyMs=Math.max(0,Number(u.latencyMs)||0),u.jitterMs=Math.max(0,Number(u.jitterMs)||0),u.dropRate=Math.max(0,Math.min(1,Number(u.dropRate)||0)),u.errorRate=Math.max(0,Math.min(1,Number(u.errorRate)||0)),u.statusCode=Number(u.statusCode)||503,u.partitionFromPorts=Array.isArray(u.partitionFromPorts)?Array.from(new Set(u.partitionFromPorts.map(Number).filter(d=>Number.isFinite(d)&&d>0))):[],u.crashed=!!u.crashed,u}function i(a){return a?!!(a.crashed||a.latencyMs>0||a.jitterMs>0||a.dropRate>0||a.errorRate>0||Array.isArray(a.partitionFromPorts)&&a.partitionFromPorts.length>0):!1}return{on(a,f){return typeof f!="function"?()=>{}:(e.has(a)||e.set(a,new Set),e.get(a).add(f),()=>{const m=e.get(a);m&&m.delete(f)})},off(a,f){const m=e.get(a);m&&m.delete(f)},emit:s,registerServer(a,f={}){const m=Number(a);if(t.has(m))throw new Error(`Port ${m} is already in use`);const b=Object.assign({port:m,registeredAt:Date.now()},f);return t.set(m,b),s("listen",b),b},unregisterServer(a){const f=Number(a),m=t.get(f),b=t.delete(f);return b&&s("close",f,m),b},unregister(a){return this.unregisterServer(a)},killProcess(a){const f=String(a);let m=!1;for(const[b,x]of Array.from(t.entries()))if(x.pid!==void 0&&String(x.pid)===f){if(x.server&&typeof x.server.close=="function")try{x.server.close()}catch(u){j.debug("portTable server.close failed",u)}if(typeof x.stop=="function")try{x.stop()}catch(u){j.debug("portTable entry.stop failed",u)}t.delete(b)&&s("close",b,x),m=!0}return m},unregisterByPid(a){return this.killProcess(a)},getServer(a){return t.get(Number(a))||null},listServers(){return Array.from(t.values())},setChaosRule(a,f={}){const m=Number(a),b=n(m,f,r.get(m)||null);return i(b)?r.set(m,b):r.delete(m),s("chaos",m,b),b},getChaosRule(a){return r.get(Number(a))||null},listChaosRules(){return Array.from(r.values())},clearChaosRules(a){if(a!=null&&a!==""){const f=Number(a),m=r.delete(f);return s("chaos",f,null),m}return r.clear(),s("chaos",null,null),!0},async dispatchRequest(a,f={}){const m=new URL(a),b=Number(m.port||(m.protocol==="https:"?443:80)),x=f&&f.headers||{},u=typeof x.get=="function"?x.get("x-codelab-from-port"):x["x-codelab-from-port"]||x["X-CodeLab-From-Port"],d=Number(f&&f._fromPort||u||0)||null,y=r.get(b);let A=0;if(y){let $=Number(y.latencyMs)||0;if(y.jitterMs>0&&($+=Math.round((Math.random()*2-1)*Number(y.jitterMs))),$=Math.max(0,$),$>0&&(A=$,await new Promise(l=>setTimeout(l,$))),y.crashed){const l=new Error(`connect ECONNREFUSED 127.0.0.1:${b} (chaos: node crashed)`);throw l.code="ECONNREFUSED",l.chaosEffect="CRASHED",l.fromPort=d,l}if(d&&Array.isArray(y.partitionFromPorts)&&y.partitionFromPorts.includes(d)){const l=new Error(`connect EHOSTUNREACH 127.0.0.1:${b} (chaos: network partition from :${d})`);throw l.code="EHOSTUNREACH",l.chaosEffect=`PARTITION(:${d}-x->:${b})`,l.fromPort=d,l}if(y.dropRate>0&&Math.random()<y.dropRate){const l=new Error(`socket hang up 127.0.0.1:${b} (chaos: packet dropped)`);throw l.code="ETIMEDOUT",l.chaosEffect="DROPPED",l.fromPort=d,l}if(y.errorRate>0&&Math.random()<y.errorRate){const l=Number(y.statusCode)||503,F=l===429?"Too Many Requests":l===504?"Gateway Timeout":"Service Unavailable",U=A>0?`ERROR_${l}+${A}ms`:`ERROR_${l}`,C=new Response(JSON.stringify({error:`${F} (Chaos Injected)`,chaos:!0,port:b,status:l}),{status:l,statusText:F,headers:{"content-type":"application/json","x-codelab-chaos":U}});return C._chaosEffect=U,C._fromPort=d,C}}const M=t.get(b);if(!M){const $=new Error(`connect ECONNREFUSED 127.0.0.1:${b}`);throw $.code="ECONNREFUSED",$.fromPort=d,$}let k;return M.fetch?k=await M.fetch(new Request(a,f)):M.server&&typeof M.server.dispatchRequest=="function"?k=await M.server.dispatchRequest(a,f):k=new Response("OK",{status:200}),k&&typeof k=="object"&&(k._fromPort=d,A>0&&!k._chaosEffect&&(k._chaosEffect=`DELAY_+${A}ms`)),k}}}const cr=Fn();function Bn(t,e=null){const r=new Map,s=[];let n=31e3;function i(u={}){const d={};for(const[y,A]of Object.entries(u))A!==void 0&&(d[y.toLowerCase()]=String(A));return d}class a extends Et{constructor({method:d="GET",url:y="/",statusCode:A=200,headers:M={},socket:k=null}={}){super(),this.method=d,this.url=y,this.statusCode=A,this.headers=i(M),this.socket=k||{remoteAddress:"127.0.0.1",encrypted:!1},this.destroyed=!1,this.complete=!1,this._BufferedChunks=[],this._flowing=!1,this._ended=!1}on(d,y){return super.on(d,y),d==="data"?(this._flowing=!0,this._flushBuffered()):d==="end"&&this._ended&&this._BufferedChunks.length===0&&queueMicrotask(()=>{this.complete||(this.complete=!0,this.emit("end"))}),this}resume(){return this._flowing=!0,this._flushBuffered(),this}pause(){return this._flowing=!1,this}pipe(d){return this.on("data",y=>{!d.destroyed&&!d.writableFinished&&d.write(y)}),this.on("end",()=>{!d.destroyed&&!d.writableFinished&&d.end()}),d}_pushData(d){if(this.destroyed)return;const y=P.isBuffer(d)?d:P.from(d);this._flowing&&this.listenerCount("data")>0?this.emit("data",y):this._BufferedChunks.push(y)}_pushEnd(){this.destroyed||this._ended||(this._ended=!0,this._flushBuffered())}_flushBuffered(){if(!this.destroyed){if(this._flowing&&this.listenerCount("data")>0)for(;this._BufferedChunks.length>0;){const d=this._BufferedChunks.shift();this.emit("data",d)}this._ended&&(this._flowing||this._BufferedChunks.length===0)&&(this._BufferedChunks.length=0,this.complete||(this.complete=!0,this.emit("end")))}}destroy(d){return this.destroyed?this:(this.destroyed=!0,d&&this.emit("error",d),this.emit("close"),this)}}class f extends Et{constructor(d,y){super(),this._clientReq=d,this._traceEntry=y,this.statusCode=200,this.statusMessage="OK",this.headersSent=!1,this.writableFinished=!1,this.destroyed=!1,this._headers={},this._clientRes=null}setHeader(d,y){if(this.headersSent)throw new Error("Cannot set headers after they are sent to the client");return this._headers[String(d).toLowerCase()]=String(y),this}getHeader(d){return this._headers[String(d).toLowerCase()]}removeHeader(d){delete this._headers[String(d).toLowerCase()]}writeHead(d,y,A){if(this.headersSent)return this;this.statusCode=Number(d)||200;let M=A;if(typeof y=="object"&&y!==null?M=y:typeof y=="string"&&(this.statusMessage=y),M)for(const[k,$]of Object.entries(M))$!==void 0&&(this._headers[k.toLowerCase()]=String($));return this.headersSent=!0,this._clientRes=new a({statusCode:this.statusCode,headers:{...this._headers}}),this._clientReq.destroyed||this._clientReq._onResponseHeaders(this._clientRes),this}write(d,y){if(this.destroyed||this.writableFinished)return!1;if(this.headersSent||this.writeHead(this.statusCode,this._headers),d!=null&&d!==""){const A=typeof d=="string"?P.from(d,y||"utf8"):P.from(d);this._traceEntry&&(this._traceEntry.responseBytes+=A.length);const M=this._clientRes,k=this._clientReq;queueMicrotask(()=>{!k.destroyed&&M&&M._pushData(A)})}return!0}end(d,y,A){if(typeof d=="function"?(A=d,d=void 0):typeof y=="function"&&(A=y,y=void 0),this.destroyed||this.writableFinished)return this;this.headersSent||this.writeHead(this.statusCode,this._headers),d!=null&&d!==""&&this.write(d,y),this.writableFinished=!0,this._traceEntry&&(this._traceEntry.status=this.statusCode,this._traceEntry.durationMs=Math.max(0,performance.now()-this._traceEntry._t0),this._traceEntry.responseHeaders={...this._headers});const M=this._clientRes,k=this._clientReq;return queueMicrotask(()=>{k._clearTimeout(),!k.destroyed&&M&&M._pushEnd(),k._finishInFlight(),this.emit("finish"),this.emit("close"),typeof A=="function"&&A()}),this}destroy(d){return this.destroyed?this:(this.destroyed=!0,this._clientReq._finishInFlight(),d&&this.emit("error",d),this.emit("close"),this)}}class m extends Et{constructor(d,y){if(super(),typeof d=="string"||typeof URL<"u"&&d instanceof URL){const A=new URL(String(d));d={host:A.hostname,port:Number(A.port)||80,path:A.pathname+A.search,method:"GET"}}this.host=d.host||d.hostname||"127.0.0.1",this.port=Number(d.port)||80,this.method=String(d.method||"GET").toUpperCase(),this.path=d.path||"/",this.headers=i(d.headers||{}),this.headers.host||(this.headers.host=`${this.host}:${this.port}`),this.destroyed=!1,this._bodyChunks=[],this._ended=!1,this._timeoutTimer=null,this._serverRes=null,this._inFlightDone=!1,typeof y=="function"&&this.once("response",y),t&&t.inFlightHttp.add(this)}_finishInFlight(){this._inFlightDone||(this._inFlightDone=!0,this._clearTimeout(),t&&t.inFlightHttp.delete(this))}_clearTimeout(){this._timeoutTimer!==null&&(clearTimeout(this._timeoutTimer),t&&t.activeTimers.delete(this._timeoutTimer),this._timeoutTimer=null)}setTimeout(d,y){if(this._clearTimeout(),typeof y=="function"&&this.once("timeout",y),d>0&&Number.isFinite(d)){const A=setTimeout(()=>{t&&t.activeTimers.delete(A),this._timeoutTimer=null,!this.destroyed&&!this._inFlightDone&&this.emit("timeout")},d);this._timeoutTimer=A,t&&t.activeTimers.add(A)}return this}write(d,y){if(this.destroyed||this._ended)return!1;if(d!=null&&d!==""){const A=typeof d=="string"?P.from(d,y||"utf8"):P.from(d);this._bodyChunks.push(A)}return!0}end(d,y,A){if(typeof d=="function"?(A=d,d=void 0):typeof y=="function"&&(A=y,y=void 0),this._ended||this.destroyed)return this;d!=null&&d!==""&&this.write(d,y),this._ended=!0,typeof A=="function"&&queueMicrotask(A);const M={id:s.length+1,method:this.method,host:this.host,port:this.port,url:this.path,status:"PENDING",durationMs:0,requestBytes:this._bodyChunks.reduce((k,$)=>k+$.length,0),responseBytes:0,requestHeaders:{...this.headers},responseHeaders:{},_t0:performance.now()};return s.length>=500&&s.shift(),s.push(M),this._traceEntry=M,queueMicrotask(()=>{if(this.destroyed){this._finishInFlight();return}const k=r.get(this.port),$=!!(e&&typeof e.getChaosRule=="function"&&e.getChaosRule(this.port)),l=!!(e&&typeof e.getServer=="function"&&e.getServer(this.port));if((!k||!k._listening||$)&&e&&(l||$)&&typeof e.dispatchRequest=="function"){let C=null;if(r.size>0){const p=Array.from(r.keys()).find(_=>Number(_)!==Number(this.port));p&&(C=p)}else if(t&&t.pid&&typeof e.listServers=="function"){const p=e.listServers().find(_=>_&&_.pid===t.pid&&Number(_.port)!==Number(this.port));p&&(C=p.port)}const w=this._bodyChunks.length>0?P.concat(this._bodyChunks):void 0,g=`http://${this.host}:${this.port}${this.path.startsWith("/")?"":"/"}${this.path}`;e.dispatchRequest(g,{method:this.method,headers:{...this.headers},body:w,_fromPort:C}).then(async p=>{if(this.destroyed){this._finishInFlight();return}const _={};p&&p.headers&&typeof p.headers.forEach=="function"&&p.headers.forEach((N,L)=>{_[String(L).toLowerCase()]=String(N)});let T=P.alloc(0);if(p&&typeof p.arrayBuffer=="function"){const N=await p.arrayBuffer();T=P.from(N)}M.status=p&&p.status||200,M.durationMs=Math.max(0,performance.now()-M._t0),M.responseBytes=T.length,M.responseHeaders=_,C&&(M.fromPort=C),p&&p._chaosEffect&&(M.chaosEffect=p._chaosEffect);const R=new a({statusCode:p&&p.status||200,headers:_});this._onResponseHeaders(R),T.length>0&&R._pushData(T),R._pushEnd(),this._finishInFlight()}).catch(p=>{if(this.destroyed){this._finishInFlight();return}p.errno=p.errno||-61,p.syscall=p.syscall||"connect",p.address=this.host,p.port=this.port,M.status=p.code||"ECONNREFUSED",M.durationMs=Math.max(0,performance.now()-M._t0),C&&(M.fromPort=C),p&&p.chaosEffect&&(M.chaosEffect=p.chaosEffect),this._finishInFlight(),this.emit("error",p)});return}if(!k||!k._listening){const C=new Error(`connect ECONNREFUSED ${this.host}:${this.port}`);C.code="ECONNREFUSED",C.errno=-61,C.syscall="connect",C.address=this.host,C.port=this.port,M.status="ECONNREFUSED",M.durationMs=Math.max(0,performance.now()-M._t0),this._finishInFlight(),this.emit("error",C);return}const F=new a({method:this.method,url:this.path,headers:{...this.headers},socket:{remoteAddress:"127.0.0.1",encrypted:!1}}),U=new f(this,M);this._serverRes=U;try{k.emit("request",F,U)}catch(C){this._finishInFlight(),this.emit("error",C);return}queueMicrotask(()=>{if(!this.destroyed)try{for(let C=0;C<this._bodyChunks.length;C++)F._pushData(this._bodyChunks[C]);F._pushEnd()}catch(C){this._finishInFlight(),this.emit("error",C)}})}),this}_onResponseHeaders(d){this.destroyed||this.emit("response",d)}destroy(d){return this.destroyed?this:(this.destroyed=!0,this._traceEntry&&this._traceEntry.status==="PENDING"&&(this._traceEntry.status=d&&d.code?d.code:"ABORTED",this._traceEntry.durationMs=Math.max(0,performance.now()-this._traceEntry._t0)),this._finishInFlight(),this._serverRes&&!this._serverRes.writableFinished&&(this._serverRes.destroyed=!0,this._serverRes.emit("close")),d&&queueMicrotask(()=>this.emit("error",d)),queueMicrotask(()=>this.emit("close")),this)}}class b extends Et{constructor(d){super(),typeof d=="function"&&this.on("request",d),this._port=null,this._host="127.0.0.1",this._listening=!1}listen(d=0,y="127.0.0.1",A){return typeof d=="function"?(A=d,d=0,y="127.0.0.1"):typeof y=="function"&&(A=y,y="127.0.0.1"),this._port=d===0?n++:Number(d),this._host=y||"127.0.0.1",this._listening=!0,r.set(this._port,this),e&&e.registerServer(this._port,{server:this,name:"http-server",port:this._port,pid:t&&t.pid||1}),typeof A=="function"&&this.once("listening",A),queueMicrotask(()=>{this.emit("listening")}),this}address(){return this._listening?{port:this._port,family:"IPv4",address:this._host}:null}closeAllConnections(){}close(d){return this._port!==null&&(r.delete(this._port),e&&e.unregisterServer(this._port)),this._listening=!1,typeof d=="function"&&queueMicrotask(()=>d()),queueMicrotask(()=>this.emit("close")),this}async dispatchRequest(d,y={}){return new Promise((A,M)=>{try{const k=new URL(d);let $=y.headers||{},l={};if($ instanceof Headers||$&&typeof $.entries=="function")for(const[_,T]of $.entries())l[_.toLowerCase()]=String(T);else if(typeof $=="object"&&$!==null)for(const[_,T]of Object.entries($))T!==void 0&&(l[_.toLowerCase()]=String(T));l.host||(l.host=`${k.hostname||"127.0.0.1"}:${k.port||this._port}`);const F=new a({method:(y.method||"GET").toUpperCase(),url:k.pathname+k.search,headers:l,socket:{remoteAddress:"127.0.0.1",encrypted:!1}}),U=new Et;U.destroyed=!1,U._clearTimeout=()=>{},U._finishInFlight=()=>{},U._onResponseHeaders=()=>{};const C=new f(U,null),w=[],g=C.write.bind(C),p=C.end.bind(C);C.write=function(_,T){if(_!=null&&_!==""){const R=typeof _=="string"?P.from(_,T||"utf8"):P.from(_);w.push(R)}return g(_,T)},C.end=function(_,T,R){if(typeof _=="function"?(R=_,_=void 0):typeof T=="function"&&(R=T,T=void 0),_!=null&&_!==""){const L=typeof _=="string"?P.from(_,T||"utf8"):P.from(_);w.push(L)}const N=p(_,T,R);return queueMicrotask(()=>{const L=P.concat(w),O=new Headers;for(const[Z,V]of Object.entries(C._headers))O.set(Z,V);const B=new Response(L,{status:C.statusCode||200,statusText:C.statusMessage||"OK",headers:O});A(B)}),N},this.emit("request",F,C),queueMicrotask(async()=>{try{if(y.body){let _=y.body;typeof _.text=="function"&&(_=await _.text());const T=typeof _=="string"?P.from(_,"utf8"):P.from(_);F._pushData(T)}F._pushEnd()}catch(_){M(_)}})}catch(k){M(k)}})}}class x{constructor(d={}){this.options=d,this.keepAlive=!!d.keepAlive,this.maxSockets=d.maxSockets||1/0}destroy(){}}return{Agent:x,Server:b,IncomingMessage:a,ServerResponse:f,ClientRequest:m,createServer(u){return new b(u)},request(u,d){return new m(u,d)},get(u,d){const y=new m(u,d);return y.end(),y},getTrace(){return s.map(({_t0:u,...d})=>d)},activeServers:r,hasActiveServers(){return r.size>0},closeAllServers(){for(const u of Array.from(r.values()))try{u.close()}catch(d){j.debug("vhttp closeAllServers close failed",d)}r.clear()}}}class Re extends Error{constructor({message:e,actual:r,expected:s,operator:n}){const i=e||`Assertion failed: ${Ot(r)} ${n||"!="} ${Ot(s)}`;super(i),this.name="AssertionError",this.code="ERR_ASSERTION",this.actual=r,this.expected=s,this.operator=n}}function Ot(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="bigint")return`${t}n`;if(t instanceof RegExp||t instanceof Error)return String(t);if(P.isBuffer(t))return`<Buffer ${t.toString("hex").slice(0,32)}>`;try{return JSON.stringify(t)}catch{return String(t)}}function Ge(t,e,r=!0,s=new Map){if((r?Object.is(t,e):t==e)||r&&typeof t=="number"&&typeof e=="number"&&Number.isNaN(t)&&Number.isNaN(e))return!0;if(t===null||e===null||typeof t!="object"||typeof e!="object")return r?Object.is(t,e):t==e;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t instanceof RegExp&&e instanceof RegExp)return t.source===e.source&&t.flags===e.flags;if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(e)){if(t.byteLength!==e.byteLength)return!1;const a=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),f=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);for(let m=0;m<a.length;m++)if(a[m]!==f[m])return!1;return!0}if(t instanceof Set&&e instanceof Set){if(t.size!==e.size)return!1;for(const a of t)if(!e.has(a))return!1;return!0}if(t instanceof Map&&e instanceof Map){if(t.size!==e.size)return!1;for(const[a,f]of t.entries())if(!e.has(a)||!Ge(f,e.get(a),r,s))return!1;return!0}if(Array.isArray(t)!==Array.isArray(e))return!1;if(s.get(t)===e)return!0;s.set(t,e);const n=Object.keys(t),i=Object.keys(e);if(n.length!==i.length)return!1;for(let a=0;a<n.length;a++){const f=n[a];if(!Object.prototype.hasOwnProperty.call(e,f)||!Ge(t[f],e[f],r,s))return!1}return!0}function jn(t,e){if(!e)return!0;if(e instanceof RegExp)return e.test(t&&t.message?t.message:String(t))||e.test(String(t));if(typeof e=="function"){if(e.prototype&&t instanceof e)return!0;if(e===Error||e.prototype&&e.prototype instanceof Error)return!!(t&&(t instanceof e||t.name===e.name));try{return!!e(t)}catch{return!1}}if(typeof e=="object"){for(const[r,s]of Object.entries(e))if(s instanceof RegExp){if(!s.test(String(t[r])))return!1}else if(t[r]!==s)return!1;return!0}return!0}function pe(t,e){if(!t)throw new Re({message:e,actual:t,expected:!0,operator:"=="})}pe.AssertionError=Re,pe.ok=pe,pe.fail=function(e){throw new Re({message:e||"Failed",actual:!1,expected:!0,operator:"fail"})},pe.equal=function(e,r,s){if(e!=r&&!(Number.isNaN(e)&&Number.isNaN(r)))throw new Re({message:s,actual:e,expected:r,operator:"=="})},pe.notEqual=function(e,r,s){if(e==r)throw new Re({message:s,actual:e,expected:r,operator:"!="})},pe.strictEqual=function(e,r,s){if(!Object.is(e,r))throw new Re({message:s,actual:e,expected:r,operator:"==="})},pe.notStrictEqual=function(e,r,s){if(Object.is(e,r))throw new Re({message:s,actual:e,expected:r,operator:"!=="})},pe.deepEqual=function(e,r,s){if(!Ge(e,r,!1))throw new Re({message:s,actual:e,expected:r,operator:"deepEqual"})},pe.notDeepEqual=function(e,r,s){if(Ge(e,r,!1))throw new Re({message:s,actual:e,expected:r,operator:"notDeepEqual"})},pe.deepStrictEqual=function(e,r,s){if(!Ge(e,r,!0))throw new Re({message:s,actual:e,expected:r,operator:"deepStrictEqual"})},pe.notDeepStrictEqual=function(e,r,s){if(Ge(e,r,!0))throw new Re({message:s,actual:e,expected:r,operator:"notDeepStrictEqual"})},pe.match=function(e,r,s){if(!(r instanceof RegExp)||!r.test(String(e)))throw new Re({message:s,actual:e,expected:r,operator:"match"})},pe.doesNotMatch=function(e,r,s){if(r instanceof RegExp&&r.test(String(e)))throw new Re({message:s,actual:e,expected:r,operator:"doesNotMatch"})},pe.throws=function(e,r,s){let n=r,i=s;typeof r=="string"&&s===void 0&&(n=null,i=r);let a=!1,f=null;try{e()}catch(m){a=!0,f=m}if(!a)throw new Re({message:i||"Missing expected exception",actual:void 0,expected:n,operator:"throws"});if(n&&!jn(f,n))throw new Re({message:i||`Unexpected exception: ${f&&f.message?f.message:f}`,actual:f,expected:n,operator:"throws"})},pe.doesNotThrow=function(e,r){try{e()}catch(s){throw new Re({message:r||`Got unwanted exception: ${s.message}`,actual:s,expected:void 0,operator:"doesNotThrow"})}},pe.rejects=async function(e,r,s){let n=r,i=s;typeof r=="string"&&s===void 0&&(n=null,i=r);let a=!1,f=null;try{await(typeof e=="function"?e():e)}catch(m){a=!0,f=m}if(!a)throw new Re({message:i||"Missing expected rejection",actual:void 0,expected:n,operator:"rejects"});if(n&&!jn(f,n))throw new Re({message:i||`Unexpected rejection: ${f&&f.message?f.message:f}`,actual:f,expected:n,operator:"rejects"})},pe.strict=pe;const Rt=Symbol.for("nodejs.util.promisify.custom");function Je(t,e={}){const r=e&&typeof e.depth=="number"?e.depth:4,s=new WeakSet;function n(i,a){if(i===null)return"null";if(i===void 0)return"undefined";if(typeof i=="string")return JSON.stringify(i);if(typeof i=="number"||typeof i=="boolean")return String(i);if(typeof i=="bigint")return`${i}n`;if(typeof i=="symbol")return i.toString();if(typeof i=="function")return`[Function: ${i.name||"anonymous"}]`;if(i instanceof RegExp)return i.toString();if(i instanceof Date)return Number.isNaN(i.getTime())?"Invalid Date":i.toISOString();if(i instanceof Error)return i.stack||`${i.name}: ${i.message}`;if(P.isBuffer(i)){const m=i.toString("hex").match(/.{1,2}/g)||[];return`<Buffer ${m.slice(0,32).join(" ")}${m.length>32?" ... ":""}>`}if(i instanceof Uint8Array)return`Uint8Array(${i.byteLength}) [ ${Array.from(i.slice(0,16)).join(", ")}${i.byteLength>16?", ...":""} ]`;if(typeof i=="object"){if(s.has(i))return"[Circular]";if(a>r)return Array.isArray(i)?"[Array]":"[Object]";s.add(i);try{if(i instanceof Map){const x=[];for(const[u,d]of i.entries())x.push(`${n(u,a+1)} => ${n(d,a+1)}`);return`Map(${i.size}) { ${x.join(", ")} }`}if(i instanceof Set){const x=[];for(const u of i.values())x.push(n(u,a+1));return`Set(${i.size}) { ${x.join(", ")} }`}if(Array.isArray(i))return i.length===0?"[]":`[ ${i.map(x=>n(x,a+1)).join(", ")} ]`;const f=Object.keys(i);if(f.length===0)return"{}";const m=f.map(x=>`${/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(x)?x:JSON.stringify(x)}: ${n(i[x],a+1)}`);return`${i.constructor&&i.constructor!==Object?`${i.constructor.name} `:""}{ ${m.join(", ")} }`}finally{s.delete(i)}}return String(i)}return n(t,0)}function ar(...t){if(t.length===0)return"";const e=t[0];if(typeof e!="string")return t.map(n=>typeof n=="object"&&n!==null?Je(n):String(n)).join(" ");let r=1,s="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+1<e.length){const i=e[n+1];if(i==="%"){s+="%",n++;continue}if(r<t.length){const a=t[r];if(i==="s"){s+=String(a),r++,n++;continue}if(i==="d"){s+=Number(a),r++,n++;continue}if(i==="i"){s+=parseInt(a,10),r++,n++;continue}if(i==="f"){s+=parseFloat(a),r++,n++;continue}if(i==="j"){try{s+=JSON.stringify(a)}catch{s+="[Circular]"}r++,n++;continue}if(i==="o"||i==="O"){s+=Je(a),r++,n++;continue}}}s+=e[n]}for(;r<t.length;){const n=t[r++];s+=" "+(typeof n=="object"&&n!==null?Je(n):String(n))}return s}function vt(t){if(typeof t!="function")throw new TypeError('The "original" argument must be of type Function');if(t[Rt]){const r=t[Rt];if(typeof r!="function")throw new TypeError('The "util.promisify.custom" property must be of type Function');return Object.defineProperty(r,Rt,{value:r,enumerable:!1,writable:!1,configurable:!0})}function e(...r){return new Promise((s,n)=>{try{t.call(this,...r,(i,...a)=>{if(i)return n(i);s(a.length<=1?a[0]:a)})}catch(i){n(i)}})}return Object.setPrototypeOf(e,Object.getPrototypeOf(t)),Object.defineProperty(e,Rt,{value:e,enumerable:!1,writable:!1,configurable:!0}),e}vt.custom=Rt;function fr(t){if(typeof t!="function")throw new TypeError('The "original" argument must be of type Function');return function(...r){const s=r.pop();if(typeof s!="function")throw new TypeError("The last argument must be of type Function");Promise.resolve().then(()=>t.apply(this,r)).then(n=>queueMicrotask(()=>s(null,n)),n=>queueMicrotask(()=>{const i=n||new Error("Promise was rejected with a falsy value");s(i)}))}}function lr(t,e){if(t==null)throw new TypeError('The constructor to "inherits" must not be null or undefined');if(e==null)throw new TypeError('The super constructor to "inherits" must not be null or undefined');t.super_=e,Object.setPrototypeOf(t.prototype,e.prototype)}const kt={format:ar,inspect:Je,promisify:vt,callbackify:fr,inherits:lr,isDeepStrictEqual:(t,e)=>Ge(t,e,!0),deprecate:t=>t,TextEncoder:typeof TextEncoder<"u"?TextEncoder:void 0,TextDecoder:typeof TextDecoder<"u"?TextDecoder:void 0,types:{isPromise:t=>!!(t&&typeof t=="object"&&typeof t.then=="function"),isRegExp:t=>t instanceof RegExp,isDate:t=>t instanceof Date,isUint8Array:t=>t instanceof Uint8Array,isArrayBuffer:t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer,isMap:t=>t instanceof Map,isSet:t=>t instanceof Set,isNativeError:t=>t instanceof Error,isBoxedPrimitive:t=>t instanceof Number||t instanceof String||t instanceof Boolean}};class ur{constructor(e="utf8"){const r=String(e||"utf8").toLowerCase().replace(/[-_]/g,"");this.encoding=r==="utf8"||r==="utf"?"utf8":r==="ucs2"||r==="utf16le"?"utf16le":r==="latin1"||r==="binary"?"latin1":r,this._pending=P.alloc(0)}write(e){const r=P.isBuffer(e)?e:P.from(e);if(r.length===0)return"";if(this.encoding!=="utf8"&&this.encoding!=="utf16le"&&this.encoding!=="base64")return r.toString(this.encoding);const s=this._pending.length>0?P.concat([this._pending,r]):r;if(this.encoding==="utf16le"){const f=s.length%2,m=s.length-f;return this._pending=f>0?P.from(s.subarray(m)):P.alloc(0),m>0?s.subarray(0,m).toString("utf16le"):""}if(this.encoding==="base64"){const f=s.length%3,m=s.length-f;return this._pending=f>0?P.from(s.subarray(m)):P.alloc(0),m>0?s.subarray(0,m).toString("base64"):""}let n=0;const i=s.length;for(let f=1;f<=3&&f<=i;f++){const m=s[i-f];if((m&192)===128)continue;let b=1;(m&224)===192?b=2:(m&240)===224?b=3:(m&248)===240&&(b=4),f<b&&(n=f);break}const a=i-n;return this._pending=n>0?P.from(s.subarray(a)):P.alloc(0),a>0?s.subarray(0,a).toString("utf8"):""}end(e){let r="";return e!==void 0&&(r+=this.write(e)),this._pending.length>0&&(r+=this._pending.toString(this.encoding),this._pending=P.alloc(0)),r}}const pn={StringDecoder:ur},ot={async lookup(t,e){const r=e&&typeof e=="object"&&e.all,s=(typeof e=="number"?e:e?.family)||4,n=s===6?"::1":"127.0.0.1";return r?[{address:n,family:s}]:{address:n,family:s}},async resolve(t,e="A"){return e==="AAAA"?["::1"]:e==="TXT"?[["v=spf1 loopback"]]:e==="MX"?[{exchange:`mail.${t}`,priority:10}]:e==="CNAME"?[`${t}.local`]:t==="example.com"?["93.184.216.34"]:["127.0.0.1"]},async resolve4(t){return t==="example.com"?["93.184.216.34"]:["127.0.0.1"]},async resolve6(){return["::1"]},async reverse(){return["localhost"]}};function Dn(t,e,r){const s=typeof e=="function"?e:r,n=typeof e=="function"?{}:e;ot.lookup(t,n).then(i=>{typeof s=="function"&&(Array.isArray(i)?s(null,i):s(null,i.address,i.family))},i=>{typeof s=="function"&&s(i)})}Dn[vt.custom]=ot.lookup;const It={ADDRCONFIG:1024,V4MAPPED:2048,lookup:Dn,resolve(t,e,r){const s=typeof e=="function"?e:r,n=typeof e=="string"?e:"A";ot.resolve(t,n).then(i=>s&&s(null,i),i=>s&&s(i))},resolve4(t,e,r){const s=typeof e=="function"?e:r;ot.resolve4(t).then(n=>s&&s(null,n),n=>s&&s(n))},resolve6(t,e,r){const s=typeof e=="function"?e:r;ot.resolve6(t).then(n=>s&&s(null,n),n=>s&&s(n))},reverse(t,e){ot.reverse(t).then(r=>e&&e(null,r),r=>e&&e(r))},promises:ot};function Pn(t,e=[]){const r=new Map;let s=4e4;class n extends un{constructor(y={}){super(y),this.connecting=!1,this.destroyed=!1,this.remoteAddress="127.0.0.1",this.remoteFamily="IPv4",this.remotePort=null,this.localAddress="127.0.0.1",this.localPort=null,this.bytesRead=0,this.bytesWritten=0,this._peer=null,this._encoding=null,this._timeoutMs=0,this._timeoutId=null,this._endEmitted=!1}setEncoding(y){return this._encoding=y,this}setNoDelay(){return this}setKeepAlive(){return this}ref(){return this}unref(){return this}setTimeout(y,A){return this._timeoutId&&(clearTimeout(this._timeoutId),this._timeoutId=null),this._timeoutMs=y,typeof A=="function"&&this.once("timeout",A),y>0&&!this.destroyed&&(this._timeoutId=setTimeout(()=>{this.emit("timeout")},y)),this}address(){return{port:this.localPort||0,family:"IPv4",address:this.localAddress}}connect(...y){let A,M="127.0.0.1",k=null;return typeof y[0]=="object"&&y[0]!==null?(A=Number(y[0].port),y[0].host&&(M=y[0].host),typeof y[1]=="function"&&(k=y[1])):(A=Number(y[0]),typeof y[1]=="string"?(M=y[1],typeof y[2]=="function"&&(k=y[2])):typeof y[1]=="function"&&(k=y[1])),k&&this.once("connect",k),this.connecting=!0,this.remotePort=A,this.remoteAddress=M,this.localPort=s++,queueMicrotask(()=>{if(this.destroyed)return;const $=r.get(A);if(!$||!$.listening){this.connecting=!1;const F=new Error(`connect ECONNREFUSED ${M}:${A}`);F.code="ECONNREFUSED",F.errno=-111,F.syscall="connect",F.address=M,F.port=A,this.emit("error",F);return}const l=new n;l.localPort=A,l.remotePort=this.localPort,l._peer=this,this._peer=l,this.connecting=!1,e.length>=500&&e.shift(),e.push({protocol:"TCP",event:"connect",localPort:this.localPort,remotePort:A,host:M,timestamp:Date.now()}),$._connections.add(l),l.once("close",()=>$._connections.delete(l)),$.emit("connection",l),this.emit("connect"),this.emit("ready")}),this}write(y,A,M){const k=typeof A=="function"?A:M,$=typeof A=="string"?A:"utf8";if(this.destroyed){const U=new Error("This socket has been ended by the other party");return U.code="EPIPE",typeof k=="function"&&queueMicrotask(()=>k(U)),!1}const l=P.isBuffer(y)?y:P.from(String(y??""),$);this.bytesWritten+=l.length;const F=this._peer;return F&&!F.destroyed?queueMicrotask(()=>{if(F.destroyed)return;F.bytesRead+=l.length;const U=F._encoding?l.toString(F._encoding):l;F.emit("data",U),typeof k=="function"&&k(null)}):typeof k=="function"&&queueMicrotask(()=>k(null)),!0}end(y,A,M){const k=typeof y=="function"?y:typeof A=="function"?A:M,$=typeof A=="string"?A:"utf8";return y!=null&&typeof y!="function"&&this.write(y,$),queueMicrotask(()=>{if(this.destroyed)return;const l=this._peer;l&&!l.destroyed&&!l._endEmitted&&(l._endEmitted=!0,l.emit("end")),this.emit("finish"),typeof k=="function"&&k(),this.destroy()}),this}destroy(y){if(this.destroyed)return this;this.destroyed=!0,this._timeoutId&&(clearTimeout(this._timeoutId),this._timeoutId=null);const A=this._peer;return this._peer=null,queueMicrotask(()=>{y&&this.emit("error",y),this.emit("close",!!y),A&&!A.destroyed&&(A._endEmitted||(A._endEmitted=!0,A.emit("end")),A.destroy())}),this}}class i extends fe{constructor(y,A){super();const M=typeof y=="function"?y:A;typeof M=="function"&&this.on("connection",M),this.listening=!1,this._port=null,this._host="127.0.0.1",this._connections=new Set}listen(...y){let A=0,M="127.0.0.1",k=null;for(const $ of y)typeof $=="number"?A=$:typeof $=="string"?M=$:typeof $=="function"?k=$:typeof $=="object"&&$!==null&&(typeof $.port=="number"&&(A=$.port),typeof $.host=="string"&&(M=$.host));if(k&&this.once("listening",k),!A||A===0)for(A=s++;r.has(A);)A=s++;return this._port=A,this._host=M,this.listening=!0,r.set(A,this),queueMicrotask(()=>{this.listening&&this.emit("listening")}),this}address(){return this.listening?{port:this._port,family:"IPv4",address:this._host}:null}getConnections(y){return typeof y=="function"&&queueMicrotask(()=>y(null,this._connections.size)),this}close(y){typeof y=="function"&&this.once("close",y),this._port!==null&&r.delete(this._port),this.listening=!1;for(const A of this._connections)A.destroy();return this._connections.clear(),queueMicrotask(()=>this.emit("close")),this}ref(){return this}unref(){return this}}function a(d){const A=String(d||"").split(".");return A.length!==4?!1:A.every(M=>/^(?:0|[1-9]\d*)$/.test(M)&&Number(M)>=0&&Number(M)<=255)}function f(d){const y=String(d||"");return y.includes(":")?/^[0-9a-fA-F:]+$/.test(y):!1}function m(d){return a(d)?4:f(d)?6:0}function b(d,y){return new i(d,y)}function x(...d){return new n().connect(...d)}function u(){for(const d of r.values())try{d.close()}catch(y){j.debug("vnet closeAllServers close failed",y)}r.clear()}return{Socket:n,Server:i,Stream:n,createServer:b,connect:x,createConnection:x,isIP:m,isIPv4:a,isIPv6:f,closeAllServers:u,getTrace:()=>[...e]}}function dr(t,e){return/\.(jsx|tsx)$/i.test(e||"")?!0:!t||t.indexOf("<")===-1?!1:!!(/@jsx\b/.test(t)||t.indexOf("<>")!==-1||/<\/[A-Za-z]/.test(t)||/<[A-Za-z_$][A-Za-z0-9_$:.\-]*\b[^>\n]*\/>/.test(t))}function mn(t){let e="React.createElement",r=null;const s=/@jsx\s+([A-Za-z_$][\w$.]*)/.exec(t);s&&(e=s[1]);const n=/@jsxFrag\s+([A-Za-z_$][\w$.]*)/.exec(t);return n&&(r=n[1]),r||(r=e==="React.createElement"?"React.Fragment":"Fragment"),{pragma:e,frag:r}}const hr=/\s/,qt=/[A-Za-z_$]/,pr=/[A-Za-z0-9_$:.\-]/;function qe(t){const e=new Error(t);throw e.jsxParse=!0,e}function yn(t,e){const r=t[e],s=t[e+1],n=t.length;if(r==="/"&&s==="/"){const i=t.indexOf(`
29
+ ${S}
30
+ }`}function Dt(t={},e={}){const r=new Set(["/","/tmp","/workspace","/etc","/home","/home/user","/home/codelab"]),s=new Map,n=new Map,i=50,a=65536,f=typeof e=="function"?e:e&&typeof e.cwdGetter=="function"?e.cwdGetter:null,p=new Map;let y=10,S=100,l=1;function d(b,w,g){if(!(!w||w.byteLength<=0||w.byteLength>a)){if(n.has(b))n.delete(b);else if(n.size>=i){const x=n.keys().next().value;x!==void 0&&n.delete(x)}n.set(b,{data:w.slice(),mtimeMs:g,deletedAtMs:Date.now()})}}function m(b){if(typeof b!="string"||!b){const x=new TypeError("path must be a non-empty string");throw x.code="ERR_INVALID_ARG_TYPE",x}const w=typeof f=="function"?f():typeof it=="function"?it():"/workspace",g=b.startsWith("/")?J.normalize(b):J.resolve(w,b);return g.length>1&&g.endsWith("/")?g.slice(0,-1):g}function A(b,w,g,x){const R=new Error(`${b}: ${x||b}, ${w} '${g}'`);return R.code=b,R.syscall=w,R.path=g,R}function N(b){const w=b.split("/").filter(Boolean);let g="";for(let x=0;x<w.length-1;x++)g+="/"+w[x],r.add(g)}function k(b,w,g,x=1,R=null){const T=new Date(w);return{size:b,ino:x,mode:R??(g?16877:33188),mtimeMs:w,ctimeMs:w,atimeMs:w,birthtimeMs:w,mtime:T,ctime:T,atime:T,birthtime:T,isFile:()=>!g,isDirectory:()=>g,isSymbolicLink:()=>!1,isBlockDevice:()=>!1,isCharacterDevice:()=>!1,isFIFO:()=>!1,isSocket:()=>!1}}for(const[b,w]of Object.entries(t)){const g=b.startsWith("/")?b.slice(1):b,x=/^\/(workspace|usr|tmp|lib|include|etc|bin|dev|home)(\/|$)/.test(b);let R=m(x?b:`/workspace/${g}`);if(!x&&R!=="/workspace"&&!R.startsWith("/workspace/")){const v=g.split("/").filter($=>$&&$!=="."&&$!=="..").join("/");R=m(`/workspace/${v||"file"}`)}N(R);const T=typeof w=="string"?se(w):new Uint8Array(w);s.set(R,{data:T,mtimeMs:Date.now(),ctimeMs:Date.now(),ino:S++,mode:33188,isInitialProjectFile:!/^\/(usr|tmp|lib|include|etc|bin|dev|home)(\/|$)/.test(R)})}let L="";const u={_setActiveStdin(b){L=b!=null?String(b):""},existsSync(b){try{const w=m(b);return r.has(w)||s.has(w)}catch{return!1}},mkdirSync(b,w){const g=m(b),x=typeof w=="object"&&w!==null?!!w.recursive:!!w;if(s.has(g))throw A("EEXIST","mkdir",b,"file already exists");if(r.has(g)){if(x)return;throw A("EEXIST","mkdir",b,"directory already exists")}const R=J.dirname(g);if(!r.has(R)){if(!x)throw A("ENOENT","mkdir",b,"no such file or directory");N(g+"/placeholder")}return r.add(g),g},mkdtempSync(b){if(typeof b!="string")throw new TypeError("filename prefix is required");const w=String(l++).padStart(4,"0")+Math.random().toString(36).slice(2,4),g=m(`${b}${w}`);return N(g+"/placeholder"),r.add(g),g},readdirSync(b,w){const g=m(b);if(!r.has(g))throw s.has(g)?A("ENOTDIR","scandir",b,"not a directory"):A("ENOENT","scandir",b,"no such file or directory");const x=g==="/"?"/":g+"/",R=new Map;for(const v of r)if(v!==g&&v.startsWith(x)){const j=v.slice(x.length).split("/")[0];j&&R.set(j,!0)}for(const v of s.keys())if(v.startsWith(x)){const $=v.slice(x.length);$.includes("/")||R.set($,!1)}const T=Array.from(R.keys()).sort();return w&&typeof w=="object"&&w.withFileTypes?T.map(v=>{const $=R.get(v);return{name:v,isFile:()=>!$,isDirectory:()=>$,isSymbolicLink:()=>!1}}):T},statSync(b){const w=m(b);if(r.has(w))return k(0,Date.now(),!0,1,16877);const g=s.get(w);if(g)return k(g.data.byteLength,g.mtimeMs,!1,g.ino,g.mode!==void 0?g.mode:33188);throw A("ENOENT","stat",b,"no such file or directory")},lstatSync(b){return u.statSync(b)},fstatSync(b){const w=p.get(b);if(!w)throw A("EBADF","fstat",String(b),"bad file descriptor");return w.isDirectory?k(0,Date.now(),!0,1,16877):k(w.inode.data.byteLength,w.inode.mtimeMs,!1,w.inode.ino,w.inode.mode!==void 0?w.inode.mode:33188)},openSync(b,w="r",g=438){const x=m(b),R=String(w||"r");if(r.has(x)){if(R==="r"){const $=y++;return p.set($,{inode:null,path:x,flags:R,pos:0,isDirectory:!0}),$}throw A("EISDIR","open",b,"illegal operation on a directory")}let T=s.get(x);if(R.includes("x")&&T)throw A("EEXIST","open",b,"file already exists");if(R.startsWith("r")&&!R.includes("c")){if(!T)throw A("ENOENT","open",b,"no such file or directory")}else if(R.startsWith("w")){const $=J.dirname(x);if(!r.has($))throw A("ENOENT","open",b,"no such file or directory");T?(T.data=new Uint8Array(0),T.mtimeMs=Date.now()):(T={data:new Uint8Array(0),mtimeMs:Date.now(),ctimeMs:Date.now(),ino:S++,mode:32768|Number(g)&511},s.set(x,T))}else if(R.startsWith("a")||R.includes("c")){const $=J.dirname(x);if(!r.has($))throw A("ENOENT","open",b,"no such file or directory");T||(T={data:new Uint8Array(0),mtimeMs:Date.now(),ctimeMs:Date.now(),ino:S++,mode:32768|Number(g)&511},s.set(x,T))}const v=y++;return p.set(v,{inode:T,path:x,flags:R,pos:R.startsWith("a")?T.data.byteLength:0,isDirectory:!1}),v},lseekSync(b,w,g=0){const x=p.get(b);if(!x||x.isDirectory)throw A("EBADF","lseek",String(b),"bad file descriptor");const R=Number(w)||0;let T=x.pos;if(g===0)T=R;else if(g===1)T=x.pos+R;else if(g===2)T=(x.inode?x.inode.data.byteLength:0)+R;else throw A("EINVAL","lseek",String(b),"invalid whence");if(T<0)throw A("EINVAL","lseek",String(b),"negative seek offset");return x.pos=T,x.pos},tellSync(b){const w=p.get(b);if(!w||w.isDirectory)throw A("EBADF","tell",String(b),"bad file descriptor");return w.pos},closeSync(b){if(!p.has(b))throw A("EBADF","close",String(b),"bad file descriptor");p.delete(b)},fsyncSync(b){if(!p.get(b))throw A("EBADF","fsync",String(b),"bad file descriptor")},fdatasyncSync(b){return u.fsyncSync(b)},writeSync(b,w,g,x,R){const T=p.get(b);if(!T||T.isDirectory)throw A("EBADF","write",String(b),"bad file descriptor");let v,$=null;if(typeof w=="string"){const Z=typeof x=="string"?x:"utf8";v=O.from(w,Z),typeof g=="number"&&($=g)}else{const Z=w instanceof Uint8Array?w:O.from(w),Q=typeof g=="number"?g:0,le=typeof x=="number"?x:Z.byteLength-Q;typeof R=="number"&&($=R),v=Z.subarray(Q,Q+le)}const j=T.inode,C=T.flags.startsWith("a")?j.data.byteLength:$!==null?$:T.pos,z=C+v.byteLength;if(z>j.data.byteLength){const Z=new Uint8Array(z);Z.set(j.data,0),j.data=Z}return j.data.set(v,C),j.mtimeMs=Date.now(),T.pos=C+v.byteLength,v.byteLength},readSync(b,w,g=0,x=w.byteLength-g,R=null){const T=p.get(b);if(!T||T.isDirectory)throw A("EBADF","read",String(b),"bad file descriptor");const v=T.inode,$=R??T.pos;if($>=v.data.byteLength||x<=0)return 0;const j=Math.min(x,v.data.byteLength-$);return w.set(v.data.subarray($,$+j),g),R==null&&(T.pos=$+j),j},readFileSync(b,w){if(b===0||b==="/dev/stdin"){const v=O.from(String(L||""),"utf8"),$=typeof w=="string"?w:w&&w.encoding;return $?v.toString($):v}const g=m(b);if(r.has(g))throw A("EISDIR","read",b,"illegal operation on a directory");const x=s.get(g);if(!x)throw A("ENOENT","open",b,"no such file or directory");const R=O.alloc(x.data.byteLength);R.set(x.data);const T=typeof w=="string"?w:w&&w.encoding;return T?R.toString(T):R},writeFileSync(b,w,g){const x=m(b);if(r.has(x))throw A("EISDIR","open",b,"illegal operation on a directory");const R=J.dirname(x);if(!r.has(R))throw A("ENOENT","open",b,"no such file or directory");const T=typeof g=="string"?g:g&&g.encoding||"utf8",v=typeof w=="string"?se(w):w instanceof Uint8Array?w.slice():new Uint8Array(O.from(String(w),T));let $=s.get(x);if($)$.data=v,$.mtimeMs=Date.now(),g&&typeof g=="object"&&g.mode!==void 0&&($.mode=32768|Number(g.mode)&511);else{const j=g&&typeof g=="object"&&g.mode!==void 0?32768|Number(g.mode)&511:33188;$={data:v,mtimeMs:Date.now(),ctimeMs:Date.now(),ino:S++,mode:j},s.set(x,$)}n.delete(x)},chmodSync(b,w){const g=m(b),x=typeof w=="string"?parseInt(w,8):Number(w);if(r.has(g))return;const R=s.get(g);if(!R)throw A("ENOENT","chmod",b,"no such file or directory");const T=(R.mode!==void 0?R.mode:33188)&-512;R.mode=T|x&511},appendFileSync(b,w,g){const x=m(b),R=typeof g=="string"?g:g&&g.encoding||"utf8",T=typeof w=="string"?se(w):w instanceof Uint8Array?w:new Uint8Array(O.from(String(w),R));let v=s.get(x);if(!v){u.writeFileSync(x,T,g);return}const $=new Uint8Array(v.data.byteLength+T.byteLength);$.set(v.data,0),$.set(T,v.data.byteLength),v.data=$,v.mtimeMs=Date.now(),n.delete(x)},truncateSync(b,w=0){const g=m(b),x=s.get(g);if(!x)throw A("ENOENT","truncate",b,"no such file or directory");const R=Math.max(0,Number(w)||0);if(R<=x.data.byteLength)x.data=x.data.slice(0,R);else{const T=new Uint8Array(R);T.set(x.data,0),x.data=T}x.mtimeMs=Date.now()},renameSync(b,w){const g=m(b),x=m(w);if(r.has(g)){if(g===x)return;if(x.startsWith(g+"/"))throw A("EINVAL","rename",b,"cannot move an ancestor to child");if(s.has(x))throw A("ENOTDIR","rename",w,"not a directory");if(r.has(x)){if(Array.from(r).some(z=>z!==x&&z.startsWith(x+"/"))||Array.from(s.keys()).some(z=>z.startsWith(x+"/")))throw A("ENOTEMPTY","rename",w,"directory not empty");r.delete(x)}N(x),r.delete(g),r.add(x);const T=g+"/",v=x+"/",$=[];for(const C of r)C.startsWith(T)&&$.push(C);for(const C of $)r.delete(C),r.add(v+C.slice(T.length));const j=[];for(const[C,z]of s.entries())C.startsWith(T)&&j.push([C,z]);for(const[C,z]of j){s.delete(C);const Z=v+C.slice(T.length);s.set(Z,z);for(const Q of p.values())Q.path===C&&(Q.path=Z)}return}const R=s.get(g);if(!R)throw A("ENOENT","rename",b,"no such file or directory");N(x),s.set(x,R),s.delete(g);for(const T of p.values())T.path===g&&(T.path=x);n.delete(g),n.delete(x)},unlinkSync(b){const w=m(b),g=s.get(w);if(!g)throw A("ENOENT","unlink",b,"no such file or directory");d(w,g.data,g.mtimeMs),s.delete(w)},rmSync(b,w={}){const g=m(b),x=!!(w&&w.recursive),R=!!(w&&w.force);if(s.has(g)){u.unlinkSync(g);return}if(r.has(g)){const T=g==="/"?"/":g+"/";for(const[v,$]of Array.from(s.entries()))if(v.startsWith(T)){if(!x)throw A("ENOTEMPTY","rm",b,"directory not empty");d(v,$.data,$.mtimeMs),s.delete(v)}for(const v of Array.from(r))(v===g||v.startsWith(T))&&v!=="/"&&v!=="/tmp"&&v!=="/workspace"&&r.delete(v);return}if(!R)throw A("ENOENT","rm",b,"no such file or directory")},rmdirSync(b,w={}){return u.rmSync(b,{...w,recursive:!!(w&&w.recursive)})},accessSync(b){const w=m(b);if(!r.has(w)&&!s.has(w))throw A("ENOENT","access",b,"no such file or directory")},realpathSync(b){const w=m(b);if(!r.has(w)&&!s.has(w))throw A("ENOENT","realpath",b,"no such file or directory");return w},copyFileSync(b,w,g=0){const x=m(b),R=m(w);if(r.has(x))throw A("EISDIR","copyfile",b,"illegal operation on a directory");const T=s.get(x);if(!T)throw A("ENOENT","copyfile",b,"no such file or directory");if(r.has(R))throw A("EISDIR","copyfile",w,"illegal operation on a directory");if(g&1&&s.has(R))throw A("EEXIST","copyfile",w,"file already exists");u.writeFileSync(R,T.data.slice())},createReadStream(b,w={}){typeof w=="string"&&(w={encoding:w});const g=m(b),x=typeof w.start=="number"?w.start:0,R=typeof w.end=="number"?w.end:1/0,T=w.highWaterMark||16384,v=new Tt({encoding:w.encoding||null});return v.path=g,v.bytesRead=0,queueMicrotask(()=>{if(v.destroyed)return;if(r.has(g)){v.destroy(A("EISDIR","read",b,"illegal operation on a directory"));return}const $=s.get(g);if(!$){v.destroy(A("ENOENT","open",b,"no such file or directory"));return}v.emit("open",100),v.emit("ready");const j=Math.min($.data.byteLength,Number.isFinite(R)?R+1:$.data.byteLength),C=$.data.subarray(Math.max(0,x),Math.max(0,j));for(let z=0;z<C.byteLength;z+=T){if(v.destroyed)return;const Z=O.from(C.subarray(z,Math.min(C.byteLength,z+T)));v.bytesRead+=Z.byteLength,v.push(Z)}v.destroyed||v.push(null)}),v},createWriteStream(b,w={}){typeof w=="string"&&(w={encoding:w});const g=m(b),x=w&&w.flags||"w";let R=null,T=null;try{R=u.openSync(g,x)}catch($){T=$}const v=new Pt({write($,j,C){if(T)return C(T);try{const z=typeof $=="string"?O.from($,j||w&&w.encoding||"utf8"):O.from($),Z=u.writeSync(R,z,0,z.byteLength);v.bytesWritten+=Z,C(null)}catch(z){C(z)}},final($){if(R!==null){try{u.closeSync(R)}catch(j){D.debug("vfs writeStream closeSync failed",j)}R=null}$(null)}});return v.path=g,v.bytesWritten=0,queueMicrotask(()=>{T?v.destroy(T):(v.emit("open",R),v.emit("ready"))}),v},constants:{F_OK:0,R_OK:4,W_OK:2,X_OK:1,COPYFILE_EXCL:1,COPYFILE_FICLONE:2,COPYFILE_FICLONE_FORCE:4},getSnapshot(){const b=[],w=g=>{const x=g.subarray(0,256);let R=0;for(let C=0;C<x.length;C++){const z=x[C];(z>=32&&z<=126||z===9||z===10||z===13)&&R++}const T=x.length===0||R/x.length>=.75,v=T?te(g.subarray(0,512)):null,$=[],j=Math.min(g.length,64);for(let C=0;C<j;C++)$.push(g[C].toString(16).padStart(2,"0"));return{isBinary:!T,preview:v,hexPreview:$.join(" ")+(g.length>64?" \u2026":"")}};for(const[g,x]of s.entries()){const{isBinary:R,preview:T,hexPreview:v}=w(x.data);b.push({path:g,size:x.data.byteLength,mtimeMs:x.mtimeMs,isDirectory:!1,deleted:!1,isInitialProjectFile:!!x.isInitialProjectFile,isBinary:R,preview:T,hexPreview:v})}for(const[g,x]of n.entries())if(!s.has(g)&&!g.endsWith(".tmp")&&x.data.byteLength>0){const{isBinary:R,preview:T,hexPreview:v}=w(x.data);b.push({path:g,size:x.data.byteLength,mtimeMs:x.mtimeMs,isDirectory:!1,deleted:!0,isInitialProjectFile:!1,isBinary:R,preview:T,hexPreview:v})}return b.sort((g,x)=>g.path.localeCompare(x.path)),b},_listOpenFds(){return Array.from(p.keys())}};u.realpathSync.native=u.realpathSync;const B=b=>(...w)=>{const g=typeof w[w.length-1]=="function"?w.pop():()=>{};queueMicrotask(()=>{try{const x=b(...w);g(null,x)}catch(x){g(x)}})};u.exists=(b,w)=>queueMicrotask(()=>typeof w=="function"?w(u.existsSync(b)):void 0),u.readFile=B(u.readFileSync),u.writeFile=B(u.writeFileSync),u.appendFile=B(u.appendFileSync),u.mkdir=B(u.mkdirSync),u.mkdtemp=B(u.mkdtempSync),u.readdir=B(u.readdirSync),u.stat=B(u.statSync),u.lstat=B(u.lstatSync),u.fstat=B(u.fstatSync),u.unlink=B(u.unlinkSync),u.rm=B(u.rmSync),u.rmdir=B(u.rmdirSync),u.rename=B(u.renameSync),u.truncate=B(u.truncateSync),u.access=B(u.accessSync),u.copyFile=B(u.copyFileSync),u.realpath=B(u.realpathSync),u.chmod=B(u.chmodSync),u.open=B(u.openSync),u.close=B(u.closeSync),u.fsync=B(u.fsyncSync),u.fdatasync=B(u.fdatasyncSync),u.read=(b,w,g,x,R,T)=>{typeof R=="function"&&(T=R,R=null),queueMicrotask(()=>{try{const v=u.readSync(b,w,g,x,R);typeof T=="function"&&T(null,v,w)}catch(v){typeof T=="function"&&T(v)}})},u.write=(b,w,g,x,R,T)=>{typeof g=="function"?(T=g,g=void 0):typeof x=="function"?(T=x,x=void 0):typeof R=="function"&&(T=R,R=void 0),queueMicrotask(()=>{try{const v=u.writeSync(b,w,g,x,R);typeof T=="function"&&T(null,v,w)}catch(v){typeof T=="function"&&T(v)}})};class F{constructor(w,g){this.fd=w,this.path=g,this._closed=!1}async read(w,g,x,R){let T=w;return w&&typeof w=="object"&&!ArrayBuffer.isView(w)?(T=w.buffer||O.alloc(w.length||16384),g=w.offset??0,x=w.length??T.byteLength-g,R=w.position??null):T||(T=O.alloc(16384),g=0,x=T.byteLength,R=null),g===void 0&&(g=0),x===void 0&&(x=T.byteLength-g),{bytesRead:u.readSync(this.fd,T,g,x,R),buffer:T}}async write(w,g,x,R){return{bytesWritten:u.writeSync(this.fd,w,g,x,R),buffer:w}}async readFile(w){return u.readFileSync(this.path,w)}async writeFile(w,g){return u.writeFileSync(this.path,w,g)}async stat(){return u.fstatSync(this.fd)}async truncate(w=0){return u.truncateSync(this.path,w)}async sync(){return u.fsyncSync(this.fd)}async datasync(){return u.fdatasyncSync(this.fd)}async close(){this._closed||(this._closed=!0,u.closeSync(this.fd))}}const U={constants:u.constants,FileHandle:F,access:async(b,w)=>u.accessSync(b,w),chmod:async(b,w)=>u.chmodSync(b,w),copyFile:async(b,w,g)=>u.copyFileSync(b,w,g),open:async(b,w="r")=>{const g=m(b),x=u.openSync(g,w);return new F(x,g)},readFile:async(b,w)=>b instanceof F?b.readFile(w):u.readFileSync(b,w),writeFile:async(b,w,g)=>b instanceof F?b.writeFile(w,g):u.writeFileSync(b,w,g),appendFile:async(b,w,g)=>u.appendFileSync(b,w,g),mkdir:async(b,w)=>u.mkdirSync(b,w),mkdtemp:async b=>u.mkdtempSync(b),readdir:async(b,w)=>u.readdirSync(b,w),stat:async b=>u.statSync(b),lstat:async b=>u.lstatSync(b),unlink:async b=>u.unlinkSync(b),rm:async(b,w)=>u.rmSync(b,w),rmdir:async(b,w)=>u.rmdirSync(b,w),rename:async(b,w)=>u.renameSync(b,w),truncate:async(b,w)=>u.truncateSync(b,w),realpath:async b=>u.realpathSync(b)};return u.promises=U,u._exportRawState=()=>{const b=new Map;for(const[w,g]of s.entries())b.set(w,g.data instanceof Uint8Array?g.data.slice():new Uint8Array(g.data||0));return{files:b,dirs:new Set(r)}},u}class fe{constructor(){this._events=new Map,this._maxListeners=fe.defaultMaxListeners}_ensureMap(){return this._events||(this._events=new Map),this._events}setMaxListeners(e){return this._maxListeners=Number(e),this}getMaxListeners(){return this._maxListeners!==void 0?this._maxListeners:fe.defaultMaxListeners}on(e,r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function');const s=this._ensureMap();return s.has(e)||s.set(e,[]),s.get(e).push({fn:r,once:!1}),e!=="newListener"&&s.has("newListener")&&this.emit("newListener",e,r),this}addListener(e,r){return this.on(e,r)}prependListener(e,r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function');const s=this._ensureMap();return s.has(e)||s.set(e,[]),s.get(e).unshift({fn:r,once:!1}),this}once(e,r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function');const s=this._ensureMap();return s.has(e)||s.set(e,[]),s.get(e).push({fn:r,once:!0}),this}prependOnceListener(e,r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function');const s=this._ensureMap();return s.has(e)||s.set(e,[]),s.get(e).unshift({fn:r,once:!0}),this}off(e,r){const s=this._ensureMap(),n=s.get(e);if(!n)return this;const i=n.findIndex(a=>a.fn===r||a.fn.listener===r);return i!==-1&&(n.splice(i,1),n.length===0&&s.delete(e),e!=="removeListener"&&s.has("removeListener")&&this.emit("removeListener",e,r)),this}removeListener(e,r){return this.off(e,r)}removeAllListeners(e){const r=this._ensureMap();return e!==void 0?r.delete(e):r.clear(),this}listeners(e){const r=this._ensureMap().get(e);return r?r.map(s=>s.fn):[]}rawListeners(e){return this.listeners(e)}listenerCount(e){const r=this._ensureMap().get(e);return r?r.length:0}eventNames(){return Array.from(this._ensureMap().keys())}emit(e,...r){const s=this._ensureMap(),n=s.get(e);if(!n||n.length===0){if(e==="error")throw r[0]instanceof Error?r[0]:new Error(String(r[0]||"Unhandled error event"));return!1}const i=n.slice(),a=n.filter(f=>!f.once);a.length>0?s.set(e,a):s.delete(e);for(let f=0;f<i.length;f++)i[f].fn.apply(this,r);return!0}}fe.defaultMaxListeners=10,fe.EventEmitter=fe,fe.listenerCount=(t,e)=>t.listenerCount(e),fe.once=(t,e)=>new Promise((r,s)=>{const n=(...a)=>{t.off("error",i),r(a)},i=a=>{t.off(e,n),s(a)};t.once(e,n),e!=="error"&&t.once("error",i)});const Et=fe,Le={escape(t){return encodeURIComponent(String(t))},unescape(t){try{return decodeURIComponent(String(t).replace(/\+/g," "))}catch{return String(t)}},parse(t,e="&",r="="){const s=Object.create(null);if(typeof t!="string"||t.length===0)return s;const i=(t.startsWith("?")?t.slice(1):t).split(e||"&");for(let a=0;a<i.length;a++){const f=i[a];if(!f)continue;const p=f.indexOf(r||"="),y=p===-1?f:f.slice(0,p),S=p===-1?"":f.slice(p+(r||"=").length),l=Le.unescape(y),d=Le.unescape(S);Object.prototype.hasOwnProperty.call(s,l)?Array.isArray(s[l])?s[l].push(d):s[l]=[s[l],d]:s[l]=d}return s},stringify(t,e="&",r="="){if(!t||typeof t!="object")return"";const s=[];for(const[n,i]of Object.entries(t)){const a=Le.escape(n);if(Array.isArray(i))for(let f=0;f<i.length;f++)s.push(`${a}${r}${Le.escape(i[f]??"")}`);else i!==void 0&&s.push(`${a}${r}${Le.escape(i??"")}`)}return s.join(e)}};Le.decode=Le.parse,Le.encode=Le.stringify;const At={URL:typeof URL<"u"?URL:null,URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:null,parse(t,e=!1){t=String(t||"");let r=null;const s=t.indexOf("#");s!==-1&&(r=t.slice(s),t=t.slice(0,s));let n=null,i=e?Object.create(null):null;const a=t.indexOf("?");if(a!==-1){n=t.slice(a);const u=n.slice(1);i=e?Le.parse(u):u,t=t.slice(0,a)}const f=/^([a-zA-Z][a-zA-Z0-9+.-]*:)?(\/\/)?([^/?#]*)?(\/.*)?$/.exec(t),p=f&&f[1]?f[1].toLowerCase():null,y=!!(f&&f[2]);let S=f&&f[2]?f[3]||"":null,l=f&&f[2]?f[4]||"/":t||"/",d=null,m=null,A=null,N=null;if(S!==null){const u=S.indexOf("@");u!==-1&&(d=S.slice(0,u),S=S.slice(u+1)),m=S;const B=S.lastIndexOf(":");B!==-1&&!S.endsWith("]")?(A=S.slice(0,B),N=S.slice(B+1)):A=S}const k=l+(n||""),L=(p||"")+(y?"//":"")+(d?d+"@":"")+(m||"")+k+(r||"");return{protocol:p,slashes:y,auth:d,host:m,port:N,hostname:A,hash:r,search:n,query:i,pathname:l,path:k,href:L}},format(t){if(typeof t=="string")return t;if(typeof URL<"u"&&t instanceof URL)return t.toString();if(!t||typeof t!="object")return"";if(t.href)return t.href;const e=t.protocol?t.protocol.endsWith(":")?t.protocol:t.protocol+":":"",r=t.slashes||e==="http:"||e==="https:"||e==="file:"?"//":"",s=t.auth?t.auth+"@":"",n=t.host||(t.hostname?t.hostname+(t.port?":"+t.port:""):""),i=t.pathname||"/";let a=t.search||"";if(!a&&t.query){const p=typeof t.query=="object"?Le.stringify(t.query):String(t.query);p&&(a="?"+p)}const f=t.hash?t.hash.startsWith("#")?t.hash:"#"+t.hash:"";return`${e}${r}${s}${n}${i}${a}${f}`},resolve(t,e){const r=String(t||""),s=String(e||"");if(!s)return r;if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(s))return s;if(typeof URL<"u")try{const i=new URL(s,new URL(r,"resolve://"));if(i.protocol==="resolve:"){const{pathname:a,search:f,hash:p}=i;return a+f+p}return i.href}catch(i){D.debug("url.resolve fallback used",i)}if(s.startsWith("/")){const i=/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]+)/.exec(r);return i?i[1]+s:s}return(r.endsWith("/")?r:r.replace(/[^/]*$/,""))+s},fileURLToPath(t){return(typeof t=="string"?t:t.href||String(t)).replace(/^file:\/\//i,"")||"/"},pathToFileURL(t){const e=J.resolve(String(t));return typeof URL<"u"?new URL(`file://${e}`):{href:`file://${e}`,pathname:e}}};class De extends fe{pipe(e,r={}){const s=n=>{!e.destroyed&&!e.writableFinished&&e.write(n)};return this.on("data",s),r.end!==!1&&this.once("end",()=>{!e.destroyed&&!e.writableFinished&&e.end()}),this.once("error",n=>{e.emit("error",n)}),e.emit("pipe",this),e}}class Tt extends De{constructor(e={}){super(),this.readable=!0,this.readableEnded=!1,this.destroyed=!1,this._objectMode=!!e.objectMode,this._encoding=e.encoding||null,this._readableBuffer=[],this._flowing=!1,this._reading=!1,typeof e.read=="function"&&(this._read=e.read),typeof e.destroy=="function"&&(this._destroy=e.destroy)}_read(){}setEncoding(e){return this._encoding=e,this}push(e,r){if(this.destroyed||this.readableEnded)return!1;if(e===null)return this.readableEnded=!0,this._flushReadable(),!1;let s=e;if(!this._objectMode){const n=typeof e=="string"?O.from(e,r||this._encoding||"utf8"):O.isBuffer(e)?e:O.from(e);s=this._encoding?n.toString(this._encoding):n}return this._readableBuffer.push(s),this._flushReadable(),!0}read(){if(this._readableBuffer.length===0&&!this.readableEnded&&!this._reading){this._reading=!0;try{this._read(16384)}finally{this._reading=!1}}return this._readableBuffer.length===0?null:this._readableBuffer.shift()}on(e,r){return super.on(e,r),e==="data"?(this._flowing=!0,queueMicrotask(()=>this._drainReadable())):e==="end"&&this.readableEnded&&this._readableBuffer.length===0&&queueMicrotask(()=>this.emit("end")),this}resume(){return this._flowing=!0,queueMicrotask(()=>this._drainReadable()),this}pause(){return this._flowing=!1,this}unpipe(){return this.removeAllListeners("data"),this}_drainReadable(){if(!this.destroyed){if(!this.readableEnded&&this._readableBuffer.length===0&&!this._reading){this._reading=!0;try{this._read(16384)}finally{this._reading=!1}}this._flushReadable()}}_flushReadable(){if(!this.destroyed){if(this._flowing&&this.listenerCount("data")>0)for(;this._readableBuffer.length>0&&this._flowing;){const e=this._readableBuffer.shift();this.emit("data",e)}this.readableEnded&&this._readableBuffer.length===0&&!this._endEmitted&&(this._endEmitted=!0,queueMicrotask(()=>{this.destroyed||(this.emit("end"),this.emit("close"))}))}}destroy(e){return this.destroyed?this:(this.destroyed=!0,e&&queueMicrotask(()=>this.emit("error",e)),queueMicrotask(()=>this.emit("close")),this)}async*[Symbol.asyncIterator](){const e=[];let r=!1,s=null,n=null;for(this.on("data",i=>{if(e.push(i),n){const a=n;n=null,a()}}),this.once("end",()=>{if(r=!0,n){const i=n;n=null,i()}}),this.once("error",i=>{if(s=i,r=!0,n){const a=n;n=null,a()}});!r||e.length>0;){if(s)throw s;e.length>0?yield e.shift():r||await new Promise(i=>{n=i})}if(s)throw s}static from(e,r={}){const s=new Tt({objectMode:!0,...r});return queueMicrotask(async()=>{try{for await(const n of e)s.push(n);s.push(null)}catch(n){s.destroy(n)}}),s}}class Pt extends De{constructor(e={}){super(),this.writable=!0,this.writableFinished=!1,this.destroyed=!1,this._objectMode=!!e.objectMode,typeof e.write=="function"&&(this._write=e.write),typeof e.final=="function"&&(this._final=e.final)}_write(e,r,s){typeof s=="function"&&s()}write(e,r,s){if(typeof r=="function"&&(s=r,r="utf8"),this.destroyed||this.writableFinished)return!1;const n=!this._objectMode&&typeof e=="string"?O.from(e,r||"utf8"):e;return this._write(n,r||"utf8",i=>{i&&this.emit("error",i),typeof s=="function"&&s(i)}),!0}cork(){}uncork(){}end(e,r,s){if(typeof e=="function"?(s=e,e=void 0,r=void 0):typeof r=="function"&&(s=r,r=void 0),this.destroyed||this.writableFinished)return this;e!=null&&this.write(e,r);const n=()=>{this.writableFinished=!0,queueMicrotask(()=>{this.emit("finish"),this.emit("close"),typeof s=="function"&&s()})};return typeof this._final=="function"?this._final(i=>{i&&this.emit("error",i),n()}):n(),this}destroy(e){return this.destroyed?this:(this.destroyed=!0,e&&queueMicrotask(()=>this.emit("error",e)),queueMicrotask(()=>this.emit("close")),this)}}class un extends Tt{constructor(e={}){super(e),this.writable=!0,this.writableFinished=!1,typeof e.write=="function"&&(this._write=e.write),typeof e.final=="function"&&(this._final=e.final)}_write(e,r,s){typeof s=="function"&&s()}write(e,r,s){return Pt.prototype.write.call(this,e,r,s)}end(e,r,s){return Pt.prototype.end.call(this,e,r,s)}}class Cn extends un{constructor(e={}){super(e),typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)}_transform(e,r,s){s(null,e)}_write(e,r,s){this._transform(e,r,(n,i)=>{if(n){typeof s=="function"?s(n):this.emit("error",n);return}i!=null&&this.push(i),typeof s=="function"&&s()})}end(e,r,s){typeof e=="function"?(s=e,e=void 0,r=void 0):typeof r=="function"&&(s=r,r=void 0),e!=null&&this.write(e,r);const n=(i,a)=>{i&&this.emit("error",i),a!=null&&this.push(a),this.push(null),this.writableFinished=!0,queueMicrotask(()=>{this.emit("finish"),typeof s=="function"&&s(i)})};return typeof this._flush=="function"?this._flush(n):n(),this}}class He extends Cn{}function dn(t,e,r){const s=typeof e=="function"?e:r;let n=!1;const i=a=>{n||(n=!0,typeof s=="function"&&s(a||null))};return t.once("end",()=>i(null)),t.once("finish",()=>i(null)),t.once("error",a=>i(a)),t.once("close",()=>i(null)),()=>{n=!0}}function Un(...t){const r=typeof t[t.length-1]=="function"?t.pop():null,s=t.flat(),n=new Promise((i,a)=>{if(s.length<2){i();return}let f=!1;const p=S=>{if(!f){f=!0;for(const l of s)typeof l.destroy=="function"&&l.destroy();a(S)}};for(let S=0;S<s.length-1;S++)s[S].on("error",p),s[S].pipe(s[S+1]);const y=s[s.length-1];y.on("error",p),dn(y,S=>{f||(f=!0,S?a(S):i())})});return r?(n.then(()=>r(null),i=>r(i)),s[s.length-1]):n}const Ot={pipeline:(...t)=>new Promise((e,r)=>Un(...t,s=>s?r(s):e())),finished:(t,e)=>new Promise((r,s)=>dn(t,e,n=>n?s(n):r()))};De.Stream=De,De.Readable=Tt,De.Writable=Pt,De.Duplex=un,De.Transform=Cn,De.PassThrough=He,De.pipeline=Un,De.finished=dn,De.promises=Ot;const hn=De;function Fn(){const t=new Map,e=new Map,r=new Map;function s(a,...f){const p=e.get(a);if(p)for(const y of Array.from(p))try{y(...f)}catch(S){typeof console<"u"&&typeof console.error=="function"&&console.error(`[portTable] listener for "${a}" threw:`,S)}}function n(a,f={},p=null){const y=Number(a),l=Object.assign({},p||{port:y,latencyMs:0,jitterMs:0,dropRate:0,errorRate:0,statusCode:503,partitionFromPorts:[],crashed:!1},f,{port:y});return l.latencyMs=Math.max(0,Number(l.latencyMs)||0),l.jitterMs=Math.max(0,Number(l.jitterMs)||0),l.dropRate=Math.max(0,Math.min(1,Number(l.dropRate)||0)),l.errorRate=Math.max(0,Math.min(1,Number(l.errorRate)||0)),l.statusCode=Number(l.statusCode)||503,l.partitionFromPorts=Array.isArray(l.partitionFromPorts)?Array.from(new Set(l.partitionFromPorts.map(Number).filter(d=>Number.isFinite(d)&&d>0))):[],l.crashed=!!l.crashed,l}function i(a){return a?!!(a.crashed||a.latencyMs>0||a.jitterMs>0||a.dropRate>0||a.errorRate>0||Array.isArray(a.partitionFromPorts)&&a.partitionFromPorts.length>0):!1}return{on(a,f){return typeof f!="function"?()=>{}:(e.has(a)||e.set(a,new Set),e.get(a).add(f),()=>{const p=e.get(a);p&&p.delete(f)})},off(a,f){const p=e.get(a);p&&p.delete(f)},emit:s,registerServer(a,f={}){const p=Number(a);if(t.has(p))throw new Error(`Port ${p} is already in use`);const y=Object.assign({port:p,registeredAt:Date.now()},f);return t.set(p,y),s("listen",y),y},unregisterServer(a){const f=Number(a),p=t.get(f),y=t.delete(f);return y&&s("close",f,p),y},unregister(a){return this.unregisterServer(a)},killProcess(a){const f=String(a);let p=!1;for(const[y,S]of Array.from(t.entries()))if(S.pid!==void 0&&String(S.pid)===f){if(S.server&&typeof S.server.close=="function")try{S.server.close()}catch(l){D.debug("portTable server.close failed",l)}if(typeof S.stop=="function")try{S.stop()}catch(l){D.debug("portTable entry.stop failed",l)}t.delete(y)&&s("close",y,S),p=!0}return p},unregisterByPid(a){return this.killProcess(a)},getServer(a){return t.get(Number(a))||null},listServers(){return Array.from(t.values())},setChaosRule(a,f={}){const p=Number(a),y=n(p,f,r.get(p)||null);return i(y)?r.set(p,y):r.delete(p),s("chaos",p,y),y},getChaosRule(a){return r.get(Number(a))||null},listChaosRules(){return Array.from(r.values())},clearChaosRules(a){if(a!=null&&a!==""){const f=Number(a),p=r.delete(f);return s("chaos",f,null),p}return r.clear(),s("chaos",null,null),!0},async dispatchRequest(a,f={}){const p=new URL(a),y=Number(p.port||(p.protocol==="https:"?443:80)),S=f&&f.headers||{},l=typeof S.get=="function"?S.get("x-codelab-from-port"):S["x-codelab-from-port"]||S["X-CodeLab-From-Port"],d=Number(f&&f._fromPort||l||0)||null,m=r.get(y);let A=0;if(m){let L=Number(m.latencyMs)||0;if(m.jitterMs>0&&(L+=Math.round((Math.random()*2-1)*Number(m.jitterMs))),L=Math.max(0,L),L>0&&(A=L,await new Promise(u=>setTimeout(u,L))),m.crashed){const u=new Error(`connect ECONNREFUSED 127.0.0.1:${y} (chaos: node crashed)`);throw u.code="ECONNREFUSED",u.chaosEffect="CRASHED",u.fromPort=d,u}if(d&&Array.isArray(m.partitionFromPorts)&&m.partitionFromPorts.includes(d)){const u=new Error(`connect EHOSTUNREACH 127.0.0.1:${y} (chaos: network partition from :${d})`);throw u.code="EHOSTUNREACH",u.chaosEffect=`PARTITION(:${d}-x->:${y})`,u.fromPort=d,u}if(m.dropRate>0&&Math.random()<m.dropRate){const u=new Error(`socket hang up 127.0.0.1:${y} (chaos: packet dropped)`);throw u.code="ETIMEDOUT",u.chaosEffect="DROPPED",u.fromPort=d,u}if(m.errorRate>0&&Math.random()<m.errorRate){const u=Number(m.statusCode)||503,B=u===429?"Too Many Requests":u===504?"Gateway Timeout":"Service Unavailable",F=A>0?`ERROR_${u}+${A}ms`:`ERROR_${u}`,U=new Response(JSON.stringify({error:`${B} (Chaos Injected)`,chaos:!0,port:y,status:u}),{status:u,statusText:B,headers:{"content-type":"application/json","x-codelab-chaos":F}});return U._chaosEffect=F,U._fromPort=d,U}}const N=t.get(y);if(!N){const L=new Error(`connect ECONNREFUSED 127.0.0.1:${y}`);throw L.code="ECONNREFUSED",L.fromPort=d,L}let k;return N.fetch?k=await N.fetch(new Request(a,f)):N.server&&typeof N.server.dispatchRequest=="function"?k=await N.server.dispatchRequest(a,f):k=new Response("OK",{status:200}),k&&typeof k=="object"&&(k._fromPort=d,A>0&&!k._chaosEffect&&(k._chaosEffect=`DELAY_+${A}ms`)),k}}}const cr=Fn();function Bn(t,e=null){const r=new Map,s=[];let n=31e3;function i(l={}){const d={};for(const[m,A]of Object.entries(l))A!==void 0&&(d[m.toLowerCase()]=String(A));return d}class a extends Et{constructor({method:d="GET",url:m="/",statusCode:A=200,headers:N={},socket:k=null}={}){super(),this.method=d,this.url=m,this.statusCode=A,this.headers=i(N),this.socket=k||{remoteAddress:"127.0.0.1",encrypted:!1},this.destroyed=!1,this.complete=!1,this._BufferedChunks=[],this._flowing=!1,this._ended=!1}on(d,m){return super.on(d,m),d==="data"?(this._flowing=!0,this._flushBuffered()):d==="end"&&this._ended&&this._BufferedChunks.length===0&&queueMicrotask(()=>{this.complete||(this.complete=!0,this.emit("end"))}),this}resume(){return this._flowing=!0,this._flushBuffered(),this}pause(){return this._flowing=!1,this}pipe(d){return this.on("data",m=>{!d.destroyed&&!d.writableFinished&&d.write(m)}),this.on("end",()=>{!d.destroyed&&!d.writableFinished&&d.end()}),d}_pushData(d){if(this.destroyed)return;const m=O.isBuffer(d)?d:O.from(d);this._flowing&&this.listenerCount("data")>0?this.emit("data",m):this._BufferedChunks.push(m)}_pushEnd(){this.destroyed||this._ended||(this._ended=!0,this._flushBuffered())}_flushBuffered(){if(!this.destroyed){if(this._flowing&&this.listenerCount("data")>0)for(;this._BufferedChunks.length>0;){const d=this._BufferedChunks.shift();this.emit("data",d)}this._ended&&(this._flowing||this._BufferedChunks.length===0)&&(this._BufferedChunks.length=0,this.complete||(this.complete=!0,this.emit("end")))}}destroy(d){return this.destroyed?this:(this.destroyed=!0,d&&this.emit("error",d),this.emit("close"),this)}}class f extends Et{constructor(d,m){super(),this._clientReq=d,this._traceEntry=m,this.statusCode=200,this.statusMessage="OK",this.headersSent=!1,this.writableFinished=!1,this.destroyed=!1,this._headers={},this._clientRes=null}setHeader(d,m){if(this.headersSent)throw new Error("Cannot set headers after they are sent to the client");return this._headers[String(d).toLowerCase()]=String(m),this}getHeader(d){return this._headers[String(d).toLowerCase()]}removeHeader(d){delete this._headers[String(d).toLowerCase()]}writeHead(d,m,A){if(this.headersSent)return this;this.statusCode=Number(d)||200;let N=A;if(typeof m=="object"&&m!==null?N=m:typeof m=="string"&&(this.statusMessage=m),N)for(const[k,L]of Object.entries(N))L!==void 0&&(this._headers[k.toLowerCase()]=String(L));return this.headersSent=!0,this._clientRes=new a({statusCode:this.statusCode,headers:{...this._headers}}),this._clientReq.destroyed||this._clientReq._onResponseHeaders(this._clientRes),this}write(d,m){if(this.destroyed||this.writableFinished)return!1;if(this.headersSent||this.writeHead(this.statusCode,this._headers),d!=null&&d!==""){const A=typeof d=="string"?O.from(d,m||"utf8"):O.from(d);this._traceEntry&&(this._traceEntry.responseBytes+=A.length);const N=this._clientRes,k=this._clientReq;queueMicrotask(()=>{!k.destroyed&&N&&N._pushData(A)})}return!0}end(d,m,A){if(typeof d=="function"?(A=d,d=void 0):typeof m=="function"&&(A=m,m=void 0),this.destroyed||this.writableFinished)return this;this.headersSent||this.writeHead(this.statusCode,this._headers),d!=null&&d!==""&&this.write(d,m),this.writableFinished=!0,this._traceEntry&&(this._traceEntry.status=this.statusCode,this._traceEntry.durationMs=Math.max(0,performance.now()-this._traceEntry._t0),this._traceEntry.responseHeaders={...this._headers});const N=this._clientRes,k=this._clientReq;return queueMicrotask(()=>{k._clearTimeout(),!k.destroyed&&N&&N._pushEnd(),k._finishInFlight(),this.emit("finish"),this.emit("close"),typeof A=="function"&&A()}),this}destroy(d){return this.destroyed?this:(this.destroyed=!0,this._clientReq._finishInFlight(),d&&this.emit("error",d),this.emit("close"),this)}}class p extends Et{constructor(d,m){if(super(),typeof d=="string"||typeof URL<"u"&&d instanceof URL){const A=new URL(String(d));d={host:A.hostname,port:Number(A.port)||80,path:A.pathname+A.search,method:"GET"}}this.host=d.host||d.hostname||"127.0.0.1",this.port=Number(d.port)||80,this.method=String(d.method||"GET").toUpperCase(),this.path=d.path||"/",this.headers=i(d.headers||{}),this.headers.host||(this.headers.host=`${this.host}:${this.port}`),this.destroyed=!1,this._bodyChunks=[],this._ended=!1,this._timeoutTimer=null,this._serverRes=null,this._inFlightDone=!1,typeof m=="function"&&this.once("response",m),t&&t.inFlightHttp.add(this)}_finishInFlight(){this._inFlightDone||(this._inFlightDone=!0,this._clearTimeout(),t&&t.inFlightHttp.delete(this))}_clearTimeout(){this._timeoutTimer!==null&&(clearTimeout(this._timeoutTimer),t&&t.activeTimers.delete(this._timeoutTimer),this._timeoutTimer=null)}setTimeout(d,m){if(this._clearTimeout(),typeof m=="function"&&this.once("timeout",m),d>0&&Number.isFinite(d)){const A=setTimeout(()=>{t&&t.activeTimers.delete(A),this._timeoutTimer=null,!this.destroyed&&!this._inFlightDone&&this.emit("timeout")},d);this._timeoutTimer=A,t&&t.activeTimers.add(A)}return this}write(d,m){if(this.destroyed||this._ended)return!1;if(d!=null&&d!==""){const A=typeof d=="string"?O.from(d,m||"utf8"):O.from(d);this._bodyChunks.push(A)}return!0}end(d,m,A){if(typeof d=="function"?(A=d,d=void 0):typeof m=="function"&&(A=m,m=void 0),this._ended||this.destroyed)return this;d!=null&&d!==""&&this.write(d,m),this._ended=!0,typeof A=="function"&&queueMicrotask(A);const N={id:s.length+1,method:this.method,host:this.host,port:this.port,url:this.path,status:"PENDING",durationMs:0,requestBytes:this._bodyChunks.reduce((k,L)=>k+L.length,0),responseBytes:0,requestHeaders:{...this.headers},responseHeaders:{},_t0:performance.now()};return s.length>=500&&s.shift(),s.push(N),this._traceEntry=N,queueMicrotask(()=>{if(this.destroyed){this._finishInFlight();return}const k=r.get(this.port),L=!!(e&&typeof e.getChaosRule=="function"&&e.getChaosRule(this.port)),u=!!(e&&typeof e.getServer=="function"&&e.getServer(this.port));if((!k||!k._listening||L)&&e&&(u||L)&&typeof e.dispatchRequest=="function"){let U=null;if(r.size>0){const g=Array.from(r.keys()).find(x=>Number(x)!==Number(this.port));g&&(U=g)}else if(t&&t.pid&&typeof e.listServers=="function"){const g=e.listServers().find(x=>x&&x.pid===t.pid&&Number(x.port)!==Number(this.port));g&&(U=g.port)}const b=this._bodyChunks.length>0?O.concat(this._bodyChunks):void 0,w=`http://${this.host}:${this.port}${this.path.startsWith("/")?"":"/"}${this.path}`;e.dispatchRequest(w,{method:this.method,headers:{...this.headers},body:b,_fromPort:U}).then(async g=>{if(this.destroyed){this._finishInFlight();return}const x={};g&&g.headers&&typeof g.headers.forEach=="function"&&g.headers.forEach((v,$)=>{x[String($).toLowerCase()]=String(v)});let R=O.alloc(0);if(g&&typeof g.arrayBuffer=="function"){const v=await g.arrayBuffer();R=O.from(v)}N.status=g&&g.status||200,N.durationMs=Math.max(0,performance.now()-N._t0),N.responseBytes=R.length,N.responseHeaders=x,U&&(N.fromPort=U),g&&g._chaosEffect&&(N.chaosEffect=g._chaosEffect);const T=new a({statusCode:g&&g.status||200,headers:x});this._onResponseHeaders(T),R.length>0&&T._pushData(R),T._pushEnd(),this._finishInFlight()}).catch(g=>{if(this.destroyed){this._finishInFlight();return}g.errno=g.errno||-61,g.syscall=g.syscall||"connect",g.address=this.host,g.port=this.port,N.status=g.code||"ECONNREFUSED",N.durationMs=Math.max(0,performance.now()-N._t0),U&&(N.fromPort=U),g&&g.chaosEffect&&(N.chaosEffect=g.chaosEffect),this._finishInFlight(),this.emit("error",g)});return}if(!k||!k._listening){const U=new Error(`connect ECONNREFUSED ${this.host}:${this.port}`);U.code="ECONNREFUSED",U.errno=-61,U.syscall="connect",U.address=this.host,U.port=this.port,N.status="ECONNREFUSED",N.durationMs=Math.max(0,performance.now()-N._t0),this._finishInFlight(),this.emit("error",U);return}const B=new a({method:this.method,url:this.path,headers:{...this.headers},socket:{remoteAddress:"127.0.0.1",encrypted:!1}}),F=new f(this,N);this._serverRes=F;try{k.emit("request",B,F)}catch(U){this._finishInFlight(),this.emit("error",U);return}queueMicrotask(()=>{if(!this.destroyed)try{for(let U=0;U<this._bodyChunks.length;U++)B._pushData(this._bodyChunks[U]);B._pushEnd()}catch(U){this._finishInFlight(),this.emit("error",U)}})}),this}_onResponseHeaders(d){this.destroyed||this.emit("response",d)}destroy(d){return this.destroyed?this:(this.destroyed=!0,this._traceEntry&&this._traceEntry.status==="PENDING"&&(this._traceEntry.status=d&&d.code?d.code:"ABORTED",this._traceEntry.durationMs=Math.max(0,performance.now()-this._traceEntry._t0)),this._finishInFlight(),this._serverRes&&!this._serverRes.writableFinished&&(this._serverRes.destroyed=!0,this._serverRes.emit("close")),d&&queueMicrotask(()=>this.emit("error",d)),queueMicrotask(()=>this.emit("close")),this)}}class y extends Et{constructor(d){super(),typeof d=="function"&&this.on("request",d),this._port=null,this._host="127.0.0.1",this._listening=!1}listen(d=0,m="127.0.0.1",A){return typeof d=="function"?(A=d,d=0,m="127.0.0.1"):typeof m=="function"&&(A=m,m="127.0.0.1"),this._port=d===0?n++:Number(d),this._host=m||"127.0.0.1",this._listening=!0,r.set(this._port,this),e&&e.registerServer(this._port,{server:this,name:"http-server",port:this._port,pid:t&&t.pid||1}),typeof A=="function"&&this.once("listening",A),queueMicrotask(()=>{this.emit("listening")}),this}address(){return this._listening?{port:this._port,family:"IPv4",address:this._host}:null}closeAllConnections(){}close(d){return this._port!==null&&(r.delete(this._port),e&&e.unregisterServer(this._port)),this._listening=!1,typeof d=="function"&&queueMicrotask(()=>d()),queueMicrotask(()=>this.emit("close")),this}async dispatchRequest(d,m={}){return new Promise((A,N)=>{try{const k=new URL(d);let L=m.headers||{},u={};if(L instanceof Headers||L&&typeof L.entries=="function")for(const[x,R]of L.entries())u[x.toLowerCase()]=String(R);else if(typeof L=="object"&&L!==null)for(const[x,R]of Object.entries(L))R!==void 0&&(u[x.toLowerCase()]=String(R));u.host||(u.host=`${k.hostname||"127.0.0.1"}:${k.port||this._port}`);const B=new a({method:(m.method||"GET").toUpperCase(),url:k.pathname+k.search,headers:u,socket:{remoteAddress:"127.0.0.1",encrypted:!1}}),F=new Et;F.destroyed=!1,F._clearTimeout=()=>{},F._finishInFlight=()=>{},F._onResponseHeaders=()=>{};const U=new f(F,null),b=[],w=U.write.bind(U),g=U.end.bind(U);U.write=function(x,R){if(x!=null&&x!==""){const T=typeof x=="string"?O.from(x,R||"utf8"):O.from(x);b.push(T)}return w(x,R)},U.end=function(x,R,T){if(typeof x=="function"?(T=x,x=void 0):typeof R=="function"&&(T=R,R=void 0),x!=null&&x!==""){const $=typeof x=="string"?O.from(x,R||"utf8"):O.from(x);b.push($)}const v=g(x,R,T);return queueMicrotask(()=>{const $=O.concat(b),j=new Headers;for(const[z,Z]of Object.entries(U._headers))j.set(z,Z);const C=new Response($,{status:U.statusCode||200,statusText:U.statusMessage||"OK",headers:j});A(C)}),v},this.emit("request",B,U),queueMicrotask(async()=>{try{if(m.body){let x=m.body;typeof x.text=="function"&&(x=await x.text());const R=typeof x=="string"?O.from(x,"utf8"):O.from(x);B._pushData(R)}B._pushEnd()}catch(x){N(x)}})}catch(k){N(k)}})}}class S{constructor(d={}){this.options=d,this.keepAlive=!!d.keepAlive,this.maxSockets=d.maxSockets||1/0}destroy(){}}return{Agent:S,Server:y,IncomingMessage:a,ServerResponse:f,ClientRequest:p,createServer(l){return new y(l)},request(l,d){return new p(l,d)},get(l,d){const m=new p(l,d);return m.end(),m},getTrace(){return s.map(({_t0:l,...d})=>d)},activeServers:r,hasActiveServers(){return r.size>0},closeAllServers(){for(const l of Array.from(r.values()))try{l.close()}catch(d){D.debug("vhttp closeAllServers close failed",d)}r.clear()}}}class Re extends Error{constructor({message:e,actual:r,expected:s,operator:n}){const i=e||`Assertion failed: ${Wt(r)} ${n||"!="} ${Wt(s)}`;super(i),this.name="AssertionError",this.code="ERR_ASSERTION",this.actual=r,this.expected=s,this.operator=n}}function Wt(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="bigint")return`${t}n`;if(t instanceof RegExp||t instanceof Error)return String(t);if(O.isBuffer(t))return`<Buffer ${t.toString("hex").slice(0,32)}>`;try{return JSON.stringify(t)}catch{return String(t)}}function Ge(t,e,r=!0,s=new Map){if((r?Object.is(t,e):t==e)||r&&typeof t=="number"&&typeof e=="number"&&Number.isNaN(t)&&Number.isNaN(e))return!0;if(t===null||e===null||typeof t!="object"||typeof e!="object")return r?Object.is(t,e):t==e;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t instanceof RegExp&&e instanceof RegExp)return t.source===e.source&&t.flags===e.flags;if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(e)){if(t.byteLength!==e.byteLength)return!1;const a=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),f=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);for(let p=0;p<a.length;p++)if(a[p]!==f[p])return!1;return!0}if(t instanceof Set&&e instanceof Set){if(t.size!==e.size)return!1;for(const a of t)if(!e.has(a))return!1;return!0}if(t instanceof Map&&e instanceof Map){if(t.size!==e.size)return!1;for(const[a,f]of t.entries())if(!e.has(a)||!Ge(f,e.get(a),r,s))return!1;return!0}if(Array.isArray(t)!==Array.isArray(e))return!1;if(s.get(t)===e)return!0;s.set(t,e);const n=Object.keys(t),i=Object.keys(e);if(n.length!==i.length)return!1;for(let a=0;a<n.length;a++){const f=n[a];if(!Object.prototype.hasOwnProperty.call(e,f)||!Ge(t[f],e[f],r,s))return!1}return!0}function jn(t,e){if(!e)return!0;if(e instanceof RegExp)return e.test(t&&t.message?t.message:String(t))||e.test(String(t));if(typeof e=="function"){if(e.prototype&&t instanceof e)return!0;if(e===Error||e.prototype&&e.prototype instanceof Error)return!!(t&&(t instanceof e||t.name===e.name));try{return!!e(t)}catch{return!1}}if(typeof e=="object"){for(const[r,s]of Object.entries(e))if(s instanceof RegExp){if(!s.test(String(t[r])))return!1}else if(t[r]!==s)return!1;return!0}return!0}function me(t,e){if(!t)throw new Re({message:e,actual:t,expected:!0,operator:"=="})}me.AssertionError=Re,me.ok=me,me.fail=function(e){throw new Re({message:e||"Failed",actual:!1,expected:!0,operator:"fail"})},me.equal=function(e,r,s){if(e!=r&&!(Number.isNaN(e)&&Number.isNaN(r)))throw new Re({message:s,actual:e,expected:r,operator:"=="})},me.notEqual=function(e,r,s){if(e==r)throw new Re({message:s,actual:e,expected:r,operator:"!="})},me.strictEqual=function(e,r,s){if(!Object.is(e,r))throw new Re({message:s,actual:e,expected:r,operator:"==="})},me.notStrictEqual=function(e,r,s){if(Object.is(e,r))throw new Re({message:s,actual:e,expected:r,operator:"!=="})},me.deepEqual=function(e,r,s){if(!Ge(e,r,!1))throw new Re({message:s,actual:e,expected:r,operator:"deepEqual"})},me.notDeepEqual=function(e,r,s){if(Ge(e,r,!1))throw new Re({message:s,actual:e,expected:r,operator:"notDeepEqual"})},me.deepStrictEqual=function(e,r,s){if(!Ge(e,r,!0))throw new Re({message:s,actual:e,expected:r,operator:"deepStrictEqual"})},me.notDeepStrictEqual=function(e,r,s){if(Ge(e,r,!0))throw new Re({message:s,actual:e,expected:r,operator:"notDeepStrictEqual"})},me.match=function(e,r,s){if(!(r instanceof RegExp)||!r.test(String(e)))throw new Re({message:s,actual:e,expected:r,operator:"match"})},me.doesNotMatch=function(e,r,s){if(r instanceof RegExp&&r.test(String(e)))throw new Re({message:s,actual:e,expected:r,operator:"doesNotMatch"})},me.throws=function(e,r,s){let n=r,i=s;typeof r=="string"&&s===void 0&&(n=null,i=r);let a=!1,f=null;try{e()}catch(p){a=!0,f=p}if(!a)throw new Re({message:i||"Missing expected exception",actual:void 0,expected:n,operator:"throws"});if(n&&!jn(f,n))throw new Re({message:i||`Unexpected exception: ${f&&f.message?f.message:f}`,actual:f,expected:n,operator:"throws"})},me.doesNotThrow=function(e,r){try{e()}catch(s){throw new Re({message:r||`Got unwanted exception: ${s.message}`,actual:s,expected:void 0,operator:"doesNotThrow"})}},me.rejects=async function(e,r,s){let n=r,i=s;typeof r=="string"&&s===void 0&&(n=null,i=r);let a=!1,f=null;try{await(typeof e=="function"?e():e)}catch(p){a=!0,f=p}if(!a)throw new Re({message:i||"Missing expected rejection",actual:void 0,expected:n,operator:"rejects"});if(n&&!jn(f,n))throw new Re({message:i||`Unexpected rejection: ${f&&f.message?f.message:f}`,actual:f,expected:n,operator:"rejects"})},me.strict=me;const Rt=Symbol.for("nodejs.util.promisify.custom");function Je(t,e={}){const r=e&&typeof e.depth=="number"?e.depth:4,s=new WeakSet;function n(i,a){if(i===null)return"null";if(i===void 0)return"undefined";if(typeof i=="string")return JSON.stringify(i);if(typeof i=="number"||typeof i=="boolean")return String(i);if(typeof i=="bigint")return`${i}n`;if(typeof i=="symbol")return i.toString();if(typeof i=="function")return`[Function: ${i.name||"anonymous"}]`;if(i instanceof RegExp)return i.toString();if(i instanceof Date)return Number.isNaN(i.getTime())?"Invalid Date":i.toISOString();if(i instanceof Error)return i.stack||`${i.name}: ${i.message}`;if(O.isBuffer(i)){const p=i.toString("hex").match(/.{1,2}/g)||[];return`<Buffer ${p.slice(0,32).join(" ")}${p.length>32?" ... ":""}>`}if(i instanceof Uint8Array)return`Uint8Array(${i.byteLength}) [ ${Array.from(i.slice(0,16)).join(", ")}${i.byteLength>16?", ...":""} ]`;if(typeof i=="object"){if(s.has(i))return"[Circular]";if(a>r)return Array.isArray(i)?"[Array]":"[Object]";s.add(i);try{if(i instanceof Map){const S=[];for(const[l,d]of i.entries())S.push(`${n(l,a+1)} => ${n(d,a+1)}`);return`Map(${i.size}) { ${S.join(", ")} }`}if(i instanceof Set){const S=[];for(const l of i.values())S.push(n(l,a+1));return`Set(${i.size}) { ${S.join(", ")} }`}if(Array.isArray(i))return i.length===0?"[]":`[ ${i.map(S=>n(S,a+1)).join(", ")} ]`;const f=Object.keys(i);if(f.length===0)return"{}";const p=f.map(S=>`${/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(S)?S:JSON.stringify(S)}: ${n(i[S],a+1)}`);return`${i.constructor&&i.constructor!==Object?`${i.constructor.name} `:""}{ ${p.join(", ")} }`}finally{s.delete(i)}}return String(i)}return n(t,0)}function ar(...t){if(t.length===0)return"";const e=t[0];if(typeof e!="string")return t.map(n=>typeof n=="object"&&n!==null?Je(n):String(n)).join(" ");let r=1,s="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+1<e.length){const i=e[n+1];if(i==="%"){s+="%",n++;continue}if(r<t.length){const a=t[r];if(i==="s"){s+=String(a),r++,n++;continue}if(i==="d"){s+=Number(a),r++,n++;continue}if(i==="i"){s+=parseInt(a,10),r++,n++;continue}if(i==="f"){s+=parseFloat(a),r++,n++;continue}if(i==="j"){try{s+=JSON.stringify(a)}catch{s+="[Circular]"}r++,n++;continue}if(i==="o"||i==="O"){s+=Je(a),r++,n++;continue}}}s+=e[n]}for(;r<t.length;){const n=t[r++];s+=" "+(typeof n=="object"&&n!==null?Je(n):String(n))}return s}function vt(t){if(typeof t!="function")throw new TypeError('The "original" argument must be of type Function');if(t[Rt]){const r=t[Rt];if(typeof r!="function")throw new TypeError('The "util.promisify.custom" property must be of type Function');return Object.defineProperty(r,Rt,{value:r,enumerable:!1,writable:!1,configurable:!0})}function e(...r){return new Promise((s,n)=>{try{t.call(this,...r,(i,...a)=>{if(i)return n(i);s(a.length<=1?a[0]:a)})}catch(i){n(i)}})}return Object.setPrototypeOf(e,Object.getPrototypeOf(t)),Object.defineProperty(e,Rt,{value:e,enumerable:!1,writable:!1,configurable:!0}),e}vt.custom=Rt;function fr(t){if(typeof t!="function")throw new TypeError('The "original" argument must be of type Function');return function(...r){const s=r.pop();if(typeof s!="function")throw new TypeError("The last argument must be of type Function");Promise.resolve().then(()=>t.apply(this,r)).then(n=>queueMicrotask(()=>s(null,n)),n=>queueMicrotask(()=>{const i=n||new Error("Promise was rejected with a falsy value");s(i)}))}}function lr(t,e){if(t==null)throw new TypeError('The constructor to "inherits" must not be null or undefined');if(e==null)throw new TypeError('The super constructor to "inherits" must not be null or undefined');t.super_=e,Object.setPrototypeOf(t.prototype,e.prototype)}const It={format:ar,inspect:Je,promisify:vt,callbackify:fr,inherits:lr,isDeepStrictEqual:(t,e)=>Ge(t,e,!0),deprecate:t=>t,TextEncoder:typeof TextEncoder<"u"?TextEncoder:void 0,TextDecoder:typeof TextDecoder<"u"?TextDecoder:void 0,types:{isPromise:t=>!!(t&&typeof t=="object"&&typeof t.then=="function"),isRegExp:t=>t instanceof RegExp,isDate:t=>t instanceof Date,isUint8Array:t=>t instanceof Uint8Array,isArrayBuffer:t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer,isMap:t=>t instanceof Map,isSet:t=>t instanceof Set,isNativeError:t=>t instanceof Error,isBoxedPrimitive:t=>t instanceof Number||t instanceof String||t instanceof Boolean}};class ur{constructor(e="utf8"){const r=String(e||"utf8").toLowerCase().replace(/[-_]/g,"");this.encoding=r==="utf8"||r==="utf"?"utf8":r==="ucs2"||r==="utf16le"?"utf16le":r==="latin1"||r==="binary"?"latin1":r,this._pending=O.alloc(0)}write(e){const r=O.isBuffer(e)?e:O.from(e);if(r.length===0)return"";if(this.encoding!=="utf8"&&this.encoding!=="utf16le"&&this.encoding!=="base64")return r.toString(this.encoding);const s=this._pending.length>0?O.concat([this._pending,r]):r;if(this.encoding==="utf16le"){const f=s.length%2,p=s.length-f;return this._pending=f>0?O.from(s.subarray(p)):O.alloc(0),p>0?s.subarray(0,p).toString("utf16le"):""}if(this.encoding==="base64"){const f=s.length%3,p=s.length-f;return this._pending=f>0?O.from(s.subarray(p)):O.alloc(0),p>0?s.subarray(0,p).toString("base64"):""}let n=0;const i=s.length;for(let f=1;f<=3&&f<=i;f++){const p=s[i-f];if((p&192)===128)continue;let y=1;(p&224)===192?y=2:(p&240)===224?y=3:(p&248)===240&&(y=4),f<y&&(n=f);break}const a=i-n;return this._pending=n>0?O.from(s.subarray(a)):O.alloc(0),a>0?s.subarray(0,a).toString("utf8"):""}end(e){let r="";return e!==void 0&&(r+=this.write(e)),this._pending.length>0&&(r+=this._pending.toString(this.encoding),this._pending=O.alloc(0)),r}}const pn={StringDecoder:ur},ot={async lookup(t,e){const r=e&&typeof e=="object"&&e.all,s=(typeof e=="number"?e:e?.family)||4,n=s===6?"::1":"127.0.0.1";return r?[{address:n,family:s}]:{address:n,family:s}},async resolve(t,e="A"){return e==="AAAA"?["::1"]:e==="TXT"?[["v=spf1 loopback"]]:e==="MX"?[{exchange:`mail.${t}`,priority:10}]:e==="CNAME"?[`${t}.local`]:t==="example.com"?["93.184.216.34"]:["127.0.0.1"]},async resolve4(t){return t==="example.com"?["93.184.216.34"]:["127.0.0.1"]},async resolve6(){return["::1"]},async reverse(){return["localhost"]}};function Dn(t,e,r){const s=typeof e=="function"?e:r,n=typeof e=="function"?{}:e;ot.lookup(t,n).then(i=>{typeof s=="function"&&(Array.isArray(i)?s(null,i):s(null,i.address,i.family))},i=>{typeof s=="function"&&s(i)})}Dn[vt.custom]=ot.lookup;const kt={ADDRCONFIG:1024,V4MAPPED:2048,lookup:Dn,resolve(t,e,r){const s=typeof e=="function"?e:r,n=typeof e=="string"?e:"A";ot.resolve(t,n).then(i=>s&&s(null,i),i=>s&&s(i))},resolve4(t,e,r){const s=typeof e=="function"?e:r;ot.resolve4(t).then(n=>s&&s(null,n),n=>s&&s(n))},resolve6(t,e,r){const s=typeof e=="function"?e:r;ot.resolve6(t).then(n=>s&&s(null,n),n=>s&&s(n))},reverse(t,e){ot.reverse(t).then(r=>e&&e(null,r),r=>e&&e(r))},promises:ot};function Pn(t,e=[]){const r=new Map;let s=4e4;class n extends un{constructor(m={}){super(m),this.connecting=!1,this.destroyed=!1,this.remoteAddress="127.0.0.1",this.remoteFamily="IPv4",this.remotePort=null,this.localAddress="127.0.0.1",this.localPort=null,this.bytesRead=0,this.bytesWritten=0,this._peer=null,this._encoding=null,this._timeoutMs=0,this._timeoutId=null,this._endEmitted=!1}setEncoding(m){return this._encoding=m,this}setNoDelay(){return this}setKeepAlive(){return this}ref(){return this}unref(){return this}setTimeout(m,A){return this._timeoutId&&(clearTimeout(this._timeoutId),this._timeoutId=null),this._timeoutMs=m,typeof A=="function"&&this.once("timeout",A),m>0&&!this.destroyed&&(this._timeoutId=setTimeout(()=>{this.emit("timeout")},m)),this}address(){return{port:this.localPort||0,family:"IPv4",address:this.localAddress}}connect(...m){let A,N="127.0.0.1",k=null;return typeof m[0]=="object"&&m[0]!==null?(A=Number(m[0].port),m[0].host&&(N=m[0].host),typeof m[1]=="function"&&(k=m[1])):(A=Number(m[0]),typeof m[1]=="string"?(N=m[1],typeof m[2]=="function"&&(k=m[2])):typeof m[1]=="function"&&(k=m[1])),k&&this.once("connect",k),this.connecting=!0,this.remotePort=A,this.remoteAddress=N,this.localPort=s++,queueMicrotask(()=>{if(this.destroyed)return;const L=r.get(A);if(!L||!L.listening){this.connecting=!1;const B=new Error(`connect ECONNREFUSED ${N}:${A}`);B.code="ECONNREFUSED",B.errno=-111,B.syscall="connect",B.address=N,B.port=A,this.emit("error",B);return}const u=new n;u.localPort=A,u.remotePort=this.localPort,u._peer=this,this._peer=u,this.connecting=!1,e.length>=500&&e.shift(),e.push({protocol:"TCP",event:"connect",localPort:this.localPort,remotePort:A,host:N,timestamp:Date.now()}),L._connections.add(u),u.once("close",()=>L._connections.delete(u)),L.emit("connection",u),this.emit("connect"),this.emit("ready")}),this}write(m,A,N){const k=typeof A=="function"?A:N,L=typeof A=="string"?A:"utf8";if(this.destroyed){const F=new Error("This socket has been ended by the other party");return F.code="EPIPE",typeof k=="function"&&queueMicrotask(()=>k(F)),!1}const u=O.isBuffer(m)?m:O.from(String(m??""),L);this.bytesWritten+=u.length;const B=this._peer;return B&&!B.destroyed?queueMicrotask(()=>{if(B.destroyed)return;B.bytesRead+=u.length;const F=B._encoding?u.toString(B._encoding):u;B.emit("data",F),typeof k=="function"&&k(null)}):typeof k=="function"&&queueMicrotask(()=>k(null)),!0}end(m,A,N){const k=typeof m=="function"?m:typeof A=="function"?A:N,L=typeof A=="string"?A:"utf8";return m!=null&&typeof m!="function"&&this.write(m,L),queueMicrotask(()=>{if(this.destroyed)return;const u=this._peer;u&&!u.destroyed&&!u._endEmitted&&(u._endEmitted=!0,u.emit("end")),this.emit("finish"),typeof k=="function"&&k(),this.destroy()}),this}destroy(m){if(this.destroyed)return this;this.destroyed=!0,this._timeoutId&&(clearTimeout(this._timeoutId),this._timeoutId=null);const A=this._peer;return this._peer=null,queueMicrotask(()=>{m&&this.emit("error",m),this.emit("close",!!m),A&&!A.destroyed&&(A._endEmitted||(A._endEmitted=!0,A.emit("end")),A.destroy())}),this}}class i extends fe{constructor(m,A){super();const N=typeof m=="function"?m:A;typeof N=="function"&&this.on("connection",N),this.listening=!1,this._port=null,this._host="127.0.0.1",this._connections=new Set}listen(...m){let A=0,N="127.0.0.1",k=null;for(const L of m)typeof L=="number"?A=L:typeof L=="string"?N=L:typeof L=="function"?k=L:typeof L=="object"&&L!==null&&(typeof L.port=="number"&&(A=L.port),typeof L.host=="string"&&(N=L.host));if(k&&this.once("listening",k),!A||A===0)for(A=s++;r.has(A);)A=s++;return this._port=A,this._host=N,this.listening=!0,r.set(A,this),queueMicrotask(()=>{this.listening&&this.emit("listening")}),this}address(){return this.listening?{port:this._port,family:"IPv4",address:this._host}:null}getConnections(m){return typeof m=="function"&&queueMicrotask(()=>m(null,this._connections.size)),this}close(m){typeof m=="function"&&this.once("close",m),this._port!==null&&r.delete(this._port),this.listening=!1;for(const A of this._connections)A.destroy();return this._connections.clear(),queueMicrotask(()=>this.emit("close")),this}ref(){return this}unref(){return this}}function a(d){const A=String(d||"").split(".");return A.length!==4?!1:A.every(N=>/^(?:0|[1-9]\d*)$/.test(N)&&Number(N)>=0&&Number(N)<=255)}function f(d){const m=String(d||"");return m.includes(":")?/^[0-9a-fA-F:]+$/.test(m):!1}function p(d){return a(d)?4:f(d)?6:0}function y(d,m){return new i(d,m)}function S(...d){return new n().connect(...d)}function l(){for(const d of r.values())try{d.close()}catch(m){D.debug("vnet closeAllServers close failed",m)}r.clear()}return{Socket:n,Server:i,Stream:n,createServer:y,connect:S,createConnection:S,isIP:p,isIPv4:a,isIPv6:f,closeAllServers:l,getTrace:()=>[...e]}}function dr(t,e){return/\.(jsx|tsx)$/i.test(e||"")?!0:!t||t.indexOf("<")===-1?!1:!!(/@jsx\b/.test(t)||t.indexOf("<>")!==-1||/<\/[A-Za-z]/.test(t)||/<[A-Za-z_$][A-Za-z0-9_$:.\-]*\b[^>\n]*\/>/.test(t))}function mn(t){let e="React.createElement",r=null;const s=/@jsx\s+([A-Za-z_$][\w$.]*)/.exec(t);s&&(e=s[1]);const n=/@jsxFrag\s+([A-Za-z_$][\w$.]*)/.exec(t);return n&&(r=n[1]),r||(r=e==="React.createElement"?"React.Fragment":"Fragment"),{pragma:e,frag:r}}const hr=/\s/,zt=/[A-Za-z_$]/,pr=/[A-Za-z0-9_$:.\-]/;function ze(t){const e=new Error(t);throw e.jsxParse=!0,e}function yn(t,e){const r=t[e],s=t[e+1],n=t.length;if(r==="/"&&s==="/"){const i=t.indexOf(`
31
31
  `,e);return i===-1?n:i}if(r==="/"&&s==="*"){const i=t.indexOf("*/",e+2);return i===-1?n:i+2}if(r==='"'||r==="'"){let i=e+1;for(;i<n;){const a=t[i];if(a==="\\"){i+=2;continue}if(a===r){i++;break}if(a===`
32
- `)break;i++}return i}if(r==="`"){let i=e+1,a=0;for(;i<n;){const f=t[i];if(f==="\\"){i+=2;continue}if(f==="$"&&t[i+1]==="{"){a++,i+=2;continue}if(f==="}"&&a>0){a--,i++;continue}if(f==="`"&&a===0){i++;break}i++}return i}return-1}function gn(t,e){qt.test(t[e]||"")||qe("jsx: expected a tag name");let r=e;for(;r<t.length&&pr.test(t[r]);)r++;return{name:t.slice(e,r),next:r}}function ht(t,e){for(;e<t.length&&hr.test(t[e]);)e++;return e}function mr(t){if(!t)return!0;let e=0;for(;e<t.length&&(e=ht(t,e),!(e>=t.length));)if(t[e]==="/"&&(t[e+1]==="/"||t[e+1]==="*")){const r=yn(t,e);if(r===-1)return!1;e=r}else return!1;return!0}function yr(t){if(!t)return"";let e=t.replace(/\r/g,"");if(e.indexOf(`
32
+ `)break;i++}return i}if(r==="`"){let i=e+1,a=0;for(;i<n;){const f=t[i];if(f==="\\"){i+=2;continue}if(f==="$"&&t[i+1]==="{"){a++,i+=2;continue}if(f==="}"&&a>0){a--,i++;continue}if(f==="`"&&a===0){i++;break}i++}return i}return-1}function gn(t,e){zt.test(t[e]||"")||ze("jsx: expected a tag name");let r=e;for(;r<t.length&&pr.test(t[r]);)r++;return{name:t.slice(e,r),next:r}}function ht(t,e){for(;e<t.length&&hr.test(t[e]);)e++;return e}function mr(t){if(!t)return!0;let e=0;for(;e<t.length&&(e=ht(t,e),!(e>=t.length));)if(t[e]==="/"&&(t[e+1]==="/"||t[e+1]==="*")){const r=yn(t,e);if(r===-1)return!1;e=r}else return!1;return!0}function yr(t){if(!t)return"";let e=t.replace(/\r/g,"");if(e.indexOf(`
33
33
  `)!==-1)e=e.split(`
34
- `).map(r=>r.replace(/[ \t]+/g," ").trim()).filter(Boolean).join(" ");else if(/\S/.test(e))e=e.replace(/[ \t]+/g," ");else return"";return e?JSON.stringify(e):""}function bn(t,e,r){let s=0,n=e;for(;n<t.length;){const i=yn(t,n);if(i!==-1){n=i;continue}const a=t[n];if(a==="{"){s++,n++;continue}if(a==="}"){if(s--,n++,s===0)return{inner:t.slice(e+1,n-1),next:n};continue}if(a==="<"&&(qt.test(t[n+1]||"")||t[n+1]===">"))try{n=zt(t,n,r).next;continue}catch(f){if(!f||!f.jsxParse)throw f}n++}qe("jsx: unterminated expression container")}function zt(t,e,r){const s=r||mn(t);let n=e+1,i=!1,a;if(t[n]===">")i=!0,a=s.frag,n++;else{const d=gn(t,n);n=d.next;const y=d.name;y.indexOf(".")!==-1||y.indexOf(":")!==-1||/^[A-Z_$]/.test(y)?a=y.replace(/:/g,"."):a=JSON.stringify(y)}const f=[];let m=!1;if(!i)for(;;){n=ht(t,n),n>=t.length&&qe("jsx: unexpected end of input inside a tag");const d=t[n];if(d==="/"){t[n+1]!==">"&&qe("jsx: malformed self-closing tag"),n+=2,m=!0;break}if(d===">"){n++;break}if(d==="{"){const $=bn(t,n,s),l=$.inner.trim();l.slice(0,3)!=="..."&&qe("jsx: only a spread {...} may appear where an attribute is expected"),f.push({spread:Zt(l.slice(3),s)}),n=$.next;continue}qt.test(d)||qe("jsx: malformed attribute");const y=gn(t,n),A=y.name;n=ht(t,y.next);let M="true";if(t[n]==="="){n=ht(t,n+1);const $=t[n];if($==='"'||$==="'"){let l=n+1;for(;l<t.length&&t[l]!==$;)t[l]==="\\"&&l++,l++;l>=t.length&&qe("jsx: unterminated attribute string"),M=JSON.stringify(t.slice(n+1,l)),n=l+1}else if($==="{"){const l=bn(t,n,s);M=Zt(l.inner,s)||"undefined",n=l.next}else if($==="<"){const l=zt(t,n,s);M=l.code,n=l.next}else qe("jsx: unsupported attribute value")}const k=/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(A)?A:JSON.stringify(A);f.push({key:k,value:M})}const b=[];if(!m)for(;;){n>=t.length&&qe("jsx: missing closing tag");const d=t[n];if(d==="<"&&t[n+1]==="/"){if(n=ht(t,n+2),t[n]===">"){n++;break}const M=gn(t,n);n=ht(t,M.next),t[n]!==">"&&qe("jsx: malformed closing tag"),n++;break}if(d==="<"){const M=zt(t,n,s);b.push(M.code),n=M.next;continue}if(d==="{"){const M=bn(t,n,s);if(!mr(M.inner)){const k=Zt(M.inner,s);k&&k.trim()&&b.push(k.indexOf("//")!==-1&&!k.endsWith(`
34
+ `).map(r=>r.replace(/[ \t]+/g," ").trim()).filter(Boolean).join(" ");else if(/\S/.test(e))e=e.replace(/[ \t]+/g," ");else return"";return e?JSON.stringify(e):""}function bn(t,e,r){let s=0,n=e;for(;n<t.length;){const i=yn(t,n);if(i!==-1){n=i;continue}const a=t[n];if(a==="{"){s++,n++;continue}if(a==="}"){if(s--,n++,s===0)return{inner:t.slice(e+1,n-1),next:n};continue}if(a==="<"&&(zt.test(t[n+1]||"")||t[n+1]===">"))try{n=qt(t,n,r).next;continue}catch(f){if(!f||!f.jsxParse)throw f}n++}ze("jsx: unterminated expression container")}function qt(t,e,r){const s=r||mn(t);let n=e+1,i=!1,a;if(t[n]===">")i=!0,a=s.frag,n++;else{const d=gn(t,n);n=d.next;const m=d.name;m.indexOf(".")!==-1||m.indexOf(":")!==-1||/^[A-Z_$]/.test(m)?a=m.replace(/:/g,"."):a=JSON.stringify(m)}const f=[];let p=!1;if(!i)for(;;){n=ht(t,n),n>=t.length&&ze("jsx: unexpected end of input inside a tag");const d=t[n];if(d==="/"){t[n+1]!==">"&&ze("jsx: malformed self-closing tag"),n+=2,p=!0;break}if(d===">"){n++;break}if(d==="{"){const L=bn(t,n,s),u=L.inner.trim();u.slice(0,3)!=="..."&&ze("jsx: only a spread {...} may appear where an attribute is expected"),f.push({spread:Zt(u.slice(3),s)}),n=L.next;continue}zt.test(d)||ze("jsx: malformed attribute");const m=gn(t,n),A=m.name;n=ht(t,m.next);let N="true";if(t[n]==="="){n=ht(t,n+1);const L=t[n];if(L==='"'||L==="'"){let u=n+1;for(;u<t.length&&t[u]!==L;)t[u]==="\\"&&u++,u++;u>=t.length&&ze("jsx: unterminated attribute string"),N=JSON.stringify(t.slice(n+1,u)),n=u+1}else if(L==="{"){const u=bn(t,n,s);N=Zt(u.inner,s)||"undefined",n=u.next}else if(L==="<"){const u=qt(t,n,s);N=u.code,n=u.next}else ze("jsx: unsupported attribute value")}const k=/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(A)?A:JSON.stringify(A);f.push({key:k,value:N})}const y=[];if(!p)for(;;){n>=t.length&&ze("jsx: missing closing tag");const d=t[n];if(d==="<"&&t[n+1]==="/"){if(n=ht(t,n+2),t[n]===">"){n++;break}const N=gn(t,n);n=ht(t,N.next),t[n]!==">"&&ze("jsx: malformed closing tag"),n++;break}if(d==="<"){const N=qt(t,n,s);y.push(N.code),n=N.next;continue}if(d==="{"){const N=bn(t,n,s);if(!mr(N.inner)){const k=Zt(N.inner,s);k&&k.trim()&&y.push(k.indexOf("//")!==-1&&!k.endsWith(`
35
35
  `)?k+`
36
- `:k)}n=M.next;continue}let y=n;for(;y<t.length&&t[y]!=="<"&&t[y]!=="{";)y++;const A=yr(t.slice(n,y));A&&b.push(A),n=y}let x="null";f.length&&(x="{ "+f.map(y=>y.spread!==void 0?"...("+y.spread+")":y.key+": "+y.value).join(", ")+" }");const u=[a,x].concat(b);return{code:s.pragma+"("+u.join(", ")+")",next:n}}function Zt(t,e){const r=e||mn(t);let s=0,n="";for(;s<t.length;){const i=yn(t,s);if(i!==-1){n+=t.slice(s,i),s=i;continue}const a=t[s];if(a==="<"&&(qt.test(t[s+1]||"")||t[s+1]===">"))try{const f=zt(t,s,r);n+=f.code,s=f.next;continue}catch(f){if(!f||!f.jsxParse)throw f}n+=a,s++}return n}function pt(t,e="module.ts",r={}){const s=!!(r&&(r.keepEsm||r.expressionOnly)),n=!!(r&&r.expressionOnly),i=n||/\.(ts|tsx|mts|cts)$/i.test(e)||/^[ \t]*(?:export\s+)?(?:abstract\s+class\s+[A-Za-z_$]|declare\s+(?:const|let|var|function|class|namespace|module|global)\b|interface\s+[A-Za-z_$][A-Za-z0-9_$]*|type\s+[A-Za-z_$][A-Za-z0-9_$]*\s*(?:<[^>]*>)?\s*=|enum\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{|namespace\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{)/m.test(t),a=!n&&(/^\s*(?:import|export)\b/m.test(t)||/\bexport\s*\{/.test(t)||/\bimport\s*\{/.test(t)||/\bexport\s+default\b/.test(t)),f=dr(t,e);if(!i&&!a&&!f)return t;if(f){const{pragma:k,frag:$}=mn(t),l=/\bimport\s+(?!type\b)(?:\*\s+as\s+React\b|React\b)|(?:\bconst|\blet|\bvar|\bfunction|\bclass)\s+React\b|\bReact\s*=/.test(t),F=!n&&k==="React.createElement"&&(s?!l:!/\bReact\b/.test(t)),U=Zt(t,{pragma:k,frag:$});if(U!==t)t=U,F&&(t=(s?`import React from "react";
36
+ `:k)}n=N.next;continue}let m=n;for(;m<t.length&&t[m]!=="<"&&t[m]!=="{";)m++;const A=yr(t.slice(n,m));A&&y.push(A),n=m}let S="null";f.length&&(S="{ "+f.map(m=>m.spread!==void 0?"...("+m.spread+")":m.key+": "+m.value).join(", ")+" }");const l=[a,S].concat(y);return{code:s.pragma+"("+l.join(", ")+")",next:n}}function Zt(t,e){const r=e||mn(t);let s=0,n="";for(;s<t.length;){const i=yn(t,s);if(i!==-1){n+=t.slice(s,i),s=i;continue}const a=t[s];if(a==="<"&&(zt.test(t[s+1]||"")||t[s+1]===">"))try{const f=qt(t,s,r);n+=f.code,s=f.next;continue}catch(f){if(!f||!f.jsxParse)throw f}n+=a,s++}return n}function pt(t,e="module.ts",r={}){const s=!!(r&&(r.keepEsm||r.expressionOnly)),n=!!(r&&r.expressionOnly),i=n||/\.(ts|tsx|mts|cts)$/i.test(e)||/^[ \t]*(?:export\s+)?(?:abstract\s+class\s+[A-Za-z_$]|declare\s+(?:const|let|var|function|class|namespace|module|global)\b|interface\s+[A-Za-z_$][A-Za-z0-9_$]*|type\s+[A-Za-z_$][A-Za-z0-9_$]*\s*(?:<[^>]*>)?\s*=|enum\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{|namespace\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{)/m.test(t),a=!n&&(/^\s*(?:import|export)\b/m.test(t)||/\bexport\s*\{/.test(t)||/\bimport\s*\{/.test(t)||/\bexport\s+default\b/.test(t)),f=dr(t,e);if(!i&&!a&&!f)return t;if(f){const{pragma:k,frag:L}=mn(t),u=/\bimport\s+(?!type\b)(?:\*\s+as\s+React\b|React\b)|(?:\bconst|\blet|\bvar|\bfunction|\bclass)\s+React\b|\bReact\s*=/.test(t),B=!n&&k==="React.createElement"&&(s?!u:!/\bReact\b/.test(t)),F=Zt(t,{pragma:k,frag:L});if(F!==t)t=F,B&&(t=(s?`import React from "react";
37
37
  `:`const React = require("react");
38
- `)+t);else if(!i&&!a)return t}const m=[],b=k=>{const $=`\0__LIT_${m.length}__\0`;return m.push(k),$},x=k=>{const $=k.trimEnd();if(!$)return!0;const l=$[$.length-1];return"(,=:[!&|?{};+-*/%~^<>".includes(l)?!0:/\b(?:return|throw|case|in|of|typeof|instanceof|void|delete|await|yield)$/.test($)};let u="",d=0;const y=t.length;for(;d<y;){const k=t[d],$=t[d+1];if(k==="/"&&$==="/"){let l=t.indexOf(`
39
- `,d+2);l===-1&&(l=y),u+=b(t.slice(d,l)),d=l;continue}if(k==="/"&&$==="*"){let l=t.indexOf("*/",d+2);l===-1?l=y:l+=2,u+=b(t.slice(d,l)),d=l;continue}if(k==="/"&&$!=="/"&&$!=="*"&&$!=="="&&x(u)){let l=d+1,F=!1,U=!1;for(;l<y;){const C=t[l];if(C===`
40
- `||C==="\r")break;if(C==="\\"){l+=2;continue}if(C==="["){F=!0,l++;continue}if(C==="]"&&F){F=!1,l++;continue}if(C==="/"&&!F){for(U=!0,l++;l<y&&/[dgimsuvy]/.test(t[l]);)l++;break}l++}if(U){u+=b(t.slice(d,l)),d=l;continue}}if(k==="'"||k==='"'){let l=d+1;for(;l<y;){if(t[l]==="\\"){l+=2;continue}if(t[l]===k||t[l]===`
41
- `){l++;break}l++}u+=b(t.slice(d,l)),d=l;continue}if(k==="`"){let l=d+1,F="`";for(;l<y;){if(t[l]==="\\"){F+=t.slice(l,l+2),l+=2;continue}if(t[l]==="`"){F+="`",l++;break}if(t[l]==="$"&&t[l+1]==="{"){l+=2;const U=l;let C=1;for(;l<y&&C>0;){const p=t[l],_=t[l+1];if(p==="/"&&_==="/"){for(l+=2;l<y&&t[l]!==`
42
- `;)l++;continue}if(p==="/"&&_==="*"){for(l+=2;l<y&&!(t[l]==="*"&&t[l+1]==="/");)l++;l+=2;continue}if(p==="'"||p==='"'){const T=p;for(l++;l<y&&t[l]!==T&&t[l]!==`
43
- `;)t[l]==="\\"?l+=2:l++;l<y&&t[l]===T&&l++;continue}if(p==="`"){l++;let T=0;for(;l<y;){if(t[l]==="\\"){l+=2;continue}if(t[l]==="$"&&t[l+1]==="{"){T++,l+=2;continue}if(t[l]==="}"&&T>0){T--,l++;continue}if(t[l]==="`"&&T===0){l++;break}l++}continue}if(p==="{")C++;else if(p==="}"&&(C--,C===0))break;l++}const w=t.slice(U,l),g=i?pt(w,e,{expressionOnly:!0}):w;F+="${"+g+"}",l<y&&t[l]==="}"&&l++;continue}F+=t[l],l++}u+=b(F),d=l;continue}u+=k,d++}const A=(k,$=",")=>{const l=[];let F="",U=0,C=0,w=0,g=0;for(let p=0;p<k.length;p++){const _=k[p];_==="<"?U++:_===">"&&U>0?U--:_==="("?C++:_===")"&&C>0?C--:_==="{"?w++:_==="}"&&w>0?w--:_==="["?g++:_==="]"&&g>0&&g--,_===$&&U===0&&C===0&&w===0&&g===0?(l.push(F),F=""):F+=_}return l.push(F),l},M=k=>{const $=(k.match(/^\s*/)||[""])[0];let l=k.trim();if(!l)return k;let F=-1,U=-1,C=0,w=0,g=0,p=0;for(let R=0;R<l.length;R++){const N=l[R];if(N==="="&&l[R+1]===">"){R++;continue}if(N==="<")C++;else if(N===">"&&C>0)C--;else if(N==="(")w++;else if(N===")"&&w>0)w--;else if(N==="{")g++;else if(N==="}"&&g>0)g--;else if(N==="[")p++;else if(N==="]"&&p>0)p--;else if(N===":"&&C===0&&w===0&&g===0&&p===0&&F===-1&&U===-1)F=R;else if(N==="="&&C===0&&w===0&&g===0&&p===0&&U===-1){U=R;break}}if(F===-1)return k;let _=l.slice(0,F).trimEnd();_.endsWith("?")&&(_=_.slice(0,-1).trimEnd());const T=U!==-1?" = "+l.slice(U+1).trim():"";return $+_+T};if(i){let _=function(T,R,N){return T.slice(R,N).trim()};u=u.replace(/^\s*(?:export\s+)?declare\s+(?:const|let|var|function|class|type|interface)\s+[^;{}\n]+(?:;|\{[^}]*\})?/gm,"");const k=(T,R)=>{let N=T,L;for(R.lastIndex=0;(L=R.exec(N))!==null;){const O=L.index,B=O+L[0].length-1;let Z=1,V=B+1;for(;V<N.length&&Z>0;)N[V]==="{"?Z++:N[V]==="}"&&Z--,V++;N=N.slice(0,O)+N.slice(V),R.lastIndex=O}return N};u=k(u,/\b(?:export\s+)?interface\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s*<[^{]*>)?(?:\s+extends\s+[^{]+)?\s*\{/g),u=u.replace(/\b(export\s+)?(?:const\s+)?enum\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\{([^}]*)\}/g,(T,R,N,L)=>{const O=L.replace(/\x00__LIT_(\d+)__\x00/g,(re,ue)=>{const ge=m[Number(ue)]||"";return ge.startsWith("//")||ge.startsWith("/*")?"":re}),B=A(O,",").map(re=>re.trim()).filter(Boolean);let Z=0;const V=[];for(const re of B){const ue=re.indexOf("=");if(ue!==-1){const ge=re.slice(0,ue).trim(),Y=re.slice(ue+1).trim(),se=Number(Y);!Number.isNaN(se)&&Y!==""?(V.push(`${N}[${N}[${JSON.stringify(ge)}] = ${se}] = ${JSON.stringify(ge)};`),Z=se+1):V.push(`${N}[${JSON.stringify(ge)}] = ${Y};`)}else V.push(`${N}[${N}[${JSON.stringify(re)}] = ${Z++}] = ${JSON.stringify(re)};`)}return`${R?"export ":""}const ${N} = {}; (function(${N}){ ${V.join(" ")} })(${N});`}),u=u.replace(/^\s*export\s+type\s*\{[\s\S]*?\}(?:\s*from\s*[^\n;]+)?;?/gm,""),u=k(u,/^\s*(?:export\s+)?type\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s*<[^>]*>)?\s*=\s*\{/gm),u=u.replace(/^\s*(?:export\s+)?type\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s*<[^>]*>)?\s*=\s*[^;]+;?/gm,""),u=u.replace(/^\s*import\s+type\s*\{[\s\S]*?\}\s*from\s*[^\n;]+;?/gm,""),u=u.replace(/^\s*import\s+type\s+[^;\n]+;?/gm,""),u=u.replace(/\b(export\s+(?:default\s+)?)?abstract\s+class\b/g,"$1class"),u=u.replace(/^[ \t]*(?:(?:public|private|protected)\s+)?abstract\s+[A-Za-z_$][A-Za-z0-9_$]*\s*(?:<[^>]*>)?\s*\([^)]*\)\s*(?::\s*[^;\n]+)?;/gm,""),u=(T=>{let R=T;const N=/(\b(?:class|function)\s+[A-Za-z_$][A-Za-z0-9_$]*)\s*</g;let L;for(;(L=N.exec(R))!==null;){const O=L.index+L[0].length-1;let B=1,Z=O+1;for(;Z<R.length&&B>0;)R[Z]==="<"?B++:R[Z]===">"&&B--,Z++;B===0&&(R=R.slice(0,O)+R.slice(Z),N.lastIndex=L.index+L[1].length)}return R})(u),u=(T=>{let R=T;const N=/(=\s*(?:async\s+)?|[\s(,]async\s+|\(\s*)</g;let L;for(;(L=N.exec(R))!==null;){const O=L.index+L[0].length-1;let B=1,Z=O+1;for(;Z<R.length&&B>0;)R[Z]==="<"?B++:R[Z]===">"&&B--,Z++;B===0&&R.slice(Z).trimStart().startsWith("(")&&(R=R.slice(0,O)+R.slice(Z),N.lastIndex=L.index+L[1].length)}return R})(u),u=u.replace(/(\bclass\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s+extends\s+[A-Za-z0-9_$.<>]+)?)\s+implements\s+[^{]+(\{)/g,"$1 $2");let F;do F=u,u=u.replace(/(\bextends\s+[A-Za-z_$][A-Za-z0-9_$.]*)\s*<[^<>]*>/g,"$1");while(u!==F);u=(T=>{let R=T;const N=/\bconstructor\s*\(([\s\S]*?)\)\s*\{/g;let L;for(;(L=N.exec(R))!==null;){const O=L[0],B=L[1],Z=L.index,V=Z+O.length-1,re=[],ge=A(B,",").map(ct=>{let We=ct.trim();if(!We)return"";const be=/^(?:(public|private|protected|readonly|override)\s+)+([A-Za-z_$][A-Za-z0-9_$]*)/.exec(We);if(be){const Mt=be[2];re.push(`this.${Mt} = ${Mt};`),We=We.replace(/^(?:(?:public|private|protected|readonly|override)\s+)+/,"")}return M(We).trim()}).filter(Boolean).join(", ");let Y=1,se=V+1;for(;se<R.length&&Y>0;)R[se]==="{"?Y++:R[se]==="}"&&Y--,se++;const K=R.slice(V+1,se-1),Ee=re.join(" ");let De=K;if(re.length>0){const ct=/\bsuper\s*\(/.exec(K);if(ct){let We=1,be=ct.index+ct[0].length;for(;be<K.length&&We>0;)K[be]==="("?We++:K[be]===")"&&We--,be++;K[be]===";"&&be++,De=K.slice(0,be)+"; "+Ee+K.slice(be)}else De=" "+Ee+K}const Pe=`constructor(${ge}) {${De}}`;R=R.slice(0,Z)+Pe+R.slice(se),N.lastIndex=Z+Pe.length}return R})(u),u=u.replace(/^[ \t]*(?:(?:public|private|protected|readonly|override|abstract)\s+)*[A-Za-z_$][A-Za-z0-9_$]*[?!]?\s*:\s*[^=;\n{}]+;[ \t]*$/gm,""),u=u.replace(/^[ \t]*(?:(?:public|private|protected|readonly|override|abstract)\s+)+(?=(?:static\s+|async\s+|get\s+|set\s+)?[A-Za-z_$])/gm," "),u=u.replace(/^[ \t]*static\s+(?:(?:public|private|protected|readonly|override)\s+)+(?=[A-Za-z_$])/gm," static "),u=u.replace(/^([ \t]*(?:static\s+)?[A-Za-z_$][A-Za-z0-9_$]*)[?!]?\s*:\s*(?:[^=\n<>()!]|<[^=\n]*>)+(?<![=!<>])=(?![=>])\s*/gm,"$1 = ");let C;do C=u,u=u.replace(/([A-Za-z0-9_$)\]\x00])!(?!=)/g,"$1");while(u!==C);do C=u,u=u.replace(/(\b[A-Za-z_$][A-Za-z0-9_$.]*)\s*<[^<>()\n]+>\s*\(/g,(T,R)=>["if","for","while","switch","return","typeof","instanceof"].includes(R)?T:`${R}(`);while(u!==C);do C=u,u=u.replace(/^([ \t]*(?:static\s+)?(?:async\s+)?[A-Za-z_$][A-Za-z0-9_$]*)\s*<[^<>()\n]+>\s*\(/gm,"$1(");while(u!==C);u=(T=>{let R="",N=0;for(;N<T.length;){const L=T.indexOf(")",N);if(L===-1){R+=T.slice(N);break}R+=T.slice(N,L+1);let O=L+1;for(;O<T.length&&(T[O]===" "||T[O]===" "||T[O]===`
44
- `||T[O]==="\r");)O++;if(T[O]!==":"){N=L+1;continue}let B=O+1,Z=0,V=0,re=0,ue=0,ge=-1;for(;B<T.length;){const Y=T[B],se=T[B+1];if(Z===0&&V===0&&re===0&&ue===0){if(Y==="="&&se===">"){ge=B;break}if(Y==="{"){let K=1,Ee=B+1;for(;Ee<T.length&&K>0;)T[Ee]==="{"?K++:T[Ee]==="}"&&K--,Ee++;const De=T.slice(Ee).trimStart();if(De.startsWith("{")||De.startsWith("=>")||De.startsWith("|")||De.startsWith("&")||De.startsWith("[")){B=Ee;continue}ge=B;break}if(Y===";"||Y===",")break}if(Y==="="&&se===">"){B+=2;continue}if(Y==="<")Z++;else if(Y===">"&&Z>0)Z--;else if(Y==="(")V++;else if(Y===")"&&V>0){if(V--,V===0&&Z===0&&re===0&&ue===0){let K=B+1;for(;K<T.length&&(T[K]===" "||T[K]===" ");)K++;if(T[K]==="="&&T[K+1]===">"){B=K+2;continue}}}else if(Y==="[")ue++;else if(Y==="]"&&ue>0)ue--;else if(Y==="{")re++;else if(Y==="}")if(re>0)re--;else break;B++}if(ge!==-1){const Y=T.slice(O+1,ge).trim();if(Y.length>0&&!/^[0-9]/.test(Y)){R+=" ",N=ge;continue}}N=L+1}return R})(u);const g=(T,R)=>!R.includes(":")||R.includes("?")&&!/[A-Za-z0-9_$}\]]\s*\?\s*:/.test(R)||/[{}]/.test(R)&&!/\}\s*\??\s*:/.test(R)&&!/:\s*[A-Za-z_$][A-Za-z0-9_$.<>[\]|&\s]*\{/.test(R)&&!A(R,",").every(Z=>{const V=Z.trim();return!V||/^(?:\.\.\.)?[A-Za-z_$][A-Za-z0-9_$]*\s*\??\s*:/.test(V)||/^\{[\s\S]*\}\s*\??\s*:/.test(V)})?T:`(${A(R,",").map(O=>M(O)).join(",")})`;do C=u,u=u.replace(/\(([^()]*)\)/g,g);while(u!==C);u=u.replace(/\(((?:[^()]|\([^()]*\))*)\)/g,g),u=u.replace(/\b(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*:\s*[^=;\n]+(?<![=!<>])=(?![=>])/g,"$1 $2 ="),u=(T=>{let R=T;const N=/(\S)[ \t]+(?:as|satisfies)[ \t]+/g;let L;for(;(L=N.exec(R))!==null;){const O=L[1],B=R.slice(Math.max(0,L.index-30),L.index+1);if(/\b(?:import|export)\b[^;\n]*$/.test(B)||!/[A-Za-z0-9_$)\]}`"'\x00]/.test(O))continue;const Z=L.index+L[0].length;let V=Z,re=0,ue=0,ge=0,Y=0,se=!1;for(;V<R.length;){const K=R[V];if(K==="<"){re++,se=!0,V++;continue}if(K===">"&&re>0){re--,V++;continue}if(K==="{"){ue++,se=!0,V++;continue}if(K==="}"&&ue>0){ue--,V++;continue}if(K==="["){ge++,se=!0,V++;continue}if(K==="]"&&ge>0){ge--,V++;continue}if(K==="("){if(!se){Y++,se=!0,V++;continue}if(re>0||ue>0||ge>0||Y>0){Y++,V++;continue}break}if(K===")"&&Y>0){Y--,V++;continue}if(re===0&&ue===0&&ge===0&&Y===0){if(K===";"||K===","||K===")"||K==="]"||K==="}"||K==="?"||K===":"||K==="=")break;if(K===`
45
- `||K==="\r"){const Ee=R.slice(V).trimStart();if(Ee.startsWith("|")||Ee.startsWith("&")){V++;continue}break}if(K===" "||K===" "){const Ee=R.slice(V).trimStart();if(/^(?:as|satisfies)\b/.test(Ee)||/^[|&]/.test(Ee)||/^readonly\b/.test(_(R,Z,V))){V++;continue}if(se)break}if(/[A-Za-z0-9_$.|&\x00]/.test(K)){se=!0,V++;continue}break}V++}se&&V>Z&&(R=R.slice(0,L.index+1)+R.slice(V),N.lastIndex=L.index)}return R})(u);do C=u,u=u.replace(/([A-Za-z0-9_$)\]\x00])!(?!=)/g,"$1");while(u!==C)}if((a||i)&&!s){u=u.replace(/\bimport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm,"const $1 = require($2);"),u=u.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm,(U,C,w,g)=>{const p=w.split(",").map(T=>T.trim()).filter(T=>T&&!/^type\s+/.test(T)).map(T=>T.replace(/\s+as\s+/g,": ")).join(", "),_=g.trim();return`const ${C} = (function(m){ return m && m.__esModule ? m.default : m; })(require(${_}));`+(p?` const { ${p} } = require(${_});`:"")}),u=u.replace(/\bimport\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm,(U,C,w)=>{const g=C.split(",").map(p=>p.trim()).filter(p=>p&&!/^type\s+/.test(p)).map(p=>p.replace(/\s+as\s+/g,": ")).join(", ");return g?`const { ${g} } = require(${w.trim()});`:""}),u=u.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm,"const $1 = (function(m){ return m && m.__esModule ? m.default : m; })(require($2));"),u=u.replace(/\bimport\s*\(\s*(\x00__LIT_\d+__\x00)\s*\)/g,"Promise.resolve().then(() => require($1))"),u=u.replace(/\bimport\s*(\x00__LIT_\d+__\x00)\s*;?/gm,"require($1);");const k=[];let $=null,l=!1;u=u.replace(/\bexport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm,(U,C,w)=>(l=!0,`exports.${C} = require(${w.trim()});`)),u=u.replace(/\bexport\s*\*\s*from\s*([^\n;]+);?/gm,(U,C)=>(l=!0,`Object.assign(exports, require(${C.trim()}));`));const F=U=>{const C=[],w=U.trim().replace(/^[\[{]|[\]}]$/g,""),g=U.trim().startsWith("{");for(const p of A(w,",")){let _=p.trim();if(!_)continue;if(_.startsWith("..."))_=_.slice(3).trim();else if(g&&_.includes(":")){const R=_.indexOf(":");_=_.slice(R+1).trim()}const T=_.indexOf("=");T!==-1&&(_=_.slice(0,T).trim()),_.startsWith("{")&&_.endsWith("}")||_.startsWith("[")&&_.endsWith("]")?C.push(...F(_)):/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(_)&&C.push(_)}return C};u=u.replace(/\bexport\s+default\s+(async\s+function\s*\*|function\s*\*|async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm,(U,C,w)=>(l=!0,$=w,`${C} ${w}`)),u=u.replace(/\bexport\s+default\s+/gm,()=>(l=!0,"exports.default = ")),u=u.replace(/\bexport\s+(async\s+function\s*\*|function\s*\*|async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm,(U,C,w)=>(l=!0,k.push(w),`${C} ${w}`)),u=u.replace(/\bexport\s+(const|let|var)\s+(\{[^;=\n]+\}|\[[^;=\n]+\])\s*=/gm,(U,C,w)=>(l=!0,k.push(...F(w)),`${C} ${w} =`)),u=u.replace(/\bexport\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm,(U,C,w)=>(l=!0,k.push(w),`${C} ${w}`)),u=u.replace(/\bexport\s*\{([^}]+)\}\s*from\s*([^\n;]+);?/gm,(U,C,w)=>{l=!0;const g=w.trim();return C.split(",").map(p=>{const _=p.trim().replace(/^type\s+/,"");if(!_)return"";const T=_.split(/\s+as\s+/),R=T[0].trim();return`exports.${(T[1]||T[0]).trim()} = require(${g}).${R};`}).join(" ")}),u=u.replace(/\bexport\s*\{([^}]+)\}\s*;?/gm,(U,C)=>(l=!0,C.split(",").map(w=>{const g=w.trim();if(!g||/^type\s+/.test(g))return"";const p=g.split(/\s+as\s+/);if(!p[0])return"";const _=p[0].trim();return`exports.${(p[1]||p[0]).trim()} = ${_};`}).join(" "))),$&&(u+=`
46
- exports.default = ${$};`),k.length>0&&(u+=`
47
- `+k.map(U=>`exports.${U} = ${U};`).join(`
48
- `)),l&&(u+=`
38
+ `)+t);else if(!i&&!a)return t}const p=[],y=k=>{const L=`\0__LIT_${p.length}__\0`;return p.push(k),L},S=k=>{const L=k.trimEnd();if(!L)return!0;const u=L[L.length-1];return"(,=:[!&|?{};+-*/%~^<>".includes(u)?!0:/\b(?:return|throw|case|in|of|typeof|instanceof|void|delete|await|yield)$/.test(L)};let l="",d=0;const m=t.length;for(;d<m;){const k=t[d],L=t[d+1];if(k==="/"&&L==="/"){let u=t.indexOf(`
39
+ `,d+2);u===-1&&(u=m),l+=y(t.slice(d,u)),d=u;continue}if(k==="/"&&L==="*"){let u=t.indexOf("*/",d+2);u===-1?u=m:u+=2,l+=y(t.slice(d,u)),d=u;continue}if(k==="/"&&L!=="/"&&L!=="*"&&L!=="="&&S(l)){let u=d+1,B=!1,F=!1;for(;u<m;){const U=t[u];if(U===`
40
+ `||U==="\r")break;if(U==="\\"){u+=2;continue}if(U==="["){B=!0,u++;continue}if(U==="]"&&B){B=!1,u++;continue}if(U==="/"&&!B){for(F=!0,u++;u<m&&/[dgimsuvy]/.test(t[u]);)u++;break}u++}if(F){l+=y(t.slice(d,u)),d=u;continue}}if(k==="'"||k==='"'){let u=d+1;for(;u<m;){if(t[u]==="\\"){u+=2;continue}if(t[u]===k||t[u]===`
41
+ `){u++;break}u++}l+=y(t.slice(d,u)),d=u;continue}if(k==="`"){let u=d+1,B="`";for(;u<m;){if(t[u]==="\\"){B+=t.slice(u,u+2),u+=2;continue}if(t[u]==="`"){B+="`",u++;break}if(t[u]==="$"&&t[u+1]==="{"){u+=2;const F=u;let U=1;for(;u<m&&U>0;){const g=t[u],x=t[u+1];if(g==="/"&&x==="/"){for(u+=2;u<m&&t[u]!==`
42
+ `;)u++;continue}if(g==="/"&&x==="*"){for(u+=2;u<m&&!(t[u]==="*"&&t[u+1]==="/");)u++;u+=2;continue}if(g==="'"||g==='"'){const R=g;for(u++;u<m&&t[u]!==R&&t[u]!==`
43
+ `;)t[u]==="\\"?u+=2:u++;u<m&&t[u]===R&&u++;continue}if(g==="`"){u++;let R=0;for(;u<m;){if(t[u]==="\\"){u+=2;continue}if(t[u]==="$"&&t[u+1]==="{"){R++,u+=2;continue}if(t[u]==="}"&&R>0){R--,u++;continue}if(t[u]==="`"&&R===0){u++;break}u++}continue}if(g==="{")U++;else if(g==="}"&&(U--,U===0))break;u++}const b=t.slice(F,u),w=i?pt(b,e,{expressionOnly:!0}):b;B+="${"+w+"}",u<m&&t[u]==="}"&&u++;continue}B+=t[u],u++}l+=y(B),d=u;continue}l+=k,d++}const A=(k,L=",")=>{const u=[];let B="",F=0,U=0,b=0,w=0;for(let g=0;g<k.length;g++){const x=k[g];x==="<"?F++:x===">"&&F>0?F--:x==="("?U++:x===")"&&U>0?U--:x==="{"?b++:x==="}"&&b>0?b--:x==="["?w++:x==="]"&&w>0&&w--,x===L&&F===0&&U===0&&b===0&&w===0?(u.push(B),B=""):B+=x}return u.push(B),u},N=k=>{const L=(k.match(/^\s*/)||[""])[0];let u=k.trim();if(!u)return k;let B=-1,F=-1,U=0,b=0,w=0,g=0;for(let T=0;T<u.length;T++){const v=u[T];if(v==="="&&u[T+1]===">"){T++;continue}if(v==="<")U++;else if(v===">"&&U>0)U--;else if(v==="(")b++;else if(v===")"&&b>0)b--;else if(v==="{")w++;else if(v==="}"&&w>0)w--;else if(v==="[")g++;else if(v==="]"&&g>0)g--;else if(v===":"&&U===0&&b===0&&w===0&&g===0&&B===-1&&F===-1)B=T;else if(v==="="&&U===0&&b===0&&w===0&&g===0&&F===-1){F=T;break}}if(B===-1)return k;let x=u.slice(0,B).trimEnd();x.endsWith("?")&&(x=x.slice(0,-1).trimEnd());const R=F!==-1?" = "+u.slice(F+1).trim():"";return L+x+R};if(i){let x=function(R,T,v){return R.slice(T,v).trim()};l=l.replace(/^\s*(?:export\s+)?declare\s+(?:const|let|var|function|class|type|interface)\s+[^;{}\n]+(?:;|\{[^}]*\})?/gm,"");const k=(R,T)=>{let v=R,$;for(T.lastIndex=0;($=T.exec(v))!==null;){const j=$.index,C=j+$[0].length-1;let z=1,Z=C+1;for(;Z<v.length&&z>0;)v[Z]==="{"?z++:v[Z]==="}"&&z--,Z++;v=v.slice(0,j)+v.slice(Z),T.lastIndex=j}return v};l=k(l,/\b(?:export\s+)?interface\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s*<[^{]*>)?(?:\s+extends\s+[^{]+)?\s*\{/g),l=l.replace(/\b(export\s+)?(?:const\s+)?enum\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\{([^}]*)\}/g,(R,T,v,$)=>{const j=$.replace(/\x00__LIT_(\d+)__\x00/g,(Q,le)=>{const de=p[Number(le)]||"";return de.startsWith("//")||de.startsWith("/*")?"":Q}),C=A(j,",").map(Q=>Q.trim()).filter(Boolean);let z=0;const Z=[];for(const Q of C){const le=Q.indexOf("=");if(le!==-1){const de=Q.slice(0,le).trim(),Y=Q.slice(le+1).trim(),ee=Number(Y);!Number.isNaN(ee)&&Y!==""?(Z.push(`${v}[${v}[${JSON.stringify(de)}] = ${ee}] = ${JSON.stringify(de)};`),z=ee+1):Z.push(`${v}[${JSON.stringify(de)}] = ${Y};`)}else Z.push(`${v}[${v}[${JSON.stringify(Q)}] = ${z++}] = ${JSON.stringify(Q)};`)}return`${T?"export ":""}const ${v} = {}; (function(${v}){ ${Z.join(" ")} })(${v});`}),l=l.replace(/^\s*export\s+type\s*\{[\s\S]*?\}(?:\s*from\s*[^\n;]+)?;?/gm,""),l=k(l,/^\s*(?:export\s+)?type\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s*<[^>]*>)?\s*=\s*\{/gm),l=l.replace(/^\s*(?:export\s+)?type\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s*<[^>]*>)?\s*=\s*[^;]+;?/gm,""),l=l.replace(/^\s*import\s+type\s*\{[\s\S]*?\}\s*from\s*[^\n;]+;?/gm,""),l=l.replace(/^\s*import\s+type\s+[^;\n]+;?/gm,""),l=l.replace(/\b(export\s+(?:default\s+)?)?abstract\s+class\b/g,"$1class"),l=l.replace(/^[ \t]*(?:(?:public|private|protected)\s+)?abstract\s+[A-Za-z_$][A-Za-z0-9_$]*\s*(?:<[^>]*>)?\s*\([^)]*\)\s*(?::\s*[^;\n]+)?;/gm,""),l=(R=>{let T=R;const v=/(\b(?:class|function)\s+[A-Za-z_$][A-Za-z0-9_$]*)\s*</g;let $;for(;($=v.exec(T))!==null;){const j=$.index+$[0].length-1;let C=1,z=j+1;for(;z<T.length&&C>0;)T[z]==="<"?C++:T[z]===">"&&C--,z++;C===0&&(T=T.slice(0,j)+T.slice(z),v.lastIndex=$.index+$[1].length)}return T})(l),l=(R=>{let T=R;const v=/(=\s*(?:async\s+)?|[\s(,]async\s+|\(\s*)</g;let $;for(;($=v.exec(T))!==null;){const j=$.index+$[0].length-1;let C=1,z=j+1;for(;z<T.length&&C>0;)T[z]==="<"?C++:T[z]===">"&&C--,z++;C===0&&T.slice(z).trimStart().startsWith("(")&&(T=T.slice(0,j)+T.slice(z),v.lastIndex=$.index+$[1].length)}return T})(l),l=l.replace(/(\bclass\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s+extends\s+[A-Za-z0-9_$.<>]+)?)\s+implements\s+[^{]+(\{)/g,"$1 $2");let B;do B=l,l=l.replace(/(\bextends\s+[A-Za-z_$][A-Za-z0-9_$.]*)\s*<[^<>]*>/g,"$1");while(l!==B);l=(R=>{let T=R;const v=/\bconstructor\s*\(([\s\S]*?)\)\s*\{/g;let $;for(;($=v.exec(T))!==null;){const j=$[0],C=$[1],z=$.index,Z=z+j.length-1,Q=[],de=A(C,",").map(ct=>{let Oe=ct.trim();if(!Oe)return"";const _e=/^(?:(public|private|protected|readonly|override)\s+)+([A-Za-z_$][A-Za-z0-9_$]*)/.exec(Oe);if(_e){const Mt=_e[2];Q.push(`this.${Mt} = ${Mt};`),Oe=Oe.replace(/^(?:(?:public|private|protected|readonly|override)\s+)+/,"")}return N(Oe).trim()}).filter(Boolean).join(", ");let Y=1,ee=Z+1;for(;ee<T.length&&Y>0;)T[ee]==="{"?Y++:T[ee]==="}"&&Y--,ee++;const K=T.slice(Z+1,ee-1),be=Q.join(" ");let Me=K;if(Q.length>0){const ct=/\bsuper\s*\(/.exec(K);if(ct){let Oe=1,_e=ct.index+ct[0].length;for(;_e<K.length&&Oe>0;)K[_e]==="("?Oe++:K[_e]===")"&&Oe--,_e++;K[_e]===";"&&_e++,Me=K.slice(0,_e)+"; "+be+K.slice(_e)}else Me=" "+be+K}const Ce=`constructor(${de}) {${Me}}`;T=T.slice(0,z)+Ce+T.slice(ee),v.lastIndex=z+Ce.length}return T})(l),l=l.replace(/^[ \t]*(?:(?:public|private|protected|readonly|override|abstract)\s+)*[A-Za-z_$][A-Za-z0-9_$]*[?!]?\s*:\s*[^=;\n{}]+;[ \t]*$/gm,""),l=l.replace(/^[ \t]*(?:(?:public|private|protected|readonly|override|abstract)\s+)+(?=(?:static\s+|async\s+|get\s+|set\s+)?[A-Za-z_$])/gm," "),l=l.replace(/^[ \t]*static\s+(?:(?:public|private|protected|readonly|override)\s+)+(?=[A-Za-z_$])/gm," static "),l=l.replace(/^([ \t]*(?:static\s+)?[A-Za-z_$][A-Za-z0-9_$]*)[?!]?\s*:\s*(?:[^=\n<>()!]|<[^=\n]*>)+(?<![=!<>])=(?![=>])\s*/gm,"$1 = ");let U;do U=l,l=l.replace(/([A-Za-z0-9_$)\]\x00])!(?!=)/g,"$1");while(l!==U);do U=l,l=l.replace(/(\b[A-Za-z_$][A-Za-z0-9_$.]*)\s*<[^<>()\n]+>\s*\(/g,(R,T)=>["if","for","while","switch","return","typeof","instanceof"].includes(T)?R:`${T}(`);while(l!==U);do U=l,l=l.replace(/^([ \t]*(?:static\s+)?(?:async\s+)?[A-Za-z_$][A-Za-z0-9_$]*)\s*<[^<>()\n]+>\s*\(/gm,"$1(");while(l!==U);l=(R=>{let T="",v=0;for(;v<R.length;){const $=R.indexOf(")",v);if($===-1){T+=R.slice(v);break}T+=R.slice(v,$+1);let j=$+1;for(;j<R.length&&(R[j]===" "||R[j]===" "||R[j]===`
44
+ `||R[j]==="\r");)j++;if(R[j]!==":"){v=$+1;continue}let C=j+1,z=0,Z=0,Q=0,le=0,de=-1;for(;C<R.length;){const Y=R[C],ee=R[C+1];if(z===0&&Z===0&&Q===0&&le===0){if(Y==="="&&ee===">"){de=C;break}if(Y==="{"){let K=1,be=C+1;for(;be<R.length&&K>0;)R[be]==="{"?K++:R[be]==="}"&&K--,be++;const Me=R.slice(be).trimStart();if(Me.startsWith("{")||Me.startsWith("=>")||Me.startsWith("|")||Me.startsWith("&")||Me.startsWith("[")){C=be;continue}de=C;break}if(Y===";"||Y===",")break}if(Y==="="&&ee===">"){C+=2;continue}if(Y==="<")z++;else if(Y===">"&&z>0)z--;else if(Y==="(")Z++;else if(Y===")"&&Z>0){if(Z--,Z===0&&z===0&&Q===0&&le===0){let K=C+1;for(;K<R.length&&(R[K]===" "||R[K]===" ");)K++;if(R[K]==="="&&R[K+1]===">"){C=K+2;continue}}}else if(Y==="[")le++;else if(Y==="]"&&le>0)le--;else if(Y==="{")Q++;else if(Y==="}")if(Q>0)Q--;else break;C++}if(de!==-1){const Y=R.slice(j+1,de).trim();if(Y.length>0&&!/^[0-9]/.test(Y)){T+=" ",v=de;continue}}v=$+1}return T})(l);const w=(R,T)=>!T.includes(":")||T.includes("?")&&!/[A-Za-z0-9_$}\]]\s*\?\s*:/.test(T)||/[{}]/.test(T)&&!/\}\s*\??\s*:/.test(T)&&!/:\s*[A-Za-z_$][A-Za-z0-9_$.<>[\]|&\s]*\{/.test(T)&&!A(T,",").every(z=>{const Z=z.trim();return!Z||/^(?:\.\.\.)?[A-Za-z_$][A-Za-z0-9_$]*\s*\??\s*:/.test(Z)||/^\{[\s\S]*\}\s*\??\s*:/.test(Z)})?R:`(${A(T,",").map(j=>N(j)).join(",")})`;do U=l,l=l.replace(/\(([^()]*)\)/g,w);while(l!==U);l=l.replace(/\(((?:[^()]|\([^()]*\))*)\)/g,w),l=l.replace(/\b(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*:\s*[^=;\n]+(?<![=!<>])=(?![=>])/g,"$1 $2 ="),l=(R=>{let T=R;const v=/(\S)[ \t]+(?:as|satisfies)[ \t]+/g;let $;for(;($=v.exec(T))!==null;){const j=$[1],C=T.slice(Math.max(0,$.index-30),$.index+1);if(/\b(?:import|export)\b[^;\n]*$/.test(C)||!/[A-Za-z0-9_$)\]}`"'\x00]/.test(j))continue;const z=$.index+$[0].length;let Z=z,Q=0,le=0,de=0,Y=0,ee=!1;for(;Z<T.length;){const K=T[Z];if(K==="<"){Q++,ee=!0,Z++;continue}if(K===">"&&Q>0){Q--,Z++;continue}if(K==="{"){le++,ee=!0,Z++;continue}if(K==="}"&&le>0){le--,Z++;continue}if(K==="["){de++,ee=!0,Z++;continue}if(K==="]"&&de>0){de--,Z++;continue}if(K==="("){if(!ee){Y++,ee=!0,Z++;continue}if(Q>0||le>0||de>0||Y>0){Y++,Z++;continue}break}if(K===")"&&Y>0){Y--,Z++;continue}if(Q===0&&le===0&&de===0&&Y===0){if(K===";"||K===","||K===")"||K==="]"||K==="}"||K==="?"||K===":"||K==="=")break;if(K===`
45
+ `||K==="\r"){const be=T.slice(Z).trimStart();if(be.startsWith("|")||be.startsWith("&")){Z++;continue}break}if(K===" "||K===" "){const be=T.slice(Z).trimStart();if(/^(?:as|satisfies)\b/.test(be)||/^[|&]/.test(be)||/^readonly\b/.test(x(T,z,Z))){Z++;continue}if(ee)break}if(/[A-Za-z0-9_$.|&\x00]/.test(K)){ee=!0,Z++;continue}break}Z++}ee&&Z>z&&(T=T.slice(0,$.index+1)+T.slice(Z),v.lastIndex=$.index)}return T})(l);do U=l,l=l.replace(/([A-Za-z0-9_$)\]\x00])!(?!=)/g,"$1");while(l!==U)}if((a||i)&&!s){l=l.replace(/\bimport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm,"const $1 = require($2);"),l=l.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm,(F,U,b,w)=>{const g=b.split(",").map(R=>R.trim()).filter(R=>R&&!/^type\s+/.test(R)).map(R=>R.replace(/\s+as\s+/g,": ")).join(", "),x=w.trim();return`const ${U} = (function(m){ return m && m.__esModule ? m.default : m; })(require(${x}));`+(g?` const { ${g} } = require(${x});`:"")}),l=l.replace(/\bimport\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm,(F,U,b)=>{const w=U.split(",").map(g=>g.trim()).filter(g=>g&&!/^type\s+/.test(g)).map(g=>g.replace(/\s+as\s+/g,": ")).join(", ");return w?`const { ${w} } = require(${b.trim()});`:""}),l=l.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm,"const $1 = (function(m){ return m && m.__esModule ? m.default : m; })(require($2));"),l=l.replace(/\bimport\s*\(\s*(\x00__LIT_\d+__\x00)\s*\)/g,"Promise.resolve().then(() => require($1))"),l=l.replace(/\bimport\s*(\x00__LIT_\d+__\x00)\s*;?/gm,"require($1);");const k=[];let L=null,u=!1;l=l.replace(/\bexport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm,(F,U,b)=>(u=!0,`exports.${U} = require(${b.trim()});`)),l=l.replace(/\bexport\s*\*\s*from\s*([^\n;]+);?/gm,(F,U)=>(u=!0,`Object.assign(exports, require(${U.trim()}));`));const B=F=>{const U=[],b=F.trim().replace(/^[\[{]|[\]}]$/g,""),w=F.trim().startsWith("{");for(const g of A(b,",")){let x=g.trim();if(!x)continue;if(x.startsWith("..."))x=x.slice(3).trim();else if(w&&x.includes(":")){const T=x.indexOf(":");x=x.slice(T+1).trim()}const R=x.indexOf("=");R!==-1&&(x=x.slice(0,R).trim()),x.startsWith("{")&&x.endsWith("}")||x.startsWith("[")&&x.endsWith("]")?U.push(...B(x)):/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(x)&&U.push(x)}return U};l=l.replace(/\bexport\s+default\s+(async\s+function\s*\*|function\s*\*|async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm,(F,U,b)=>(u=!0,L=b,`${U} ${b}`)),l=l.replace(/\bexport\s+default\s+/gm,()=>(u=!0,"exports.default = ")),l=l.replace(/\bexport\s+(async\s+function\s*\*|function\s*\*|async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm,(F,U,b)=>(u=!0,k.push(b),`${U} ${b}`)),l=l.replace(/\bexport\s+(const|let|var)\s+(\{[^;=\n]+\}|\[[^;=\n]+\])\s*=/gm,(F,U,b)=>(u=!0,k.push(...B(b)),`${U} ${b} =`)),l=l.replace(/\bexport\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm,(F,U,b)=>(u=!0,k.push(b),`${U} ${b}`)),l=l.replace(/\bexport\s*\{([^}]+)\}\s*from\s*([^\n;]+);?/gm,(F,U,b)=>{u=!0;const w=b.trim();return U.split(",").map(g=>{const x=g.trim().replace(/^type\s+/,"");if(!x)return"";const R=x.split(/\s+as\s+/),T=R[0].trim();return`exports.${(R[1]||R[0]).trim()} = require(${w}).${T};`}).join(" ")}),l=l.replace(/\bexport\s*\{([^}]+)\}\s*;?/gm,(F,U)=>(u=!0,U.split(",").map(b=>{const w=b.trim();if(!w||/^type\s+/.test(w))return"";const g=w.split(/\s+as\s+/);if(!g[0])return"";const x=g[0].trim();return`exports.${(g[1]||g[0]).trim()} = ${x};`}).join(" "))),L&&(l+=`
46
+ exports.default = ${L};`),k.length>0&&(l+=`
47
+ `+k.map(F=>`exports.${F} = ${F};`).join(`
48
+ `)),u&&(l+=`
49
49
  Object.defineProperty(exports, "__esModule", { value: true, enumerable: false, configurable: true });
50
50
  if (Object.prototype.hasOwnProperty.call(exports, "default") && module.exports === exports) {
51
51
  if ((typeof exports.default === "object" && exports.default !== null) || typeof exports.default === "function") {
@@ -54,76 +54,76 @@ if (Object.prototype.hasOwnProperty.call(exports, "default") && module.exports =
54
54
  } else if (Object.keys(exports).every((k) => k === "default")) {
55
55
  module.exports = exports.default;
56
56
  }
57
- }`)}return u=u.replace(/\x00__LIT_(\d+)__\x00/g,(k,$)=>m[Number($)]),u}function gr(t){let e=t;return e=e.replace(/const\s+test\s*=\s*\(\s*name\s*,\s*fn\s*\)\s*=>\s*tests\.push\(\s*\{\s*name\s*,\s*fn\s*\}\s*\)\s*;/g,'const test = (name, fn) => { if (typeof __shouldSkipTest === "function" && __shouldSkipTest(name)) return; fn = typeof __wrapTestFn === "function" ? __wrapTestFn(name, fn) : fn; return tests.push({ name, fn }); };'),e=e.replace(/function\s+test\s*\(\s*name\s*,\s*fn\s*\)\s*\{/g,'function test(name, fn) { if (typeof __shouldSkipTest === "function" && __shouldSkipTest(name)) return; fn = typeof __wrapTestFn === "function" ? __wrapTestFn(name, fn) : fn;'),e}class Wn extends Error{constructor(e){super(`process.exit(${e})`),this.name="ProcessExitSignal",this.exitCode=e,this._isProcessExit=!0}}const On=new Map,_n=new Map;async function br(t={},e=null,r=null){const s=x=>!!x&&typeof x!="function"&&typeof x.has=="function"&&typeof x.get=="function";let n=null,i=On;typeof e=="function"?n=e:s(e)&&(i=e),typeof r=="function"?n=n||r:s(r)&&(i=r);const a=new Set,f=new Set(["fs","fs/promises","path","os","crypto","zlib","http","https","net","dns","dns/promises","string_decoder","child_process","process","assert","assert/strict","events","util","util/types","url","querystring","stream","stream/promises","stream/web","stream/consumers","test","perf_hooks","timers","timers/promises","buffer","tty","tls","dgram","readline","readline/promises","async_hooks","worker_threads","v8","vm","module","constants","domain","diagnostics_channel","http2","cluster","repl","inspector","trace_events","wasi","console","bun","bun:test","bun:sqlite"]);function m(x){if(!x||typeof x!="string")return;const u=x.trim();if(!u||u.startsWith(".")||u.startsWith("/")||u.startsWith("node:")||u.startsWith("bun:"))return;const d=u.split("/"),y=u.startsWith("@")?d.slice(0,2).join("/"):d[0];f.has(y)||f.has(u)||a.add(y)}for(const[x,u]of Object.entries(t||{})){if(typeof u!="string")continue;if(x.endsWith("package.json")){try{const M=JSON.parse(u);for(const k of Object.keys(M.dependencies||{}))m(k)}catch(M){j.debug("preloadNpmPackages invalid package.json",M)}continue}const d=/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g,y=/\bfrom\s+['"]([^'"]+)['"]/g;let A;for(;(A=d.exec(u))!==null;)m(A[1]);for(;(A=y.exec(u))!==null;)m(A[1])}if(typeof fetch=="function"){let x=0;for(;x<6;){const u=[];for(const d of a)_n.has(d)||u.push(d);if(u.length===0)break;x++,await Promise.all(u.map(async d=>{let y=[];try{const A=await fetch(`https://cdn.jsdelivr.net/npm/${d}/package.json`);if(A&&A.ok){const M=await A.json();y=Object.keys(M&&M.dependencies||{})}}catch(A){j.debug("preloadNpmPackages metadata fetch failed",{pkg:d,err:A})}_n.set(d,y)}));for(const d of u)for(const y of _n.get(d)||[])m(y)}}const b={};for(const x of a){const u=`node_modules/${x}/index.js`;if(!(t[u]||t[`/workspace/${u}`])){if(i.has(x)){b[x]=i.get(x);continue}if(typeof n=="function")try{n(x)}catch(d){j.debug("preloadNpmPackages onProgress callback failed",d)}if(typeof fetch=="function")try{const d=await fetch(`https://cdn.jsdelivr.net/npm/${x}`);if(d&&d.ok){const y=await d.text();typeof i.set=="function"&&i.set(x,y),b[x]=y}}catch(d){j.debug("preloadNpmPackages package fetch failed",{pkg:x,err:d})}}}return b}class _r extends Error{constructor(e){super(`WASI proc_exit(${e})`),this.name="WasiExitSignal",this.code=Number(e)||0,this._isWasiExit=!0}}function wn(t={}){class e{constructor(n={}){const i=Object.assign({},t,n);this.args=Array.isArray(i.args)?i.args.map(String):["wasm"],this.env=i.env&&typeof i.env=="object"?Object.assign({},i.env):{},this.preopens=i.preopens&&typeof i.preopens=="object"?Object.assign({},i.preopens):{".":"/workspace","/workspace":"/workspace","/usr":"/usr","/tmp":"/tmp","/":"/"},this.returnOnExit=i.returnOnExit!==!1,this.vfs=i.vfs||Dt(),this.onStdout=typeof i.onStdout=="function"?i.onStdout:null,this.onStderr=typeof i.onStderr=="function"?i.onStderr:null;const a=i.stdin!==void 0?i.stdin:"";this._stdinBytes=typeof a=="string"?ne(a):a instanceof Uint8Array?a:new Uint8Array(0),this._stdinPos=0,this.memory=i.memory||null,this._fds=new Map,this._nextFd=3,this._fds.set(0,{type:"stdio",path:"/dev/stdin",isDir:!1,preopen:null,vfsFd:null}),this._fds.set(1,{type:"stdio",path:"/dev/stdout",isDir:!1,preopen:null,vfsFd:null}),this._fds.set(2,{type:"stdio",path:"/dev/stderr",isDir:!1,preopen:null,vfsFd:null});for(const[f,m]of Object.entries(this.preopens)){const b=String(m||"/");try{this.vfs.existsSync(b)||this.vfs.mkdirSync(b,{recursive:!0})}catch(u){j.debug("WASI preopen mkdir skipped",u)}const x=this._nextFd++;this._fds.set(x,{type:"preopen",path:b,isDir:!0,preopen:String(f),vfsFd:null})}this.wasiImport=this._createImports()}_getMem(n){const i=n&&n.exports&&n.exports.memory||this.memory;if(!i)throw new Error("WASI instance does not export WebAssembly.Memory");return{bytes:new Uint8Array(i.buffer),view:new DataView(i.buffer)}}_mapFsError(n){const i=n&&n.code;return i==="ENOENT"?44:i==="EBADF"?8:i==="EEXIST"?20:i==="EINVAL"?28:i==="EISDIR"?31:i==="ENOTDIR"?54:i==="ENOTEMPTY"?55:i==="EPERM"||i==="EACCES"?63:29}_resolveAt(n,i){const a=this._fds.get(n);if(!a||!a.isDir)return{err:8,path:null};const f=String(i||"").replace(/\0+$/,"");return!f||f==="."?{err:0,path:a.path}:f.startsWith("/")?{err:0,path:J.resolve("/",f)}:{err:0,path:J.resolve(a.path,f)}}_writeFilestat(n,i,a,f){n.setBigUint64(i+0,1n,!0),n.setBigUint64(i+8,BigInt(a&&a.ino?a.ino:1),!0),n.setUint8(i+16,f?3:4);for(let b=17;b<24;b++)n.setUint8(i+b,0);n.setBigUint64(i+24,1n,!0),n.setBigUint64(i+32,BigInt(a&&a.size?a.size:0),!0);const m=BigInt(Math.floor(a&&a.mtimeMs||Date.now()))*1000000n;n.setBigUint64(i+40,m,!0),n.setBigUint64(i+48,m,!0),n.setBigUint64(i+56,m,!0)}_createImports(){const n=this;return{args_sizes_get(i,a){const{view:f}=n._getMem();let m=0;for(const b of n.args)m+=ne(b).byteLength+1;return f.setUint32(i,n.args.length,!0),f.setUint32(a,m,!0),0},args_get(i,a){const{bytes:f,view:m}=n._getMem();let b=a;for(let x=0;x<n.args.length;x++){m.setUint32(i+x*4,b,!0);const u=ne(n.args[x]);f.set(u,b),f[b+u.byteLength]=0,b+=u.byteLength+1}return 0},environ_sizes_get(i,a){const{view:f}=n._getMem(),m=Object.entries(n.env);let b=0;for(const[x,u]of m)b+=ne(`${x}=${u}`).byteLength+1;return f.setUint32(i,m.length,!0),f.setUint32(a,b,!0),0},environ_get(i,a){const{bytes:f,view:m}=n._getMem(),b=Object.entries(n.env);let x=a;for(let u=0;u<b.length;u++){m.setUint32(i+u*4,x,!0);const d=ne(`${b[u][0]}=${b[u][1]}`);f.set(d,x),f[x+d.byteLength]=0,x+=d.byteLength+1}return 0},clock_res_get(i,a){const{view:f}=n._getMem();return f.setBigUint64(a,1000n,!0),0},clock_time_get(i,a,f){const{view:m}=n._getMem(),b=i===0?Date.now():performance.now();return m.setBigUint64(f,BigInt(Math.round(b*1e6)),!0),0},fd_advise(){return 0},fd_allocate(i,a,f){const m=n._fds.get(i);if(!m||m.isDir||m.vfsFd===null)return 8;try{const b=n.vfs.fstatSync(m.vfsFd),x=Number(a)+Number(f);return x>b.size&&n.vfs.truncateSync(m.path,x),0}catch(b){return n._mapFsError(b)}},fd_close(i){const a=n._fds.get(i);if(!a)return 8;if(a.type==="stdio")return 0;if(a.vfsFd!==null)try{n.vfs.closeSync(a.vfsFd)}catch(f){j.debug("WASI fd_close vfs error",f)}return n._fds.delete(i),0},fd_datasync(){return 0},fd_sync(){return 0},fd_fdstat_get(i,a){const f=n._fds.get(i);if(!f)return 8;const{view:m}=n._getMem(),b=f.type==="stdio"?2:f.isDir?3:4;return m.setUint8(a+0,b),m.setUint8(a+1,0),m.setUint16(a+2,f.fdflags||0,!0),m.setUint32(a+4,0,!0),m.setBigUint64(a+8,0xffffffffffffffffn,!0),m.setBigUint64(a+16,0xffffffffffffffffn,!0),0},fd_fdstat_set_flags(i,a){const f=n._fds.get(i);return f?(f.fdflags=a,0):8},fd_fdstat_set_rights(){return 0},fd_filestat_get(i,a){const f=n._fds.get(i);if(!f)return 8;const{view:m}=n._getMem();if(f.type==="stdio")return n._writeFilestat(m,a,{ino:i+1,size:0,mtimeMs:Date.now()},!1),m.setUint8(a+16,2),0;try{const b=n.vfs.statSync(f.path);return n._writeFilestat(m,a,b,b.isDirectory()),0}catch(b){return n._mapFsError(b)}},fd_filestat_set_size(i,a){const f=n._fds.get(i);if(!f||f.isDir)return 8;try{return n.vfs.truncateSync(f.path,Number(a)),0}catch(m){return n._mapFsError(m)}},fd_filestat_set_times(){return 0},fd_prestat_get(i,a){const f=n._fds.get(i);if(!f||f.type!=="preopen")return 8;const{view:m}=n._getMem(),b=ne(f.preopen);return m.setUint8(a+0,0),m.setUint32(a+4,b.byteLength,!0),0},fd_prestat_dir_name(i,a,f){const m=n._fds.get(i);if(!m||m.type!=="preopen")return 8;const{bytes:b}=n._getMem(),x=ne(m.preopen);return b.set(x.subarray(0,f),a),0},fd_read(i,a,f,m){const b=n._fds.get(i);if(!b)return 8;const{bytes:x,view:u}=n._getMem();let d=0;if(i===0){for(let y=0;y<f;y++){const A=u.getUint32(a+y*8,!0),M=u.getUint32(a+y*8+4,!0);if(M<=0)continue;const k=Math.min(M,n._stdinBytes.byteLength-n._stdinPos);if(k>0&&(x.set(n._stdinBytes.subarray(n._stdinPos,n._stdinPos+k),A),n._stdinPos+=k,d+=k),k<M)break}return u.setUint32(m,d,!0),0}if(b.isDir||b.vfsFd===null)return 8;try{for(let y=0;y<f;y++){const A=u.getUint32(a+y*8,!0),M=u.getUint32(a+y*8+4,!0);if(M<=0)continue;const k=n.vfs.readSync(b.vfsFd,x,A,M,null);if(d+=k,k<M)break}return u.setUint32(m,d,!0),0}catch(y){return n._mapFsError(y)}},fd_pread(i,a,f,m,b){const x=n._fds.get(i);if(!x||x.isDir||x.vfsFd===null)return 8;const{bytes:u,view:d}=n._getMem();let y=Number(m),A=0;try{for(let M=0;M<f;M++){const k=d.getUint32(a+M*8,!0),$=d.getUint32(a+M*8+4,!0);if($<=0)continue;const l=n.vfs.readSync(x.vfsFd,u,k,$,y);if(y+=l,A+=l,l<$)break}return d.setUint32(b,A,!0),0}catch(M){return n._mapFsError(M)}},fd_write(i,a,f,m){const b=n._fds.get(i);if(!b)return 8;const{bytes:x,view:u}=n._getMem();let d=0;if(i===1||i===2){const y=[];for(let A=0;A<f;A++){const M=u.getUint32(a+A*8,!0),k=u.getUint32(a+A*8+4,!0);k>0&&(y.push(x.subarray(M,M+k)),d+=k)}if(d>0){const A=new Uint8Array(d);let M=0;for(const $ of y)A.set($,M),M+=$.byteLength;const k=Q(A);i===1&&n.onStdout?n.onStdout(k):i===2&&n.onStderr&&n.onStderr(k)}return u.setUint32(m,d,!0),0}if(b.isDir||b.vfsFd===null)return 8;try{for(let y=0;y<f;y++){const A=u.getUint32(a+y*8,!0),M=u.getUint32(a+y*8+4,!0);if(M<=0)continue;const k=n.vfs.writeSync(b.vfsFd,x,A,M);d+=k}return u.setUint32(m,d,!0),0}catch(y){return n._mapFsError(y)}},fd_pwrite(i,a,f,m,b){const x=n._fds.get(i);if(!x||x.isDir||x.vfsFd===null)return 8;const{bytes:u,view:d}=n._getMem();let y=Number(m),A=0;try{for(let M=0;M<f;M++){const k=d.getUint32(a+M*8,!0),$=d.getUint32(a+M*8+4,!0);if($<=0)continue;const l=n.vfs.writeSync(x.vfsFd,u,k,$,y);y+=l,A+=l}return d.setUint32(b,A,!0),0}catch(M){return n._mapFsError(M)}},fd_seek(i,a,f,m){const b=n._fds.get(i);if(!b||b.isDir||b.vfsFd===null)return 8;const{view:x}=n._getMem();try{const u=n.vfs.lseekSync(b.vfsFd,Number(a),Number(f));return x.setBigUint64(m,BigInt(u),!0),0}catch(u){return n._mapFsError(u)}},fd_tell(i,a){const f=n._fds.get(i);if(!f||f.isDir||f.vfsFd===null)return 8;const{view:m}=n._getMem();try{const b=n.vfs.tellSync(f.vfsFd);return m.setBigUint64(a,BigInt(b),!0),0}catch(b){return n._mapFsError(b)}},fd_renumber(i,a){const f=n._fds.get(i);if(!f)return 8;const m=n._fds.get(a);if(m&&m.vfsFd!==null)try{n.vfs.closeSync(m.vfsFd)}catch(b){j.debug("WASI fd_renumber close error",b)}return n._fds.set(a,f),n._fds.delete(i),0},fd_readdir(i,a,f,m,b){const x=n._fds.get(i);if(!x||!x.isDir)return 8;const{bytes:u,view:d}=n._getMem();try{const y=[".","..",...n.vfs.readdirSync(x.path)];let A=0;const M=Number(m);for(let k=M;k<y.length;k++){const $=y[k],l=ne($),F=$==="."||$===".."?x.path:J.resolve(x.path,$);let U=!0,C=1;try{const _=n.vfs.statSync(F);U=_.isDirectory(),C=_.ino||1}catch(_){j.debug("WASI fd_readdir stat skipped",_)}const w=24,g=w+l.byteLength;if(A+w>f)break;d.setBigUint64(a+A+0,BigInt(k+1),!0),d.setBigUint64(a+A+8,BigInt(C),!0),d.setUint32(a+A+16,l.byteLength,!0),d.setUint8(a+A+20,U?3:4);const p=Math.min(l.byteLength,f-(A+w));if(u.set(l.subarray(0,p),a+A+w),A+=w+p,p<l.byteLength)break}return d.setUint32(b,A,!0),0}catch(y){return n._mapFsError(y)}},path_create_directory(i,a,f){const{bytes:m}=n._getMem(),b=Q(m.subarray(a,a+f)),x=n._resolveAt(i,b);if(x.err)return x.err;try{return n.vfs.mkdirSync(x.path,{recursive:!0}),0}catch(u){return n._mapFsError(u)}},path_filestat_get(i,a,f,m,b){const{bytes:x,view:u}=n._getMem(),d=Q(x.subarray(f,f+m)),y=n._resolveAt(i,d);if(y.err)return y.err;try{const A=n.vfs.statSync(y.path);return n._writeFilestat(u,b,A,A.isDirectory()),0}catch(A){return n._mapFsError(A)}},path_filestat_set_times(){return 0},path_link(){return 52},path_open(i,a,f,m,b,x,u,d,y){const{bytes:A,view:M}=n._getMem(),k=Q(A.subarray(f,f+m)),$=n._resolveAt(i,k);if($.err)return $.err;const l=$.path,F=(b&1)!==0,U=(b&2)!==0,C=(b&4)!==0,w=(b&8)!==0,g=(d&1)!==0;try{if(n.vfs.existsSync(l)&&n.vfs.statSync(l).isDirectory()){const N=n._nextFd++;return n._fds.set(N,{type:"dir",path:l,isDir:!0,preopen:null,vfsFd:null,fdflags:d}),M.setUint32(y,N,!0),0}if(U)return 54;let p="r+";g?p="a+":w?p="w+":F&&(p="r+c"),C&&(p+="x");const _=J.dirname(l);F&&!n.vfs.existsSync(_)&&n.vfs.mkdirSync(_,{recursive:!0});const T=n.vfs.openSync(l,p),R=n._nextFd++;return n._fds.set(R,{type:"file",path:l,isDir:!1,preopen:null,vfsFd:T,fdflags:d}),M.setUint32(y,R,!0),0}catch(p){return n._mapFsError(p)}},path_readlink(){return 52},path_remove_directory(i,a,f){const{bytes:m}=n._getMem(),b=Q(m.subarray(a,a+f)),x=n._resolveAt(i,b);if(x.err)return x.err;try{return n.vfs.rmdirSync(x.path),0}catch(u){return n._mapFsError(u)}},path_rename(i,a,f,m,b,x){const{bytes:u}=n._getMem(),d=Q(u.subarray(a,a+f)),y=Q(u.subarray(b,b+x)),A=n._resolveAt(i,d);if(A.err)return A.err;const M=n._resolveAt(m,y);if(M.err)return M.err;try{return n.vfs.renameSync(A.path,M.path),0}catch(k){return n._mapFsError(k)}},path_symlink(){return 52},path_unlink_file(i,a,f){const{bytes:m}=n._getMem(),b=Q(m.subarray(a,a+f)),x=n._resolveAt(i,b);if(x.err)return x.err;try{return n.vfs.unlinkSync(x.path),0}catch(u){return n._mapFsError(u)}},poll_oneoff(i,a,f,m){const{view:b}=n._getMem();return b.setUint32(m,0,!0),0},proc_exit(i){throw new _r(i)},proc_raise(){return 0},random_get(i,a){const{bytes:f}=n._getMem(),m=Fe.randomBytes(a);return f.set(m,i),0},sched_yield(){return 0},sock_accept(){return 52},sock_recv(){return 52},sock_send(){return 52},sock_shutdown(){return 52}}}getImportObject(){return{wasi_snapshot_preview1:this.wasiImport,wasi_unstable:this.wasiImport}}bindMemory(n){return this.memory=n,this}setMemory(n){return this.memory=n,this}start(n){if(!n||!n.exports)throw new Error("WASI.start requires a WebAssembly.Instance with exports");n.exports.memory&&(this.memory=n.exports.memory);try{if(typeof n.exports._start=="function")n.exports._start();else if(typeof n.exports.main=="function"){const i=n.exports.main(0,0);if(typeof i=="number")return i}return 0}catch(i){if(i&&i._isWasiExit){if(this.returnOnExit)return i.code;throw i}throw i}}initialize(n){if(!n||!n.exports)throw new Error("WASI.initialize requires a WebAssembly.Instance with exports");n.exports.memory&&(this.memory=n.exports.memory),typeof n.exports._initialize=="function"&&n.exports._initialize()}}const r=new e(t);return r.WASI=e,r}async function Vt(t,e={}){const r=performance.now(),s=[],n=[],i=u=>{s.push(u),typeof e.onStdout=="function"&&e.onStdout(u)},a=u=>{n.push(u),typeof e.onStderr=="function"&&e.onStderr(u)},f=e.vfs||Dt(e.files||{}),{WASI:m}=wn(),b=new m({args:e.args||e.argv||["wasm"],env:e.env||{},preopens:e.preopens||{".":"/workspace","/workspace":"/workspace","/usr":"/usr","/tmp":"/tmp","/":"/"},vfs:f,stdin:e.stdin||"",onStdout:i,onStderr:a,returnOnExit:!0});let x=0;try{const u=Object.assign({},b.getImportObject(),e.imports||{});let d;if(typeof WebAssembly<"u"&&t instanceof WebAssembly.Module)d=await WebAssembly.instantiate(t,u);else{const y=t instanceof Uint8Array?t:new Uint8Array(t),A=await WebAssembly.instantiate(y,u);d=A.instance||A}x=b.start(d)}catch(u){u&&u._isWasiExit?x=u.code:(x=1,a((u&&u.stack?u.stack:String(u))+`
58
- `))}return{ok:x===0,exitCode:x,durationMs:Math.max(0,performance.now()-r),stdout:s.join(""),stderr:n.join(""),vfs:f}}async function wr(t={}){const{files:e={},packages:r={},npmModules:s={},entry:n="demo.js",mode:i="run",replCode:a="",testFilter:f=null,timeoutMs:m=3e4,maxOutputBytes:b=262144,maxConsoleCalls:x=5e3,onStdout:u=null,onStderr:d=null,onTestResult:y=null,vfs:A=null,activePortTable:M=null,portTable:k=null,pid:$=1e3,argv:l=null,isBackground:F=!1,signal:U=null}=t,C=performance.now(),w=[],g=[],p=[];let _=0,T=0,R=!1,N=0,L=0,O=!1;const B={activeTimers:new Set,allTimers:new Set,activeImmediates:new Set,inFlightHttp:new Set,pendingTests:new Set,pid:$};function Z(o){if(typeof o=="string")return o;if(o instanceof Error)return o.stack||`${o.name}: ${o.message}`;if(P.isBuffer(o))return`<Buffer ${o.toString("hex").slice(0,64)}>`;if(typeof o=="object"&&o!==null)try{return JSON.stringify(o)}catch{return Je(o)}return String(o)}const V=`
57
+ }`)}return l=l.replace(/\x00__LIT_(\d+)__\x00/g,(k,L)=>p[Number(L)]),l}function gr(t){let e=t;return e=e.replace(/const\s+test\s*=\s*\(\s*name\s*,\s*fn\s*\)\s*=>\s*tests\.push\(\s*\{\s*name\s*,\s*fn\s*\}\s*\)\s*;/g,'const test = (name, fn) => { if (typeof __shouldSkipTest === "function" && __shouldSkipTest(name)) return; fn = typeof __wrapTestFn === "function" ? __wrapTestFn(name, fn) : fn; return tests.push({ name, fn }); };'),e=e.replace(/function\s+test\s*\(\s*name\s*,\s*fn\s*\)\s*\{/g,'function test(name, fn) { if (typeof __shouldSkipTest === "function" && __shouldSkipTest(name)) return; fn = typeof __wrapTestFn === "function" ? __wrapTestFn(name, fn) : fn;'),e}class On extends Error{constructor(e){super(`process.exit(${e})`),this.name="ProcessExitSignal",this.exitCode=e,this._isProcessExit=!0}}const Wn=new Map,_n=new Map;async function br(t={},e=null,r=null){const s=S=>!!S&&typeof S!="function"&&typeof S.has=="function"&&typeof S.get=="function";let n=null,i=Wn;typeof e=="function"?n=e:s(e)&&(i=e),typeof r=="function"?n=n||r:s(r)&&(i=r);const a=new Set,f=new Set(["fs","fs/promises","path","os","crypto","zlib","http","https","net","dns","dns/promises","string_decoder","child_process","process","assert","assert/strict","events","util","util/types","url","querystring","stream","stream/promises","stream/web","stream/consumers","test","perf_hooks","timers","timers/promises","buffer","tty","tls","dgram","readline","readline/promises","async_hooks","worker_threads","v8","vm","module","constants","domain","diagnostics_channel","http2","cluster","repl","inspector","trace_events","wasi","console","bun","bun:test","bun:sqlite"]);function p(S){if(!S||typeof S!="string")return;const l=S.trim();if(!l||l.startsWith(".")||l.startsWith("/")||l.startsWith("node:")||l.startsWith("bun:"))return;const d=l.split("/"),m=l.startsWith("@")?d.slice(0,2).join("/"):d[0];f.has(m)||f.has(l)||a.add(m)}for(const[S,l]of Object.entries(t||{})){if(typeof l!="string")continue;if(S.endsWith("package.json")){try{const N=JSON.parse(l);for(const k of Object.keys(N.dependencies||{}))p(k)}catch(N){D.debug("preloadNpmPackages invalid package.json",N)}continue}const d=/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g,m=/\bfrom\s+['"]([^'"]+)['"]/g;let A;for(;(A=d.exec(l))!==null;)p(A[1]);for(;(A=m.exec(l))!==null;)p(A[1])}if(typeof fetch=="function"){let S=0;for(;S<6;){const l=[];for(const d of a)_n.has(d)||l.push(d);if(l.length===0)break;S++,await Promise.all(l.map(async d=>{let m=[];try{const A=await fetch(`https://cdn.jsdelivr.net/npm/${d}/package.json`);if(A&&A.ok){const N=await A.json();m=Object.keys(N&&N.dependencies||{})}}catch(A){D.debug("preloadNpmPackages metadata fetch failed",{pkg:d,err:A})}_n.set(d,m)}));for(const d of l)for(const m of _n.get(d)||[])p(m)}}const y={};for(const S of a){const l=`node_modules/${S}/index.js`;if(!(t[l]||t[`/workspace/${l}`])){if(i.has(S)){y[S]=i.get(S);continue}if(typeof n=="function")try{n(S)}catch(d){D.debug("preloadNpmPackages onProgress callback failed",d)}if(typeof fetch=="function")try{const d=await fetch(`https://cdn.jsdelivr.net/npm/${S}`);if(d&&d.ok){const m=await d.text();typeof i.set=="function"&&i.set(S,m),y[S]=m}}catch(d){D.debug("preloadNpmPackages package fetch failed",{pkg:S,err:d})}}}return y}class _r extends Error{constructor(e){super(`WASI proc_exit(${e})`),this.name="WasiExitSignal",this.code=Number(e)||0,this._isWasiExit=!0}}function wn(t={}){class e{constructor(n={}){const i=Object.assign({},t,n);this.args=Array.isArray(i.args)?i.args.map(String):["wasm"],this.env=i.env&&typeof i.env=="object"?Object.assign({},i.env):{},this.preopens=i.preopens&&typeof i.preopens=="object"?Object.assign({},i.preopens):{".":"/workspace","/workspace":"/workspace","/usr":"/usr","/tmp":"/tmp","/":"/"},this.returnOnExit=i.returnOnExit!==!1,this.vfs=i.vfs||Dt(),this.onStdout=typeof i.onStdout=="function"?i.onStdout:null,this.onStderr=typeof i.onStderr=="function"?i.onStderr:null;const a=i.stdin!==void 0?i.stdin:"";this._stdinBytes=typeof a=="string"?se(a):a instanceof Uint8Array?a:new Uint8Array(0),this._stdinPos=0,this.memory=i.memory||null,this._fds=new Map,this._nextFd=3,this._fds.set(0,{type:"stdio",path:"/dev/stdin",isDir:!1,preopen:null,vfsFd:null}),this._fds.set(1,{type:"stdio",path:"/dev/stdout",isDir:!1,preopen:null,vfsFd:null}),this._fds.set(2,{type:"stdio",path:"/dev/stderr",isDir:!1,preopen:null,vfsFd:null});for(const[f,p]of Object.entries(this.preopens)){const y=String(p||"/");try{this.vfs.existsSync(y)||this.vfs.mkdirSync(y,{recursive:!0})}catch(l){D.debug("WASI preopen mkdir skipped",l)}const S=this._nextFd++;this._fds.set(S,{type:"preopen",path:y,isDir:!0,preopen:String(f),vfsFd:null})}this.wasiImport=this._createImports()}_getMem(n){const i=n&&n.exports&&n.exports.memory||this.memory;if(!i)throw new Error("WASI instance does not export WebAssembly.Memory");return{bytes:new Uint8Array(i.buffer),view:new DataView(i.buffer)}}_mapFsError(n){const i=n&&n.code;return i==="ENOENT"?44:i==="EBADF"?8:i==="EEXIST"?20:i==="EINVAL"?28:i==="EISDIR"?31:i==="ENOTDIR"?54:i==="ENOTEMPTY"?55:i==="EPERM"||i==="EACCES"?63:29}_resolveAt(n,i){const a=this._fds.get(n);if(!a||!a.isDir)return{err:8,path:null};const f=String(i||"").replace(/\0+$/,"");return!f||f==="."?{err:0,path:a.path}:f.startsWith("/")?{err:0,path:J.resolve("/",f)}:{err:0,path:J.resolve(a.path,f)}}_writeFilestat(n,i,a,f){n.setBigUint64(i+0,1n,!0),n.setBigUint64(i+8,BigInt(a&&a.ino?a.ino:1),!0),n.setUint8(i+16,f?3:4);for(let y=17;y<24;y++)n.setUint8(i+y,0);n.setBigUint64(i+24,1n,!0),n.setBigUint64(i+32,BigInt(a&&a.size?a.size:0),!0);const p=BigInt(Math.floor(a&&a.mtimeMs||Date.now()))*1000000n;n.setBigUint64(i+40,p,!0),n.setBigUint64(i+48,p,!0),n.setBigUint64(i+56,p,!0)}_createImports(){const n=this;return{args_sizes_get(i,a){const{view:f}=n._getMem();let p=0;for(const y of n.args)p+=se(y).byteLength+1;return f.setUint32(i,n.args.length,!0),f.setUint32(a,p,!0),0},args_get(i,a){const{bytes:f,view:p}=n._getMem();let y=a;for(let S=0;S<n.args.length;S++){p.setUint32(i+S*4,y,!0);const l=se(n.args[S]);f.set(l,y),f[y+l.byteLength]=0,y+=l.byteLength+1}return 0},environ_sizes_get(i,a){const{view:f}=n._getMem(),p=Object.entries(n.env);let y=0;for(const[S,l]of p)y+=se(`${S}=${l}`).byteLength+1;return f.setUint32(i,p.length,!0),f.setUint32(a,y,!0),0},environ_get(i,a){const{bytes:f,view:p}=n._getMem(),y=Object.entries(n.env);let S=a;for(let l=0;l<y.length;l++){p.setUint32(i+l*4,S,!0);const d=se(`${y[l][0]}=${y[l][1]}`);f.set(d,S),f[S+d.byteLength]=0,S+=d.byteLength+1}return 0},clock_res_get(i,a){const{view:f}=n._getMem();return f.setBigUint64(a,1000n,!0),0},clock_time_get(i,a,f){const{view:p}=n._getMem(),y=i===0?Date.now():performance.now();return p.setBigUint64(f,BigInt(Math.round(y*1e6)),!0),0},fd_advise(){return 0},fd_allocate(i,a,f){const p=n._fds.get(i);if(!p||p.isDir||p.vfsFd===null)return 8;try{const y=n.vfs.fstatSync(p.vfsFd),S=Number(a)+Number(f);return S>y.size&&n.vfs.truncateSync(p.path,S),0}catch(y){return n._mapFsError(y)}},fd_close(i){const a=n._fds.get(i);if(!a)return 8;if(a.type==="stdio")return 0;if(a.vfsFd!==null)try{n.vfs.closeSync(a.vfsFd)}catch(f){D.debug("WASI fd_close vfs error",f)}return n._fds.delete(i),0},fd_datasync(){return 0},fd_sync(){return 0},fd_fdstat_get(i,a){const f=n._fds.get(i);if(!f)return 8;const{view:p}=n._getMem(),y=f.type==="stdio"?2:f.isDir?3:4;return p.setUint8(a+0,y),p.setUint8(a+1,0),p.setUint16(a+2,f.fdflags||0,!0),p.setUint32(a+4,0,!0),p.setBigUint64(a+8,0xffffffffffffffffn,!0),p.setBigUint64(a+16,0xffffffffffffffffn,!0),0},fd_fdstat_set_flags(i,a){const f=n._fds.get(i);return f?(f.fdflags=a,0):8},fd_fdstat_set_rights(){return 0},fd_filestat_get(i,a){const f=n._fds.get(i);if(!f)return 8;const{view:p}=n._getMem();if(f.type==="stdio")return n._writeFilestat(p,a,{ino:i+1,size:0,mtimeMs:Date.now()},!1),p.setUint8(a+16,2),0;try{const y=n.vfs.statSync(f.path);return n._writeFilestat(p,a,y,y.isDirectory()),0}catch(y){return n._mapFsError(y)}},fd_filestat_set_size(i,a){const f=n._fds.get(i);if(!f||f.isDir)return 8;try{return n.vfs.truncateSync(f.path,Number(a)),0}catch(p){return n._mapFsError(p)}},fd_filestat_set_times(){return 0},fd_prestat_get(i,a){const f=n._fds.get(i);if(!f||f.type!=="preopen")return 8;const{view:p}=n._getMem(),y=se(f.preopen);return p.setUint8(a+0,0),p.setUint32(a+4,y.byteLength,!0),0},fd_prestat_dir_name(i,a,f){const p=n._fds.get(i);if(!p||p.type!=="preopen")return 8;const{bytes:y}=n._getMem(),S=se(p.preopen);return y.set(S.subarray(0,f),a),0},fd_read(i,a,f,p){const y=n._fds.get(i);if(!y)return 8;const{bytes:S,view:l}=n._getMem();let d=0;if(i===0){for(let m=0;m<f;m++){const A=l.getUint32(a+m*8,!0),N=l.getUint32(a+m*8+4,!0);if(N<=0)continue;const k=Math.min(N,n._stdinBytes.byteLength-n._stdinPos);if(k>0&&(S.set(n._stdinBytes.subarray(n._stdinPos,n._stdinPos+k),A),n._stdinPos+=k,d+=k),k<N)break}return l.setUint32(p,d,!0),0}if(y.isDir||y.vfsFd===null)return 8;try{for(let m=0;m<f;m++){const A=l.getUint32(a+m*8,!0),N=l.getUint32(a+m*8+4,!0);if(N<=0)continue;const k=n.vfs.readSync(y.vfsFd,S,A,N,null);if(d+=k,k<N)break}return l.setUint32(p,d,!0),0}catch(m){return n._mapFsError(m)}},fd_pread(i,a,f,p,y){const S=n._fds.get(i);if(!S||S.isDir||S.vfsFd===null)return 8;const{bytes:l,view:d}=n._getMem();let m=Number(p),A=0;try{for(let N=0;N<f;N++){const k=d.getUint32(a+N*8,!0),L=d.getUint32(a+N*8+4,!0);if(L<=0)continue;const u=n.vfs.readSync(S.vfsFd,l,k,L,m);if(m+=u,A+=u,u<L)break}return d.setUint32(y,A,!0),0}catch(N){return n._mapFsError(N)}},fd_write(i,a,f,p){const y=n._fds.get(i);if(!y)return 8;const{bytes:S,view:l}=n._getMem();let d=0;if(i===1||i===2){const m=[];for(let A=0;A<f;A++){const N=l.getUint32(a+A*8,!0),k=l.getUint32(a+A*8+4,!0);k>0&&(m.push(S.subarray(N,N+k)),d+=k)}if(d>0){const A=new Uint8Array(d);let N=0;for(const L of m)A.set(L,N),N+=L.byteLength;const k=te(A);i===1&&n.onStdout?n.onStdout(k):i===2&&n.onStderr&&n.onStderr(k)}return l.setUint32(p,d,!0),0}if(y.isDir||y.vfsFd===null)return 8;try{for(let m=0;m<f;m++){const A=l.getUint32(a+m*8,!0),N=l.getUint32(a+m*8+4,!0);if(N<=0)continue;const k=n.vfs.writeSync(y.vfsFd,S,A,N);d+=k}return l.setUint32(p,d,!0),0}catch(m){return n._mapFsError(m)}},fd_pwrite(i,a,f,p,y){const S=n._fds.get(i);if(!S||S.isDir||S.vfsFd===null)return 8;const{bytes:l,view:d}=n._getMem();let m=Number(p),A=0;try{for(let N=0;N<f;N++){const k=d.getUint32(a+N*8,!0),L=d.getUint32(a+N*8+4,!0);if(L<=0)continue;const u=n.vfs.writeSync(S.vfsFd,l,k,L,m);m+=u,A+=u}return d.setUint32(y,A,!0),0}catch(N){return n._mapFsError(N)}},fd_seek(i,a,f,p){const y=n._fds.get(i);if(!y||y.isDir||y.vfsFd===null)return 8;const{view:S}=n._getMem();try{const l=n.vfs.lseekSync(y.vfsFd,Number(a),Number(f));return S.setBigUint64(p,BigInt(l),!0),0}catch(l){return n._mapFsError(l)}},fd_tell(i,a){const f=n._fds.get(i);if(!f||f.isDir||f.vfsFd===null)return 8;const{view:p}=n._getMem();try{const y=n.vfs.tellSync(f.vfsFd);return p.setBigUint64(a,BigInt(y),!0),0}catch(y){return n._mapFsError(y)}},fd_renumber(i,a){const f=n._fds.get(i);if(!f)return 8;const p=n._fds.get(a);if(p&&p.vfsFd!==null)try{n.vfs.closeSync(p.vfsFd)}catch(y){D.debug("WASI fd_renumber close error",y)}return n._fds.set(a,f),n._fds.delete(i),0},fd_readdir(i,a,f,p,y){const S=n._fds.get(i);if(!S||!S.isDir)return 8;const{bytes:l,view:d}=n._getMem();try{const m=[".","..",...n.vfs.readdirSync(S.path)];let A=0;const N=Number(p);for(let k=N;k<m.length;k++){const L=m[k],u=se(L),B=L==="."||L===".."?S.path:J.resolve(S.path,L);let F=!0,U=1;try{const x=n.vfs.statSync(B);F=x.isDirectory(),U=x.ino||1}catch(x){D.debug("WASI fd_readdir stat skipped",x)}const b=24,w=b+u.byteLength;if(A+b>f)break;d.setBigUint64(a+A+0,BigInt(k+1),!0),d.setBigUint64(a+A+8,BigInt(U),!0),d.setUint32(a+A+16,u.byteLength,!0),d.setUint8(a+A+20,F?3:4);const g=Math.min(u.byteLength,f-(A+b));if(l.set(u.subarray(0,g),a+A+b),A+=b+g,g<u.byteLength)break}return d.setUint32(y,A,!0),0}catch(m){return n._mapFsError(m)}},path_create_directory(i,a,f){const{bytes:p}=n._getMem(),y=te(p.subarray(a,a+f)),S=n._resolveAt(i,y);if(S.err)return S.err;try{return n.vfs.mkdirSync(S.path,{recursive:!0}),0}catch(l){return n._mapFsError(l)}},path_filestat_get(i,a,f,p,y){const{bytes:S,view:l}=n._getMem(),d=te(S.subarray(f,f+p)),m=n._resolveAt(i,d);if(m.err)return m.err;try{const A=n.vfs.statSync(m.path);return n._writeFilestat(l,y,A,A.isDirectory()),0}catch(A){return n._mapFsError(A)}},path_filestat_set_times(){return 0},path_link(){return 52},path_open(i,a,f,p,y,S,l,d,m){const{bytes:A,view:N}=n._getMem(),k=te(A.subarray(f,f+p)),L=n._resolveAt(i,k);if(L.err)return L.err;const u=L.path,B=(y&1)!==0,F=(y&2)!==0,U=(y&4)!==0,b=(y&8)!==0,w=(d&1)!==0;try{if(n.vfs.existsSync(u)&&n.vfs.statSync(u).isDirectory()){const v=n._nextFd++;return n._fds.set(v,{type:"dir",path:u,isDir:!0,preopen:null,vfsFd:null,fdflags:d}),N.setUint32(m,v,!0),0}if(F)return 54;let g="r+";w?g="a+":b?g="w+":B&&(g="r+c"),U&&(g+="x");const x=J.dirname(u);B&&!n.vfs.existsSync(x)&&n.vfs.mkdirSync(x,{recursive:!0});const R=n.vfs.openSync(u,g),T=n._nextFd++;return n._fds.set(T,{type:"file",path:u,isDir:!1,preopen:null,vfsFd:R,fdflags:d}),N.setUint32(m,T,!0),0}catch(g){return n._mapFsError(g)}},path_readlink(){return 52},path_remove_directory(i,a,f){const{bytes:p}=n._getMem(),y=te(p.subarray(a,a+f)),S=n._resolveAt(i,y);if(S.err)return S.err;try{return n.vfs.rmdirSync(S.path),0}catch(l){return n._mapFsError(l)}},path_rename(i,a,f,p,y,S){const{bytes:l}=n._getMem(),d=te(l.subarray(a,a+f)),m=te(l.subarray(y,y+S)),A=n._resolveAt(i,d);if(A.err)return A.err;const N=n._resolveAt(p,m);if(N.err)return N.err;try{return n.vfs.renameSync(A.path,N.path),0}catch(k){return n._mapFsError(k)}},path_symlink(){return 52},path_unlink_file(i,a,f){const{bytes:p}=n._getMem(),y=te(p.subarray(a,a+f)),S=n._resolveAt(i,y);if(S.err)return S.err;try{return n.vfs.unlinkSync(S.path),0}catch(l){return n._mapFsError(l)}},poll_oneoff(i,a,f,p){const{view:y}=n._getMem();return y.setUint32(p,0,!0),0},proc_exit(i){throw new _r(i)},proc_raise(){return 0},random_get(i,a){const{bytes:f}=n._getMem(),p=je.randomBytes(a);return f.set(p,i),0},sched_yield(){return 0},sock_accept(){return 52},sock_recv(){return 52},sock_send(){return 52},sock_shutdown(){return 52}}}getImportObject(){return{wasi_snapshot_preview1:this.wasiImport,wasi_unstable:this.wasiImport}}bindMemory(n){return this.memory=n,this}setMemory(n){return this.memory=n,this}start(n){if(!n||!n.exports)throw new Error("WASI.start requires a WebAssembly.Instance with exports");n.exports.memory&&(this.memory=n.exports.memory);try{if(typeof n.exports._start=="function")n.exports._start();else if(typeof n.exports.main=="function"){const i=n.exports.main(0,0);if(typeof i=="number")return i}return 0}catch(i){if(i&&i._isWasiExit){if(this.returnOnExit)return i.code;throw i}throw i}}initialize(n){if(!n||!n.exports)throw new Error("WASI.initialize requires a WebAssembly.Instance with exports");n.exports.memory&&(this.memory=n.exports.memory),typeof n.exports._initialize=="function"&&n.exports._initialize()}}const r=new e(t);return r.WASI=e,r}async function Vt(t,e={}){const r=performance.now(),s=[],n=[],i=l=>{s.push(l),typeof e.onStdout=="function"&&e.onStdout(l)},a=l=>{n.push(l),typeof e.onStderr=="function"&&e.onStderr(l)},f=e.vfs||Dt(e.files||{}),{WASI:p}=wn(),y=new p({args:e.args||e.argv||["wasm"],env:e.env||{},preopens:e.preopens||{".":"/workspace","/workspace":"/workspace","/usr":"/usr","/tmp":"/tmp","/":"/"},vfs:f,stdin:e.stdin||"",onStdout:i,onStderr:a,returnOnExit:!0});let S=0;try{const l=Object.assign({},y.getImportObject(),e.imports||{});let d;if(typeof WebAssembly<"u"&&t instanceof WebAssembly.Module)d=await WebAssembly.instantiate(t,l);else{const m=t instanceof Uint8Array?t:new Uint8Array(t),A=await WebAssembly.instantiate(m,l);d=A.instance||A}S=y.start(d)}catch(l){l&&l._isWasiExit?S=l.code:(S=1,a((l&&l.stack?l.stack:String(l))+`
58
+ `))}return{ok:S===0,exitCode:S,durationMs:Math.max(0,performance.now()-r),stdout:s.join(""),stderr:n.join(""),vfs:f}}async function wr(t={}){const{files:e={},packages:r={},npmModules:s={},entry:n="demo.js",mode:i="run",replCode:a="",testFilter:f=null,timeoutMs:p=3e4,maxOutputBytes:y=262144,maxConsoleCalls:S=5e3,onStdout:l=null,onStderr:d=null,onTestResult:m=null,vfs:A=null,activePortTable:N=null,portTable:k=null,pid:L=1e3,argv:u=null,isBackground:B=!1,signal:F=null}=t,U=performance.now(),b=[],w=[],g=[];let x=0,R=0,T=!1,v=0,$=0,j=!1;const C={activeTimers:new Set,allTimers:new Set,activeImmediates:new Set,inFlightHttp:new Set,pendingTests:new Set,pid:L};function z(o){if(typeof o=="string")return o;if(o instanceof Error)return o.stack||`${o.name}: ${o.message}`;if(O.isBuffer(o))return`<Buffer ${o.toString("hex").slice(0,64)}>`;if(typeof o=="object"&&o!==null)try{return JSON.stringify(o)}catch{return Je(o)}return String(o)}const Z=`
59
59
  [Output truncated: exceeded 256 KB limit]
60
- `;function re(o,c){R||(R=!0,o.push(V),typeof c=="function"&&c(V))}let ue="";function ge(o){let c=String(o);if(c.includes("__CODELAB_TEST__:")||ue.length>0){const S=(ue+c).split(`
61
- `);ue=S.pop()||"";const E=[];for(const I of S){const v=I.replace(/\r$/,""),D=v.indexOf("__CODELAB_TEST__:");if(D!==-1){const W=v.slice(0,D);W&&E.push(W);const q=v.slice(D+17).trim();try{const H=JSON.parse(q);if(H&&H.name&&!Ee(H.name)){const ie=++N,me=H.passed!==void 0?!!H.passed:H.status==="pass"||H.status==="passed",ve={index:ie,name:String(H.name),status:me?"pass":"fail",passed:me,durationMs:Number(H.durationMs)||0,error:H.error||null};p.push(ve),typeof y=="function"&&y(ve)}}catch(H){j.debug("Failed to parse __CODELAB_TEST__ payload",H)}}else E.push(I)}c=E.length>0?E.join(`
60
+ `;function Q(o,c){T||(T=!0,o.push(Z),typeof c=="function"&&c(Z))}let le="";function de(o){let c=String(o);if(c.includes("__CODELAB_TEST__:")||le.length>0){const _=(le+c).split(`
61
+ `);le=_.pop()||"";const E=[];for(const M of _){const I=M.replace(/\r$/,""),P=I.indexOf("__CODELAB_TEST__:");if(P!==-1){const W=I.slice(0,P);W&&E.push(W);const q=I.slice(P+17).trim();try{const H=JSON.parse(q);if(H&&H.name&&!be(H.name)){const ie=++v,ye=H.passed!==void 0?!!H.passed:H.status==="pass"||H.status==="passed",ve={index:ie,name:String(H.name),status:ye?"pass":"fail",passed:ye,durationMs:Number(H.durationMs)||0,error:H.error||null};g.push(ve),typeof m=="function"&&m(ve)}}catch(H){D.debug("Failed to parse __CODELAB_TEST__ payload",H)}}else E.push(M)}c=E.length>0?E.join(`
62
62
  `)+`
63
- `:""}return c}function Y(o){if(R)return;const c=ge(o);if(c){if(_+c.length>b){const h=Math.max(0,b-_);if(h>0){const S=c.slice(0,h);w.push(S),_+=S.length,typeof u=="function"&&u(S)}re(w,u);return}_+=c.length,w.push(c),typeof u=="function"&&u(c)}}function se(o){if(R)return;const c=String(o);if(_+c.length>b){const h=Math.max(0,b-_);if(h>0){const S=c.slice(0,h);g.push(S),_+=S.length,typeof d=="function"&&d(S)}re(g,d);return}_+=c.length,g.push(c),typeof d=="function"&&d(c)}function K(o){return o?{name:o.name||"Error",message:o.message||String(o),stack:o.stack||String(o),actual:o.actual!==void 0?Ot(o.actual):void 0,expected:o.expected!==void 0?Ot(o.expected):void 0,operator:o.operator}:null}function Ee(o){return f?typeof f=="string"?!o.toLowerCase().includes(f.toLowerCase()):Array.isArray(f)&&f.length>0?!f.includes(o):!1:!1}function De(o,c){return function(...S){const E=++N,I=performance.now();let v;try{v=c.apply(this,S)}catch(q){if(q&&q._isProcessExit)throw q;const H=Math.max(0,performance.now()-I),ie={index:E,name:o,status:"fail",passed:!1,durationMs:H,error:K(q)};throw p.push(ie),typeof y=="function"&&y(ie),q}if(v&&typeof v.then=="function"){const q=v.then(H=>{B.pendingTests.delete(q);const ie=Math.max(0,performance.now()-I),me={index:E,name:o,status:"pass",passed:!0,durationMs:ie,error:null};return p.push(me),typeof y=="function"&&y(me),H},H=>{if(B.pendingTests.delete(q),H&&H._isProcessExit)throw H;const ie=Math.max(0,performance.now()-I),me={index:E,name:o,status:"fail",passed:!1,durationMs:ie,error:K(H)};throw p.push(me),typeof y=="function"&&y(me),H});return q.catch(()=>{}),B.pendingTests.add(q),q}const D=Math.max(0,performance.now()-I),W={index:E,name:o,status:"pass",passed:!0,durationMs:D,error:null};return p.push(W),typeof y=="function"&&y(W),v}}const Pe=M||k||cr;B.pid=$;const ct=it,We=xt;let be=typeof t.cwd=="string"&&t.cwd.trim()?J.resolve("/workspace",t.cwd.trim()):"/workspace";const Mt=t.env&&typeof t.env.HOME=="string"&&t.env.HOME.trim()?t.env.HOME.trim():"/home/codelab";it=()=>be,xt=()=>Mt;const z=A||Dt(e,{cwdGetter:()=>be}),zn=typeof z._listOpenFds=="function"?new Set(z._listOpenFds()):null;if(A&&e&&typeof e=="object")for(const[o,c]of Object.entries(e)){const h=o.startsWith("/")?o:"/workspace/"+o;try{const S=J.dirname(h);z.existsSync(S)||z.mkdirSync(S,{recursive:!0}),z.writeFileSync(h,c)}catch(S){j.warn("vfs initial file seed failed",{abs:h,err:S})}}typeof z._setActiveStdin=="function"&&z._setActiveStdin(t&&t.stdin?String(t.stdin):"");const Ze=Bn(B,Pe),Nt=Pn(B,Ze.getTrace()),at=new Map,xr=Object.assign({},Object.fromEntries(On.entries()),s||{},r||{});for(const[o,c]of Object.entries(xr))if(typeof c=="string"){const h=`/workspace/node_modules/${o}/index.js`;z.existsSync(h)||(z.mkdirSync(J.dirname(h),{recursive:!0}),z.writeFileSync(h,c))}else c!=null&&at.set(o,c);const Ht=t&&t._captureVfsDiff&&typeof z._exportRawState=="function"?z._exportRawState():null;function Zn(o,c){return{_id:o,_isInterval:c,_ref:!0,unref(){return this._ref=!1,B.activeTimers.delete(o),this},ref(){return this._ref=!0,B.activeTimers.add(o),this},hasRef(){return this._ref},[Symbol.toPrimitive](){return o}}}function mt(o,c=0,...h){const S=setTimeout(()=>{if(B.activeTimers.delete(S),B.allTimers.delete(S),!O)try{o(...h)}catch(E){E&&E._isProcessExit?(L=E.exitCode,O=!0):(se((E&&E.stack?E.stack:String(E))+`
64
- `),L=1)}},c);return B.activeTimers.add(S),B.allTimers.add(S),Zn(S,!1)}function Gt(o){if(o==null)return;const c=typeof o=="object"&&"_id"in o?o._id:o;clearTimeout(c),B.activeTimers.delete(c),B.allTimers.delete(c)}function Jt(o,c=0,...h){const S=setInterval(()=>{if(O){clearInterval(S);return}try{o(...h)}catch(E){E&&E._isProcessExit?(L=E.exitCode,O=!0,clearInterval(S)):(se((E&&E.stack?E.stack:String(E))+`
65
- `),L=1)}},c);return B.activeTimers.add(S),B.allTimers.add(S),Zn(S,!0)}function Xt(o){if(o==null)return;const c=typeof o=="object"&&"_id"in o?o._id:o;clearInterval(c),B.activeTimers.delete(c),B.allTimers.delete(c)}function $t(o,...c){const h={};return B.activeImmediates.add(h),queueMicrotask(()=>{if(B.activeImmediates.has(h)&&(B.activeImmediates.delete(h),!O))try{o(...c)}catch(S){S&&S._isProcessExit?(L=S.exitCode,O=!0):(se((S&&S.stack?S.stack:String(S))+`
66
- `),L=1)}}),h}function Kt(o){B.activeImmediates.delete(o)}const yt=new Map,Sn=new Map;let Xe=0;function Ke(o){if(o.length===0)return"";if(o.length>1&&typeof o[0]=="string"&&/%[sdifjoO%]/.test(o[0])){const c=o[0];let h=1,S="";for(let E=0;E<c.length;E++){if(c[E]==="%"&&E+1<c.length){const I=c[E+1];if(I==="%"){S+="%",E++;continue}if(h<o.length){const v=o[h];if(I==="s"){S+=String(v),h++,E++;continue}if(I==="d"){S+=Number(v),h++,E++;continue}if(I==="i"){S+=parseInt(v,10),h++,E++;continue}if(I==="f"){S+=parseFloat(v),h++,E++;continue}if(I==="j"){try{S+=JSON.stringify(v)}catch{S+="[Circular]"}h++,E++;continue}if(I==="o"||I==="O"){S+=Je(v),h++,E++;continue}}}S+=c[E]}for(;h<o.length;)S+=" "+Z(o[h++]);return S}return o.map(Z).join(" ")}function Vn(o){return o===void 0?"":o===null?"null":typeof o=="string"?`'${o}'`:typeof o=="number"||typeof o=="boolean"||typeof o=="bigint"?String(o):Je(o,{depth:0})}function Er(o,c){if(o===null||typeof o!="object")return null;const h=Array.isArray(o)?o.map((oe,G)=>[String(G),oe]):Object.entries(o);if(h.length===0)return"(empty table)";const S=Array.isArray(c)?new Set(c.map(String)):null,E=[],I=new Set;let v=!1;for(const[,oe]of h)if(oe!==null&&typeof oe=="object"&&!P.isBuffer(oe)&&!(oe instanceof Date)&&!(oe instanceof RegExp))for(const G of Object.keys(oe))(!S||S.has(G))&&(I.has(G)||(I.add(G),E.push(G)));else v=!0;const D=["(index)",...E,...v?["Values"]:[]],W=h.map(([oe,G])=>{const ae=G!==null&&typeof G=="object"&&!P.isBuffer(G)&&!(G instanceof Date)&&!(G instanceof RegExp),we=[String(oe)];for(const Ue of E)we.push(ae&&Object.prototype.hasOwnProperty.call(G,Ue)?Vn(G[Ue]):"");return v&&we.push(ae?"":Vn(G)),we}),q=D.map((oe,G)=>{let ae=oe.length;for(const we of W)we[G].length>ae&&(ae=we[G].length);return ae}),H="\u250C\u2500"+q.map(oe=>"\u2500".repeat(oe)).join("\u2500\u252C\u2500")+"\u2500\u2510",ie="\u251C\u2500"+q.map(oe=>"\u2500".repeat(oe)).join("\u2500\u253C\u2500")+"\u2500\u2524",me="\u2514\u2500"+q.map(oe=>"\u2500".repeat(oe)).join("\u2500\u2534\u2500")+"\u2500\u2518",ve=oe=>"\u2502 "+oe.map((G,ae)=>G.padEnd(q[ae]," ")).join(" \u2502 ")+" \u2502";return[H,ve(D),ie,...W.map(ve),me].join(`
67
- `)}function Le(o){if(Xe<=0)return o;const c=" ".repeat(Xe);return String(o).split(`
63
+ `:""}return c}function Y(o){if(T)return;const c=de(o);if(c){if(x+c.length>y){const h=Math.max(0,y-x);if(h>0){const _=c.slice(0,h);b.push(_),x+=_.length,typeof l=="function"&&l(_)}Q(b,l);return}x+=c.length,b.push(c),typeof l=="function"&&l(c)}}function ee(o){if(T)return;const c=String(o);if(x+c.length>y){const h=Math.max(0,y-x);if(h>0){const _=c.slice(0,h);w.push(_),x+=_.length,typeof d=="function"&&d(_)}Q(w,d);return}x+=c.length,w.push(c),typeof d=="function"&&d(c)}function K(o){return o?{name:o.name||"Error",message:o.message||String(o),stack:o.stack||String(o),actual:o.actual!==void 0?Wt(o.actual):void 0,expected:o.expected!==void 0?Wt(o.expected):void 0,operator:o.operator}:null}function be(o){return f?typeof f=="string"?!o.toLowerCase().includes(f.toLowerCase()):Array.isArray(f)&&f.length>0?!f.includes(o):!1:!1}function Me(o,c){return function(..._){const E=++v,M=performance.now();let I;try{I=c.apply(this,_)}catch(q){if(q&&q._isProcessExit)throw q;const H=Math.max(0,performance.now()-M),ie={index:E,name:o,status:"fail",passed:!1,durationMs:H,error:K(q)};throw g.push(ie),typeof m=="function"&&m(ie),q}if(I&&typeof I.then=="function"){const q=I.then(H=>{C.pendingTests.delete(q);const ie=Math.max(0,performance.now()-M),ye={index:E,name:o,status:"pass",passed:!0,durationMs:ie,error:null};return g.push(ye),typeof m=="function"&&m(ye),H},H=>{if(C.pendingTests.delete(q),H&&H._isProcessExit)throw H;const ie=Math.max(0,performance.now()-M),ye={index:E,name:o,status:"fail",passed:!1,durationMs:ie,error:K(H)};throw g.push(ye),typeof m=="function"&&m(ye),H});return q.catch(()=>{}),C.pendingTests.add(q),q}const P=Math.max(0,performance.now()-M),W={index:E,name:o,status:"pass",passed:!0,durationMs:P,error:null};return g.push(W),typeof m=="function"&&m(W),I}}const Ce=N||k||cr;C.pid=L;const ct=it,Oe=xt;let _e=typeof t.cwd=="string"&&t.cwd.trim()?J.resolve("/workspace",t.cwd.trim()):"/workspace";const Mt=t.env&&typeof t.env.HOME=="string"&&t.env.HOME.trim()?t.env.HOME.trim():"/home/codelab";it=()=>_e,xt=()=>Mt;const V=A||Dt(e,{cwdGetter:()=>_e}),qn=typeof V._listOpenFds=="function"?new Set(V._listOpenFds()):null;if(A&&e&&typeof e=="object")for(const[o,c]of Object.entries(e)){const h=o.startsWith("/")?o:"/workspace/"+o;try{const _=J.dirname(h);V.existsSync(_)||V.mkdirSync(_,{recursive:!0}),V.writeFileSync(h,c)}catch(_){D.warn("vfs initial file seed failed",{abs:h,err:_})}}typeof V._setActiveStdin=="function"&&V._setActiveStdin(t&&t.stdin?String(t.stdin):"");const Ze=Bn(C,Ce),Nt=Pn(C,Ze.getTrace()),at=new Map,xr=Object.assign({},Object.fromEntries(Wn.entries()),s||{},r||{});for(const[o,c]of Object.entries(xr))if(typeof c=="string"){const h=`/workspace/node_modules/${o}/index.js`;V.existsSync(h)||(V.mkdirSync(J.dirname(h),{recursive:!0}),V.writeFileSync(h,c))}else c!=null&&at.set(o,c);const Ht=t&&t._captureVfsDiff&&typeof V._exportRawState=="function"?V._exportRawState():null;function Zn(o,c){return{_id:o,_isInterval:c,_ref:!0,unref(){return this._ref=!1,C.activeTimers.delete(o),this},ref(){return this._ref=!0,C.allTimers.has(o)&&C.activeTimers.add(o),this},hasRef(){return this._ref},[Symbol.toPrimitive](){return o}}}function mt(o,c=0,...h){const _=setTimeout(()=>{if(C.activeTimers.delete(_),C.allTimers.delete(_),!j)try{o(...h)}catch(E){E&&E._isProcessExit?($=E.exitCode,j=!0):(ee((E&&E.stack?E.stack:String(E))+`
64
+ `),$=1)}},c);return C.activeTimers.add(_),C.allTimers.add(_),Zn(_,!1)}function Gt(o){if(o==null)return;const c=typeof o=="object"&&"_id"in o?o._id:o;clearTimeout(c),C.activeTimers.delete(c),C.allTimers.delete(c)}function Jt(o,c=0,...h){const _=setInterval(()=>{if(j){clearInterval(_);return}try{o(...h)}catch(E){E&&E._isProcessExit?($=E.exitCode,j=!0,clearInterval(_)):(ee((E&&E.stack?E.stack:String(E))+`
65
+ `),$=1)}},c);return C.activeTimers.add(_),C.allTimers.add(_),Zn(_,!0)}function Xt(o){if(o==null)return;const c=typeof o=="object"&&"_id"in o?o._id:o;clearInterval(c),C.activeTimers.delete(c),C.allTimers.delete(c)}function $t(o,...c){const h={};return C.activeImmediates.add(h),queueMicrotask(()=>{if(C.activeImmediates.has(h)&&(C.activeImmediates.delete(h),!j))try{o(...c)}catch(_){_&&_._isProcessExit?($=_.exitCode,j=!0):(ee((_&&_.stack?_.stack:String(_))+`
66
+ `),$=1)}}),h}function Kt(o){C.activeImmediates.delete(o)}const yt=new Map,Sn=new Map;let Xe=0;function Ke(o){if(o.length===0)return"";if(o.length>1&&typeof o[0]=="string"&&/%[sdifjoO%]/.test(o[0])){const c=o[0];let h=1,_="";for(let E=0;E<c.length;E++){if(c[E]==="%"&&E+1<c.length){const M=c[E+1];if(M==="%"){_+="%",E++;continue}if(h<o.length){const I=o[h];if(M==="s"){_+=String(I),h++,E++;continue}if(M==="d"){_+=Number(I),h++,E++;continue}if(M==="i"){_+=parseInt(I,10),h++,E++;continue}if(M==="f"){_+=parseFloat(I),h++,E++;continue}if(M==="j"){try{_+=JSON.stringify(I)}catch{_+="[Circular]"}h++,E++;continue}if(M==="o"||M==="O"){_+=Je(I),h++,E++;continue}}}_+=c[E]}for(;h<o.length;)_+=" "+z(o[h++]);return _}return o.map(z).join(" ")}function Vn(o){return o===void 0?"":o===null?"null":typeof o=="string"?`'${o}'`:typeof o=="number"||typeof o=="boolean"||typeof o=="bigint"?String(o):Je(o,{depth:0})}function Er(o,c){if(o===null||typeof o!="object")return null;const h=Array.isArray(o)?o.map((oe,G)=>[String(G),oe]):Object.entries(o);if(h.length===0)return"(empty table)";const _=Array.isArray(c)?new Set(c.map(String)):null,E=[],M=new Set;let I=!1;for(const[,oe]of h)if(oe!==null&&typeof oe=="object"&&!O.isBuffer(oe)&&!(oe instanceof Date)&&!(oe instanceof RegExp))for(const G of Object.keys(oe))(!_||_.has(G))&&(M.has(G)||(M.add(G),E.push(G)));else I=!0;const P=["(index)",...E,...I?["Values"]:[]],W=h.map(([oe,G])=>{const ae=G!==null&&typeof G=="object"&&!O.isBuffer(G)&&!(G instanceof Date)&&!(G instanceof RegExp),Se=[String(oe)];for(const Be of E)Se.push(ae&&Object.prototype.hasOwnProperty.call(G,Be)?Vn(G[Be]):"");return I&&Se.push(ae?"":Vn(G)),Se}),q=P.map((oe,G)=>{let ae=oe.length;for(const Se of W)Se[G].length>ae&&(ae=Se[G].length);return ae}),H="\u250C\u2500"+q.map(oe=>"\u2500".repeat(oe)).join("\u2500\u252C\u2500")+"\u2500\u2510",ie="\u251C\u2500"+q.map(oe=>"\u2500".repeat(oe)).join("\u2500\u253C\u2500")+"\u2500\u2524",ye="\u2514\u2500"+q.map(oe=>"\u2500".repeat(oe)).join("\u2500\u2534\u2500")+"\u2500\u2518",ve=oe=>"\u2502 "+oe.map((G,ae)=>G.padEnd(q[ae]," ")).join(" \u2502 ")+" \u2502";return[H,ve(P),ie,...W.map(ve),ye].join(`
67
+ `)}function Ue(o){if(Xe<=0)return o;const c=" ".repeat(Xe);return String(o).split(`
68
68
  `).map(h=>c+h).join(`
69
- `)}function Ce(o=!1,c=null,h=null){return R?!1:(T++,T>x?(re(c||(o?g:w),h!==null?h:o?d:u),!1):!0)}function Hn(o,c){const h={log:(...S)=>{Ce(!1)&&o(Le(Ke(S))+`
70
- `)},info:(...S)=>{Ce(!1)&&o(Le(Ke(S))+`
71
- `)},debug:(...S)=>{Ce(!1)&&o(Le(Ke(S))+`
72
- `)},warn:(...S)=>{Ce(!0)&&c(Le(Ke(S))+`
73
- `)},error:(...S)=>{Ce(!0)&&c(Le(Ke(S))+`
74
- `)},dir:(S,E)=>{Ce(!1)&&o(Le(Je(S,E))+`
75
- `)},table:(S,E)=>{const I=Er(S,E);I===null?h.log(S):Ce(!1)&&o(Le(I)+`
76
- `)},time:(S="default")=>{yt.set(String(S),performance.now())},timeLog:(S="default",...E)=>{const I=String(S);if(!yt.has(I)){Ce(!0)&&c(Le(`Warning: No such label '${I}' for console.timeLog()`)+`
77
- `);return}const v=(performance.now()-yt.get(I)).toFixed(2),D=E.length>0?" "+Ke(E):"";Ce(!1)&&o(Le(`${I}: ${v}ms${D}`)+`
78
- `)},timeEnd:(S="default")=>{const E=String(S);if(!yt.has(E)){Ce(!0)&&c(Le(`Warning: No such label '${E}' for console.timeEnd()`)+`
79
- `);return}const I=(performance.now()-yt.get(E)).toFixed(2);yt.delete(E),Ce(!1)&&o(Le(`${E}: ${I}ms`)+`
80
- `)},count:(S="default")=>{const E=String(S),I=(Sn.get(E)||0)+1;Sn.set(E,I),Ce(!1)&&o(Le(`${E}: ${I}`)+`
81
- `)},countReset:(S="default")=>{Sn.delete(String(S))},assert:(S,...E)=>{if(!S){const I=E.length>0?"Assertion failed: "+Ke(E):"Assertion failed";Ce(!0)&&c(Le(I)+`
82
- `)}},group:(...S)=>{S.length>0&&h.log(...S),Xe=Math.min(Xe+1,20)},groupCollapsed:(...S)=>{S.length>0&&h.log(...S),Xe=Math.min(Xe+1,20)},groupEnd:()=>{Xe=Math.max(0,Xe-1)},trace:(...S)=>{if(!Ce(!0))return;const E=S.length>0?"Trace: "+Ke(S):"Trace",I=new Error,v=String(I.stack||"").split(`
83
- `).slice(2),D=v.length>0?`
84
- `+v.join(`
85
- `):"";c(Le(E+D)+`
86
- `)},clear:()=>{typeof t.onConsoleClear=="function"&&t.onConsoleClear()}};return h}const Ye=Hn(Y,se),Gn=function(c){const h=BigInt(Math.round(performance.now()*1e6)),S=Number(h/1000000000n),E=Number(h%1000000000n);if(Array.isArray(c)&&c.length===2){let I=S-c[0],v=E-c[1];return v<0&&(I-=1,v+=1e9),[I,v]}return[S,E]};Gn.bigint=()=>BigInt(Math.round(performance.now()*1e6));let xn=0;const Lt=new He,Qe=[];if(t&&typeof t.stdin=="string"&&t.stdin.length>0){const o=t.stdin.replace(/\r\n/g,`
69
+ `)}function Fe(o=!1,c=null,h=null){return T?!1:(R++,R>S?(Q(c||(o?w:b),h!==null?h:o?d:l),!1):!0)}function Hn(o,c){const h={log:(..._)=>{Fe(!1)&&o(Ue(Ke(_))+`
70
+ `)},info:(..._)=>{Fe(!1)&&o(Ue(Ke(_))+`
71
+ `)},debug:(..._)=>{Fe(!1)&&o(Ue(Ke(_))+`
72
+ `)},warn:(..._)=>{Fe(!0)&&c(Ue(Ke(_))+`
73
+ `)},error:(..._)=>{Fe(!0)&&c(Ue(Ke(_))+`
74
+ `)},dir:(_,E)=>{Fe(!1)&&o(Ue(Je(_,E))+`
75
+ `)},table:(_,E)=>{const M=Er(_,E);M===null?h.log(_):Fe(!1)&&o(Ue(M)+`
76
+ `)},time:(_="default")=>{yt.set(String(_),performance.now())},timeLog:(_="default",...E)=>{const M=String(_);if(!yt.has(M)){Fe(!0)&&c(Ue(`Warning: No such label '${M}' for console.timeLog()`)+`
77
+ `);return}const I=(performance.now()-yt.get(M)).toFixed(2),P=E.length>0?" "+Ke(E):"";Fe(!1)&&o(Ue(`${M}: ${I}ms${P}`)+`
78
+ `)},timeEnd:(_="default")=>{const E=String(_);if(!yt.has(E)){Fe(!0)&&c(Ue(`Warning: No such label '${E}' for console.timeEnd()`)+`
79
+ `);return}const M=(performance.now()-yt.get(E)).toFixed(2);yt.delete(E),Fe(!1)&&o(Ue(`${E}: ${M}ms`)+`
80
+ `)},count:(_="default")=>{const E=String(_),M=(Sn.get(E)||0)+1;Sn.set(E,M),Fe(!1)&&o(Ue(`${E}: ${M}`)+`
81
+ `)},countReset:(_="default")=>{Sn.delete(String(_))},assert:(_,...E)=>{if(!_){const M=E.length>0?"Assertion failed: "+Ke(E):"Assertion failed";Fe(!0)&&c(Ue(M)+`
82
+ `)}},group:(..._)=>{_.length>0&&h.log(..._),Xe=Math.min(Xe+1,20)},groupCollapsed:(..._)=>{_.length>0&&h.log(..._),Xe=Math.min(Xe+1,20)},groupEnd:()=>{Xe=Math.max(0,Xe-1)},trace:(..._)=>{if(!Fe(!0))return;const E=_.length>0?"Trace: "+Ke(_):"Trace",M=new Error,I=String(M.stack||"").split(`
83
+ `).slice(2),P=I.length>0?`
84
+ `+I.join(`
85
+ `):"";c(Ue(E+P)+`
86
+ `)},clear:()=>{typeof t.onConsoleClear=="function"&&t.onConsoleClear()}};return h}const Ye=Hn(Y,ee),Gn=function(c){const h=BigInt(Math.round(performance.now()*1e6)),_=Number(h/1000000000n),E=Number(h%1000000000n);if(Array.isArray(c)&&c.length===2){let M=_-c[0],I=E-c[1];return I<0&&(M-=1,I+=1e9),[M,I]}return[_,E]};Gn.bigint=()=>BigInt(Math.round(performance.now()*1e6));let xn=0;const Lt=new He,Qe=[];if(t&&typeof t.stdin=="string"&&t.stdin.length>0){const o=t.stdin.replace(/\r\n/g,`
87
87
  `),c=o.split(`
88
88
  `);c.length>0&&c[c.length-1]===""&&o.endsWith(`
89
- `)&&c.pop();for(const h of c)Qe.push(h);Lt.write(t.stdin),typeof t.onRequestStdin!="function"&&Lt.end()}else(!t||typeof t.onRequestStdin!="function")&&Lt.end();const Ae=Object.assign(new fe,{env:Object.assign({NODE_ENV:"development",PATH:"/usr/local/bin:/usr/bin:/bin",HOME:Mt},t.env||{}),argv:l||["node",n.startsWith("/")?n:J.resolve(be,n)],argv0:"node",execArgv:[],execPath:"/usr/local/bin/node",pid:$,ppid:1,title:"node",version:"v22.0.0",versions:{node:"22.0.0",v8:"12.4",uv:"1.48.0",modules:"127"},platform:"linux",arch:"x64",cwd:()=>be,chdir:o=>{const c=J.resolve(be,String(o));if(!z.existsSync(c)){const h=new Error(`ENOENT: no such file or directory, chdir '${o}'`);throw h.code="ENOENT",h}if(!z.statSync(c).isDirectory()){const h=new Error(`ENOTDIR: not a directory, chdir '${o}'`);throw h.code="ENOTDIR",h}be=c},uptime:()=>Math.max(0,(performance.now()-C)/1e3),memoryUsage:()=>({rss:33554432,heapTotal:16777216,heapUsed:8388608,external:1048576,arrayBuffers:524288}),cpuUsage:o=>{const c={user:Math.round((performance.now()-C)*1e3),system:200};return o&&typeof o.user=="number"?{user:Math.max(0,c.user-o.user),system:Math.max(0,c.system-(o.system||0))}:c},emitWarning:(o,c,h)=>{const S=o instanceof Error?o:new Error(String(o));typeof c=="string"&&(S.name=c),typeof h=="string"&&(S.code=h),Ae.emit("warning",S)},hrtime:Gn,stdout:{write:o=>(Y(String(o)),!0),isTTY:!1},stderr:{write:o=>(se(String(o)),!0),isTTY:!1},stdin:Lt,nextTick:(o,...c)=>queueMicrotask(()=>o(...c)),exit:(o=0)=>{if(L=Number(o)||0,!O){O=!0;try{Ae.emit("exit",L)}catch(c){j.debug("process exit listener threw",c)}}if(xn>0)throw new Wn(L)}});let Yt=!1;const gt=()=>{if(!O){Yt=!0,L=130,O=!0;try{Ae.emit("SIGINT")}catch(o){se((o&&o.stack?o.stack:String(o))+`
90
- `)}typeof z._setActiveStdin=="function"&&z._setActiveStdin("");for(const o of B.allTimers)clearTimeout(o),clearInterval(o);if(B.activeTimers.clear(),B.allTimers.clear(),B.activeImmediates.clear(),B.inFlightHttp.clear(),!F){try{Ze.closeAllServers()}catch(o){j.debug("SIGINT vhttp closeAllServers failed",o)}try{Nt.closeAllServers()}catch(o){j.debug("SIGINT vnet closeAllServers failed",o)}}}};let Qt=null;U&&(U.aborted?gt():(Qt=()=>gt(),U.addEventListener("abort",Qt,{once:!0})));const Ar={prefix:"",pendingBefore:[],afterCallbacks:[],beforeEach:[],afterEach:[]},Ct=[];function bt(){return Ct.length>0?Ct[Ct.length-1]:Ar}const en=[];function Jn(o=()=>{}){const c=[];let h=o;const S=[],E=function(...v){const D=S.length>0?S.shift():h;let W,q;try{return W=D.apply(this,v),c.push({arguments:v,result:W,error:void 0,this:this}),W}catch(H){throw q=H,c.push({arguments:v,result:void 0,error:q,this:this}),H}};return E.mock={calls:c,callCount:()=>c.length,resetCalls:()=>{c.length=0},mockImplementation:I=>{h=I},mockImplementationOnce:I=>{S.push(I)},restore:()=>{}},en.push(E.mock),E}const Xn={fn:o=>Jn(o),method:(o,c,h)=>{const S=o[c],E=Jn(h||(typeof S=="function"?S.bind(o):()=>{}));return E.mock.restore=()=>{o[c]=S},o[c]=E,E},reset:()=>{for(const o of en)o.resetCalls(),o.restore();en.length=0},restoreAll:()=>{for(const o of en)o.restore()}};let tn=Promise.resolve();function Tr(o,c,h){if(Ee(o))return Promise.resolve();const S=tn.then(async()=>{if(O)return;for(const v of h.beforeToRun)await v();h.beforeToRun.length=0;for(const v of h.beforeEachList)await v();const E={name:o,mock:Xn,diagnostic:v=>Ye.log(`# ${v}`),test:(v,D,W)=>_e(`${o} > ${v}`,D,W)},I=De(o,()=>c(E));try{await I(),Ye.log(`\u2713 ${o}`)}catch(v){if(v&&v._isProcessExit)throw v;L=1,Ye.log(`\u2717 ${o}
91
- ${v&&v.stack?v.stack:v}`)}finally{for(const v of h.afterEachList)try{await v()}catch(D){j.debug("node:test afterEach hook failed",D)}for(const v of h.afterToRun)try{await v()}catch(D){j.debug("node:test after hook failed",D)}h.afterToRun.length=0}});return tn=S.catch(()=>{}),B.pendingTests.add(S),S.finally(()=>B.pendingTests.delete(S)),S}function _e(o,c,h){const S=typeof c=="function"?c:h;if((typeof c=="object"&&c!==null?c:{}).skip||typeof S!="function")return Promise.resolve();const I=bt(),v=I&&I.prefix?`${I.prefix} > ${o}`:o,D={beforeToRun:I?I.pendingBefore:[],afterToRun:[],beforeEachList:I?[...I.beforeEach]:[],afterEachList:I?[...I.afterEach]:[]};return Tr(v,S,D)}function nn(o,c,h){const S=typeof c=="function"?c:h;if((typeof c=="object"&&c!==null?c:{}).skip||typeof S!="function")return;const I=bt(),D={prefix:I&&I.prefix?`${I.prefix} > ${o}`:o,pendingBefore:[],afterCallbacks:[],beforeEach:I?[...I.beforeEach]:[],afterEach:I?[...I.afterEach]:[]};Ct.push(D);try{S()}finally{if(Ct.pop(),D.afterCallbacks.length>0){const W=[...D.afterCallbacks],q=tn.then(async()=>{for(const H of W)try{await H()}catch(ie){j.debug("node:test suite after hook failed",ie)}});tn=q.catch(()=>{}),B.pendingTests.add(q),q.finally(()=>B.pendingTests.delete(q))}}}_e.test=_e,_e.describe=nn,_e.suite=nn,_e.it=_e,_e.before=o=>{const c=bt();c&&typeof o=="function"&&c.pendingBefore.push(o)},_e.after=o=>{const c=bt();c&&typeof o=="function"&&c.afterCallbacks.push(o)},_e.beforeEach=o=>{const c=bt();c&&typeof o=="function"&&c.beforeEach.push(o)},_e.afterEach=o=>{const c=bt();c&&typeof o=="function"&&c.afterEach.push(o)},_e.mock=Xn;const En={setTimeout:mt,clearTimeout:Gt,setInterval:Jt,clearInterval:Xt,setImmediate:$t,clearImmediate:Kt},An={setTimeout:(o=0,c)=>new Promise(h=>mt(()=>h(c),o)),setImmediate:o=>new Promise(c=>$t(()=>c(o)))};En.promises=An;const Te=[],Tn=new Set;function Rn(o){for(const c of Tn)if(!c._entryTypes||c._entryTypes.includes(o.entryType)){c._records.push(o);const h={getEntries:()=>[o],getEntriesByName:(S,E)=>o.name===S&&(!E||o.entryType===E)?[o]:[],getEntriesByType:S=>o.entryType===S?[o]:[]};try{c._cb(h,c)}catch(S){j.debug("PerformanceObserver callback failed",S)}}}const _t={now:()=>performance.now()-C,timeOrigin:performance.timeOrigin||Date.now(),mark(o,c={}){const h={name:String(o),entryType:"mark",startTime:c&&typeof c.startTime=="number"?c.startTime:_t.now(),duration:0,detail:c&&c.detail!==void 0?c.detail:null};return Te.push(h),Rn(h),h},measure(o,c,h){let S=0,E=_t.now(),I=null;if(typeof c=="object"&&c!==null){if(I=c.detail!==void 0?c.detail:null,typeof c.start=="number")S=c.start;else if(typeof c.start=="string"){const D=[...Te].reverse().find(W=>W.name===c.start&&W.entryType==="mark");D&&(S=D.startTime)}if(typeof c.end=="number")E=c.end;else if(typeof c.end=="string"){const D=[...Te].reverse().find(W=>W.name===c.end&&W.entryType==="mark");D&&(E=D.startTime)}else typeof c.duration=="number"&&(E=S+c.duration)}else{if(typeof c=="string"){const D=[...Te].reverse().find(W=>W.name===c&&W.entryType==="mark");D&&(S=D.startTime)}if(typeof h=="string"){const D=[...Te].reverse().find(W=>W.name===h&&W.entryType==="mark");D&&(E=D.startTime)}}const v={name:String(o),entryType:"measure",startTime:S,duration:Math.max(0,E-S),detail:I};return Te.push(v),Rn(v),v},getEntries:()=>[...Te],getEntriesByName:(o,c)=>Te.filter(h=>h.name===o&&(!c||h.entryType===c)),getEntriesByType:o=>Te.filter(c=>c.entryType===o),clearMarks(o){for(let c=Te.length-1;c>=0;c--)Te[c].entryType==="mark"&&(!o||Te[c].name===o)&&Te.splice(c,1)},clearMeasures(o){for(let c=Te.length-1;c>=0;c--)Te[c].entryType==="measure"&&(!o||Te[c].name===o)&&Te.splice(c,1)},timerify(o){return function(...h){const S=_t.now();try{return o.apply(this,h)}finally{const E=_t.now(),I={name:o.name||"anonymous",entryType:"function",startTime:S,duration:E-S,detail:h};Te.push(I),Rn(I)}}}};class Kn{constructor(c){this._cb=c,this._entryTypes=null,this._records=[]}observe(c={}){if(Array.isArray(c.entryTypes)?this._entryTypes=c.entryTypes:c.type&&(this._entryTypes=[c.type]),Tn.add(this),c.buffered&&this._entryTypes){const h=Te.filter(S=>this._entryTypes.includes(S.entryType));if(h.length>0){const S={getEntries:()=>h,getEntriesByName:(E,I)=>h.filter(v=>v.name===E&&(!I||v.entryType===I)),getEntriesByType:E=>h.filter(I=>I.entryType===E)};queueMicrotask(()=>{try{this._cb(S,this)}catch(E){j.debug("PerformanceObserver buffered callback failed",E)}})}}}disconnect(){Tn.delete(this)}takeRecords(){const c=[...this._records];return this._records.length=0,c}}const Yn={performance:_t,PerformanceObserver:Kn,monitorEventLoopDelay:()=>({enable(){return!0},disable(){return!0},reset(){},percentile(){return 0},min:0,max:0,mean:0,stddev:0,percentiles:new Map}),constants:{NODE_PERFORMANCE_GC_MAJOR:4,NODE_PERFORMANCE_GC_MINOR:1}};let rn=2e3;function Rr(o){const c=[];let h="",S=null;for(let E=0;E<o.length;E++){const I=o[E];S?I===S?S=null:I==="\\"&&S==='"'&&E+1<o.length?h+=o[++E]:h+=I:I==='"'||I==="'"?S=I:/\s/.test(I)?h.length>0&&(c.push(h),h=""):h+=I}return h.length>0&&c.push(h),c}function vn(o,c=[],h={}){const S=h.cwd?J.resolve(be,h.cwd):be,E=Object.assign({},Ae.env,h.env||{});let I="",v="",D=0;if(o==="echo")I=c.join(" ")+`
92
- `;else if(o==="pwd")I=S+`
93
- `;else if(o==="true")D=0;else if(o==="false")D=1;else if(o==="env"||o==="printenv")I=Object.entries(E).map(([W,q])=>`${W}=${q}`).join(`
89
+ `)&&c.pop();for(const h of c)Qe.push(h);Lt.write(t.stdin),typeof t.onRequestStdin!="function"&&Lt.end()}else(!t||typeof t.onRequestStdin!="function")&&Lt.end();const Ae=Object.assign(new fe,{env:Object.assign({NODE_ENV:"development",PATH:"/usr/local/bin:/usr/bin:/bin",HOME:Mt},t.env||{}),argv:u||["node",n.startsWith("/")?n:J.resolve(_e,n)],argv0:"node",execArgv:[],execPath:"/usr/local/bin/node",pid:L,ppid:1,title:"node",version:"v22.0.0",versions:{node:"22.0.0",v8:"12.4",uv:"1.48.0",modules:"127"},platform:"linux",arch:"x64",cwd:()=>_e,chdir:o=>{const c=J.resolve(_e,String(o));if(!V.existsSync(c)){const h=new Error(`ENOENT: no such file or directory, chdir '${o}'`);throw h.code="ENOENT",h}if(!V.statSync(c).isDirectory()){const h=new Error(`ENOTDIR: not a directory, chdir '${o}'`);throw h.code="ENOTDIR",h}_e=c},uptime:()=>Math.max(0,(performance.now()-U)/1e3),memoryUsage:()=>({rss:33554432,heapTotal:16777216,heapUsed:8388608,external:1048576,arrayBuffers:524288}),cpuUsage:o=>{const c={user:Math.round((performance.now()-U)*1e3),system:200};return o&&typeof o.user=="number"?{user:Math.max(0,c.user-o.user),system:Math.max(0,c.system-(o.system||0))}:c},emitWarning:(o,c,h)=>{const _=o instanceof Error?o:new Error(String(o));typeof c=="string"&&(_.name=c),typeof h=="string"&&(_.code=h),Ae.emit("warning",_)},hrtime:Gn,stdout:{write:o=>(Y(String(o)),!0),isTTY:!1},stderr:{write:o=>(ee(String(o)),!0),isTTY:!1},stdin:Lt,nextTick:(o,...c)=>queueMicrotask(()=>o(...c)),exit:(o=0)=>{if($=Number(o)||0,!j){j=!0;try{Ae.emit("exit",$)}catch(c){D.debug("process exit listener threw",c)}}if(xn>0)throw new On($)}});let Yt=!1;const gt=()=>{if(!j){Yt=!0,$=130,j=!0;try{Ae.emit("SIGINT")}catch(o){ee((o&&o.stack?o.stack:String(o))+`
90
+ `)}typeof V._setActiveStdin=="function"&&V._setActiveStdin("");for(const o of C.allTimers)clearTimeout(o),clearInterval(o);if(C.activeTimers.clear(),C.allTimers.clear(),C.activeImmediates.clear(),C.inFlightHttp.clear(),!B){try{Ze.closeAllServers()}catch(o){D.debug("SIGINT vhttp closeAllServers failed",o)}try{Nt.closeAllServers()}catch(o){D.debug("SIGINT vnet closeAllServers failed",o)}}}};let Qt=null;F&&(F.aborted?gt():(Qt=()=>gt(),F.addEventListener("abort",Qt,{once:!0})));const Ar={prefix:"",pendingBefore:[],afterCallbacks:[],beforeEach:[],afterEach:[]},Ct=[];function bt(){return Ct.length>0?Ct[Ct.length-1]:Ar}const en=[];function Jn(o=()=>{}){const c=[];let h=o;const _=[],E=function(...I){const P=_.length>0?_.shift():h;let W,q;try{return W=P.apply(this,I),c.push({arguments:I,result:W,error:void 0,this:this}),W}catch(H){throw q=H,c.push({arguments:I,result:void 0,error:q,this:this}),H}};return E.mock={calls:c,callCount:()=>c.length,resetCalls:()=>{c.length=0},mockImplementation:M=>{h=M},mockImplementationOnce:M=>{_.push(M)},restore:()=>{}},en.push(E.mock),E}const Xn={fn:o=>Jn(o),method:(o,c,h)=>{const _=o[c],E=Jn(h||(typeof _=="function"?_.bind(o):()=>{}));return E.mock.restore=()=>{o[c]=_},o[c]=E,E},reset:()=>{for(const o of en)o.resetCalls(),o.restore();en.length=0},restoreAll:()=>{for(const o of en)o.restore()}};let tn=Promise.resolve();function Tr(o,c,h){if(be(o))return Promise.resolve();const _=tn.then(async()=>{if(j)return;for(const I of h.beforeToRun)await I();h.beforeToRun.length=0;for(const I of h.beforeEachList)await I();const E={name:o,mock:Xn,diagnostic:I=>Ye.log(`# ${I}`),test:(I,P,W)=>we(`${o} > ${I}`,P,W)},M=Me(o,()=>c(E));try{await M(),Ye.log(`\u2713 ${o}`)}catch(I){if(I&&I._isProcessExit)throw I;$=1,Ye.log(`\u2717 ${o}
91
+ ${I&&I.stack?I.stack:I}`)}finally{for(const I of h.afterEachList)try{await I()}catch(P){D.debug("node:test afterEach hook failed",P)}for(const I of h.afterToRun)try{await I()}catch(P){D.debug("node:test after hook failed",P)}h.afterToRun.length=0}});return tn=_.catch(()=>{}),C.pendingTests.add(_),_.finally(()=>C.pendingTests.delete(_)),_}function we(o,c,h){const _=typeof c=="function"?c:h;if((typeof c=="object"&&c!==null?c:{}).skip||typeof _!="function")return Promise.resolve();const M=bt(),I=M&&M.prefix?`${M.prefix} > ${o}`:o,P={beforeToRun:M?M.pendingBefore:[],afterToRun:[],beforeEachList:M?[...M.beforeEach]:[],afterEachList:M?[...M.afterEach]:[]};return Tr(I,_,P)}function nn(o,c,h){const _=typeof c=="function"?c:h;if((typeof c=="object"&&c!==null?c:{}).skip||typeof _!="function")return;const M=bt(),P={prefix:M&&M.prefix?`${M.prefix} > ${o}`:o,pendingBefore:[],afterCallbacks:[],beforeEach:M?[...M.beforeEach]:[],afterEach:M?[...M.afterEach]:[]};Ct.push(P);try{_()}finally{if(Ct.pop(),P.afterCallbacks.length>0){const W=[...P.afterCallbacks],q=tn.then(async()=>{for(const H of W)try{await H()}catch(ie){D.debug("node:test suite after hook failed",ie)}});tn=q.catch(()=>{}),C.pendingTests.add(q),q.finally(()=>C.pendingTests.delete(q))}}}we.test=we,we.describe=nn,we.suite=nn,we.it=we,we.before=o=>{const c=bt();c&&typeof o=="function"&&c.pendingBefore.push(o)},we.after=o=>{const c=bt();c&&typeof o=="function"&&c.afterCallbacks.push(o)},we.beforeEach=o=>{const c=bt();c&&typeof o=="function"&&c.beforeEach.push(o)},we.afterEach=o=>{const c=bt();c&&typeof o=="function"&&c.afterEach.push(o)},we.mock=Xn;const En={setTimeout:mt,clearTimeout:Gt,setInterval:Jt,clearInterval:Xt,setImmediate:$t,clearImmediate:Kt},An={setTimeout:(o=0,c)=>new Promise(h=>mt(()=>h(c),o)),setImmediate:o=>new Promise(c=>$t(()=>c(o)))};En.promises=An;const Te=[],Tn=new Set;function Rn(o){for(const c of Tn)if(!c._entryTypes||c._entryTypes.includes(o.entryType)){c._records.push(o);const h={getEntries:()=>[o],getEntriesByName:(_,E)=>o.name===_&&(!E||o.entryType===E)?[o]:[],getEntriesByType:_=>o.entryType===_?[o]:[]};try{c._cb(h,c)}catch(_){D.debug("PerformanceObserver callback failed",_)}}}const _t={now:()=>performance.now()-U,timeOrigin:performance.timeOrigin||Date.now(),mark(o,c={}){const h={name:String(o),entryType:"mark",startTime:c&&typeof c.startTime=="number"?c.startTime:_t.now(),duration:0,detail:c&&c.detail!==void 0?c.detail:null};return Te.push(h),Rn(h),h},measure(o,c,h){let _=0,E=_t.now(),M=null;if(typeof c=="object"&&c!==null){if(M=c.detail!==void 0?c.detail:null,typeof c.start=="number")_=c.start;else if(typeof c.start=="string"){const P=[...Te].reverse().find(W=>W.name===c.start&&W.entryType==="mark");P&&(_=P.startTime)}if(typeof c.end=="number")E=c.end;else if(typeof c.end=="string"){const P=[...Te].reverse().find(W=>W.name===c.end&&W.entryType==="mark");P&&(E=P.startTime)}else typeof c.duration=="number"&&(E=_+c.duration)}else{if(typeof c=="string"){const P=[...Te].reverse().find(W=>W.name===c&&W.entryType==="mark");P&&(_=P.startTime)}if(typeof h=="string"){const P=[...Te].reverse().find(W=>W.name===h&&W.entryType==="mark");P&&(E=P.startTime)}}const I={name:String(o),entryType:"measure",startTime:_,duration:Math.max(0,E-_),detail:M};return Te.push(I),Rn(I),I},getEntries:()=>[...Te],getEntriesByName:(o,c)=>Te.filter(h=>h.name===o&&(!c||h.entryType===c)),getEntriesByType:o=>Te.filter(c=>c.entryType===o),clearMarks(o){for(let c=Te.length-1;c>=0;c--)Te[c].entryType==="mark"&&(!o||Te[c].name===o)&&Te.splice(c,1)},clearMeasures(o){for(let c=Te.length-1;c>=0;c--)Te[c].entryType==="measure"&&(!o||Te[c].name===o)&&Te.splice(c,1)},timerify(o){return function(...h){const _=_t.now();try{return o.apply(this,h)}finally{const E=_t.now(),M={name:o.name||"anonymous",entryType:"function",startTime:_,duration:E-_,detail:h};Te.push(M),Rn(M)}}}};class Kn{constructor(c){this._cb=c,this._entryTypes=null,this._records=[]}observe(c={}){if(Array.isArray(c.entryTypes)?this._entryTypes=c.entryTypes:c.type&&(this._entryTypes=[c.type]),Tn.add(this),c.buffered&&this._entryTypes){const h=Te.filter(_=>this._entryTypes.includes(_.entryType));if(h.length>0){const _={getEntries:()=>h,getEntriesByName:(E,M)=>h.filter(I=>I.name===E&&(!M||I.entryType===M)),getEntriesByType:E=>h.filter(M=>M.entryType===E)};queueMicrotask(()=>{try{this._cb(_,this)}catch(E){D.debug("PerformanceObserver buffered callback failed",E)}})}}}disconnect(){Tn.delete(this)}takeRecords(){const c=[...this._records];return this._records.length=0,c}}const Yn={performance:_t,PerformanceObserver:Kn,monitorEventLoopDelay:()=>({enable(){return!0},disable(){return!0},reset(){},percentile(){return 0},min:0,max:0,mean:0,stddev:0,percentiles:new Map}),constants:{NODE_PERFORMANCE_GC_MAJOR:4,NODE_PERFORMANCE_GC_MINOR:1}};let rn=2e3;function Rr(o){const c=[];let h="",_=null;for(let E=0;E<o.length;E++){const M=o[E];_?M===_?_=null:M==="\\"&&_==='"'&&E+1<o.length?h+=o[++E]:h+=M:M==='"'||M==="'"?_=M:/\s/.test(M)?h.length>0&&(c.push(h),h=""):h+=M}return h.length>0&&c.push(h),c}function vn(o,c=[],h={}){const _=h.cwd?J.resolve(_e,h.cwd):_e,E=Object.assign({},Ae.env,h.env||{});let M="",I="",P=0;if(o==="echo")M=c.join(" ")+`
92
+ `;else if(o==="pwd")M=_+`
93
+ `;else if(o==="true")P=0;else if(o==="false")P=1;else if(o==="env"||o==="printenv")M=Object.entries(E).map(([W,q])=>`${W}=${q}`).join(`
94
94
  `)+`
95
- `;else if(o==="ls"){const W=c.find(H=>!H.startsWith("-"))||S,q=J.resolve(S,W);try{I=z.readdirSync(q).join(`
95
+ `;else if(o==="ls"){const W=c.find(H=>!H.startsWith("-"))||_,q=J.resolve(_,W);try{M=V.readdirSync(q).join(`
96
96
  `)+`
97
- `}catch(H){v=H.message+`
98
- `,D=1}}else if(o==="cat")for(const W of c){const q=J.resolve(S,W);try{I+=z.readFileSync(q,"utf8")}catch(H){v+=H.message+`
99
- `,D=1}}else if(o==="node"||o==="/usr/local/bin/node"){let W=null,q=-1;for(let G=0;G<c.length;G++)if(c[G]==="-e"||c[G]==="--eval"){W=c[G+1]||"";break}else if(c[G]==="-p"||c[G]==="--print"){W=`console.log(${c[G+1]||""});`;break}else if(!c[G].startsWith("-")){q=G;break}let H=!1;const ie=G=>{if(H||R)return;const ae=String(G);if(I.length+ae.length>b||_+ae.length>b){const we=Math.max(0,Math.min(b-I.length,b-_));if(we>0){const Ue=ae.slice(0,we);I+=Ue,_+=Ue.length}I+=V,H=!0,re(w,u);return}I+=ae,_+=ae.length},me=G=>{if(H||R)return;const ae=String(G);if(v.length+ae.length>b||_+ae.length>b){const we=Math.max(0,Math.min(b-v.length,b-_));if(we>0){const Ue=ae.slice(0,we);v+=Ue,_+=Ue.length}v+=V,H=!0,re(g,d);return}v+=ae,_+=ae.length},ve=Hn(ie,me),oe=Object.assign(new fe,Ae,{env:E,argv:q>=0?["node",J.resolve(S,c[q]),...c.slice(q+1)]:["node"],cwd:()=>S,stdout:{write:G=>(ie(G),!0),isTTY:!1},stderr:{write:G=>(me(G),!0),isTTY:!1},exit:(G=0)=>{throw D=Number(G)||0,new Wn(D)}});try{let G=W,ae=J.join(S,"__eval__.js");if(G===null&&q>=0){const we=c[q];ae=St(J.resolve(S,we))||lt(we,S),G=z.readFileSync(ae,"utf8")}if(G!==null){const we=J.dirname(ae),Ue=pt(G,ae),ir={id:ae,filename:ae,loaded:!1,exports:{}},Xr=Bt=>{if(Object.prototype.hasOwnProperty.call(Me,Bt))return Me[Bt];if(at.has(Bt))return at.get(Bt);const Kr=lt(Bt,we);return Ft(Kr,!1)};new Function("exports","require","module","__filename","__dirname","Buffer","process","console",Ue)(ir.exports,Xr,ir,ae,we,P,oe,ve)}}catch(G){G&&G._isProcessExit?D=G.exitCode:(D=1,v+=(G&&G.stack?G.stack:String(G))+`
100
- `)}}else v=`${o}: command not found
101
- `,D=127;return{status:D,stdout:I,stderr:v,pid:rn++}}function sn(o,c={}){const h=Rr(String(o).trim());return h.length===0?{status:0,stdout:"",stderr:"",pid:rn++}:vn(h[0],h.slice(1),c)}const ft={execSync(o,c={}){const h=sn(o,c),S=typeof c=="string"?c:c&&c.encoding,E=S&&S!=="buffer"?h.stdout:P.from(h.stdout),I=S&&S!=="buffer"?h.stderr:P.from(h.stderr);if(h.status!==0){const v=new Error(`Command failed: ${o}
102
- ${h.stderr}`);throw v.status=h.status,v.stdout=E,v.stderr=I,v}return E},spawnSync(o,c=[],h={}){Array.isArray(c)||(h=c||{},c=[]);const S=h.shell?sn([o,...c].join(" "),h):vn(o,c,h),E=h&&h.encoding,I=E&&E!=="buffer"?S.stdout:P.from(S.stdout),v=E&&E!=="buffer"?S.stderr:P.from(S.stderr);return{pid:S.pid,output:[null,I,v],stdout:I,stderr:v,status:S.status,signal:null,error:null}},exec(o,c,h){const S=typeof c=="function"?c:h,E=typeof c=="object"&&c!==null?c:{},I=Object.assign(new fe,{pid:rn++,stdout:new He,stderr:new He,stdin:new He,killed:!1,kill(){return this.killed=!0,!0}});return queueMicrotask(()=>{const v=sn(o,E);if(v.stdout&&I.stdout.write(v.stdout),I.stdout.end(),v.stderr&&I.stderr.write(v.stderr),I.stderr.end(),I.emit("exit",v.status,null),I.emit("close",v.status,null),typeof S=="function")if(v.status!==0){const D=new Error(`Command failed: ${o}
103
- ${v.stderr}`);D.code=v.status,S(D,v.stdout,v.stderr)}else S(null,v.stdout,v.stderr)}),I},execFile(o,c,h,S){let E=[],I={},v=S;return Array.isArray(c)?(E=c,typeof h=="function"?v=h:h&&(I=h)):typeof c=="function"?v=c:c&&(I=c,typeof h=="function"&&(v=h)),ft.exec([o,...E].join(" "),I,v)},spawn(o,c=[],h={}){Array.isArray(c)||(h=c||{},c=[]);const S=Object.assign(new fe,{pid:rn++,stdout:new He,stderr:new He,stdin:new He,killed:!1,kill(){return this.killed=!0,!0}});return queueMicrotask(()=>{const E=h.shell?sn([o,...c].join(" "),h):vn(o,c,h);E.stdout&&S.stdout.write(P.from(E.stdout)),S.stdout.end(),E.stderr&&S.stderr.write(P.from(E.stderr)),S.stderr.end(),S.emit("exit",E.status,null),S.emit("close",E.status,null)}),S}};ft.exec[vt.custom]=(o,c={})=>new Promise((h,S)=>{ft.exec(o,c,(E,I,v)=>{E?(E.stdout=I,E.stderr=v,S(E)):h({stdout:I,stderr:v})})}),ft.execFile[vt.custom]=(o,c=[],h={})=>new Promise((S,E)=>{ft.execFile(o,c,h,(I,v,D)=>{I?(I.stdout=v,I.stderr=D,E(I)):S({stdout:v,stderr:D})})});const vr=qn(z,()=>Ae.cwd());function on(o){return xe.crc32(typeof o=="string"||o instanceof Uint8Array?o:String(o))}const kn=function(c){return on(c)};kn.crc32=o=>on(o),kn.cityHash64=o=>{const c=on(o),h=on(String(o)+":seed64");return BigInt(c)<<32n|BigInt(h)};function In(o,c){return Ge(o,c,!0)}const et=new Set,Ut={version:"1.1.0",serve(o={}){const c=Number(o.port||3e3),h=o.hostname||"127.0.0.1",S={port:c,hostname:h,development:!1,stop(){et.delete(S),Pe.unregisterServer(c)}};return Pe.registerServer(c,{server:S,name:o.name||"bun-server",port:c,pid:B.pid||1,fetch:o.fetch?o.fetch.bind(S):void 0,stop:()=>S.stop()}),et.add(S),S},file(o){const c=J.resolve(Ae.cwd(),String(o));return{name:J.basename(c),get size(){try{return z.statSync(c).size}catch{return 0}},async exists(){return z.existsSync(c)},async text(){return z.readFileSync(c,"utf8")},async json(){return JSON.parse(z.readFileSync(c,"utf8"))},async arrayBuffer(){const h=z.readFileSync(c);return h.buffer.slice(h.byteOffset,h.byteOffset+h.byteLength)}}},async write(o,c){const h=J.resolve(Ae.cwd(),String(o)),S=J.dirname(h);z.existsSync(S)||z.mkdirSync(S,{recursive:!0});let E;if(typeof c=="string")E=P.from(c,"utf8");else if(c&&c.arrayBuffer&&typeof c.arrayBuffer=="function"){const I=await c.arrayBuffer();E=P.from(I)}else c instanceof Uint8Array||P.isBuffer(c)?E=P.from(c):E=P.from(String(c),"utf8");return z.writeFileSync(h,E),E.length},sleep(o){return new Promise(c=>mt(c,Number(o)||0))},hash:kn,deepEquals:In,inspect(o){return kt.inspect(o)},nanoseconds(){return Math.round(performance.now()*1e6)}},kr=(()=>{function o(h,S=!1){const E=(v,D)=>{if(!(S?!v:v))throw new Error(D||`expect assertion failed: actual=${h}`)},I={toBe(v){E(Object.is(h,v),`Expected ${h} to be ${v}`)},toEqual(v){E(In(h,v),`Expected ${JSON.stringify(h)} to equal ${JSON.stringify(v)}`)},toContain(v){let D=!1;h&&typeof h.includes=="function"?D=h.includes(v):h&&typeof h.has=="function"&&(D=h.has(v)),E(D,`Expected collection to contain ${v}`)},toThrow(v){let D=!1,W=null;try{typeof h=="function"&&h()}catch(q){D=!0,W=q}if(!D){E(!1,"Expected function to throw");return}if(v){const q=W&&W.message?W.message:String(W);typeof v=="string"?E(q.includes(v),`Expected error message "${q}" to contain "${v}"`):v instanceof RegExp&&E(v.test(q),`Expected error message "${q}" to match ${v}`)}else E(!0)},toBeTruthy(){E(!!h,`Expected ${h} to be truthy`)},toBeFalsy(){E(!h,`Expected ${h} to be falsy`)},toBeGreaterThan(v){E(h>v,`Expected ${h} to be greater than ${v}`)},toBeLessThan(v){E(h<v,`Expected ${h} to be less than ${v}`)},toHaveBeenCalled(){const v=h&&h.mock&&h.mock.calls||[];E(v.length>0,"Expected mock function to have been called")},toHaveBeenCalledTimes(v){const D=h&&h.mock&&h.mock.calls||[];E(D.length===v,`Expected mock function to have been called ${v} times, was called ${D.length}`)},toHaveBeenCalledWith(...v){const W=(h&&h.mock&&h.mock.calls||[]).some(q=>{const H=Array.isArray(q)?q:q&&Array.isArray(q.arguments)?q.arguments:[];return In(H,v)});E(W,`Expected mock to have been called with ${JSON.stringify(v)}`)}};return S||(I.not=o(h,!0)),I}function c(h){const S=[],E=[],I=function(...v){S.push(v);let D;try{return typeof h=="function"&&(D=h.apply(this,v)),E.push({type:"return",value:D}),D}catch(W){throw E.push({type:"throw",value:W}),W}};return I.mock={calls:S,results:E},I}return{describe:(h,S)=>nn(h,S),test:(h,S)=>_e(h,S),it:(h,S)=>_e(h,S),expect:h=>o(h),mock:h=>c(h),beforeAll:h=>_e.before(h),afterAll:h=>_e.after(h),beforeEach:h=>_e.beforeEach(h),afterEach:h=>_e.afterEach(h)}})(),Ir={isatty(){return!1},ReadStream:class extends fe{},WriteStream:class extends fe{constructor(c){super(),this.fd=c,this.columns=80,this.rows=24,this.isTTY=!1}getColorDepth(){return 1}hasColors(){return!1}cursorTo(){return!0}clearLine(){return!0}moveCursor(){return!0}}};function Mn(o){if(o&&Y(String(o)),Qe.length>0)return Promise.resolve(Qe.shift());if(t&&typeof t.onRequestStdin=="function"&&!O){const c={};return B.inFlightHttp.add(c),Promise.resolve(t.onRequestStdin("")).then(h=>{if(B.inFlightHttp.delete(c),h==null)return null;const S=String(h);return Lt.write(S+`
104
- `),S}).catch(()=>(B.inFlightHttp.delete(c),null))}return Promise.resolve(null)}function Qn(o){const c=new fe;let h=!1,S=o&&typeof o.prompt=="string"?o.prompt:"> ";return c.terminal=!1,c.line="",c.cursor=0,c.question=(E,I,v)=>{const D=typeof I=="function"?I:v;Mn(E).then(W=>{const q=W===null?"":W;c.line=q,typeof D=="function"&&!h&&!O&&D(q)})},c.prompt=()=>{Y(S)},c.setPrompt=E=>{S=String(E??"")},c.getPrompt=()=>S,c.write=E=>{E!=null&&Y(String(E))},c.pause=()=>c,c.resume=()=>(queueMicrotask(async()=>{for(;!h&&!O&&Qe.length>0;){const E=Qe.shift();c.line=E,c.emit("line",E)}}),c),c.close=()=>(h||(h=!0,queueMicrotask(()=>c.emit("close"))),c),c[Symbol.asyncIterator]=async function*(){for(;!h&&!O;){const E=await Mn("");if(E===null)break;c.line=E,yield E}},queueMicrotask(()=>{if(c.listenerCount("line")>0&&Qe.length>0){for(;!h&&!O&&Qe.length>0;){const E=Qe.shift();c.line=E,c.emit("line",E)}(!t||typeof t.onRequestStdin!="function")&&c.close()}}),c}const Mr={createInterface:Qn,Interface:class extends fe{},clearLine:()=>!0,clearScreenDown:()=>!0,cursorTo:()=>!0,moveCursor:()=>!0,emitKeypressEvents:()=>{}},Nr={createInterface:o=>{const c=Qn(o);return c.question=h=>Mn(h).then(S=>S===null?"":S),c},Interface:class extends fe{}},$r={AsyncLocalStorage:class{constructor(){this._store=void 0}getStore(){return this._store}run(c,h,...S){const E=this._store;this._store=c;try{return h(...S)}finally{this._store=E}}exit(c,...h){const S=this._store;this._store=void 0;try{return c(...h)}finally{this._store=S}}enterWith(c){this._store=c}disable(){this._store=void 0}},AsyncResource:class{constructor(c){this.type=c||"AsyncResource"}runInAsyncScope(c,h,...S){return c.apply(h,S)}emitDestroy(){return this}asyncId(){return 0}triggerAsyncId(){return 0}static bind(c){return c}},createHook(){return{enable(){},disable(){}}},executionAsyncId(){return 0},triggerAsyncId(){return 0},executionAsyncResource(){return null}},Lr={isMainThread:!0,threadId:0,parentPort:null,workerData:null,resourceLimits:{},SHARE_ENV:Symbol("nodejs.worker_threads.SHARE_ENV"),receiveMessageOnPort(){},Worker:class extends fe{constructor(c){super(),this.threadId=-1,this.filename=c,queueMicrotask(()=>this.emit("error",new Error("worker_threads.Worker is not supported in the virtual runtime.")))}postMessage(){}terminate(){return Promise.resolve(0)}ref(){return this}unref(){return this}},MessageChannel:class{},MessagePort:class extends fe{}},Cr={serialize(o){return P.from(JSON.stringify(o===void 0?null:o),"utf8")},deserialize(o){try{return JSON.parse(String(o))}catch{return}},getHeapStatistics(){return{total_heap_size:0,total_heap_size_executable:0,total_physical_size:0,total_available_size:0,used_heap_size:0,heap_size_limit:0,malloced_memory:0,peak_malloced_memory:0,does_zap_garbage:0,number_of_native_contexts:1,number_of_detached_contexts:0}},getHeapSpaceStatistics(){return[]},setFlagsFromString(){},cachedDataVersionTag(){return 0},Serializer:class{constructor(){this._value=void 0}writeHeader(){}writeValue(c){this._value=c}releaseBuffer(){return P.from(JSON.stringify(this._value===void 0?null:this._value),"utf8")}},Deserializer:class{constructor(c){this._buffer=c}readHeader(){return!0}readValue(){try{return JSON.parse(String(this._buffer))}catch{return}}}},Ur={createContext(o){return o&&typeof o=="object"?o:{}},isContext(){return!1},createScript(){throw new Error("vm code compilation is not supported in the virtual runtime.")},runInContext(){throw new Error("vm.runInContext is not supported in the virtual runtime.")},runInNewContext(){throw new Error("vm.runInNewContext is not supported in the virtual runtime.")},runInThisContext(){throw new Error("vm.runInThisContext is not supported in the virtual runtime.")},compileFunction(){throw new Error("vm.compileFunction is not supported in the virtual runtime.")},Script:class{runInThisContext(){throw new Error("vm.Script is not supported in the virtual runtime.")}runInContext(){throw new Error("vm.Script is not supported in the virtual runtime.")}runInNewContext(){throw new Error("vm.Script is not supported in the virtual runtime.")}}},er={create(){const o=new fe;return o.members=[],o.add=()=>o,o.remove=()=>o,o.bind=c=>c,o.intercept=c=>c,o.run=(c,...h)=>c(...h),o.dispose=()=>o,o},createDomain(){return er.create()}},wt={_channels:new Map,channel(o){const c=String(o);if(!wt._channels.has(c)){const h=new fe;h.name=c,h.hasSubscribers=!1,h.subscribe=()=>{h.hasSubscribers=!0},h.unsubscribe=()=>{h.hasSubscribers=!1},wt._channels.set(c,h)}return wt._channels.get(c)},subscribe(o,c){const h=wt.channel(o);h.subscribe(),typeof c=="function"&&h.on("message",c)},unsubscribe(o){wt.channel(o).unsubscribe()},Channel:class extends fe{}},ze=o=>()=>{throw new Error(o+" is not supported in the virtual runtime.")},Fr={DEFAULT_MIN_VERSION:"TLSv1.2",DEFAULT_MAX_VERSION:"TLSv1.3",rootCertificates:[],createSecureContext(){return{context:{}}},SecureContext:class{},TLSSocket:class extends fe{},Server:class extends fe{},checkServerIdentity(){},connect:ze("tls.connect"),createServer:ze("tls.createServer")},Br={createSocket(o){const c=new fe;return c.type=o||"udp4",c.bind=(...h)=>{const S=h[h.length-1];return typeof S=="function"&&queueMicrotask(S),c},c.close=h=>(queueMicrotask(()=>{c.emit("close"),typeof h=="function"&&h()}),c),c.send=ze("dgram.send"),c.address=()=>({address:"0.0.0.0",family:"IPv4",port:0}),c.setBroadcast=()=>c,c.setTTL=()=>c,c.addMembership=()=>{},c.dropMembership=()=>{},c},Socket:class extends fe{}},jr={constants:{NGHTTP2_REFUSED_STREAM:7,NGHTTP2_CANCEL:8},connect:ze("http2.connect"),createServer:ze("http2.createServer"),createSecureServer:ze("http2.createSecureServer")},Dr={isPrimary:!0,isMaster:!0,isWorker:!1,workers:{},fork:ze("cluster.fork"),setupPrimary:ze("cluster.setupPrimary"),setupMaster:ze("cluster.setupMaster"),disconnect:()=>{}},Pr={start:ze("repl.start")},Wr={open:()=>null,close:()=>{},url:()=>"",Session:class{connect(){}disconnect(){}post(){}}},Or={createTracing:()=>({enable(){},disable(){}}),getEnabledCategories:()=>""},qr=wn({vfs:z,onStdout:Y,onStderr:se}),zr={ReadableStream:typeof ReadableStream<"u"?ReadableStream:void 0,WritableStream:typeof WritableStream<"u"?WritableStream:void 0,TransformStream:typeof TransformStream<"u"?TransformStream:void 0};async function cn(o,c){const h=[];if(c&&typeof c[Symbol.asyncIterator]=="function")for await(const I of c)h.push(I);else c&&typeof c.on=="function"&&await new Promise((I,v)=>{c.on("data",D=>h.push(D)),c.on("end",I),c.on("error",v)});const S=h.map(I=>P.from(I)),E=P.concat(S);return o==="buffer"?E:o==="arrayBuffer"?E.buffer?E.buffer.slice(E.byteOffset,E.byteOffset+E.byteLength):new ArrayBuffer(0):o==="text"?E.toString("utf8"):o==="json"?JSON.parse(E.toString("utf8")):E}const Zr={text:o=>cn("text",o),json:o=>cn("json",o),buffer:o=>cn("buffer",o),arrayBuffer:o=>cn("arrayBuffer",o)},Me={fs:z,"node:fs":z,"fs/promises":z.promises,"node:fs/promises":z.promises,path:J,"node:path":J,os:ln,"node:os":ln,crypto:Fe,"node:crypto":Fe,zlib:xe,"node:zlib":xe,http:Ze,"node:http":Ze,https:Ze,"node:https":Ze,net:Nt,"node:net":Nt,dns:It,"node:dns":It,"dns/promises":It.promises,"node:dns/promises":It.promises,string_decoder:pn,"node:string_decoder":pn,child_process:ft,"node:child_process":ft,process:Ae,"node:process":Ae,console:Ye,"node:console":Ye,assert:pe,"node:assert":pe,"assert/strict":pe.strict,"node:assert/strict":pe.strict,events:fe,"node:events":fe,util:kt,"node:util":kt,url:At,"node:url":At,querystring:$e,"node:querystring":$e,stream:hn,"node:stream":hn,"stream/promises":Wt,"node:stream/promises":Wt,test:_e,"node:test":_e,perf_hooks:Yn,"node:perf_hooks":Yn,timers:En,"node:timers":En,"timers/promises":An,"node:timers/promises":An,buffer:{Buffer:P},"node:buffer":{Buffer:P},bun:Ut,"node:bun":Ut,"bun:test":kr,"bun:sqlite":{Database:vr},tty:Ir,tls:Fr,dgram:Br,readline:Mr,"readline/promises":Nr,async_hooks:$r,worker_threads:Lr,v8:Cr,vm:Ur,domain:er,diagnostics_channel:wt,http2:jr,cluster:Dr,repl:Pr,inspector:Wr,trace_events:Or,wasi:qr,constants:z.constants,"util/types":kt.types,"stream/web":zr,"stream/consumers":Zr};for(const o of Object.keys(Me))!o.startsWith("node:")&&!o.startsWith("bun:")&&(Me["node:"+o]=Me[o]);const tr={builtinModules:Object.keys(Me),Module:class{},isBuiltin(o){return Object.prototype.hasOwnProperty.call(Me,String(o))},createRequire(o){const c=typeof o=="string"?o:"/workspace",h=/\.(?:js|mjs|cjs|ts|json)$/.test(c)?J.dirname(c):c,S=E=>Object.prototype.hasOwnProperty.call(Me,E)?Me[E]:Ft(lt(E,h),!1);return S.resolve=E=>lt(E,h),S.cache={},S}};Me.module=tr,Me["node:module"]=tr;const an=new Map;let nr=null;function St(o){const c=["",".js",".ts",".mjs",".cjs",".json"];for(const h of c){const S=o+h;if(z.existsSync(S)&&z.statSync(S).isFile())return S}if(z.existsSync(o)&&z.statSync(o).isDirectory()){const h=J.join(o,"package.json");if(z.existsSync(h)&&z.statSync(h).isFile())try{const E=JSON.parse(z.readFileSync(h,"utf8"));let I=null;if(typeof E.exports=="string")I=E.exports;else if(E.exports&&typeof E.exports=="object"){const v=E.exports["."]||E.exports;typeof v=="string"?I=v:v&&typeof v=="object"&&(I=v.require||v.import||v.default||v.node)}if(I||(I=E.main||E.module||(typeof E.browser=="string"?E.browser:null)),I){const v=St(J.resolve(o,I));if(v)return v}}catch(E){j.debug("resolveFileOrDirCandidates package.json parse failed",E)}const S=["index.js","index.ts","index.mjs","index.cjs","index.json"];for(const E of S){const I=J.join(o,E);if(z.existsSync(I)&&z.statSync(I).isFile())return I}}return null}function lt(o,c="/workspace"){let h=o,S=c;if(typeof o=="string"&&typeof c=="string"&&o.startsWith("/workspace")&&!c.startsWith("/workspace")&&z.existsSync(o)&&z.statSync(o).isDirectory()&&(S=o,h=c),h.startsWith(".")||h.startsWith("/")){const I=h.startsWith("/")?J.normalize(h):J.resolve(S,h),v=St(I);if(v)return v}else{const I=h.split("/"),v=h.startsWith("@")?I.slice(0,2).join("/"):I[0],D=h.startsWith("@")?I.slice(2).join("/"):I.slice(1).join("/");let W=J.resolve("/workspace",S||"/workspace");const q=[];for(;;){q.push(J.join(W,"node_modules"));const H=J.dirname(W);if(H===W)break;W=H}q.includes("/workspace/node_modules")||q.push("/workspace/node_modules");for(const H of q){const ie=J.join(H,v);if(D){const me=J.join(ie,"package.json");if(z.existsSync(me)&&z.statSync(me).isFile())try{const oe=JSON.parse(z.readFileSync(me,"utf8")),G=`./${D}`;if(oe.exports&&oe.exports[G]){const ae=oe.exports[G],we=typeof ae=="string"?ae:ae.require||ae.import||ae.default;if(we){const Ue=St(J.resolve(ie,we));if(Ue)return Ue}}}catch(oe){j.debug("resolveModulePath subpath package.json parse failed",oe)}const ve=St(J.join(ie,D));if(ve)return ve}else{const me=St(ie);if(me)return me}}}const E=new Error(`Cannot find module '${h}' from '${S}'`);throw E.code="MODULE_NOT_FOUND",E}const rr=(o,c,h)=>_e(o,c,h),Vr=(o,c,h)=>nn(o,c,h),Hr=async(o,c={})=>{let h,S=c||{};typeof o=="string"?h=o:o&&o.url?(h=o.url,S=Object.assign({method:o.method,headers:o.headers,body:o.body},c)):h=String(o);let E=null;try{const I=new URL(h);(I.hostname==="localhost"||I.hostname==="127.0.0.1"||I.hostname==="0.0.0.0")&&(E=I)}catch(I){j.debug("virtualFetch local URL parse skipped",I)}if(E&&Pe){let I=S;if(!I._fromPort&&B&&B.pid&&typeof Pe.listServers=="function"){const v=Number(E.port||(E.protocol==="https:"?443:80)),D=Pe.listServers().find(W=>W&&W.pid===B.pid&&Number(W.port)!==v);D&&(I=Object.assign({},S,{_fromPort:D.port}))}return await Pe.dispatchRequest(h,I)}if(typeof globalThis.fetch=="function")return await globalThis.fetch(o,c);throw new Error(`fetch failed for ${h}`)},ut={Buffer:P,process:Ae,console:Ye,setTimeout:mt,clearTimeout:Gt,setInterval:Jt,clearInterval:Xt,setImmediate:$t,clearImmediate:Kt,queueMicrotask,TextEncoder:typeof TextEncoder<"u"?TextEncoder:void 0,TextDecoder:typeof TextDecoder<"u"?TextDecoder:void 0,performance:_t,PerformanceObserver:Kn,URL:At.URL,URLSearchParams:At.URLSearchParams,crypto:Fe,fetch:Hr,Request,Response,Headers,Bun:Ut};ut.global=ut,ut.globalThis=ut;function Ft(o,c=!1){if(an.has(o))return an.get(o).exports;const h={id:o,filename:o,loaded:!1,exports:{}};c&&(nr=h),an.set(o,h);const S=z.readFileSync(o,"utf8");if(o.endsWith(".json"))return h.exports=JSON.parse(S),h.loaded=!0,h.exports;const E=J.dirname(o),I=function(ie){if(Object.prototype.hasOwnProperty.call(Me,ie))return Me[ie];if(at.has(ie))return at.get(ie);const me=lt(ie,E);return Ft(me,!1)};I.main=nr,I.resolve=H=>lt(H,E),I.cache=Object.fromEntries(an.entries());let v=pt(S,o);(i==="test"||c||o.endsWith("test.js")||o.endsWith("test.ts"))&&(v=gr(v));const D=`{
105
- `+v+`
97
+ `}catch(H){I=H.message+`
98
+ `,P=1}}else if(o==="cat")for(const W of c){const q=J.resolve(_,W);try{M+=V.readFileSync(q,"utf8")}catch(H){I+=H.message+`
99
+ `,P=1}}else if(o==="node"||o==="/usr/local/bin/node"){let W=null,q=-1;for(let G=0;G<c.length;G++)if(c[G]==="-e"||c[G]==="--eval"){W=c[G+1]||"";break}else if(c[G]==="-p"||c[G]==="--print"){W=`console.log(${c[G+1]||""});`;break}else if(!c[G].startsWith("-")){q=G;break}let H=!1;const ie=G=>{if(H||T)return;const ae=String(G);if(M.length+ae.length>y||x+ae.length>y){const Se=Math.max(0,Math.min(y-M.length,y-x));if(Se>0){const Be=ae.slice(0,Se);M+=Be,x+=Be.length}M+=Z,H=!0,Q(b,l);return}M+=ae,x+=ae.length},ye=G=>{if(H||T)return;const ae=String(G);if(I.length+ae.length>y||x+ae.length>y){const Se=Math.max(0,Math.min(y-I.length,y-x));if(Se>0){const Be=ae.slice(0,Se);I+=Be,x+=Be.length}I+=Z,H=!0,Q(w,d);return}I+=ae,x+=ae.length},ve=Hn(ie,ye),oe=Object.assign(new fe,Ae,{env:E,argv:q>=0?["node",J.resolve(_,c[q]),...c.slice(q+1)]:["node"],cwd:()=>_,stdout:{write:G=>(ie(G),!0),isTTY:!1},stderr:{write:G=>(ye(G),!0),isTTY:!1},exit:(G=0)=>{throw P=Number(G)||0,new On(P)}});try{let G=W,ae=J.join(_,"__eval__.js");if(G===null&&q>=0){const Se=c[q];ae=St(J.resolve(_,Se))||lt(Se,_),G=V.readFileSync(ae,"utf8")}if(G!==null){const Se=J.dirname(ae),Be=pt(G,ae),ir={id:ae,filename:ae,loaded:!1,exports:{}},Xr=Bt=>{if(Object.prototype.hasOwnProperty.call(Ne,Bt))return Ne[Bt];if(at.has(Bt))return at.get(Bt);const Kr=lt(Bt,Se);return Ft(Kr,!1)};new Function("exports","require","module","__filename","__dirname","Buffer","process","console",Be)(ir.exports,Xr,ir,ae,Se,O,oe,ve)}}catch(G){G&&G._isProcessExit?P=G.exitCode:(P=1,I+=(G&&G.stack?G.stack:String(G))+`
100
+ `)}}else I=`${o}: command not found
101
+ `,P=127;return{status:P,stdout:M,stderr:I,pid:rn++}}function sn(o,c={}){const h=Rr(String(o).trim());return h.length===0?{status:0,stdout:"",stderr:"",pid:rn++}:vn(h[0],h.slice(1),c)}const ft={execSync(o,c={}){const h=sn(o,c),_=typeof c=="string"?c:c&&c.encoding,E=_&&_!=="buffer"?h.stdout:O.from(h.stdout),M=_&&_!=="buffer"?h.stderr:O.from(h.stderr);if(h.status!==0){const I=new Error(`Command failed: ${o}
102
+ ${h.stderr}`);throw I.status=h.status,I.stdout=E,I.stderr=M,I}return E},spawnSync(o,c=[],h={}){Array.isArray(c)||(h=c||{},c=[]);const _=h.shell?sn([o,...c].join(" "),h):vn(o,c,h),E=h&&h.encoding,M=E&&E!=="buffer"?_.stdout:O.from(_.stdout),I=E&&E!=="buffer"?_.stderr:O.from(_.stderr);return{pid:_.pid,output:[null,M,I],stdout:M,stderr:I,status:_.status,signal:null,error:null}},exec(o,c,h){const _=typeof c=="function"?c:h,E=typeof c=="object"&&c!==null?c:{},M=Object.assign(new fe,{pid:rn++,stdout:new He,stderr:new He,stdin:new He,killed:!1,kill(){return this.killed=!0,!0}});return queueMicrotask(()=>{const I=sn(o,E);if(I.stdout&&M.stdout.write(I.stdout),M.stdout.end(),I.stderr&&M.stderr.write(I.stderr),M.stderr.end(),M.emit("exit",I.status,null),M.emit("close",I.status,null),typeof _=="function")if(I.status!==0){const P=new Error(`Command failed: ${o}
103
+ ${I.stderr}`);P.code=I.status,_(P,I.stdout,I.stderr)}else _(null,I.stdout,I.stderr)}),M},execFile(o,c,h,_){let E=[],M={},I=_;return Array.isArray(c)?(E=c,typeof h=="function"?I=h:h&&(M=h)):typeof c=="function"?I=c:c&&(M=c,typeof h=="function"&&(I=h)),ft.exec([o,...E].join(" "),M,I)},spawn(o,c=[],h={}){Array.isArray(c)||(h=c||{},c=[]);const _=Object.assign(new fe,{pid:rn++,stdout:new He,stderr:new He,stdin:new He,killed:!1,kill(){return this.killed=!0,!0}});return queueMicrotask(()=>{const E=h.shell?sn([o,...c].join(" "),h):vn(o,c,h);E.stdout&&_.stdout.write(O.from(E.stdout)),_.stdout.end(),E.stderr&&_.stderr.write(O.from(E.stderr)),_.stderr.end(),_.emit("exit",E.status,null),_.emit("close",E.status,null)}),_}};ft.exec[vt.custom]=(o,c={})=>new Promise((h,_)=>{ft.exec(o,c,(E,M,I)=>{E?(E.stdout=M,E.stderr=I,_(E)):h({stdout:M,stderr:I})})}),ft.execFile[vt.custom]=(o,c=[],h={})=>new Promise((_,E)=>{ft.execFile(o,c,h,(M,I,P)=>{M?(M.stdout=I,M.stderr=P,E(M)):_({stdout:I,stderr:P})})});const vr=zn(V,()=>Ae.cwd());function on(o){return Ee.crc32(typeof o=="string"||o instanceof Uint8Array?o:String(o))}const In=function(c){return on(c)};In.crc32=o=>on(o),In.cityHash64=o=>{const c=on(o),h=on(String(o)+":seed64");return BigInt(c)<<32n|BigInt(h)};function kn(o,c){return Ge(o,c,!0)}const et=new Set,Ut={version:"1.1.0",serve(o={}){const c=Number(o.port||3e3),h=o.hostname||"127.0.0.1",_={port:c,hostname:h,development:!1,stop(){et.delete(_),Ce.unregisterServer(c)}};return Ce.registerServer(c,{server:_,name:o.name||"bun-server",port:c,pid:C.pid||1,fetch:o.fetch?o.fetch.bind(_):void 0,stop:()=>_.stop()}),et.add(_),_},file(o){const c=J.resolve(Ae.cwd(),String(o));return{name:J.basename(c),get size(){try{return V.statSync(c).size}catch{return 0}},async exists(){return V.existsSync(c)},async text(){return V.readFileSync(c,"utf8")},async json(){return JSON.parse(V.readFileSync(c,"utf8"))},async arrayBuffer(){const h=V.readFileSync(c);return h.buffer.slice(h.byteOffset,h.byteOffset+h.byteLength)}}},async write(o,c){const h=J.resolve(Ae.cwd(),String(o)),_=J.dirname(h);V.existsSync(_)||V.mkdirSync(_,{recursive:!0});let E;if(typeof c=="string")E=O.from(c,"utf8");else if(c&&c.arrayBuffer&&typeof c.arrayBuffer=="function"){const M=await c.arrayBuffer();E=O.from(M)}else c instanceof Uint8Array||O.isBuffer(c)?E=O.from(c):E=O.from(String(c),"utf8");return V.writeFileSync(h,E),E.length},sleep(o){return new Promise(c=>mt(c,Number(o)||0))},hash:In,deepEquals:kn,inspect(o){return It.inspect(o)},nanoseconds(){return Math.round(performance.now()*1e6)}},Ir=(()=>{function o(h,_=!1){const E=(I,P)=>{if(!(_?!I:I))throw new Error(P||`expect assertion failed: actual=${h}`)},M={toBe(I){E(Object.is(h,I),`Expected ${h} to be ${I}`)},toEqual(I){E(kn(h,I),`Expected ${JSON.stringify(h)} to equal ${JSON.stringify(I)}`)},toContain(I){let P=!1;h&&typeof h.includes=="function"?P=h.includes(I):h&&typeof h.has=="function"&&(P=h.has(I)),E(P,`Expected collection to contain ${I}`)},toThrow(I){let P=!1,W=null;try{typeof h=="function"&&h()}catch(q){P=!0,W=q}if(!P){E(!1,"Expected function to throw");return}if(I){const q=W&&W.message?W.message:String(W);typeof I=="string"?E(q.includes(I),`Expected error message "${q}" to contain "${I}"`):I instanceof RegExp&&E(I.test(q),`Expected error message "${q}" to match ${I}`)}else E(!0)},toBeTruthy(){E(!!h,`Expected ${h} to be truthy`)},toBeFalsy(){E(!h,`Expected ${h} to be falsy`)},toBeGreaterThan(I){E(h>I,`Expected ${h} to be greater than ${I}`)},toBeLessThan(I){E(h<I,`Expected ${h} to be less than ${I}`)},toHaveBeenCalled(){const I=h&&h.mock&&h.mock.calls||[];E(I.length>0,"Expected mock function to have been called")},toHaveBeenCalledTimes(I){const P=h&&h.mock&&h.mock.calls||[];E(P.length===I,`Expected mock function to have been called ${I} times, was called ${P.length}`)},toHaveBeenCalledWith(...I){const W=(h&&h.mock&&h.mock.calls||[]).some(q=>{const H=Array.isArray(q)?q:q&&Array.isArray(q.arguments)?q.arguments:[];return kn(H,I)});E(W,`Expected mock to have been called with ${JSON.stringify(I)}`)}};return _||(M.not=o(h,!0)),M}function c(h){const _=[],E=[],M=function(...I){_.push(I);let P;try{return typeof h=="function"&&(P=h.apply(this,I)),E.push({type:"return",value:P}),P}catch(W){throw E.push({type:"throw",value:W}),W}};return M.mock={calls:_,results:E},M}return{describe:(h,_)=>nn(h,_),test:(h,_)=>we(h,_),it:(h,_)=>we(h,_),expect:h=>o(h),mock:h=>c(h),beforeAll:h=>we.before(h),afterAll:h=>we.after(h),beforeEach:h=>we.beforeEach(h),afterEach:h=>we.afterEach(h)}})(),kr={isatty(){return!1},ReadStream:class extends fe{},WriteStream:class extends fe{constructor(c){super(),this.fd=c,this.columns=80,this.rows=24,this.isTTY=!1}getColorDepth(){return 1}hasColors(){return!1}cursorTo(){return!0}clearLine(){return!0}moveCursor(){return!0}}};function Mn(o){if(o&&Y(String(o)),Qe.length>0)return Promise.resolve(Qe.shift());if(t&&typeof t.onRequestStdin=="function"&&!j){const c={};return C.inFlightHttp.add(c),Promise.resolve(t.onRequestStdin("")).then(h=>{if(C.inFlightHttp.delete(c),h==null)return null;const _=String(h);return Lt.write(_+`
104
+ `),_}).catch(()=>(C.inFlightHttp.delete(c),null))}return Promise.resolve(null)}function Qn(o){const c=new fe;let h=!1,_=o&&typeof o.prompt=="string"?o.prompt:"> ";return c.terminal=!1,c.line="",c.cursor=0,c.question=(E,M,I)=>{const P=typeof M=="function"?M:I;Mn(E).then(W=>{const q=W===null?"":W;c.line=q,typeof P=="function"&&!h&&!j&&P(q)})},c.prompt=()=>{Y(_)},c.setPrompt=E=>{_=String(E??"")},c.getPrompt=()=>_,c.write=E=>{E!=null&&Y(String(E))},c.pause=()=>c,c.resume=()=>(queueMicrotask(async()=>{for(;!h&&!j&&Qe.length>0;){const E=Qe.shift();c.line=E,c.emit("line",E)}}),c),c.close=()=>(h||(h=!0,queueMicrotask(()=>c.emit("close"))),c),c[Symbol.asyncIterator]=async function*(){for(;!h&&!j;){const E=await Mn("");if(E===null)break;c.line=E,yield E}},queueMicrotask(()=>{if(c.listenerCount("line")>0&&Qe.length>0){for(;!h&&!j&&Qe.length>0;){const E=Qe.shift();c.line=E,c.emit("line",E)}(!t||typeof t.onRequestStdin!="function")&&c.close()}}),c}const Mr={createInterface:Qn,Interface:class extends fe{},clearLine:()=>!0,clearScreenDown:()=>!0,cursorTo:()=>!0,moveCursor:()=>!0,emitKeypressEvents:()=>{}},Nr={createInterface:o=>{const c=Qn(o);return c.question=h=>Mn(h).then(_=>_===null?"":_),c},Interface:class extends fe{}},$r={AsyncLocalStorage:class{constructor(){this._store=void 0}getStore(){return this._store}run(c,h,..._){const E=this._store;this._store=c;try{return h(..._)}finally{this._store=E}}exit(c,...h){const _=this._store;this._store=void 0;try{return c(...h)}finally{this._store=_}}enterWith(c){this._store=c}disable(){this._store=void 0}},AsyncResource:class{constructor(c){this.type=c||"AsyncResource"}runInAsyncScope(c,h,..._){return c.apply(h,_)}emitDestroy(){return this}asyncId(){return 0}triggerAsyncId(){return 0}static bind(c){return c}},createHook(){return{enable(){},disable(){}}},executionAsyncId(){return 0},triggerAsyncId(){return 0},executionAsyncResource(){return null}},Lr={isMainThread:!0,threadId:0,parentPort:null,workerData:null,resourceLimits:{},SHARE_ENV:Symbol("nodejs.worker_threads.SHARE_ENV"),receiveMessageOnPort(){},Worker:class extends fe{constructor(c){super(),this.threadId=-1,this.filename=c,queueMicrotask(()=>this.emit("error",new Error("worker_threads.Worker is not supported in the virtual runtime.")))}postMessage(){}terminate(){return Promise.resolve(0)}ref(){return this}unref(){return this}},MessageChannel:class{},MessagePort:class extends fe{}},Cr={serialize(o){return O.from(JSON.stringify(o===void 0?null:o),"utf8")},deserialize(o){try{return JSON.parse(String(o))}catch{return}},getHeapStatistics(){return{total_heap_size:0,total_heap_size_executable:0,total_physical_size:0,total_available_size:0,used_heap_size:0,heap_size_limit:0,malloced_memory:0,peak_malloced_memory:0,does_zap_garbage:0,number_of_native_contexts:1,number_of_detached_contexts:0}},getHeapSpaceStatistics(){return[]},setFlagsFromString(){},cachedDataVersionTag(){return 0},Serializer:class{constructor(){this._value=void 0}writeHeader(){}writeValue(c){this._value=c}releaseBuffer(){return O.from(JSON.stringify(this._value===void 0?null:this._value),"utf8")}},Deserializer:class{constructor(c){this._buffer=c}readHeader(){return!0}readValue(){try{return JSON.parse(String(this._buffer))}catch{return}}}},Ur={createContext(o){return o&&typeof o=="object"?o:{}},isContext(){return!1},createScript(){throw new Error("vm code compilation is not supported in the virtual runtime.")},runInContext(){throw new Error("vm.runInContext is not supported in the virtual runtime.")},runInNewContext(){throw new Error("vm.runInNewContext is not supported in the virtual runtime.")},runInThisContext(){throw new Error("vm.runInThisContext is not supported in the virtual runtime.")},compileFunction(){throw new Error("vm.compileFunction is not supported in the virtual runtime.")},Script:class{runInThisContext(){throw new Error("vm.Script is not supported in the virtual runtime.")}runInContext(){throw new Error("vm.Script is not supported in the virtual runtime.")}runInNewContext(){throw new Error("vm.Script is not supported in the virtual runtime.")}}},er={create(){const o=new fe;return o.members=[],o.add=()=>o,o.remove=()=>o,o.bind=c=>c,o.intercept=c=>c,o.run=(c,...h)=>c(...h),o.dispose=()=>o,o},createDomain(){return er.create()}},wt={_channels:new Map,channel(o){const c=String(o);if(!wt._channels.has(c)){const h=new fe;h.name=c,h.hasSubscribers=!1,h.subscribe=()=>{h.hasSubscribers=!0},h.unsubscribe=()=>{h.hasSubscribers=!1},wt._channels.set(c,h)}return wt._channels.get(c)},subscribe(o,c){const h=wt.channel(o);h.subscribe(),typeof c=="function"&&h.on("message",c)},unsubscribe(o){wt.channel(o).unsubscribe()},Channel:class extends fe{}},qe=o=>()=>{throw new Error(o+" is not supported in the virtual runtime.")},Fr={DEFAULT_MIN_VERSION:"TLSv1.2",DEFAULT_MAX_VERSION:"TLSv1.3",rootCertificates:[],createSecureContext(){return{context:{}}},SecureContext:class{},TLSSocket:class extends fe{},Server:class extends fe{},checkServerIdentity(){},connect:qe("tls.connect"),createServer:qe("tls.createServer")},Br={createSocket(o){const c=new fe;return c.type=o||"udp4",c.bind=(...h)=>{const _=h[h.length-1];return typeof _=="function"&&queueMicrotask(_),c},c.close=h=>(queueMicrotask(()=>{c.emit("close"),typeof h=="function"&&h()}),c),c.send=qe("dgram.send"),c.address=()=>({address:"0.0.0.0",family:"IPv4",port:0}),c.setBroadcast=()=>c,c.setTTL=()=>c,c.addMembership=()=>{},c.dropMembership=()=>{},c},Socket:class extends fe{}},jr={constants:{NGHTTP2_REFUSED_STREAM:7,NGHTTP2_CANCEL:8},connect:qe("http2.connect"),createServer:qe("http2.createServer"),createSecureServer:qe("http2.createSecureServer")},Dr={isPrimary:!0,isMaster:!0,isWorker:!1,workers:{},fork:qe("cluster.fork"),setupPrimary:qe("cluster.setupPrimary"),setupMaster:qe("cluster.setupMaster"),disconnect:()=>{}},Pr={start:qe("repl.start")},Or={open:()=>null,close:()=>{},url:()=>"",Session:class{connect(){}disconnect(){}post(){}}},Wr={createTracing:()=>({enable(){},disable(){}}),getEnabledCategories:()=>""},zr=wn({vfs:V,onStdout:Y,onStderr:ee}),qr={ReadableStream:typeof ReadableStream<"u"?ReadableStream:void 0,WritableStream:typeof WritableStream<"u"?WritableStream:void 0,TransformStream:typeof TransformStream<"u"?TransformStream:void 0};async function cn(o,c){const h=[];if(c&&typeof c[Symbol.asyncIterator]=="function")for await(const M of c)h.push(M);else c&&typeof c.on=="function"&&await new Promise((M,I)=>{c.on("data",P=>h.push(P)),c.on("end",M),c.on("error",I)});const _=h.map(M=>O.from(M)),E=O.concat(_);return o==="buffer"?E:o==="arrayBuffer"?E.buffer?E.buffer.slice(E.byteOffset,E.byteOffset+E.byteLength):new ArrayBuffer(0):o==="text"?E.toString("utf8"):o==="json"?JSON.parse(E.toString("utf8")):E}const Zr={text:o=>cn("text",o),json:o=>cn("json",o),buffer:o=>cn("buffer",o),arrayBuffer:o=>cn("arrayBuffer",o)},Ne={fs:V,"node:fs":V,"fs/promises":V.promises,"node:fs/promises":V.promises,path:J,"node:path":J,os:ln,"node:os":ln,crypto:je,"node:crypto":je,zlib:Ee,"node:zlib":Ee,http:Ze,"node:http":Ze,https:Ze,"node:https":Ze,net:Nt,"node:net":Nt,dns:kt,"node:dns":kt,"dns/promises":kt.promises,"node:dns/promises":kt.promises,string_decoder:pn,"node:string_decoder":pn,child_process:ft,"node:child_process":ft,process:Ae,"node:process":Ae,console:Ye,"node:console":Ye,assert:me,"node:assert":me,"assert/strict":me.strict,"node:assert/strict":me.strict,events:fe,"node:events":fe,util:It,"node:util":It,url:At,"node:url":At,querystring:Le,"node:querystring":Le,stream:hn,"node:stream":hn,"stream/promises":Ot,"node:stream/promises":Ot,test:we,"node:test":we,perf_hooks:Yn,"node:perf_hooks":Yn,timers:En,"node:timers":En,"timers/promises":An,"node:timers/promises":An,buffer:{Buffer:O},"node:buffer":{Buffer:O},bun:Ut,"node:bun":Ut,"bun:test":Ir,"bun:sqlite":{Database:vr},tty:kr,tls:Fr,dgram:Br,readline:Mr,"readline/promises":Nr,async_hooks:$r,worker_threads:Lr,v8:Cr,vm:Ur,domain:er,diagnostics_channel:wt,http2:jr,cluster:Dr,repl:Pr,inspector:Or,trace_events:Wr,wasi:zr,constants:V.constants,"util/types":It.types,"stream/web":qr,"stream/consumers":Zr};for(const o of Object.keys(Ne))!o.startsWith("node:")&&!o.startsWith("bun:")&&(Ne["node:"+o]=Ne[o]);const tr={builtinModules:Object.keys(Ne),Module:class{},isBuiltin(o){return Object.prototype.hasOwnProperty.call(Ne,String(o))},createRequire(o){const c=typeof o=="string"?o:"/workspace",h=/\.(?:js|mjs|cjs|ts|json)$/.test(c)?J.dirname(c):c,_=E=>Object.prototype.hasOwnProperty.call(Ne,E)?Ne[E]:Ft(lt(E,h),!1);return _.resolve=E=>lt(E,h),_.cache={},_}};Ne.module=tr,Ne["node:module"]=tr;const an=new Map;let nr=null;function St(o){const c=["",".js",".ts",".mjs",".cjs",".json"];for(const h of c){const _=o+h;if(V.existsSync(_)&&V.statSync(_).isFile())return _}if(V.existsSync(o)&&V.statSync(o).isDirectory()){const h=J.join(o,"package.json");if(V.existsSync(h)&&V.statSync(h).isFile())try{const E=JSON.parse(V.readFileSync(h,"utf8"));let M=null;if(typeof E.exports=="string")M=E.exports;else if(E.exports&&typeof E.exports=="object"){const I=E.exports["."]||E.exports;typeof I=="string"?M=I:I&&typeof I=="object"&&(M=I.require||I.import||I.default||I.node)}if(M||(M=E.main||E.module||(typeof E.browser=="string"?E.browser:null)),M){const I=St(J.resolve(o,M));if(I)return I}}catch(E){D.debug("resolveFileOrDirCandidates package.json parse failed",E)}const _=["index.js","index.ts","index.mjs","index.cjs","index.json"];for(const E of _){const M=J.join(o,E);if(V.existsSync(M)&&V.statSync(M).isFile())return M}}return null}function lt(o,c="/workspace"){let h=o,_=c;if(typeof o=="string"&&typeof c=="string"&&o.startsWith("/workspace")&&!c.startsWith("/workspace")&&V.existsSync(o)&&V.statSync(o).isDirectory()&&(_=o,h=c),h.startsWith(".")||h.startsWith("/")){const M=h.startsWith("/")?J.normalize(h):J.resolve(_,h),I=St(M);if(I)return I}else{const M=h.split("/"),I=h.startsWith("@")?M.slice(0,2).join("/"):M[0],P=h.startsWith("@")?M.slice(2).join("/"):M.slice(1).join("/");let W=J.resolve("/workspace",_||"/workspace");const q=[];for(;;){q.push(J.join(W,"node_modules"));const H=J.dirname(W);if(H===W)break;W=H}q.includes("/workspace/node_modules")||q.push("/workspace/node_modules");for(const H of q){const ie=J.join(H,I);if(P){const ye=J.join(ie,"package.json");if(V.existsSync(ye)&&V.statSync(ye).isFile())try{const oe=JSON.parse(V.readFileSync(ye,"utf8")),G=`./${P}`;if(oe.exports&&oe.exports[G]){const ae=oe.exports[G],Se=typeof ae=="string"?ae:ae.require||ae.import||ae.default;if(Se){const Be=St(J.resolve(ie,Se));if(Be)return Be}}}catch(oe){D.debug("resolveModulePath subpath package.json parse failed",oe)}const ve=St(J.join(ie,P));if(ve)return ve}else{const ye=St(ie);if(ye)return ye}}}const E=new Error(`Cannot find module '${h}' from '${_}'`);throw E.code="MODULE_NOT_FOUND",E}const rr=(o,c,h)=>we(o,c,h),Vr=(o,c,h)=>nn(o,c,h),Hr=async(o,c={})=>{let h,_=c||{};typeof o=="string"?h=o:o&&o.url?(h=o.url,_=Object.assign({method:o.method,headers:o.headers,body:o.body},c)):h=String(o);let E=null;try{const M=new URL(h);(M.hostname==="localhost"||M.hostname==="127.0.0.1"||M.hostname==="0.0.0.0")&&(E=M)}catch(M){D.debug("virtualFetch local URL parse skipped",M)}if(E&&Ce){let M=_;if(!M._fromPort&&C&&C.pid&&typeof Ce.listServers=="function"){const I=Number(E.port||(E.protocol==="https:"?443:80)),P=Ce.listServers().find(W=>W&&W.pid===C.pid&&Number(W.port)!==I);P&&(M=Object.assign({},_,{_fromPort:P.port}))}return await Ce.dispatchRequest(h,M)}if(typeof globalThis.fetch=="function")return await globalThis.fetch(o,c);throw new Error(`fetch failed for ${h}`)},ut={Buffer:O,process:Ae,console:Ye,setTimeout:mt,clearTimeout:Gt,setInterval:Jt,clearInterval:Xt,setImmediate:$t,clearImmediate:Kt,queueMicrotask,TextEncoder:typeof TextEncoder<"u"?TextEncoder:void 0,TextDecoder:typeof TextDecoder<"u"?TextDecoder:void 0,performance:_t,PerformanceObserver:Kn,URL:At.URL,URLSearchParams:At.URLSearchParams,crypto:je,fetch:Hr,Request,Response,Headers,Bun:Ut};ut.global=ut,ut.globalThis=ut;function Ft(o,c=!1){if(an.has(o))return an.get(o).exports;const h={id:o,filename:o,loaded:!1,exports:{}};c&&(nr=h),an.set(o,h);const _=V.readFileSync(o,"utf8");if(o.endsWith(".json"))return h.exports=JSON.parse(_),h.loaded=!0,h.exports;const E=J.dirname(o),M=function(ie){if(Object.prototype.hasOwnProperty.call(Ne,ie))return Ne[ie];if(at.has(ie))return at.get(ie);const ye=lt(ie,E);return Ft(ye,!1)};M.main=nr,M.resolve=H=>lt(H,E),M.cache=Object.fromEntries(an.entries());let I=pt(_,o);(i==="test"||c||o.endsWith("test.js")||o.endsWith("test.ts"))&&(I=gr(I));const P=`{
105
+ `+I+`
106
106
  }
107
107
  //# sourceURL=`+o+`
108
- `,W=Nn(["exports","require","module","__filename","__dirname","Buffer","process","console","setTimeout","clearTimeout","setInterval","clearInterval","setImmediate","clearImmediate","global","__shouldSkipTest","__wrapTestFn","test","describe","it","Bun","fetch","Request","Response","Headers"],D);xn++;let q;try{q=W(h.exports,I,h,o,E,P,Ae,Ye,mt,Gt,Jt,Xt,$t,Kt,ut,Ee,De,rr,Vr,rr,Ut,ut.fetch,Request,Response,Headers)}finally{xn--}return q&&typeof q.then=="function"?(B.pendingTests.add(q),q.then(()=>(B.pendingTests.delete(q),h.loaded=!0,h.exports)).catch(H=>{throw B.pendingTests.delete(q),H})):(h.loaded=!0,h.exports)}const Gr=Object.getPrototypeOf(async function(){}).constructor;let Jr=0;function Nn(o,c){try{return new Function(...o,c)}catch(h){if(h instanceof SyntaxError&&(/\bawait\b/.test(c)||/await/i.test(h.message)))try{return new Gr(...o,c)}catch(S){j.debug("AsyncFunction compilation fallback failed",S)}if(h&&h.name==="EvalError"&&typeof importScripts=="function"&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function"){const S=typeof self<"u"?self:globalThis,E="__cl_fn_"+ ++Jr+"_"+Math.random().toString(36).slice(2),I=`self[${JSON.stringify(E)}] = function(${o.join(", ")}) {
108
+ `,W=Nn(["exports","require","module","__filename","__dirname","Buffer","process","console","setTimeout","clearTimeout","setInterval","clearInterval","setImmediate","clearImmediate","global","__shouldSkipTest","__wrapTestFn","test","describe","it","Bun","fetch","Request","Response","Headers"],P);xn++;let q;try{q=W(h.exports,M,h,o,E,O,Ae,Ye,mt,Gt,Jt,Xt,$t,Kt,ut,be,Me,rr,Vr,rr,Ut,ut.fetch,Request,Response,Headers)}finally{xn--}return q&&typeof q.then=="function"?(C.pendingTests.add(q),q.then(()=>(C.pendingTests.delete(q),h.loaded=!0,h.exports)).catch(H=>{throw C.pendingTests.delete(q),H})):(h.loaded=!0,h.exports)}const Gr=Object.getPrototypeOf(async function(){}).constructor;let Jr=0;function Nn(o,c){try{return new Function(...o,c)}catch(h){if(h instanceof SyntaxError&&(/\bawait\b/.test(c)||/await/i.test(h.message)))try{return new Gr(...o,c)}catch(_){D.debug("AsyncFunction compilation fallback failed",_)}if(h&&h.name==="EvalError"&&typeof importScripts=="function"&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function"){const _=typeof self<"u"?self:globalThis,E="__cl_fn_"+ ++Jr+"_"+Math.random().toString(36).slice(2),M=`self[${JSON.stringify(E)}] = function(${o.join(", ")}) {
109
109
  ${c}
110
- };`,v=new Blob([I],{type:"application/javascript"}),D=URL.createObjectURL(v);try{importScripts(D);const W=S[E];if(delete S[E],typeof W=="function")return W}finally{URL.revokeObjectURL(D)}}throw h}}function sr(o){return!o||typeof o.then!="function"?Promise.resolve(o):O||Yt||U&&U.aborted?(O||gt(),Promise.resolve()):(o.catch(()=>{}),new Promise((c,h)=>{let S=null,E=!1;const I=()=>{if(!E&&(E=!0,S&&(clearTimeout(S),S=null),U&&v))try{U.removeEventListener("abort",v)}catch(W){j.debug("raceWithAbort removeEventListener failed",W)}},v=()=>{I(),gt(),c()};if(U){if(U.aborted){v();return}U.addEventListener("abort",v,{once:!0})}const D=m-(performance.now()-C);D>0&&Number.isFinite(D)&&(S=setTimeout(()=>{I(),c()},D),S&&typeof S.unref=="function"&&S.unref()),o.then(W=>{I(),c(W)},W=>{I(),h(W)})}))}let dt;try{if(O||Yt||U&&U.aborted)O||gt();else if(i==="repl"){const S="/workspace/__repl__.ts";z.writeFileSync(S,a||"");const E="/workspace",I=function(oe){if(Object.prototype.hasOwnProperty.call(Me,oe))return Me[oe];if(at.has(oe))return at.get(oe);const G=lt(oe,E);return Ft(G,!1)},v=pt(a||"",S);let D=v.trim();const W=D.lastIndexOf(";");let q="",H=D;if(W!==-1&&W<D.length-1)q=D.slice(0,W+1)+`
111
- `,H=D.slice(W+1).trim();else{const ve=D.split(`
110
+ };`,I=new Blob([M],{type:"application/javascript"}),P=URL.createObjectURL(I);try{importScripts(P);const W=_[E];if(delete _[E],typeof W=="function")return W}finally{URL.revokeObjectURL(P)}}throw h}}function sr(o){return!o||typeof o.then!="function"?Promise.resolve(o):j||Yt||F&&F.aborted?(j||gt(),Promise.resolve()):(o.catch(()=>{}),new Promise((c,h)=>{let _=null,E=!1;const M=()=>{if(!E&&(E=!0,_&&(clearTimeout(_),_=null),F&&I))try{F.removeEventListener("abort",I)}catch(W){D.debug("raceWithAbort removeEventListener failed",W)}},I=()=>{M(),gt(),c()};if(F){if(F.aborted){I();return}F.addEventListener("abort",I,{once:!0})}const P=p-(performance.now()-U);P>0&&Number.isFinite(P)&&(_=setTimeout(()=>{M(),c()},P),_&&typeof _.unref=="function"&&_.unref()),o.then(W=>{M(),c(W)},W=>{M(),h(W)})}))}let dt;try{if(j||Yt||F&&F.aborted)j||gt();else if(i==="repl"){const _="/workspace/__repl__.ts";V.writeFileSync(_,a||"");const E="/workspace",M=function(oe){if(Object.prototype.hasOwnProperty.call(Ne,oe))return Ne[oe];if(at.has(oe))return at.get(oe);const G=lt(oe,E);return Ft(G,!1)},I=pt(a||"",_);let P=I.trim();const W=P.lastIndexOf(";");let q="",H=P;if(W!==-1&&W<P.length-1)q=P.slice(0,W+1)+`
111
+ `,H=P.slice(W+1).trim();else{const ve=P.split(`
112
112
  `);q=ve.slice(0,-1).join(`
113
113
  `)+`
114
- `,H=(ve[ve.length-1]||"").trim()}if(H&&!/^\s*(const|let|var|function|class|if|for|while|switch|try|return|throw)\b/.test(H)){const ve=q+`return (${H.replace(/;+\s*$/,"")});`;try{Nn([],ve),D=ve}catch{D=v}}let ie=null;t&&typeof t.replSessionId=="string"&&t.replSessionId&&(ie=jt.get(t.replSessionId),ie||(ie=Object.create(null),jt.set(t.replSessionId,ie)),D=or(D,ie));const me=Nn(["require","Buffer","process","console","setTimeout","clearTimeout","setInterval","clearInterval","setImmediate","clearImmediate","Bun","fetch","__replCtx"],`return (async () => {
115
- ${D}
116
- })();`);dt=await sr(me(I,P,Ae,Ye,mt,Gt,Jt,Xt,$t,Kt,Ut,ut.fetch,ie||Object.create(null))),ie&&dt!==void 0&&(ie._=dt),!O&&dt!==void 0&&t.printReplResult!==!1&&Y(Z(dt)+`
117
- `)}else{const S=n.startsWith("/")?n:J.resolve(be,n);let E=z.existsSync(S)?S:z.existsSync(n)?n:`/workspace/${n.replace(/^\/+/,"")}`;if(!z.existsSync(E)){const W=`/workspace/src/${n.replace(/^\/+/,"")}`;z.existsSync(W)&&(E=W)}const I=/\.(cpp|cc|cxx)$/i.test(E),v=/\.py$/i.test(E);if(/\.wasm$/i.test(E)||!!t.wasmBinary){const W=t.wasmBinary||z.readFileSync(E);L=(await Vt(W,{vfs:z,args:l||[E],env:Object.assign({},Ae.env,t.env||{}),stdin:t.stdin||"",onStdout:Y,onStderr:se})).exitCode,O=!0}else if(I){const W=t.cppCompiler||typeof globalThis<"u"&&globalThis.__codelabCppCompiler||X&&X.__codelabCppCompiler;if(typeof W!="function")throw new Error('C++ toolchain is not registered. Enable cppExtension from "@innovatorved/code-lab/extensions/cpp" to compile and run C++ files.');const q=await W({entry:E,vfs:z,files:typeof z.toSnapshot=="function"?z.toSnapshot("/workspace"):e||{},args:l||[E],env:Object.assign({},Ae.env,t.env||{}),stdin:t.stdin||"",testFilter:f,onStdout:Y,onStderr:se});q&&q.wasmBinary?(L=(await Vt(q.wasmBinary,{vfs:z,args:q.args||l||[E],env:Object.assign({},Ae.env,t.env||{}),stdin:t.stdin||"",onStdout:Y,onStderr:se})).exitCode,O=!0):q&&typeof q.exitCode=="number"&&(L=q.exitCode,O=!0)}else if(v){const W=t.pythonCompiler||typeof globalThis<"u"&&globalThis.__codelabPythonCompiler||X&&X.__codelabPythonCompiler;if(typeof W!="function")throw new Error('Python WebAssembly toolchain is not registered. Enable pythonExtension from "@innovatorved/code-lab/extensions/python" to run Python files.');const q=await W({entry:E,vfs:z,files:typeof z.toSnapshot=="function"?z.toSnapshot("/workspace"):e||{},args:l||[E],env:Object.assign({},Ae.env,t.env||{}),stdin:t.stdin||"",testFilter:f,onStdout:Y,onStderr:se});if(q&&(L=typeof q.exitCode=="number"?q.exitCode:q.ok?0:1,q.testResults&&Array.isArray(q.testResults)))for(const H of q.testResults)p.push(H);O=!0}else{let W=null;if(z.existsSync(E))try{W=z.readFileSync(E)}catch(q){j.debug("Failed to probe binary header",q)}if(W&&W.length>=4&&W[0]===0&&W[1]===97&&W[2]===115&&W[3]===109)L=(await Vt(W,{vfs:z,args:l||[E],env:Object.assign({},Ae.env,t.env||{}),stdin:t.stdin||"",onStdout:Y,onStderr:se})).exitCode,O=!0;else{const q=Ft(E,!0);q&&typeof q.then=="function"&&await sr(q)}}}const o=()=>{if(Ze.hasActiveServers())return!0;if(et.size>0){for(const S of Array.from(et))Pe.getServer(S.port)||et.delete(S);return et.size>0}return!1},c=performance.now()+m;let h=0;for(;!O;){if(U&&U.aborted){gt();break}const S=o(),E=!!(!F&&U&&S);if(!E&&performance.now()>=c)break;if(await Promise.resolve(),await Promise.resolve(),B.activeTimers.size>0||B.activeImmediates.size>0||B.inFlightHttp.size>0||B.pendingTests.size>0||(F||!!U)&&S)h=0;else if(h++,h>=2)break;await new Promise(v=>setTimeout(v,E?25:2))}}catch(o){o&&o._isProcessExit?L=o.exitCode:(L=1,se((o&&o.stack?o.stack:String(o))+`
118
- `))}finally{if(U&&Qt)try{U.removeEventListener("abort",Qt)}catch(o){j.debug("executeInVirtualRuntime removeEventListener failed",o)}if(!O){O=!0;try{Ae.emit("exit",L)}catch(o){j.debug("executeInVirtualRuntime exit listener failed",o)}}typeof z._setActiveStdin=="function"&&z._setActiveStdin("");for(const o of B.allTimers)clearTimeout(o),clearInterval(o);if(B.activeTimers.clear(),B.allTimers.clear(),B.activeImmediates.clear(),B.inFlightHttp.clear(),ue.length>0){const o=ue;ue="",Y(o+`
119
- `)}if(!F){Ze.closeAllServers(),Nt.closeAllServers();for(const o of Array.from(et))try{o.stop()}catch(c){j.debug("executeInVirtualRuntime bun server stop failed",c)}if(et.clear(),zn&&typeof z._listOpenFds=="function"&&typeof z.closeSync=="function"){for(const o of z._listOpenFds())if(!zn.has(o))try{z.closeSync(o)}catch(c){j.debug("executeInVirtualRuntime closeSync leak cleanup failed",{fd:o,err:c})}}}it=ct,xt=We}const $n=p.filter(o=>!o.passed).length;$n>0&&L===0&&(L=1);let Ln;if(Ht&&typeof z._exportRawState=="function"){const o=z._exportRawState(),c={},h=[],S=[],E=v=>v==="/workspace/node_modules"||v.startsWith("/workspace/node_modules/"),I=(v,D)=>{if(!v||!D||v.byteLength!==D.byteLength)return!1;for(let W=0;W<v.byteLength;W++)if(v[W]!==D[W])return!1;return!0};for(const v of o.dirs)!Ht.dirs.has(v)&&!E(v)&&S.push(v);for(const[v,D]of o.files.entries()){if(E(v))continue;const W=Ht.files.get(v);(!W||!I(W,D))&&(c[v]=D)}for(const v of Ht.files.keys())E(v)||o.files.has(v)||h.push(v);Ln={modifiedFiles:c,deletedFiles:h,createdDirs:S}}return{ok:L===0,exitCode:L,durationMs:Math.max(0,performance.now()-C),stdout:w.join(""),stderr:g.join(""),cancelled:L===130||Yt||!!(U&&U.aborted),outputTruncated:R,testResults:p,testSummary:{total:p.length,passed:p.length-$n,failed:$n},fsSnapshot:typeof z.getSnapshot=="function"?z.getSnapshot():[],...Ln?{vfsChanges:Ln}:{},httpTrace:[...Ze.getTrace(),...Nt.getTrace()],replValue:dt!==void 0?Z(dt):void 0}}function Sr(t,e="module.js"){return pt(t,e,{keepEsm:!0})}function qn(t=null,e=null){function r(i){return String(i||"").replace(/\/\*[\s\S]*?\*\//g," ").replace(/--[^\r\n]*/g," ").trim()}function s(i){const a=[];let f=0,m=null,b=-1;for(let x=0;x<i.length;x++){const u=i[x];if(m){u===m&&i[x-1]!=="\\"&&(m=null);continue}u==="'"||u==='"'?m=u:u==="("?(f===0&&(b=x+1),f++):u===")"&&(f--,f===0&&b!==-1&&(a.push(i.slice(b,x)),b=-1))}return a}function n(i){const a=[];let f="",m=null,b=0;for(let x=0;x<i.length;x++){const u=i[x];if(m){f+=u,u===m&&i[x-1]!=="\\"&&(m=null);continue}u==="'"||u==='"'?(m=u,f+=u):u==="("?(b++,f+=u):u===")"?(b=Math.max(0,b-1),f+=u):u===","&&b===0?(a.push(f.trim()),f=""):f+=u}return f.trim()&&a.push(f.trim()),a}return class{constructor(a=":memory:"){this.filename=a||":memory:",this.tables=new Map,this.indexes=new Map,this._loadFromVfs()}_resolveDbPath(){if(!this.filename||this.filename===":memory:")return null;const a=typeof e=="function"?e():"/workspace";return J.resolve(a||"/workspace",String(this.filename))}_loadFromVfs(){const a=this._resolveDbPath();if(!(!a||!t||typeof t.existsSync!="function"||!t.existsSync(a)))try{const f=t.readFileSync(a,"utf8"),m=String(f||"").trim();if(!m)return;if(m.startsWith("{")){const b=JSON.parse(m);if(b&&b.__codelab_sqlite__){if(b.tables&&typeof b.tables=="object")for(const[x,u]of Object.entries(b.tables))this.tables.set(x,u);if(b.indexes&&typeof b.indexes=="object")for(const[x,u]of Object.entries(b.indexes))this.indexes.set(x,u);return}}this.exec(m)}catch(f){j.debug("SqliteDatabase._loadFromVfs skipped",f)}}_persistToVfs(){const a=this._resolveDbPath();if(!(!a||!t||typeof t.writeFileSync!="function"))try{const f=J.dirname(a);typeof t.existsSync=="function"&&!t.existsSync(f)&&typeof t.mkdirSync=="function"&&t.mkdirSync(f,{recursive:!0});const m=JSON.stringify({__codelab_sqlite__:1,tables:Object.fromEntries(this.tables),indexes:Object.fromEntries(this.indexes)});t.writeFileSync(a,m)}catch(f){j.debug("SqliteDatabase._persistToVfs failed",f)}}run(a,f=[]){const m=r(a).replace(/;$/,"").trim();if(!m)return{changes:0,lastInsertRowid:0};if(/^CREATE\s+(?:TEMP\s+|TEMPORARY\s+)?TABLE/i.test(m)){const b=m.match(/^CREATE\s+(?:TEMP\s+|TEMPORARY\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-zA-Z0-9_]+)\s*\(([\s\S]*)\)/i);if(b){const x=b[1],u=n(b[2]),d=[];for(const y of u){if(/^(PRIMARY\s+KEY|FOREIGN\s+KEY|CONSTRAINT|UNIQUE|CHECK)\b/i.test(y))continue;const A=y.split(/\s+/),M=A[0].replace(/^["'`]|["'`]$/g,""),k=/PRIMARY\s+KEY/i.test(y),$=/AUTOINCREMENT/i.test(y)||/INTEGER/i.test(A[1]||"")&&k;d.push({name:M,type:A[1]||"TEXT",isPk:k,isAuto:$,raw:y})}this.tables.has(x)||(this.tables.set(x,{columns:d,rows:[],autoInc:0,sql:m}),this._persistToVfs())}return{changes:0,lastInsertRowid:0}}if(/^DROP\s+TABLE/i.test(m)){const b=m.match(/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([a-zA-Z0-9_]+)/i);return b&&(this.tables.delete(b[1]),this._persistToVfs()),{changes:0,lastInsertRowid:0}}if(/^CREATE\s+(?:UNIQUE\s+)?INDEX/i.test(m)){const b=m.match(/^CREATE\s+(UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-zA-Z0-9_]+)\s+ON\s+([a-zA-Z0-9_]+)\s*\(([^)]+)\)/i);if(b){const x=!!b[1],u=b[2],d=b[3],y=b[4].split(",").map(A=>A.trim().split(/\s+/)[0]);this.indexes.set(u,{name:u,table:d,columns:y,unique:x,sql:m}),this._persistToVfs()}return{changes:0,lastInsertRowid:0}}if(/^DROP\s+INDEX/i.test(m)){const b=m.match(/^DROP\s+INDEX\s+(?:IF\s+EXISTS\s+)?([a-zA-Z0-9_]+)/i);return b&&(this.indexes.delete(b[1]),this._persistToVfs()),{changes:0,lastInsertRowid:0}}if(/^ALTER\s+TABLE/i.test(m)){const b=m.match(/^ALTER\s+TABLE\s+([a-zA-Z0-9_]+)\s+ADD\s+(?:COLUMN\s+)?([a-zA-Z0-9_]+)\s*(.*)$/i);if(b){const x=this.tables.get(b[1]);if(x){const u=b[2],d=(b[3]||"TEXT").split(/\s+/)[0]||"TEXT";x.columns.push({name:u,type:d,isPk:!1,isAuto:!1}),this._persistToVfs()}}return{changes:0,lastInsertRowid:0}}if(/^PRAGMA\s+/i.test(m))return{changes:0,lastInsertRowid:0};if(/^INSERT\s+(?:OR\s+(?:REPLACE|IGNORE)\s+)?INTO/i.test(m)){const b=m.match(/^INSERT\s+(?:OR\s+(REPLACE|IGNORE)\s+)?INTO\s+([a-zA-Z0-9_]+)(?:\s*\(([^)]+)\))?\s*VALUES\s*([\s\S]*)$/i);if(b){const x=(b[1]||"").toUpperCase(),u=b[2],d=this.tables.get(u);if(!d)throw new Error(`no such table: ${u}`);const y=b[3]?b[3].split(",").map($=>$.trim()):null,A=s(b[4]),M=Array.isArray(f)?[...f]:[f];let k=0;for(const $ of A.length>0?A:[b[4].replace(/^\(|\)$/g,"")]){const l=n($),F=y||(l.length===d.columns.length?d.columns.map(w=>w.name):d.columns.filter(w=>!w.isPk).map(w=>w.name)),U={},C=d.columns.find(w=>w.isPk);for(let w=0;w<F.length;w++){const g=F[w],p=l[w]!==void 0?l[w]:"?";p==="?"?U[g]=M.shift():/^['"][\s\S]*['"]$/.test(p)?U[g]=p.slice(1,-1).replace(/''/g,"'"):/^null$/i.test(p)?U[g]=null:isNaN(Number(p))?U[g]=p:U[g]=Number(p)}if(C){U[C.name]===void 0||U[C.name]===null?(d.autoInc++,U[C.name]=d.autoInc):typeof U[C.name]=="number"&&U[C.name]>d.autoInc&&(d.autoInc=U[C.name]);const w=d.rows.findIndex(g=>String(g[C.name])===String(U[C.name]));if(w!==-1){if(x==="IGNORE")continue;if(x==="REPLACE"){d.rows[w]=U,k++;continue}}}else d.autoInc++;d.rows.push(U),k++}return this._persistToVfs(),{changes:k,lastInsertRowid:d.autoInc}}}if(/^DELETE\s+FROM/i.test(m)){const b=m.match(/^DELETE\s+FROM\s+([a-zA-Z0-9_]+)(?:\s+WHERE\s+([\s\S]*))?$/i);if(b){const x=this.tables.get(b[1]);if(!x)throw new Error(`no such table: ${b[1]}`);const u=b[2]?b[2].trim():null,d=Array.isArray(f)?[...f]:[f],y=x.rows.length;return u?x.rows=x.rows.filter(A=>!this._matchWhere(A,u,[...d])):x.rows=[],this._persistToVfs(),{changes:y-x.rows.length,lastInsertRowid:x.autoInc}}}if(/^UPDATE\s+/i.test(m)){const b=m.match(/^UPDATE\s+([a-zA-Z0-9_]+)\s+SET\s+([\s\S]*?)(?:\s+WHERE\s+([\s\S]*))?$/i);if(b){const x=this.tables.get(b[1]);if(!x)throw new Error(`no such table: ${b[1]}`);const u=n(b[2]),d=b[3]?b[3].trim():null,y=Array.isArray(f)?[...f]:[f];let A=0;for(const M of x.rows){const k=[...y],$=[];for(const l of u){const F=l.indexOf("="),U=l.slice(0,F).trim(),C=l.slice(F+1).trim(),w=C==="?"?k.shift():/^['"][\s\S]*['"]$/.test(C)?C.slice(1,-1):isNaN(Number(C))?C:Number(C);$.push([U,w])}if(!d||this._matchWhere(M,d,k)){for(const[l,F]of $)M[l]=F;A++}}return this._persistToVfs(),{changes:A,lastInsertRowid:x.autoInc}}}return{changes:0,lastInsertRowid:0}}_matchWhere(a,f,m){if(!f)return!0;const b=f.split(/\s+AND\s+/i);for(const x of b){const u=x.trim(),d=u.match(/^([a-zA-Z0-9_]+)\s+IS\s+(NOT\s+)?NULL$/i);if(d){const M=d[1],k=!!d[2],$=a[M]===null||a[M]===void 0;if(k?$:!$)return!1;continue}const y=u.match(/^([a-zA-Z0-9_]+)\s+LIKE\s+(.+)$/i);if(y){const M=y[1];let k=y[2].trim();if(k==="?"?k=String(m.shift()||""):/^['"].*['"]$/.test(k)&&(k=k.slice(1,-1)),!new RegExp("^"+k.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".")+"$","i").test(String(a[M]??"")))return!1;continue}const A=u.match(/^([a-zA-Z0-9_]+)\s*(=|!=|<>|>=|<=|>|<)\s*(.*)$/);if(A){const M=A[1].trim(),k=A[2];let $=A[3].trim();$==="?"?$=m.shift():/^['"].*['"]$/.test($)?$=$.slice(1,-1):isNaN(Number($))||($=Number($));const l=a[M];let F=!0;if(k==="="?F=String(l)===String($):k==="!="||k==="<>"?F=String(l)!==String($):k===">"?F=Number(l)>Number($):k==="<"?F=Number(l)<Number($):k===">="?F=Number(l)>=Number($):k==="<="&&(F=Number(l)<=Number($)),!F)return!1}}return!0}exec(a){const f=r(a),m=[];let b="",x=0;for(;x<f.length;){const u=f[x];if(u==="'"||u==='"'){const d=u;for(b+=u,x++;x<f.length;){if(f[x]===d&&f[x+1]===d){b+=d+d,x+=2;continue}if(f[x]==="\\"&&d==='"'){b+=f.slice(x,x+2),x+=2;continue}if(b+=f[x],f[x]===d){x++;break}x++}continue}if(u===";"){const d=b.trim();d&&m.push(d),b="",x++;continue}b+=u,x++}b.trim()&&m.push(b.trim());for(const u of m)this.run(u)}transaction(a){const f=this;return(...m)=>{const b=new Map;for(const[x,u]of f.tables.entries())b.set(x,{columns:u.columns.map(d=>Object.assign({},d)),rows:u.rows.map(d=>Object.assign({},d)),autoInc:u.autoInc});try{return a(...m)}catch(x){throw f.tables=b,f._persistToVfs(),x}}}close(){this._persistToVfs()}query(a){const f=this;return{all(...m){let b=m;return m.length===1&&Array.isArray(m[0])&&(b=m[0]),f._executeSelect(a,b)},get(...m){return this.all(...m)[0]||null},values(...m){return this.all(...m).map(x=>Object.values(x))},run(...m){let b=m;return m.length===1&&Array.isArray(m[0])&&(b=m[0]),f.run(a,b)}}}prepare(a){return this.query(a)}_evalAggregate(a,f,m){if(a==="COUNT")return f==="*"?m.length:m.filter(b=>b[f]!==null&&b[f]!==void 0).length;if(a==="AVG"){const b=m.reduce((x,u)=>x+(Number(u[f])||0),0);return m.length>0?b/m.length:0}return a==="SUM"?m.reduce((b,x)=>b+(Number(x[f])||0),0):a==="MIN"?m.length>0?Math.min(...m.map(b=>Number(b[f])||0)):null:a==="MAX"&&m.length>0?Math.max(...m.map(b=>Number(b[f])||0)):null}_executeSelect(a,f=[]){const m=r(a).replace(/;$/,"").trim();if(!m)return[];if(/^EXPLAIN\s+QUERY\s+PLAN\s+/i.test(m)){const p=m.replace(/^EXPLAIN\s+QUERY\s+PLAN\s+/i,"").trim().match(/^SELECT\s+[\s\S]*?\s+FROM\s+([a-zA-Z0-9_]+)(?:\s+WHERE\s+([\s\S]*?))?(?:\s+GROUP|\s+ORDER|\s+LIMIT|$)/i);if(p){const _=p[1],T=(p[2]||"").replace(/'[^']*'|"[^"]*"/g,""),R=this.tables.get(_),N=R&&R.columns.find(L=>L.isPk);if(N&&new RegExp(`\\b${N.name}\\b`,"i").test(T))return[{id:0,parent:0,notused:0,detail:`SEARCH ${_} USING INTEGER PRIMARY KEY (rowid=?)`}];for(const L of this.indexes.values())if(L.table===_&&L.columns.some(O=>new RegExp(`\\b${O}\\b`,"i").test(T)))return[{id:0,parent:0,notused:0,detail:`SEARCH ${_} USING INDEX ${L.name} (${L.columns.join(",")}=?)`}];return[{id:0,parent:0,notused:0,detail:`SCAN ${_}`}]}return[{id:0,parent:0,notused:0,detail:"SCAN"}]}if(/^PRAGMA\s+table_info\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i.test(m)){const g=m.match(/^PRAGMA\s+table_info\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i),p=g&&this.tables.get(g[1]);return p?p.columns.map((_,T)=>({cid:T,name:_.name,type:_.type||"TEXT",notnull:0,dflt_value:null,pk:_.isPk?1:0})):[]}if(/^PRAGMA\s+index_list\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i.test(m)){const g=m.match(/^PRAGMA\s+index_list\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i),p=g?g[1]:"",_=[];let T=0;for(const R of this.indexes.values())R.table===p&&_.push({seq:T++,name:R.name,unique:R.unique?1:0,origin:"c",partial:0});return _}if(/^(?:INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|PRAGMA)\b/i.test(m))return this.run(m,f),[];const b=m.match(/^SELECT\s+(?:DISTINCT\s+)?([\s\S]*?)\s+FROM\s+([a-zA-Z0-9_]+)(?:\s+WHERE\s+([\s\S]*?))?(?:\s+GROUP\s+BY\s+([\s\S]*?))?(?:\s+ORDER\s+BY\s+([\s\S]*?))?(?:\s+LIMIT\s+(\d+|\?)(?:\s+OFFSET\s+(\d+|\?))?)?$/i);if(!b){const g=m.match(/^SELECT\s+([\s\S]+)$/i);if(g){const p=n(g[1]),_={};for(const T of p){const R=T.match(/^([\s\S]*?)\s+AS\s+([a-zA-Z0-9_]+)$/i),N=(R?R[1]:T).trim(),L=(R?R[2]:T).trim();/^sqlite_version\(\)$/i.test(N)?_[L]="3.45.0":/^['"].*['"]$/.test(N)?_[L]=N.slice(1,-1):isNaN(Number(N))?_[L]=N:_[L]=Number(N)}return[_]}return[]}const x=b[1].trim(),u=b[2].trim(),d=b[3]?b[3].trim():null,y=b[4]?b[4].trim():null,A=b[5]?b[5].trim():null,M=b[6]?b[6].trim():null,k=b[7]?b[7].trim():null,$=this.tables.get(u);if(!$)return[];const l=Array.isArray(f)?[...f]:[f],F=$.rows.filter(g=>{const p=[...l];return this._matchWhere(g,d,p)});if(d&&d.includes("?")){const g=(d.match(/\?/g)||[]).length;l.splice(0,g)}const U=[];let C=!1;if(x!=="*"){const g=n(x);for(const p of g){const _=p.match(/^([\s\S]*?)\s+(?:AS\s+)?([a-zA-Z0-9_]+)$/i),T=/^(AVG|SUM|COUNT|MIN|MAX)\s*\([^)]+\)$/i.test(p.trim()),R=_&&!T?{expr:_[1].trim(),alias:_[2].trim()}:{expr:p.trim(),alias:p.trim()};/^(AVG|SUM|COUNT|MIN|MAX)\s*\(([^)]+)\)$/i.test(R.expr)&&(C=!0),U.push(R)}}let w=[];if(y){const g=y.trim(),p=new Map;for(const _ of F){const T=_[g];p.has(T)||p.set(T,[]),p.get(T).push(_)}for(const[_,T]of p.entries()){const R={};for(const N of U){const L=N.expr,O=N.alias,B=L.match(/^(AVG|SUM|COUNT|MIN|MAX)\s*\(([^)]+)\)$/i);B?R[O]=this._evalAggregate(B[1].toUpperCase(),B[2].trim(),T):L===g?R[O]=_:R[O]=T[0]?T[0][L]:null}w.push(R)}}else if(C){const g={};for(const p of U){const _=p.expr.match(/^(AVG|SUM|COUNT|MIN|MAX)\s*\(([^)]+)\)$/i);_?g[p.alias]=this._evalAggregate(_[1].toUpperCase(),_[2].trim(),F):g[p.alias]=F[0]?F[0][p.expr]:null}w.push(g)}else for(const g of F)if(x==="*")w.push(Object.assign({},g));else{const p={};for(const _ of U)p[_.alias]=g[_.expr];w.push(p)}if(A){const g=A.trim().split(/\s+/),p=g[0],_=g[1]&&g[1].toUpperCase()==="DESC";w.sort((T,R)=>{const N=T[p],L=R[p];if(N===L)return 0;if(N===void 0)return 1;if(L===void 0)return-1;const O=N>L?1:-1;return _?-O:O})}if(M!==null){const g=Number(M==="?"?l.shift()||0:M),p=k!==null?Number(k==="?"?l.shift()||0:k):0;w=w.slice(p,p+g)}return w}}}return{VirtualBuffer:P,VirtualCrypto:Fe,VirtualZlib:xe,VirtualPath:J,VirtualOs:ln,VirtualAssert:pe,EventEmitter:fe,VirtualUtil:kt,VirtualUrl:At,VirtualQuerystring:$e,VirtualStream:hn,VirtualStreamPromises:Wt,VirtualStringDecoder:pn,VirtualDns:It,createVirtualFs:Dt,createVirtualHttp:Bn,createVirtualNet:Pn,createSqliteDatabase:qn,transpileTS:pt,transpileForBrowser:Sr,preloadNpmPackages:br,createVirtualPortTable:Fn,createVirtualWasi:wn,executeWasiModule:Vt,executeInVirtualRuntime:wr,clearReplSession(t){t?jt.delete(t):jt.clear()}}}function __workerMessageLoop(X){const j=X.__virtualRuntime,de=new Map;let ce=1;X.onmessage=async function(ne){const Q=ne.data||{},{requestId:ee,type:le,payload:ye={}}=Q;if(le==="clear-repl"){j&&typeof j.clearReplSession=="function"&&j.clearReplSession(Q.replSessionId);return}if(le==="stdin-reply"){const Se=de.get(Q.stdinId);Se&&(de.delete(Q.stdinId),Se(Q.value));return}if(le==="execute"){X.postMessage({requestId:ee,type:"started"});try{const Se=await j.executeInVirtualRuntime({...ye,_captureVfsDiff:!0,...ye.interactiveStdin?{onRequestStdin(Ne){const ke=`${ee}_${ce++}`;return new Promise(P=>{de.set(ke,P),X.postMessage({requestId:ee,type:"stdin-request",stdinId:ke,prompt:Ne})})}}:{},onStdout(Ne){X.postMessage({requestId:ee,type:"stdout",text:Ne})},onStderr(Ne){X.postMessage({requestId:ee,type:"stderr",text:Ne})},onTestResult(Ne){X.postMessage({requestId:ee,type:"test-result",testResult:Ne})}});X.postMessage({requestId:ee,type:"complete",result:Se})}catch(Se){X.postMessage({requestId:ee,type:"error",error:{message:Se&&Se.message?Se.message:String(Se),stack:Se&&Se.stack}})}}}}function createWorkerRuntimeSource(){return`'use strict';
114
+ `,H=(ve[ve.length-1]||"").trim()}if(H&&!/^\s*(const|let|var|function|class|if|for|while|switch|try|return|throw)\b/.test(H)){const ve=q+`return (${H.replace(/;+\s*$/,"")});`;try{Nn([],ve),P=ve}catch{P=I}}let ie=null;t&&typeof t.replSessionId=="string"&&t.replSessionId&&(ie=jt.get(t.replSessionId),ie||(ie=Object.create(null),jt.set(t.replSessionId,ie)),P=or(P,ie));const ye=Nn(["require","Buffer","process","console","setTimeout","clearTimeout","setInterval","clearInterval","setImmediate","clearImmediate","Bun","fetch","__replCtx"],`return (async () => {
115
+ ${P}
116
+ })();`);dt=await sr(ye(M,O,Ae,Ye,mt,Gt,Jt,Xt,$t,Kt,Ut,ut.fetch,ie||Object.create(null))),ie&&dt!==void 0&&(ie._=dt),!j&&dt!==void 0&&t.printReplResult!==!1&&Y(z(dt)+`
117
+ `)}else{const _=n.startsWith("/")?n:J.resolve(_e,n);let E=V.existsSync(_)?_:V.existsSync(n)?n:`/workspace/${n.replace(/^\/+/,"")}`;if(!V.existsSync(E)){const W=`/workspace/src/${n.replace(/^\/+/,"")}`;V.existsSync(W)&&(E=W)}const M=/\.(cpp|cc|cxx)$/i.test(E),I=/\.py$/i.test(E);if(/\.wasm$/i.test(E)||!!t.wasmBinary){const W=t.wasmBinary||V.readFileSync(E);$=(await Vt(W,{vfs:V,args:u||[E],env:Object.assign({},Ae.env,t.env||{}),stdin:t.stdin||"",onStdout:Y,onStderr:ee})).exitCode,j=!0}else if(M){const W=t.cppCompiler||typeof globalThis<"u"&&globalThis.__codelabCppCompiler||X&&X.__codelabCppCompiler;if(typeof W!="function")throw new Error('C++ toolchain is not registered. Enable cppExtension from "@innovatorved/code-lab/extensions/cpp" to compile and run C++ files.');const q=await W({entry:E,vfs:V,files:typeof V.toSnapshot=="function"?V.toSnapshot("/workspace"):e||{},args:u||[E],env:Object.assign({},Ae.env,t.env||{}),stdin:t.stdin||"",testFilter:f,onStdout:Y,onStderr:ee});q&&q.wasmBinary?($=(await Vt(q.wasmBinary,{vfs:V,args:q.args||u||[E],env:Object.assign({},Ae.env,t.env||{}),stdin:t.stdin||"",onStdout:Y,onStderr:ee})).exitCode,j=!0):q&&typeof q.exitCode=="number"&&($=q.exitCode,j=!0)}else if(I){const W=t.pythonCompiler||typeof globalThis<"u"&&globalThis.__codelabPythonCompiler||X&&X.__codelabPythonCompiler;if(typeof W!="function")throw new Error('Python WebAssembly toolchain is not registered. Enable pythonExtension from "@innovatorved/code-lab/extensions/python" to run Python files.');const q=g.length,H=await W({entry:E,vfs:V,files:typeof V.toSnapshot=="function"?V.toSnapshot("/workspace"):e||{},args:u||[E],env:Object.assign({},Ae.env,t.env||{}),stdin:t.stdin||"",onRequestStdin:t.onRequestStdin,testFilter:f,onStdout:Y,onStderr:ee});if(H&&($=typeof H.exitCode=="number"?H.exitCode:H.ok?0:1,g.length===q&&H.testResults&&Array.isArray(H.testResults)))for(const ie of H.testResults)g.push(ie);j=!0}else{let W=null;if(V.existsSync(E))try{W=V.readFileSync(E)}catch(q){D.debug("Failed to probe binary header",q)}if(W&&W.length>=4&&W[0]===0&&W[1]===97&&W[2]===115&&W[3]===109)$=(await Vt(W,{vfs:V,args:u||[E],env:Object.assign({},Ae.env,t.env||{}),stdin:t.stdin||"",onStdout:Y,onStderr:ee})).exitCode,j=!0;else{const q=Ft(E,!0);q&&typeof q.then=="function"&&await sr(q)}}}const o=()=>{if(Ze.hasActiveServers())return!0;if(et.size>0){for(const _ of Array.from(et))Ce.getServer(_.port)||et.delete(_);return et.size>0}return!1},c=performance.now()+p;let h=0;for(;!j;){if(F&&F.aborted){gt();break}const _=o(),E=!!(!B&&F&&_);if(!E&&performance.now()>=c)break;if(await Promise.resolve(),await Promise.resolve(),C.activeTimers.size>0||C.activeImmediates.size>0||C.inFlightHttp.size>0||C.pendingTests.size>0||(B||!!F)&&_)h=0;else if(h++,h>=2)break;await new Promise(I=>setTimeout(I,E?25:2))}}catch(o){o&&o._isProcessExit?$=o.exitCode:($=1,ee((o&&o.stack?o.stack:String(o))+`
118
+ `))}finally{if(F&&Qt)try{F.removeEventListener("abort",Qt)}catch(o){D.debug("executeInVirtualRuntime removeEventListener failed",o)}if(!j){j=!0;try{Ae.emit("exit",$)}catch(o){D.debug("executeInVirtualRuntime exit listener failed",o)}}typeof V._setActiveStdin=="function"&&V._setActiveStdin("");for(const o of C.allTimers)clearTimeout(o),clearInterval(o);if(C.activeTimers.clear(),C.allTimers.clear(),C.activeImmediates.clear(),C.inFlightHttp.clear(),le.length>0){const o=le;le="",Y(o+`
119
+ `)}if(!B){Ze.closeAllServers(),Nt.closeAllServers();for(const o of Array.from(et))try{o.stop()}catch(c){D.debug("executeInVirtualRuntime bun server stop failed",c)}if(et.clear(),qn&&typeof V._listOpenFds=="function"&&typeof V.closeSync=="function"){for(const o of V._listOpenFds())if(!qn.has(o))try{V.closeSync(o)}catch(c){D.debug("executeInVirtualRuntime closeSync leak cleanup failed",{fd:o,err:c})}}}it=ct,xt=Oe}const $n=g.filter(o=>!o.passed).length;$n>0&&$===0&&($=1);let Ln;if(Ht&&typeof V._exportRawState=="function"){const o=V._exportRawState(),c={},h=[],_=[],E=I=>I==="/workspace/node_modules"||I.startsWith("/workspace/node_modules/"),M=(I,P)=>{if(!I||!P||I.byteLength!==P.byteLength)return!1;for(let W=0;W<I.byteLength;W++)if(I[W]!==P[W])return!1;return!0};for(const I of o.dirs)!Ht.dirs.has(I)&&!E(I)&&_.push(I);for(const[I,P]of o.files.entries()){if(E(I))continue;const W=Ht.files.get(I);(!W||!M(W,P))&&(c[I]=P)}for(const I of Ht.files.keys())E(I)||o.files.has(I)||h.push(I);Ln={modifiedFiles:c,deletedFiles:h,createdDirs:_}}return{ok:$===0,exitCode:$,durationMs:Math.max(0,performance.now()-U),stdout:b.join(""),stderr:w.join(""),cancelled:$===130||Yt||!!(F&&F.aborted),outputTruncated:T,testResults:g,testSummary:{total:g.length,passed:g.length-$n,failed:$n},fsSnapshot:typeof V.getSnapshot=="function"?V.getSnapshot():[],...Ln?{vfsChanges:Ln}:{},httpTrace:[...Ze.getTrace(),...Nt.getTrace()],replValue:dt!==void 0?z(dt):void 0}}function Sr(t,e="module.js"){return pt(t,e,{keepEsm:!0})}function zn(t=null,e=null){function r(i){return String(i||"").replace(/\/\*[\s\S]*?\*\//g," ").replace(/--[^\r\n]*/g," ").trim()}function s(i){const a=[];let f=0,p=null,y=-1;for(let S=0;S<i.length;S++){const l=i[S];if(p){l===p&&i[S-1]!=="\\"&&(p=null);continue}l==="'"||l==='"'?p=l:l==="("?(f===0&&(y=S+1),f++):l===")"&&(f--,f===0&&y!==-1&&(a.push(i.slice(y,S)),y=-1))}return a}function n(i){const a=[];let f="",p=null,y=0;for(let S=0;S<i.length;S++){const l=i[S];if(p){f+=l,l===p&&i[S-1]!=="\\"&&(p=null);continue}l==="'"||l==='"'?(p=l,f+=l):l==="("?(y++,f+=l):l===")"?(y=Math.max(0,y-1),f+=l):l===","&&y===0?(a.push(f.trim()),f=""):f+=l}return f.trim()&&a.push(f.trim()),a}return class{constructor(a=":memory:"){this.filename=a||":memory:",this.tables=new Map,this.indexes=new Map,this._loadFromVfs()}_resolveDbPath(){if(!this.filename||this.filename===":memory:")return null;const a=typeof e=="function"?e():"/workspace";return J.resolve(a||"/workspace",String(this.filename))}_loadFromVfs(){const a=this._resolveDbPath();if(!(!a||!t||typeof t.existsSync!="function"||!t.existsSync(a)))try{const f=t.readFileSync(a,"utf8"),p=String(f||"").trim();if(!p)return;if(p.startsWith("{")){const y=JSON.parse(p);if(y&&y.__codelab_sqlite__){if(y.tables&&typeof y.tables=="object")for(const[S,l]of Object.entries(y.tables))this.tables.set(S,l);if(y.indexes&&typeof y.indexes=="object")for(const[S,l]of Object.entries(y.indexes))this.indexes.set(S,l);return}}this.exec(p)}catch(f){D.debug("SqliteDatabase._loadFromVfs skipped",f)}}_persistToVfs(){const a=this._resolveDbPath();if(!(!a||!t||typeof t.writeFileSync!="function"))try{const f=J.dirname(a);typeof t.existsSync=="function"&&!t.existsSync(f)&&typeof t.mkdirSync=="function"&&t.mkdirSync(f,{recursive:!0});const p=JSON.stringify({__codelab_sqlite__:1,tables:Object.fromEntries(this.tables),indexes:Object.fromEntries(this.indexes)});t.writeFileSync(a,p)}catch(f){D.debug("SqliteDatabase._persistToVfs failed",f)}}run(a,f=[]){const p=r(a).replace(/;$/,"").trim();if(!p)return{changes:0,lastInsertRowid:0};if(/^CREATE\s+(?:TEMP\s+|TEMPORARY\s+)?TABLE/i.test(p)){const y=p.match(/^CREATE\s+(?:TEMP\s+|TEMPORARY\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-zA-Z0-9_]+)\s*\(([\s\S]*)\)/i);if(y){const S=y[1],l=n(y[2]),d=[];for(const m of l){if(/^(PRIMARY\s+KEY|FOREIGN\s+KEY|CONSTRAINT|UNIQUE|CHECK)\b/i.test(m))continue;const A=m.split(/\s+/),N=A[0].replace(/^["'`]|["'`]$/g,""),k=/PRIMARY\s+KEY/i.test(m),L=/AUTOINCREMENT/i.test(m)||/INTEGER/i.test(A[1]||"")&&k;d.push({name:N,type:A[1]||"TEXT",isPk:k,isAuto:L,raw:m})}this.tables.has(S)||(this.tables.set(S,{columns:d,rows:[],autoInc:0,sql:p}),this._persistToVfs())}return{changes:0,lastInsertRowid:0}}if(/^DROP\s+TABLE/i.test(p)){const y=p.match(/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([a-zA-Z0-9_]+)/i);return y&&(this.tables.delete(y[1]),this._persistToVfs()),{changes:0,lastInsertRowid:0}}if(/^CREATE\s+(?:UNIQUE\s+)?INDEX/i.test(p)){const y=p.match(/^CREATE\s+(UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-zA-Z0-9_]+)\s+ON\s+([a-zA-Z0-9_]+)\s*\(([^)]+)\)/i);if(y){const S=!!y[1],l=y[2],d=y[3],m=y[4].split(",").map(A=>A.trim().split(/\s+/)[0]);this.indexes.set(l,{name:l,table:d,columns:m,unique:S,sql:p}),this._persistToVfs()}return{changes:0,lastInsertRowid:0}}if(/^DROP\s+INDEX/i.test(p)){const y=p.match(/^DROP\s+INDEX\s+(?:IF\s+EXISTS\s+)?([a-zA-Z0-9_]+)/i);return y&&(this.indexes.delete(y[1]),this._persistToVfs()),{changes:0,lastInsertRowid:0}}if(/^ALTER\s+TABLE/i.test(p)){const y=p.match(/^ALTER\s+TABLE\s+([a-zA-Z0-9_]+)\s+ADD\s+(?:COLUMN\s+)?([a-zA-Z0-9_]+)\s*(.*)$/i);if(y){const S=this.tables.get(y[1]);if(S){const l=y[2],d=(y[3]||"TEXT").split(/\s+/)[0]||"TEXT";S.columns.push({name:l,type:d,isPk:!1,isAuto:!1}),this._persistToVfs()}}return{changes:0,lastInsertRowid:0}}if(/^PRAGMA\s+/i.test(p))return{changes:0,lastInsertRowid:0};if(/^INSERT\s+(?:OR\s+(?:REPLACE|IGNORE)\s+)?INTO/i.test(p)){const y=p.match(/^INSERT\s+(?:OR\s+(REPLACE|IGNORE)\s+)?INTO\s+([a-zA-Z0-9_]+)(?:\s*\(([^)]+)\))?\s*VALUES\s*([\s\S]*)$/i);if(y){const S=(y[1]||"").toUpperCase(),l=y[2],d=this.tables.get(l);if(!d)throw new Error(`no such table: ${l}`);const m=y[3]?y[3].split(",").map(L=>L.trim()):null,A=s(y[4]),N=Array.isArray(f)?[...f]:[f];let k=0;for(const L of A.length>0?A:[y[4].replace(/^\(|\)$/g,"")]){const u=n(L),B=m||(u.length===d.columns.length?d.columns.map(b=>b.name):d.columns.filter(b=>!b.isPk).map(b=>b.name)),F={},U=d.columns.find(b=>b.isPk);for(let b=0;b<B.length;b++){const w=B[b],g=u[b]!==void 0?u[b]:"?";g==="?"?F[w]=N.shift():/^['"][\s\S]*['"]$/.test(g)?F[w]=g.slice(1,-1).replace(/''/g,"'"):/^null$/i.test(g)?F[w]=null:isNaN(Number(g))?F[w]=g:F[w]=Number(g)}if(U){F[U.name]===void 0||F[U.name]===null?(d.autoInc++,F[U.name]=d.autoInc):typeof F[U.name]=="number"&&F[U.name]>d.autoInc&&(d.autoInc=F[U.name]);const b=d.rows.findIndex(w=>String(w[U.name])===String(F[U.name]));if(b!==-1){if(S==="IGNORE")continue;if(S==="REPLACE"){d.rows[b]=F,k++;continue}}}else d.autoInc++;d.rows.push(F),k++}return this._persistToVfs(),{changes:k,lastInsertRowid:d.autoInc}}}if(/^DELETE\s+FROM/i.test(p)){const y=p.match(/^DELETE\s+FROM\s+([a-zA-Z0-9_]+)(?:\s+WHERE\s+([\s\S]*))?$/i);if(y){const S=this.tables.get(y[1]);if(!S)throw new Error(`no such table: ${y[1]}`);const l=y[2]?y[2].trim():null,d=Array.isArray(f)?[...f]:[f],m=S.rows.length;return l?S.rows=S.rows.filter(A=>!this._matchWhere(A,l,[...d])):S.rows=[],this._persistToVfs(),{changes:m-S.rows.length,lastInsertRowid:S.autoInc}}}if(/^UPDATE\s+/i.test(p)){const y=p.match(/^UPDATE\s+([a-zA-Z0-9_]+)\s+SET\s+([\s\S]*?)(?:\s+WHERE\s+([\s\S]*))?$/i);if(y){const S=this.tables.get(y[1]);if(!S)throw new Error(`no such table: ${y[1]}`);const l=n(y[2]),d=y[3]?y[3].trim():null,m=Array.isArray(f)?[...f]:[f];let A=0;for(const N of S.rows){const k=[...m],L=[];for(const u of l){const B=u.indexOf("="),F=u.slice(0,B).trim(),U=u.slice(B+1).trim(),b=U==="?"?k.shift():/^['"][\s\S]*['"]$/.test(U)?U.slice(1,-1):isNaN(Number(U))?U:Number(U);L.push([F,b])}if(!d||this._matchWhere(N,d,k)){for(const[u,B]of L)N[u]=B;A++}}return this._persistToVfs(),{changes:A,lastInsertRowid:S.autoInc}}}return{changes:0,lastInsertRowid:0}}_matchWhere(a,f,p){if(!f)return!0;const y=f.split(/\s+AND\s+/i);for(const S of y){const l=S.trim(),d=l.match(/^([a-zA-Z0-9_.]+)\s+IS\s+(NOT\s+)?NULL$/i);if(d){const N=d[1],k=!!d[2],L=a[N]===null||a[N]===void 0;if(k?L:!L)return!1;continue}const m=l.match(/^([a-zA-Z0-9_.]+)\s+LIKE\s+(.+)$/i);if(m){const N=m[1];let k=m[2].trim();if(k==="?"?k=String(p.shift()||""):/^['"].*['"]$/.test(k)&&(k=k.slice(1,-1)),!new RegExp("^"+k.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".")+"$","i").test(String(a[N]??"")))return!1;continue}const A=l.match(/^([a-zA-Z0-9_.]+)\s*(=|!=|<>|>=|<=|>|<)\s*(.*)$/);if(A){const N=A[1].trim(),k=A[2];let L=A[3].trim();L==="?"?L=p.shift():/^['"].*['"]$/.test(L)?L=L.slice(1,-1):isNaN(Number(L))||(L=Number(L));const u=a[N];let B=!0;if(k==="="?B=String(u)===String(L):k==="!="||k==="<>"?B=String(u)!==String(L):k===">"?B=Number(u)>Number(L):k==="<"?B=Number(u)<Number(L):k===">="?B=Number(u)>=Number(L):k==="<="&&(B=Number(u)<=Number(L)),!B)return!1}}return!0}exec(a){const f=r(a),p=[];let y="",S=0;for(;S<f.length;){const l=f[S];if(l==="'"||l==='"'){const d=l;for(y+=l,S++;S<f.length;){if(f[S]===d&&f[S+1]===d){y+=d+d,S+=2;continue}if(f[S]==="\\"&&d==='"'){y+=f.slice(S,S+2),S+=2;continue}if(y+=f[S],f[S]===d){S++;break}S++}continue}if(l===";"){const d=y.trim();d&&p.push(d),y="",S++;continue}y+=l,S++}y.trim()&&p.push(y.trim());for(const l of p)this.run(l)}transaction(a){const f=this;return(...p)=>{const y=new Map;for(const[S,l]of f.tables.entries())y.set(S,{columns:l.columns.map(d=>Object.assign({},d)),rows:l.rows.map(d=>Object.assign({},d)),autoInc:l.autoInc});try{return a(...p)}catch(S){throw f.tables=y,f._persistToVfs(),S}}}close(){this._persistToVfs()}query(a){const f=this;return{all(...p){let y=p;return p.length===1&&Array.isArray(p[0])&&(y=p[0]),f._executeSelect(a,y)},get(...p){return this.all(...p)[0]||null},values(...p){return this.all(...p).map(S=>Object.values(S))},run(...p){let y=p;return p.length===1&&Array.isArray(p[0])&&(y=p[0]),f.run(a,y)}}}prepare(a){return this.query(a)}_evalAggregate(a,f,p){if(a==="COUNT")return f==="*"?p.length:p.filter(y=>y[f]!==null&&y[f]!==void 0).length;if(a==="AVG"){const y=p.reduce((S,l)=>S+(Number(l[f])||0),0);return p.length>0?y/p.length:0}return a==="SUM"?p.reduce((y,S)=>y+(Number(S[f])||0),0):a==="MIN"?p.length>0?Math.min(...p.map(y=>Number(y[f])||0)):null:a==="MAX"&&p.length>0?Math.max(...p.map(y=>Number(y[f])||0)):null}_evalSelectExpr(a,f,p){const y=a.trim(),S=y.match(/^ROUND\s*\(([\s\S]+),\s*(\d+)\s*\)$/i);if(S){const m=Number(this._evalSelectExpr(S[1],f,p)),A=Number(S[2]),N=Math.pow(10,A);return Number.isFinite(m)?Math.round(m*N)/N:null}const l=y.match(/^((?:AVG|SUM|COUNT|MIN|MAX)\s*\([^)]+\))\s*([/*+-])\s*([0-9.]+)$/i);if(l){const m=Number(this._evalSelectExpr(l[1],f,p)),A=Number(l[3]);if(l[2]==="/")return A!==0?m/A:null;if(l[2]==="*")return m*A;if(l[2]==="+")return m+A;if(l[2]==="-")return m-A}const d=y.match(/^(AVG|SUM|COUNT|MIN|MAX)\s*\(([^)]+)\)$/i);return d?this._evalAggregate(d[1].toUpperCase(),d[2].trim(),f):p&&Object.prototype.hasOwnProperty.call(p,y)?p[y]:f[0]&&Object.prototype.hasOwnProperty.call(f[0],y)?f[0][y]:null}_executeSelect(a,f=[]){const p=r(a).replace(/;$/,"").trim();if(!p)return[];if(/^EXPLAIN\s+QUERY\s+PLAN\s+/i.test(p)){const v=p.replace(/^EXPLAIN\s+QUERY\s+PLAN\s+/i,"").trim().match(/^SELECT\s+[\s\S]*?\s+FROM\s+([a-zA-Z0-9_]+)(?:\s+WHERE\s+([\s\S]*?))?(?:\s+GROUP|\s+ORDER|\s+LIMIT|$)/i);if(v){const $=v[1],j=(v[2]||"").replace(/'[^']*'|"[^"]*"/g,""),C=this.tables.get($),z=C&&C.columns.find(Z=>Z.isPk);if(z&&new RegExp(`\\b${z.name}\\b`,"i").test(j))return[{id:0,parent:0,notused:0,detail:`SEARCH ${$} USING INTEGER PRIMARY KEY (rowid=?)`}];for(const Z of this.indexes.values())if(Z.table===$&&Z.columns.some(Q=>new RegExp(`\\b${Q}\\b`,"i").test(j)))return[{id:0,parent:0,notused:0,detail:`SEARCH ${$} USING INDEX ${Z.name} (${Z.columns.join(",")}=?)`}];return[{id:0,parent:0,notused:0,detail:`SCAN ${$}`}]}return[{id:0,parent:0,notused:0,detail:"SCAN"}]}if(/^PRAGMA\s+table_info\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i.test(p)){const T=p.match(/^PRAGMA\s+table_info\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i),v=T&&this.tables.get(T[1]);return v?v.columns.map(($,j)=>({cid:j,name:$.name,type:$.type||"TEXT",notnull:0,dflt_value:null,pk:$.isPk?1:0})):[]}if(/^PRAGMA\s+index_list\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i.test(p)){const T=p.match(/^PRAGMA\s+index_list\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i),v=T?T[1]:"",$=[];let j=0;for(const C of this.indexes.values())C.table===v&&$.push({seq:j++,name:C.name,unique:C.unique?1:0,origin:"c",partial:0});return $}if(/^(?:INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|PRAGMA)\b/i.test(p))return this.run(p,f),[];const y=p.match(/^SELECT\s+(?:DISTINCT\s+)?([\s\S]*?)\s+FROM\s+([a-zA-Z0-9_]+)(?:\s+(?:AS\s+)?(?!WHERE\b|JOIN\b|INNER\b|LEFT\b|RIGHT\b|FULL\b|CROSS\b|GROUP\b|ORDER\b|LIMIT\b)([a-zA-Z0-9_]+))?((?:\s+(?:(?:INNER|LEFT(?:\s+OUTER)?)\s+)?JOIN\s+[a-zA-Z0-9_]+(?:\s+(?:AS\s+)?(?!ON\b)[a-zA-Z0-9_]+)?\s+ON\s+[a-zA-Z0-9_.]+\s*=\s*[a-zA-Z0-9_.]+)*)(?:\s+WHERE\s+([\s\S]*?))?(?:\s+GROUP\s+BY\s+([\s\S]*?))?(?:\s+ORDER\s+BY\s+([\s\S]*?))?(?:\s+LIMIT\s+(\d+|\?)(?:\s+OFFSET\s+(\d+|\?))?)?$/i);if(!y){const T=p.match(/^SELECT\s+([\s\S]+)$/i);if(T){const v=n(T[1]),$={};for(const j of v){const C=j.match(/^([\s\S]*?)\s+AS\s+([a-zA-Z0-9_]+)$/i),z=(C?C[1]:j).trim(),Z=(C?C[2]:j).trim();/^sqlite_version\(\)$/i.test(z)?$[Z]="3.45.0":/^['"].*['"]$/.test(z)?$[Z]=z.slice(1,-1):isNaN(Number(z))?$[Z]=z:$[Z]=Number(z)}return[$]}return[]}const S=y[1].trim(),l=y[2].trim(),d=(y[3]||l).trim(),m=(y[4]||"").trim(),A=y[5]?y[5].trim():null,N=y[6]?y[6].trim():null,k=y[7]?y[7].trim():null,L=y[8]?y[8].trim():null,u=y[9]?y[9].trim():null,B=this.tables.get(l);if(!B)return[];const F=(T,v,$)=>{const j=Object.assign({},T);for(const[C,z]of Object.entries(T))j[`${v}.${C}`]=z,$&&$!==v&&(j[`${$}.${C}`]=z);return j};let U=B.rows.map(T=>F(T,l,d));if(m){const T=/(?:(INNER|LEFT(?:\s+OUTER)?)\s+)?JOIN\s+([a-zA-Z0-9_]+)(?:\s+(?:AS\s+)?(?!ON\b)([a-zA-Z0-9_]+))?\s+ON\s+([a-zA-Z0-9_.]+)\s*=\s*([a-zA-Z0-9_.]+)/gi;let v;for(;(v=T.exec(m))!==null;){const $=!!(v[1]&&/^LEFT/i.test(v[1])),j=v[2],C=v[3]||j,z=v[4],Z=v[5],Q=this.tables.get(j);if(!Q){U=[];break}const le=[];for(const de of U){let Y=!1;for(const ee of Q.rows){const K=F(ee,j,C),be=Object.assign({},de,K),Me=Object.prototype.hasOwnProperty.call(de,z)?de[z]:K[z],Ce=Object.prototype.hasOwnProperty.call(K,Z)?K[Z]:de[Z];Me!==void 0&&Ce!==void 0&&String(Me)===String(Ce)&&(le.push(be),Y=!0)}if(!Y&&$){const ee=Object.assign({},de);for(const K of Q.columns)ee[`${j}.${K.name}`]=null,C!==j&&(ee[`${C}.${K.name}`]=null);le.push(ee)}}U=le}}const b=Array.isArray(f)?[...f]:[f],w=U.filter(T=>{const v=[...b];return this._matchWhere(T,A,v)});if(A&&A.includes("?")){const T=(A.match(/\?/g)||[]).length;b.splice(0,T)}const g=[];let x=!1;if(S!=="*"){const T=n(S);for(const v of T){const $=v.match(/^([\s\S]*?)\s+AS\s+([a-zA-Z0-9_]+)$/i)||(/\)/.test(v.trim())?null:v.match(/^([a-zA-Z0-9_.]+)\s+([a-zA-Z0-9_]+)$/)),j=($?$[1]:v).trim(),C=j.includes(".")&&!/[()\s]/.test(j)?j.split(".").pop():j,z={expr:j,alias:$?$[2].trim():C};/\b(AVG|SUM|COUNT|MIN|MAX)\s*\(/i.test(z.expr)&&(x=!0),g.push(z)}}let R=[];if(N){const T=N.split(",").map($=>$.trim()).filter(Boolean),v=new Map;for(const $ of w){const j=T.length===1?$[T[0]]:JSON.stringify(T.map(C=>$[C]));v.has(j)||v.set(j,[]),v.get(j).push($)}for(const[,$]of v.entries()){const j={};for(const C of g)j[C.alias]=this._evalSelectExpr(C.expr,$,$[0]);R.push(j)}}else if(x){const T={};for(const v of g)T[v.alias]=this._evalSelectExpr(v.expr,w,w[0]);R.push(T)}else for(const T of w)if(S==="*"){const v={};for(const[$,j]of Object.entries(T))$.includes(".")||(v[$]=j);R.push(v)}else{const v={};for(const $ of g)v[$.alias]=this._evalSelectExpr($.expr,[T],T);R.push(v)}if(k){const T=k.trim().split(/\s+/),v=T[0],$=T[1]&&T[1].toUpperCase()==="DESC";R.sort((j,C)=>{const z=j[v],Z=C[v];if(z===Z)return 0;if(z===void 0)return 1;if(Z===void 0)return-1;const Q=z>Z?1:-1;return $?-Q:Q})}if(L!==null){const T=Number(L==="?"?b.shift()||0:L),v=u!==null?Number(u==="?"?b.shift()||0:u):0;R=R.slice(v,v+T)}return R}}}return{VirtualBuffer:O,VirtualCrypto:je,VirtualZlib:Ee,VirtualPath:J,VirtualOs:ln,VirtualAssert:me,EventEmitter:fe,VirtualUtil:It,VirtualUrl:At,VirtualQuerystring:Le,VirtualStream:hn,VirtualStreamPromises:Ot,VirtualStringDecoder:pn,VirtualDns:kt,createVirtualFs:Dt,createVirtualHttp:Bn,createVirtualNet:Pn,createSqliteDatabase:zn,transpileTS:pt,transpileForBrowser:Sr,preloadNpmPackages:br,createVirtualPortTable:Fn,createVirtualWasi:wn,executeWasiModule:Vt,executeInVirtualRuntime:wr,clearReplSession(t){t?jt.delete(t):jt.clear()}}}function __workerMessageLoop(X){const D=X.__virtualRuntime,he=new Map;let ce=1;X.onmessage=async function(se){const te=se.data||{},{requestId:ne,type:ue,payload:ge={}}=te;if(ue==="clear-repl"){D&&typeof D.clearReplSession=="function"&&D.clearReplSession(te.replSessionId);return}if(ue==="stdin-reply"){const xe=he.get(te.stdinId);xe&&(he.delete(te.stdinId),xe(te.value));return}if(ue==="execute"){X.postMessage({requestId:ne,type:"started"});try{const xe=await D.executeInVirtualRuntime({...ge,_captureVfsDiff:!0,...ge.interactiveStdin?{onRequestStdin($e){const Ie=`${ne}_${ce++}`;return new Promise(O=>{he.set(Ie,O),X.postMessage({requestId:ne,type:"stdin-request",stdinId:Ie,prompt:$e})})}}:{},onStdout($e){X.postMessage({requestId:ne,type:"stdout",text:$e})},onStderr($e){X.postMessage({requestId:ne,type:"stderr",text:$e})},onTestResult($e){X.postMessage({requestId:ne,type:"test-result",testResult:$e})}});X.postMessage({requestId:ne,type:"complete",result:xe})}catch(xe){X.postMessage({requestId:ne,type:"error",error:{message:xe&&xe.message?xe.message:String(xe),stack:xe&&xe.stack}})}}}}function createWorkerRuntimeSource(){return`'use strict';
120
120
  self.__virtualRuntime = (${__initVirtualRuntime.toString()})(self);
121
121
  (${__workerMessageLoop.toString()})(self);
122
- `}const _hostScope=typeof globalThis<"u"?globalThis:typeof window<"u"?window:global,_hostLogger=_hostScope&&_hostScope.CodeLabLogger&&typeof _hostScope.CodeLabLogger.createLogger=="function"?_hostScope.CodeLabLogger.createLogger():{debug(){},info(){},warn(X,j){typeof console<"u"&&console.warn&&console.warn("[CodeLab]",X,j||"")},error(X,j){typeof console<"u"&&console.error&&console.error("[CodeLab]",X,j||"")}},_hostRuntime=__initVirtualRuntime(_hostScope);_hostRuntime.createWorkerRuntimeSource=createWorkerRuntimeSource;let _cachedWorkerUrl=null,_warmWorker=null,_warmWorkerBusy=!1;const _activeWorkerJobs=new Map;function _ensureWorkerUrl(){if(!_cachedWorkerUrl){const X=new Blob([createWorkerRuntimeSource()],{type:"application/javascript"});_cachedWorkerUrl=URL.createObjectURL(X)}return _cachedWorkerUrl}function _ensureWarmWorker(){return _warmWorker&&typeof Worker=="function"&&_warmWorker instanceof Worker||(_warmWorker&&_destroyWarmWorker(),_warmWorker=new Worker(_ensureWorkerUrl()),_warmWorker&&typeof _warmWorker.unref=="function"&&_warmWorker.unref()),_warmWorker}function _destroyWarmWorker(){if(_warmWorker){try{_warmWorker.terminate()}catch(X){_hostLogger.debug("warmWorker.terminate failed",X)}_warmWorker=null}_warmWorkerBusy=!1}_hostRuntime.destroyWorkerPool=function(){if(_destroyWarmWorker(),_cachedWorkerUrl&&typeof URL<"u"&&typeof URL.revokeObjectURL=="function")try{URL.revokeObjectURL(_cachedWorkerUrl)}catch(j){_hostLogger.debug("revokeObjectURL failed",j)}_cachedWorkerUrl=null},_hostRuntime.cancelWorkerExecution=function(j="Execution cancelled",de){let ce=!1;for(const[ne,Q]of Array.from(_activeWorkerJobs.entries()))(!de||Q.instanceId===de)&&(_activeWorkerJobs.delete(ne),Q.cancel(j),ce=!0);return ce};function _extractWorkerFilesFromVfs(X){const j={};if(!X||typeof X!="object")return j;try{if(typeof X._exportRawState=="function"){const de=X._exportRawState();for(const[ce,ne]of de.files.entries())j[ce]=ne;return j}if(X.files instanceof Map){for(const[de,ce]of X.files.entries()){if(!ce)continue;const ne=ce.data!==void 0?ce.data:ce;typeof ne=="string"?j[de]=ne:ne instanceof Uint8Array?j[de]=ne.slice():ArrayBuffer.isView(ne)&&(j[de]=new Uint8Array(ne.buffer,ne.byteOffset,ne.byteLength).slice())}return j}if(typeof X.readdirSync=="function"&&typeof X.readFileSync=="function"){const de=ce=>{let ne=[];try{ne=X.readdirSync(ce)}catch{return}for(const Q of ne){const ee=ce==="/"?"/"+Q:ce+"/"+Q;let le=!1;try{le=X.statSync(ee).isDirectory()}catch{le=!1}if(le)de(ee);else try{const ye=X.readFileSync(ee);j[ee]=ye instanceof Uint8Array?ye.slice():typeof ye=="string"?ye:String(ye??"")}catch(ye){_hostLogger.debug("_extractWorkerFilesFromVfs: skip unreadable entry",ee,ye)}}};de("/workspace"),de("/tmp"),de("/home")}}catch(de){_hostLogger.debug("_extractWorkerFilesFromVfs failed",de)}return j}function _applyWorkerVfsChanges(X,j){if(!X||!j||typeof j!="object")return;const{createdDirs:de=[],modifiedFiles:ce={},deletedFiles:ne=[]}=j;try{if(Array.isArray(de)&&typeof X.mkdirSync=="function")for(const Q of de)try{X.mkdirSync(Q,{recursive:!0})}catch(ee){_hostLogger.debug("_applyWorkerVfsChanges: mkdirSync failed",Q,ee)}if(ce&&typeof ce=="object")for(const[Q,ee]of Object.entries(ce)){const le=Q.lastIndexOf("/");if(le>0&&typeof X.mkdirSync=="function")try{X.mkdirSync(Q.slice(0,le),{recursive:!0})}catch(Se){_hostLogger.debug("_applyWorkerVfsChanges: parent mkdirSync failed",Q,Se)}const ye=ee instanceof Uint8Array?ee:ArrayBuffer.isView(ee)?new Uint8Array(ee.buffer,ee.byteOffset,ee.byteLength):ee;typeof X.writeFileSync=="function"?X.writeFileSync(Q,ye):typeof X.writeFile=="function"&&X.writeFile(Q,ye)}if(Array.isArray(ne))for(const Q of ne)try{typeof X.unlinkSync=="function"?X.unlinkSync(Q):typeof X.rmSync=="function"&&X.rmSync(Q,{force:!0})}catch(ee){_hostLogger.debug("_applyWorkerVfsChanges: delete failed",Q,ee)}}catch(Q){_hostLogger.debug("_applyWorkerVfsChanges failed",Q)}}_hostRuntime.executeInWorker=async function(j={}){if(!!j.wasmBinary||!!j.cppCompiler||!!j.pythonCompiler||!!j.activePortTable||!!j.portTable||typeof j.entry=="string"&&/\.(cpp|cc|cxx|wasm|py)$/i.test(j.entry)||typeof Worker>"u"||typeof Blob>"u"||typeof URL>"u"||!URL.createObjectURL)return _hostRuntime.executeInVirtualRuntime(j);const ce="req_"+Date.now()+"_"+Math.random().toString(36).slice(2,8),ne=j.instanceId||(j.concurrent?ce:"default");j.concurrent||_hostRuntime.cancelWorkerExecution("Execution cancelled by new run",ne);const Q=j.vfs?Object.assign(_extractWorkerFilesFromVfs(j.vfs),j.files||{}):j.files;return new Promise(ee=>{let le,ye=!1;try{_warmWorkerBusy?(le=new Worker(_ensureWorkerUrl()),ye=!1):(le=_ensureWarmWorker(),_warmWorkerBusy=!0,ye=!0),le&&typeof le.ref=="function"&&le.ref()}catch{ye&&(_warmWorkerBusy=!1),ee(_hostRuntime.executeInVirtualRuntime(j));return}const Se=typeof performance<"u"?performance.now():Date.now(),Ne=j.timeoutMs||15e3;let ke=!1,P=!1,tt=null;const Ve=[],nt=[],Oe=[],Ie=()=>{const he=Oe.filter(te=>!te.passed).length;return{total:Oe.length,passed:Oe.length-he,failed:he}};function rt(he){if(j.signal&&tt){try{j.signal.removeEventListener("abort",tt)}catch(te){_hostLogger.debug("executeInWorker removeEventListener failed",te)}tt=null}if(_activeWorkerJobs.delete(ce),ye)he?_destroyWarmWorker():(_warmWorkerBusy=!1,_warmWorker&&(_warmWorker.onmessage=null,_warmWorker.onerror=null,typeof _warmWorker.unref=="function"&&_warmWorker.unref()));else try{le.terminate()}catch(te){_hostLogger.debug("worker.terminate failed",te)}}let je=null;const st=()=>{je&&clearTimeout(je),je=setTimeout(()=>{if(ke)return;ke=!0,rt(!0);const he=`Execution timed out after ${Ne}ms (infinite loop or hung timer terminated).
123
- `;ee({ok:!1,timedOut:!0,exitCode:124,durationMs:Ne,stdout:Ve.join(""),stderr:nt.join("")+he,testResults:Oe.slice(),testSummary:Ie(),fsSnapshot:[],httpTrace:[],error:{message:`Execution timed out after ${Ne}ms`}})},Ne+500)};if(st(),_activeWorkerJobs.set(ce,{requestId:ce,instanceId:ne,cancel(he="Execution cancelled by new run"){if(ke)return;ke=!0,clearTimeout(je),rt(!0);const te=Math.max(0,(typeof performance<"u"?performance.now():Date.now())-Se);ee({ok:!1,cancelled:!0,exitCode:130,durationMs:te,stdout:Ve.join(""),stderr:nt.join("")+`${he}
124
- `,testResults:Oe.slice(),testSummary:Ie(),fsSnapshot:[],httpTrace:[],error:{message:he}})}}),j.signal)if(j.signal.aborted){const he=_activeWorkerJobs.get(ce);he&&he.cancel("SIGINT: Interrupted by user (Ctrl+C)")}else tt=()=>{const he=_activeWorkerJobs.get(ce);he&&he.cancel("SIGINT: Interrupted by user (Ctrl+C)")},j.signal.addEventListener("abort",tt,{once:!0});le.onmessage=he=>{const te=he.data||{};if(te.requestId===ce){if(te.type==="started")P=!0;else if(te.type==="stdout")P=!0,typeof te.text=="string"&&Ve.push(te.text),typeof j.onStdout=="function"&&j.onStdout(te.text);else if(te.type==="stderr")P=!0,typeof te.text=="string"&&nt.push(te.text),typeof j.onStderr=="function"&&j.onStderr(te.text);else if(te.type==="stdin-request")P=!0,je&&(clearTimeout(je),je=null),typeof j.onRequestStdin=="function"?Promise.resolve(j.onRequestStdin(te.prompt||"")).then(Fe=>{ke||(st(),le.postMessage({requestId:ce,type:"stdin-reply",stdinId:te.stdinId,value:Fe}))}).catch(()=>{ke||(st(),le.postMessage({requestId:ce,type:"stdin-reply",stdinId:te.stdinId,value:null}))}):(st(),le.postMessage({requestId:ce,type:"stdin-reply",stdinId:te.stdinId,value:null}));else if(te.type==="test-result")P=!0,te.testResult&&Oe.push(te.testResult),typeof j.onTestResult=="function"&&j.onTestResult(te.testResult);else if(te.type==="complete"){if(ke)return;ke=!0,clearTimeout(je),j.vfs&&te.result&&te.result.vfsChanges&&_applyWorkerVfsChanges(j.vfs,te.result.vfsChanges),rt(!1),ee(te.result)}else if(te.type==="error"){if(ke)return;ke=!0,clearTimeout(je),rt(!1);const Fe=Math.max(0,(typeof performance<"u"?performance.now():Date.now())-Se),fn=(te.error?.stack||te.error?.message||"Worker execution error")+`
125
- `;ee({ok:!1,exitCode:1,durationMs:Fe,stdout:Ve.join(""),stderr:nt.join("")+fn,testResults:Oe.slice(),testSummary:Ie(),fsSnapshot:[],httpTrace:[],error:{message:te.error?.message||"Worker execution error",stack:te.error?.stack}})}}},le.onerror=he=>{if(ke)return;if(ke=!0,clearTimeout(je),rt(!0),!P&&j.allowMainThreadFallback!==!1){ee(_hostRuntime.executeInVirtualRuntime(j));return}const te=Math.max(0,(typeof performance<"u"?performance.now():Date.now())-Se),Fe=he&&he.message?String(he.message):"Uncaught fatal error in Web Worker execution";ee({ok:!1,exitCode:1,durationMs:te,stdout:Ve.join(""),stderr:nt.join("")+Fe+`
126
- `,testResults:Oe.slice(),testSummary:Ie(),fsSnapshot:[],httpTrace:[],error:{message:Fe}})},le.postMessage({requestId:ce,type:"execute",payload:{files:Q,entry:j.entry,mode:j.mode,replCode:j.replCode,replSessionId:j.replSessionId,interactiveStdin:typeof j.onRequestStdin=="function",testFilter:j.testFilter,timeoutMs:j.timeoutMs,maxOutputBytes:j.maxOutputBytes,maxConsoleCalls:j.maxConsoleCalls,packages:j.packages,npmModules:j.npmModules,argv:j.argv,pid:j.pid,isBackground:j.isBackground,printReplResult:j.printReplResult,stdin:j.stdin,wasmBinary:j.wasmBinary,env:j.env,cwd:j.cwd}})})},typeof window<"u"&&(window.VirtualNodeRuntime=_hostRuntime,window.CodeLabRuntime=_hostRuntime),typeof globalThis<"u"&&(globalThis.CodeLabRuntime=_hostRuntime),typeof module<"u"&&module.exports&&(module.exports=_hostRuntime);
122
+ `}const _hostScope=typeof globalThis<"u"?globalThis:typeof window<"u"?window:global,_hostLogger=_hostScope&&_hostScope.CodeLabLogger&&typeof _hostScope.CodeLabLogger.createLogger=="function"?_hostScope.CodeLabLogger.createLogger():{debug(){},info(){},warn(X,D){typeof console<"u"&&console.warn&&console.warn("[CodeLab]",X,D||"")},error(X,D){typeof console<"u"&&console.error&&console.error("[CodeLab]",X,D||"")}},_hostRuntime=__initVirtualRuntime(_hostScope);_hostRuntime.createWorkerRuntimeSource=createWorkerRuntimeSource;let _cachedWorkerUrl=null,_warmWorker=null,_warmWorkerBusy=!1;const _activeWorkerJobs=new Map;function _ensureWorkerUrl(){if(!_cachedWorkerUrl){const X=new Blob([createWorkerRuntimeSource()],{type:"application/javascript"});_cachedWorkerUrl=URL.createObjectURL(X)}return _cachedWorkerUrl}function _ensureWarmWorker(){return _warmWorker&&typeof Worker=="function"&&_warmWorker instanceof Worker||(_warmWorker&&_destroyWarmWorker(),_warmWorker=new Worker(_ensureWorkerUrl()),_warmWorker&&typeof _warmWorker.unref=="function"&&_warmWorker.unref()),_warmWorker}function _destroyWarmWorker(){if(_warmWorker){try{_warmWorker.terminate()}catch(X){_hostLogger.debug("warmWorker.terminate failed",X)}_warmWorker=null}_warmWorkerBusy=!1}_hostRuntime.destroyWorkerPool=function(){if(_destroyWarmWorker(),_cachedWorkerUrl&&typeof URL<"u"&&typeof URL.revokeObjectURL=="function")try{URL.revokeObjectURL(_cachedWorkerUrl)}catch(D){_hostLogger.debug("revokeObjectURL failed",D)}_cachedWorkerUrl=null},_hostRuntime.cancelWorkerExecution=function(D="Execution cancelled",he){let ce=!1;for(const[se,te]of Array.from(_activeWorkerJobs.entries()))(!he||te.instanceId===he)&&(_activeWorkerJobs.delete(se),te.cancel(D),ce=!0);return ce};function _extractWorkerFilesFromVfs(X){const D={};if(!X||typeof X!="object")return D;try{if(typeof X._exportRawState=="function"){const he=X._exportRawState();for(const[ce,se]of he.files.entries())D[ce]=se;return D}if(X.files instanceof Map){for(const[he,ce]of X.files.entries()){if(!ce)continue;const se=ce.data!==void 0?ce.data:ce;typeof se=="string"?D[he]=se:se instanceof Uint8Array?D[he]=se.slice():ArrayBuffer.isView(se)&&(D[he]=new Uint8Array(se.buffer,se.byteOffset,se.byteLength).slice())}return D}if(typeof X.readdirSync=="function"&&typeof X.readFileSync=="function"){const he=ce=>{let se=[];try{se=X.readdirSync(ce)}catch{return}for(const te of se){const ne=ce==="/"?"/"+te:ce+"/"+te;let ue=!1;try{ue=X.statSync(ne).isDirectory()}catch{ue=!1}if(ue)he(ne);else try{const ge=X.readFileSync(ne);D[ne]=ge instanceof Uint8Array?ge.slice():typeof ge=="string"?ge:String(ge??"")}catch(ge){_hostLogger.debug("_extractWorkerFilesFromVfs: skip unreadable entry",ne,ge)}}};he("/workspace"),he("/tmp"),he("/home")}}catch(he){_hostLogger.debug("_extractWorkerFilesFromVfs failed",he)}return D}function _applyWorkerVfsChanges(X,D){if(!X||!D||typeof D!="object")return;const{createdDirs:he=[],modifiedFiles:ce={},deletedFiles:se=[]}=D;try{if(Array.isArray(he)&&typeof X.mkdirSync=="function")for(const te of he)try{X.mkdirSync(te,{recursive:!0})}catch(ne){_hostLogger.debug("_applyWorkerVfsChanges: mkdirSync failed",te,ne)}if(ce&&typeof ce=="object")for(const[te,ne]of Object.entries(ce)){const ue=te.lastIndexOf("/");if(ue>0&&typeof X.mkdirSync=="function")try{X.mkdirSync(te.slice(0,ue),{recursive:!0})}catch(xe){_hostLogger.debug("_applyWorkerVfsChanges: parent mkdirSync failed",te,xe)}const ge=ne instanceof Uint8Array?ne:ArrayBuffer.isView(ne)?new Uint8Array(ne.buffer,ne.byteOffset,ne.byteLength):ne;typeof X.writeFileSync=="function"?X.writeFileSync(te,ge):typeof X.writeFile=="function"&&X.writeFile(te,ge)}if(Array.isArray(se))for(const te of se)try{typeof X.unlinkSync=="function"?X.unlinkSync(te):typeof X.rmSync=="function"&&X.rmSync(te,{force:!0})}catch(ne){_hostLogger.debug("_applyWorkerVfsChanges: delete failed",te,ne)}}catch(te){_hostLogger.debug("_applyWorkerVfsChanges failed",te)}}_hostRuntime.executeInWorker=async function(D={}){if(!!D.wasmBinary||!!D.cppCompiler||!!D.pythonCompiler||!!D.activePortTable||!!D.portTable||typeof D.entry=="string"&&/\.(cpp|cc|cxx|wasm|py)$/i.test(D.entry)||typeof Worker>"u"||typeof Blob>"u"||typeof URL>"u"||!URL.createObjectURL)return _hostRuntime.executeInVirtualRuntime(D);const ce="req_"+Date.now()+"_"+Math.random().toString(36).slice(2,8),se=D.instanceId||(D.concurrent?ce:"default");D.concurrent||_hostRuntime.cancelWorkerExecution("Execution cancelled by new run",se);const te=D.vfs?Object.assign(_extractWorkerFilesFromVfs(D.vfs),D.files||{}):D.files;return new Promise(ne=>{let ue,ge=!1;try{_warmWorkerBusy?(ue=new Worker(_ensureWorkerUrl()),ge=!1):(ue=_ensureWarmWorker(),_warmWorkerBusy=!0,ge=!0),ue&&typeof ue.ref=="function"&&ue.ref()}catch{ge&&(_warmWorkerBusy=!1),ne(_hostRuntime.executeInVirtualRuntime(D));return}const xe=typeof performance<"u"?performance.now():Date.now(),$e=D.timeoutMs||15e3;let Ie=!1,O=!1,tt=null;const Ve=[],nt=[],We=[],ke=()=>{const pe=We.filter(re=>!re.passed).length;return{total:We.length,passed:We.length-pe,failed:pe}};function rt(pe){if(D.signal&&tt){try{D.signal.removeEventListener("abort",tt)}catch(re){_hostLogger.debug("executeInWorker removeEventListener failed",re)}tt=null}if(_activeWorkerJobs.delete(ce),ge)pe?_destroyWarmWorker():(_warmWorkerBusy=!1,_warmWorker&&(_warmWorker.onmessage=null,_warmWorker.onerror=null,typeof _warmWorker.unref=="function"&&_warmWorker.unref()));else try{ue.terminate()}catch(re){_hostLogger.debug("worker.terminate failed",re)}}let Pe=null;const st=()=>{Pe&&clearTimeout(Pe),Pe=setTimeout(()=>{if(Ie)return;Ie=!0,rt(!0);const pe=`Execution timed out after ${$e}ms (infinite loop or hung timer terminated).
123
+ `;ne({ok:!1,timedOut:!0,exitCode:124,durationMs:$e,stdout:Ve.join(""),stderr:nt.join("")+pe,testResults:We.slice(),testSummary:ke(),fsSnapshot:[],httpTrace:[],error:{message:`Execution timed out after ${$e}ms`}})},$e+500)};if(st(),_activeWorkerJobs.set(ce,{requestId:ce,instanceId:se,cancel(pe="Execution cancelled by new run"){if(Ie)return;Ie=!0,clearTimeout(Pe),rt(!0);const re=Math.max(0,(typeof performance<"u"?performance.now():Date.now())-xe);ne({ok:!1,cancelled:!0,exitCode:130,durationMs:re,stdout:Ve.join(""),stderr:nt.join("")+`${pe}
124
+ `,testResults:We.slice(),testSummary:ke(),fsSnapshot:[],httpTrace:[],error:{message:pe}})}}),D.signal)if(D.signal.aborted){const pe=_activeWorkerJobs.get(ce);pe&&pe.cancel("SIGINT: Interrupted by user (Ctrl+C)");return}else tt=()=>{const pe=_activeWorkerJobs.get(ce);pe&&pe.cancel("SIGINT: Interrupted by user (Ctrl+C)")},D.signal.addEventListener("abort",tt,{once:!0});ue.onmessage=pe=>{const re=pe.data||{};if(re.requestId===ce){if(re.type==="started")O=!0;else if(re.type==="stdout")O=!0,typeof re.text=="string"&&Ve.push(re.text),typeof D.onStdout=="function"&&D.onStdout(re.text);else if(re.type==="stderr")O=!0,typeof re.text=="string"&&nt.push(re.text),typeof D.onStderr=="function"&&D.onStderr(re.text);else if(re.type==="stdin-request")O=!0,Pe&&(clearTimeout(Pe),Pe=null),typeof D.onRequestStdin=="function"?Promise.resolve(D.onRequestStdin(re.prompt||"")).then(je=>{Ie||(st(),ue.postMessage({requestId:ce,type:"stdin-reply",stdinId:re.stdinId,value:je}))}).catch(()=>{Ie||(st(),ue.postMessage({requestId:ce,type:"stdin-reply",stdinId:re.stdinId,value:null}))}):(st(),ue.postMessage({requestId:ce,type:"stdin-reply",stdinId:re.stdinId,value:null}));else if(re.type==="test-result")O=!0,re.testResult&&We.push(re.testResult),typeof D.onTestResult=="function"&&D.onTestResult(re.testResult);else if(re.type==="complete"){if(Ie)return;Ie=!0,clearTimeout(Pe),D.vfs&&re.result&&re.result.vfsChanges&&_applyWorkerVfsChanges(D.vfs,re.result.vfsChanges),rt(!1),ne(re.result)}else if(re.type==="error"){if(Ie)return;Ie=!0,clearTimeout(Pe),rt(!1);const je=Math.max(0,(typeof performance<"u"?performance.now():Date.now())-xe),fn=(re.error?.stack||re.error?.message||"Worker execution error")+`
125
+ `;ne({ok:!1,exitCode:1,durationMs:je,stdout:Ve.join(""),stderr:nt.join("")+fn,testResults:We.slice(),testSummary:ke(),fsSnapshot:[],httpTrace:[],error:{message:re.error?.message||"Worker execution error",stack:re.error?.stack}})}}},ue.onerror=pe=>{if(Ie)return;if(Ie=!0,clearTimeout(Pe),rt(!0),!O&&D.allowMainThreadFallback!==!1){ne(_hostRuntime.executeInVirtualRuntime(D));return}const re=Math.max(0,(typeof performance<"u"?performance.now():Date.now())-xe),je=pe&&pe.message?String(pe.message):"Uncaught fatal error in Web Worker execution";ne({ok:!1,exitCode:1,durationMs:re,stdout:Ve.join(""),stderr:nt.join("")+je+`
126
+ `,testResults:We.slice(),testSummary:ke(),fsSnapshot:[],httpTrace:[],error:{message:je}})},ue.postMessage({requestId:ce,type:"execute",payload:{files:te,entry:D.entry,mode:D.mode,replCode:D.replCode,replSessionId:D.replSessionId,interactiveStdin:typeof D.onRequestStdin=="function",testFilter:D.testFilter,timeoutMs:D.timeoutMs,maxOutputBytes:D.maxOutputBytes,maxConsoleCalls:D.maxConsoleCalls,packages:D.packages,npmModules:D.npmModules,argv:D.argv,pid:D.pid,isBackground:D.isBackground,printReplResult:D.printReplResult,stdin:D.stdin,wasmBinary:D.wasmBinary,env:D.env,cwd:D.cwd}})})},typeof window<"u"&&(window.VirtualNodeRuntime=_hostRuntime,window.CodeLabRuntime=_hostRuntime),typeof globalThis<"u"&&(globalThis.CodeLabRuntime=_hostRuntime),typeof module<"u"&&module.exports&&(module.exports=_hostRuntime);
127
127
 
128
128
  })();
129
129