veryfront 0.0.68 → 0.0.69

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.
@@ -1,16 +1,47 @@
1
+ var __create = Object.create;
1
2
  var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __require2 = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined")
11
+ return require.apply(this, arguments);
12
+ throw Error('Dynamic require of "' + x + '" is not supported');
13
+ });
3
14
  var __esm = (fn, res) => function __init() {
4
15
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
16
  };
17
+ var __commonJS = (cb, mod) => function __require3() {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ };
6
20
  var __export = (target, all) => {
7
21
  for (var name in all)
8
22
  __defProp(target, name, { get: all[name], enumerable: true });
9
23
  };
24
+ var __copyProps = (to, from, except, desc) => {
25
+ if (from && typeof from === "object" || typeof from === "function") {
26
+ for (let key of __getOwnPropNames(from))
27
+ if (!__hasOwnProp.call(to, key) && key !== except)
28
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
29
+ }
30
+ return to;
31
+ };
32
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
33
+ // If the importer is in node compatibility mode or this is not an ESM
34
+ // file that has been converted to a CommonJS file using a Babel-
35
+ // compatible transform (i.e. "__esModule" has not been set), then set
36
+ // "default" to the CommonJS "module.exports" for node compatibility.
37
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
38
+ mod
39
+ ));
10
40
 
11
41
  // src/_shims/deno-env.ts
12
42
  var init_deno_env = __esm({
13
43
  "src/_shims/deno-env.ts"() {
44
+ "use strict";
14
45
  globalThis.Deno = globalThis.Deno || {
15
46
  env: {
16
47
  get(key) {
@@ -45,6 +76,7 @@ function hasBunRuntime(global) {
45
76
  }
46
77
  var init_runtime_guards = __esm({
47
78
  "src/core/utils/runtime-guards.ts"() {
79
+ "use strict";
48
80
  init_deno_env();
49
81
  }
50
82
  });
@@ -77,6 +109,7 @@ function isDevelopmentEnvironment() {
77
109
  }
78
110
  var init_env = __esm({
79
111
  "src/core/utils/logger/env.ts"() {
112
+ "use strict";
80
113
  init_deno_env();
81
114
  init_runtime_guards();
82
115
  }
@@ -126,6 +159,7 @@ function __loggerResetForTests(options = {}) {
126
159
  var LogLevel, originalConsole, cachedLogLevel, ConsoleLogger, getDefaultLevel, trackedLoggers, cliLogger, serverLogger, rendererLogger, bundlerLogger, agentLogger, logger;
127
160
  var init_logger = __esm({
128
161
  "src/core/utils/logger/logger.ts"() {
162
+ "use strict";
129
163
  init_deno_env();
130
164
  init_env();
131
165
  LogLevel = /* @__PURE__ */ ((LogLevel2) => {
@@ -209,6 +243,7 @@ var init_logger = __esm({
209
243
  // src/core/utils/logger/index.ts
210
244
  var init_logger2 = __esm({
211
245
  "src/core/utils/logger/index.ts"() {
246
+ "use strict";
212
247
  init_deno_env();
213
248
  init_logger();
214
249
  init_env();
@@ -219,6 +254,7 @@ var init_logger2 = __esm({
219
254
  var DEFAULT_BUILD_CONCURRENCY, IMAGE_OPTIMIZATION;
220
255
  var init_build = __esm({
221
256
  "src/core/utils/constants/build.ts"() {
257
+ "use strict";
222
258
  init_deno_env();
223
259
  DEFAULT_BUILD_CONCURRENCY = 4;
224
260
  IMAGE_OPTIMIZATION = {
@@ -232,6 +268,7 @@ var init_build = __esm({
232
268
  var SECONDS_PER_MINUTE, MINUTES_PER_HOUR, HOURS_PER_DAY, MS_PER_SECOND, DEFAULT_LRU_MAX_ENTRIES, COMPONENT_LOADER_MAX_ENTRIES, COMPONENT_LOADER_TTL_MS, MDX_RENDERER_MAX_ENTRIES, MDX_RENDERER_TTL_MS, RENDERER_CORE_MAX_ENTRIES, RENDERER_CORE_TTL_MS, TSX_LAYOUT_MAX_ENTRIES, TSX_LAYOUT_TTL_MS, DATA_FETCHING_MAX_ENTRIES, DATA_FETCHING_TTL_MS, MDX_CACHE_TTL_PRODUCTION_MS, MDX_CACHE_TTL_DEVELOPMENT_MS, BUNDLE_CACHE_TTL_PRODUCTION_MS, BUNDLE_CACHE_TTL_DEVELOPMENT_MS, BUNDLE_MANIFEST_PROD_TTL_MS, BUNDLE_MANIFEST_DEV_TTL_MS, RSC_MANIFEST_CACHE_TTL_MS, SERVER_ACTION_DEFAULT_TTL_SEC, DENO_KV_SAFE_SIZE_LIMIT_BYTES, HTTP_CACHE_SHORT_MAX_AGE_SEC, HTTP_CACHE_MEDIUM_MAX_AGE_SEC, HTTP_CACHE_LONG_MAX_AGE_SEC, ONE_DAY_MS, CACHE_CLEANUP_INTERVAL_MS, LRU_DEFAULT_MAX_ENTRIES, LRU_DEFAULT_MAX_SIZE_BYTES, CLEANUP_INTERVAL_MULTIPLIER;
233
269
  var init_cache = __esm({
234
270
  "src/core/utils/constants/cache.ts"() {
271
+ "use strict";
235
272
  init_deno_env();
236
273
  SECONDS_PER_MINUTE = 60;
237
274
  MINUTES_PER_HOUR = 60;
@@ -485,6 +522,7 @@ var init_deno = __esm({
485
522
  var isDeno, isNode, isBun, isCloudflare;
486
523
  var init_runtime = __esm({
487
524
  "src/platform/compat/runtime.ts"() {
525
+ "use strict";
488
526
  init_deno_env();
489
527
  isDeno = typeof Deno !== "undefined";
490
528
  isNode = typeof globalThis.process !== "undefined" && globalThis.process?.versions?.node !== void 0;
@@ -524,6 +562,7 @@ function execPath() {
524
562
  var nodeProcess, hasNodeProcess2;
525
563
  var init_process = __esm({
526
564
  "src/platform/compat/process.ts"() {
565
+ "use strict";
527
566
  init_deno_env();
528
567
  init_runtime();
529
568
  nodeProcess = globalThis.process;
@@ -535,6 +574,7 @@ var init_process = __esm({
535
574
  var VERSION;
536
575
  var init_version = __esm({
537
576
  "src/core/utils/version.ts"() {
577
+ "use strict";
538
578
  init_deno_env();
539
579
  init_deno();
540
580
  init_process();
@@ -580,6 +620,7 @@ function getUnoCSSTailwindResetUrl() {
580
620
  var ESM_CDN_BASE, JSDELIVR_CDN_BASE, DENO_STD_BASE, REACT_VERSION_17, REACT_VERSION_18_2, REACT_VERSION_18_3, REACT_VERSION_19_RC, REACT_VERSION_19, REACT_DEFAULT_VERSION, DEFAULT_ALLOWED_CDN_HOSTS, DENO_STD_VERSION, UNOCSS_VERSION;
581
621
  var init_cdn = __esm({
582
622
  "src/core/utils/constants/cdn.ts"() {
623
+ "use strict";
583
624
  init_deno_env();
584
625
  init_version();
585
626
  ESM_CDN_BASE = "https://esm.sh";
@@ -616,6 +657,7 @@ function isAnyDebugEnabled(env) {
616
657
  var ENV_VARS;
617
658
  var init_env2 = __esm({
618
659
  "src/core/utils/constants/env.ts"() {
660
+ "use strict";
619
661
  init_deno_env();
620
662
  ENV_VARS = {
621
663
  DEBUG: "VERYFRONT_DEBUG",
@@ -631,6 +673,7 @@ var init_env2 = __esm({
631
673
  var HASH_SEED_DJB2, HASH_SEED_FNV1A;
632
674
  var init_hash = __esm({
633
675
  "src/core/utils/constants/hash.ts"() {
676
+ "use strict";
634
677
  init_deno_env();
635
678
  HASH_SEED_DJB2 = 5381;
636
679
  HASH_SEED_FNV1A = 2166136261;
@@ -641,6 +684,7 @@ var init_hash = __esm({
641
684
  var KB_IN_BYTES, HTTP_MODULE_FETCH_TIMEOUT_MS, HMR_RECONNECT_DELAY_MS, HMR_RELOAD_DELAY_MS, HMR_FILE_WATCHER_DEBOUNCE_MS, HMR_KEEP_ALIVE_INTERVAL_MS, DASHBOARD_RECONNECT_DELAY_MS, SERVER_FUNCTION_DEFAULT_TIMEOUT_MS, PREFETCH_MAX_SIZE_BYTES, PREFETCH_DEFAULT_TIMEOUT_MS, PREFETCH_DEFAULT_DELAY_MS, HTTP_OK, HTTP_NO_CONTENT, HTTP_CREATED, HTTP_REDIRECT_FOUND, HTTP_NOT_MODIFIED, HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED, HTTP_FORBIDDEN, HTTP_NOT_FOUND, HTTP_METHOD_NOT_ALLOWED, HTTP_GONE, HTTP_PAYLOAD_TOO_LARGE, HTTP_URI_TOO_LONG, HTTP_TOO_MANY_REQUESTS, HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE, HTTP_SERVER_ERROR, HTTP_INTERNAL_SERVER_ERROR, HTTP_BAD_GATEWAY, HTTP_NOT_IMPLEMENTED, HTTP_UNAVAILABLE, HTTP_NETWORK_CONNECT_TIMEOUT, HTTP_STATUS_SUCCESS_MIN, HTTP_STATUS_REDIRECT_MIN, HTTP_STATUS_CLIENT_ERROR_MIN, HTTP_STATUS_SERVER_ERROR_MIN, HTTP_CONTENT_TYPES, MS_PER_MINUTE, HTTP_CONTENT_TYPE_IMAGE_PNG, HTTP_CONTENT_TYPE_IMAGE_JPEG, HTTP_CONTENT_TYPE_IMAGE_WEBP, HTTP_CONTENT_TYPE_IMAGE_AVIF, HTTP_CONTENT_TYPE_IMAGE_SVG, HTTP_CONTENT_TYPE_IMAGE_GIF, HTTP_CONTENT_TYPE_IMAGE_ICO;
642
685
  var init_http = __esm({
643
686
  "src/core/utils/constants/http.ts"() {
687
+ "use strict";
644
688
  init_deno_env();
645
689
  init_cache();
646
690
  KB_IN_BYTES = 1024;
@@ -706,6 +750,7 @@ function isValidHMRMessageType(type) {
706
750
  var HMR_MAX_MESSAGE_SIZE_BYTES, HMR_MAX_MESSAGES_PER_MINUTE, HMR_CLIENT_RELOAD_DELAY_MS, HMR_PORT_OFFSET, HMR_RATE_LIMIT_WINDOW_MS, HMR_CLOSE_NORMAL, HMR_CLOSE_RATE_LIMIT, HMR_CLOSE_MESSAGE_TOO_LARGE, HMR_MESSAGE_TYPES;
707
751
  var init_hmr = __esm({
708
752
  "src/core/utils/constants/hmr.ts"() {
753
+ "use strict";
709
754
  init_deno_env();
710
755
  init_http();
711
756
  HMR_MAX_MESSAGE_SIZE_BYTES = 1024 * KB_IN_BYTES;
@@ -730,6 +775,7 @@ var init_hmr = __esm({
730
775
  var Z_INDEX_DEV_INDICATOR, Z_INDEX_ERROR_OVERLAY, BREAKPOINT_SM, BREAKPOINT_MD, BREAKPOINT_LG, BREAKPOINT_XL, PROSE_MAX_WIDTH;
731
776
  var init_html = __esm({
732
777
  "src/core/utils/constants/html.ts"() {
778
+ "use strict";
733
779
  init_deno_env();
734
780
  Z_INDEX_DEV_INDICATOR = 9998;
735
781
  Z_INDEX_ERROR_OVERLAY = 9999;
@@ -745,6 +791,7 @@ var init_html = __esm({
745
791
  var DEFAULT_DEV_SERVER_PORT, DEFAULT_REDIS_PORT, DEFAULT_API_SERVER_PORT, DEFAULT_PREVIEW_SERVER_PORT, DEFAULT_METRICS_PORT, BYTES_PER_KB, BYTES_PER_MB, DEFAULT_IMAGE_THUMBNAIL_SIZE, DEFAULT_IMAGE_SMALL_SIZE, DEFAULT_IMAGE_LARGE_SIZE, RESPONSIVE_IMAGE_WIDTH_XS, RESPONSIVE_IMAGE_WIDTH_SM, RESPONSIVE_IMAGE_WIDTH_MD, RESPONSIVE_IMAGE_WIDTH_LG, RESPONSIVE_IMAGE_WIDTHS, MAX_CHUNK_SIZE_KB, MIN_PORT, MAX_PORT, DEFAULT_SERVER_PORT;
746
792
  var init_network = __esm({
747
793
  "src/core/utils/constants/network.ts"() {
794
+ "use strict";
748
795
  init_deno_env();
749
796
  DEFAULT_DEV_SERVER_PORT = 3e3;
750
797
  DEFAULT_REDIS_PORT = 6379;
@@ -777,6 +824,7 @@ var init_network = __esm({
777
824
  var MAX_PATH_TRAVERSAL_DEPTH, FORBIDDEN_PATH_PATTERNS, DIRECTORY_TRAVERSAL_PATTERN, ABSOLUTE_PATH_PATTERN, MAX_PATH_LENGTH, DEFAULT_MAX_STRING_LENGTH;
778
825
  var init_security = __esm({
779
826
  "src/core/utils/constants/security.ts"() {
827
+ "use strict";
780
828
  init_deno_env();
781
829
  MAX_PATH_TRAVERSAL_DEPTH = 10;
782
830
  FORBIDDEN_PATH_PATTERNS = [
@@ -815,6 +863,7 @@ function normalizeChunkPath(filename, basePath = INTERNAL_PATH_PREFIXES.CHUNKS)
815
863
  var DEFAULT_DASHBOARD_PORT, INTERNAL_PREFIX, INTERNAL_PATH_PREFIXES, INTERNAL_ENDPOINTS, BUILD_DIRS, PROJECT_DIRS, DEFAULT_CACHE_DIR, DEV_SERVER_ENDPOINTS;
816
864
  var init_server = __esm({
817
865
  "src/core/utils/constants/server.ts"() {
866
+ "use strict";
818
867
  init_deno_env();
819
868
  init_defaults();
820
869
  DEFAULT_DASHBOARD_PORT = 3002;
@@ -900,6 +949,7 @@ var init_server = __esm({
900
949
  // src/core/utils/constants/index.ts
901
950
  var init_constants = __esm({
902
951
  "src/core/utils/constants/index.ts"() {
952
+ "use strict";
903
953
  init_deno_env();
904
954
  init_build();
905
955
  init_cache();
@@ -919,6 +969,7 @@ var init_constants = __esm({
919
969
  var PATHS, VERYFRONT_PATHS, FILE_EXTENSIONS;
920
970
  var init_paths = __esm({
921
971
  "src/core/utils/paths.ts"() {
972
+ "use strict";
922
973
  init_deno_env();
923
974
  init_server();
924
975
  PATHS = {
@@ -982,6 +1033,7 @@ async function shortHash(content) {
982
1033
  }
983
1034
  var init_hash_utils = __esm({
984
1035
  "src/core/utils/hash-utils.ts"() {
1036
+ "use strict";
985
1037
  init_deno_env();
986
1038
  }
987
1039
  });
@@ -1027,9 +1079,12 @@ function simpleHash2(...values) {
1027
1079
  var MemoCache;
1028
1080
  var init_memoize = __esm({
1029
1081
  "src/core/utils/memoize.ts"() {
1082
+ "use strict";
1030
1083
  init_deno_env();
1031
1084
  MemoCache = class {
1032
- cache = /* @__PURE__ */ new Map();
1085
+ constructor() {
1086
+ this.cache = /* @__PURE__ */ new Map();
1087
+ }
1033
1088
  get(key) {
1034
1089
  return this.cache.get(key);
1035
1090
  }
@@ -1099,6 +1154,7 @@ function fromBase64Url(encoded) {
1099
1154
  }
1100
1155
  var init_path_utils = __esm({
1101
1156
  "src/core/utils/path-utils.ts"() {
1157
+ "use strict";
1102
1158
  init_deno_env();
1103
1159
  init_logger();
1104
1160
  }
@@ -1192,6 +1248,7 @@ function truncateString(str, maxLength) {
1192
1248
  }
1193
1249
  var init_format_utils = __esm({
1194
1250
  "src/core/utils/format-utils.ts"() {
1251
+ "use strict";
1195
1252
  init_deno_env();
1196
1253
  init_logger();
1197
1254
  }
@@ -1210,13 +1267,16 @@ function getBundleManifestStore() {
1210
1267
  var InMemoryBundleManifestStore, manifestStore;
1211
1268
  var init_bundle_manifest = __esm({
1212
1269
  "src/core/utils/bundle-manifest.ts"() {
1270
+ "use strict";
1213
1271
  init_deno_env();
1214
1272
  init_logger2();
1215
1273
  init_hash_utils();
1216
1274
  InMemoryBundleManifestStore = class {
1217
- metadata = /* @__PURE__ */ new Map();
1218
- code = /* @__PURE__ */ new Map();
1219
- sourceIndex = /* @__PURE__ */ new Map();
1275
+ constructor() {
1276
+ this.metadata = /* @__PURE__ */ new Map();
1277
+ this.code = /* @__PURE__ */ new Map();
1278
+ this.sourceIndex = /* @__PURE__ */ new Map();
1279
+ }
1220
1280
  getBundleMetadata(key) {
1221
1281
  const entry = this.metadata.get(key);
1222
1282
  if (!entry)
@@ -1412,6 +1472,7 @@ async function warmupBundleManifest(store, keys) {
1412
1472
  }
1413
1473
  var init_bundle_manifest_init = __esm({
1414
1474
  "src/core/utils/bundle-manifest-init.ts"() {
1475
+ "use strict";
1415
1476
  init_deno_env();
1416
1477
  init_logger2();
1417
1478
  init_bundle_manifest();
@@ -1428,6 +1489,7 @@ function isRSCEnabled(config) {
1428
1489
  }
1429
1490
  var init_feature_flags = __esm({
1430
1491
  "src/core/utils/feature-flags.ts"() {
1492
+ "use strict";
1431
1493
  init_deno_env();
1432
1494
  init_process();
1433
1495
  }
@@ -1446,6 +1508,7 @@ function isCompiledBinary() {
1446
1508
  }
1447
1509
  var init_platform = __esm({
1448
1510
  "src/core/utils/platform.ts"() {
1511
+ "use strict";
1449
1512
  init_deno_env();
1450
1513
  init_runtime();
1451
1514
  init_process();
@@ -1706,6 +1769,7 @@ function toError(veryfrontError) {
1706
1769
  }
1707
1770
  var init_veryfront_error = __esm({
1708
1771
  "src/core/errors/veryfront-error.ts"() {
1772
+ "use strict";
1709
1773
  init_deno_env();
1710
1774
  }
1711
1775
  });
@@ -1715,6 +1779,7 @@ import { z } from "zod";
1715
1779
  var corsSchema, veryfrontConfigSchema;
1716
1780
  var init_schema = __esm({
1717
1781
  "src/core/config/schema.ts"() {
1782
+ "use strict";
1718
1783
  init_deno_env();
1719
1784
  init_veryfront_error();
1720
1785
  corsSchema = z.union([z.boolean(), z.object({ origin: z.string().optional() }).strict()]);
@@ -1862,6 +1927,7 @@ function getDefaultImportMapForConfig() {
1862
1927
  var DEFAULT_CONFIG;
1863
1928
  var init_loader = __esm({
1864
1929
  "src/core/config/loader.ts"() {
1930
+ "use strict";
1865
1931
  init_deno_env();
1866
1932
  init_schema();
1867
1933
  init_logger();
@@ -1922,6 +1988,7 @@ var init_loader = __esm({
1922
1988
  // src/core/config/define-config.ts
1923
1989
  var init_define_config = __esm({
1924
1990
  "src/core/config/define-config.ts"() {
1991
+ "use strict";
1925
1992
  init_deno_env();
1926
1993
  init_veryfront_error();
1927
1994
  init_process();
@@ -1931,6 +1998,7 @@ var init_define_config = __esm({
1931
1998
  // src/core/config/network-defaults.ts
1932
1999
  var init_network_defaults = __esm({
1933
2000
  "src/core/config/network-defaults.ts"() {
2001
+ "use strict";
1934
2002
  init_deno_env();
1935
2003
  }
1936
2004
  });
@@ -1956,6 +2024,7 @@ __export(deno_exports, {
1956
2024
  var DenoFileSystemAdapter, DenoEnvironmentAdapter, DenoServerAdapter, DenoShellAdapter, DenoServer, DenoAdapter, denoAdapter;
1957
2025
  var init_deno2 = __esm({
1958
2026
  "src/platform/adapters/deno.ts"() {
2027
+ "use strict";
1959
2028
  init_deno_env();
1960
2029
  init_veryfront_error();
1961
2030
  init_config();
@@ -2146,34 +2215,36 @@ var init_deno2 = __esm({
2146
2215
  }
2147
2216
  };
2148
2217
  DenoAdapter = class {
2149
- id = "deno";
2150
- name = "deno";
2151
- /** @deprecated Use `id` instead */
2152
- platform = "deno";
2153
- fs = new DenoFileSystemAdapter();
2154
- env = new DenoEnvironmentAdapter();
2155
- server = new DenoServerAdapter();
2156
- shell = new DenoShellAdapter();
2157
- capabilities = {
2158
- typescript: true,
2159
- jsx: true,
2160
- http2: true,
2161
- websocket: true,
2162
- workers: true,
2163
- fileWatching: true,
2164
- shell: true,
2165
- kvStore: true,
2166
- // Deno KV available
2167
- writableFs: true
2168
- };
2169
- /** @deprecated Use `capabilities` instead */
2170
- features = {
2171
- websocket: true,
2172
- http2: true,
2173
- workers: true,
2174
- jsx: true,
2175
- typescript: true
2176
- };
2218
+ constructor() {
2219
+ this.id = "deno";
2220
+ this.name = "deno";
2221
+ /** @deprecated Use `id` instead */
2222
+ this.platform = "deno";
2223
+ this.fs = new DenoFileSystemAdapter();
2224
+ this.env = new DenoEnvironmentAdapter();
2225
+ this.server = new DenoServerAdapter();
2226
+ this.shell = new DenoShellAdapter();
2227
+ this.capabilities = {
2228
+ typescript: true,
2229
+ jsx: true,
2230
+ http2: true,
2231
+ websocket: true,
2232
+ workers: true,
2233
+ fileWatching: true,
2234
+ shell: true,
2235
+ kvStore: true,
2236
+ // Deno KV available
2237
+ writableFs: true
2238
+ };
2239
+ /** @deprecated Use `capabilities` instead */
2240
+ this.features = {
2241
+ websocket: true,
2242
+ http2: true,
2243
+ workers: true,
2244
+ jsx: true,
2245
+ typescript: true
2246
+ };
2247
+ }
2177
2248
  serve(handler, options = {}) {
2178
2249
  const { port = DEFAULT_PORT, hostname = "localhost", onListen } = options;
2179
2250
  const controller = new AbortController();
@@ -2276,153 +2347,3893 @@ function createFileWatcher(iterator, cleanup) {
2276
2347
  }
2277
2348
  var init_shared_watcher = __esm({
2278
2349
  "src/platform/adapters/shared-watcher.ts"() {
2350
+ "use strict";
2351
+ init_deno_env();
2352
+ }
2353
+ });
2354
+
2355
+ // src/platform/adapters/node/filesystem-adapter.ts
2356
+ var NodeFileSystemAdapter;
2357
+ var init_filesystem_adapter = __esm({
2358
+ "src/platform/adapters/node/filesystem-adapter.ts"() {
2359
+ "use strict";
2360
+ init_deno_env();
2361
+ init_shared_watcher();
2362
+ init_utils();
2363
+ NodeFileSystemAdapter = class {
2364
+ async readFile(path) {
2365
+ const fs = await import("node:fs/promises");
2366
+ return await fs.readFile(path, "utf-8");
2367
+ }
2368
+ async readFileBytes(path) {
2369
+ const fs = await import("node:fs/promises");
2370
+ const buffer = await fs.readFile(path);
2371
+ return buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
2372
+ }
2373
+ async writeFile(path, content) {
2374
+ const fs = await import("node:fs/promises");
2375
+ await fs.writeFile(path, content, "utf-8");
2376
+ }
2377
+ async exists(path) {
2378
+ const fs = await import("node:fs/promises");
2379
+ try {
2380
+ await fs.access(path);
2381
+ return true;
2382
+ } catch (error) {
2383
+ serverLogger.debug(`File access check failed for ${path}:`, error);
2384
+ return false;
2385
+ }
2386
+ }
2387
+ async *readDir(path) {
2388
+ const fs = await import("node:fs/promises");
2389
+ const entries = await fs.readdir(path, { withFileTypes: true });
2390
+ for (const entry of entries) {
2391
+ yield {
2392
+ name: entry.name,
2393
+ isFile: entry.isFile(),
2394
+ isDirectory: entry.isDirectory(),
2395
+ isSymlink: entry.isSymbolicLink()
2396
+ };
2397
+ }
2398
+ }
2399
+ async stat(path) {
2400
+ const fs = await import("node:fs/promises");
2401
+ const stats = await fs.stat(path);
2402
+ return {
2403
+ size: stats.size,
2404
+ isFile: stats.isFile(),
2405
+ isDirectory: stats.isDirectory(),
2406
+ isSymlink: stats.isSymbolicLink(),
2407
+ mtime: stats.mtime
2408
+ };
2409
+ }
2410
+ async mkdir(path, options) {
2411
+ const fs = await import("node:fs/promises");
2412
+ await fs.mkdir(path, options);
2413
+ }
2414
+ async remove(path, options) {
2415
+ const fs = await import("node:fs/promises");
2416
+ await fs.rm(path, { recursive: options?.recursive, force: true });
2417
+ }
2418
+ async makeTempDir(prefix) {
2419
+ const { mkdtemp } = await import("node:fs/promises");
2420
+ const { join: join5 } = await import("node:path");
2421
+ const { tmpdir } = await import("node:os");
2422
+ return await mkdtemp(join5(tmpdir(), prefix));
2423
+ }
2424
+ watch(paths, options) {
2425
+ const pathArray = Array.isArray(paths) ? paths : [paths];
2426
+ const recursive = options?.recursive ?? true;
2427
+ const signal = options?.signal;
2428
+ let closed = false;
2429
+ const watchers = [];
2430
+ const eventQueue = [];
2431
+ let resolver = null;
2432
+ Promise.all(
2433
+ pathArray.map(
2434
+ (path) => setupNodeFsWatcher(path, {
2435
+ recursive,
2436
+ closed: () => closed,
2437
+ signal,
2438
+ eventQueue,
2439
+ getResolver: () => resolver,
2440
+ setResolver: (r) => {
2441
+ resolver = r;
2442
+ },
2443
+ watchers,
2444
+ onError: (error, path2) => serverLogger.error(`File watcher error for ${path2}:`, error)
2445
+ })
2446
+ )
2447
+ ).catch((error) => {
2448
+ serverLogger.error("Failed to setup file watchers:", error);
2449
+ });
2450
+ const iterator = createWatcherIterator(
2451
+ eventQueue,
2452
+ () => resolver,
2453
+ (r) => {
2454
+ resolver = r;
2455
+ },
2456
+ () => closed,
2457
+ () => signal?.aborted ?? false
2458
+ );
2459
+ const cleanup = () => {
2460
+ closed = true;
2461
+ watchers.forEach((watcher) => {
2462
+ try {
2463
+ watcher.close();
2464
+ } catch (error) {
2465
+ serverLogger.debug("Error closing file watcher during cleanup:", error);
2466
+ }
2467
+ });
2468
+ if (resolver) {
2469
+ resolver({ done: true, value: void 0 });
2470
+ resolver = null;
2471
+ }
2472
+ };
2473
+ if (signal) {
2474
+ signal.addEventListener("abort", cleanup);
2475
+ }
2476
+ return createFileWatcher(iterator, cleanup);
2477
+ }
2478
+ };
2479
+ }
2480
+ });
2481
+
2482
+ // src/platform/adapters/node/environment-adapter.ts
2483
+ import process2 from "node:process";
2484
+ var NodeEnvironmentAdapter;
2485
+ var init_environment_adapter = __esm({
2486
+ "src/platform/adapters/node/environment-adapter.ts"() {
2487
+ "use strict";
2488
+ init_deno_env();
2489
+ NodeEnvironmentAdapter = class {
2490
+ get(key) {
2491
+ return process2.env[key];
2492
+ }
2493
+ set(key, value) {
2494
+ process2.env[key] = value;
2495
+ }
2496
+ toObject() {
2497
+ return { ...process2.env };
2498
+ }
2499
+ };
2500
+ }
2501
+ });
2502
+
2503
+ // ../node_modules/ws/lib/constants.js
2504
+ var require_constants = __commonJS({
2505
+ "../node_modules/ws/lib/constants.js"(exports, module) {
2506
+ "use strict";
2507
+ init_deno_env();
2508
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
2509
+ var hasBlob = typeof Blob !== "undefined";
2510
+ if (hasBlob)
2511
+ BINARY_TYPES.push("blob");
2512
+ module.exports = {
2513
+ BINARY_TYPES,
2514
+ EMPTY_BUFFER: Buffer.alloc(0),
2515
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
2516
+ hasBlob,
2517
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
2518
+ kListener: Symbol("kListener"),
2519
+ kStatusCode: Symbol("status-code"),
2520
+ kWebSocket: Symbol("websocket"),
2521
+ NOOP: () => {
2522
+ }
2523
+ };
2524
+ }
2525
+ });
2526
+
2527
+ // ../node_modules/ws/lib/buffer-util.js
2528
+ var require_buffer_util = __commonJS({
2529
+ "../node_modules/ws/lib/buffer-util.js"(exports, module) {
2530
+ "use strict";
2531
+ init_deno_env();
2532
+ var { EMPTY_BUFFER } = require_constants();
2533
+ var FastBuffer = Buffer[Symbol.species];
2534
+ function concat(list, totalLength) {
2535
+ if (list.length === 0)
2536
+ return EMPTY_BUFFER;
2537
+ if (list.length === 1)
2538
+ return list[0];
2539
+ const target = Buffer.allocUnsafe(totalLength);
2540
+ let offset = 0;
2541
+ for (let i = 0; i < list.length; i++) {
2542
+ const buf = list[i];
2543
+ target.set(buf, offset);
2544
+ offset += buf.length;
2545
+ }
2546
+ if (offset < totalLength) {
2547
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
2548
+ }
2549
+ return target;
2550
+ }
2551
+ function _mask(source, mask, output, offset, length) {
2552
+ for (let i = 0; i < length; i++) {
2553
+ output[offset + i] = source[i] ^ mask[i & 3];
2554
+ }
2555
+ }
2556
+ function _unmask(buffer, mask) {
2557
+ for (let i = 0; i < buffer.length; i++) {
2558
+ buffer[i] ^= mask[i & 3];
2559
+ }
2560
+ }
2561
+ function toArrayBuffer(buf) {
2562
+ if (buf.length === buf.buffer.byteLength) {
2563
+ return buf.buffer;
2564
+ }
2565
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
2566
+ }
2567
+ function toBuffer(data) {
2568
+ toBuffer.readOnly = true;
2569
+ if (Buffer.isBuffer(data))
2570
+ return data;
2571
+ let buf;
2572
+ if (data instanceof ArrayBuffer) {
2573
+ buf = new FastBuffer(data);
2574
+ } else if (ArrayBuffer.isView(data)) {
2575
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
2576
+ } else {
2577
+ buf = Buffer.from(data);
2578
+ toBuffer.readOnly = false;
2579
+ }
2580
+ return buf;
2581
+ }
2582
+ module.exports = {
2583
+ concat,
2584
+ mask: _mask,
2585
+ toArrayBuffer,
2586
+ toBuffer,
2587
+ unmask: _unmask
2588
+ };
2589
+ if (!process.env.WS_NO_BUFFER_UTIL) {
2590
+ try {
2591
+ const bufferUtil = __require2("bufferutil");
2592
+ module.exports.mask = function(source, mask, output, offset, length) {
2593
+ if (length < 48)
2594
+ _mask(source, mask, output, offset, length);
2595
+ else
2596
+ bufferUtil.mask(source, mask, output, offset, length);
2597
+ };
2598
+ module.exports.unmask = function(buffer, mask) {
2599
+ if (buffer.length < 32)
2600
+ _unmask(buffer, mask);
2601
+ else
2602
+ bufferUtil.unmask(buffer, mask);
2603
+ };
2604
+ } catch (e) {
2605
+ }
2606
+ }
2607
+ }
2608
+ });
2609
+
2610
+ // ../node_modules/ws/lib/limiter.js
2611
+ var require_limiter = __commonJS({
2612
+ "../node_modules/ws/lib/limiter.js"(exports, module) {
2613
+ "use strict";
2614
+ init_deno_env();
2615
+ var kDone = Symbol("kDone");
2616
+ var kRun = Symbol("kRun");
2617
+ var Limiter = class {
2618
+ /**
2619
+ * Creates a new `Limiter`.
2620
+ *
2621
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
2622
+ * to run concurrently
2623
+ */
2624
+ constructor(concurrency) {
2625
+ this[kDone] = () => {
2626
+ this.pending--;
2627
+ this[kRun]();
2628
+ };
2629
+ this.concurrency = concurrency || Infinity;
2630
+ this.jobs = [];
2631
+ this.pending = 0;
2632
+ }
2633
+ /**
2634
+ * Adds a job to the queue.
2635
+ *
2636
+ * @param {Function} job The job to run
2637
+ * @public
2638
+ */
2639
+ add(job) {
2640
+ this.jobs.push(job);
2641
+ this[kRun]();
2642
+ }
2643
+ /**
2644
+ * Removes a job from the queue and runs it if possible.
2645
+ *
2646
+ * @private
2647
+ */
2648
+ [kRun]() {
2649
+ if (this.pending === this.concurrency)
2650
+ return;
2651
+ if (this.jobs.length) {
2652
+ const job = this.jobs.shift();
2653
+ this.pending++;
2654
+ job(this[kDone]);
2655
+ }
2656
+ }
2657
+ };
2658
+ module.exports = Limiter;
2659
+ }
2660
+ });
2661
+
2662
+ // ../node_modules/ws/lib/permessage-deflate.js
2663
+ var require_permessage_deflate = __commonJS({
2664
+ "../node_modules/ws/lib/permessage-deflate.js"(exports, module) {
2665
+ "use strict";
2279
2666
  init_deno_env();
2667
+ var zlib = __require2("zlib");
2668
+ var bufferUtil = require_buffer_util();
2669
+ var Limiter = require_limiter();
2670
+ var { kStatusCode } = require_constants();
2671
+ var FastBuffer = Buffer[Symbol.species];
2672
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
2673
+ var kPerMessageDeflate = Symbol("permessage-deflate");
2674
+ var kTotalLength = Symbol("total-length");
2675
+ var kCallback = Symbol("callback");
2676
+ var kBuffers = Symbol("buffers");
2677
+ var kError = Symbol("error");
2678
+ var zlibLimiter;
2679
+ var PerMessageDeflate = class {
2680
+ /**
2681
+ * Creates a PerMessageDeflate instance.
2682
+ *
2683
+ * @param {Object} [options] Configuration options
2684
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
2685
+ * for, or request, a custom client window size
2686
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
2687
+ * acknowledge disabling of client context takeover
2688
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
2689
+ * calls to zlib
2690
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
2691
+ * use of a custom server window size
2692
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
2693
+ * disabling of server context takeover
2694
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
2695
+ * messages should not be compressed if context takeover is disabled
2696
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
2697
+ * deflate
2698
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
2699
+ * inflate
2700
+ * @param {Boolean} [isServer=false] Create the instance in either server or
2701
+ * client mode
2702
+ * @param {Number} [maxPayload=0] The maximum allowed message length
2703
+ */
2704
+ constructor(options, isServer, maxPayload) {
2705
+ this._maxPayload = maxPayload | 0;
2706
+ this._options = options || {};
2707
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
2708
+ this._isServer = !!isServer;
2709
+ this._deflate = null;
2710
+ this._inflate = null;
2711
+ this.params = null;
2712
+ if (!zlibLimiter) {
2713
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
2714
+ zlibLimiter = new Limiter(concurrency);
2715
+ }
2716
+ }
2717
+ /**
2718
+ * @type {String}
2719
+ */
2720
+ static get extensionName() {
2721
+ return "permessage-deflate";
2722
+ }
2723
+ /**
2724
+ * Create an extension negotiation offer.
2725
+ *
2726
+ * @return {Object} Extension parameters
2727
+ * @public
2728
+ */
2729
+ offer() {
2730
+ const params = {};
2731
+ if (this._options.serverNoContextTakeover) {
2732
+ params.server_no_context_takeover = true;
2733
+ }
2734
+ if (this._options.clientNoContextTakeover) {
2735
+ params.client_no_context_takeover = true;
2736
+ }
2737
+ if (this._options.serverMaxWindowBits) {
2738
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
2739
+ }
2740
+ if (this._options.clientMaxWindowBits) {
2741
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
2742
+ } else if (this._options.clientMaxWindowBits == null) {
2743
+ params.client_max_window_bits = true;
2744
+ }
2745
+ return params;
2746
+ }
2747
+ /**
2748
+ * Accept an extension negotiation offer/response.
2749
+ *
2750
+ * @param {Array} configurations The extension negotiation offers/reponse
2751
+ * @return {Object} Accepted configuration
2752
+ * @public
2753
+ */
2754
+ accept(configurations) {
2755
+ configurations = this.normalizeParams(configurations);
2756
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
2757
+ return this.params;
2758
+ }
2759
+ /**
2760
+ * Releases all resources used by the extension.
2761
+ *
2762
+ * @public
2763
+ */
2764
+ cleanup() {
2765
+ if (this._inflate) {
2766
+ this._inflate.close();
2767
+ this._inflate = null;
2768
+ }
2769
+ if (this._deflate) {
2770
+ const callback = this._deflate[kCallback];
2771
+ this._deflate.close();
2772
+ this._deflate = null;
2773
+ if (callback) {
2774
+ callback(
2775
+ new Error(
2776
+ "The deflate stream was closed while data was being processed"
2777
+ )
2778
+ );
2779
+ }
2780
+ }
2781
+ }
2782
+ /**
2783
+ * Accept an extension negotiation offer.
2784
+ *
2785
+ * @param {Array} offers The extension negotiation offers
2786
+ * @return {Object} Accepted configuration
2787
+ * @private
2788
+ */
2789
+ acceptAsServer(offers) {
2790
+ const opts = this._options;
2791
+ const accepted = offers.find((params) => {
2792
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
2793
+ return false;
2794
+ }
2795
+ return true;
2796
+ });
2797
+ if (!accepted) {
2798
+ throw new Error("None of the extension offers can be accepted");
2799
+ }
2800
+ if (opts.serverNoContextTakeover) {
2801
+ accepted.server_no_context_takeover = true;
2802
+ }
2803
+ if (opts.clientNoContextTakeover) {
2804
+ accepted.client_no_context_takeover = true;
2805
+ }
2806
+ if (typeof opts.serverMaxWindowBits === "number") {
2807
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
2808
+ }
2809
+ if (typeof opts.clientMaxWindowBits === "number") {
2810
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
2811
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
2812
+ delete accepted.client_max_window_bits;
2813
+ }
2814
+ return accepted;
2815
+ }
2816
+ /**
2817
+ * Accept the extension negotiation response.
2818
+ *
2819
+ * @param {Array} response The extension negotiation response
2820
+ * @return {Object} Accepted configuration
2821
+ * @private
2822
+ */
2823
+ acceptAsClient(response) {
2824
+ const params = response[0];
2825
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
2826
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
2827
+ }
2828
+ if (!params.client_max_window_bits) {
2829
+ if (typeof this._options.clientMaxWindowBits === "number") {
2830
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
2831
+ }
2832
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
2833
+ throw new Error(
2834
+ 'Unexpected or invalid parameter "client_max_window_bits"'
2835
+ );
2836
+ }
2837
+ return params;
2838
+ }
2839
+ /**
2840
+ * Normalize parameters.
2841
+ *
2842
+ * @param {Array} configurations The extension negotiation offers/reponse
2843
+ * @return {Array} The offers/response with normalized parameters
2844
+ * @private
2845
+ */
2846
+ normalizeParams(configurations) {
2847
+ configurations.forEach((params) => {
2848
+ Object.keys(params).forEach((key) => {
2849
+ let value = params[key];
2850
+ if (value.length > 1) {
2851
+ throw new Error(`Parameter "${key}" must have only a single value`);
2852
+ }
2853
+ value = value[0];
2854
+ if (key === "client_max_window_bits") {
2855
+ if (value !== true) {
2856
+ const num = +value;
2857
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
2858
+ throw new TypeError(
2859
+ `Invalid value for parameter "${key}": ${value}`
2860
+ );
2861
+ }
2862
+ value = num;
2863
+ } else if (!this._isServer) {
2864
+ throw new TypeError(
2865
+ `Invalid value for parameter "${key}": ${value}`
2866
+ );
2867
+ }
2868
+ } else if (key === "server_max_window_bits") {
2869
+ const num = +value;
2870
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
2871
+ throw new TypeError(
2872
+ `Invalid value for parameter "${key}": ${value}`
2873
+ );
2874
+ }
2875
+ value = num;
2876
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
2877
+ if (value !== true) {
2878
+ throw new TypeError(
2879
+ `Invalid value for parameter "${key}": ${value}`
2880
+ );
2881
+ }
2882
+ } else {
2883
+ throw new Error(`Unknown parameter "${key}"`);
2884
+ }
2885
+ params[key] = value;
2886
+ });
2887
+ });
2888
+ return configurations;
2889
+ }
2890
+ /**
2891
+ * Decompress data. Concurrency limited.
2892
+ *
2893
+ * @param {Buffer} data Compressed data
2894
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
2895
+ * @param {Function} callback Callback
2896
+ * @public
2897
+ */
2898
+ decompress(data, fin, callback) {
2899
+ zlibLimiter.add((done) => {
2900
+ this._decompress(data, fin, (err, result) => {
2901
+ done();
2902
+ callback(err, result);
2903
+ });
2904
+ });
2905
+ }
2906
+ /**
2907
+ * Compress data. Concurrency limited.
2908
+ *
2909
+ * @param {(Buffer|String)} data Data to compress
2910
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
2911
+ * @param {Function} callback Callback
2912
+ * @public
2913
+ */
2914
+ compress(data, fin, callback) {
2915
+ zlibLimiter.add((done) => {
2916
+ this._compress(data, fin, (err, result) => {
2917
+ done();
2918
+ callback(err, result);
2919
+ });
2920
+ });
2921
+ }
2922
+ /**
2923
+ * Decompress data.
2924
+ *
2925
+ * @param {Buffer} data Compressed data
2926
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
2927
+ * @param {Function} callback Callback
2928
+ * @private
2929
+ */
2930
+ _decompress(data, fin, callback) {
2931
+ const endpoint = this._isServer ? "client" : "server";
2932
+ if (!this._inflate) {
2933
+ const key = `${endpoint}_max_window_bits`;
2934
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
2935
+ this._inflate = zlib.createInflateRaw({
2936
+ ...this._options.zlibInflateOptions,
2937
+ windowBits
2938
+ });
2939
+ this._inflate[kPerMessageDeflate] = this;
2940
+ this._inflate[kTotalLength] = 0;
2941
+ this._inflate[kBuffers] = [];
2942
+ this._inflate.on("error", inflateOnError);
2943
+ this._inflate.on("data", inflateOnData);
2944
+ }
2945
+ this._inflate[kCallback] = callback;
2946
+ this._inflate.write(data);
2947
+ if (fin)
2948
+ this._inflate.write(TRAILER);
2949
+ this._inflate.flush(() => {
2950
+ const err = this._inflate[kError];
2951
+ if (err) {
2952
+ this._inflate.close();
2953
+ this._inflate = null;
2954
+ callback(err);
2955
+ return;
2956
+ }
2957
+ const data2 = bufferUtil.concat(
2958
+ this._inflate[kBuffers],
2959
+ this._inflate[kTotalLength]
2960
+ );
2961
+ if (this._inflate._readableState.endEmitted) {
2962
+ this._inflate.close();
2963
+ this._inflate = null;
2964
+ } else {
2965
+ this._inflate[kTotalLength] = 0;
2966
+ this._inflate[kBuffers] = [];
2967
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
2968
+ this._inflate.reset();
2969
+ }
2970
+ }
2971
+ callback(null, data2);
2972
+ });
2973
+ }
2974
+ /**
2975
+ * Compress data.
2976
+ *
2977
+ * @param {(Buffer|String)} data Data to compress
2978
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
2979
+ * @param {Function} callback Callback
2980
+ * @private
2981
+ */
2982
+ _compress(data, fin, callback) {
2983
+ const endpoint = this._isServer ? "server" : "client";
2984
+ if (!this._deflate) {
2985
+ const key = `${endpoint}_max_window_bits`;
2986
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
2987
+ this._deflate = zlib.createDeflateRaw({
2988
+ ...this._options.zlibDeflateOptions,
2989
+ windowBits
2990
+ });
2991
+ this._deflate[kTotalLength] = 0;
2992
+ this._deflate[kBuffers] = [];
2993
+ this._deflate.on("data", deflateOnData);
2994
+ }
2995
+ this._deflate[kCallback] = callback;
2996
+ this._deflate.write(data);
2997
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
2998
+ if (!this._deflate) {
2999
+ return;
3000
+ }
3001
+ let data2 = bufferUtil.concat(
3002
+ this._deflate[kBuffers],
3003
+ this._deflate[kTotalLength]
3004
+ );
3005
+ if (fin) {
3006
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
3007
+ }
3008
+ this._deflate[kCallback] = null;
3009
+ this._deflate[kTotalLength] = 0;
3010
+ this._deflate[kBuffers] = [];
3011
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
3012
+ this._deflate.reset();
3013
+ }
3014
+ callback(null, data2);
3015
+ });
3016
+ }
3017
+ };
3018
+ module.exports = PerMessageDeflate;
3019
+ function deflateOnData(chunk) {
3020
+ this[kBuffers].push(chunk);
3021
+ this[kTotalLength] += chunk.length;
3022
+ }
3023
+ function inflateOnData(chunk) {
3024
+ this[kTotalLength] += chunk.length;
3025
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
3026
+ this[kBuffers].push(chunk);
3027
+ return;
3028
+ }
3029
+ this[kError] = new RangeError("Max payload size exceeded");
3030
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
3031
+ this[kError][kStatusCode] = 1009;
3032
+ this.removeListener("data", inflateOnData);
3033
+ this.reset();
3034
+ }
3035
+ function inflateOnError(err) {
3036
+ this[kPerMessageDeflate]._inflate = null;
3037
+ if (this[kError]) {
3038
+ this[kCallback](this[kError]);
3039
+ return;
3040
+ }
3041
+ err[kStatusCode] = 1007;
3042
+ this[kCallback](err);
3043
+ }
3044
+ }
3045
+ });
3046
+
3047
+ // ../node_modules/ws/lib/validation.js
3048
+ var require_validation = __commonJS({
3049
+ "../node_modules/ws/lib/validation.js"(exports, module) {
3050
+ "use strict";
3051
+ init_deno_env();
3052
+ var { isUtf8 } = __require2("buffer");
3053
+ var { hasBlob } = require_constants();
3054
+ var tokenChars = [
3055
+ 0,
3056
+ 0,
3057
+ 0,
3058
+ 0,
3059
+ 0,
3060
+ 0,
3061
+ 0,
3062
+ 0,
3063
+ 0,
3064
+ 0,
3065
+ 0,
3066
+ 0,
3067
+ 0,
3068
+ 0,
3069
+ 0,
3070
+ 0,
3071
+ // 0 - 15
3072
+ 0,
3073
+ 0,
3074
+ 0,
3075
+ 0,
3076
+ 0,
3077
+ 0,
3078
+ 0,
3079
+ 0,
3080
+ 0,
3081
+ 0,
3082
+ 0,
3083
+ 0,
3084
+ 0,
3085
+ 0,
3086
+ 0,
3087
+ 0,
3088
+ // 16 - 31
3089
+ 0,
3090
+ 1,
3091
+ 0,
3092
+ 1,
3093
+ 1,
3094
+ 1,
3095
+ 1,
3096
+ 1,
3097
+ 0,
3098
+ 0,
3099
+ 1,
3100
+ 1,
3101
+ 0,
3102
+ 1,
3103
+ 1,
3104
+ 0,
3105
+ // 32 - 47
3106
+ 1,
3107
+ 1,
3108
+ 1,
3109
+ 1,
3110
+ 1,
3111
+ 1,
3112
+ 1,
3113
+ 1,
3114
+ 1,
3115
+ 1,
3116
+ 0,
3117
+ 0,
3118
+ 0,
3119
+ 0,
3120
+ 0,
3121
+ 0,
3122
+ // 48 - 63
3123
+ 0,
3124
+ 1,
3125
+ 1,
3126
+ 1,
3127
+ 1,
3128
+ 1,
3129
+ 1,
3130
+ 1,
3131
+ 1,
3132
+ 1,
3133
+ 1,
3134
+ 1,
3135
+ 1,
3136
+ 1,
3137
+ 1,
3138
+ 1,
3139
+ // 64 - 79
3140
+ 1,
3141
+ 1,
3142
+ 1,
3143
+ 1,
3144
+ 1,
3145
+ 1,
3146
+ 1,
3147
+ 1,
3148
+ 1,
3149
+ 1,
3150
+ 1,
3151
+ 0,
3152
+ 0,
3153
+ 0,
3154
+ 1,
3155
+ 1,
3156
+ // 80 - 95
3157
+ 1,
3158
+ 1,
3159
+ 1,
3160
+ 1,
3161
+ 1,
3162
+ 1,
3163
+ 1,
3164
+ 1,
3165
+ 1,
3166
+ 1,
3167
+ 1,
3168
+ 1,
3169
+ 1,
3170
+ 1,
3171
+ 1,
3172
+ 1,
3173
+ // 96 - 111
3174
+ 1,
3175
+ 1,
3176
+ 1,
3177
+ 1,
3178
+ 1,
3179
+ 1,
3180
+ 1,
3181
+ 1,
3182
+ 1,
3183
+ 1,
3184
+ 1,
3185
+ 0,
3186
+ 1,
3187
+ 0,
3188
+ 1,
3189
+ 0
3190
+ // 112 - 127
3191
+ ];
3192
+ function isValidStatusCode(code) {
3193
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
3194
+ }
3195
+ function _isValidUTF8(buf) {
3196
+ const len = buf.length;
3197
+ let i = 0;
3198
+ while (i < len) {
3199
+ if ((buf[i] & 128) === 0) {
3200
+ i++;
3201
+ } else if ((buf[i] & 224) === 192) {
3202
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
3203
+ return false;
3204
+ }
3205
+ i += 2;
3206
+ } else if ((buf[i] & 240) === 224) {
3207
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
3208
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
3209
+ return false;
3210
+ }
3211
+ i += 3;
3212
+ } else if ((buf[i] & 248) === 240) {
3213
+ if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
3214
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
3215
+ return false;
3216
+ }
3217
+ i += 4;
3218
+ } else {
3219
+ return false;
3220
+ }
3221
+ }
3222
+ return true;
3223
+ }
3224
+ function isBlob(value) {
3225
+ return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
3226
+ }
3227
+ module.exports = {
3228
+ isBlob,
3229
+ isValidStatusCode,
3230
+ isValidUTF8: _isValidUTF8,
3231
+ tokenChars
3232
+ };
3233
+ if (isUtf8) {
3234
+ module.exports.isValidUTF8 = function(buf) {
3235
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
3236
+ };
3237
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
3238
+ try {
3239
+ const isValidUTF8 = __require2("utf-8-validate");
3240
+ module.exports.isValidUTF8 = function(buf) {
3241
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
3242
+ };
3243
+ } catch (e) {
3244
+ }
3245
+ }
3246
+ }
3247
+ });
3248
+
3249
+ // ../node_modules/ws/lib/receiver.js
3250
+ var require_receiver = __commonJS({
3251
+ "../node_modules/ws/lib/receiver.js"(exports, module) {
3252
+ "use strict";
3253
+ init_deno_env();
3254
+ var { Writable } = __require2("stream");
3255
+ var PerMessageDeflate = require_permessage_deflate();
3256
+ var {
3257
+ BINARY_TYPES,
3258
+ EMPTY_BUFFER,
3259
+ kStatusCode,
3260
+ kWebSocket
3261
+ } = require_constants();
3262
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
3263
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
3264
+ var FastBuffer = Buffer[Symbol.species];
3265
+ var GET_INFO = 0;
3266
+ var GET_PAYLOAD_LENGTH_16 = 1;
3267
+ var GET_PAYLOAD_LENGTH_64 = 2;
3268
+ var GET_MASK = 3;
3269
+ var GET_DATA = 4;
3270
+ var INFLATING = 5;
3271
+ var DEFER_EVENT = 6;
3272
+ var Receiver2 = class extends Writable {
3273
+ /**
3274
+ * Creates a Receiver instance.
3275
+ *
3276
+ * @param {Object} [options] Options object
3277
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3278
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3279
+ * multiple times in the same tick
3280
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
3281
+ * @param {Object} [options.extensions] An object containing the negotiated
3282
+ * extensions
3283
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
3284
+ * client or server mode
3285
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
3286
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3287
+ * not to skip UTF-8 validation for text and close messages
3288
+ */
3289
+ constructor(options = {}) {
3290
+ super();
3291
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
3292
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
3293
+ this._extensions = options.extensions || {};
3294
+ this._isServer = !!options.isServer;
3295
+ this._maxPayload = options.maxPayload | 0;
3296
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
3297
+ this[kWebSocket] = void 0;
3298
+ this._bufferedBytes = 0;
3299
+ this._buffers = [];
3300
+ this._compressed = false;
3301
+ this._payloadLength = 0;
3302
+ this._mask = void 0;
3303
+ this._fragmented = 0;
3304
+ this._masked = false;
3305
+ this._fin = false;
3306
+ this._opcode = 0;
3307
+ this._totalPayloadLength = 0;
3308
+ this._messageLength = 0;
3309
+ this._fragments = [];
3310
+ this._errored = false;
3311
+ this._loop = false;
3312
+ this._state = GET_INFO;
3313
+ }
3314
+ /**
3315
+ * Implements `Writable.prototype._write()`.
3316
+ *
3317
+ * @param {Buffer} chunk The chunk of data to write
3318
+ * @param {String} encoding The character encoding of `chunk`
3319
+ * @param {Function} cb Callback
3320
+ * @private
3321
+ */
3322
+ _write(chunk, encoding, cb) {
3323
+ if (this._opcode === 8 && this._state == GET_INFO)
3324
+ return cb();
3325
+ this._bufferedBytes += chunk.length;
3326
+ this._buffers.push(chunk);
3327
+ this.startLoop(cb);
3328
+ }
3329
+ /**
3330
+ * Consumes `n` bytes from the buffered data.
3331
+ *
3332
+ * @param {Number} n The number of bytes to consume
3333
+ * @return {Buffer} The consumed bytes
3334
+ * @private
3335
+ */
3336
+ consume(n) {
3337
+ this._bufferedBytes -= n;
3338
+ if (n === this._buffers[0].length)
3339
+ return this._buffers.shift();
3340
+ if (n < this._buffers[0].length) {
3341
+ const buf = this._buffers[0];
3342
+ this._buffers[0] = new FastBuffer(
3343
+ buf.buffer,
3344
+ buf.byteOffset + n,
3345
+ buf.length - n
3346
+ );
3347
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
3348
+ }
3349
+ const dst = Buffer.allocUnsafe(n);
3350
+ do {
3351
+ const buf = this._buffers[0];
3352
+ const offset = dst.length - n;
3353
+ if (n >= buf.length) {
3354
+ dst.set(this._buffers.shift(), offset);
3355
+ } else {
3356
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
3357
+ this._buffers[0] = new FastBuffer(
3358
+ buf.buffer,
3359
+ buf.byteOffset + n,
3360
+ buf.length - n
3361
+ );
3362
+ }
3363
+ n -= buf.length;
3364
+ } while (n > 0);
3365
+ return dst;
3366
+ }
3367
+ /**
3368
+ * Starts the parsing loop.
3369
+ *
3370
+ * @param {Function} cb Callback
3371
+ * @private
3372
+ */
3373
+ startLoop(cb) {
3374
+ this._loop = true;
3375
+ do {
3376
+ switch (this._state) {
3377
+ case GET_INFO:
3378
+ this.getInfo(cb);
3379
+ break;
3380
+ case GET_PAYLOAD_LENGTH_16:
3381
+ this.getPayloadLength16(cb);
3382
+ break;
3383
+ case GET_PAYLOAD_LENGTH_64:
3384
+ this.getPayloadLength64(cb);
3385
+ break;
3386
+ case GET_MASK:
3387
+ this.getMask();
3388
+ break;
3389
+ case GET_DATA:
3390
+ this.getData(cb);
3391
+ break;
3392
+ case INFLATING:
3393
+ case DEFER_EVENT:
3394
+ this._loop = false;
3395
+ return;
3396
+ }
3397
+ } while (this._loop);
3398
+ if (!this._errored)
3399
+ cb();
3400
+ }
3401
+ /**
3402
+ * Reads the first two bytes of a frame.
3403
+ *
3404
+ * @param {Function} cb Callback
3405
+ * @private
3406
+ */
3407
+ getInfo(cb) {
3408
+ if (this._bufferedBytes < 2) {
3409
+ this._loop = false;
3410
+ return;
3411
+ }
3412
+ const buf = this.consume(2);
3413
+ if ((buf[0] & 48) !== 0) {
3414
+ const error = this.createError(
3415
+ RangeError,
3416
+ "RSV2 and RSV3 must be clear",
3417
+ true,
3418
+ 1002,
3419
+ "WS_ERR_UNEXPECTED_RSV_2_3"
3420
+ );
3421
+ cb(error);
3422
+ return;
3423
+ }
3424
+ const compressed = (buf[0] & 64) === 64;
3425
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
3426
+ const error = this.createError(
3427
+ RangeError,
3428
+ "RSV1 must be clear",
3429
+ true,
3430
+ 1002,
3431
+ "WS_ERR_UNEXPECTED_RSV_1"
3432
+ );
3433
+ cb(error);
3434
+ return;
3435
+ }
3436
+ this._fin = (buf[0] & 128) === 128;
3437
+ this._opcode = buf[0] & 15;
3438
+ this._payloadLength = buf[1] & 127;
3439
+ if (this._opcode === 0) {
3440
+ if (compressed) {
3441
+ const error = this.createError(
3442
+ RangeError,
3443
+ "RSV1 must be clear",
3444
+ true,
3445
+ 1002,
3446
+ "WS_ERR_UNEXPECTED_RSV_1"
3447
+ );
3448
+ cb(error);
3449
+ return;
3450
+ }
3451
+ if (!this._fragmented) {
3452
+ const error = this.createError(
3453
+ RangeError,
3454
+ "invalid opcode 0",
3455
+ true,
3456
+ 1002,
3457
+ "WS_ERR_INVALID_OPCODE"
3458
+ );
3459
+ cb(error);
3460
+ return;
3461
+ }
3462
+ this._opcode = this._fragmented;
3463
+ } else if (this._opcode === 1 || this._opcode === 2) {
3464
+ if (this._fragmented) {
3465
+ const error = this.createError(
3466
+ RangeError,
3467
+ `invalid opcode ${this._opcode}`,
3468
+ true,
3469
+ 1002,
3470
+ "WS_ERR_INVALID_OPCODE"
3471
+ );
3472
+ cb(error);
3473
+ return;
3474
+ }
3475
+ this._compressed = compressed;
3476
+ } else if (this._opcode > 7 && this._opcode < 11) {
3477
+ if (!this._fin) {
3478
+ const error = this.createError(
3479
+ RangeError,
3480
+ "FIN must be set",
3481
+ true,
3482
+ 1002,
3483
+ "WS_ERR_EXPECTED_FIN"
3484
+ );
3485
+ cb(error);
3486
+ return;
3487
+ }
3488
+ if (compressed) {
3489
+ const error = this.createError(
3490
+ RangeError,
3491
+ "RSV1 must be clear",
3492
+ true,
3493
+ 1002,
3494
+ "WS_ERR_UNEXPECTED_RSV_1"
3495
+ );
3496
+ cb(error);
3497
+ return;
3498
+ }
3499
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
3500
+ const error = this.createError(
3501
+ RangeError,
3502
+ `invalid payload length ${this._payloadLength}`,
3503
+ true,
3504
+ 1002,
3505
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
3506
+ );
3507
+ cb(error);
3508
+ return;
3509
+ }
3510
+ } else {
3511
+ const error = this.createError(
3512
+ RangeError,
3513
+ `invalid opcode ${this._opcode}`,
3514
+ true,
3515
+ 1002,
3516
+ "WS_ERR_INVALID_OPCODE"
3517
+ );
3518
+ cb(error);
3519
+ return;
3520
+ }
3521
+ if (!this._fin && !this._fragmented)
3522
+ this._fragmented = this._opcode;
3523
+ this._masked = (buf[1] & 128) === 128;
3524
+ if (this._isServer) {
3525
+ if (!this._masked) {
3526
+ const error = this.createError(
3527
+ RangeError,
3528
+ "MASK must be set",
3529
+ true,
3530
+ 1002,
3531
+ "WS_ERR_EXPECTED_MASK"
3532
+ );
3533
+ cb(error);
3534
+ return;
3535
+ }
3536
+ } else if (this._masked) {
3537
+ const error = this.createError(
3538
+ RangeError,
3539
+ "MASK must be clear",
3540
+ true,
3541
+ 1002,
3542
+ "WS_ERR_UNEXPECTED_MASK"
3543
+ );
3544
+ cb(error);
3545
+ return;
3546
+ }
3547
+ if (this._payloadLength === 126)
3548
+ this._state = GET_PAYLOAD_LENGTH_16;
3549
+ else if (this._payloadLength === 127)
3550
+ this._state = GET_PAYLOAD_LENGTH_64;
3551
+ else
3552
+ this.haveLength(cb);
3553
+ }
3554
+ /**
3555
+ * Gets extended payload length (7+16).
3556
+ *
3557
+ * @param {Function} cb Callback
3558
+ * @private
3559
+ */
3560
+ getPayloadLength16(cb) {
3561
+ if (this._bufferedBytes < 2) {
3562
+ this._loop = false;
3563
+ return;
3564
+ }
3565
+ this._payloadLength = this.consume(2).readUInt16BE(0);
3566
+ this.haveLength(cb);
3567
+ }
3568
+ /**
3569
+ * Gets extended payload length (7+64).
3570
+ *
3571
+ * @param {Function} cb Callback
3572
+ * @private
3573
+ */
3574
+ getPayloadLength64(cb) {
3575
+ if (this._bufferedBytes < 8) {
3576
+ this._loop = false;
3577
+ return;
3578
+ }
3579
+ const buf = this.consume(8);
3580
+ const num = buf.readUInt32BE(0);
3581
+ if (num > Math.pow(2, 53 - 32) - 1) {
3582
+ const error = this.createError(
3583
+ RangeError,
3584
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
3585
+ false,
3586
+ 1009,
3587
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
3588
+ );
3589
+ cb(error);
3590
+ return;
3591
+ }
3592
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
3593
+ this.haveLength(cb);
3594
+ }
3595
+ /**
3596
+ * Payload length has been read.
3597
+ *
3598
+ * @param {Function} cb Callback
3599
+ * @private
3600
+ */
3601
+ haveLength(cb) {
3602
+ if (this._payloadLength && this._opcode < 8) {
3603
+ this._totalPayloadLength += this._payloadLength;
3604
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
3605
+ const error = this.createError(
3606
+ RangeError,
3607
+ "Max payload size exceeded",
3608
+ false,
3609
+ 1009,
3610
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
3611
+ );
3612
+ cb(error);
3613
+ return;
3614
+ }
3615
+ }
3616
+ if (this._masked)
3617
+ this._state = GET_MASK;
3618
+ else
3619
+ this._state = GET_DATA;
3620
+ }
3621
+ /**
3622
+ * Reads mask bytes.
3623
+ *
3624
+ * @private
3625
+ */
3626
+ getMask() {
3627
+ if (this._bufferedBytes < 4) {
3628
+ this._loop = false;
3629
+ return;
3630
+ }
3631
+ this._mask = this.consume(4);
3632
+ this._state = GET_DATA;
3633
+ }
3634
+ /**
3635
+ * Reads data bytes.
3636
+ *
3637
+ * @param {Function} cb Callback
3638
+ * @private
3639
+ */
3640
+ getData(cb) {
3641
+ let data = EMPTY_BUFFER;
3642
+ if (this._payloadLength) {
3643
+ if (this._bufferedBytes < this._payloadLength) {
3644
+ this._loop = false;
3645
+ return;
3646
+ }
3647
+ data = this.consume(this._payloadLength);
3648
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
3649
+ unmask(data, this._mask);
3650
+ }
3651
+ }
3652
+ if (this._opcode > 7) {
3653
+ this.controlMessage(data, cb);
3654
+ return;
3655
+ }
3656
+ if (this._compressed) {
3657
+ this._state = INFLATING;
3658
+ this.decompress(data, cb);
3659
+ return;
3660
+ }
3661
+ if (data.length) {
3662
+ this._messageLength = this._totalPayloadLength;
3663
+ this._fragments.push(data);
3664
+ }
3665
+ this.dataMessage(cb);
3666
+ }
3667
+ /**
3668
+ * Decompresses data.
3669
+ *
3670
+ * @param {Buffer} data Compressed data
3671
+ * @param {Function} cb Callback
3672
+ * @private
3673
+ */
3674
+ decompress(data, cb) {
3675
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
3676
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
3677
+ if (err)
3678
+ return cb(err);
3679
+ if (buf.length) {
3680
+ this._messageLength += buf.length;
3681
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
3682
+ const error = this.createError(
3683
+ RangeError,
3684
+ "Max payload size exceeded",
3685
+ false,
3686
+ 1009,
3687
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
3688
+ );
3689
+ cb(error);
3690
+ return;
3691
+ }
3692
+ this._fragments.push(buf);
3693
+ }
3694
+ this.dataMessage(cb);
3695
+ if (this._state === GET_INFO)
3696
+ this.startLoop(cb);
3697
+ });
3698
+ }
3699
+ /**
3700
+ * Handles a data message.
3701
+ *
3702
+ * @param {Function} cb Callback
3703
+ * @private
3704
+ */
3705
+ dataMessage(cb) {
3706
+ if (!this._fin) {
3707
+ this._state = GET_INFO;
3708
+ return;
3709
+ }
3710
+ const messageLength = this._messageLength;
3711
+ const fragments = this._fragments;
3712
+ this._totalPayloadLength = 0;
3713
+ this._messageLength = 0;
3714
+ this._fragmented = 0;
3715
+ this._fragments = [];
3716
+ if (this._opcode === 2) {
3717
+ let data;
3718
+ if (this._binaryType === "nodebuffer") {
3719
+ data = concat(fragments, messageLength);
3720
+ } else if (this._binaryType === "arraybuffer") {
3721
+ data = toArrayBuffer(concat(fragments, messageLength));
3722
+ } else if (this._binaryType === "blob") {
3723
+ data = new Blob(fragments);
3724
+ } else {
3725
+ data = fragments;
3726
+ }
3727
+ if (this._allowSynchronousEvents) {
3728
+ this.emit("message", data, true);
3729
+ this._state = GET_INFO;
3730
+ } else {
3731
+ this._state = DEFER_EVENT;
3732
+ setImmediate(() => {
3733
+ this.emit("message", data, true);
3734
+ this._state = GET_INFO;
3735
+ this.startLoop(cb);
3736
+ });
3737
+ }
3738
+ } else {
3739
+ const buf = concat(fragments, messageLength);
3740
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
3741
+ const error = this.createError(
3742
+ Error,
3743
+ "invalid UTF-8 sequence",
3744
+ true,
3745
+ 1007,
3746
+ "WS_ERR_INVALID_UTF8"
3747
+ );
3748
+ cb(error);
3749
+ return;
3750
+ }
3751
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
3752
+ this.emit("message", buf, false);
3753
+ this._state = GET_INFO;
3754
+ } else {
3755
+ this._state = DEFER_EVENT;
3756
+ setImmediate(() => {
3757
+ this.emit("message", buf, false);
3758
+ this._state = GET_INFO;
3759
+ this.startLoop(cb);
3760
+ });
3761
+ }
3762
+ }
3763
+ }
3764
+ /**
3765
+ * Handles a control message.
3766
+ *
3767
+ * @param {Buffer} data Data to handle
3768
+ * @return {(Error|RangeError|undefined)} A possible error
3769
+ * @private
3770
+ */
3771
+ controlMessage(data, cb) {
3772
+ if (this._opcode === 8) {
3773
+ if (data.length === 0) {
3774
+ this._loop = false;
3775
+ this.emit("conclude", 1005, EMPTY_BUFFER);
3776
+ this.end();
3777
+ } else {
3778
+ const code = data.readUInt16BE(0);
3779
+ if (!isValidStatusCode(code)) {
3780
+ const error = this.createError(
3781
+ RangeError,
3782
+ `invalid status code ${code}`,
3783
+ true,
3784
+ 1002,
3785
+ "WS_ERR_INVALID_CLOSE_CODE"
3786
+ );
3787
+ cb(error);
3788
+ return;
3789
+ }
3790
+ const buf = new FastBuffer(
3791
+ data.buffer,
3792
+ data.byteOffset + 2,
3793
+ data.length - 2
3794
+ );
3795
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
3796
+ const error = this.createError(
3797
+ Error,
3798
+ "invalid UTF-8 sequence",
3799
+ true,
3800
+ 1007,
3801
+ "WS_ERR_INVALID_UTF8"
3802
+ );
3803
+ cb(error);
3804
+ return;
3805
+ }
3806
+ this._loop = false;
3807
+ this.emit("conclude", code, buf);
3808
+ this.end();
3809
+ }
3810
+ this._state = GET_INFO;
3811
+ return;
3812
+ }
3813
+ if (this._allowSynchronousEvents) {
3814
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
3815
+ this._state = GET_INFO;
3816
+ } else {
3817
+ this._state = DEFER_EVENT;
3818
+ setImmediate(() => {
3819
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
3820
+ this._state = GET_INFO;
3821
+ this.startLoop(cb);
3822
+ });
3823
+ }
3824
+ }
3825
+ /**
3826
+ * Builds an error object.
3827
+ *
3828
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
3829
+ * @param {String} message The error message
3830
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
3831
+ * `message`
3832
+ * @param {Number} statusCode The status code
3833
+ * @param {String} errorCode The exposed error code
3834
+ * @return {(Error|RangeError)} The error
3835
+ * @private
3836
+ */
3837
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
3838
+ this._loop = false;
3839
+ this._errored = true;
3840
+ const err = new ErrorCtor(
3841
+ prefix ? `Invalid WebSocket frame: ${message}` : message
3842
+ );
3843
+ Error.captureStackTrace(err, this.createError);
3844
+ err.code = errorCode;
3845
+ err[kStatusCode] = statusCode;
3846
+ return err;
3847
+ }
3848
+ };
3849
+ module.exports = Receiver2;
3850
+ }
3851
+ });
3852
+
3853
+ // ../node_modules/ws/lib/sender.js
3854
+ var require_sender = __commonJS({
3855
+ "../node_modules/ws/lib/sender.js"(exports, module) {
3856
+ "use strict";
3857
+ init_deno_env();
3858
+ var { Duplex } = __require2("stream");
3859
+ var { randomFillSync } = __require2("crypto");
3860
+ var PerMessageDeflate = require_permessage_deflate();
3861
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
3862
+ var { isBlob, isValidStatusCode } = require_validation();
3863
+ var { mask: applyMask, toBuffer } = require_buffer_util();
3864
+ var kByteLength = Symbol("kByteLength");
3865
+ var maskBuffer = Buffer.alloc(4);
3866
+ var RANDOM_POOL_SIZE = 8 * 1024;
3867
+ var randomPool;
3868
+ var randomPoolPointer = RANDOM_POOL_SIZE;
3869
+ var DEFAULT = 0;
3870
+ var DEFLATING = 1;
3871
+ var GET_BLOB_DATA = 2;
3872
+ var Sender2 = class _Sender {
3873
+ /**
3874
+ * Creates a Sender instance.
3875
+ *
3876
+ * @param {Duplex} socket The connection socket
3877
+ * @param {Object} [extensions] An object containing the negotiated extensions
3878
+ * @param {Function} [generateMask] The function used to generate the masking
3879
+ * key
3880
+ */
3881
+ constructor(socket, extensions, generateMask) {
3882
+ this._extensions = extensions || {};
3883
+ if (generateMask) {
3884
+ this._generateMask = generateMask;
3885
+ this._maskBuffer = Buffer.alloc(4);
3886
+ }
3887
+ this._socket = socket;
3888
+ this._firstFragment = true;
3889
+ this._compress = false;
3890
+ this._bufferedBytes = 0;
3891
+ this._queue = [];
3892
+ this._state = DEFAULT;
3893
+ this.onerror = NOOP;
3894
+ this[kWebSocket] = void 0;
3895
+ }
3896
+ /**
3897
+ * Frames a piece of data according to the HyBi WebSocket protocol.
3898
+ *
3899
+ * @param {(Buffer|String)} data The data to frame
3900
+ * @param {Object} options Options object
3901
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
3902
+ * FIN bit
3903
+ * @param {Function} [options.generateMask] The function used to generate the
3904
+ * masking key
3905
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
3906
+ * `data`
3907
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
3908
+ * key
3909
+ * @param {Number} options.opcode The opcode
3910
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
3911
+ * modified
3912
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
3913
+ * RSV1 bit
3914
+ * @return {(Buffer|String)[]} The framed data
3915
+ * @public
3916
+ */
3917
+ static frame(data, options) {
3918
+ let mask;
3919
+ let merge = false;
3920
+ let offset = 2;
3921
+ let skipMasking = false;
3922
+ if (options.mask) {
3923
+ mask = options.maskBuffer || maskBuffer;
3924
+ if (options.generateMask) {
3925
+ options.generateMask(mask);
3926
+ } else {
3927
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
3928
+ if (randomPool === void 0) {
3929
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
3930
+ }
3931
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
3932
+ randomPoolPointer = 0;
3933
+ }
3934
+ mask[0] = randomPool[randomPoolPointer++];
3935
+ mask[1] = randomPool[randomPoolPointer++];
3936
+ mask[2] = randomPool[randomPoolPointer++];
3937
+ mask[3] = randomPool[randomPoolPointer++];
3938
+ }
3939
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
3940
+ offset = 6;
3941
+ }
3942
+ let dataLength;
3943
+ if (typeof data === "string") {
3944
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
3945
+ dataLength = options[kByteLength];
3946
+ } else {
3947
+ data = Buffer.from(data);
3948
+ dataLength = data.length;
3949
+ }
3950
+ } else {
3951
+ dataLength = data.length;
3952
+ merge = options.mask && options.readOnly && !skipMasking;
3953
+ }
3954
+ let payloadLength = dataLength;
3955
+ if (dataLength >= 65536) {
3956
+ offset += 8;
3957
+ payloadLength = 127;
3958
+ } else if (dataLength > 125) {
3959
+ offset += 2;
3960
+ payloadLength = 126;
3961
+ }
3962
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
3963
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
3964
+ if (options.rsv1)
3965
+ target[0] |= 64;
3966
+ target[1] = payloadLength;
3967
+ if (payloadLength === 126) {
3968
+ target.writeUInt16BE(dataLength, 2);
3969
+ } else if (payloadLength === 127) {
3970
+ target[2] = target[3] = 0;
3971
+ target.writeUIntBE(dataLength, 4, 6);
3972
+ }
3973
+ if (!options.mask)
3974
+ return [target, data];
3975
+ target[1] |= 128;
3976
+ target[offset - 4] = mask[0];
3977
+ target[offset - 3] = mask[1];
3978
+ target[offset - 2] = mask[2];
3979
+ target[offset - 1] = mask[3];
3980
+ if (skipMasking)
3981
+ return [target, data];
3982
+ if (merge) {
3983
+ applyMask(data, mask, target, offset, dataLength);
3984
+ return [target];
3985
+ }
3986
+ applyMask(data, mask, data, 0, dataLength);
3987
+ return [target, data];
3988
+ }
3989
+ /**
3990
+ * Sends a close message to the other peer.
3991
+ *
3992
+ * @param {Number} [code] The status code component of the body
3993
+ * @param {(String|Buffer)} [data] The message component of the body
3994
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
3995
+ * @param {Function} [cb] Callback
3996
+ * @public
3997
+ */
3998
+ close(code, data, mask, cb) {
3999
+ let buf;
4000
+ if (code === void 0) {
4001
+ buf = EMPTY_BUFFER;
4002
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
4003
+ throw new TypeError("First argument must be a valid error code number");
4004
+ } else if (data === void 0 || !data.length) {
4005
+ buf = Buffer.allocUnsafe(2);
4006
+ buf.writeUInt16BE(code, 0);
4007
+ } else {
4008
+ const length = Buffer.byteLength(data);
4009
+ if (length > 123) {
4010
+ throw new RangeError("The message must not be greater than 123 bytes");
4011
+ }
4012
+ buf = Buffer.allocUnsafe(2 + length);
4013
+ buf.writeUInt16BE(code, 0);
4014
+ if (typeof data === "string") {
4015
+ buf.write(data, 2);
4016
+ } else {
4017
+ buf.set(data, 2);
4018
+ }
4019
+ }
4020
+ const options = {
4021
+ [kByteLength]: buf.length,
4022
+ fin: true,
4023
+ generateMask: this._generateMask,
4024
+ mask,
4025
+ maskBuffer: this._maskBuffer,
4026
+ opcode: 8,
4027
+ readOnly: false,
4028
+ rsv1: false
4029
+ };
4030
+ if (this._state !== DEFAULT) {
4031
+ this.enqueue([this.dispatch, buf, false, options, cb]);
4032
+ } else {
4033
+ this.sendFrame(_Sender.frame(buf, options), cb);
4034
+ }
4035
+ }
4036
+ /**
4037
+ * Sends a ping message to the other peer.
4038
+ *
4039
+ * @param {*} data The message to send
4040
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
4041
+ * @param {Function} [cb] Callback
4042
+ * @public
4043
+ */
4044
+ ping(data, mask, cb) {
4045
+ let byteLength;
4046
+ let readOnly;
4047
+ if (typeof data === "string") {
4048
+ byteLength = Buffer.byteLength(data);
4049
+ readOnly = false;
4050
+ } else if (isBlob(data)) {
4051
+ byteLength = data.size;
4052
+ readOnly = false;
4053
+ } else {
4054
+ data = toBuffer(data);
4055
+ byteLength = data.length;
4056
+ readOnly = toBuffer.readOnly;
4057
+ }
4058
+ if (byteLength > 125) {
4059
+ throw new RangeError("The data size must not be greater than 125 bytes");
4060
+ }
4061
+ const options = {
4062
+ [kByteLength]: byteLength,
4063
+ fin: true,
4064
+ generateMask: this._generateMask,
4065
+ mask,
4066
+ maskBuffer: this._maskBuffer,
4067
+ opcode: 9,
4068
+ readOnly,
4069
+ rsv1: false
4070
+ };
4071
+ if (isBlob(data)) {
4072
+ if (this._state !== DEFAULT) {
4073
+ this.enqueue([this.getBlobData, data, false, options, cb]);
4074
+ } else {
4075
+ this.getBlobData(data, false, options, cb);
4076
+ }
4077
+ } else if (this._state !== DEFAULT) {
4078
+ this.enqueue([this.dispatch, data, false, options, cb]);
4079
+ } else {
4080
+ this.sendFrame(_Sender.frame(data, options), cb);
4081
+ }
4082
+ }
4083
+ /**
4084
+ * Sends a pong message to the other peer.
4085
+ *
4086
+ * @param {*} data The message to send
4087
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
4088
+ * @param {Function} [cb] Callback
4089
+ * @public
4090
+ */
4091
+ pong(data, mask, cb) {
4092
+ let byteLength;
4093
+ let readOnly;
4094
+ if (typeof data === "string") {
4095
+ byteLength = Buffer.byteLength(data);
4096
+ readOnly = false;
4097
+ } else if (isBlob(data)) {
4098
+ byteLength = data.size;
4099
+ readOnly = false;
4100
+ } else {
4101
+ data = toBuffer(data);
4102
+ byteLength = data.length;
4103
+ readOnly = toBuffer.readOnly;
4104
+ }
4105
+ if (byteLength > 125) {
4106
+ throw new RangeError("The data size must not be greater than 125 bytes");
4107
+ }
4108
+ const options = {
4109
+ [kByteLength]: byteLength,
4110
+ fin: true,
4111
+ generateMask: this._generateMask,
4112
+ mask,
4113
+ maskBuffer: this._maskBuffer,
4114
+ opcode: 10,
4115
+ readOnly,
4116
+ rsv1: false
4117
+ };
4118
+ if (isBlob(data)) {
4119
+ if (this._state !== DEFAULT) {
4120
+ this.enqueue([this.getBlobData, data, false, options, cb]);
4121
+ } else {
4122
+ this.getBlobData(data, false, options, cb);
4123
+ }
4124
+ } else if (this._state !== DEFAULT) {
4125
+ this.enqueue([this.dispatch, data, false, options, cb]);
4126
+ } else {
4127
+ this.sendFrame(_Sender.frame(data, options), cb);
4128
+ }
4129
+ }
4130
+ /**
4131
+ * Sends a data message to the other peer.
4132
+ *
4133
+ * @param {*} data The message to send
4134
+ * @param {Object} options Options object
4135
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
4136
+ * or text
4137
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
4138
+ * compress `data`
4139
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
4140
+ * last one
4141
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
4142
+ * `data`
4143
+ * @param {Function} [cb] Callback
4144
+ * @public
4145
+ */
4146
+ send(data, options, cb) {
4147
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
4148
+ let opcode = options.binary ? 2 : 1;
4149
+ let rsv1 = options.compress;
4150
+ let byteLength;
4151
+ let readOnly;
4152
+ if (typeof data === "string") {
4153
+ byteLength = Buffer.byteLength(data);
4154
+ readOnly = false;
4155
+ } else if (isBlob(data)) {
4156
+ byteLength = data.size;
4157
+ readOnly = false;
4158
+ } else {
4159
+ data = toBuffer(data);
4160
+ byteLength = data.length;
4161
+ readOnly = toBuffer.readOnly;
4162
+ }
4163
+ if (this._firstFragment) {
4164
+ this._firstFragment = false;
4165
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
4166
+ rsv1 = byteLength >= perMessageDeflate._threshold;
4167
+ }
4168
+ this._compress = rsv1;
4169
+ } else {
4170
+ rsv1 = false;
4171
+ opcode = 0;
4172
+ }
4173
+ if (options.fin)
4174
+ this._firstFragment = true;
4175
+ const opts = {
4176
+ [kByteLength]: byteLength,
4177
+ fin: options.fin,
4178
+ generateMask: this._generateMask,
4179
+ mask: options.mask,
4180
+ maskBuffer: this._maskBuffer,
4181
+ opcode,
4182
+ readOnly,
4183
+ rsv1
4184
+ };
4185
+ if (isBlob(data)) {
4186
+ if (this._state !== DEFAULT) {
4187
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
4188
+ } else {
4189
+ this.getBlobData(data, this._compress, opts, cb);
4190
+ }
4191
+ } else if (this._state !== DEFAULT) {
4192
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
4193
+ } else {
4194
+ this.dispatch(data, this._compress, opts, cb);
4195
+ }
4196
+ }
4197
+ /**
4198
+ * Gets the contents of a blob as binary data.
4199
+ *
4200
+ * @param {Blob} blob The blob
4201
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
4202
+ * the data
4203
+ * @param {Object} options Options object
4204
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
4205
+ * FIN bit
4206
+ * @param {Function} [options.generateMask] The function used to generate the
4207
+ * masking key
4208
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
4209
+ * `data`
4210
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
4211
+ * key
4212
+ * @param {Number} options.opcode The opcode
4213
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
4214
+ * modified
4215
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
4216
+ * RSV1 bit
4217
+ * @param {Function} [cb] Callback
4218
+ * @private
4219
+ */
4220
+ getBlobData(blob, compress, options, cb) {
4221
+ this._bufferedBytes += options[kByteLength];
4222
+ this._state = GET_BLOB_DATA;
4223
+ blob.arrayBuffer().then((arrayBuffer) => {
4224
+ if (this._socket.destroyed) {
4225
+ const err = new Error(
4226
+ "The socket was closed while the blob was being read"
4227
+ );
4228
+ process.nextTick(callCallbacks, this, err, cb);
4229
+ return;
4230
+ }
4231
+ this._bufferedBytes -= options[kByteLength];
4232
+ const data = toBuffer(arrayBuffer);
4233
+ if (!compress) {
4234
+ this._state = DEFAULT;
4235
+ this.sendFrame(_Sender.frame(data, options), cb);
4236
+ this.dequeue();
4237
+ } else {
4238
+ this.dispatch(data, compress, options, cb);
4239
+ }
4240
+ }).catch((err) => {
4241
+ process.nextTick(onError, this, err, cb);
4242
+ });
4243
+ }
4244
+ /**
4245
+ * Dispatches a message.
4246
+ *
4247
+ * @param {(Buffer|String)} data The message to send
4248
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
4249
+ * `data`
4250
+ * @param {Object} options Options object
4251
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
4252
+ * FIN bit
4253
+ * @param {Function} [options.generateMask] The function used to generate the
4254
+ * masking key
4255
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
4256
+ * `data`
4257
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
4258
+ * key
4259
+ * @param {Number} options.opcode The opcode
4260
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
4261
+ * modified
4262
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
4263
+ * RSV1 bit
4264
+ * @param {Function} [cb] Callback
4265
+ * @private
4266
+ */
4267
+ dispatch(data, compress, options, cb) {
4268
+ if (!compress) {
4269
+ this.sendFrame(_Sender.frame(data, options), cb);
4270
+ return;
4271
+ }
4272
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
4273
+ this._bufferedBytes += options[kByteLength];
4274
+ this._state = DEFLATING;
4275
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
4276
+ if (this._socket.destroyed) {
4277
+ const err = new Error(
4278
+ "The socket was closed while data was being compressed"
4279
+ );
4280
+ callCallbacks(this, err, cb);
4281
+ return;
4282
+ }
4283
+ this._bufferedBytes -= options[kByteLength];
4284
+ this._state = DEFAULT;
4285
+ options.readOnly = false;
4286
+ this.sendFrame(_Sender.frame(buf, options), cb);
4287
+ this.dequeue();
4288
+ });
4289
+ }
4290
+ /**
4291
+ * Executes queued send operations.
4292
+ *
4293
+ * @private
4294
+ */
4295
+ dequeue() {
4296
+ while (this._state === DEFAULT && this._queue.length) {
4297
+ const params = this._queue.shift();
4298
+ this._bufferedBytes -= params[3][kByteLength];
4299
+ Reflect.apply(params[0], this, params.slice(1));
4300
+ }
4301
+ }
4302
+ /**
4303
+ * Enqueues a send operation.
4304
+ *
4305
+ * @param {Array} params Send operation parameters.
4306
+ * @private
4307
+ */
4308
+ enqueue(params) {
4309
+ this._bufferedBytes += params[3][kByteLength];
4310
+ this._queue.push(params);
4311
+ }
4312
+ /**
4313
+ * Sends a frame.
4314
+ *
4315
+ * @param {(Buffer | String)[]} list The frame to send
4316
+ * @param {Function} [cb] Callback
4317
+ * @private
4318
+ */
4319
+ sendFrame(list, cb) {
4320
+ if (list.length === 2) {
4321
+ this._socket.cork();
4322
+ this._socket.write(list[0]);
4323
+ this._socket.write(list[1], cb);
4324
+ this._socket.uncork();
4325
+ } else {
4326
+ this._socket.write(list[0], cb);
4327
+ }
4328
+ }
4329
+ };
4330
+ module.exports = Sender2;
4331
+ function callCallbacks(sender, err, cb) {
4332
+ if (typeof cb === "function")
4333
+ cb(err);
4334
+ for (let i = 0; i < sender._queue.length; i++) {
4335
+ const params = sender._queue[i];
4336
+ const callback = params[params.length - 1];
4337
+ if (typeof callback === "function")
4338
+ callback(err);
4339
+ }
4340
+ }
4341
+ function onError(sender, err, cb) {
4342
+ callCallbacks(sender, err, cb);
4343
+ sender.onerror(err);
4344
+ }
4345
+ }
4346
+ });
4347
+
4348
+ // ../node_modules/ws/lib/event-target.js
4349
+ var require_event_target = __commonJS({
4350
+ "../node_modules/ws/lib/event-target.js"(exports, module) {
4351
+ "use strict";
4352
+ init_deno_env();
4353
+ var { kForOnEventAttribute, kListener } = require_constants();
4354
+ var kCode = Symbol("kCode");
4355
+ var kData = Symbol("kData");
4356
+ var kError = Symbol("kError");
4357
+ var kMessage = Symbol("kMessage");
4358
+ var kReason = Symbol("kReason");
4359
+ var kTarget = Symbol("kTarget");
4360
+ var kType = Symbol("kType");
4361
+ var kWasClean = Symbol("kWasClean");
4362
+ var Event2 = class {
4363
+ /**
4364
+ * Create a new `Event`.
4365
+ *
4366
+ * @param {String} type The name of the event
4367
+ * @throws {TypeError} If the `type` argument is not specified
4368
+ */
4369
+ constructor(type) {
4370
+ this[kTarget] = null;
4371
+ this[kType] = type;
4372
+ }
4373
+ /**
4374
+ * @type {*}
4375
+ */
4376
+ get target() {
4377
+ return this[kTarget];
4378
+ }
4379
+ /**
4380
+ * @type {String}
4381
+ */
4382
+ get type() {
4383
+ return this[kType];
4384
+ }
4385
+ };
4386
+ Object.defineProperty(Event2.prototype, "target", { enumerable: true });
4387
+ Object.defineProperty(Event2.prototype, "type", { enumerable: true });
4388
+ var CloseEvent2 = class extends Event2 {
4389
+ /**
4390
+ * Create a new `CloseEvent`.
4391
+ *
4392
+ * @param {String} type The name of the event
4393
+ * @param {Object} [options] A dictionary object that allows for setting
4394
+ * attributes via object members of the same name
4395
+ * @param {Number} [options.code=0] The status code explaining why the
4396
+ * connection was closed
4397
+ * @param {String} [options.reason=''] A human-readable string explaining why
4398
+ * the connection was closed
4399
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
4400
+ * connection was cleanly closed
4401
+ */
4402
+ constructor(type, options = {}) {
4403
+ super(type);
4404
+ this[kCode] = options.code === void 0 ? 0 : options.code;
4405
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
4406
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
4407
+ }
4408
+ /**
4409
+ * @type {Number}
4410
+ */
4411
+ get code() {
4412
+ return this[kCode];
4413
+ }
4414
+ /**
4415
+ * @type {String}
4416
+ */
4417
+ get reason() {
4418
+ return this[kReason];
4419
+ }
4420
+ /**
4421
+ * @type {Boolean}
4422
+ */
4423
+ get wasClean() {
4424
+ return this[kWasClean];
4425
+ }
4426
+ };
4427
+ Object.defineProperty(CloseEvent2.prototype, "code", { enumerable: true });
4428
+ Object.defineProperty(CloseEvent2.prototype, "reason", { enumerable: true });
4429
+ Object.defineProperty(CloseEvent2.prototype, "wasClean", { enumerable: true });
4430
+ var ErrorEvent2 = class extends Event2 {
4431
+ /**
4432
+ * Create a new `ErrorEvent`.
4433
+ *
4434
+ * @param {String} type The name of the event
4435
+ * @param {Object} [options] A dictionary object that allows for setting
4436
+ * attributes via object members of the same name
4437
+ * @param {*} [options.error=null] The error that generated this event
4438
+ * @param {String} [options.message=''] The error message
4439
+ */
4440
+ constructor(type, options = {}) {
4441
+ super(type);
4442
+ this[kError] = options.error === void 0 ? null : options.error;
4443
+ this[kMessage] = options.message === void 0 ? "" : options.message;
4444
+ }
4445
+ /**
4446
+ * @type {*}
4447
+ */
4448
+ get error() {
4449
+ return this[kError];
4450
+ }
4451
+ /**
4452
+ * @type {String}
4453
+ */
4454
+ get message() {
4455
+ return this[kMessage];
4456
+ }
4457
+ };
4458
+ Object.defineProperty(ErrorEvent2.prototype, "error", { enumerable: true });
4459
+ Object.defineProperty(ErrorEvent2.prototype, "message", { enumerable: true });
4460
+ var MessageEvent2 = class extends Event2 {
4461
+ /**
4462
+ * Create a new `MessageEvent`.
4463
+ *
4464
+ * @param {String} type The name of the event
4465
+ * @param {Object} [options] A dictionary object that allows for setting
4466
+ * attributes via object members of the same name
4467
+ * @param {*} [options.data=null] The message content
4468
+ */
4469
+ constructor(type, options = {}) {
4470
+ super(type);
4471
+ this[kData] = options.data === void 0 ? null : options.data;
4472
+ }
4473
+ /**
4474
+ * @type {*}
4475
+ */
4476
+ get data() {
4477
+ return this[kData];
4478
+ }
4479
+ };
4480
+ Object.defineProperty(MessageEvent2.prototype, "data", { enumerable: true });
4481
+ var EventTarget = {
4482
+ /**
4483
+ * Register an event listener.
4484
+ *
4485
+ * @param {String} type A string representing the event type to listen for
4486
+ * @param {(Function|Object)} handler The listener to add
4487
+ * @param {Object} [options] An options object specifies characteristics about
4488
+ * the event listener
4489
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
4490
+ * listener should be invoked at most once after being added. If `true`,
4491
+ * the listener would be automatically removed when invoked.
4492
+ * @public
4493
+ */
4494
+ addEventListener(type, handler, options = {}) {
4495
+ for (const listener of this.listeners(type)) {
4496
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
4497
+ return;
4498
+ }
4499
+ }
4500
+ let wrapper;
4501
+ if (type === "message") {
4502
+ wrapper = function onMessage(data, isBinary) {
4503
+ const event = new MessageEvent2("message", {
4504
+ data: isBinary ? data : data.toString()
4505
+ });
4506
+ event[kTarget] = this;
4507
+ callListener(handler, this, event);
4508
+ };
4509
+ } else if (type === "close") {
4510
+ wrapper = function onClose(code, message) {
4511
+ const event = new CloseEvent2("close", {
4512
+ code,
4513
+ reason: message.toString(),
4514
+ wasClean: this._closeFrameReceived && this._closeFrameSent
4515
+ });
4516
+ event[kTarget] = this;
4517
+ callListener(handler, this, event);
4518
+ };
4519
+ } else if (type === "error") {
4520
+ wrapper = function onError(error) {
4521
+ const event = new ErrorEvent2("error", {
4522
+ error,
4523
+ message: error.message
4524
+ });
4525
+ event[kTarget] = this;
4526
+ callListener(handler, this, event);
4527
+ };
4528
+ } else if (type === "open") {
4529
+ wrapper = function onOpen() {
4530
+ const event = new Event2("open");
4531
+ event[kTarget] = this;
4532
+ callListener(handler, this, event);
4533
+ };
4534
+ } else {
4535
+ return;
4536
+ }
4537
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
4538
+ wrapper[kListener] = handler;
4539
+ if (options.once) {
4540
+ this.once(type, wrapper);
4541
+ } else {
4542
+ this.on(type, wrapper);
4543
+ }
4544
+ },
4545
+ /**
4546
+ * Remove an event listener.
4547
+ *
4548
+ * @param {String} type A string representing the event type to remove
4549
+ * @param {(Function|Object)} handler The listener to remove
4550
+ * @public
4551
+ */
4552
+ removeEventListener(type, handler) {
4553
+ for (const listener of this.listeners(type)) {
4554
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
4555
+ this.removeListener(type, listener);
4556
+ break;
4557
+ }
4558
+ }
4559
+ }
4560
+ };
4561
+ module.exports = {
4562
+ CloseEvent: CloseEvent2,
4563
+ ErrorEvent: ErrorEvent2,
4564
+ Event: Event2,
4565
+ EventTarget,
4566
+ MessageEvent: MessageEvent2
4567
+ };
4568
+ function callListener(listener, thisArg, event) {
4569
+ if (typeof listener === "object" && listener.handleEvent) {
4570
+ listener.handleEvent.call(listener, event);
4571
+ } else {
4572
+ listener.call(thisArg, event);
4573
+ }
4574
+ }
4575
+ }
4576
+ });
4577
+
4578
+ // ../node_modules/ws/lib/extension.js
4579
+ var require_extension = __commonJS({
4580
+ "../node_modules/ws/lib/extension.js"(exports, module) {
4581
+ "use strict";
4582
+ init_deno_env();
4583
+ var { tokenChars } = require_validation();
4584
+ function push(dest, name, elem) {
4585
+ if (dest[name] === void 0)
4586
+ dest[name] = [elem];
4587
+ else
4588
+ dest[name].push(elem);
4589
+ }
4590
+ function parse(header) {
4591
+ const offers = /* @__PURE__ */ Object.create(null);
4592
+ let params = /* @__PURE__ */ Object.create(null);
4593
+ let mustUnescape = false;
4594
+ let isEscaping = false;
4595
+ let inQuotes = false;
4596
+ let extensionName;
4597
+ let paramName;
4598
+ let start = -1;
4599
+ let code = -1;
4600
+ let end = -1;
4601
+ let i = 0;
4602
+ for (; i < header.length; i++) {
4603
+ code = header.charCodeAt(i);
4604
+ if (extensionName === void 0) {
4605
+ if (end === -1 && tokenChars[code] === 1) {
4606
+ if (start === -1)
4607
+ start = i;
4608
+ } else if (i !== 0 && (code === 32 || code === 9)) {
4609
+ if (end === -1 && start !== -1)
4610
+ end = i;
4611
+ } else if (code === 59 || code === 44) {
4612
+ if (start === -1) {
4613
+ throw new SyntaxError(`Unexpected character at index ${i}`);
4614
+ }
4615
+ if (end === -1)
4616
+ end = i;
4617
+ const name = header.slice(start, end);
4618
+ if (code === 44) {
4619
+ push(offers, name, params);
4620
+ params = /* @__PURE__ */ Object.create(null);
4621
+ } else {
4622
+ extensionName = name;
4623
+ }
4624
+ start = end = -1;
4625
+ } else {
4626
+ throw new SyntaxError(`Unexpected character at index ${i}`);
4627
+ }
4628
+ } else if (paramName === void 0) {
4629
+ if (end === -1 && tokenChars[code] === 1) {
4630
+ if (start === -1)
4631
+ start = i;
4632
+ } else if (code === 32 || code === 9) {
4633
+ if (end === -1 && start !== -1)
4634
+ end = i;
4635
+ } else if (code === 59 || code === 44) {
4636
+ if (start === -1) {
4637
+ throw new SyntaxError(`Unexpected character at index ${i}`);
4638
+ }
4639
+ if (end === -1)
4640
+ end = i;
4641
+ push(params, header.slice(start, end), true);
4642
+ if (code === 44) {
4643
+ push(offers, extensionName, params);
4644
+ params = /* @__PURE__ */ Object.create(null);
4645
+ extensionName = void 0;
4646
+ }
4647
+ start = end = -1;
4648
+ } else if (code === 61 && start !== -1 && end === -1) {
4649
+ paramName = header.slice(start, i);
4650
+ start = end = -1;
4651
+ } else {
4652
+ throw new SyntaxError(`Unexpected character at index ${i}`);
4653
+ }
4654
+ } else {
4655
+ if (isEscaping) {
4656
+ if (tokenChars[code] !== 1) {
4657
+ throw new SyntaxError(`Unexpected character at index ${i}`);
4658
+ }
4659
+ if (start === -1)
4660
+ start = i;
4661
+ else if (!mustUnescape)
4662
+ mustUnescape = true;
4663
+ isEscaping = false;
4664
+ } else if (inQuotes) {
4665
+ if (tokenChars[code] === 1) {
4666
+ if (start === -1)
4667
+ start = i;
4668
+ } else if (code === 34 && start !== -1) {
4669
+ inQuotes = false;
4670
+ end = i;
4671
+ } else if (code === 92) {
4672
+ isEscaping = true;
4673
+ } else {
4674
+ throw new SyntaxError(`Unexpected character at index ${i}`);
4675
+ }
4676
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
4677
+ inQuotes = true;
4678
+ } else if (end === -1 && tokenChars[code] === 1) {
4679
+ if (start === -1)
4680
+ start = i;
4681
+ } else if (start !== -1 && (code === 32 || code === 9)) {
4682
+ if (end === -1)
4683
+ end = i;
4684
+ } else if (code === 59 || code === 44) {
4685
+ if (start === -1) {
4686
+ throw new SyntaxError(`Unexpected character at index ${i}`);
4687
+ }
4688
+ if (end === -1)
4689
+ end = i;
4690
+ let value = header.slice(start, end);
4691
+ if (mustUnescape) {
4692
+ value = value.replace(/\\/g, "");
4693
+ mustUnescape = false;
4694
+ }
4695
+ push(params, paramName, value);
4696
+ if (code === 44) {
4697
+ push(offers, extensionName, params);
4698
+ params = /* @__PURE__ */ Object.create(null);
4699
+ extensionName = void 0;
4700
+ }
4701
+ paramName = void 0;
4702
+ start = end = -1;
4703
+ } else {
4704
+ throw new SyntaxError(`Unexpected character at index ${i}`);
4705
+ }
4706
+ }
4707
+ }
4708
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
4709
+ throw new SyntaxError("Unexpected end of input");
4710
+ }
4711
+ if (end === -1)
4712
+ end = i;
4713
+ const token = header.slice(start, end);
4714
+ if (extensionName === void 0) {
4715
+ push(offers, token, params);
4716
+ } else {
4717
+ if (paramName === void 0) {
4718
+ push(params, token, true);
4719
+ } else if (mustUnescape) {
4720
+ push(params, paramName, token.replace(/\\/g, ""));
4721
+ } else {
4722
+ push(params, paramName, token);
4723
+ }
4724
+ push(offers, extensionName, params);
4725
+ }
4726
+ return offers;
4727
+ }
4728
+ function format(extensions) {
4729
+ return Object.keys(extensions).map((extension) => {
4730
+ let configurations = extensions[extension];
4731
+ if (!Array.isArray(configurations))
4732
+ configurations = [configurations];
4733
+ return configurations.map((params) => {
4734
+ return [extension].concat(
4735
+ Object.keys(params).map((k) => {
4736
+ let values = params[k];
4737
+ if (!Array.isArray(values))
4738
+ values = [values];
4739
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
4740
+ })
4741
+ ).join("; ");
4742
+ }).join(", ");
4743
+ }).join(", ");
4744
+ }
4745
+ module.exports = { format, parse };
4746
+ }
4747
+ });
4748
+
4749
+ // ../node_modules/ws/lib/websocket.js
4750
+ var require_websocket = __commonJS({
4751
+ "../node_modules/ws/lib/websocket.js"(exports, module) {
4752
+ "use strict";
4753
+ init_deno_env();
4754
+ var EventEmitter = __require2("events");
4755
+ var https = __require2("https");
4756
+ var http = __require2("http");
4757
+ var net = __require2("net");
4758
+ var tls = __require2("tls");
4759
+ var { randomBytes, createHash: createHash2 } = __require2("crypto");
4760
+ var { Duplex, Readable } = __require2("stream");
4761
+ var { URL: URL2 } = __require2("url");
4762
+ var PerMessageDeflate = require_permessage_deflate();
4763
+ var Receiver2 = require_receiver();
4764
+ var Sender2 = require_sender();
4765
+ var { isBlob } = require_validation();
4766
+ var {
4767
+ BINARY_TYPES,
4768
+ EMPTY_BUFFER,
4769
+ GUID,
4770
+ kForOnEventAttribute,
4771
+ kListener,
4772
+ kStatusCode,
4773
+ kWebSocket,
4774
+ NOOP
4775
+ } = require_constants();
4776
+ var {
4777
+ EventTarget: { addEventListener, removeEventListener }
4778
+ } = require_event_target();
4779
+ var { format, parse } = require_extension();
4780
+ var { toBuffer } = require_buffer_util();
4781
+ var closeTimeout = 30 * 1e3;
4782
+ var kAborted = Symbol("kAborted");
4783
+ var protocolVersions = [8, 13];
4784
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
4785
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
4786
+ var WebSocket2 = class _WebSocket extends EventEmitter {
4787
+ /**
4788
+ * Create a new `WebSocket`.
4789
+ *
4790
+ * @param {(String|URL)} address The URL to which to connect
4791
+ * @param {(String|String[])} [protocols] The subprotocols
4792
+ * @param {Object} [options] Connection options
4793
+ */
4794
+ constructor(address, protocols, options) {
4795
+ super();
4796
+ this._binaryType = BINARY_TYPES[0];
4797
+ this._closeCode = 1006;
4798
+ this._closeFrameReceived = false;
4799
+ this._closeFrameSent = false;
4800
+ this._closeMessage = EMPTY_BUFFER;
4801
+ this._closeTimer = null;
4802
+ this._errorEmitted = false;
4803
+ this._extensions = {};
4804
+ this._paused = false;
4805
+ this._protocol = "";
4806
+ this._readyState = _WebSocket.CONNECTING;
4807
+ this._receiver = null;
4808
+ this._sender = null;
4809
+ this._socket = null;
4810
+ if (address !== null) {
4811
+ this._bufferedAmount = 0;
4812
+ this._isServer = false;
4813
+ this._redirects = 0;
4814
+ if (protocols === void 0) {
4815
+ protocols = [];
4816
+ } else if (!Array.isArray(protocols)) {
4817
+ if (typeof protocols === "object" && protocols !== null) {
4818
+ options = protocols;
4819
+ protocols = [];
4820
+ } else {
4821
+ protocols = [protocols];
4822
+ }
4823
+ }
4824
+ initAsClient(this, address, protocols, options);
4825
+ } else {
4826
+ this._autoPong = options.autoPong;
4827
+ this._isServer = true;
4828
+ }
4829
+ }
4830
+ /**
4831
+ * For historical reasons, the custom "nodebuffer" type is used by the default
4832
+ * instead of "blob".
4833
+ *
4834
+ * @type {String}
4835
+ */
4836
+ get binaryType() {
4837
+ return this._binaryType;
4838
+ }
4839
+ set binaryType(type) {
4840
+ if (!BINARY_TYPES.includes(type))
4841
+ return;
4842
+ this._binaryType = type;
4843
+ if (this._receiver)
4844
+ this._receiver._binaryType = type;
4845
+ }
4846
+ /**
4847
+ * @type {Number}
4848
+ */
4849
+ get bufferedAmount() {
4850
+ if (!this._socket)
4851
+ return this._bufferedAmount;
4852
+ return this._socket._writableState.length + this._sender._bufferedBytes;
4853
+ }
4854
+ /**
4855
+ * @type {String}
4856
+ */
4857
+ get extensions() {
4858
+ return Object.keys(this._extensions).join();
4859
+ }
4860
+ /**
4861
+ * @type {Boolean}
4862
+ */
4863
+ get isPaused() {
4864
+ return this._paused;
4865
+ }
4866
+ /**
4867
+ * @type {Function}
4868
+ */
4869
+ /* istanbul ignore next */
4870
+ get onclose() {
4871
+ return null;
4872
+ }
4873
+ /**
4874
+ * @type {Function}
4875
+ */
4876
+ /* istanbul ignore next */
4877
+ get onerror() {
4878
+ return null;
4879
+ }
4880
+ /**
4881
+ * @type {Function}
4882
+ */
4883
+ /* istanbul ignore next */
4884
+ get onopen() {
4885
+ return null;
4886
+ }
4887
+ /**
4888
+ * @type {Function}
4889
+ */
4890
+ /* istanbul ignore next */
4891
+ get onmessage() {
4892
+ return null;
4893
+ }
4894
+ /**
4895
+ * @type {String}
4896
+ */
4897
+ get protocol() {
4898
+ return this._protocol;
4899
+ }
4900
+ /**
4901
+ * @type {Number}
4902
+ */
4903
+ get readyState() {
4904
+ return this._readyState;
4905
+ }
4906
+ /**
4907
+ * @type {String}
4908
+ */
4909
+ get url() {
4910
+ return this._url;
4911
+ }
4912
+ /**
4913
+ * Set up the socket and the internal resources.
4914
+ *
4915
+ * @param {Duplex} socket The network socket between the server and client
4916
+ * @param {Buffer} head The first packet of the upgraded stream
4917
+ * @param {Object} options Options object
4918
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
4919
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
4920
+ * multiple times in the same tick
4921
+ * @param {Function} [options.generateMask] The function used to generate the
4922
+ * masking key
4923
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
4924
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
4925
+ * not to skip UTF-8 validation for text and close messages
4926
+ * @private
4927
+ */
4928
+ setSocket(socket, head, options) {
4929
+ const receiver = new Receiver2({
4930
+ allowSynchronousEvents: options.allowSynchronousEvents,
4931
+ binaryType: this.binaryType,
4932
+ extensions: this._extensions,
4933
+ isServer: this._isServer,
4934
+ maxPayload: options.maxPayload,
4935
+ skipUTF8Validation: options.skipUTF8Validation
4936
+ });
4937
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
4938
+ this._receiver = receiver;
4939
+ this._sender = sender;
4940
+ this._socket = socket;
4941
+ receiver[kWebSocket] = this;
4942
+ sender[kWebSocket] = this;
4943
+ socket[kWebSocket] = this;
4944
+ receiver.on("conclude", receiverOnConclude);
4945
+ receiver.on("drain", receiverOnDrain);
4946
+ receiver.on("error", receiverOnError);
4947
+ receiver.on("message", receiverOnMessage);
4948
+ receiver.on("ping", receiverOnPing);
4949
+ receiver.on("pong", receiverOnPong);
4950
+ sender.onerror = senderOnError;
4951
+ if (socket.setTimeout)
4952
+ socket.setTimeout(0);
4953
+ if (socket.setNoDelay)
4954
+ socket.setNoDelay();
4955
+ if (head.length > 0)
4956
+ socket.unshift(head);
4957
+ socket.on("close", socketOnClose);
4958
+ socket.on("data", socketOnData);
4959
+ socket.on("end", socketOnEnd);
4960
+ socket.on("error", socketOnError);
4961
+ this._readyState = _WebSocket.OPEN;
4962
+ this.emit("open");
4963
+ }
4964
+ /**
4965
+ * Emit the `'close'` event.
4966
+ *
4967
+ * @private
4968
+ */
4969
+ emitClose() {
4970
+ if (!this._socket) {
4971
+ this._readyState = _WebSocket.CLOSED;
4972
+ this.emit("close", this._closeCode, this._closeMessage);
4973
+ return;
4974
+ }
4975
+ if (this._extensions[PerMessageDeflate.extensionName]) {
4976
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
4977
+ }
4978
+ this._receiver.removeAllListeners();
4979
+ this._readyState = _WebSocket.CLOSED;
4980
+ this.emit("close", this._closeCode, this._closeMessage);
4981
+ }
4982
+ /**
4983
+ * Start a closing handshake.
4984
+ *
4985
+ * +----------+ +-----------+ +----------+
4986
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
4987
+ * | +----------+ +-----------+ +----------+ |
4988
+ * +----------+ +-----------+ |
4989
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
4990
+ * +----------+ +-----------+ |
4991
+ * | | | +---+ |
4992
+ * +------------------------+-->|fin| - - - -
4993
+ * | +---+ | +---+
4994
+ * - - - - -|fin|<---------------------+
4995
+ * +---+
4996
+ *
4997
+ * @param {Number} [code] Status code explaining why the connection is closing
4998
+ * @param {(String|Buffer)} [data] The reason why the connection is
4999
+ * closing
5000
+ * @public
5001
+ */
5002
+ close(code, data) {
5003
+ if (this.readyState === _WebSocket.CLOSED)
5004
+ return;
5005
+ if (this.readyState === _WebSocket.CONNECTING) {
5006
+ const msg = "WebSocket was closed before the connection was established";
5007
+ abortHandshake(this, this._req, msg);
5008
+ return;
5009
+ }
5010
+ if (this.readyState === _WebSocket.CLOSING) {
5011
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
5012
+ this._socket.end();
5013
+ }
5014
+ return;
5015
+ }
5016
+ this._readyState = _WebSocket.CLOSING;
5017
+ this._sender.close(code, data, !this._isServer, (err) => {
5018
+ if (err)
5019
+ return;
5020
+ this._closeFrameSent = true;
5021
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
5022
+ this._socket.end();
5023
+ }
5024
+ });
5025
+ setCloseTimer(this);
5026
+ }
5027
+ /**
5028
+ * Pause the socket.
5029
+ *
5030
+ * @public
5031
+ */
5032
+ pause() {
5033
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
5034
+ return;
5035
+ }
5036
+ this._paused = true;
5037
+ this._socket.pause();
5038
+ }
5039
+ /**
5040
+ * Send a ping.
5041
+ *
5042
+ * @param {*} [data] The data to send
5043
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
5044
+ * @param {Function} [cb] Callback which is executed when the ping is sent
5045
+ * @public
5046
+ */
5047
+ ping(data, mask, cb) {
5048
+ if (this.readyState === _WebSocket.CONNECTING) {
5049
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
5050
+ }
5051
+ if (typeof data === "function") {
5052
+ cb = data;
5053
+ data = mask = void 0;
5054
+ } else if (typeof mask === "function") {
5055
+ cb = mask;
5056
+ mask = void 0;
5057
+ }
5058
+ if (typeof data === "number")
5059
+ data = data.toString();
5060
+ if (this.readyState !== _WebSocket.OPEN) {
5061
+ sendAfterClose(this, data, cb);
5062
+ return;
5063
+ }
5064
+ if (mask === void 0)
5065
+ mask = !this._isServer;
5066
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
5067
+ }
5068
+ /**
5069
+ * Send a pong.
5070
+ *
5071
+ * @param {*} [data] The data to send
5072
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
5073
+ * @param {Function} [cb] Callback which is executed when the pong is sent
5074
+ * @public
5075
+ */
5076
+ pong(data, mask, cb) {
5077
+ if (this.readyState === _WebSocket.CONNECTING) {
5078
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
5079
+ }
5080
+ if (typeof data === "function") {
5081
+ cb = data;
5082
+ data = mask = void 0;
5083
+ } else if (typeof mask === "function") {
5084
+ cb = mask;
5085
+ mask = void 0;
5086
+ }
5087
+ if (typeof data === "number")
5088
+ data = data.toString();
5089
+ if (this.readyState !== _WebSocket.OPEN) {
5090
+ sendAfterClose(this, data, cb);
5091
+ return;
5092
+ }
5093
+ if (mask === void 0)
5094
+ mask = !this._isServer;
5095
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
5096
+ }
5097
+ /**
5098
+ * Resume the socket.
5099
+ *
5100
+ * @public
5101
+ */
5102
+ resume() {
5103
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
5104
+ return;
5105
+ }
5106
+ this._paused = false;
5107
+ if (!this._receiver._writableState.needDrain)
5108
+ this._socket.resume();
5109
+ }
5110
+ /**
5111
+ * Send a data message.
5112
+ *
5113
+ * @param {*} data The message to send
5114
+ * @param {Object} [options] Options object
5115
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
5116
+ * text
5117
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
5118
+ * `data`
5119
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
5120
+ * last one
5121
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
5122
+ * @param {Function} [cb] Callback which is executed when data is written out
5123
+ * @public
5124
+ */
5125
+ send(data, options, cb) {
5126
+ if (this.readyState === _WebSocket.CONNECTING) {
5127
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
5128
+ }
5129
+ if (typeof options === "function") {
5130
+ cb = options;
5131
+ options = {};
5132
+ }
5133
+ if (typeof data === "number")
5134
+ data = data.toString();
5135
+ if (this.readyState !== _WebSocket.OPEN) {
5136
+ sendAfterClose(this, data, cb);
5137
+ return;
5138
+ }
5139
+ const opts = {
5140
+ binary: typeof data !== "string",
5141
+ mask: !this._isServer,
5142
+ compress: true,
5143
+ fin: true,
5144
+ ...options
5145
+ };
5146
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
5147
+ opts.compress = false;
5148
+ }
5149
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
5150
+ }
5151
+ /**
5152
+ * Forcibly close the connection.
5153
+ *
5154
+ * @public
5155
+ */
5156
+ terminate() {
5157
+ if (this.readyState === _WebSocket.CLOSED)
5158
+ return;
5159
+ if (this.readyState === _WebSocket.CONNECTING) {
5160
+ const msg = "WebSocket was closed before the connection was established";
5161
+ abortHandshake(this, this._req, msg);
5162
+ return;
5163
+ }
5164
+ if (this._socket) {
5165
+ this._readyState = _WebSocket.CLOSING;
5166
+ this._socket.destroy();
5167
+ }
5168
+ }
5169
+ };
5170
+ Object.defineProperty(WebSocket2, "CONNECTING", {
5171
+ enumerable: true,
5172
+ value: readyStates.indexOf("CONNECTING")
5173
+ });
5174
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
5175
+ enumerable: true,
5176
+ value: readyStates.indexOf("CONNECTING")
5177
+ });
5178
+ Object.defineProperty(WebSocket2, "OPEN", {
5179
+ enumerable: true,
5180
+ value: readyStates.indexOf("OPEN")
5181
+ });
5182
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
5183
+ enumerable: true,
5184
+ value: readyStates.indexOf("OPEN")
5185
+ });
5186
+ Object.defineProperty(WebSocket2, "CLOSING", {
5187
+ enumerable: true,
5188
+ value: readyStates.indexOf("CLOSING")
5189
+ });
5190
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
5191
+ enumerable: true,
5192
+ value: readyStates.indexOf("CLOSING")
5193
+ });
5194
+ Object.defineProperty(WebSocket2, "CLOSED", {
5195
+ enumerable: true,
5196
+ value: readyStates.indexOf("CLOSED")
5197
+ });
5198
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
5199
+ enumerable: true,
5200
+ value: readyStates.indexOf("CLOSED")
5201
+ });
5202
+ [
5203
+ "binaryType",
5204
+ "bufferedAmount",
5205
+ "extensions",
5206
+ "isPaused",
5207
+ "protocol",
5208
+ "readyState",
5209
+ "url"
5210
+ ].forEach((property) => {
5211
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
5212
+ });
5213
+ ["open", "error", "close", "message"].forEach((method) => {
5214
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
5215
+ enumerable: true,
5216
+ get() {
5217
+ for (const listener of this.listeners(method)) {
5218
+ if (listener[kForOnEventAttribute])
5219
+ return listener[kListener];
5220
+ }
5221
+ return null;
5222
+ },
5223
+ set(handler) {
5224
+ for (const listener of this.listeners(method)) {
5225
+ if (listener[kForOnEventAttribute]) {
5226
+ this.removeListener(method, listener);
5227
+ break;
5228
+ }
5229
+ }
5230
+ if (typeof handler !== "function")
5231
+ return;
5232
+ this.addEventListener(method, handler, {
5233
+ [kForOnEventAttribute]: true
5234
+ });
5235
+ }
5236
+ });
5237
+ });
5238
+ WebSocket2.prototype.addEventListener = addEventListener;
5239
+ WebSocket2.prototype.removeEventListener = removeEventListener;
5240
+ module.exports = WebSocket2;
5241
+ function initAsClient(websocket, address, protocols, options) {
5242
+ const opts = {
5243
+ allowSynchronousEvents: true,
5244
+ autoPong: true,
5245
+ protocolVersion: protocolVersions[1],
5246
+ maxPayload: 100 * 1024 * 1024,
5247
+ skipUTF8Validation: false,
5248
+ perMessageDeflate: true,
5249
+ followRedirects: false,
5250
+ maxRedirects: 10,
5251
+ ...options,
5252
+ socketPath: void 0,
5253
+ hostname: void 0,
5254
+ protocol: void 0,
5255
+ timeout: void 0,
5256
+ method: "GET",
5257
+ host: void 0,
5258
+ path: void 0,
5259
+ port: void 0
5260
+ };
5261
+ websocket._autoPong = opts.autoPong;
5262
+ if (!protocolVersions.includes(opts.protocolVersion)) {
5263
+ throw new RangeError(
5264
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
5265
+ );
5266
+ }
5267
+ let parsedUrl;
5268
+ if (address instanceof URL2) {
5269
+ parsedUrl = address;
5270
+ } else {
5271
+ try {
5272
+ parsedUrl = new URL2(address);
5273
+ } catch (e) {
5274
+ throw new SyntaxError(`Invalid URL: ${address}`);
5275
+ }
5276
+ }
5277
+ if (parsedUrl.protocol === "http:") {
5278
+ parsedUrl.protocol = "ws:";
5279
+ } else if (parsedUrl.protocol === "https:") {
5280
+ parsedUrl.protocol = "wss:";
5281
+ }
5282
+ websocket._url = parsedUrl.href;
5283
+ const isSecure = parsedUrl.protocol === "wss:";
5284
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
5285
+ let invalidUrlMessage;
5286
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
5287
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
5288
+ } else if (isIpcUrl && !parsedUrl.pathname) {
5289
+ invalidUrlMessage = "The URL's pathname is empty";
5290
+ } else if (parsedUrl.hash) {
5291
+ invalidUrlMessage = "The URL contains a fragment identifier";
5292
+ }
5293
+ if (invalidUrlMessage) {
5294
+ const err = new SyntaxError(invalidUrlMessage);
5295
+ if (websocket._redirects === 0) {
5296
+ throw err;
5297
+ } else {
5298
+ emitErrorAndClose(websocket, err);
5299
+ return;
5300
+ }
5301
+ }
5302
+ const defaultPort = isSecure ? 443 : 80;
5303
+ const key = randomBytes(16).toString("base64");
5304
+ const request = isSecure ? https.request : http.request;
5305
+ const protocolSet = /* @__PURE__ */ new Set();
5306
+ let perMessageDeflate;
5307
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
5308
+ opts.defaultPort = opts.defaultPort || defaultPort;
5309
+ opts.port = parsedUrl.port || defaultPort;
5310
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
5311
+ opts.headers = {
5312
+ ...opts.headers,
5313
+ "Sec-WebSocket-Version": opts.protocolVersion,
5314
+ "Sec-WebSocket-Key": key,
5315
+ Connection: "Upgrade",
5316
+ Upgrade: "websocket"
5317
+ };
5318
+ opts.path = parsedUrl.pathname + parsedUrl.search;
5319
+ opts.timeout = opts.handshakeTimeout;
5320
+ if (opts.perMessageDeflate) {
5321
+ perMessageDeflate = new PerMessageDeflate(
5322
+ opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
5323
+ false,
5324
+ opts.maxPayload
5325
+ );
5326
+ opts.headers["Sec-WebSocket-Extensions"] = format({
5327
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
5328
+ });
5329
+ }
5330
+ if (protocols.length) {
5331
+ for (const protocol of protocols) {
5332
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
5333
+ throw new SyntaxError(
5334
+ "An invalid or duplicated subprotocol was specified"
5335
+ );
5336
+ }
5337
+ protocolSet.add(protocol);
5338
+ }
5339
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
5340
+ }
5341
+ if (opts.origin) {
5342
+ if (opts.protocolVersion < 13) {
5343
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
5344
+ } else {
5345
+ opts.headers.Origin = opts.origin;
5346
+ }
5347
+ }
5348
+ if (parsedUrl.username || parsedUrl.password) {
5349
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
5350
+ }
5351
+ if (isIpcUrl) {
5352
+ const parts = opts.path.split(":");
5353
+ opts.socketPath = parts[0];
5354
+ opts.path = parts[1];
5355
+ }
5356
+ let req;
5357
+ if (opts.followRedirects) {
5358
+ if (websocket._redirects === 0) {
5359
+ websocket._originalIpc = isIpcUrl;
5360
+ websocket._originalSecure = isSecure;
5361
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
5362
+ const headers = options && options.headers;
5363
+ options = { ...options, headers: {} };
5364
+ if (headers) {
5365
+ for (const [key2, value] of Object.entries(headers)) {
5366
+ options.headers[key2.toLowerCase()] = value;
5367
+ }
5368
+ }
5369
+ } else if (websocket.listenerCount("redirect") === 0) {
5370
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
5371
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
5372
+ delete opts.headers.authorization;
5373
+ delete opts.headers.cookie;
5374
+ if (!isSameHost)
5375
+ delete opts.headers.host;
5376
+ opts.auth = void 0;
5377
+ }
5378
+ }
5379
+ if (opts.auth && !options.headers.authorization) {
5380
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
5381
+ }
5382
+ req = websocket._req = request(opts);
5383
+ if (websocket._redirects) {
5384
+ websocket.emit("redirect", websocket.url, req);
5385
+ }
5386
+ } else {
5387
+ req = websocket._req = request(opts);
5388
+ }
5389
+ if (opts.timeout) {
5390
+ req.on("timeout", () => {
5391
+ abortHandshake(websocket, req, "Opening handshake has timed out");
5392
+ });
5393
+ }
5394
+ req.on("error", (err) => {
5395
+ if (req === null || req[kAborted])
5396
+ return;
5397
+ req = websocket._req = null;
5398
+ emitErrorAndClose(websocket, err);
5399
+ });
5400
+ req.on("response", (res) => {
5401
+ const location = res.headers.location;
5402
+ const statusCode = res.statusCode;
5403
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
5404
+ if (++websocket._redirects > opts.maxRedirects) {
5405
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
5406
+ return;
5407
+ }
5408
+ req.abort();
5409
+ let addr;
5410
+ try {
5411
+ addr = new URL2(location, address);
5412
+ } catch (e) {
5413
+ const err = new SyntaxError(`Invalid URL: ${location}`);
5414
+ emitErrorAndClose(websocket, err);
5415
+ return;
5416
+ }
5417
+ initAsClient(websocket, addr, protocols, options);
5418
+ } else if (!websocket.emit("unexpected-response", req, res)) {
5419
+ abortHandshake(
5420
+ websocket,
5421
+ req,
5422
+ `Unexpected server response: ${res.statusCode}`
5423
+ );
5424
+ }
5425
+ });
5426
+ req.on("upgrade", (res, socket, head) => {
5427
+ websocket.emit("upgrade", res);
5428
+ if (websocket.readyState !== WebSocket2.CONNECTING)
5429
+ return;
5430
+ req = websocket._req = null;
5431
+ const upgrade = res.headers.upgrade;
5432
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
5433
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
5434
+ return;
5435
+ }
5436
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
5437
+ if (res.headers["sec-websocket-accept"] !== digest) {
5438
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
5439
+ return;
5440
+ }
5441
+ const serverProt = res.headers["sec-websocket-protocol"];
5442
+ let protError;
5443
+ if (serverProt !== void 0) {
5444
+ if (!protocolSet.size) {
5445
+ protError = "Server sent a subprotocol but none was requested";
5446
+ } else if (!protocolSet.has(serverProt)) {
5447
+ protError = "Server sent an invalid subprotocol";
5448
+ }
5449
+ } else if (protocolSet.size) {
5450
+ protError = "Server sent no subprotocol";
5451
+ }
5452
+ if (protError) {
5453
+ abortHandshake(websocket, socket, protError);
5454
+ return;
5455
+ }
5456
+ if (serverProt)
5457
+ websocket._protocol = serverProt;
5458
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
5459
+ if (secWebSocketExtensions !== void 0) {
5460
+ if (!perMessageDeflate) {
5461
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
5462
+ abortHandshake(websocket, socket, message);
5463
+ return;
5464
+ }
5465
+ let extensions;
5466
+ try {
5467
+ extensions = parse(secWebSocketExtensions);
5468
+ } catch (err) {
5469
+ const message = "Invalid Sec-WebSocket-Extensions header";
5470
+ abortHandshake(websocket, socket, message);
5471
+ return;
5472
+ }
5473
+ const extensionNames = Object.keys(extensions);
5474
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
5475
+ const message = "Server indicated an extension that was not requested";
5476
+ abortHandshake(websocket, socket, message);
5477
+ return;
5478
+ }
5479
+ try {
5480
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
5481
+ } catch (err) {
5482
+ const message = "Invalid Sec-WebSocket-Extensions header";
5483
+ abortHandshake(websocket, socket, message);
5484
+ return;
5485
+ }
5486
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
5487
+ }
5488
+ websocket.setSocket(socket, head, {
5489
+ allowSynchronousEvents: opts.allowSynchronousEvents,
5490
+ generateMask: opts.generateMask,
5491
+ maxPayload: opts.maxPayload,
5492
+ skipUTF8Validation: opts.skipUTF8Validation
5493
+ });
5494
+ });
5495
+ if (opts.finishRequest) {
5496
+ opts.finishRequest(req, websocket);
5497
+ } else {
5498
+ req.end();
5499
+ }
5500
+ }
5501
+ function emitErrorAndClose(websocket, err) {
5502
+ websocket._readyState = WebSocket2.CLOSING;
5503
+ websocket._errorEmitted = true;
5504
+ websocket.emit("error", err);
5505
+ websocket.emitClose();
5506
+ }
5507
+ function netConnect(options) {
5508
+ options.path = options.socketPath;
5509
+ return net.connect(options);
5510
+ }
5511
+ function tlsConnect(options) {
5512
+ options.path = void 0;
5513
+ if (!options.servername && options.servername !== "") {
5514
+ options.servername = net.isIP(options.host) ? "" : options.host;
5515
+ }
5516
+ return tls.connect(options);
5517
+ }
5518
+ function abortHandshake(websocket, stream, message) {
5519
+ websocket._readyState = WebSocket2.CLOSING;
5520
+ const err = new Error(message);
5521
+ Error.captureStackTrace(err, abortHandshake);
5522
+ if (stream.setHeader) {
5523
+ stream[kAborted] = true;
5524
+ stream.abort();
5525
+ if (stream.socket && !stream.socket.destroyed) {
5526
+ stream.socket.destroy();
5527
+ }
5528
+ process.nextTick(emitErrorAndClose, websocket, err);
5529
+ } else {
5530
+ stream.destroy(err);
5531
+ stream.once("error", websocket.emit.bind(websocket, "error"));
5532
+ stream.once("close", websocket.emitClose.bind(websocket));
5533
+ }
5534
+ }
5535
+ function sendAfterClose(websocket, data, cb) {
5536
+ if (data) {
5537
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
5538
+ if (websocket._socket)
5539
+ websocket._sender._bufferedBytes += length;
5540
+ else
5541
+ websocket._bufferedAmount += length;
5542
+ }
5543
+ if (cb) {
5544
+ const err = new Error(
5545
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
5546
+ );
5547
+ process.nextTick(cb, err);
5548
+ }
5549
+ }
5550
+ function receiverOnConclude(code, reason) {
5551
+ const websocket = this[kWebSocket];
5552
+ websocket._closeFrameReceived = true;
5553
+ websocket._closeMessage = reason;
5554
+ websocket._closeCode = code;
5555
+ if (websocket._socket[kWebSocket] === void 0)
5556
+ return;
5557
+ websocket._socket.removeListener("data", socketOnData);
5558
+ process.nextTick(resume, websocket._socket);
5559
+ if (code === 1005)
5560
+ websocket.close();
5561
+ else
5562
+ websocket.close(code, reason);
5563
+ }
5564
+ function receiverOnDrain() {
5565
+ const websocket = this[kWebSocket];
5566
+ if (!websocket.isPaused)
5567
+ websocket._socket.resume();
5568
+ }
5569
+ function receiverOnError(err) {
5570
+ const websocket = this[kWebSocket];
5571
+ if (websocket._socket[kWebSocket] !== void 0) {
5572
+ websocket._socket.removeListener("data", socketOnData);
5573
+ process.nextTick(resume, websocket._socket);
5574
+ websocket.close(err[kStatusCode]);
5575
+ }
5576
+ if (!websocket._errorEmitted) {
5577
+ websocket._errorEmitted = true;
5578
+ websocket.emit("error", err);
5579
+ }
5580
+ }
5581
+ function receiverOnFinish() {
5582
+ this[kWebSocket].emitClose();
5583
+ }
5584
+ function receiverOnMessage(data, isBinary) {
5585
+ this[kWebSocket].emit("message", data, isBinary);
5586
+ }
5587
+ function receiverOnPing(data) {
5588
+ const websocket = this[kWebSocket];
5589
+ if (websocket._autoPong)
5590
+ websocket.pong(data, !this._isServer, NOOP);
5591
+ websocket.emit("ping", data);
5592
+ }
5593
+ function receiverOnPong(data) {
5594
+ this[kWebSocket].emit("pong", data);
5595
+ }
5596
+ function resume(stream) {
5597
+ stream.resume();
5598
+ }
5599
+ function senderOnError(err) {
5600
+ const websocket = this[kWebSocket];
5601
+ if (websocket.readyState === WebSocket2.CLOSED)
5602
+ return;
5603
+ if (websocket.readyState === WebSocket2.OPEN) {
5604
+ websocket._readyState = WebSocket2.CLOSING;
5605
+ setCloseTimer(websocket);
5606
+ }
5607
+ this._socket.end();
5608
+ if (!websocket._errorEmitted) {
5609
+ websocket._errorEmitted = true;
5610
+ websocket.emit("error", err);
5611
+ }
5612
+ }
5613
+ function setCloseTimer(websocket) {
5614
+ websocket._closeTimer = setTimeout(
5615
+ websocket._socket.destroy.bind(websocket._socket),
5616
+ closeTimeout
5617
+ );
5618
+ }
5619
+ function socketOnClose() {
5620
+ const websocket = this[kWebSocket];
5621
+ this.removeListener("close", socketOnClose);
5622
+ this.removeListener("data", socketOnData);
5623
+ this.removeListener("end", socketOnEnd);
5624
+ websocket._readyState = WebSocket2.CLOSING;
5625
+ let chunk;
5626
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
5627
+ websocket._receiver.write(chunk);
5628
+ }
5629
+ websocket._receiver.end();
5630
+ this[kWebSocket] = void 0;
5631
+ clearTimeout(websocket._closeTimer);
5632
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
5633
+ websocket.emitClose();
5634
+ } else {
5635
+ websocket._receiver.on("error", receiverOnFinish);
5636
+ websocket._receiver.on("finish", receiverOnFinish);
5637
+ }
5638
+ }
5639
+ function socketOnData(chunk) {
5640
+ if (!this[kWebSocket]._receiver.write(chunk)) {
5641
+ this.pause();
5642
+ }
5643
+ }
5644
+ function socketOnEnd() {
5645
+ const websocket = this[kWebSocket];
5646
+ websocket._readyState = WebSocket2.CLOSING;
5647
+ websocket._receiver.end();
5648
+ this.end();
5649
+ }
5650
+ function socketOnError() {
5651
+ const websocket = this[kWebSocket];
5652
+ this.removeListener("error", socketOnError);
5653
+ this.on("error", NOOP);
5654
+ if (websocket) {
5655
+ websocket._readyState = WebSocket2.CLOSING;
5656
+ this.destroy();
5657
+ }
5658
+ }
5659
+ }
5660
+ });
5661
+
5662
+ // ../node_modules/ws/lib/stream.js
5663
+ var require_stream = __commonJS({
5664
+ "../node_modules/ws/lib/stream.js"(exports, module) {
5665
+ "use strict";
5666
+ init_deno_env();
5667
+ var WebSocket2 = require_websocket();
5668
+ var { Duplex } = __require2("stream");
5669
+ function emitClose(stream) {
5670
+ stream.emit("close");
5671
+ }
5672
+ function duplexOnEnd() {
5673
+ if (!this.destroyed && this._writableState.finished) {
5674
+ this.destroy();
5675
+ }
5676
+ }
5677
+ function duplexOnError(err) {
5678
+ this.removeListener("error", duplexOnError);
5679
+ this.destroy();
5680
+ if (this.listenerCount("error") === 0) {
5681
+ this.emit("error", err);
5682
+ }
5683
+ }
5684
+ function createWebSocketStream2(ws, options) {
5685
+ let terminateOnDestroy = true;
5686
+ const duplex = new Duplex({
5687
+ ...options,
5688
+ autoDestroy: false,
5689
+ emitClose: false,
5690
+ objectMode: false,
5691
+ writableObjectMode: false
5692
+ });
5693
+ ws.on("message", function message(msg, isBinary) {
5694
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
5695
+ if (!duplex.push(data))
5696
+ ws.pause();
5697
+ });
5698
+ ws.once("error", function error(err) {
5699
+ if (duplex.destroyed)
5700
+ return;
5701
+ terminateOnDestroy = false;
5702
+ duplex.destroy(err);
5703
+ });
5704
+ ws.once("close", function close() {
5705
+ if (duplex.destroyed)
5706
+ return;
5707
+ duplex.push(null);
5708
+ });
5709
+ duplex._destroy = function(err, callback) {
5710
+ if (ws.readyState === ws.CLOSED) {
5711
+ callback(err);
5712
+ process.nextTick(emitClose, duplex);
5713
+ return;
5714
+ }
5715
+ let called = false;
5716
+ ws.once("error", function error(err2) {
5717
+ called = true;
5718
+ callback(err2);
5719
+ });
5720
+ ws.once("close", function close() {
5721
+ if (!called)
5722
+ callback(err);
5723
+ process.nextTick(emitClose, duplex);
5724
+ });
5725
+ if (terminateOnDestroy)
5726
+ ws.terminate();
5727
+ };
5728
+ duplex._final = function(callback) {
5729
+ if (ws.readyState === ws.CONNECTING) {
5730
+ ws.once("open", function open() {
5731
+ duplex._final(callback);
5732
+ });
5733
+ return;
5734
+ }
5735
+ if (ws._socket === null)
5736
+ return;
5737
+ if (ws._socket._writableState.finished) {
5738
+ callback();
5739
+ if (duplex._readableState.endEmitted)
5740
+ duplex.destroy();
5741
+ } else {
5742
+ ws._socket.once("finish", function finish() {
5743
+ callback();
5744
+ });
5745
+ ws.close();
5746
+ }
5747
+ };
5748
+ duplex._read = function() {
5749
+ if (ws.isPaused)
5750
+ ws.resume();
5751
+ };
5752
+ duplex._write = function(chunk, encoding, callback) {
5753
+ if (ws.readyState === ws.CONNECTING) {
5754
+ ws.once("open", function open() {
5755
+ duplex._write(chunk, encoding, callback);
5756
+ });
5757
+ return;
5758
+ }
5759
+ ws.send(chunk, callback);
5760
+ };
5761
+ duplex.on("end", duplexOnEnd);
5762
+ duplex.on("error", duplexOnError);
5763
+ return duplex;
5764
+ }
5765
+ module.exports = createWebSocketStream2;
2280
5766
  }
2281
5767
  });
2282
5768
 
2283
- // src/platform/adapters/node/filesystem-adapter.ts
2284
- var NodeFileSystemAdapter;
2285
- var init_filesystem_adapter = __esm({
2286
- "src/platform/adapters/node/filesystem-adapter.ts"() {
5769
+ // ../node_modules/ws/lib/subprotocol.js
5770
+ var require_subprotocol = __commonJS({
5771
+ "../node_modules/ws/lib/subprotocol.js"(exports, module) {
5772
+ "use strict";
2287
5773
  init_deno_env();
2288
- init_shared_watcher();
2289
- init_utils();
2290
- NodeFileSystemAdapter = class {
2291
- async readFile(path) {
2292
- const fs = await import("node:fs/promises");
2293
- return await fs.readFile(path, "utf-8");
5774
+ var { tokenChars } = require_validation();
5775
+ function parse(header) {
5776
+ const protocols = /* @__PURE__ */ new Set();
5777
+ let start = -1;
5778
+ let end = -1;
5779
+ let i = 0;
5780
+ for (i; i < header.length; i++) {
5781
+ const code = header.charCodeAt(i);
5782
+ if (end === -1 && tokenChars[code] === 1) {
5783
+ if (start === -1)
5784
+ start = i;
5785
+ } else if (i !== 0 && (code === 32 || code === 9)) {
5786
+ if (end === -1 && start !== -1)
5787
+ end = i;
5788
+ } else if (code === 44) {
5789
+ if (start === -1) {
5790
+ throw new SyntaxError(`Unexpected character at index ${i}`);
5791
+ }
5792
+ if (end === -1)
5793
+ end = i;
5794
+ const protocol2 = header.slice(start, end);
5795
+ if (protocols.has(protocol2)) {
5796
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
5797
+ }
5798
+ protocols.add(protocol2);
5799
+ start = end = -1;
5800
+ } else {
5801
+ throw new SyntaxError(`Unexpected character at index ${i}`);
5802
+ }
2294
5803
  }
2295
- async readFileBytes(path) {
2296
- const fs = await import("node:fs/promises");
2297
- const buffer = await fs.readFile(path);
2298
- return buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
5804
+ if (start === -1 || end !== -1) {
5805
+ throw new SyntaxError("Unexpected end of input");
2299
5806
  }
2300
- async writeFile(path, content) {
2301
- const fs = await import("node:fs/promises");
2302
- await fs.writeFile(path, content, "utf-8");
5807
+ const protocol = header.slice(start, i);
5808
+ if (protocols.has(protocol)) {
5809
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
2303
5810
  }
2304
- async exists(path) {
2305
- const fs = await import("node:fs/promises");
2306
- try {
2307
- await fs.access(path);
2308
- return true;
2309
- } catch (error) {
2310
- serverLogger.debug(`File access check failed for ${path}:`, error);
2311
- return false;
5811
+ protocols.add(protocol);
5812
+ return protocols;
5813
+ }
5814
+ module.exports = { parse };
5815
+ }
5816
+ });
5817
+
5818
+ // ../node_modules/ws/lib/websocket-server.js
5819
+ var require_websocket_server = __commonJS({
5820
+ "../node_modules/ws/lib/websocket-server.js"(exports, module) {
5821
+ "use strict";
5822
+ init_deno_env();
5823
+ var EventEmitter = __require2("events");
5824
+ var http = __require2("http");
5825
+ var { Duplex } = __require2("stream");
5826
+ var { createHash: createHash2 } = __require2("crypto");
5827
+ var extension = require_extension();
5828
+ var PerMessageDeflate = require_permessage_deflate();
5829
+ var subprotocol = require_subprotocol();
5830
+ var WebSocket2 = require_websocket();
5831
+ var { GUID, kWebSocket } = require_constants();
5832
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
5833
+ var RUNNING = 0;
5834
+ var CLOSING = 1;
5835
+ var CLOSED = 2;
5836
+ var WebSocketServer2 = class extends EventEmitter {
5837
+ /**
5838
+ * Create a `WebSocketServer` instance.
5839
+ *
5840
+ * @param {Object} options Configuration options
5841
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
5842
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
5843
+ * multiple times in the same tick
5844
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
5845
+ * automatically send a pong in response to a ping
5846
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
5847
+ * pending connections
5848
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
5849
+ * track clients
5850
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
5851
+ * @param {String} [options.host] The hostname where to bind the server
5852
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
5853
+ * size
5854
+ * @param {Boolean} [options.noServer=false] Enable no server mode
5855
+ * @param {String} [options.path] Accept only connections matching this path
5856
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
5857
+ * permessage-deflate
5858
+ * @param {Number} [options.port] The port where to bind the server
5859
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
5860
+ * server to use
5861
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
5862
+ * not to skip UTF-8 validation for text and close messages
5863
+ * @param {Function} [options.verifyClient] A hook to reject connections
5864
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
5865
+ * class to use. It must be the `WebSocket` class or class that extends it
5866
+ * @param {Function} [callback] A listener for the `listening` event
5867
+ */
5868
+ constructor(options, callback) {
5869
+ super();
5870
+ options = {
5871
+ allowSynchronousEvents: true,
5872
+ autoPong: true,
5873
+ maxPayload: 100 * 1024 * 1024,
5874
+ skipUTF8Validation: false,
5875
+ perMessageDeflate: false,
5876
+ handleProtocols: null,
5877
+ clientTracking: true,
5878
+ verifyClient: null,
5879
+ noServer: false,
5880
+ backlog: null,
5881
+ // use default (511 as implemented in net.js)
5882
+ server: null,
5883
+ host: null,
5884
+ path: null,
5885
+ port: null,
5886
+ WebSocket: WebSocket2,
5887
+ ...options
5888
+ };
5889
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
5890
+ throw new TypeError(
5891
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
5892
+ );
2312
5893
  }
2313
- }
2314
- async *readDir(path) {
2315
- const fs = await import("node:fs/promises");
2316
- const entries = await fs.readdir(path, { withFileTypes: true });
2317
- for (const entry of entries) {
2318
- yield {
2319
- name: entry.name,
2320
- isFile: entry.isFile(),
2321
- isDirectory: entry.isDirectory(),
2322
- isSymlink: entry.isSymbolicLink()
2323
- };
5894
+ if (options.port != null) {
5895
+ this._server = http.createServer((req, res) => {
5896
+ const body = http.STATUS_CODES[426];
5897
+ res.writeHead(426, {
5898
+ "Content-Length": body.length,
5899
+ "Content-Type": "text/plain"
5900
+ });
5901
+ res.end(body);
5902
+ });
5903
+ this._server.listen(
5904
+ options.port,
5905
+ options.host,
5906
+ options.backlog,
5907
+ callback
5908
+ );
5909
+ } else if (options.server) {
5910
+ this._server = options.server;
5911
+ }
5912
+ if (this._server) {
5913
+ const emitConnection = this.emit.bind(this, "connection");
5914
+ this._removeListeners = addListeners(this._server, {
5915
+ listening: this.emit.bind(this, "listening"),
5916
+ error: this.emit.bind(this, "error"),
5917
+ upgrade: (req, socket, head) => {
5918
+ this.handleUpgrade(req, socket, head, emitConnection);
5919
+ }
5920
+ });
2324
5921
  }
5922
+ if (options.perMessageDeflate === true)
5923
+ options.perMessageDeflate = {};
5924
+ if (options.clientTracking) {
5925
+ this.clients = /* @__PURE__ */ new Set();
5926
+ this._shouldEmitClose = false;
5927
+ }
5928
+ this.options = options;
5929
+ this._state = RUNNING;
2325
5930
  }
2326
- async stat(path) {
2327
- const fs = await import("node:fs/promises");
2328
- const stats = await fs.stat(path);
2329
- return {
2330
- size: stats.size,
2331
- isFile: stats.isFile(),
2332
- isDirectory: stats.isDirectory(),
2333
- isSymlink: stats.isSymbolicLink(),
2334
- mtime: stats.mtime
2335
- };
5931
+ /**
5932
+ * Returns the bound address, the address family name, and port of the server
5933
+ * as reported by the operating system if listening on an IP socket.
5934
+ * If the server is listening on a pipe or UNIX domain socket, the name is
5935
+ * returned as a string.
5936
+ *
5937
+ * @return {(Object|String|null)} The address of the server
5938
+ * @public
5939
+ */
5940
+ address() {
5941
+ if (this.options.noServer) {
5942
+ throw new Error('The server is operating in "noServer" mode');
5943
+ }
5944
+ if (!this._server)
5945
+ return null;
5946
+ return this._server.address();
2336
5947
  }
2337
- async mkdir(path, options) {
2338
- const fs = await import("node:fs/promises");
2339
- await fs.mkdir(path, options);
5948
+ /**
5949
+ * Stop the server from accepting new connections and emit the `'close'` event
5950
+ * when all existing connections are closed.
5951
+ *
5952
+ * @param {Function} [cb] A one-time listener for the `'close'` event
5953
+ * @public
5954
+ */
5955
+ close(cb) {
5956
+ if (this._state === CLOSED) {
5957
+ if (cb) {
5958
+ this.once("close", () => {
5959
+ cb(new Error("The server is not running"));
5960
+ });
5961
+ }
5962
+ process.nextTick(emitClose, this);
5963
+ return;
5964
+ }
5965
+ if (cb)
5966
+ this.once("close", cb);
5967
+ if (this._state === CLOSING)
5968
+ return;
5969
+ this._state = CLOSING;
5970
+ if (this.options.noServer || this.options.server) {
5971
+ if (this._server) {
5972
+ this._removeListeners();
5973
+ this._removeListeners = this._server = null;
5974
+ }
5975
+ if (this.clients) {
5976
+ if (!this.clients.size) {
5977
+ process.nextTick(emitClose, this);
5978
+ } else {
5979
+ this._shouldEmitClose = true;
5980
+ }
5981
+ } else {
5982
+ process.nextTick(emitClose, this);
5983
+ }
5984
+ } else {
5985
+ const server = this._server;
5986
+ this._removeListeners();
5987
+ this._removeListeners = this._server = null;
5988
+ server.close(() => {
5989
+ emitClose(this);
5990
+ });
5991
+ }
2340
5992
  }
2341
- async remove(path, options) {
2342
- const fs = await import("node:fs/promises");
2343
- await fs.rm(path, { recursive: options?.recursive, force: true });
5993
+ /**
5994
+ * See if a given request should be handled by this server instance.
5995
+ *
5996
+ * @param {http.IncomingMessage} req Request object to inspect
5997
+ * @return {Boolean} `true` if the request is valid, else `false`
5998
+ * @public
5999
+ */
6000
+ shouldHandle(req) {
6001
+ if (this.options.path) {
6002
+ const index = req.url.indexOf("?");
6003
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
6004
+ if (pathname !== this.options.path)
6005
+ return false;
6006
+ }
6007
+ return true;
2344
6008
  }
2345
- async makeTempDir(prefix) {
2346
- const { mkdtemp } = await import("node:fs/promises");
2347
- const { join: join5 } = await import("node:path");
2348
- const { tmpdir } = await import("node:os");
2349
- return await mkdtemp(join5(tmpdir(), prefix));
6009
+ /**
6010
+ * Handle a HTTP Upgrade request.
6011
+ *
6012
+ * @param {http.IncomingMessage} req The request object
6013
+ * @param {Duplex} socket The network socket between the server and client
6014
+ * @param {Buffer} head The first packet of the upgraded stream
6015
+ * @param {Function} cb Callback
6016
+ * @public
6017
+ */
6018
+ handleUpgrade(req, socket, head, cb) {
6019
+ socket.on("error", socketOnError);
6020
+ const key = req.headers["sec-websocket-key"];
6021
+ const upgrade = req.headers.upgrade;
6022
+ const version = +req.headers["sec-websocket-version"];
6023
+ if (req.method !== "GET") {
6024
+ const message = "Invalid HTTP method";
6025
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
6026
+ return;
6027
+ }
6028
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
6029
+ const message = "Invalid Upgrade header";
6030
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
6031
+ return;
6032
+ }
6033
+ if (key === void 0 || !keyRegex.test(key)) {
6034
+ const message = "Missing or invalid Sec-WebSocket-Key header";
6035
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
6036
+ return;
6037
+ }
6038
+ if (version !== 13 && version !== 8) {
6039
+ const message = "Missing or invalid Sec-WebSocket-Version header";
6040
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
6041
+ "Sec-WebSocket-Version": "13, 8"
6042
+ });
6043
+ return;
6044
+ }
6045
+ if (!this.shouldHandle(req)) {
6046
+ abortHandshake(socket, 400);
6047
+ return;
6048
+ }
6049
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
6050
+ let protocols = /* @__PURE__ */ new Set();
6051
+ if (secWebSocketProtocol !== void 0) {
6052
+ try {
6053
+ protocols = subprotocol.parse(secWebSocketProtocol);
6054
+ } catch (err) {
6055
+ const message = "Invalid Sec-WebSocket-Protocol header";
6056
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
6057
+ return;
6058
+ }
6059
+ }
6060
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
6061
+ const extensions = {};
6062
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
6063
+ const perMessageDeflate = new PerMessageDeflate(
6064
+ this.options.perMessageDeflate,
6065
+ true,
6066
+ this.options.maxPayload
6067
+ );
6068
+ try {
6069
+ const offers = extension.parse(secWebSocketExtensions);
6070
+ if (offers[PerMessageDeflate.extensionName]) {
6071
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
6072
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
6073
+ }
6074
+ } catch (err) {
6075
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
6076
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
6077
+ return;
6078
+ }
6079
+ }
6080
+ if (this.options.verifyClient) {
6081
+ const info = {
6082
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
6083
+ secure: !!(req.socket.authorized || req.socket.encrypted),
6084
+ req
6085
+ };
6086
+ if (this.options.verifyClient.length === 2) {
6087
+ this.options.verifyClient(info, (verified, code, message, headers) => {
6088
+ if (!verified) {
6089
+ return abortHandshake(socket, code || 401, message, headers);
6090
+ }
6091
+ this.completeUpgrade(
6092
+ extensions,
6093
+ key,
6094
+ protocols,
6095
+ req,
6096
+ socket,
6097
+ head,
6098
+ cb
6099
+ );
6100
+ });
6101
+ return;
6102
+ }
6103
+ if (!this.options.verifyClient(info))
6104
+ return abortHandshake(socket, 401);
6105
+ }
6106
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
2350
6107
  }
2351
- watch(paths, options) {
2352
- const pathArray = Array.isArray(paths) ? paths : [paths];
2353
- const recursive = options?.recursive ?? true;
2354
- const signal = options?.signal;
2355
- let closed = false;
2356
- const watchers = [];
2357
- const eventQueue = [];
2358
- let resolver = null;
2359
- Promise.all(
2360
- pathArray.map(
2361
- (path) => setupNodeFsWatcher(path, {
2362
- recursive,
2363
- closed: () => closed,
2364
- signal,
2365
- eventQueue,
2366
- getResolver: () => resolver,
2367
- setResolver: (r) => {
2368
- resolver = r;
2369
- },
2370
- watchers,
2371
- onError: (error, path2) => serverLogger.error(`File watcher error for ${path2}:`, error)
2372
- })
2373
- )
2374
- ).catch((error) => {
2375
- serverLogger.error("Failed to setup file watchers:", error);
6108
+ /**
6109
+ * Upgrade the connection to WebSocket.
6110
+ *
6111
+ * @param {Object} extensions The accepted extensions
6112
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
6113
+ * @param {Set} protocols The subprotocols
6114
+ * @param {http.IncomingMessage} req The request object
6115
+ * @param {Duplex} socket The network socket between the server and client
6116
+ * @param {Buffer} head The first packet of the upgraded stream
6117
+ * @param {Function} cb Callback
6118
+ * @throws {Error} If called more than once with the same socket
6119
+ * @private
6120
+ */
6121
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
6122
+ if (!socket.readable || !socket.writable)
6123
+ return socket.destroy();
6124
+ if (socket[kWebSocket]) {
6125
+ throw new Error(
6126
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
6127
+ );
6128
+ }
6129
+ if (this._state > RUNNING)
6130
+ return abortHandshake(socket, 503);
6131
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
6132
+ const headers = [
6133
+ "HTTP/1.1 101 Switching Protocols",
6134
+ "Upgrade: websocket",
6135
+ "Connection: Upgrade",
6136
+ `Sec-WebSocket-Accept: ${digest}`
6137
+ ];
6138
+ const ws = new this.options.WebSocket(null, void 0, this.options);
6139
+ if (protocols.size) {
6140
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
6141
+ if (protocol) {
6142
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
6143
+ ws._protocol = protocol;
6144
+ }
6145
+ }
6146
+ if (extensions[PerMessageDeflate.extensionName]) {
6147
+ const params = extensions[PerMessageDeflate.extensionName].params;
6148
+ const value = extension.format({
6149
+ [PerMessageDeflate.extensionName]: [params]
6150
+ });
6151
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
6152
+ ws._extensions = extensions;
6153
+ }
6154
+ this.emit("headers", headers, req);
6155
+ socket.write(headers.concat("\r\n").join("\r\n"));
6156
+ socket.removeListener("error", socketOnError);
6157
+ ws.setSocket(socket, head, {
6158
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
6159
+ maxPayload: this.options.maxPayload,
6160
+ skipUTF8Validation: this.options.skipUTF8Validation
2376
6161
  });
2377
- const iterator = createWatcherIterator(
2378
- eventQueue,
2379
- () => resolver,
2380
- (r) => {
2381
- resolver = r;
2382
- },
2383
- () => closed,
2384
- () => signal?.aborted ?? false
2385
- );
2386
- const cleanup = () => {
2387
- closed = true;
2388
- watchers.forEach((watcher) => {
2389
- try {
2390
- watcher.close();
2391
- } catch (error) {
2392
- serverLogger.debug("Error closing file watcher during cleanup:", error);
6162
+ if (this.clients) {
6163
+ this.clients.add(ws);
6164
+ ws.on("close", () => {
6165
+ this.clients.delete(ws);
6166
+ if (this._shouldEmitClose && !this.clients.size) {
6167
+ process.nextTick(emitClose, this);
2393
6168
  }
2394
6169
  });
2395
- if (resolver) {
2396
- resolver({ done: true, value: void 0 });
2397
- resolver = null;
2398
- }
2399
- };
2400
- if (signal) {
2401
- signal.addEventListener("abort", cleanup);
2402
6170
  }
2403
- return createFileWatcher(iterator, cleanup);
6171
+ cb(ws, req);
2404
6172
  }
2405
6173
  };
6174
+ module.exports = WebSocketServer2;
6175
+ function addListeners(server, map) {
6176
+ for (const event of Object.keys(map))
6177
+ server.on(event, map[event]);
6178
+ return function removeListeners() {
6179
+ for (const event of Object.keys(map)) {
6180
+ server.removeListener(event, map[event]);
6181
+ }
6182
+ };
6183
+ }
6184
+ function emitClose(server) {
6185
+ server._state = CLOSED;
6186
+ server.emit("close");
6187
+ }
6188
+ function socketOnError() {
6189
+ this.destroy();
6190
+ }
6191
+ function abortHandshake(socket, code, message, headers) {
6192
+ message = message || http.STATUS_CODES[code];
6193
+ headers = {
6194
+ Connection: "close",
6195
+ "Content-Type": "text/html",
6196
+ "Content-Length": Buffer.byteLength(message),
6197
+ ...headers
6198
+ };
6199
+ socket.once("finish", socket.destroy);
6200
+ socket.end(
6201
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
6202
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
6203
+ );
6204
+ }
6205
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
6206
+ if (server.listenerCount("wsClientError")) {
6207
+ const err = new Error(message);
6208
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
6209
+ server.emit("wsClientError", err, socket, req);
6210
+ } else {
6211
+ abortHandshake(socket, code, message, headers);
6212
+ }
6213
+ }
2406
6214
  }
2407
6215
  });
2408
6216
 
2409
- // src/platform/adapters/node/environment-adapter.ts
2410
- import process2 from "node:process";
2411
- var NodeEnvironmentAdapter;
2412
- var init_environment_adapter = __esm({
2413
- "src/platform/adapters/node/environment-adapter.ts"() {
6217
+ // ../node_modules/ws/wrapper.mjs
6218
+ var wrapper_exports = {};
6219
+ __export(wrapper_exports, {
6220
+ Receiver: () => import_receiver.default,
6221
+ Sender: () => import_sender.default,
6222
+ WebSocket: () => import_websocket.default,
6223
+ WebSocketServer: () => import_websocket_server.default,
6224
+ createWebSocketStream: () => import_stream.default,
6225
+ default: () => wrapper_default
6226
+ });
6227
+ var import_stream, import_receiver, import_sender, import_websocket, import_websocket_server, wrapper_default;
6228
+ var init_wrapper = __esm({
6229
+ "../node_modules/ws/wrapper.mjs"() {
2414
6230
  init_deno_env();
2415
- NodeEnvironmentAdapter = class {
2416
- get(key) {
2417
- return process2.env[key];
2418
- }
2419
- set(key, value) {
2420
- process2.env[key] = value;
2421
- }
2422
- toObject() {
2423
- return { ...process2.env };
2424
- }
2425
- };
6231
+ import_stream = __toESM(require_stream(), 1);
6232
+ import_receiver = __toESM(require_receiver(), 1);
6233
+ import_sender = __toESM(require_sender(), 1);
6234
+ import_websocket = __toESM(require_websocket(), 1);
6235
+ import_websocket_server = __toESM(require_websocket_server(), 1);
6236
+ wrapper_default = import_websocket.default;
2426
6237
  }
2427
6238
  });
2428
6239
 
@@ -2494,9 +6305,9 @@ async function createNodeServer(handler, options = {}) {
2494
6305
  });
2495
6306
  server.on("upgrade", async (request, socket, head) => {
2496
6307
  try {
2497
- const { WebSocketServer } = await import("ws");
6308
+ const { WebSocketServer: WebSocketServer2 } = await Promise.resolve().then(() => (init_wrapper(), wrapper_exports));
2498
6309
  if (!wsServer) {
2499
- wsServer = new WebSocketServer({ noServer: true });
6310
+ wsServer = new WebSocketServer2({ noServer: true });
2500
6311
  }
2501
6312
  const requestId = createRequestId(request);
2502
6313
  wsServer.handleUpgrade(request, socket, head, (ws) => {
@@ -2532,6 +6343,7 @@ async function createNodeServer(handler, options = {}) {
2532
6343
  var pendingWebSocketUpgrades, wsServer, NodeServer;
2533
6344
  var init_http_server = __esm({
2534
6345
  "src/platform/adapters/node/http-server.ts"() {
6346
+ "use strict";
2535
6347
  init_deno_env();
2536
6348
  init_config();
2537
6349
  pendingWebSocketUpgrades = /* @__PURE__ */ new Map();
@@ -2563,6 +6375,7 @@ import * as crypto2 from "node:crypto";
2563
6375
  var NodeServerAdapter, NodeWebSocket;
2564
6376
  var init_websocket_adapter = __esm({
2565
6377
  "src/platform/adapters/node/websocket-adapter.ts"() {
6378
+ "use strict";
2566
6379
  init_deno_env();
2567
6380
  init_veryfront_error();
2568
6381
  init_utils();
@@ -2602,19 +6415,29 @@ var init_websocket_adapter = __esm({
2602
6415
  }
2603
6416
  };
2604
6417
  NodeWebSocket = class {
2605
- ws = null;
2606
- readyState = 0;
2607
- // CONNECTING
2608
- onopen = null;
2609
- onclose = null;
2610
- onerror = null;
2611
- onmessage = null;
2612
- static CONNECTING = 0;
2613
- static OPEN = 1;
2614
- static CLOSING = 2;
2615
- static CLOSED = 3;
2616
- // Queue messages sent before the socket is ready
2617
- pendingMessages = [];
6418
+ constructor() {
6419
+ this.ws = null;
6420
+ this.readyState = 0;
6421
+ // CONNECTING
6422
+ this.onopen = null;
6423
+ this.onclose = null;
6424
+ this.onerror = null;
6425
+ this.onmessage = null;
6426
+ // Queue messages sent before the socket is ready
6427
+ this.pendingMessages = [];
6428
+ }
6429
+ static {
6430
+ this.CONNECTING = 0;
6431
+ }
6432
+ static {
6433
+ this.OPEN = 1;
6434
+ }
6435
+ static {
6436
+ this.CLOSING = 2;
6437
+ }
6438
+ static {
6439
+ this.CLOSED = 3;
6440
+ }
2618
6441
  /**
2619
6442
  * Attach the real WebSocket after upgrade completes
2620
6443
  * Called by NodeServerAdapter
@@ -2709,40 +6532,43 @@ var init_websocket_adapter = __esm({
2709
6532
  var NodeAdapter, nodeAdapter;
2710
6533
  var init_adapter = __esm({
2711
6534
  "src/platform/adapters/node/adapter.ts"() {
6535
+ "use strict";
2712
6536
  init_deno_env();
2713
6537
  init_filesystem_adapter();
2714
6538
  init_environment_adapter();
2715
6539
  init_websocket_adapter();
2716
6540
  init_http_server();
2717
6541
  NodeAdapter = class {
2718
- id = "node";
2719
- name = "node";
2720
- /** @deprecated Use `id` instead */
2721
- platform = "node";
2722
- fs = new NodeFileSystemAdapter();
2723
- env = new NodeEnvironmentAdapter();
2724
- server = new NodeServerAdapter();
2725
- capabilities = {
2726
- typescript: false,
2727
- // Requires compilation
2728
- jsx: false,
2729
- // Requires compilation
2730
- http2: true,
2731
- websocket: true,
2732
- workers: true,
2733
- fileWatching: true,
2734
- shell: true,
2735
- kvStore: false,
2736
- writableFs: true
2737
- };
2738
- /** @deprecated Use `capabilities` instead */
2739
- features = {
2740
- websocket: true,
2741
- http2: true,
2742
- workers: true,
2743
- jsx: false,
2744
- typescript: false
2745
- };
6542
+ constructor() {
6543
+ this.id = "node";
6544
+ this.name = "node";
6545
+ /** @deprecated Use `id` instead */
6546
+ this.platform = "node";
6547
+ this.fs = new NodeFileSystemAdapter();
6548
+ this.env = new NodeEnvironmentAdapter();
6549
+ this.server = new NodeServerAdapter();
6550
+ this.capabilities = {
6551
+ typescript: false,
6552
+ // Requires compilation
6553
+ jsx: false,
6554
+ // Requires compilation
6555
+ http2: true,
6556
+ websocket: true,
6557
+ workers: true,
6558
+ fileWatching: true,
6559
+ shell: true,
6560
+ kvStore: false,
6561
+ writableFs: true
6562
+ };
6563
+ /** @deprecated Use `capabilities` instead */
6564
+ this.features = {
6565
+ websocket: true,
6566
+ http2: true,
6567
+ workers: true,
6568
+ jsx: false,
6569
+ typescript: false
6570
+ };
6571
+ }
2746
6572
  serve(handler, options = {}) {
2747
6573
  return createNodeServer(handler, options);
2748
6574
  }
@@ -2754,6 +6580,7 @@ var init_adapter = __esm({
2754
6580
  // src/platform/adapters/node/index.ts
2755
6581
  var init_node = __esm({
2756
6582
  "src/platform/adapters/node/index.ts"() {
6583
+ "use strict";
2757
6584
  init_deno_env();
2758
6585
  init_adapter();
2759
6586
  init_filesystem_adapter();
@@ -2777,6 +6604,7 @@ __export(node_exports, {
2777
6604
  });
2778
6605
  var init_node2 = __esm({
2779
6606
  "src/platform/adapters/node.ts"() {
6607
+ "use strict";
2780
6608
  init_deno_env();
2781
6609
  init_node();
2782
6610
  }
@@ -2786,10 +6614,9 @@ var init_node2 = __esm({
2786
6614
  var VeryfrontError;
2787
6615
  var init_types = __esm({
2788
6616
  "src/core/errors/types.ts"() {
6617
+ "use strict";
2789
6618
  init_deno_env();
2790
6619
  VeryfrontError = class extends Error {
2791
- code;
2792
- context;
2793
6620
  constructor(message, code, context) {
2794
6621
  super(message);
2795
6622
  this.name = "VeryfrontError";
@@ -2803,6 +6630,7 @@ var init_types = __esm({
2803
6630
  // src/core/errors/agent-errors.ts
2804
6631
  var init_agent_errors = __esm({
2805
6632
  "src/core/errors/agent-errors.ts"() {
6633
+ "use strict";
2806
6634
  init_deno_env();
2807
6635
  init_types();
2808
6636
  }
@@ -2811,6 +6639,7 @@ var init_agent_errors = __esm({
2811
6639
  // src/core/errors/build-errors.ts
2812
6640
  var init_build_errors = __esm({
2813
6641
  "src/core/errors/build-errors.ts"() {
6642
+ "use strict";
2814
6643
  init_deno_env();
2815
6644
  init_types();
2816
6645
  }
@@ -2819,6 +6648,7 @@ var init_build_errors = __esm({
2819
6648
  // src/core/errors/runtime-errors.ts
2820
6649
  var init_runtime_errors = __esm({
2821
6650
  "src/core/errors/runtime-errors.ts"() {
6651
+ "use strict";
2822
6652
  init_deno_env();
2823
6653
  init_types();
2824
6654
  }
@@ -2828,6 +6658,7 @@ var init_runtime_errors = __esm({
2828
6658
  var FileSystemError;
2829
6659
  var init_system_errors = __esm({
2830
6660
  "src/core/errors/system-errors.ts"() {
6661
+ "use strict";
2831
6662
  init_deno_env();
2832
6663
  init_types();
2833
6664
  FileSystemError = class extends VeryfrontError {
@@ -2842,6 +6673,7 @@ var init_system_errors = __esm({
2842
6673
  // src/core/errors/error-handlers.ts
2843
6674
  var init_error_handlers = __esm({
2844
6675
  "src/core/errors/error-handlers.ts"() {
6676
+ "use strict";
2845
6677
  init_deno_env();
2846
6678
  init_logger();
2847
6679
  init_types();
@@ -2855,6 +6687,7 @@ function getErrorDocsUrl(code) {
2855
6687
  var ErrorCode2;
2856
6688
  var init_error_codes = __esm({
2857
6689
  "src/core/errors/error-codes.ts"() {
6690
+ "use strict";
2858
6691
  init_deno_env();
2859
6692
  ErrorCode2 = {
2860
6693
  CONFIG_NOT_FOUND: "VF001",
@@ -2932,6 +6765,7 @@ function createSimpleError(code, title, message, steps) {
2932
6765
  }
2933
6766
  var init_factory = __esm({
2934
6767
  "src/core/errors/catalog/factory.ts"() {
6768
+ "use strict";
2935
6769
  init_deno_env();
2936
6770
  init_error_codes();
2937
6771
  }
@@ -2941,6 +6775,7 @@ var init_factory = __esm({
2941
6775
  var CONFIG_ERROR_CATALOG;
2942
6776
  var init_config_errors = __esm({
2943
6777
  "src/core/errors/catalog/config-errors.ts"() {
6778
+ "use strict";
2944
6779
  init_deno_env();
2945
6780
  init_error_codes();
2946
6781
  init_factory();
@@ -3047,6 +6882,7 @@ export default {
3047
6882
  var BUILD_ERROR_CATALOG;
3048
6883
  var init_build_errors2 = __esm({
3049
6884
  "src/core/errors/catalog/build-errors.ts"() {
6885
+ "use strict";
3050
6886
  init_deno_env();
3051
6887
  init_error_codes();
3052
6888
  init_factory();
@@ -3138,6 +6974,7 @@ import Button from './components/Button.jsx'
3138
6974
  var RUNTIME_ERROR_CATALOG;
3139
6975
  var init_runtime_errors2 = __esm({
3140
6976
  "src/core/errors/catalog/runtime-errors.ts"() {
6977
+ "use strict";
3141
6978
  init_deno_env();
3142
6979
  init_error_codes();
3143
6980
  init_factory();
@@ -3235,6 +7072,7 @@ export default function RootLayout({ children }) {
3235
7072
  var ROUTE_ERROR_CATALOG;
3236
7073
  var init_route_errors = __esm({
3237
7074
  "src/core/errors/catalog/route-errors.ts"() {
7075
+ "use strict";
3238
7076
  init_deno_env();
3239
7077
  init_error_codes();
3240
7078
  init_factory();
@@ -3310,6 +7148,7 @@ export async function GET() {
3310
7148
  var MODULE_ERROR_CATALOG;
3311
7149
  var init_module_errors = __esm({
3312
7150
  "src/core/errors/catalog/module-errors.ts"() {
7151
+ "use strict";
3313
7152
  init_deno_env();
3314
7153
  init_error_codes();
3315
7154
  init_factory();
@@ -3398,6 +7237,7 @@ resolve: {
3398
7237
  var SERVER_ERROR_CATALOG;
3399
7238
  var init_server_errors = __esm({
3400
7239
  "src/core/errors/catalog/server-errors.ts"() {
7240
+ "use strict";
3401
7241
  init_deno_env();
3402
7242
  init_error_codes();
3403
7243
  init_factory();
@@ -3473,6 +7313,7 @@ dev: {
3473
7313
  var RSC_ERROR_CATALOG;
3474
7314
  var init_rsc_errors = __esm({
3475
7315
  "src/core/errors/catalog/rsc-errors.ts"() {
7316
+ "use strict";
3476
7317
  init_deno_env();
3477
7318
  init_error_codes();
3478
7319
  init_factory();
@@ -3560,6 +7401,7 @@ import React from 'react'`
3560
7401
  var DEV_ERROR_CATALOG;
3561
7402
  var init_dev_errors = __esm({
3562
7403
  "src/core/errors/catalog/dev-errors.ts"() {
7404
+ "use strict";
3563
7405
  init_deno_env();
3564
7406
  init_error_codes();
3565
7407
  init_factory();
@@ -3612,6 +7454,7 @@ var init_dev_errors = __esm({
3612
7454
  var DEPLOYMENT_ERROR_CATALOG;
3613
7455
  var init_deployment_errors = __esm({
3614
7456
  "src/core/errors/catalog/deployment-errors.ts"() {
7457
+ "use strict";
3615
7458
  init_deno_env();
3616
7459
  init_error_codes();
3617
7460
  init_factory();
@@ -3664,6 +7507,7 @@ var init_deployment_errors = __esm({
3664
7507
  var GENERAL_ERROR_CATALOG;
3665
7508
  var init_general_errors = __esm({
3666
7509
  "src/core/errors/catalog/general-errors.ts"() {
7510
+ "use strict";
3667
7511
  init_deno_env();
3668
7512
  init_error_codes();
3669
7513
  init_factory();
@@ -3727,6 +7571,7 @@ var init_general_errors = __esm({
3727
7571
  var ERROR_CATALOG;
3728
7572
  var init_catalog = __esm({
3729
7573
  "src/core/errors/catalog/index.ts"() {
7574
+ "use strict";
3730
7575
  init_deno_env();
3731
7576
  init_config_errors();
3732
7577
  init_build_errors2();
@@ -3757,6 +7602,7 @@ var init_catalog = __esm({
3757
7602
  // src/core/errors/user-friendly/error-catalog.ts
3758
7603
  var init_error_catalog = __esm({
3759
7604
  "src/core/errors/user-friendly/error-catalog.ts"() {
7605
+ "use strict";
3760
7606
  init_deno_env();
3761
7607
  }
3762
7608
  });
@@ -3806,6 +7652,7 @@ __export(deno_exports2, {
3806
7652
  var colors;
3807
7653
  var init_deno3 = __esm({
3808
7654
  "src/platform/compat/console/deno.ts"() {
7655
+ "use strict";
3809
7656
  init_deno_env();
3810
7657
  init_ansi();
3811
7658
  colors = {
@@ -3861,6 +7708,7 @@ async function initColors() {
3861
7708
  var pc, lazyColor, colors2, red2, green2, yellow2, blue2, cyan2, magenta2, white2, gray2, bold2, dim2, italic2, underline2, strikethrough2, reset2;
3862
7709
  var init_node3 = __esm({
3863
7710
  "src/platform/compat/console/node.ts"() {
7711
+ "use strict";
3864
7712
  init_deno_env();
3865
7713
  pc = null;
3866
7714
  lazyColor = (fn) => (s) => pc?.[fn]?.(s) ?? s;
@@ -3944,6 +7792,7 @@ var init_console = __esm({
3944
7792
  // src/core/errors/user-friendly/error-identifier.ts
3945
7793
  var init_error_identifier = __esm({
3946
7794
  "src/core/errors/user-friendly/error-identifier.ts"() {
7795
+ "use strict";
3947
7796
  init_deno_env();
3948
7797
  }
3949
7798
  });
@@ -3951,6 +7800,7 @@ var init_error_identifier = __esm({
3951
7800
  // src/core/errors/user-friendly/error-formatter.ts
3952
7801
  var init_error_formatter = __esm({
3953
7802
  "src/core/errors/user-friendly/error-formatter.ts"() {
7803
+ "use strict";
3954
7804
  init_deno_env();
3955
7805
  init_console();
3956
7806
  init_error_catalog();
@@ -3961,6 +7811,7 @@ var init_error_formatter = __esm({
3961
7811
  // src/core/errors/user-friendly/error-wrapper.ts
3962
7812
  var init_error_wrapper = __esm({
3963
7813
  "src/core/errors/user-friendly/error-wrapper.ts"() {
7814
+ "use strict";
3964
7815
  init_deno_env();
3965
7816
  init_console();
3966
7817
  init_process();
@@ -3972,6 +7823,7 @@ var init_error_wrapper = __esm({
3972
7823
  // src/core/errors/user-friendly/index.ts
3973
7824
  var init_user_friendly = __esm({
3974
7825
  "src/core/errors/user-friendly/index.ts"() {
7826
+ "use strict";
3975
7827
  init_deno_env();
3976
7828
  init_error_catalog();
3977
7829
  init_error_formatter();
@@ -3999,6 +7851,7 @@ var init_errors = __esm({
3999
7851
  var BunFileSystemAdapter;
4000
7852
  var init_filesystem_adapter2 = __esm({
4001
7853
  "src/platform/adapters/bun/filesystem-adapter.ts"() {
7854
+ "use strict";
4002
7855
  init_deno_env();
4003
7856
  init_errors();
4004
7857
  init_veryfront_error();
@@ -4156,6 +8009,7 @@ var init_filesystem_adapter2 = __esm({
4156
8009
  var BunEnvironmentAdapter;
4157
8010
  var init_environment_adapter2 = __esm({
4158
8011
  "src/platform/adapters/bun/environment-adapter.ts"() {
8012
+ "use strict";
4159
8013
  init_deno_env();
4160
8014
  BunEnvironmentAdapter = class {
4161
8015
  get(key) {
@@ -4175,6 +8029,7 @@ var init_environment_adapter2 = __esm({
4175
8029
  var BunServerAdapter, BunWebSocket;
4176
8030
  var init_websocket_adapter2 = __esm({
4177
8031
  "src/platform/adapters/bun/websocket-adapter.ts"() {
8032
+ "use strict";
4178
8033
  init_deno_env();
4179
8034
  init_veryfront_error();
4180
8035
  BunServerAdapter = class {
@@ -4195,15 +8050,25 @@ var init_websocket_adapter2 = __esm({
4195
8050
  }
4196
8051
  };
4197
8052
  BunWebSocket = class {
4198
- readyState = 1;
4199
- onopen = null;
4200
- onclose = null;
4201
- onerror = null;
4202
- onmessage = null;
4203
- static CONNECTING = 0;
4204
- static OPEN = 1;
4205
- static CLOSING = 2;
4206
- static CLOSED = 3;
8053
+ constructor() {
8054
+ this.readyState = 1;
8055
+ this.onopen = null;
8056
+ this.onclose = null;
8057
+ this.onerror = null;
8058
+ this.onmessage = null;
8059
+ }
8060
+ static {
8061
+ this.CONNECTING = 0;
8062
+ }
8063
+ static {
8064
+ this.OPEN = 1;
8065
+ }
8066
+ static {
8067
+ this.CLOSING = 2;
8068
+ }
8069
+ static {
8070
+ this.CLOSED = 3;
8071
+ }
4207
8072
  send(_data) {
4208
8073
  throw toError(createError({
4209
8074
  type: "network",
@@ -4238,6 +8103,7 @@ function createBunServer(handler, options = {}) {
4238
8103
  var BunServer;
4239
8104
  var init_http_server2 = __esm({
4240
8105
  "src/platform/adapters/bun/http-server.ts"() {
8106
+ "use strict";
4241
8107
  init_deno_env();
4242
8108
  init_config();
4243
8109
  init_utils();
@@ -4262,39 +8128,42 @@ var init_http_server2 = __esm({
4262
8128
  var BunAdapter, bunAdapter;
4263
8129
  var init_adapter2 = __esm({
4264
8130
  "src/platform/adapters/bun/adapter.ts"() {
8131
+ "use strict";
4265
8132
  init_deno_env();
4266
8133
  init_filesystem_adapter2();
4267
8134
  init_environment_adapter2();
4268
8135
  init_websocket_adapter2();
4269
8136
  init_http_server2();
4270
8137
  BunAdapter = class {
4271
- id = "bun";
4272
- name = "bun";
4273
- /** @deprecated Use `id` instead */
4274
- platform = "bun";
4275
- fs = new BunFileSystemAdapter();
4276
- env = new BunEnvironmentAdapter();
4277
- server = new BunServerAdapter();
4278
- capabilities = {
4279
- typescript: true,
4280
- jsx: true,
4281
- http2: false,
4282
- // Bun's HTTP/2 support is experimental
4283
- websocket: true,
4284
- workers: true,
4285
- fileWatching: true,
4286
- shell: true,
4287
- kvStore: false,
4288
- writableFs: true
4289
- };
4290
- /** @deprecated Use `capabilities` instead */
4291
- features = {
4292
- websocket: true,
4293
- http2: false,
4294
- workers: true,
4295
- jsx: true,
4296
- typescript: true
4297
- };
8138
+ constructor() {
8139
+ this.id = "bun";
8140
+ this.name = "bun";
8141
+ /** @deprecated Use `id` instead */
8142
+ this.platform = "bun";
8143
+ this.fs = new BunFileSystemAdapter();
8144
+ this.env = new BunEnvironmentAdapter();
8145
+ this.server = new BunServerAdapter();
8146
+ this.capabilities = {
8147
+ typescript: true,
8148
+ jsx: true,
8149
+ http2: false,
8150
+ // Bun's HTTP/2 support is experimental
8151
+ websocket: true,
8152
+ workers: true,
8153
+ fileWatching: true,
8154
+ shell: true,
8155
+ kvStore: false,
8156
+ writableFs: true
8157
+ };
8158
+ /** @deprecated Use `capabilities` instead */
8159
+ this.features = {
8160
+ websocket: true,
8161
+ http2: false,
8162
+ workers: true,
8163
+ jsx: true,
8164
+ typescript: true
8165
+ };
8166
+ }
4298
8167
  serve(handler, options = {}) {
4299
8168
  return createBunServer(handler, options);
4300
8169
  }
@@ -4306,6 +8175,7 @@ var init_adapter2 = __esm({
4306
8175
  // src/platform/adapters/bun/index.ts
4307
8176
  var init_bun = __esm({
4308
8177
  "src/platform/adapters/bun/index.ts"() {
8178
+ "use strict";
4309
8179
  init_deno_env();
4310
8180
  init_adapter2();
4311
8181
  init_filesystem_adapter2();
@@ -4329,6 +8199,7 @@ __export(bun_exports, {
4329
8199
  });
4330
8200
  var init_bun2 = __esm({
4331
8201
  "src/platform/adapters/bun.ts"() {
8202
+ "use strict";
4332
8203
  init_deno_env();
4333
8204
  init_bun();
4334
8205
  }
@@ -4490,6 +8361,7 @@ function createMockAdapter() {
4490
8361
  }
4491
8362
  var init_mock = __esm({
4492
8363
  "src/platform/adapters/mock.ts"() {
8364
+ "use strict";
4493
8365
  init_deno_env();
4494
8366
  init_veryfront_error();
4495
8367
  }
@@ -4499,12 +8371,13 @@ var init_mock = __esm({
4499
8371
  var AdapterRegistry, runtime;
4500
8372
  var init_registry = __esm({
4501
8373
  "src/platform/adapters/registry.ts"() {
8374
+ "use strict";
4502
8375
  init_deno_env();
4503
8376
  AdapterRegistry = class {
4504
- instance = null;
4505
- initialized = false;
4506
- loaders = /* @__PURE__ */ new Map();
4507
8377
  constructor() {
8378
+ this.instance = null;
8379
+ this.initialized = false;
8380
+ this.loaders = /* @__PURE__ */ new Map();
4508
8381
  this.loaders.set("deno", async () => {
4509
8382
  const { denoAdapter: denoAdapter2 } = await Promise.resolve().then(() => (init_deno2(), deno_exports));
4510
8383
  return denoAdapter2;
@@ -4725,8 +8598,10 @@ init_deno_env();
4725
8598
  // src/core/utils/cache/stores/memory/lru-list-manager.ts
4726
8599
  init_deno_env();
4727
8600
  var LRUListManager = class {
4728
- head = null;
4729
- tail = null;
8601
+ constructor() {
8602
+ this.head = null;
8603
+ this.tail = null;
8604
+ }
4730
8605
  getHead() {
4731
8606
  return this.head;
4732
8607
  }
@@ -4776,7 +8651,6 @@ var LRUListManager = class {
4776
8651
  // src/core/utils/cache/eviction/eviction-manager.ts
4777
8652
  init_deno_env();
4778
8653
  var EvictionManager = class {
4779
- onEvict;
4780
8654
  constructor(options = {}) {
4781
8655
  this.onEvict = options.onEvict;
4782
8656
  }
@@ -4967,17 +8841,11 @@ function defaultSizeEstimator(value) {
4967
8841
  }
4968
8842
  }
4969
8843
  var LRUCacheAdapter = class {
4970
- store = /* @__PURE__ */ new Map();
4971
- tagIndex = /* @__PURE__ */ new Map();
4972
- listManager = new LRUListManager();
4973
- evictionManager;
4974
- entryManager;
4975
- currentSize = 0;
4976
- maxEntries;
4977
- maxSizeBytes;
4978
- defaultTtlMs;
4979
- onEvict;
4980
8844
  constructor(options = {}) {
8845
+ this.store = /* @__PURE__ */ new Map();
8846
+ this.tagIndex = /* @__PURE__ */ new Map();
8847
+ this.listManager = new LRUListManager();
8848
+ this.currentSize = 0;
4981
8849
  this.maxEntries = options.maxEntries || 1e3;
4982
8850
  this.maxSizeBytes = options.maxSizeBytes || 50 * 1024 * 1024;
4983
8851
  this.defaultTtlMs = options.ttlMs;