veryfront 0.0.70 → 0.0.72

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