pptclaw 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/.output/nitro.json +15 -0
  2. package/.output/public/_nuxt/BAtwhwpp.js +1 -0
  3. package/.output/public/_nuxt/BEQoYl5X.js +2616 -0
  4. package/.output/public/_nuxt/BMr1Z083.js +1 -0
  5. package/.output/public/_nuxt/BXBiPOBE.js +1 -0
  6. package/.output/public/_nuxt/BuUsXmAh.js +1 -0
  7. package/.output/public/_nuxt/CPsbnj8a.js +1 -0
  8. package/.output/public/_nuxt/D9BEMGXo.js +1 -0
  9. package/.output/public/_nuxt/DQNz2huy.js +1 -0
  10. package/.output/public/_nuxt/DQxlKO7N.js +1 -0
  11. package/.output/public/_nuxt/_id_.C3K2GZV8.css +1 -0
  12. package/.output/public/_nuxt/builds/latest.json +1 -0
  13. package/.output/public/_nuxt/builds/meta/e405cd67-1e23-4b39-85e1-217b00c69ec7.json +1 -0
  14. package/.output/public/_nuxt/entry.BqkL7BC_.css +1 -0
  15. package/.output/public/_nuxt/error-404.BzoSHD6c.css +1 -0
  16. package/.output/public/_nuxt/error-500.DwAqVzgo.css +1 -0
  17. package/.output/public/_nuxt/j2eJltcB.js +2614 -0
  18. package/.output/public/alipay.svg +27 -0
  19. package/.output/public/android-chrome-192x192.png +0 -0
  20. package/.output/public/android-chrome-512x512.png +0 -0
  21. package/.output/public/animations/arrow.lottie +0 -0
  22. package/.output/public/animations/cubes.lottie +0 -0
  23. package/.output/public/animations/stars.lottie +0 -0
  24. package/.output/public/apple-touch-icon.png +0 -0
  25. package/.output/public/auth-bg.svg +30 -0
  26. package/.output/public/auth-logo.svg +4 -0
  27. package/.output/public/cursor.png +0 -0
  28. package/.output/public/customerServiceQr.png +0 -0
  29. package/.output/public/favicon-16x16.png +0 -0
  30. package/.output/public/favicon-32x32.png +0 -0
  31. package/.output/public/favicon.ico +0 -0
  32. package/.output/public/logo.svg +4 -0
  33. package/.output/public/rect.svg +9 -0
  34. package/.output/public/site.webmanifest +1 -0
  35. package/.output/public/templates.json +1623 -0
  36. package/.output/public/watermark.svg +7 -0
  37. package/.output/public/wechat-pay-sm.svg +9 -0
  38. package/.output/public/wechat-pay.svg +21 -0
  39. package/.output/server/chunks/_/error-500.mjs +1 -0
  40. package/.output/server/chunks/_/shared.cjs.prod.mjs +1 -0
  41. package/.output/server/chunks/build/client.precomputed.mjs +1 -0
  42. package/.output/server/chunks/nitro/nitro.mjs +1 -0
  43. package/.output/server/chunks/routes/api/auth/_...path_.mjs +1 -0
  44. package/.output/server/chunks/routes/api/auth/login.post.mjs +1 -0
  45. package/.output/server/chunks/routes/api/auth/logout.post.mjs +1 -0
  46. package/.output/server/chunks/routes/api/auth/user.get.mjs +1 -0
  47. package/.output/server/chunks/routes/api/cloud/_...path_.mjs +1 -0
  48. package/.output/server/chunks/routes/api/credits/_...path_.mjs +1 -0
  49. package/.output/server/chunks/routes/api/images/_...path_.mjs +1 -0
  50. package/.output/server/chunks/routes/api/payments/_...path_.mjs +1 -0
  51. package/.output/server/chunks/routes/api/public/ping.mjs +1 -0
  52. package/.output/server/chunks/routes/api/public/test.mjs +1 -0
  53. package/.output/server/chunks/routes/api/sync/assets/_session/_...filename_.get.mjs +1 -0
  54. package/.output/server/chunks/routes/api/sync/close.post.mjs +1 -0
  55. package/.output/server/chunks/routes/api/sync/open.post.mjs +1 -0
  56. package/.output/server/chunks/routes/api/sync/sessions.get.mjs +1 -0
  57. package/.output/server/chunks/routes/api/sync/switch.post.mjs +1 -0
  58. package/.output/server/chunks/routes/api/sync/upload.post.mjs +1 -0
  59. package/.output/server/chunks/routes/api/sync/validate.post.mjs +1 -0
  60. package/.output/server/chunks/routes/api/sync/ws.mjs +1 -0
  61. package/.output/server/chunks/routes/renderer.mjs +1 -0
  62. package/.output/server/chunks/virtual/_virtual_spa-template.mjs +1 -0
  63. package/.output/server/index.mjs +1 -0
  64. package/README.md +49 -0
  65. package/bin/pptclaw.mjs +165 -0
  66. package/package.json +130 -0
@@ -0,0 +1 @@
1
+ import e from"node:process";globalThis._importMeta_=globalThis._importMeta_||{url:"file:///_entry.js",env:e.env};import t,{Server as s}from"node:http";import a,{Server as c}from"node:https";import l,{createHash as d}from"node:crypto";import h from"stream";import u,{EventEmitter as f}from"events";import m from"http";import g from"crypto";import _ from"buffer";import S from"zlib";import E from"https";import k from"net";import x from"tls";import R from"url";import{EventEmitter as C}from"node:events";import{Buffer as T}from"node:buffer";import{promises as O,existsSync as P}from"node:fs";import{resolve as I,dirname as N,join as j,basename as H,relative as W,sep as L}from"node:path";import{readdir as D,readFile as B,writeFile as M,mkdir as U,unlink as q,lstat as z,stat as F,realpath as $}from"node:fs/promises";import{unwatchFile as K,watchFile as G,watch as V,stat as Z}from"fs";import{realpath as J,stat as Q,lstat as X,open as Y,readdir as ee}from"fs/promises";import*as te from"path";import{Readable as re}from"node:stream";import{type as se}from"os";import{homedir as ne}from"node:os";import{fileURLToPath as oe}from"node:url";l.webcrypto;const randomUUID=()=>l.randomUUID(),ie=Symbol.for("nodejs.util.inspect.custom");function toBufferLike(e){if(null==e)return"";const t=typeof e;return"string"===t?e:"number"===t||"boolean"===t||"bigint"===t?e.toString():"function"===t||"symbol"===t?"{}":e instanceof Uint8Array||e instanceof ArrayBuffer?e:function(e){if(null===e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);if(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t))return!1;if(Symbol.iterator in e)return!1;if(Symbol.toStringTag in e)return"[object Module]"===Object.prototype.toString.call(e);return!0}(e)?JSON.stringify(e):e}class Message{event;peer;rawData;#e;#t;#r;#s;#n;#o;constructor(e,t,s){this.rawData=e||"",this.peer=t,this.event=s}get id(){return this.#e||(this.#e=randomUUID()),this.#e}uint8Array(){const e=this.#t;if(e)return e;const t=this.rawData;if(t instanceof Uint8Array)return this.#t=t;if(t instanceof ArrayBuffer||t instanceof SharedArrayBuffer)return this.#r=t,this.#t=new Uint8Array(t);if("string"==typeof t)return this.#n=t,this.#t=(new TextEncoder).encode(this.#n);if(Symbol.iterator in t)return this.#t=new Uint8Array(t);if("number"==typeof t?.length)return this.#t=new Uint8Array(t);if(t instanceof DataView)return this.#t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new TypeError(`Unsupported message type: ${Object.prototype.toString.call(t)}`)}arrayBuffer(){const e=this.#r;if(e)return e;const t=this.rawData;return t instanceof ArrayBuffer||t instanceof SharedArrayBuffer?this.#r=t:this.#r=this.uint8Array().buffer}blob(){const e=this.#s;if(e)return e;const t=this.rawData;return t instanceof Blob?this.#s=t:this.#s=new Blob([this.uint8Array()])}text(){const e=this.#n;if(e)return e;const t=this.rawData;return this.#n="string"==typeof t?t:(new TextDecoder).decode(this.uint8Array())}json(){const e=this.#o;return e||(this.#o=JSON.parse(this.text()))}get data(){switch(this.peer?.websocket?.binaryType){case"arraybuffer":return this.arrayBuffer();case"blob":return this.blob();case"nodebuffer":return globalThis.Buffer?Buffer.from(this.uint8Array()):this.uint8Array();case"uint8array":return this.uint8Array();case"text":return this.text();default:return this.rawData}}toString(){return this.text()}[Symbol.toPrimitive](){return this.text()}[ie](){return{data:this.rawData}}}class Peer{_internal;_topics;_id;#i;constructor(e){this._topics=new Set,this._internal=e}get context(){return this._internal.context??={}}get id(){return this._id||(this._id=randomUUID()),this._id}get remoteAddress(){}get request(){return this._internal.request}get websocket(){if(!this.#i){const t=this._internal.ws,s=this._internal.request;this.#i=s?(e=s,new Proxy(t,{get:(t,s)=>{const a=Reflect.get(t,s);if(!a)switch(s){case"protocol":return e?.headers?.get("sec-websocket-protocol")||"";case"extensions":return e?.headers?.get("sec-websocket-extensions")||"";case"url":return e?.url?.replace(/^http/,"ws")||void 0}return a}})):t}var e;return this.#i}get peers(){return this._internal.peers||new Set}get topics(){return this._topics}terminate(){this.close()}subscribe(e){this._topics.add(e)}unsubscribe(e){this._topics.delete(e)}toString(){return this.id}[Symbol.toPrimitive](){return this.id}[Symbol.toStringTag](){return"WebSocket"}[ie](){return Object.fromEntries([["id",this.id],["remoteAddress",this.remoteAddress],["peers",this.peers],["webSocket",this.websocket]].filter(e=>e[1]))}}class AdapterHookable{options;constructor(e){this.options=e||{}}callHook(e,t,s){const a=this.options.hooks?.[e],c=a?.(t,s),l=this.options.resolve?.(t);if(!l)return c;const d=l instanceof Promise?l.then(t=>t?.[e]):l?.[e];return Promise.all([c,d]).then(([e,a])=>{const c=a?.(t,s);return c instanceof Promise?c.then(t=>t||e):c||e})}async upgrade(e){let t=e.context;t||(t={},Object.defineProperty(e,"context",{enumerable:!0,value:t}));try{const s=await this.callHook("upgrade",e);if(!s)return{context:t};if(!1===s.ok)return{context:t,endResponse:s};if(s.headers)return{context:t,upgradeHeaders:s.headers}}catch(e){const s=e.response||e;if(s instanceof Response)return{context:t,endResponse:s};throw e}return{context:t}}}function adapterUtils(e){return{peers:e,publish(t,s,a){let c;for(const s of e)if(s.topics.has(t)){c=s;break}c&&(c.send(s,a),c.publish(t,s,a))}}}class WSError extends Error{constructor(...e){super(...e),this.name="WSError"}}function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ae,ce,le,de,he,ue,fe,pe={exports:{}};function requireConstants(){if(ce)return ae;ce=1;const e=["nodebuffer","arraybuffer","fragments"],t="undefined"!=typeof Blob;return t&&e.push("blob"),ae={BINARY_TYPES:e,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:t,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}function requireBufferUtil(){if(le)return pe.exports;le=1;const{EMPTY_BUFFER:t}=requireConstants(),s=Buffer[Symbol.species];function _mask(e,t,s,a,c){for(let l=0;l<c;l++)s[a+l]=e[l]^t[3&l]}function _unmask(e,t){for(let s=0;s<e.length;s++)e[s]^=t[3&s]}if(pe.exports={concat:function(e,a){if(0===e.length)return t;if(1===e.length)return e[0];const c=Buffer.allocUnsafe(a);let l=0;for(let t=0;t<e.length;t++){const s=e[t];c.set(s,l),l+=s.length}return l<a?new s(c.buffer,c.byteOffset,l):c},mask:_mask,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function toBuffer(e){if(toBuffer.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new s(e):ArrayBuffer.isView(e)?t=new s(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),toBuffer.readOnly=!1),t},unmask:_unmask},!e.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");pe.exports.mask=function(t,s,a,c,l){l<48?_mask(t,s,a,c,l):e.mask(t,s,a,c,l)},pe.exports.unmask=function(t,s){t.length<32?_unmask(t,s):e.unmask(t,s)}}catch(e){}return pe.exports}function requirePermessageDeflate(){if(fe)return ue;fe=1;const e=S,t=requireBufferUtil(),s=function(){if(he)return de;he=1;const e=Symbol("kDone"),t=Symbol("kRun");return de=class{constructor(s){this[e]=()=>{this.pending--,this[t]()},this.concurrency=s||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[t]()}[t](){if(this.pending!==this.concurrency&&this.jobs.length){const t=this.jobs.shift();this.pending++,t(this[e])}}}}(),{kStatusCode:a}=requireConstants(),c=Buffer[Symbol.species],l=Buffer.from([0,0,255,255]),d=Symbol("permessage-deflate"),h=Symbol("total-length"),u=Symbol("callback"),f=Symbol("buffers"),m=Symbol("error");let g;function deflateOnData(e){this[f].push(e),this[h]+=e.length}function inflateOnData(e){this[h]+=e.length,this[d]._maxPayload<1||this[h]<=this[d]._maxPayload?this[f].push(e):(this[m]=new RangeError("Max payload size exceeded"),this[m].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[m][a]=1009,this.removeListener("data",inflateOnData),this.reset())}function inflateOnError(e){this[d]._inflate=null,this[m]?this[u](this[m]):(e[a]=1007,this[u](e))}return ue=class{constructor(e,t,a){if(this._maxPayload=0|a,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!g){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;g=new s(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,s=e.find(e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(s.server_no_context_takeover=!0),t.clientNoContextTakeover&&(s.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(s.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?s.client_max_window_bits=t.clientMaxWindowBits:!0!==s.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete s.client_max_window_bits,s}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let s=e[t];if(s.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(s=s[0],"client_max_window_bits"===t){if(!0!==s){const e=+s;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${s}`)}else if("server_max_window_bits"===t){const e=+s;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==s)throw new TypeError(`Invalid value for parameter "${t}": ${s}`)}e[t]=s})}),e}decompress(e,t,s){g.add(a=>{this._decompress(e,t,(e,t)=>{a(),s(e,t)})})}compress(e,t,s){g.add(a=>{this._compress(e,t,(e,t)=>{a(),s(e,t)})})}_decompress(s,a,c){const g=this._isServer?"client":"server";if(!this._inflate){const t=`${g}_max_window_bits`,s="number"!=typeof this.params[t]?e.Z_DEFAULT_WINDOWBITS:this.params[t];this._inflate=e.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[d]=this,this._inflate[h]=0,this._inflate[f]=[],this._inflate.on("error",inflateOnError),this._inflate.on("data",inflateOnData)}this._inflate[u]=c,this._inflate.write(s),a&&this._inflate.write(l),this._inflate.flush(()=>{const e=this._inflate[m];if(e)return this._inflate.close(),this._inflate=null,void c(e);const s=t.concat(this._inflate[f],this._inflate[h]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[h]=0,this._inflate[f]=[],a&&this.params[`${g}_no_context_takeover`]&&this._inflate.reset()),c(null,s)})}_compress(s,a,l){const d=this._isServer?"server":"client";if(!this._deflate){const t=`${d}_max_window_bits`,s="number"!=typeof this.params[t]?e.Z_DEFAULT_WINDOWBITS:this.params[t];this._deflate=e.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[h]=0,this._deflate[f]=[],this._deflate.on("data",deflateOnData)}this._deflate[u]=l,this._deflate.write(s),this._deflate.flush(e.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=t.concat(this._deflate[f],this._deflate[h]);a&&(e=new c(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[h]=0,this._deflate[f]=[],a&&this.params[`${d}_no_context_takeover`]&&this._deflate.reset(),l(null,e)})}},ue}var me,ye,ge,_e,we,be,ve,Se,Ee,ke,xe,Re,Ce,Te,Oe,Ae,Pe,Ie={exports:{}};function requireValidation(){if(me)return Ie.exports;me=1;const{isUtf8:t}=_,{hasBlob:s}=requireConstants();function _isValidUTF8(e){const t=e.length;let s=0;for(;s<t;)if(128&e[s])if(192==(224&e[s])){if(s+1===t||128!=(192&e[s+1])||192==(254&e[s]))return!1;s+=2}else if(224==(240&e[s])){if(s+2>=t||128!=(192&e[s+1])||128!=(192&e[s+2])||224===e[s]&&128==(224&e[s+1])||237===e[s]&&160==(224&e[s+1]))return!1;s+=3}else{if(240!=(248&e[s]))return!1;if(s+3>=t||128!=(192&e[s+1])||128!=(192&e[s+2])||128!=(192&e[s+3])||240===e[s]&&128==(240&e[s+1])||244===e[s]&&e[s+1]>143||e[s]>244)return!1;s+=4}else s++;return!0}if(Ie.exports={isBlob:function(e){return s&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:_isValidUTF8,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},t)Ie.exports.isValidUTF8=function(e){return e.length<24?_isValidUTF8(e):t(e)};else if(!e.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Ie.exports.isValidUTF8=function(t){return t.length<32?_isValidUTF8(t):e(t)}}catch(e){}return Ie.exports}function requireReceiver(){if(ge)return ye;ge=1;const{Writable:e}=h,t=requirePermessageDeflate(),{BINARY_TYPES:s,EMPTY_BUFFER:a,kStatusCode:c,kWebSocket:l}=requireConstants(),{concat:d,toArrayBuffer:u,unmask:f}=requireBufferUtil(),{isValidStatusCode:m,isValidUTF8:g}=requireValidation(),_=Buffer[Symbol.species];return ye=class extends e{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||s[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[l]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,s){if(8===this._opcode&&0==this._state)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new _(t.buffer,t.byteOffset+e,t.length-e),new _(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const s=this._buffers[0],a=t.length-e;e>=s.length?t.set(this._buffers.shift(),a):(t.set(new Uint8Array(s.buffer,s.byteOffset,e),a),this._buffers[0]=new _(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const s=this.consume(2);if(48&s[0]){return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"))}const a=!(64&~s[0]);if(a&&!this._extensions[t.extensionName]){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._fin=!(128&~s[0]),this._opcode=15&s[0],this._payloadLength=127&s[1],0===this._opcode){if(a){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(!this._fragmented){return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"))}this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}this._compressed=a}else{if(!(this._opcode>7&&this._opcode<11)){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}if(!this._fin){return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"))}if(a){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength){return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=!(128&~s[1]),this._isServer){if(!this._masked){return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}}else if(this._masked){return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"))}126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),s=t.readUInt32BE(0);if(s>Math.pow(2,21)-1){return void e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"))}this._payloadLength=s*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){return void e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"))}this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!==(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&f(t,this._mask)}if(this._opcode>7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,s){this._extensions[t.extensionName].decompress(e,this._fin,(e,t)=>{if(e)return s(e);if(t.length){if(this._messageLength+=t.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void s(e)}this._fragments.push(t)}this.dataMessage(s),0===this._state&&this.startLoop(s)})}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let a;a="nodebuffer"===this._binaryType?d(s,t):"arraybuffer"===this._binaryType?u(d(s,t)):"blob"===this._binaryType?new Blob(s):s,this._allowSynchronousEvents?(this.emit("message",a,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",a,!0),this._state=0,this.startLoop(e)}))}else{const a=d(s,t);if(!this._skipUTF8Validation&&!g(a)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",a,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",a,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)}));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,a),this.end();else{const s=e.readUInt16BE(0);if(!m(s)){const e=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const a=new _(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!g(a)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",s,a),this.end()}this._state=0}}createError(e,t,s,a,l){this._loop=!1,this._errored=!0;const d=new e(s?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(d,this.createError),d.code=l,d[c]=a,d}}}function requireSender(){if(we)return _e;we=1;const{Duplex:t}=h,{randomFillSync:s}=g,a=requirePermessageDeflate(),{EMPTY_BUFFER:c,kWebSocket:l,NOOP:d}=requireConstants(),{isBlob:u,isValidStatusCode:f}=requireValidation(),{mask:m,toBuffer:_}=requireBufferUtil(),S=Symbol("kByteLength"),E=Buffer.alloc(4),k=8192;let x,R=k;class Sender{constructor(e,t,s){this._extensions=t||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=d,this[l]=void 0}static frame(e,t){let a,c,l=!1,d=2,h=!1;t.mask&&(a=t.maskBuffer||E,t.generateMask?t.generateMask(a):(R===k&&(void 0===x&&(x=Buffer.alloc(k)),s(x,0,k),R=0),a[0]=x[R++],a[1]=x[R++],a[2]=x[R++],a[3]=x[R++]),h=0===(a[0]|a[1]|a[2]|a[3]),d=6),"string"==typeof e?c=t.mask&&!h||void 0===t[S]?(e=Buffer.from(e)).length:t[S]:(c=e.length,l=t.mask&&t.readOnly&&!h);let u=c;c>=65536?(d+=8,u=127):c>125&&(d+=2,u=126);const f=Buffer.allocUnsafe(l?c+d:d);return f[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(f[0]|=64),f[1]=u,126===u?f.writeUInt16BE(c,2):127===u&&(f[2]=f[3]=0,f.writeUIntBE(c,4,6)),t.mask?(f[1]|=128,f[d-4]=a[0],f[d-3]=a[1],f[d-2]=a[2],f[d-1]=a[3],h?[f,e]:l?(m(e,a,f,d,c),[f]):(m(e,a,e,0,c),[f,e])):[f,e]}close(e,t,s,a){let l;if(void 0===e)l=c;else{if("number"!=typeof e||!f(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const s=Buffer.byteLength(t);if(s>123)throw new RangeError("The message must not be greater than 123 bytes");l=Buffer.allocUnsafe(2+s),l.writeUInt16BE(e,0),"string"==typeof t?l.write(t,2):l.set(t,2)}else l=Buffer.allocUnsafe(2),l.writeUInt16BE(e,0)}const d={[S]:l.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,l,!1,d,a]):this.sendFrame(Sender.frame(l,d),a)}ping(e,t,s){let a,c;if("string"==typeof e?(a=Buffer.byteLength(e),c=!1):u(e)?(a=e.size,c=!1):(a=(e=_(e)).length,c=_.readOnly),a>125)throw new RangeError("The data size must not be greater than 125 bytes");const l={[S]:a,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};u(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,l,s]):this.getBlobData(e,!1,l,s):0!==this._state?this.enqueue([this.dispatch,e,!1,l,s]):this.sendFrame(Sender.frame(e,l),s)}pong(e,t,s){let a,c;if("string"==typeof e?(a=Buffer.byteLength(e),c=!1):u(e)?(a=e.size,c=!1):(a=(e=_(e)).length,c=_.readOnly),a>125)throw new RangeError("The data size must not be greater than 125 bytes");const l={[S]:a,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};u(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,l,s]):this.getBlobData(e,!1,l,s):0!==this._state?this.enqueue([this.dispatch,e,!1,l,s]):this.sendFrame(Sender.frame(e,l),s)}send(e,t,s){const c=this._extensions[a.extensionName];let l,d,h=t.binary?2:1,f=t.compress;"string"==typeof e?(l=Buffer.byteLength(e),d=!1):u(e)?(l=e.size,d=!1):(l=(e=_(e)).length,d=_.readOnly),this._firstFragment?(this._firstFragment=!1,f&&c&&c.params[c._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(f=l>=c._threshold),this._compress=f):(f=!1,h=0),t.fin&&(this._firstFragment=!0);const m={[S]:l,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:h,readOnly:d,rsv1:f};u(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,m,s]):this.getBlobData(e,this._compress,m,s):0!==this._state?this.enqueue([this.dispatch,e,this._compress,m,s]):this.dispatch(e,this._compress,m,s)}getBlobData(t,s,a,c){this._bufferedBytes+=a[S],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){const t=new Error("The socket was closed while the blob was being read");return void e.nextTick(callCallbacks,this,t,c)}this._bufferedBytes-=a[S];const l=_(t);s?this.dispatch(l,s,a,c):(this._state=0,this.sendFrame(Sender.frame(l,a),c),this.dequeue())}).catch(t=>{e.nextTick(onError,this,t,c)})}dispatch(e,t,s,c){if(!t)return void this.sendFrame(Sender.frame(e,s),c);const l=this._extensions[a.extensionName];this._bufferedBytes+=s[S],this._state=1,l.compress(e,s.fin,(e,t)=>{if(this._socket.destroyed){return void callCallbacks(this,new Error("The socket was closed while data was being compressed"),c)}this._bufferedBytes-=s[S],this._state=0,s.readOnly=!1,this.sendFrame(Sender.frame(t,s),c),this.dequeue()})}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][S],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][S],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}function callCallbacks(e,t,s){"function"==typeof s&&s(t);for(let s=0;s<e._queue.length;s++){const a=e._queue[s],c=a[a.length-1];"function"==typeof c&&c(t)}}function onError(e,t,s){callCallbacks(e,t,s),e.onerror(t)}return _e=Sender}function requireExtension(){if(Ee)return Se;Ee=1;const{tokenChars:e}=requireValidation();function push(e,t,s){void 0===e[t]?e[t]=[s]:e[t].push(s)}return Se={format:function(e){return Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>[t].concat(Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>!0===e?t:`${t}=${e}`).join("; ")})).join("; ")).join(", ")}).join(", ")},parse:function(t){const s=Object.create(null);let a,c,l=Object.create(null),d=!1,h=!1,u=!1,f=-1,m=-1,g=-1,_=0;for(;_<t.length;_++)if(m=t.charCodeAt(_),void 0===a)if(-1===g&&1===e[m])-1===f&&(f=_);else if(0===_||32!==m&&9!==m){if(59!==m&&44!==m)throw new SyntaxError(`Unexpected character at index ${_}`);{if(-1===f)throw new SyntaxError(`Unexpected character at index ${_}`);-1===g&&(g=_);const e=t.slice(f,g);44===m?(push(s,e,l),l=Object.create(null)):a=e,f=g=-1}}else-1===g&&-1!==f&&(g=_);else if(void 0===c)if(-1===g&&1===e[m])-1===f&&(f=_);else if(32===m||9===m)-1===g&&-1!==f&&(g=_);else if(59===m||44===m){if(-1===f)throw new SyntaxError(`Unexpected character at index ${_}`);-1===g&&(g=_),push(l,t.slice(f,g),!0),44===m&&(push(s,a,l),l=Object.create(null),a=void 0),f=g=-1}else{if(61!==m||-1===f||-1!==g)throw new SyntaxError(`Unexpected character at index ${_}`);c=t.slice(f,_),f=g=-1}else if(h){if(1!==e[m])throw new SyntaxError(`Unexpected character at index ${_}`);-1===f?f=_:d||(d=!0),h=!1}else if(u)if(1===e[m])-1===f&&(f=_);else if(34===m&&-1!==f)u=!1,g=_;else{if(92!==m)throw new SyntaxError(`Unexpected character at index ${_}`);h=!0}else if(34===m&&61===t.charCodeAt(_-1))u=!0;else if(-1===g&&1===e[m])-1===f&&(f=_);else if(-1===f||32!==m&&9!==m){if(59!==m&&44!==m)throw new SyntaxError(`Unexpected character at index ${_}`);{if(-1===f)throw new SyntaxError(`Unexpected character at index ${_}`);-1===g&&(g=_);let e=t.slice(f,g);d&&(e=e.replace(/\\/g,""),d=!1),push(l,c,e),44===m&&(push(s,a,l),l=Object.create(null),a=void 0),c=void 0,f=g=-1}}else-1===g&&(g=_);if(-1===f||u||32===m||9===m)throw new SyntaxError("Unexpected end of input");-1===g&&(g=_);const S=t.slice(f,g);return void 0===a?push(s,S,l):(void 0===c?push(l,S,!0):push(l,c,d?S.replace(/\\/g,""):S),push(s,a,l)),s}},Se}function requireWebsocket(){if(xe)return ke;xe=1;const t=u,s=E,a=m,c=k,l=x,{randomBytes:d,createHash:f}=g,{Duplex:_,Readable:S}=h,{URL:C}=R,T=requirePermessageDeflate(),O=requireReceiver(),P=requireSender(),{isBlob:I}=requireValidation(),{BINARY_TYPES:N,EMPTY_BUFFER:j,GUID:H,kForOnEventAttribute:W,kListener:L,kStatusCode:D,kWebSocket:B,NOOP:M}=requireConstants(),{EventTarget:{addEventListener:U,removeEventListener:q}}=function(){if(ve)return be;ve=1;const{kForOnEventAttribute:e,kListener:t}=requireConstants(),s=Symbol("kCode"),a=Symbol("kData"),c=Symbol("kError"),l=Symbol("kMessage"),d=Symbol("kReason"),h=Symbol("kTarget"),u=Symbol("kType"),f=Symbol("kWasClean");class Event{constructor(e){this[h]=null,this[u]=e}get target(){return this[h]}get type(){return this[u]}}Object.defineProperty(Event.prototype,"target",{enumerable:!0}),Object.defineProperty(Event.prototype,"type",{enumerable:!0});class CloseEvent extends Event{constructor(e,t={}){super(e),this[s]=void 0===t.code?0:t.code,this[d]=void 0===t.reason?"":t.reason,this[f]=void 0!==t.wasClean&&t.wasClean}get code(){return this[s]}get reason(){return this[d]}get wasClean(){return this[f]}}Object.defineProperty(CloseEvent.prototype,"code",{enumerable:!0}),Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:!0}),Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:!0});class ErrorEvent extends Event{constructor(e,t={}){super(e),this[c]=void 0===t.error?null:t.error,this[l]=void 0===t.message?"":t.message}get error(){return this[c]}get message(){return this[l]}}Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:!0}),Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:!0});class MessageEvent extends Event{constructor(e,t={}){super(e),this[a]=void 0===t.data?null:t.data}get data(){return this[a]}}Object.defineProperty(MessageEvent.prototype,"data",{enumerable:!0});const m={addEventListener(s,a,c={}){for(const l of this.listeners(s))if(!c[e]&&l[t]===a&&!l[e])return;let l;if("message"===s)l=function(e,t){const s=new MessageEvent("message",{data:t?e:e.toString()});s[h]=this,callListener(a,this,s)};else if("close"===s)l=function(e,t){const s=new CloseEvent("close",{code:e,reason:t.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[h]=this,callListener(a,this,s)};else if("error"===s)l=function(e){const t=new ErrorEvent("error",{error:e,message:e.message});t[h]=this,callListener(a,this,t)};else{if("open"!==s)return;l=function(){const e=new Event("open");e[h]=this,callListener(a,this,e)}}l[e]=!!c[e],l[t]=a,c.once?this.once(s,l):this.on(s,l)},removeEventListener(s,a){for(const c of this.listeners(s))if(c[t]===a&&!c[e]){this.removeListener(s,c);break}}};function callListener(e,t,s){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,s):e.call(t,s)}return be={CloseEvent:CloseEvent,ErrorEvent:ErrorEvent,Event:Event,EventTarget:m,MessageEvent:MessageEvent}}(),{format:z,parse:F}=requireExtension(),{toBuffer:$}=requireBufferUtil(),K=Symbol("kAborted"),G=[8,13],V=["CONNECTING","OPEN","CLOSING","CLOSED"],Z=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class WebSocket extends t{constructor(e,t,s){super(),this._binaryType=N[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=j,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=WebSocket.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(s=t,t=[]):t=[t]),initAsClient(this,e,t,s)):(this._autoPong=s.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){N.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,s){const a=new O({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),c=new P(e,this._extensions,s.generateMask);this._receiver=a,this._sender=c,this._socket=e,a[B]=this,c[B]=this,e[B]=this,a.on("conclude",receiverOnConclude),a.on("drain",receiverOnDrain),a.on("error",receiverOnError),a.on("message",receiverOnMessage),a.on("ping",receiverOnPing),a.on("pong",receiverOnPong),c.onerror=senderOnError,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",socketOnClose),e.on("data",socketOnData),e.on("end",socketOnEnd),e.on("error",socketOnError),this._readyState=WebSocket.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=WebSocket.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[T.extensionName]&&this._extensions[T.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==WebSocket.CLOSED){if(this.readyState===WebSocket.CONNECTING){const e="WebSocket was closed before the connection was established";return void abortHandshake(this,this._req,e)}this.readyState!==WebSocket.CLOSING?(this._readyState=WebSocket.CLOSING,this._sender.close(e,t,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),setCloseTimer(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end()}}pause(){this.readyState!==WebSocket.CONNECTING&&this.readyState!==WebSocket.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,s){if(this.readyState===WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(s=e,e=t=void 0):"function"==typeof t&&(s=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===WebSocket.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||j,t,s)):sendAfterClose(this,e,s)}pong(e,t,s){if(this.readyState===WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(s=e,e=t=void 0):"function"==typeof t&&(s=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===WebSocket.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||j,t,s)):sendAfterClose(this,e,s)}resume(){this.readyState!==WebSocket.CONNECTING&&this.readyState!==WebSocket.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,s){if(this.readyState===WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(s=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==WebSocket.OPEN)return void sendAfterClose(this,e,s);const a={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[T.extensionName]||(a.compress=!1),this._sender.send(e||j,a,s)}terminate(){if(this.readyState!==WebSocket.CLOSED){if(this.readyState===WebSocket.CONNECTING){const e="WebSocket was closed before the connection was established";return void abortHandshake(this,this._req,e)}this._socket&&(this._readyState=WebSocket.CLOSING,this._socket.destroy())}}}function initAsClient(e,t,c,l){const h={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:G[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...l,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=h.autoPong,!G.includes(h.protocolVersion))throw new RangeError(`Unsupported protocol version: ${h.protocolVersion} (supported versions: ${G.join(", ")})`);let u;if(t instanceof C)u=t;else try{u=new C(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===u.protocol?u.protocol="ws:":"https:"===u.protocol&&(u.protocol="wss:"),e._url=u.href;const m="wss:"===u.protocol,g="ws+unix:"===u.protocol;let _;if("ws:"===u.protocol||m||g?g&&!u.pathname?_="The URL's pathname is empty":u.hash&&(_="The URL contains a fragment identifier"):_='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',_){const t=new SyntaxError(_);if(0===e._redirects)throw t;return void emitErrorAndClose(e,t)}const S=m?443:80,E=d(16).toString("base64"),k=m?s.request:a.request,x=new Set;let R,O;if(h.createConnection=h.createConnection||(m?tlsConnect:netConnect),h.defaultPort=h.defaultPort||S,h.port=u.port||S,h.host=u.hostname.startsWith("[")?u.hostname.slice(1,-1):u.hostname,h.headers={...h.headers,"Sec-WebSocket-Version":h.protocolVersion,"Sec-WebSocket-Key":E,Connection:"Upgrade",Upgrade:"websocket"},h.path=u.pathname+u.search,h.timeout=h.handshakeTimeout,h.perMessageDeflate&&(R=new T(!0!==h.perMessageDeflate?h.perMessageDeflate:{},!1,h.maxPayload),h.headers["Sec-WebSocket-Extensions"]=z({[T.extensionName]:R.offer()})),c.length){for(const e of c){if("string"!=typeof e||!Z.test(e)||x.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");x.add(e)}h.headers["Sec-WebSocket-Protocol"]=c.join(",")}if(h.origin&&(h.protocolVersion<13?h.headers["Sec-WebSocket-Origin"]=h.origin:h.headers.Origin=h.origin),(u.username||u.password)&&(h.auth=`${u.username}:${u.password}`),g){const e=h.path.split(":");h.socketPath=e[0],h.path=e[1]}if(h.followRedirects){if(0===e._redirects){e._originalIpc=g,e._originalSecure=m,e._originalHostOrSocketPath=g?h.socketPath:u.host;const t=l&&l.headers;if(l={...l,headers:{}},t)for(const[e,s]of Object.entries(t))l.headers[e.toLowerCase()]=s}else if(0===e.listenerCount("redirect")){const t=g?!!e._originalIpc&&h.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&u.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!m)&&(delete h.headers.authorization,delete h.headers.cookie,t||delete h.headers.host,h.auth=void 0)}h.auth&&!l.headers.authorization&&(l.headers.authorization="Basic "+Buffer.from(h.auth).toString("base64")),O=e._req=k(h),e._redirects&&e.emit("redirect",e.url,O)}else O=e._req=k(h);h.timeout&&O.on("timeout",()=>{abortHandshake(e,O,"Opening handshake has timed out")}),O.on("error",t=>{null===O||O[K]||(O=e._req=null,emitErrorAndClose(e,t))}),O.on("response",s=>{const a=s.headers.location,d=s.statusCode;if(a&&h.followRedirects&&d>=300&&d<400){if(++e._redirects>h.maxRedirects)return void abortHandshake(e,O,"Maximum redirects exceeded");let s;O.abort();try{s=new C(a,t)}catch(t){const s=new SyntaxError(`Invalid URL: ${a}`);return void emitErrorAndClose(e,s)}initAsClient(e,s,c,l)}else e.emit("unexpected-response",O,s)||abortHandshake(e,O,`Unexpected server response: ${s.statusCode}`)}),O.on("upgrade",(t,s,a)=>{if(e.emit("upgrade",t),e.readyState!==WebSocket.CONNECTING)return;O=e._req=null;const c=t.headers.upgrade;if(void 0===c||"websocket"!==c.toLowerCase())return void abortHandshake(e,s,"Invalid Upgrade header");const l=f("sha1").update(E+H).digest("base64");if(t.headers["sec-websocket-accept"]!==l)return void abortHandshake(e,s,"Invalid Sec-WebSocket-Accept header");const d=t.headers["sec-websocket-protocol"];let u;if(void 0!==d?x.size?x.has(d)||(u="Server sent an invalid subprotocol"):u="Server sent a subprotocol but none was requested":x.size&&(u="Server sent no subprotocol"),u)return void abortHandshake(e,s,u);d&&(e._protocol=d);const m=t.headers["sec-websocket-extensions"];if(void 0!==m){if(!R){return void abortHandshake(e,s,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=F(m)}catch(t){return void abortHandshake(e,s,"Invalid Sec-WebSocket-Extensions header")}const a=Object.keys(t);if(1!==a.length||a[0]!==T.extensionName){return void abortHandshake(e,s,"Server indicated an extension that was not requested")}try{R.accept(t[T.extensionName])}catch(t){return void abortHandshake(e,s,"Invalid Sec-WebSocket-Extensions header")}e._extensions[T.extensionName]=R}e.setSocket(s,a,{allowSynchronousEvents:h.allowSynchronousEvents,generateMask:h.generateMask,maxPayload:h.maxPayload,skipUTF8Validation:h.skipUTF8Validation})}),h.finishRequest?h.finishRequest(O,e):O.end()}function emitErrorAndClose(e,t){e._readyState=WebSocket.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function netConnect(e){return e.path=e.socketPath,c.connect(e)}function tlsConnect(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=c.isIP(e.host)?"":e.host),l.connect(e)}function abortHandshake(t,s,a){t._readyState=WebSocket.CLOSING;const c=new Error(a);Error.captureStackTrace(c,abortHandshake),s.setHeader?(s[K]=!0,s.abort(),s.socket&&!s.socket.destroyed&&s.socket.destroy(),e.nextTick(emitErrorAndClose,t,c)):(s.destroy(c),s.once("error",t.emit.bind(t,"error")),s.once("close",t.emitClose.bind(t)))}function sendAfterClose(t,s,a){if(s){const e=I(s)?s.size:$(s).length;t._socket?t._sender._bufferedBytes+=e:t._bufferedAmount+=e}if(a){const s=new Error(`WebSocket is not open: readyState ${t.readyState} (${V[t.readyState]})`);e.nextTick(a,s)}}function receiverOnConclude(t,s){const a=this[B];a._closeFrameReceived=!0,a._closeMessage=s,a._closeCode=t,void 0!==a._socket[B]&&(a._socket.removeListener("data",socketOnData),e.nextTick(resume,a._socket),1005===t?a.close():a.close(t,s))}function receiverOnDrain(){const e=this[B];e.isPaused||e._socket.resume()}function receiverOnError(t){const s=this[B];void 0!==s._socket[B]&&(s._socket.removeListener("data",socketOnData),e.nextTick(resume,s._socket),s.close(t[D])),s._errorEmitted||(s._errorEmitted=!0,s.emit("error",t))}function receiverOnFinish(){this[B].emitClose()}function receiverOnMessage(e,t){this[B].emit("message",e,t)}function receiverOnPing(e){const t=this[B];t._autoPong&&t.pong(e,!this._isServer,M),t.emit("ping",e)}function receiverOnPong(e){this[B].emit("pong",e)}function resume(e){e.resume()}function senderOnError(e){const t=this[B];t.readyState!==WebSocket.CLOSED&&(t.readyState===WebSocket.OPEN&&(t._readyState=WebSocket.CLOSING,setCloseTimer(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function setCloseTimer(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function socketOnClose(){const e=this[B];let t;this.removeListener("close",socketOnClose),this.removeListener("data",socketOnData),this.removeListener("end",socketOnEnd),e._readyState=WebSocket.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[B]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",receiverOnFinish),e._receiver.on("finish",receiverOnFinish))}function socketOnData(e){this[B]._receiver.write(e)||this.pause()}function socketOnEnd(){const e=this[B];e._readyState=WebSocket.CLOSING,e._receiver.end(),this.end()}function socketOnError(){const e=this[B];this.removeListener("error",socketOnError),this.on("error",M),e&&(e._readyState=WebSocket.CLOSING,this.destroy())}return Object.defineProperty(WebSocket,"CONNECTING",{enumerable:!0,value:V.indexOf("CONNECTING")}),Object.defineProperty(WebSocket.prototype,"CONNECTING",{enumerable:!0,value:V.indexOf("CONNECTING")}),Object.defineProperty(WebSocket,"OPEN",{enumerable:!0,value:V.indexOf("OPEN")}),Object.defineProperty(WebSocket.prototype,"OPEN",{enumerable:!0,value:V.indexOf("OPEN")}),Object.defineProperty(WebSocket,"CLOSING",{enumerable:!0,value:V.indexOf("CLOSING")}),Object.defineProperty(WebSocket.prototype,"CLOSING",{enumerable:!0,value:V.indexOf("CLOSING")}),Object.defineProperty(WebSocket,"CLOSED",{enumerable:!0,value:V.indexOf("CLOSED")}),Object.defineProperty(WebSocket.prototype,"CLOSED",{enumerable:!0,value:V.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(WebSocket.prototype,e,{enumerable:!0})}),["open","error","close","message"].forEach(e=>{Object.defineProperty(WebSocket.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[W])return t[L];return null},set(t){for(const t of this.listeners(e))if(t[W]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[W]:!0})}})}),WebSocket.prototype.addEventListener=U,WebSocket.prototype.removeEventListener=q,ke=WebSocket}function requireSubprotocol(){if(Oe)return Te;Oe=1;const{tokenChars:e}=requireValidation();return Te={parse:function(t){const s=new Set;let a=-1,c=-1,l=0;for(;l<t.length;l++){const d=t.charCodeAt(l);if(-1===c&&1===e[d])-1===a&&(a=l);else if(0===l||32!==d&&9!==d){if(44!==d)throw new SyntaxError(`Unexpected character at index ${l}`);{if(-1===a)throw new SyntaxError(`Unexpected character at index ${l}`);-1===c&&(c=l);const e=t.slice(a,c);if(s.has(e))throw new SyntaxError(`The "${e}" subprotocol is duplicated`);s.add(e),a=c=-1}}else-1===c&&-1!==a&&(c=l)}if(-1===a||-1!==c)throw new SyntaxError("Unexpected end of input");const d=t.slice(a,l);if(s.has(d))throw new SyntaxError(`The "${d}" subprotocol is duplicated`);return s.add(d),s}},Te}!function(){if(Ce)return Re;Ce=1,requireWebsocket();const{Duplex:t}=h;function emitClose(e){e.emit("close")}function duplexOnEnd(){!this.destroyed&&this._writableState.finished&&this.destroy()}function duplexOnError(e){this.removeListener("error",duplexOnError),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}Re=function(s,a){let c=!0;const l=new t({...a,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return s.on("message",function(e,t){const a=!t&&l._readableState.objectMode?e.toString():e;l.push(a)||s.pause()}),s.once("error",function(e){l.destroyed||(c=!1,l.destroy(e))}),s.once("close",function(){l.destroyed||l.push(null)}),l._destroy=function(t,a){if(s.readyState===s.CLOSED)return a(t),void e.nextTick(emitClose,l);let d=!1;s.once("error",function(e){d=!0,a(e)}),s.once("close",function(){d||a(t),e.nextTick(emitClose,l)}),c&&s.terminate()},l._final=function(e){s.readyState!==s.CONNECTING?null!==s._socket&&(s._socket._writableState.finished?(e(),l._readableState.endEmitted&&l.destroy()):(s._socket.once("finish",function(){e()}),s.close())):s.once("open",function(){l._final(e)})},l._read=function(){s.isPaused&&s.resume()},l._write=function(e,t,a){s.readyState!==s.CONNECTING?s.send(e,a):s.once("open",function(){l._write(e,t,a)})},l.on("end",duplexOnEnd),l.on("error",duplexOnError),l}}(),requireReceiver(),requireSender(),requireWebsocket();var Ne=function(){if(Pe)return Ae;Pe=1;const t=u,s=m,{Duplex:a}=h,{createHash:c}=g,l=requireExtension(),d=requirePermessageDeflate(),f=requireSubprotocol(),_=requireWebsocket(),{GUID:S,kWebSocket:E}=requireConstants(),k=/^[+/0-9A-Za-z]{22}==$/;function emitClose(e){e._state=2,e.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(e,t,a,c){a=a||s.STATUS_CODES[t],c={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(a),...c},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${s.STATUS_CODES[t]}\r\n`+Object.keys(c).map(e=>`${e}: ${c[e]}`).join("\r\n")+"\r\n\r\n"+a)}function abortHandshakeOrEmitwsClientError(e,t,s,a,c){if(e.listenerCount("wsClientError")){const a=new Error(c);Error.captureStackTrace(a,abortHandshakeOrEmitwsClientError),e.emit("wsClientError",a,s,t)}else abortHandshake(s,a,c)}return Ae=class extends t{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:_,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=s.createServer((e,t)=>{const a=s.STATUS_CODES[426];t.writeHead(426,{"Content-Length":a.length,"Content-Type":"text/plain"}),t.end(a)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const s of Object.keys(t))e.on(s,t[s]);return function(){for(const s of Object.keys(t))e.removeListener(s,t[s])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,s,a)=>{this.handleUpgrade(t,s,a,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(2===this._state)return t&&this.once("close",()=>{t(new Error("The server is not running"))}),void e.nextTick(emitClose,this);if(t&&this.once("close",t),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:e.nextTick(emitClose,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{emitClose(this)})}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,s,a){t.on("error",socketOnError);const c=e.headers["sec-websocket-key"],h=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void abortHandshakeOrEmitwsClientError(this,e,t,405,"Invalid HTTP method")}if(void 0===h||"websocket"!==h.toLowerCase()){return void abortHandshakeOrEmitwsClientError(this,e,t,400,"Invalid Upgrade header")}if(void 0===c||!k.test(c)){return void abortHandshakeOrEmitwsClientError(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==u&&13!==u){return void abortHandshakeOrEmitwsClientError(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void abortHandshake(t,400);const m=e.headers["sec-websocket-protocol"];let g=new Set;if(void 0!==m)try{g=f.parse(m)}catch(s){return void abortHandshakeOrEmitwsClientError(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const _=e.headers["sec-websocket-extensions"],S={};if(this.options.perMessageDeflate&&void 0!==_){const s=new d(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=l.parse(_);e[d.extensionName]&&(s.accept(e[d.extensionName]),S[d.extensionName]=s)}catch(s){return void abortHandshakeOrEmitwsClientError(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const l={origin:e.headers[""+(8===u?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(l,(l,d,h,u)=>{if(!l)return abortHandshake(t,d||401,h,u);this.completeUpgrade(S,c,g,e,t,s,a)});if(!this.options.verifyClient(l))return abortHandshake(t,401)}this.completeUpgrade(S,c,g,e,t,s,a)}completeUpgrade(t,s,a,h,u,f,m){if(!u.readable||!u.writable)return u.destroy();if(u[E])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return abortHandshake(u,503);const g=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${c("sha1").update(s+S).digest("base64")}`],_=new this.options.WebSocket(null,void 0,this.options);if(a.size){const e=this.options.handleProtocols?this.options.handleProtocols(a,h):a.values().next().value;e&&(g.push(`Sec-WebSocket-Protocol: ${e}`),_._protocol=e)}if(t[d.extensionName]){const e=t[d.extensionName].params,s=l.format({[d.extensionName]:[e]});g.push(`Sec-WebSocket-Extensions: ${s}`),_._extensions=t}this.emit("headers",g,h),u.write(g.concat("\r\n").join("\r\n")),u.removeListener("error",socketOnError),_.setSocket(u,f,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(_),_.on("close",()=>{this.clients.delete(_),this._shouldEmitClose&&!this.clients.size&&e.nextTick(emitClose,this)})),m(_,h)}},Ae}();const je=getDefaultExportFromCjs(Ne),nodeAdapter=(e={})=>{const t=new AdapterHookable(e),s=new Set,a=e.wss||new je({noServer:!0,...e.serverOptions});return a.on("connection",(e,a)=>{const c=new NodeReqProxy(a),l=new NodePeer({ws:e,request:c,peers:s,nodeReq:a});s.add(l),t.callHook("open",l),e.on("message",e=>{Array.isArray(e)&&(e=Buffer.concat(e)),t.callHook("message",l,new Message(e,l))}),e.on("error",e=>{s.delete(l),t.callHook("error",l,new WSError(e))}),e.on("close",(e,a)=>{s.delete(l),t.callHook("close",l,{code:e,reason:a?.toString()})})}),a.on("headers",(e,t)=>{const s=t._upgradeHeaders;if(s)for(const[t,a]of new Headers(s))e.push(`${t}: ${a}`)}),{...adapterUtils(s),handleUpgrade:async(e,s,c)=>{const l=new NodeReqProxy(e),{upgradeHeaders:d,endResponse:h,context:u}=await t.upgrade(l);if(h)return async function(e,t){const s=[`HTTP/1.1 ${t.status||200} ${t.statusText||""}`,...[...t.headers.entries()].map(([e,t])=>`${encodeURIComponent(e)}: ${encodeURIComponent(t)}`)];if(e.write(s.join("\r\n")+"\r\n\r\n"),t.body)for await(const s of t.body)e.write(s);return new Promise(t=>{e.end(()=>{e.destroy(),t()})})}(s,h);e._request=l,e._upgradeHeaders=d,e._context=u,a.handleUpgrade(e,s,c,t=>{a.emit("connection",t,e)})},closeAll:(e,t,s)=>{for(const c of a.clients)s?c.terminate():c.close(e,t)}}};class NodePeer extends Peer{get remoteAddress(){return this._internal.nodeReq.socket?.remoteAddress}get context(){return this._internal.nodeReq._context}send(e,t){const s=toBufferLike(e),a="string"!=typeof s;return this._internal.ws.send(s,{compress:t?.compress,binary:a,...t}),0}publish(e,t,s){const a=toBufferLike(t),c="string"!=typeof t,l={compress:s?.compress,binary:c,...s};for(const t of this._internal.peers)t!==this&&t._topics.has(e)&&t._internal.ws.send(a,l)}close(e,t){this._internal.ws.close(e,t)}terminate(){this._internal.ws.terminate()}}class NodeReqProxy{_req;_headers;_url;constructor(e){this._req=e}get url(){if(!this._url){const e=this._req,t=e.headers.host||"localhost",s=e.socket?.encrypted??"https"===e.headers["x-forwarded-proto"];this._url=`${s?"https":"http"}://${t}${e.url}`}return this._url}get headers(){return this._headers||(this._headers=new Headers(this._req.headers)),this._headers}}const He=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,We=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,Le=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function jsonParseTransform(e,t){if(!("__proto__"===e||"constructor"===e&&t&&"object"==typeof t&&"prototype"in t))return t;!function(e){console.warn(`[destr] Dropping "${e}" key to prevent prototype pollution.`)}(e)}function destr(e,t={}){if("string"!=typeof e)return e;if('"'===e[0]&&'"'===e[e.length-1]&&-1===e.indexOf("\\"))return e.slice(1,-1);const s=e.trim();if(s.length<=9)switch(s.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!Le.test(e)){if(t.strict)throw new SyntaxError("[destr] Invalid JSON");return e}try{if(He.test(e)||We.test(e)){if(t.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(e,jsonParseTransform)}return JSON.parse(e)}catch(s){if(t.strict)throw s;return e}}const De=/#/g,Be=/&/g,Me=/\//g,Ue=/=/g,qe=/\+/g,ze=/%5e/gi,Fe=/%60/gi,$e=/%7c/gi,Ke=/%20/gi,Ge=/%2f/gi;function encodeQueryValue(e){return(t="string"==typeof e?e:JSON.stringify(e),encodeURI(""+t).replace($e,"|")).replace(qe,"%2B").replace(Ke,"+").replace(De,"%23").replace(Be,"%26").replace(Fe,"`").replace(ze,"^").replace(Me,"%2F");var t}function encodeQueryKey(e){return encodeQueryValue(e).replace(Ue,"%3D")}function decode(e=""){try{return decodeURIComponent(""+e)}catch{return""+e}}function decodePath(e){return decode(e.replace(Ge,"%252F"))}function decodeQueryKey(e){return decode(e.replace(qe," "))}function decodeQueryValue(e){return decode(e.replace(qe," "))}function parseQuery(e=""){const t=Object.create(null);"?"===e[0]&&(e=e.slice(1));for(const s of e.split("&")){const e=s.match(/([^=]+)=?(.*)/)||[];if(e.length<2)continue;const a=decodeQueryKey(e[1]);if("__proto__"===a||"constructor"===a)continue;const c=decodeQueryValue(e[2]||"");void 0===t[a]?t[a]=c:Array.isArray(t[a])?t[a].push(c):t[a]=[t[a],c]}return t}function stringifyQuery(e){return Object.keys(e).filter(t=>void 0!==e[t]).map(t=>function(e,t){return"number"!=typeof t&&"boolean"!=typeof t||(t=String(t)),t?Array.isArray(t)?t.map(t=>`${encodeQueryKey(e)}=${encodeQueryValue(t)}`).join("&"):`${encodeQueryKey(e)}=${encodeQueryValue(t)}`:encodeQueryKey(e)}(t,e[t])).filter(Boolean).join("&")}const Ve=/^[\s\w\0+.-]{2,}:([/\\]{1,2})/,Ze=/^[\s\w\0+.-]{2,}:([/\\]{2})?/,Je=/^([/\\]\s*){2,}[^/\\]/,Qe=/^\.?\//;function hasProtocol(e,t={}){return"boolean"==typeof t&&(t={acceptRelative:t}),t.strict?Ve.test(e):Ze.test(e)||!!t.acceptRelative&&Je.test(e)}function withoutTrailingSlash(e="",t){return(function(e=""){return e.endsWith("/")}(e)?e.slice(0,-1):e)||"/"}function withTrailingSlash(e="",t){return e.endsWith("/")?e:e+"/"}function withLeadingSlash(e=""){return function(e=""){return e.startsWith("/")}(e)?e:"/"+e}function withoutBase(e,t){if(isEmptyURL(t))return e;const s=withoutTrailingSlash(t);if(!e.startsWith(s))return e;const a=e[s.length];if(a&&"/"!==a&&"?"!==a)return e;const c=e.slice(s.length);return"/"===c[0]?c:"/"+c}function withQuery(e,t){const s=parseURL(e),a={...parseQuery(s.search),...t};return s.search=stringifyQuery(a),function(e){const t=e.pathname||"",s=e.search?(e.search.startsWith("?")?"":"?")+e.search:"",a=e.hash||"",c=e.auth?e.auth+"@":"",l=e.host||"",d=e.protocol||e[Xe]?(e.protocol||"")+"//":"";return d+c+l+t+s+a}(s)}function getQuery$1(e){return parseQuery(parseURL(e).search)}function isEmptyURL(e){return!e||"/"===e}function joinURL(e,...t){let s=e||"";for(const e of t.filter(e=>function(e){return e&&"/"!==e}(e)))if(s){const t=e.replace(Qe,"");s=withTrailingSlash(s)+t}else s=e;return s}function joinRelativeURL(...e){const t=/\/(?!\/)/,s=e.filter(Boolean),a=[];let c=0;for(const e of s)if(e&&"/"!==e)for(const[s,l]of e.split(t).entries())if(l&&"."!==l)if(".."!==l)1===s&&a[a.length-1]?.endsWith(":/")?a[a.length-1]+="/"+l:(a.push(l),c++);else{if(1===a.length&&hasProtocol(a[0]))continue;a.pop(),c--}let l=a.join("/");return c>=0?s[0]?.startsWith("/")&&!l.startsWith("/")?l="/"+l:s[0]?.startsWith("./")&&!l.startsWith("./")&&(l="./"+l):l="../".repeat(-1*c)+l,s[s.length-1]?.endsWith("/")&&!l.endsWith("/")&&(l+="/"),l}const Xe=Symbol.for("ufo:protocolRelative");function parseURL(e="",t){const s=e.match(/^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i);if(s){const[,e,t=""]=s;return{protocol:e.toLowerCase(),pathname:t,href:e+t,auth:"",host:"",search:"",hash:""}}if(!hasProtocol(e,{acceptRelative:!0}))return parsePath(e);const[,a="",c,l=""]=e.replace(/\\/g,"/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/)||[];let[,d="",h=""]=l.match(/([^#/?]*)(.*)?/)||[];"file:"===a&&(h=h.replace(/\/(?=[A-Za-z]:)/,""));const{pathname:u,search:f,hash:m}=parsePath(h);return{protocol:a.toLowerCase(),auth:c?c.slice(0,Math.max(0,c.length-1)):"",host:d,pathname:u,search:f,hash:m,[Xe]:!a}}function parsePath(e=""){const[t="",s="",a=""]=(e.match(/([^#?]*)(\?[^#]*)?(#.*)?/)||[]).splice(1);return{pathname:t,search:s,hash:a}}const Ye=0,et=1,tt=2;function createRouter$1(e={}){const t={options:e,rootNode:createRadixNode(),staticRoutesMap:{}},normalizeTrailingSlash=t=>e.strictTrailingSlash?t:t.replace(/\/$/,"")||"/";if(e.routes)for(const s in e.routes)insert(t,normalizeTrailingSlash(s),e.routes[s]);return{ctx:t,lookup:e=>function(e,t){const s=e.staticRoutesMap[t];if(s)return s.data;const a=t.split("/"),c={};let l=!1,d=null,h=e.rootNode,u=null;for(let e=0;e<a.length;e++){const t=a[e];null!==h.wildcardChildNode&&(d=h.wildcardChildNode,u=a.slice(e).join("/"));const s=h.children.get(t);if(void 0===s){if(h&&h.placeholderChildren.length>1){const t=a.length-e;h=h.placeholderChildren.find(e=>e.maxDepth===t)||null}else h=h.placeholderChildren[0]||null;if(!h)break;h.paramName&&(c[h.paramName]=t),l=!0}else h=s}null!==h&&null!==h.data||null===d||(h=d,c[h.paramName||"_"]=u,l=!0);if(!h)return null;if(l)return{...h.data,params:l?c:void 0};return h.data}(t,normalizeTrailingSlash(e)),insert:(e,s)=>insert(t,normalizeTrailingSlash(e),s),remove:e=>function(e,t){let s=!1;const a=t.split("/");let c=e.rootNode;for(const e of a)if(c=c.children.get(e),!c)return s;if(c.data){const e=a.at(-1)||"";c.data=null,0===Object.keys(c.children).length&&c.parent&&(c.parent.children.delete(e),c.parent.wildcardChildNode=null,c.parent.placeholderChildren=[]),s=!0}return s}(t,normalizeTrailingSlash(e))}}function insert(e,t,s){let a=!0;const c=t.split("/");let l=e.rootNode,d=0;const h=[l];for(const e of c){let t;if(t=l.children.get(e))l=t;else{const s=getNodeType(e);t=createRadixNode({type:s,parent:l}),l.children.set(e,t),s===tt?(t.paramName="*"===e?"_"+d++:e.slice(1),l.placeholderChildren.push(t),a=!1):s===et&&(l.wildcardChildNode=t,t.paramName=e.slice(3)||"_",a=!1),h.push(t),l=t}}for(const[e,t]of h.entries())t.maxDepth=Math.max(h.length-e,t.maxDepth||0);return l.data=s,!0===a&&(e.staticRoutesMap[t]=l),l}function createRadixNode(e={}){return{type:e.type||Ye,maxDepth:0,parent:e.parent||null,children:new Map,data:e.data||null,paramName:e.paramName||null,wildcardChildNode:null,placeholderChildren:[]}}function getNodeType(e){return e.startsWith("**")?et:":"===e[0]||"*"===e?tt:Ye}function toRouteMatcher(e){return function(e,t){return{ctx:{table:e},matchAll:s=>_matchRoutes(s,e,t)}}(_routerNodeToTable("",e.ctx.rootNode),e.ctx.options.strictTrailingSlash)}function _matchRoutes(e,t,s){!0!==s&&e.endsWith("/")&&(e=e.slice(0,-1)||"/");const a=[];for(const[s,c]of _sortRoutesMap(t.wildcard))(e===s||e.startsWith(s+"/"))&&a.push(c);for(const[s,c]of _sortRoutesMap(t.dynamic))if(e.startsWith(s+"/")){const t="/"+e.slice(s.length).split("/").splice(2).join("/");a.push(..._matchRoutes(t,c))}const c=t.static.get(e);return c&&a.push(c),a.filter(Boolean)}function _sortRoutesMap(e){return[...e.entries()].sort((e,t)=>e[0].length-t[0].length)}function _routerNodeToTable(e,t){const s={static:new Map,wildcard:new Map,dynamic:new Map};return function _addNode(e,t){if(e)if(t.type!==Ye||e.includes("*")||e.includes(":")){if(t.type===et)s.wildcard.set(e.replace("/**",""),t.data);else if(t.type===tt){const a=_routerNodeToTable("",t);return t.data&&a.static.set("/",t.data),void s.dynamic.set(e.replace(/\/\*|\/:\w+/,""),a)}}else t.data&&s.static.set(e,t.data);for(const[s,a]of t.children.entries())_addNode(`${e}/${s}`.replace("//","/"),a)}(e,t),s}function isPlainObject(e){if(null===e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&(!(Symbol.iterator in e)&&(!(Symbol.toStringTag in e)||"[object Module]"===Object.prototype.toString.call(e)))}function _defu(e,t,s=".",a){if(!isPlainObject(t))return _defu(e,{},s,a);const c=Object.assign({},t);for(const t in e){if("__proto__"===t||"constructor"===t)continue;const l=e[t];null!=l&&(a&&a(c,t,l,s)||(Array.isArray(l)&&Array.isArray(c[t])?c[t]=[...l,...c[t]]:isPlainObject(l)&&isPlainObject(c[t])?c[t]=_defu(l,c[t],(s?`${s}.`:"")+t.toString(),a):c[t]=l))}return c}function createDefu(e){return(...t)=>t.reduce((t,s)=>_defu(t,s,"",e),{})}const rt=createDefu(),st=createDefu((e,t,s)=>{if(void 0!==e[t]&&"function"==typeof s)return e[t]=s(e[t]),!0});function o(e){throw new Error(`${e} is not implemented yet!`)}let nt=class i extends C{__unenv__={};readableEncoding=null;readableEnded=!0;readableFlowing=!1;readableHighWaterMark=0;readableLength=0;readableObjectMode=!1;readableAborted=!1;readableDidRead=!1;closed=!1;errored=null;readable=!1;destroyed=!1;static from(e,t){return new i(t)}constructor(e){super()}_read(e){}read(e){}setEncoding(e){return this}pause(){return this}resume(){return this}isPaused(){return!0}unpipe(e){return this}unshift(e,t){}wrap(e){return this}push(e,t){return!1}_destroy(e,t){this.removeAllListeners()}destroy(e){return this.destroyed=!0,this._destroy(e),this}pipe(e,t){return{}}compose(e,t){throw new Error("Method not implemented.")}[Symbol.asyncDispose](){return this.destroy(),Promise.resolve()}async*[Symbol.asyncIterator](){throw o("Readable.asyncIterator")}iterator(e){throw o("Readable.iterator")}map(e,t){throw o("Readable.map")}filter(e,t){throw o("Readable.filter")}forEach(e,t){throw o("Readable.forEach")}reduce(e,t,s){throw o("Readable.reduce")}find(e,t){throw o("Readable.find")}findIndex(e,t){throw o("Readable.findIndex")}some(e,t){throw o("Readable.some")}toArray(e){throw o("Readable.toArray")}every(e,t){throw o("Readable.every")}flatMap(e,t){throw o("Readable.flatMap")}drop(e,t){throw o("Readable.drop")}take(e,t){throw o("Readable.take")}asIndexedPairs(e){throw o("Readable.asIndexedPairs")}},ot=class extends C{__unenv__={};writable=!0;writableEnded=!1;writableFinished=!1;writableHighWaterMark=0;writableLength=0;writableObjectMode=!1;writableCorked=0;closed=!1;errored=null;writableNeedDrain=!1;writableAborted=!1;destroyed=!1;_data;_encoding="utf8";constructor(e){super()}pipe(e,t){return{}}_write(e,t,s){if(this.writableEnded)s&&s();else{if(void 0===this._data)this._data=e;else{const s="string"==typeof this._data?T.from(this._data,this._encoding||t||"utf8"):this._data,a="string"==typeof e?T.from(e,t||this._encoding||"utf8"):e;this._data=T.concat([s,a])}this._encoding=t,s&&s()}}_writev(e,t){}_destroy(e,t){}_final(e){}write(e,t,s){const a="string"==typeof t?this._encoding:"utf8",c="function"==typeof t?t:"function"==typeof s?s:void 0;return this._write(e,a,c),!0}setDefaultEncoding(e){return this}end(e,t,s){const a="function"==typeof e?e:"function"==typeof t?t:"function"==typeof s?s:void 0;if(this.writableEnded)return a&&a(),this;const c=e===a?void 0:e;if(c){const e=t===a?void 0:t;this.write(c,e,a)}return this.writableEnded=!0,this.writableFinished=!0,this.emit("close"),this.emit("finish"),this}cork(){}uncork(){}destroy(e){return this.destroyed=!0,delete this._data,this.removeAllListeners(),this}compose(e,t){throw new Error("Method not implemented.")}[Symbol.asyncDispose](){return Promise.resolve()}};const it=class{allowHalfOpen=!0;_destroy;constructor(e=new nt,t=new ot){Object.assign(this,e),Object.assign(this,t),this._destroy=function(...e){return function(...t){for(const s of e)s(...t)}}(e._destroy,t._destroy)}};const at=(Object.assign(it.prototype,nt.prototype),Object.assign(it.prototype,ot.prototype),it);class A extends at{__unenv__={};bufferSize=0;bytesRead=0;bytesWritten=0;connecting=!1;destroyed=!1;pending=!1;localAddress="";localPort=0;remoteAddress="";remoteFamily="";remotePort=0;autoSelectFamilyAttemptedAddresses=[];readyState="readOnly";constructor(e){super()}write(e,t,s){return!1}connect(e,t,s){return this}end(e,t,s){return this}setEncoding(e){return this}pause(){return this}resume(){return this}setTimeout(e,t){return this}setNoDelay(e){return this}setKeepAlive(e,t){return this}address(){return{}}unref(){return this}ref(){return this}destroySoon(){this.destroy()}resetAndDestroy(){const e=new Error("ERR_SOCKET_CLOSED");return e.code="ERR_SOCKET_CLOSED",this.destroy(e),this}}class y extends nt{aborted=!1;httpVersion="1.1";httpVersionMajor=1;httpVersionMinor=1;complete=!0;connection;socket;headers={};trailers={};method="GET";url="/";statusCode=200;statusMessage="";closed=!1;errored=null;readable=!1;constructor(e){super(),this.socket=this.connection=e||new A}get rawHeaders(){const e=this.headers,t=[];for(const s in e)if(Array.isArray(e[s]))for(const a of e[s])t.push(s,a);else t.push(s,e[s]);return t}get rawTrailers(){return[]}setTimeout(e,t){return this}get headersDistinct(){return p(this.headers)}get trailersDistinct(){return p(this.trailers)}}function p(e){const t={};for(const[s,a]of Object.entries(e))s&&(t[s]=(Array.isArray(a)?a:[a]).filter(Boolean));return t}class w extends ot{statusCode=200;statusMessage="";upgrading=!1;chunkedEncoding=!1;shouldKeepAlive=!1;useChunkedEncodingByDefault=!1;sendDate=!1;finished=!1;headersSent=!1;strictContentLength=!1;connection=null;socket=null;req;_headers={};constructor(e){super(),this.req=e}assignSocket(e){e._httpMessage=this,this.socket=e,this.connection=e,this.emit("socket",e),this._flush()}_flush(){this.flushHeaders()}detachSocket(e){}writeContinue(e){}writeHead(e,t,s){e&&(this.statusCode=e),"string"==typeof t&&(this.statusMessage=t,t=void 0);const a=s||t;if(a&&!Array.isArray(a))for(const e in a)this.setHeader(e,a[e]);return this.headersSent=!0,this}writeProcessing(){}setTimeout(e,t){return this}appendHeader(e,t){e=e.toLowerCase();const s=this._headers[e],a=[...Array.isArray(s)?s:[s],...Array.isArray(t)?t:[t]].filter(Boolean);return this._headers[e]=a.length>1?a:a[0],this}setHeader(e,t){return this._headers[e.toLowerCase()]=t,this}setHeaders(e){for(const[t,s]of Object.entries(e))this.setHeader(t,s);return this}getHeader(e){return this._headers[e.toLowerCase()]}getHeaders(){return this._headers}getHeaderNames(){return Object.keys(this._headers)}hasHeader(e){return e.toLowerCase()in this._headers}removeHeader(e){delete this._headers[e.toLowerCase()]}addTrailers(e){}flushHeaders(){}writeEarlyHints(e,t){"function"==typeof t&&t()}}const ct=(()=>{const n=function(){};return n.prototype=Object.create(null),n})();function v(e={}){if(e instanceof Headers)return e;const t=new Headers;for(const[s,a]of Object.entries(e))if(void 0!==a){if(Array.isArray(a)){for(const e of a)t.append(s,String(e));continue}t.set(s,String(a))}return t}const lt=new Set([101,204,205,304]);async function b(e,t){const s=new y,a=new w(s);let c;if(s.url=t.url?.toString()||"/",!s.url.startsWith("/")){const e=new URL(s.url);c=e.host,s.url=e.pathname+e.search+e.hash}s.method=t.method||"GET",s.headers=function(e={}){const t=new ct,s=Array.isArray(e)||function(e){return"function"==typeof e?.entries}(e)?e:Object.entries(e);for(const[e,a]of s)if(a){if(void 0===t[e]){t[e]=a;continue}t[e]=[...Array.isArray(t[e])?t[e]:[t[e]],...Array.isArray(a)?a:[a]]}return t}(t.headers||{}),s.headers.host||(s.headers.host=t.host||c||"localhost"),s.connection.encrypted=s.connection.encrypted||"https"===t.protocol,s.body=t.body||null,s.__unenv__=t.context,await e(s,a);let l=a._data;(lt.has(a.statusCode)||"HEAD"===s.method.toUpperCase())&&(l=null,delete a._headers["content-length"]);const d={status:a.statusCode,statusText:a.statusMessage,headers:a._headers,body:l};return s.destroy(),a.destroy(),d}function hasProp(e,t){try{return t in e}catch{return!1}}class H3Error extends Error{static __h3_error__=!0;statusCode=500;fatal=!1;unhandled=!1;statusMessage;data;cause;constructor(e,t={}){super(e,t),t.cause&&!this.cause&&(this.cause=t.cause)}toJSON(){const e={message:this.message,statusCode:sanitizeStatusCode(this.statusCode,500)};return this.statusMessage&&(e.statusMessage=sanitizeStatusMessage(this.statusMessage)),void 0!==this.data&&(e.data=this.data),e}}function createError$1(e){if("string"==typeof e)return new H3Error(e);if(isError(e))return e;const t=new H3Error(e.message??e.statusMessage??"",{cause:e.cause||e});if(hasProp(e,"stack"))try{Object.defineProperty(t,"stack",{get:()=>e.stack})}catch{try{t.stack=e.stack}catch{}}if(e.data&&(t.data=e.data),e.statusCode?t.statusCode=sanitizeStatusCode(e.statusCode,t.statusCode):e.status&&(t.statusCode=sanitizeStatusCode(e.status,t.statusCode)),e.statusMessage?t.statusMessage=e.statusMessage:e.statusText&&(t.statusMessage=e.statusText),t.statusMessage){const e=t.statusMessage;sanitizeStatusMessage(t.statusMessage)!==e&&console.warn("[h3] Please prefer using `message` for longer error messages instead of `statusMessage`. In the future, `statusMessage` will be sanitized by default.")}return void 0!==e.fatal&&(t.fatal=e.fatal),void 0!==e.unhandled&&(t.unhandled=e.unhandled),t}function isError(e){return!0===e?.constructor?.__h3_error__}function process$1(e,t){const s={},a=t.find(e=>"content-disposition"===e[0])?.[1]||"";for(const e of a.split(";")){const t=e.split("=");if(2!==t.length)continue;const a=(t[0]||"").trim();if("name"===a||"filename"===a){const e=(t[1]||"").trim().replace(/"/g,"");s[a]=Buffer.from(e,"latin1").toString("utf8")}}const c=t.find(e=>"content-type"===e[0])?.[1]||"";return c&&(s.type=c),s.data=Buffer.from(e),s}function getQuery(e){return getQuery$1(e.path||"")}function getRouterParam(e,t,s={}){const a=function(e,t={}){let s=e.context.params||{};if(t.decode){s={...s};for(const e in s)s[e]=decode(s[e])}return s}(e,s);return a[t]}function getRequestHeaders(e){const t={};for(const s in e.node.req.headers){const a=e.node.req.headers[s];t[s]=Array.isArray(a)?a.filter(Boolean).join(", "):a}return t}function getRequestHeader(e,t){return getRequestHeaders(e)[t.toLowerCase()]}function getRequestHost(e,t={}){if(t.xForwardedHost){const t=e.node.req.headers["x-forwarded-host"],s=(t||"").split(",").shift()?.trim();if(s)return s}return e.node.req.headers.host||"localhost"}const dt=Symbol.for("h3RawBody"),ht=Symbol.for("h3ParsedBody"),ut=["PATCH","POST","PUT","DELETE"];function readRawBody(e,t="utf8"){!function(e,t){if(!function(e,t){if("string"==typeof t){if(e.method===t)return!0}else if(t.includes(e.method))return!0;return!1}(e,t))throw createError$1({statusCode:405,statusMessage:"HTTP method is not allowed."})}(e,ut);const s=e._requestBody||e.web?.request?.body||e.node.req[dt]||e.node.req.rawBody||e.node.req.body;if(s){const e=Promise.resolve(s).then(e=>Buffer.isBuffer(e)?e:"function"==typeof e.pipeTo?new Promise((t,s)=>{const a=[];e.pipeTo(new WritableStream({write(e){a.push(e)},close(){t(Buffer.concat(a))},abort(e){s(e)}})).catch(s)}):"function"==typeof e.pipe?new Promise((t,s)=>{const a=[];e.on("data",e=>{a.push(e)}).on("end",()=>{t(Buffer.concat(a))}).on("error",s)}):e.constructor===Object?Buffer.from(JSON.stringify(e)):e instanceof URLSearchParams?Buffer.from(e.toString()):e instanceof FormData?new Response(e).bytes().then(e=>Buffer.from(e)):Buffer.from(e));return t?e.then(e=>e.toString(t)):e}if(!Number.parseInt(e.node.req.headers["content-length"]||"")&&!/\bchunked\b/i.test(String(e.node.req.headers["transfer-encoding"]??"")))return Promise.resolve(void 0);const a=e.node.req[dt]=new Promise((t,s)=>{const a=[];e.node.req.on("error",e=>{s(e)}).on("data",e=>{a.push(e)}).on("end",()=>{t(Buffer.concat(a))})});return t?a.then(e=>e.toString(t)):a}async function readBody(e,t={}){const s=e.node.req;if(hasProp(s,ht))return s[ht];const a=s.headers["content-type"]||"",c=await readRawBody(e);let l;return l="application/json"===a?_parseJSON(c,t.strict??!0):a.startsWith("application/x-www-form-urlencoded")?function(e){const t=new URLSearchParams(e),s=Object.create(null);for(const[e,a]of t.entries())hasProp(s,e)?(Array.isArray(s[e])||(s[e]=[s[e]]),s[e].push(a)):s[e]=a;return s}(c):a.startsWith("text/")?c:_parseJSON(c,t.strict??!1),s[ht]=l,l}async function readMultipartFormData(e){const t=getRequestHeader(e,"content-type");if(!t||!t.startsWith("multipart/form-data"))return;const s=t.match(/boundary=([^;]*)(;|$)/i)?.[1];if(!s)return;const a=await readRawBody(e,!1);return a?function(e,t){let s="",a=0,c=[];const l=[];let d=[];for(let h=0;h<e.length;h++){const u=h>0?e[h-1]:null,f=e[h];10===f||13===f||(s+=String.fromCodePoint(f));const m=10===f&&13===u;if(0===a&&m)"--"+t===s&&(a=1),s="";else if(1===a&&m){if(s.length>0){const e=s.indexOf(":");if(e>0){const t=s.slice(0,e).toLowerCase(),a=s.slice(e+1).trim();d.push([t,a])}}else a=2,c=[];s=""}else if(2===a){if(s.length>t.length+4&&(s=""),"--"+t===s){const e=c.length-s.length,t=c.slice(0,e-1);l.push(process$1(t,d)),c=[],d=[],s="",a=3}else c.push(f);m&&(s="")}else 3===a&&m&&(a=1)}return l}(a,s):void 0}function _parseJSON(e="",t){if(e)try{return destr(e,{strict:t})}catch{throw createError$1({statusCode:400,statusMessage:"Bad Request",message:"Invalid JSON body"})}}function handleCacheHeaders(e,t){const s=["public",...t.cacheControls||[]];let a=!1;if(void 0!==t.maxAge&&s.push("max-age="+ +t.maxAge,"s-maxage="+ +t.maxAge),t.modifiedTime){const s=new Date(t.modifiedTime),c=e.node.req.headers["if-modified-since"];e.node.res.setHeader("last-modified",s.toUTCString()),c&&new Date(c)>=s&&(a=!0)}if(t.etag){e.node.res.setHeader("etag",t.etag);e.node.req.headers["if-none-match"]===t.etag&&(a=!0)}return e.node.res.setHeader("cache-control",s.join(", ")),!!a&&(e.node.res.statusCode=304,e.handled||e.node.res.end(),!0)}const ft={html:"text/html",json:"application/json"},pt=/[^\u0009\u0020-\u007E]/g;function sanitizeStatusMessage(e=""){return e.replace(pt,"")}function sanitizeStatusCode(e,t=200){return e?("string"==typeof e&&(e=Number.parseInt(e,10)),e<100||e>999?t:e):t}function splitCookiesString(e){if(Array.isArray(e))return e.flatMap(e=>splitCookiesString(e));if("string"!=typeof e)return[];const t=[];let s,a,c,l,d,h=0;const skipWhitespace=()=>{for(;h<e.length&&/\s/.test(e.charAt(h));)h+=1;return h<e.length},notSpecialChar=()=>(a=e.charAt(h),"="!==a&&";"!==a&&","!==a);for(;h<e.length;){for(s=h,d=!1;skipWhitespace();)if(a=e.charAt(h),","===a){for(c=h,h+=1,skipWhitespace(),l=h;h<e.length&&notSpecialChar();)h+=1;h<e.length&&"="===e.charAt(h)?(d=!0,h=l,t.push(e.slice(s,c)),s=h):h=c+1}else h+=1;(!d||h>=e.length)&&t.push(e.slice(s))}return t}const mt="undefined"==typeof setImmediate?e=>e():setImmediate;function send(e,t,s){return s&&function(e,t){t&&304!==e.node.res.statusCode&&!e.node.res.getHeader("content-type")&&e.node.res.setHeader("content-type",t)}(e,s),new Promise(s=>{mt(()=>{e.handled||e.node.res.end(t),s()})})}function setResponseStatus(e,t,s){t&&(e.node.res.statusCode=sanitizeStatusCode(t,e.node.res.statusCode)),s&&(e.node.res.statusMessage=sanitizeStatusMessage(s))}function getResponseStatus(e){return e.node.res.statusCode}function getResponseStatusText(e){return e.node.res.statusMessage}function getResponseHeader(e,t){return e.node.res.getHeader(t)}function setResponseHeaders(e,t){for(const[s,a]of Object.entries(t))e.node.res.setHeader(s,a)}const yt=setResponseHeaders;function setResponseHeader(e,t,s){e.node.res.setHeader(t,s)}const gt=setResponseHeader;function appendResponseHeader(e,t,s){let a=e.node.res.getHeader(t);a?(Array.isArray(a)||(a=[a.toString()]),e.node.res.setHeader(t,[...a,s])):e.node.res.setHeader(t,s)}function sendStream(e,t){if(!t||"object"!=typeof t)throw new Error("[h3] Invalid stream provided.");if(e.node.res._data=t,!e.node.res.socket)return e._handled=!0,Promise.resolve();if(hasProp(t,"pipeTo")&&"function"==typeof t.pipeTo)return t.pipeTo(new WritableStream({write(t){e.node.res.write(t)}})).then(()=>{e.node.res.end()});if(hasProp(t,"pipe")&&"function"==typeof t.pipe)return new Promise((s,a)=>{t.pipe(e.node.res),t.on&&(t.on("end",()=>{e.node.res.end(),s()}),t.on("error",e=>{a(e)})),e.node.res.on("close",()=>{t.abort&&t.abort()})});throw new Error("[h3] Invalid or incompatible stream provided.")}function sendWebResponse(e,t){for(const[s,a]of t.headers)"set-cookie"===s?e.node.res.appendHeader(s,splitCookiesString(a)):e.node.res.setHeader(s,a);if(t.status&&(e.node.res.statusCode=sanitizeStatusCode(t.status,e.node.res.statusCode)),t.statusText&&(e.node.res.statusMessage=sanitizeStatusMessage(t.statusText)),t.redirected&&e.node.res.setHeader("location",t.url),t.body)return sendStream(e,t.body);e.node.res.end()}const _t=new Set(["PATCH","POST","PUT","DELETE"]),wt=new Set(["transfer-encoding","accept-encoding","connection","keep-alive","upgrade","expect","host","accept"]);async function proxyRequest(e,t,s={}){let a,c;_t.has(e.method)&&(s.streamRequest?(a=function(e){if(!ut.includes(e.method))return;const t=e.web?.request?.body||e._requestBody;return t||(dt in e.node.req||"rawBody"in e.node.req||"body"in e.node.req||"__unenv__"in e.node.req?new ReadableStream({async start(t){const s=await readRawBody(e,!1);s&&t.enqueue(s),t.close()}}):new ReadableStream({start:t=>{e.node.req.on("data",e=>{t.enqueue(e)}),e.node.req.on("end",()=>{t.close()}),e.node.req.on("error",e=>{t.error(e)})}}))}(e),c="half"):a=await readRawBody(e,!1).catch(()=>{}));const l=s.fetchOptions?.method||e.method,d=function(e,...t){const s=t.filter(Boolean);if(0===s.length)return e;const a=new Headers(e);for(const e of s){const t=Array.isArray(e)?e:"function"==typeof e.entries?e.entries():Object.entries(e);for(const[e,s]of t)void 0!==s&&a.set(e,s)}return a}(getProxyRequestHeaders(e,{host:t.startsWith("/")}),s.fetchOptions?.headers,s.headers);return async function(e,t,s={}){let a;try{a=await _getFetch(s.fetch)(t,{headers:s.headers,ignoreResponseError:!0,...s.fetchOptions})}catch(e){throw createError$1({status:502,statusMessage:"Bad Gateway",cause:e})}e.node.res.statusCode=sanitizeStatusCode(a.status,e.node.res.statusCode),e.node.res.statusMessage=sanitizeStatusMessage(a.statusText);const c=[];for(const[t,s]of a.headers.entries())"content-encoding"!==t&&"content-length"!==t&&("set-cookie"!==t?e.node.res.setHeader(t,s):c.push(...splitCookiesString(s)));c.length>0&&e.node.res.setHeader("set-cookie",c.map(e=>(s.cookieDomainRewrite&&(e=rewriteCookieProperty(e,s.cookieDomainRewrite,"domain")),s.cookiePathRewrite&&(e=rewriteCookieProperty(e,s.cookiePathRewrite,"path")),e)));s.onResponse&&await s.onResponse(e,a);if(void 0!==a._data)return a._data;if(e.handled)return;if(!1===s.sendStream){const t=new Uint8Array(await a.arrayBuffer());return e.node.res.end(t)}if(a.body)for await(const t of a.body)e.node.res.write(t);return e.node.res.end()}(e,t,{...s,fetchOptions:{method:l,body:a,duplex:c,...s.fetchOptions,headers:d}})}function getProxyRequestHeaders(e,t){const s=Object.create(null),a=getRequestHeaders(e);for(const e in a)(!wt.has(e)||"host"===e&&t?.host)&&(s[e]=a[e]);return s}function fetchWithEvent(e,t,s,a){return _getFetch(a?.fetch)(t,{...s,context:s?.context||e.context,headers:{...getProxyRequestHeaders(e,{host:"string"==typeof t&&t.startsWith("/")}),...s?.headers}})}function _getFetch(e){if(e)return e;if(globalThis.fetch)return globalThis.fetch;throw new Error("fetch is not available. Try importing `node-fetch-native/polyfill` for Node.js.")}function rewriteCookieProperty(e,t,s){const a="string"==typeof t?{"*":t}:t;return e.replace(new RegExp(`(;\\s*${s}=)([^;]+)`,"gi"),(e,t,s)=>{let c;if(s in a)c=a[s];else{if(!("*"in a))return e;c=a["*"]}return c?t+c:""})}function defineWebSocketHandler(e){return defineEventHandler({handler(){throw createError$1({statusCode:426,statusMessage:"Upgrade Required"})},websocket:e})}class H3Event{__is_event__=!0;node;web;context={};_method;_path;_headers;_requestBody;_handled=!1;_onBeforeResponseCalled;_onAfterResponseCalled;constructor(e,t){this.node={req:e,res:t}}get method(){return this._method||(this._method=(this.node.req.method||"GET").toUpperCase()),this._method}get path(){return this._path||this.node.req.url||"/"}get headers(){return this._headers||(this._headers=function(e){const t=new Headers;for(const[s,a]of Object.entries(e))if(Array.isArray(a))for(const e of a)t.append(s,e);else a&&t.set(s,a);return t}(this.node.req.headers)),this._headers}get handled(){return this._handled||this.node.res.writableEnded||this.node.res.headersSent}respondWith(e){return Promise.resolve(e).then(e=>sendWebResponse(this,e))}toString(){return`[${this.method}] ${this.path}`}toJSON(){return this.toString()}get req(){return this.node.req}get res(){return this.node.res}}function isEvent(e){return hasProp(e,"__is_event__")}function createEvent(e,t){return new H3Event(e,t)}function defineEventHandler(e){if("function"==typeof e)return e.__is_handler__=!0,e;const t={onRequest:_normalizeArray(e.onRequest),onBeforeResponse:_normalizeArray(e.onBeforeResponse)},_handler=s=>async function(e,t,s){if(s.onRequest)for(const t of s.onRequest)if(await t(e),e.handled)return;const a=await t(e),c={body:a};if(s.onBeforeResponse)for(const t of s.onBeforeResponse)await t(e,c);return c.body}(s,e.handler,t);return _handler.__is_handler__=!0,_handler.__resolve__=e.handler.__resolve__,_handler.__websocket__=e.websocket,_handler}function _normalizeArray(e){return e?Array.isArray(e)?e:[e]:void 0}const bt=defineEventHandler;function isEventHandler(e){return hasProp(e,"__is_handler__")}function toEventHandler(e,t,s){return isEventHandler(e)||console.warn("[h3] Implicit event handler conversion is deprecated. Use `eventHandler()` or `fromNodeMiddleware()` to define event handlers.",s&&"/"!==s?`\n Route: ${s}`:"",`\n Handler: ${e}`),e}const lazyEventHandler=function(e){let t,s;const resolveHandler=()=>s?Promise.resolve(s):(t||(t=Promise.resolve(e()).then(e=>{const t=e.default||e;if("function"!=typeof t)throw new TypeError("Invalid lazy handler result. It should be a function:",t);return s={handler:toEventHandler(e.default||e)},s})),t),a=bt(e=>s?s.handler(e):resolveHandler().then(t=>t.handler(e)));return a.__resolve__=resolveHandler,a};function createApp(e={}){const t=[],s=function(e,t){const s=t.debug?2:void 0;return bt(async a=>{a.node.req.originalUrl=a.node.req.originalUrl||a.node.req.url||"/";const c=a._path||a.node.req.url||"/";let l;t.onRequest&&await t.onRequest(a);for(const d of e){if(d.route.length>1){if(!c.startsWith(d.route))continue;l=c.slice(d.route.length)||"/"}else l=c;if(d.match&&!d.match(l,a))continue;a._path=l,a.node.req.url=l;const e=await d.handler(a),h=void 0===e?void 0:await e;if(void 0!==h){const e={body:h};return t.onBeforeResponse&&(a._onBeforeResponseCalled=!0,await t.onBeforeResponse(a,e)),await handleHandlerResponse(a,e.body,s),void(t.onAfterResponse&&(a._onAfterResponseCalled=!0,await t.onAfterResponse(a,e)))}if(a.handled)return void(t.onAfterResponse&&(a._onAfterResponseCalled=!0,await t.onAfterResponse(a,void 0)))}if(!a.handled)throw createError$1({statusCode:404,statusMessage:`Cannot find any path matching ${a.path||"/"}.`});t.onAfterResponse&&(a._onAfterResponseCalled=!0,await t.onAfterResponse(a,void 0))})}(t,e),a=function(e){return async t=>{let s;for(const a of e){if("/"===a.route&&!a.handler.__resolve__)continue;if(!t.startsWith(a.route))continue;if(s=t.slice(a.route.length)||"/",a.match&&!a.match(s,void 0))continue;let e={route:a.route,handler:a.handler};if(e.handler.__resolve__){const t=await e.handler.__resolve__(s);if(!t)continue;e={...e,...t,route:joinURL(e.route||"/",t.route||"/")}}return e}}}(t);s.__resolve__=a;const c=function(e){let t;return()=>(t||(t=e()),t)}(()=>{return t=a,{...e.websocket,async resolve(e){const s=e.request?.url||e.url||"/",{pathname:a}="string"==typeof s?parseURL(s):s,c=await t(a);return c?.handler?.__websocket__||{}}};var t}),l={use:(e,t,s)=>use(l,e,t,s),resolve:a,handler:s,stack:t,options:e,get websocket(){return c()}};return l}function use(e,t,s,a){if(Array.isArray(t))for(const c of t)use(e,c,s,a);else if(Array.isArray(s))for(const c of s)use(e,t,c,a);else"string"==typeof t?e.stack.push(normalizeLayer({...a,route:t,handler:s})):"function"==typeof t?e.stack.push(normalizeLayer({...s,handler:t})):e.stack.push(normalizeLayer({...t}));return e}function normalizeLayer(e){let t=e.handler;return t.handler&&(t=t.handler),e.lazy?t=lazyEventHandler(t):isEventHandler(t)||(t=toEventHandler(t,0,e.route)),{route:withoutTrailingSlash(e.route),match:e.match,handler:t}}function handleHandlerResponse(e,t,s){if(null===t)return function(e,t){if(e.handled)return;t||200===e.node.res.statusCode||(t=e.node.res.statusCode);const s=sanitizeStatusCode(t,204);204===s&&e.node.res.removeHeader("content-length"),e.node.res.writeHead(s),e.node.res.end()}(e);if(t){if(a=t,"undefined"!=typeof Response&&a instanceof Response)return sendWebResponse(e,t);if(function(e){if(!e||"object"!=typeof e)return!1;if("function"==typeof e.pipe){if("function"==typeof e._read)return!0;if("function"==typeof e.abort)return!0}return"function"==typeof e.pipeTo}(t))return sendStream(e,t);if(t.buffer)return send(e,t);if(t.arrayBuffer&&"function"==typeof t.arrayBuffer)return t.arrayBuffer().then(s=>send(e,Buffer.from(s),t.type));if(t instanceof Error)throw createError$1(t);if("function"==typeof t.end)return!0}var a;const c=typeof t;if("string"===c)return send(e,t,ft.html);if("object"===c||"boolean"===c||"number"===c)return send(e,JSON.stringify(t,void 0,s),ft.json);if("bigint"===c)return send(e,t.toString(),ft.json);throw createError$1({statusCode:500,statusMessage:`[h3] Cannot send ${c} as response.`})}const vt=["connect","delete","get","head","options","post","put","trace","patch"];function toNodeListener(e){return async function(t,s){const a=createEvent(t,s);try{await e.handler(a)}catch(t){const s=createError$1(t);if(isError(t)||(s.unhandled=!0),setResponseStatus(a,s.statusCode,s.statusMessage),e.options.onError&&await e.options.onError(s,a),a.handled)return;(s.unhandled||s.fatal)&&console.error("[h3]",s.fatal?"[fatal]":"[unhandled]",s),e.options.onBeforeResponse&&!a._onBeforeResponseCalled&&await e.options.onBeforeResponse(a,{body:s}),await function(e,t,s){if(e.handled)return;const a=isError(t)?t:createError$1(t),c={statusCode:a.statusCode,statusMessage:a.statusMessage,stack:[],data:a.data};if(s&&(c.stack=(a.stack||"").split("\n").map(e=>e.trim())),e.handled)return;setResponseStatus(e,Number.parseInt(a.statusCode),a.statusMessage),e.node.res.setHeader("content-type",ft.json),e.node.res.end(JSON.stringify(c,void 0,2))}(a,s,!!e.options.debug),e.options.onAfterResponse&&!a._onAfterResponseCalled&&await e.options.onAfterResponse(a,{body:s})}}}function flatHooks(e,t={},s){for(const a in e){const c=e[a],l=s?`${s}:${a}`:a;"object"==typeof c&&null!==c?flatHooks(c,t,l):"function"==typeof c&&(t[l]=c)}return t}const St={run:e=>e()},Et=void 0!==console.createTask?console.createTask:()=>St;function serialTaskCaller(e,t){const s=t.shift(),a=Et(s);return e.reduce((e,s)=>e.then(()=>a.run(()=>s(...t))),Promise.resolve())}function parallelTaskCaller(e,t){const s=t.shift(),a=Et(s);return Promise.all(e.map(e=>a.run(()=>e(...t))))}function callEachWith(e,t){for(const s of[...e])s(t)}class Hookable{constructor(){this._hooks={},this._before=void 0,this._after=void 0,this._deprecatedMessages=void 0,this._deprecatedHooks={},this.hook=this.hook.bind(this),this.callHook=this.callHook.bind(this),this.callHookWith=this.callHookWith.bind(this)}hook(e,t,s={}){if(!e||"function"!=typeof t)return()=>{};const a=e;let c;for(;this._deprecatedHooks[e];)c=this._deprecatedHooks[e],e=c.to;if(c&&!s.allowDeprecated){let e=c.message;e||(e=`${a} hook has been deprecated`+(c.to?`, please use ${c.to}`:"")),this._deprecatedMessages||(this._deprecatedMessages=new Set),this._deprecatedMessages.has(e)||(console.warn(e),this._deprecatedMessages.add(e))}if(!t.name)try{Object.defineProperty(t,"name",{get:()=>"_"+e.replace(/\W+/g,"_")+"_hook_cb",configurable:!0})}catch{}return this._hooks[e]=this._hooks[e]||[],this._hooks[e].push(t),()=>{t&&(this.removeHook(e,t),t=void 0)}}hookOnce(e,t){let s,_function=(...e)=>("function"==typeof s&&s(),s=void 0,_function=void 0,t(...e));return s=this.hook(e,_function),s}removeHook(e,t){if(this._hooks[e]){const s=this._hooks[e].indexOf(t);-1!==s&&this._hooks[e].splice(s,1),0===this._hooks[e].length&&delete this._hooks[e]}}deprecateHook(e,t){this._deprecatedHooks[e]="string"==typeof t?{to:t}:t;const s=this._hooks[e]||[];delete this._hooks[e];for(const t of s)this.hook(e,t)}deprecateHooks(e){Object.assign(this._deprecatedHooks,e);for(const t in e)this.deprecateHook(t,e[t])}addHooks(e){const t=flatHooks(e),s=Object.keys(t).map(e=>this.hook(e,t[e]));return()=>{for(const e of s.splice(0,s.length))e()}}removeHooks(e){const t=flatHooks(e);for(const e in t)this.removeHook(e,t[e])}removeAllHooks(){for(const e in this._hooks)delete this._hooks[e]}callHook(e,...t){return t.unshift(e),this.callHookWith(serialTaskCaller,e,...t)}callHookParallel(e,...t){return t.unshift(e),this.callHookWith(parallelTaskCaller,e,...t)}callHookWith(e,t,...s){const a=this._before||this._after?{name:t,args:s,context:{}}:void 0;this._before&&callEachWith(this._before,a);const c=e(t in this._hooks?[...this._hooks[t]]:[],s);return c instanceof Promise?c.finally(()=>{this._after&&a&&callEachWith(this._after,a)}):(this._after&&a&&callEachWith(this._after,a),c)}beforeEach(e){return this._before=this._before||[],this._before.push(e),()=>{if(void 0!==this._before){const t=this._before.indexOf(e);-1!==t&&this._before.splice(t,1)}}}afterEach(e){return this._after=this._after||[],this._after.push(e),()=>{if(void 0!==this._after){const t=this._after.indexOf(e);-1!==t&&this._after.splice(t,1)}}}}const kt=globalThis.Headers,xt=globalThis.AbortController,Rt=globalThis.fetch||(()=>{throw new Error("[node-fetch-native] Failed to fetch: `globalThis.fetch` is not available!")});class FetchError extends Error{constructor(e,t){super(e,t),this.name="FetchError",t?.cause&&!this.cause&&(this.cause=t.cause)}}const Ct=new Set(Object.freeze(["PATCH","POST","PUT","DELETE"]));function isPayloadMethod(e="GET"){return Ct.has(e.toUpperCase())}const Tt=new Set(["image/svg","application/xml","application/xhtml","application/html"]),Ot=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function resolveFetchOptions(e,t,s,a){const c=function(e,t,s){if(!t)return new s(e);const a=new s(t);if(e)for(const[t,c]of Symbol.iterator in e||Array.isArray(e)?e:new s(e))a.set(t,c);return a}(t?.headers??e?.headers,s?.headers,a);let l;return(s?.query||s?.params||t?.params||t?.query)&&(l={...s?.params,...s?.query,...t?.params,...t?.query}),{...s,...t,query:l,params:l,headers:c}}async function callHooks(e,t){if(t)if(Array.isArray(t))for(const s of t)await s(e);else await t(e)}const At=new Set([408,409,425,429,500,502,503,504]),Pt=new Set([101,204,205,304]);function createFetch(e={}){const{fetch:t=globalThis.fetch,Headers:s=globalThis.Headers,AbortController:a=globalThis.AbortController}=e;async function onError(e){const t=e.error&&"AbortError"===e.error.name&&!e.options.timeout||!1;if(!1!==e.options.retry&&!t){let t;t="number"==typeof e.options.retry?e.options.retry:isPayloadMethod(e.options.method)?0:1;const s=e.response&&e.response.status||500;if(t>0&&(Array.isArray(e.options.retryStatusCodes)?e.options.retryStatusCodes.includes(s):At.has(s))){const s="function"==typeof e.options.retryDelay?e.options.retryDelay(e):e.options.retryDelay||0;return s>0&&await new Promise(e=>setTimeout(e,s)),$fetchRaw(e.request,{...e.options,retry:t-1})}}const s=function(e){const t=e.error?.message||e.error?.toString()||"",s=e.request?.method||e.options?.method||"GET",a=e.request?.url||String(e.request)||"/",c=`[${s}] ${JSON.stringify(a)}`,l=e.response?`${e.response.status} ${e.response.statusText}`:"<no response>",d=new FetchError(`${c}: ${l}${t?` ${t}`:""}`,e.error?{cause:e.error}:void 0);for(const t of["request","options","response"])Object.defineProperty(d,t,{get:()=>e[t]});for(const[t,s]of[["data","_data"],["status","status"],["statusCode","status"],["statusText","statusText"],["statusMessage","statusText"]])Object.defineProperty(d,t,{get:()=>e.response&&e.response[s]});return d}(e);throw Error.captureStackTrace&&Error.captureStackTrace(s,$fetchRaw),s}const $fetchRaw=async function(c,l={}){const d={request:c,options:resolveFetchOptions(c,l,e.defaults,s),response:void 0,error:void 0};if(d.options.method&&(d.options.method=d.options.method.toUpperCase()),d.options.onRequest&&(await callHooks(d,d.options.onRequest),d.options.headers instanceof s||(d.options.headers=new s(d.options.headers||{}))),"string"==typeof d.request&&(d.options.baseURL&&(d.request=function(e,t){if(isEmptyURL(t)||hasProtocol(e))return e;const s=withoutTrailingSlash(t);if(e.startsWith(s)){const t=e[s.length];if(!t||"/"===t||"?"===t)return e}return joinURL(s,e)}(d.request,d.options.baseURL)),d.options.query&&(d.request=withQuery(d.request,d.options.query),delete d.options.query),"query"in d.options&&delete d.options.query,"params"in d.options&&delete d.options.params),d.options.body&&isPayloadMethod(d.options.method))if(function(e){if(void 0===e)return!1;const t=typeof e;return"string"===t||"number"===t||"boolean"===t||null===t||"object"===t&&(!!Array.isArray(e)||!e.buffer&&!(e instanceof FormData||e instanceof URLSearchParams)&&(e.constructor&&"Object"===e.constructor.name||"function"==typeof e.toJSON))}(d.options.body)){const e=d.options.headers.get("content-type");"string"!=typeof d.options.body&&(d.options.body="application/x-www-form-urlencoded"===e?new URLSearchParams(d.options.body).toString():JSON.stringify(d.options.body)),e||d.options.headers.set("content-type","application/json"),d.options.headers.has("accept")||d.options.headers.set("accept","application/json")}else("pipeTo"in d.options.body&&"function"==typeof d.options.body.pipeTo||"function"==typeof d.options.body.pipe)&&("duplex"in d.options||(d.options.duplex="half"));let h;if(!d.options.signal&&d.options.timeout){const e=new a;h=setTimeout(()=>{const t=new Error("[TimeoutError]: The operation was aborted due to timeout");t.name="TimeoutError",t.code=23,e.abort(t)},d.options.timeout),d.options.signal=e.signal}try{d.response=await t(d.request,d.options)}catch(e){return d.error=e,d.options.onRequestError&&await callHooks(d,d.options.onRequestError),await onError(d)}finally{h&&clearTimeout(h)}if((d.response.body||d.response._bodyInit)&&!Pt.has(d.response.status)&&"HEAD"!==d.options.method){const e=(d.options.parseResponse?"json":d.options.responseType)||function(e=""){if(!e)return"json";const t=e.split(";").shift()||"";return Ot.test(t)?"json":"text/event-stream"===t?"stream":Tt.has(t)||t.startsWith("text/")?"text":"blob"}(d.response.headers.get("content-type")||"");switch(e){case"json":{const e=await d.response.text(),t=d.options.parseResponse||destr;d.response._data=t(e);break}case"stream":d.response._data=d.response.body||d.response._bodyInit;break;default:d.response._data=await d.response[e]()}}return d.options.onResponse&&await callHooks(d,d.options.onResponse),!d.options.ignoreResponseError&&d.response.status>=400&&d.response.status<600?(d.options.onResponseError&&await callHooks(d,d.options.onResponseError),await onError(d)):d.response},$fetch=async function(e,t){return(await $fetchRaw(e,t))._data};return $fetch.raw=$fetchRaw,$fetch.native=(...e)=>t(...e),$fetch.create=(t={},s={})=>createFetch({...e,...s,defaults:{...e.defaults,...s.defaults,...t}}),$fetch}const It=globalThis.fetch?(...e)=>globalThis.fetch(...e):function(){if(!JSON.parse(e.env.FETCH_KEEP_ALIVE||"false"))return Rt;const s={keepAlive:!0},c=new t.Agent(s),l=new a.Agent(s),d={agent:e=>"http:"===e.protocol?c:l};return function(e,t){return Rt(e,{...d,...t})}}(),Nt=globalThis.Headers||kt,jt=globalThis.AbortController||xt;function asyncCall(e,...t){try{return(s=e(...t))&&"function"==typeof s.then?s:Promise.resolve(s)}catch(e){return Promise.reject(e)}var s}function stringify(e){if(function(e){const t=typeof e;return null===e||"object"!==t&&"function"!==t}(e))return String(e);if(function(e){const t=Object.getPrototypeOf(e);return!t||t.isPrototypeOf(Object)}(e)||Array.isArray(e))return JSON.stringify(e);if("function"==typeof e.toJSON)return stringify(e.toJSON());throw new Error("[unstorage] Cannot stringify value!")}createFetch({fetch:It,Headers:Nt,AbortController:jt});const Ht="base64:";function serializeRaw(e){return"string"==typeof e?e:Ht+function(e){if(globalThis.Buffer)return Buffer.from(e).toString("base64");return globalThis.btoa(String.fromCodePoint(...e))}(e)}function deserializeRaw(e){return"string"!=typeof e?e:e.startsWith(Ht)?function(e){if(globalThis.Buffer)return Buffer.from(e,"base64");return Uint8Array.from(globalThis.atob(e),e=>e.codePointAt(0))}(e.slice(7)):e}const Wt=["has","hasItem","get","getItem","getItemRaw","set","setItem","setItemRaw","del","remove","removeItem","getMeta","setMeta","removeMeta","getKeys","clear","mount","unmount"];function normalizeKey$1(e){return e&&e.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function joinKeys(...e){return normalizeKey$1(e.join(":"))}function normalizeBaseKey(e){return(e=normalizeKey$1(e))?e+":":""}const memory=()=>{const e=new Map;return{name:"memory",getInstance:()=>e,hasItem:t=>e.has(t),getItem:t=>e.get(t)??null,getItemRaw:t=>e.get(t)??null,setItem(t,s){e.set(t,s)},setItemRaw(t,s){e.set(t,s)},removeItem(t){e.delete(t)},getKeys:()=>[...e.keys()],clear(){e.clear()},dispose(){e.clear()}}};function watch$1(e,t,s){return e.watch?e.watch((e,a)=>t(e,s+a)):()=>{}}async function dispose(e){"function"==typeof e.dispose&&await asyncCall(e.dispose)}const Lt={},normalizeKey=function(e){return e&&e.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""},Dt={getKeys:()=>Promise.resolve(Object.keys(Lt)),hasItem:e=>(e=normalizeKey(e),Promise.resolve(e in Lt)),getItem:e=>(e=normalizeKey(e),Promise.resolve(Lt[e]?Lt[e].import():null)),getMeta:e=>(e=normalizeKey(e),Promise.resolve(Lt[e]?Lt[e].meta:{}))};function createError(e,t,s){const a=new Error(`[unstorage] [${e}] ${t}`,s);return Error.captureStackTrace&&Error.captureStackTrace(a,createError),a}function ignoreNotfound(e){return"ENOENT"===e.code||"EISDIR"===e.code?null:e}function ignoreExists(e){return"EEXIST"===e.code?null:e}async function writeFile(e,t,s){return await ensuredir(N(e)),O.writeFile(e,t,s)}function readFile(e,t){return O.readFile(e,t).catch(ignoreNotfound)}function readdir(e){return O.readdir(e,{withFileTypes:!0}).catch(ignoreNotfound).then(e=>e||[])}async function ensuredir(e){P(e)||(await ensuredir(N(e)).catch(ignoreExists),await O.mkdir(e).catch(ignoreExists))}async function readdirRecursive(e,t,s){if(t&&t(e))return[];const a=await readdir(e),c=[];return await Promise.all(a.map(async a=>{const l=I(e,a.name);if(a.isDirectory()){if(void 0===s||s>0){const e=await readdirRecursive(l,t,void 0===s?void 0:s-1);c.push(...e.map(e=>a.name+"/"+e))}}else t&&t(a.name)||c.push(a.name)})),c}async function rmRecursive(e){const t=await readdir(e);await Promise.all(t.map(t=>{const s=I(e,t.name);return t.isDirectory()?rmRecursive(s).then(()=>O.rmdir(s)):O.unlink(s)}))}const Bt=/\.\.:|\.\.$/,Mt="fs-lite",unstorage_47drivers_47fs_45lite=(e={})=>{if(!e.base)throw t=Mt,s="base",Array.isArray(s)?createError(t,`Missing some of the required options ${s.map(e=>"`"+e+"`").join(", ")}`):createError(t,`Missing required option \`${s}\`.`);var t,s;e.base=I(e.base);const r=t=>{if(Bt.test(t))throw createError(Mt,`Invalid key: ${JSON.stringify(t)}. It should not contain .. segments`);return j(e.base,t.replace(/:/g,"/"))};return{name:Mt,options:e,flags:{maxDepth:!0},hasItem:e=>P(r(e)),getItem:e=>readFile(r(e),"utf8"),getItemRaw:e=>readFile(r(e)),async getMeta(e){const{atime:t,mtime:s,size:a,birthtime:c,ctime:l}=await O.stat(r(e)).catch(()=>({}));return{atime:t,mtime:s,size:a,birthtime:c,ctime:l}},setItem(t,s){if(!e.readOnly)return writeFile(r(t),s,"utf8")},setItemRaw(t,s){if(!e.readOnly)return writeFile(r(t),s)},removeItem(t){if(!e.readOnly)return function(e){return O.unlink(e).catch(ignoreNotfound)}(r(t))},getKeys:(t,s)=>readdirRecursive(r("."),e.ignore,s?.maxDepth),async clear(){e.readOnly||e.noClear||await rmRecursive(r("."))}}},Ut=function(e={}){const t={mounts:{"":e.driver||memory()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},getMount=e=>{for(const s of t.mountpoints)if(e.startsWith(s))return{base:s,relativeKey:e.slice(s.length),driver:t.mounts[s]};return{base:"",relativeKey:e,driver:t.mounts[""]}},getMounts=(e,s)=>t.mountpoints.filter(t=>t.startsWith(e)||s&&e.startsWith(t)).map(s=>({relativeBase:e.length>s.length?e.slice(s.length):void 0,mountpoint:s,driver:t.mounts[s]})),onChange=(e,s)=>{if(t.watching){s=normalizeKey$1(s);for(const a of t.watchListeners)a(e,s)}},stopWatch=async()=>{if(t.watching){for(const e in t.unwatch)await t.unwatch[e]();t.unwatch={},t.watching=!1}},runBatch=(e,t,s)=>{const a=new Map,getBatch=e=>{let t=a.get(e.base);return t||(t={driver:e.driver,base:e.base,items:[]},a.set(e.base,t)),t};for(const s of e){const e="string"==typeof s,a=normalizeKey$1(e?s:s.key),c=e?void 0:s.value,l=e||!s.options?t:{...t,...s.options},d=getMount(a);getBatch(d).items.push({key:a,value:c,relativeKey:d.relativeKey,options:l})}return Promise.all([...a.values()].map(e=>s(e))).then(e=>e.flat())},s={hasItem(e,t={}){e=normalizeKey$1(e);const{relativeKey:s,driver:a}=getMount(e);return asyncCall(a.hasItem,s,t)},getItem(e,t={}){e=normalizeKey$1(e);const{relativeKey:s,driver:a}=getMount(e);return asyncCall(a.getItem,s,t).then(e=>destr(e))},getItems:(e,t={})=>runBatch(e,t,e=>e.driver.getItems?asyncCall(e.driver.getItems,e.items.map(e=>({key:e.relativeKey,options:e.options})),t).then(t=>t.map(t=>({key:joinKeys(e.base,t.key),value:destr(t.value)}))):Promise.all(e.items.map(t=>asyncCall(e.driver.getItem,t.relativeKey,t.options).then(e=>({key:t.key,value:destr(e)}))))),getItemRaw(e,t={}){e=normalizeKey$1(e);const{relativeKey:s,driver:a}=getMount(e);return a.getItemRaw?asyncCall(a.getItemRaw,s,t):asyncCall(a.getItem,s,t).then(e=>deserializeRaw(e))},async setItem(e,t,a={}){if(void 0===t)return s.removeItem(e);e=normalizeKey$1(e);const{relativeKey:c,driver:l}=getMount(e);l.setItem&&(await asyncCall(l.setItem,c,stringify(t),a),l.watch||onChange("update",e))},async setItems(e,t){await runBatch(e,t,async e=>{if(e.driver.setItems)return asyncCall(e.driver.setItems,e.items.map(e=>({key:e.relativeKey,value:stringify(e.value),options:e.options})),t);e.driver.setItem&&await Promise.all(e.items.map(t=>asyncCall(e.driver.setItem,t.relativeKey,stringify(t.value),t.options)))})},async setItemRaw(e,t,a={}){if(void 0===t)return s.removeItem(e,a);e=normalizeKey$1(e);const{relativeKey:c,driver:l}=getMount(e);if(l.setItemRaw)await asyncCall(l.setItemRaw,c,t,a);else{if(!l.setItem)return;await asyncCall(l.setItem,c,serializeRaw(t),a)}l.watch||onChange("update",e)},async removeItem(e,t={}){"boolean"==typeof t&&(t={removeMeta:t}),e=normalizeKey$1(e);const{relativeKey:s,driver:a}=getMount(e);a.removeItem&&(await asyncCall(a.removeItem,s,t),(t.removeMeta||t.removeMata)&&await asyncCall(a.removeItem,s+"$",t),a.watch||onChange("remove",e))},async getMeta(e,t={}){"boolean"==typeof t&&(t={nativeOnly:t}),e=normalizeKey$1(e);const{relativeKey:s,driver:a}=getMount(e),c=Object.create(null);if(a.getMeta&&Object.assign(c,await asyncCall(a.getMeta,s,t)),!t.nativeOnly){const e=await asyncCall(a.getItem,s+"$",t).then(e=>destr(e));e&&"object"==typeof e&&("string"==typeof e.atime&&(e.atime=new Date(e.atime)),"string"==typeof e.mtime&&(e.mtime=new Date(e.mtime)),Object.assign(c,e))}return c},setMeta(e,t,s={}){return this.setItem(e+"$",t,s)},removeMeta(e,t={}){return this.removeItem(e+"$",t)},async getKeys(e,t={}){e=normalizeBaseKey(e);const s=getMounts(e,!0);let a=[];const c=[];let l=!0;for(const e of s){e.driver.flags?.maxDepth||(l=!1);const s=await asyncCall(e.driver.getKeys,e.relativeBase,t);for(const t of s){const s=e.mountpoint+normalizeKey$1(t);a.some(e=>s.startsWith(e))||c.push(s)}a=[e.mountpoint,...a.filter(t=>!t.startsWith(e.mountpoint))]}const d=void 0!==t.maxDepth&&!l;return c.filter(s=>(!d||function(e,t){if(void 0===t)return!0;let s=0,a=e.indexOf(":");for(;a>-1;)s++,a=e.indexOf(":",a+1);return s<=t}(s,t.maxDepth))&&function(e,t){return t?e.startsWith(t)&&"$"!==e[e.length-1]:"$"!==e[e.length-1]}(s,e))},async clear(e,t={}){e=normalizeBaseKey(e),await Promise.all(getMounts(e,!1).map(async e=>{if(e.driver.clear)return asyncCall(e.driver.clear,e.relativeBase,t);if(e.driver.removeItem){const s=await e.driver.getKeys(e.relativeBase||"",t);return Promise.all(s.map(s=>e.driver.removeItem(s,t)))}}))},async dispose(){await Promise.all(Object.values(t.mounts).map(e=>dispose(e)))},watch:async e=>(await(async()=>{if(!t.watching){t.watching=!0;for(const e in t.mounts)t.unwatch[e]=await watch$1(t.mounts[e],onChange,e)}})(),t.watchListeners.push(e),async()=>{t.watchListeners=t.watchListeners.filter(t=>t!==e),0===t.watchListeners.length&&await stopWatch()}),async unwatch(){t.watchListeners=[],await stopWatch()},mount(e,a){if((e=normalizeBaseKey(e))&&t.mounts[e])throw new Error(`already mounted at ${e}`);return e&&(t.mountpoints.push(e),t.mountpoints.sort((e,t)=>t.length-e.length)),t.mounts[e]=a,t.watching&&Promise.resolve(watch$1(a,onChange,e)).then(s=>{t.unwatch[e]=s}).catch(console.error),s},async unmount(e,s=!0){(e=normalizeBaseKey(e))&&t.mounts[e]&&(t.watching&&e in t.unwatch&&(t.unwatch[e]?.(),delete t.unwatch[e]),s&&await dispose(t.mounts[e]),t.mountpoints=t.mountpoints.filter(t=>t!==e),delete t.mounts[e])},getMount(e=""){e=normalizeKey$1(e)+":";const t=getMount(e);return{driver:t.driver,base:t.base}},getMounts(e="",t={}){e=normalizeKey$1(e);return getMounts(e,t.parents).map(e=>({driver:e.driver,base:e.mountpoint}))},keys:(e,t={})=>s.getKeys(e,t),get:(e,t={})=>s.getItem(e,t),set:(e,t,a={})=>s.setItem(e,t,a),has:(e,t={})=>s.hasItem(e,t),del:(e,t={})=>s.removeItem(e,t),remove:(e,t={})=>s.removeItem(e,t)};return s}({});function useStorage(e=""){return e?function(e,t){if(!(t=normalizeBaseKey(t)))return e;const s={...e};for(const a of Wt)s[a]=(s="",...c)=>e[a](t+s,...c);return s.getKeys=(s="",...a)=>e.getKeys(t+s,...a).then(e=>e.map(e=>e.slice(t.length))),s.keys=s.getKeys,s.getItems=async(s,a)=>{const c=s.map(e=>"string"==typeof e?t+e:{...e,key:t+e.key});return(await e.getItems(c,a)).map(e=>({key:e.key.slice(t.length),value:e.value}))},s.setItems=async(s,a)=>{const c=s.map(e=>({key:t+e.key,value:e.value,options:e.options}));return e.setItems(c,a)},s}(Ut,e):Ut}Ut.mount("/assets",Dt),Ut.mount("data",unstorage_47drivers_47fs_45lite({driver:"fsLite",base:"./.data/kv"}));const qt=globalThis.process?.getBuiltinModule?.("crypto")?.hash,zt="sha256",Ft="base64url";const $t=(()=>{class Hasher2{buff="";#a=new Map;write(e){this.buff+=e}dispatch(e){return this[null===e?"null":typeof e](e)}object(e){if(e&&"function"==typeof e.toJSON)return this.object(e.toJSON());const t=Object.prototype.toString.call(e);let s="";const a=t.length;s=a<10?"unknown:["+t+"]":t.slice(8,a-1),s=s.toLowerCase();let c=null;if(void 0!==(c=this.#a.get(e)))return this.dispatch("[CIRCULAR:"+c+"]");if(this.#a.set(e,this.#a.size),"undefined"!=typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(e))return this.write("buffer:"),this.write(e.toString("utf8"));if("object"!==s&&"function"!==s&&"asyncfunction"!==s)this[s]?this[s](e):this.unknown(e,s);else{const t=Object.keys(e).sort(),s=[];this.write("object:"+(t.length+s.length)+":");const dispatchForKey=t=>{this.dispatch(t),this.write(":"),this.dispatch(e[t]),this.write(",")};for(const e of t)dispatchForKey(e);for(const e of s)dispatchForKey(e)}}array(e,t){if(t=void 0!==t&&t,this.write("array:"+e.length+":"),!t||e.length<=1){for(const t of e)this.dispatch(t);return}const s=new Map,a=e.map(e=>{const t=new Hasher2;t.dispatch(e);for(const[e,a]of t.#a)s.set(e,a);return t.toString()});return this.#a=s,a.sort(),this.array(a,!1)}date(e){return this.write("date:"+e.toJSON())}symbol(e){return this.write("symbol:"+e.toString())}unknown(e,t){if(this.write(t),e)return this.write(":"),e&&"function"==typeof e.entries?this.array([...e.entries()],!0):void 0}error(e){return this.write("error:"+e.toString())}boolean(e){return this.write("bool:"+e)}string(e){this.write("string:"+e.length+":"),this.write(e)}function(e){this.write("fn:"),!function(e){if("function"!=typeof e)return!1;return"[native code] }"===Function.prototype.toString.call(e).slice(-15)}(e)?this.dispatch(e.toString()):this.dispatch("[native]")}number(e){return this.write("number:"+e)}null(){return this.write("Null")}undefined(){return this.write("Undefined")}regexp(e){return this.write("regex:"+e.toString())}arraybuffer(e){return this.write("arraybuffer:"),this.dispatch(new Uint8Array(e))}url(e){return this.write("url:"+e.toString())}map(e){this.write("map:");const t=[...e];return this.array(t,!1)}set(e){this.write("set:");const t=[...e];return this.array(t,!1)}bigint(e){return this.write("bigint:"+e.toString())}}for(const e of["uint8array","uint8clampedarray","unt8array","uint16array","unt16array","uint32array","unt32array","float32array","float64array"])Hasher2.prototype[e]=function(t){return this.write(e+":"),this.array([...t],!1)};return Hasher2})();function hash(e){return function(e){if(qt)return qt(zt,e,Ft);const t=d(zt).update(e);return globalThis.process?.versions?.webcontainer?t.digest().toString(Ft):t.digest(Ft)}("string"==typeof e?e:function(e){const t=new $t;return t.dispatch(e),t.buff}(e)).replace(/[-_]/g,"").slice(0,10)}function defineCachedFunction(e,t={}){t={name:"_",base:"/cache",swr:!0,maxAge:1,...t};const s={},a=t.group||"nitro/functions",c=t.name||e.name||"_",l=t.integrity||hash([e,t]),d=t.validate||(e=>void 0!==e.value);return async(...h)=>{if(await(t.shouldBypassCache?.(...h)))return e(...h);const u=await(t.getKey||getKey)(...h),f=await(t.shouldInvalidateCache?.(...h)),m=await async function(e,h,u,f){const m=[t.base,a,c,e+".json"].filter(Boolean).join(":").replace(/:\/$/,":index");let g=await useStorage().getItem(m).catch(e=>{console.error("[cache] Cache read error.",e),useNitroApp().captureError(e,{event:f,tags:["cache"]})})||{};if("object"!=typeof g){g={};const e=new Error("Malformed data read from cache.");console.error("[cache]",e),useNitroApp().captureError(e,{event:f,tags:["cache"]})}const _=1e3*(t.maxAge??0);_&&(g.expires=Date.now()+_);const S=u||g.integrity!==l||_&&Date.now()-(g.mtime||0)>_||!1===d(g),E=S?(async()=>{const a=s[e];a||(void 0!==g.value&&(t.staleMaxAge||0)>=0&&!1===t.swr&&(g.value=void 0,g.integrity=void 0,g.mtime=void 0,g.expires=void 0),s[e]=Promise.resolve(h()));try{g.value=await s[e]}catch(t){throw a||delete s[e],t}if(!a&&(g.mtime=Date.now(),g.integrity=l,delete s[e],!1!==d(g))){let e;t.maxAge&&!t.swr&&(e={ttl:t.maxAge});const s=useStorage().setItem(m,g,e).catch(e=>{console.error("[cache] Cache write error.",e),useNitroApp().captureError(e,{event:f,tags:["cache"]})});f?.waitUntil&&f.waitUntil(s)}})():Promise.resolve();return void 0===g.value?await E:S&&f&&f.waitUntil&&f.waitUntil(E),t.swr&&!1!==d(g)?(E.catch(e=>{console.error("[cache] SWR handler error.",e),useNitroApp().captureError(e,{event:f,tags:["cache"]})}),g):E.then(()=>g)}(u,()=>e(...h),f,h[0]&&isEvent(h[0])?h[0]:void 0);let g=m.value;return t.transform&&(g=await t.transform(m,...h)||g),g}}function getKey(...e){return e.length>0?hash(e):""}function escapeKey(e){return String(e).replace(/\W/g,"")}function cloneWithProxy(e,t){return new Proxy(e,{get:(e,s,a)=>s in t?t[s]:Reflect.get(e,s,a),set:(e,s,a,c)=>s in t?(t[s]=a,!0):Reflect.set(e,s,a,c)})}const cachedEventHandler=function(e,t={name:"_",base:"/cache",swr:!0,maxAge:1}){const s=(t.varies||[]).filter(Boolean).map(e=>e.toLowerCase()).sort(),a={...t,getKey:async e=>{const a=await(t.getKey?.(e));if(a)return escapeKey(a);const c=e.node.req.originalUrl||e.node.req.url||e.path;let l;try{l=escapeKey(decodeURI(parseURL(c).pathname)).slice(0,16)||"index"}catch{l="-"}return[`${l}.${hash(c)}`,...s.map(t=>[t,e.node.req.headers[t]]).map(([e,t])=>`${escapeKey(e)}.${hash(t)}`)].join(":")},validate:e=>!!e.value&&(!(e.value.code>=400)&&(void 0!==e.value.body&&("undefined"!==e.value.headers.etag&&"undefined"!==e.value.headers["last-modified"]))),group:t.group||"nitro/handlers",integrity:t.integrity||hash([e,t])},c=function(e,t={}){return defineCachedFunction(e,t)}(async c=>{const l={};for(const e of s){const t=c.node.req.headers[e];void 0!==t&&(l[e]=t)}const d=cloneWithProxy(c.node.req,{headers:l}),h={};let u;const f=createEvent(d,cloneWithProxy(c.node.res,{statusCode:200,writableEnded:!1,writableFinished:!1,headersSent:!1,closed:!1,getHeader:e=>h[e],setHeader(e,t){return h[e]=t,this},getHeaderNames:()=>Object.keys(h),hasHeader:e=>e in h,removeHeader(e){delete h[e]},getHeaders:()=>h,end(e,t,s){return"string"==typeof e&&(u=e),"function"==typeof t&&t(),"function"==typeof s&&s(),this},write:(e,t,s)=>("string"==typeof e&&(u=e),"function"==typeof t&&t(void 0),"function"==typeof s&&s(),!0),writeHead(e,t){if(this.statusCode=e,t){if(Array.isArray(t)||"string"==typeof t)throw new TypeError("Raw headers is not supported.");for(const e in t){const s=t[e];void 0!==s&&this.setHeader(e,s)}}return this}}));f.fetch=(e,t)=>fetchWithEvent(f,e,t,{fetch:useNitroApp().localFetch}),f.$fetch=(e,t)=>fetchWithEvent(f,e,t,{fetch:globalThis.$fetch}),f.waitUntil=c.waitUntil,f.context=c.context,f.context.cache={options:a};const m=await e(f)||u,g=f.node.res.getHeaders();g.etag=String(g.Etag||g.etag||`W/"${hash(m)}"`),g["last-modified"]=String(g["Last-Modified"]||g["last-modified"]||(new Date).toUTCString());const _=[];t.swr?(t.maxAge&&_.push(`s-maxage=${t.maxAge}`),t.staleMaxAge?_.push(`stale-while-revalidate=${t.staleMaxAge}`):_.push("stale-while-revalidate")):t.maxAge&&_.push(`max-age=${t.maxAge}`),_.length>0&&(g["cache-control"]=_.join(", "));return{code:f.node.res.statusCode,headers:g,body:m}},a);return defineEventHandler(async s=>{if(t.headersOnly){if(handleCacheHeaders(s,{maxAge:t.maxAge}))return;return e(s)}const a=await c(s);if(s.node.res.headersSent||s.node.res.writableEnded)return a.body;if(!handleCacheHeaders(s,{modifiedTime:new Date(a.headers["last-modified"]),etag:a.headers.etag,maxAge:t.maxAge})){s.node.res.statusCode=a.code;for(const e in a.headers){const t=a.headers[e];"set-cookie"===e?s.node.res.appendHeader(e,splitCookiesString(t)):void 0!==t&&s.node.res.setHeader(e,t)}return a.body}})};function klona(e){if("object"!=typeof e)return e;var t,s,a=Object.prototype.toString.call(e);if("[object Object]"===a){if(e.constructor!==Object&&"function"==typeof e.constructor)for(t in s=new e.constructor,e)e.hasOwnProperty(t)&&s[t]!==e[t]&&(s[t]=klona(e[t]));else for(t in s={},e)"__proto__"===t?Object.defineProperty(s,t,{value:klona(e[t]),configurable:!0,enumerable:!0,writable:!0}):s[t]=klona(e[t]);return s}if("[object Array]"===a){for(t=e.length,s=Array(t);t--;)s[t]=klona(e[t]);return s}return"[object Set]"===a?(s=new Set,e.forEach(function(e){s.add(klona(e))}),s):"[object Map]"===a?(s=new Map,e.forEach(function(e,t){s.set(klona(t),klona(e))}),s):"[object Date]"===a?new Date(+e):"[object RegExp]"===a?((s=new RegExp(e.source,e.flags)).lastIndex=e.lastIndex,s):"[object DataView]"===a?new e.constructor(klona(e.buffer)):"[object ArrayBuffer]"===a?e.slice(0):"Array]"===a.slice(-6)?new e.constructor(e):e}const Kt=st({nuxt:{}}),Gt=/\d/,Vt=["-","_","/","."];function isUppercase(e=""){if(!Gt.test(e))return e!==e.toLowerCase()}function kebabCase(e,t){return e?(Array.isArray(e)?e:function(e){const t=Vt,s=[];if(!e||"string"!=typeof e)return s;let a,c,l="";for(const d of e){const e=t.includes(d);if(!0===e){s.push(l),l="",a=void 0;continue}const h=isUppercase(d);if(!1===c){if(!1===a&&!0===h){s.push(l),l=d,a=h;continue}if(!0===a&&!1===h&&l.length>1){const e=l.at(-1);s.push(l.slice(0,Math.max(0,l.length-1))),l=e+d,a=h;continue}}l+=d,a=h,c=e}return s.push(l),s}(e)).map(e=>e.toLowerCase()).join(t):""}function getEnv(t,s){const a=(c=t,kebabCase(c||"","_")).toUpperCase();var c;return destr(e.env[s.prefix+a]??e.env[s.altPrefix+a])}function _isObject(e){return"object"==typeof e&&!Array.isArray(e)}function applyEnv(e,t,s=""){for(const a in e){const c=s?`${s}_${a}`:a,l=getEnv(c,t);_isObject(e[a])?_isObject(l)?(e[a]={...e[a],...l},applyEnv(e[a],t,c)):void 0===l?applyEnv(e[a],t,c):e[a]=l??e[a]:e[a]=l??e[a],t.envExpansion&&"string"==typeof e[a]&&(e[a]=_expandFromEnv(e[a]))}return e}const Zt=/\{\{([^{}]*)\}\}/g;function _expandFromEnv(t){return t.replace(Zt,(t,s)=>e.env[s]||t)}const Jt={app:{baseURL:"/",buildId:"e405cd67-1e23-4b39-85e1-217b00c69ec7",buildAssetsDir:"/_nuxt/",cdnURL:""},nitro:{envPrefix:"NUXT_",routeRules:{"/__nuxt_error":{cache:!1},"/api/**":{headers:{"Cache-Control":"no-cache"}},"/_nuxt/builds/meta/**":{headers:{"cache-control":"public, max-age=31536000, immutable"}},"/_nuxt/builds/**":{headers:{"cache-control":"public, max-age=1, immutable"}},"/_nuxt/**":{headers:{"cache-control":"public, max-age=31536000, immutable"}}}},public:{ldClientSideId:"",captchaAppId:""}},Qt={prefix:"NITRO_",altPrefix:Jt.nitro.envPrefix??e.env.NITRO_ENV_PREFIX??"_",envExpansion:Jt.nitro.envExpansion??e.env.NITRO_ENV_EXPANSION??!1},Xt=_deepFreeze(applyEnv(klona(Jt),Qt));function useRuntimeConfig(e){if(!e)return Xt;if(e.context.nitro.runtimeConfig)return e.context.nitro.runtimeConfig;const t=klona(Jt);return applyEnv(t,Qt),e.context.nitro.runtimeConfig=t,t}function _deepFreeze(e){const t=Object.getOwnPropertyNames(e);for(const s of t){const t=e[s];t&&"object"==typeof t&&_deepFreeze(t)}return Object.freeze(e)}_deepFreeze(klona(Kt)),new Proxy(Object.create(null),{get:(e,t)=>{console.warn("Please use `useRuntimeConfig()` instead of accessing config directly.");const s=useRuntimeConfig();if(t in s)return s[t]}});const Yt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:{},er="__unctx__",tr=Yt[er]||(Yt[er]=function(e={}){const t={};return{get:(s,a={})=>(t[s]||(t[s]=function(e={}){let t,s=!1;const checkConflict=e=>{if(t&&t!==e)throw new Error("Context conflict")};let a;if(e.asyncContext){const t=e.AsyncLocalStorage||globalThis.AsyncLocalStorage;t?a=new t:console.warn("[unctx] `AsyncLocalStorage` is not provided.")}const _getCurrentInstance=()=>{if(a){const e=a.getStore();if(void 0!==e)return e}return t};return{use:()=>{const e=_getCurrentInstance();if(void 0===e)throw new Error("Context is not available");return e},tryUse:()=>_getCurrentInstance(),set:(e,a)=>{a||checkConflict(e),t=e,s=!0},unset:()=>{t=void 0,s=!1},call:(e,c)=>{checkConflict(e),t=e;try{return a?a.run(e,c):c()}finally{s||(t=void 0)}},async callAsync(e,c){t=e;const onRestore=()=>{t=e},onLeave=()=>t===e?onRestore:void 0;sr.add(onLeave);try{const l=a?a.run(e,c):c();return s||(t=void 0),await l}finally{sr.delete(onLeave)}}}}({...e,...a})),t[s])}}()),rr="__unctx_async_handlers__",sr=Yt[rr]||(Yt[rr]=new Set);((e,t={})=>{tr.get(e,t)})("nitro-app",{asyncContext:!1,AsyncLocalStorage:void 0});const nr=toRouteMatcher(createRouter$1({routes:useRuntimeConfig().nitro.routeRules}));function createRouteRulesHandler(e){return bt(t=>{const s=getRouteRules(t);if(s.headers&&yt(t,s.headers),s.redirect){let e=s.redirect.to;if(e.endsWith("/**")){let a=t.path;const c=s.redirect._redirectStripBase;c&&(a=withoutBase(a,c)),e=joinURL(e.slice(0,-3),a)}else if(t.path.includes("?")){e=withQuery(e,getQuery$1(t.path))}return function(e,t,s=302){return e.node.res.statusCode=sanitizeStatusCode(s,e.node.res.statusCode),e.node.res.setHeader("location",t),send(e,`<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=${t.replace(/"/g,"%22")}"></head></html>`,ft.html)}(t,e,s.redirect.statusCode)}if(s.proxy){let a=s.proxy.to;if(a.endsWith("/**")){let e=t.path;const c=s.proxy._proxyStripBase;c&&(e=withoutBase(e,c)),a=joinURL(a.slice(0,-3),e)}else if(t.path.includes("?")){a=withQuery(a,getQuery$1(t.path))}return proxyRequest(t,a,{fetch:e.localFetch,...s.proxy})}})}function getRouteRules(e){return e.context._nitro=e.context._nitro||{},e.context._nitro.routeRules||(e.context._nitro.routeRules=getRouteRulesForPath(withoutBase(e.path.split("?")[0],useRuntimeConfig().app.baseURL))),e.context._nitro.routeRules}function getRouteRulesForPath(e){return rt({},...nr.matchAll(e).reverse())}function _captureError(e,t){console.error(`[${t}]`,e),useNitroApp().captureError(e,{tags:[t]})}function joinHeaders(e){return Array.isArray(e)?e.join(", "):String(e)}function normalizeCookieHeader(e=""){return splitCookiesString(joinHeaders(e))}function normalizeCookieHeaders(e){const t=new Headers;for(const[s,a]of e)if("set-cookie"===s)for(const e of normalizeCookieHeader(a))t.append("set-cookie",e);else t.set(s,joinHeaders(a));return t}function hasReqHeader(e,t,s){const a=getRequestHeader(e,t);return a&&"string"==typeof a&&a.toLowerCase().includes(s)}function defaultHandler(e,t,s){const a=e.unhandled||e.fatal,c=e.statusCode||500,l=e.statusMessage||"Server Error",d=function(e,t={}){const s=getRequestHost(e,t),a=function(e,t={}){return!1!==t.xForwardedProto&&"https"===e.node.req.headers["x-forwarded-proto"]||e.node.req.connection?.encrypted?"https":"http"}(e,t),c=(e.node.req.originalUrl||e.path).replace(/^[/\\]+/g,"/");return new URL(c,`${a}://${s}`)}(t,{xForwardedHost:!0,xForwardedProto:!0});if(404===c){const e="/";if(/^\/[^/]/.test(e)&&!d.pathname.startsWith(e)){return{status:302,statusText:"Found",headers:{location:`${e}${d.pathname.slice(1)}${d.search}`},body:"Redirecting..."}}}if(a&&!s?.silent){const s=[e.unhandled&&"[unhandled]",e.fatal&&"[fatal]"].filter(Boolean).join(" ");console.error(`[request error] ${s} [${t.method}] ${d}\n`,e)}const h={"content-type":"application/json","x-content-type-options":"nosniff","x-frame-options":"DENY","referrer-policy":"no-referrer","content-security-policy":"script-src 'none'; frame-ancestors 'none';"};setResponseStatus(t,c,l),404!==c&&getResponseHeader(t,"cache-control")||(h["cache-control"]="no-cache");return{status:c,statusText:l,headers:h,body:{error:!0,url:d.href,statusCode:c,statusMessage:l,message:a?"Server Error":e.message,data:a?void 0:e.data}}}const or=[async function(e,t,{defaultHandler:s}){if(t.handled||function(e){return!hasReqHeader(e,"accept","text/html")&&(hasReqHeader(e,"accept","application/json")||hasReqHeader(e,"user-agent","curl/")||hasReqHeader(e,"user-agent","httpie/")||hasReqHeader(e,"sec-fetch-mode","cors")||e.path.startsWith("/api/")||e.path.endsWith(".json"))}(t))return;const a=await s(e,t,{json:!0});if(404===(e.status||e.statusCode||500)&&302===a.status)return setResponseHeaders(t,a.headers),setResponseStatus(t,a.status,a.statusText),send(t,JSON.stringify(a.body,null,2));const c=a.body,l=new URL(c.url);c.url=withoutBase(l.pathname,useRuntimeConfig(t).app.baseURL)+l.search+l.hash,c.message||="Server Error",c.data||=e.data,c.statusText||=e.statusText||e.statusMessage,delete a.headers["content-type"],delete a.headers["content-security-policy"],setResponseHeaders(t,a.headers);const d=getRequestHeaders(t),h=t.path.startsWith("/__nuxt_error")||!!d["x-nuxt-error"]?null:await useNitroApp().localFetch(withQuery(joinURL(useRuntimeConfig(t).app.baseURL,"/__nuxt_error"),c),{headers:{...d,"x-nuxt-error":"true"},redirect:"manual"}).catch(()=>null);if(t.handled)return;if(!h){const{template:e}=await import("../_/error-500.mjs");return setResponseHeader(t,"Content-Type","text/html;charset=UTF-8"),send(t,e(c))}const u=await h.text();for(const[e,s]of h.headers.entries())"set-cookie"!==e?setResponseHeader(t,e,s):appendResponseHeader(t,e,s);return setResponseStatus(t,h.status&&200!==h.status?h.status:a.status,h.statusText||a.statusText),send(t,u)},function(e,t){const s=defaultHandler(e,t);return setResponseHeaders(t,s.headers),setResponseStatus(t,s.status,s.statusText),send(t,JSON.stringify(s.body,null,2))}];const ir=/^(\d{3})-([a-zA-Z0-9]+)\.json$/;function parseSlideFilename(e){const t=H(e).match(ir);return t?{order:parseInt(t[1],10),id:t[2]}:null}function buildSlideFilename(e,t){return`${String(e).padStart(3,"0")}-${t}.json`}async function readManifest(e){const t=j(e,"manifest.json"),s=await B(t,"utf-8");return JSON.parse(s)}async function writeManifest(e,t){const s=j(e,"manifest.json");await M(s,JSON.stringify(t,null,2)+"\n","utf-8")}async function readSlide(e){const t=await B(e,"utf-8");return JSON.parse(t)}async function writeSlide(e,t){await M(e,JSON.stringify(t,null,2)+"\n","utf-8")}async function writeDeck(e,t){await U(j(e,"slides"),{recursive:!0}),await U(j(e,"assets"),{recursive:!0}),await writeManifest(e,t.manifest);const s=new Set;for(let e=0;e<t.slides.length;e++)s.add(buildSlideFilename(e+1,t.slides[e].id));const a=j(e,"slides"),c=await D(a).catch(()=>[]);for(const e of c)ir.test(e)&&!s.has(e)&&await q(j(a,e)).catch(()=>{});for(let e=0;e<t.slides.length;e++){const s=t.slides[e],c=buildSlideFilename(e+1,s.id);await writeSlide(j(a,c),s)}}const ar=new Map;function markPendingWrite(e){ar.set(e,Date.now())}function isPendingWrite(e){const t=ar.get(e);return void 0!==t&&(Date.now()-t<=500||(ar.delete(e),!1))}function diskToEditorUrl(e,t){return`/api/sync/assets/${t}/${encodeURIComponent(e)}`}function editorToDiskFilename(e){const t=e.match(/\/api\/sync\/assets\/[^/]+\/([^/?#]+)/);return t?decodeURIComponent(t[1]):null}function transformSlideAssetsToUrls(e,t){var s,a,c,l,d;const h=JSON.parse(JSON.stringify(e));if(Array.isArray(h.elements))for(const e of h.elements)e&&"string"==typeof e.type&&("image"!==e.type&&"video"!==e.type&&"audio"!==e.type||"string"!=typeof e.src||isLocalAssetRef(e.src)&&(e.src=diskToEditorUrl(e.src,t)),"image"===e.type&&(null==(a=null==(s=e.imageSource)?void 0:s.upload)?void 0:a.url)&&isLocalAssetRef(e.imageSource.upload.url)&&(e.imageSource.upload.url=diskToEditorUrl(e.imageSource.upload.url,t)));if(null==(c=h.background)?void 0:c.image){const e=h.background.image;"object"==typeof e&&(null==(d=null==(l=e.imageSource)?void 0:l.upload)?void 0:d.url)&&isLocalAssetRef(e.imageSource.upload.url)&&(e.imageSource.upload.url=diskToEditorUrl(e.imageSource.upload.url,t)),"string"==typeof e&&isLocalAssetRef(e)&&(h.background.image=diskToEditorUrl(e,t))}return h}function transformSlideAssetsToDisk(e){var t,s,a,c,l;const d=JSON.parse(JSON.stringify(e));if(Array.isArray(d.elements))for(const e of d.elements)if(e&&"string"==typeof e.type){if(("image"===e.type||"video"===e.type||"audio"===e.type)&&"string"==typeof e.src){const t=editorToDiskFilename(e.src);t&&(e.src=t)}if("image"===e.type&&(null==(s=null==(t=e.imageSource)?void 0:t.upload)?void 0:s.url)){const t=editorToDiskFilename(e.imageSource.upload.url);t&&(e.imageSource.upload.url=t)}}if(null==(a=d.background)?void 0:a.image){const e=d.background.image;if("object"==typeof e&&(null==(l=null==(c=e.imageSource)?void 0:c.upload)?void 0:l.url)){const t=editorToDiskFilename(e.imageSource.upload.url);t&&(e.imageSource.upload.url=t)}if("string"==typeof e){const t=editorToDiskFilename(e);t&&(d.background.image=t)}}return d}function isLocalAssetRef(e){return!(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("/api/"))&&e.length>0}const cr="files",lr="directories",dr="files_directories",hr="all",ur={root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:cr,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(ur);const fr="READDIRP_RECURSIVE_ERROR",pr=new Set(["ENOENT","EPERM","EACCES","ELOOP",fr]),mr=[lr,hr,dr,cr],yr=new Set([lr,hr,dr]),gr=new Set([hr,dr,cr]),_r="win32"===e.platform,emptyFn=e=>!0,normalizeFilter=e=>{if(void 0===e)return emptyFn;if("function"==typeof e)return e;if("string"==typeof e){const t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){const t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return emptyFn};class ReaddirpStream extends re{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});const t={...ur,...e},{root:s,type:a}=t;this._fileFilter=normalizeFilter(t.fileFilter),this._directoryFilter=normalizeFilter(t.directoryFilter);const c=t.lstat?z:F;this._stat=_r?e=>c(e,{bigint:!0}):c,this._maxDepth=t.depth??ur.depth,this._wantsDir=!!a&&yr.has(a),this._wantsFile=!!a&&gr.has(a),this._wantsEverything=a===hr,this._root=I(s),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(s,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){const t=this.parent,s=t&&t.files;if(s&&s.length>0){const{path:a,depth:c}=t,l=s.splice(0,e).map(e=>this._formatEntry(e,a)),d=await Promise.all(l);for(const t of d){if(!t)continue;if(this.destroyed)return;const s=await this._getEntryType(t);"directory"===s&&this._directoryFilter(t)?(c<=this._maxDepth&&this.parents.push(this._exploreDir(t.fullPath,c+1)),this._wantsDir&&(this.push(t),e--)):("file"===s||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{const e=this.parents.pop();if(!e){this.push(null);break}if(this.parent=await e,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,t){let s;try{s=await D(e,this._rdOptions)}catch(e){this._onError(e)}return{files:s,depth:t,path:e}}async _formatEntry(e,t){let s;const a=this._isDirent?e.name:e;try{const c=I(j(t,a));s={path:W(this._root,c),fullPath:c,basename:a},s[this._statsProp]=this._isDirent?e:await this._stat(c)}catch(e){return void this._onError(e)}return s}_onError(e){var t;t=e,pr.has(t.code)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return"";const t=e[this._statsProp];if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){const t=e.fullPath;try{const e=await $(t),s=await z(e);if(s.isFile())return"file";if(s.isDirectory()){const s=e.length;if(t.startsWith(e)&&t.substr(s,1)===L){const s=new Error(`Circular symlink detected: "${t}" points to "${e}"`);return s.code=fr,this._onError(s)}return"directory"}}catch(e){return this._onError(e),""}}}_includeAsFile(e){const t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}}const EMPTY_FN=()=>{},wr=e.platform,br="win32"===wr,vr="darwin"===wr,Sr="linux"===wr,Er="freebsd"===wr,kr="OS400"===se(),xr={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Rr=xr,Cr={lstat:X,stat:Q},Tr="listeners",Or="errHandlers",Ar="rawEmitters",Pr=[Tr,Or,Ar],Ir=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),foreach=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},addAndConvert=(e,t,s)=>{let a=e[t];a instanceof Set||(e[t]=a=new Set([a])),a.add(s)},delFromSet=(e,t,s)=>{const a=e[t];a instanceof Set?a.delete(s):a===s&&delete e[t]},isEmptySet=e=>e instanceof Set?0===e.size:!e,Nr=new Map;function createFsWatchInstance(e,t,s,a,c){const handleEvent=(t,a)=>{s(e),c(t,a,{watchedPath:e}),a&&e!==a&&fsWatchBroadcast(te.resolve(e,a),Tr,te.join(e,a))};try{return V(e,{persistent:t.persistent},handleEvent)}catch(e){return void a(e)}}const fsWatchBroadcast=(e,t,s,a,c)=>{const l=Nr.get(e);l&&foreach(l[t],e=>{e(s,a,c)})},setFsWatchListener=(e,t,s,a)=>{const{listener:c,errHandler:l,rawEmitter:d}=a;let h,u=Nr.get(t);if(!s.persistent){if(h=createFsWatchInstance(e,s,c,l,d),!h)return;return h.close.bind(h)}if(u)addAndConvert(u,Tr,c),addAndConvert(u,Or,l),addAndConvert(u,Ar,d);else{if(h=createFsWatchInstance(e,s,fsWatchBroadcast.bind(null,t,Tr),l,fsWatchBroadcast.bind(null,t,Ar)),!h)return;h.on(Rr.ERROR,async s=>{const a=fsWatchBroadcast.bind(null,t,Or);if(u&&(u.watcherUnusable=!0),br&&"EPERM"===s.code)try{const t=await Y(e,"r");await t.close(),a(s)}catch(e){}else a(s)}),u={listeners:c,errHandlers:l,rawEmitters:d,watcher:h},Nr.set(t,u)}return()=>{delFromSet(u,Tr,c),delFromSet(u,Or,l),delFromSet(u,Ar,d),isEmptySet(u.listeners)&&(u.watcher.close(),Nr.delete(t),Pr.forEach((e=>t=>{const s=e[t];s instanceof Set?s.clear():delete e[t]})(u)),u.watcher=void 0,Object.freeze(u))}},jr=new Map;class NodeFsHandler{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){const s=this.fsw.options,a=te.dirname(e),c=te.basename(e);this.fsw._getWatchedDir(a).add(c);const l=te.resolve(e),d={persistent:s.persistent};let h;if(t||(t=EMPTY_FN),s.usePolling){const a=s.interval!==s.binaryInterval;d.interval=a&&(u=c,Ir.has(te.extname(u).slice(1).toLowerCase()))?s.binaryInterval:s.interval,h=((e,t,s,a)=>{const{listener:c,rawEmitter:l}=a;let d=jr.get(t);const h=d&&d.options;return h&&(h.persistent<s.persistent||h.interval>s.interval)&&(K(t),d=void 0),d?(addAndConvert(d,Tr,c),addAndConvert(d,Ar,l)):(d={listeners:c,rawEmitters:l,options:s,watcher:G(t,s,(s,a)=>{foreach(d.rawEmitters,e=>{e(Rr.CHANGE,t,{curr:s,prev:a})});const c=s.mtimeMs;(s.size!==a.size||c>a.mtimeMs||0===c)&&foreach(d.listeners,t=>t(e,s))})},jr.set(t,d)),()=>{delFromSet(d,Tr,c),delFromSet(d,Ar,l),isEmptySet(d.listeners)&&(jr.delete(t),K(t),d.options=d.watcher=void 0,Object.freeze(d))}})(e,l,d,{listener:t,rawEmitter:this.fsw._emitRaw})}else h=setFsWatchListener(e,l,d,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});var u;return h}_handleFile(e,t,s){if(this.fsw.closed)return;const a=te.dirname(e),c=te.basename(e),l=this.fsw._getWatchedDir(a);let d=t;if(l.has(c))return;const listener=async(t,s)=>{if(this.fsw._throttle("watch",e,5))if(s&&0!==s.mtimeMs){if(l.has(c)){const t=s.atimeMs,a=s.mtimeMs;(!t||t<=a||a!==d.mtimeMs)&&this.fsw._emit(Rr.CHANGE,e,s),d=s}}else try{const s=await Q(e);if(this.fsw.closed)return;const a=s.atimeMs,c=s.mtimeMs;if((!a||a<=c||c!==d.mtimeMs)&&this.fsw._emit(Rr.CHANGE,e,s),(vr||Sr||Er)&&d.ino!==s.ino){this.fsw._closeFile(t),d=s;const a=this._watchWithNodeFs(e,listener);a&&this.fsw._addPathCloser(t,a)}else d=s}catch(e){this.fsw._remove(a,c)}},h=this._watchWithNodeFs(e,listener);if((!s||!this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Rr.ADD,e,0))return;this.fsw._emit(Rr.ADD,e,t)}return h}async _handleSymlink(e,t,s,a){if(this.fsw.closed)return;const c=e.fullPath,l=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){let t;this.fsw._incrReadyCount();try{t=await J(s)}catch(e){return this.fsw._emitReady(),!0}if(this.fsw.closed)return;return l.has(a)?this.fsw._symlinkPaths.get(c)!==t&&(this.fsw._symlinkPaths.set(c,t),this.fsw._emit(Rr.CHANGE,s,e.stats)):(l.add(a),this.fsw._symlinkPaths.set(c,t),this.fsw._emit(Rr.ADD,s,e.stats)),this.fsw._emitReady(),!0}if(this.fsw._symlinkPaths.has(c))return!0;this.fsw._symlinkPaths.set(c,!0)}_handleRead(e,t,s,a,c,l,d){if(e=te.join(e,""),!(d=this.fsw._throttle("readdir",e,1e3)))return;const h=this.fsw._getWatchedDir(s.path),u=new Set;let f=this.fsw._readdirp(e,{fileFilter:e=>s.filterPath(e),directoryFilter:e=>s.filterDir(e)});return f?(f.on("data",async d=>{if(this.fsw.closed)return void(f=void 0);const m=d.path;let g=te.join(e,m);u.add(m),d.stats.isSymbolicLink()&&await this._handleSymlink(d,e,g,m)||(this.fsw.closed?f=void 0:m!==a&&(a||h.has(m))||(this.fsw._incrReadyCount(),g=te.join(c,te.relative(c,g)),this._addToNodeFs(g,t,s,l+1)))}).on(Rr.ERROR,this._boundHandleError),new Promise((t,m)=>{if(!f)return m();f.once("end",()=>{if(this.fsw.closed)return void(f=void 0);const m=!!d&&d.clear();t(void 0),h.getChildren().filter(t=>t!==e&&!u.has(t)).forEach(t=>{this.fsw._remove(e,t)}),f=void 0,m&&this._handleRead(e,!1,s,a,c,l,d)})})):void 0}async _handleDir(e,t,s,a,c,l,d){const h=this.fsw._getWatchedDir(te.dirname(e)),u=h.has(te.basename(e));let f,m;s&&this.fsw.options.ignoreInitial||c||u||this.fsw._emit(Rr.ADD_DIR,e,t),h.add(te.basename(e)),this.fsw._getWatchedDir(e);const g=this.fsw.options.depth;if((null==g||a<=g)&&!this.fsw._symlinkPaths.has(d)){if(!c&&(await this._handleRead(e,s,l,c,e,a,f),this.fsw.closed))return;m=this._watchWithNodeFs(e,(t,s)=>{s&&0===s.mtimeMs||this._handleRead(t,!1,l,c,e,a,f)})}return m}async _addToNodeFs(e,t,s,a,c){const l=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return l(),!1;const d=this.fsw._getWatchHelpers(e);s&&(d.filterPath=e=>s.filterPath(e),d.filterDir=e=>s.filterDir(e));try{const s=await Cr[d.statMethod](d.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(d.watchPath,s))return l(),!1;const h=this.fsw.options.followSymlinks;let u;if(s.isDirectory()){const l=te.resolve(e),f=h?await J(e):e;if(this.fsw.closed)return;if(u=await this._handleDir(d.watchPath,s,t,a,c,d,f),this.fsw.closed)return;l!==f&&void 0!==f&&this.fsw._symlinkPaths.set(l,f)}else if(s.isSymbolicLink()){const c=h?await J(e):e;if(this.fsw.closed)return;const l=te.dirname(d.watchPath);if(this.fsw._getWatchedDir(l).add(d.watchPath),this.fsw._emit(Rr.ADD,d.watchPath,s),u=await this._handleDir(l,s,t,a,e,d,c),this.fsw.closed)return;void 0!==c&&this.fsw._symlinkPaths.set(te.resolve(e),c)}else u=this._handleFile(d.watchPath,s,t);return l(),u&&this.fsw._addPathCloser(e,u),!1}catch(t){if(this.fsw._handleError(t))return l(),e}}}const Hr=/\\/g,Wr=/\/\//,Lr=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Dr=/^\.[/\\]/;function arrify(e){return Array.isArray(e)?e:[e]}const isMatcherObject=e=>"object"==typeof e&&null!==e&&!(e instanceof RegExp);function matchPatterns(e,t,s){const a=function(e){if("string"!=typeof e)throw new Error("string expected");let t=!1;(e=(e=te.normalize(e)).replace(/\\/g,"/")).startsWith("//")&&(t=!0);const s=/\/\//;for(;e.match(s);)e=e.replace(s,"/");return t&&(e="/"+e),e}(t);for(let t=0;t<e.length;t++){if((0,e[t])(a,s))return!0}return!1}function anymatch(e,t){if(null==e)throw new TypeError("anymatch: specify first argument");const s=arrify(e).map(e=>function(e){return"function"==typeof e?e:"string"==typeof e?t=>e===t:e instanceof RegExp?t=>e.test(t):"object"==typeof e&&null!==e?t=>{if(e.path===t)return!0;if(e.recursive){const s=te.relative(e.path,t);return!!s&&!s.startsWith("..")&&!te.isAbsolute(s)}return!1}:()=>!1}(e));return(e,t)=>matchPatterns(s,e,t)}const unifyPaths=e=>{const t=arrify(e).flat();if(!t.every(e=>"string"==typeof e))throw new TypeError(`Non-string provided as watch path: ${t}`);return t.map(normalizePathToUnix)},toUnix=e=>{let t=e.replace(Hr,"/"),s=!1;for(t.startsWith("//")&&(s=!0);t.match(Wr);)t=t.replace(Wr,"/");return s&&(t="/"+t),t},normalizePathToUnix=e=>toUnix(te.normalize(toUnix(e))),normalizeIgnored=(e="")=>t=>"string"==typeof t?normalizePathToUnix(te.isAbsolute(t)?t:te.join(e,t)):t,Br=Object.freeze(new Set);class DirEntry{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){const{items:t}=this;t&&"."!==e&&".."!==e&&t.add(e)}async remove(e){const{items:t}=this;if(!t)return;if(t.delete(e),t.size>0)return;const s=this.path;try{await ee(s)}catch(e){this._removeWatcher&&this._removeWatcher(te.dirname(s),te.basename(s))}}has(e){const{items:t}=this;if(t)return t.has(e)}getChildren(){const{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=EMPTY_FN,this.items=Br,Object.freeze(this)}}class WatchHelper{constructor(e,t,s){this.fsw=s;const a=e;this.path=e=e.replace(Dr,""),this.watchPath=a,this.fullWatchPath=te.resolve(a),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?"stat":"lstat"}entryPath(e){return te.join(this.watchPath,te.relative(this.watchPath,e.fullPath))}filterPath(e){const{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);const s=this.entryPath(e);return this.fsw._isntIgnored(s,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}}class FSWatcher extends f{constructor(t={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;const s=t.awaitWriteFinish,a={stabilityThreshold:2e3,pollInterval:100},c={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...t,ignored:t.ignored?arrify(t.ignored):arrify([]),awaitWriteFinish:!0===s?a:"object"==typeof s&&{...a,...s}};kr&&(c.usePolling=!0),void 0===c.atomic&&(c.atomic=!c.usePolling);const l=e.env.CHOKIDAR_USEPOLLING;if(void 0!==l){const e=l.toLowerCase();c.usePolling="false"!==e&&"0"!==e&&("true"===e||"1"===e||!!e)}const d=e.env.CHOKIDAR_INTERVAL;d&&(c.interval=Number.parseInt(d,10));let h=0;this._emitReady=()=>{h++,h>=this._readyCount&&(this._emitReady=EMPTY_FN,this._readyEmitted=!0,e.nextTick(()=>this.emit(xr.READY)))},this._emitRaw=(...e)=>this.emit(xr.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=c,this._nodeFsHandler=new NodeFsHandler(this),Object.freeze(c)}_addIgnoredPath(e){if(isMatcherObject(e))for(const t of this._ignoredPaths)if(isMatcherObject(t)&&t.path===e.path&&t.recursive===e.recursive)return;this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),"string"==typeof e)for(const t of this._ignoredPaths)isMatcherObject(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,s){const{cwd:a}=this.options;this.closed=!1,this._closePromise=void 0;let c=unifyPaths(e);return a&&(c=c.map(e=>{const t=((e,t)=>te.isAbsolute(e)?e:te.join(t,e))(e,a);return t})),c.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=c.length,Promise.all(c.map(async e=>{const a=await this._nodeFsHandler._addToNodeFs(e,!s,void 0,0,t);return a&&this._emitReady(),a})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(te.dirname(e),te.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;const t=unifyPaths(e),{cwd:s}=this.options;return t.forEach(e=>{te.isAbsolute(e)||this._closers.has(e)||(s&&(e=te.join(s,e)),e=te.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();const e=[];return this._closers.forEach(t=>t.forEach(t=>{const s=t();s instanceof Promise&&e.push(s)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){const e={};return this._watched.forEach((t,s)=>{const a=this.options.cwd?te.relative(this.options.cwd,s):s;e[a||"."]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==xr.ERROR&&this.emit(xr.ALL,e,...t)}async _emit(e,t,s){if(this.closed)return;const a=this.options;br&&(t=te.normalize(t)),a.cwd&&(t=te.relative(a.cwd,t));const c=[t];null!=s&&c.push(s);const l=a.awaitWriteFinish;let d;if(l&&(d=this._pendingWrites.get(t)))return d.lastChange=new Date,this;if(a.atomic){if(e===xr.UNLINK)return this._pendingUnlinks.set(t,[e,...c]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(xr.ALL,...e),this._pendingUnlinks.delete(t)})},"number"==typeof a.atomic?a.atomic:100),this;e===xr.ADD&&this._pendingUnlinks.has(t)&&(e=xr.CHANGE,this._pendingUnlinks.delete(t))}if(l&&(e===xr.ADD||e===xr.CHANGE)&&this._readyEmitted){const awfEmit=(t,s)=>{t?(e=xr.ERROR,c[0]=t,this.emitWithAll(e,c)):s&&(c.length>1?c[1]=s:c.push(s),this.emitWithAll(e,c))};return this._awaitWriteFinish(t,l.stabilityThreshold,e,awfEmit),this}if(e===xr.CHANGE){if(!this._throttle(xr.CHANGE,t,50))return this}if(a.alwaysStat&&void 0===s&&(e===xr.ADD||e===xr.ADD_DIR||e===xr.CHANGE)){const e=a.cwd?te.join(a.cwd,t):t;let s;try{s=await Q(e)}catch(e){}if(!s||this.closed)return;c.push(s)}return this.emitWithAll(e,c),this}_handleError(e){const t=e&&e.code;return e&&"ENOENT"!==t&&"ENOTDIR"!==t&&(!this.options.ignorePermissionErrors||"EPERM"!==t&&"EACCES"!==t)&&this.emit(xr.ERROR,e),e||this.closed}_throttle(e,t,s){this._throttled.has(e)||this._throttled.set(e,new Map);const a=this._throttled.get(e);if(!a)throw new Error("invalid throttle");const c=a.get(t);if(c)return c.count++,!1;let l;const clear=()=>{const e=a.get(t),s=e?e.count:0;return a.delete(t),clearTimeout(l),e&&clearTimeout(e.timeoutObject),s};l=setTimeout(clear,s);const d={timeoutObject:l,clear:clear,count:0};return a.set(t,d),d}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,s,a){const c=this.options.awaitWriteFinish;if("object"!=typeof c)return;const l=c.pollInterval;let d,h=e;this.options.cwd&&!te.isAbsolute(e)&&(h=te.join(this.options.cwd,e));const u=new Date,f=this._pendingWrites;f.has(e)||(f.set(e,{lastChange:u,cancelWait:()=>(f.delete(e),clearTimeout(d),s)}),d=setTimeout(function awaitWriteFinishFn(s){Z(h,(c,h)=>{if(c||!f.has(e))return void(c&&"ENOENT"!==c.code&&a(c));const u=Number(new Date);s&&h.size!==s.size&&(f.get(e).lastChange=u),u-f.get(e).lastChange>=t?(f.delete(e),a(void 0,h)):d=setTimeout(awaitWriteFinishFn,l,h)})},l))}_isIgnored(e,t){if(this.options.atomic&&Lr.test(e))return!0;if(!this._userIgnored){const{cwd:e}=this.options,t=(this.options.ignored||[]).map(normalizeIgnored(e)),s=[...[...this._ignoredPaths].map(normalizeIgnored(e)),...t];this._userIgnored=anymatch(s)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new WatchHelper(e,this.options.followSymlinks,this)}_getWatchedDir(e){const t=te.resolve(e);return this._watched.has(t)||this._watched.set(t,new DirEntry(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return!!this.options.ignorePermissionErrors||Boolean(256&Number(e.mode))}_remove(e,t,s){const a=te.join(e,t),c=te.resolve(a);if(s=null!=s?s:this._watched.has(a)||this._watched.has(c),!this._throttle("remove",a,100))return;s||1!==this._watched.size||this.add(e,t,!0);this._getWatchedDir(a).getChildren().forEach(e=>this._remove(a,e));const l=this._getWatchedDir(e),d=l.has(t);l.remove(t),this._symlinkPaths.has(c)&&this._symlinkPaths.delete(c);let h=a;if(this.options.cwd&&(h=te.relative(this.options.cwd,a)),this.options.awaitWriteFinish&&this._pendingWrites.has(h)){if(this._pendingWrites.get(h).cancelWait()===xr.ADD)return}this._watched.delete(a),this._watched.delete(c);const u=s?xr.UNLINK_DIR:xr.UNLINK;d&&!this._isIgnored(a)&&this._emit(u,a),this._closePath(a)}_closePath(e){this._closeFile(e);const t=te.dirname(e);this._getWatchedDir(t).remove(te.basename(e))}_closeFile(e){const t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let s=this._closers.get(e);s||(s=[],this._closers.set(e,s)),s.push(t)}_readdirp(e,t){if(this.closed)return;let s=function(e,t={}){let s=t.entryType||t.type;if("both"===s&&(s=dr),s&&(t.type=s),!e)throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");if("string"!=typeof e)throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(s&&!mr.includes(s))throw new Error(`readdirp: Invalid type passed. Use one of ${mr.join(", ")}`);return t.root=e,new ReaddirpStream(t)}(e,{type:xr.ALL,alwaysStat:!0,lstat:!0,...t,depth:0});return this._streams.add(s),s.once("close",()=>{s=void 0}),s.once("end",()=>{s&&(this._streams.delete(s),s=void 0)}),s}}function startSyncWatcher(e){const t=function(e,t={}){const s=new FSWatcher(t);return s.add(e),s}([j(e.deckPath,"slides"),j(e.deckPath,"manifest.json")],{ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:200}});t.on("change",async t=>{if(!isPendingWrite(t))try{if("manifest.json"===H(t)){const t=await readManifest(e.deckPath);e.manifest=t,broadcastToSession(e.id,{type:"manifest:updated",sessionId:e.id,manifest:t})}else if(t.includes("/slides/")&&t.endsWith(".json")){const s=transformSlideAssetsToUrls(await readSlide(t),e.id),a=e.slides.findIndex(e=>e.id===s.id);-1!==a&&(e.slides[a]=s,broadcastToSession(e.id,{type:"slide:updated",sessionId:e.id,slideId:s.id,slide:s}))}}catch(e){console.error("[sync:watcher] error handling change:",t,e)}}),t.on("add",async t=>{if(!isPendingWrite(t)&&t.includes("/slides/")&&t.endsWith(".json"))try{const s=transformSlideAssetsToUrls(await readSlide(t),e.id),a=parseSlideFilename(H(t)),c=a?a.order-1:e.slides.length,l=e.slides.findIndex(e=>e.id===s.id);if(-1!==l)return;e.slides.splice(c,0,s),broadcastToSession(e.id,{type:"slide:added",sessionId:e.id,slideId:s.id,slide:s,index:c})}catch(e){console.error("[sync:watcher] error handling add:",t,e)}}),t.on("unlink",t=>{if(!isPendingWrite(t)&&t.includes("/slides/")&&t.endsWith(".json"))try{const s=parseSlideFilename(H(t));if(!s)return;const a=e.slides.findIndex(e=>e.id===s.id);if(-1!==a){const t=e.slides[a].id;e.slides.splice(a,1),broadcastToSession(e.id,{type:"slide:deleted",sessionId:e.id,slideId:t})}}catch(e){console.error("[sync:watcher] error handling unlink:",t,e)}}),e.watcher=t}const Mr=new Map,Ur=new Map;function deckPathToSessionId(e){return d("md5").update(e).digest("hex").slice(0,12)}async function persistSessions(){}async function restoreSessions(){}async function createSyncSession(e,t){const s=await async function(e){const t=await readManifest(e),s=j(e,"slides"),a=(await D(s)).filter(e=>ir.test(e)).sort(),c=[];for(const e of a){const t=await readSlide(j(s,e));c.push(t)}return{manifest:t,slides:c}}(t),a={id:e,deckPath:t,watcher:null,manifest:s.manifest,slides:s.slides,activeInEditor:!1},c=Array.from(Mr.values()).some(e=>e.activeInEditor);return c||(a.activeInEditor=!0),Mr.set(e,a),Ur.set(e,new Set),startSyncWatcher(a),persistSessions(),a}function closeSyncSession(e){const t=Mr.get(e);t&&(!function(e){e.watcher&&(e.watcher.close(),e.watcher=null)}(t),Mr.delete(e),Ur.delete(e),persistSessions())}function getSyncSession(e){return Mr.get(e)}function listSyncSessions(){return Array.from(Mr.values()).map(e=>({id:e.id,deckPath:e.deckPath,slideCount:e.slides.length,activeInEditor:e.activeInEditor}))}function switchActiveSyncSession(e){const t=Mr.get(e);if(t){for(const e of Mr.values())e.activeInEditor=!1;return t.activeInEditor=!0,t}}function hasSyncPeers(e){const t=Ur.get(e);return!!t&&t.size>0}function addSyncPeer(e,t){let s=Ur.get(e);s||(s=new Set,Ur.set(e,s)),s.add(t)}function removeSyncPeerFromAll(e){for(const t of Ur.values())t.delete(e)}function broadcastToSession(e,t){const s=Ur.get(e);if(!s)return;const a=JSON.stringify(t);for(const e of s)try{e.send(a)}catch(e){console.error("[sync:session] failed to send to peer:",e)}}j(e.cwd(),".pptclaw","sessions.json");const qr="https://cloud.mangoppt.com/api",zr=j(ne(),".pptclaw"),Fr=j(zr,"auth.json");let $r=null,Kr=null;async function saveRefreshToken(){await U(zr,{recursive:!0}),await M(Fr,JSON.stringify({refreshToken:Kr}),"utf-8")}async function initCloudAuth(){if(await async function(){try{const e=JSON.parse(await B(Fr,"utf-8"));Kr=e.refreshToken||null}catch{Kr=null}}(),Kr)try{await cloudRefresh(),console.log("[cloudAuth] Restored session from stored refresh token")}catch{console.log("[cloudAuth] Stored refresh token expired or invalid"),Kr=null}}async function cloudLogin(e,t){const s=await fetch(`${qr}/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!s.ok){const e=await s.json().catch(()=>({}));throw createError$1({statusCode:s.status,message:e.statusMessage||e.message||"登录失败"})}const a=await s.json();$r=a.accessToken;const c=(s.headers.get("set-cookie")||"").match(/refreshToken=([^;]+)/);return c&&(Kr=decodeURIComponent(c[1]),await saveRefreshToken()),{accessToken:$r}}async function cloudRefresh(){if(!Kr)throw createError$1({statusCode:401,message:"未登录"});const e=await $fetch(`${qr}/auth/refresh`,{method:"POST",headers:{Cookie:`refreshToken=${Kr}`}});return $r=e.accessToken,{accessToken:$r}}async function getAccessToken(){if($r&&!function(e){try{return 1e3*JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()).exp<Date.now()+3e4}catch{return!0}}($r))return $r;if(!Kr)throw createError$1({statusCode:401,message:"未登录"});return await cloudRefresh(),$r}async function cloudLogout(){Kr&&await fetch(`${qr}/auth/logout`,{method:"POST",headers:{...$r?{Authorization:`Bearer ${$r}`}:{},Cookie:`refreshToken=${Kr}`}}).catch(()=>{}),$r=null,Kr=null,await saveRefreshToken()}async function getCloudAuthHeaders(){try{return{Authorization:`Bearer ${await getAccessToken()}`}}catch{return{}}}function proxyToCloudAuthed(e,t,s={}){return proxyRequest(e,`${qr}/${t}`,{headers:s})}const _mRDyLUsyZ7J6RcuHajia9yXaPEQ_Nk2pdaPGV8CHZoQ=async e=>{console.log("[sync] PPTClaw sync server initializing..."),await Promise.all([restoreSessions(),initCloudAuth()]);const t=listSyncSessions();if(t.length>0){console.log(`[sync] Restored ${t.length} session(s):`);for(const e of t)console.log(` ${e.id} — ${e.deckPath} (${e.slideCount} slides)`)}else console.log("[sync] No sessions to restore")},Gr=[_mRDyLUsyZ7J6RcuHajia9yXaPEQ_Nk2pdaPGV8CHZoQ],Vr={"/.DS_Store":{type:"text/plain; charset=utf-8",etag:'"1804-zPUR3A5Jx6abggDUkWyUsBJN92w"',mtime:"2026-03-18T02:18:06.081Z",size:6148,path:"../public/.DS_Store"},"/alipay.svg":{type:"image/svg+xml",etag:'"da1-2SsdC0JxmDacpq12ab1GrH2nsR8"',mtime:"2026-03-18T02:18:06.081Z",size:3489,path:"../public/alipay.svg"},"/android-chrome-192x192.png":{type:"image/png",etag:'"177f-a+hxWPJ6F1/zk9jFXYmIouNg1k0"',mtime:"2026-03-18T02:18:06.081Z",size:6015,path:"../public/android-chrome-192x192.png"},"/android-chrome-512x512.png":{type:"image/png",etag:'"392c-v5fa4+3B7eWRORLXaQ7KvS5vjLA"',mtime:"2026-03-18T02:18:06.083Z",size:14636,path:"../public/android-chrome-512x512.png"},"/auth-bg.svg":{type:"image/svg+xml",etag:'"c18-TSCNFQebFoQ9l5AyyaxE/b6g1aA"',mtime:"2026-03-18T02:18:06.081Z",size:3096,path:"../public/auth-bg.svg"},"/apple-touch-icon.png":{type:"image/png",etag:'"1441-1Ax0exBVGbfTM1p/GtJ/IId1yp0"',mtime:"2026-03-18T02:18:06.081Z",size:5185,path:"../public/apple-touch-icon.png"},"/auth-logo.svg":{type:"image/svg+xml",etag:'"2fa8-ZOzKmG6/JcG4kjghb5L/jqnJ/SQ"',mtime:"2026-03-18T02:18:06.081Z",size:12200,path:"../public/auth-logo.svg"},"/cursor.png":{type:"image/png",etag:'"26f-3f9uUOjUeuTnP8tNNm84R424YnQ"',mtime:"2026-03-18T02:18:06.081Z",size:623,path:"../public/cursor.png"},"/favicon-16x16.png":{type:"image/png",etag:'"192-AK4rR/PC12TLcpK0ieWhyJkPhgo"',mtime:"2026-03-18T02:18:06.081Z",size:402,path:"../public/favicon-16x16.png"},"/customerServiceQr.png":{type:"image/png",etag:'"b2dd-1BEQ+pEJXTxxZbewFhE2hv7rcGE"',mtime:"2026-03-18T02:18:06.081Z",size:45789,path:"../public/customerServiceQr.png"},"/favicon-32x32.png":{type:"image/png",etag:'"2ce-CPqCr38f6OKcFEPyYZLX1pUjEs8"',mtime:"2026-03-18T02:18:06.081Z",size:718,path:"../public/favicon-32x32.png"},"/favicon.ico":{type:"image/vnd.microsoft.icon",etag:'"3c2e-NkOrflskOnQpu/YM1yZqD+5g5Hs"',mtime:"2026-03-18T02:18:06.081Z",size:15406,path:"../public/favicon.ico"},"/logo.svg":{type:"image/svg+xml",etag:'"2e07-3oltjACGM/Y0WJUEcPygrKL3hFs"',mtime:"2026-03-18T02:18:06.082Z",size:11783,path:"../public/logo.svg"},"/rect.svg":{type:"image/svg+xml",etag:'"15b-vqB51aIjW+UOxbEpBBbmXrxHoSg"',mtime:"2026-03-18T02:18:06.082Z",size:347,path:"../public/rect.svg"},"/site.webmanifest":{type:"application/manifest+json",etag:'"107-vzG6+RvdL83iSkXj8qG+M3M8b2k"',mtime:"2026-03-18T02:18:06.082Z",size:263,path:"../public/site.webmanifest"},"/templates.json":{type:"application/json",etag:'"79ac-lQmIdsxsvxUHUc6dah6mkG0g2cY"',mtime:"2026-03-18T02:18:06.083Z",size:31148,path:"../public/templates.json"},"/watermark.svg":{type:"image/svg+xml",etag:'"4239-0IBc6TzqiAqqWfFhAn9OaMqJIzI"',mtime:"2026-03-18T02:18:06.082Z",size:16953,path:"../public/watermark.svg"},"/wechat-pay-sm.svg":{type:"image/svg+xml",etag:'"4c4-YJoHySAx6v5oZ/On4+pkLJbR+4s"',mtime:"2026-03-18T02:18:06.082Z",size:1220,path:"../public/wechat-pay-sm.svg"},"/wechat-pay.svg":{type:"image/svg+xml",etag:'"fe7-qqmYYQwjIO5hC21Xh8JCkYZfnhQ"',mtime:"2026-03-18T02:18:06.082Z",size:4071,path:"../public/wechat-pay.svg"},"/_nuxt/BAtwhwpp.js":{type:"text/javascript; charset=utf-8",etag:'"386-SiparztUbr9klqXjISc+WLMbmYs"',mtime:"2026-03-18T02:18:06.014Z",size:902,path:"../public/_nuxt/BAtwhwpp.js"},"/_nuxt/BMr1Z083.js":{type:"text/javascript; charset=utf-8",etag:'"227e-RtvVHeNcYWv8opMbvrhK4MKeeuQ"',mtime:"2026-03-18T02:18:06.014Z",size:8830,path:"../public/_nuxt/BMr1Z083.js"},"/_nuxt/BXBiPOBE.js":{type:"text/javascript; charset=utf-8",etag:'"135-16twuQB/Ilz0kTj5YDom17lc2XE"',mtime:"2026-03-18T02:18:06.014Z",size:309,path:"../public/_nuxt/BXBiPOBE.js"},"/_nuxt/BuUsXmAh.js":{type:"text/javascript; charset=utf-8",etag:'"4e0-cHTI9gBXNXso3He1gPVX/zMpP54"',mtime:"2026-03-18T02:18:06.014Z",size:1248,path:"../public/_nuxt/BuUsXmAh.js"},"/_nuxt/CPsbnj8a.js":{type:"text/javascript; charset=utf-8",etag:'"9db-tRjz6ZsCM0xL9skwzYJQKPppnpI"',mtime:"2026-03-18T02:18:06.014Z",size:2523,path:"../public/_nuxt/CPsbnj8a.js"},"/_nuxt/D9BEMGXo.js":{type:"text/javascript; charset=utf-8",etag:'"144-kiu2p1+7JLb63oTLkkcY7a0cGW0"',mtime:"2026-03-18T02:18:06.014Z",size:324,path:"../public/_nuxt/D9BEMGXo.js"},"/_nuxt/DQNz2huy.js":{type:"text/javascript; charset=utf-8",etag:'"d7b-8DIOwok5wV9uqZLModnS5vuGvWM"',mtime:"2026-03-18T02:18:06.014Z",size:3451,path:"../public/_nuxt/DQNz2huy.js"},"/_nuxt/DQxlKO7N.js":{type:"text/javascript; charset=utf-8",etag:'"24f-riC9o+0lakjp72t/4hXRReUraSc"',mtime:"2026-03-18T02:18:06.014Z",size:591,path:"../public/_nuxt/DQxlKO7N.js"},"/_nuxt/_id_.C3K2GZV8.css":{type:"text/css; charset=utf-8",etag:'"25ce0-X4Numow0XeU6nZyfaZT5EjiIxXc"',mtime:"2026-03-18T02:18:06.015Z",size:154848,path:"../public/_nuxt/_id_.C3K2GZV8.css"},"/_nuxt/error-404.BzoSHD6c.css":{type:"text/css; charset=utf-8",etag:'"97e-tCpp7XY8hEix+qjyKK1D7x7GdfE"',mtime:"2026-03-18T02:18:06.015Z",size:2430,path:"../public/_nuxt/error-404.BzoSHD6c.css"},"/_nuxt/error-500.DwAqVzgo.css":{type:"text/css; charset=utf-8",etag:'"773-1fWdO6+oCki1U2ju/kbrrxFOOdM"',mtime:"2026-03-18T02:18:06.015Z",size:1907,path:"../public/_nuxt/error-500.DwAqVzgo.css"},"/_nuxt/entry.BqkL7BC_.css":{type:"text/css; charset=utf-8",etag:'"30e56-cm5zyxI+bq3yw9HBEb67Msp8qlg"',mtime:"2026-03-18T02:18:06.015Z",size:200278,path:"../public/_nuxt/entry.BqkL7BC_.css"},"/animations/arrow.lottie":{type:"application/zip+dotlottie",etag:'"49e-PLQcWISqEB432IIfIcbXfSY8lb4"',mtime:"2026-03-18T02:18:06.079Z",size:1182,path:"../public/animations/arrow.lottie"},"/animations/cubes.lottie":{type:"application/zip+dotlottie",etag:'"12fb-5j/x6CUeHZ2Bmrx+U00tozyrE5E"',mtime:"2026-03-18T02:18:06.079Z",size:4859,path:"../public/animations/cubes.lottie"},"/animations/stars.lottie":{type:"application/zip+dotlottie",etag:'"7d2-Srrw8h/QZgKO5WUHvxpU+Mf0NEA"',mtime:"2026-03-18T02:18:06.080Z",size:2002,path:"../public/animations/stars.lottie"},"/_nuxt/builds/latest.json":{type:"application/json",etag:'"47-WRUhdRvEke+JaSt4hyXM3TwtCUw"',mtime:"2026-03-18T02:18:05.997Z",size:71,path:"../public/_nuxt/builds/latest.json"},"/_nuxt/builds/meta/e405cd67-1e23-4b39-85e1-217b00c69ec7.json":{type:"application/json",etag:'"58-RDKEIZgqUVT+cWhfe1ewoX0DMxU"',mtime:"2026-03-18T02:18:05.990Z",size:88,path:"../public/_nuxt/builds/meta/e405cd67-1e23-4b39-85e1-217b00c69ec7.json"},"/_nuxt/BEQoYl5X.js":{type:"text/javascript; charset=utf-8",etag:'"33a1ea-Wmy+VkeHum6kTnwmiuJtE4dgBJs"',mtime:"2026-03-18T02:18:06.020Z",size:3383786,path:"../public/_nuxt/BEQoYl5X.js"},"/_nuxt/j2eJltcB.js":{type:"text/javascript; charset=utf-8",etag:'"244032-vuaNxP7Tb4vY9+hBW2WReKnPGvc"',mtime:"2026-03-18T02:18:06.019Z",size:2375730,path:"../public/_nuxt/j2eJltcB.js"}},Zr=/^[A-Za-z]:\//;function normalizeWindowsPath(e=""){return e?e.replace(/\\/g,"/").replace(Zr,e=>e.toUpperCase()):e}const Jr=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,Qr=/^[A-Za-z]:$/;function cwd(){return void 0!==e&&"function"==typeof e.cwd?e.cwd().replace(/\\/g,"/"):"/"}const isAbsolute=function(e){return Jr.test(e)};function readAsset(e){const t=function(e){const t=normalizeWindowsPath(e).replace(/\/$/,"").split("/").slice(0,-1);return 1===t.length&&Qr.test(t[0])&&(t[0]+="/"),t.join("/")||(isAbsolute(e)?"/":".")}(oe(globalThis._importMeta_.url));return O.readFile(function(...e){let t="",s=!1;for(let a=(e=e.map(e=>normalizeWindowsPath(e))).length-1;a>=-1&&!s;a--){const c=a>=0?e[a]:cwd();c&&0!==c.length&&(t=`${c}/${t}`,s=isAbsolute(c))}return t=function(e,t){let s="",a=0,c=-1,l=0,d=null;for(let h=0;h<=e.length;++h){if(h<e.length)d=e[h];else{if("/"===d)break;d="/"}if("/"===d){if(c===h-1||1===l);else if(2===l){if(s.length<2||2!==a||"."!==s[s.length-1]||"."!==s[s.length-2]){if(s.length>2){const e=s.lastIndexOf("/");-1===e?(s="",a=0):(s=s.slice(0,e),a=s.length-1-s.lastIndexOf("/")),c=h,l=0;continue}if(s.length>0){s="",a=0,c=h,l=0;continue}}t&&(s+=s.length>0?"/..":"..",a=2)}else s.length>0?s+=`/${e.slice(c+1,h)}`:s=e.slice(c+1,h),a=h-c-1;c=h,l=0}else"."===d&&-1!==l?++l:l=-1}return s}(t,!s),s&&!isAbsolute(t)?`/${t}`:t.length>0?t:"."}(t,Vr[e].path))}const Xr={"/_nuxt/builds/meta/":{maxAge:31536e3},"/_nuxt/builds/":{maxAge:1},"/_nuxt/":{maxAge:31536e3}};function getAsset(e){return Vr[e]}const Yr=new Set(["HEAD","GET"]),es={gzip:".gz",br:".br"},ts=bt(e=>{if(e.method&&!Yr.has(e.method))return;let t,s=decodePath(withLeadingSlash(withoutTrailingSlash(parseURL(e.path).pathname)));const a=[...String(getRequestHeader(e,"accept-encoding")||"").split(",").map(e=>es[e.trim()]).filter(Boolean).sort(),""];for(const e of a)for(const a of[s+e,joinURL(s,"index.html"+e)]){const e=getAsset(a);if(e){t=e,s=a;break}}if(!t){if(function(e=""){if(Vr[e])return!0;for(const t in Xr)if(e.startsWith(t))return!0;return!1}(s))throw function(e,t){e.node.res.removeHeader(t)}(e,"Cache-Control"),createError$1({statusCode:404});return}void 0!==t.encoding&&appendResponseHeader(e,"Vary","Accept-Encoding");if(getRequestHeader(e,"if-none-match")===t.etag)return setResponseStatus(e,304,"Not Modified"),"";const c=getRequestHeader(e,"if-modified-since"),l=new Date(t.mtime);return c&&t.mtime&&new Date(c)>=l?(setResponseStatus(e,304,"Not Modified"),""):(t.type&&!getResponseHeader(e,"Content-Type")&&setResponseHeader(e,"Content-Type",t.type),t.etag&&!getResponseHeader(e,"ETag")&&setResponseHeader(e,"ETag",t.etag),t.mtime&&!getResponseHeader(e,"Last-Modified")&&setResponseHeader(e,"Last-Modified",l.toUTCString()),t.encoding&&!getResponseHeader(e,"Content-Encoding")&&setResponseHeader(e,"Content-Encoding",t.encoding),t.size>0&&!getResponseHeader(e,"Content-Length")&&setResponseHeader(e,"Content-Length",t.size),readAsset(s))}),_lazy_mATxGC=()=>import("../routes/renderer.mjs"),rs=[{route:"",handler:ts,lazy:!1,middleware:!0,method:void 0},{route:"/api/auth/**:path",handler:()=>import("../routes/api/auth/_...path_.mjs"),lazy:!0,middleware:!1,method:void 0},{route:"/api/auth/login",handler:()=>import("../routes/api/auth/login.post.mjs"),lazy:!0,middleware:!1,method:"post"},{route:"/api/auth/logout",handler:()=>import("../routes/api/auth/logout.post.mjs"),lazy:!0,middleware:!1,method:"post"},{route:"/api/auth/user",handler:()=>import("../routes/api/auth/user.get.mjs"),lazy:!0,middleware:!1,method:"get"},{route:"/api/cloud/**:path",handler:()=>import("../routes/api/cloud/_...path_.mjs"),lazy:!0,middleware:!1,method:void 0},{route:"/api/credits/**:path",handler:()=>import("../routes/api/credits/_...path_.mjs"),lazy:!0,middleware:!1,method:void 0},{route:"/api/images/**:path",handler:()=>import("../routes/api/images/_...path_.mjs"),lazy:!0,middleware:!1,method:void 0},{route:"/api/payments/**:path",handler:()=>import("../routes/api/payments/_...path_.mjs"),lazy:!0,middleware:!1,method:void 0},{route:"/api/public/ping",handler:()=>import("../routes/api/public/ping.mjs"),lazy:!0,middleware:!1,method:void 0},{route:"/api/public/test",handler:()=>import("../routes/api/public/test.mjs"),lazy:!0,middleware:!1,method:void 0},{route:"/api/sync/assets/:session/**:filename",handler:()=>import("../routes/api/sync/assets/_session/_...filename_.get.mjs"),lazy:!0,middleware:!1,method:"get"},{route:"/api/sync/close",handler:()=>import("../routes/api/sync/close.post.mjs"),lazy:!0,middleware:!1,method:"post"},{route:"/api/sync/open",handler:()=>import("../routes/api/sync/open.post.mjs"),lazy:!0,middleware:!1,method:"post"},{route:"/api/sync/sessions",handler:()=>import("../routes/api/sync/sessions.get.mjs"),lazy:!0,middleware:!1,method:"get"},{route:"/api/sync/switch",handler:()=>import("../routes/api/sync/switch.post.mjs"),lazy:!0,middleware:!1,method:"post"},{route:"/api/sync/upload",handler:()=>import("../routes/api/sync/upload.post.mjs"),lazy:!0,middleware:!1,method:"post"},{route:"/api/sync/validate",handler:()=>import("../routes/api/sync/validate.post.mjs"),lazy:!0,middleware:!1,method:"post"},{route:"/api/sync/ws",handler:()=>import("../routes/api/sync/ws.mjs"),lazy:!0,middleware:!1,method:void 0},{route:"/__nuxt_error",handler:_lazy_mATxGC,lazy:!0,middleware:!1,method:void 0},{route:"/__nuxt_island/**",handler:defineEventHandler(()=>{}),lazy:!1,middleware:!1,method:void 0},{route:"/**",handler:_lazy_mATxGC,lazy:!0,middleware:!1,method:void 0}];const ss=function(){const e=useRuntimeConfig(),t=new Hookable,captureError=(e,s={})=>{const a=t.callHookParallel("error",e,s).catch(e=>{console.error("Error while capturing another error",e)});if(s.event&&isEvent(s.event)){const t=s.event.context.nitro?.errors;t&&t.push({error:e,context:s}),s.event.waitUntil&&s.event.waitUntil(a)}},s=createApp({debug:destr(!1),onError:(e,t)=>(captureError(e,{event:t,tags:["request"]}),async function(e,t){for(const s of or)try{if(await s(e,t,{defaultHandler:defaultHandler}),t.handled)return}catch(e){console.error(e)}}(e,t)),onRequest:async e=>{e.context.nitro=e.context.nitro||{errors:[]};const t=e.node.req?.__unenv__;t?._platform&&(e.context={_platform:t?._platform,...t._platform,...e.context}),!e.context.waitUntil&&t?.waitUntil&&(e.context.waitUntil=t.waitUntil),e.fetch=(t,s)=>fetchWithEvent(e,t,s,{fetch:localFetch}),e.$fetch=(t,s)=>fetchWithEvent(e,t,s,{fetch:l}),e.waitUntil=t=>{e.context.nitro._waitUntilPromises||(e.context.nitro._waitUntilPromises=[]),e.context.nitro._waitUntilPromises.push(t),e.context.waitUntil&&e.context.waitUntil(t)},e.captureError=(t,s)=>{captureError(t,{event:e,...s})},await ss.hooks.callHook("request",e).catch(t=>{captureError(t,{event:e,tags:["request"]})})},onBeforeResponse:async(e,t)=>{await ss.hooks.callHook("beforeResponse",e,t).catch(t=>{captureError(t,{event:e,tags:["request","response"]})})},onAfterResponse:async(e,t)=>{await ss.hooks.callHook("afterResponse",e,t).catch(t=>{captureError(t,{event:e,tags:["request","response"]})})}}),a=function(e={}){const t=createRouter$1({}),s={};let a;const c={},addRoute=(e,a,l)=>{let d=s[e];if(d||(s[e]=d={path:e,handlers:{}},t.insert(e,d)),Array.isArray(l))for(const t of l)addRoute(e,a,t);else d.handlers[l]=toEventHandler(a,0,e);return c};c.use=c.add=(e,t,s)=>addRoute(e,t,s||"all");for(const e of vt)c[e]=(t,s)=>c.add(t,s,e);const matchHandler=(e="/",s="get")=>{const c=e.indexOf("?");-1!==c&&(e=e.slice(0,Math.max(0,c)));const l=t.lookup(e);if(!l||!l.handlers)return{error:createError$1({statusCode:404,name:"Not Found",statusMessage:`Cannot find any route matching ${e||"/"}.`})};let d=l.handlers[s]||l.handlers.all;if(!d){a||(a=toRouteMatcher(t));const c=a.matchAll(e).reverse();for(const e of c){if(e.handlers[s]){d=e.handlers[s],l.handlers[s]=l.handlers[s]||d;break}if(e.handlers.all){d=e.handlers.all,l.handlers.all=l.handlers.all||d;break}}}return d?{matched:l,handler:d}:{error:createError$1({statusCode:405,name:"Method Not Allowed",statusMessage:`Method ${s} is not allowed on this route.`})}},l=e.preemptive||e.preemtive;return c.handler=bt(e=>{const t=matchHandler(e.path,e.method.toLowerCase());if("error"in t){if(l)throw t.error;return}e.context.matchedRoute=t.matched;const s=t.matched.params||{};return e.context.params=s,Promise.resolve(t.handler(e)).then(e=>void 0===e&&l?null:e)}),c.handler.__resolve__=async e=>{e=withLeadingSlash(e);const t=matchHandler(e);if("error"in t)return;let s={route:t.matched.path,handler:t.handler};if(t.handler.__resolve__){const a=await t.handler.__resolve__(e);if(!a)return;s={...s,...a}}return s},c}({preemptive:!0}),c=toNodeListener(s),localFetch=(e,t)=>e.toString().startsWith("/")?async function(e,t,s={}){try{const a=await b(e,{url:t,...s});return new Response(a.body,{status:a.status,statusText:a.statusText,headers:v(a.headers)})}catch(e){return new Response(e.toString(),{status:Number.parseInt(e.statusCode||e.code)||500,statusText:e.statusText})}}(c,e,t).then(e=>function(e){return e.headers.has("set-cookie")?new Response(e.body,{status:e.status,statusText:e.statusText,headers:normalizeCookieHeaders(e.headers)}):e}(e)):globalThis.fetch(e,t),l=createFetch({fetch:localFetch,Headers:Nt,defaults:{baseURL:e.app.baseURL}});globalThis.$fetch=l,s.use(createRouteRulesHandler({localFetch:localFetch}));for(const t of rs){let c=t.lazy?lazyEventHandler(t.handler):t.handler;if(t.middleware||!t.route){const a=(e.app.baseURL+(t.route||"/")).replace(/\/+/g,"/");s.use(a,c)}else{const e=getRouteRulesForPath(t.route.replace(/:\w+|\*\*/g,"_"));e.cache&&(c=cachedEventHandler(c,{group:"nitro/routes",...e.cache})),a.use(t.route,c,t.method)}}return s.use(e.app.baseURL,a.handler),{hooks:t,h3App:s,router:a,localCall:e=>b(c,e),localFetch:localFetch,captureError:captureError}}();function useNitroApp(){return ss}function defineRenderHandler(e){const t=useRuntimeConfig();return bt(async s=>{const a=useNitroApp(),c={event:s,render:e,response:void 0};if(await a.hooks.callHook("render:before",c),!c.response){if(s.path===`${t.app.baseURL}favicon.ico`)return setResponseHeader(s,"Content-Type","image/x-icon"),send(s,"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7");if(c.response=await c.render(s),!c.response){const e=getResponseStatus(s);return setResponseStatus(s,200===e?500:e),send(s,"No response returned from render handler: "+s.path)}}return await a.hooks.callHook("render:response",c.response,c),c.response.headers&&setResponseHeaders(s,c.response.headers),(c.response.statusCode||c.response.statusMessage)&&setResponseStatus(s,c.response.statusCode,c.response.statusMessage),c.response.body})}!function(e){for(const t of Gr)try{t(e)}catch(t){throw e.captureError(t,{tags:["plugin"]}),t}}(ss);function GracefulShutdown(s,a){a=a||{};const c=Object.assign({signals:"SIGINT SIGTERM",timeout:3e4,development:!1,forceExit:!0,onShutdown:e=>Promise.resolve(e),preShutdown:e=>Promise.resolve(e)},a);let l=!1;const d={};let h=0;const u={};let f=0,m=!1,g=!1;const _=c.signals.split(" ").map(e=>e.trim()).filter(e=>e.length>0),S=function(){let e=!1;return(t,s,a)=>{function call(){if(!e)return e=!0,Reflect.apply(a,this,arguments)}for(const e of s)t.on(e,call)}}();function destroy(e,s=!1){(e._isIdle&&l||s)&&(e.destroy(),e.server instanceof t.Server?delete d[e._connectionId]:delete u[e._connectionId])}function destroyAllConnections(e=!1){for(const t of Object.keys(d)){const s=d[t],a=s._httpMessage;a&&!e?a.headersSent||a.setHeader("connection","close"):destroy(s)}for(const t of Object.keys(u)){const s=u[t],a=s._httpMessage;a&&!e?a.headersSent||a.setHeader("connection","close"):destroy(s)}}function shutdown(t){if(c.development)return e.exit(0);function waitForReadyToShutDown(e){if(0===e)return c.timeout,Promise.resolve(!0);return 0===Object.keys(d).length&&0===Object.keys(u).length?Promise.resolve(!1):new Promise(t=>{setTimeout(()=>{t(waitForReadyToShutDown(e-1))},250)})}return l?Promise.resolve():c.preShutdown(t).then(()=>{l=!0,destroyAllConnections(),new Promise((e,t)=>{s.close(s=>s?t(s):e(!0))})}).then(()=>waitForReadyToShutDown(c.timeout?Math.round(c.timeout/250):0)).then(e=>(e&&destroyAllConnections(e),c.onShutdown(t))).then(function(){return g||(g=!0,c.finally&&function(e){const t=Object.prototype.toString.call(e);return/^\[object\s([A-Za-z]+)?Function]$/.test(t)}(c.finally)&&c.finally()),Promise.resolve()}).catch(e=>{const t="string"==typeof e?e:JSON.stringify(e);throw m=!0,t})}return S(e,_,t=>{shutdown(t).then(()=>{c.forceExit&&e.exit(m?1:0)}).catch(t=>{e.exit(1)})}),s.on("request",(e,t)=>{e.socket._isIdle=!1,l&&!t.headersSent&&t.setHeader("connection","close"),t.on("finish",()=>{e.socket._isIdle=!0,destroy(e.socket)})}),s.on("connection",e=>{if(l)e.destroy();else{const t=h++;e._isIdle=!0,e._connectionId=t,d[t]=e,e.once("close",()=>{delete d[e._connectionId]})}}),s.on("secureConnection",e=>{if(l)e.destroy();else{const t=f++;e._isIdle=!0,e._connectionId=t,u[t]=e,e.once("close",()=>{delete u[e._connectionId]})}}),e.on("close",()=>{}),function(){return shutdown("manual")}}const ns=e.env.NITRO_SSL_CERT,os=e.env.NITRO_SSL_KEY,is=useNitroApp(),as=ns&&os?new c({key:os,cert:ns},toNodeListener(is.h3App)):new s(toNodeListener(is.h3App)),cs=destr(e.env.NITRO_PORT||e.env.PORT)||3e3,ls=e.env.NITRO_HOST||e.env.HOST,ds=e.env.NITRO_UNIX_SOCKET,hs=as.listen(ds?{path:ds}:{port:cs,host:ls},t=>{t&&(console.error(t),e.exit(1));const s=ns&&os?"https":"http",a=hs.address();if("string"==typeof a)return void console.log(`Listening on unix socket ${a}`);const c=(useRuntimeConfig().app.baseURL||"").replace(/\/$/,""),l=`${s}://${"IPv6"===a.family?`[${a.address}]`:a.address}:${a.port}${c}`;console.log(`Listening on ${l}`)});e.on("unhandledRejection",e=>_captureError(e,"unhandledRejection")),e.on("uncaughtException",e=>_captureError(e,"uncaughtException")),function(t,s){const a={disabled:!!e.env.NITRO_SHUTDOWN_DISABLED,signals:(e.env.NITRO_SHUTDOWN_SIGNALS||"SIGTERM SIGINT").split(" ").map(e=>e.trim()),timeout:Number.parseInt(e.env.NITRO_SHUTDOWN_TIMEOUT||"",10)||3e4,forceExit:!e.env.NITRO_SHUTDOWN_NO_FORCE_EXIT};a.disabled||GracefulShutdown(t,{signals:a.signals.join(" "),timeout:a.timeout,forceExit:a.forceExit,onShutdown:async()=>{await new Promise(e=>{const t=setTimeout(()=>{console.warn("Graceful shutdown timeout, force exiting..."),e()},a.timeout);s.hooks.callHook("close").catch(e=>{console.error(e)}).finally(()=>{clearTimeout(t),e()})})}})}(hs,is);{const{handleUpgrade:e}=nodeAdapter(is.h3App.websocket);as.on("upgrade",e)}const us={};export{removeSyncPeerFromAll as A,addSyncPeer as B,transformSlideAssetsToDisk as C,writeSlide as D,writeManifest as E,writeDeck as F,withLeadingSlash as G,joinRelativeURL as H,useRuntimeConfig as I,getResponseStatusText as J,getResponseStatus as K,decodePath as L,defineRenderHandler as M,destr as N,getRouteRules as O,joinURL as P,useNitroApp as Q,us as R,getCloudAuthHeaders as a,cloudLogout as b,cloudLogin as c,defineEventHandler as d,getQuery as e,getSyncSession as f,getRouterParam as g,createError$1 as h,sendStream as i,closeSyncSession as j,getRequestHost as k,listSyncSessions as l,hasSyncPeers as m,deckPathToSessionId as n,createSyncSession as o,proxyToCloudAuthed as p,switchActiveSyncSession as q,readBody as r,gt as s,transformSlideAssetsToUrls as t,broadcastToSession as u,readMultipartFormData as v,markPendingWrite as w,parseSlideFilename as x,buildSlideFilename as y,defineWebSocketHandler as z};
@@ -0,0 +1 @@
1
+ import{d as t,g as o,a as r,p}from"../../../nitro/nitro.mjs";import"node:http";import"node:https";import"node:crypto";import"stream";import"events";import"http";import"crypto";import"buffer";import"zlib";import"https";import"net";import"tls";import"url";import"node:events";import"node:buffer";import"node:fs";import"node:path";import"node:fs/promises";import"fs";import"fs/promises";import"path";import"node:stream";import"os";import"node:os";import"node:url";const i=["register","sendCode","forget"],m=t(async t=>{const m=o(t,"path"),e=!i.some(t=>m.startsWith(t))?await r():{};return p(t,`auth/${m}`,e)});export{m as default};
@@ -0,0 +1 @@
1
+ import{d as t,r as o,c as r}from"../../../nitro/nitro.mjs";import"node:http";import"node:https";import"node:crypto";import"stream";import"events";import"http";import"crypto";import"buffer";import"zlib";import"https";import"net";import"tls";import"url";import"node:events";import"node:buffer";import"node:fs";import"node:path";import"node:fs/promises";import"fs";import"fs/promises";import"path";import"node:stream";import"os";import"node:os";import"node:url";const p=t(async t=>{const p=await o(t);return r(p.username,p.password)});export{p as default};
@@ -0,0 +1 @@
1
+ import{d as t,b as o}from"../../../nitro/nitro.mjs";import"node:http";import"node:https";import"node:crypto";import"stream";import"events";import"http";import"crypto";import"buffer";import"zlib";import"https";import"net";import"tls";import"url";import"node:events";import"node:buffer";import"node:fs";import"node:path";import"node:fs/promises";import"fs";import"fs/promises";import"path";import"node:stream";import"os";import"node:os";import"node:url";const r=t(async()=>(await o(),{status:"OK"}));export{r as default};
@@ -0,0 +1 @@
1
+ import{d as t,a as o,p as r}from"../../../nitro/nitro.mjs";import"node:http";import"node:https";import"node:crypto";import"stream";import"events";import"http";import"crypto";import"buffer";import"zlib";import"https";import"net";import"tls";import"url";import"node:events";import"node:buffer";import"node:fs";import"node:path";import"node:fs/promises";import"fs";import"fs/promises";import"path";import"node:stream";import"os";import"node:os";import"node:url";const p=t(async t=>{const p=await o();return r(t,"auth/user",p)});export{p as default};
@@ -0,0 +1 @@
1
+ import{d as t,g as o,a as r,p}from"../../../nitro/nitro.mjs";import"node:http";import"node:https";import"node:crypto";import"stream";import"events";import"http";import"crypto";import"buffer";import"zlib";import"https";import"net";import"tls";import"url";import"node:events";import"node:buffer";import"node:fs";import"node:path";import"node:fs/promises";import"fs";import"fs/promises";import"path";import"node:stream";import"os";import"node:os";import"node:url";const i=t(async t=>{const i=o(t,"path"),m=await r();return p(t,i,m)});export{i as default};
@@ -0,0 +1 @@
1
+ import{d as t,g as o,a as r,p}from"../../../nitro/nitro.mjs";import"node:http";import"node:https";import"node:crypto";import"stream";import"events";import"http";import"crypto";import"buffer";import"zlib";import"https";import"net";import"tls";import"url";import"node:events";import"node:buffer";import"node:fs";import"node:path";import"node:fs/promises";import"fs";import"fs/promises";import"path";import"node:stream";import"os";import"node:os";import"node:url";const i=t(async t=>{const i=o(t,"path"),m=await r();return p(t,`credits/${i}`,m)});export{i as default};
@@ -0,0 +1 @@
1
+ import{d as t,g as o,a as r,p}from"../../../nitro/nitro.mjs";import"node:http";import"node:https";import"node:crypto";import"stream";import"events";import"http";import"crypto";import"buffer";import"zlib";import"https";import"net";import"tls";import"url";import"node:events";import"node:buffer";import"node:fs";import"node:path";import"node:fs/promises";import"fs";import"fs/promises";import"path";import"node:stream";import"os";import"node:os";import"node:url";const i=t(async t=>{const i=o(t,"path"),m=await r();return p(t,`images/${i}`,m)});export{i as default};
@@ -0,0 +1 @@
1
+ import{d as t,g as o,a as r,p}from"../../../nitro/nitro.mjs";import"node:http";import"node:https";import"node:crypto";import"stream";import"events";import"http";import"crypto";import"buffer";import"zlib";import"https";import"net";import"tls";import"url";import"node:events";import"node:buffer";import"node:fs";import"node:path";import"node:fs/promises";import"fs";import"fs/promises";import"path";import"node:stream";import"os";import"node:os";import"node:url";const m=t(async t=>{const m=o(t,"path"),i=await r();return p(t,`payments/${m}`,i)});export{m as default};
@@ -0,0 +1 @@
1
+ import{d as t,e as o}from"../../../nitro/nitro.mjs";import"node:http";import"node:https";import"node:crypto";import"stream";import"events";import"http";import"crypto";import"buffer";import"zlib";import"https";import"net";import"tls";import"url";import"node:events";import"node:buffer";import"node:fs";import"node:path";import"node:fs/promises";import"fs";import"fs/promises";import"path";import"node:stream";import"os";import"node:os";import"node:url";const r=t(async t=>(o(t),{success:!0}));export{r as default};
@@ -0,0 +1 @@
1
+ import{d as t}from"../../../nitro/nitro.mjs";import"node:http";import"node:https";import"node:crypto";import"stream";import"events";import"http";import"crypto";import"buffer";import"zlib";import"https";import"net";import"tls";import"url";import"node:events";import"node:buffer";import"node:fs";import"node:path";import"node:fs/promises";import"fs";import"fs/promises";import"path";import"node:stream";import"os";import"node:os";import"node:url";const o=t(async t=>"test");export{o as default};
@@ -0,0 +1 @@
1
+ import{d as o,g as t,f as e,h as i,s as p,i as s}from"../../../../../nitro/nitro.mjs";import{createReadStream as m}from"node:fs";import{stat as r}from"node:fs/promises";import{join as a,extname as n}from"node:path";import"node:http";import"node:https";import"node:crypto";import"stream";import"events";import"http";import"crypto";import"buffer";import"zlib";import"https";import"net";import"tls";import"url";import"node:events";import"node:buffer";import"fs";import"fs/promises";import"path";import"node:stream";import"os";import"node:os";import"node:url";const d={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".pdf":"application/pdf",".json":"application/json"},g=o(async o=>{const g=t(o,"session"),f=decodeURIComponent(t(o,"filename")),c=e(g);if(!c)throw i({statusCode:404,message:"Session not found"});if(f.includes(".."))throw i({statusCode:400,message:"Invalid filename"});const u=a(c.deckPath,"assets",f);try{await r(u)}catch{throw i({statusCode:404,message:"Asset not found"})}const l=n(u).toLowerCase();p(o,"Content-Type",d[l]||"application/octet-stream"),p(o,"Cache-Control","public, max-age=3600");const h=m(u);return s(o,h)});export{g as default};
@@ -0,0 +1 @@
1
+ import{d as t,r as o,h as r,j as i}from"../../../nitro/nitro.mjs";import"node:http";import"node:https";import"node:crypto";import"stream";import"events";import"http";import"crypto";import"buffer";import"zlib";import"https";import"net";import"tls";import"url";import"node:events";import"node:buffer";import"node:fs";import"node:path";import"node:fs/promises";import"fs";import"fs/promises";import"path";import"node:stream";import"os";import"node:os";import"node:url";const p=t(async t=>{const p=await o(t),{sessionId:s}=p;if(!s)throw r({statusCode:400,message:"sessionId is required"});return i(s),{ok:!0}});export{p as default};
@@ -0,0 +1 @@
1
+ import{d as o,r as t,h as s,k as r,l as e,m as i,n as p,o as n}from"../../../nitro/nitro.mjs";import{resolve as d}from"node:path";import{exec as m}from"node:child_process";import"node:http";import"node:https";import"node:crypto";import"stream";import"events";import"http";import"crypto";import"buffer";import"zlib";import"https";import"net";import"tls";import"url";import"node:events";import"node:buffer";import"node:fs";import"node:fs/promises";import"fs";import"fs/promises";import"path";import"node:stream";import"os";import"node:os";import"node:url";function openBrowser(o){const t="darwin"===process.platform?"open":"win32"===process.platform?"start":"xdg-open";m(`${t} "${o}"`)}const a=o(async o=>{const m=await t(o),{path:a,sessionId:c}=m;if(!a)throw s({statusCode:400,message:"path is required"});const h=d(a),f=r(o,{xForwardedHost:!0});(null==f?void 0:f.split(":")[1])||process.env.PORT||process.env.NUXT_PORT;const l=e().find(o=>o.deckPath===h);if(l)return i(l.id)||openBrowser(`http://${f}/docs/${l.id}`),{sessionId:l.id,deckPath:l.deckPath,slideCount:l.slideCount};const u=c||p(h),w=await n(u,h);return openBrowser(`http://${f}/docs/${w.id}`),{sessionId:w.id,deckPath:w.deckPath,slideCount:w.slides.length}});export{a as default};
@@ -0,0 +1 @@
1
+ import{d as t,l as o}from"../../../nitro/nitro.mjs";import"node:http";import"node:https";import"node:crypto";import"stream";import"events";import"http";import"crypto";import"buffer";import"zlib";import"https";import"net";import"tls";import"url";import"node:events";import"node:buffer";import"node:fs";import"node:path";import"node:fs/promises";import"fs";import"fs/promises";import"path";import"node:stream";import"os";import"node:os";import"node:url";const r=t(()=>o());export{r as default};
@@ -0,0 +1 @@
1
+ import{d as t,r as o,h as s,q as i,t as e,u as r}from"../../../nitro/nitro.mjs";import"node:http";import"node:https";import"node:crypto";import"stream";import"events";import"http";import"crypto";import"buffer";import"zlib";import"https";import"net";import"tls";import"url";import"node:events";import"node:buffer";import"node:fs";import"node:path";import"node:fs/promises";import"fs";import"fs/promises";import"path";import"node:stream";import"os";import"node:os";import"node:url";const p=t(async t=>{const p=await o(t),{sessionId:m}=p;if(!m)throw s({statusCode:400,message:"sessionId is required"});const n=i(m);if(!n)throw s({statusCode:404,message:"Session not found"});const d={manifest:n.manifest,slides:n.slides.map(t=>e(t,n.id))};return r(n.id,{type:"session:switched",sessionId:n.id,deck:d}),{sessionId:n.id,deckPath:n.deckPath}});export{p as default};
@@ -0,0 +1 @@
1
+ import{d as t,v as o,h as s,f as e,w as r}from"../../../nitro/nitro.mjs";import{join as i}from"node:path";import{mkdir as m,writeFile as a}from"node:fs/promises";import{existsSync as n}from"node:fs";import"node:http";import"node:https";import"node:crypto";import"stream";import"events";import"http";import"crypto";import"buffer";import"zlib";import"https";import"net";import"tls";import"url";import"node:events";import"node:buffer";import"fs";import"fs/promises";import"path";import"node:stream";import"os";import"node:os";import"node:url";const p=t(async t=>{const p=await o(t);if(!p)throw s({statusCode:400,message:"No form data"});const d=p.find(t=>"sessionId"===t.name),f=p.find(t=>"image"===t.name);if(!d||!f)throw s({statusCode:400,message:"sessionId and image are required"});const c=d.data.toString("utf-8"),u=e(c);if(!u)throw s({statusCode:404,message:`Session not found: ${c}`});const l=f.filename||"image.png",h=i(u.deckPath,"assets");await m(h,{recursive:!0});let g=l,w=1;for(;n(i(h,g));){const t=l.lastIndexOf(".");g=`${t>0?l.slice(0,t):l}-${w}${t>0?l.slice(t):""}`,w++}const $=i(h,g);r($),await a($,f.data);return{success:!0,url:`/api/sync/assets/${c}/${encodeURIComponent(g)}`,filename:g}});export{p as default};