eve 0.24.2 → 0.24.4
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/CHANGELOG.md +22 -0
- package/dist/src/channel/adapter.d.ts +4 -2
- package/dist/src/channel/adapter.js +1 -1
- package/dist/src/channel/session.d.ts +5 -1
- package/dist/src/channel/types.d.ts +7 -6
- package/dist/src/chunks/{use-eve-agent-CFBTHlPx.js → use-eve-agent-BP9FpQsJ.js} +15 -4
- package/dist/src/chunks/{use-eve-agent-dEGV09g_.js → use-eve-agent-Dwa2j1wE.js} +15 -4
- package/dist/src/cli/dev/environment.d.ts +6 -0
- package/dist/src/cli/dev/environment.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +2 -2
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/client/index.d.ts +1 -1
- package/dist/src/client/message-reducer.js +1 -1
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session-utils.js +1 -1
- package/dist/src/client/session.d.ts +4 -2
- package/dist/src/client/session.js +1 -1
- package/dist/src/client/types.d.ts +3 -2
- package/dist/src/compiled/.vendor-stamp.json +2 -1
- package/dist/src/compiled/@chat-adapter/slack/index.js +12 -12
- package/dist/src/compiled/@chat-adapter/twilio/index.js +1 -1
- package/dist/src/compiled/@vercel/sandbox/index.js +19 -19
- package/dist/src/compiled/@workflow/world-local/index.d.ts +14 -0
- package/dist/src/compiled/_chunks/node/{auth-CWHn3Yve.js → auth-BuQkq4Gr.js} +2 -2
- package/dist/src/compiled/_chunks/node/{dist-BdTs18CF.js → chunk-BTyA9uPd.js} +1 -1
- package/dist/src/compiled/_chunks/node/{dist-W8yle6rh.js → dist-CdH_Yoxt.js} +5 -5
- package/dist/src/compiled/_chunks/node/{dist-RHRJZ03Q.js → dist-Drt-_JVK.js} +1 -1
- package/dist/src/compiled/_chunks/node/dist-DsNhwdzf.js +1 -0
- package/dist/src/compiled/_chunks/node/retry-DngYleaI.js +1 -0
- package/dist/src/compiled/_chunks/node/token-DabMnh8F.js +1 -0
- package/dist/src/compiled/_chunks/node/token-util-BoSJPKrG.js +1 -0
- package/dist/src/compiled/_chunks/node/token-util-DVigMYWS.js +1 -0
- package/dist/src/compiled/_chunks/node/virtual-loader-B8K8w9cr.js +1 -0
- package/dist/src/compiled/chat/index.js +1 -1
- package/dist/src/compiled/env-runner/LICENSE +21 -0
- package/dist/src/compiled/env-runner/index.d.ts +38 -0
- package/dist/src/compiled/env-runner/index.js +1 -0
- package/dist/src/compiled/env-runner/node-worker.d.ts +1 -0
- package/dist/src/compiled/env-runner/node-worker.js +12 -0
- package/dist/src/compiler/compile-agent.d.ts +4 -6
- package/dist/src/compiler/compile-agent.js +1 -1
- package/dist/src/discover/filesystem.js +1 -1
- package/dist/src/execution/create-session-step.d.ts +2 -2
- package/dist/src/execution/create-session-step.js +1 -1
- package/dist/src/execution/durable-session-migrations/turn-workflow.d.ts +1 -0
- package/dist/src/execution/durable-session-migrations/turn-workflow.js +1 -1
- package/dist/src/execution/next-driver-action.d.ts +7 -0
- package/dist/src/execution/settle-cancelled-turn-step.d.ts +16 -0
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -0
- package/dist/src/execution/subagent-hitl-proxy.js +1 -1
- package/dist/src/execution/terminal-session-failure-step.d.ts +6 -0
- package/dist/src/execution/terminal-session-failure-step.js +1 -0
- package/dist/src/execution/turn-cancellation-control.d.ts +40 -0
- package/dist/src/execution/turn-cancellation-control.js +1 -0
- package/dist/src/execution/turn-dispatch.d.ts +14 -1
- package/dist/src/execution/turn-dispatch.js +1 -1
- package/dist/src/execution/turn-execution-cursor.d.ts +2 -1
- package/dist/src/execution/turn-execution-cursor.js +1 -1
- package/dist/src/execution/turn-workflow.d.ts +9 -1
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.d.ts +8 -6
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/active-turn-id.d.ts +11 -0
- package/dist/src/harness/active-turn-id.js +1 -0
- package/dist/src/harness/cancelled-turn-emission.d.ts +11 -0
- package/dist/src/harness/cancelled-turn-emission.js +1 -0
- package/dist/src/harness/emission.d.ts +4 -2
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/proxy-input-requests.d.ts +5 -0
- package/dist/src/harness/proxy-input-requests.js +1 -1
- package/dist/src/harness/session-limit-enforcement.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/internal/application/compiled-artifacts.d.ts +13 -0
- package/dist/src/internal/application/compiled-artifacts.js +5 -3
- package/dist/src/internal/application/dev-environment.d.ts +4 -0
- package/dist/src/internal/application/dev-environment.js +1 -0
- package/dist/src/internal/application/optional-package-install.d.ts +2 -10
- package/dist/src/internal/application/optional-package-install.js +1 -1
- package/dist/src/internal/application/output-publication-lock.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/application/tsconfig-dependencies.js +1 -1
- package/dist/src/internal/authored-module-loader.d.ts +3 -9
- package/dist/src/internal/authored-module-loader.js +2 -2
- package/dist/src/internal/authored-package-boundary.d.ts +0 -2
- package/dist/src/internal/authored-package-boundary.js +1 -1
- package/dist/src/internal/authored-package-tsconfig-paths.js +1 -1
- package/dist/src/internal/bundler/nitro-rolldown.d.ts +18 -2
- package/dist/src/internal/bundler/nitro-rolldown.js +1 -1
- package/dist/src/internal/compiled-manifest-fingerprint.d.ts +5 -0
- package/dist/src/internal/compiled-manifest-fingerprint.js +1 -0
- package/dist/src/internal/materialized-authored-modules.d.ts +0 -3
- package/dist/src/internal/materialized-authored-modules.js +1 -1
- package/dist/src/internal/nitro/dev-client-address.d.ts +22 -0
- package/dist/src/internal/nitro/dev-client-address.js +1 -0
- package/dist/src/internal/nitro/dev-runtime-artifacts-retention.d.ts +12 -0
- package/dist/src/internal/nitro/dev-runtime-artifacts-retention.js +1 -0
- package/dist/src/internal/nitro/dev-runtime-artifacts.d.ts +19 -1
- package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-source-snapshot-copy.js +1 -1
- package/dist/src/internal/nitro/development-generation.d.ts +5 -1
- package/dist/src/internal/nitro/development-generation.js +1 -1
- package/dist/src/internal/nitro/host/artifacts-config.d.ts +2 -0
- package/dist/src/internal/nitro/host/artifacts-config.js +1 -1
- package/dist/src/internal/nitro/host/channel-routes.d.ts +1 -13
- package/dist/src/internal/nitro/host/channel-routes.js +3 -3
- package/dist/src/internal/nitro/host/configure-nitro-routes.d.ts +1 -2
- package/dist/src/internal/nitro/host/configure-nitro-routes.js +2 -2
- package/dist/src/internal/nitro/host/create-application-nitro.d.ts +3 -5
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.d.ts +32 -0
- package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.js +1 -0
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.d.ts +4 -15
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
- package/dist/src/internal/nitro/host/dev-host-candidate.d.ts +16 -0
- package/dist/src/internal/nitro/host/dev-host-candidate.js +1 -0
- package/dist/src/internal/nitro/host/dev-host-fingerprint.d.ts +2 -0
- package/dist/src/internal/nitro/host/dev-host-fingerprint.js +1 -0
- package/dist/src/internal/nitro/host/dev-host-workspace.d.ts +10 -0
- package/dist/src/internal/nitro/host/dev-host-workspace.js +1 -0
- package/dist/src/internal/nitro/host/dev-runner.d.ts +21 -0
- package/dist/src/internal/nitro/host/dev-runner.js +1 -0
- package/dist/src/internal/nitro/host/dev-server-http.d.ts +5 -0
- package/dist/src/internal/nitro/host/dev-server-http.js +1 -0
- package/dist/src/internal/nitro/host/dev-server-url.d.ts +6 -0
- package/dist/src/internal/nitro/host/dev-server-url.js +1 -0
- package/dist/src/internal/nitro/host/dev-workflow-world-setup.d.ts +9 -0
- package/dist/src/internal/nitro/host/dev-workflow-world-setup.js +1 -0
- package/dist/src/internal/nitro/host/dispatch-schedule-in-dev.js +1 -1
- package/dist/src/internal/nitro/host/drained-nitro-dev-server.d.ts +53 -0
- package/dist/src/internal/nitro/host/drained-nitro-dev-server.js +1 -0
- package/dist/src/internal/nitro/host/prepare-application-host.d.ts +4 -5
- package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
- package/dist/src/internal/nitro/host/start-development-server.d.ts +2 -5
- package/dist/src/internal/nitro/host/start-development-server.js +2 -2
- package/dist/src/internal/nitro/host/types.d.ts +6 -0
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/nitro/routes/runtime-artifacts.d.ts +7 -0
- package/dist/src/internal/nitro/routes/runtime-artifacts.js +1 -1
- package/dist/src/internal/nitro/routes/schedule-task.d.ts +9 -0
- package/dist/src/internal/nitro/routes/schedule-task.js +1 -1
- package/dist/src/internal/workflow/development-generation-context.d.ts +8 -0
- package/dist/src/internal/workflow/development-generation-context.js +1 -0
- package/dist/src/internal/workflow/development-world-client.d.ts +29 -0
- package/dist/src/internal/workflow/development-world-client.js +1 -0
- package/dist/src/internal/workflow/development-world-codec.d.ts +11 -0
- package/dist/src/internal/workflow/development-world-codec.js +1 -0
- package/dist/src/internal/workflow/development-world-protocol.d.ts +31 -0
- package/dist/src/internal/workflow/development-world-protocol.js +1 -0
- package/dist/src/internal/workflow/development-world-server.d.ts +27 -0
- package/dist/src/internal/workflow/development-world-server.js +1 -0
- package/dist/src/internal/workflow/local-world-data-directory.d.ts +2 -0
- package/dist/src/internal/workflow/local-world-data-directory.js +1 -0
- package/dist/src/internal/workflow-bundle/builder-support.js +3 -3
- package/dist/src/internal/workflow-bundle/builder.js +2 -2
- package/dist/src/internal/workflow-bundle/vercel-workflow-output.js +1 -1
- package/dist/src/protocol/message.d.ts +23 -3
- package/dist/src/protocol/message.js +2 -2
- package/dist/src/public/channels/discord/discordChannel.d.ts +1 -0
- package/dist/src/public/channels/eve.js +1 -1
- package/dist/src/public/channels/github/githubChannel.d.ts +1 -0
- package/dist/src/public/channels/linear/linearChannel.d.ts +1 -0
- package/dist/src/public/channels/slack/slackChannel.d.ts +1 -0
- package/dist/src/public/channels/teams/teamsChannel.d.ts +1 -0
- package/dist/src/public/channels/telegram/telegramChannel.d.ts +1 -0
- package/dist/src/public/channels/twilio/twilioChannel.d.ts +1 -0
- package/dist/src/public/definitions/channel.d.ts +5 -4
- package/dist/src/public/definitions/channel.js +1 -1
- package/dist/src/runtime/agent/mock-model-adapter.js +1 -1
- package/dist/src/runtime/compiled-artifacts-source.d.ts +9 -0
- package/dist/src/runtime/compiled-artifacts-source.js +1 -1
- package/dist/src/runtime/durable-compiled-artifacts-source.d.ts +8 -0
- package/dist/src/runtime/durable-compiled-artifacts-source.js +1 -0
- package/dist/src/runtime/sessions/runtime-context-keys.js +1 -1
- package/dist/src/services/dev-client/runtime-artifacts.d.ts +2 -2
- package/dist/src/services/dev-client.d.ts +10 -18
- package/dist/src/services/dev-client.js +1 -1
- package/dist/src/setup/scaffold/create/extension.js +0 -1
- package/dist/src/setup/scaffold/create/project.js +1 -3
- package/dist/src/shared/atomic-write-file.d.ts +1 -1
- package/dist/src/shared/atomic-write-file.js +1 -1
- package/dist/src/shared/continuation-token.d.ts +2 -0
- package/dist/src/shared/continuation-token.js +1 -0
- package/dist/src/shared/rename-with-retry.d.ts +5 -0
- package/dist/src/shared/rename-with-retry.js +1 -0
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/agent-config.md +2 -0
- package/docs/concepts/execution-model-and-durability.md +1 -1
- package/docs/concepts/sessions-runs-and-streaming.md +13 -4
- package/docs/guides/client/continuations.mdx +14 -1
- package/docs/guides/client/streaming.mdx +14 -1
- package/docs/guides/deployment.md +1 -1
- package/docs/reference/cli.md +1 -1
- package/package.json +2 -1
- package/dist/src/compiled/_chunks/node/retry-DkR2H1Y0.js +0 -1
- package/dist/src/compiled/_chunks/node/token-ORseRyWn.js +0 -1
- package/dist/src/internal/bundler/nitro-node-file-trace.d.ts +0 -10
- package/dist/src/internal/bundler/nitro-node-file-trace.js +0 -1
- package/dist/src/internal/materialize-authored-external-dependencies.d.ts +0 -10
- package/dist/src/internal/materialize-authored-external-dependencies.js +0 -2
- package/dist/src/internal/nitro/host/dev-live-virtual-modules.d.ts +0 -15
- package/dist/src/internal/nitro/host/dev-live-virtual-modules.js +0 -1
- package/dist/src/internal/nitro/host/server-external-packages.d.ts +0 -5
- package/dist/src/internal/nitro/host/server-external-packages.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{I as e,K as t,L as n,kt as r}from"./dist-
|
|
1
|
+
import{I as e,K as t,L as n,kt as r}from"./dist-CdH_Yoxt.js";import i from"crypto";function a(e){return t(e)?e:typeof e==`object`&&e&&`card`in e?e.card:null}function o(e){return typeof e==`object`&&e&&`files`in e?e.files??[]:[]}function s(e){return typeof e==`object`&&e&&`attachments`in e?e.attachments??[]:[]}var c=class extends Error{adapter;code;constructor(e,t,n){super(e),this.name=`AdapterError`,this.adapter=t,this.code=n}},l=class extends c{retryAfter;constructor(e,t){super(`Rate limited by ${e}${t?`, retry after ${t}s`:``}`,e,`RATE_LIMITED`),this.name=`AdapterRateLimitError`,this.retryAfter=t}},u=class extends c{constructor(e,t){super(t||`Authentication failed for ${e}`,e,`AUTH_FAILED`),this.name=`AuthenticationError`}},d=class extends c{constructor(e,t){super(t,e,`VALIDATION_ERROR`),this.name=`ValidationError`}},f=class extends c{originalError;constructor(e,t,n){super(t||`Network error communicating with ${e}`,e,`NETWORK_ERROR`),this.name=`NetworkError`,this.originalError=n}};async function p(e,t){let{platform:n,throwOnUnsupported:r=!0}=t;if(Buffer.isBuffer(e))return e;if(e instanceof ArrayBuffer)return Buffer.from(e);if(e instanceof Blob){let t=await e.arrayBuffer();return Buffer.from(t)}if(r)throw new d(n,`Unsupported file data type`);return null}var m={slack:{primary:`primary`,danger:`danger`},gchat:{primary:`primary`,danger:`danger`},teams:{primary:`positive`,danger:`destructive`},discord:{primary:`primary`,danger:`danger`}};function h(e){return t=>n(t,e)}function g(e,t){if(e)return m[t][e]}function _(e,t={}){let{boldFormat:n=`*`,lineBreak:r=`
|
|
2
2
|
`,platform:i}=t,a=i?h(i):e=>e,o=[];e.title&&o.push(`${n}${a(e.title)}${n}`),e.subtitle&&o.push(a(e.subtitle));for(let t of e.children){let e=v(t,a);e&&o.push(e)}return o.join(r)}function v(t,n){switch(t.type){case`text`:return n(t.content);case`link`:return`${n(t.label)} (${t.url})`;case`fields`:return t.children.map(e=>`${n(e.label)}: ${n(e.value)}`).join(`
|
|
3
3
|
`);case`actions`:return null;case`section`:return t.children.map(e=>v(e,n)).filter(Boolean).join(`
|
|
4
4
|
`);case`table`:return r(t.headers,t.rows);case`divider`:return`---`;default:return e(t)}}var y=`aes-256-gcm`,b=12,x=16,S=/^[0-9a-fA-F]{64}$/;function C(e,t){let n=i.randomBytes(b),r=i.createCipheriv(y,t,n,{authTagLength:x}),a=Buffer.concat([r.update(e,`utf8`),r.final()]),o=r.getAuthTag();return{iv:n.toString(`base64`),data:a.toString(`base64`),tag:o.toString(`base64`)}}function w(e,t){let n=Buffer.from(e.iv,`base64`),r=Buffer.from(e.data,`base64`),a=Buffer.from(e.tag,`base64`),o=i.createDecipheriv(y,t,n,{authTagLength:x});return o.setAuthTag(a),Buffer.concat([o.update(r),o.final()]).toString(`utf8`)}function T(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.iv==`string`&&typeof t.data==`string`&&typeof t.tag==`string`}function E(e){let t=e.trim(),n=S.test(t),r=Buffer.from(t,n?`hex`:`base64`);if(r.length!==32)throw Error(`Encryption key must decode to exactly 32 bytes (received ${r.length}). Use a 64-char hex string or 44-char base64 string.`);return r}export{_ as a,w as c,o as d,s as f,p as h,d as i,C as l,g as m,u as n,h as o,T as p,f as r,E as s,l as t,a as u};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=Symbol.for(`workflow-serialize`),t=Symbol.for(`workflow-deserialize`);export{e as n,t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./chunk-BTyA9uPd.js";var t=e(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),n=e(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1;var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),r=e((e=>{var t=n();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*Math.max(t.minTimeout,1)*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),i=e(((e,t)=>{t.exports=r()}));export{t as n,i as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./chunk-BTyA9uPd.js";import{r as t,t as n}from"./token-util-BoSJPKrG.js";var r=e(((e,r)=>{var i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)i(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of o(t))!s.call(e,c)&&c!==n&&i(e,c,{get:()=>t[c],enumerable:!(r=a(t,c))||r.enumerable});return e},u=e=>l(i({},`__esModule`,{value:!0}),e),d={};c(d,{refreshToken:()=>m}),r.exports=u(d);var f=t(),p=n();async function m(e){let t=e?.project,n=e?.team;if(!t&&!n){let e=(0,p.findProjectInfo)();t=e.projectId,n=e.teamId}else if(!t||!n){let e=(0,p.findProjectInfo)();t??=e.projectId,n??=e.teamId}if(!t)throw new f.VercelOidcTokenError("Failed to refresh OIDC token: No project specified. Try re-linking your project with `vc link`");let r=(0,p.loadToken)(t);if(!r||(0,p.isExpired)((0,p.getTokenPayload)(r.token),e?.expirationBufferMs)){let i=await(0,p.getVercelToken)({expirationBufferMs:e?.expirationBufferMs});if(r=await(0,p.getVercelOidcToken)(i,t,n),!r)throw new f.VercelOidcTokenError(`Failed to refresh OIDC token`);(0,p.saveToken)(r,t)}process.env.VERCEL_OIDC_TOKEN=r.token}0&&(r.exports={refreshToken:m})}));export default r();export{};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e,t}from"./chunk-BTyA9uPd.js";var n=t(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{VercelOidcTokenError:()=>u}),t.exports=c(l);var u=class extends Error{constructor(e,t){super(e),this.name=`VercelOidcTokenError`,this.cause=t}toString(){return this.cause?`${this.name}: ${this.message}: ${this.cause}`:`${this.name}: ${this.message}`}};0&&(t.exports={VercelOidcTokenError:u})})),r=t(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{AccessTokenMissingError:()=>u,RefreshAccessTokenFailedError:()=>d}),t.exports=c(l);var u=class extends Error{constructor(){super(`No authentication found. Please log in with the Vercel CLI (vercel login).`),this.name=`AccessTokenMissingError`}},d=class extends Error{constructor(e){super(`Failed to refresh authentication token.`,{cause:e}),this.name=`RefreshAccessTokenFailedError`}};0&&(t.exports={AccessTokenMissingError:u,RefreshAccessTokenFailedError:d})})),i=t(((t,r)=>{var i=Object.create,a=Object.defineProperty,o=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,c=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty,u=(e,t)=>{for(var n in t)a(e,n,{get:t[n],enumerable:!0})},d=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of s(t))!l.call(e,i)&&i!==n&&a(e,i,{get:()=>t[i],enumerable:!(r=o(t,i))||r.enumerable});return e},f=(e,t,n)=>(n=e==null?{}:i(c(e)),d(t||!e||!e.__esModule?a(n,`default`,{value:e,enumerable:!0}):n,e)),p=e=>d(a({},`__esModule`,{value:!0}),e),m={};u(m,{findRootDir:()=>y,getUserDataDir:()=>b}),r.exports=p(m);var h=f(e(`path`)),g=f(e(`fs`)),_=f(e(`os`)),v=n();function y(){try{let e=process.cwd();for(;e!==h.default.dirname(e);){let t=h.default.join(e,`.vercel`);if(g.default.existsSync(t))return e;e=h.default.dirname(e)}}catch{throw new v.VercelOidcTokenError(`Token refresh only supported in node server environments`)}return null}function b(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(_.default.platform()){case`darwin`:return h.default.join(_.default.homedir(),`Library/Application Support`);case`linux`:return h.default.join(_.default.homedir(),`.local/share`);case`win32`:return process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:null;default:return null}}0&&(r.exports={findRootDir:y,getUserDataDir:b})})),a=t(((t,n)=>{var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,c=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty,u=(e,t)=>{for(var n in t)i(e,n,{get:t[n],enumerable:!0})},d=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of o(t))!l.call(e,s)&&s!==n&&i(e,s,{get:()=>t[s],enumerable:!(r=a(t,s))||r.enumerable});return e},f=(e,t,n)=>(n=e==null?{}:r(c(e)),d(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),p=e=>d(i({},`__esModule`,{value:!0}),e),m={};u(m,{isValidAccessToken:()=>x,readAuthConfig:()=>y,writeAuthConfig:()=>b}),n.exports=p(m);var h=f(e(`fs`)),g=f(e(`path`)),_=s();function v(){let e=(0,_.getVercelDataDir)();if(!e)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return g.join(e,`auth.json`)}function y(){try{let e=v();if(!h.existsSync(e))return null;let t=h.readFileSync(e,`utf8`);return t?JSON.parse(t):null}catch{return null}}function b(e){let t=v(),n=g.dirname(t);h.existsSync(n)||h.mkdirSync(n,{mode:504,recursive:!0}),h.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}function x(e,t=0){if(!e.token)return!1;if(typeof e.expiresAt!=`number`)return!0;let n=Math.floor(Date.now()/1e3),r=t/1e3;return e.expiresAt>=n+r}0&&(n.exports={isValidAccessToken:x,readAuthConfig:y,writeAuthConfig:b})})),o=t(((t,n)=>{var r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},c=(e,t,n,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(r({},`__esModule`,{value:!0}),e),u={};s(u,{processTokenResponse:()=>g,refreshTokenRequest:()=>h}),n.exports=l(u);var d=e(`os`);let f=`@vercel/oidc node-${process.version} ${(0,d.platform)()} (${(0,d.arch)()}) ${(0,d.hostname)()}`,p=null;async function m(){if(p)return p;let e=await fetch(`https://vercel.com/.well-known/openid-configuration`,{headers:{"user-agent":f}});if(!e.ok)throw Error(`Failed to discover OAuth endpoints`);let t=await e.json();if(!t||typeof t.token_endpoint!=`string`)throw Error(`Invalid OAuth discovery response`);let n=t.token_endpoint;return p=n,n}async function h(e){let t=await m();return await fetch(t,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":f},body:new URLSearchParams({client_id:`cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp`,grant_type:`refresh_token`,...e})})}async function g(e){let t=await e.json();if(!e.ok){let e=typeof t==`object`&&t&&`error`in t?String(t.error):`Token refresh failed`;return[Error(e)]}return typeof t!=`object`||!t?[Error(`Invalid token response`)]:typeof t.access_token==`string`?t.token_type===`Bearer`?typeof t.expires_in==`number`?[null,t]:[Error(`Missing expires_in in response`)]:[Error(`Invalid token_type in response`)]:[Error(`Missing access_token in response`)]}0&&(n.exports={processTokenResponse:g,refreshTokenRequest:h})})),s=t(((t,s)=>{var c=Object.create,l=Object.defineProperty,u=Object.getOwnPropertyDescriptor,d=Object.getOwnPropertyNames,f=Object.getPrototypeOf,p=Object.prototype.hasOwnProperty,m=(e,t)=>{for(var n in t)l(e,n,{get:t[n],enumerable:!0})},h=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of d(t))!p.call(e,i)&&i!==n&&l(e,i,{get:()=>t[i],enumerable:!(r=u(t,i))||r.enumerable});return e},g=(e,t,n)=>(n=e==null?{}:c(f(e)),h(t||!e||!e.__esModule?l(n,`default`,{value:e,enumerable:!0}):n,e)),_=e=>h(l({},`__esModule`,{value:!0}),e),v={};m(v,{assertVercelOidcTokenResponse:()=>k,findProjectInfo:()=>A,getTokenPayload:()=>N,getVercelDataDir:()=>E,getVercelOidcToken:()=>O,getVercelToken:()=>D,isExpired:()=>P,loadToken:()=>M,saveToken:()=>j}),s.exports=_(v);var y=g(e(`path`)),b=g(e(`fs`)),x=n(),S=i(),C=a(),w=o(),T=r();function E(){let e=(0,S.getUserDataDir)();return e?y.join(e,`com.vercel.cli`):null}async function D(e){let t=(0,C.readAuthConfig)();if(!t?.token)throw new T.AccessTokenMissingError;if((0,C.isValidAccessToken)(t,e?.expirationBufferMs))return t.token;if(!t.refreshToken)throw(0,C.writeAuthConfig)({}),new T.RefreshAccessTokenFailedError(`No refresh token available`);try{let e=await(0,w.refreshTokenRequest)({refresh_token:t.refreshToken}),[n,r]=await(0,w.processTokenResponse)(e);if(n||!r)throw(0,C.writeAuthConfig)({}),new T.RefreshAccessTokenFailedError(n);let i={token:r.access_token,expiresAt:Math.floor(Date.now()/1e3)+r.expires_in};return r.refresh_token&&(i.refreshToken=r.refresh_token),(0,C.writeAuthConfig)(i),i.token}catch(e){throw(0,C.writeAuthConfig)({}),e instanceof T.AccessTokenMissingError||e instanceof T.RefreshAccessTokenFailedError?e:new T.RefreshAccessTokenFailedError(e)}}async function O(e,t,n){let r=`https://api.vercel.com/v1/projects/${t}/token?source=vercel-oidc-refresh${n?`&teamId=${n}`:``}`,i=await fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${e}`}});if(!i.ok)throw new x.VercelOidcTokenError(`Failed to refresh OIDC token: ${i.statusText}`);let a=await i.json();return k(a),a}function k(e){if(!e||typeof e!=`object`)throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!(`token`in e)||typeof e.token!=`string`)throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function A(){let e=(0,S.findRootDir)();if(!e)throw new x.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let t=y.join(e,`.vercel`,`project.json`);if(!b.existsSync(t))throw new x.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let n=JSON.parse(b.readFileSync(t,`utf8`));if(typeof n.projectId!=`string`&&typeof n.orgId!=`string`)throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:n.projectId,teamId:n.orgId}}function j(e,t){let n=(0,S.getUserDataDir)();if(!n)throw new x.VercelOidcTokenError(`Unable to find user data directory. Please reach out to Vercel support.`);let r=y.join(n,`com.vercel.token`,`${t}.json`),i=JSON.stringify(e);b.mkdirSync(y.dirname(r),{mode:504,recursive:!0}),b.writeFileSync(r,i),b.chmodSync(r,432)}function M(e){let t=(0,S.getUserDataDir)();if(!t)throw new x.VercelOidcTokenError(`Unable to find user data directory. Please reach out to Vercel support.`);let n=y.join(t,`com.vercel.token`,`${e}.json`);if(!b.existsSync(n))return null;let r=JSON.parse(b.readFileSync(n,`utf8`));return k(r),r}function N(e){let t=e.split(`.`);if(t.length!==3)throw new x.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`),r=n.padEnd(n.length+(4-n.length%4)%4,`=`);return JSON.parse(Buffer.from(r,`base64`).toString(`utf8`))}function P(e,t=0){return e.exp*1e3<Date.now()+t}0&&(s.exports={assertVercelOidcTokenResponse:k,findProjectInfo:A,getTokenPayload:N,getVercelDataDir:E,getVercelOidcToken:O,getVercelToken:D,isExpired:P,loadToken:M,saveToken:j})}));export{r as n,n as r,s as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./token-util-BoSJPKrG.js";export default e();export{};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{pathToFileURL as e}from"node:url";async function t(e){let t=await Promise.all(Object.entries(e).map(async([e,t])=>[e,typeof t==`function`?await t():t]));return Object.fromEntries(t)}const n=`virtual:`;function r(e,t,r=c()){return{resolve:(i,a,o)=>{let c=s(i);if(Object.hasOwn(e,c)){let e=t?.get(c);return{url:n+encodeURIComponent(i)+(e?`?v=${e}`:``),shortCircuit:!0}}return a.parentURL?.startsWith(n)?o(i,{...a,parentURL:r}):o(i,a)},load:(t,r,a)=>{if(t.startsWith(n)){let n=s(decodeURIComponent(t.slice(8)));if(Object.hasOwn(e,n))return{format:i(n),source:e[n],shortCircuit:!0}}return a(t,r)}}}function i(e){return e.endsWith(`.json`)?`json`:e.endsWith(`.ts`)||e.endsWith(`.mts`)?`module-typescript`:`module`}function a(e,t,n,r){if(typeof n!=`function`)throw TypeError(`[env-runner] virtual TypeScript module "${e}" requires \`module.stripTypeScriptTypes\` ${r.requirement}; ${r.remedy} or provide a pre-transpiled JavaScript source instead.`);return n(t)}function o(e,t){let n=[t],r=new Set(n);for(let t of n){let i=[`"${t}"`,`'${t}'`,"`"+t+"`"];for(let[t,a]of Object.entries(e))!r.has(t)&&i.some(e=>a.includes(e))&&(r.add(t),n.push(t))}return n}function s(e){let t=e.indexOf(`?`);return t===-1?e:e.slice(0,t)}function c(){return e(process.cwd()+`/`).href}export{i as a,a as i,o as n,t as r,r as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as e,A as t,At as n,B as r,C as i,Ct as a,D as o,Dt as s,E as c,Et as l,F as u,G as d,H as f,I as p,J as m,K as h,L as g,M as _,Mt as v,N as y,Nt as b,O as x,Ot as S,P as C,Q as w,R as T,S as E,St as D,T as O,Tt as k,U as A,V as j,W as M,X as N,Y as P,Z as F,_ as I,_t as L,a as R,at as z,b as B,bt as V,c as H,ct as U,d as W,dt as G,et as K,f as q,ft as J,g as Y,gt as X,h as Z,ht as Q,i as $,it as ee,j as te,jt as ne,k as re,kt as ie,l as ae,lt as oe,m as se,mt as ce,n as le,nt as ue,o as de,ot as fe,p as pe,pt as me,q as he,r as ge,rt as _e,s as ve,st as ye,t as be,tt as xe,u as Se,ut as Ce,v as we,vt as Te,w as Ee,wt as De,x as Oe,xt as ke,y as Ae,yt as je,z as Me}from"../_chunks/node/dist-
|
|
1
|
+
import{$ as e,A as t,At as n,B as r,C as i,Ct as a,D as o,Dt as s,E as c,Et as l,F as u,G as d,H as f,I as p,J as m,K as h,L as g,M as _,Mt as v,N as y,Nt as b,O as x,Ot as S,P as C,Q as w,R as T,S as E,St as D,T as O,Tt as k,U as A,V as j,W as M,X as N,Y as P,Z as F,_ as I,_t as L,a as R,at as z,b as B,bt as V,c as H,ct as U,d as W,dt as G,et as K,f as q,ft as J,g as Y,gt as X,h as Z,ht as Q,i as $,it as ee,j as te,jt as ne,k as re,kt as ie,l as ae,lt as oe,m as se,mt as ce,n as le,nt as ue,o as de,ot as fe,p as pe,pt as me,q as he,r as ge,rt as _e,s as ve,st as ye,t as be,tt as xe,u as Se,ut as Ce,v as we,vt as Te,w as Ee,wt as De,x as Oe,xt as ke,y as Ae,yt as je,z as Me}from"../_chunks/node/dist-CdH_Yoxt.js";export{be as Actions,K as BaseFormatConverter,le as Button,ge as Card,$ as CardLink,R as CardText,de as ChannelImpl,ve as Chat,H as ChatError,ae as ConsoleLogger,Se as DEFAULT_EMOJI_MAP,W as Divider,q as EmojiResolver,pe as ExternalSelect,se as Field,Z as Fields,Y as Image,I as LinkButton,we as LockError,Ae as Message,B as MessageHistoryCache,Oe as Modal,E as NotImplementedError,i as Plan,Ee as RadioSelect,O as RateLimitError,c as Section,o as Select,x as SelectOption,re as StreamingMarkdownRenderer,t as StreamingPlan,te as THREAD_STATE_TTL_MS,_ as Table,y as TextInput,C as ThreadHistoryCache,u as ThreadImpl,xe as blockquote,p as cardChildToFallbackText,ue as codeBlock,g as convertEmojiPlaceholders,T as createEmoji,Me as defaultEmojiResolver,r as deriveChannelId,j as emoji,_e as emphasis,f as fromFullStream,A as fromReactElement,M as fromReactModalElement,d as getEmoji,ee as getNodeChildren,z as getNodeValue,fe as inlineCode,ye as isBlockquoteNode,h as isCardElement,U as isCodeNode,oe as isDeleteNode,Ce as isEmphasisNode,G as isInlineCodeNode,he as isJSX,J as isLinkNode,me as isListItemNode,ce as isListNode,m as isModalElement,Q as isParagraphNode,P as isPostableObject,X as isStrongNode,L as isTableCellNode,Te as isTableNode,je as isTableRowNode,V as isTextNode,ke as link,D as markdownToPlainText,a as paragraph,De as parseMarkdown,N as reviver,k as root,l as strikethrough,s as stringifyMarkdown,S as strong,ie as tableElementToAscii,n as tableToAscii,ne as text,e as toAiMessages,F as toCardElement,w as toModalElement,v as toPlainText,b as walkAst};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) Pooya Parsa <pooya@pi0.io>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { IncomingMessage } from "node:http";
|
|
2
|
+
import type { Socket } from "node:net";
|
|
3
|
+
|
|
4
|
+
export interface WorkerHooks {
|
|
5
|
+
onClose?(runner: BaseEnvRunner, cause?: unknown): void;
|
|
6
|
+
onReady?(runner: BaseEnvRunner): void;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface BaseEnvRunnerOptions {
|
|
10
|
+
readonly data?: Record<string, unknown>;
|
|
11
|
+
readonly hooks?: WorkerHooks;
|
|
12
|
+
readonly name: string;
|
|
13
|
+
readonly workerEntry: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export class BaseEnvRunner {
|
|
17
|
+
readonly closed: boolean;
|
|
18
|
+
readonly ready: boolean;
|
|
19
|
+
protected readonly _data: Record<string, unknown> | undefined;
|
|
20
|
+
protected readonly _name: string;
|
|
21
|
+
protected readonly _workerEntry: string;
|
|
22
|
+
|
|
23
|
+
constructor(options: BaseEnvRunnerOptions);
|
|
24
|
+
|
|
25
|
+
close(cause?: unknown): Promise<void>;
|
|
26
|
+
fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
|
|
27
|
+
sendMessage(message: unknown): void;
|
|
28
|
+
upgrade(context: {
|
|
29
|
+
node: { head: Uint8Array; req: IncomingMessage; socket: Socket };
|
|
30
|
+
}): Promise<void>;
|
|
31
|
+
waitForReady(timeout?: number): Promise<void>;
|
|
32
|
+
|
|
33
|
+
protected _closeRuntime(): Promise<void>;
|
|
34
|
+
protected _handleMessage(message: unknown): void;
|
|
35
|
+
protected _hasRuntime(): boolean;
|
|
36
|
+
protected _initWithVirtualData(initialize: () => void): void;
|
|
37
|
+
protected _runtimeType(): string;
|
|
38
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e}from"../_chunks/node/virtual-loader-B8K8w9cr.js";import{Readable as t}from"node:stream";import{rm as n}from"node:fs/promises";import r,{request as i}from"node:http";import a,{request as o}from"node:https";import"node:http2";const s=/(^|,)\s*upgrade\s*($|,)/i,c=/(^|,)\s*transfer-encoding\s*($|,)/i,l={http:new r.Agent({keepAlive:!0,maxSockets:256,maxFreeSockets:64}),https:new a.Agent({keepAlive:!0,maxSockets:256,maxFreeSockets:64})},u=/^https|wss/;function d(e){let t=!1;for(let n in e)if(e[n]!==void 0&&n.toLowerCase()===`transfer-encoding`){t=!0;break}let n=e.connection,r=typeof n==`string`&&c.test(n);(t||r)&&(e.connection=`close`)}const f=[`:method`,`:path`,`:scheme`,`:authority`];function p(e,t,n,r){e.port=t[r||`target`].port||(u.test(t[r||`target`].protocol??`http`)?443:80);for(let n of[`host`,`hostname`,`socketPath`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`secureProtocol`]){let i=t[r||`target`][n];i!==void 0&&(e[n]=i)}if(e.host===void 0&&typeof e.hostname==`string`){let t=e.hostname.includes(`:`)&&!e.hostname.startsWith(`[`)?`[${e.hostname}]`:e.hostname;e.host=e.port?`${t}:${e.port}`:t}if(e.method=t.method||n.method,e.headers={...n.headers},n.headers?.[`:authority`]&&(e.headers.host=n.headers[`:authority`]),t.headers)for(let n of Object.keys(t.headers))e.headers[n]=t.headers[n];if(n.httpVersionMajor>1)for(let t of f)delete e.headers[t];if(t.auth&&(e.auth=t.auth),t.ca&&(e.ca=t.ca),u.test(t[r||`target`].protocol??`http`)&&(e.rejectUnauthorized=t.secure===void 0?!0:t.secure),t.agent!==void 0)e.agent=t.agent||!1;else if(n.httpVersionMajor>1||s.test(n.headers.connection||``))e.agent=!1;else{let n=t[r||`target`].protocol??`http`;e.agent=u.test(n)?l.https:l.http}e.localAddress=t.localAddress,e.agent||(e.headers=e.headers||{},(typeof e.headers.connection!=`string`||!s.test(e.headers.connection))&&(e.headers.connection=`close`)),e.headers=e.headers||{},d(e.headers);let i=t[r||`target`],a=i&&t.prependPath!==!1&&i.pathname||``,o=i instanceof URL&&t.prependPath!==!1&&i.search||``,c=n.url||``,p=c.indexOf(`?`),h=p===-1?c:c.slice(0,p),g=p===-1?``:c.slice(p),_=h?h[0]===`/`?h:`/`+h:`/`,v=t.toProxy?`/`+c:_+g;v=t.ignorePath?``:v;let y=m(a,v);return o&&(y=y.includes(`?`)?y.replace(`?`,o+`&`):y+o),e.path=y,t.changeOrigin&&(e.headers.host=x(e.port,t[r||`target`].protocol)&&!b(e.host)?e.host+`:`+e.port:e.host??void 0),e}function m(e,t){if(!e||e===`/`)return t||`/`;if(!t||t===`/`)return e||`/`;let n=e[e.length-1]===`/`,r=t[0]===`/`;return n&&r?e+t.slice(1):!n&&!r?e+`/`+t:e+t}function h(e){return e.setTimeout(0),e.setNoDelay(!0),e.setKeepAlive(!0,0),e}function g(e){let t=e.headers[`:authority`]||e.headers.host,n=t?t.match(/:(\d+)/):``;return n?n[1]:_(e)?`443`:`80`}function _(e){let t=e.socket;return!!t&&`encrypted`in t&&t.encrypted}function v(e,t,n){return Array.isArray(e)?e.map(function(e){return v(e,t,n)}):e.replace(RegExp(String.raw`(;\s*`+n+`=)([^;]+)`,`i`),function(e,n,r){let i;if(r in t)i=t[r];else if(`*`in t)i=t[`*`];else return e;return i?n+i:``})}function y(e){if(typeof e==`string`){if(e.startsWith(`unix:`))return{socketPath:e.slice(5)};let t=new URL(e);return{host:t.hostname,port:Number(t.port)||(u.test(t.protocol)?443:80)}}if(!e.socketPath&&!e.port)throw Error("ProxyAddr must have either `port` or `socketPath`");return e}function b(e){return e?!!~e.indexOf(`:`):!1}function x(e,t){let n=t?.split(`:`)[0],r=+e;if(!r)return!1;switch(n){case`http`:case`ws`:return r!==80;case`https`:case`wss`:return r!==443;case`ftp`:return r!==21;case`gopher`:return r!==70;case`file`:return!1}return r!==0}async function S(e,n,r,a){let s=y(e),c=!1,d=``;if(typeof e==`string`&&!e.startsWith(`unix:`)){let t=new URL(e);c=u.test(t.protocol),t.pathname&&t.pathname!==`/`&&(d=t.pathname)}let f,p;n instanceof Request?(f=new URL(n.url),p={...C(n),...C(r)}):(f=new URL(n),p=C(r)),p={redirect:`manual`,...p},p.body&&(p.duplex=`half`);let h=f.pathname+f.search,g=d?m(d,h):h,_={};if(p.headers)if(!(p.headers instanceof Headers)&&!Array.isArray(p.headers))Object.assign(_,p.headers);else for(let[e,t]of p.headers){let n=_[e];n===void 0?_[e]=t:_[e]=Array.isArray(n)?[...n,t]:[n,t]}if(a?.xfwd&&(_[`x-forwarded-for`]||=f.hostname,_[`x-forwarded-port`]||=f.port||(f.protocol===`https:`?`443`:`80`),_[`x-forwarded-proto`]||=f.protocol.replace(`:`,``),_[`x-forwarded-host`]||=f.host),a?.changeOrigin)if(s.socketPath)_.host=`localhost`;else{let e=s.host||`localhost`,t=s.port;_.host=t&&t!==(c?443:80)?`${e}:${t}`:e}let v=typeof a?.followRedirects==`number`?a.followRedirects:a?.followRedirects?5:0,b=v>0?await T(p.body):w(p.body),x=a?.agent===void 0?c?l.https:l.http:a.agent||!1,S=await D(c?o:i,p.method||`GET`,g,_,s,b,{signal:p.signal||void 0,agent:x,timeout:a?.timeout,ssl:a?.ssl,maxRedirects:v,redirectCount:0,originalHeaders:_}),E=[],O=S.rawHeaders;for(let e=0;e<O.length;e+=2){let t=O[e],n=t.toLowerCase();n===`transfer-encoding`||n===`keep-alive`||n===`connection`||E.push([t,O[e+1]])}let k=S.statusCode!==204&&S.statusCode!==304;return new Response(k?t.toWeb(S):null,{status:S.statusCode,statusText:S.statusMessage,headers:E})}function C(e){if(e)return e instanceof Request?{method:e.method,headers:e.headers,body:e.body,duplex:e.body?`half`:void 0}:e}function w(e){if(e)return typeof e==`string`||e instanceof ArrayBuffer||ArrayBuffer.isView(e)?Buffer.from(e):e instanceof ReadableStream?t.fromWeb(e):e instanceof Blob?t.fromWeb(e.stream()):Buffer.from(String(e))}async function T(e){if(e){if(typeof e==`string`||e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Buffer.from(e);if(e instanceof ReadableStream){let n=t.fromWeb(e),r=[];for await(let e of n)r.push(typeof e==`string`?Buffer.from(e):e);return Buffer.concat(r)}return e instanceof Blob?Buffer.from(await e.arrayBuffer()):Buffer.from(String(e))}}const E=new Set([301,302,303,307,308]);function D(e,n,r,a,s,c,l){return d(a),new Promise((d,f)=>{let p={method:n,path:r,headers:a,agent:l.agent};s.socketPath?p.socketPath=s.socketPath:(p.hostname=s.host||`localhost`,p.port=s.port),l.signal&&(p.signal=l.signal),l.ssl&&Object.assign(p,l.ssl);let m=e(p,e=>{let t=e.statusCode;if(l.maxRedirects>0&&E.has(t)&&l.redirectCount<l.maxRedirects&&e.headers.location){e.resume();let a=new URL(r,`http://${s.host||`localhost`}:${s.port||80}`),p=new URL(e.headers.location,a),m=u.test(p.protocol),h=t===307||t===308,g=h?n:`GET`,_={...l.originalHeaders};_.host=p.host,p.host!==a.host&&(delete _.authorization,delete _.cookie),h||(delete _[`content-length`],delete _[`content-type`],delete _[`transfer-encoding`]),D(m?o:i,g,p.pathname+p.search,_,{host:p.hostname,port:Number(p.port)||(m?443:80)},h?c:void 0,{...l,redirectCount:l.redirectCount+1}).then(d,f);return}d(e)});m.on(`error`,f),l.timeout&&m.setTimeout(l.timeout,()=>{m.destroy(Error(`Proxy request timed out`))}),c instanceof t?(c.on(`error`,e=>{m.destroy(e),f(e)}),c.pipe(m)):c?m.end(c):m.end()})}function O(e,t,n,r,a){let s=y(e),c=!1;if(typeof e==`string`&&!e.startsWith(`unix:`)&&(c=u.test(new URL(e).protocol)),t.method!==`GET`||t.headers.upgrade?.toLowerCase()!==`websocket`)return n.destroy(),Promise.reject(Error(`Not a valid WebSocket upgrade request`));if(a?.xfwd!==!1){let e=t.headers[`x-forwarded-for`],n=t.headers[`x-forwarded-port`],r=t.headers[`x-forwarded-proto`];t.headers[`x-forwarded-for`]=`${e?`${e},`:``}${t.socket?.remoteAddress}`,t.headers[`x-forwarded-port`]=`${n?`${n},`:``}${g(t)}`,t.headers[`x-forwarded-proto`]=`${r?`${r},`:``}${_(t)?`wss`:`ws`}`}let l=k(s,c),d={...a,target:l,prependPath:a?.prependPath!==!1},f=p(d.ssl||{},d,t),m=n;return new Promise((e,t)=>{let n=!1;h(m),r&&r.length>0&&m.unshift(r),m.once(`error`,s);let a=(u.test(l.protocol)?o:i)(f);a.once(`error`,c),a.once(`response`,e=>{e.upgrade||(!m.destroyed&&m.writable?(m.write(A(`HTTP/${e.httpVersion} ${e.statusCode} ${e.statusMessage}`,e.headers)),e.on(`error`,c),e.pipe(m)):e.resume(),n||(n=!0,t(Error(`Upstream server did not upgrade the connection`))))}),a.once(`upgrade`,(t,r,i)=>{r.once(`error`,c),m.removeListener(`error`,s),m.once(`error`,()=>{r.end()}),h(r),i&&i.length>0&&r.unshift(i),m.write(A(`HTTP/1.1 101 Switching Protocols`,t.headers)),r.pipe(m).pipe(r),n=!0,e(r)}),a.end();function s(e){a.destroy(),n||(n=!0,t(e))}function c(e){m.end(),n||(n=!0,t(e))}})}function k(e,t=!1){let n=t?`https`:`http`;if(e.socketPath){let t=new URL(`${n}://unix`);return t.socketPath=e.socketPath,t}return new URL(`${n}://${e.host||`localhost`}${e.port?`:${e.port}`:``}`)}function A(e,t){let n=e;for(let e of Object.keys(t)){let r=t[e];if(r!==void 0)if(Array.isArray(r))for(let t of r)n+=`\r\n${e}: ${t}`;else n+=`\r\n${e}: ${r}`}return`${n}\r\n\r\n`}var j=class{closed=!1;_name;_workerEntry;_data;_virtualSources;_hooks;_address;_messageListeners;_pendingRequests;_virtualResolved;constructor(e){this._name=e.name,this._workerEntry=e.workerEntry,this._data=e.data,this._hooks=e.hooks||{},this._messageListeners=new Set,this._pendingRequests=new Set}get ready(){return!!(!this.closed&&this._address&&this._hasRuntime())}async fetch(e,t){for(let e=0;e<5&&!this._address&&!this.closed;e++)await new Promise(t=>setTimeout(t,100*2**e));return this._address?S(this._address,this._resolveFetchInput(e),t):new Response(`${this._runtimeType()} env runner is unavailable`,{status:503})}async upgrade(e){!this.ready||!this._address||await O(this._address,e.node.req,e.node.socket,e.node.head)}onMessage(e){this._messageListeners.add(e)}offMessage(e){this._messageListeners.delete(e)}waitForReady(e=5e3){return this.ready?Promise.resolve():this.closed?Promise.reject(Error(`Runner closed before becoming ready`)):new Promise((t,n)=>{let r=setTimeout(()=>{this._messageListeners.delete(i),n(Error(`Runner did not become ready in time`))},e),i=()=>{this.ready?(clearTimeout(r),this._messageListeners.delete(i),t()):this.closed&&(clearTimeout(r),this._messageListeners.delete(i),n(Error(`Runner closed before becoming ready`)))};this._messageListeners.add(i)})}rpc(e,t,n){let r=Math.random().toString(36).slice(2);return this._request({__rpc:e,__rpc_id:r,data:t},{match:e=>e?.__rpc_id===r,timeout:n?.timeout??3e3,timeoutError:`RPC "${e}" timed out`}).then(e=>e.data)}async reloadModule(e=5e3){await this._request({event:`reload-module`},{match:e=>e?.event===`module-reloaded`,timeout:e,timeoutError:`Module reload timed out`})}async invalidateModule(e,t=5e3){let n=await this._refreshVirtualSource(e);await this._request({event:`invalidate-module`,specifier:e,source:n},{match:t=>t?.event===`module-invalidated`&&t.specifier===e,timeout:t,timeoutError:`Module invalidation timed out for "${e}"`})}async close(e){if(this.closed)return;this.closed=!0;for(let t of this._pendingRequests)t(e);this._pendingRequests.clear(),this._hooks.onClose?.(this,e),this._hooks={};let t=e=>console.error(e);await this._closeRuntime().catch(t),await this._closeSocket().catch(t)}async[Symbol.asyncDispose](){await this.close()}[Symbol.for(`nodejs.util.inspect.custom`)](){let e=this.closed?`closed`:this.ready?`ready`:`pending`;return`${this.constructor.name}#${this._name}(${e})`}_resolveFetchInput(e){return typeof e==`string`&&!URL.canParse(e)?new URL(e,`http://localhost`):e}_handleMessage(e){e?.address&&(this._address=e.address,this._hooks.onReady?.(this,this._address)),e?.event===`init-error`&&!this.ready&&!this.closed&&this.close(Error(String(e.error||`Worker initialization failed`)));for(let t of this._messageListeners)t(e)}_request(e,t){return this.closed?Promise.reject(Error(`Runner is closed`)):new Promise((n,r)=>{let i=setTimeout(()=>{s(),r(Error(t.timeoutError))},t.timeout),a=e=>{t.match(e)&&(s(),e.error?r(typeof e.error==`string`?Error(e.error):e.error):n(e))},o=e=>{s(),r(Error(`Runner closed before responding`,e?{cause:e}:void 0))},s=()=>{clearTimeout(i),this.offMessage(a),this._pendingRequests.delete(o)};this.onMessage(a),this._pendingRequests.add(o);try{(t.send??(e=>this.sendMessage(e)))(e)}catch(e){s(),r(e)}})}_resolveVirtualData(){let t=this._data?.virtual;if(this._virtualSources=t,!(!t||!Object.values(t).some(e=>typeof e==`function`)))return this._virtualResolved=e(t).then(e=>{this._data={...this._data,virtual:e}}),this._virtualResolved}async _refreshVirtualSource(e){await this._virtualResolved?.catch(()=>{});let t=this._virtualSources?.[e];if(typeof t!=`function`)return;let n=await t(),r=this._data?.virtual;return r&&(r[e]=n),n}_initWithVirtualData(e){let t=this._resolveVirtualData();t?t.then(()=>{this.closed||e()},e=>this.close(e)):e()}async _closeSocket(){let e=this._address?.socketPath;e&&e[0]!==`\0`&&!e.startsWith(String.raw`\\.\\pipe`)&&await n(e).catch(()=>{}),this._address=void 0}};export{j as BaseEnvRunner};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{a as e,i as t,n,t as r}from"../_chunks/node/virtual-loader-B8K8w9cr.js";import{createRequire as i}from"node:module";import{isAbsolute as a}from"node:path";import{pathToFileURL as o}from"node:url";import{existsSync as s,readFileSync as c}from"node:fs";import{Readable as l}from"node:stream";import u from"node:http";import d from"node:https";import f from"node:http2";import{parentPort as p,workerData as m}from"node:worker_threads";import{pipeline as h}from"node:stream/promises";async function g(e){if(!e||Object.keys(e).length===0)return C;let{registerHooks:t,stripTypeScriptTypes:n}=await import(`node:module`);if(typeof t==`function`){let i;if(`Deno`in globalThis){i=(e,t)=>S(e,t,n);let t={};for(let[n,r]of Object.entries(e))t[n]=i(n,r);e=t}let a={virtual:e,versions:new Map,transformSource:i},o=t(r(e,a.versions));return y.unshift(a),w(()=>{let e=y.indexOf(a);e!==-1&&y.splice(e,1),o.deregister()})}return typeof globalThis.Bun?.plugin==`function`?(b=e,x(Object.keys(e)),w(()=>{b===e&&(b=void 0)})):(console.warn("[env-runner] virtual modules require `module.registerHooks` (Node.js >= 22.15 / Deno >= 2.x) or `Bun.plugin`; skipping registration."),C)}function _(e){return b?.[e]===void 0?!1:(x([e]),!0)}function v(e,t){for(let r of y){if(!Object.hasOwn(r.virtual,e))continue;let{virtual:i,versions:a,transformSource:o}=r;t!==void 0&&(i[e]=o?o(e,t):t);for(let t of n(i,e))a.set(t,(a.get(t)??0)+1);return!0}return b&&Object.hasOwn(b,e)?(t!==void 0&&(b[e]=t),x(n(b,e)),!0):!1}function ee(e,t){let n=v(e.specifier,e.source);t({event:`module-invalidated`,specifier:e.specifier,error:n?void 0:`Cannot invalidate "${e.specifier}" (not a registered virtual module)`})}const y=[];let b;function x(t){globalThis.Bun.plugin({name:`env-runner-virtual`,setup(n){for(let r of t)n.module(r,()=>{let t=b?.[r];if(t===void 0)throw Error(`Cannot find virtual module "${r}" (unregistered)`);let n=e(r);return n===`json`?{exports:{default:JSON.parse(t)},loader:`object`}:{contents:t,loader:n===`module-typescript`?`ts`:`js`}})}})}function S(n,r,i){let a=e(n);return a===`module-typescript`?t(n,r,i,{requirement:`(custom load hooks bypass Deno's native type stripping)`,remedy:`upgrade Deno`}):a===`json`?`export default JSON.parse(${JSON.stringify(r)});`:r}const C=()=>{};function w(e){let t=!1;return()=>{t||(t=!0,e())}}function te(e,t){return!!(e&&t&&Object.hasOwn(t,e))}async function ne(e,t){let n=await(t?import(e):import(ae(e))),r=n.default||n;if(typeof r.fetch!=`function`)throw Error(`[env-runner] Entry module "${e}" must export a \`fetch\` handler (export default { fetch(req) { ... } }).`);return r}function re(e){let t=new URL(e.url);return{host:t.hostname,port:Number(t.port)}}async function ie(e,t,n,r){await t.ipc?.onClose?.();let i=await E(e,r);return await i.ipc?.onOpen?.({sendMessage:n}),i}function ae(e){let t=e.indexOf(`?`),n=t===-1?e:e.slice(0,t),r=t===-1?``:e.slice(t);return a(n)?o(n).href+r:e}let T=0;async function E(e,t){let n=e.indexOf(`?`),r=n===-1?e:e.slice(0,n),i;if(!t&&s(r)){let e=c(r,`utf8`);i=await import(`data:text/javascript;base64,`+Buffer.from(e).toString(`base64`))}else i=t&&_(r)?await import(r):await import(e+(n===-1?`?`:`&`)+`__envRunnerReload=`+ T++);let a=i.default||i;if(typeof a.fetch!=`function`)throw Error(`[env-runner] Entry module "${e}" must export a \`fetch\` handler (export default { fetch(req) { ... } }).`);return a}function D(e,t,n){for(let r of[...Object.getOwnPropertyNames(t),...Object.getOwnPropertySymbols(t)]){if(r===`constructor`)continue;let i=Object.getOwnPropertyDescriptor(e,r),a=Object.getOwnPropertyDescriptor(t,r),o=!1;a.get&&=(o=!0,i?.get||function(){return this[n][r]}),a.set&&=(o=!0,i?.set||function(e){this[n][r]=e}),!i?.value&&typeof a.value==`function`&&(o=!0,a.value=function(...e){return this[n][r](...e)}),o&&Object.defineProperty(e,r,a)}}const O=/(?:(?:^|\/)(?:\.|\.\.|%2e|%2e\.|\.%2e|%2e%2e)(?:\/|$))|[\\^#"<>{}`\x80-\uffff]/i,k=/[#"'<>]/,A=(()=>{let e=globalThis.URL,t=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(t){if(typeof t==`string`){let n=t[0]===`/`;n&&!k.test(t)?this.#t=t:this.#e=new e(n?`http://localhost${t}`:t)}else O.test(t.pathname)||t.search&&k.test(t.search)?this.#e=new e(`${t.protocol||`http:`}//${t.host||`localhost`}${t.pathname}${t.search||``}`):(this.#n=t.protocol,this.#r=t.host,this.#i=t.pathname,this.#a=t.search)}static[Symbol.hasInstance](t){return t instanceof e}get _url(){return this.#e?this.#e:(this.#e=new e(this.href),this.#t=void 0,this.#n=void 0,this.#r=void 0,this.#i=void 0,this.#a=void 0,this.#o=void 0,this.#s=void 0,this.#e)}get href(){return this.#e?this.#e.href:(this.#t||=`${this.#n||`http:`}//${this.#r||`localhost`}${this.#i||`/`}${this.#a||``}`,this.#t)}#c(){if(!this.#s){let e=this.href,t=e.indexOf(`://`),n=t===-1?-1:e.indexOf(`/`,t+4),r=n===-1?-1:e.indexOf(`?`,n);this.#s=[t,n,r]}return this.#s}get pathname(){if(this.#e)return this.#e.pathname;if(this.#i===void 0){let[,e,t]=this.#c();if(e===-1)return this._url.pathname;this.#i=this.href.slice(e,t===-1?void 0:t)}return this.#i}get search(){if(this.#e)return this.#e.search;if(this.#a===void 0){let[,e,t]=this.#c();if(e===-1)return this._url.search;let n=this.href;this.#a=t===-1||t===n.length-1?``:n.slice(t)}return this.#a}get searchParams(){return this.#e?this.#e.searchParams:(this.#o||=new URLSearchParams(this.search),this.#o)}get protocol(){if(this.#e)return this.#e.protocol;if(this.#n===void 0){let[e]=this.#c();if(e===-1)return this._url.protocol;let t=this.href;this.#n=t.slice(0,e+1)}return this.#n}toString(){return this.href}toJSON(){return this.href}};return D(t.prototype,e.prototype,`_url`),Object.setPrototypeOf(t.prototype,e.prototype),Object.setPrototypeOf(t,e),t})();function oe(e){let t=e.port??globalThis.process?.env.PORT??3e3,n=typeof t==`number`?t:Number.parseInt(t,10);if(n<0||n>65535)throw RangeError(`Port must be between 0 and 65535 (got "${n}").`);return{port:n,hostname:e.hostname??globalThis.process?.env.HOST}}function se(e,t,n){if(!(!e||!t))return e.includes(`:`)&&(e=`[${e}]`),`http${n?`s`:``}://${e}:${t}/`}function j(e,t){if(!t||(e.silent??globalThis.process?.env?.TEST))return;let n=``;try{let e=new URL(t);(e.hostname===`[::]`||e.hostname===`0.0.0.0`)&&(e.hostname=`localhost`,t=e.href,n=` (all interfaces)`)}catch{}let r=`➜ Listening on:`;globalThis.process.stdout?.isTTY&&(r=`\u001B[32m${r}\u001B[0m`,t=`\u001B[36m${t}\u001B[0m`,n=`\u001B[2m${n}\u001B[0m`),console.log(`${r} ${t}${n}`)}function M(e){if(!e.tls||e.protocol===`http`)return;let t=N(e.tls.cert),n=N(e.tls.key);if(!t&&!n){if(e.protocol===`https`)throw TypeError("TLS `cert` and `key` must be provided for `https` protocol.");return}if(!t||!n)throw TypeError("TLS `cert` and `key` must be provided together.");return{cert:t,key:n,passphrase:e.tls.passphrase}}function N(e){if(!e)return;if(typeof e!=`string`)throw TypeError(`TLS certificate and key must be strings in PEM format or file paths.`);if(e.startsWith(`-----BEGIN `))return e;let{readFileSync:t}=process.getBuiltinModule(`node:fs`);return t(e,`utf8`)}function ce(){let e=new Set;return{waitUntil:t=>{typeof t?.then==`function`&&e.add(Promise.resolve(t).catch(console.error).finally(()=>{e.delete(t)}))},wait:()=>Promise.all(e)}}const le=(()=>{let e=globalThis.process?.env??{};return e.NO_COLOR===`1`||e.TERM===`dumb`})(),P=(e,t=39)=>n=>le?n:`\u001B[${e}m${n}\u001B[${t}m`,ue=P(1,22),de=P(31),fe=P(32),F=P(90);function pe(e){let t=e.options.fetch,n=e.options.middleware||[];return n.length===0?t:e=>I(e,t,n,0)}function I(e,t,n,r){return r===n.length?t(e):n[r](e,()=>I(e,t,n,r+1))}const L=e=>{let t=e.options.error;t&&e.options.middleware.unshift((e,n)=>{try{let e=n();return e instanceof Promise?e.catch(e=>t(e)):e}catch(e){return t(e)}})},R=e=>{let t=e.options?.gracefulShutdown;if(!globalThis.process?.on||t===!1||t===void 0&&(process.env.CI||process.env.TEST))return;let n=t===!0||!t?.gracefulTimeout?Number.parseInt(process.env.SERVER_SHUTDOWN_TIMEOUT||``)||5:t.gracefulTimeout,r=!1,i=!1,a=e.options.silent?()=>{}:process.stderr.write.bind(process.stderr),o=async()=>{i||(a(de(`\x1B[2K\rForcibly closing connections...
|
|
2
|
+
`)),i=!0,await e.close(!0))},s=async()=>{if(r||i)return;setTimeout(()=>{globalThis.process.once(`SIGINT`,o)},100),r=!0;let t=e.close();for(let e=n;e>0;e--)if(a(F(`\rStopping server gracefully (${e}s)... Press ${ue(`Ctrl+C`)} again to force close.`)),await Promise.race([t.then(()=>!0),new Promise(e=>setTimeout(()=>e(!1),1e3))])){a(`\x1B[2K\r`+fe(`Server closed successfully.
|
|
3
|
+
`)),i=!0;return}a(`\x1B[2K\rGraceful shutdown timed out.
|
|
4
|
+
`),await o()};for(let e of[`SIGINT`,`SIGTERM`])globalThis.process.on(e,s)};function z(e,t){if(e===void 0||e===!1)return!1;if(e===!0)return!0;if(e===`loopback`)return me(t);if(t===void 0)return!1;if(e.includes(t))return!0;let n=B(t);return n!==void 0&&e.includes(n)}function B(e){return e.startsWith(`::ffff:`)&&e.includes(`.`)?e.slice(7):void 0}function me(e){return!!e&&(e===`::1`||e.startsWith(`127.`)||e.startsWith(`::ffff:127.`))}const he=/^(\[(?:[A-Fa-f0-9:.]+)\]|(?:[A-Za-z0-9_-]+\.)*[A-Za-z0-9_-]+|(?:\d{1,3}\.){3}\d{1,3})(:\d{1,5})?$/;function V(e){if(e)return(Array.isArray(e)?e[0]:e).split(`,`)[0].trim()||void 0}function ge(e){return Object.assign(Error(`Request body exceeds the maximum allowed size of ${e} bytes.`),{code:`ERR_BODY_TOO_LARGE`,statusCode:413,status:413})}function _e(e,t){let n=e.getReader(),r=0;return new ReadableStream({async pull(e){let{done:i,value:a}=await n.read();if(i){e.close();return}if(r+=a.byteLength,r>t){let r=ge(t);n.cancel(r).catch(()=>{}),e.error(r);return}e.enqueue(a)},cancel(e){return n.cancel(e)}})}function ve(e,t){try{return be(e,t,!0)}catch(t){ye(e,t)}}function ye(e,t){e.headersSent?e.destroy():(e.statusCode=500,e.end())}function be(e,t,n){if(!t)return e.statusCode=500,U(e,n);if(t._toNodeResponse){let r=t._toNodeResponse();if(r.body){if(r.body instanceof ReadableStream)return H(e,r.status,r.statusText,r.headers),Se(r.body,e);if(typeof r.body?.pipe==`function`)return xe(r.body,e,r.status,r.statusText,r.headers);H(e,r.status,r.statusText,r.headers),e.write(r.body)}else H(e,r.status,r.statusText,r.headers);return U(e,n)}let r=[];for(let[e,n]of t.headers)r.push(e,n);return H(e,t.status,t.statusText,r),t.body?Se(t.body,e):U(e,n)}function H(e,t,n,r){e.headersSent||(e.req?.httpVersion===`2.0`?e.writeHead(t,r):e.writeHead(t,n,r))}function U(e,t){if(t){e.end();return}return new Promise(t=>e.end(t))}function xe(e,t,n,r,i){if(t.destroyed){e.destroy?.();return}return typeof e.on!=`function`||typeof e.destroy!=`function`?(H(t,n,r,i),e.pipe(t),new Promise(e=>t.on(`close`,e))):e.destroyed?(H(t,500,`Internal Server Error`,[]),U(t)):new Promise(a=>{function o(){e.off(`readable`,s),e.destroy(),H(t,500,`Internal Server Error`,[]),U(t).then(a)}function s(){if(e.off(`error`,o),t.destroyed)return e.destroy(),a();H(t,n,r,i),h(e,t).catch(()=>{}).then(()=>a())}e.once(`error`,o),e.once(`readable`,s)})}function Se(e,t){if(t.destroyed){e.cancel();return}let n=e.getReader();function r(e){n.cancel(e).catch(()=>{}),e&&t.destroy(e)}function i({done:e,value:a}){try{e?t.end():t.write(a)?n.read().then(i,r):t.once(`drain`,()=>n.read().then(i,r))}catch(e){r(e instanceof Error?e:void 0)}}return t.on(`close`,r),t.on(`error`,r),n.read().then(i,r),n.closed.catch(r).finally(()=>{t.off(`close`,r),t.off(`error`,r)})}var Ce=class extends A{constructor({req:e,trusted:t=!1}){let n=e.url||`/`,r=t?V(e.headers[`x-forwarded-host`]):void 0,i=(r&&he.test(r)?r:void 0)||e.headers.host||e.headers[`:authority`];i&&!he.test(i)?i=`_invalid_`:i||=e.socket?`${e.socket.localFamily===`IPv6`?`[`+e.socket.localAddress+`]`:e.socket.localAddress}:${e.socket?.localPort||`80`}`:`localhost`;let a=t?V(e.headers[`x-forwarded-proto`]):void 0,o=e.socket?.encrypted||a===`https`||t&&e.headers[`:scheme`]===`https`?`https:`:`http:`;if(n[0]===`/`){let e=n.indexOf(`?`);super({protocol:o,host:i,pathname:e===-1?n:n.slice(0,e)||`/`,search:e===-1?``:n.slice(e)||``})}else super(n===`*`?{protocol:o,host:i,pathname:`/*`,search:``}:n)}};const we=new Set([`age`,`authorization`,`content-length`,`content-type`,`etag`,`expires`,`from`,`host`,`if-modified-since`,`if-unmodified-since`,`last-modified`,`location`,`max-forwards`,`proxy-authorization`,`referer`,`retry-after`,`server`,`user-agent`]),Te=/^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/;function Ee(e,t){let n=!1;for(let r=0;r<e.length;r+=2){let i=e[r];if(i.length===t.length&&i.toLowerCase()===t){if(n)return!0;n=!0}}return!1}const De=(()=>{let e=globalThis.Headers;class t{#e;#t;constructor(e){this.#e=e}static[Symbol.hasInstance](t){return t instanceof e}get _headers(){if(!this.#t){let t=new e,n=this.#e.rawHeaders,r=n.length;for(let e=0;e<r;e+=2){let r=n[e];if(r.charCodeAt(0)===58)continue;let i=n[e+1];t.append(r,i)}this.#t=t}return this.#t}get(e){if(this.#t)return this.#t.get(e);let t=e.toLowerCase();if(t.charCodeAt(0)===58)return this._headers.get(e);let n=this.#e.headers[t];return typeof n==`string`?we.has(t)&&Ee(this.#e.rawHeaders,t)?this._headers.get(e):n:Array.isArray(n)?n.join(`, `):t!==`__proto__`&&Te.test(e)?null:this._headers.get(e)}has(e){if(this.#t)return this.#t.has(e);let t=e.toLowerCase();return t.charCodeAt(0)===58?this._headers.has(e):Object.hasOwn(this.#e.headers,t)?!0:t!==`__proto__`&&Te.test(e)?!1:this._headers.has(e)}getSetCookie(){if(this.#t)return this.#t.getSetCookie();let e=this.#e.headers[`set-cookie`];return Array.isArray(e)?e.slice():e?[e]:[]}entries(){return this._headers.entries()}[Symbol.iterator](){return this.entries()}}return D(t.prototype,e.prototype,`_headers`),Object.setPrototypeOf(t,e),Object.setPrototypeOf(t.prototype,e.prototype),t})(),Oe=Symbol.for(`srvx.nativeRequest`),ke=(()=>{let e=je();class t{runtime;waitUntil;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=!1;#u;#d;constructor(e){this.#e=e.req,this.#o=e.maxRequestBodySize,this.#s=e.trustProxy,this.runtime={name:`node`,node:e}}static[Symbol.hasInstance](t){return t instanceof e}#f(){return this.#d===void 0&&(this.#u=this.#e.socket?.remoteAddress,this.#d=z(this.#s,this.#u)),this.#d}get ip(){if(this.#l)return this.#c;if(this.#l=!0,this.#f()){let e=V(this.#e.headers[`x-forwarded-for`]);if(e)return this.#c=e}return this.#c=this.#u}get method(){return this.#r?this.#r.method:this.#e.method||`GET`}get _url(){return this.#t||=new Ce({req:this.#e,trusted:this.#f()})}set _url(e){this.#t=e}get url(){return this.#r?this.#r.url:this._url.href}get headers(){return this.#r?this.#r.headers:this.#i||=new De(this.#e)}get _abortController(){if(!this.#a){this.#a=new AbortController;let{req:e,res:t}=this.runtime.node,n=this.#a,r=e=>n.abort?.(e);t?t.once(`close`,()=>{let n=e.errored;n?r(n):t.writableEnded||r()}):e.once(`close`,()=>{e.complete||r()})}return this.#a}get signal(){return this.#r?this.#r.signal:this._abortController.signal}get body(){if(this.#r)return this.#r.body;if(this.#n===void 0){let e=this.method,t=e===`GET`||e===`HEAD`?null:l.toWeb(this.#e);t&&this.#o!==void 0&&(t=_e(t,this.#o)),this.#n=t}return this.#n}#p(){return Ae(this.#e,this.#o)}text(){return this.#r?this.#r.text():this.#n===void 0?this.#p().then(e=>e.toString()):this.#n?new Response(this.#n).text():Promise.resolve(``)}json(){return this.#r?this.#r.json():this.#n===void 0?this.#p().then(e=>JSON.parse(e.toString())):this.text().then(e=>JSON.parse(e))}get _request(){if(!this.#r){let t=this.body;this.#r=new e(this.url,{method:this.method,headers:this.headers,signal:this._abortController.signal,body:t,duplex:t?`half`:void 0}),this.#i=void 0,this.#n=void 0}return this.#r}}return D(t.prototype,e.prototype,`_request`),Object.setPrototypeOf(t.prototype,e.prototype),t})();function Ae(e,t){return`rawBody`in e&&Buffer.isBuffer(e.rawBody)?t!==void 0&&e.rawBody.length>t?Promise.reject(ge(t)):Promise.resolve(e.rawBody):new Promise((n,r)=>{let i=[],a=0,o=()=>{e.off(`data`,s),e.off(`end`,l),e.off(`error`,c)},s=n=>{if(t!==void 0&&(a+=n.length,a>t)){o(),e.pause?.(),r(ge(t));return}i.push(n)},c=e=>{o(),r(e)},l=()=>{o(),n(i.length===1?i[0]:Buffer.concat(i))};e.on(`data`,s).once(`end`,l).once(`error`,c)})}function je(){let e=globalThis[Oe]||globalThis.Request;for(;e?._srvx;)e=Object.getPrototypeOf(e);return globalThis[Oe]??=e}function Me(e){return new Ne(e)}var Ne=class{runtime=`node`;options;node;serveOptions;fetch;waitUntil;#e;#t;#n;#r;constructor(e){this.options={...e,middleware:[...e.middleware||[]]};for(let t of e.plugins||[])t(this);L(this);let t=this.fetch=pe(this),n=(e,n)=>{let r=e.url;if(r&&r[0]!==`/`&&r!==`*`&&!URL.canParse(r)){n.statusCode=400,n.end();return}let i=new ke({req:e,res:n,maxRequestBodySize:this.options.maxRequestBodySize,trustProxy:this.options.trustProxy});i.waitUntil=this.#r?.waitUntil;let a=t(i);return a instanceof Promise?a.then(e=>ve(n,e)):ve(n,a)};this.node={handler:n,server:void 0};let r=globalThis.__srvxLoader__;if(r){r({server:this});return}R(this),this.#r=ce(),this.waitUntil=this.#r.waitUntil;let i=M(this.options),{port:a,hostname:o}=oe(this.options);this.serveOptions={port:a,host:o,exclusive:!this.options.reusePort,...i,...this.options.node};let s;if(this.#e=!!this.serveOptions.cert&&this.options.protocol!==`http`,this.options.node?.http2??this.#e)if(this.#e)s=f.createSecureServer({allowHTTP1:!0,...this.serveOptions},n);else throw Error(`node.http2 option requires tls certificate!`);else s=this.#e?d.createServer(this.serveOptions,n):u.createServer(this.serveOptions,n);this.node.server=s,e.manual||this.serve().catch(()=>{})}serve(){if(this.#t)return this.#t.then(()=>this);let e=this.node?.server;return e?(this.#n=void 0,this.#t=new Promise((t,n)=>{let r=t=>{e.off(`listening`,i),this.#n=t,this.#t=void 0,n(t)},i=()=>{e.off(`error`,r),j(this.options,this.url),t()};e.once(`error`,r),e.once(`listening`,i),e.listen(this.serveOptions)}),this.#t.then(()=>this)):Promise.reject(Error(`Server not initialized`))}get url(){let e=this.node?.server?.address();if(e)return typeof e==`string`?e:se(e.address,e.port,this.#e)}ready(){return this.#n?Promise.reject(this.#n):Promise.resolve(this.#t).then(()=>this)}async close(e){await Promise.all([this.#r?.wait(),new Promise((t,n)=>{let r=this.node?.server;if(r&&e&&`closeAllConnections`in r&&r.closeAllConnections(),!r||!r.listening)return t();r.close(e=>e?n(e):t())})])}},Pe=Object.create,Fe=Object.defineProperty,Ie=Object.getOwnPropertyDescriptor,Le=Object.getOwnPropertyNames,Re=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty,W=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Be=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Le(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ze.call(e,s)&&s!==n&&Fe(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ie(t,s))||r.enumerable});return e},Ve=(e,t,n)=>(n=e==null?{}:Pe(Re(e)),Be(t||!e||!e.__esModule?Fe(n,`default`,{value:e,enumerable:!0}):n,e)),G=i(import.meta.url),K=W(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),q=W(((e,t)=>{let{EMPTY_BUFFER:n}=K(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=G(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),He=W(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),J=W(((e,t)=>{let n=G(`zlib`),r=q(),i=He(),{kStatusCode:a}=K(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e){this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),Y=W(((e,t)=>{let{isUtf8:n}=G(`buffer`),{hasBlob:r}=K(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=G(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),Ue=W(((e,t)=>{let{Writable:n}=G(`stream`),r=J(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=K(),{concat:c,toArrayBuffer:l,unmask:u}=q(),{isValidStatusCode:d,isValidUTF8:f}=Y(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,`Too many buffered chunks`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}if(t.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){e(this.createError(RangeError,`Too many message fragments`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}this._messageLength=this._totalPayloadLength,this._fragments.push(t)}this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){t(this.createError(RangeError,`Too many message fragments`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),We=W(((e,t)=>{let{Duplex:n}=G(`stream`),{randomFillSync:r}=G(`crypto`),{types:{isUint8Array:i}}=G(`util`),a=J(),{EMPTY_BUFFER:o,kWebSocket:s,NOOP:c}=K(),{isBlob:l,isValidStatusCode:u}=Y(),{mask:d,toBuffer:f}=q(),p=Symbol(`kByteLength`),m=Buffer.alloc(4),h=8*1024,g,_=h;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=c,this[s]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||m,t.generateMask?t.generateMask(n):(_===h&&(g===void 0&&(g=Buffer.alloc(h)),r(g,0,h),_=0),n[0]=g[_++],n[1]=g[_++],n[2]=g[_++],n[3]=g[_++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[p]!==void 0?s=t[p]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(d(e,n,l,a,s),[l]):(d(e,n,e,0,s),[l,e])}close(t,n,r,a){let s;if(t===void 0)s=o;else if(typeof t!=`number`||!u(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);if(s=Buffer.allocUnsafe(2+e),s.writeUInt16BE(t,0),typeof n==`string`)s.write(n,2);else if(i(n))s.set(n,2);else throw TypeError(`Second argument must be a string or a Uint8Array`)}let c={[p]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(s,c),a):this.enqueue([this.dispatch,s,!1,c,a])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):l(t)?(i=t.size,a=!1):(t=f(t),i=t.length,a=f.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[p]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};l(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):l(t)?(i=t.size,a=!1):(t=f(t),i=t.length,a=f.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[p]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};l(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[a.extensionName],i=t.binary?2:1,o=t.compress,s,c;typeof e==`string`?(s=Buffer.byteLength(e),c=!1):l(e)?(s=e.size,c=!1):(e=f(e),s=e.length,c=f.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let u={[p]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};l(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[p],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(v,this,e,i);return}this._bufferedBytes-=r[p];let a=f(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(ee,this,e,i)})}dispatch(t,n,r,i){if(!n){this.sendFrame(e.frame(t,r),i);return}let o=this._extensions[a.extensionName];this._bufferedBytes+=r[p],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){let e=Error(`The socket was closed while data was being compressed`);v(this,e,i);return}this._bufferedBytes-=r[p],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][p],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][p],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function v(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function ee(e,t,n){v(e,t,n),e.onerror(t)}})),Ge=W(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=K(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,"target",{enumerable:!0}),Object.defineProperty(f.prototype,"type",{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,"code",{enumerable:!0}),Object.defineProperty(p.prototype,"reason",{enumerable:!0}),Object.defineProperty(p.prototype,"wasClean",{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,"error",{enumerable:!0}),Object.defineProperty(m.prototype,"message",{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,"data",{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),Ke=W(((e,t)=>{let{tokenChars:n}=Y();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),qe=W(((e,t)=>{let n=G(`events`),r=G(`https`),i=G(`http`),a=G(`net`),o=G(`tls`),{randomBytes:s,createHash:c}=G(`crypto`),{Duplex:l,Readable:u}=G(`stream`),{URL:d}=G(`url`),f=J(),p=Ue(),m=We(),{isBlob:h}=Y(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:ee,kForOnEventAttribute:y,kListener:b,kStatusCode:x,kWebSocket:S,NOOP:C}=K(),{EventTarget:{addEventListener:w,removeEventListener:te}}=Ge(),{format:ne,parse:re}=Ke(),{toBuffer:ie}=q(),ae=Symbol(`kAborted`),T=[8,13],E=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],D=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var O=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),k(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[S]=this,a[S]=this,t[S]=this,i.on(`conclude`,N),i.on(`drain`,ce),i.on(`error`,le),i.on(`message`,ue),i.on(`ping`,de),i.on(`pong`,fe),a.onerror=pe,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,L),t.on(`data`,R),t.on(`end`,z),t.on(`error`,B),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){j(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),I(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){M(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){M(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){M(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){j(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(O,"CONNECTING",{enumerable:!0,value:E.indexOf(`CONNECTING`)}),Object.defineProperty(O.prototype,"CONNECTING",{enumerable:!0,value:E.indexOf(`CONNECTING`)}),Object.defineProperty(O,"OPEN",{enumerable:!0,value:E.indexOf(`OPEN`)}),Object.defineProperty(O.prototype,"OPEN",{enumerable:!0,value:E.indexOf(`OPEN`)}),Object.defineProperty(O,"CLOSING",{enumerable:!0,value:E.indexOf(`CLOSING`)}),Object.defineProperty(O.prototype,"CLOSING",{enumerable:!0,value:E.indexOf(`CLOSING`)}),Object.defineProperty(O,"CLOSED",{enumerable:!0,value:E.indexOf(`CLOSED`)}),Object.defineProperty(O.prototype,"CLOSED",{enumerable:!0,value:E.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(O.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(O.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[y])return t[b];return null},set(t){for(let t of this.listeners(e))if(t[y]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[y]:!0})}})}),O.prototype.addEventListener=w,O.prototype.removeEventListener=te,t.exports=O;function k(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:T[1],maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!T.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${T.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;A(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,y=new Set,b;if(o.createConnection=o.createConnection||(u?se:oe),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new f({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers[`Sec-WebSocket-Extensions`]=ne({[f.extensionName]:b.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!D.test(e)||y.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);y.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let x;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),x=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,x)}else x=e._req=v(o);o.timeout&&x.on(`timeout`,()=>{j(e,x,`Opening handshake has timed out`)}),x.on(`error`,t=>{x===null||x[ae]||(x=e._req=null,A(e,t))}),x.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){j(e,x,`Maximum redirects exceeded`);return}x.abort();let r;try{r=new d(i,t)}catch{A(e,SyntaxError(`Invalid URL: ${i}`));return}k(e,r,n,a)}else e.emit(`unexpected-response`,x,r)||j(e,x,`Unexpected server response: ${r.statusCode}`)}),x.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==O.CONNECTING)return;x=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){j(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+ee).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){j(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?y.size&&(l=`Server sent no subprotocol`):y.size?y.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){j(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!b){j(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=re(u)}catch{j(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){j(e,n,`Server indicated an extension that was not requested`);return}try{b.accept(t[f.extensionName])}catch{j(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=b}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(x,e):x.end()}function A(e,t){e._readyState=O.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function oe(e){return e.path=e.socketPath,a.connect(e)}function se(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function j(e,t,n){e._readyState=O.CLOSING;let r=Error(n);Error.captureStackTrace(r,j),t.setHeader?(t[ae]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(A,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function M(e,t,n){if(t){let n=h(t)?t.size:ie(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${E[e.readyState]})`);process.nextTick(n,t)}}function N(e,t){let n=this[S];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[S]!==void 0&&(n._socket.removeListener(`data`,R),process.nextTick(F,n._socket),e===1005?n.close():n.close(e,t))}function ce(){let e=this[S];e.isPaused||e._socket.resume()}function le(e){let t=this[S];t._socket[S]!==void 0&&(t._socket.removeListener(`data`,R),process.nextTick(F,t._socket),t.close(e[x])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function P(){this[S].emitClose()}function ue(e,t){this[S].emit(`message`,e,t)}function de(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,C),t.emit(`ping`,e)}function fe(e){this[S].emit(`pong`,e)}function F(e){e.resume()}function pe(e){let t=this[S];t.readyState!==O.CLOSED&&(t.readyState===O.OPEN&&(t._readyState=O.CLOSING,I(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function I(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function L(){let e=this[S];if(this.removeListener(`close`,L),this.removeListener(`data`,R),this.removeListener(`end`,z),e._readyState=O.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[S]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,P),e._receiver.on(`finish`,P))}function R(e){this[S]._receiver.write(e)||this.pause()}function z(){let e=this[S];e._readyState=O.CLOSING,e._receiver.end(),this.end()}function B(){let e=this[S];this.removeListener(`error`,B),this.on(`error`,C),e&&(e._readyState=O.CLOSING,this.destroy())}})),Je=W(((e,t)=>{qe();let{Duplex:n}=G(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),Ye=W(((e,t)=>{let{tokenChars:n}=Y();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),Xe=W(((e,t)=>{let n=G(`events`),r=G(`http`),{Duplex:i}=G(`stream`),{createHash:a}=G(`crypto`),o=Ke(),s=J(),c=Ye(),l=qe(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=K(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
|
|
5
|
+
`).join(`\r
|
|
6
|
+
`)),i.removeListener(`error`,g),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)})),l(p,r)}};function m(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function h(e){e._state=2,e.emit(`close`)}function g(){this.destroy()}function _(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
|
|
7
|
+
`)+`\r
|
|
8
|
+
\r
|
|
9
|
+
`+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}}));Je(),Ke(),J(),Ue(),We(),Ye(),qe();var Ze=Ve(Xe(),1),Qe=class{options;#e=new WeakMap;constructor(e){this.options=e||{}}callHook(e,t,n,r){let i=this.options.hooks?.[e],a=i?.(t,n),o=this.options.resolve;if(!o)return a;let s=t.request||t,c=r||t.context||s,l;if(this.#e.has(c))l=this.#e.get(c);else{try{l=o(s)}catch(e){l=Promise.reject(e)}this.#e.set(c,l),l instanceof Promise&&l.catch(()=>{this.#e.get(c)===l&&this.#e.delete(c)})}if(!l)return a;let u=l instanceof Promise?l.then(t=>t?.[e]):l?.[e];return Promise.all([a,u]).then(([e,r])=>{let i=r?.(t,n);return i instanceof Promise?i.then(t=>t||e):i||e})}async upgrade(e){let t=this.options.getNamespace?.(e)??new URL(e.url).pathname,n=e.context||{},r,i;try{let a=await this.callHook(`upgrade`,e,void 0,n);if(a){if(a.namespace&&(t=a.namespace),a.context&&Object.assign(n,a.context),a instanceof Response)return{context:n,namespace:t,endResponse:a};if(a.handled)return{context:n,namespace:t,handled:!0};r=a.headers,i=a.protocol}}catch(e){let r=e.response||e;if(r instanceof Response)return{context:n,namespace:t,endResponse:r};throw e}let a=await this._resolveProtocol(e,r,i);if(a){let e=new Headers(r);e.set(`sec-websocket-protocol`,a),r=e}return{context:n,namespace:t,upgradeHeaders:r}}async _resolveProtocol(e,t,n){if(n)return n;if(t){let e=(t instanceof Headers?t:new Headers(t)).get(`sec-websocket-protocol`);if(e)return e}let r=this.options.handleProtocols;if(r){let t=$e(e.headers.get(`sec-websocket-protocol`));if(t.size>0){let n=await r(t,e);if(n)return n}}}};function $e(e){let t=new Set;if(!e)return t;for(let n of e.split(`,`)){let e=n.trim();e&&t.add(e)}return t}const et=Symbol.for(`nodejs.util.inspect.custom`);function tt(e){if(e==null)return``;let t=typeof e;return t===`string`?e:t===`number`||t===`boolean`||t===`bigint`?e.toString():t===`function`||t===`symbol`?`{}`:e instanceof Uint8Array||e instanceof ArrayBuffer?e:rt(e)?JSON.stringify(e):e}function nt(e){let t=tt(e);return typeof t==`string`||t instanceof Uint8Array?t:new Uint8Array(t)}function rt(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function it(e,t,n){let r=(t,r,i)=>{for(let a of i?.namespace?[e.get(i.namespace)||[]]:e.values()){let e;for(let n of a)if(n.topics.has(t)){e=n;break}if(e&&(e.send(r,i),e._publish(t,r,i),n?.nativePubSub&&!i?.namespace))break}},i;if(t?.sync){let e=(e,n)=>{t.onError?t.onError(n,{stage:e}):console.error(`[crossws] sync ${e} failed:`,n)},n=t.sync({id:crypto.randomUUID()}),a=t=>{try{r(t.topic,t.data,{namespace:t.namespace||void 0})}catch(t){e(`delivery`,t)}};try{Promise.resolve(n.subscribe(a)).catch(t=>e(`subscribe`,t))}catch(t){e(`subscribe`,t)}i={subscribe:e=>n.subscribe(e),publish:t=>{try{return Promise.resolve(n.publish(t)).catch(t=>e(`publish`,t))}catch(t){e(`publish`,t)}},close:n.close?()=>n.close():void 0}}return{peers:e,sync:i,publish(e,t,n){r(e,t,n),i?.publish({namespace:n?.namespace||``,topic:e,data:nt(t)})},async close(t,n){for(let r of e.values())for(let e of r)e.close(t,n);await i?.close?.()}}}function at(e,t){if(!t)throw Error(`Websocket publish namespace missing.`);let n=e.get(t);return n||(n=new Set,e.set(t,n)),n}var ot=class{event;peer;rawData;#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.rawData=e||``,this.peer=t,this.event=n}get id(){return this.#e||=crypto.randomUUID(),this.#e}uint8Array(){let e=this.#t;if(e)return e;let t=this.rawData;if(t instanceof Uint8Array)return this.#t=t;if(t instanceof ArrayBuffer||t instanceof SharedArrayBuffer)return this.#n=t,this.#t=new Uint8Array(t);if(typeof t==`string`)return this.#i=t,this.#t=new TextEncoder().encode(this.#i);if(Symbol.iterator in t||typeof t?.length==`number`)return this.#t=new Uint8Array(t);if(t instanceof DataView)return this.#t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw TypeError(`Unsupported message type: ${Object.prototype.toString.call(t)}`)}arrayBuffer(){let e=this.#n;if(e)return e;let t=this.rawData;return t instanceof ArrayBuffer||t instanceof SharedArrayBuffer?this.#n=t:this.#n=this.uint8Array().buffer}blob(){let e=this.#r;if(e)return e;let t=this.rawData;return t instanceof Blob?this.#r=t:this.#r=new Blob([this.uint8Array()])}text(){let e=this.#i;if(e)return e;let t=this.rawData;return typeof t==`string`?this.#i=t:this.#i=new TextDecoder().decode(this.uint8Array())}json(){return this.#a||=JSON.parse(this.text())}get data(){switch(this.peer?.websocket?.binaryType){case`arraybuffer`:return this.arrayBuffer();case`blob`:return this.blob();case`nodebuffer`:return globalThis.Buffer?Buffer.from(this.uint8Array()):this.uint8Array();case`uint8array`:return this.uint8Array();case`text`:return this.text();default:return this.rawData}}toString(){return this.text()}[Symbol.toPrimitive](){return this.text()}[et](){return{message:{id:this.id,peer:this.peer,text:this.text()}}}},st=class{_internal;_topics;_id;#e;#t=!1;constructor(e){this._topics=new Set,this._internal=e}get context(){return this._internal.context??={}}get namespace(){return this._internal.namespace}get id(){return this._id||=crypto.randomUUID(),this._id}get remoteAddress(){}get request(){return this._internal.request}get websocket(){if(!this.#e){let e=this._internal.ws,t=this._internal.request;this.#e=t?ct(e,t):e}return this.#e}get peers(){return this._internal.peers||new Set}get topics(){return this._topics}get bufferedAmount(){return this._internal.ws?.bufferedAmount??0}waitForDrain(e={}){let t=e.threshold??0;if(this.bufferedAmount<=t)return Promise.resolve();let n=e.signal;return n?.aborted?Promise.reject(n.reason):new Promise((r,i)=>{let a=()=>{(this.bufferedAmount<=t||(this.websocket.readyState??1)>1)&&(c(),r())},o=()=>{c(),i(n.reason)},s=setInterval(a,e.pollInterval??100);s.unref?.();let c=()=>{clearInterval(s),n?.removeEventListener(`abort`,o)};n?.addEventListener(`abort`,o,{once:!0})})}terminate(){this.close()}ping(e){this.#t||(this.#t=!0,console.warn("[crossws] `peer.ping()` is not supported by this adapter."))}subscribe(e){this._topics.add(e)}unsubscribe(e){this._topics.delete(e)}publish(e,t,n){this._publish(e,t,n),this._internal.sync?.publish({namespace:this.namespace,topic:e,data:nt(t)})}toString(){return this.id}[Symbol.toPrimitive](){return this.id}[Symbol.toStringTag](){return`WebSocket`}[et](){return{peer:{id:this.id,ip:this.remoteAddress}}}};function ct(e,t){return new Proxy(e,{get:(e,n)=>{let r=Reflect.get(e,n);if(!r)switch(n){case`protocol`:return t?.headers?.get(`sec-websocket-protocol`)||``;case`extensions`:return t?.headers?.get(`sec-websocket-extensions`)||``;case`url`:return t?.url?.replace(/^http/,`ws`)||void 0}return r}})}var lt=class extends Error{constructor(...e){super(...e),this.name=`WSError`}};const ut=(()=>{class e{url;_abortController;_headers;_init;constructor(e,t={}){this.url=e,this._init=t}get headers(){return this._headers||=new Headers(this._init?.headers),this._headers}clone(){return new e(this.url,this._init)}get method(){return`GET`}get signal(){return this._abortController||=new AbortController,this._abortController.signal}get cache(){return`default`}get credentials(){return`same-origin`}get destination(){return``}get integrity(){return``}get keepalive(){return!1}get redirect(){return`follow`}get mode(){return`cors`}get referrer(){return`about:client`}get referrerPolicy(){return``}get body(){return null}get bodyUsed(){return!1}arrayBuffer(){return Promise.resolve(new ArrayBuffer(0))}blob(){return Promise.resolve(new Blob)}bytes(){return Promise.resolve(new Uint8Array)}formData(){return Promise.resolve(new FormData)}json(){return Promise.resolve(JSON.parse(``))}text(){return Promise.resolve(``)}}return Object.setPrototypeOf(e.prototype,globalThis.Request.prototype),e})(),dt=Buffer.from(`crossws-ping`),ft=(e={})=>{if(`Deno`in globalThis||`Bun`in globalThis)throw Error(`[crossws] Using Node.js adapter in an incompatible environment.`);let t=new Qe(e),n=new Map,r=it(n,e),i=e.wss||new Ze.default({noServer:!0,handleProtocols:()=>!1,...e.serverOptions}),a=new Set,o=(e.idleTimeout??30)*1e3,s=Math.max(1,Math.floor(o));i.on(`connection`,(e,i)=>{let s=new mt(i),c=at(n,i._namespace),l=new pt({ws:e,request:s,peers:c,nodeReq:i,namespace:i._namespace,sync:r.sync,hooks:t});if(c.add(l),a.add(e),o>0){e._isAlive=!0;let t=()=>{e._isAlive=!0};e.on(`pong`,t),e.on(`ping`,t),e.on(`message`,t)}t.callHook(`open`,l),e.on(`message`,(e,n)=>{Array.isArray(e)&&(e=Buffer.concat(e)),!n&&Buffer.isBuffer(e)&&(e=e.toString(`utf8`)),t.callHook(`message`,l,new ot(e,l))}),e.on(`ping`,e=>{t.callHook(`ping`,l,e)}),e.on(`pong`,e=>{e.equals(dt)||t.callHook(`pong`,l,e)}),e.on(`error`,e=>{c.delete(l),t.callHook(`error`,l,new lt(e))});let u=e._socket,d=()=>t.callHook(`drain`,l);u?.on(`drain`,d),e.on(`close`,(n,r)=>{c.delete(l),a.delete(e),u?.off(`drain`,d),t.callHook(`close`,l,{code:n,reason:r?.toString()})})});let c,l=()=>{c&&=(clearInterval(c),void 0)};return o>0&&(c=setInterval(()=>{for(let e of a){if(e._isAlive===!1){e.terminate();continue}e._isAlive=!1;try{e.ping(dt)}catch{}}},s),c.unref?.(),i.on(`close`,l)),i.on(`headers`,(e,t)=>{let n=t._upgradeHeaders;if(n)for(let[t,r]of new Headers(n))e.push(`${t}: ${r}`)}),{...r,close:async(e,t)=>{l(),await r.close(e,t)},handleUpgrade:async(e,n,r,a)=>{let o=a||new mt(e),s;try{s=await t.upgrade(o)}catch{return ht(n,new Response(`Internal Server Error`,{status:500}))}let{upgradeHeaders:c,endResponse:l,handled:u,context:d,namespace:f}=s;if(l)return ht(n,l);u||(e._request=o,e._upgradeHeaders=c,e._context=d,e._namespace=f,i.handleUpgrade(e,n,r,t=>{i.emit(`connection`,t,e)}))},closeAll:(e,t,n)=>{for(let r of a)n?r.terminate():r.close(e,t)}}};var pt=class extends st{get remoteAddress(){return this._internal.nodeReq.socket?.remoteAddress}get context(){return this._internal.nodeReq._context}send(e,t){let n=tt(e),r=typeof n!=`string`;return this._internal.ws.send(n,{compress:t?.compress,binary:r,...t}),this._internal.ws.bufferedAmount}_publish(e,t,n){let r=tt(t),i=typeof r!=`string`,a={compress:n?.compress,binary:i,...n};for(let t of this._internal.peers)t!==this&&t._topics.has(e)&&t._internal.ws.send(r,a)}close(e,t){this._internal.ws.close(e,t)}terminate(){this._internal.ws.terminate()}ping(e){try{this._internal.ws.ping(e)}catch(e){this._internal.hooks.callHook(`error`,this,new lt(e))}}},mt=class extends ut{constructor(e){let t=e.headers.host||`localhost`,n=`${e.socket?.encrypted??e.headers[`x-forwarded-proto`]===`https`?`https`:`http`}://${t}${e.url}`;super(n,{headers:e.headers})}};async function ht(e,t){let n=[`HTTP/1.1 ${t.status||200} ${t.statusText||``}`,...[...t.headers.entries()].map(([e,t])=>`${e}: ${t}`)];if(e.write(n.join(`\r
|
|
10
|
+
`)+`\r
|
|
11
|
+
\r
|
|
12
|
+
`),t.body)for await(let n of t.body)e.write(n);return new Promise(t=>{e.end(()=>{e.destroy(),t()})})}const gt=[`upgrade`,`message`,`open`,`close`,`drain`,`error`,`ping`,`pong`];function _t(e,t){if(t.resolve)return t.resolve;if(gt.some(e=>typeof t[e]==`function`))return;let n=e.options.fetch;if(typeof n!=`function`)throw Error(`[crossws] server has no fetch handler to resolve WebSocket hooks from`);return e=>Promise.resolve(n(e)).then(e=>vt(e))}function vt(e){let t=e?.crossws;if(e instanceof Response){if(t)return e.body?.cancel().catch(()=>{}),t;if(!e.ok&&e.status!==101)return{upgrade:()=>e};e.body?.cancel().catch(()=>{});return}let n=e?.headers;if(!n)return t;let r=t?.upgrade;return{...t,async upgrade(e){let t=await r?.(e);return t instanceof Response?t:{...t,headers:yt(n,t?.headers)}}}}function yt(e,t){if(!t)return e;let n=new Headers(e);for(let[e,r]of new Headers(t))n.set(e,r);return n}function bt(e){return t=>{let n=ft({hooks:e,resolve:_t(t,e),...e.options?.node}),r=t.serve;t.serve=()=>(t.node?.server.on(`upgrade`,(e,t,r)=>{n.handleUpgrade(e,t,r,new ke({req:e,upgrade:{socket:t,head:r}}))}),r.call(t))}}const X=m||{},Z=e=>p?.postMessage(e),xt=te(X.entry,X.virtual);let St,Q;try{St=await g(X.virtual),Q=await ne(X.entry,xt)}catch(e){let t=e?.message||String(e);Z({event:`init-error`,error:t}),console.error(`[env-runner] worker init failed: ${t}`),process.exit(1)}const $=Me({port:0,hostname:`127.0.0.1`,silent:!0,fetch:e=>Q.fetch(e),middleware:Q.middleware,plugins:[...Q.plugins||[],...Q.websocket?[bt(Q.websocket)]:[]],gracefulShutdown:!1});await $.ready(),Q.upgrade&&$.node?.server?.on(`upgrade`,(e,t,n)=>{Q.upgrade({node:{req:e,socket:t,head:n}})}),Q.ipc&&await Q.ipc.onOpen?.({sendMessage:Z}),p?.postMessage({address:re($)}),p?.on(`message`,async e=>{if(e?.event===`shutdown`){Promise.resolve(Q.ipc?.onClose?.()).then(()=>$.close()).then(()=>{St(),p?.postMessage({event:`exit`})});return}if(e?.event===`reload-module`){try{Q=await ie(X.entry,Q,Z,xt),p?.postMessage({event:`module-reloaded`})}catch(e){p?.postMessage({event:`module-reloaded`,error:e?.message||String(e)})}return}if(e?.event===`invalidate-module`){ee(e,Z);return}if(e?.type===`ping`){p?.postMessage({type:`pong`,data:e.data});return}Q.ipc?.onMessage?.(e)});export{};
|
|
@@ -42,13 +42,11 @@ export declare class CompileAgentError extends Error {
|
|
|
42
42
|
*/
|
|
43
43
|
export declare function compileAgent(input?: CompileAgentInput): Promise<CompileAgentResult>;
|
|
44
44
|
/**
|
|
45
|
-
* Compiles an agent
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
* where publication later installs them — so the recorded paths stay
|
|
49
|
-
* relocatable and identical across builds of the same source.
|
|
45
|
+
* Compiles an agent into a caller-owned workspace. Artifacts are written to
|
|
46
|
+
* `writeRoot`, while metadata and module maps record paths under the stable
|
|
47
|
+
* `publishedRoot` where the caller will expose them.
|
|
50
48
|
*/
|
|
51
|
-
export declare function
|
|
49
|
+
export declare function compileAgentInWorkspace(input: {
|
|
52
50
|
readonly artifactLocations: CompilerArtifactLocations;
|
|
53
51
|
readonly startPath: string;
|
|
54
52
|
}): Promise<CompileAgentResult>;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{join}from"node:path";import{discoverAgent}from"#discover/discover-agent.js";import{hasDiscoverErrors,summarizeDiscoverDiagnostics}from"#discover/diagnostics.js";import{resolveDiscoveryProject}from"#discover/project.js";import{createDiskProjectSource}from"#discover/project-source.js";import{writeCompilerArtifacts}from"#compiler/artifacts.js";var CompileAgentError=class CompileAgentError extends Error{result;constructor(e,t){super(t),this.name=`CompileAgentError`,this.result=e}static fromDurableArtifacts(e){let[t,...n]=formatCompileAgentErrorLines(e.diagnostics);return new CompileAgentError(e,[t,`Diagnostics artifact: ${e.paths.diagnosticsPath}`,...n].join(`
|
|
2
2
|
`))}static fromTransientArtifacts(e){return new CompileAgentError(e,formatCompileAgentErrorLines(e.diagnostics).join(`
|
|
3
|
-
`))}};async function compileAgent(t={}){let n=await discoverAgentForCompilation(t),r=join(n.project.appRoot,`.eve`);return finishAgentCompilation(await writeAgentCompilation(n,{publishedRoot:r,writeRoot:r}),CompileAgentError.fromDurableArtifacts)}async function
|
|
3
|
+
`))}};async function compileAgent(t={}){let n=await discoverAgentForCompilation(t),r=join(n.project.appRoot,`.eve`);return finishAgentCompilation(await writeAgentCompilation(n,{publishedRoot:r,writeRoot:r}),CompileAgentError.fromDurableArtifacts)}async function compileAgentInWorkspace(e){return finishAgentCompilation(await writeAgentCompilation(await discoverAgentForCompilation({startPath:e.startPath}),e.artifactLocations),CompileAgentError.fromTransientArtifacts)}async function discoverAgentForCompilation(e){let n=e.source??createDiskProjectSource(),r=await resolveDiscoveryProject(e.startPath,{source:n}),i=await discoverAgent({...r,source:n});return{diagnostics:i.diagnostics,manifest:i.manifest,project:r}}async function writeAgentCompilation(e,t){let n=await writeCompilerArtifacts({appRoot:e.project.appRoot,artifactLocations:t,diagnostics:e.diagnostics,manifest:e.manifest});return{diagnostics:e.diagnostics,manifest:n.compiledManifest,metadata:n.metadata,paths:n.paths,project:e.project}}function finishAgentCompilation(e,t){if(hasDiscoverErrors(e.diagnostics))throw t(e);return reportDiscoverWarnings(e.diagnostics),e}function reportDiscoverWarnings(e){let t=e.filter(e=>e.severity===`warning`);if(t.length!==0)for(let e of t)console.warn(`Warning [${e.code}]: ${e.message}\n source: ${e.sourcePath}`)}function formatCompileAgentErrorLines(e){let t=summarizeDiscoverDiagnostics(e),n=[`Discovery failed with ${t.errors} error(s) and ${t.warnings} warning(s).`];if(e.length===0)return n;n.push(`Discovery diagnostics:`);for(let t of e)n.push(`- ${formatDiagnosticSeverity(t.severity)}: ${t.message}`),n.push(` source: ${t.sourcePath}`);return n}function formatDiagnosticSeverity(e){return e===`error`?`Error`:`Warning`}export{CompileAgentError,compileAgent,compileAgentInWorkspace};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sep}from"node:path";const SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS=[`.cts`,`.mts`,`.cjs`,`.mjs`,`.ts`,`.js`],PROJECT_MARKER_FILE_NAMES=[`package.json`,`vercel.json`],PROJECT_MARKER_FILE_NAME_SET=new Set(PROJECT_MARKER_FILE_NAMES),GENERATED_AGENT_DIRECTORY_NAMES=new Set([`.eve`,`.next`,`.output`,`.vercel
|
|
1
|
+
import{sep}from"node:path";const SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS=[`.cts`,`.mts`,`.cjs`,`.mjs`,`.ts`,`.js`],PROJECT_MARKER_FILE_NAMES=[`package.json`,`vercel.json`],PROJECT_MARKER_FILE_NAME_SET=new Set(PROJECT_MARKER_FILE_NAMES),GENERATED_AGENT_DIRECTORY_NAMES=new Set([`.eve`,`.next`,`.output`,`.vercel`,`node_modules`]);function getDirectoryEntryType(e){return e.isDirectory()?`directory`:e.isFile()?`file`:`other`}function isProjectMarkerEntry(e,t){return t===`file`&&PROJECT_MARKER_FILE_NAME_SET.has(e)}function classifyAgentRootEntry(e,t){if(t===`file`)return matchesSupportedModuleBaseName(e,`agent`)?`agent-config-module`:e.toLowerCase()===`instructions.md`?`instructions-markdown`:matchesSupportedModuleBaseName(e,`instructions`)?`instructions-module`:e.toLowerCase()===`system.md`?`system-markdown`:matchesSupportedModuleBaseName(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(GENERATED_AGENT_DIRECTORY_NAMES.has(e))return`ignored-directory`;if(e===`channels`)return`channels-directory`;if(e===`connections`)return`connections-directory`;if(e===`extensions`)return`extensions-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`instructions`)return`instructions-directory`;if(e===`lib`)return`lib-directory`;if(e===`skills`)return`skills-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`tools`)return`tools-directory`;if(e===`schedules`)return`schedules-directory`;if(e===`subagents`)return`subagents-directory`}return`unknown`}function classifyLocalSubagentEntry(e,t){if(t===`file`)return matchesSupportedModuleBaseName(e,`agent`)?`agent-config-module`:e.toLowerCase()===`instructions.md`?`instructions-markdown`:matchesSupportedModuleBaseName(e,`instructions`)?`instructions-module`:e.toLowerCase()===`system.md`?`system-markdown`:matchesSupportedModuleBaseName(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(GENERATED_AGENT_DIRECTORY_NAMES.has(e))return`ignored-directory`;if(e===`connections`)return`connections-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`instructions`)return`instructions-directory`;if(e===`lib`)return`lib-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`skills`)return`skills-directory`;if(e===`tools`)return`tools-directory`;if(e===`subagents`)return`subagents-directory`;if(e===`schedules`)return`invalid-schedules-directory`}return`unknown`}function classifySkillPackageEntry(e,t){if(t===`file`)return e.toLowerCase()===`skill.md`?`skill-markdown`:`skill-resource`;if(t===`directory`){if(e===`scripts`)return`skill-scripts-directory`;if(e===`references`)return`skill-references-directory`;if(e===`assets`)return`skill-assets-directory`}return`skill-resource`}function classifySkillsDirectoryEntry(e,t){if(t===`directory`)return`skill-package-directory`;if(t===`file`){if(e.toLowerCase().endsWith(`.md`))return`flat-skill-markdown`;if(getSupportedModuleBaseName(e)!==null)return`flat-skill-module`}return`unknown`}function normalizeLogicalPath(t){return t.replaceAll(sep,`/`).replace(/^\.\//,``).replace(/^\/+/,``)}function getSupportedModuleBaseName(e){for(let n of SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS)if(e.endsWith(n)&&e.length>n.length)return e.slice(0,-n.length);return null}function matchesSupportedModuleBaseName(e,t){return getSupportedModuleBaseName(e)===t}function stripLogicalPathExtension(e){let t=normalizeLogicalPath(e),n=t.lastIndexOf(`/`),r=t.lastIndexOf(`.`);return r===-1||r<n?t:t.slice(0,r)}export{PROJECT_MARKER_FILE_NAMES,SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS,classifyAgentRootEntry,classifyLocalSubagentEntry,classifySkillPackageEntry,classifySkillsDirectoryEntry,getDirectoryEntryType,getSupportedModuleBaseName,isProjectMarkerEntry,matchesSupportedModuleBaseName,normalizeLogicalPath,stripLogicalPathExtension};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type DurableCompiledArtifactsSource } from "#runtime/durable-compiled-artifacts-source.js";
|
|
2
2
|
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
3
3
|
import type { RunSessionLimits } from "#channel/types.js";
|
|
4
4
|
import type { JsonObject } from "#shared/json.js";
|
|
@@ -18,7 +18,7 @@ export interface CreateSessionStepResult {
|
|
|
18
18
|
* the root agent.
|
|
19
19
|
*/
|
|
20
20
|
export declare function createSessionStep(input: {
|
|
21
|
-
readonly compiledArtifactsSource:
|
|
21
|
+
readonly compiledArtifactsSource: DurableCompiledArtifactsSource;
|
|
22
22
|
readonly continuationToken: string;
|
|
23
23
|
readonly inheritedLimits?: RunSessionLimits;
|
|
24
24
|
readonly outputSchema?: JsonObject;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{createDurableSessionState}from"#execution/durable-session-store.js";import{createSession}from"#execution/session.js";import{resolveInheritedTokenLimit}from"#execution/run-session-limits.js";async function createSessionStep(e){"use step";let t=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId});return{state:createDurableSessionState({session:createSession({compactionOverrides:{thresholdPercent:t.resolvedAgent.config.compaction?.thresholdPercent},continuationToken:e.continuationToken,limits:{maxInputTokensPerSession:resolveInheritedTokenLimit({configured:t.resolvedAgent.config.limits?.maxInputTokensPerSession,inherited:e.inheritedLimits?.maxInputTokensPerSession}),maxOutputTokensPerSession:resolveInheritedTokenLimit({configured:t.resolvedAgent.config.limits?.maxOutputTokensPerSession,inherited:e.inheritedLimits?.maxOutputTokensPerSession})},outputSchema:e.outputSchema,rootSessionId:e.rootSessionId,sessionId:e.sessionId,subagentDepth:e.subagentDepth,turnAgent:t.turnAgent,workflowMaxSubagents:t.resolvedAgent.workflowTool?.maxSubagents})})}}export{createSessionStep};
|
|
1
|
+
import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveDurableCompiledArtifactsSource}from"#runtime/durable-compiled-artifacts-source.js";import{createDurableSessionState}from"#execution/durable-session-store.js";import{createSession}from"#execution/session.js";import{resolveInheritedTokenLimit}from"#execution/run-session-limits.js";async function createSessionStep(e){"use step";let t=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:resolveDurableCompiledArtifactsSource(e.compiledArtifactsSource),nodeId:e.nodeId});return{state:createDurableSessionState({session:createSession({compactionOverrides:{thresholdPercent:t.resolvedAgent.config.compaction?.thresholdPercent},continuationToken:e.continuationToken,limits:{maxInputTokensPerSession:resolveInheritedTokenLimit({configured:t.resolvedAgent.config.limits?.maxInputTokensPerSession,inherited:e.inheritedLimits?.maxInputTokensPerSession}),maxOutputTokensPerSession:resolveInheritedTokenLimit({configured:t.resolvedAgent.config.limits?.maxOutputTokensPerSession,inherited:e.inheritedLimits?.maxOutputTokensPerSession})},outputSchema:e.outputSchema,rootSessionId:e.rootSessionId,sessionId:e.sessionId,subagentDepth:e.subagentDepth,turnAgent:t.turnAgent,workflowMaxSubagents:t.resolvedAgent.workflowTool?.maxSubagents})})}}export{createSessionStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{runMigrationChain}from"./chain.js";import{turnWorkflowInputV0ToV1}from"./turn-workflow-v0-to-v1.js";const TURN_WORKFLOW_INPUT_VERSION=1,turnWorkflowInputMigrations=[turnWorkflowInputV0ToV1];function createTurnWorkflowInput(e){return{capabilities:e.capabilities,completionToken:e.completionToken,driverCapabilities:{turnInbox:!0},mode:e.mode,stepInput:{input:e.delivery,parentWritable:e.parentWritable,serializedContext:e.serializedContext,sessionState:e.sessionState},version:1}}function migrateTurnWorkflowInput(t){return runMigrationChain({initialVersion:0,label:`turn workflow input`,migrations:turnWorkflowInputMigrations,targetVersion:1,value:t})}export{TURN_WORKFLOW_INPUT_VERSION,createTurnWorkflowInput,migrateTurnWorkflowInput};
|
|
1
|
+
import{runMigrationChain}from"./chain.js";import{turnWorkflowInputV0ToV1}from"./turn-workflow-v0-to-v1.js";const TURN_WORKFLOW_INPUT_VERSION=1,turnWorkflowInputMigrations=[turnWorkflowInputV0ToV1];function createTurnWorkflowInput(e){return{capabilities:e.capabilities,completionToken:e.completionToken,driverCapabilities:{cancelledTurnSettle:!0,turnInbox:!0},mode:e.mode,stepInput:{input:e.delivery,parentWritable:e.parentWritable,serializedContext:e.serializedContext,sessionState:e.sessionState},version:1}}function migrateTurnWorkflowInput(t){return runMigrationChain({initialVersion:0,label:`turn workflow input`,migrations:turnWorkflowInputMigrations,targetVersion:1,value:t})}export{TURN_WORKFLOW_INPUT_VERSION,createTurnWorkflowInput,migrateTurnWorkflowInput};
|
|
@@ -27,6 +27,13 @@ export type NextDriverAction = {
|
|
|
27
27
|
readonly sessionState: DurableSessionState;
|
|
28
28
|
readonly serializedContext: Record<string, unknown>;
|
|
29
29
|
readonly authorizationNames?: readonly string[];
|
|
30
|
+
/**
|
|
31
|
+
* Set when the parked turn was cancelled: the driver runs
|
|
32
|
+
* `settleCancelledTurnStep` before the normal park playbook. An
|
|
33
|
+
* optional field rather than a new arm so pinned drivers keep
|
|
34
|
+
* working.
|
|
35
|
+
*/
|
|
36
|
+
readonly cancelled?: true;
|
|
30
37
|
} | {
|
|
31
38
|
readonly kind: "dispatch-runtime-actions";
|
|
32
39
|
readonly pendingActionKeys: readonly string[];
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
2
|
+
export interface CancelledTurnSettleResult {
|
|
3
|
+
readonly serializedContext: Record<string, unknown>;
|
|
4
|
+
readonly sessionState: DurableSessionState;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Settles one cancelled turn: emits `turn.cancelled` → `session.waiting`,
|
|
8
|
+
* drops pending runtime-action state, and persists the between-turns
|
|
9
|
+
* session. Runs in the *driver* run, whose wake sources exclude the
|
|
10
|
+
* cancel hook, so a queued cancel wake cannot re-dispatch it.
|
|
11
|
+
*/
|
|
12
|
+
export declare function settleCancelledTurnStep(input: {
|
|
13
|
+
readonly parentWritable: WritableStream<Uint8Array>;
|
|
14
|
+
readonly serializedContext: Record<string, unknown>;
|
|
15
|
+
readonly sessionState: DurableSessionState;
|
|
16
|
+
}): Promise<CancelledTurnSettleResult>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{callAdapterEventHandler}from"#channel/adapter.js";import{encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{clearPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{clearPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{clearAllProxyInputRequests,hasProxyInputRequests}from"#harness/proxy-input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{withContextScope}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{emitCancelledTurn}from"#harness/cancelled-turn-emission.js";async function settleCancelledTurnStep(r){"use step";let i=await readDurableSession(r.sessionState),a=await deserializeContext(r.serializedContext),o=a.require(ChannelKey),s=buildAdapterContext(o,a),c=a.require(BundleKey),l=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.resolvedAgent.config.compaction?.thresholdPercent},durable:i,turnAgent:c.turnAgent}),u=getHarnessEmissionState(i.state);if(!(isHarnessBetweenTurns(l)&&hasProxyInputRequests(i.state))){let e=r.parentWritable.getWriter();try{let t=await withContextScope(a,l,async t=>({result:await emitCancelledTurn(async t=>{let n=await callAdapterEventHandler(o,t,s);setChannelContext(a,{...o,state:{...s.state}}),await e.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(n))),await dispatchStreamEventHooks({ctx:a,event:n,registry:c.hookRegistry})},u,t.continuationToken),session:t}));u=t.result,l=t.session}finally{e.releaseLock()}}let d=reconcileSessionContinuationToken(a,setHarnessEmissionState(clearAllProxyInputRequests(clearPendingWorkflowInterrupt(clearPendingRuntimeActionBatch(l))),u));return{serializedContext:serializeContext(a),sessionState:createDurableSessionState({session:d})}}export{settleCancelledTurnStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createInputRequestedEvent}from"#protocol/message.js";import{emitTurnEpilogue,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{getProxyInputRequests,toProxyInputRequestEntries}from"#harness/proxy-input-requests.js";async function emitProxiedInputRequest(i){await i.emit(createInputRequestedEvent({requests:i.hookPayload.event.requests,sequence:i.hookPayload.event.sequence,stepIndex:i.hookPayload.event.stepIndex,turnId:i.hookPayload.event.turnId}));let o=i.session;if(i.mode===`conversation`){let e=getHarnessEmissionState(i.session.state),a=await emitTurnEpilogue(i.emit,e,i.mode);o=setHarnessEmissionState(i.session,a)}return{entries:toProxyInputRequestEntries(i.hookPayload),session:o}}function routeDeliverPayload(e){let t=getProxyInputRequests(e.state),n=e.payload.inputResponses??[],r=new Map,a=[];for(let e of n){let n=t.get(e.requestId);if(n===void 0){a.push(e);continue}let i=r.get(n);i===void 0?r.set(n,[e]):i.push(e)}let o=[...r.entries()].map(([e,t])=>({childContinuationToken:e,payload:{inputResponses:t}})),s={};for(let[t,n]of Object.entries(e.payload))t===`inputResponses`||n===void 0||(s[t]=n);return a.length>0&&(s.inputResponses=a),{forChildren:o,forSelf:Object.keys(s).length>0?s:void 0}}export{emitProxiedInputRequest,routeDeliverPayload};
|
|
1
|
+
import{createInputRequestedEvent}from"#protocol/message.js";import{emitTurnEpilogue,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{getProxyInputRequests,toProxyInputRequestEntries}from"#harness/proxy-input-requests.js";async function emitProxiedInputRequest(i){await i.emit(createInputRequestedEvent({requests:i.hookPayload.event.requests,sequence:i.hookPayload.event.sequence,stepIndex:i.hookPayload.event.stepIndex,turnId:i.hookPayload.event.turnId}));let o=i.session;if(i.mode===`conversation`){let e=getHarnessEmissionState(i.session.state),a=await emitTurnEpilogue(i.emit,e,i.mode,i.session.continuationToken);o=setHarnessEmissionState(i.session,a)}return{entries:toProxyInputRequestEntries(i.hookPayload),session:o}}function routeDeliverPayload(e){let t=getProxyInputRequests(e.state),n=e.payload.inputResponses??[],r=new Map,a=[];for(let e of n){let n=t.get(e.requestId);if(n===void 0){a.push(e);continue}let i=r.get(n);i===void 0?r.set(n,[e]):i.push(e)}let o=[...r.entries()].map(([e,t])=>({childContinuationToken:e,payload:{inputResponses:t}})),s={};for(let[t,n]of Object.entries(e.payload))t===`inputResponses`||n===void 0||(s[t]=n);return a.length>0&&(s.inputResponses=a),{forChildren:o,forSelf:Object.keys(s).length>0?s:void 0}}export{emitProxiedInputRequest,routeDeliverPayload};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Emits a terminal `session.failed` to the adapter and durable stream. */
|
|
2
|
+
export declare function emitTerminalSessionFailureStep(input: {
|
|
3
|
+
readonly error: unknown;
|
|
4
|
+
readonly parentWritable: WritableStream<Uint8Array>;
|
|
5
|
+
readonly serializedContext: Record<string, unknown>;
|
|
6
|
+
}): Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createLogger,formatError}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{createSessionFailedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionFailureStep(e){"use step";let r=formatError(e.error),i=typeof r.name==`string`?r.name:`WORKFLOW_EXECUTION_FAILED`,a=typeof r.message==`string`?r.message:String(e.error),o=e.serializedContext[`eve.sessionId`]??``;log.error(`workflow loop threw — emitting terminal session.failed`,{sessionId:o,errorId:typeof r.errorId==`string`?r.errorId:void 0,code:i,message:a,detail:typeof r.detail==`string`?r.detail:void 0});let s=createSessionFailedEvent({code:i,details:r,message:a,sessionId:o});try{let t=await deserializeContext(e.serializedContext),n=t.get(ChannelKey);n!==void 0&&await callAdapterEventHandler(n,s,buildAdapterContext(n,t))}catch(e){log.error(`adapter failed to handle terminal session.failed event`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}try{let t=e.parentWritable.getWriter();try{await t.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(s)))}finally{t.releaseLock()}}catch(e){log.error(`failed to write terminal session.failed event to durable stream`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}}export{emitTerminalSessionFailureStep};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Derives the session-scoped cancel hook token. Stable for the session's
|
|
3
|
+
* lifetime, so a cancel trigger can address it from the session id alone.
|
|
4
|
+
*/
|
|
5
|
+
export declare function sessionCancelHookToken(sessionId: string): string;
|
|
6
|
+
/**
|
|
7
|
+
* Payload accepted by the session cancel hook. The optional `turnId`
|
|
8
|
+
* guard scopes the cancel to the turn the caller observed; a mismatch is
|
|
9
|
+
* consumed as a benign no-op. Omitting it cancels the current turn.
|
|
10
|
+
*/
|
|
11
|
+
export interface TurnCancelPayload {
|
|
12
|
+
readonly turnId?: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Owns one turn's cancellation surface inside the turn workflow: the
|
|
16
|
+
* session-scoped cancel hook and the durable `AbortController` whose
|
|
17
|
+
* signal is serialized into every `turnStep`. Must be created inside a
|
|
18
|
+
* `"use workflow"` body.
|
|
19
|
+
*/
|
|
20
|
+
export interface TurnCancellationControl {
|
|
21
|
+
/** Turn signal to serialize into each `turnStep` input. */
|
|
22
|
+
readonly signal: AbortSignal;
|
|
23
|
+
/**
|
|
24
|
+
* Resolves `"cancel"` once a matching cancel payload is consumed and
|
|
25
|
+
* the signal aborted. Race it against turn-owned awaits — never
|
|
26
|
+
* `await` it alone.
|
|
27
|
+
*/
|
|
28
|
+
readonly requested: Promise<"cancel">;
|
|
29
|
+
/** Disposes the hook, abandoning any outstanding read. Idempotent. */
|
|
30
|
+
dispose(): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Creates and claims the session cancel hook for one turn workflow run.
|
|
34
|
+
* Returns `undefined` when the token is still claimed by a crashed prior
|
|
35
|
+
* run — the turn then runs uncancellable rather than failing.
|
|
36
|
+
*/
|
|
37
|
+
export declare function createTurnCancellationControl(input: {
|
|
38
|
+
readonly expectedTurnId: string;
|
|
39
|
+
readonly sessionId: string;
|
|
40
|
+
}): Promise<TurnCancellationControl | undefined>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHook}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{TurnCancelledError}from"#harness/turn-cancellation.js";function sessionCancelHookToken(e){return`${e}:cancel`}async function createTurnCancellationControl(r){let i=createHook({token:sessionCancelHookToken(r.sessionId)}),a=i[Symbol.asyncIterator]();try{await claimHookOwnership(i)}catch(e){if(isHookConflictError(e))return;throw e}let o=new AbortController,s=consumeMatchingCancel(a,r.expectedTurnId).then(()=>(o.abort(new TurnCancelledError),`cancel`)),c=!1;return{signal:o.signal,requested:s,async dispose(){c||(c=!0,await disposeHook(i))}}}async function consumeMatchingCancel(e,t){for(;;){let n=await e.next();if(n.done)return await new Promise(()=>{});if(matchesActiveTurn(n.value,t))return}}function matchesActiveTurn(e,t){if(typeof e!=`object`||!e)return!0;let n=e.turnId;return n===void 0||n===t}export{createTurnCancellationControl,sessionCancelHookToken};
|