hytopia 0.8.6-devtrace-34d95d5 → 0.8.6-devtrace-6d51c5e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/node-server.mjs CHANGED
@@ -455,7 +455,7 @@ qYGMwU/HBVHkLAn5XvT2a9xM0mzZ558d+ahbw8qAgRxg7BZ+2PW/bf7F2WRBUk1f
455
455
  xauhAoGBALEspoxQozwohGQnP7EMF0/0JoKNpdNv0b0qCVvNiMo0+N297lI2mFQp
456
456
  6xYlW/1l9afLokklF/J2IsyBrTCZoY7SaEk/lMMrQSyra+y0z71ogZ8A4ny9fxsj
457
457
  0dDYJZGllL+3E/MQfd7k+KnOM/+A+cPoAnci76+L3vdkUb2P8SJk
458
- -----END RSA PRIVATE KEY-----`;var UA=process.env.PORT??8080,BA="0.8.6-devtrace-34d95d5",LA;(($)=>{$.READY="WEBSERVER.READY";$.STOPPED="WEBSERVER.STOPPED";$.ERROR="WEBSERVER.ERROR";$.UPGRADE="WEBSERVER.UPGRADE"})(LA||={});class I3 extends O0{static instance=new I3;_webserver=zN.default();_internalHttpServer;constructor(){super();this._webserver.use((Z,J,X)=>{J.header("Access-Control-Allow-Origin","*"),X()}),this._webserver.get("/",(Z,J)=>{J.json({status:"OK",version:BA,runtime:typeof Bun!=="undefined"?"bun":"node"})}),this._webserver.use(zN.default.static("assets"));try{this._webserver.use(zN.default.static(Pe1.dirname(m.resolve("/Users/arkdev/Desktop/HYTOPIA/hytopia/assets/release/index.js"))))}catch{}}start(){if(!this._internalHttpServer)this._internalHttpServer=process.env.NODE_ENV==="production"?je1.createServer(this._webserver):De1.createServer({key:VN.existsSync("assets/certs/localhost.key")?VN.readFileSync("assets/certs/localhost.key"):wW0,cert:VN.existsSync("assets/certs/localhost.crt")?VN.readFileSync("assets/certs/localhost.crt"):LW0},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else c.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(UA,this._onStarted),console.info(`WebServer.start(): Server running on port ${UA}.`)}stop(){if(this._internalHttpServer)return new Promise((Z,J)=>{this._internalHttpServer.close((X)=>{if(X)J(X);else Z(!0)})});else return c.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=async(Z,J,X)=>{let Y=Ce1.parse(Z.url??"",!0).query,$=Y.connectionId?.toString(),Q=Y.sessionToken?.toString()??"";if($&&YZ.instance.isValidConnectionId($))Z.connectionId=$;else{let K=await p7.instance.getPlayerSession(Q);if(K?.error){let W=`${K.error.code}: ${K.error.message}`;J.write(`HTTP/1.1 401 Unauthorized\r
458
+ -----END RSA PRIVATE KEY-----`;var UA=process.env.PORT??8080,BA="0.8.6-devtrace-6d51c5e",LA;(($)=>{$.READY="WEBSERVER.READY";$.STOPPED="WEBSERVER.STOPPED";$.ERROR="WEBSERVER.ERROR";$.UPGRADE="WEBSERVER.UPGRADE"})(LA||={});class I3 extends O0{static instance=new I3;_webserver=zN.default();_internalHttpServer;constructor(){super();this._webserver.use((Z,J,X)=>{J.header("Access-Control-Allow-Origin","*"),X()}),this._webserver.get("/",(Z,J)=>{J.json({status:"OK",version:BA,runtime:typeof Bun!=="undefined"?"bun":"node"})}),this._webserver.use(zN.default.static("assets"));try{this._webserver.use(zN.default.static(Pe1.dirname(m.resolve("/Users/arkdev/Desktop/HYTOPIA/hytopia/assets/release/index.js"))))}catch{}}start(){if(!this._internalHttpServer)this._internalHttpServer=process.env.NODE_ENV==="production"?je1.createServer(this._webserver):De1.createServer({key:VN.existsSync("assets/certs/localhost.key")?VN.readFileSync("assets/certs/localhost.key"):wW0,cert:VN.existsSync("assets/certs/localhost.crt")?VN.readFileSync("assets/certs/localhost.crt"):LW0},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else c.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(UA,this._onStarted),console.info(`WebServer.start(): Server running on port ${UA}.`)}stop(){if(this._internalHttpServer)return new Promise((Z,J)=>{this._internalHttpServer.close((X)=>{if(X)J(X);else Z(!0)})});else return c.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=async(Z,J,X)=>{let Y=Ce1.parse(Z.url??"",!0).query,$=Y.connectionId?.toString(),Q=Y.sessionToken?.toString()??"";if($&&YZ.instance.isValidConnectionId($))Z.connectionId=$;else{let K=await p7.instance.getPlayerSession(Q);if(K?.error){let W=`${K.error.code}: ${K.error.message}`;J.write(`HTTP/1.1 401 Unauthorized\r
459
459
  Content-Type: text/plain\r
460
460
  Content-Length: ${W.length}\r
461
461
  Connection: close\r
@@ -490,4 +490,4 @@ ${$.stack}`:"unknown"}}}}}var rT8=(Z={})=>{let J=Z.limit??lT8;return{name:pT8,pr
490
490
  `;let W=ZX1(Y);Y.write(`${K}\r
491
491
  `);let{connect:G,buffered:V}=await W;if(Z.emit("proxyConnect",G),this.emit("proxyConnect",G,Z),G.statusCode===200){if(Z.once("socket",gJ6),J.secureEndpoint){OU("Upgrading socket connection to TLS");let F=J.servername||J.host;return Mg.connect({...JX1(J,"host","path","port"),socket:Y,servername:dJ.isIP(F)?void 0:F})}return Y}Y.destroy();let z=new dJ.Socket({writable:!1});return z.readable=!0,Z.once("socket",(F)=>{OU("Replaying proxy buffer for failed request"),F.push(V),F.push(null)}),z}}Sj.__initStatic();function gJ6(Z){Z.resume()}function JX1(Z,...J){let X={},Y;for(Y in Z)if(!J.includes(Y))X[Y]=Z[Y];return X}var lJ6=32768;function pJ6(Z){return new dJ6({read(){this.push(Z),this.push(null)}})}function MU(Z){let J;try{J=new URL(Z.url)}catch(G){return e0(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),KG(Z,()=>Promise.resolve({}))}let X=J.protocol==="https:",Y=iJ6(J,Z.proxy||(X?process.env.https_proxy:void 0)||process.env.http_proxy),$=X?uJ6:mJ6,Q=Z.keepAlive===void 0?!1:Z.keepAlive,K=Y?new Sj(Y):new $.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),W=nJ6(Z,Z.httpModule??$,K);return KG(Z,W)}function iJ6(Z,J){let{no_proxy:X}=process.env;if(X?.split(",").some(($)=>Z.host.endsWith($)||Z.hostname.endsWith($)))return;else return J}function nJ6(Z,J,X){let{hostname:Y,pathname:$,port:Q,protocol:K,search:W}=new URL(Z.url);return function G(V){return new Promise((z,F)=>{cQ(()=>{let H=pJ6(V.body),q={...Z.headers};if(V.body.length>lJ6)q["content-encoding"]="gzip",H=H.pipe(cJ6());let U=J.request({method:"POST",agent:X,headers:q,hostname:Y,path:`${$}${W}`,port:Q,protocol:K,ca:Z.caCerts},(B)=>{B.on("data",()=>{}),B.on("end",()=>{}),B.setEncoding("utf8");let L=B.headers["retry-after"]??null,w=B.headers["x-sentry-rate-limits"]??null;z({statusCode:B.statusCode,headers:{"retry-after":L,"x-sentry-rate-limits":Array.isArray(w)?w[0]||null:w}})});U.on("error",F),H.pipe(U)})})}}var aJ6=new Set(["false","f","n","no","off","0"]),sJ6=new Set(["true","t","y","yes","on","1"]);function Aj(Z,J){let X=String(Z).toLowerCase();if(aJ6.has(X))return!1;if(sJ6.has(X))return!0;return J?.strict?null:Boolean(Z)}import{posix as oJ6,sep as rJ6}from"node:path";function XX1(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function NU(Z=process.argv[1]?_y(process.argv[1]):process.cwd(),J=rJ6==="\\"){let X=J?XX1(Z):Z;return(Y)=>{if(!Y)return;let $=J?XX1(Y):Y,{dir:Q,base:K,ext:W}=oJ6.parse($);if(W===".js"||W===".mjs"||W===".cjs")K=K.slice(0,W.length*-1);let G=decodeURIComponent(K);if(!Q)Q=".";let V=Q.lastIndexOf("/node_modules");if(V>-1)return`${Q.slice(V+14).replace(/\//g,".")}:${G}`;if(Q.startsWith(X)){let z=Q.slice(X.length+1).replace(/\//g,".");return z?`${z}:${G}`:G}return G}}function RU(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(M0.SENTRY_RELEASE?.id)return M0.SENTRY_RELEASE.id;let J=process.env.GITHUB_SHA||process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA||process.env.CI_BUILD_REF||process.env.CI_COMMIT_SHA||process.env.BITBUCKET_COMMIT,X=process.env.APPVEYOR_PULL_REQUEST_HEAD_COMMIT||process.env.APPVEYOR_REPO_COMMIT||process.env.CODEBUILD_RESOLVED_SOURCE_VERSION||process.env.AWS_COMMIT_ID||process.env.BUILD_SOURCEVERSION||process.env.GIT_CLONE_COMMIT_HASH||process.env.BUDDY_EXECUTION_REVISION||process.env.BUILDKITE_COMMIT||process.env.CIRCLE_SHA1||process.env.CIRRUS_CHANGE_IN_REPO||process.env.CF_REVISION||process.env.CM_COMMIT||process.env.CF_PAGES_COMMIT_SHA||process.env.DRONE_COMMIT_SHA||process.env.FC_GIT_COMMIT_SHA||process.env.HEROKU_TEST_RUN_COMMIT_VERSION||process.env.HEROKU_SLUG_COMMIT||process.env.RAILWAY_GIT_COMMIT_SHA||process.env.RENDER_GIT_COMMIT||process.env.SEMAPHORE_GIT_SHA||process.env.TRAVIS_PULL_REQUEST_SHA||process.env.VERCEL_GIT_COMMIT_SHA||process.env.VERCEL_GITHUB_COMMIT_SHA||process.env.VERCEL_GITLAB_COMMIT_SHA||process.env.VERCEL_BITBUCKET_COMMIT_SHA||process.env.ZEIT_GITHUB_COMMIT_SHA||process.env.ZEIT_GITLAB_COMMIT_SHA||process.env.ZEIT_BITBUCKET_COMMIT_SHA,Y=process.env.CI_COMMIT_ID||process.env.SOURCE_COMMIT||process.env.SOURCE_VERSION||process.env.GIT_COMMIT||process.env.COMMIT_REF||process.env.BUILD_VCS_NUMBER||process.env.CI_COMMIT_SHA;return J||X||Y||Z}var jU=RR(Kb(NU()));var $X1=r(Y0(),1),QX1=r(r0(),1);import*as YX1 from"node:os";import{threadId as tJ6,isMainThread as eJ6}from"worker_threads";var ZX6=60000;class IG extends pR{constructor(Z){let J=Z.includeServerName===!1?void 0:Z.serverName||global.process.env.SENTRY_NAME||YX1.hostname(),X={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)QX1.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});nQ(X,"node"),h.log(`Initializing Sentry: process: ${process.pid}, thread: ${eJ6?"main":`worker-${tJ6}`}.`);super(X);let{enableLogs:Y,_experiments:$}=this.getOptions();if(Y??$?.enableLogs){if(this._logOnExitFlushListener=()=>{NY(this)},J)this.on("beforeCaptureLog",(K)=>{K.attributes={...K.attributes,"server.address":J}});process.on("beforeExit",this._logOnExitFlushListener)}}get tracer(){if(this._tracer)return this._tracer;let Z="@sentry/node",J=R1,X=$X1.trace.getTracer(Z,J);return this._tracer=X,X}async flush(Z){if(await this.traceProvider?.forceFlush(),this.getOptions().sendClientReports)this._flushOutcomes();return super.flush(Z)}close(Z){if(this._clientReportInterval)clearInterval(this._clientReportInterval);if(this._clientReportOnExitFlushListener)process.off("beforeExit",this._clientReportOnExitFlushListener);if(this._logOnExitFlushListener)process.off("beforeExit",this._logOnExitFlushListener);return super.close(Z)}startClientReportTracking(){let Z=this.getOptions();if(Z.sendClientReports)this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{G1&&h.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??ZX6).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return JJ1(this,Z)}}var KX1=r(UR(),1);import JX6 from"module";function WX1(){let[Z=0,J=0]=process.versions.node.split(".").map(Number);if(Z>=21||Z===20&&J>=6||Z===18&&J>=19){if(!M0._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:X}=KX1.createAddHookMessageChannel();JX6.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:X,include:[]},transferList:[X]})}catch(X){h.warn("Failed to register ESM hook",X)}}else e0(()=>{console.warn(`[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`)})}function xj(){return[cq(),dq(),lq(),pq(),iq(),FJ1(),OJ1(),FU(),qU(),WU(),VU(),KU(),BU(),eJ1(),zU()]}function Ng(Z={}){return XX6(Z,xj)}function XX6(Z={},J){let X=YX6(Z,J);if(X.debug===!0)if(G1)h.enable();else e0(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if(!C4()&&X.registerEsmLoaderHooks!==!1)WX1();if(Pj(),T0().update(X.initialScope),X.spotlight&&!X.integrations.some(({name:Q})=>Q===Fg))X.integrations.push(UU({sidecarUrl:typeof X.spotlight==="string"?X.spotlight:void 0}));nQ(X,"node-core");let $=new IG(X);return T0().setClient($),$.init(),h.log(`Running in ${C4()?"CommonJS":"ESM"} mode.`),$.startClientReportTracking(),KX6(),iZ1($),XJ1($),$}function DU(){if(!G1)return;let Z=oZ1(),J=["SentryContextManager","SentryPropagator"];if(u8())J.push("SentrySpanProcessor");for(let X of J)if(!Z.includes(X))h.error(`You have to set up the ${X}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);if(!Z.includes("SentrySampler"))h.warn("You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected. If you use a custom sampler, make sure to use `wrapSamplingDecision`.")}function YX6(Z,J){let X=$X6(Z.release),Y=Z.spotlight??Aj(process.env.SENTRY_SPOTLIGHT,{strict:!0})??process.env.SENTRY_SPOTLIGHT,$=QX6(Z.tracesSampleRate),Q={...Z,dsn:Z.dsn??process.env.SENTRY_DSN,environment:Z.environment??process.env.SENTRY_ENVIRONMENT,sendClientReports:Z.sendClientReports??!0,transport:Z.transport??MU,stackParser:Hf(Z.stackParser||jU),release:X,tracesSampleRate:$,spotlight:Y,debug:Aj(Z.debug??process.env.SENTRY_DEBUG)},K=Z.integrations,W=Z.defaultIntegrations??J(Q);return{...Q,integrations:Vy({defaultIntegrations:W,integrations:K})}}function $X6(Z){if(Z!==void 0)return Z;let J=RU();if(J!==void 0)return J;return}function QX6(Z){if(Z!==void 0)return Z;let J=process.env.SENTRY_TRACES_SAMPLE_RATE;if(!J)return;let X=parseFloat(J);return isFinite(X)?X:void 0}function KX6(){if(Aj(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,X=yQ(Z,J);T0().setPropagationContext(X)}}function s1(Z,J){Z.setAttribute(v0,J)}var VX1=r(r0(),1);var GX1=(Z)=>({package:Z,"javascript.is_cjs":C4()});function cJ(Z,J){let X=X0()?.getOptions();if(!X?.disableInstrumentationWarnings&&!VX1.isWrapped(Z)&&lQ()&&u8(X))e0(()=>{if(C4())console.warn(`[Sentry] ${J} is not instrumented. This is likely because you required/imported ${J} before calling \`Sentry.init()\`.`);else console.warn(`[Sentry] ${J} is not instrumented. Please make sure to initialize Sentry in a separate file that you \`--import\` when running node, see: https://docs.sentry.io/platforms/javascript/guides/${J}/install/esm/.`)}),z7().setContext("missing_instrumentation",GX1(J))}var WX6=[["january","1"],["february","2"],["march","3"],["april","4"],["may","5"],["june","6"],["july","7"],["august","8"],["september","9"],["october","10"],["november","11"],["december","12"],["jan","1"],["feb","2"],["mar","3"],["apr","4"],["may","5"],["jun","6"],["jul","7"],["aug","8"],["sep","9"],["oct","10"],["nov","11"],["dec","12"],["sunday","0"],["monday","1"],["tuesday","2"],["wednesday","3"],["thursday","4"],["friday","5"],["saturday","6"],["sun","0"],["mon","1"],["tue","2"],["wed","3"],["thu","4"],["fri","5"],["sat","6"]];function zK(Z){return WX6.reduce((J,[X,Y])=>J.replace(new RegExp(X,"gi"),Y),Z)}var zX1="Automatic instrumentation of CronJob only supports crontab string";function HX1(Z,J){let X=!1;return new Proxy(Z,{construct(Y,$){let[Q,K,W,G,V,...z]=$;if(typeof Q!=="string")throw new Error(zX1);if(X)throw new Error(`A job named '${J}' has already been scheduled`);X=!0;let F=zK(Q);async function H(q,U){return UZ(J,async()=>{try{await K(q,U)}catch(B){throw Z1(B),B}},{schedule:{type:"crontab",value:F},timezone:V||void 0})}return new Y(Q,H,W,G,V,...z)},get(Y,$){if($==="from")return(Q)=>{let{cronTime:K,onTick:W,timeZone:G}=Q;if(typeof K!=="string")throw new Error(zX1);if(X)throw new Error(`A job named '${J}' has already been scheduled`);X=!0;let V=zK(K);return Q.onTick=async(z,F)=>{return UZ(J,async()=>{try{await W(z,F)}catch(H){throw Z1(H),H}},{schedule:{type:"crontab",value:V},timezone:G||void 0})},Y.from(Q)};else return Y[$]}})}function FX1(Z){return new Proxy(Z,{get(J,X){if(X==="schedule"&&J.schedule)return new Proxy(J.schedule,{apply(Y,$,Q){let[K,W,G]=Q,V=G?.name,z=G?.timezone;if(!V)throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.');let F=async()=>{return UZ(V,async()=>{try{return await W()}catch(H){throw Z1(H),H}},{schedule:{type:"crontab",value:zK(K)},timezone:z})};return Y.apply($,[K,F,G])}});else return J[X]}})}function qX1(Z){return new Proxy(Z,{get(J,X){if(X==="scheduleJob")return new Proxy(J.scheduleJob,{apply(Y,$,Q){let[K,W,G]=Q;if(typeof K!=="string"||typeof W!=="string"||typeof G!=="function")throw new Error("Automatic instrumentation of 'node-schedule' requires the first parameter of 'scheduleJob' to be a job name string and the second parameter to be a crontab string");let V=K,z=W;async function F(){return UZ(V,async()=>{await G?.()},{schedule:{type:"crontab",value:zK(z)}})}return Y.apply($,[V,z,F])}});return J[X]}})}var Rg={instrumentCron:HX1,instrumentNodeCron:FX1,instrumentNodeSchedule:qX1};var jg="Http",UX1="@opentelemetry_sentry-patched/instrumentation-http",GX6=B0(`${jg}.sentry`,(Z)=>{return new CG(Z)}),Dg=B0(jg,(Z)=>{let J=new LX1.HttpInstrumentation(Z);try{J._diag=BX1.diag.createComponentLogger({namespace:UX1}),J.instrumentationName=UX1}catch{}return J});function VX6(Z,J={}){if(typeof Z.spans==="boolean")return Z.spans;if(J.skipOpenTelemetrySetup)return!1;if(!u8(J)&&_9.major>=22)return!1;return!0}var hj=a((Z={})=>{let J=Z.dropSpansForIncomingRequestStatusCodes??[[401,404],[300,399]];return{name:jg,setupOnce(){let X=VX6(Z,X0()?.getOptions());if(GX6({...Z,extractIncomingTraceFromHeader:!X,propagateTraceInOutgoingRequests:!X}),X){let Y=FX6(Z);Dg(Y)}},processEvent(X){if(X.type==="transaction"){let Y=X.contexts?.trace?.data?.["http.response.status_code"];if(typeof Y==="number"&&J.some(($)=>{if(typeof $==="number")return $===Y;let[Q,K]=$;return Y>=Q&&Y<=K}))return null}return X}}});function zX6(Z){return"outputData"in Z&&"outputSize"in Z&&!("client"in Z)&&!("statusCode"in Z)}function HX6(Z){return Z.headers["next-router-prefetch"]==="1"}function FX6(Z={}){return{...Z.instrumentation?._experimentalConfig,disableIncomingRequestInstrumentation:Z.disableIncomingRequestSpans,ignoreOutgoingRequestHook:(X)=>{let Y=DG(X);if(!Y)return!1;let $=Z.ignoreOutgoingRequests;if($?.(Y,X))return!0;return!1},ignoreIncomingRequestHook:(X)=>{let Y=X.url,$=X.method?.toUpperCase();if($==="OPTIONS"||$==="HEAD")return!0;let Q=Z.ignoreIncomingRequests;if(Y&&Q?.(Y,X))return!0;return!1},requireParentforOutgoingSpans:!1,requireParentforIncomingSpans:!1,requestHook:(X,Y)=>{if(s1(X,"auto.http.otel.http"),!zX6(Y)&&HX6(Y))X.setAttribute("sentry.http.prefetch",!0);Z.instrumentation?.requestHook?.(X,Y)},responseHook:(X,Y)=>{Z.instrumentation?.responseHook?.(X,Y)},applyCustomAttributesOnSpan:(X,Y,$)=>{Z.instrumentation?.applyCustomAttributesOnSpan?.(X,Y,$)}}}var SX1=r(vX1(),1);var AX1="NodeFetch",LX6=B0(AX1,SX1.UndiciInstrumentation,(Z)=>{return RX6(Z)}),wX6=B0(`${AX1}.sentry`,kG,(Z)=>{return Z}),OX6=(Z={})=>{return{name:"NodeFetch",setupOnce(){if(NX6(Z,X0()?.getOptions()))LX6(Z);wX6(Z)}}},yj=a(OX6);function MX6(Z,J="/"){let X=`${Z}`;if(X.endsWith("/")&&J.startsWith("/"))return`${X}${J.slice(1)}`;if(!X.endsWith("/")&&!J.startsWith("/"))return`${X}/${J.slice(1)}`;return`${X}${J}`}function NX6(Z,J={}){return typeof Z.spans==="boolean"?Z.spans:!J.skipOpenTelemetrySetup&&u8(J)}function RX6(Z={}){return{requireParentforSpans:!1,ignoreRequestHook:(X)=>{let Y=MX6(X.origin,X.path),$=Z.ignoreOutgoingRequests;return!!($&&Y&&$(Y))},startSpanHook:()=>{return{[v0]:"auto.http.otel.node_fetch"}}}}var ZY1=r(tX1(),1);var eX1="FileSystem",JY1=a((Z={})=>{return{name:eX1,setupOnce(){B0(eX1,()=>new ZY1.FsInstrumentation({requireParentSpan:!0,endHook(J,{args:X,span:Y,error:$}){if(Y.updateName(`fs.${J}`),Y.setAttributes({[j0]:"file",[v0]:"auto.file.fs"}),Z.recordErrorMessagesAsSpanAttributes){if(typeof X[0]==="string"&&xX6.includes(J))Y.setAttribute("path_argument",X[0]);else if(typeof X[0]==="string"&&typeof X[1]==="string"&&AX6.includes(J))Y.setAttribute("target_argument",X[0]),Y.setAttribute("path_argument",X[1]);else if(typeof X[0]==="string"&&SX6.includes(J))Y.setAttribute("prefix_argument",X[0]);else if(typeof X[0]==="string"&&typeof X[1]==="string"&&vX6.includes(J))Y.setAttribute("existing_path_argument",X[0]),Y.setAttribute("new_path_argument",X[1]);else if(typeof X[0]==="string"&&typeof X[1]==="string"&&_X6.includes(J))Y.setAttribute("src_argument",X[0]),Y.setAttribute("dest_argument",X[1]);else if(typeof X[0]==="string"&&typeof X[1]==="string"&&IX6.includes(J))Y.setAttribute("old_path_argument",X[0]),Y.setAttribute("new_path_argument",X[1])}if($&&Z.recordErrorMessagesAsSpanAttributes)Y.setAttribute("fs_error",$.message)}}))()}}}),IX6=["rename","renameSync"],_X6=["copyFile","cp","copyFileSync","cpSync"],vX6=["link","linkSync"],SX6=["mkdtemp","mkdtempSync"],AX6=["symlink","symlinkSync"],xX6=["access","appendFile","chmod","chown","exists","mkdir","lchown","lstat","lutimes","open","opendir","readdir","readFile","readlink","realpath","realpath.native","rm","rmdir","stat","truncate","unlink","utimes","writeFile","accessSync","appendFileSync","chmodSync","chownSync","existsSync","lchownSync","lstatSync","lutimesSync","opendirSync","mkdirSync","openSync","readdirSync","readFileSync","readlinkSync","realpathSync","realpathSync.native","rmdirSync","rmSync","statSync","truncateSync","unlinkSync","utimesSync","writeFileSync"];var _Y1=r(DY1(),1);var T4=typeof __SENTRY_DEBUG__==="undefined"||__SENTRY_DEBUG__;var R7=r(Y0(),1),lj=r(q1(),1),DZ=r(r0(),1),IY1=r(j1(),1);var k4;(function(Z){Z.EXPRESS_TYPE="express.type";let X="express.name";Z.EXPRESS_NAME=X})(k4||(k4={}));var pJ;(function(Z){Z.ROUTER="router";let X="middleware";Z.MIDDLEWARE=X;let Y="request_handler";Z.REQUEST_HANDLER=Y})(pJ||(pJ={}));var _g=Symbol("express-layer-patched"),SY="__ot_middlewares";var CY1=(Z,J)=>{if(Array.isArray(Z[SY])===!1)Object.defineProperty(Z,SY,{enumerable:!1,value:[]});if(J===void 0)return;Z[SY].push(J)},TY1=(Z,J)=>{let X=J.handle?.stack?.[0];if(X?.route?.path)return`${Z}${X.route.path}`;if(X?.handle?.stack)return TY1(Z,X);return Z},kY1=(Z,J,X)=>{if(J.name==="router"){let Y=TY1("",J),$=Y?Y:X||Z||"/";return{attributes:{[k4.EXPRESS_NAME]:$,[k4.EXPRESS_TYPE]:pJ.ROUTER},name:`router - ${$}`}}else if(J.name==="bound dispatch"||J.name==="handle")return{attributes:{[k4.EXPRESS_NAME]:(Z||X)??"request handler",[k4.EXPRESS_TYPE]:pJ.REQUEST_HANDLER},name:`request handler${J.path?` - ${Z||X}`:""}`};else return{attributes:{[k4.EXPRESS_NAME]:J.name,[k4.EXPRESS_TYPE]:pJ.MIDDLEWARE},name:`middleware - ${J.name}`}},tX6=(Z,J)=>{if(typeof J==="string")return J===Z;else if(J instanceof RegExp)return J.test(Z);else if(typeof J==="function")return J(Z);else throw new TypeError("Pattern is in unsupported datatype")},EY1=(Z,J,X)=>{if(Array.isArray(X?.ignoreLayersType)&&X?.ignoreLayersType?.includes(J))return!0;if(Array.isArray(X?.ignoreLayers)===!1)return!1;try{for(let Y of X.ignoreLayers)if(tX6(Z,Y))return!0}catch{}return!1},vg=(Z)=>Z instanceof Error?[Z,Z.message]:[String(Z),String(Z)],cj=(Z)=>{let J=Z[0];if(Array.isArray(J))return J.map((X)=>PY1(X)||"").join(",");return PY1(J)},PY1=(Z)=>{if(typeof Z==="string")return Z;if(Z instanceof RegExp||typeof Z==="number")return Z.toString();return};var eX6="0.1.0",ZY6="@sentry/instrumentation-express-v5";class Sg extends DZ.InstrumentationBase{constructor(Z={}){super(ZY6,eX6,Z)}init(){return[new DZ.InstrumentationNodeModuleDefinition("express",[">=5.0.0"],(Z)=>this._setup(Z),(Z)=>this._tearDown(Z))]}_setup(Z){let J=Z.Router.prototype;if(DZ.isWrapped(J.route))this._unwrap(J,"route");if(this._wrap(J,"route",this._getRoutePatch()),DZ.isWrapped(J.use))this._unwrap(J,"use");if(this._wrap(J,"use",this._getRouterUsePatch()),DZ.isWrapped(Z.application.use))this._unwrap(Z.application,"use");return this._wrap(Z.application,"use",this._getAppUsePatch()),Z}_tearDown(Z){if(Z===void 0)return;let J=Z.Router.prototype;this._unwrap(J,"route"),this._unwrap(J,"use"),this._unwrap(Z.application,"use")}_getRoutePatch(){let Z=this;return function(J){return function X(...Y){let $=J.apply(this,Y),Q=this.stack[this.stack.length-1];return Z._applyPatch(Q,cj(Y)),$}}}_getRouterUsePatch(){let Z=this;return function(J){return function X(...Y){let $=J.apply(this,Y),Q=this.stack[this.stack.length-1];return Z._applyPatch(Q,cj(Y)),$}}}_getAppUsePatch(){let Z=this;return function(J){return function X(...Y){let $=this.router,Q=J.apply(this,Y);if($){let K=$.stack[$.stack.length-1];Z._applyPatch(K,cj(Y))}return Q}}}_applyPatch(Z,J){let X=this;if(Z[_g]===!0)return;Z[_g]=!0,this._wrap(Z,"handle",(Y)=>{if(Y.length===4)return Y;let $=function(Q,K){CY1(Q,J);let W=Q[SY].filter((R)=>R!=="/"&&R!=="/*").join("").replace(/\/{2,}/g,"/"),G=W.length>0?W:void 0,V={[IY1.SEMATTRS_HTTP_ROUTE]:G},z=kY1(W,Z,J),F=z.attributes[k4.EXPRESS_TYPE],H=lj.getRPCMetadata(R7.context.active());if(H?.type===lj.RPCType.HTTP)H.route=G;if(EY1(z.name,F,X.getConfig())){if(F===pJ.MIDDLEWARE)Q[SY].pop();return Y.apply(this,arguments)}if(R7.trace.getSpan(R7.context.active())===void 0)return Y.apply(this,arguments);let q=X._getSpanName({request:Q,layerType:F,route:W},z.name),U=X.tracer.startSpan(q,{attributes:Object.assign(V,z.attributes)}),{requestHook:B}=X.getConfig();if(B)DZ.safeExecuteInTheMiddle(()=>B(U,{request:Q,layerType:F,route:W}),(R)=>{if(R)R7.diag.error("express instrumentation: request hook failed",R)},!0);let L=!1;if(z.attributes[k4.EXPRESS_TYPE]!==pJ.MIDDLEWARE)U.end(),L=!0;let w=()=>{if(L===!1)L=!0,U.end()},M=Array.from(arguments),N=M.findIndex((R)=>typeof R==="function");if(N>=0)arguments[N]=function(){let R=arguments[0],P=![void 0,null,"route","router"].includes(R);if(!L&&P){let[C,T]=vg(R);U.recordException(C),U.setStatus({code:R7.SpanStatusCode.ERROR,message:T})}if(L===!1)L=!0,Q.res?.removeListener("finish",w),U.end();if(!(Q.route&&P))Q[SY].pop();return M[N].apply(this,arguments)};try{return Y.apply(this,arguments)}catch(R){let[P,D]=vg(R);throw U.recordException(P),U.setStatus({code:R7.SpanStatusCode.ERROR,message:D}),R}finally{if(!L)K.once("finish",w)}};for(let Q in Y)Object.defineProperty($,Q,{get(){return Y[Q]},set(K){Y[Q]=K}});return $})}_getSpanName(Z,J){let{spanNameHook:X}=this.getConfig();if(!(X instanceof Function))return J;try{return X(Z,J)??J}catch(Y){return R7.diag.error("express instrumentation: error calling span name rewrite hook",Y),J}}}var vY1="Express",JY6="Express-V5";function SY1(Z){s1(Z,"auto.http.otel.express");let J=L0(Z).data,X=J["express.type"];if(X)Z.setAttribute(j0,`${X}.express`);let Y=J["express.name"];if(typeof Y==="string")Z.updateName(Y)}function AY1(Z,J){if(E0()===B4())return T4&&h.warn("Isolation scope is still default isolation scope - skipping setting transactionName"),J;if(Z.layerType==="request_handler"){let X=Z.request,Y=X.method?X.method.toUpperCase():"GET";E0().setTransactionName(`${Y} ${Z.route}`)}return J}var Ag=B0(vY1,()=>new _Y1.ExpressInstrumentation({requestHook:(Z)=>SY1(Z),spanNameHook:(Z,J)=>AY1(Z,J)})),xg=B0(JY6,()=>new Sg({requestHook:(Z)=>SY1(Z),spanNameHook:(Z,J)=>AY1(Z,J)})),XY6=()=>{return{name:vY1,setupOnce(){Ag(),xg()}}},pj=a(XY6);function hg(Z){return function J(X,Y,$,Q){let K=WG(Y);if(E0().setSDKProcessingMetadata({normalizedRequest:K}),(Z?.shouldHandleError||QY6)(X)){let G=Z1(X,{mechanism:{type:"middleware",handled:!1}});$.sentry=G}Q(X)}}function YY6(){return function Z(J,X,Y){let $=WG(J);E0().setSDKProcessingMetadata({normalizedRequest:$}),Y()}}function xY1(Z,J){Z.use(YY6()),Z.use(hg(J)),cJ(Z.use,"express")}function $Y6(Z){let J=Z.status||Z.statusCode||Z.status_code||Z.output?.statusCode;return J?parseInt(J,10):500}function QY6(Z){return $Y6(Z)>=500}import*as cg from"node:diagnostics_channel";var A8=r(Y0(),1),aj=r(q1(),1),H$1=r(r0(),1),d8=r(j1(),1);import K$1 from"node:diagnostics_channel";var J$1=r(nY1(),1);var EU=(Z)=>{if(typeof Z!=="string")throw new TypeError("invalid pattern");if(Z.length>65536)throw new TypeError("pattern is too long")};var qY6={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},IU=(Z)=>Z.replace(/[[\]\\-]/g,"\\$&"),UY6=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),aY1=(Z)=>Z.join(""),sY1=(Z,J)=>{let X=J;if(Z.charAt(X)!=="[")throw new Error("not in a brace expression");let Y=[],$=[],Q=X+1,K=!1,W=!1,G=!1,V=!1,z=X,F="";Z:while(Q<Z.length){let B=Z.charAt(Q);if((B==="!"||B==="^")&&Q===X+1){V=!0,Q++;continue}if(B==="]"&&K&&!G){z=Q+1;break}if(K=!0,B==="\\"){if(!G){G=!0,Q++;continue}}if(B==="["&&!G){for(let[L,[w,M,N]]of Object.entries(qY6))if(Z.startsWith(L,Q)){if(F)return["$.",!1,Z.length-X,!0];if(Q+=L.length,N)$.push(w);else Y.push(w);W=W||M;continue Z}}if(G=!1,F){if(B>F)Y.push(IU(F)+"-"+IU(B));else if(B===F)Y.push(IU(B));F="",Q++;continue}if(Z.startsWith("-]",Q+1)){Y.push(IU(B+"-")),Q+=2;continue}if(Z.startsWith("-",Q+1)){F=B,Q+=2;continue}Y.push(IU(B)),Q++}if(z<Q)return["",!1,0,!1];if(!Y.length&&!$.length)return["$.",!1,Z.length-X,!0];if($.length===0&&Y.length===1&&/^\\?.$/.test(Y[0])&&!V){let B=Y[0].length===2?Y[0].slice(-1):Y[0];return[UY6(B),!1,z-X,!1]}let H="["+(V?"^":"")+aY1(Y)+"]",q="["+(V?"":"^")+aY1($)+"]";return[Y.length&&$.length?"("+H+"|"+q+")":Y.length?H:q,W,z-X,!0]};var AY=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/\[([^\/\\])\]/g,"$1"):Z.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1")};var BY6=new Set(["!","?","+","*","@"]),oY1=(Z)=>BY6.has(Z),LY6="(?!(?:^|/)\\.\\.?(?:$|/))",ij="(?!\\.)",wY6=new Set(["[","."]),OY6=new Set(["..","."]),MY6=new Set("().*{}+?[]^$\\!"),NY6=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),bg="[^/]",rY1=bg+"*?",tY1=bg+"+?";class I6{type;#Z;#J;#Y=!1;#X=[];#$;#z;#F;#W=!1;#G;#V;#H=!1;constructor(Z,J,X={}){if(this.type=Z,Z)this.#J=!0;if(this.#$=J,this.#Z=this.#$?this.#$.#Z:this,this.#G=this.#Z===this?X:this.#Z.#G,this.#F=this.#Z===this?[]:this.#Z.#F,Z==="!"&&!this.#Z.#W)this.#F.push(this);this.#z=this.#$?this.#$.#X.length:0}get hasMagic(){if(this.#J!==void 0)return this.#J;for(let Z of this.#X){if(typeof Z==="string")continue;if(Z.type||Z.hasMagic)return this.#J=!0}return this.#J}toString(){if(this.#V!==void 0)return this.#V;if(!this.type)return this.#V=this.#X.map((Z)=>String(Z)).join("");else return this.#V=this.type+"("+this.#X.map((Z)=>String(Z)).join("|")+")"}#Q(){if(this!==this.#Z)throw new Error("should only call on root");if(this.#W)return this;this.toString(),this.#W=!0;let Z;while(Z=this.#F.pop()){if(Z.type!=="!")continue;let J=Z,X=J.#$;while(X){for(let Y=J.#z+1;!X.type&&Y<X.#X.length;Y++)for(let $ of Z.#X){if(typeof $==="string")throw new Error("string part in extglob AST??");$.copyIn(X.#X[Y])}J=X,X=J.#$}}return this}push(...Z){for(let J of Z){if(J==="")continue;if(typeof J!=="string"&&!(J instanceof I6&&J.#$===this))throw new Error("invalid part: "+J);this.#X.push(J)}}toJSON(){let Z=this.type===null?this.#X.slice().map((J)=>typeof J==="string"?J:J.toJSON()):[this.type,...this.#X.map((J)=>J.toJSON())];if(this.isStart()&&!this.type)Z.unshift([]);if(this.isEnd()&&(this===this.#Z||this.#Z.#W&&this.#$?.type==="!"))Z.push({});return Z}isStart(){if(this.#Z===this)return!0;if(!this.#$?.isStart())return!1;if(this.#z===0)return!0;let Z=this.#$;for(let J=0;J<this.#z;J++){let X=Z.#X[J];if(!(X instanceof I6&&X.type==="!"))return!1}return!0}isEnd(){if(this.#Z===this)return!0;if(this.#$?.type==="!")return!0;if(!this.#$?.isEnd())return!1;if(!this.type)return this.#$?.isEnd();let Z=this.#$?this.#$.#X.length:0;return this.#z===Z-1}copyIn(Z){if(typeof Z==="string")this.push(Z);else this.push(Z.clone(this))}clone(Z){let J=new I6(this.type,Z);for(let X of this.#X)J.copyIn(X);return J}static#U(Z,J,X,Y){let $=!1,Q=!1,K=-1,W=!1;if(J.type===null){let H=X,q="";while(H<Z.length){let U=Z.charAt(H++);if($||U==="\\"){$=!$,q+=U;continue}if(Q){if(H===K+1){if(U==="^"||U==="!")W=!0}else if(U==="]"&&!(H===K+2&&W))Q=!1;q+=U;continue}else if(U==="["){Q=!0,K=H,W=!1,q+=U;continue}if(!Y.noext&&oY1(U)&&Z.charAt(H)==="("){J.push(q),q="";let B=new I6(U,J);H=I6.#U(Z,B,H,Y),J.push(B);continue}q+=U}return J.push(q),H}let G=X+1,V=new I6(null,J),z=[],F="";while(G<Z.length){let H=Z.charAt(G++);if($||H==="\\"){$=!$,F+=H;continue}if(Q){if(G===K+1){if(H==="^"||H==="!")W=!0}else if(H==="]"&&!(G===K+2&&W))Q=!1;F+=H;continue}else if(H==="["){Q=!0,K=G,W=!1,F+=H;continue}if(oY1(H)&&Z.charAt(G)==="("){V.push(F),F="";let q=new I6(H,V);V.push(q),G=I6.#U(Z,q,G,Y);continue}if(H==="|"){V.push(F),F="",z.push(V),V=new I6(null,J);continue}if(H===")"){if(F===""&&J.#X.length===0)J.#H=!0;return V.push(F),F="",J.push(...z,V),G}F+=H}return J.type=null,J.#J=void 0,J.#X=[Z.substring(X-1)],G}static fromGlob(Z,J={}){let X=new I6(null,void 0,J);return I6.#U(Z,X,0,J),X}toMMPattern(){if(this!==this.#Z)return this.#Z.toMMPattern();let Z=this.toString(),[J,X,Y,$]=this.toRegExpSource();if(!(Y||this.#J||this.#G.nocase&&!this.#G.nocaseMagicOnly&&Z.toUpperCase()!==Z.toLowerCase()))return X;let K=(this.#G.nocase?"i":"")+($?"u":"");return Object.assign(new RegExp(`^${J}$`,K),{_src:J,_glob:Z})}get options(){return this.#G}toRegExpSource(Z){let J=Z??!!this.#G.dot;if(this.#Z===this)this.#Q();if(!this.type){let W=this.isStart()&&this.isEnd(),G=this.#X.map((H)=>{let[q,U,B,L]=typeof H==="string"?I6.#B(H,this.#J,W):H.toRegExpSource(Z);return this.#J=this.#J||B,this.#Y=this.#Y||L,q}).join(""),V="";if(this.isStart()){if(typeof this.#X[0]==="string"){if(!(this.#X.length===1&&OY6.has(this.#X[0]))){let q=wY6,U=J&&q.has(G.charAt(0))||G.startsWith("\\.")&&q.has(G.charAt(2))||G.startsWith("\\.\\.")&&q.has(G.charAt(4)),B=!J&&!Z&&q.has(G.charAt(0));V=U?LY6:B?ij:""}}}let z="";if(this.isEnd()&&this.#Z.#W&&this.#$?.type==="!")z="(?:$|\\/)";return[V+G+z,AY(G),this.#J=!!this.#J,this.#Y]}let X=this.type==="*"||this.type==="+",Y=this.type==="!"?"(?:(?!(?:":"(?:",$=this.#L(J);if(this.isStart()&&this.isEnd()&&!$&&this.type!=="!"){let W=this.toString();return this.#X=[W],this.type=null,this.#J=void 0,[W,AY(this.toString()),!1,!1]}let Q=!X||Z||J||!ij?"":this.#L(!0);if(Q===$)Q="";if(Q)$=`(?:${$})(?:${Q})*?`;let K="";if(this.type==="!"&&this.#H)K=(this.isStart()&&!J?ij:"")+tY1;else{let W=this.type==="!"?"))"+(this.isStart()&&!J&&!Z?ij:"")+rY1+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&Q?")":this.type==="*"&&Q?")?":`)${this.type}`;K=Y+$+W}return[K,AY($),this.#J=!!this.#J,this.#Y]}#L(Z){return this.#X.map((J)=>{if(typeof J==="string")throw new Error("string type in extglob ast??");let[X,Y,$,Q]=J.toRegExpSource(Z);return this.#Y=this.#Y||Q,X}).filter((J)=>!(this.isStart()&&this.isEnd())||!!J).join("|")}static#B(Z,J,X=!1){let Y=!1,$="",Q=!1;for(let K=0;K<Z.length;K++){let W=Z.charAt(K);if(Y){Y=!1,$+=(MY6.has(W)?"\\":"")+W;continue}if(W==="\\"){if(K===Z.length-1)$+="\\\\";else Y=!0;continue}if(W==="["){let[G,V,z,F]=sY1(Z,K);if(z){$+=G,Q=Q||V,K+=z-1,J=J||F;continue}}if(W==="*"){if(X&&Z==="*")$+=tY1;else $+=rY1;J=!0;continue}if(W==="?"){$+=bg,J=!0;continue}$+=NY6(W)}return[$,AY(Z),!!J,Q]}}var gg=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/[?*()[\]]/g,"[$&]"):Z.replace(/[?*()[\]\\]/g,"\\$&")};var _6=(Z,J,X={})=>{if(EU(J),!X.nocomment&&J.charAt(0)==="#")return!1;return new _U(J,X).match(Z)},RY6=/^\*+([^+@!?\*\[\(]*)$/,jY6=(Z)=>(J)=>!J.startsWith(".")&&J.endsWith(Z),DY6=(Z)=>(J)=>J.endsWith(Z),PY6=(Z)=>{return Z=Z.toLowerCase(),(J)=>!J.startsWith(".")&&J.toLowerCase().endsWith(Z)},CY6=(Z)=>{return Z=Z.toLowerCase(),(J)=>J.toLowerCase().endsWith(Z)},TY6=/^\*+\.\*+$/,kY6=(Z)=>!Z.startsWith(".")&&Z.includes("."),EY6=(Z)=>Z!=="."&&Z!==".."&&Z.includes("."),IY6=/^\.\*+$/,_Y6=(Z)=>Z!=="."&&Z!==".."&&Z.startsWith("."),vY6=/^\*+$/,SY6=(Z)=>Z.length!==0&&!Z.startsWith("."),AY6=(Z)=>Z.length!==0&&Z!=="."&&Z!=="..",xY6=/^\?+([^+@!?\*\[\(]*)?$/,hY6=([Z,J=""])=>{let X=X$1([Z]);if(!J)return X;return J=J.toLowerCase(),(Y)=>X(Y)&&Y.toLowerCase().endsWith(J)},fY6=([Z,J=""])=>{let X=Y$1([Z]);if(!J)return X;return J=J.toLowerCase(),(Y)=>X(Y)&&Y.toLowerCase().endsWith(J)},yY6=([Z,J=""])=>{let X=Y$1([Z]);return!J?X:(Y)=>X(Y)&&Y.endsWith(J)},bY6=([Z,J=""])=>{let X=X$1([Z]);return!J?X:(Y)=>X(Y)&&Y.endsWith(J)},X$1=([Z])=>{let J=Z.length;return(X)=>X.length===J&&!X.startsWith(".")},Y$1=([Z])=>{let J=Z.length;return(X)=>X.length===J&&X!=="."&&X!==".."},$$1=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",eY1={win32:{sep:"\\"},posix:{sep:"/"}},gY6=$$1==="win32"?eY1.win32.sep:eY1.posix.sep;_6.sep=gY6;var I4=Symbol("globstar **");_6.GLOBSTAR=I4;var mY6="[^/]",uY6=mY6+"*?",dY6="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",cY6="(?:(?!(?:\\/|^)\\.).)*?",lY6=(Z,J={})=>(X)=>_6(X,Z,J);_6.filter=lY6;var E4=(Z,J={})=>Object.assign({},Z,J),pY6=(Z)=>{if(!Z||typeof Z!=="object"||!Object.keys(Z).length)return _6;let J=_6;return Object.assign((Y,$,Q={})=>J(Y,$,E4(Z,Q)),{Minimatch:class Y extends J.Minimatch{constructor($,Q={}){super($,E4(Z,Q))}static defaults($){return J.defaults(E4(Z,$)).Minimatch}},AST:class Y extends J.AST{constructor($,Q,K={}){super($,Q,E4(Z,K))}static fromGlob($,Q={}){return J.AST.fromGlob($,E4(Z,Q))}},unescape:(Y,$={})=>J.unescape(Y,E4(Z,$)),escape:(Y,$={})=>J.escape(Y,E4(Z,$)),filter:(Y,$={})=>J.filter(Y,E4(Z,$)),defaults:(Y)=>J.defaults(E4(Z,Y)),makeRe:(Y,$={})=>J.makeRe(Y,E4(Z,$)),braceExpand:(Y,$={})=>J.braceExpand(Y,E4(Z,$)),match:(Y,$,Q={})=>J.match(Y,$,E4(Z,Q)),sep:J.sep,GLOBSTAR:I4})};_6.defaults=pY6;var Q$1=(Z,J={})=>{if(EU(Z),J.nobrace||!/\{(?:(?!\{).)*\}/.test(Z))return[Z];return J$1.default(Z)};_6.braceExpand=Q$1;var iY6=(Z,J={})=>new _U(Z,J).makeRe();_6.makeRe=iY6;var nY6=(Z,J,X={})=>{let Y=new _U(J,X);if(Z=Z.filter(($)=>Y.match($)),Y.options.nonull&&!Z.length)Z.push(J);return Z};_6.match=nY6;var Z$1=/[?*]|[+@!]\(.*?\)|\[|\]/,aY6=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class _U{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(Z,J={}){if(EU(Z),J=J||{},this.options=J,this.pattern=Z,this.platform=J.platform||$$1,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!J.windowsPathsNoEscape||J.allowWindowsEscape===!1,this.windowsPathsNoEscape)this.pattern=this.pattern.replace(/\\/g,"/");this.preserveMultipleSlashes=!!J.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!J.nonegate,this.comment=!1,this.empty=!1,this.partial=!!J.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=J.windowsNoMagicRoot!==void 0?J.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let Z of this.set)for(let J of Z)if(typeof J!=="string")return!0;return!1}debug(...Z){}make(){let Z=this.pattern,J=this.options;if(!J.nocomment&&Z.charAt(0)==="#"){this.comment=!0;return}if(!Z){this.empty=!0;return}if(this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],J.debug)this.debug=(...$)=>console.error(...$);this.debug(this.pattern,this.globSet);let X=this.globSet.map(($)=>this.slashSplit($));this.globParts=this.preprocess(X),this.debug(this.pattern,this.globParts);let Y=this.globParts.map(($,Q,K)=>{if(this.isWindows&&this.windowsNoMagicRoot){let W=$[0]===""&&$[1]===""&&($[2]==="?"||!Z$1.test($[2]))&&!Z$1.test($[3]),G=/^[a-z]:/i.test($[0]);if(W)return[...$.slice(0,4),...$.slice(4).map((V)=>this.parse(V))];else if(G)return[$[0],...$.slice(1).map((V)=>this.parse(V))]}return $.map((W)=>this.parse(W))});if(this.debug(this.pattern,Y),this.set=Y.filter(($)=>$.indexOf(!1)===-1),this.isWindows)for(let $=0;$<this.set.length;$++){let Q=this.set[$];if(Q[0]===""&&Q[1]===""&&this.globParts[$][2]==="?"&&typeof Q[3]==="string"&&/^[a-z]:$/i.test(Q[3]))Q[2]="?"}this.debug(this.pattern,this.set)}preprocess(Z){if(this.options.noglobstar){for(let X=0;X<Z.length;X++)for(let Y=0;Y<Z[X].length;Y++)if(Z[X][Y]==="**")Z[X][Y]="*"}let{optimizationLevel:J=1}=this.options;if(J>=2)Z=this.firstPhasePreProcess(Z),Z=this.secondPhasePreProcess(Z);else if(J>=1)Z=this.levelOneOptimize(Z);else Z=this.adjascentGlobstarOptimize(Z);return Z}adjascentGlobstarOptimize(Z){return Z.map((J)=>{let X=-1;while((X=J.indexOf("**",X+1))!==-1){let Y=X;while(J[Y+1]==="**")Y++;if(Y!==X)J.splice(X,Y-X)}return J})}levelOneOptimize(Z){return Z.map((J)=>{return J=J.reduce((X,Y)=>{let $=X[X.length-1];if(Y==="**"&&$==="**")return X;if(Y===".."){if($&&$!==".."&&$!=="."&&$!=="**")return X.pop(),X}return X.push(Y),X},[]),J.length===0?[""]:J})}levelTwoFileOptimize(Z){if(!Array.isArray(Z))Z=this.slashSplit(Z);let J=!1;do{if(J=!1,!this.preserveMultipleSlashes){for(let Y=1;Y<Z.length-1;Y++){let $=Z[Y];if(Y===1&&$===""&&Z[0]==="")continue;if($==="."||$==="")J=!0,Z.splice(Y,1),Y--}if(Z[0]==="."&&Z.length===2&&(Z[1]==="."||Z[1]===""))J=!0,Z.pop()}let X=0;while((X=Z.indexOf("..",X+1))!==-1){let Y=Z[X-1];if(Y&&Y!=="."&&Y!==".."&&Y!=="**")J=!0,Z.splice(X-1,2),X-=2}}while(J);return Z.length===0?[""]:Z}firstPhasePreProcess(Z){let J=!1;do{J=!1;for(let X of Z){let Y=-1;while((Y=X.indexOf("**",Y+1))!==-1){let Q=Y;while(X[Q+1]==="**")Q++;if(Q>Y)X.splice(Y+1,Q-Y);let K=X[Y+1],W=X[Y+2],G=X[Y+3];if(K!=="..")continue;if(!W||W==="."||W===".."||!G||G==="."||G==="..")continue;J=!0,X.splice(Y,1);let V=X.slice(0);V[Y]="**",Z.push(V),Y--}if(!this.preserveMultipleSlashes){for(let Q=1;Q<X.length-1;Q++){let K=X[Q];if(Q===1&&K===""&&X[0]==="")continue;if(K==="."||K==="")J=!0,X.splice(Q,1),Q--}if(X[0]==="."&&X.length===2&&(X[1]==="."||X[1]===""))J=!0,X.pop()}let $=0;while(($=X.indexOf("..",$+1))!==-1){let Q=X[$-1];if(Q&&Q!=="."&&Q!==".."&&Q!=="**"){J=!0;let W=$===1&&X[$+1]==="**"?["."]:[];if(X.splice($-1,2,...W),X.length===0)X.push("");$-=2}}}}while(J);return Z}secondPhasePreProcess(Z){for(let J=0;J<Z.length-1;J++)for(let X=J+1;X<Z.length;X++){let Y=this.partsMatch(Z[J],Z[X],!this.preserveMultipleSlashes);if(Y){Z[J]=[],Z[X]=Y;break}}return Z.filter((J)=>J.length)}partsMatch(Z,J,X=!1){let Y=0,$=0,Q=[],K="";while(Y<Z.length&&$<J.length)if(Z[Y]===J[$])Q.push(K==="b"?J[$]:Z[Y]),Y++,$++;else if(X&&Z[Y]==="**"&&J[$]===Z[Y+1])Q.push(Z[Y]),Y++;else if(X&&J[$]==="**"&&Z[Y]===J[$+1])Q.push(J[$]),$++;else if(Z[Y]==="*"&&J[$]&&(this.options.dot||!J[$].startsWith("."))&&J[$]!=="**"){if(K==="b")return!1;K="a",Q.push(Z[Y]),Y++,$++}else if(J[$]==="*"&&Z[Y]&&(this.options.dot||!Z[Y].startsWith("."))&&Z[Y]!=="**"){if(K==="a")return!1;K="b",Q.push(J[$]),Y++,$++}else return!1;return Z.length===J.length&&Q}parseNegate(){if(this.nonegate)return;let Z=this.pattern,J=!1,X=0;for(let Y=0;Y<Z.length&&Z.charAt(Y)==="!";Y++)J=!J,X++;if(X)this.pattern=Z.slice(X);this.negate=J}matchOne(Z,J,X=!1){let Y=this.options;if(this.isWindows){let U=typeof Z[0]==="string"&&/^[a-z]:$/i.test(Z[0]),B=!U&&Z[0]===""&&Z[1]===""&&Z[2]==="?"&&/^[a-z]:$/i.test(Z[3]),L=typeof J[0]==="string"&&/^[a-z]:$/i.test(J[0]),w=!L&&J[0]===""&&J[1]===""&&J[2]==="?"&&typeof J[3]==="string"&&/^[a-z]:$/i.test(J[3]),M=B?3:U?0:void 0,N=w?3:L?0:void 0;if(typeof M==="number"&&typeof N==="number"){let[R,P]=[Z[M],J[N]];if(R.toLowerCase()===P.toLowerCase()){if(J[N]=R,N>M)J=J.slice(N);else if(M>N)Z=Z.slice(M)}}}let{optimizationLevel:$=1}=this.options;if($>=2)Z=this.levelTwoFileOptimize(Z);this.debug("matchOne",this,{file:Z,pattern:J}),this.debug("matchOne",Z.length,J.length);for(var Q=0,K=0,W=Z.length,G=J.length;Q<W&&K<G;Q++,K++){this.debug("matchOne loop");var V=J[K],z=Z[Q];if(this.debug(J,V,z),V===!1)return!1;if(V===I4){this.debug("GLOBSTAR",[J,V,z]);var F=Q,H=K+1;if(H===G){this.debug("** at the end");for(;Q<W;Q++)if(Z[Q]==="."||Z[Q]===".."||!Y.dot&&Z[Q].charAt(0)===".")return!1;return!0}while(F<W){var q=Z[F];if(this.debug(`
492
492
  globstar while`,Z,F,J,H,q),this.matchOne(Z.slice(F),J.slice(H),X))return this.debug("globstar found match!",F,W,q),!0;else{if(q==="."||q===".."||!Y.dot&&q.charAt(0)==="."){this.debug("dot detected!",Z,F,J,H);break}this.debug("globstar swallow a segment, and continue"),F++}}if(X){if(this.debug(`
493
- >>> no match, partial?`,Z,F,J,H),F===W)return!0}return!1}let U;if(typeof V==="string")U=z===V,this.debug("string match",V,z,U);else U=V.test(z),this.debug("pattern match",V,z,U);if(!U)return!1}if(Q===W&&K===G)return!0;else if(Q===W)return X;else if(K===G)return Q===W-1&&Z[Q]==="";else throw new Error("wtf?")}braceExpand(){return Q$1(this.pattern,this.options)}parse(Z){EU(Z);let J=this.options;if(Z==="**")return I4;if(Z==="")return"";let X,Y=null;if(X=Z.match(vY6))Y=J.dot?AY6:SY6;else if(X=Z.match(RY6))Y=(J.nocase?J.dot?CY6:PY6:J.dot?DY6:jY6)(X[1]);else if(X=Z.match(xY6))Y=(J.nocase?J.dot?fY6:hY6:J.dot?yY6:bY6)(X);else if(X=Z.match(TY6))Y=J.dot?EY6:kY6;else if(X=Z.match(IY6))Y=_Y6;let $=I6.fromGlob(Z,this.options).toMMPattern();if(Y&&typeof $==="object")Reflect.defineProperty($,"test",{value:Y});return $}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let Z=this.set;if(!Z.length)return this.regexp=!1,this.regexp;let J=this.options,X=J.noglobstar?uY6:J.dot?dY6:cY6,Y=new Set(J.nocase?["i"]:[]),$=Z.map((W)=>{let G=W.map((V)=>{if(V instanceof RegExp)for(let z of V.flags.split(""))Y.add(z);return typeof V==="string"?aY6(V):V===I4?I4:V._src});return G.forEach((V,z)=>{let F=G[z+1],H=G[z-1];if(V!==I4||H===I4)return;if(H===void 0)if(F!==void 0&&F!==I4)G[z+1]="(?:\\/|"+X+"\\/)?"+F;else G[z]=X;else if(F===void 0)G[z-1]=H+"(?:\\/|"+X+")?";else if(F!==I4)G[z-1]=H+"(?:\\/|\\/"+X+"\\/)"+F,G[z+1]=I4}),G.filter((V)=>V!==I4).join("/")}).join("|"),[Q,K]=Z.length>1?["(?:",")"]:["",""];if($="^"+Q+$+K+"$",this.negate)$="^(?!"+$+").+$";try{this.regexp=new RegExp($,[...Y].join(""))}catch(W){this.regexp=!1}return this.regexp}slashSplit(Z){if(this.preserveMultipleSlashes)return Z.split("/");else if(this.isWindows&&/^\/\/[^\/]+/.test(Z))return["",...Z.split(/\/+/)];else return Z.split(/\/+/)}match(Z,J=this.partial){if(this.debug("match",Z,this.pattern),this.comment)return!1;if(this.empty)return Z==="";if(Z==="/"&&J)return!0;let X=this.options;if(this.isWindows)Z=Z.split("\\").join("/");let Y=this.slashSplit(Z);this.debug(this.pattern,"split",Y);let $=this.set;this.debug(this.pattern,"set",$);let Q=Y[Y.length-1];if(!Q)for(let K=Y.length-2;!Q&&K>=0;K--)Q=Y[K];for(let K=0;K<$.length;K++){let W=$[K],G=Y;if(X.matchBase&&W.length===1)G=[Q];if(this.matchOne(G,W,J)){if(X.flipNegate)return!0;return!this.negate}}if(X.flipNegate)return!1;return this.negate}static defaults(Z){return _6.defaults(Z).Minimatch}}_6.AST=I6;_6.Minimatch=_U;_6.escape=gg;_6.unescape=AY;var W$1="@fastify/otel",oY6="0.8.0",rY6=">=4.0.0 <6",G$1=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],o1={HOOK_NAME:"hook.name",FASTIFY_TYPE:"fastify.type",HOOK_CALLBACK_NAME:"hook.callback.name",ROOT:"fastify.root"},xY={ROUTE:"route-hook",INSTANCE:"hook",HANDLER:"request-handler"},iJ="anonymous",T5=Symbol("fastify otel instance"),hY=Symbol("fastify otel request spans"),vU=Symbol("fastify otel request context"),V$1=Symbol("fastify otel addhook original"),z$1=Symbol("fastify otel setnotfound original"),nj=Symbol("fastify otel ignore path");class mg extends H$1.InstrumentationBase{constructor(Z){super(W$1,oY6,Z);if(this.servername=Z?.servername??process.env.OTEL_SERVICE_NAME??"fastify",this[nj]=null,this._logger=A8.diag.createComponentLogger({namespace:W$1}),Z?.ignorePaths!=null||process.env.OTEL_FASTIFY_IGNORE_PATHS!=null){let J=Z?.ignorePaths??process.env.OTEL_FASTIFY_IGNORE_PATHS;if((typeof J!=="string"||J.length===0)&&typeof J!=="function")throw new TypeError("ignorePaths must be a string or a function");let X=_6;this[nj]=(Y)=>{if(typeof J==="function")return J(Y);else return X(Y.url,J)}}}enable(){if(this._handleInitialization===void 0&&this.getConfig().registerOnInitialization){let Z=this.plugin();this._handleInitialization=(J)=>{J.fastify.register(Z)},K$1.subscribe("fastify.initialization",this._handleInitialization)}return super.enable()}disable(){if(this._handleInitialization)K$1.unsubscribe("fastify.initialization",this._handleInitialization),this._handleInitialization=void 0;return super.disable()}init(){return[]}plugin(){let Z=this;return J[Symbol.for("skip-override")]=!0,J[Symbol.for("fastify.display-name")]="@fastify/otel",J[Symbol.for("plugin-meta")]={fastify:rY6,name:"@fastify/otel"},J;function J(X,Y,$){X.decorate(T5,Z),X.decorate(V$1,X.addHook),X.decorate(z$1,X.setNotFoundHandler),X.decorateRequest("opentelemetry",function z(){let F=this[vU];return{span:this[hY],tracer:Z.tracer,context:F,inject:(q,U)=>{return A8.propagation.inject(F,q,U)},extract:(q,U)=>{return A8.propagation.extract(F,q,U)}}}),X.decorateRequest(hY,null),X.decorateRequest(vU,null),X.addHook("onRoute",function(z){if(Z[nj]?.(z)===!0){Z._logger.debug(`Ignoring route instrumentation ${z.method} ${z.url} because it matches the ignore path`);return}for(let F of G$1)if(z[F]!=null){let H=z[F];if(typeof H==="function")z[F]=V(H,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - route -> ${F}`,[o1.FASTIFY_TYPE]:xY.ROUTE,[d8.ATTR_HTTP_ROUTE]:z.url,[o1.HOOK_CALLBACK_NAME]:H.name?.length>0?H.name:iJ});else if(Array.isArray(H)){let q=[];for(let U of H)q.push(V(U,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - route -> ${F}`,[o1.FASTIFY_TYPE]:xY.ROUTE,[d8.ATTR_HTTP_ROUTE]:z.url,[o1.HOOK_CALLBACK_NAME]:U.name?.length>0?U.name:iJ}));z[F]=q}}if(z.onSend!=null)z.onSend=Array.isArray(z.onSend)?[...z.onSend,Q]:[z.onSend,Q];else z.onSend=Q;if(z.onError!=null)z.onError=Array.isArray(z.onError)?[...z.onError,K]:[z.onError,K];else z.onError=K;z.handler=V(z.handler,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - route-handler`,[o1.FASTIFY_TYPE]:xY.HANDLER,[d8.ATTR_HTTP_ROUTE]:z.url,[o1.HOOK_CALLBACK_NAME]:z.handler.name.length>0?z.handler.name:iJ})}),X.addHook("onRequest",function(z,F,H){if(this[T5].isEnabled()===!1)return H();else if(this[T5][nj]?.({url:z.url,method:z.method})===!0)return this[T5]._logger.debug(`Ignoring request ${z.method} ${z.url} because it matches the ignore path`),H();let q=A8.context.active();if(A8.trace.getSpan(q)==null)q=A8.propagation.extract(q,z.headers);let U=aj.getRPCMetadata(q);if(z.routeOptions.url!=null&&U?.type===aj.RPCType.HTTP)U.route=z.routeOptions.url;let B=this[T5].tracer.startSpan("request",{attributes:{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.ROOT]:"@fastify/otel",[d8.ATTR_HTTP_ROUTE]:z.url,[d8.ATTR_HTTP_REQUEST_METHOD]:z.method}},q);z[vU]=A8.trace.setSpan(q,B),z[hY]=B,A8.context.with(z[vU],()=>{H()})}),X.addHook("onResponse",function(z,F,H){let q=z[hY];if(q!=null)q.setStatus({code:A8.SpanStatusCode.OK,message:"OK"}),q.setAttributes({[d8.ATTR_HTTP_RESPONSE_STATUS_CODE]:404}),q.end();z[hY]=null,H()}),X.addHook=W,X.setNotFoundHandler=G,$();function Q(z,F,H,q){let U=z[hY];if(U!=null){if(F.statusCode<500)U.setStatus({code:A8.SpanStatusCode.OK,message:"OK"});U.setAttributes({[d8.ATTR_HTTP_RESPONSE_STATUS_CODE]:F.statusCode}),U.end()}z[hY]=null,q(null,H)}function K(z,F,H,q){let U=z[hY];if(U!=null)U.setStatus({code:A8.SpanStatusCode.ERROR,message:H.message}),U.recordException(H);q()}function W(z,F){let H=this[V$1];if(G$1.includes(z))return H.call(this,z,V(F,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - ${z}`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:iJ}));else return H.call(this,z,F)}function G(z,F){let H=this[z$1];if(typeof z==="function")F=V(z,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:z.name?.length>0?z.name:iJ}),H.call(this,F);else{if(z.preValidation!=null)z.preValidation=V(z.preValidation,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preValidation`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:z.preValidation.name?.length>0?z.preValidation.name:iJ});if(z.preHandler!=null)z.preHandler=V(z.preHandler,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preHandler`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:z.preHandler.name?.length>0?z.preHandler.name:iJ});F=V(F,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:iJ}),H.call(this,z,F)}}function V(z,F={}){return function H(...q){let U=this[T5],[B]=q;if(U.isEnabled()===!1)return z.call(this,...q);let L=B[vU]??A8.context.active(),w=U.tracer.startSpan(`handler - ${z.name?.length>0?z.name:this.pluginName??iJ}`,{attributes:F},L);return A8.context.with(A8.trace.setSpan(L,w),function(){try{let M=z.call(this,...q);if(typeof M?.then==="function")return M.then((N)=>{return w.end(),N},(N)=>{return w.setStatus({code:A8.SpanStatusCode.ERROR,message:N.message}),w.recordException(N),w.end(),Promise.reject(N)});return w.end(),M}catch(M){throw w.setStatus({code:A8.SpanStatusCode.ERROR,message:M.message}),w.recordException(M),w.end(),M}},this)}}}}}var j7=r(Y0(),1),oj=r(q1(),1),FK=r(r0(),1),L$1=r(j1(),1);var nJ;(function(Z){Z.FASTIFY_NAME="fastify.name";let X="fastify.type";Z.FASTIFY_TYPE=X;let Y="hook.name";Z.HOOK_NAME=Y;let $="plugin.name";Z.PLUGIN_NAME=$})(nJ||(nJ={}));var SU;(function(Z){Z.MIDDLEWARE="middleware";let X="request_handler";Z.REQUEST_HANDLER=X})(SU||(SU={}));var AU;(function(Z){Z.MIDDLEWARE="middleware";let X="request handler";Z.REQUEST_HANDLER=X})(AU||(AU={}));var q$1=r(Y0(),1);var xU=Symbol("opentelemetry.instrumentation.fastify.request_active_span");function ug(Z,J,X,Y={}){let $=J.startSpan(X,{attributes:Y}),Q=Z[xU]||[];return Q.push($),Object.defineProperty(Z,xU,{enumerable:!1,configurable:!0,value:Q}),$}function sj(Z,J){let X=Z[xU]||[];if(!X.length)return;X.forEach((Y)=>{if(J)Y.setStatus({code:q$1.SpanStatusCode.ERROR,message:J.message}),Y.recordException(J);Y.end()}),delete Z[xU]}function U$1(Z,J,X){let Y,$=void 0;try{if($=Z(),F$1($))$.then((Q)=>J(void 0,Q),(Q)=>J(Q))}catch(Q){Y=Q}finally{if(!F$1($)){if(J(Y,$),Y)throw Y}return $}}function F$1(Z){return typeof Z==="object"&&Z&&typeof Object.getOwnPropertyDescriptor(Z,"then")?.value==="function"||!1}var tY6="0.1.0",eY6="@sentry/instrumentation-fastify-v3",B$1="anonymous",Z$6=new Set(["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError"]);class dg extends FK.InstrumentationBase{constructor(Z={}){super(eY6,tY6,Z)}init(){return[new FK.InstrumentationNodeModuleDefinition("fastify",[">=3.0.0 <4"],(Z)=>{return this._patchConstructor(Z)})]}_hookOnRequest(){let Z=this;return function J(X,Y,$){if(!Z.isEnabled())return $();Z._wrap(Y,"send",Z._patchSend());let Q=X,K=oj.getRPCMetadata(j7.context.active()),W=Q.routeOptions?Q.routeOptions.url:X.routerPath;if(W&&K?.type===oj.RPCType.HTTP)K.route=W;let G=X.method||"GET";E0().setTransactionName(`${G} ${W}`),$()}}_wrapHandler(Z,J,X,Y){let $=this;return this._diag.debug("Patching fastify route.handler function"),function(...Q){if(!$.isEnabled())return X.apply(this,Q);let K=X.name||Z||B$1,W=`${AU.MIDDLEWARE} - ${K}`,G=Q[1],V=ug(G,$.tracer,W,{[nJ.FASTIFY_TYPE]:SU.MIDDLEWARE,[nJ.PLUGIN_NAME]:Z,[nJ.HOOK_NAME]:J}),z=Y&&Q[Q.length-1];if(z)Q[Q.length-1]=function(...F){sj(G),z.apply(this,F)};return j7.context.with(j7.trace.setSpan(j7.context.active(),V),()=>{return U$1(()=>{return X.apply(this,Q)},(F)=>{if(F instanceof Error)V.setStatus({code:j7.SpanStatusCode.ERROR,message:F.message}),V.recordException(F);if(!Y)sj(G)})})}}_wrapAddHook(){let Z=this;return this._diag.debug("Patching fastify server.addHook function"),function(J){return function X(...Y){let $=Y[0],Q=Y[1],K=this.pluginName;if(!Z$6.has($))return J.apply(this,Y);let W=typeof Y[Y.length-1]==="function"&&Q.constructor.name!=="AsyncFunction";return J.apply(this,[$,Z._wrapHandler(K,$,Q,W)])}}}_patchConstructor(Z){let J=this;function X(...Y){let $=Z.fastify.apply(this,Y);return $.addHook("onRequest",J._hookOnRequest()),$.addHook("preHandler",J._hookPreHandler()),J$6(),J._wrap($,"addHook",J._wrapAddHook()),$}if(Z.errorCodes!==void 0)X.errorCodes=Z.errorCodes;return X.fastify=X,X.default=X,X}_patchSend(){let Z=this;return this._diag.debug("Patching fastify reply.send function"),function J(X){return function Y(...$){let Q=$[0];if(!Z.isEnabled())return X.apply(this,$);return FK.safeExecuteInTheMiddle(()=>{return X.apply(this,$)},(K)=>{if(!K&&Q instanceof Error)K=Q;sj(this,K)})}}}_hookPreHandler(){let Z=this;return this._diag.debug("Patching fastify preHandler function"),function J(X,Y,$){if(!Z.isEnabled())return $();let Q=X,K=Q.routeOptions?.handler||Q.context?.handler,W=K?.name.startsWith("bound ")?K.name.substring(6):K?.name,G=`${AU.REQUEST_HANDLER} - ${W||this.pluginName||B$1}`,V={[nJ.PLUGIN_NAME]:this.pluginName,[nJ.FASTIFY_TYPE]:SU.REQUEST_HANDLER,[L$1.SEMATTRS_HTTP_ROUTE]:Q.routeOptions?Q.routeOptions.url:X.routerPath};if(W)V[nJ.FASTIFY_NAME]=W;let z=ug(Y,Z.tracer,G,V);w$1(z);let{requestHook:F}=Z.getConfig();if(F)FK.safeExecuteInTheMiddle(()=>F(z,{request:X}),(H)=>{if(H)Z._diag.error("request hook failed",H)},!0);return j7.context.with(j7.trace.setSpan(j7.context.active(),z),()=>{$()})}}}function J$6(){let Z=X0();if(Z)Z.on("spanStart",(J)=>{w$1(J)})}function w$1(Z){let J=L0(Z).data,X=J["fastify.type"];if(J[j0]||!X)return;Z.setAttributes({[v0]:"auto.http.otel.fastify",[j0]:`${X}.fastify`});let Y=J["fastify.name"]||J["plugin.name"]||J["hook.name"];if(typeof Y==="string"){let $=Y.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName($)}}var O$1="Fastify",X$6="Fastify-V5",Y$6="Fastify-V3",lg=B0(Y$6,()=>new dg);function M$1(){let Z=X0();if(!Z)return;else return Z.getIntegrationByName(O$1)}function rj(Z,J,X,Y){let $=M$1()?.getShouldHandleError()||N$1;if(Y==="diagnostics-channel")this.diagnosticsChannelExists=!0;if(this.diagnosticsChannelExists&&Y==="onError-hook"){T4&&h.warn("Fastify error handler was already registered via diagnostics channel.","You can safely remove `setupFastifyErrorHandler` call and set `shouldHandleError` on the integration options.");return}if($(Z,J,X))Z1(Z,{mechanism:{handled:!1,type:"fastify"}})}var pg=B0(X$6,()=>{let Z=new mg,J=Z.plugin();return cg.subscribe("fastify.initialization",(X)=>{let Y=X.fastify;Y?.register(J).after(($)=>{if($)T4&&h.error("Failed to setup Fastify instrumentation",$);else if(Q$6(),Y)K$6(Y)})}),cg.subscribe("tracing:fastify.request.handler:error",(X)=>{let{error:Y,request:$,reply:Q}=X;rj.call(rj,Y,$,Q,"diagnostics-channel")}),Z}),$$6=({shouldHandleError:Z})=>{let J;return{name:O$1,setupOnce(){J=Z||N$1,lg(),pg()},getShouldHandleError(){return J},setShouldHandleError(X){J=X}}},tj=a((Z={})=>$$6(Z));function N$1(Z,J,X){let Y=X.statusCode;return Y>=500||Y<=299}function R$1(Z,J){if(J?.shouldHandleError)M$1()?.setShouldHandleError(J.shouldHandleError);let X=Object.assign(function(Y,$,Q){Y.addHook("onError",async(K,W,G)=>{rj.call(rj,G,K,W,"onError-hook")}),Q()},{[Symbol.for("skip-override")]:!0,[Symbol.for("fastify.display-name")]:"sentry-fastify-error-handler"});Z.register(X)}function j$1(Z){let J=L0(Z),X=J.description,Y=J.data,$=Y["fastify.type"],Q=$==="hook",K=$===X?.startsWith("handler -"),W=X==="request"||$==="request-handler";if(Y[j0]||!K&&!W&&!Q)return;let G=Q?"hook":K?"middleware":W?"request-handler":"<unknown>";Z.setAttributes({[v0]:"auto.http.otel.fastify",[j0]:`${G}.fastify`});let V=Y["fastify.name"]||Y["plugin.name"]||Y["hook.name"];if(typeof V==="string"){let z=V.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(z)}}function Q$6(){let Z=X0();if(Z)Z.on("spanStart",(J)=>{j$1(J)})}function K$6(Z){Z.addHook("onRequest",async(J,X)=>{if(J.opentelemetry){let{span:Q}=J.opentelemetry();if(Q)j$1(Q)}let Y=J.routeOptions?.url,$=J.method||"GET";E0().setTransactionName(`${$} ${Y}`)})}var KQ1=r(Y0(),1),WQ1=r(QQ1(),1);var GQ1="Graphql",tg=B0(GQ1,WQ1.GraphQLInstrumentation,(Z)=>{let J=VQ1(Z);return{...J,responseHook(X,Y){if(s1(X,"auto.graphql.otel.graphql"),Y.errors?.length&&!L0(X).status)X.setStatus({code:KQ1.SpanStatusCode.ERROR});let Q=L0(X).data,K=Q["graphql.operation.type"],W=Q["graphql.operation.name"];if(J.useOperationNameForRootSpan&&K){let G=a1(X),z=L0(G).data[RG]||[],F=W?`${K} ${W}`:`${K}`;if(Array.isArray(z))z.push(F),G.setAttribute(RG,z);else if(typeof z==="string")G.setAttribute(RG,[z,F]);else G.setAttribute(RG,F);if(!L0(G).data["original-description"])G.setAttribute("original-description",L0(G).description);G.updateName(`${L0(G).data["original-description"]} (${A$6(z)})`)}}}}),S$6=(Z={})=>{return{name:GQ1,setupOnce(){tg(VQ1(Z))}}},XD=a(S$6);function VQ1(Z){return{ignoreResolveSpans:!0,ignoreTrivialResolveSpans:!0,useOperationNameForRootSpan:!0,...Z}}function A$6(Z){if(Array.isArray(Z)){let J=Z.slice().sort();if(J.length<=5)return J.join(", ");else return`${J.slice(0,5).join(", ")}, +${J.length-5}`}return`${Z}`}var TQ1=r(CQ1(),1);var kQ1="Kafka",eg=B0(kQ1,()=>new TQ1.KafkaJsInstrumentation({consumerHook(Z){s1(Z,"auto.kafkajs.otel.consumer")},producerHook(Z){s1(Z,"auto.kafkajs.otel.producer")}})),f$6=()=>{return{name:kQ1,setupOnce(){eg()}}},YD=a(f$6);var gQ1=r(bQ1(),1);var mQ1="LruMemoizer",Zm=B0(mQ1,()=>new gQ1.LruMemoizerInstrumentation),m$6=()=>{return{name:mQ1,setupOnce(){Zm()}}},$D=a(m$6);var JK1=r(ZK1(),1);var XK1="Mongo",Qm=B0(XK1,()=>new JK1.MongoDBInstrumentation({dbStatementSerializer:p$6,responseHook(Z){s1(Z,"auto.db.otel.mongo")}}));function p$6(Z){let J=$m(Z);return JSON.stringify(J)}function $m(Z){if(Array.isArray(Z))return Z.map((J)=>$m(J));if(i$6(Z)){let J={};return Object.entries(Z).map(([X,Y])=>[X,$m(Y)]).reduce((X,Y)=>{if(a$6(Y))X[Y[0]]=Y[1];return X},J)}return"?"}function i$6(Z){return typeof Z==="object"&&Z!==null&&!n$6(Z)}function n$6(Z){let J=!1;if(typeof Buffer!=="undefined")J=Buffer.isBuffer(Z);return J}function a$6(Z){return Array.isArray(Z)}var s$6=()=>{return{name:XK1,setupOnce(){Qm()}}},QD=a(s$6);var DK1=r(jK1(),1);var PK1="Mongoose",Gm=B0(PK1,()=>new DK1.MongooseInstrumentation({responseHook(Z){s1(Z,"auto.db.otel.mongoose")}})),GQ6=()=>{return{name:PK1,setupOnce(){Gm()}}},WD=a(GQ6);var dK1=r(uK1(),1);var cK1="Mysql",Fm=B0(cK1,()=>new dK1.MySQLInstrumentation({})),PQ6=()=>{return{name:cK1,setupOnce(){Fm()}}},VD=a(PQ6);var VW1=r(GW1(),1);var zW1="Mysql2",wm=B0(zW1,()=>new VW1.MySQL2Instrumentation({responseHook(Z){s1(Z,"auto.db.otel.mysql2")}})),uQ6=()=>{return{name:zW1,setupOnce(){wm()}}},HD=a(uQ6);var rW1=r(IW1(),1),tW1=r(iW1(),1);var JK6=["get","set","setex"],Mm=["get","mget"],XK6=["set","setex"];function cU(Z,J){return Z.includes(J.toLowerCase())}function Nm(Z){if(cU(Mm,Z))return"cache.get";else if(cU(XK6,Z))return"cache.put";else return}function YK6(Z,J){return J.some((X)=>Z.startsWith(X))}function aW1(Z,J){try{if(J.length===0)return;let X=($)=>{if(typeof $==="string"||typeof $==="number"||Buffer.isBuffer($))return[$.toString()];else if(Array.isArray($))return nW1($.map((Q)=>X(Q)));else return["<unknown>"]},Y=J[0];if(cU(JK6,Z)&&Y!=null)return X(Y);return nW1(J.map(($)=>X($)))}catch{return}}function sW1(Z,J,X){if(!Nm(Z))return!1;for(let Y of J)if(YK6(Y,X))return!0;return!1}function oW1(Z){let J=(X)=>{try{if(Buffer.isBuffer(X))return X.byteLength;else if(typeof X==="string")return X.length;else if(typeof X==="number")return X.toString().length;else if(X===null||X===void 0)return 0;return JSON.stringify(X).length}catch{return}};return Array.isArray(Z)?Z.reduce((X,Y)=>{let $=J(Y);return typeof $==="number"?X!==void 0?X+$:$:X},0):J(Z)}function nW1(Z){let J=[],X=(Y)=>{Y.forEach(($)=>{if(Array.isArray($))X($);else J.push($)})};return X(Z),J}var eW1="Redis",Rm={},Z31=(Z,J,X,Y)=>{Z.setAttribute(v0,"auto.db.otel.redis");let $=aW1(J,X),Q=Nm(J);if(!$||!Q||!Rm.cachePrefixes||!sW1(J,$,Rm.cachePrefixes))return;let K=L0(Z).data["net.peer.name"],W=L0(Z).data["net.peer.port"];if(W&&K)Z.setAttributes({"network.peer.address":K,"network.peer.port":W});let G=oW1(Y);if(G)Z.setAttribute(_f,G);if(cU(Mm,J)&&G!==void 0)Z.setAttribute(Ef,G>0);Z.setAttributes({[j0]:Q,[If]:$});let V=$.join(", ");Z.updateName(t5(V,1024))},$K6=B0("IORedis",()=>{return new rW1.IORedisInstrumentation({responseHook:Z31})}),QK6=B0("Redis-4",()=>{return new tW1.RedisInstrumentation({responseHook:Z31})}),jm=Object.assign(()=>{$K6(),QK6()},{id:eW1}),KK6=(Z={})=>{return{name:eW1,setupOnce(){Rm=Z,jm()}}},qD=a(KK6);var S31=r(v31(),1);var A31="Postgres",_m=B0(A31,()=>new S31.PgInstrumentation({requireParentSpan:!0,requestHook(Z){s1(Z,"auto.db.otel.postgres")}})),lK6=()=>{return{name:A31,setupOnce(){_m()}}},wD=a(lK6);var yG=r(Y0(),1),ZX=r(r0(),1),Z5=r(j1(),1);var vm="PostgresJs",x31=[">=3.0.0 <4"],Sm=B0(vm,(Z)=>new h31({requireParentSpan:Z?.requireParentSpan??!0,requestHook:Z?.requestHook}));class h31 extends ZX.InstrumentationBase{constructor(Z){super("sentry-postgres-js",R1,Z)}init(){let Z=new ZX.InstrumentationNodeModuleDefinition("postgres",x31);return["src","cf/src","cjs/src"].forEach((J)=>{Z.files.push(new ZX.InstrumentationNodeModuleFile(`postgres/${J}/connection.js`,["*"],this._patchConnection.bind(this),this._unwrap.bind(this))),Z.files.push(new ZX.InstrumentationNodeModuleFile(`postgres/${J}/query.js`,x31,this._patchQuery.bind(this),this._unwrap.bind(this)))}),[Z]}_shouldCreateSpans(){let Z=this.getConfig();return yG.trace.getSpan(yG.context.active())!==void 0||!Z.requireParentSpan}_patchReject(Z,J){return new Proxy(Z,{apply:(X,Y,$)=>{J.setStatus({code:S8,message:$?.[0]?.message||"unknown_error"});let Q=Reflect.apply(X,Y,$);return J.setAttribute(Z5.ATTR_DB_RESPONSE_STATUS_CODE,$?.[0]?.code||"Unknown error"),J.setAttribute(Z5.ATTR_ERROR_TYPE,$?.[0]?.name||"Unknown error"),J.end(),Q}})}_patchResolve(Z,J){return new Proxy(Z,{apply:(X,Y,$)=>{let Q=Reflect.apply(X,Y,$),K=$?.[0]?.command;if(K)J.setAttribute(Z5.ATTR_DB_OPERATION_NAME,K);return J.end(),Q}})}_patchQuery(Z){return Z.Query.prototype.handle=new Proxy(Z.Query.prototype.handle,{apply:async(J,X,Y)=>{if(!this._shouldCreateSpans())return Reflect.apply(J,X,Y);let $=this._sanitizeSqlQuery(X.strings?.[0]);return dQ({name:$||"postgresjs.query",op:"db"},(Q)=>{let W=T0().getScopeData().contexts.postgresjsConnection;s1(Q,"auto.db.otel.postgres");let{requestHook:G}=this.getConfig();if(G)ZX.safeExecuteInTheMiddle(()=>G(Q,$,W),(H)=>{if(H)h.error(`Error in requestHook for ${vm} integration:`,H)});let V=W?.ATTR_DB_NAMESPACE||"<unknown database>",z=W?.ATTR_SERVER_ADDRESS||"<unknown host>",F=W?.ATTR_SERVER_PORT||"<unknown port>";Q.setAttribute(Z5.ATTR_DB_SYSTEM_NAME,"postgres"),Q.setAttribute(Z5.ATTR_DB_NAMESPACE,V),Q.setAttribute(Z5.ATTR_SERVER_ADDRESS,z),Q.setAttribute(Z5.ATTR_SERVER_PORT,F),Q.setAttribute(Z5.ATTR_DB_QUERY_TEXT,$),X.resolve=this._patchResolve(X.resolve,Q),X.reject=this._patchReject(X.reject,Q);try{return Reflect.apply(J,X,Y)}catch(H){throw Q.setStatus({code:S8}),Q.end(),H}})}}),Z}_patchConnection(Z){return new Proxy(Z,{apply:(J,X,Y)=>{let $=Y[0]?.database||"<unknown database>",Q=Y[0]?.host?.[0]||"<unknown host>",K=Y[0]?.port?.[0]||"<unknown port>";return T0().setContext("postgresjsConnection",{ATTR_DB_NAMESPACE:$,ATTR_SERVER_ADDRESS:Q,ATTR_SERVER_PORT:K}),Reflect.apply(J,X,Y)}})}_sanitizeSqlQuery(Z){if(!Z)return"Unknown SQL Query";return Z.replace(/\s+/g," ").trim().substring(0,1024).replace(/--.*?(\r?\n|$)/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/;\s*$/,"").replace(/\b\d+\b/g,"?").replace(/\s+/g," ").replace(/\bIN\b\s*\(\s*\?(?:\s*,\s*\?)*\s*\)/g,"IN (?)")}}var pK6=()=>{return{name:vm,setupOnce(){Sm()}}},OD=a(pK6);var b31=r(Y0(),1),MD=r(r0(),1),oY=r(Y0(),1);var iK6=process.env.PRISMA_SHOW_ALL_TRACES==="true",nK6="00-10-10-00";function aK6(Z){switch(Z){case"client":return oY.SpanKind.CLIENT;case"internal":default:return oY.SpanKind.INTERNAL}}var sK6=class{traceMiddleware;tracerProvider;ignoreSpanTypes;constructor({traceMiddleware:Z,tracerProvider:J,ignoreSpanTypes:X}){this.traceMiddleware=Z,this.tracerProvider=J,this.ignoreSpanTypes=X}isEnabled(){return!0}getTraceParent(Z){let J=oY.trace.getSpanContext(Z??oY.context.active());if(J)return`00-${J.traceId}-${J.spanId}-0${J.traceFlags}`;return nK6}dispatchEngineSpans(Z){let J=this.tracerProvider.getTracer("prisma"),X=new Map,Y=Z.filter(($)=>$.parentId===null);for(let $ of Y)g31(J,$,Z,X,this.ignoreSpanTypes)}getActiveContext(){return oY.context.active()}runInChildSpan(Z,J){if(typeof Z==="string")Z={name:Z};if(Z.internal&&!iK6)return J();if(Z.middleware&&!this.traceMiddleware)return J();let X=this.tracerProvider.getTracer("prisma"),Y=Z.context??this.getActiveContext(),$=`prisma:client:${Z.name}`;if(m31($,this.ignoreSpanTypes))return J();if(Z.active===!1){let Q=X.startSpan($,Z,Y);return f31(Q,J(Q,Y))}return X.startActiveSpan($,Z,(Q)=>f31(Q,J(Q,Y)))}};function g31(Z,J,X,Y,$){if(m31(J.name,$))return;let Q={attributes:J.attributes,kind:aK6(J.kind),startTime:J.startTime};Z.startActiveSpan(J.name,Q,(K)=>{if(Y.set(J.id,K.spanContext().spanId),J.links)K.addLinks(J.links.flatMap((G)=>{let V=Y.get(G);if(!V)return[];return{context:{spanId:V,traceId:K.spanContext().traceId,traceFlags:K.spanContext().traceFlags}}}));let W=X.filter((G)=>G.parentId===J.id);for(let G of W)g31(Z,G,X,Y,$);K.end(J.endTime)})}function f31(Z,J){if(oK6(J))return J.then((X)=>{return Z.end(),X},(X)=>{throw Z.end(),X});return Z.end(),J}function oK6(Z){return Z!=null&&typeof Z.then==="function"}function m31(Z,J){return J.some((X)=>typeof X==="string"?X===Z:X.test(Z))}var u31={name:"@prisma/instrumentation",version:"6.11.1",description:"OpenTelemetry compliant instrumentation for Prisma Client",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",exports:{".":{require:{types:"./dist/index.d.ts",default:"./dist/index.js"},import:{types:"./dist/index.d.ts",default:"./dist/index.mjs"}}},license:"Apache-2.0",homepage:"https://www.prisma.io",repository:{type:"git",url:"https://github.com/prisma/prisma.git",directory:"packages/instrumentation"},bugs:"https://github.com/prisma/prisma/issues",devDependencies:{"@prisma/internals":"workspace:*","@swc/core":"1.11.5","@types/jest":"29.5.14","@types/node":"18.19.76","@opentelemetry/api":"1.9.0",jest:"29.7.0","jest-junit":"16.0.0",typescript:"5.4.5"},dependencies:{"@opentelemetry/instrumentation":"^0.52.0 || ^0.53.0 || ^0.54.0 || ^0.55.0 || ^0.56.0 || ^0.57.0"},peerDependencies:{"@opentelemetry/api":"^1.8"},files:["dist"],keywords:["prisma","instrumentation","opentelemetry","otel"],scripts:{dev:"DEV=true tsx helpers/build.ts",build:"tsx helpers/build.ts",prepublishOnly:"pnpm run build",test:"jest"},sideEffects:!1},xm=u31.version,rK6=xm.split(".")[0],y31="PRISMA_INSTRUMENTATION",Am=`V${rK6}_PRISMA_INSTRUMENTATION`,tK6=u31.name,eK6="@prisma/client",d31=class extends MD.InstrumentationBase{tracerProvider;constructor(Z={}){super(tK6,xm,Z)}setTracerProvider(Z){this.tracerProvider=Z}init(){return[new MD.InstrumentationNodeModuleDefinition(eK6,[xm])]}enable(){let Z=this._config,J={helper:new sK6({traceMiddleware:Z.middleware??!1,tracerProvider:this.tracerProvider??b31.trace.getTracerProvider(),ignoreSpanTypes:Z.ignoreSpanTypes??[]})};global[y31]=J,global[Am]=J}disable(){delete global[y31],delete global[Am]}isEnabled(){return Boolean(global[Am])}};var c31="Prisma";function ZW6(Z){return!!Z&&typeof Z==="object"&&"dispatchEngineSpans"in Z}function l31(){let Z=globalThis.PRISMA_INSTRUMENTATION;return Z&&typeof Z==="object"&&"helper"in Z?Z.helper:void 0}class p31 extends d31{constructor(){super()}enable(){super.enable();let Z=l31(),J=!1;if(ZW6(Z))Z.createEngineSpan=()=>{e0(()=>{if(!J)J=!0,console.warn("[Sentry] The Sentry SDK supports tracing with Prisma version 5 only with limited capabilities. For full tracing capabilities pass `prismaInstrumentation` for version 5 to the Sentry `prismaIntegration`. Read more: https://docs.sentry.io/platforms/javascript/guides/node/configuration/integrations/prisma/")})}}}var JW6=B0(c31,(Z)=>{if(Z?.prismaInstrumentation)return Z.prismaInstrumentation;return new p31}),ND=a(({prismaInstrumentation:Z}={})=>{return{name:c31,setupOnce(){JW6({prismaInstrumentation:Z})},setup(J){if(!l31())return;J.on("spanStart",(X)=>{let Y=L0(X);if(Y.description?.startsWith("prisma:"))X.setAttribute(v0,"auto.db.otel.prisma");if(Y.description==="prisma:engine:db_query"&&Y.data["db.query.text"])X.updateName(Y.data["db.query.text"]);if(Y.description==="prisma:engine:db_query"&&!Y.data["db.system"])X.setAttribute("db.system","prisma")})}}});var VG1=r(GG1(),1);var zG1="Hapi",DD=B0(zG1,()=>new VG1.HapiInstrumentation),jW6=()=>{return{name:zG1,setupOnce(){DD()}}},PD=a(jW6);function DW6(Z){return!!(Z&&typeof Z==="object"&&("error"in Z)&&Z.error)}function PW6(Z){Z1(Z,{mechanism:{type:"hapi",handled:!1,data:{function:"hapiErrorPlugin"}}})}var CW6={name:"SentryHapiErrorPlugin",version:R1,register:async function(Z){Z.events.on({name:"request",channels:["error"]},(X,Y)=>{if(E0()!==B4()){let $=X.route;if($.path)E0().setTransactionName(`${$.method.toUpperCase()} ${$.path}`)}else T4&&h.warn("Isolation scope is still the default isolation scope - skipping setting transactionName");if(DW6(Y))PW6(Y.error)})}};async function HG1(Z){await Z.register(CW6);let J=X0();if(J)J.on("spanStart",(X)=>{TW6(X)});cJ(Z.register,"hapi")}function TW6(Z){let J=L0(Z).data,X=J["hapi.type"];if(J[j0]||!X)return;Z.setAttributes({[v0]:"auto.http.otel.hapi",[j0]:`${X}.hapi`})}var xG1=r(AG1(),1),hG1=r(j1(),1);var fG1="Koa",cm=B0(fG1,xG1.KoaInstrumentation,(Z={})=>{return{ignoreLayersType:Z.ignoreLayersType,requestHook(J,X){s1(J,"auto.http.otel.koa");let Y=L0(J).data,$=Y["koa.type"];if($)J.setAttribute(j0,`${$}.koa`);let Q=Y["koa.name"];if(typeof Q==="string")J.updateName(Q||"< unknown >");if(E0()===B4()){T4&&h.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let K=Y[hG1.ATTR_HTTP_ROUTE],W=X.context?.request?.method?.toUpperCase()||"GET";if(K)E0().setTransactionName(`${W} ${K}`)}}}),hW6=(Z={})=>{return{name:fG1,setupOnce(){cm(Z)}}},kD=a(hW6),yG1=(Z)=>{Z.use(async(J,X)=>{try{await X()}catch(Y){throw Z1(Y),Y}}),cJ(Z.use,"koa")};var $V1=r(YV1(),1);var QV1="Connect",am=B0(QV1,()=>new $V1.ConnectInstrumentation),sW6=()=>{return{name:QV1,setupOnce(){am()}}},ID=a(sW6);function oW6(Z,J,X,Y){Z1(Z),Y(Z)}var KV1=(Z)=>{Z.use(oW6);let J=X0();if(J)J.on("spanStart",(X)=>{rW6(X)});cJ(Z.use,"connect")};function rW6(Z){let J=L0(Z).data,X=J["connect.type"];if(J[j0]||!X)return;Z.setAttributes({[v0]:"auto.http.otel.connect",[j0]:`${X}.connect`});let Y=J["connect.name"];if(typeof Y==="string")Z.updateName(Y)}var kV1=r(TV1(),1);var EV1="Knex",q36=B0(EV1,()=>new kV1.KnexInstrumentation({requireParentSpan:!0})),U36=()=>{let Z;return{name:EV1,setupOnce(){let J=q36();Z=fJ(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let{data:Y}=L0(X);if("knex.version"in Y)X.setAttribute(v0,"auto.db.otel.knex")}))}}},IV1=a(U36);var nV1=r(iV1(),1);var R36=new Set(["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"]),aV1="Tedious",om=B0(aV1,()=>new nV1.TediousInstrumentation({})),j36=()=>{let Z;return{name:aV1,setupOnce(){let J=om();Z=fJ(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let{description:Y,data:$}=L0(X);if(!Y||$["db.system"]!=="mssql")return;let Q=Y.split(" ")[0]||"";if(R36.has(Q))X.setAttribute(v0,"auto.db.otel.tedious")}))}}},xD=a(j36);var $z1=r(Yz1(),1);var Qz1="GenericPool",tm=B0(Qz1,()=>new $z1.GenericPoolInstrumentation({})),T36=()=>{let Z;return{name:Qz1,setupOnce(){let J=tm();Z=fJ(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let $=L0(X).description;if($==="generic-pool.aquire"||$==="generic-pool.acquire")X.setAttribute(v0,"auto.db.otel.generic_pool")}))}}},hD=a(T36);var Oz1=r(wz1(),1);var Mz1="Dataloader",I36=B0(Mz1,()=>new Oz1.DataloaderInstrumentation({requireParentSpan:!0})),_36=()=>{let Z;return{name:Mz1,setupOnce(){let J=I36();Z=fJ(J)},setup(J){Z?.(()=>{J.on("spanStart",(X)=>{let Y=L0(X);if(Y.description?.startsWith("dataloader"))X.setAttribute(v0,"auto.db.otel.dataloader");if(Y.description==="dataloader.load"||Y.description==="dataloader.loadMany"||Y.description==="dataloader.batch")X.setAttribute(j0,"cache.get")})})}}},Nz1=a(_36);var mz1=r(gz1(),1);var uz1="Amqplib",o36={consumeEndHook:(Z)=>{s1(Z,"auto.amqplib.otel.consumer")},publishHook:(Z)=>{s1(Z,"auto.amqplib.otel.publisher")}},Yu=B0(uz1,()=>new mz1.AmqplibInstrumentation(o36)),r36=()=>{return{name:uz1,setupOnce(){Yu()}}},bD=a(r36);var sU="VercelAI";var gD=r(r0(),1);var dz1=["generateText","streamText","generateObject","streamObject","embed","embedMany"];function t36(Z,J,X,Y){let $=Z?.recordInputs!==void 0?Z.recordInputs:J.recordInputs!==void 0?J.recordInputs:X===!0?!0:Y,Q=Z?.recordOutputs!==void 0?Z.recordOutputs:J.recordOutputs!==void 0?J.recordOutputs:X===!0?!0:Y;return{recordInputs:$,recordOutputs:Q}}class oU extends gD.InstrumentationBase{__init(){this._isPatched=!1}__init2(){this._callbacks=[]}constructor(Z={}){super("@sentry/instrumentation-vercel-ai",R1,Z);oU.prototype.__init.call(this),oU.prototype.__init2.call(this)}init(){return new gD.InstrumentationNodeModuleDefinition("ai",[">=3.0.0 <5"],this._patch.bind(this))}callWhenPatched(Z){if(this._isPatched)Z();else this._callbacks.push(Z)}_patch(Z){this._isPatched=!0,this._callbacks.forEach((X)=>X()),this._callbacks=[];function J(X){return(...Y)=>{let $=Y[0].experimental_telemetry||{},Q=$.isEnabled,K=T0().getClient(),W=K?.getIntegrationByName(sU),G=W?.options,V=W?Boolean(K?.getOptions().sendDefaultPii):!1,{recordInputs:z,recordOutputs:F}=t36(G,$,Q,V);return Y[0].experimental_telemetry={...$,isEnabled:Q!==void 0?Q:!0,recordInputs:z,recordOutputs:F},SJ(()=>{return X.apply(this,Y)},(H)=>{if(H&&typeof H==="object")e1(H,"_sentry_active_span",C6())})}}if(Object.prototype.toString.call(Z)==="[object Module]"){for(let X of dz1)Z[X]=J(Z[X]);return Z}else{let X=dz1.reduce((Y,$)=>{return Y[$]=J(Z[$]),Y},{});return{...Z,...X}}}}var $u=B0(sU,()=>new oU({}));function e36(Z){return!!Z.getIntegrationByName("Modules")?.getModules?.()?.ai}var ZG6=(Z={})=>{let J;return{name:sU,options:Z,setupOnce(){J=$u()},afterAllSetup(X){if(Z.force??e36(X))$j(X);else J?.callWhenPatched(()=>$j(X))}}},mD=a(ZG6);var uD=r(r0(),1);var JG6=[">=4.0.0 <6"];function XG6(Z,J){let X=Z?.recordInputs??J,Y=Z?.recordOutputs??J;return{recordInputs:X,recordOutputs:Y}}class Qu extends uD.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-openai",R1,Z)}init(){return new uD.InstrumentationNodeModuleDefinition("openai",JG6,this._patch.bind(this))}_patch(Z){let J=Z.OpenAI,X=function(...Y){let $=Reflect.construct(J,Y),Q=T0().getClient(),W=Q?.getIntegrationByName(PY)?.options,G=Boolean(Q?.getOptions().sendDefaultPii),{recordInputs:V,recordOutputs:z}=XG6(W,G);return Qb($,{recordInputs:V,recordOutputs:z})};Object.setPrototypeOf(X,J),Object.setPrototypeOf(X.prototype,J.prototype);for(let Y of Object.getOwnPropertyNames(J))if(!["length","name","prototype"].includes(Y)){let $=Object.getOwnPropertyDescriptor(J,Y);if($)Object.defineProperty(X,Y,$)}try{Z.OpenAI=X}catch(Y){Object.defineProperty(Z,"OpenAI",{value:X,writable:!0,configurable:!0,enumerable:!0})}return Z}}var Ku=B0(PY,()=>new Qu({})),YG6=(Z={})=>{return{name:PY,options:Z,setupOnce(){Ku()}}},dD=a(YG6);var cz1=a((Z)=>{if(!O7())e0(()=>{console.warn("The launchDarklyIntegration() can only be used in the browser.")});return{name:"LaunchDarkly"}});function lz1(){if(!O7())e0(()=>{console.warn("The buildLaunchDarklyFlagUsedHandler() can only be used in the browser.")});return{name:"sentry-flag-auditor",type:"flag-used",synchronous:!0,method:()=>null}}var pz1=a((Z)=>{if(!O7())e0(()=>{console.warn("The openFeatureIntegration() can only be used in the browser.")});return{name:"OpenFeature"}});class Wu{constructor(){if(!O7())e0(()=>{console.warn("The OpenFeatureIntegrationHook can only be used in the browser.")})}after(){}error(){}}var iz1=a((Z)=>{if(!O7())e0(()=>{console.warn("The statsigIntegration() can only be used in the browser.")});return{name:"Statsig"}});var nz1=a((Z)=>{if(!O7())e0(()=>{console.warn("The unleashIntegration() can only be used in the browser.")});return{name:"Unleash"}});function cD(){return[pj(),tj(),XD(),QD(),WD(),VD(),HD(),qD(),wD(),ND(),PD(),kD(),ID(),xD(),hD(),YD(),bD(),$D(),mD(),dD(),OD()]}function az1(){return[Dg,Ag,xg,am,pg,lg,DD,eg,cm,Zm,Qm,Gm,Fm,wm,_m,DD,tg,jm,om,tm,Yu,$u,Ku,Sm]}var dG=r(Y0(),1),sz1=r(xb(),1),oz1=r(yb(),1),cG=r(j1(),1);var rz1=r(UR(),1);import $G6 from"module";var Gu=1e6;function lD(Z,J={}){if(Z.getOptions().debug)Lg();let X=WG6(Z,J);Z.traceProvider=X}function QG6(){let[Z=0,J=0]=process.versions.node.split(".").map(Number);if(Z>=21||Z===20&&J>=6||Z===18&&J>=19){if(!M0._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:X}=rz1.createAddHookMessageChannel();$G6.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:X,include:[]},transferList:[X]})}catch(X){h.warn("Failed to register ESM hook",X)}}else e0(()=>{console.warn(`[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`)})}function tz1(Z={}){let{debug:J}=Z;if(J)h.enable();if(!C4())QG6();KG6(Z.integrations).forEach((X)=>{if(X(),J)h.log(`[Sentry] Preloaded ${X.id} instrumentation`)})}function KG6(Z){let J=az1();if(!Z)return J;return J.filter((X)=>Z.includes(X.id))}function WG6(Z,J={}){let X=new oz1.BasicTracerProvider({sampler:new Xg(Z),resource:new sz1.Resource({[cG.ATTR_SERVICE_NAME]:"node",[cG.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[cG.ATTR_SERVICE_VERSION]:R1}),forceFlushTimeoutMillis:500,spanProcessors:[new Jg({timeout:GG6(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});return dG.trace.setGlobalTracerProvider(X),dG.propagation.setGlobalPropagator(new ob),dG.context.setGlobalContextManager(new LU),X}function GG6(Z){if(Z==null)return;if(Z>Gu)return T4&&h.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${Gu}`),Gu;else if(Z<=0||Number.isNaN(Z)){T4&&h.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function Vu(){return xj().filter((J)=>J.name!=="Http"&&J.name!=="NodeFetch").concat(hj(),yj())}function zu(Z){return[...Vu(),...u8(Z)?cD():[]]}function pD(Z={}){return ez1(Z,zu)}function ez1(Z={},J){nQ(Z,"node");let X=Ng({...Z,defaultIntegrations:Z.defaultIntegrations??J(Z)});if(X&&!Z.skipOpenTelemetrySetup)lD(X,{spanProcessors:Z.openTelemetrySpanProcessors}),DU();return X}function ZH1(Z={}){return ez1(Z,()=>[])}var NK;((B)=>{B.BUILD_PACKETS="build_packets";B.ENTITIES_EMIT_UPDATES="entities_emit_updates";B.ENTITIES_TICK="entities_tick";B.NETWORK_SYNCHRONIZE="network_synchronize";B.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";B.PHYSICS_CLEANUP="physics_cleanup";B.PHYSICS_STEP="physics_step";B.SEND_ALL_PACKETS="send_all_packets";B.SEND_PACKETS="send_packets";B.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";B.SERIALIZE_PACKETS="serialize_packets";B.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";B.SIMULATION_STEP="simulation_step";B.TICKER_TICK="ticker_tick";B.WORLD_TICK="world_tick"})(NK||={});class R8{static getProcessStats(Z=!1){let J=process.memoryUsage(),X={jsHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:J.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:J.heapUsed/J.heapTotal,unit:"percent"},processHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:J.rss/1024/1024,unit:"megabyte"}};if(Z)return X;return Object.fromEntries(Object.entries(X).map(([Y,$])=>[Y,$.value]))}static initializeSentry(Z,J=50){pD({dsn:Z,release:BA,environment:process.env.NODE_ENV||"development",tracesSampleRate:1,initialScope:{tags:{gameId:process.env.HYTOPIA_GAME_ID??"unknown",gameSlug:process.env.HYTOPIA_GAME_SLUG??"unknown",lobbyId:process.env.HYTOPIA_LOBBY_ID??"unknown",region:process.env.REGION??"unknown"}},beforeSend:(X)=>{return X.extra=R8.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let $=X?.start_timestamp,Q=X?.timestamp;if(!$||!Q)return null;if((Q-$)*1000>J)return X.measurements=R8.getProcessStats(!0),X}return null}})}static startSpan(Z,J){if(mq())return O4({attributes:Z.attributes,name:Z.operation,op:Z.operation},J);else return J()}static sentry(){return Hu}}var JH1=new e$,zG6=5000,XH1={RAW:0,GZIP:1};class Q7 extends O0{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_wrtcDirectTransport=null;_wrtcClientServerTransport=null;_wrtcClientServerDataProducers=[];_wrtcClientServerDataConsumers=[];_wrtcServerClientTransport=null;_wrtcServerClientReliableDataProducer=null;_wrtcServerClientUnreliableDataProducer=null;_wrtcServerClientDataConsumers=[];_ws;id;constructor(Z,J){super();this.id=e40(),this.onPacket(Q0.PacketId.CONNECTION,this._onConnectionPacket),this.onPacket(Q0.PacketId.HEARTBEAT,this._onHeartbeatPacket),this.bindWs(Z),O0.globalInstance.emit("CONNECTION.OPENED",{connection:this,req:J})}static clearCachedPacketsSerializedBuffers(){if(Q7._cachedPacketsSerializedBuffer.size>0)Q7._cachedPacketsSerializedBuffer.clear()}static serializePackets(Z){for(let X of Z)if(!Q0.isValidPacket(X))return c.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let J=Q7._cachedPacketsSerializedBuffer.get(Z);if(J)return J;return R8.startSpan({operation:"serialize_packets",attributes:{packets:Z.length,packetIds:Z.map((X)=>X[0]).join(",")}},(X)=>{let Y=JH1.pack(Z),$=Y.byteLength>128,Q=$?VG6(Y,{level:1}):Y,K=$?XH1.GZIP:XH1.RAW;return Y=Buffer.allocUnsafe(Q.length+1),Y[0]=K,Q.copy(Y,1),X?.setAttribute("serializedBytes",Y.byteLength),Q7._cachedPacketsSerializedBuffer.set(Z,Y),Y})}bindWs(Z){let J=!!this._ws;if(J&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{},this.send([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{k:!0})]);if(this._ws=Z,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onWsClose,this._ws.onerror=this._onWsError,this.send([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})],!0,!0),J)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this});if(YZ.instance.isWrtcEnabled)this._upgradeToWRTC()}closeWrtc(){this._closeWrtcClientServerTransport(),this._closeWrtcServerClientTransport()}disconnect(){try{this._ws.close()}catch(Z){c.error(`Connection.disconnect(): Connection disconnect failed. Error: ${Z}`)}}onPacket(Z,J){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===Z)J(X)})}send(Z,J=!0,X=!1){if(this._closeTimeout)return;if(this._ws.readyState!==h_.default.OPEN)return;R8.startSpan({operation:"send_packets",attributes:{forceWs:X?"true":"false",wrtcConnected:this._wrtcServerClientTransport?.iceState==="completed"?"true":"false"}},()=>{try{let Y=Q7.serializePackets(Z);if(!Y)return;if(this._wrtcServerClientTransport?.iceState==="completed"&&Y.length<(this._wrtcServerClientTransport?.sctpParameters?.maxMessageSize??0)&&!X)try{(J?this._wrtcServerClientReliableDataProducer:this._wrtcServerClientUnreliableDataProducer).send(Y)}catch{this._ws.send(Y)}else this._ws.send(Y);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:Z})}catch(Y){c.error(`Connection.send(): Packet send failed. Error: ${Y}`)}})}_closeWrtcClientServerTransport(){this._wrtcDirectTransport?.close(),this._wrtcDirectTransport=null,this._wrtcClientServerTransport?.close(),this._wrtcClientServerTransport=null,this._wrtcClientServerDataProducers.forEach((Z)=>Z.close()),this._wrtcClientServerDataProducers=[],this._wrtcClientServerDataConsumers.forEach((Z)=>Z.close()),this._wrtcClientServerDataConsumers=[]}_closeWrtcServerClientTransport(){this._wrtcServerClientTransport?.close(),this._wrtcServerClientTransport=null,this._wrtcServerClientDataConsumers.forEach((Z)=>Z.close()),this._wrtcServerClientDataConsumers=[],this._wrtcServerClientReliableDataProducer?.close(),this._wrtcServerClientReliableDataProducer=null,this._wrtcServerClientUnreliableDataProducer?.close(),this._wrtcServerClientUnreliableDataProducer=null}_onConnectionPacket=async(Z)=>{let J=Z[1],X=J.c,Y=J.d;if(X){let{i:$,d:Q}=X,K=!1;if($==this._wrtcClientServerTransport?.id)await this._wrtcClientServerTransport.connect({dtlsParameters:Q}),K=!0;if($==this._wrtcServerClientTransport?.id)await this._wrtcServerClientTransport.connect({dtlsParameters:Q}),K=!0;if(K)this.send([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{ca:{i:$}})])}if(Y)for(let $ of Y){let{s:Q,l:K}=$,W=await this._wrtcClientServerTransport.produceData({label:K,sctpStreamParameters:Q}),G=await this._wrtcDirectTransport.consumeData({dataProducerId:W.id});this._wrtcClientServerDataProducers.push(W),this._wrtcClientServerDataConsumers.push(G),G.on("message",(V)=>this._onMessage(V)),this.send([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{pa:{i:W.id,l:K}})])}};_onHeartbeatPacket=()=>{this.send([Q0.createPacket(Q0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0,!0)};_onMessage=(Z)=>{try{let J=this._deserialize(Z);if(!J)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:J})}catch(J){c.error(`Connection._ws.onmessage(): Error: ${J}`)}};_onWrtcIceStateChange=(Z,J)=>{if(["disconnected","closed"].includes(J)){if(Z==this._wrtcClientServerTransport)this._closeWrtcClientServerTransport();else if(Z==this._wrtcServerClientTransport)this._closeWrtcServerClientTransport()}};_onWsClose=()=>{this.closeWrtc(),this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},zG6)};_onWsError=(Z)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:Z})};_upgradeToWRTC=async()=>{let Z=await YZ.instance.createWrtcTransports();if(!Z)return!1;let{directTransport:J,clientServerTransport:X,serverClientTransport:Y}=Z;this._wrtcDirectTransport=J,this._wrtcClientServerTransport=X,this._wrtcClientServerTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcClientServerTransport,K)}),this._wrtcServerClientTransport=Y,this._wrtcServerClientTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcServerClientTransport,K)}),this._wrtcServerClientReliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scr",sctpStreamParameters:{streamId:0,ordered:!0}}),this._wrtcServerClientUnreliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scu",sctpStreamParameters:{streamId:1,ordered:!1,maxPacketLifeTime:35}});let $=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientReliableDataProducer.id}),Q=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientUnreliableDataProducer.id});return this._wrtcServerClientDataConsumers.push($,Q),this.send([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{d:[{i:$.id,pi:$.dataProducerId,l:"scr",s:$.sctpStreamParameters},{i:Q.id,pi:Q.dataProducerId,l:"scu",s:Q.sctpStreamParameters}],t:[{i:this._wrtcClientServerTransport.id,f:"cs",d:this._wrtcClientServerTransport.dtlsParameters,ic:this._wrtcClientServerTransport.iceCandidates,ip:this._wrtcClientServerTransport.iceParameters,s:this._wrtcClientServerTransport.sctpParameters},{i:this._wrtcServerClientTransport.id,f:"sc",d:this._wrtcServerClientTransport.dtlsParameters,ic:this._wrtcServerClientTransport.iceCandidates,ip:this._wrtcServerClientTransport.iceParameters,s:this._wrtcServerClientTransport.sctpParameters}]})]),!0};_deserialize(Z){let J=JH1.unpack(Z);if(!J||typeof J!=="object"||typeof J[0]!=="number")return c.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(J)}`);if(!Q0.isValidPacket(J))return c.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(J)}`);return J}}class rU{_lights=new Map;_nextLightId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedLights(Z){this.getAllEntityAttachedLights(Z).forEach((J)=>{J.despawn()})}getAllLights(){return Array.from(this._lights.values())}getAllEntityAttachedLights(Z){return this.getAllLights().filter((J)=>J.attachedToEntity===Z)}registerLight(Z){if(Z.id!==void 0)return Z.id;let J=this._nextLightId;return this._lights.set(J,Z),this._nextLightId++,J}unregisterLight(Z){if(Z.id===void 0)return;this._lights.delete(Z.id)}}class U6{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(Z){return this._map.get(Z)}set(Z,J){let X=this._map.has(Z);if(this._map.set(Z,J),!X)this._values.push(J);else this._isDirty=!0;return this}has(Z){return this._map.has(Z)}delete(Z){let J=this._map.delete(Z);if(J)this._isDirty=!0;return J}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(Z,J){this._map.forEach((X,Y)=>{Z.call(J,X,Y,this)})}keys(){return this._map.keys()}values(){return this._map.values()}entries(){return this._map.entries()}[Symbol.iterator](){return this._map[Symbol.iterator]()}_syncArray(){this._values.length=0;for(let Z of this._map.values())this._values.push(Z);this._isDirty=!1}}var YH1;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(YH1||={});var Fu;((H)=>{H.DESPAWN="LIGHT.DESPAWN";H.SET_ANGLE="LIGHT.SET_ANGLE";H.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";H.SET_COLOR="LIGHT.SET_COLOR";H.SET_DISTANCE="LIGHT.SET_DISTANCE";H.SET_INTENSITY="LIGHT.SET_INTENSITY";H.SET_OFFSET="LIGHT.SET_OFFSET";H.SET_PENUMBRA="LIGHT.SET_PENUMBRA";H.SET_POSITION="LIGHT.SET_POSITION";H.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";H.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";H.SPAWN="LIGHT.SPAWN"})(Fu||={});class qu extends O0{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)c.fatalError("Either attachedToEntity or position must be set, but not both.");super();c.warning("WARNING: Lights are poorly optimized at this time. Using more than a few lights in your game can cause extremely bad performance (FPS) issues. Use lights sparingly!"),this._angle=Z.angle,this._attachedToEntity=Z.attachedToEntity,this._color=Z.color??{r:255,g:255,b:255},this._distance=Z.distance,this._intensity=Z.intensity??1,this._offset=Z.offset,this._penumbra=Z.penumbra,this._position=Z.position,this._trackedEntity=Z.trackedEntity,this._trackedPosition=Z.trackedPosition,this._type=Z.type??0}get id(){return this._id}get angle(){return this._angle}get attachedToEntity(){return this._attachedToEntity}get color(){return this._color}get distance(){return this._distance}get intensity(){return this._intensity}get isSpawned(){return this._id!==void 0}get offset(){return this._offset}get penumbra(){return this._penumbra}get position(){return this._position}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get type(){return this._type}get world(){return this._world}setAngle(Z){if(this._angle===Z)return;if(this._angle=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return c.error(`Light.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:Z})}setColor(Z){if(this._color.r===Z.r&&this._color.g===Z.g&&this._color.b===Z.b)return;if(this._color=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:Z})}setDistance(Z){if(this._distance===Z)return;if(this._distance=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:Z})}setIntensity(Z){if(this._intensity===Z)return;if(this._intensity=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:Z})}setPenumbra(Z){if(this._penumbra===Z)return;if(this._penumbra=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:Z})}setTrackedEntity(Z){if(!Z.isSpawned)return c.error(`Light.setTrackedEntity(): Entity ${Z.id} is not spawned!`);if(this._trackedEntity===Z)return;if(this._trackedEntity=Z,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:Z})}setTrackedPosition(Z){if(this._trackedPosition===Z)return;if(this._trackedPosition=Z,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.lightManager.unregisterLight(this),this.emitWithWorld(this._world,"LIGHT.DESPAWN",{light:this}),this._id=void 0,this._world=void 0}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return c.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=Z.lightManager.registerLight(this),this._world=Z,this.emitWithWorld(Z,"LIGHT.SPAWN",{light:this})}serialize(){return k0.serializeLight(this)}}var Uu;((u)=>{u.BURST="PARTICLE_EMITTER.BURST";u.DESPAWN="PARTICLE_EMITTER.DESPAWN";u.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";u.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";u.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";u.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";u.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";u.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";u.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";u.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";u.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";u.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";u.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";u.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";u.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";u.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";u.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";u.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";u.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";u.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";u.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";u.SET_RATE="PARTICLE_EMITTER.SET_RATE";u.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";u.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";u.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";u.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";u.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";u.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";u.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";u.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";u.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";u.SPAWN="PARTICLE_EMITTER.SPAWN"})(Uu||={});class Bu extends O0{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)c.fatalError("Either attachedToEntity or position must be set, but not both.");if(!Z.textureUri)c.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=Z.alphaTest??0.5,this._attachedToEntity=Z.attachedToEntity,this._attachedToEntityNodeName=Z.attachedToEntityNodeName,this._colorEnd=Z.colorEnd,this._colorEndVariance=Z.colorEndVariance,this._colorStart=Z.colorStart,this._colorStartVariance=Z.colorStartVariance,this._gravity=Z.gravity,this._lifetime=Z.lifetime,this._lifetimeVariance=Z.lifetimeVariance,this._maxParticles=Z.maxParticles,this._offset=Z.offset,this._opacityEnd=Z.opacityEnd,this._opacityEndVariance=Z.opacityEndVariance,this._opacityStart=Z.opacityStart,this._opacityStartVariance=Z.opacityStartVariance,this._paused=!1,this._position=Z.position,this._positionVariance=Z.positionVariance,this._rate=Z.rate,this._rateVariance=Z.rateVariance,this._sizeEnd=Z.sizeEnd,this._sizeEndVariance=Z.sizeEndVariance,this._sizeStart=Z.sizeStart,this._sizeStartVariance=Z.sizeStartVariance,this._textureUri=Z.textureUri,this._transparent=Z.transparent,this._velocity=Z.velocity,this._velocityVariance=Z.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(Z){if(this._alphaTest===Z)return;if(this._alphaTest=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return c.error(`ParticleEmitter.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:Z})}setAttachedToEntityNodeName(Z){if(this._attachedToEntityNodeName===Z)return;if(this._attachedToEntityNodeName=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:Z})}setColorEnd(Z){if(this._colorEnd&&this._colorEnd.r===Z.r&&this._colorEnd.g===Z.g&&this._colorEnd.b===Z.b)return;if(this._colorEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:Z})}setColorEndVariance(Z){if(this._colorEndVariance&&this._colorEndVariance.r===Z.r&&this._colorEndVariance.g===Z.g&&this._colorEndVariance.b===Z.b)return;if(this._colorEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:Z})}setColorStart(Z){if(this._colorStart&&this._colorStart.r===Z.r&&this._colorStart.g===Z.g&&this._colorStart.b===Z.b)return;if(this._colorStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:Z})}setColorStartVariance(Z){if(this._colorStartVariance&&this._colorStartVariance.r===Z.r&&this._colorStartVariance.g===Z.g&&this._colorStartVariance.b===Z.b)return;if(this._colorStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:Z})}setGravity(Z){if(this._gravity&&this._gravity.x===Z.x&&this._gravity.y===Z.y&&this._gravity.z===Z.z)return;if(this._gravity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:Z})}setLifetime(Z){if(this._lifetime===Z)return;if(this._lifetime=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:Z})}setLifetimeVariance(Z){if(this._lifetimeVariance===Z)return;if(this._lifetimeVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:Z})}setMaxParticles(Z){if(this._maxParticles===Z)return;if(this._maxParticles=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:Z})}setOpacityEnd(Z){if(this._opacityEnd===Z)return;if(this._opacityEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:Z})}setOpacityEndVariance(Z){if(this._opacityEndVariance===Z)return;if(this._opacityEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:Z})}setOpacityStart(Z){if(this._opacityStart===Z)return;if(this._opacityStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:Z})}setOpacityStartVariance(Z){if(this._opacityStartVariance===Z)return;if(this._opacityStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:Z})}setPositionVariance(Z){if(this._positionVariance&&this._positionVariance.x===Z.x&&this._positionVariance.y===Z.y&&this._positionVariance.z===Z.z)return;if(this._positionVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:Z})}setRate(Z){if(this._rate===Z)return;if(this._rate=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:Z})}setRateVariance(Z){if(this._rateVariance===Z)return;if(this._rateVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:Z})}setSizeEnd(Z){if(this._sizeEnd===Z)return;if(this._sizeEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:Z})}setSizeEndVariance(Z){if(this._sizeEndVariance===Z)return;if(this._sizeEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:Z})}setSizeStart(Z){if(this._sizeStart===Z)return;if(this._sizeStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:Z})}setSizeStartVariance(Z){if(this._sizeStartVariance===Z)return;if(this._sizeStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:Z})}setTextureUri(Z){if(this._textureUri===Z)return;if(this._textureUri=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:Z})}setTransparent(Z){if(this._transparent===Z)return;if(this._transparent=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:Z})}setVelocity(Z){if(this._velocity&&this._velocity.x===Z.x&&this._velocity.y===Z.y&&this._velocity.z===Z.z)return;if(this._velocity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:Z})}setVelocityVariance(Z){if(this._velocityVariance&&this._velocityVariance.x===Z.x&&this._velocityVariance.y===Z.y&&this._velocityVariance.z===Z.z)return;if(this._velocityVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:Z})}burst(Z){if(this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.BURST",{particleEmitter:this,count:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return c.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=Z.particleEmitterManager.registerParticleEmitter(this),this._world=Z,this.emitWithWorld(Z,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){return k0.serializeParticleEmitter(this)}}var tU=r(_V(),1);var HG6={x:0,y:-32,z:0},Lu=60,wu;(($)=>{$.STEP_START="SIMULATION.STEP_START";$.STEP_END="SIMULATION.STEP_END";$.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";$.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(wu||={});class eU extends O0{_colliderMap=new NH;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(Z,J=Lu,X=HG6){super();this._rapierEventQueue=new tU.default.EventQueue(!0),this._rapierSimulation=new tU.default.World(X),this._rapierSimulation.timestep=Math.fround(1/J),this._world=Z}get colliderMap(){return this._colliderMap}get isDebugRaycastingEnabled(){return this._debugRaycastingEnabled}get isDebugRenderingEnabled(){return this._debugRenderingEnabled}get gravity(){return this._rapierSimulation.gravity}get timestepS(){return this._rapierSimulation.timestep}get world(){return this._world}createRawCollider(Z,J){return this._rapierSimulation.createCollider(Z,J)}createRawRigidBody(Z){return this._rapierSimulation.createRigidBody(Z)}enableDebugRaycasting(Z){this._debugRaycastingEnabled=Z}enableDebugRendering(Z,J=tU.default.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=Z,this._debugRenderingFilterFlags=J}getContactManifolds(Z,J){let X=[];return this._rapierSimulation.narrowPhase.contactPair(Z,J,(Y,$)=>{if(Y.numContacts()===0)return;let Q=Y.normal(),K=[];for(let W=0;W<Y.numSolverContacts();W++)K.push(Y.solverContactPoint(W));X.push({contactPoints:K,localNormalA:!$?Y.localNormal1():Y.localNormal2(),localNormalB:!$?Y.localNormal2():Y.localNormal1(),normal:!$?Q:{x:-Q.x,y:-Q.y,z:-Q.z}})}),X}intersectionsWithRawShape(Z,J,X,Y={}){let $=new Set,Q=[];return this._rapierSimulation.intersectionsWithShape(J,X,Z,(K)=>{let W=this._colliderMap.getColliderHandleBlockType(K.handle);if(W&&!$.has(W))return $.add(W),Q.push({intersectedBlockType:W}),!0;let G=this._colliderMap.getColliderHandleEntity(K.handle);if(G&&!$.has(G))return $.add(G),Q.push({intersectedEntity:G}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),Q}raycast(Z,J,X,Y={}){let $=new tU.default.Ray(Z,J),Q=this._rapierSimulation.castRay($,X,Y.solidMode??!0,Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate);if(this._debugRaycastingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RAYCAST",{simulation:this,origin:Z,direction:J,length:X,hit:!!Q});if(!Q)return null;let K=$.pointAt(Q.timeOfImpact),W=Q.timeOfImpact,G=Q.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:IK.fromGlobalCoordinate({x:Math.floor(K.x-($.dir.x<0?0.0001:-0.0001)),y:Math.floor(K.y-($.dir.y<0?0.0001:-0.0001)),z:Math.floor(K.z-($.dir.z<0?0.0001:-0.0001))},V),hitPoint:K,hitDistance:W};let z=this._colliderMap.getColliderHandleEntity(G.handle);if(z)return{hitEntity:z,hitPoint:K,hitDistance:W};return null}removeRawCollider(Z){this._colliderMap.queueColliderHandleForCleanup(Z.handle),this._rapierSimulation.removeCollider(Z,!1)}removeRawRigidBody(Z){this._rapierSimulation.removeRigidBody(Z)}setGravity(Z){this._rapierSimulation.gravity=Z}step=(Z)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:Z});let J=performance.now();if(R8.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),R8.startSpan({operation:"physics_cleanup"},()=>{this._rapierEventQueue.drainContactForceEvents(this._onContactForceEvent),this._rapierEventQueue.drainCollisionEvents(this._onCollisionEvent),this._colliderMap.cleanup()}),this.emitWithWorld(this._world,"SIMULATION.STEP_END",{simulation:this,stepDurationMs:performance.now()-J}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(Z,J,X)=>{let[Y,$]=this._getCollisionObjects(Z,J);if(!Y||!$)return;let Q=(K,W)=>{if(K instanceof q9&&W instanceof a8&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof a8&&W instanceof q9&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof a8&&W instanceof a8&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(typeof K==="function"&&(W instanceof a8||W instanceof q9))K(W,X,Z,J)};Q(Y,$),Q($,Y)};_onContactForceEvent=(Z)=>{let[J,X]=this._getCollisionObjects(Z.collider1(),Z.collider2());if(!J||typeof J==="function"||!X||typeof X==="function")return;let Y={totalForce:Z.totalForce(),totalForceMagnitude:Z.totalForceMagnitude(),maxForceDirection:Z.maxForceDirection(),maxForceMagnitude:Z.maxForceMagnitude()},$=(Q,K)=>{if(Q instanceof q9&&K instanceof a8&&Q.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))Q.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:Q,entity:K,contactForceData:Y});else if(Q instanceof a8&&K instanceof q9&&Q.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))Q.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:Q,blockType:K,contactForceData:Y});else if(Q instanceof a8&&K instanceof a8&&Q.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Q.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:Q,otherEntity:K,contactForceData:Y})};$(J,X),$(X,J)};_getCollisionObjects(Z,J){let X=this._colliderMap.getColliderHandleBlockType(Z)??this._colliderMap.getColliderHandleCollisionCallback(Z)??this._colliderMap.getColliderHandleEntity(Z),Y=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J);return[X,Y]}}class iD{_synchronizedPlayerReliablePackets=new U6;_queuedBroadcasts=[];_queuedAudioSynchronizations=new U6;_queuedBlockSynchronizations=new U6;_queuedBlockTypeSynchronizations=new U6;_queuedChunkSynchronizations=new U6;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new U6;_queuedLightSynchronizations=new U6;_queuedParticleEmitterSynchronizations=new U6;_queuedPerPlayerSynchronizations=new U6;_queuedPerPlayerCameraSynchronizations=new U6;_queuedPerPlayerUISynchronizations=new U6;_queuedPerPlayerUIDatasSynchronizations=new U6;_queuedPlayerSynchronizations=new U6;_queuedSceneUISynchronizations=new U6;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(Z){this._world=Z,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let Z=[],J=[],X=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(...$);if(this._queuedEntitySynchronizations.size>0){let Y=[],$=[];for(let Q of this._queuedEntitySynchronizations.valuesArray){let K=!1;for(let W in Q)if(W!=="i"&&W!=="p"&&W!=="r"){K=!0;break}if(K)Y.push(Q);else $.push(Q)}if($.length>0){let Q=Q0.createPacket(Q0.outboundPackets.entitiesPacketDefinition,$,X);J.push(Q)}if(Y.length>0){let Q=Q0.createPacket(Q0.outboundPackets.entitiesPacketDefinition,Y,X);Z.push(Q);for(let K of this._synchronizedPlayerReliablePackets.valuesArray)K.push(Q)}}if(this._queuedAudioSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBlockTypeSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedChunkSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBlockSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedLightSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedParticleEmitterSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerUISynchronizations){let Q=Q0.createPacket(Q0.outboundPackets.uiPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerUIDatasSynchronizations){let Q=Q0.createPacket(Q0.outboundPackets.uiDatasPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedSceneUISynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedWorldSynchronization){let Y=Q0.createPacket(Q0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerCameraSynchronizations){let Q=Q0.createPacket(Q0.outboundPackets.cameraPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedPlayerSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBroadcasts.length>0)for(let Y of this._queuedBroadcasts){Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedDebugRaycastSynchronizations.length>0){let Y=Q0.createPacket(Q0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}R8.startSpan({operation:"send_all_packets"},()=>{for(let Y of N9.instance.getConnectedPlayersByWorld(this._world)){let $=this._synchronizedPlayerReliablePackets.get(Y)??Z;if($.length>0)Y.connection.send($);if(J.length>0)Y.connection.send(J,!1)}}),R8.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts.length=0;if(this._queuedAudioSynchronizations.size>0)this._queuedAudioSynchronizations.clear();if(this._queuedBlockSynchronizations.size>0)this._queuedBlockSynchronizations.clear();if(this._queuedBlockTypeSynchronizations.size>0)this._queuedBlockTypeSynchronizations.clear();if(this._queuedChunkSynchronizations.size>0)this._queuedChunkSynchronizations.clear();if(this._queuedDebugRaycastSynchronizations.length>0)this._queuedDebugRaycastSynchronizations.length=0;if(this._queuedEntitySynchronizations.size>0)this._queuedEntitySynchronizations.clear();if(this._queuedLightSynchronizations.size>0)this._queuedLightSynchronizations.clear();if(this._queuedParticleEmitterSynchronizations.size>0)this._queuedParticleEmitterSynchronizations.clear();if(this._queuedPerPlayerSynchronizations.size>0)this._queuedPerPlayerSynchronizations.clear();if(this._queuedPerPlayerCameraSynchronizations.size>0)this._queuedPerPlayerCameraSynchronizations.clear();if(this._queuedPerPlayerUISynchronizations.size>0)this._queuedPerPlayerUISynchronizations.clear();if(this._queuedPerPlayerUIDatasSynchronizations.size>0)this._queuedPerPlayerUIDatasSynchronizations.clear();if(this._queuedPlayerSynchronizations.size>0)this._queuedPlayerSynchronizations.clear();if(this._queuedSceneUISynchronizations.size>0)this._queuedSceneUISynchronizations.clear();if(this._queuedWorldSynchronization)this._queuedWorldSynchronization=void 0;if(this._loadedSceneUIs.size>0)this._loadedSceneUIs.clear();if(this._spawnedChunks.size>0)this._spawnedChunks.clear();if(this._spawnedEntities.size>0)this._spawnedEntities.clear();if(this._synchronizedPlayerReliablePackets.size>0)this._synchronizedPlayerReliablePackets.clear();Q7.clearCachedPacketsSerializedBuffers()})}_subscribeToAudioEvents(){this._world.final("AUDIO.PAUSE",this._onAudioPause),this._world.final("AUDIO.PLAY",this._onAudioPlay),this._world.final("AUDIO.PLAY_RESTART",this._onAudioPlayRestart),this._world.final("AUDIO.SET_ATTACHED_TO_ENTITY",this._onAudioSetAttachedToEntity),this._world.final("AUDIO.SET_CUTOFF_DISTANCE",this._onAudioSetCutoffDistance),this._world.final("AUDIO.SET_DETUNE",this._onAudioSetDetune),this._world.final("AUDIO.SET_DISTORTION",this._onAudioSetDistortion),this._world.final("AUDIO.SET_POSITION",this._onAudioSetPosition),this._world.final("AUDIO.SET_PLAYBACK_RATE",this._onAudioSetPlaybackRate),this._world.final("AUDIO.SET_REFERENCE_DISTANCE",this._onAudioSetReferenceDistance),this._world.final("AUDIO.SET_VOLUME",this._onAudioSetVolume)}_subscribeToBlockTypeRegistryEvents(){this._world.final("BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",this._onBlockTypeRegistryRegisterBlockType)}_subscribeToChatEvents(){this._world.final("CHAT.BROADCAST_MESSAGE",this._onChatSendBroadcastMessage),this._world.final("CHAT.PLAYER_MESSAGE",this._onChatSendPlayerMessage)}_subscribeToChunkLatticeEvents(){this._world.final("CHUNK_LATTICE.ADD_CHUNK",this._onChunkLatticeAddChunk),this._world.final("CHUNK_LATTICE.REMOVE_CHUNK",this._onChunkLatticeRemoveChunk),this._world.final("CHUNK_LATTICE.SET_BLOCK",this._onChunkLatticeSetBlock)}_subscribeToEntityEvents(){this._world.final("ENTITY.SPAWN",this._onEntitySpawn),this._world.final("ENTITY.DESPAWN",this._onEntityDespawn),this._world.final("ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",this._onEntitySetModelAnimationsPlaybackRate),this._world.final("ENTITY.SET_MODEL_HIDDEN_NODES",this._onEntitySetModelHiddenNodes),this._world.final("ENTITY.SET_MODEL_SCALE",this._onEntitySetModelScale),this._world.final("ENTITY.SET_MODEL_SHOWN_NODES",this._onEntitySetModelShownNodes),this._world.final("ENTITY.SET_MODEL_TEXTURE_URI",this._onEntitySetModelTextureUri),this._world.final("ENTITY.SET_OPACITY",this._onEntitySetOpacity),this._world.final("ENTITY.SET_PARENT",this._onEntitySetParent),this._world.final("ENTITY.SET_TINT_COLOR",this._onEntitySetTintColor),this._world.final("ENTITY.START_MODEL_LOOPED_ANIMATIONS",this._onEntityStartModelLoopedAnimations),this._world.final("ENTITY.START_MODEL_ONESHOT_ANIMATIONS",this._onEntityStartModelOneshotAnimations),this._world.final("ENTITY.STOP_MODEL_ANIMATIONS",this._onEntityStopModelAnimations),this._world.final("ENTITY.UPDATE_POSITION",this._onEntityUpdatePosition),this._world.final("ENTITY.UPDATE_ROTATION",this._onEntityUpdateRotation)}_subscribeToLightEvents(){this._world.final("LIGHT.DESPAWN",this._onLightDespawn),this._world.final("LIGHT.SET_ANGLE",this._onLightSetAngle),this._world.final("LIGHT.SET_ATTACHED_TO_ENTITY",this._onLightSetAttachedToEntity),this._world.final("LIGHT.SET_COLOR",this._onLightSetColor),this._world.final("LIGHT.SET_DISTANCE",this._onLightSetDistance),this._world.final("LIGHT.SET_INTENSITY",this._onLightSetIntensity),this._world.final("LIGHT.SET_OFFSET",this._onLightSetOffset),this._world.final("LIGHT.SET_PENUMBRA",this._onLightSetPenumbra),this._world.final("LIGHT.SET_POSITION",this._onLightSetPosition),this._world.final("LIGHT.SET_TRACKED_ENTITY",this._onLightSetTrackedEntity),this._world.final("LIGHT.SET_TRACKED_POSITION",this._onLightSetTrackedPosition),this._world.final("LIGHT.SPAWN",this._onLightSpawn)}_subscribeToParticleEmitterEvents(){this._world.final("PARTICLE_EMITTER.DESPAWN",this._onParticleEmitterDespawn),this._world.final("PARTICLE_EMITTER.BURST",this._onParticleEmitterBurst),this._world.final("PARTICLE_EMITTER.SET_ALPHA_TEST",this._onParticleEmitterSetAlphaTest),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",this._onParticleEmitterSetAttachedToEntity),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",this._onParticleEmitterSetAttachedToEntityNodeName),this._world.final("PARTICLE_EMITTER.SET_COLOR_END",this._onParticleEmitterSetColorEnd),this._world.final("PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",this._onParticleEmitterSetColorEndVariance),this._world.final("PARTICLE_EMITTER.SET_COLOR_START",this._onParticleEmitterSetColorStart),this._world.final("PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",this._onParticleEmitterSetColorStartVariance),this._world.final("PARTICLE_EMITTER.SET_GRAVITY",this._onParticleEmitterSetGravity),this._world.final("PARTICLE_EMITTER.SET_LIFETIME",this._onParticleEmitterSetLifetime),this._world.final("PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",this._onParticleEmitterSetLifetimeVariance),this._world.final("PARTICLE_EMITTER.SET_MAX_PARTICLES",this._onParticleEmitterSetMaxParticles),this._world.final("PARTICLE_EMITTER.SET_OFFSET",this._onParticleEmitterSetOffset),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END",this._onParticleEmitterSetOpacityEnd),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",this._onParticleEmitterSetOpacityEndVariance),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START",this._onParticleEmitterSetOpacityStart),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",this._onParticleEmitterSetOpacityStartVariance),this._world.final("PARTICLE_EMITTER.SET_PAUSED",this._onParticleEmitterSetPaused),this._world.final("PARTICLE_EMITTER.SET_POSITION",this._onParticleEmitterSetPosition),this._world.final("PARTICLE_EMITTER.SET_POSITION_VARIANCE",this._onParticleEmitterSetPositionVariance),this._world.final("PARTICLE_EMITTER.SET_RATE",this._onParticleEmitterSetRate),this._world.final("PARTICLE_EMITTER.SET_RATE_VARIANCE",this._onParticleEmitterSetRateVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_END",this._onParticleEmitterSetSizeEnd),this._world.final("PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",this._onParticleEmitterSetSizeEndVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_START",this._onParticleEmitterSetSizeStart),this._world.final("PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",this._onParticleEmitterSetSizeStartVariance),this._world.final("PARTICLE_EMITTER.SET_TEXTURE_URI",this._onParticleEmitterSetTextureUri),this._world.final("PARTICLE_EMITTER.SET_TRANSPARENT",this._onParticleEmitterSetTransparent),this._world.final("PARTICLE_EMITTER.SET_VELOCITY",this._onParticleEmitterSetVelocity),this._world.final("PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",this._onParticleEmitterSetVelocityVariance),this._world.final("PARTICLE_EMITTER.SPAWN",this._onParticleEmitterSpawn)}_subscribeToPlayerEvents(){this._world.final("PLAYER.JOINED_WORLD",this._onPlayerJoinedWorld),this._world.final("PLAYER.LEFT_WORLD",this._onPlayerLeftWorld),this._world.final("PLAYER.RECONNECTED_WORLD",this._onPlayerReconnectedWorld),this._world.final("PLAYER.REQUEST_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity)}_onAudioPause=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pa=!0,delete J.pl,delete J.r};_onAudioPlay=(Z)=>{let J=Z.audio.serialize();J.pl=!0,delete J.pa,delete J.r,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioPlayRestart=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.r=!0,delete J.pa,delete J.pl,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onAudioSetCutoffDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.cd=Z.cutoffDistance};_onAudioSetDetune=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.de=Z.detune};_onAudioSetDistortion=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.di=Z.distortion};_onAudioSetPosition=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.position?void 0:J.e,J.p=Z.position?k0.serializeVector(Z.position):void 0};_onAudioSetPlaybackRate=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pr=Z.playbackRate};_onAudioSetReferenceDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.rd=Z.referenceDistance};_onAudioSetVolume=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.v=Z.volume};_onBlockTypeRegistryRegisterBlockType=(Z)=>{let J=Z.blockType.serialize();this._queuedBlockTypeSynchronizations.set(Z.blockType.id,J)};_onChatSendBroadcastMessage=(Z)=>{let{player:J,message:X,color:Y}=Z;this._queuedBroadcasts.push(Q0.createPacket(Q0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y,p:J?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(Z)=>{let{player:J,message:X,color:Y}=Z,$=this._queuedPerPlayerSynchronizations.get(J)??[];$.push(Q0.createPacket(Q0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set(J,$)};_onChunkLatticeAddChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk);J.b=Array.from(Z.chunk.blocks),J.rm=void 0,this._spawnedChunks.add(J.c.join(","))};_onChunkLatticeRemoveChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk),X=J.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else J.rm=!0};_onChunkLatticeSetBlock=(Z)=>{let J=this._createOrGetQueuedBlockSync(Z.globalCoordinate);J.i=Z.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.ap=Z.playbackRate};_onEntitySpawn=(Z)=>{let J=Z.entity.serialize();this._queuedEntitySynchronizations.set(J.i,J),this._spawnedEntities.add(J.i)};_onEntityDespawn=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(this._spawnedEntities.has(J.i))this._queuedEntitySynchronizations.delete(J.i),this._spawnedEntities.delete(J.i);else J.rm=!0};_onEntitySetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.h=Array.from(Z.modelHiddenNodes)};_onEntitySetModelScale=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.s=Z.modelScale};_onEntitySetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.sn=Array.from(Z.modelShownNodes)};_onEntitySetModelTextureUri=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.mt=Z.modelTextureUri};_onEntitySetOpacity=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.o=Z.opacity};_onEntitySetParent=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.pe=Z.parent?Z.parent.id:void 0,J.pn=Z.parentNodeName};_onEntitySetTintColor=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.t=Z.tintColor?k0.serializeRgbColor(Z.tintColor):void 0};_onEntityStartModelLoopedAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al=Array.from(new Set([...J.al??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.ao=Array.from(new Set([...J.ao??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStopModelAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al)J.al=J.al.filter((X)=>!Z.animations.has(X)).filter(Boolean);if(J.ao)J.ao=J.ao.filter((X)=>!Z.animations.has(X)).filter(Boolean);J.as=Array.from(new Set([...J.as??[],...Z.animations]))};_onEntityUpdateRotation=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.r=[Z.rotation.x,Z.rotation.y,Z.rotation.z,Z.rotation.w]};_onEntityUpdatePosition=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.p=[Z.position.x,Z.position.y,Z.position.z]};_onLightDespawn=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.rm=!0};_onLightSetAngle=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.a=Z.angle};_onLightSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onLightSetColor=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.c=k0.serializeRgbColor(Z.color)};_onLightSetDistance=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.d=Z.distance};_onLightSetIntensity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.n=Z.intensity};_onLightSetOffset=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.o=Z.offset?k0.serializeVector(Z.offset):void 0};_onLightSetPenumbra=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.pe=Z.penumbra};_onLightSetPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.p=Z.position?k0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e};_onLightSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.te=Z.entity?Z.entity.id:void 0,J.tp=Z.entity?void 0:J.tp};_onLightSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.tp=Z.position?k0.serializeVector(Z.position):void 0,J.te=Z.position?void 0:J.te};_onLightSpawn=(Z)=>{let J=Z.light.serialize();this._queuedLightSynchronizations.set(J.i,J)};_onParticleEmitterBurst=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.b=Z.count};_onParticleEmitterDespawn=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rm=!0};_onParticleEmitterSetAlphaTest=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.at=Z.alphaTest};_onParticleEmitterSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onParticleEmitterSetAttachedToEntityNodeName=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.en=Z.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ce=Z.colorEnd?k0.serializeRgbColor(Z.colorEnd):void 0};_onParticleEmitterSetColorEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cev=Z.colorEndVariance?k0.serializeRgbColor(Z.colorEndVariance):void 0};_onParticleEmitterSetColorStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cs=Z.colorStart?k0.serializeRgbColor(Z.colorStart):void 0};_onParticleEmitterSetColorStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.csv=Z.colorStartVariance?k0.serializeRgbColor(Z.colorStartVariance):void 0};_onParticleEmitterSetGravity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.g=Z.gravity?k0.serializeVector(Z.gravity):void 0};_onParticleEmitterSetLifetime=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.l=Z.lifetime};_onParticleEmitterSetLifetimeVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.lv=Z.lifetimeVariance};_onParticleEmitterSetMaxParticles=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.mp=Z.maxParticles};_onParticleEmitterSetOffset=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.o=Z.offset?k0.serializeVector(Z.offset):void 0};_onParticleEmitterSetOpacityEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oe=Z.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oev=Z.opacityEndVariance};_onParticleEmitterSetOpacityStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.os=Z.opacityStart};_onParticleEmitterSetOpacityStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.osv=Z.opacityStartVariance};_onParticleEmitterSetPaused=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pa=Z.paused};_onParticleEmitterSetPosition=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.p=Z.position?k0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e,J.en=Z.position?void 0:J.en};_onParticleEmitterSetPositionVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pv=Z.positionVariance?k0.serializeVector(Z.positionVariance):void 0};_onParticleEmitterSetRate=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.r=Z.rate};_onParticleEmitterSetRateVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rv=Z.rateVariance};_onParticleEmitterSetSizeEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.se=Z.sizeEnd};_onParticleEmitterSetSizeEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.sev=Z.sizeEndVariance};_onParticleEmitterSetSizeStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ss=Z.sizeStart};_onParticleEmitterSetSizeStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ssv=Z.sizeStartVariance};_onParticleEmitterSetTextureUri=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.tu=Z.textureUri};_onParticleEmitterSetTransparent=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.t=Z.transparent};_onParticleEmitterSetVelocity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.v=Z.velocity?k0.serializeVector(Z.velocity):void 0};_onParticleEmitterSetVelocityVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.vv=Z.velocityVariance?k0.serializeVector(Z.velocityVariance):void 0};_onParticleEmitterSpawn=(Z)=>{let J=Z.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set(J.i,J)};_onPlayerCameraLookAtEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=k0.serializeVector(Z.entity.position),delete J.et,delete J.pt};_onPlayerCameraLookAtPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=Z.position?k0.serializeVector(Z.position):void 0,delete J.et,delete J.pt};_onPlayerCameraSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.e=Z.entity.id,delete J.p};_onPlayerCameraSetAttachedToPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.p=Z.position?k0.serializeVector(Z.position):void 0,delete J.e};_onPlayerCameraSetFilmOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fo=Z.filmOffset};_onPlayerCameraSetForwardOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.ffo=Z.forwardOffset};_onPlayerCameraSetFov=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fv=Z.fov};_onPlayerCameraSetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.h=Array.from(Z.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.s=Array.from(Z.modelShownNodes)};_onPlayerCameraSetMode=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.m=Z.mode};_onPlayerCameraSetOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.o=Z.offset?k0.serializeVector(Z.offset):void 0};_onPlayerCameraSetShoulderAngle=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.sa=Z.shoulderAngle};_onPlayerCameraSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.et=Z.entity?Z.entity.id:void 0,delete J.pl,delete J.pt};_onPlayerCameraSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pt=Z.position?k0.serializeVector(Z.position):void 0,delete J.et,delete J.pl};_onPlayerCameraSetZoom=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.z=Z.zoom};_onPlayerJoinedWorld=(Z)=>{let{player:J}=Z,X=this._queuedPerPlayerSynchronizations.get(J)??[];X.push(Q0.createPacket(Q0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map(($)=>{if(J.camera.attachedToEntity===void 0&&$ instanceof i7&&$.player===J)J.camera.setAttachedToEntity($);return $.serialize()}),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.particleEmittersPacketDefinition,this._world.particleEmitterManager.getAllParticleEmitters().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.playersPacketDefinition,N9.instance.getConnectedPlayers().map(($)=>$.serialize()),this._world.loop.currentTick));let Y=this._createOrGetQueuedPlayerCameraSync(J.camera);this._queuedPerPlayerCameraSynchronizations.set(J,{...J.camera.serialize(),...Y}),this._queuedPerPlayerSynchronizations.set(J,X),this._queuedPlayerSynchronizations.set(J.id,J.serialize())};_onPlayerLeftWorld=(Z)=>{let J=this._createOrGetQueuedPlayerSync(Z.player);J.rm=!0};_onPlayerReconnectedWorld=(Z)=>{this._onPlayerJoinedWorld(Z)};_onPlayerRequestSync=(Z)=>{Z.player.connection.send([Q0.createPacket(Q0.outboundPackets.syncResponsePacketDefinition,{r:Z.receivedAt,s:Date.now(),p:performance.now()-Z.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_onPlayerUILoad=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.u=Z.htmlUri};_onPlayerUILockPointer=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.p=Z.lock};_onPlayerUISendData=(Z)=>{this._createOrGetQueuedPlayerUIDatasSync(Z.playerUI).push(Z.data)};_onSceneUILoad=(Z)=>{let J=Z.sceneUI.serialize();this._queuedSceneUISynchronizations.set(J.i,J),this._loadedSceneUIs.add(J.i)};_onSceneUISetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onSceneUISetOffset=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.o=Z.offset?k0.serializeVector(Z.offset):void 0};_onSceneUISetPosition=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.p=Z.position?k0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e};_onSceneUISetState=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.s=Z.state};_onSceneUISetViewDistance=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.v=Z.viewDistance};_onSceneUIUnload=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);if(this._loadedSceneUIs.has(J.i))this._queuedSceneUISynchronizations.delete(J.i),this._loadedSceneUIs.delete(J.i);else J.rm=!0};_onSimulationDebugRaycast=(Z)=>{this._queuedDebugRaycastSynchronizations.push(k0.serializePhysicsDebugRaycast(Z))};_onSimulationDebugRender=(Z)=>{this._queuedBroadcasts.push(Q0.createPacket(Q0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(Z.vertices),c:Array.from(Z.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ac=k0.serializeRgbColor(Z.color)};_onWorldSetAmbientLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ai=Z.intensity};_onWorldSetDirectionalLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dc=k0.serializeRgbColor(Z.color)};_onWorldSetDirectionalLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.di=Z.intensity};_onWorldSetDirectionalLightPosition=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dp=k0.serializeVector(Z.position)};_onWorldSetFogColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fc=k0.serializeRgbColor(Z.color)};_onWorldSetFogFar=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ff=Z.far};_onWorldSetFogNear=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fn=Z.near};_onWorldSetSkyboxIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.si=Z.intensity};_createOrGetQueuedAudioSync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let J=this._queuedAudioSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedAudioSynchronizations.set(Z.id,J);return J}_createOrGetQueuedBlockSync(Z){let{x:J,y:X,z:Y}=Z,$=`${J},${X},${Y}`,Q=this._queuedBlockSynchronizations.get($);if(!Q)Q={i:0,c:[J,X,Y]},this._queuedBlockSynchronizations.set($,Q);return Q}_createOrGetQueuedChunkSync(Z){if(!Z.originCoordinate)c.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:J,y:X,z:Y}=Z.originCoordinate,$=`${J},${X},${Y}`,Q=this._queuedChunkSynchronizations.get($);if(!Q)Q={c:[J,X,Y]},this._queuedChunkSynchronizations.set($,Q);return Q}_createOrGetQueuedEntitySync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let J=this._queuedEntitySynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedEntitySynchronizations.set(Z.id,J);return J}_createOrGetQueuedLightSync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let J=this._queuedLightSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedLightSynchronizations.set(Z.id,J);return J}_createOrGetQueuedParticleEmitterSync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let J=this._queuedParticleEmitterSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedParticleEmitterSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerSync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let J=this._queuedPlayerSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedPlayerSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerCameraSync(Z){let J=this._queuedPerPlayerCameraSynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerCameraSynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUISync(Z){let J=this._queuedPerPlayerUISynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerUISynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUIDatasSync(Z){let J=this._queuedPerPlayerUIDatasSynchronizations.get(Z.player);if(!J)J=[],this._queuedPerPlayerUIDatasSynchronizations.set(Z.player,J);return J}_createOrGetQueuedSceneUISync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let J=this._queuedSceneUISynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedSceneUISynchronizations.set(Z.id,J);return J}_createOrGetQueuedWorldSync(Z){if(Z.id!==this._world.id)c.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:Z.id}}_createOrGetSynchronizedPlayerReliablePackets(Z,J){let X=this._synchronizedPlayerReliablePackets.get(Z);if(!X)X=[...J],this._synchronizedPlayerReliablePackets.set(Z,X);return X}}class Z2{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedParticleEmitters(Z){this.getAllEntityAttachedParticleEmitters(Z).forEach((J)=>{J.despawn()})}getAllParticleEmitters(){return Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(Z){return this.getAllParticleEmitters().filter((J)=>J.attachedToEntity===Z)}registerParticleEmitter(Z){if(Z.id!==void 0)return Z.id;let J=this._nextParticleEmitterId;return this._particleEmitters.set(J,Z),this._nextParticleEmitterId++,J}unregisterParticleEmitter(Z){if(Z.id===void 0)return;this._particleEmitters.delete(Z.id)}}class J2{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}getAllSceneUIs(){return Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(Z){return this.getAllSceneUIs().filter((J)=>J.attachedToEntity===Z)}getSceneUIById(Z){return this._sceneUIs.get(Z)}registerSceneUI(Z){if(Z.id!==void 0)return Z.id;let J=this._nextSceneUIId;return this._sceneUIs.set(J,Z),this._nextSceneUIId++,J}unloadEntityAttachedSceneUIs(Z){this.getAllEntityAttachedSceneUIs(Z).forEach((J)=>{J.unload()})}unregisterSceneUI(Z){if(Z.id===void 0)return;this._sceneUIs.delete(Z.id)}}var FG6=2,qG6=3;class X2{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(Z,J,X){this._targetTicksPerSecond=Z,this._fixedTimestepS=Math.fround(1/Z),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*qG6,this._tickFunction=J,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get isStarted(){return!!this._tickHandle}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return;this._lastLoopTimeMs=performance.now();let Z=()=>{let J=performance.now(),X=J-this._lastLoopTimeMs;if(this._lastLoopTimeMs=J,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)R8.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<FG6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++});this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs),this._tickHandle=setTimeout(Z,this._nextTickMs)};Z()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(Z){try{this._tickFunction(Z)}catch(J){if(J instanceof Error&&this._tickErrorCallback)this._tickErrorCallback(J);else c.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${J}`)}}}var $H1;((Q)=>{Q.START="WORLD_LOOP.START";Q.STOP="WORLD_LOOP.STOP";Q.TICK_START="WORLD_LOOP.TICK_START";Q.TICK_END="WORLD_LOOP.TICK_END";Q.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})($H1||={});class Y2 extends O0{_currentTick=0;_ticker;_world;constructor(Z,J=Lu){super();this._ticker=new X2(J,this._tick,this._onTickError),this._world=Z}get currentTick(){return this._currentTick}get isStarted(){return this._ticker.isStarted}get nextTickMs(){return this._ticker.nextTickMs}get timestepS(){return this._ticker.fixedTimestepS}get world(){return this._world}start(){this._ticker.start(),this.emitWithWorld(this._world,"WORLD_LOOP.START",{worldLoop:this})}stop(){this._ticker.stop(),this.emitWithWorld(this._world,"WORLD_LOOP.STOP",{worldLoop:this})}_tick=(Z)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:Z});let J=performance.now();R8.startSpan({operation:"world_tick",attributes:{serverPlayerCount:N9.instance.playerCount,targetTickRate:this._ticker.targetTicksPerSecond,targetTickRateMs:this._ticker.fixedTimestepMs,worldId:this._world.id,worldName:this._world.name,worldChunkCount:this._world.chunkLattice.chunkCount,worldEntityCount:this._world.entityManager.entityCount,worldLoopTick:this._currentTick}},()=>{R8.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(Z)),R8.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(Z)),R8.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),R8.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-J})};_onTickError=(Z)=>{c.error(`WorldLoop._onTickError(): Error: ${Z}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:Z})}}var Ou;((F)=>{F.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";F.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";F.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";F.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";F.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";F.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";F.SET_FOG_FAR="WORLD.SET_FOG_FAR";F.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";F.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";F.START="WORLD.START";F.STOP="WORLD.STOP"})(Ou||={});class $2 extends O0{_id;_ambientLightColor;_ambientLightIntensity;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_fogColor;_fogFar;_fogNear;_name;_skyboxIntensity;_skyboxUri;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_entityManager;_lightManager;_loop;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_tag;constructor(Z){super();if(this._id=Z.id,this._ambientLightColor=Z.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=Z.ambientLightIntensity??1,this._directionalLightColor=Z.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=Z.directionalLightIntensity??3,this._directionalLightPosition=Z.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=Z.fogColor,this._fogFar=Z.fogFar??550,this._fogNear=Z.fogNear??500,this._name=Z.name,this._skyboxIntensity=Z.skyboxIntensity??1,this._skyboxUri=Z.skyboxUri,this._tag=Z.tag,this._audioManager=new aG(this),this._blockTypeRegistry=new dz(this),this._chatManager=new OH(this),this._chunkLattice=new MH(this),this._entityManager=new DH(this),this._lightManager=new rU(this),this._loop=new Y2(this,Z.tickRate),this._networkSynchronizer=new iD(this),this._particleEmitterManager=new Z2(this),this._sceneUIManager=new J2(this),this._simulation=new eU(this,Z.tickRate,Z.gravity),Z.map)this.loadMap(Z.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get name(){return this._name}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get entityManager(){return this._entityManager}get lightManager(){return this._lightManager}get loop(){return this._loop}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}loadMap(Z){if(this.chunkLattice.clear(),Z.blockTypes)for(let J of Z.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:J.id,isLiquid:J.isLiquid,name:J.name,textureUri:J.textureUri});if(Z.blocks)for(let[J,X]of Object.entries(Z.blocks)){let[Y,$,Q]=J.split(",").map(Number);this.chunkLattice.setBlock({x:Y,y:$,z:Q},X)}if(Z.entities)for(let[J,X]of Object.entries(Z.entities)){let[Y,$,Q]=J.split(",").map(Number);new a8({isEnvironmental:!0,...X}).spawn(this,{x:Y,y:$,z:Q})}}setAmbientLightColor(Z){this._ambientLightColor=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:Z})}setAmbientLightIntensity(Z){this._ambientLightIntensity=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightColor(Z){this._directionalLightColor=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:Z})}setDirectionalLightIntensity(Z){this._directionalLightIntensity=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightPosition(Z){this._directionalLightPosition=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:Z})}setFogColor(Z){this._fogColor=Z,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:Z})}setFogFar(Z){this._fogFar=Z,this.emit("WORLD.SET_FOG_FAR",{world:this,far:Z})}setFogNear(Z){this._fogNear=Z,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:Z})}setSkyboxIntensity(Z){this._skyboxIntensity=Z,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:Z})}start(){if(this._loop.isStarted)return;this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){if(!this._loop.isStarted)return;this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return k0.serializeWorld(this)}}var QH1;((J)=>J.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(QH1||={});class K${static instance=new K$;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(Z){let J=new $2({...Z,id:this._nextWorldId++});return J.start(),this._worlds.set(J.id,J),O0.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:J}),J}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(Z){let J=[];return this._worlds.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getWorld(Z){return this._worlds.get(Z)}setDefaultWorld(Z){this._defaultWorld=Z}}var KH1;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(KH1||={});class N9{static instance=new N9;worldSelectionHandler;_connectionPlayers=new Map;constructor(){O0.globalInstance.on("CONNECTION.OPENED",({connection:Z,req:J})=>{this._onConnectionOpened(Z,J.session)}),O0.globalInstance.on("CONNECTION.DISCONNECTED",({connection:Z})=>{this._onConnectionDisconnected(Z)}),O0.globalInstance.on("CONNECTION.RECONNECTED",({connection:Z})=>{this._onConnectionReconnected(Z)}),O0.globalInstance.on("CONNECTION.CLOSED",({connection:Z})=>{this._onConnectionClosed(Z)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(Z){return this.getConnectedPlayers().filter((J)=>J.world===Z)}getConnectedPlayerByUsername(Z){return Array.from(this._connectionPlayers.values()).find((J)=>{return J.username.toLowerCase()===Z.toLowerCase()})}async _onConnectionOpened(Z,J){let X=new uW(Z,J);await X.loadInitialPersistedData(),this._connectionPlayers.set(Z,X),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let Y=await this.worldSelectionHandler?.(X);X.joinWorld(Y??K$.instance.getDefaultWorld())}_onConnectionDisconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.resetInputs(),J.camera.reset()}_onConnectionReconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.reconnected(),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:J});else c.warning(`PlayerManager._onConnectionReconnected(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(Z){let J=this._connectionPlayers.get(Z);if(J)J.disconnect(),this._connectionPlayers.delete(Z),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:J});else c.warning(`PlayerManager._onConnectionClosed(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}}Buffer.poolSize=134217728;var GH1;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(GH1||={});function UG6(Z){WH1.default.init().then(()=>{return RK.instance.modelRegistry.preloadModels()}).then(()=>{if(Z.length>0)Z(RK.instance.worldManager.getDefaultWorld());else Z();RK.instance.start()}).catch((J)=>{c.fatalError(`Failed to initialize the game engine, exiting. Error: ${J}`)})}class RK{static _instance;_modelRegistry=g5.instance;_playerManager=N9.instance;_socket=YZ.instance;_worldManager=K$.instance;_webServer=I3.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new RK;return this._instance}get modelRegistry(){return this._modelRegistry}get playerManager(){return this._playerManager}get socket(){return this._socket}get webServer(){return this._webServer}get worldManager(){return this._worldManager}start(){O0.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start()}}var B6=r(PK(),1);class CK extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get determinant(){return B6.mat2.determinant(this)}get frobeniusNorm(){return B6.mat2.frob(this)}static create(){let Z=new CK(0,0,0,0);return B6.mat2.identity(Z),Z}static fromRotation(Z){let J=CK.create();return B6.mat2.fromRotation(J,Z),J}static fromScaling(Z){let J=CK.create();return B6.mat2.fromScaling(J,Z),J}add(Z){return B6.mat2.add(this,this,Z),this}adjoint(){return B6.mat2.adjoint(this,this),this}clone(){return new CK(this[0],this[1],this[2],this[3])}copy(Z){return B6.mat2.copy(this,Z),this}equals(Z){return B6.mat2.equals(this,Z)}exactEquals(Z){return B6.mat2.exactEquals(this,Z)}identity(){return B6.mat2.identity(this),this}invert(){return B6.mat2.invert(this,this),this}multiply(Z){return B6.mat2.mul(this,this,Z),this}multiplyScalar(Z){return B6.mat2.multiplyScalar(this,this,Z),this}rotate(Z){return B6.mat2.rotate(this,this,Z),this}subtract(Z){return B6.mat2.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return B6.mat2.transpose(this,this),this}}var j8=r(PK(),1);class kZ extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G){super([Z,J,X,Y,$,Q,K,W,G])}get determinant(){return j8.mat3.determinant(this)}get frobeniusNorm(){return j8.mat3.frob(this)}static create(){let Z=new kZ(0,0,0,0,0,0,0,0,0);return j8.mat3.identity(Z),Z}static fromMatrix4(Z){let J=kZ.create();return j8.mat3.fromMat4(J,Z),J}static fromQuaternion(Z){let J=kZ.create();return j8.mat3.fromQuat(J,Z),J}static fromRotation(Z){let J=kZ.create();return j8.mat3.fromRotation(J,Z),J}static fromScaling(Z){let J=kZ.create();return j8.mat3.fromScaling(J,Z),J}static fromTranslation(Z){let J=kZ.create();return j8.mat3.fromTranslation(J,Z),J}add(Z){return j8.mat3.add(this,this,Z),this}adjoint(){return j8.mat3.adjoint(this,this),this}clone(){return new kZ(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(Z){return j8.mat3.copy(this,Z),this}equals(Z){return j8.mat3.equals(this,Z)}exactEquals(Z){return j8.mat3.exactEquals(this,Z)}identity(){return j8.mat3.identity(this),this}invert(){return j8.mat3.invert(this,this),this}multiply(Z){return j8.mat3.mul(this,this,Z),this}multiplyScalar(Z){return j8.mat3.multiplyScalar(this,this,Z),this}transformVector(Z){return Z.transformMatrix3(this)}projection(Z,J){return j8.mat3.projection(this,Z,J),this}rotate(Z){return j8.mat3.rotate(this,this,Z),this}subtract(Z){return j8.mat3.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return j8.mat3.transpose(this,this),this}}var $1=r(PK(),1);class v5 extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G,V,z,F,H,q,U,B){super([Z,J,X,Y,$,Q,K,W,G,V,z,F,H,q,U,B])}get determinant(){return $1.mat4.determinant(this)}get frobeniusNorm(){return $1.mat4.frob(this)}static create(){let Z=new v5(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return $1.mat4.identity(Z),Z}static fromQuaternion(Z){let J=v5.create();return $1.mat4.fromQuat(J,Z),J}static fromRotation(Z,J){let X=v5.create();return $1.mat4.fromRotation(X,Z,J),X}static fromRotationTranslation(Z,J){let X=v5.create();return $1.mat4.fromRotationTranslation(X,Z,J),X}static fromRotationTranslationScale(Z,J,X){let Y=v5.create();return $1.mat4.fromRotationTranslationScale(Y,Z,J,X),Y}static fromRotationTranslationScaleOrigin(Z,J,X,Y){let $=v5.create();return $1.mat4.fromRotationTranslationScaleOrigin($,Z,J,X,Y),$}static fromScaling(Z){let J=v5.create();return $1.mat4.fromScaling(J,Z),J}static fromTranslation(Z){let J=v5.create();return $1.mat4.fromTranslation(J,Z),J}static fromXRotation(Z){let J=v5.create();return $1.mat4.fromXRotation(J,Z),J}static fromYRotation(Z){let J=v5.create();return $1.mat4.fromYRotation(J,Z),J}static fromZRotation(Z){let J=v5.create();return $1.mat4.fromZRotation(J,Z),J}add(Z){return $1.mat4.add(this,this,Z),this}adjoint(){return $1.mat4.adjoint(this,this),this}clone(){return new v5(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8],this[9],this[10],this[11],this[12],this[13],this[14],this[15])}copy(Z){return $1.mat4.copy(this,Z),this}equals(Z){return $1.mat4.equals(this,Z)}exactEquals(Z){return $1.mat4.exactEquals(this,Z)}frustrum(Z,J,X,Y,$,Q){return $1.mat4.frustum(this,Z,J,X,Y,$,Q),this}identity(){return $1.mat4.identity(this),this}invert(){return $1.mat4.invert(this,this),this}lookAt(Z,J,X){return $1.mat4.lookAt(this,Z,J,X),this}multiply(Z){return $1.mat4.mul(this,this,Z),this}multiplyScalar(Z){return $1.mat4.multiplyScalar(this,this,Z),this}orthographic(Z,J,X,Y,$,Q){return $1.mat4.ortho(this,Z,J,X,Y,$,Q),this}perspective(Z,J,X,Y){return $1.mat4.perspective(this,Z,J,X,Y),this}rotate(Z,J){return $1.mat4.rotate(this,this,Z,J),this}rotateX(Z){return $1.mat4.rotateX(this,this,Z),this}rotateY(Z){return $1.mat4.rotateY(this,this,Z),this}rotateZ(Z){return $1.mat4.rotateZ(this,this,Z),this}scale(Z){return $1.mat4.scale(this,this,Z),this}subtract(Z){return $1.mat4.sub(this,this,Z),this}targetTo(Z,J,X){return $1.mat4.targetTo(this,Z,J,X),this}toString(){return`[${this[0]},${this[1]},${this[2]},${this[3]}][${this[4]},${this[5]},${this[6]},${this[7]}][${this[8]},${this[9]},${this[10]},${this[11]}][${this[12]},${this[13]},${this[14]},${this[15]}]`}translate(Z){return $1.mat4.translate(this,this,Z),this}transpose(){return $1.mat4.transpose(this,this),this}}var b1=r(PK(),1);class lG extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get length(){return b1.quat.length(this)}get squaredLength(){return b1.quat.squaredLength(this)}get magnitude(){return b1.quat.length(this)}get squaredMagnitude(){return b1.quat.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}get w(){return this[3]}set w(Z){this[3]=Z}static fromEuler(Z,J,X){let Y=b1.quat.fromEuler(new Float32Array(4),Z,J,X);return new lG(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(Z){return new lG(Z.x,Z.y,Z.z,Z.w)}clone(){return new lG(this.x,this.y,this.z,this.w)}conjugate(){return b1.quat.conjugate(this,this),this}copy(Z){return b1.quat.copy(this,Z),this}dot(Z){return b1.quat.dot(this,Z)}exponential(){return b1.quat.exp(this,this),this}equals(Z){return b1.quat.equals(this,Z)}exactEquals(Z){return b1.quat.exactEquals(this,Z)}getAngle(Z){return b1.quat.getAngle(this,Z)}identity(){return b1.quat.identity(this),this}invert(){return b1.quat.invert(this,this),this}lerp(Z,J){return b1.quat.lerp(this,this,Z,J),this}logarithm(){return b1.quat.ln(this,this),this}multiply(Z){return b1.quat.multiply(this,this,Z),this}transformVector(Z){return Z.transformQuaternion(this)}normalize(){return b1.quat.normalize(this,this),this}power(Z){return b1.quat.pow(this,this,Z),this}randomize(){return b1.quat.random(this),this}rotateX(Z){return b1.quat.rotateX(this,this,Z),this}rotateY(Z){return b1.quat.rotateY(this,this,Z),this}rotateZ(Z){return b1.quat.rotateZ(this,this,Z),this}scale(Z){return b1.quat.scale(this,this,Z),this}setAxisAngle(Z,J){return b1.quat.setAxisAngle(this,Z,J),this}slerp(Z,J){return b1.quat.slerp(this,this,Z,J),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var U1=r(PK(),1);class Q2 extends Float32Array{constructor(Z,J){super([Z,J])}get length(){return U1.vec2.length(this)}get squaredLength(){return U1.vec2.squaredLength(this)}get magnitude(){return U1.vec2.length(this)}get squaredMagnitude(){return U1.vec2.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}static create(){return new Q2(0,0)}add(Z){return U1.vec2.add(this,this,Z),this}angle(Z){return U1.vec2.angle(this,Z)}ceil(){return U1.vec2.ceil(this,this),this}clone(){return new Q2(this.x,this.y)}copy(Z){return U1.vec2.copy(this,Z),this}distance(Z){return U1.vec2.distance(this,Z)}divide(Z){return U1.vec2.divide(this,this,Z),this}dot(Z){return U1.vec2.dot(this,Z)}equals(Z){return U1.vec2.equals(this,Z)}exactEquals(Z){return U1.vec2.exactEquals(this,Z)}floor(){return U1.vec2.floor(this,this),this}invert(){return U1.vec2.inverse(this,this),this}lerp(Z,J){return U1.vec2.lerp(this,this,Z,J),this}max(Z){return U1.vec2.max(this,this,Z),this}min(Z){return U1.vec2.min(this,this,Z),this}multiply(Z){return U1.vec2.mul(this,this,Z),this}negate(){return U1.vec2.negate(this,this),this}normalize(){return U1.vec2.normalize(this,this),this}randomize(Z){return U1.vec2.random(this,Z),this}rotate(Z,J){return U1.vec2.rotate(this,this,Z,J),this}round(){return U1.vec2.round(this,this),this}scale(Z){return U1.vec2.scale(this,this,Z),this}scaleAndAdd(Z,J){return U1.vec2.scaleAndAdd(this,this,Z,J),this}subtract(Z){return U1.vec2.sub(this,this,Z),this}toString(){return`${this.x},${this.y}`}transformMatrix2(Z){return U1.vec2.transformMat2(this,this,Z),this}transformMatrix3(Z){return U1.vec2.transformMat3(this,this,Z),this}transformMatrix4(Z){return U1.vec2.transformMat4(this,this,Z),this}zero(){return U1.vec2.zero(this),this}}var H1=r(PK(),1);class pG extends Float32Array{constructor(Z,J,X){super([Z,J,X])}get length(){return H1.vec3.length(this)}get squaredLength(){return H1.vec3.squaredLength(this)}get magnitude(){return H1.vec3.length(this)}get squaredMagnitude(){return H1.vec3.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}static create(){return new pG(0,0,0)}static fromVector3Like(Z){return new pG(Z.x,Z.y,Z.z)}add(Z){return H1.vec3.add(this,this,Z),this}ceil(){return H1.vec3.ceil(this,this),this}clone(){return new pG(this.x,this.y,this.z)}copy(Z){return H1.vec3.copy(this,Z),this}cross(Z){return H1.vec3.cross(this,this,Z),this}distance(Z){return H1.vec3.distance(this,Z)}divide(Z){return H1.vec3.div(this,this,Z),this}dot(Z){return H1.vec3.dot(this,Z)}equals(Z){return H1.vec3.equals(this,Z)}exactEquals(Z){return H1.vec3.exactEquals(this,Z)}floor(){return H1.vec3.floor(this,this),this}invert(){return H1.vec3.inverse(this,this),this}lerp(Z,J){return H1.vec3.lerp(this,this,Z,J),this}max(Z){return H1.vec3.max(this,this,Z),this}min(Z){return H1.vec3.min(this,this,Z),this}multiply(Z){return H1.vec3.mul(this,this,Z),this}negate(){return H1.vec3.negate(this,this),this}normalize(){return H1.vec3.normalize(this,this),this}randomize(Z){return H1.vec3.random(this,Z),this}rotateX(Z,J){return H1.vec3.rotateX(this,this,Z,J),this}rotateY(Z,J){return H1.vec3.rotateY(this,this,Z,J),this}rotateZ(Z,J){return H1.vec3.rotateZ(this,this,Z,J),this}round(){return H1.vec3.round(this,this),this}scale(Z){return H1.vec3.scale(this,this,Z),this}scaleAndAdd(Z,J){return H1.vec3.scaleAndAdd(this,this,Z,J),this}subtract(Z){return H1.vec3.sub(this,this,Z),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(Z){return H1.vec3.transformMat3(this,this,Z),this}transformMatrix4(Z){return H1.vec3.transformMat4(this,this,Z),this}transformQuaternion(Z){return H1.vec3.transformQuat(this,this,Z),this}zero(){return H1.vec3.zero(this),this}}var oF1=r(aF1(),1);var sF1=0.099856;class K2 extends V${faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=sF1;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(Z={}){super();this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=Z.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=Z.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=Z.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(Z){super.spawn(Z),this._startIdleAnimations(Z)}face(Z,J,X){this._faceTarget=Z,this.faceSpeed=J,this._onFace=X?.faceCallback,this._onFaceComplete=X?.faceCompleteCallback}jump(Z){this._jumpHeight=Z}move(Z,J,X){this.moveSpeed=J,this._moveCompletesWhenStuck=X?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=X?.moveStoppingDistance?X.moveStoppingDistance**2:sF1,this._moveTarget=Z,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(Z,J){if(super.tick(Z,J),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(Z),this._moveStartMoveAnimations=!1;let X=J/1000,Y=Z.position;if(Z.isDynamic&&this._jumpHeight>0){let $=Math.abs(Z.world.simulation.gravity.y),Q=Math.sqrt(2*$*this._jumpHeight);Z.applyImpulse({x:0,y:Q*Z.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(Z)}if(this._moveTarget){let $={x:this._moveIgnoreAxes.x?0:this._moveTarget.x-Y.x,y:this._moveIgnoreAxes.y?0:this._moveTarget.y-Y.y,z:this._moveIgnoreAxes.z?0:this._moveTarget.z-Y.z},Q=$.x*$.x+$.y*$.y+$.z*$.z,K=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=J,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let W=Y.x-this._moveStuckLastPosition.x,G=Y.y-this._moveStuckLastPosition.y,V=Y.z-this._moveStuckLastPosition.z;K=Math.sqrt(W*W+G*G+V*V)<this.moveSpeed*0.1}this._moveStuckLastPosition=Y,this._moveStuckAccumulatorMs=0}}if(Q>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!K){let W=Math.sqrt(Q),G=this.moveSpeed*X,z=Math.min(W,G)/W,F={x:Y.x+$.x*z,y:Y.y+$.y*z,z:Y.z+$.z*z};if(Z.setPosition(F),this._onMove)this._onMove(F,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(Z);if(this._onMoveComplete){let W=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,W(Y)}}}if(this._faceTarget){let $={x:this._faceTarget.x-Y.x,z:this._faceTarget.z-Y.z},Q=Math.atan2(-$.x,-$.z),K=Z.rotation,W=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),G=Q-W;while(G>Math.PI)G-=2*Math.PI;while(G<-Math.PI)G+=2*Math.PI;if(Math.abs(G)>0.01&&!this._stopFaceRequested){let V=this.faceSpeed*X,z=Math.abs(G)<V?G:Math.sign(G)*V,H=(W+z)/2,q={x:0,y:Math.fround(Math.sin(H)),z:0,w:Math.fround(Math.cos(H))};if(Z.setRotation(q),this._onFace)this._onFace(K,q)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let V=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,V(Z.rotation)}}}_startIdleAnimations(Z){if(this.idleLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.jumpOneshotAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(Z){Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(Z){if(this.moveLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);Z.stopModelAnimations(this.jumpOneshotAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.moveLoopedAnimations)}}class ku extends K2{_debug=!1;_entity;_maxFall=0;_maxJump=0;_maxOpenSetIterations=200;_onPathfindAbort;_onPathfindComplete;_onWaypointMoveComplete;_onWaypointMoveSkipped;_speed=0;_target;_verticalPenalty=0;_waypoints=[];_waypointNextIndex=0;_waypointStoppingDistance;_waypointTimeoutMs=2000;constructor(Z={}){super(Z)}get debug(){return this._debug}get maxFall(){return this._maxFall}get maxJump(){return this._maxJump}get maxOpenSetIterations(){return this._maxOpenSetIterations}get speed(){return this._speed}get target(){return this._target}get verticalPenalty(){return this._verticalPenalty}get waypoints(){return this._waypoints}get waypointNextIndex(){return this._waypointNextIndex}get waypointTimeoutMs(){return this._waypointTimeoutMs}pathfind(Z,J,X){if(this._target=Z,this._speed=J,this._debug=X?.debug??!1,this._maxFall=X?.maxFall?-Math.abs(X.maxFall):0,this._maxJump=X?.maxJump?Math.abs(X.maxJump):0,this._maxOpenSetIterations=X?.maxOpenSetIterations??200,this._onPathfindAbort=X?.pathfindAbortCallback,this._onPathfindComplete=X?.pathfindCompleteCallback,this._onWaypointMoveComplete=X?.waypointMoveCompleteCallback,this._onWaypointMoveSkipped=X?.waypointMoveSkippedCallback,this._verticalPenalty=X?.verticalPenalty??0,this._waypoints=[],this._waypointNextIndex=0,this._waypointStoppingDistance=X?.waypointStoppingDistance,this._waypointTimeoutMs=X?.waypointTimeoutMs??2000/J,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(Z){super.attach(Z),this._entity=Z}detach(Z){super.detach(Z),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return c.error("PathfindingEntityController._calculatePath: No target or world"),!1;let Z=this._entity.height,J=this._findGroundedStart();if(!J){if(this._debug)c.warning(`PathfindingEntityController._calculatePath: No valid grounded start found within maxFall distance, path search aborted. Start: ${this._coordinateToKey(this._target)}, Target: ${this._coordinateToKey(this._target)}`);return!1}let X={x:Math.floor(this._target.x),y:Math.floor(this._target.y),z:Math.floor(this._target.z)},Y=Math.abs(X.x-J.x),$=Math.abs(X.y-J.y),Q=Math.abs(X.z-J.z);if(Y<=2&&$<=2&&Q<=2&&!this._isNeighborCoordinateBlocked(J,X,this._entity.height))return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5},{x:X.x+0.5,y:X.y+Z/2,z:X.z+0.5}],!0;if(J.x===X.x&&J.y===X.y&&J.z===X.z)return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5}],!0;let W=this._coordinateToKey(J),G=new Map,V=new Map([[W,0]]),z=new Map([[W,this._pathfindingHeuristic(J,X)]]),F=new Set,H=new oF1.Heap((N,R)=>{let P=z.get(N[0])??1/0,D=z.get(R[0])??1/0;return P-D});H.push([W,J]);let q=[{x:0,y:0,z:1},{x:1,y:0,z:0},{x:0,y:0,z:-1},{x:-1,y:0,z:0},{x:1,y:0,z:1},{x:1,y:0,z:-1},{x:-1,y:0,z:1},{x:-1,y:0,z:-1}],U=[];for(let N=this._maxJump;N>=this._maxFall;N--){if(N===0)continue;let R=Math.abs(J.y+N-X.y);U.push({y:N,distanceToTargetY:R})}U.sort((N,R)=>N.distanceToTargetY-R.distanceToTargetY);let B=[...q,...U.flatMap(({y:N})=>q.map((R)=>({...R,y:N})))],L=0,w=Math.abs(X.x-J.x)+Math.abs(X.y-J.y)+Math.abs(X.z-J.z),M=Math.min(this._maxOpenSetIterations,w*20);while(!H.isEmpty()&&L<M){L++;let[N,R]=H.pop();if(R.x===X.x&&R.y===X.y&&R.z===X.z){let C=this._reconstructPath(G,R);if(this._waypoints=C.map((T)=>({x:T.x+0.5,y:T.y+Z/2,z:T.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${L} open set iterations. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return!0}F.add(N);let P=V.get(N),D=new Map;for(let C of B){let T=`${C.x},${C.z}`,k=C.y<0;if(k&&D.has(T))continue;let A={x:R.x+C.x,y:R.y+C.y,z:R.z+C.z};if(Math.abs(X.x-A.x)+Math.abs(X.y-A.y)+Math.abs(X.z-A.z)>w*1.5)continue;let x=this._coordinateToKey(A);if(F.has(x))continue;let I=this._isNeighborCoordinateBlocked(R,A,this._entity.height);if(k&&I){D.set(T,!0);continue}if(I)continue;let _=Math.abs(C.x),b=Math.abs(C.y),u=Math.abs(C.z),i=b===0?0:this._verticalPenalty,e=(Math.max(_,b,u)===1&&_+b+u>1?1.4:1)+i,Z0=P+e,K0=V.get(x)??1/0;if(Z0>=K0)continue;G.set(x,R),V.set(x,Z0);let S0=Z0+this._pathfindingHeuristic(A,X);z.set(x,S0),H.push([x,A])}}if(L>=M){if(this._onPathfindAbort?.(),this._debug)c.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${M}), path search aborted. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)c.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(Z,J){let X=[J],Y=J;while(Z.has(this._coordinateToKey(Y)))Y=Z.get(this._coordinateToKey(Y)),X.unshift(Y);return X}_coordinateToKey(Z){return`${Z.x},${Z.y},${Z.z}`}_moveToNextWaypoint(){let Z=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,J=this._waypoints[this._waypointNextIndex];if(!J||!this._entity)return;let X=0;if(this._entity.isDynamic&&Z&&J.y>Z.y){let Y=J.y-Z.y,$=Math.min(Y,this._maxJump)+0.75;this.jump($);let Q=Math.abs(this._entity.world.simulation.gravity.y),K=Math.sqrt(2*Q*$),W=Z.x+0.5,G=Z.z+0.5,V=J.x+0.5,z=J.z+0.5,F=V-W,H=z-G,q=Math.sqrt(F*F+H*H),U=K/Q,B=q/this._speed;X=Math.min(U*0.8,B)*1000}setTimeout(()=>{if(!this._entity)return;let Y=Date.now();this.face(J,this._speed),this.move(J,this._speed,{moveCompletesWhenStuck:!0,moveIgnoreAxes:{y:this._entity.isDynamic},moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveStoppingDistance:this._waypointStoppingDistance,moveCallback:()=>{if(Date.now()-Y>this._waypointTimeoutMs&&this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveSkipped?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},X)}_pathfindingHeuristic(Z,J){return Math.abs(Z.x-J.x)+Math.abs(Z.y-J.y)+Math.abs(Z.z-J.z)}_isNeighborCoordinateBlocked(Z,J,X){if(!this._entity?.world)return!1;let Y=this._entity.world,$=Math.floor(J.x),Q=Math.floor(J.y),K=Math.floor(J.z),W=Math.floor(Z.x),G=Math.floor(Z.z);if(!Y.chunkLattice.hasBlock({x:$,y:Q-1,z:K}))return!0;for(let V=0;V<X;V++)if(Y.chunkLattice.hasBlock({x:$,y:Q+V,z:K}))return!0;if($!==W&&K!==G)for(let V=0;V<X;V++){let z=Y.chunkLattice.hasBlock({x:$,y:Q+V,z:G}),F=Y.chunkLattice.hasBlock({x:W,y:Q+V,z:K});if(z||F)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:Z,y:J,z:X}=this._entity.position,Y={x:Math.floor(Z),y:Math.floor(J),z:Math.floor(X)};for(let $=0;$<=Math.abs(this._maxFall);$++)if(this._entity.world.chunkLattice.hasBlock({...Y,y:Y.y-$-1}))return{...Y,y:Y.y-$};return}}export{UG6 as startServer,QH1 as WorldManagerEvent,K$ as WorldManager,$H1 as WorldLoopEvent,Y2 as WorldLoop,Ou as WorldEvent,$2 as World,LA as WebServerEvent,I3 as WebServer,pG as Vector3,Q2 as Vector2,X2 as Ticker,NK as TelemetrySpanOperation,R8 as Telemetry,wu as SimulationEvent,eU as Simulation,K2 as SimpleEntityController,J2 as SceneUIManager,M_ as SceneUIEvent,jH as SceneUI,u50 as SUPPORTED_INPUT_KEYS,mz as RigidBodyType,f$ as RigidBody,lG as Quaternion,SO as PlayerUIEvent,LH as PlayerUI,KH1 as PlayerManagerEvent,N9 as PlayerManager,wH as PlayerEvent,i7 as PlayerEntity,m50 as PlayerCameraMode,B_ as PlayerCameraEvent,BH as PlayerCamera,uW as Player,l$ as PersistenceManager,ku as PathfindingEntityController,Z2 as ParticleEmitterManager,Uu as ParticleEmitterEvent,Bu as ParticleEmitter,UA as PORT,i50 as PLAYER_ROTATION_UPDATE_THRESHOLD,p50 as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,g5 as ModelRegistry,v5 as Matrix4,kZ as Matrix3,CK as Matrix2,YH1 as LightType,rU as LightManager,Fu as LightEvent,qu as Light,U6 as IterationMap,GH1 as GameServerEvent,RK as GameServer,O0 as EventRouter,c as ErrorHandler,DH as EntityManager,RH as EntityEvent,a8 as Entity,l50 as ENTITY_ROTATION_UPDATE_THRESHOLD,c50 as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,m1 as DefaultPlayerEntityController,N_ as DefaultPlayerEntity,d50 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,g4 as CollisionGroupsBuilder,B$ as CollisionGroup,uz as ColliderShape,NH as ColliderMap,F9 as Collider,xE as CoefficientCombineRule,O_ as ChunkLatticeEvent,MH as ChunkLattice,B9 as Chunk,OH as ChatManager,L_ as ChatEvent,fE as BlockTypeRegistryEvent,dz as BlockTypeRegistry,hE as BlockTypeEvent,q9 as BlockType,IK as Block,xu as BaseEntityControllerEvent,V$ as BaseEntityController,aG as AudioManager,VP as AudioEvent,nG as Audio};
493
+ >>> no match, partial?`,Z,F,J,H),F===W)return!0}return!1}let U;if(typeof V==="string")U=z===V,this.debug("string match",V,z,U);else U=V.test(z),this.debug("pattern match",V,z,U);if(!U)return!1}if(Q===W&&K===G)return!0;else if(Q===W)return X;else if(K===G)return Q===W-1&&Z[Q]==="";else throw new Error("wtf?")}braceExpand(){return Q$1(this.pattern,this.options)}parse(Z){EU(Z);let J=this.options;if(Z==="**")return I4;if(Z==="")return"";let X,Y=null;if(X=Z.match(vY6))Y=J.dot?AY6:SY6;else if(X=Z.match(RY6))Y=(J.nocase?J.dot?CY6:PY6:J.dot?DY6:jY6)(X[1]);else if(X=Z.match(xY6))Y=(J.nocase?J.dot?fY6:hY6:J.dot?yY6:bY6)(X);else if(X=Z.match(TY6))Y=J.dot?EY6:kY6;else if(X=Z.match(IY6))Y=_Y6;let $=I6.fromGlob(Z,this.options).toMMPattern();if(Y&&typeof $==="object")Reflect.defineProperty($,"test",{value:Y});return $}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let Z=this.set;if(!Z.length)return this.regexp=!1,this.regexp;let J=this.options,X=J.noglobstar?uY6:J.dot?dY6:cY6,Y=new Set(J.nocase?["i"]:[]),$=Z.map((W)=>{let G=W.map((V)=>{if(V instanceof RegExp)for(let z of V.flags.split(""))Y.add(z);return typeof V==="string"?aY6(V):V===I4?I4:V._src});return G.forEach((V,z)=>{let F=G[z+1],H=G[z-1];if(V!==I4||H===I4)return;if(H===void 0)if(F!==void 0&&F!==I4)G[z+1]="(?:\\/|"+X+"\\/)?"+F;else G[z]=X;else if(F===void 0)G[z-1]=H+"(?:\\/|"+X+")?";else if(F!==I4)G[z-1]=H+"(?:\\/|\\/"+X+"\\/)"+F,G[z+1]=I4}),G.filter((V)=>V!==I4).join("/")}).join("|"),[Q,K]=Z.length>1?["(?:",")"]:["",""];if($="^"+Q+$+K+"$",this.negate)$="^(?!"+$+").+$";try{this.regexp=new RegExp($,[...Y].join(""))}catch(W){this.regexp=!1}return this.regexp}slashSplit(Z){if(this.preserveMultipleSlashes)return Z.split("/");else if(this.isWindows&&/^\/\/[^\/]+/.test(Z))return["",...Z.split(/\/+/)];else return Z.split(/\/+/)}match(Z,J=this.partial){if(this.debug("match",Z,this.pattern),this.comment)return!1;if(this.empty)return Z==="";if(Z==="/"&&J)return!0;let X=this.options;if(this.isWindows)Z=Z.split("\\").join("/");let Y=this.slashSplit(Z);this.debug(this.pattern,"split",Y);let $=this.set;this.debug(this.pattern,"set",$);let Q=Y[Y.length-1];if(!Q)for(let K=Y.length-2;!Q&&K>=0;K--)Q=Y[K];for(let K=0;K<$.length;K++){let W=$[K],G=Y;if(X.matchBase&&W.length===1)G=[Q];if(this.matchOne(G,W,J)){if(X.flipNegate)return!0;return!this.negate}}if(X.flipNegate)return!1;return this.negate}static defaults(Z){return _6.defaults(Z).Minimatch}}_6.AST=I6;_6.Minimatch=_U;_6.escape=gg;_6.unescape=AY;var W$1="@fastify/otel",oY6="0.8.0",rY6=">=4.0.0 <6",G$1=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],o1={HOOK_NAME:"hook.name",FASTIFY_TYPE:"fastify.type",HOOK_CALLBACK_NAME:"hook.callback.name",ROOT:"fastify.root"},xY={ROUTE:"route-hook",INSTANCE:"hook",HANDLER:"request-handler"},iJ="anonymous",T5=Symbol("fastify otel instance"),hY=Symbol("fastify otel request spans"),vU=Symbol("fastify otel request context"),V$1=Symbol("fastify otel addhook original"),z$1=Symbol("fastify otel setnotfound original"),nj=Symbol("fastify otel ignore path");class mg extends H$1.InstrumentationBase{constructor(Z){super(W$1,oY6,Z);if(this.servername=Z?.servername??process.env.OTEL_SERVICE_NAME??"fastify",this[nj]=null,this._logger=A8.diag.createComponentLogger({namespace:W$1}),Z?.ignorePaths!=null||process.env.OTEL_FASTIFY_IGNORE_PATHS!=null){let J=Z?.ignorePaths??process.env.OTEL_FASTIFY_IGNORE_PATHS;if((typeof J!=="string"||J.length===0)&&typeof J!=="function")throw new TypeError("ignorePaths must be a string or a function");let X=_6;this[nj]=(Y)=>{if(typeof J==="function")return J(Y);else return X(Y.url,J)}}}enable(){if(this._handleInitialization===void 0&&this.getConfig().registerOnInitialization){let Z=this.plugin();this._handleInitialization=(J)=>{J.fastify.register(Z)},K$1.subscribe("fastify.initialization",this._handleInitialization)}return super.enable()}disable(){if(this._handleInitialization)K$1.unsubscribe("fastify.initialization",this._handleInitialization),this._handleInitialization=void 0;return super.disable()}init(){return[]}plugin(){let Z=this;return J[Symbol.for("skip-override")]=!0,J[Symbol.for("fastify.display-name")]="@fastify/otel",J[Symbol.for("plugin-meta")]={fastify:rY6,name:"@fastify/otel"},J;function J(X,Y,$){X.decorate(T5,Z),X.decorate(V$1,X.addHook),X.decorate(z$1,X.setNotFoundHandler),X.decorateRequest("opentelemetry",function z(){let F=this[vU];return{span:this[hY],tracer:Z.tracer,context:F,inject:(q,U)=>{return A8.propagation.inject(F,q,U)},extract:(q,U)=>{return A8.propagation.extract(F,q,U)}}}),X.decorateRequest(hY,null),X.decorateRequest(vU,null),X.addHook("onRoute",function(z){if(Z[nj]?.(z)===!0){Z._logger.debug(`Ignoring route instrumentation ${z.method} ${z.url} because it matches the ignore path`);return}for(let F of G$1)if(z[F]!=null){let H=z[F];if(typeof H==="function")z[F]=V(H,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - route -> ${F}`,[o1.FASTIFY_TYPE]:xY.ROUTE,[d8.ATTR_HTTP_ROUTE]:z.url,[o1.HOOK_CALLBACK_NAME]:H.name?.length>0?H.name:iJ});else if(Array.isArray(H)){let q=[];for(let U of H)q.push(V(U,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - route -> ${F}`,[o1.FASTIFY_TYPE]:xY.ROUTE,[d8.ATTR_HTTP_ROUTE]:z.url,[o1.HOOK_CALLBACK_NAME]:U.name?.length>0?U.name:iJ}));z[F]=q}}if(z.onSend!=null)z.onSend=Array.isArray(z.onSend)?[...z.onSend,Q]:[z.onSend,Q];else z.onSend=Q;if(z.onError!=null)z.onError=Array.isArray(z.onError)?[...z.onError,K]:[z.onError,K];else z.onError=K;z.handler=V(z.handler,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - route-handler`,[o1.FASTIFY_TYPE]:xY.HANDLER,[d8.ATTR_HTTP_ROUTE]:z.url,[o1.HOOK_CALLBACK_NAME]:z.handler.name.length>0?z.handler.name:iJ})}),X.addHook("onRequest",function(z,F,H){if(this[T5].isEnabled()===!1)return H();else if(this[T5][nj]?.({url:z.url,method:z.method})===!0)return this[T5]._logger.debug(`Ignoring request ${z.method} ${z.url} because it matches the ignore path`),H();let q=A8.context.active();if(A8.trace.getSpan(q)==null)q=A8.propagation.extract(q,z.headers);let U=aj.getRPCMetadata(q);if(z.routeOptions.url!=null&&U?.type===aj.RPCType.HTTP)U.route=z.routeOptions.url;let B=this[T5].tracer.startSpan("request",{attributes:{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.ROOT]:"@fastify/otel",[d8.ATTR_HTTP_ROUTE]:z.url,[d8.ATTR_HTTP_REQUEST_METHOD]:z.method}},q);z[vU]=A8.trace.setSpan(q,B),z[hY]=B,A8.context.with(z[vU],()=>{H()})}),X.addHook("onResponse",function(z,F,H){let q=z[hY];if(q!=null)q.setStatus({code:A8.SpanStatusCode.OK,message:"OK"}),q.setAttributes({[d8.ATTR_HTTP_RESPONSE_STATUS_CODE]:404}),q.end();z[hY]=null,H()}),X.addHook=W,X.setNotFoundHandler=G,$();function Q(z,F,H,q){let U=z[hY];if(U!=null){if(F.statusCode<500)U.setStatus({code:A8.SpanStatusCode.OK,message:"OK"});U.setAttributes({[d8.ATTR_HTTP_RESPONSE_STATUS_CODE]:F.statusCode}),U.end()}z[hY]=null,q(null,H)}function K(z,F,H,q){let U=z[hY];if(U!=null)U.setStatus({code:A8.SpanStatusCode.ERROR,message:H.message}),U.recordException(H);q()}function W(z,F){let H=this[V$1];if(G$1.includes(z))return H.call(this,z,V(F,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - ${z}`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:iJ}));else return H.call(this,z,F)}function G(z,F){let H=this[z$1];if(typeof z==="function")F=V(z,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:z.name?.length>0?z.name:iJ}),H.call(this,F);else{if(z.preValidation!=null)z.preValidation=V(z.preValidation,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preValidation`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:z.preValidation.name?.length>0?z.preValidation.name:iJ});if(z.preHandler!=null)z.preHandler=V(z.preHandler,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preHandler`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:z.preHandler.name?.length>0?z.preHandler.name:iJ});F=V(F,{[d8.ATTR_SERVICE_NAME]:X[T5].servername,[o1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[o1.FASTIFY_TYPE]:xY.INSTANCE,[o1.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:iJ}),H.call(this,z,F)}}function V(z,F={}){return function H(...q){let U=this[T5],[B]=q;if(U.isEnabled()===!1)return z.call(this,...q);let L=B[vU]??A8.context.active(),w=U.tracer.startSpan(`handler - ${z.name?.length>0?z.name:this.pluginName??iJ}`,{attributes:F},L);return A8.context.with(A8.trace.setSpan(L,w),function(){try{let M=z.call(this,...q);if(typeof M?.then==="function")return M.then((N)=>{return w.end(),N},(N)=>{return w.setStatus({code:A8.SpanStatusCode.ERROR,message:N.message}),w.recordException(N),w.end(),Promise.reject(N)});return w.end(),M}catch(M){throw w.setStatus({code:A8.SpanStatusCode.ERROR,message:M.message}),w.recordException(M),w.end(),M}},this)}}}}}var j7=r(Y0(),1),oj=r(q1(),1),FK=r(r0(),1),L$1=r(j1(),1);var nJ;(function(Z){Z.FASTIFY_NAME="fastify.name";let X="fastify.type";Z.FASTIFY_TYPE=X;let Y="hook.name";Z.HOOK_NAME=Y;let $="plugin.name";Z.PLUGIN_NAME=$})(nJ||(nJ={}));var SU;(function(Z){Z.MIDDLEWARE="middleware";let X="request_handler";Z.REQUEST_HANDLER=X})(SU||(SU={}));var AU;(function(Z){Z.MIDDLEWARE="middleware";let X="request handler";Z.REQUEST_HANDLER=X})(AU||(AU={}));var q$1=r(Y0(),1);var xU=Symbol("opentelemetry.instrumentation.fastify.request_active_span");function ug(Z,J,X,Y={}){let $=J.startSpan(X,{attributes:Y}),Q=Z[xU]||[];return Q.push($),Object.defineProperty(Z,xU,{enumerable:!1,configurable:!0,value:Q}),$}function sj(Z,J){let X=Z[xU]||[];if(!X.length)return;X.forEach((Y)=>{if(J)Y.setStatus({code:q$1.SpanStatusCode.ERROR,message:J.message}),Y.recordException(J);Y.end()}),delete Z[xU]}function U$1(Z,J,X){let Y,$=void 0;try{if($=Z(),F$1($))$.then((Q)=>J(void 0,Q),(Q)=>J(Q))}catch(Q){Y=Q}finally{if(!F$1($)){if(J(Y,$),Y)throw Y}return $}}function F$1(Z){return typeof Z==="object"&&Z&&typeof Object.getOwnPropertyDescriptor(Z,"then")?.value==="function"||!1}var tY6="0.1.0",eY6="@sentry/instrumentation-fastify-v3",B$1="anonymous",Z$6=new Set(["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError"]);class dg extends FK.InstrumentationBase{constructor(Z={}){super(eY6,tY6,Z)}init(){return[new FK.InstrumentationNodeModuleDefinition("fastify",[">=3.0.0 <4"],(Z)=>{return this._patchConstructor(Z)})]}_hookOnRequest(){let Z=this;return function J(X,Y,$){if(!Z.isEnabled())return $();Z._wrap(Y,"send",Z._patchSend());let Q=X,K=oj.getRPCMetadata(j7.context.active()),W=Q.routeOptions?Q.routeOptions.url:X.routerPath;if(W&&K?.type===oj.RPCType.HTTP)K.route=W;let G=X.method||"GET";E0().setTransactionName(`${G} ${W}`),$()}}_wrapHandler(Z,J,X,Y){let $=this;return this._diag.debug("Patching fastify route.handler function"),function(...Q){if(!$.isEnabled())return X.apply(this,Q);let K=X.name||Z||B$1,W=`${AU.MIDDLEWARE} - ${K}`,G=Q[1],V=ug(G,$.tracer,W,{[nJ.FASTIFY_TYPE]:SU.MIDDLEWARE,[nJ.PLUGIN_NAME]:Z,[nJ.HOOK_NAME]:J}),z=Y&&Q[Q.length-1];if(z)Q[Q.length-1]=function(...F){sj(G),z.apply(this,F)};return j7.context.with(j7.trace.setSpan(j7.context.active(),V),()=>{return U$1(()=>{return X.apply(this,Q)},(F)=>{if(F instanceof Error)V.setStatus({code:j7.SpanStatusCode.ERROR,message:F.message}),V.recordException(F);if(!Y)sj(G)})})}}_wrapAddHook(){let Z=this;return this._diag.debug("Patching fastify server.addHook function"),function(J){return function X(...Y){let $=Y[0],Q=Y[1],K=this.pluginName;if(!Z$6.has($))return J.apply(this,Y);let W=typeof Y[Y.length-1]==="function"&&Q.constructor.name!=="AsyncFunction";return J.apply(this,[$,Z._wrapHandler(K,$,Q,W)])}}}_patchConstructor(Z){let J=this;function X(...Y){let $=Z.fastify.apply(this,Y);return $.addHook("onRequest",J._hookOnRequest()),$.addHook("preHandler",J._hookPreHandler()),J$6(),J._wrap($,"addHook",J._wrapAddHook()),$}if(Z.errorCodes!==void 0)X.errorCodes=Z.errorCodes;return X.fastify=X,X.default=X,X}_patchSend(){let Z=this;return this._diag.debug("Patching fastify reply.send function"),function J(X){return function Y(...$){let Q=$[0];if(!Z.isEnabled())return X.apply(this,$);return FK.safeExecuteInTheMiddle(()=>{return X.apply(this,$)},(K)=>{if(!K&&Q instanceof Error)K=Q;sj(this,K)})}}}_hookPreHandler(){let Z=this;return this._diag.debug("Patching fastify preHandler function"),function J(X,Y,$){if(!Z.isEnabled())return $();let Q=X,K=Q.routeOptions?.handler||Q.context?.handler,W=K?.name.startsWith("bound ")?K.name.substring(6):K?.name,G=`${AU.REQUEST_HANDLER} - ${W||this.pluginName||B$1}`,V={[nJ.PLUGIN_NAME]:this.pluginName,[nJ.FASTIFY_TYPE]:SU.REQUEST_HANDLER,[L$1.SEMATTRS_HTTP_ROUTE]:Q.routeOptions?Q.routeOptions.url:X.routerPath};if(W)V[nJ.FASTIFY_NAME]=W;let z=ug(Y,Z.tracer,G,V);w$1(z);let{requestHook:F}=Z.getConfig();if(F)FK.safeExecuteInTheMiddle(()=>F(z,{request:X}),(H)=>{if(H)Z._diag.error("request hook failed",H)},!0);return j7.context.with(j7.trace.setSpan(j7.context.active(),z),()=>{$()})}}}function J$6(){let Z=X0();if(Z)Z.on("spanStart",(J)=>{w$1(J)})}function w$1(Z){let J=L0(Z).data,X=J["fastify.type"];if(J[j0]||!X)return;Z.setAttributes({[v0]:"auto.http.otel.fastify",[j0]:`${X}.fastify`});let Y=J["fastify.name"]||J["plugin.name"]||J["hook.name"];if(typeof Y==="string"){let $=Y.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName($)}}var O$1="Fastify",X$6="Fastify-V5",Y$6="Fastify-V3",lg=B0(Y$6,()=>new dg);function M$1(){let Z=X0();if(!Z)return;else return Z.getIntegrationByName(O$1)}function rj(Z,J,X,Y){let $=M$1()?.getShouldHandleError()||N$1;if(Y==="diagnostics-channel")this.diagnosticsChannelExists=!0;if(this.diagnosticsChannelExists&&Y==="onError-hook"){T4&&h.warn("Fastify error handler was already registered via diagnostics channel.","You can safely remove `setupFastifyErrorHandler` call and set `shouldHandleError` on the integration options.");return}if($(Z,J,X))Z1(Z,{mechanism:{handled:!1,type:"fastify"}})}var pg=B0(X$6,()=>{let Z=new mg,J=Z.plugin();return cg.subscribe("fastify.initialization",(X)=>{let Y=X.fastify;Y?.register(J).after(($)=>{if($)T4&&h.error("Failed to setup Fastify instrumentation",$);else if(Q$6(),Y)K$6(Y)})}),cg.subscribe("tracing:fastify.request.handler:error",(X)=>{let{error:Y,request:$,reply:Q}=X;rj.call(rj,Y,$,Q,"diagnostics-channel")}),Z}),$$6=({shouldHandleError:Z})=>{let J;return{name:O$1,setupOnce(){J=Z||N$1,lg(),pg()},getShouldHandleError(){return J},setShouldHandleError(X){J=X}}},tj=a((Z={})=>$$6(Z));function N$1(Z,J,X){let Y=X.statusCode;return Y>=500||Y<=299}function R$1(Z,J){if(J?.shouldHandleError)M$1()?.setShouldHandleError(J.shouldHandleError);let X=Object.assign(function(Y,$,Q){Y.addHook("onError",async(K,W,G)=>{rj.call(rj,G,K,W,"onError-hook")}),Q()},{[Symbol.for("skip-override")]:!0,[Symbol.for("fastify.display-name")]:"sentry-fastify-error-handler"});Z.register(X)}function j$1(Z){let J=L0(Z),X=J.description,Y=J.data,$=Y["fastify.type"],Q=$==="hook",K=$===X?.startsWith("handler -"),W=X==="request"||$==="request-handler";if(Y[j0]||!K&&!W&&!Q)return;let G=Q?"hook":K?"middleware":W?"request-handler":"<unknown>";Z.setAttributes({[v0]:"auto.http.otel.fastify",[j0]:`${G}.fastify`});let V=Y["fastify.name"]||Y["plugin.name"]||Y["hook.name"];if(typeof V==="string"){let z=V.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(z)}}function Q$6(){let Z=X0();if(Z)Z.on("spanStart",(J)=>{j$1(J)})}function K$6(Z){Z.addHook("onRequest",async(J,X)=>{if(J.opentelemetry){let{span:Q}=J.opentelemetry();if(Q)j$1(Q)}let Y=J.routeOptions?.url,$=J.method||"GET";E0().setTransactionName(`${$} ${Y}`)})}var KQ1=r(Y0(),1),WQ1=r(QQ1(),1);var GQ1="Graphql",tg=B0(GQ1,WQ1.GraphQLInstrumentation,(Z)=>{let J=VQ1(Z);return{...J,responseHook(X,Y){if(s1(X,"auto.graphql.otel.graphql"),Y.errors?.length&&!L0(X).status)X.setStatus({code:KQ1.SpanStatusCode.ERROR});let Q=L0(X).data,K=Q["graphql.operation.type"],W=Q["graphql.operation.name"];if(J.useOperationNameForRootSpan&&K){let G=a1(X),z=L0(G).data[RG]||[],F=W?`${K} ${W}`:`${K}`;if(Array.isArray(z))z.push(F),G.setAttribute(RG,z);else if(typeof z==="string")G.setAttribute(RG,[z,F]);else G.setAttribute(RG,F);if(!L0(G).data["original-description"])G.setAttribute("original-description",L0(G).description);G.updateName(`${L0(G).data["original-description"]} (${A$6(z)})`)}}}}),S$6=(Z={})=>{return{name:GQ1,setupOnce(){tg(VQ1(Z))}}},XD=a(S$6);function VQ1(Z){return{ignoreResolveSpans:!0,ignoreTrivialResolveSpans:!0,useOperationNameForRootSpan:!0,...Z}}function A$6(Z){if(Array.isArray(Z)){let J=Z.slice().sort();if(J.length<=5)return J.join(", ");else return`${J.slice(0,5).join(", ")}, +${J.length-5}`}return`${Z}`}var TQ1=r(CQ1(),1);var kQ1="Kafka",eg=B0(kQ1,()=>new TQ1.KafkaJsInstrumentation({consumerHook(Z){s1(Z,"auto.kafkajs.otel.consumer")},producerHook(Z){s1(Z,"auto.kafkajs.otel.producer")}})),f$6=()=>{return{name:kQ1,setupOnce(){eg()}}},YD=a(f$6);var gQ1=r(bQ1(),1);var mQ1="LruMemoizer",Zm=B0(mQ1,()=>new gQ1.LruMemoizerInstrumentation),m$6=()=>{return{name:mQ1,setupOnce(){Zm()}}},$D=a(m$6);var JK1=r(ZK1(),1);var XK1="Mongo",Qm=B0(XK1,()=>new JK1.MongoDBInstrumentation({dbStatementSerializer:p$6,responseHook(Z){s1(Z,"auto.db.otel.mongo")}}));function p$6(Z){let J=$m(Z);return JSON.stringify(J)}function $m(Z){if(Array.isArray(Z))return Z.map((J)=>$m(J));if(i$6(Z)){let J={};return Object.entries(Z).map(([X,Y])=>[X,$m(Y)]).reduce((X,Y)=>{if(a$6(Y))X[Y[0]]=Y[1];return X},J)}return"?"}function i$6(Z){return typeof Z==="object"&&Z!==null&&!n$6(Z)}function n$6(Z){let J=!1;if(typeof Buffer!=="undefined")J=Buffer.isBuffer(Z);return J}function a$6(Z){return Array.isArray(Z)}var s$6=()=>{return{name:XK1,setupOnce(){Qm()}}},QD=a(s$6);var DK1=r(jK1(),1);var PK1="Mongoose",Gm=B0(PK1,()=>new DK1.MongooseInstrumentation({responseHook(Z){s1(Z,"auto.db.otel.mongoose")}})),GQ6=()=>{return{name:PK1,setupOnce(){Gm()}}},WD=a(GQ6);var dK1=r(uK1(),1);var cK1="Mysql",Fm=B0(cK1,()=>new dK1.MySQLInstrumentation({})),PQ6=()=>{return{name:cK1,setupOnce(){Fm()}}},VD=a(PQ6);var VW1=r(GW1(),1);var zW1="Mysql2",wm=B0(zW1,()=>new VW1.MySQL2Instrumentation({responseHook(Z){s1(Z,"auto.db.otel.mysql2")}})),uQ6=()=>{return{name:zW1,setupOnce(){wm()}}},HD=a(uQ6);var rW1=r(IW1(),1),tW1=r(iW1(),1);var JK6=["get","set","setex"],Mm=["get","mget"],XK6=["set","setex"];function cU(Z,J){return Z.includes(J.toLowerCase())}function Nm(Z){if(cU(Mm,Z))return"cache.get";else if(cU(XK6,Z))return"cache.put";else return}function YK6(Z,J){return J.some((X)=>Z.startsWith(X))}function aW1(Z,J){try{if(J.length===0)return;let X=($)=>{if(typeof $==="string"||typeof $==="number"||Buffer.isBuffer($))return[$.toString()];else if(Array.isArray($))return nW1($.map((Q)=>X(Q)));else return["<unknown>"]},Y=J[0];if(cU(JK6,Z)&&Y!=null)return X(Y);return nW1(J.map(($)=>X($)))}catch{return}}function sW1(Z,J,X){if(!Nm(Z))return!1;for(let Y of J)if(YK6(Y,X))return!0;return!1}function oW1(Z){let J=(X)=>{try{if(Buffer.isBuffer(X))return X.byteLength;else if(typeof X==="string")return X.length;else if(typeof X==="number")return X.toString().length;else if(X===null||X===void 0)return 0;return JSON.stringify(X).length}catch{return}};return Array.isArray(Z)?Z.reduce((X,Y)=>{let $=J(Y);return typeof $==="number"?X!==void 0?X+$:$:X},0):J(Z)}function nW1(Z){let J=[],X=(Y)=>{Y.forEach(($)=>{if(Array.isArray($))X($);else J.push($)})};return X(Z),J}var eW1="Redis",Rm={},Z31=(Z,J,X,Y)=>{Z.setAttribute(v0,"auto.db.otel.redis");let $=aW1(J,X),Q=Nm(J);if(!$||!Q||!Rm.cachePrefixes||!sW1(J,$,Rm.cachePrefixes))return;let K=L0(Z).data["net.peer.name"],W=L0(Z).data["net.peer.port"];if(W&&K)Z.setAttributes({"network.peer.address":K,"network.peer.port":W});let G=oW1(Y);if(G)Z.setAttribute(_f,G);if(cU(Mm,J)&&G!==void 0)Z.setAttribute(Ef,G>0);Z.setAttributes({[j0]:Q,[If]:$});let V=$.join(", ");Z.updateName(t5(V,1024))},$K6=B0("IORedis",()=>{return new rW1.IORedisInstrumentation({responseHook:Z31})}),QK6=B0("Redis-4",()=>{return new tW1.RedisInstrumentation({responseHook:Z31})}),jm=Object.assign(()=>{$K6(),QK6()},{id:eW1}),KK6=(Z={})=>{return{name:eW1,setupOnce(){Rm=Z,jm()}}},qD=a(KK6);var S31=r(v31(),1);var A31="Postgres",_m=B0(A31,()=>new S31.PgInstrumentation({requireParentSpan:!0,requestHook(Z){s1(Z,"auto.db.otel.postgres")}})),lK6=()=>{return{name:A31,setupOnce(){_m()}}},wD=a(lK6);var yG=r(Y0(),1),ZX=r(r0(),1),Z5=r(j1(),1);var vm="PostgresJs",x31=[">=3.0.0 <4"],Sm=B0(vm,(Z)=>new h31({requireParentSpan:Z?.requireParentSpan??!0,requestHook:Z?.requestHook}));class h31 extends ZX.InstrumentationBase{constructor(Z){super("sentry-postgres-js",R1,Z)}init(){let Z=new ZX.InstrumentationNodeModuleDefinition("postgres",x31);return["src","cf/src","cjs/src"].forEach((J)=>{Z.files.push(new ZX.InstrumentationNodeModuleFile(`postgres/${J}/connection.js`,["*"],this._patchConnection.bind(this),this._unwrap.bind(this))),Z.files.push(new ZX.InstrumentationNodeModuleFile(`postgres/${J}/query.js`,x31,this._patchQuery.bind(this),this._unwrap.bind(this)))}),[Z]}_shouldCreateSpans(){let Z=this.getConfig();return yG.trace.getSpan(yG.context.active())!==void 0||!Z.requireParentSpan}_patchReject(Z,J){return new Proxy(Z,{apply:(X,Y,$)=>{J.setStatus({code:S8,message:$?.[0]?.message||"unknown_error"});let Q=Reflect.apply(X,Y,$);return J.setAttribute(Z5.ATTR_DB_RESPONSE_STATUS_CODE,$?.[0]?.code||"Unknown error"),J.setAttribute(Z5.ATTR_ERROR_TYPE,$?.[0]?.name||"Unknown error"),J.end(),Q}})}_patchResolve(Z,J){return new Proxy(Z,{apply:(X,Y,$)=>{let Q=Reflect.apply(X,Y,$),K=$?.[0]?.command;if(K)J.setAttribute(Z5.ATTR_DB_OPERATION_NAME,K);return J.end(),Q}})}_patchQuery(Z){return Z.Query.prototype.handle=new Proxy(Z.Query.prototype.handle,{apply:async(J,X,Y)=>{if(!this._shouldCreateSpans())return Reflect.apply(J,X,Y);let $=this._sanitizeSqlQuery(X.strings?.[0]);return dQ({name:$||"postgresjs.query",op:"db"},(Q)=>{let W=T0().getScopeData().contexts.postgresjsConnection;s1(Q,"auto.db.otel.postgres");let{requestHook:G}=this.getConfig();if(G)ZX.safeExecuteInTheMiddle(()=>G(Q,$,W),(H)=>{if(H)h.error(`Error in requestHook for ${vm} integration:`,H)});let V=W?.ATTR_DB_NAMESPACE||"<unknown database>",z=W?.ATTR_SERVER_ADDRESS||"<unknown host>",F=W?.ATTR_SERVER_PORT||"<unknown port>";Q.setAttribute(Z5.ATTR_DB_SYSTEM_NAME,"postgres"),Q.setAttribute(Z5.ATTR_DB_NAMESPACE,V),Q.setAttribute(Z5.ATTR_SERVER_ADDRESS,z),Q.setAttribute(Z5.ATTR_SERVER_PORT,F),Q.setAttribute(Z5.ATTR_DB_QUERY_TEXT,$),X.resolve=this._patchResolve(X.resolve,Q),X.reject=this._patchReject(X.reject,Q);try{return Reflect.apply(J,X,Y)}catch(H){throw Q.setStatus({code:S8}),Q.end(),H}})}}),Z}_patchConnection(Z){return new Proxy(Z,{apply:(J,X,Y)=>{let $=Y[0]?.database||"<unknown database>",Q=Y[0]?.host?.[0]||"<unknown host>",K=Y[0]?.port?.[0]||"<unknown port>";return T0().setContext("postgresjsConnection",{ATTR_DB_NAMESPACE:$,ATTR_SERVER_ADDRESS:Q,ATTR_SERVER_PORT:K}),Reflect.apply(J,X,Y)}})}_sanitizeSqlQuery(Z){if(!Z)return"Unknown SQL Query";return Z.replace(/\s+/g," ").trim().substring(0,1024).replace(/--.*?(\r?\n|$)/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/;\s*$/,"").replace(/\b\d+\b/g,"?").replace(/\s+/g," ").replace(/\bIN\b\s*\(\s*\?(?:\s*,\s*\?)*\s*\)/g,"IN (?)")}}var pK6=()=>{return{name:vm,setupOnce(){Sm()}}},OD=a(pK6);var b31=r(Y0(),1),MD=r(r0(),1),oY=r(Y0(),1);var iK6=process.env.PRISMA_SHOW_ALL_TRACES==="true",nK6="00-10-10-00";function aK6(Z){switch(Z){case"client":return oY.SpanKind.CLIENT;case"internal":default:return oY.SpanKind.INTERNAL}}var sK6=class{traceMiddleware;tracerProvider;ignoreSpanTypes;constructor({traceMiddleware:Z,tracerProvider:J,ignoreSpanTypes:X}){this.traceMiddleware=Z,this.tracerProvider=J,this.ignoreSpanTypes=X}isEnabled(){return!0}getTraceParent(Z){let J=oY.trace.getSpanContext(Z??oY.context.active());if(J)return`00-${J.traceId}-${J.spanId}-0${J.traceFlags}`;return nK6}dispatchEngineSpans(Z){let J=this.tracerProvider.getTracer("prisma"),X=new Map,Y=Z.filter(($)=>$.parentId===null);for(let $ of Y)g31(J,$,Z,X,this.ignoreSpanTypes)}getActiveContext(){return oY.context.active()}runInChildSpan(Z,J){if(typeof Z==="string")Z={name:Z};if(Z.internal&&!iK6)return J();if(Z.middleware&&!this.traceMiddleware)return J();let X=this.tracerProvider.getTracer("prisma"),Y=Z.context??this.getActiveContext(),$=`prisma:client:${Z.name}`;if(m31($,this.ignoreSpanTypes))return J();if(Z.active===!1){let Q=X.startSpan($,Z,Y);return f31(Q,J(Q,Y))}return X.startActiveSpan($,Z,(Q)=>f31(Q,J(Q,Y)))}};function g31(Z,J,X,Y,$){if(m31(J.name,$))return;let Q={attributes:J.attributes,kind:aK6(J.kind),startTime:J.startTime};Z.startActiveSpan(J.name,Q,(K)=>{if(Y.set(J.id,K.spanContext().spanId),J.links)K.addLinks(J.links.flatMap((G)=>{let V=Y.get(G);if(!V)return[];return{context:{spanId:V,traceId:K.spanContext().traceId,traceFlags:K.spanContext().traceFlags}}}));let W=X.filter((G)=>G.parentId===J.id);for(let G of W)g31(Z,G,X,Y,$);K.end(J.endTime)})}function f31(Z,J){if(oK6(J))return J.then((X)=>{return Z.end(),X},(X)=>{throw Z.end(),X});return Z.end(),J}function oK6(Z){return Z!=null&&typeof Z.then==="function"}function m31(Z,J){return J.some((X)=>typeof X==="string"?X===Z:X.test(Z))}var u31={name:"@prisma/instrumentation",version:"6.11.1",description:"OpenTelemetry compliant instrumentation for Prisma Client",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",exports:{".":{require:{types:"./dist/index.d.ts",default:"./dist/index.js"},import:{types:"./dist/index.d.ts",default:"./dist/index.mjs"}}},license:"Apache-2.0",homepage:"https://www.prisma.io",repository:{type:"git",url:"https://github.com/prisma/prisma.git",directory:"packages/instrumentation"},bugs:"https://github.com/prisma/prisma/issues",devDependencies:{"@prisma/internals":"workspace:*","@swc/core":"1.11.5","@types/jest":"29.5.14","@types/node":"18.19.76","@opentelemetry/api":"1.9.0",jest:"29.7.0","jest-junit":"16.0.0",typescript:"5.4.5"},dependencies:{"@opentelemetry/instrumentation":"^0.52.0 || ^0.53.0 || ^0.54.0 || ^0.55.0 || ^0.56.0 || ^0.57.0"},peerDependencies:{"@opentelemetry/api":"^1.8"},files:["dist"],keywords:["prisma","instrumentation","opentelemetry","otel"],scripts:{dev:"DEV=true tsx helpers/build.ts",build:"tsx helpers/build.ts",prepublishOnly:"pnpm run build",test:"jest"},sideEffects:!1},xm=u31.version,rK6=xm.split(".")[0],y31="PRISMA_INSTRUMENTATION",Am=`V${rK6}_PRISMA_INSTRUMENTATION`,tK6=u31.name,eK6="@prisma/client",d31=class extends MD.InstrumentationBase{tracerProvider;constructor(Z={}){super(tK6,xm,Z)}setTracerProvider(Z){this.tracerProvider=Z}init(){return[new MD.InstrumentationNodeModuleDefinition(eK6,[xm])]}enable(){let Z=this._config,J={helper:new sK6({traceMiddleware:Z.middleware??!1,tracerProvider:this.tracerProvider??b31.trace.getTracerProvider(),ignoreSpanTypes:Z.ignoreSpanTypes??[]})};global[y31]=J,global[Am]=J}disable(){delete global[y31],delete global[Am]}isEnabled(){return Boolean(global[Am])}};var c31="Prisma";function ZW6(Z){return!!Z&&typeof Z==="object"&&"dispatchEngineSpans"in Z}function l31(){let Z=globalThis.PRISMA_INSTRUMENTATION;return Z&&typeof Z==="object"&&"helper"in Z?Z.helper:void 0}class p31 extends d31{constructor(){super()}enable(){super.enable();let Z=l31(),J=!1;if(ZW6(Z))Z.createEngineSpan=()=>{e0(()=>{if(!J)J=!0,console.warn("[Sentry] The Sentry SDK supports tracing with Prisma version 5 only with limited capabilities. For full tracing capabilities pass `prismaInstrumentation` for version 5 to the Sentry `prismaIntegration`. Read more: https://docs.sentry.io/platforms/javascript/guides/node/configuration/integrations/prisma/")})}}}var JW6=B0(c31,(Z)=>{if(Z?.prismaInstrumentation)return Z.prismaInstrumentation;return new p31}),ND=a(({prismaInstrumentation:Z}={})=>{return{name:c31,setupOnce(){JW6({prismaInstrumentation:Z})},setup(J){if(!l31())return;J.on("spanStart",(X)=>{let Y=L0(X);if(Y.description?.startsWith("prisma:"))X.setAttribute(v0,"auto.db.otel.prisma");if(Y.description==="prisma:engine:db_query"&&Y.data["db.query.text"])X.updateName(Y.data["db.query.text"]);if(Y.description==="prisma:engine:db_query"&&!Y.data["db.system"])X.setAttribute("db.system","prisma")})}}});var VG1=r(GG1(),1);var zG1="Hapi",DD=B0(zG1,()=>new VG1.HapiInstrumentation),jW6=()=>{return{name:zG1,setupOnce(){DD()}}},PD=a(jW6);function DW6(Z){return!!(Z&&typeof Z==="object"&&("error"in Z)&&Z.error)}function PW6(Z){Z1(Z,{mechanism:{type:"hapi",handled:!1,data:{function:"hapiErrorPlugin"}}})}var CW6={name:"SentryHapiErrorPlugin",version:R1,register:async function(Z){Z.events.on({name:"request",channels:["error"]},(X,Y)=>{if(E0()!==B4()){let $=X.route;if($.path)E0().setTransactionName(`${$.method.toUpperCase()} ${$.path}`)}else T4&&h.warn("Isolation scope is still the default isolation scope - skipping setting transactionName");if(DW6(Y))PW6(Y.error)})}};async function HG1(Z){await Z.register(CW6);let J=X0();if(J)J.on("spanStart",(X)=>{TW6(X)});cJ(Z.register,"hapi")}function TW6(Z){let J=L0(Z).data,X=J["hapi.type"];if(J[j0]||!X)return;Z.setAttributes({[v0]:"auto.http.otel.hapi",[j0]:`${X}.hapi`})}var xG1=r(AG1(),1),hG1=r(j1(),1);var fG1="Koa",cm=B0(fG1,xG1.KoaInstrumentation,(Z={})=>{return{ignoreLayersType:Z.ignoreLayersType,requestHook(J,X){s1(J,"auto.http.otel.koa");let Y=L0(J).data,$=Y["koa.type"];if($)J.setAttribute(j0,`${$}.koa`);let Q=Y["koa.name"];if(typeof Q==="string")J.updateName(Q||"< unknown >");if(E0()===B4()){T4&&h.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let K=Y[hG1.ATTR_HTTP_ROUTE],W=X.context?.request?.method?.toUpperCase()||"GET";if(K)E0().setTransactionName(`${W} ${K}`)}}}),hW6=(Z={})=>{return{name:fG1,setupOnce(){cm(Z)}}},kD=a(hW6),yG1=(Z)=>{Z.use(async(J,X)=>{try{await X()}catch(Y){throw Z1(Y),Y}}),cJ(Z.use,"koa")};var $V1=r(YV1(),1);var QV1="Connect",am=B0(QV1,()=>new $V1.ConnectInstrumentation),sW6=()=>{return{name:QV1,setupOnce(){am()}}},ID=a(sW6);function oW6(Z,J,X,Y){Z1(Z),Y(Z)}var KV1=(Z)=>{Z.use(oW6);let J=X0();if(J)J.on("spanStart",(X)=>{rW6(X)});cJ(Z.use,"connect")};function rW6(Z){let J=L0(Z).data,X=J["connect.type"];if(J[j0]||!X)return;Z.setAttributes({[v0]:"auto.http.otel.connect",[j0]:`${X}.connect`});let Y=J["connect.name"];if(typeof Y==="string")Z.updateName(Y)}var kV1=r(TV1(),1);var EV1="Knex",q36=B0(EV1,()=>new kV1.KnexInstrumentation({requireParentSpan:!0})),U36=()=>{let Z;return{name:EV1,setupOnce(){let J=q36();Z=fJ(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let{data:Y}=L0(X);if("knex.version"in Y)X.setAttribute(v0,"auto.db.otel.knex")}))}}},IV1=a(U36);var nV1=r(iV1(),1);var R36=new Set(["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"]),aV1="Tedious",om=B0(aV1,()=>new nV1.TediousInstrumentation({})),j36=()=>{let Z;return{name:aV1,setupOnce(){let J=om();Z=fJ(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let{description:Y,data:$}=L0(X);if(!Y||$["db.system"]!=="mssql")return;let Q=Y.split(" ")[0]||"";if(R36.has(Q))X.setAttribute(v0,"auto.db.otel.tedious")}))}}},xD=a(j36);var $z1=r(Yz1(),1);var Qz1="GenericPool",tm=B0(Qz1,()=>new $z1.GenericPoolInstrumentation({})),T36=()=>{let Z;return{name:Qz1,setupOnce(){let J=tm();Z=fJ(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let $=L0(X).description;if($==="generic-pool.aquire"||$==="generic-pool.acquire")X.setAttribute(v0,"auto.db.otel.generic_pool")}))}}},hD=a(T36);var Oz1=r(wz1(),1);var Mz1="Dataloader",I36=B0(Mz1,()=>new Oz1.DataloaderInstrumentation({requireParentSpan:!0})),_36=()=>{let Z;return{name:Mz1,setupOnce(){let J=I36();Z=fJ(J)},setup(J){Z?.(()=>{J.on("spanStart",(X)=>{let Y=L0(X);if(Y.description?.startsWith("dataloader"))X.setAttribute(v0,"auto.db.otel.dataloader");if(Y.description==="dataloader.load"||Y.description==="dataloader.loadMany"||Y.description==="dataloader.batch")X.setAttribute(j0,"cache.get")})})}}},Nz1=a(_36);var mz1=r(gz1(),1);var uz1="Amqplib",o36={consumeEndHook:(Z)=>{s1(Z,"auto.amqplib.otel.consumer")},publishHook:(Z)=>{s1(Z,"auto.amqplib.otel.publisher")}},Yu=B0(uz1,()=>new mz1.AmqplibInstrumentation(o36)),r36=()=>{return{name:uz1,setupOnce(){Yu()}}},bD=a(r36);var sU="VercelAI";var gD=r(r0(),1);var dz1=["generateText","streamText","generateObject","streamObject","embed","embedMany"];function t36(Z,J,X,Y){let $=Z?.recordInputs!==void 0?Z.recordInputs:J.recordInputs!==void 0?J.recordInputs:X===!0?!0:Y,Q=Z?.recordOutputs!==void 0?Z.recordOutputs:J.recordOutputs!==void 0?J.recordOutputs:X===!0?!0:Y;return{recordInputs:$,recordOutputs:Q}}class oU extends gD.InstrumentationBase{__init(){this._isPatched=!1}__init2(){this._callbacks=[]}constructor(Z={}){super("@sentry/instrumentation-vercel-ai",R1,Z);oU.prototype.__init.call(this),oU.prototype.__init2.call(this)}init(){return new gD.InstrumentationNodeModuleDefinition("ai",[">=3.0.0 <5"],this._patch.bind(this))}callWhenPatched(Z){if(this._isPatched)Z();else this._callbacks.push(Z)}_patch(Z){this._isPatched=!0,this._callbacks.forEach((X)=>X()),this._callbacks=[];function J(X){return(...Y)=>{let $=Y[0].experimental_telemetry||{},Q=$.isEnabled,K=T0().getClient(),W=K?.getIntegrationByName(sU),G=W?.options,V=W?Boolean(K?.getOptions().sendDefaultPii):!1,{recordInputs:z,recordOutputs:F}=t36(G,$,Q,V);return Y[0].experimental_telemetry={...$,isEnabled:Q!==void 0?Q:!0,recordInputs:z,recordOutputs:F},SJ(()=>{return X.apply(this,Y)},(H)=>{if(H&&typeof H==="object")e1(H,"_sentry_active_span",C6())})}}if(Object.prototype.toString.call(Z)==="[object Module]"){for(let X of dz1)Z[X]=J(Z[X]);return Z}else{let X=dz1.reduce((Y,$)=>{return Y[$]=J(Z[$]),Y},{});return{...Z,...X}}}}var $u=B0(sU,()=>new oU({}));function e36(Z){return!!Z.getIntegrationByName("Modules")?.getModules?.()?.ai}var ZG6=(Z={})=>{let J;return{name:sU,options:Z,setupOnce(){J=$u()},afterAllSetup(X){if(Z.force??e36(X))$j(X);else J?.callWhenPatched(()=>$j(X))}}},mD=a(ZG6);var uD=r(r0(),1);var JG6=[">=4.0.0 <6"];function XG6(Z,J){let X=Z?.recordInputs??J,Y=Z?.recordOutputs??J;return{recordInputs:X,recordOutputs:Y}}class Qu extends uD.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-openai",R1,Z)}init(){return new uD.InstrumentationNodeModuleDefinition("openai",JG6,this._patch.bind(this))}_patch(Z){let J=Z.OpenAI,X=function(...Y){let $=Reflect.construct(J,Y),Q=T0().getClient(),W=Q?.getIntegrationByName(PY)?.options,G=Boolean(Q?.getOptions().sendDefaultPii),{recordInputs:V,recordOutputs:z}=XG6(W,G);return Qb($,{recordInputs:V,recordOutputs:z})};Object.setPrototypeOf(X,J),Object.setPrototypeOf(X.prototype,J.prototype);for(let Y of Object.getOwnPropertyNames(J))if(!["length","name","prototype"].includes(Y)){let $=Object.getOwnPropertyDescriptor(J,Y);if($)Object.defineProperty(X,Y,$)}try{Z.OpenAI=X}catch(Y){Object.defineProperty(Z,"OpenAI",{value:X,writable:!0,configurable:!0,enumerable:!0})}return Z}}var Ku=B0(PY,()=>new Qu({})),YG6=(Z={})=>{return{name:PY,options:Z,setupOnce(){Ku()}}},dD=a(YG6);var cz1=a((Z)=>{if(!O7())e0(()=>{console.warn("The launchDarklyIntegration() can only be used in the browser.")});return{name:"LaunchDarkly"}});function lz1(){if(!O7())e0(()=>{console.warn("The buildLaunchDarklyFlagUsedHandler() can only be used in the browser.")});return{name:"sentry-flag-auditor",type:"flag-used",synchronous:!0,method:()=>null}}var pz1=a((Z)=>{if(!O7())e0(()=>{console.warn("The openFeatureIntegration() can only be used in the browser.")});return{name:"OpenFeature"}});class Wu{constructor(){if(!O7())e0(()=>{console.warn("The OpenFeatureIntegrationHook can only be used in the browser.")})}after(){}error(){}}var iz1=a((Z)=>{if(!O7())e0(()=>{console.warn("The statsigIntegration() can only be used in the browser.")});return{name:"Statsig"}});var nz1=a((Z)=>{if(!O7())e0(()=>{console.warn("The unleashIntegration() can only be used in the browser.")});return{name:"Unleash"}});function cD(){return[pj(),tj(),XD(),QD(),WD(),VD(),HD(),qD(),wD(),ND(),PD(),kD(),ID(),xD(),hD(),YD(),bD(),$D(),mD(),dD(),OD()]}function az1(){return[Dg,Ag,xg,am,pg,lg,DD,eg,cm,Zm,Qm,Gm,Fm,wm,_m,DD,tg,jm,om,tm,Yu,$u,Ku,Sm]}var dG=r(Y0(),1),sz1=r(xb(),1),oz1=r(yb(),1),cG=r(j1(),1);var rz1=r(UR(),1);import $G6 from"module";var Gu=1e6;function lD(Z,J={}){if(Z.getOptions().debug)Lg();let X=WG6(Z,J);Z.traceProvider=X}function QG6(){let[Z=0,J=0]=process.versions.node.split(".").map(Number);if(Z>=21||Z===20&&J>=6||Z===18&&J>=19){if(!M0._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:X}=rz1.createAddHookMessageChannel();$G6.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:X,include:[]},transferList:[X]})}catch(X){h.warn("Failed to register ESM hook",X)}}else e0(()=>{console.warn(`[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`)})}function tz1(Z={}){let{debug:J}=Z;if(J)h.enable();if(!C4())QG6();KG6(Z.integrations).forEach((X)=>{if(X(),J)h.log(`[Sentry] Preloaded ${X.id} instrumentation`)})}function KG6(Z){let J=az1();if(!Z)return J;return J.filter((X)=>Z.includes(X.id))}function WG6(Z,J={}){let X=new oz1.BasicTracerProvider({sampler:new Xg(Z),resource:new sz1.Resource({[cG.ATTR_SERVICE_NAME]:"node",[cG.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[cG.ATTR_SERVICE_VERSION]:R1}),forceFlushTimeoutMillis:500,spanProcessors:[new Jg({timeout:GG6(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});return dG.trace.setGlobalTracerProvider(X),dG.propagation.setGlobalPropagator(new ob),dG.context.setGlobalContextManager(new LU),X}function GG6(Z){if(Z==null)return;if(Z>Gu)return T4&&h.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${Gu}`),Gu;else if(Z<=0||Number.isNaN(Z)){T4&&h.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function Vu(){return xj().filter((J)=>J.name!=="Http"&&J.name!=="NodeFetch").concat(hj(),yj())}function zu(Z){return[...Vu(),...u8(Z)?cD():[]]}function pD(Z={}){return ez1(Z,zu)}function ez1(Z={},J){nQ(Z,"node");let X=Ng({...Z,defaultIntegrations:Z.defaultIntegrations??J(Z)});if(X&&!Z.skipOpenTelemetrySetup)lD(X,{spanProcessors:Z.openTelemetrySpanProcessors}),DU();return X}function ZH1(Z={}){return ez1(Z,()=>[])}var NK;((B)=>{B.BUILD_PACKETS="build_packets";B.ENTITIES_EMIT_UPDATES="entities_emit_updates";B.ENTITIES_TICK="entities_tick";B.NETWORK_SYNCHRONIZE="network_synchronize";B.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";B.PHYSICS_CLEANUP="physics_cleanup";B.PHYSICS_STEP="physics_step";B.SEND_ALL_PACKETS="send_all_packets";B.SEND_PACKETS="send_packets";B.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";B.SERIALIZE_PACKETS="serialize_packets";B.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";B.SIMULATION_STEP="simulation_step";B.TICKER_TICK="ticker_tick";B.WORLD_TICK="world_tick"})(NK||={});class R8{static getProcessStats(Z=!1){let J=process.memoryUsage(),X={jsHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:J.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:J.heapUsed/J.heapTotal,unit:"percent"},processHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:J.rss/1024/1024,unit:"megabyte"}};if(Z)return X;return Object.fromEntries(Object.entries(X).map(([Y,$])=>[Y,$.value]))}static initializeSentry(Z,J=50){pD({dsn:Z,release:BA,environment:process.env.NODE_ENV||"development",tracesSampleRate:1,initialScope:{tags:{gameId:process.env.HYTOPIA_GAME_ID??"unknown",gameSlug:process.env.HYTOPIA_GAME_SLUG??"unknown",lobbyId:process.env.HYTOPIA_LOBBY_ID??"unknown",region:process.env.REGION??"unknown"}},beforeSend:(X)=>{return X.extra=R8.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let $=X?.start_timestamp,Q=X?.timestamp;if(!$||!Q)return null;if((Q-$)*1000>J)return X.measurements=R8.getProcessStats(!0),X}return null}})}static startSpan(Z,J){if(mq())return O4({attributes:Z.attributes,name:Z.operation,op:Z.operation},J);else return J()}static sentry(){return Hu}}var JH1=new e$,zG6=5000,XH1={RAW:0,GZIP:1};class Q7 extends O0{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_wrtcDirectTransport=null;_wrtcClientServerTransport=null;_wrtcClientServerDataProducers=[];_wrtcClientServerDataConsumers=[];_wrtcServerClientTransport=null;_wrtcServerClientReliableDataProducer=null;_wrtcServerClientUnreliableDataProducer=null;_wrtcServerClientDataConsumers=[];_ws;id;constructor(Z,J){super();this.id=e40(),this.onPacket(Q0.PacketId.CONNECTION,this._onConnectionPacket),this.onPacket(Q0.PacketId.HEARTBEAT,this._onHeartbeatPacket),this.bindWs(Z),O0.globalInstance.emit("CONNECTION.OPENED",{connection:this,req:J})}static clearCachedPacketsSerializedBuffers(){if(Q7._cachedPacketsSerializedBuffer.size>0)Q7._cachedPacketsSerializedBuffer.clear()}static serializePackets(Z){for(let X of Z)if(!Q0.isValidPacket(X))return c.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let J=Q7._cachedPacketsSerializedBuffer.get(Z);if(J)return J;return R8.startSpan({operation:"serialize_packets",attributes:{packets:Z.length,packetIds:Z.map((X)=>X[0]).join(",")}},(X)=>{let Y=JH1.pack(Z),$=Y.byteLength>16384,Q=$?VG6(Y,{level:1}):Y,K=$?XH1.GZIP:XH1.RAW;return Y=Buffer.allocUnsafe(Q.length+1),Y[0]=K,Q.copy(Y,1),X?.setAttribute("serializedBytes",Y.byteLength),Q7._cachedPacketsSerializedBuffer.set(Z,Y),Y})}bindWs(Z){let J=!!this._ws;if(J&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{},this.send([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{k:!0})]);if(this._ws=Z,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onWsClose,this._ws.onerror=this._onWsError,this.send([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})],!0,!0),J)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this});if(YZ.instance.isWrtcEnabled)this._upgradeToWRTC()}closeWrtc(){this._closeWrtcClientServerTransport(),this._closeWrtcServerClientTransport()}disconnect(){try{this._ws.close()}catch(Z){c.error(`Connection.disconnect(): Connection disconnect failed. Error: ${Z}`)}}onPacket(Z,J){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===Z)J(X)})}send(Z,J=!0,X=!1){if(this._closeTimeout)return;if(this._ws.readyState!==h_.default.OPEN)return;R8.startSpan({operation:"send_packets",attributes:{forceWs:X?"true":"false",wrtcConnected:this._wrtcServerClientTransport?.iceState==="completed"?"true":"false"}},()=>{try{let Y=Q7.serializePackets(Z);if(!Y)return;if(this._wrtcServerClientTransport?.iceState==="completed"&&Y.length<(this._wrtcServerClientTransport?.sctpParameters?.maxMessageSize??0)&&!X)try{(J?this._wrtcServerClientReliableDataProducer:this._wrtcServerClientUnreliableDataProducer).send(Y)}catch{this._ws.send(Y)}else this._ws.send(Y);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:Z})}catch(Y){c.error(`Connection.send(): Packet send failed. Error: ${Y}`)}})}_closeWrtcClientServerTransport(){this._wrtcDirectTransport?.close(),this._wrtcDirectTransport=null,this._wrtcClientServerTransport?.close(),this._wrtcClientServerTransport=null,this._wrtcClientServerDataProducers.forEach((Z)=>Z.close()),this._wrtcClientServerDataProducers=[],this._wrtcClientServerDataConsumers.forEach((Z)=>Z.close()),this._wrtcClientServerDataConsumers=[]}_closeWrtcServerClientTransport(){this._wrtcServerClientTransport?.close(),this._wrtcServerClientTransport=null,this._wrtcServerClientDataConsumers.forEach((Z)=>Z.close()),this._wrtcServerClientDataConsumers=[],this._wrtcServerClientReliableDataProducer?.close(),this._wrtcServerClientReliableDataProducer=null,this._wrtcServerClientUnreliableDataProducer?.close(),this._wrtcServerClientUnreliableDataProducer=null}_onConnectionPacket=async(Z)=>{let J=Z[1],X=J.c,Y=J.d;if(X){let{i:$,d:Q}=X,K=!1;if($==this._wrtcClientServerTransport?.id)await this._wrtcClientServerTransport.connect({dtlsParameters:Q}),K=!0;if($==this._wrtcServerClientTransport?.id)await this._wrtcServerClientTransport.connect({dtlsParameters:Q}),K=!0;if(K)this.send([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{ca:{i:$}})])}if(Y)for(let $ of Y){let{s:Q,l:K}=$,W=await this._wrtcClientServerTransport.produceData({label:K,sctpStreamParameters:Q}),G=await this._wrtcDirectTransport.consumeData({dataProducerId:W.id});this._wrtcClientServerDataProducers.push(W),this._wrtcClientServerDataConsumers.push(G),G.on("message",(V)=>this._onMessage(V)),this.send([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{pa:{i:W.id,l:K}})])}};_onHeartbeatPacket=()=>{this.send([Q0.createPacket(Q0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0,!0)};_onMessage=(Z)=>{try{let J=this._deserialize(Z);if(!J)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:J})}catch(J){c.error(`Connection._ws.onmessage(): Error: ${J}`)}};_onWrtcIceStateChange=(Z,J)=>{if(["disconnected","closed"].includes(J)){if(Z==this._wrtcClientServerTransport)this._closeWrtcClientServerTransport();else if(Z==this._wrtcServerClientTransport)this._closeWrtcServerClientTransport()}};_onWsClose=()=>{this.closeWrtc(),this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},zG6)};_onWsError=(Z)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:Z})};_upgradeToWRTC=async()=>{let Z=await YZ.instance.createWrtcTransports();if(!Z)return!1;let{directTransport:J,clientServerTransport:X,serverClientTransport:Y}=Z;this._wrtcDirectTransport=J,this._wrtcClientServerTransport=X,this._wrtcClientServerTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcClientServerTransport,K)}),this._wrtcServerClientTransport=Y,this._wrtcServerClientTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcServerClientTransport,K)}),this._wrtcServerClientReliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scr",sctpStreamParameters:{streamId:0,ordered:!0}}),this._wrtcServerClientUnreliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scu",sctpStreamParameters:{streamId:1,ordered:!1,maxPacketLifeTime:35}});let $=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientReliableDataProducer.id}),Q=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientUnreliableDataProducer.id});return this._wrtcServerClientDataConsumers.push($,Q),this.send([Q0.createPacket(Q0.bidirectionalPackets.connectionPacketDefinition,{d:[{i:$.id,pi:$.dataProducerId,l:"scr",s:$.sctpStreamParameters},{i:Q.id,pi:Q.dataProducerId,l:"scu",s:Q.sctpStreamParameters}],t:[{i:this._wrtcClientServerTransport.id,f:"cs",d:this._wrtcClientServerTransport.dtlsParameters,ic:this._wrtcClientServerTransport.iceCandidates,ip:this._wrtcClientServerTransport.iceParameters,s:this._wrtcClientServerTransport.sctpParameters},{i:this._wrtcServerClientTransport.id,f:"sc",d:this._wrtcServerClientTransport.dtlsParameters,ic:this._wrtcServerClientTransport.iceCandidates,ip:this._wrtcServerClientTransport.iceParameters,s:this._wrtcServerClientTransport.sctpParameters}]})]),!0};_deserialize(Z){let J=JH1.unpack(Z);if(!J||typeof J!=="object"||typeof J[0]!=="number")return c.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(J)}`);if(!Q0.isValidPacket(J))return c.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(J)}`);return J}}class rU{_lights=new Map;_nextLightId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedLights(Z){this.getAllEntityAttachedLights(Z).forEach((J)=>{J.despawn()})}getAllLights(){return Array.from(this._lights.values())}getAllEntityAttachedLights(Z){return this.getAllLights().filter((J)=>J.attachedToEntity===Z)}registerLight(Z){if(Z.id!==void 0)return Z.id;let J=this._nextLightId;return this._lights.set(J,Z),this._nextLightId++,J}unregisterLight(Z){if(Z.id===void 0)return;this._lights.delete(Z.id)}}class U6{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(Z){return this._map.get(Z)}set(Z,J){let X=this._map.has(Z);if(this._map.set(Z,J),!X)this._values.push(J);else this._isDirty=!0;return this}has(Z){return this._map.has(Z)}delete(Z){let J=this._map.delete(Z);if(J)this._isDirty=!0;return J}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(Z,J){this._map.forEach((X,Y)=>{Z.call(J,X,Y,this)})}keys(){return this._map.keys()}values(){return this._map.values()}entries(){return this._map.entries()}[Symbol.iterator](){return this._map[Symbol.iterator]()}_syncArray(){this._values.length=0;for(let Z of this._map.values())this._values.push(Z);this._isDirty=!1}}var YH1;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(YH1||={});var Fu;((H)=>{H.DESPAWN="LIGHT.DESPAWN";H.SET_ANGLE="LIGHT.SET_ANGLE";H.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";H.SET_COLOR="LIGHT.SET_COLOR";H.SET_DISTANCE="LIGHT.SET_DISTANCE";H.SET_INTENSITY="LIGHT.SET_INTENSITY";H.SET_OFFSET="LIGHT.SET_OFFSET";H.SET_PENUMBRA="LIGHT.SET_PENUMBRA";H.SET_POSITION="LIGHT.SET_POSITION";H.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";H.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";H.SPAWN="LIGHT.SPAWN"})(Fu||={});class qu extends O0{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)c.fatalError("Either attachedToEntity or position must be set, but not both.");super();c.warning("WARNING: Lights are poorly optimized at this time. Using more than a few lights in your game can cause extremely bad performance (FPS) issues. Use lights sparingly!"),this._angle=Z.angle,this._attachedToEntity=Z.attachedToEntity,this._color=Z.color??{r:255,g:255,b:255},this._distance=Z.distance,this._intensity=Z.intensity??1,this._offset=Z.offset,this._penumbra=Z.penumbra,this._position=Z.position,this._trackedEntity=Z.trackedEntity,this._trackedPosition=Z.trackedPosition,this._type=Z.type??0}get id(){return this._id}get angle(){return this._angle}get attachedToEntity(){return this._attachedToEntity}get color(){return this._color}get distance(){return this._distance}get intensity(){return this._intensity}get isSpawned(){return this._id!==void 0}get offset(){return this._offset}get penumbra(){return this._penumbra}get position(){return this._position}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get type(){return this._type}get world(){return this._world}setAngle(Z){if(this._angle===Z)return;if(this._angle=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return c.error(`Light.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:Z})}setColor(Z){if(this._color.r===Z.r&&this._color.g===Z.g&&this._color.b===Z.b)return;if(this._color=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:Z})}setDistance(Z){if(this._distance===Z)return;if(this._distance=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:Z})}setIntensity(Z){if(this._intensity===Z)return;if(this._intensity=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:Z})}setPenumbra(Z){if(this._penumbra===Z)return;if(this._penumbra=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:Z})}setTrackedEntity(Z){if(!Z.isSpawned)return c.error(`Light.setTrackedEntity(): Entity ${Z.id} is not spawned!`);if(this._trackedEntity===Z)return;if(this._trackedEntity=Z,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:Z})}setTrackedPosition(Z){if(this._trackedPosition===Z)return;if(this._trackedPosition=Z,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.lightManager.unregisterLight(this),this.emitWithWorld(this._world,"LIGHT.DESPAWN",{light:this}),this._id=void 0,this._world=void 0}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return c.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=Z.lightManager.registerLight(this),this._world=Z,this.emitWithWorld(Z,"LIGHT.SPAWN",{light:this})}serialize(){return k0.serializeLight(this)}}var Uu;((u)=>{u.BURST="PARTICLE_EMITTER.BURST";u.DESPAWN="PARTICLE_EMITTER.DESPAWN";u.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";u.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";u.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";u.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";u.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";u.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";u.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";u.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";u.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";u.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";u.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";u.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";u.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";u.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";u.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";u.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";u.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";u.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";u.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";u.SET_RATE="PARTICLE_EMITTER.SET_RATE";u.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";u.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";u.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";u.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";u.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";u.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";u.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";u.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";u.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";u.SPAWN="PARTICLE_EMITTER.SPAWN"})(Uu||={});class Bu extends O0{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)c.fatalError("Either attachedToEntity or position must be set, but not both.");if(!Z.textureUri)c.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=Z.alphaTest??0.5,this._attachedToEntity=Z.attachedToEntity,this._attachedToEntityNodeName=Z.attachedToEntityNodeName,this._colorEnd=Z.colorEnd,this._colorEndVariance=Z.colorEndVariance,this._colorStart=Z.colorStart,this._colorStartVariance=Z.colorStartVariance,this._gravity=Z.gravity,this._lifetime=Z.lifetime,this._lifetimeVariance=Z.lifetimeVariance,this._maxParticles=Z.maxParticles,this._offset=Z.offset,this._opacityEnd=Z.opacityEnd,this._opacityEndVariance=Z.opacityEndVariance,this._opacityStart=Z.opacityStart,this._opacityStartVariance=Z.opacityStartVariance,this._paused=!1,this._position=Z.position,this._positionVariance=Z.positionVariance,this._rate=Z.rate,this._rateVariance=Z.rateVariance,this._sizeEnd=Z.sizeEnd,this._sizeEndVariance=Z.sizeEndVariance,this._sizeStart=Z.sizeStart,this._sizeStartVariance=Z.sizeStartVariance,this._textureUri=Z.textureUri,this._transparent=Z.transparent,this._velocity=Z.velocity,this._velocityVariance=Z.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(Z){if(this._alphaTest===Z)return;if(this._alphaTest=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return c.error(`ParticleEmitter.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:Z})}setAttachedToEntityNodeName(Z){if(this._attachedToEntityNodeName===Z)return;if(this._attachedToEntityNodeName=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:Z})}setColorEnd(Z){if(this._colorEnd&&this._colorEnd.r===Z.r&&this._colorEnd.g===Z.g&&this._colorEnd.b===Z.b)return;if(this._colorEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:Z})}setColorEndVariance(Z){if(this._colorEndVariance&&this._colorEndVariance.r===Z.r&&this._colorEndVariance.g===Z.g&&this._colorEndVariance.b===Z.b)return;if(this._colorEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:Z})}setColorStart(Z){if(this._colorStart&&this._colorStart.r===Z.r&&this._colorStart.g===Z.g&&this._colorStart.b===Z.b)return;if(this._colorStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:Z})}setColorStartVariance(Z){if(this._colorStartVariance&&this._colorStartVariance.r===Z.r&&this._colorStartVariance.g===Z.g&&this._colorStartVariance.b===Z.b)return;if(this._colorStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:Z})}setGravity(Z){if(this._gravity&&this._gravity.x===Z.x&&this._gravity.y===Z.y&&this._gravity.z===Z.z)return;if(this._gravity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:Z})}setLifetime(Z){if(this._lifetime===Z)return;if(this._lifetime=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:Z})}setLifetimeVariance(Z){if(this._lifetimeVariance===Z)return;if(this._lifetimeVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:Z})}setMaxParticles(Z){if(this._maxParticles===Z)return;if(this._maxParticles=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:Z})}setOpacityEnd(Z){if(this._opacityEnd===Z)return;if(this._opacityEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:Z})}setOpacityEndVariance(Z){if(this._opacityEndVariance===Z)return;if(this._opacityEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:Z})}setOpacityStart(Z){if(this._opacityStart===Z)return;if(this._opacityStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:Z})}setOpacityStartVariance(Z){if(this._opacityStartVariance===Z)return;if(this._opacityStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:Z})}setPositionVariance(Z){if(this._positionVariance&&this._positionVariance.x===Z.x&&this._positionVariance.y===Z.y&&this._positionVariance.z===Z.z)return;if(this._positionVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:Z})}setRate(Z){if(this._rate===Z)return;if(this._rate=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:Z})}setRateVariance(Z){if(this._rateVariance===Z)return;if(this._rateVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:Z})}setSizeEnd(Z){if(this._sizeEnd===Z)return;if(this._sizeEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:Z})}setSizeEndVariance(Z){if(this._sizeEndVariance===Z)return;if(this._sizeEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:Z})}setSizeStart(Z){if(this._sizeStart===Z)return;if(this._sizeStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:Z})}setSizeStartVariance(Z){if(this._sizeStartVariance===Z)return;if(this._sizeStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:Z})}setTextureUri(Z){if(this._textureUri===Z)return;if(this._textureUri=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:Z})}setTransparent(Z){if(this._transparent===Z)return;if(this._transparent=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:Z})}setVelocity(Z){if(this._velocity&&this._velocity.x===Z.x&&this._velocity.y===Z.y&&this._velocity.z===Z.z)return;if(this._velocity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:Z})}setVelocityVariance(Z){if(this._velocityVariance&&this._velocityVariance.x===Z.x&&this._velocityVariance.y===Z.y&&this._velocityVariance.z===Z.z)return;if(this._velocityVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:Z})}burst(Z){if(this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.BURST",{particleEmitter:this,count:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return c.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=Z.particleEmitterManager.registerParticleEmitter(this),this._world=Z,this.emitWithWorld(Z,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){return k0.serializeParticleEmitter(this)}}var tU=r(_V(),1);var HG6={x:0,y:-32,z:0},Lu=60,wu;(($)=>{$.STEP_START="SIMULATION.STEP_START";$.STEP_END="SIMULATION.STEP_END";$.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";$.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(wu||={});class eU extends O0{_colliderMap=new NH;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(Z,J=Lu,X=HG6){super();this._rapierEventQueue=new tU.default.EventQueue(!0),this._rapierSimulation=new tU.default.World(X),this._rapierSimulation.timestep=Math.fround(1/J),this._world=Z}get colliderMap(){return this._colliderMap}get isDebugRaycastingEnabled(){return this._debugRaycastingEnabled}get isDebugRenderingEnabled(){return this._debugRenderingEnabled}get gravity(){return this._rapierSimulation.gravity}get timestepS(){return this._rapierSimulation.timestep}get world(){return this._world}createRawCollider(Z,J){return this._rapierSimulation.createCollider(Z,J)}createRawRigidBody(Z){return this._rapierSimulation.createRigidBody(Z)}enableDebugRaycasting(Z){this._debugRaycastingEnabled=Z}enableDebugRendering(Z,J=tU.default.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=Z,this._debugRenderingFilterFlags=J}getContactManifolds(Z,J){let X=[];return this._rapierSimulation.narrowPhase.contactPair(Z,J,(Y,$)=>{if(Y.numContacts()===0)return;let Q=Y.normal(),K=[];for(let W=0;W<Y.numSolverContacts();W++)K.push(Y.solverContactPoint(W));X.push({contactPoints:K,localNormalA:!$?Y.localNormal1():Y.localNormal2(),localNormalB:!$?Y.localNormal2():Y.localNormal1(),normal:!$?Q:{x:-Q.x,y:-Q.y,z:-Q.z}})}),X}intersectionsWithRawShape(Z,J,X,Y={}){let $=new Set,Q=[];return this._rapierSimulation.intersectionsWithShape(J,X,Z,(K)=>{let W=this._colliderMap.getColliderHandleBlockType(K.handle);if(W&&!$.has(W))return $.add(W),Q.push({intersectedBlockType:W}),!0;let G=this._colliderMap.getColliderHandleEntity(K.handle);if(G&&!$.has(G))return $.add(G),Q.push({intersectedEntity:G}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),Q}raycast(Z,J,X,Y={}){let $=new tU.default.Ray(Z,J),Q=this._rapierSimulation.castRay($,X,Y.solidMode??!0,Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate);if(this._debugRaycastingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RAYCAST",{simulation:this,origin:Z,direction:J,length:X,hit:!!Q});if(!Q)return null;let K=$.pointAt(Q.timeOfImpact),W=Q.timeOfImpact,G=Q.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:IK.fromGlobalCoordinate({x:Math.floor(K.x-($.dir.x<0?0.0001:-0.0001)),y:Math.floor(K.y-($.dir.y<0?0.0001:-0.0001)),z:Math.floor(K.z-($.dir.z<0?0.0001:-0.0001))},V),hitPoint:K,hitDistance:W};let z=this._colliderMap.getColliderHandleEntity(G.handle);if(z)return{hitEntity:z,hitPoint:K,hitDistance:W};return null}removeRawCollider(Z){this._colliderMap.queueColliderHandleForCleanup(Z.handle),this._rapierSimulation.removeCollider(Z,!1)}removeRawRigidBody(Z){this._rapierSimulation.removeRigidBody(Z)}setGravity(Z){this._rapierSimulation.gravity=Z}step=(Z)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:Z});let J=performance.now();if(R8.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),R8.startSpan({operation:"physics_cleanup"},()=>{this._rapierEventQueue.drainContactForceEvents(this._onContactForceEvent),this._rapierEventQueue.drainCollisionEvents(this._onCollisionEvent),this._colliderMap.cleanup()}),this.emitWithWorld(this._world,"SIMULATION.STEP_END",{simulation:this,stepDurationMs:performance.now()-J}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(Z,J,X)=>{let[Y,$]=this._getCollisionObjects(Z,J);if(!Y||!$)return;let Q=(K,W)=>{if(K instanceof q9&&W instanceof a8&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof a8&&W instanceof q9&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof a8&&W instanceof a8&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(typeof K==="function"&&(W instanceof a8||W instanceof q9))K(W,X,Z,J)};Q(Y,$),Q($,Y)};_onContactForceEvent=(Z)=>{let[J,X]=this._getCollisionObjects(Z.collider1(),Z.collider2());if(!J||typeof J==="function"||!X||typeof X==="function")return;let Y={totalForce:Z.totalForce(),totalForceMagnitude:Z.totalForceMagnitude(),maxForceDirection:Z.maxForceDirection(),maxForceMagnitude:Z.maxForceMagnitude()},$=(Q,K)=>{if(Q instanceof q9&&K instanceof a8&&Q.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))Q.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:Q,entity:K,contactForceData:Y});else if(Q instanceof a8&&K instanceof q9&&Q.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))Q.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:Q,blockType:K,contactForceData:Y});else if(Q instanceof a8&&K instanceof a8&&Q.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Q.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:Q,otherEntity:K,contactForceData:Y})};$(J,X),$(X,J)};_getCollisionObjects(Z,J){let X=this._colliderMap.getColliderHandleBlockType(Z)??this._colliderMap.getColliderHandleCollisionCallback(Z)??this._colliderMap.getColliderHandleEntity(Z),Y=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J);return[X,Y]}}class iD{_synchronizedPlayerReliablePackets=new U6;_queuedBroadcasts=[];_queuedAudioSynchronizations=new U6;_queuedBlockSynchronizations=new U6;_queuedBlockTypeSynchronizations=new U6;_queuedChunkSynchronizations=new U6;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new U6;_queuedLightSynchronizations=new U6;_queuedParticleEmitterSynchronizations=new U6;_queuedPerPlayerSynchronizations=new U6;_queuedPerPlayerCameraSynchronizations=new U6;_queuedPerPlayerUISynchronizations=new U6;_queuedPerPlayerUIDatasSynchronizations=new U6;_queuedPlayerSynchronizations=new U6;_queuedSceneUISynchronizations=new U6;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(Z){this._world=Z,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let Z=[],J=[],X=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(...$);if(this._queuedEntitySynchronizations.size>0){let Y=[],$=[];for(let Q of this._queuedEntitySynchronizations.valuesArray){let K=!1;for(let W in Q)if(W!=="i"&&W!=="p"&&W!=="r"){K=!0;break}if(K)Y.push(Q);else $.push(Q)}if($.length>0){let Q=Q0.createPacket(Q0.outboundPackets.entitiesPacketDefinition,$,X);J.push(Q)}if(Y.length>0){let Q=Q0.createPacket(Q0.outboundPackets.entitiesPacketDefinition,Y,X);Z.push(Q);for(let K of this._synchronizedPlayerReliablePackets.valuesArray)K.push(Q)}}if(this._queuedAudioSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBlockTypeSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedChunkSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBlockSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedLightSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedParticleEmitterSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerUISynchronizations){let Q=Q0.createPacket(Q0.outboundPackets.uiPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerUIDatasSynchronizations){let Q=Q0.createPacket(Q0.outboundPackets.uiDatasPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedSceneUISynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedWorldSynchronization){let Y=Q0.createPacket(Q0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerCameraSynchronizations){let Q=Q0.createPacket(Q0.outboundPackets.cameraPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedPlayerSynchronizations.size>0){let Y=Q0.createPacket(Q0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBroadcasts.length>0)for(let Y of this._queuedBroadcasts){Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedDebugRaycastSynchronizations.length>0){let Y=Q0.createPacket(Q0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}R8.startSpan({operation:"send_all_packets"},()=>{for(let Y of N9.instance.getConnectedPlayersByWorld(this._world)){let $=this._synchronizedPlayerReliablePackets.get(Y)??Z;if($.length>0)Y.connection.send($);if(J.length>0)Y.connection.send(J,!1)}}),R8.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts.length=0;if(this._queuedAudioSynchronizations.size>0)this._queuedAudioSynchronizations.clear();if(this._queuedBlockSynchronizations.size>0)this._queuedBlockSynchronizations.clear();if(this._queuedBlockTypeSynchronizations.size>0)this._queuedBlockTypeSynchronizations.clear();if(this._queuedChunkSynchronizations.size>0)this._queuedChunkSynchronizations.clear();if(this._queuedDebugRaycastSynchronizations.length>0)this._queuedDebugRaycastSynchronizations.length=0;if(this._queuedEntitySynchronizations.size>0)this._queuedEntitySynchronizations.clear();if(this._queuedLightSynchronizations.size>0)this._queuedLightSynchronizations.clear();if(this._queuedParticleEmitterSynchronizations.size>0)this._queuedParticleEmitterSynchronizations.clear();if(this._queuedPerPlayerSynchronizations.size>0)this._queuedPerPlayerSynchronizations.clear();if(this._queuedPerPlayerCameraSynchronizations.size>0)this._queuedPerPlayerCameraSynchronizations.clear();if(this._queuedPerPlayerUISynchronizations.size>0)this._queuedPerPlayerUISynchronizations.clear();if(this._queuedPerPlayerUIDatasSynchronizations.size>0)this._queuedPerPlayerUIDatasSynchronizations.clear();if(this._queuedPlayerSynchronizations.size>0)this._queuedPlayerSynchronizations.clear();if(this._queuedSceneUISynchronizations.size>0)this._queuedSceneUISynchronizations.clear();if(this._queuedWorldSynchronization)this._queuedWorldSynchronization=void 0;if(this._loadedSceneUIs.size>0)this._loadedSceneUIs.clear();if(this._spawnedChunks.size>0)this._spawnedChunks.clear();if(this._spawnedEntities.size>0)this._spawnedEntities.clear();if(this._synchronizedPlayerReliablePackets.size>0)this._synchronizedPlayerReliablePackets.clear();Q7.clearCachedPacketsSerializedBuffers()})}_subscribeToAudioEvents(){this._world.final("AUDIO.PAUSE",this._onAudioPause),this._world.final("AUDIO.PLAY",this._onAudioPlay),this._world.final("AUDIO.PLAY_RESTART",this._onAudioPlayRestart),this._world.final("AUDIO.SET_ATTACHED_TO_ENTITY",this._onAudioSetAttachedToEntity),this._world.final("AUDIO.SET_CUTOFF_DISTANCE",this._onAudioSetCutoffDistance),this._world.final("AUDIO.SET_DETUNE",this._onAudioSetDetune),this._world.final("AUDIO.SET_DISTORTION",this._onAudioSetDistortion),this._world.final("AUDIO.SET_POSITION",this._onAudioSetPosition),this._world.final("AUDIO.SET_PLAYBACK_RATE",this._onAudioSetPlaybackRate),this._world.final("AUDIO.SET_REFERENCE_DISTANCE",this._onAudioSetReferenceDistance),this._world.final("AUDIO.SET_VOLUME",this._onAudioSetVolume)}_subscribeToBlockTypeRegistryEvents(){this._world.final("BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",this._onBlockTypeRegistryRegisterBlockType)}_subscribeToChatEvents(){this._world.final("CHAT.BROADCAST_MESSAGE",this._onChatSendBroadcastMessage),this._world.final("CHAT.PLAYER_MESSAGE",this._onChatSendPlayerMessage)}_subscribeToChunkLatticeEvents(){this._world.final("CHUNK_LATTICE.ADD_CHUNK",this._onChunkLatticeAddChunk),this._world.final("CHUNK_LATTICE.REMOVE_CHUNK",this._onChunkLatticeRemoveChunk),this._world.final("CHUNK_LATTICE.SET_BLOCK",this._onChunkLatticeSetBlock)}_subscribeToEntityEvents(){this._world.final("ENTITY.SPAWN",this._onEntitySpawn),this._world.final("ENTITY.DESPAWN",this._onEntityDespawn),this._world.final("ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",this._onEntitySetModelAnimationsPlaybackRate),this._world.final("ENTITY.SET_MODEL_HIDDEN_NODES",this._onEntitySetModelHiddenNodes),this._world.final("ENTITY.SET_MODEL_SCALE",this._onEntitySetModelScale),this._world.final("ENTITY.SET_MODEL_SHOWN_NODES",this._onEntitySetModelShownNodes),this._world.final("ENTITY.SET_MODEL_TEXTURE_URI",this._onEntitySetModelTextureUri),this._world.final("ENTITY.SET_OPACITY",this._onEntitySetOpacity),this._world.final("ENTITY.SET_PARENT",this._onEntitySetParent),this._world.final("ENTITY.SET_TINT_COLOR",this._onEntitySetTintColor),this._world.final("ENTITY.START_MODEL_LOOPED_ANIMATIONS",this._onEntityStartModelLoopedAnimations),this._world.final("ENTITY.START_MODEL_ONESHOT_ANIMATIONS",this._onEntityStartModelOneshotAnimations),this._world.final("ENTITY.STOP_MODEL_ANIMATIONS",this._onEntityStopModelAnimations),this._world.final("ENTITY.UPDATE_POSITION",this._onEntityUpdatePosition),this._world.final("ENTITY.UPDATE_ROTATION",this._onEntityUpdateRotation)}_subscribeToLightEvents(){this._world.final("LIGHT.DESPAWN",this._onLightDespawn),this._world.final("LIGHT.SET_ANGLE",this._onLightSetAngle),this._world.final("LIGHT.SET_ATTACHED_TO_ENTITY",this._onLightSetAttachedToEntity),this._world.final("LIGHT.SET_COLOR",this._onLightSetColor),this._world.final("LIGHT.SET_DISTANCE",this._onLightSetDistance),this._world.final("LIGHT.SET_INTENSITY",this._onLightSetIntensity),this._world.final("LIGHT.SET_OFFSET",this._onLightSetOffset),this._world.final("LIGHT.SET_PENUMBRA",this._onLightSetPenumbra),this._world.final("LIGHT.SET_POSITION",this._onLightSetPosition),this._world.final("LIGHT.SET_TRACKED_ENTITY",this._onLightSetTrackedEntity),this._world.final("LIGHT.SET_TRACKED_POSITION",this._onLightSetTrackedPosition),this._world.final("LIGHT.SPAWN",this._onLightSpawn)}_subscribeToParticleEmitterEvents(){this._world.final("PARTICLE_EMITTER.DESPAWN",this._onParticleEmitterDespawn),this._world.final("PARTICLE_EMITTER.BURST",this._onParticleEmitterBurst),this._world.final("PARTICLE_EMITTER.SET_ALPHA_TEST",this._onParticleEmitterSetAlphaTest),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",this._onParticleEmitterSetAttachedToEntity),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",this._onParticleEmitterSetAttachedToEntityNodeName),this._world.final("PARTICLE_EMITTER.SET_COLOR_END",this._onParticleEmitterSetColorEnd),this._world.final("PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",this._onParticleEmitterSetColorEndVariance),this._world.final("PARTICLE_EMITTER.SET_COLOR_START",this._onParticleEmitterSetColorStart),this._world.final("PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",this._onParticleEmitterSetColorStartVariance),this._world.final("PARTICLE_EMITTER.SET_GRAVITY",this._onParticleEmitterSetGravity),this._world.final("PARTICLE_EMITTER.SET_LIFETIME",this._onParticleEmitterSetLifetime),this._world.final("PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",this._onParticleEmitterSetLifetimeVariance),this._world.final("PARTICLE_EMITTER.SET_MAX_PARTICLES",this._onParticleEmitterSetMaxParticles),this._world.final("PARTICLE_EMITTER.SET_OFFSET",this._onParticleEmitterSetOffset),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END",this._onParticleEmitterSetOpacityEnd),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",this._onParticleEmitterSetOpacityEndVariance),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START",this._onParticleEmitterSetOpacityStart),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",this._onParticleEmitterSetOpacityStartVariance),this._world.final("PARTICLE_EMITTER.SET_PAUSED",this._onParticleEmitterSetPaused),this._world.final("PARTICLE_EMITTER.SET_POSITION",this._onParticleEmitterSetPosition),this._world.final("PARTICLE_EMITTER.SET_POSITION_VARIANCE",this._onParticleEmitterSetPositionVariance),this._world.final("PARTICLE_EMITTER.SET_RATE",this._onParticleEmitterSetRate),this._world.final("PARTICLE_EMITTER.SET_RATE_VARIANCE",this._onParticleEmitterSetRateVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_END",this._onParticleEmitterSetSizeEnd),this._world.final("PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",this._onParticleEmitterSetSizeEndVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_START",this._onParticleEmitterSetSizeStart),this._world.final("PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",this._onParticleEmitterSetSizeStartVariance),this._world.final("PARTICLE_EMITTER.SET_TEXTURE_URI",this._onParticleEmitterSetTextureUri),this._world.final("PARTICLE_EMITTER.SET_TRANSPARENT",this._onParticleEmitterSetTransparent),this._world.final("PARTICLE_EMITTER.SET_VELOCITY",this._onParticleEmitterSetVelocity),this._world.final("PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",this._onParticleEmitterSetVelocityVariance),this._world.final("PARTICLE_EMITTER.SPAWN",this._onParticleEmitterSpawn)}_subscribeToPlayerEvents(){this._world.final("PLAYER.JOINED_WORLD",this._onPlayerJoinedWorld),this._world.final("PLAYER.LEFT_WORLD",this._onPlayerLeftWorld),this._world.final("PLAYER.RECONNECTED_WORLD",this._onPlayerReconnectedWorld),this._world.final("PLAYER.REQUEST_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity)}_onAudioPause=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pa=!0,delete J.pl,delete J.r};_onAudioPlay=(Z)=>{let J=Z.audio.serialize();J.pl=!0,delete J.pa,delete J.r,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioPlayRestart=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.r=!0,delete J.pa,delete J.pl,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onAudioSetCutoffDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.cd=Z.cutoffDistance};_onAudioSetDetune=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.de=Z.detune};_onAudioSetDistortion=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.di=Z.distortion};_onAudioSetPosition=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.position?void 0:J.e,J.p=Z.position?k0.serializeVector(Z.position):void 0};_onAudioSetPlaybackRate=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pr=Z.playbackRate};_onAudioSetReferenceDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.rd=Z.referenceDistance};_onAudioSetVolume=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.v=Z.volume};_onBlockTypeRegistryRegisterBlockType=(Z)=>{let J=Z.blockType.serialize();this._queuedBlockTypeSynchronizations.set(Z.blockType.id,J)};_onChatSendBroadcastMessage=(Z)=>{let{player:J,message:X,color:Y}=Z;this._queuedBroadcasts.push(Q0.createPacket(Q0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y,p:J?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(Z)=>{let{player:J,message:X,color:Y}=Z,$=this._queuedPerPlayerSynchronizations.get(J)??[];$.push(Q0.createPacket(Q0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set(J,$)};_onChunkLatticeAddChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk);J.b=Array.from(Z.chunk.blocks),J.rm=void 0,this._spawnedChunks.add(J.c.join(","))};_onChunkLatticeRemoveChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk),X=J.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else J.rm=!0};_onChunkLatticeSetBlock=(Z)=>{let J=this._createOrGetQueuedBlockSync(Z.globalCoordinate);J.i=Z.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.ap=Z.playbackRate};_onEntitySpawn=(Z)=>{let J=Z.entity.serialize();this._queuedEntitySynchronizations.set(J.i,J),this._spawnedEntities.add(J.i)};_onEntityDespawn=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(this._spawnedEntities.has(J.i))this._queuedEntitySynchronizations.delete(J.i),this._spawnedEntities.delete(J.i);else J.rm=!0};_onEntitySetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.h=Array.from(Z.modelHiddenNodes)};_onEntitySetModelScale=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.s=Z.modelScale};_onEntitySetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.sn=Array.from(Z.modelShownNodes)};_onEntitySetModelTextureUri=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.mt=Z.modelTextureUri};_onEntitySetOpacity=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.o=Z.opacity};_onEntitySetParent=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.pe=Z.parent?Z.parent.id:void 0,J.pn=Z.parentNodeName};_onEntitySetTintColor=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.t=Z.tintColor?k0.serializeRgbColor(Z.tintColor):void 0};_onEntityStartModelLoopedAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al=Array.from(new Set([...J.al??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.ao=Array.from(new Set([...J.ao??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStopModelAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al)J.al=J.al.filter((X)=>!Z.animations.has(X)).filter(Boolean);if(J.ao)J.ao=J.ao.filter((X)=>!Z.animations.has(X)).filter(Boolean);J.as=Array.from(new Set([...J.as??[],...Z.animations]))};_onEntityUpdateRotation=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.r=[Z.rotation.x,Z.rotation.y,Z.rotation.z,Z.rotation.w]};_onEntityUpdatePosition=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.p=[Z.position.x,Z.position.y,Z.position.z]};_onLightDespawn=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.rm=!0};_onLightSetAngle=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.a=Z.angle};_onLightSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onLightSetColor=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.c=k0.serializeRgbColor(Z.color)};_onLightSetDistance=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.d=Z.distance};_onLightSetIntensity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.n=Z.intensity};_onLightSetOffset=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.o=Z.offset?k0.serializeVector(Z.offset):void 0};_onLightSetPenumbra=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.pe=Z.penumbra};_onLightSetPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.p=Z.position?k0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e};_onLightSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.te=Z.entity?Z.entity.id:void 0,J.tp=Z.entity?void 0:J.tp};_onLightSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.tp=Z.position?k0.serializeVector(Z.position):void 0,J.te=Z.position?void 0:J.te};_onLightSpawn=(Z)=>{let J=Z.light.serialize();this._queuedLightSynchronizations.set(J.i,J)};_onParticleEmitterBurst=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.b=Z.count};_onParticleEmitterDespawn=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rm=!0};_onParticleEmitterSetAlphaTest=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.at=Z.alphaTest};_onParticleEmitterSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onParticleEmitterSetAttachedToEntityNodeName=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.en=Z.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ce=Z.colorEnd?k0.serializeRgbColor(Z.colorEnd):void 0};_onParticleEmitterSetColorEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cev=Z.colorEndVariance?k0.serializeRgbColor(Z.colorEndVariance):void 0};_onParticleEmitterSetColorStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cs=Z.colorStart?k0.serializeRgbColor(Z.colorStart):void 0};_onParticleEmitterSetColorStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.csv=Z.colorStartVariance?k0.serializeRgbColor(Z.colorStartVariance):void 0};_onParticleEmitterSetGravity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.g=Z.gravity?k0.serializeVector(Z.gravity):void 0};_onParticleEmitterSetLifetime=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.l=Z.lifetime};_onParticleEmitterSetLifetimeVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.lv=Z.lifetimeVariance};_onParticleEmitterSetMaxParticles=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.mp=Z.maxParticles};_onParticleEmitterSetOffset=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.o=Z.offset?k0.serializeVector(Z.offset):void 0};_onParticleEmitterSetOpacityEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oe=Z.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oev=Z.opacityEndVariance};_onParticleEmitterSetOpacityStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.os=Z.opacityStart};_onParticleEmitterSetOpacityStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.osv=Z.opacityStartVariance};_onParticleEmitterSetPaused=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pa=Z.paused};_onParticleEmitterSetPosition=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.p=Z.position?k0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e,J.en=Z.position?void 0:J.en};_onParticleEmitterSetPositionVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pv=Z.positionVariance?k0.serializeVector(Z.positionVariance):void 0};_onParticleEmitterSetRate=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.r=Z.rate};_onParticleEmitterSetRateVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rv=Z.rateVariance};_onParticleEmitterSetSizeEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.se=Z.sizeEnd};_onParticleEmitterSetSizeEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.sev=Z.sizeEndVariance};_onParticleEmitterSetSizeStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ss=Z.sizeStart};_onParticleEmitterSetSizeStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ssv=Z.sizeStartVariance};_onParticleEmitterSetTextureUri=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.tu=Z.textureUri};_onParticleEmitterSetTransparent=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.t=Z.transparent};_onParticleEmitterSetVelocity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.v=Z.velocity?k0.serializeVector(Z.velocity):void 0};_onParticleEmitterSetVelocityVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.vv=Z.velocityVariance?k0.serializeVector(Z.velocityVariance):void 0};_onParticleEmitterSpawn=(Z)=>{let J=Z.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set(J.i,J)};_onPlayerCameraLookAtEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=k0.serializeVector(Z.entity.position),delete J.et,delete J.pt};_onPlayerCameraLookAtPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=Z.position?k0.serializeVector(Z.position):void 0,delete J.et,delete J.pt};_onPlayerCameraSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.e=Z.entity.id,delete J.p};_onPlayerCameraSetAttachedToPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.p=Z.position?k0.serializeVector(Z.position):void 0,delete J.e};_onPlayerCameraSetFilmOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fo=Z.filmOffset};_onPlayerCameraSetForwardOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.ffo=Z.forwardOffset};_onPlayerCameraSetFov=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fv=Z.fov};_onPlayerCameraSetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.h=Array.from(Z.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.s=Array.from(Z.modelShownNodes)};_onPlayerCameraSetMode=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.m=Z.mode};_onPlayerCameraSetOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.o=Z.offset?k0.serializeVector(Z.offset):void 0};_onPlayerCameraSetShoulderAngle=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.sa=Z.shoulderAngle};_onPlayerCameraSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.et=Z.entity?Z.entity.id:void 0,delete J.pl,delete J.pt};_onPlayerCameraSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pt=Z.position?k0.serializeVector(Z.position):void 0,delete J.et,delete J.pl};_onPlayerCameraSetZoom=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.z=Z.zoom};_onPlayerJoinedWorld=(Z)=>{let{player:J}=Z,X=this._queuedPerPlayerSynchronizations.get(J)??[];X.push(Q0.createPacket(Q0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map(($)=>{if(J.camera.attachedToEntity===void 0&&$ instanceof i7&&$.player===J)J.camera.setAttachedToEntity($);return $.serialize()}),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.particleEmittersPacketDefinition,this._world.particleEmitterManager.getAllParticleEmitters().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(Q0.createPacket(Q0.outboundPackets.playersPacketDefinition,N9.instance.getConnectedPlayers().map(($)=>$.serialize()),this._world.loop.currentTick));let Y=this._createOrGetQueuedPlayerCameraSync(J.camera);this._queuedPerPlayerCameraSynchronizations.set(J,{...J.camera.serialize(),...Y}),this._queuedPerPlayerSynchronizations.set(J,X),this._queuedPlayerSynchronizations.set(J.id,J.serialize())};_onPlayerLeftWorld=(Z)=>{let J=this._createOrGetQueuedPlayerSync(Z.player);J.rm=!0};_onPlayerReconnectedWorld=(Z)=>{this._onPlayerJoinedWorld(Z)};_onPlayerRequestSync=(Z)=>{Z.player.connection.send([Q0.createPacket(Q0.outboundPackets.syncResponsePacketDefinition,{r:Z.receivedAt,s:Date.now(),p:performance.now()-Z.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_onPlayerUILoad=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.u=Z.htmlUri};_onPlayerUILockPointer=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.p=Z.lock};_onPlayerUISendData=(Z)=>{this._createOrGetQueuedPlayerUIDatasSync(Z.playerUI).push(Z.data)};_onSceneUILoad=(Z)=>{let J=Z.sceneUI.serialize();this._queuedSceneUISynchronizations.set(J.i,J),this._loadedSceneUIs.add(J.i)};_onSceneUISetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onSceneUISetOffset=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.o=Z.offset?k0.serializeVector(Z.offset):void 0};_onSceneUISetPosition=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.p=Z.position?k0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e};_onSceneUISetState=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.s=Z.state};_onSceneUISetViewDistance=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.v=Z.viewDistance};_onSceneUIUnload=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);if(this._loadedSceneUIs.has(J.i))this._queuedSceneUISynchronizations.delete(J.i),this._loadedSceneUIs.delete(J.i);else J.rm=!0};_onSimulationDebugRaycast=(Z)=>{this._queuedDebugRaycastSynchronizations.push(k0.serializePhysicsDebugRaycast(Z))};_onSimulationDebugRender=(Z)=>{this._queuedBroadcasts.push(Q0.createPacket(Q0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(Z.vertices),c:Array.from(Z.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ac=k0.serializeRgbColor(Z.color)};_onWorldSetAmbientLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ai=Z.intensity};_onWorldSetDirectionalLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dc=k0.serializeRgbColor(Z.color)};_onWorldSetDirectionalLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.di=Z.intensity};_onWorldSetDirectionalLightPosition=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dp=k0.serializeVector(Z.position)};_onWorldSetFogColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fc=k0.serializeRgbColor(Z.color)};_onWorldSetFogFar=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ff=Z.far};_onWorldSetFogNear=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fn=Z.near};_onWorldSetSkyboxIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.si=Z.intensity};_createOrGetQueuedAudioSync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let J=this._queuedAudioSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedAudioSynchronizations.set(Z.id,J);return J}_createOrGetQueuedBlockSync(Z){let{x:J,y:X,z:Y}=Z,$=`${J},${X},${Y}`,Q=this._queuedBlockSynchronizations.get($);if(!Q)Q={i:0,c:[J,X,Y]},this._queuedBlockSynchronizations.set($,Q);return Q}_createOrGetQueuedChunkSync(Z){if(!Z.originCoordinate)c.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:J,y:X,z:Y}=Z.originCoordinate,$=`${J},${X},${Y}`,Q=this._queuedChunkSynchronizations.get($);if(!Q)Q={c:[J,X,Y]},this._queuedChunkSynchronizations.set($,Q);return Q}_createOrGetQueuedEntitySync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let J=this._queuedEntitySynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedEntitySynchronizations.set(Z.id,J);return J}_createOrGetQueuedLightSync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let J=this._queuedLightSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedLightSynchronizations.set(Z.id,J);return J}_createOrGetQueuedParticleEmitterSync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let J=this._queuedParticleEmitterSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedParticleEmitterSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerSync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let J=this._queuedPlayerSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedPlayerSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerCameraSync(Z){let J=this._queuedPerPlayerCameraSynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerCameraSynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUISync(Z){let J=this._queuedPerPlayerUISynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerUISynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUIDatasSync(Z){let J=this._queuedPerPlayerUIDatasSynchronizations.get(Z.player);if(!J)J=[],this._queuedPerPlayerUIDatasSynchronizations.set(Z.player,J);return J}_createOrGetQueuedSceneUISync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let J=this._queuedSceneUISynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedSceneUISynchronizations.set(Z.id,J);return J}_createOrGetQueuedWorldSync(Z){if(Z.id!==this._world.id)c.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:Z.id}}_createOrGetSynchronizedPlayerReliablePackets(Z,J){let X=this._synchronizedPlayerReliablePackets.get(Z);if(!X)X=[...J],this._synchronizedPlayerReliablePackets.set(Z,X);return X}}class Z2{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedParticleEmitters(Z){this.getAllEntityAttachedParticleEmitters(Z).forEach((J)=>{J.despawn()})}getAllParticleEmitters(){return Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(Z){return this.getAllParticleEmitters().filter((J)=>J.attachedToEntity===Z)}registerParticleEmitter(Z){if(Z.id!==void 0)return Z.id;let J=this._nextParticleEmitterId;return this._particleEmitters.set(J,Z),this._nextParticleEmitterId++,J}unregisterParticleEmitter(Z){if(Z.id===void 0)return;this._particleEmitters.delete(Z.id)}}class J2{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}getAllSceneUIs(){return Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(Z){return this.getAllSceneUIs().filter((J)=>J.attachedToEntity===Z)}getSceneUIById(Z){return this._sceneUIs.get(Z)}registerSceneUI(Z){if(Z.id!==void 0)return Z.id;let J=this._nextSceneUIId;return this._sceneUIs.set(J,Z),this._nextSceneUIId++,J}unloadEntityAttachedSceneUIs(Z){this.getAllEntityAttachedSceneUIs(Z).forEach((J)=>{J.unload()})}unregisterSceneUI(Z){if(Z.id===void 0)return;this._sceneUIs.delete(Z.id)}}var FG6=2,qG6=3;class X2{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(Z,J,X){this._targetTicksPerSecond=Z,this._fixedTimestepS=Math.fround(1/Z),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*qG6,this._tickFunction=J,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get isStarted(){return!!this._tickHandle}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return;this._lastLoopTimeMs=performance.now();let Z=()=>{let J=performance.now(),X=J-this._lastLoopTimeMs;if(this._lastLoopTimeMs=J,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)R8.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<FG6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++});this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs),this._tickHandle=setTimeout(Z,this._nextTickMs)};Z()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(Z){try{this._tickFunction(Z)}catch(J){if(J instanceof Error&&this._tickErrorCallback)this._tickErrorCallback(J);else c.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${J}`)}}}var $H1;((Q)=>{Q.START="WORLD_LOOP.START";Q.STOP="WORLD_LOOP.STOP";Q.TICK_START="WORLD_LOOP.TICK_START";Q.TICK_END="WORLD_LOOP.TICK_END";Q.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})($H1||={});class Y2 extends O0{_currentTick=0;_ticker;_world;constructor(Z,J=Lu){super();this._ticker=new X2(J,this._tick,this._onTickError),this._world=Z}get currentTick(){return this._currentTick}get isStarted(){return this._ticker.isStarted}get nextTickMs(){return this._ticker.nextTickMs}get timestepS(){return this._ticker.fixedTimestepS}get world(){return this._world}start(){this._ticker.start(),this.emitWithWorld(this._world,"WORLD_LOOP.START",{worldLoop:this})}stop(){this._ticker.stop(),this.emitWithWorld(this._world,"WORLD_LOOP.STOP",{worldLoop:this})}_tick=(Z)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:Z});let J=performance.now();R8.startSpan({operation:"world_tick",attributes:{serverPlayerCount:N9.instance.playerCount,targetTickRate:this._ticker.targetTicksPerSecond,targetTickRateMs:this._ticker.fixedTimestepMs,worldId:this._world.id,worldName:this._world.name,worldChunkCount:this._world.chunkLattice.chunkCount,worldEntityCount:this._world.entityManager.entityCount,worldLoopTick:this._currentTick}},()=>{R8.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(Z)),R8.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(Z)),R8.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),R8.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-J})};_onTickError=(Z)=>{c.error(`WorldLoop._onTickError(): Error: ${Z}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:Z})}}var Ou;((F)=>{F.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";F.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";F.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";F.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";F.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";F.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";F.SET_FOG_FAR="WORLD.SET_FOG_FAR";F.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";F.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";F.START="WORLD.START";F.STOP="WORLD.STOP"})(Ou||={});class $2 extends O0{_id;_ambientLightColor;_ambientLightIntensity;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_fogColor;_fogFar;_fogNear;_name;_skyboxIntensity;_skyboxUri;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_entityManager;_lightManager;_loop;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_tag;constructor(Z){super();if(this._id=Z.id,this._ambientLightColor=Z.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=Z.ambientLightIntensity??1,this._directionalLightColor=Z.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=Z.directionalLightIntensity??3,this._directionalLightPosition=Z.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=Z.fogColor,this._fogFar=Z.fogFar??550,this._fogNear=Z.fogNear??500,this._name=Z.name,this._skyboxIntensity=Z.skyboxIntensity??1,this._skyboxUri=Z.skyboxUri,this._tag=Z.tag,this._audioManager=new aG(this),this._blockTypeRegistry=new dz(this),this._chatManager=new OH(this),this._chunkLattice=new MH(this),this._entityManager=new DH(this),this._lightManager=new rU(this),this._loop=new Y2(this,Z.tickRate),this._networkSynchronizer=new iD(this),this._particleEmitterManager=new Z2(this),this._sceneUIManager=new J2(this),this._simulation=new eU(this,Z.tickRate,Z.gravity),Z.map)this.loadMap(Z.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get name(){return this._name}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get entityManager(){return this._entityManager}get lightManager(){return this._lightManager}get loop(){return this._loop}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}loadMap(Z){if(this.chunkLattice.clear(),Z.blockTypes)for(let J of Z.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:J.id,isLiquid:J.isLiquid,name:J.name,textureUri:J.textureUri});if(Z.blocks)for(let[J,X]of Object.entries(Z.blocks)){let[Y,$,Q]=J.split(",").map(Number);this.chunkLattice.setBlock({x:Y,y:$,z:Q},X)}if(Z.entities)for(let[J,X]of Object.entries(Z.entities)){let[Y,$,Q]=J.split(",").map(Number);new a8({isEnvironmental:!0,...X}).spawn(this,{x:Y,y:$,z:Q})}}setAmbientLightColor(Z){this._ambientLightColor=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:Z})}setAmbientLightIntensity(Z){this._ambientLightIntensity=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightColor(Z){this._directionalLightColor=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:Z})}setDirectionalLightIntensity(Z){this._directionalLightIntensity=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightPosition(Z){this._directionalLightPosition=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:Z})}setFogColor(Z){this._fogColor=Z,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:Z})}setFogFar(Z){this._fogFar=Z,this.emit("WORLD.SET_FOG_FAR",{world:this,far:Z})}setFogNear(Z){this._fogNear=Z,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:Z})}setSkyboxIntensity(Z){this._skyboxIntensity=Z,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:Z})}start(){if(this._loop.isStarted)return;this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){if(!this._loop.isStarted)return;this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return k0.serializeWorld(this)}}var QH1;((J)=>J.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(QH1||={});class K${static instance=new K$;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(Z){let J=new $2({...Z,id:this._nextWorldId++});return J.start(),this._worlds.set(J.id,J),O0.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:J}),J}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(Z){let J=[];return this._worlds.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getWorld(Z){return this._worlds.get(Z)}setDefaultWorld(Z){this._defaultWorld=Z}}var KH1;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(KH1||={});class N9{static instance=new N9;worldSelectionHandler;_connectionPlayers=new Map;constructor(){O0.globalInstance.on("CONNECTION.OPENED",({connection:Z,req:J})=>{this._onConnectionOpened(Z,J.session)}),O0.globalInstance.on("CONNECTION.DISCONNECTED",({connection:Z})=>{this._onConnectionDisconnected(Z)}),O0.globalInstance.on("CONNECTION.RECONNECTED",({connection:Z})=>{this._onConnectionReconnected(Z)}),O0.globalInstance.on("CONNECTION.CLOSED",({connection:Z})=>{this._onConnectionClosed(Z)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(Z){return this.getConnectedPlayers().filter((J)=>J.world===Z)}getConnectedPlayerByUsername(Z){return Array.from(this._connectionPlayers.values()).find((J)=>{return J.username.toLowerCase()===Z.toLowerCase()})}async _onConnectionOpened(Z,J){let X=new uW(Z,J);await X.loadInitialPersistedData(),this._connectionPlayers.set(Z,X),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let Y=await this.worldSelectionHandler?.(X);X.joinWorld(Y??K$.instance.getDefaultWorld())}_onConnectionDisconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.resetInputs(),J.camera.reset()}_onConnectionReconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.reconnected(),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:J});else c.warning(`PlayerManager._onConnectionReconnected(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(Z){let J=this._connectionPlayers.get(Z);if(J)J.disconnect(),this._connectionPlayers.delete(Z),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:J});else c.warning(`PlayerManager._onConnectionClosed(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}}Buffer.poolSize=134217728;var GH1;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(GH1||={});function UG6(Z){WH1.default.init().then(()=>{return RK.instance.modelRegistry.preloadModels()}).then(()=>{if(Z.length>0)Z(RK.instance.worldManager.getDefaultWorld());else Z();RK.instance.start()}).catch((J)=>{c.fatalError(`Failed to initialize the game engine, exiting. Error: ${J}`)})}class RK{static _instance;_modelRegistry=g5.instance;_playerManager=N9.instance;_socket=YZ.instance;_worldManager=K$.instance;_webServer=I3.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new RK;return this._instance}get modelRegistry(){return this._modelRegistry}get playerManager(){return this._playerManager}get socket(){return this._socket}get webServer(){return this._webServer}get worldManager(){return this._worldManager}start(){O0.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start()}}var B6=r(PK(),1);class CK extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get determinant(){return B6.mat2.determinant(this)}get frobeniusNorm(){return B6.mat2.frob(this)}static create(){let Z=new CK(0,0,0,0);return B6.mat2.identity(Z),Z}static fromRotation(Z){let J=CK.create();return B6.mat2.fromRotation(J,Z),J}static fromScaling(Z){let J=CK.create();return B6.mat2.fromScaling(J,Z),J}add(Z){return B6.mat2.add(this,this,Z),this}adjoint(){return B6.mat2.adjoint(this,this),this}clone(){return new CK(this[0],this[1],this[2],this[3])}copy(Z){return B6.mat2.copy(this,Z),this}equals(Z){return B6.mat2.equals(this,Z)}exactEquals(Z){return B6.mat2.exactEquals(this,Z)}identity(){return B6.mat2.identity(this),this}invert(){return B6.mat2.invert(this,this),this}multiply(Z){return B6.mat2.mul(this,this,Z),this}multiplyScalar(Z){return B6.mat2.multiplyScalar(this,this,Z),this}rotate(Z){return B6.mat2.rotate(this,this,Z),this}subtract(Z){return B6.mat2.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return B6.mat2.transpose(this,this),this}}var j8=r(PK(),1);class kZ extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G){super([Z,J,X,Y,$,Q,K,W,G])}get determinant(){return j8.mat3.determinant(this)}get frobeniusNorm(){return j8.mat3.frob(this)}static create(){let Z=new kZ(0,0,0,0,0,0,0,0,0);return j8.mat3.identity(Z),Z}static fromMatrix4(Z){let J=kZ.create();return j8.mat3.fromMat4(J,Z),J}static fromQuaternion(Z){let J=kZ.create();return j8.mat3.fromQuat(J,Z),J}static fromRotation(Z){let J=kZ.create();return j8.mat3.fromRotation(J,Z),J}static fromScaling(Z){let J=kZ.create();return j8.mat3.fromScaling(J,Z),J}static fromTranslation(Z){let J=kZ.create();return j8.mat3.fromTranslation(J,Z),J}add(Z){return j8.mat3.add(this,this,Z),this}adjoint(){return j8.mat3.adjoint(this,this),this}clone(){return new kZ(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(Z){return j8.mat3.copy(this,Z),this}equals(Z){return j8.mat3.equals(this,Z)}exactEquals(Z){return j8.mat3.exactEquals(this,Z)}identity(){return j8.mat3.identity(this),this}invert(){return j8.mat3.invert(this,this),this}multiply(Z){return j8.mat3.mul(this,this,Z),this}multiplyScalar(Z){return j8.mat3.multiplyScalar(this,this,Z),this}transformVector(Z){return Z.transformMatrix3(this)}projection(Z,J){return j8.mat3.projection(this,Z,J),this}rotate(Z){return j8.mat3.rotate(this,this,Z),this}subtract(Z){return j8.mat3.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return j8.mat3.transpose(this,this),this}}var $1=r(PK(),1);class v5 extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G,V,z,F,H,q,U,B){super([Z,J,X,Y,$,Q,K,W,G,V,z,F,H,q,U,B])}get determinant(){return $1.mat4.determinant(this)}get frobeniusNorm(){return $1.mat4.frob(this)}static create(){let Z=new v5(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return $1.mat4.identity(Z),Z}static fromQuaternion(Z){let J=v5.create();return $1.mat4.fromQuat(J,Z),J}static fromRotation(Z,J){let X=v5.create();return $1.mat4.fromRotation(X,Z,J),X}static fromRotationTranslation(Z,J){let X=v5.create();return $1.mat4.fromRotationTranslation(X,Z,J),X}static fromRotationTranslationScale(Z,J,X){let Y=v5.create();return $1.mat4.fromRotationTranslationScale(Y,Z,J,X),Y}static fromRotationTranslationScaleOrigin(Z,J,X,Y){let $=v5.create();return $1.mat4.fromRotationTranslationScaleOrigin($,Z,J,X,Y),$}static fromScaling(Z){let J=v5.create();return $1.mat4.fromScaling(J,Z),J}static fromTranslation(Z){let J=v5.create();return $1.mat4.fromTranslation(J,Z),J}static fromXRotation(Z){let J=v5.create();return $1.mat4.fromXRotation(J,Z),J}static fromYRotation(Z){let J=v5.create();return $1.mat4.fromYRotation(J,Z),J}static fromZRotation(Z){let J=v5.create();return $1.mat4.fromZRotation(J,Z),J}add(Z){return $1.mat4.add(this,this,Z),this}adjoint(){return $1.mat4.adjoint(this,this),this}clone(){return new v5(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8],this[9],this[10],this[11],this[12],this[13],this[14],this[15])}copy(Z){return $1.mat4.copy(this,Z),this}equals(Z){return $1.mat4.equals(this,Z)}exactEquals(Z){return $1.mat4.exactEquals(this,Z)}frustrum(Z,J,X,Y,$,Q){return $1.mat4.frustum(this,Z,J,X,Y,$,Q),this}identity(){return $1.mat4.identity(this),this}invert(){return $1.mat4.invert(this,this),this}lookAt(Z,J,X){return $1.mat4.lookAt(this,Z,J,X),this}multiply(Z){return $1.mat4.mul(this,this,Z),this}multiplyScalar(Z){return $1.mat4.multiplyScalar(this,this,Z),this}orthographic(Z,J,X,Y,$,Q){return $1.mat4.ortho(this,Z,J,X,Y,$,Q),this}perspective(Z,J,X,Y){return $1.mat4.perspective(this,Z,J,X,Y),this}rotate(Z,J){return $1.mat4.rotate(this,this,Z,J),this}rotateX(Z){return $1.mat4.rotateX(this,this,Z),this}rotateY(Z){return $1.mat4.rotateY(this,this,Z),this}rotateZ(Z){return $1.mat4.rotateZ(this,this,Z),this}scale(Z){return $1.mat4.scale(this,this,Z),this}subtract(Z){return $1.mat4.sub(this,this,Z),this}targetTo(Z,J,X){return $1.mat4.targetTo(this,Z,J,X),this}toString(){return`[${this[0]},${this[1]},${this[2]},${this[3]}][${this[4]},${this[5]},${this[6]},${this[7]}][${this[8]},${this[9]},${this[10]},${this[11]}][${this[12]},${this[13]},${this[14]},${this[15]}]`}translate(Z){return $1.mat4.translate(this,this,Z),this}transpose(){return $1.mat4.transpose(this,this),this}}var b1=r(PK(),1);class lG extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get length(){return b1.quat.length(this)}get squaredLength(){return b1.quat.squaredLength(this)}get magnitude(){return b1.quat.length(this)}get squaredMagnitude(){return b1.quat.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}get w(){return this[3]}set w(Z){this[3]=Z}static fromEuler(Z,J,X){let Y=b1.quat.fromEuler(new Float32Array(4),Z,J,X);return new lG(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(Z){return new lG(Z.x,Z.y,Z.z,Z.w)}clone(){return new lG(this.x,this.y,this.z,this.w)}conjugate(){return b1.quat.conjugate(this,this),this}copy(Z){return b1.quat.copy(this,Z),this}dot(Z){return b1.quat.dot(this,Z)}exponential(){return b1.quat.exp(this,this),this}equals(Z){return b1.quat.equals(this,Z)}exactEquals(Z){return b1.quat.exactEquals(this,Z)}getAngle(Z){return b1.quat.getAngle(this,Z)}identity(){return b1.quat.identity(this),this}invert(){return b1.quat.invert(this,this),this}lerp(Z,J){return b1.quat.lerp(this,this,Z,J),this}logarithm(){return b1.quat.ln(this,this),this}multiply(Z){return b1.quat.multiply(this,this,Z),this}transformVector(Z){return Z.transformQuaternion(this)}normalize(){return b1.quat.normalize(this,this),this}power(Z){return b1.quat.pow(this,this,Z),this}randomize(){return b1.quat.random(this),this}rotateX(Z){return b1.quat.rotateX(this,this,Z),this}rotateY(Z){return b1.quat.rotateY(this,this,Z),this}rotateZ(Z){return b1.quat.rotateZ(this,this,Z),this}scale(Z){return b1.quat.scale(this,this,Z),this}setAxisAngle(Z,J){return b1.quat.setAxisAngle(this,Z,J),this}slerp(Z,J){return b1.quat.slerp(this,this,Z,J),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var U1=r(PK(),1);class Q2 extends Float32Array{constructor(Z,J){super([Z,J])}get length(){return U1.vec2.length(this)}get squaredLength(){return U1.vec2.squaredLength(this)}get magnitude(){return U1.vec2.length(this)}get squaredMagnitude(){return U1.vec2.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}static create(){return new Q2(0,0)}add(Z){return U1.vec2.add(this,this,Z),this}angle(Z){return U1.vec2.angle(this,Z)}ceil(){return U1.vec2.ceil(this,this),this}clone(){return new Q2(this.x,this.y)}copy(Z){return U1.vec2.copy(this,Z),this}distance(Z){return U1.vec2.distance(this,Z)}divide(Z){return U1.vec2.divide(this,this,Z),this}dot(Z){return U1.vec2.dot(this,Z)}equals(Z){return U1.vec2.equals(this,Z)}exactEquals(Z){return U1.vec2.exactEquals(this,Z)}floor(){return U1.vec2.floor(this,this),this}invert(){return U1.vec2.inverse(this,this),this}lerp(Z,J){return U1.vec2.lerp(this,this,Z,J),this}max(Z){return U1.vec2.max(this,this,Z),this}min(Z){return U1.vec2.min(this,this,Z),this}multiply(Z){return U1.vec2.mul(this,this,Z),this}negate(){return U1.vec2.negate(this,this),this}normalize(){return U1.vec2.normalize(this,this),this}randomize(Z){return U1.vec2.random(this,Z),this}rotate(Z,J){return U1.vec2.rotate(this,this,Z,J),this}round(){return U1.vec2.round(this,this),this}scale(Z){return U1.vec2.scale(this,this,Z),this}scaleAndAdd(Z,J){return U1.vec2.scaleAndAdd(this,this,Z,J),this}subtract(Z){return U1.vec2.sub(this,this,Z),this}toString(){return`${this.x},${this.y}`}transformMatrix2(Z){return U1.vec2.transformMat2(this,this,Z),this}transformMatrix3(Z){return U1.vec2.transformMat3(this,this,Z),this}transformMatrix4(Z){return U1.vec2.transformMat4(this,this,Z),this}zero(){return U1.vec2.zero(this),this}}var H1=r(PK(),1);class pG extends Float32Array{constructor(Z,J,X){super([Z,J,X])}get length(){return H1.vec3.length(this)}get squaredLength(){return H1.vec3.squaredLength(this)}get magnitude(){return H1.vec3.length(this)}get squaredMagnitude(){return H1.vec3.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}static create(){return new pG(0,0,0)}static fromVector3Like(Z){return new pG(Z.x,Z.y,Z.z)}add(Z){return H1.vec3.add(this,this,Z),this}ceil(){return H1.vec3.ceil(this,this),this}clone(){return new pG(this.x,this.y,this.z)}copy(Z){return H1.vec3.copy(this,Z),this}cross(Z){return H1.vec3.cross(this,this,Z),this}distance(Z){return H1.vec3.distance(this,Z)}divide(Z){return H1.vec3.div(this,this,Z),this}dot(Z){return H1.vec3.dot(this,Z)}equals(Z){return H1.vec3.equals(this,Z)}exactEquals(Z){return H1.vec3.exactEquals(this,Z)}floor(){return H1.vec3.floor(this,this),this}invert(){return H1.vec3.inverse(this,this),this}lerp(Z,J){return H1.vec3.lerp(this,this,Z,J),this}max(Z){return H1.vec3.max(this,this,Z),this}min(Z){return H1.vec3.min(this,this,Z),this}multiply(Z){return H1.vec3.mul(this,this,Z),this}negate(){return H1.vec3.negate(this,this),this}normalize(){return H1.vec3.normalize(this,this),this}randomize(Z){return H1.vec3.random(this,Z),this}rotateX(Z,J){return H1.vec3.rotateX(this,this,Z,J),this}rotateY(Z,J){return H1.vec3.rotateY(this,this,Z,J),this}rotateZ(Z,J){return H1.vec3.rotateZ(this,this,Z,J),this}round(){return H1.vec3.round(this,this),this}scale(Z){return H1.vec3.scale(this,this,Z),this}scaleAndAdd(Z,J){return H1.vec3.scaleAndAdd(this,this,Z,J),this}subtract(Z){return H1.vec3.sub(this,this,Z),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(Z){return H1.vec3.transformMat3(this,this,Z),this}transformMatrix4(Z){return H1.vec3.transformMat4(this,this,Z),this}transformQuaternion(Z){return H1.vec3.transformQuat(this,this,Z),this}zero(){return H1.vec3.zero(this),this}}var oF1=r(aF1(),1);var sF1=0.099856;class K2 extends V${faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=sF1;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(Z={}){super();this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=Z.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=Z.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=Z.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(Z){super.spawn(Z),this._startIdleAnimations(Z)}face(Z,J,X){this._faceTarget=Z,this.faceSpeed=J,this._onFace=X?.faceCallback,this._onFaceComplete=X?.faceCompleteCallback}jump(Z){this._jumpHeight=Z}move(Z,J,X){this.moveSpeed=J,this._moveCompletesWhenStuck=X?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=X?.moveStoppingDistance?X.moveStoppingDistance**2:sF1,this._moveTarget=Z,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(Z,J){if(super.tick(Z,J),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(Z),this._moveStartMoveAnimations=!1;let X=J/1000,Y=Z.position;if(Z.isDynamic&&this._jumpHeight>0){let $=Math.abs(Z.world.simulation.gravity.y),Q=Math.sqrt(2*$*this._jumpHeight);Z.applyImpulse({x:0,y:Q*Z.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(Z)}if(this._moveTarget){let $={x:this._moveIgnoreAxes.x?0:this._moveTarget.x-Y.x,y:this._moveIgnoreAxes.y?0:this._moveTarget.y-Y.y,z:this._moveIgnoreAxes.z?0:this._moveTarget.z-Y.z},Q=$.x*$.x+$.y*$.y+$.z*$.z,K=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=J,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let W=Y.x-this._moveStuckLastPosition.x,G=Y.y-this._moveStuckLastPosition.y,V=Y.z-this._moveStuckLastPosition.z;K=Math.sqrt(W*W+G*G+V*V)<this.moveSpeed*0.1}this._moveStuckLastPosition=Y,this._moveStuckAccumulatorMs=0}}if(Q>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!K){let W=Math.sqrt(Q),G=this.moveSpeed*X,z=Math.min(W,G)/W,F={x:Y.x+$.x*z,y:Y.y+$.y*z,z:Y.z+$.z*z};if(Z.setPosition(F),this._onMove)this._onMove(F,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(Z);if(this._onMoveComplete){let W=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,W(Y)}}}if(this._faceTarget){let $={x:this._faceTarget.x-Y.x,z:this._faceTarget.z-Y.z},Q=Math.atan2(-$.x,-$.z),K=Z.rotation,W=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),G=Q-W;while(G>Math.PI)G-=2*Math.PI;while(G<-Math.PI)G+=2*Math.PI;if(Math.abs(G)>0.01&&!this._stopFaceRequested){let V=this.faceSpeed*X,z=Math.abs(G)<V?G:Math.sign(G)*V,H=(W+z)/2,q={x:0,y:Math.fround(Math.sin(H)),z:0,w:Math.fround(Math.cos(H))};if(Z.setRotation(q),this._onFace)this._onFace(K,q)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let V=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,V(Z.rotation)}}}_startIdleAnimations(Z){if(this.idleLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.jumpOneshotAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(Z){Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(Z){if(this.moveLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);Z.stopModelAnimations(this.jumpOneshotAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.moveLoopedAnimations)}}class ku extends K2{_debug=!1;_entity;_maxFall=0;_maxJump=0;_maxOpenSetIterations=200;_onPathfindAbort;_onPathfindComplete;_onWaypointMoveComplete;_onWaypointMoveSkipped;_speed=0;_target;_verticalPenalty=0;_waypoints=[];_waypointNextIndex=0;_waypointStoppingDistance;_waypointTimeoutMs=2000;constructor(Z={}){super(Z)}get debug(){return this._debug}get maxFall(){return this._maxFall}get maxJump(){return this._maxJump}get maxOpenSetIterations(){return this._maxOpenSetIterations}get speed(){return this._speed}get target(){return this._target}get verticalPenalty(){return this._verticalPenalty}get waypoints(){return this._waypoints}get waypointNextIndex(){return this._waypointNextIndex}get waypointTimeoutMs(){return this._waypointTimeoutMs}pathfind(Z,J,X){if(this._target=Z,this._speed=J,this._debug=X?.debug??!1,this._maxFall=X?.maxFall?-Math.abs(X.maxFall):0,this._maxJump=X?.maxJump?Math.abs(X.maxJump):0,this._maxOpenSetIterations=X?.maxOpenSetIterations??200,this._onPathfindAbort=X?.pathfindAbortCallback,this._onPathfindComplete=X?.pathfindCompleteCallback,this._onWaypointMoveComplete=X?.waypointMoveCompleteCallback,this._onWaypointMoveSkipped=X?.waypointMoveSkippedCallback,this._verticalPenalty=X?.verticalPenalty??0,this._waypoints=[],this._waypointNextIndex=0,this._waypointStoppingDistance=X?.waypointStoppingDistance,this._waypointTimeoutMs=X?.waypointTimeoutMs??2000/J,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(Z){super.attach(Z),this._entity=Z}detach(Z){super.detach(Z),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return c.error("PathfindingEntityController._calculatePath: No target or world"),!1;let Z=this._entity.height,J=this._findGroundedStart();if(!J){if(this._debug)c.warning(`PathfindingEntityController._calculatePath: No valid grounded start found within maxFall distance, path search aborted. Start: ${this._coordinateToKey(this._target)}, Target: ${this._coordinateToKey(this._target)}`);return!1}let X={x:Math.floor(this._target.x),y:Math.floor(this._target.y),z:Math.floor(this._target.z)},Y=Math.abs(X.x-J.x),$=Math.abs(X.y-J.y),Q=Math.abs(X.z-J.z);if(Y<=2&&$<=2&&Q<=2&&!this._isNeighborCoordinateBlocked(J,X,this._entity.height))return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5},{x:X.x+0.5,y:X.y+Z/2,z:X.z+0.5}],!0;if(J.x===X.x&&J.y===X.y&&J.z===X.z)return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5}],!0;let W=this._coordinateToKey(J),G=new Map,V=new Map([[W,0]]),z=new Map([[W,this._pathfindingHeuristic(J,X)]]),F=new Set,H=new oF1.Heap((N,R)=>{let P=z.get(N[0])??1/0,D=z.get(R[0])??1/0;return P-D});H.push([W,J]);let q=[{x:0,y:0,z:1},{x:1,y:0,z:0},{x:0,y:0,z:-1},{x:-1,y:0,z:0},{x:1,y:0,z:1},{x:1,y:0,z:-1},{x:-1,y:0,z:1},{x:-1,y:0,z:-1}],U=[];for(let N=this._maxJump;N>=this._maxFall;N--){if(N===0)continue;let R=Math.abs(J.y+N-X.y);U.push({y:N,distanceToTargetY:R})}U.sort((N,R)=>N.distanceToTargetY-R.distanceToTargetY);let B=[...q,...U.flatMap(({y:N})=>q.map((R)=>({...R,y:N})))],L=0,w=Math.abs(X.x-J.x)+Math.abs(X.y-J.y)+Math.abs(X.z-J.z),M=Math.min(this._maxOpenSetIterations,w*20);while(!H.isEmpty()&&L<M){L++;let[N,R]=H.pop();if(R.x===X.x&&R.y===X.y&&R.z===X.z){let C=this._reconstructPath(G,R);if(this._waypoints=C.map((T)=>({x:T.x+0.5,y:T.y+Z/2,z:T.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${L} open set iterations. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return!0}F.add(N);let P=V.get(N),D=new Map;for(let C of B){let T=`${C.x},${C.z}`,k=C.y<0;if(k&&D.has(T))continue;let A={x:R.x+C.x,y:R.y+C.y,z:R.z+C.z};if(Math.abs(X.x-A.x)+Math.abs(X.y-A.y)+Math.abs(X.z-A.z)>w*1.5)continue;let x=this._coordinateToKey(A);if(F.has(x))continue;let I=this._isNeighborCoordinateBlocked(R,A,this._entity.height);if(k&&I){D.set(T,!0);continue}if(I)continue;let _=Math.abs(C.x),b=Math.abs(C.y),u=Math.abs(C.z),i=b===0?0:this._verticalPenalty,e=(Math.max(_,b,u)===1&&_+b+u>1?1.4:1)+i,Z0=P+e,K0=V.get(x)??1/0;if(Z0>=K0)continue;G.set(x,R),V.set(x,Z0);let S0=Z0+this._pathfindingHeuristic(A,X);z.set(x,S0),H.push([x,A])}}if(L>=M){if(this._onPathfindAbort?.(),this._debug)c.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${M}), path search aborted. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)c.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(Z,J){let X=[J],Y=J;while(Z.has(this._coordinateToKey(Y)))Y=Z.get(this._coordinateToKey(Y)),X.unshift(Y);return X}_coordinateToKey(Z){return`${Z.x},${Z.y},${Z.z}`}_moveToNextWaypoint(){let Z=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,J=this._waypoints[this._waypointNextIndex];if(!J||!this._entity)return;let X=0;if(this._entity.isDynamic&&Z&&J.y>Z.y){let Y=J.y-Z.y,$=Math.min(Y,this._maxJump)+0.75;this.jump($);let Q=Math.abs(this._entity.world.simulation.gravity.y),K=Math.sqrt(2*Q*$),W=Z.x+0.5,G=Z.z+0.5,V=J.x+0.5,z=J.z+0.5,F=V-W,H=z-G,q=Math.sqrt(F*F+H*H),U=K/Q,B=q/this._speed;X=Math.min(U*0.8,B)*1000}setTimeout(()=>{if(!this._entity)return;let Y=Date.now();this.face(J,this._speed),this.move(J,this._speed,{moveCompletesWhenStuck:!0,moveIgnoreAxes:{y:this._entity.isDynamic},moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveStoppingDistance:this._waypointStoppingDistance,moveCallback:()=>{if(Date.now()-Y>this._waypointTimeoutMs&&this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveSkipped?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},X)}_pathfindingHeuristic(Z,J){return Math.abs(Z.x-J.x)+Math.abs(Z.y-J.y)+Math.abs(Z.z-J.z)}_isNeighborCoordinateBlocked(Z,J,X){if(!this._entity?.world)return!1;let Y=this._entity.world,$=Math.floor(J.x),Q=Math.floor(J.y),K=Math.floor(J.z),W=Math.floor(Z.x),G=Math.floor(Z.z);if(!Y.chunkLattice.hasBlock({x:$,y:Q-1,z:K}))return!0;for(let V=0;V<X;V++)if(Y.chunkLattice.hasBlock({x:$,y:Q+V,z:K}))return!0;if($!==W&&K!==G)for(let V=0;V<X;V++){let z=Y.chunkLattice.hasBlock({x:$,y:Q+V,z:G}),F=Y.chunkLattice.hasBlock({x:W,y:Q+V,z:K});if(z||F)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:Z,y:J,z:X}=this._entity.position,Y={x:Math.floor(Z),y:Math.floor(J),z:Math.floor(X)};for(let $=0;$<=Math.abs(this._maxFall);$++)if(this._entity.world.chunkLattice.hasBlock({...Y,y:Y.y-$-1}))return{...Y,y:Y.y-$};return}}export{UG6 as startServer,QH1 as WorldManagerEvent,K$ as WorldManager,$H1 as WorldLoopEvent,Y2 as WorldLoop,Ou as WorldEvent,$2 as World,LA as WebServerEvent,I3 as WebServer,pG as Vector3,Q2 as Vector2,X2 as Ticker,NK as TelemetrySpanOperation,R8 as Telemetry,wu as SimulationEvent,eU as Simulation,K2 as SimpleEntityController,J2 as SceneUIManager,M_ as SceneUIEvent,jH as SceneUI,u50 as SUPPORTED_INPUT_KEYS,mz as RigidBodyType,f$ as RigidBody,lG as Quaternion,SO as PlayerUIEvent,LH as PlayerUI,KH1 as PlayerManagerEvent,N9 as PlayerManager,wH as PlayerEvent,i7 as PlayerEntity,m50 as PlayerCameraMode,B_ as PlayerCameraEvent,BH as PlayerCamera,uW as Player,l$ as PersistenceManager,ku as PathfindingEntityController,Z2 as ParticleEmitterManager,Uu as ParticleEmitterEvent,Bu as ParticleEmitter,UA as PORT,i50 as PLAYER_ROTATION_UPDATE_THRESHOLD,p50 as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,g5 as ModelRegistry,v5 as Matrix4,kZ as Matrix3,CK as Matrix2,YH1 as LightType,rU as LightManager,Fu as LightEvent,qu as Light,U6 as IterationMap,GH1 as GameServerEvent,RK as GameServer,O0 as EventRouter,c as ErrorHandler,DH as EntityManager,RH as EntityEvent,a8 as Entity,l50 as ENTITY_ROTATION_UPDATE_THRESHOLD,c50 as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,m1 as DefaultPlayerEntityController,N_ as DefaultPlayerEntity,d50 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,g4 as CollisionGroupsBuilder,B$ as CollisionGroup,uz as ColliderShape,NH as ColliderMap,F9 as Collider,xE as CoefficientCombineRule,O_ as ChunkLatticeEvent,MH as ChunkLattice,B9 as Chunk,OH as ChatManager,L_ as ChatEvent,fE as BlockTypeRegistryEvent,dz as BlockTypeRegistry,hE as BlockTypeEvent,q9 as BlockType,IK as Block,xu as BaseEntityControllerEvent,V$ as BaseEntityController,aG as AudioManager,VP as AudioEvent,nG as Audio};