@gjsify/example-node-express-webserver 0.64.17-next.292 → 0.64.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.gjs.js CHANGED
@@ -229,7 +229,7 @@ var n=ul()(`finalhandler`),r=Zd(),i=Qd(),o=Ql(),s=$d(),c=ml(),l=o.isFinished;fun
229
229
  * MIT Licensed
230
230
  */
231
231
  var n=ul()(`express:view`),r=(Rr(),__toCommonJS(Sr)),i=(yp(),__toCommonJS(gp)),o=r.dirname,s=r.basename,c=r.extname,l=r.join,u=r.resolve;t.exports=View;function View(e,t){var r=t||{};if(this.defaultEngine=r.defaultEngine,this.ext=c(e),this.name=e,this.root=r.root,!this.ext&&!this.defaultEngine)throw Error(`No default engine was specified and no extension was provided.`);var i=e;if(this.ext||(this.ext=this.defaultEngine[0]===`.`?this.defaultEngine:`.`+this.defaultEngine,i+=this.ext),!r.engines[this.ext]){var o=this.ext.slice(1);n(`require "%s"`,o);var s=y(o).__express;if(typeof s!=`function`)throw Error(`Module "`+o+`" does not provide a view engine.`);r.engines[this.ext]=s}this.engine=r.engines[this.ext],this.path=this.lookup(i)}View.prototype.lookup=function lookup(e){var t,r=[].concat(this.root);n(`lookup "%s"`,e);for(var i=0;i<r.length&&!t;i++){var c=r[i],l=u(c,e),d=o(l),p=s(l);t=this.resolve(d,p)}return t},View.prototype.render=function render(e,t){var r=!0;n(`render "%s"`,this.path),this.engine(this.path,e,function onRender(){if(!r)return t.apply(this,arguments);for(var e=Array(arguments.length),n=this,i=0;i<arguments.length;i++)e[i]=arguments[i];return process.nextTick(function renderTick(){return t.apply(n,e)})}),r=!1},View.prototype.resolve=function resolve(e,t){var n=this.ext,r=l(e,t),i=tryStat(r);if(i&&i.isFile()||(r=l(e,s(t,n),`index`+n),i=tryStat(r),i&&i.isFile()))return r};function tryStat(e){n(`stat "%s"`,e);try{return i.statSync(e)}catch{return}}}));function validateHeaderName(e){if(typeof e!=`string`||!/^[\^`\-\w!#$%&'*+.|~]+$/.test(e)){let t=TypeError(`Header name must be a valid HTTP token ["${e}"]`);throw Object.defineProperty(t,"code",{value:`ERR_INVALID_HTTP_TOKEN`}),t}}function validateHeaderValue(e,t){if(t===void 0){let t=TypeError(`Header "${e}" value must not be undefined`);throw Object.defineProperty(t,"code",{value:`ERR_HTTP_INVALID_HEADER_VALUE`}),t}if(typeof t==`string`&&/[^\t -~€-ÿ]/.test(t)){let t=TypeError(`Invalid character in header content ["${e}"]`);throw Object.defineProperty(t,"code",{value:`ERR_INVALID_CHAR`}),t}}var xp=__esmMin(()=>{}),Sp,Cp,wp=__esmMin(()=>{Sp={100:`Continue`,101:`Switching Protocols`,102:`Processing`,103:`Early Hints`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad Request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a Teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too Many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,500:`Internal Server Error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Service Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},Cp=`ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PRI.PROPFIND.PROPPATCH.PURGE.PUT.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE`.split(`.`)}),IncomingMessage,Tp=__esmMin(()=>{H(),Ma(),IncomingMessage=class extends Ea{httpVersion=`1.1`;httpVersionMajor=1;httpVersionMinor=1;headers={};rawHeaders=[];method;url;statusCode;statusMessage;complete=!1;socket=null;aborted=!1;get connection(){return this.socket}_timeoutTimer=null;constructor(){super()}_read(e){}_autoClose(){}_pushBody(e){e&&e.length>0&&this.push(V.from(e)),this.push(null),this.complete=!0,this._timeoutTimer&&=(clearTimeout(this._timeoutTimer),null)}setTimeout(e,t){return this._timeoutTimer&&=(clearTimeout(this._timeoutTimer),null),t&&this.once(`timeout`,t),e>0&&(this._timeoutTimer=setTimeout(()=>{this._timeoutTimer=null,this.emit(`timeout`)},e)),this}destroy(e){return this._timeoutTimer&&=(clearTimeout(this._timeoutTimer),null),this.aborted=!0,super.destroy(e)}}}),ServerRequestSocket,Ep=__esmMin(()=>{Ma(),ServerRequestSocket=class extends Oa{remoteAddress;remotePort;localAddress;localPort;remoteFamily=`IPv4`;encrypted;connecting=!1;pending=!1;bytesRead=0;bytesWritten=0;_bridgeRes;_bridgePaused=!1;constructor(e,t,n,r,i,o=!1){super({allowHalfOpen:!0}),this.remoteAddress=e,this.remotePort=t,this.localAddress=n,this.localPort=r,this.encrypted=o,this._bridgeRes=i}pause(){return this._bridgePaused?this:(this._bridgePaused=!0,super.pause())}resume(){return this._bridgePaused&&=!1,super.resume()}_read(e){}_write(e,t,n){n()}destroySoon(){this.writableEnded||this.end(),this.writableFinished?this.destroy():this.once(`finish`,()=>this.destroy())}setTimeout(e,t){return t&&this.once(`timeout`,t),this}setNoDelay(e){return this}setKeepAlive(e,t){return this}ref(){return this}unref(){return this}address(){return{address:this.localAddress,family:`IPv4`,port:this.localPort}}}});function unfqdn(e){return e.endsWith(`.`)?e.slice(0,-1):e}function splitHost(e){return unfqdn(e).toLowerCase().split(`.`)}function isPrintableAscii(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<33||n>126)return!1}return!0}function checkHostMatch(e,t){if(!t)return!1;let n=splitHost(t);if(e.length!==n.length||n.includes(``)||!n.every(isPrintableAscii))return!1;for(let t=e.length-1;t>0;t--)if(e[t]!==n[t])return!1;let r=e[0],i=n[0],o=i.split(`*`,3);if(o.length===1||i.includes(`xn--`))return r===i;if(o.length>2||n.length<=2)return!1;let s=o[0],c=o[1];return!(s.length+c.length>r.length||!r.startsWith(s)||!r.endsWith(c))}function checkServerIdentity(e,t){let n=t.subject,r=t.subjectaltname,i=[],o=[];if(e=String(e),r){let e=r.split(`, `);for(let t of e)t.startsWith(`DNS:`)?i.push(t.slice(4)):t.startsWith(`IP Address:`)&&o.push(t.slice(11).trim())}let s=!1,c=`Unknown reason`;e=unfqdn(e);let l=/^(\d{1,3}\.){3}\d{1,3}$/.test(e),u=e.includes(`:`);if(l||u)s=o.some(t=>t.toLowerCase()===e.toLowerCase()),s||(c=`IP: ${e} is not in the cert's list: ${o.join(`, `)}`);else if(i.length>0||n?.CN){let t=splitHost(e);if(i.length>0)s=i.some(e=>checkHostMatch(t,e.trim())),s||(c=`Host: ${e}. is not in the cert's altnames: ${r}`);else{let r=n?.CN;Array.isArray(r)?s=r.some(e=>checkHostMatch(t,e)):r&&(s=checkHostMatch(t,r)),s||(c=`Host: ${e}. is not cert's CN: ${r}`)}}else c=`Cert does not contain a DNS name`;if(!s){let n=Error(`Hostname/IP does not match certificate's altnames: ${c}`);return n.reason=c,n.host=e,n.cert=t,n.code=`ERR_TLS_CERT_ALTNAME_INVALID`,n}}var Dp=__esmMin(()=>{});function pemToString(e){return Array.isArray(e)?e.map(pemToString).join(`
232
- `):typeof e==`string`?e:e instanceof Uint8Array?new TextDecoder(`utf-8`).decode(e):String(e)}function splitPemBlocks(e){let t=[],n=/-----BEGIN [^-]+-----[\s\S]*?-----END [^-]+-----/g,r;for(;(r=n.exec(e))!==null;)t.push(r[0]);return t}function buildGioCertificate(e,t){let n=pemToString(e),r=t?pemToString(t):``,i=r?`${n}\n${r}`:n;return Y.TlsCertificate.new_from_pem(i,i.length)}function buildCaCertificates(e){let t=[];if(Array.isArray(e))for(let n of e)t.push(...splitPemBlocks(pemToString(n)));else t.push(...splitPemBlocks(pemToString(e)));let n=[];for(let e of t)try{n.push(Y.TlsCertificate.new_from_pem(e,e.length))}catch{}return n}function pemToDer(e){let t=/-----BEGIN CERTIFICATE-----([\s\S]*?)-----END CERTIFICATE-----/.exec(e);if(!t)return new Uint8Array;let n=t[1].replace(/[\s\r\n]+/g,``);try{let e=globalThis.atob;if(!e)return new Uint8Array;let t=e(n),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}catch{return new Uint8Array}}var Op=__esmMin(()=>{X()});function createSecureContext(e){let t=e??{},n=null;if(t.cert)try{n=buildGioCertificate(t.cert,t.key)}catch{n=null}let r=t.ca?buildCaCertificates(t.ca):[],i={certificate:n,caCertificates:r,options:t};return i.context=i,i}var kp=__esmMin(()=>{Op()}),Ap,jp=__esmMin(()=>{P(),Ap=loadOptionalNativeModule(`GjsifyTls`,[`Tls`,`SessionAccess`]),Ap.module}),Mp=__esmMin(()=>{jp()});function parseDistinguishedName(e){if(!e)return{};let t={};for(let n of e.split(/,(?![^=]*=)/)){let e=n.indexOf(`=`);if(e<0)continue;let r=n.slice(0,e).trim(),i=n.slice(e+1).trim(),o=t[r];o===void 0?t[r]=i:Array.isArray(o)?o.push(i):t[r]=[o,i]}return t}function formatCertDate(e){if(!e)return``;try{return e.format(`%b %d %H:%M:%S %Y GMT`)??``}catch{return``}}function formatAltNames(e){let t=[],n=e.get_dns_names();if(n)for(let e of n){let n=e.get_data();n&&t.push(`DNS:${new TextDecoder(`utf-8`).decode(n)}`)}let r=e.get_ip_addresses();if(r)for(let e of r)t.push(`IP Address:${e.to_string()}`);return t.join(`, `)}function fingerprintFromBytes(e,t){try{let n=new U.Checksum(t);n.update(e);let r=n.get_string();if(!r)return``;let i=[];for(let e=0;e<r.length;e+=2)i.push(r.slice(e,e+2).toUpperCase());return i.join(`:`)}catch{return``}}function tlsCertToPeerCert(e,t){let n={};try{n.subject=parseDistinguishedName(e.get_subject_name())}catch{}try{n.issuer=parseDistinguishedName(e.get_issuer_name())}catch{}n.subjectaltname=formatAltNames(e);try{n.valid_from=formatCertDate(e.get_not_valid_before()),n.valid_to=formatCertDate(e.get_not_valid_after())}catch{}try{let t=e,r=t.certificate_pem??t.certificatePem;if(r){let e=pemToDer(r);n.raw=e,n.fingerprint=fingerprintFromBytes(e,U.ChecksumType.SHA1),n.fingerprint256=fingerprintFromBytes(e,U.ChecksumType.SHA256)}}catch{}if(t)try{let t=e.get_issuer();t&&!t.is_same(e)?n.issuerCertificate=tlsCertToPeerCert(t,!0):t&&(n.issuerCertificate=n)}catch{}return n}var Np=__esmMin(()=>{Op(),W()});function resolveRejectUnauthorized(e){return e===void 0?U.getenv(`NODE_TLS_REJECT_UNAUTHORIZED`)!==`0`:e!==!1}function createPeerVerifier(e){let t=resolveRejectUnauthorized(e.rejectUnauthorized),n=e.checkServerIdentity??checkServerIdentity,r=e.caCertificates??[],i=null;return{accept(o){return i=chainError(o,r)??n(e.host,tlsCertToPeerCert(o,!0))??null,i===null||!t},get error(){return i},get authorized(){return i===null},get authorizationError(){if(i)return i.code??i.message}}}function chainFlags(e,t){if(t.length===0)return Y.TlsBackend.get_default().get_default_database().verify_chain(e,Y.TLS_DATABASE_PURPOSE_AUTHENTICATE_SERVER,null,null,Y.TlsDatabaseVerifyFlags.NONE,null);let n=Y.TlsCertificateFlags.UNKNOWN_CA;for(let r of t){let t=e.verify(null,r)&chainFlagsMask();if(t===Y.TlsCertificateFlags.NO_FLAGS)return t;t&Y.TlsCertificateFlags.UNKNOWN_CA||(n=t)}return n}function isSelfSigned(e){return e.get_subject_name()===e.get_issuer_name()}function verifyError(e,t){let n=Error(t);return n.code=e,n}function chainError(e,t=[]){let n=chainFlags(e,t)&chainFlagsMask(),r=Y.TlsCertificateFlags;if(n===r.NO_FLAGS)return null;if(n&r.UNKNOWN_CA){if(isSelfSigned(e))return verifyError(`DEPTH_ZERO_SELF_SIGNED_CERT`,`self-signed certificate`);let t=e;for(let e=t.get_issuer();e&&!e.is_same(t);e=t.get_issuer())t=e;return t===e?verifyError(`UNABLE_TO_VERIFY_LEAF_SIGNATURE`,`unable to verify the first certificate`):isSelfSigned(t)?verifyError(`SELF_SIGNED_CERT_IN_CHAIN`,`self-signed certificate in certificate chain`):verifyError(`UNABLE_TO_GET_ISSUER_CERT_LOCALLY`,`unable to get local issuer certificate`)}return n&r.REVOKED?verifyError(`CERT_REVOKED`,`certificate revoked`):n&r.EXPIRED?verifyError(`CERT_HAS_EXPIRED`,`certificate has expired`):n&r.NOT_ACTIVATED?verifyError(`CERT_NOT_YET_VALID`,`certificate is not yet valid`):n&r.INSECURE?verifyError(`CA_MD_TOO_WEAK`,`CA signature digest algorithm too weak`):verifyError(`CERT_REJECTED`,`certificate rejected`)}var chainFlagsMask,Pp=__esmMin(()=>{Dp(),Np(),kp(),X(),W(),chainFlagsMask=()=>Y.TlsCertificateFlags.VALIDATE_ALL&~Y.TlsCertificateFlags.BAD_IDENTITY});function isIP(e){if(typeof e!=`string`)return 0;let t=e.includes(`%`)?e.slice(0,e.indexOf(`%`)):e,n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(n)return n.slice(1).every(e=>(e.length===1||e[0]!==`0`)&&Number(e)<=255)?4:0;if(t.length===0||!t.includes(`:`))return 0;let r=/:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(t),i=r?t.slice(0,t.length-r[0].length):t;if(r&&isIP(r[1])!==4)return 0;let o=i.split(`::`);if(o.length>2)return 0;let s=0;for(let e of o)if(e!==``)for(let t of e.split(`:`)){if(!/^[0-9a-fA-F]{1,4}$/.test(t))return 0;s++}let c=r?6:8;return o.length===2?s<c?6:0:s===c?6:0}function isIPv4(e){return isIP(e)===4}function isIPv6(e){return isIP(e)===6}var Fp=__esmMin(()=>{});function destroyedError(){let e=Error(`Cannot call write after a stream was destroyed`);return e.code=`ERR_STREAM_DESTROYED`,e}var Socket,Ip=__esmMin(()=>{X(),W(),Ma(),H(),Bf(),Socket=class extends Oa{remoteAddress;remotePort;remoteFamily;localAddress;localPort;bytesRead=0;bytesWritten=0;connecting=!1;destroyed=!1;pending=!0;readyState=`closed`;_connection=null;_ioStream=null;_inputStream=null;_outputStream=null;_cancellable=new Y.Cancellable;_readCancellable=new Y.Cancellable;_reading=!1;_detaching=!1;_detachResolve=null;_pendingIo=0;_afterIo=null;_timeout=0;_timeoutId=null;constructor(e){super(e),this.allowHalfOpen=e?.allowHalfOpen??!1}_setConnection(e){this._connection=e}_setupFromIOStream(e){this._ioStream=e;try{let t=e;if(typeof t.get_socket==`function`){this._connection=t;let e=t.get_remote_address();this.remoteAddress=e.get_address().to_string(),this.remotePort=e.get_port(),this.remoteFamily=e.get_address().get_family()===Y.SocketFamily.IPV6?`IPv6`:`IPv4`;let n=t.get_local_address();this.localAddress=n.get_address().to_string(),this.localPort=n.get_port()}}catch{}this._inputStream=e.get_input_stream(),this._outputStream=e.get_output_stream(),this.connecting=!1,this.pending=!1,this.readyState=`open`,this.emit(`connect`),this.emit(`ready`),this._startReading()}_attachOutputOnly(e){this._ioStream=e;try{let t=e;if(typeof t.get_socket==`function`){this._connection=t;let e=t.get_remote_address();this.remoteAddress=e.get_address().to_string(),this.remotePort=e.get_port(),this.remoteFamily=e.get_address().get_family()===Y.SocketFamily.IPV6?`IPv6`:`IPv4`;let n=t.get_local_address();this.localAddress=n.get_address().to_string(),this.localPort=n.get_port()}}catch{}this._inputStream=e.get_input_stream(),this._outputStream=e.get_output_stream(),this.connecting=!1,this.pending=!1,this.readyState=`open`,this.emit(`connect`),this.emit(`ready`)}_releaseIOStream(){let e=this._ioStream;return this._ioStream=null,this._inputStream=null,this._outputStream=null,this._connection=null,e}_claimConnection(){let e={connection:this._connection,ioStream:this._ioStream,inputStream:this._inputStream,outputStream:this._outputStream};return this._connection=null,this._ioStream=null,this._inputStream=null,this._outputStream=null,e}connect(e,t,n){let r;typeof e==`number`?(r={port:e,host:typeof t==`string`?t:`localhost`},typeof t==`function`&&(n=t)):(r=e,typeof t==`function`&&(n=t)),n&&this.once(`connect`,n),this.connecting=!0,this.readyState=`opening`,this.pending=!0;let i=r.host||`localhost`,o=r.port,s=new Y.SocketClient;return r.timeout&&s.set_timeout(Math.ceil(r.timeout/1e3)),s.connect_to_host_async(i,o,this._cancellable,(e,t)=>{try{let e=s.connect_to_host_finish(t);if(this.destroyed){e.close(null);return}this._connection=e,this._setupConnection(r)}catch(e){this.connecting=!1,this.readyState=`closed`;let t=createNodeError$1(e,`connect`,{address:i,port:o});this.destroy(t)}}),this}_setupConnection(e,t=!0){if(!this._connection)return;let n=this._connection.get_socket();if(this._inputStream=this._connection.get_input_stream(),this._outputStream=this._connection.get_output_stream(),`keepAlive`in e&&e.keepAlive&&n.set_keepalive(!0),!(`noDelay`in e)||e.noDelay!==!1)try{n.set_option(6,1,1)}catch{}try{let e=this._connection.get_remote_address();this.remoteAddress=e.get_address().to_string(),this.remotePort=e.get_port(),this.remoteFamily=e.get_address().get_family()===Y.SocketFamily.IPV6?`IPv6`:`IPv4`}catch{}try{let e=this._connection.get_local_address();this.localAddress=e.get_address().to_string(),this.localPort=e.get_port()}catch{}this.connecting=!1,this.pending=!1,this.readyState=`open`,this.emit(`connect`),this.emit(`ready`),t&&this._startReading()}_startReading(){this._reading||!this._inputStream||(this._reading=!0,this._readLoop())}async _readLoop(){let e=this._inputStream;if(e)try{for(;this._reading&&e;){let t=await new Promise((t,n)=>{this._pendingIo++,e.read_bytes_async(16384,U.PRIORITY_DEFAULT,this._readCancellable,(r,i)=>{try{t(e.read_bytes_finish(i))}catch(e){n(e)}finally{this._ioSettled()}})});if(this._detaching){this._resolveDetach(t&&t.get_size()>0?V.from(gbytesToUint8Array(t)):null);return}if(!t||t.get_size()===0){this._reading=!1,this.allowHalfOpen?this.readyState=this.writable?`writeOnly`:`closed`:this.once(`end`,()=>{this.end(),this.readyState=`closed`}),this.push(null),this.read(0);break}let n=gbytesToUint8Array(t);if(this.bytesRead+=n.length,this._resetTimeout(),!this.push(V.from(n))){this._reading=!1;break}}}catch(e){if(this._detaching){this._resolveDetach(null);return}this._readCancellable.is_cancelled()||this.destroy(createNodeError$1(e,`read`,{address:this.remoteAddress}))}}_detachReader(){return this._reading?(this._detaching=!0,this._reading=!1,this._readCancellable.cancel(),new Promise(e=>{this._detachResolve=e})):Promise.resolve(null)}_resolveDetach(e){this._detaching=!1;let t=this._detachResolve;this._detachResolve=null,t&&t(e)}_read(e){!this._reading&&this._inputStream&&this._startReading()}_write(e,t,n){if(!this._outputStream){n(Error(`Socket is not connected`));return}let r=V.isBuffer(e)?e:typeof e==`string`?V.from(e,t):V.from(e),i=this._outputStream;this._pendingIo++,i.write_bytes_async(new U.Bytes(r),U.PRIORITY_DEFAULT,this._cancellable,(e,t)=>{let r=null;try{let e=i.write_bytes_finish(t);this.bytesWritten+=e,this._resetTimeout()}catch(e){r=this._cancellable.is_cancelled()?destroyedError():createNodeError$1(e,`write`,{address:this.remoteAddress})}this._ioSettled(),n(r)})}_final(e){if(this._connection)try{this._connection.get_socket().shutdown(!1,!0),this.readyState=this.readable?`readOnly`:`closed`}catch{}else if(this._ioStream){try{this._ioStream.close(null),this.readyState=`closed`}catch{}this._ioStream=null,this._inputStream=null,this._outputStream=null}e()}_destroy(e,t){this._reading=!1,this._clearTimeout(),this._cancellable.cancel(),this._readCancellable.cancel();let release=()=>this._release(e,t);this._pendingIo===0?release():this._afterIo=release}_ioSettled(){if(this._pendingIo--,this._pendingIo===0&&this._afterIo){let e=this._afterIo;this._afterIo=null,e()}}_release(e,t){if(this._connection){try{this._connection.close(null)}catch{}this._connection=null}else if(this._ioStream)try{this._ioStream.close(null)}catch{}this._ioStream=null,this._inputStream=null,this._outputStream=null,this.readyState=`closed`,this.destroyed=!0,t(e)}setTimeout(e,t){return this._timeout=e,this._clearTimeout(),t&&this.once(`timeout`,t),e>0&&this._resetTimeout(),this}_resetTimeout(){this._clearTimeout(),this._timeout>0&&(this._timeoutId=setTimeout(()=>{this.emit(`timeout`)},this._timeout))}_clearTimeout(){this._timeoutId!==null&&(clearTimeout(this._timeoutId),this._timeoutId=null)}_gioSocket(){let e=this._connection;for(;e instanceof Y.TlsConnection;)e=e.base_io_stream;return e instanceof Y.SocketConnection?e.get_socket():null}setKeepAlive(e,t){return this._gioSocket()?.set_keepalive(e??!1),this}setNoDelay(e){try{this._gioSocket()?.set_option(6,1,e===!1?0:1)}catch{}return this}destroySoon(){this.writable&&this.end(),this.writableFinished?this.destroy():this.once(`finish`,this.destroy.bind(this))}address(){return this.localAddress&&this.localPort?{port:this.localPort,family:this.remoteFamily||`IPv4`,address:this.localAddress}:{}}ref(){return this}unref(){return this}}}),Lp,Server$1,Rp=__esmMin(()=>{Ip(),X(),Bf(),$n(),P(),Lp=new Set,Server$1=class extends G{static{__name(this,`Server`)}listening=!1;maxConnections;allowHalfOpen;_service=null;_connections=new Set;_closingService=null;_address=null;constructor(e,t){super(),typeof e==`function`?(t=e,this.allowHalfOpen=!1):this.allowHalfOpen=e?.allowHalfOpen??!1,t&&this.on(`connection`,t)}listen(...e){let t=0,n=`0.0.0.0`,r=511,i;if(typeof e[0]==`object`&&e[0]!==null&&!Array.isArray(e[0])){let o=e[0];t=o.port??0,n=o.host??`0.0.0.0`,r=o.backlog??511,i=e[1]}else{typeof e[0]==`number`&&(t=e[0]);for(let t=1;t<e.length;t++)typeof e[t]==`string`?n=e[t]:typeof e[t]==`number`?r=e[t]:typeof e[t]==`function`&&(i=e[t])}i&&this.once(`listening`,i);try{releaseListenPort(t),this._service=new Y.SocketService,this._service.set_backlog(r);let e;t===0?e=this._service.add_any_inet_port(null):(this._service.add_inet_port(t,null),e=t),this._service.connect(`incoming`,(e,t)=>(this._handleConnection(t),!0)),this._service.start(),ensureMainLoop(),this.listening=!0,Lp.add(this);let i=n.includes(`:`)?`IPv6`:`IPv4`;this._address={port:e,family:i,address:n},deferEmit(this,`listening`)}catch(e){this._service=null;let r=createNodeError$1(e,`listen`,{address:n,port:t});deferEmit(this,`error`,r)}return this}_handleConnection(e){if(this.maxConnections&&this._connections.size>=this.maxConnections){try{e.close(null)}catch{}return}let t=new Socket({allowHalfOpen:this.allowHalfOpen});t._setConnection(e),t._setupConnection({},!1),this._connections.add(t),t.on(`close`,()=>{this._connections.delete(t),this._emitCloseIfDrained()}),this.emit(`connection`,t),t._startReading()}address(){return this._address}close(e){let t=this._service;return e&&this.once(`close`,t?e:()=>{let t=Error(`Server is not running.`);t.code=`ERR_SERVER_NOT_RUNNING`,e(t)}),t&&(this._service=null,this.listening=!1,this._closingService=t,closeSocketService(t,this._address?[this._address.port]:[],()=>{this._closingService===t&&(this._closingService=null),this._emitCloseIfDrained()})),this._emitCloseIfDrained(),this}_emitCloseIfDrained(){this._service||this._closingService||this._connections.size>0||(Lp.delete(this),nextTick(()=>this.emit(`close`)))}getConnections(e){e(null,this._connections.size)}ref(){return this}unref(){return this}}}),zp=__exportAll$5({Server:()=>Server$1,Socket:()=>Socket,connect:()=>Bp,createConnection:()=>createConnection,createServer:()=>createServer$1,default:()=>Vp,isIP:()=>isIP,isIPv4:()=>isIPv4,isIPv6:()=>isIPv6});function createConnection(e,t,n){return new Socket().connect(e,t,n)}function createServer$1(e,t){return typeof e==`function`?new Server$1(e):new Server$1(e,t)}var Bp,Vp,Hp=__esmMin(()=>{Fp(),Ip(),Rp(),Bp=createConnection,__name(createServer$1,`createServer`),Vp={Socket,Server:Server$1,isIP,isIPv4,isIPv6,createConnection,connect:Bp,createServer:createServer$1}}),Up=__esmMin(()=>{N(),Np(),kp(),Mp(),Pp(),X(),W(),Hp()}),Wp=__esmMin(()=>{Up()}),Gp=__esmMin(()=>{kp(),Up(),X(),W(),Hp()}),Kp=__esmMin(()=>{jp()}),qp=__esmMin(()=>{kp(),Mp(),Up(),Wp(),Gp(),Kp()});function resolveServerTls(e){let t=createSecureContext(e);if(e.cert&&!t.certificate)throw Error(`https.Server: cannot parse the key/cert pair as PEM`);if(!t.certificate)return null;let n=Y.TlsAuthenticationMode.NONE;return e.requestCert&&(n=e.rejectUnauthorized===!1?Y.TlsAuthenticationMode.REQUESTED:Y.TlsAuthenticationMode.REQUIRED),{certificate:t.certificate,authenticationMode:n,clientCa:e.requestCert?t.caCertificates:[]}}function createTrustDatabase(e){let[t,n]=Y.File.new_tmp(`gjsify-https-ca-XXXXXX.pem`);try{let r=e.map(e=>e.certificate_pem).join(`
232
+ `):typeof e==`string`?e:e instanceof Uint8Array?new TextDecoder(`utf-8`).decode(e):String(e)}function splitPemBlocks(e){let t=[],n=/-----BEGIN [^-]+-----[\s\S]*?-----END [^-]+-----/g,r;for(;(r=n.exec(e))!==null;)t.push(r[0]);return t}function buildGioCertificate(e,t){let n=pemToString(e),r=t?pemToString(t):``,i=r?`${n}\n${r}`:n;return Y.TlsCertificate.new_from_pem(i,i.length)}function buildCaCertificates(e){let t=[];if(Array.isArray(e))for(let n of e)t.push(...splitPemBlocks(pemToString(n)));else t.push(...splitPemBlocks(pemToString(e)));let n=[];for(let e of t)try{n.push(Y.TlsCertificate.new_from_pem(e,e.length))}catch{}return n}function pemToDer(e){let t=/-----BEGIN CERTIFICATE-----([\s\S]*?)-----END CERTIFICATE-----/.exec(e);if(!t)return new Uint8Array;let n=t[1].replace(/[\s\r\n]+/g,``);try{let e=globalThis.atob;if(!e)return new Uint8Array;let t=e(n),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}catch{return new Uint8Array}}var Op=__esmMin(()=>{X()});function createSecureContext(e){let t=e??{},n=null;if(t.cert)try{n=buildGioCertificate(t.cert,t.key)}catch{n=null}let r=t.ca?buildCaCertificates(t.ca):[],i={certificate:n,caCertificates:r,options:t};return i.context=i,i}var kp=__esmMin(()=>{Op()}),Ap,jp=__esmMin(()=>{P(),Ap=loadOptionalNativeModule(`GjsifyTls`,[`Tls`,`SessionAccess`]),Ap.module}),Mp=__esmMin(()=>{jp()});function parseDistinguishedName(e){if(!e)return{};let t={};for(let n of e.split(/,(?![^=]*=)/)){let e=n.indexOf(`=`);if(e<0)continue;let r=n.slice(0,e).trim(),i=n.slice(e+1).trim(),o=t[r];o===void 0?t[r]=i:Array.isArray(o)?o.push(i):t[r]=[o,i]}return t}function formatCertDate(e){if(!e)return``;try{return e.format(`%b %d %H:%M:%S %Y GMT`)??``}catch{return``}}function formatAltNames(e){let t=[],n=e.get_dns_names();if(n)for(let e of n){let n=e.get_data();n&&t.push(`DNS:${new TextDecoder(`utf-8`).decode(n)}`)}let r=e.get_ip_addresses();if(r)for(let e of r)t.push(`IP Address:${e.to_string()}`);return t.join(`, `)}function fingerprintFromBytes(e,t){try{let n=new U.Checksum(t);n.update(e);let r=n.get_string();if(!r)return``;let i=[];for(let e=0;e<r.length;e+=2)i.push(r.slice(e,e+2).toUpperCase());return i.join(`:`)}catch{return``}}function tlsCertToPeerCert(e,t){let n={};try{n.subject=parseDistinguishedName(e.get_subject_name())}catch{}try{n.issuer=parseDistinguishedName(e.get_issuer_name())}catch{}n.subjectaltname=formatAltNames(e);try{n.valid_from=formatCertDate(e.get_not_valid_before()),n.valid_to=formatCertDate(e.get_not_valid_after())}catch{}try{let t=e,r=t.certificate_pem??t.certificatePem;if(r){let e=pemToDer(r);n.raw=e,n.fingerprint=fingerprintFromBytes(e,U.ChecksumType.SHA1),n.fingerprint256=fingerprintFromBytes(e,U.ChecksumType.SHA256)}}catch{}if(t)try{let t=e.get_issuer();t&&!t.is_same(e)?n.issuerCertificate=tlsCertToPeerCert(t,!0):t&&(n.issuerCertificate=n)}catch{}return n}var Np=__esmMin(()=>{Op(),W()});function resolveRejectUnauthorized(e){return e===void 0?U.getenv(`NODE_TLS_REJECT_UNAUTHORIZED`)!==`0`:e!==!1}function createPeerVerifier(e){let t=resolveRejectUnauthorized(e.rejectUnauthorized),n=e.checkServerIdentity??checkServerIdentity,r=e.caCertificates??[],i=null;return{accept(o){return i=chainError(o,r)??n(e.host,tlsCertToPeerCert(o,!0))??null,i===null||!t},get error(){return i},get authorized(){return i===null},get authorizationError(){if(i)return i.code??i.message}}}function chainFlags(e,t){if(t.length===0)return Y.TlsBackend.get_default().get_default_database().verify_chain(e,Y.TLS_DATABASE_PURPOSE_AUTHENTICATE_SERVER,null,null,Y.TlsDatabaseVerifyFlags.NONE,null);let n=Y.TlsCertificateFlags.UNKNOWN_CA;for(let r of t){let t=e.verify(null,r)&chainFlagsMask();if(t===Y.TlsCertificateFlags.NO_FLAGS)return t;t&Y.TlsCertificateFlags.UNKNOWN_CA||(n=t)}return n}function isSelfSigned(e){return e.get_subject_name()===e.get_issuer_name()}function verifyError(e,t){let n=Error(t);return n.code=e,n}function chainError(e,t=[]){let n=chainFlags(e,t)&chainFlagsMask(),r=Y.TlsCertificateFlags;if(n===r.NO_FLAGS)return null;if(n&r.UNKNOWN_CA){if(isSelfSigned(e))return verifyError(`DEPTH_ZERO_SELF_SIGNED_CERT`,`self-signed certificate`);let t=e;for(let e=t.get_issuer();e&&!e.is_same(t);e=t.get_issuer())t=e;return t===e?verifyError(`UNABLE_TO_VERIFY_LEAF_SIGNATURE`,`unable to verify the first certificate`):isSelfSigned(t)?verifyError(`SELF_SIGNED_CERT_IN_CHAIN`,`self-signed certificate in certificate chain`):verifyError(`UNABLE_TO_GET_ISSUER_CERT_LOCALLY`,`unable to get local issuer certificate`)}return n&r.REVOKED?verifyError(`CERT_REVOKED`,`certificate revoked`):n&r.EXPIRED?verifyError(`CERT_HAS_EXPIRED`,`certificate has expired`):n&r.NOT_ACTIVATED?verifyError(`CERT_NOT_YET_VALID`,`certificate is not yet valid`):n&r.INSECURE?verifyError(`CA_MD_TOO_WEAK`,`CA signature digest algorithm too weak`):verifyError(`CERT_REJECTED`,`certificate rejected`)}var chainFlagsMask,Pp=__esmMin(()=>{Dp(),Np(),kp(),X(),W(),chainFlagsMask=()=>Y.TlsCertificateFlags.VALIDATE_ALL&~Y.TlsCertificateFlags.BAD_IDENTITY});function isIP(e){if(typeof e!=`string`)return 0;let t=e.includes(`%`)?e.slice(0,e.indexOf(`%`)):e,n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(n)return n.slice(1).every(e=>(e.length===1||e[0]!==`0`)&&Number(e)<=255)?4:0;if(t.length===0||!t.includes(`:`))return 0;let r=/:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(t),i=r?t.slice(0,t.length-r[0].length):t;if(r&&isIP(r[1])!==4)return 0;let o=i.split(`::`);if(o.length>2)return 0;let s=0;for(let e of o)if(e!==``)for(let t of e.split(`:`)){if(!/^[0-9a-fA-F]{1,4}$/.test(t))return 0;s++}let c=r?6:8;return o.length===2?s<c?6:0:s===c?6:0}function isIPv4(e){return isIP(e)===4}function isIPv6(e){return isIP(e)===6}var Fp=__esmMin(()=>{});function destroyedError(){let e=Error(`Cannot call write after a stream was destroyed`);return e.code=`ERR_STREAM_DESTROYED`,e}var Socket,Ip=__esmMin(()=>{X(),W(),Ma(),H(),Bf(),Socket=class extends Oa{remoteAddress;remotePort;remoteFamily;localAddress;localPort;bytesRead=0;bytesWritten=0;connecting=!1;destroyed=!1;pending=!0;readyState=`closed`;_connection=null;_ioStream=null;_inputStream=null;_outputStream=null;_cancellable=new Y.Cancellable;_readCancellable=new Y.Cancellable;_reading=!1;_detaching=!1;_detachResolve=null;_pendingIo=0;_afterIo=null;_timeout=0;_timeoutId=null;constructor(e){super(e),this.allowHalfOpen=e?.allowHalfOpen??!1}_setConnection(e){this._connection=e}_setupFromIOStream(e){this._ioStream=e;try{let t=e;if(typeof t.get_socket==`function`){this._connection=t;let e=t.get_remote_address();this.remoteAddress=e.get_address().to_string(),this.remotePort=e.get_port(),this.remoteFamily=e.get_address().get_family()===Y.SocketFamily.IPV6?`IPv6`:`IPv4`;let n=t.get_local_address();this.localAddress=n.get_address().to_string(),this.localPort=n.get_port()}}catch{}this._inputStream=e.get_input_stream(),this._outputStream=e.get_output_stream(),this.connecting=!1,this.pending=!1,this.readyState=`open`,this.emit(`connect`),this.emit(`ready`),this._startReading()}_attachOutputOnly(e){this._ioStream=e;try{let t=e;if(typeof t.get_socket==`function`){this._connection=t;let e=t.get_remote_address();this.remoteAddress=e.get_address().to_string(),this.remotePort=e.get_port(),this.remoteFamily=e.get_address().get_family()===Y.SocketFamily.IPV6?`IPv6`:`IPv4`;let n=t.get_local_address();this.localAddress=n.get_address().to_string(),this.localPort=n.get_port()}}catch{}this._inputStream=e.get_input_stream(),this._outputStream=e.get_output_stream(),this.connecting=!1,this.pending=!1,this.readyState=`open`,this.emit(`connect`),this.emit(`ready`)}_releaseIOStream(){let e=this._ioStream;return this._ioStream=null,this._inputStream=null,this._outputStream=null,this._connection=null,e}_claimConnection(){let e={connection:this._connection,ioStream:this._ioStream,inputStream:this._inputStream,outputStream:this._outputStream};return this._connection=null,this._ioStream=null,this._inputStream=null,this._outputStream=null,e}connect(e,t,n){let r;typeof e==`number`?(r={port:e,host:typeof t==`string`?t:`localhost`},typeof t==`function`&&(n=t)):(r=e,typeof t==`function`&&(n=t)),n&&this.once(`connect`,n),this.connecting=!0,this.readyState=`opening`,this.pending=!0;let i=r.host||`localhost`,o=r.port,s=new Y.SocketClient;return r.timeout&&s.set_timeout(Math.ceil(r.timeout/1e3)),s.connect_to_host_async(i,o,this._cancellable,(e,t)=>{try{let e=s.connect_to_host_finish(t);if(this.destroyed){e.close(null);return}this._connection=e,this._setupConnection(r)}catch(e){this.connecting=!1,this.readyState=`closed`;let t=createNodeError$1(e,`connect`,{address:i,port:o});this.destroy(t)}}),this}_setupConnection(e,t=!0){if(!this._connection)return;let n=this._connection.get_socket();if(this._inputStream=this._connection.get_input_stream(),this._outputStream=this._connection.get_output_stream(),`keepAlive`in e&&e.keepAlive&&n.set_keepalive(!0),!(`noDelay`in e)||e.noDelay!==!1)try{n.set_option(6,1,1)}catch{}try{let e=this._connection.get_remote_address();this.remoteAddress=e.get_address().to_string(),this.remotePort=e.get_port(),this.remoteFamily=e.get_address().get_family()===Y.SocketFamily.IPV6?`IPv6`:`IPv4`}catch{}try{let e=this._connection.get_local_address();this.localAddress=e.get_address().to_string(),this.localPort=e.get_port()}catch{}this.connecting=!1,this.pending=!1,this.readyState=`open`,this.emit(`connect`),this.emit(`ready`),t&&this._startReading()}_startReading(){this._reading||!this._inputStream||(this._reading=!0,this._readLoop())}async _readLoop(){let e=this._inputStream;if(e)try{for(;this._reading&&e;){let t=await new Promise((t,n)=>{this._pendingIo++,e.read_bytes_async(16384,U.PRIORITY_DEFAULT,this._readCancellable,(r,i)=>{try{t(e.read_bytes_finish(i))}catch(e){n(e)}finally{this._ioSettled()}})});if(this._detaching){this._resolveDetach(t&&t.get_size()>0?V.from(gbytesToUint8Array(t)):null);return}if(!t||t.get_size()===0){this._reading=!1,this.allowHalfOpen?this.readyState=this.writable?`writeOnly`:`closed`:this.once(`end`,()=>{this.end(),this.readyState=`closed`}),this.push(null),this.read(0);break}let n=gbytesToUint8Array(t);if(this.bytesRead+=n.length,this._resetTimeout(),!this.push(V.from(n))){this._reading=!1;break}}}catch(e){if(this._detaching){this._resolveDetach(null);return}this._readCancellable.is_cancelled()||this.destroy(createNodeError$1(e,`read`,{address:this.remoteAddress}))}}_detachReader(){return this._reading?(this._detaching=!0,this._reading=!1,this._readCancellable.cancel(),new Promise(e=>{this._detachResolve=e})):Promise.resolve(null)}_resolveDetach(e){this._detaching=!1;let t=this._detachResolve;this._detachResolve=null,t&&t(e)}_read(e){!this._reading&&this._inputStream&&this._startReading()}_write(e,t,n){if(!this._outputStream){n(Error(`Socket is not connected`));return}let r=V.isBuffer(e)?e:typeof e==`string`?V.from(e,t):V.from(e),i=this._outputStream;this._pendingIo++,i.write_bytes_async(new U.Bytes(r),U.PRIORITY_DEFAULT,this._cancellable,(e,t)=>{let r=null;try{let e=i.write_bytes_finish(t);this.bytesWritten+=e,this._resetTimeout()}catch(e){r=this._cancellable.is_cancelled()?destroyedError():createNodeError$1(e,`write`,{address:this.remoteAddress})}this._ioSettled(),n(r)})}_final(e){if(this._connection)try{this._connection.get_socket().shutdown(!1,!0),this.readyState=this.readable?`readOnly`:`closed`}catch{}else if(this._ioStream){try{this._ioStream.close(null),this.readyState=`closed`}catch{}this._ioStream=null,this._inputStream=null,this._outputStream=null}e()}_destroy(e,t){this._reading=!1,this._clearTimeout(),this._cancellable.cancel(),this._readCancellable.cancel();let release=()=>this._release(e,t);this._pendingIo===0?release():this._afterIo=release}_ioSettled(){if(this._pendingIo--,this._pendingIo===0&&this._afterIo){let e=this._afterIo;this._afterIo=null,e()}}_release(e,t){if(this._connection){try{this._connection.close(null)}catch{}this._connection=null}else if(this._ioStream)try{this._ioStream.close(null)}catch{}this._ioStream=null,this._inputStream=null,this._outputStream=null,this.readyState=`closed`,this.destroyed=!0,t(e)}setTimeout(e,t){return this._timeout=e,this._clearTimeout(),t&&this.once(`timeout`,t),e>0&&this._resetTimeout(),this}_resetTimeout(){this._clearTimeout(),this._timeout>0&&(this._timeoutId=setTimeout(()=>{this.emit(`timeout`)},this._timeout))}_clearTimeout(){this._timeoutId!==null&&(clearTimeout(this._timeoutId),this._timeoutId=null)}_gioSocket(){let e=this._connection;for(;e instanceof Y.TlsConnection;)e=e.base_io_stream;return e instanceof Y.SocketConnection?e.get_socket():null}setKeepAlive(e,t){return this._gioSocket()?.set_keepalive(e??!1),this}setNoDelay(e){try{this._gioSocket()?.set_option(6,1,e===!1?0:1)}catch{}return this}destroySoon(){this.writable&&this.end(),this.writableFinished?this.destroy():this.once(`finish`,this.destroy.bind(this))}address(){return this.localAddress&&this.localPort?{port:this.localPort,family:this.remoteFamily||`IPv4`,address:this.localAddress}:{}}ref(){return this}unref(){return this}}}),Lp,Server$1,Rp=__esmMin(()=>{Ip(),X(),Bf(),$n(),P(),Lp=new Set,Server$1=class extends G{static{__name(this,`Server`)}listening=!1;maxConnections;allowHalfOpen;_service=null;_connections=new Set;_closingService=null;_address=null;constructor(e,t){super(),typeof e==`function`?(t=e,this.allowHalfOpen=!1):this.allowHalfOpen=e?.allowHalfOpen??!1,t&&this.on(`connection`,t)}listen(...e){let t=0,n=`0.0.0.0`,r=!1,i=511,o;if(typeof e[0]==`object`&&e[0]!==null&&!Array.isArray(e[0])){let s=e[0];t=s.port??0,n=s.host??`0.0.0.0`,r=s.host!==void 0,i=s.backlog??511,o=e[1]}else{typeof e[0]==`number`&&(t=e[0]);for(let t=1;t<e.length;t++)typeof e[t]==`string`?(n=e[t],r=!0):typeof e[t]==`number`?i=e[t]:typeof e[t]==`function`&&(o=e[t])}o&&this.once(`listening`,o);try{releaseListenPort(t),this._service=new Y.SocketService,this._service.set_backlog(i);let e;if(r){let r=n===`localhost`?`127.0.0.1`:n,i=Y.InetSocketAddress.new_from_string(r,t);if(!i)throw createNodeError$1({code:Y.IOErrorEnum.INVALID_ARGUMENT,message:`invalid address ${n}`},`listen`,{address:n,port:t});let[,o]=this._service.add_address(i,Y.SocketType.STREAM,Y.SocketProtocol.DEFAULT,null);e=o.get_port()}else t===0?e=this._service.add_any_inet_port(null):(this._service.add_inet_port(t,null),e=t);this._service.connect(`incoming`,(e,t)=>(this._handleConnection(t),!0)),this._service.start(),ensureMainLoop(),this.listening=!0,Lp.add(this);let o=n.includes(`:`)?`IPv6`:`IPv4`;this._address={port:e,family:o,address:n},deferEmit(this,`listening`)}catch(e){this._service=null;let r=createNodeError$1(e,`listen`,{address:n,port:t});deferEmit(this,`error`,r)}return this}_handleConnection(e){if(this.maxConnections&&this._connections.size>=this.maxConnections){try{e.close(null)}catch{}return}let t=new Socket({allowHalfOpen:this.allowHalfOpen});t._setConnection(e),t._setupConnection({},!1),this._connections.add(t),t.on(`close`,()=>{this._connections.delete(t),this._emitCloseIfDrained()}),this.emit(`connection`,t),t._startReading()}address(){return this._address}close(e){let t=this._service;return e&&this.once(`close`,t?e:()=>{let t=Error(`Server is not running.`);t.code=`ERR_SERVER_NOT_RUNNING`,e(t)}),t&&(this._service=null,this.listening=!1,this._closingService=t,closeSocketService(t,this._address?[this._address.port]:[],()=>{this._closingService===t&&(this._closingService=null),this._emitCloseIfDrained()})),this._emitCloseIfDrained(),this}_emitCloseIfDrained(){this._service||this._closingService||this._connections.size>0||(Lp.delete(this),nextTick(()=>this.emit(`close`)))}getConnections(e){e(null,this._connections.size)}ref(){return this}unref(){return this}}}),zp=__exportAll$5({Server:()=>Server$1,Socket:()=>Socket,connect:()=>Bp,createConnection:()=>createConnection,createServer:()=>createServer$1,default:()=>Vp,isIP:()=>isIP,isIPv4:()=>isIPv4,isIPv6:()=>isIPv6});function createConnection(e,t,n){return new Socket().connect(e,t,n)}function createServer$1(e,t){return typeof e==`function`?new Server$1(e):new Server$1(e,t)}var Bp,Vp,Hp=__esmMin(()=>{Fp(),Ip(),Rp(),Bp=createConnection,__name(createServer$1,`createServer`),Vp={Socket,Server:Server$1,isIP,isIPv4,isIPv6,createConnection,connect:Bp,createServer:createServer$1}}),Up=__esmMin(()=>{N(),Np(),kp(),Mp(),Pp(),X(),W(),Hp()}),Wp=__esmMin(()=>{Up()}),Gp=__esmMin(()=>{kp(),Up(),X(),W(),Hp()}),Kp=__esmMin(()=>{jp()}),qp=__esmMin(()=>{kp(),Mp(),Up(),Wp(),Gp(),Kp()});function resolveServerTls(e){let t=createSecureContext(e);if(e.cert&&!t.certificate)throw Error(`https.Server: cannot parse the key/cert pair as PEM`);if(!t.certificate)return null;let n=Y.TlsAuthenticationMode.NONE;return e.requestCert&&(n=e.rejectUnauthorized===!1?Y.TlsAuthenticationMode.REQUESTED:Y.TlsAuthenticationMode.REQUIRED),{certificate:t.certificate,authenticationMode:n,clientCa:e.requestCert?t.caCertificates:[]}}function createTrustDatabase(e){let[t,n]=Y.File.new_tmp(`gjsify-https-ca-XXXXXX.pem`);try{let r=e.map(e=>e.certificate_pem).join(`
233
233
  `);return n.get_output_stream().write_all(new TextEncoder().encode(r),null),n.close(null),{database:Y.TlsFileDatabase.new(t.get_path()),file:t}}catch(e){throw removeFile(t),e}}function removeFile(e){try{e.delete(null)}catch{}}var Jp=__esmMin(()=>{X(),qp()}),Yp,Xp=__esmMin(()=>{Yp=u}),Zp,Qp=__esmMin(()=>{Xp(),Zp=Yp}),$p,em,tm=__esmMin(()=>{if(P(),$p=openNativeLibrary(`GjsifyHttpSoupBridge`),$p)throw $p;em=d.Server,d.Request,d.Response}),OutgoingMessage,ServerResponse,nm,Server,im=__esmMin(()=>{N(),Ep(),wp(),Tp(),Jp(),Qp(),X(),H(),$n(),Ma(),Ip(),tm(),P(),OutgoingMessage=class extends Da{headersSent=!1;sendDate=!0;finished=!1;socket=null;_headers=new Map;setHeader(e,t){return this._headers.set(e.toLowerCase(),typeof t==`number`?String(t):t),this}getHeader(e){return this._headers.get(e.toLowerCase())}removeHeader(e){this._headers.delete(e.toLowerCase())}hasHeader(e){return this._headers.has(e.toLowerCase())}getHeaderNames(){return Array.from(this._headers.keys())}getHeaders(){let e={};for(let[t,n]of this._headers)e[t]=n;return e}appendHeader(e,t){let n=e.toLowerCase(),r=this._headers.get(n);return r===void 0?this._headers.set(n,t):Array.isArray(r)?Array.isArray(t)?r.push(...t):r.push(t):Array.isArray(t)?this._headers.set(n,[r,...t]):this._headers.set(n,[r,t]),this}flushHeaders(){this.headersSent=!0}_write(e,t,n){n()}},ServerResponse=class extends OutgoingMessage{statusCode=200;statusMessage=``;_streaming=!1;_bridge;_timeoutTimer=null;constructor(e){super(),this._bridge=e,e.connect(`close`,()=>{this.emit(`close`)})}setTimeout(e,t){return this._timeoutTimer&&=(clearTimeout(this._timeoutTimer),null),t&&this.once(`timeout`,t),e>0&&(this._timeoutTimer=setTimeout(()=>{this._timeoutTimer=null,this.emit(`timeout`)},e)),this}writeHead(e,t,n){if(this.statusCode=e,typeof t==`object`&&(n=t,t=void 0),this.statusMessage=t||Sp[e]||``,n)for(let[e,t]of Object.entries(n))this.setHeader(e,t);return this}writeContinue(e){e&&Promise.resolve().then(e)}writeProcessing(e){e&&Promise.resolve().then(e)}flushHeaders(){this.headersSent||=!0}addTrailers(e){for(let[t,n]of Object.entries(e))this._headers.set(`trailer-`+t.toLowerCase(),n)}_startStreaming(){if(!this._streaming){this._streaming=!0,this.headersSent=!0,this._timeoutTimer&&=(clearTimeout(this._timeoutTimer),null);for(let[e,t]of this._headers)if(Array.isArray(t))for(let n of t)this._bridge.append_header(e,n);else this._bridge.set_header(e,t);this._bridge.write_head(this.statusCode,this.statusMessage||null)}}_write(e,t,n){let r=V.isBuffer(e)?e:typeof e==`string`?V.from(e,t):V.from(e);this._startStreaming(),r.byteLength>0&&this._bridge.write_chunk(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),n()}_final(e){if(!this._streaming){for(let[e,t]of this._headers)if(Array.isArray(t))for(let n of t)this._bridge.append_header(e,n);else this._bridge.set_header(e,t);this._bridge.write_head(this.statusCode,this.statusMessage||null)}this._bridge.end(),this.finished=!0,e()}end(e,t,n){return typeof e==`function`?(n=e,e=void 0):typeof t==`function`&&(n=t,t=void 0),e!=null&&this.write(e,t),super.end(n),this}},nm=new Set,Server=class extends G{listening=!1;maxHeadersCount=2e3;timeout=0;keepAliveTimeout=5e3;headersTimeout=6e4;requestTimeout=3e5;_bridge=null;_tls=null;_tlsRequested=!1;_trustFile=null;_address=null;get soupServer(){return this._bridge?.soup_server??null}constructor(e,t){super();let n=typeof e==`function`?e:t;n&&this.on(`request`,n)}_useTls(e){this._tlsRequested=!0,this._tls=resolveServerTls(e)}listen(...e){let t=0,n=`0.0.0.0`,r;for(let i of e)typeof i==`number`?t=i:typeof i==`string`?n=i:typeof i==`function`&&(r=i);if(this._tlsRequested&&!this._tls)return deferEmit(this,`error`,Error(`https.Server: no certificate — pass key and cert (PEM)`)),this;r&&this.once(`listening`,r);try{this._bridge=new em,this._bridge.connect(`request-received`,(e,t,n)=>{this._handleRequest(t,n)}),this._bridge.connect(`upgrade`,(e,t,n,r)=>{this._handleUpgrade(t,n)}),this._bridge.connect(`error-occurred`,(e,t)=>{this.emit(`error`,Error(t))});let e=this._tls?this._listenTls(this._bridge,t):this._listenPlain(this._bridge,t,n);ensureMainLoop(),this.listening=!0,this._address={port:e,family:`IPv4`,address:this._bridge.address||n},nm.add(this),deferEmit(this,`listening`)}catch(e){let r=createNodeError$1(e,`listen`,{address:n,port:t});deferEmit(this,`error`,r)}return this}_listenPlain(e,t,n){return e.listen(t,n),e.port}_listenTls(e,t){let n=this._tls,r=e.soup_server;if(r.tls_certificate=n.certificate,r.tls_auth_mode=n.authenticationMode,n.clientCa.length>0){let e=createTrustDatabase(n.clientCa);r.tls_database=e.database,this._trustFile&&removeFile(this._trustFile),this._trustFile=e.file}if(n.authenticationMode!==Y.TlsAuthenticationMode.NONE){let e=n.authenticationMode===Y.TlsAuthenticationMode.REQUIRED;r.connect(`request-started`,(t,n)=>{n.connect(`accept-certificate`,(t,n,r)=>!e||r===Y.TlsCertificateFlags.NO_FLAGS)})}try{r.listen_local(t,Zp.ServerListenOptions.IPV4_ONLY|Zp.ServerListenOptions.HTTPS)}catch(e){throw this._trustFile&&removeFile(this._trustFile),this._trustFile=null,e}return(r.get_listeners()[0]?.get_local_address())?.get_port()??t}_handleRequest(e,t){let n=new IncomingMessage,r=new ServerResponse(t);n.method=e.method,n.url=e.url,n.httpVersion=`1.1`;let i=e.header_pairs??[];for(let e=0;e+1<i.length;e+=2){let t=i[e],r=i[e+1],o=t.toLowerCase();if(n.rawHeaders.push(t,r),o in n.headers){let e=n.headers[o];Array.isArray(e)?e.push(r):n.headers[o]=[e,r]}else n.headers[o]=r}n.socket=new ServerRequestSocket(e.remote_address??`127.0.0.1`,e.remote_port??0,this._address?.address??`127.0.0.1`,this._address?.port??0,t,this._tls!==null);let o=e.get_body();o.length>0?n._pushBody(o):n._pushBody(null),e.connect(`aborted_signal`,()=>{n.aborted||(n.aborted=!0,n.emit(`aborted`))}),e.connect(`close`,()=>{n.emit(`close`)});try{let e=this.emit(`request`,n,r);(e instanceof Promise||typeof e==`object`&&e&&typeof e.then==`function`)&&e.catch(e=>{if(M.error(`[HTTP] Unhandled error in async request handler:`,e),!r.headersSent)try{r.writeHead(500),r.end(`Internal Server Error`)}catch{}})}catch(e){if(M.error(`[HTTP] Unhandled error in request handler:`,e),!r.headersSent)try{r.writeHead(500),r.end(`Internal Server Error`)}catch{}}}_handleUpgrade(e,t){let n=new IncomingMessage;n.method=e.method,n.url=e.url,n.httpVersion=`1.1`;let r=e.header_pairs??[];for(let e=0;e+1<r.length;e+=2){let t=r[e],i=r[e+1],o=t.toLowerCase();n.rawHeaders.push(t,i),n.headers[o]=i}if(this.listenerCount(`upgrade`)>0){let r=new Socket;r._attachOutputOnly(t),n.socket=r,r.remoteAddress??=e.remote_address||void 0,r.remotePort??=e.remote_port??void 0,r.remoteFamily??=r.remoteAddress?.includes(`:`)?`IPv6`:`IPv4`,r.localAddress??=this._address?.address,r.localPort??=this._address?.port,this.emit(`upgrade`,n,r,V.alloc(0))}}address(){return this._address}addWebSocketHandler(e,t){if(!this._bridge)throw Error(`Server must be listening before adding WebSocket handlers. Call listen() first.`);this._bridge.soup_server.add_websocket_handler(e,null,null,(e,n,r,i)=>{t(i)})}close(e){return e&&this.once(`close`,e),this._bridge&&=(this._tls?this._bridge.soup_server.disconnect():this._bridge.close(),null),this._trustFile&&=(removeFile(this._trustFile),null),this.listening=!1,nm.delete(this),deferEmit(this,`close`),this}setTimeout(e,t){return this.timeout=e,t&&this.on(`timeout`,t),this}}}),ClientRequest,am=__esmMin(()=>{Tp(),im(),W(),Qp(),X(),H(),Jr(),Bf(),Pp(),ClientRequest=class extends OutgoingMessage{method;path;protocol;host;hostname;port;aborted=!1;reusedSocket=!1;maxHeadersCount=2e3;_chunks=[];_session;_message;_cancellable;_timeout=0;_timeoutTimer=null;_responseCallback;_tlsRejection=null;constructor(e,t,n){super();let r;if(typeof e==`string`||e instanceof q){let i=typeof e==`string`?new q(e):e;r={protocol:i.protocol,hostname:i.hostname,port:i.port?Number(i.port):void 0,path:i.pathname+i.search,...typeof t==`object`?t:{}},typeof t==`function`&&(n=t)}else r=e,typeof t==`function`&&(n=t);if(this.method=(r.method||`GET`).toUpperCase(),this.protocol=r.protocol||`http:`,this.hostname=r.hostname||r.host?.split(`:`)[0]||`localhost`,this.port=Number(r.port)||(this.protocol===`https:`?443:80),this.path=r.path||`/`,this.host=r.host||`${this.hostname}:${this.port}`,this._timeout=r.timeout||0,n&&(this._responseCallback=n,this.once(`response`,n)),r.headers)for(let[e,t]of Object.entries(r.headers))this.setHeader(e,t);if(r.setHost!==!1&&!this._headers.has(`host`)){let e=this.protocol===`https:`?443:80,t=this.port===e?this.hostname:`${this.hostname}:${this.port}`;this.setHeader(`Host`,t)}r.auth&&!this._headers.has(`authorization`)&&this.setHeader(`Authorization`,`Basic `+V.from(r.auth).toString(`base64`)),r.signal&&(r.signal.aborted?this.abort():r.signal.addEventListener(`abort`,()=>this.abort(),{once:!0}));let i=U.Uri.parse(this._buildUrl(),U.UriFlags.NONE);this._session=new Zp.Session,this._message=new Zp.Message({method:this.method,uri:i}),this._cancellable=new Y.Cancellable,this.protocol===`https:`&&this._setupTls(r),this._timeout>0&&(this._session.timeout=Math.ceil(this._timeout/1e3),this._timeoutTimer=setTimeout(()=>{this._timeoutTimer=null,this.emit(`timeout`)},this._timeout))}_setupTls(e){let t=e.agent===void 0?e._defaultAgent:e.agent,n=t&&typeof t==`object`?t.options:void 0,r={...e,...n},i=r.secureContext??createSecureContext(r),o=createPeerVerifier({caCertificates:i.caCertificates,rejectUnauthorized:r.rejectUnauthorized,host:r.servername||this.hostname,checkServerIdentity:r.checkServerIdentity});this._session.set_tls_database(null),this._message.connect(`accept-certificate`,(e,t,n)=>{let r=o.accept(t);return this._tlsRejection=r?null:o.error,r}),i.certificate&&this._message.set_tls_client_certificate(i.certificate)}_buildUrl(){let e=this.protocol.endsWith(`:`)?this.protocol:this.protocol+`:`,t=e===`https:`?443:80,n=this.port===t?``:`:${this.port}`;return`${e}//${this.hostname}${n}${this.path}`}getRawHeaderNames(){return Array.from(this._headers.keys())}flushHeaders(){this.headersSent||this._applyHeaders()}setTimeout(e,t){return this._timeout=e,this._timeoutTimer&&=(clearTimeout(this._timeoutTimer),null),t&&this.once(`timeout`,t),e>0&&(this._session.timeout=Math.ceil(e/1e3),this._timeoutTimer=setTimeout(()=>{this._timeoutTimer=null,this.emit(`timeout`)},e)),this}abort(){this.aborted||(this.aborted=!0,this._timeoutTimer&&=(clearTimeout(this._timeoutTimer),null),this._cancellable.cancel(),this.emit(`abort`),this.destroy())}_write(e,t,n){let r=V.isBuffer(e)?e:typeof e==`string`?V.from(e,t):V.from(e);this._chunks.push(r),n()}_final(e){this._sendRequest().then(()=>e()).catch(t=>e(t))}_applyHeaders(){if(this.headersSent)return;this.headersSent=!0;let e=this._message.get_request_headers();for(let[t,n]of this._headers)if(Array.isArray(n))for(let r of n)e.append(t,r);else e.replace(t,n)}async _sendRequest(){this._applyHeaders();let e=V.concat(this._chunks);if(e.length>0){let t=this._headers.get(`content-type`)||`application/octet-stream`;this._message.set_request_body_from_bytes(t,new U.Bytes(e))}try{let e=await new Promise((e,t)=>{this._session.send_async(this._message,U.PRIORITY_DEFAULT,this._cancellable,(n,r)=>{try{e(this._session.send_finish(r))}catch(e){t(e)}})}),t=[];try{let n;for(;(n=await readBytesAsync(e,4096,U.PRIORITY_DEFAULT,this._cancellable))!==null;)t.push(V.from(n))}catch{}let n=new IncomingMessage;n.statusCode=this._message.status_code,n.statusMessage=this._message.get_reason_phrase(),n.httpVersion=`1.1`,this._message.get_response_headers().foreach((e,t)=>{let r=e.toLowerCase();if(n.rawHeaders.push(e,t),r in n.headers){let e=n.headers[r];Array.isArray(e)?e.push(t):n.headers[r]=[e,t]}else n.headers[r]=t}),this.finished=!0,this._timeoutTimer&&=(clearTimeout(this._timeoutTimer),null),this.emit(`response`,n),setTimeout(()=>{for(let e of t)n.push(e);n.push(null),n.complete=!0},0)}catch(e){this.aborted?this.emit(`abort`):this._tlsRejection?this.emit(`error`,this._tlsRejection):this.emit(`error`,e instanceof Error?e:Error(String(e)))}}}}),om=__exportAll$5({Agent:()=>Agent,ClientRequest:()=>ClientRequest,IncomingMessage:()=>IncomingMessage,METHODS:()=>Cp,OutgoingMessage:()=>OutgoingMessage,STATUS_CODES:()=>Sp,Server:()=>Server,ServerResponse:()=>ServerResponse,createServer:()=>createServer,default:()=>lm,get:()=>get,globalAgent:()=>sm,maxHeaderSize:()=>cm,request:()=>request,setMaxIdleHTTPParsers:()=>setMaxIdleHTTPParsers,validateHeaderName:()=>validateHeaderName,validateHeaderValue:()=>validateHeaderValue});function createServer(e,t){return typeof e==`function`?new Server(e):new Server(t)}function request(e,t,n){return new ClientRequest(e,t,n)}function get(e,t,n){let r,i=n;typeof e==`string`||e instanceof q?(r=typeof t==`object`?{...t,method:`GET`}:{method:`GET`},typeof t==`function`&&(i=t)):(r={...e,method:`GET`},typeof t==`function`&&(i=t),e=r);let o=typeof e==`string`||e instanceof q?new ClientRequest(e,{...r,method:`GET`},i):new ClientRequest({...r,method:`GET`},i);return o.end(),o}function setMaxIdleHTTPParsers(e){}var Agent,sm,cm,lm,um=__esmMin(()=>{xp(),wp(),Tp(),im(),am(),Jr(),Agent=class{defaultPort=80;protocol=`http:`;maxSockets;maxTotalSockets;maxFreeSockets;keepAliveMsecs;keepAlive;scheduling;requests={};sockets={};freeSockets={};options;constructor(e){this.options={...e},this.keepAlive=e?.keepAlive??!1,this.keepAliveMsecs=e?.keepAliveMsecs??1e3,this.maxSockets=e?.maxSockets??1/0,this.maxTotalSockets=e?.maxTotalSockets??1/0,this.maxFreeSockets=e?.maxFreeSockets??256,this.scheduling=e?.scheduling??`lifo`}destroy(){}getName(e){let t=e.host||`localhost`;return e.port&&(t+=`:`+e.port),e.localAddress&&(t+=`:`+e.localAddress),(e.family===4||e.family===6)&&(t+=`:`+e.family),t}},sm=new Agent,cm=16384,lm={STATUS_CODES:Sp,METHODS:Cp,Server,IncomingMessage,OutgoingMessage,ServerResponse,ClientRequest,Agent,globalAgent:sm,createServer,request,get,validateHeaderName,validateHeaderValue,maxHeaderSize:cm,setMaxIdleHTTPParsers}}),dm=__commonJSMin(((e,t)=>{
234
234
  /*!
235
235
  * etag
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gjsify/example-node-express-webserver",
3
- "version": "0.64.17-next.292",
3
+ "version": "0.64.18",
4
4
  "description": "Express.js blog showcase with JSON API and static frontend — a real Node.js web app running on GJS",
5
5
  "main": "dist/index.gjs.js",
6
6
  "type": "module",
@@ -21,12 +21,12 @@
21
21
  "build:public": "gjsify copy src/public dist/public"
22
22
  },
23
23
  "dependencies": {
24
- "@gjsify/http-soup-bridge": "0.64.17-next.292"
24
+ "@gjsify/http-soup-bridge": "^0.64.18"
25
25
  },
26
26
  "devDependencies": {
27
- "@gjsify/cli": "0.64.17-next.292",
28
- "@gjsify/node-globals": "0.64.17-next.292",
29
- "@gjsify/runtime": "0.64.17-next.292",
27
+ "@gjsify/cli": "^0.64.18",
28
+ "@gjsify/node-globals": "^0.64.18",
29
+ "@gjsify/runtime": "^0.64.18",
30
30
  "@types/express": "^5.0.6",
31
31
  "@types/node": "^25.9.2",
32
32
  "express": "^5.2.1",
@@ -60,6 +60,5 @@
60
60
  ],
61
61
  "node": "dist/index.node.mjs"
62
62
  }
63
- },
64
- "gitHead": "1cd14727f5a53991fbdee0f38eedea4dd8fdecdd"
63
+ }
65
64
  }